database_util.go 22 KB

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