database_util.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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.NewRegisteredCounter("db/preimage/total", nil)
  62. preimageHitCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil)
  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, error) {
  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. return db.Get(key)
  305. }
  306. // WriteCanonicalHash stores the canonical hash for the given block number.
  307. func WriteCanonicalHash(db ethdb.Putter, hash common.Hash, number uint64) error {
  308. key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
  309. if err := db.Put(key, hash.Bytes()); err != nil {
  310. log.Crit("Failed to store number to hash mapping", "err", err)
  311. }
  312. return nil
  313. }
  314. // WriteHeadHeaderHash stores the head header's hash.
  315. func WriteHeadHeaderHash(db ethdb.Putter, hash common.Hash) error {
  316. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  317. log.Crit("Failed to store last header's hash", "err", err)
  318. }
  319. return nil
  320. }
  321. // WriteHeadBlockHash stores the head block's hash.
  322. func WriteHeadBlockHash(db ethdb.Putter, hash common.Hash) error {
  323. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  324. log.Crit("Failed to store last block's hash", "err", err)
  325. }
  326. return nil
  327. }
  328. // WriteHeadFastBlockHash stores the fast head block's hash.
  329. func WriteHeadFastBlockHash(db ethdb.Putter, hash common.Hash) error {
  330. if err := db.Put(headFastKey, hash.Bytes()); err != nil {
  331. log.Crit("Failed to store last fast block's hash", "err", err)
  332. }
  333. return nil
  334. }
  335. // WriteHeader serializes a block header into the database.
  336. func WriteHeader(db ethdb.Putter, header *types.Header) error {
  337. data, err := rlp.EncodeToBytes(header)
  338. if err != nil {
  339. return err
  340. }
  341. hash := header.Hash().Bytes()
  342. num := header.Number.Uint64()
  343. encNum := encodeBlockNumber(num)
  344. key := append(blockHashPrefix, hash...)
  345. if err := db.Put(key, encNum); err != nil {
  346. log.Crit("Failed to store hash to number mapping", "err", err)
  347. }
  348. key = append(append(headerPrefix, encNum...), hash...)
  349. if err := db.Put(key, data); err != nil {
  350. log.Crit("Failed to store header", "err", err)
  351. }
  352. return nil
  353. }
  354. // WriteBody serializes the body of a block into the database.
  355. func WriteBody(db ethdb.Putter, hash common.Hash, number uint64, body *types.Body) error {
  356. data, err := rlp.EncodeToBytes(body)
  357. if err != nil {
  358. return err
  359. }
  360. return WriteBodyRLP(db, hash, number, data)
  361. }
  362. // WriteBodyRLP writes a serialized body of a block into the database.
  363. func WriteBodyRLP(db ethdb.Putter, hash common.Hash, number uint64, rlp rlp.RawValue) error {
  364. key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  365. if err := db.Put(key, rlp); err != nil {
  366. log.Crit("Failed to store block body", "err", err)
  367. }
  368. return nil
  369. }
  370. // WriteTd serializes the total difficulty of a block into the database.
  371. func WriteTd(db ethdb.Putter, hash common.Hash, number uint64, td *big.Int) error {
  372. data, err := rlp.EncodeToBytes(td)
  373. if err != nil {
  374. return err
  375. }
  376. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
  377. if err := db.Put(key, data); err != nil {
  378. log.Crit("Failed to store block total difficulty", "err", err)
  379. }
  380. return nil
  381. }
  382. // WriteBlock serializes a block into the database, header and body separately.
  383. func WriteBlock(db ethdb.Putter, block *types.Block) error {
  384. // Store the body first to retain database consistency
  385. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  386. return err
  387. }
  388. // Store the header too, signaling full block ownership
  389. if err := WriteHeader(db, block.Header()); err != nil {
  390. return err
  391. }
  392. return nil
  393. }
  394. // WriteBlockReceipts stores all the transaction receipts belonging to a block
  395. // as a single receipt slice. This is used during chain reorganisations for
  396. // rescheduling dropped transactions.
  397. func WriteBlockReceipts(db ethdb.Putter, hash common.Hash, number uint64, receipts types.Receipts) error {
  398. // Convert the receipts into their storage form and serialize them
  399. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  400. for i, receipt := range receipts {
  401. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  402. }
  403. bytes, err := rlp.EncodeToBytes(storageReceipts)
  404. if err != nil {
  405. return err
  406. }
  407. // Store the flattened receipt slice
  408. key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  409. if err := db.Put(key, bytes); err != nil {
  410. log.Crit("Failed to store block receipts", "err", err)
  411. }
  412. return nil
  413. }
  414. // WriteTxLookupEntries stores a positional metadata for every transaction from
  415. // a block, enabling hash based transaction and receipt lookups.
  416. func WriteTxLookupEntries(db ethdb.Putter, block *types.Block) error {
  417. // Iterate over each transaction and encode its metadata
  418. for i, tx := range block.Transactions() {
  419. entry := TxLookupEntry{
  420. BlockHash: block.Hash(),
  421. BlockIndex: block.NumberU64(),
  422. Index: uint64(i),
  423. }
  424. data, err := rlp.EncodeToBytes(entry)
  425. if err != nil {
  426. return err
  427. }
  428. if err := db.Put(append(lookupPrefix, tx.Hash().Bytes()...), data); err != nil {
  429. return err
  430. }
  431. }
  432. return nil
  433. }
  434. // WriteBloomBits writes the compressed bloom bits vector belonging to the given
  435. // section and bit index.
  436. func WriteBloomBits(db ethdb.Putter, bit uint, section uint64, head common.Hash, bits []byte) {
  437. key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...)
  438. binary.BigEndian.PutUint16(key[1:], uint16(bit))
  439. binary.BigEndian.PutUint64(key[3:], section)
  440. if err := db.Put(key, bits); err != nil {
  441. log.Crit("Failed to store bloom bits", "err", err)
  442. }
  443. }
  444. // DeleteCanonicalHash removes the number to hash canonical mapping.
  445. func DeleteCanonicalHash(db DatabaseDeleter, number uint64) {
  446. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
  447. }
  448. // DeleteHeader removes all block header data associated with a hash.
  449. func DeleteHeader(db DatabaseDeleter, hash common.Hash, number uint64) {
  450. db.Delete(append(blockHashPrefix, hash.Bytes()...))
  451. db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  452. }
  453. // DeleteBody removes all block body data associated with a hash.
  454. func DeleteBody(db DatabaseDeleter, hash common.Hash, number uint64) {
  455. db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  456. }
  457. // DeleteTd removes all block total difficulty data associated with a hash.
  458. func DeleteTd(db DatabaseDeleter, hash common.Hash, number uint64) {
  459. db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
  460. }
  461. // DeleteBlock removes all block data associated with a hash.
  462. func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) {
  463. DeleteBlockReceipts(db, hash, number)
  464. DeleteHeader(db, hash, number)
  465. DeleteBody(db, hash, number)
  466. DeleteTd(db, hash, number)
  467. }
  468. // DeleteBlockReceipts removes all receipt data associated with a block hash.
  469. func DeleteBlockReceipts(db DatabaseDeleter, hash common.Hash, number uint64) {
  470. db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  471. }
  472. // DeleteTxLookupEntry removes all transaction data associated with a hash.
  473. func DeleteTxLookupEntry(db DatabaseDeleter, hash common.Hash) {
  474. db.Delete(append(lookupPrefix, hash.Bytes()...))
  475. }
  476. // PreimageTable returns a Database instance with the key prefix for preimage entries.
  477. func PreimageTable(db ethdb.Database) ethdb.Database {
  478. return ethdb.NewTable(db, preimagePrefix)
  479. }
  480. // WritePreimages writes the provided set of preimages to the database. `number` is the
  481. // current block number, and is used for debug messages only.
  482. func WritePreimages(db ethdb.Database, number uint64, preimages map[common.Hash][]byte) error {
  483. table := PreimageTable(db)
  484. batch := table.NewBatch()
  485. hitCount := 0
  486. for hash, preimage := range preimages {
  487. if _, err := table.Get(hash.Bytes()); err != nil {
  488. batch.Put(hash.Bytes(), preimage)
  489. hitCount++
  490. }
  491. }
  492. preimageCounter.Inc(int64(len(preimages)))
  493. preimageHitCounter.Inc(int64(hitCount))
  494. if hitCount > 0 {
  495. if err := batch.Write(); err != nil {
  496. return fmt.Errorf("preimage write fail for block %d: %v", number, err)
  497. }
  498. }
  499. return nil
  500. }
  501. // GetBlockChainVersion reads the version number from db.
  502. func GetBlockChainVersion(db DatabaseReader) int {
  503. var vsn uint
  504. enc, _ := db.Get([]byte("BlockchainVersion"))
  505. rlp.DecodeBytes(enc, &vsn)
  506. return int(vsn)
  507. }
  508. // WriteBlockChainVersion writes vsn as the version number to db.
  509. func WriteBlockChainVersion(db ethdb.Putter, vsn int) {
  510. enc, _ := rlp.EncodeToBytes(uint(vsn))
  511. db.Put([]byte("BlockchainVersion"), enc)
  512. }
  513. // WriteChainConfig writes the chain config settings to the database.
  514. func WriteChainConfig(db ethdb.Putter, hash common.Hash, cfg *params.ChainConfig) error {
  515. // short circuit and ignore if nil config. GetChainConfig
  516. // will return a default.
  517. if cfg == nil {
  518. return nil
  519. }
  520. jsonChainConfig, err := json.Marshal(cfg)
  521. if err != nil {
  522. return err
  523. }
  524. return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
  525. }
  526. // GetChainConfig will fetch the network settings based on the given hash.
  527. func GetChainConfig(db DatabaseReader, hash common.Hash) (*params.ChainConfig, error) {
  528. jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
  529. if len(jsonChainConfig) == 0 {
  530. return nil, ErrChainConfigNotFound
  531. }
  532. var config params.ChainConfig
  533. if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
  534. return nil, err
  535. }
  536. return &config, nil
  537. }
  538. // FindCommonAncestor returns the last common ancestor of two block headers
  539. func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header {
  540. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  541. a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
  542. if a == nil {
  543. return nil
  544. }
  545. }
  546. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  547. b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
  548. if b == nil {
  549. return nil
  550. }
  551. }
  552. for a.Hash() != b.Hash() {
  553. a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
  554. if a == nil {
  555. return nil
  556. }
  557. b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
  558. if b == nil {
  559. return nil
  560. }
  561. }
  562. return a
  563. }