database_util.go 22 KB

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