database_util.go 22 KB

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