database_util.go 22 KB

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