database_util.go 19 KB

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