database_util.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "sync"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/logger"
  29. "github.com/ethereum/go-ethereum/logger/glog"
  30. "github.com/ethereum/go-ethereum/params"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. var (
  34. headHeaderKey = []byte("LastHeader")
  35. headBlockKey = []byte("LastBlock")
  36. headFastKey = []byte("LastFast")
  37. headerPrefix = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
  38. tdSuffix = []byte("t") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
  39. numSuffix = []byte("n") // headerPrefix + num (uint64 big endian) + numSuffix -> hash
  40. blockHashPrefix = []byte("H") // blockHashPrefix + hash -> num (uint64 big endian)
  41. bodyPrefix = []byte("b") // bodyPrefix + num (uint64 big endian) + hash -> block body
  42. blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
  43. txMetaSuffix = []byte{0x01}
  44. receiptsPrefix = []byte("receipts-")
  45. mipmapPre = []byte("mipmap-log-bloom-")
  46. MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
  47. configPrefix = []byte("ethereum-config-") // config prefix for the db
  48. // used by old (non-sequential keys) db, now only used for conversion
  49. oldBlockPrefix = []byte("block-")
  50. oldHeaderSuffix = []byte("-header")
  51. oldTdSuffix = []byte("-td") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
  52. oldBodySuffix = []byte("-body")
  53. oldBlockNumPrefix = []byte("block-num-")
  54. oldBlockReceiptsPrefix = []byte("receipts-block-")
  55. oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
  56. ChainConfigNotFoundErr = errors.New("ChainConfig not found") // general config not found error
  57. mipmapBloomMu sync.Mutex // protect against race condition when updating mipmap blooms
  58. )
  59. // encodeBlockNumber encodes a block number as big endian uint64
  60. func encodeBlockNumber(number uint64) []byte {
  61. enc := make([]byte, 8)
  62. binary.BigEndian.PutUint64(enc, number)
  63. return enc
  64. }
  65. // GetCanonicalHash retrieves a hash assigned to a canonical block number.
  66. func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
  67. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
  68. if len(data) == 0 {
  69. data, _ = db.Get(append(oldBlockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  70. if len(data) == 0 {
  71. return common.Hash{}
  72. }
  73. }
  74. return common.BytesToHash(data)
  75. }
  76. // missingNumber is returned by GetBlockNumber if no header with the
  77. // given block hash has been stored in the database
  78. const missingNumber = uint64(0xffffffffffffffff)
  79. // GetBlockNumber returns the block number assigned to a block hash
  80. // if the corresponding header is present in the database
  81. func GetBlockNumber(db ethdb.Database, hash common.Hash) uint64 {
  82. data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...))
  83. if len(data) != 8 {
  84. data, _ := db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldHeaderSuffix...))
  85. if len(data) == 0 {
  86. return missingNumber
  87. }
  88. header := new(types.Header)
  89. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  90. glog.Fatalf("failed to decode block header: %v", err)
  91. }
  92. return header.Number.Uint64()
  93. }
  94. return binary.BigEndian.Uint64(data)
  95. }
  96. // GetHeadHeaderHash retrieves the hash of the current canonical head block's
  97. // header. The difference between this and GetHeadBlockHash is that whereas the
  98. // last block hash is only updated upon a full block import, the last header
  99. // hash is updated already at header import, allowing head tracking for the
  100. // light synchronization mechanism.
  101. func GetHeadHeaderHash(db ethdb.Database) common.Hash {
  102. data, _ := db.Get(headHeaderKey)
  103. if len(data) == 0 {
  104. return common.Hash{}
  105. }
  106. return common.BytesToHash(data)
  107. }
  108. // GetHeadBlockHash retrieves the hash of the current canonical head block.
  109. func GetHeadBlockHash(db ethdb.Database) common.Hash {
  110. data, _ := db.Get(headBlockKey)
  111. if len(data) == 0 {
  112. return common.Hash{}
  113. }
  114. return common.BytesToHash(data)
  115. }
  116. // GetHeadFastBlockHash retrieves the hash of the current canonical head block during
  117. // fast synchronization. The difference between this and GetHeadBlockHash is that
  118. // whereas the last block hash is only updated upon a full block import, the last
  119. // fast hash is updated when importing pre-processed blocks.
  120. func GetHeadFastBlockHash(db ethdb.Database) common.Hash {
  121. data, _ := db.Get(headFastKey)
  122. if len(data) == 0 {
  123. return common.Hash{}
  124. }
  125. return common.BytesToHash(data)
  126. }
  127. // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
  128. // if the header's not found.
  129. func GetHeaderRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
  130. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  131. if len(data) == 0 {
  132. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldHeaderSuffix...))
  133. }
  134. return data
  135. }
  136. // GetHeader retrieves the block header corresponding to the hash, nil if none
  137. // found.
  138. func GetHeader(db ethdb.Database, hash common.Hash, number uint64) *types.Header {
  139. data := GetHeaderRLP(db, hash, number)
  140. if len(data) == 0 {
  141. return nil
  142. }
  143. header := new(types.Header)
  144. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  145. glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
  146. return nil
  147. }
  148. return header
  149. }
  150. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  151. func GetBodyRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
  152. data, _ := db.Get(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  153. if len(data) == 0 {
  154. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldBodySuffix...))
  155. }
  156. return data
  157. }
  158. // GetBody retrieves the block body (transactons, uncles) corresponding to the
  159. // hash, nil if none found.
  160. func GetBody(db ethdb.Database, hash common.Hash, number uint64) *types.Body {
  161. data := GetBodyRLP(db, hash, number)
  162. if len(data) == 0 {
  163. return nil
  164. }
  165. body := new(types.Body)
  166. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  167. glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
  168. return nil
  169. }
  170. return body
  171. }
  172. // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
  173. // none found.
  174. func GetTd(db ethdb.Database, hash common.Hash, number uint64) *big.Int {
  175. data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...))
  176. if len(data) == 0 {
  177. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldTdSuffix...))
  178. if len(data) == 0 {
  179. return nil
  180. }
  181. }
  182. td := new(big.Int)
  183. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  184. glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
  185. return nil
  186. }
  187. return td
  188. }
  189. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  190. // back from the stored header and body. If either the header or body could not
  191. // be retrieved nil is returned.
  192. //
  193. // Note, due to concurrent download of header and block body the header and thus
  194. // canonical hash can be stored in the database but the body data not (yet).
  195. func GetBlock(db ethdb.Database, hash common.Hash, number uint64) *types.Block {
  196. // Retrieve the block header and body contents
  197. header := GetHeader(db, hash, number)
  198. if header == nil {
  199. return nil
  200. }
  201. body := GetBody(db, hash, number)
  202. if body == nil {
  203. return nil
  204. }
  205. // Reassemble the block and return
  206. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  207. }
  208. // GetBlockReceipts retrieves the receipts generated by the transactions included
  209. // in a block given by its hash.
  210. func GetBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) types.Receipts {
  211. data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
  212. if len(data) == 0 {
  213. data, _ = db.Get(append(oldBlockReceiptsPrefix, hash.Bytes()...))
  214. if len(data) == 0 {
  215. return nil
  216. }
  217. }
  218. storageReceipts := []*types.ReceiptForStorage{}
  219. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  220. glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, err)
  221. return nil
  222. }
  223. receipts := make(types.Receipts, len(storageReceipts))
  224. for i, receipt := range storageReceipts {
  225. receipts[i] = (*types.Receipt)(receipt)
  226. }
  227. return receipts
  228. }
  229. // GetTransaction retrieves a specific transaction from the database, along with
  230. // its added positional metadata.
  231. func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
  232. // Retrieve the transaction itself from the database
  233. data, _ := db.Get(hash.Bytes())
  234. if len(data) == 0 {
  235. return nil, common.Hash{}, 0, 0
  236. }
  237. var tx types.Transaction
  238. if err := rlp.DecodeBytes(data, &tx); err != nil {
  239. return nil, common.Hash{}, 0, 0
  240. }
  241. // Retrieve the blockchain positional metadata
  242. data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
  243. if len(data) == 0 {
  244. return nil, common.Hash{}, 0, 0
  245. }
  246. var meta struct {
  247. BlockHash common.Hash
  248. BlockIndex uint64
  249. Index uint64
  250. }
  251. if err := rlp.DecodeBytes(data, &meta); err != nil {
  252. return nil, common.Hash{}, 0, 0
  253. }
  254. return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
  255. }
  256. // GetReceipt returns a receipt by hash
  257. func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
  258. data, _ := db.Get(append(receiptsPrefix, txHash[:]...))
  259. if len(data) == 0 {
  260. return nil
  261. }
  262. var receipt types.ReceiptForStorage
  263. err := rlp.DecodeBytes(data, &receipt)
  264. if err != nil {
  265. glog.V(logger.Core).Infoln("GetReceipt err:", err)
  266. }
  267. return (*types.Receipt)(&receipt)
  268. }
  269. // WriteCanonicalHash stores the canonical hash for the given block number.
  270. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  271. key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
  272. if err := db.Put(key, hash.Bytes()); err != nil {
  273. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  274. }
  275. return nil
  276. }
  277. // WriteHeadHeaderHash stores the head header's hash.
  278. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  279. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  280. glog.Fatalf("failed to store last header's hash into database: %v", err)
  281. }
  282. return nil
  283. }
  284. // WriteHeadBlockHash stores the head block's hash.
  285. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  286. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  287. glog.Fatalf("failed to store last block's hash into database: %v", err)
  288. }
  289. return nil
  290. }
  291. // WriteHeadFastBlockHash stores the fast head block's hash.
  292. func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
  293. if err := db.Put(headFastKey, hash.Bytes()); err != nil {
  294. glog.Fatalf("failed to store last fast block's hash into database: %v", err)
  295. }
  296. return nil
  297. }
  298. // WriteHeader serializes a block header into the database.
  299. func WriteHeader(db ethdb.Database, header *types.Header) error {
  300. data, err := rlp.EncodeToBytes(header)
  301. if err != nil {
  302. return err
  303. }
  304. hash := header.Hash().Bytes()
  305. num := header.Number.Uint64()
  306. encNum := encodeBlockNumber(num)
  307. key := append(blockHashPrefix, hash...)
  308. if err := db.Put(key, encNum); err != nil {
  309. glog.Fatalf("failed to store hash to number mapping into database: %v", err)
  310. }
  311. key = append(append(headerPrefix, encNum...), hash...)
  312. if err := db.Put(key, data); err != nil {
  313. glog.Fatalf("failed to store header into database: %v", err)
  314. }
  315. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, hash[:4])
  316. return nil
  317. }
  318. // WriteBody serializes the body of a block into the database.
  319. func WriteBody(db ethdb.Database, hash common.Hash, number uint64, body *types.Body) error {
  320. data, err := rlp.EncodeToBytes(body)
  321. if err != nil {
  322. return err
  323. }
  324. return WriteBodyRLP(db, hash, number, data)
  325. }
  326. // WriteBodyRLP writes a serialized body of a block into the database.
  327. func WriteBodyRLP(db ethdb.Database, hash common.Hash, number uint64, rlp rlp.RawValue) error {
  328. key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  329. if err := db.Put(key, rlp); err != nil {
  330. glog.Fatalf("failed to store block body into database: %v", err)
  331. }
  332. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  333. return nil
  334. }
  335. // WriteTd serializes the total difficulty of a block into the database.
  336. func WriteTd(db ethdb.Database, hash common.Hash, number uint64, td *big.Int) error {
  337. data, err := rlp.EncodeToBytes(td)
  338. if err != nil {
  339. return err
  340. }
  341. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
  342. if err := db.Put(key, data); err != nil {
  343. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  344. }
  345. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  346. return nil
  347. }
  348. // WriteBlock serializes a block into the database, header and body separately.
  349. func WriteBlock(db ethdb.Database, block *types.Block) error {
  350. // Store the body first to retain database consistency
  351. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  352. return err
  353. }
  354. // Store the header too, signaling full block ownership
  355. if err := WriteHeader(db, block.Header()); err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // WriteBlockReceipts stores all the transaction receipts belonging to a block
  361. // as a single receipt slice. This is used during chain reorganisations for
  362. // rescheduling dropped transactions.
  363. func WriteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64, receipts types.Receipts) error {
  364. // Convert the receipts into their storage form and serialize them
  365. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  366. for i, receipt := range receipts {
  367. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  368. }
  369. bytes, err := rlp.EncodeToBytes(storageReceipts)
  370. if err != nil {
  371. return err
  372. }
  373. // Store the flattened receipt slice
  374. key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  375. if err := db.Put(key, bytes); err != nil {
  376. glog.Fatalf("failed to store block receipts into database: %v", err)
  377. }
  378. glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
  379. return nil
  380. }
  381. // WriteTransactions stores the transactions associated with a specific block
  382. // into the given database. Beside writing the transaction, the function also
  383. // stores a metadata entry along with the transaction, detailing the position
  384. // of this within the blockchain.
  385. func WriteTransactions(db ethdb.Database, block *types.Block) error {
  386. batch := db.NewBatch()
  387. // Iterate over each transaction and encode it with its metadata
  388. for i, tx := range block.Transactions() {
  389. // Encode and queue up the transaction for storage
  390. data, err := rlp.EncodeToBytes(tx)
  391. if err != nil {
  392. return err
  393. }
  394. if err := batch.Put(tx.Hash().Bytes(), data); err != nil {
  395. return err
  396. }
  397. // Encode and queue up the transaction metadata for storage
  398. meta := struct {
  399. BlockHash common.Hash
  400. BlockIndex uint64
  401. Index uint64
  402. }{
  403. BlockHash: block.Hash(),
  404. BlockIndex: block.NumberU64(),
  405. Index: uint64(i),
  406. }
  407. data, err = rlp.EncodeToBytes(meta)
  408. if err != nil {
  409. return err
  410. }
  411. if err := batch.Put(append(tx.Hash().Bytes(), txMetaSuffix...), data); err != nil {
  412. return err
  413. }
  414. }
  415. // Write the scheduled data into the database
  416. if err := batch.Write(); err != nil {
  417. glog.Fatalf("failed to store transactions into database: %v", err)
  418. }
  419. return nil
  420. }
  421. // WriteReceipt stores a single transaction receipt into the database.
  422. func WriteReceipt(db ethdb.Database, receipt *types.Receipt) error {
  423. storageReceipt := (*types.ReceiptForStorage)(receipt)
  424. data, err := rlp.EncodeToBytes(storageReceipt)
  425. if err != nil {
  426. return err
  427. }
  428. return db.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data)
  429. }
  430. // WriteReceipts stores a batch of transaction receipts into the database.
  431. func WriteReceipts(db ethdb.Database, receipts types.Receipts) error {
  432. batch := db.NewBatch()
  433. // Iterate over all the receipts and queue them for database injection
  434. for _, receipt := range receipts {
  435. storageReceipt := (*types.ReceiptForStorage)(receipt)
  436. data, err := rlp.EncodeToBytes(storageReceipt)
  437. if err != nil {
  438. return err
  439. }
  440. if err := batch.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data); err != nil {
  441. return err
  442. }
  443. }
  444. // Write the scheduled data into the database
  445. if err := batch.Write(); err != nil {
  446. glog.Fatalf("failed to store receipts into database: %v", err)
  447. }
  448. return nil
  449. }
  450. // DeleteCanonicalHash removes the number to hash canonical mapping.
  451. func DeleteCanonicalHash(db ethdb.Database, number uint64) {
  452. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
  453. }
  454. // DeleteHeader removes all block header data associated with a hash.
  455. func DeleteHeader(db ethdb.Database, hash common.Hash, number uint64) {
  456. db.Delete(append(blockHashPrefix, hash.Bytes()...))
  457. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  458. }
  459. // DeleteBody removes all block body data associated with a hash.
  460. func DeleteBody(db ethdb.Database, hash common.Hash, number uint64) {
  461. db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  462. }
  463. // DeleteTd removes all block total difficulty data associated with a hash.
  464. func DeleteTd(db ethdb.Database, hash common.Hash, number uint64) {
  465. db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
  466. }
  467. // DeleteBlock removes all block data associated with a hash.
  468. func DeleteBlock(db ethdb.Database, hash common.Hash, number uint64) {
  469. DeleteBlockReceipts(db, hash, number)
  470. DeleteHeader(db, hash, number)
  471. DeleteBody(db, hash, number)
  472. DeleteTd(db, hash, number)
  473. }
  474. // DeleteBlockReceipts removes all receipt data associated with a block hash.
  475. func DeleteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) {
  476. db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  477. }
  478. // DeleteTransaction removes all transaction data associated with a hash.
  479. func DeleteTransaction(db ethdb.Database, hash common.Hash) {
  480. db.Delete(hash.Bytes())
  481. db.Delete(append(hash.Bytes(), txMetaSuffix...))
  482. }
  483. // DeleteReceipt removes all receipt data associated with a transaction hash.
  484. func DeleteReceipt(db ethdb.Database, hash common.Hash) {
  485. db.Delete(append(receiptsPrefix, hash.Bytes()...))
  486. }
  487. // [deprecated by the header/block split, remove eventually]
  488. // GetBlockByHashOld returns the old combined block corresponding to the hash
  489. // or nil if not found. This method is only used by the upgrade mechanism to
  490. // access the old combined block representation. It will be dropped after the
  491. // network transitions to eth/63.
  492. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  493. data, _ := db.Get(append(oldBlockHashPrefix, hash[:]...))
  494. if len(data) == 0 {
  495. return nil
  496. }
  497. var block types.StorageBlock
  498. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  499. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  500. return nil
  501. }
  502. return (*types.Block)(&block)
  503. }
  504. // returns a formatted MIP mapped key by adding prefix, canonical number and level
  505. //
  506. // ex. fn(98, 1000) = (prefix || 1000 || 0)
  507. func mipmapKey(num, level uint64) []byte {
  508. lkey := make([]byte, 8)
  509. binary.BigEndian.PutUint64(lkey, level)
  510. key := new(big.Int).SetUint64(num / level * level)
  511. return append(mipmapPre, append(lkey, key.Bytes()...)...)
  512. }
  513. // WriteMapmapBloom writes each address included in the receipts' logs to the
  514. // MIP bloom bin.
  515. func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
  516. mipmapBloomMu.Lock()
  517. defer mipmapBloomMu.Unlock()
  518. batch := db.NewBatch()
  519. for _, level := range MIPMapLevels {
  520. key := mipmapKey(number, level)
  521. bloomDat, _ := db.Get(key)
  522. bloom := types.BytesToBloom(bloomDat)
  523. for _, receipt := range receipts {
  524. for _, log := range receipt.Logs {
  525. bloom.Add(log.Address.Big())
  526. }
  527. }
  528. batch.Put(key, bloom.Bytes())
  529. }
  530. if err := batch.Write(); err != nil {
  531. return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
  532. }
  533. return nil
  534. }
  535. // GetMipmapBloom returns a bloom filter using the number and level as input
  536. // parameters. For available levels see MIPMapLevels.
  537. func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
  538. bloomDat, _ := db.Get(mipmapKey(number, level))
  539. return types.BytesToBloom(bloomDat)
  540. }
  541. // GetBlockChainVersion reads the version number from db.
  542. func GetBlockChainVersion(db ethdb.Database) int {
  543. var vsn uint
  544. enc, _ := db.Get([]byte("BlockchainVersion"))
  545. rlp.DecodeBytes(enc, &vsn)
  546. return int(vsn)
  547. }
  548. // WriteBlockChainVersion writes vsn as the version number to db.
  549. func WriteBlockChainVersion(db ethdb.Database, vsn int) {
  550. enc, _ := rlp.EncodeToBytes(uint(vsn))
  551. db.Put([]byte("BlockchainVersion"), enc)
  552. }
  553. // WriteChainConfig writes the chain config settings to the database.
  554. func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *params.ChainConfig) error {
  555. // short circuit and ignore if nil config. GetChainConfig
  556. // will return a default.
  557. if cfg == nil {
  558. return nil
  559. }
  560. jsonChainConfig, err := json.Marshal(cfg)
  561. if err != nil {
  562. return err
  563. }
  564. return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
  565. }
  566. // GetChainConfig will fetch the network settings based on the given hash.
  567. func GetChainConfig(db ethdb.Database, hash common.Hash) (*params.ChainConfig, error) {
  568. jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
  569. if len(jsonChainConfig) == 0 {
  570. return nil, ChainConfigNotFoundErr
  571. }
  572. var config params.ChainConfig
  573. if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
  574. return nil, err
  575. }
  576. return &config, nil
  577. }
  578. // FindCommonAncestor returns the last common ancestor of two block headers
  579. func FindCommonAncestor(db ethdb.Database, a, b *types.Header) *types.Header {
  580. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  581. a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
  582. if a == nil {
  583. return nil
  584. }
  585. }
  586. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  587. b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
  588. if b == nil {
  589. return nil
  590. }
  591. }
  592. for a.Hash() != b.Hash() {
  593. a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
  594. if a == nil {
  595. return nil
  596. }
  597. b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
  598. if b == nil {
  599. return nil
  600. }
  601. }
  602. return a
  603. }