database_util.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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.
  186. func GetBlock(db ethdb.Database, hash common.Hash, number uint64) *types.Block {
  187. // Retrieve the block header and body contents
  188. header := GetHeader(db, hash, number)
  189. if header == nil {
  190. return nil
  191. }
  192. body := GetBody(db, hash, number)
  193. if body == nil {
  194. return nil
  195. }
  196. // Reassemble the block and return
  197. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  198. }
  199. // GetBlockReceipts retrieves the receipts generated by the transactions included
  200. // in a block given by its hash.
  201. func GetBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) types.Receipts {
  202. data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
  203. if len(data) == 0 {
  204. data, _ = db.Get(append(oldBlockReceiptsPrefix, hash.Bytes()...))
  205. if len(data) == 0 {
  206. return nil
  207. }
  208. }
  209. storageReceipts := []*types.ReceiptForStorage{}
  210. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  211. glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, err)
  212. return nil
  213. }
  214. receipts := make(types.Receipts, len(storageReceipts))
  215. for i, receipt := range storageReceipts {
  216. receipts[i] = (*types.Receipt)(receipt)
  217. }
  218. return receipts
  219. }
  220. // GetTransaction retrieves a specific transaction from the database, along with
  221. // its added positional metadata.
  222. func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
  223. // Retrieve the transaction itself from the database
  224. data, _ := db.Get(hash.Bytes())
  225. if len(data) == 0 {
  226. return nil, common.Hash{}, 0, 0
  227. }
  228. var tx types.Transaction
  229. if err := rlp.DecodeBytes(data, &tx); err != nil {
  230. return nil, common.Hash{}, 0, 0
  231. }
  232. // Retrieve the blockchain positional metadata
  233. data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
  234. if len(data) == 0 {
  235. return nil, common.Hash{}, 0, 0
  236. }
  237. var meta struct {
  238. BlockHash common.Hash
  239. BlockIndex uint64
  240. Index uint64
  241. }
  242. if err := rlp.DecodeBytes(data, &meta); err != nil {
  243. return nil, common.Hash{}, 0, 0
  244. }
  245. return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
  246. }
  247. // GetReceipt returns a receipt by hash
  248. func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
  249. data, _ := db.Get(append(receiptsPrefix, txHash[:]...))
  250. if len(data) == 0 {
  251. return nil
  252. }
  253. var receipt types.ReceiptForStorage
  254. err := rlp.DecodeBytes(data, &receipt)
  255. if err != nil {
  256. glog.V(logger.Core).Infoln("GetReceipt err:", err)
  257. }
  258. return (*types.Receipt)(&receipt)
  259. }
  260. // WriteCanonicalHash stores the canonical hash for the given block number.
  261. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  262. key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
  263. if err := db.Put(key, hash.Bytes()); err != nil {
  264. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  265. }
  266. return nil
  267. }
  268. // WriteHeadHeaderHash stores the head header's hash.
  269. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  270. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  271. glog.Fatalf("failed to store last header's hash into database: %v", err)
  272. }
  273. return nil
  274. }
  275. // WriteHeadBlockHash stores the head block's hash.
  276. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  277. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  278. glog.Fatalf("failed to store last block's hash into database: %v", err)
  279. }
  280. return nil
  281. }
  282. // WriteHeadFastBlockHash stores the fast head block's hash.
  283. func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
  284. if err := db.Put(headFastKey, hash.Bytes()); err != nil {
  285. glog.Fatalf("failed to store last fast block's hash into database: %v", err)
  286. }
  287. return nil
  288. }
  289. // WriteHeader serializes a block header into the database.
  290. func WriteHeader(db ethdb.Database, header *types.Header) error {
  291. data, err := rlp.EncodeToBytes(header)
  292. if err != nil {
  293. return err
  294. }
  295. hash := header.Hash().Bytes()
  296. num := header.Number.Uint64()
  297. encNum := encodeBlockNumber(num)
  298. key := append(blockHashPrefix, hash...)
  299. if err := db.Put(key, encNum); err != nil {
  300. glog.Fatalf("failed to store hash to number mapping into database: %v", err)
  301. }
  302. key = append(append(headerPrefix, encNum...), hash...)
  303. if err := db.Put(key, data); err != nil {
  304. glog.Fatalf("failed to store header into database: %v", err)
  305. }
  306. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, hash[:4])
  307. return nil
  308. }
  309. // WriteBody serializes the body of a block into the database.
  310. func WriteBody(db ethdb.Database, hash common.Hash, number uint64, body *types.Body) error {
  311. data, err := rlp.EncodeToBytes(body)
  312. if err != nil {
  313. return err
  314. }
  315. key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  316. if err := db.Put(key, data); err != nil {
  317. glog.Fatalf("failed to store block body into database: %v", err)
  318. }
  319. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  320. return nil
  321. }
  322. // WriteTd serializes the total difficulty of a block into the database.
  323. func WriteTd(db ethdb.Database, hash common.Hash, number uint64, td *big.Int) error {
  324. data, err := rlp.EncodeToBytes(td)
  325. if err != nil {
  326. return err
  327. }
  328. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
  329. if err := db.Put(key, data); err != nil {
  330. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  331. }
  332. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  333. return nil
  334. }
  335. // WriteBlock serializes a block into the database, header and body separately.
  336. func WriteBlock(db ethdb.Database, block *types.Block) error {
  337. // Store the body first to retain database consistency
  338. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  339. return err
  340. }
  341. // Store the header too, signaling full block ownership
  342. if err := WriteHeader(db, block.Header()); err != nil {
  343. return err
  344. }
  345. return nil
  346. }
  347. // WriteBlockReceipts stores all the transaction receipts belonging to a block
  348. // as a single receipt slice. This is used during chain reorganisations for
  349. // rescheduling dropped transactions.
  350. func WriteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64, receipts types.Receipts) error {
  351. // Convert the receipts into their storage form and serialize them
  352. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  353. for i, receipt := range receipts {
  354. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  355. }
  356. bytes, err := rlp.EncodeToBytes(storageReceipts)
  357. if err != nil {
  358. return err
  359. }
  360. // Store the flattened receipt slice
  361. key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  362. if err := db.Put(key, bytes); err != nil {
  363. glog.Fatalf("failed to store block receipts into database: %v", err)
  364. }
  365. glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
  366. return nil
  367. }
  368. // WriteTransactions stores the transactions associated with a specific block
  369. // into the given database. Beside writing the transaction, the function also
  370. // stores a metadata entry along with the transaction, detailing the position
  371. // of this within the blockchain.
  372. func WriteTransactions(db ethdb.Database, block *types.Block) error {
  373. batch := db.NewBatch()
  374. // Iterate over each transaction and encode it with its metadata
  375. for i, tx := range block.Transactions() {
  376. // Encode and queue up the transaction for storage
  377. data, err := rlp.EncodeToBytes(tx)
  378. if err != nil {
  379. return err
  380. }
  381. if err := batch.Put(tx.Hash().Bytes(), data); err != nil {
  382. return err
  383. }
  384. // Encode and queue up the transaction metadata for storage
  385. meta := struct {
  386. BlockHash common.Hash
  387. BlockIndex uint64
  388. Index uint64
  389. }{
  390. BlockHash: block.Hash(),
  391. BlockIndex: block.NumberU64(),
  392. Index: uint64(i),
  393. }
  394. data, err = rlp.EncodeToBytes(meta)
  395. if err != nil {
  396. return err
  397. }
  398. if err := batch.Put(append(tx.Hash().Bytes(), txMetaSuffix...), data); err != nil {
  399. return err
  400. }
  401. }
  402. // Write the scheduled data into the database
  403. if err := batch.Write(); err != nil {
  404. glog.Fatalf("failed to store transactions into database: %v", err)
  405. }
  406. return nil
  407. }
  408. // WriteReceipts stores a batch of transaction receipts into the database.
  409. func WriteReceipts(db ethdb.Database, receipts types.Receipts) error {
  410. batch := db.NewBatch()
  411. // Iterate over all the receipts and queue them for database injection
  412. for _, receipt := range receipts {
  413. storageReceipt := (*types.ReceiptForStorage)(receipt)
  414. data, err := rlp.EncodeToBytes(storageReceipt)
  415. if err != nil {
  416. return err
  417. }
  418. if err := batch.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data); err != nil {
  419. return err
  420. }
  421. }
  422. // Write the scheduled data into the database
  423. if err := batch.Write(); err != nil {
  424. glog.Fatalf("failed to store receipts into database: %v", err)
  425. }
  426. return nil
  427. }
  428. // DeleteCanonicalHash removes the number to hash canonical mapping.
  429. func DeleteCanonicalHash(db ethdb.Database, number uint64) {
  430. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
  431. }
  432. // DeleteHeader removes all block header data associated with a hash.
  433. func DeleteHeader(db ethdb.Database, hash common.Hash, number uint64) {
  434. db.Delete(append(blockHashPrefix, hash.Bytes()...))
  435. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  436. }
  437. // DeleteBody removes all block body data associated with a hash.
  438. func DeleteBody(db ethdb.Database, hash common.Hash, number uint64) {
  439. db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  440. }
  441. // DeleteTd removes all block total difficulty data associated with a hash.
  442. func DeleteTd(db ethdb.Database, hash common.Hash, number uint64) {
  443. db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
  444. }
  445. // DeleteBlock removes all block data associated with a hash.
  446. func DeleteBlock(db ethdb.Database, hash common.Hash, number uint64) {
  447. DeleteBlockReceipts(db, hash, number)
  448. DeleteHeader(db, hash, number)
  449. DeleteBody(db, hash, number)
  450. DeleteTd(db, hash, number)
  451. }
  452. // DeleteBlockReceipts removes all receipt data associated with a block hash.
  453. func DeleteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) {
  454. db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  455. }
  456. // DeleteTransaction removes all transaction data associated with a hash.
  457. func DeleteTransaction(db ethdb.Database, hash common.Hash) {
  458. db.Delete(hash.Bytes())
  459. db.Delete(append(hash.Bytes(), txMetaSuffix...))
  460. }
  461. // DeleteReceipt removes all receipt data associated with a transaction hash.
  462. func DeleteReceipt(db ethdb.Database, hash common.Hash) {
  463. db.Delete(append(receiptsPrefix, hash.Bytes()...))
  464. }
  465. // [deprecated by the header/block split, remove eventually]
  466. // GetBlockByHashOld returns the old combined block corresponding to the hash
  467. // or nil if not found. This method is only used by the upgrade mechanism to
  468. // access the old combined block representation. It will be dropped after the
  469. // network transitions to eth/63.
  470. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  471. data, _ := db.Get(append(oldBlockHashPrefix, hash[:]...))
  472. if len(data) == 0 {
  473. return nil
  474. }
  475. var block types.StorageBlock
  476. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  477. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  478. return nil
  479. }
  480. return (*types.Block)(&block)
  481. }
  482. // returns a formatted MIP mapped key by adding prefix, canonical number and level
  483. //
  484. // ex. fn(98, 1000) = (prefix || 1000 || 0)
  485. func mipmapKey(num, level uint64) []byte {
  486. lkey := make([]byte, 8)
  487. binary.BigEndian.PutUint64(lkey, level)
  488. key := new(big.Int).SetUint64(num / level * level)
  489. return append(mipmapPre, append(lkey, key.Bytes()...)...)
  490. }
  491. // WriteMapmapBloom writes each address included in the receipts' logs to the
  492. // MIP bloom bin.
  493. func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
  494. batch := db.NewBatch()
  495. for _, level := range MIPMapLevels {
  496. key := mipmapKey(number, level)
  497. bloomDat, _ := db.Get(key)
  498. bloom := types.BytesToBloom(bloomDat)
  499. for _, receipt := range receipts {
  500. for _, log := range receipt.Logs {
  501. bloom.Add(log.Address.Big())
  502. }
  503. }
  504. batch.Put(key, bloom.Bytes())
  505. }
  506. if err := batch.Write(); err != nil {
  507. return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
  508. }
  509. return nil
  510. }
  511. // GetMipmapBloom returns a bloom filter using the number and level as input
  512. // parameters. For available levels see MIPMapLevels.
  513. func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
  514. bloomDat, _ := db.Get(mipmapKey(number, level))
  515. return types.BytesToBloom(bloomDat)
  516. }
  517. // GetBlockChainVersion reads the version number from db.
  518. func GetBlockChainVersion(db ethdb.Database) int {
  519. var vsn uint
  520. enc, _ := db.Get([]byte("BlockchainVersion"))
  521. rlp.DecodeBytes(enc, &vsn)
  522. return int(vsn)
  523. }
  524. // WriteBlockChainVersion writes vsn as the version number to db.
  525. func WriteBlockChainVersion(db ethdb.Database, vsn int) {
  526. enc, _ := rlp.EncodeToBytes(uint(vsn))
  527. db.Put([]byte("BlockchainVersion"), enc)
  528. }
  529. // WriteChainConfig writes the chain config settings to the database.
  530. func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *ChainConfig) error {
  531. // short circuit and ignore if nil config. GetChainConfig
  532. // will return a default.
  533. if cfg == nil {
  534. return nil
  535. }
  536. jsonChainConfig, err := json.Marshal(cfg)
  537. if err != nil {
  538. return err
  539. }
  540. return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
  541. }
  542. // GetChainConfig will fetch the network settings based on the given hash.
  543. func GetChainConfig(db ethdb.Database, hash common.Hash) (*ChainConfig, error) {
  544. jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
  545. if len(jsonChainConfig) == 0 {
  546. return nil, ChainConfigNotFoundErr
  547. }
  548. var config ChainConfig
  549. if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
  550. return nil, err
  551. }
  552. return &config, nil
  553. }