database_util.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. "fmt"
  22. "math/big"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/logger"
  27. "github.com/ethereum/go-ethereum/logger/glog"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. )
  30. var (
  31. headHeaderKey = []byte("LastHeader")
  32. headBlockKey = []byte("LastBlock")
  33. headFastKey = []byte("LastFast")
  34. headerPrefix = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
  35. tdSuffix = []byte("t") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
  36. numSuffix = []byte("n") // headerPrefix + num (uint64 big endian) + numSuffix -> hash
  37. blockHashPrefix = []byte("H") // blockHashPrefix + hash -> num (uint64 big endian)
  38. bodyPrefix = []byte("b") // bodyPrefix + num (uint64 big endian) + hash -> block body
  39. blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
  40. txMetaSuffix = []byte{0x01}
  41. receiptsPrefix = []byte("receipts-")
  42. mipmapPre = []byte("mipmap-log-bloom-")
  43. MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
  44. configPrefix = []byte("ethereum-config-") // config prefix for the db
  45. // used by old (non-sequential keys) db, now only used for conversion
  46. oldBlockPrefix = []byte("block-")
  47. oldHeaderSuffix = []byte("-header")
  48. oldTdSuffix = []byte("-td") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
  49. oldBodySuffix = []byte("-body")
  50. oldBlockNumPrefix = []byte("block-num-")
  51. oldBlockReceiptsPrefix = []byte("receipts-block-")
  52. oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
  53. )
  54. // encodeBlockNumber encodes a block number as big endian uint64
  55. func encodeBlockNumber(number uint64) []byte {
  56. enc := make([]byte, 8)
  57. binary.BigEndian.PutUint64(enc, number)
  58. return enc
  59. }
  60. // GetCanonicalHash retrieves a hash assigned to a canonical block number.
  61. func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
  62. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
  63. if len(data) == 0 {
  64. data, _ = db.Get(append(oldBlockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  65. if len(data) == 0 {
  66. return common.Hash{}
  67. }
  68. }
  69. return common.BytesToHash(data)
  70. }
  71. // missingNumber is returned by GetBlockNumber if no header with the
  72. // given block hash has been stored in the database
  73. const missingNumber = uint64(0xffffffffffffffff)
  74. // GetBlockNumber returns the block number assigned to a block hash
  75. // if the corresponding header is present in the database
  76. func GetBlockNumber(db ethdb.Database, hash common.Hash) uint64 {
  77. data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...))
  78. if len(data) != 8 {
  79. data, _ := db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldHeaderSuffix...))
  80. if len(data) == 0 {
  81. return missingNumber
  82. }
  83. header := new(types.Header)
  84. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  85. glog.Fatalf("failed to decode block header: %v", err)
  86. }
  87. return header.Number.Uint64()
  88. }
  89. return binary.BigEndian.Uint64(data)
  90. }
  91. // GetHeadHeaderHash retrieves the hash of the current canonical head block's
  92. // header. The difference between this and GetHeadBlockHash is that whereas the
  93. // last block hash is only updated upon a full block import, the last header
  94. // hash is updated already at header import, allowing head tracking for the
  95. // light synchronization mechanism.
  96. func GetHeadHeaderHash(db ethdb.Database) common.Hash {
  97. data, _ := db.Get(headHeaderKey)
  98. if len(data) == 0 {
  99. return common.Hash{}
  100. }
  101. return common.BytesToHash(data)
  102. }
  103. // GetHeadBlockHash retrieves the hash of the current canonical head block.
  104. func GetHeadBlockHash(db ethdb.Database) common.Hash {
  105. data, _ := db.Get(headBlockKey)
  106. if len(data) == 0 {
  107. return common.Hash{}
  108. }
  109. return common.BytesToHash(data)
  110. }
  111. // GetHeadFastBlockHash retrieves the hash of the current canonical head block during
  112. // fast synchronization. The difference between this and GetHeadBlockHash is that
  113. // whereas the last block hash is only updated upon a full block import, the last
  114. // fast hash is updated when importing pre-processed blocks.
  115. func GetHeadFastBlockHash(db ethdb.Database) common.Hash {
  116. data, _ := db.Get(headFastKey)
  117. if len(data) == 0 {
  118. return common.Hash{}
  119. }
  120. return common.BytesToHash(data)
  121. }
  122. // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
  123. // if the header's not found.
  124. func GetHeaderRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
  125. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  126. if len(data) == 0 {
  127. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldHeaderSuffix...))
  128. }
  129. return data
  130. }
  131. // GetHeader retrieves the block header corresponding to the hash, nil if none
  132. // found.
  133. func GetHeader(db ethdb.Database, hash common.Hash, number uint64) *types.Header {
  134. data := GetHeaderRLP(db, hash, number)
  135. if len(data) == 0 {
  136. return nil
  137. }
  138. header := new(types.Header)
  139. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  140. glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
  141. return nil
  142. }
  143. return header
  144. }
  145. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  146. func GetBodyRLP(db ethdb.Database, hash common.Hash, number uint64) rlp.RawValue {
  147. data, _ := db.Get(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  148. if len(data) == 0 {
  149. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldBodySuffix...))
  150. }
  151. return data
  152. }
  153. // GetBody retrieves the block body (transactons, uncles) corresponding to the
  154. // hash, nil if none found.
  155. func GetBody(db ethdb.Database, hash common.Hash, number uint64) *types.Body {
  156. data := GetBodyRLP(db, hash, number)
  157. if len(data) == 0 {
  158. return nil
  159. }
  160. body := new(types.Body)
  161. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  162. glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
  163. return nil
  164. }
  165. return body
  166. }
  167. // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
  168. // none found.
  169. func GetTd(db ethdb.Database, hash common.Hash, number uint64) *big.Int {
  170. data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...))
  171. if len(data) == 0 {
  172. data, _ = db.Get(append(append(oldBlockPrefix, hash.Bytes()...), oldTdSuffix...))
  173. if len(data) == 0 {
  174. return nil
  175. }
  176. }
  177. td := new(big.Int)
  178. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  179. glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
  180. return nil
  181. }
  182. return td
  183. }
  184. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  185. // back from the stored header and body. If either the header or body could not
  186. // be retrieved nil is returned.
  187. //
  188. // Note, due to concurrent download of header and block body the header and thus
  189. // canonical hash can be stored in the database but the body data not (yet).
  190. func GetBlock(db ethdb.Database, hash common.Hash, number uint64) *types.Block {
  191. // Retrieve the block header and body contents
  192. header := GetHeader(db, hash, number)
  193. if header == nil {
  194. return nil
  195. }
  196. body := GetBody(db, hash, number)
  197. if body == nil {
  198. return nil
  199. }
  200. // Reassemble the block and return
  201. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  202. }
  203. // GetBlockReceipts retrieves the receipts generated by the transactions included
  204. // in a block given by its hash.
  205. func GetBlockReceipts(db ethdb.Database, hash common.Hash, number uint64) types.Receipts {
  206. data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
  207. if len(data) == 0 {
  208. data, _ = db.Get(append(oldBlockReceiptsPrefix, hash.Bytes()...))
  209. if len(data) == 0 {
  210. return nil
  211. }
  212. }
  213. storageReceipts := []*types.ReceiptForStorage{}
  214. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  215. glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, 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. // GetTransaction retrieves a specific transaction from the database, along with
  225. // its added positional metadata.
  226. func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
  227. // Retrieve the transaction itself from the database
  228. data, _ := db.Get(hash.Bytes())
  229. if len(data) == 0 {
  230. return nil, common.Hash{}, 0, 0
  231. }
  232. var tx types.Transaction
  233. if err := rlp.DecodeBytes(data, &tx); err != nil {
  234. return nil, common.Hash{}, 0, 0
  235. }
  236. // Retrieve the blockchain positional metadata
  237. data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
  238. if len(data) == 0 {
  239. return nil, common.Hash{}, 0, 0
  240. }
  241. var meta struct {
  242. BlockHash common.Hash
  243. BlockIndex uint64
  244. Index uint64
  245. }
  246. if err := rlp.DecodeBytes(data, &meta); err != nil {
  247. return nil, common.Hash{}, 0, 0
  248. }
  249. return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
  250. }
  251. // GetReceipt returns a receipt by hash
  252. func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
  253. data, _ := db.Get(append(receiptsPrefix, txHash[:]...))
  254. if len(data) == 0 {
  255. return nil
  256. }
  257. var receipt types.ReceiptForStorage
  258. err := rlp.DecodeBytes(data, &receipt)
  259. if err != nil {
  260. glog.V(logger.Core).Infoln("GetReceipt err:", err)
  261. }
  262. return (*types.Receipt)(&receipt)
  263. }
  264. // WriteCanonicalHash stores the canonical hash for the given block number.
  265. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  266. key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
  267. if err := db.Put(key, hash.Bytes()); err != nil {
  268. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  269. }
  270. return nil
  271. }
  272. // WriteHeadHeaderHash stores the head header's hash.
  273. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  274. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  275. glog.Fatalf("failed to store last header's hash into database: %v", err)
  276. }
  277. return nil
  278. }
  279. // WriteHeadBlockHash stores the head block's hash.
  280. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  281. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  282. glog.Fatalf("failed to store last block's hash into database: %v", err)
  283. }
  284. return nil
  285. }
  286. // WriteHeadFastBlockHash stores the fast head block's hash.
  287. func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
  288. if err := db.Put(headFastKey, hash.Bytes()); err != nil {
  289. glog.Fatalf("failed to store last fast block's hash into database: %v", err)
  290. }
  291. return nil
  292. }
  293. // WriteHeader serializes a block header into the database.
  294. func WriteHeader(db ethdb.Database, header *types.Header) error {
  295. data, err := rlp.EncodeToBytes(header)
  296. if err != nil {
  297. return err
  298. }
  299. hash := header.Hash().Bytes()
  300. num := header.Number.Uint64()
  301. encNum := encodeBlockNumber(num)
  302. key := append(blockHashPrefix, hash...)
  303. if err := db.Put(key, encNum); err != nil {
  304. glog.Fatalf("failed to store hash to number mapping into database: %v", err)
  305. }
  306. key = append(append(headerPrefix, encNum...), hash...)
  307. if err := db.Put(key, data); err != nil {
  308. glog.Fatalf("failed to store header into database: %v", err)
  309. }
  310. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, hash[:4])
  311. return nil
  312. }
  313. // WriteBody serializes the body of a block into the database.
  314. func WriteBody(db ethdb.Database, hash common.Hash, number uint64, body *types.Body) error {
  315. data, err := rlp.EncodeToBytes(body)
  316. if err != nil {
  317. return err
  318. }
  319. return WriteBodyRLP(db, hash, number, data)
  320. }
  321. // WriteBodyRLP writes a serialized body of a block into the database.
  322. func WriteBodyRLP(db ethdb.Database, hash common.Hash, number uint64, rlp rlp.RawValue) error {
  323. key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  324. if err := db.Put(key, rlp); err != nil {
  325. glog.Fatalf("failed to store block body into database: %v", err)
  326. }
  327. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  328. return nil
  329. }
  330. // WriteTd serializes the total difficulty of a block into the database.
  331. func WriteTd(db ethdb.Database, hash common.Hash, number uint64, td *big.Int) error {
  332. data, err := rlp.EncodeToBytes(td)
  333. if err != nil {
  334. return err
  335. }
  336. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
  337. if err := db.Put(key, data); err != nil {
  338. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  339. }
  340. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  341. return nil
  342. }
  343. // WriteBlock serializes a block into the database, header and body separately.
  344. func WriteBlock(db ethdb.Database, block *types.Block) error {
  345. // Store the body first to retain database consistency
  346. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  347. return err
  348. }
  349. // Store the header too, signaling full block ownership
  350. if err := WriteHeader(db, block.Header()); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. // WriteBlockReceipts stores all the transaction receipts belonging to a block
  356. // as a single receipt slice. This is used during chain reorganisations for
  357. // rescheduling dropped transactions.
  358. func WriteBlockReceipts(db ethdb.Database, hash common.Hash, number uint64, receipts types.Receipts) error {
  359. // Convert the receipts into their storage form and serialize them
  360. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  361. for i, receipt := range receipts {
  362. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  363. }
  364. bytes, err := rlp.EncodeToBytes(storageReceipts)
  365. if err != nil {
  366. return err
  367. }
  368. // Store the flattened receipt slice
  369. key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  370. if err := db.Put(key, bytes); err != nil {
  371. glog.Fatalf("failed to store block receipts into database: %v", err)
  372. }
  373. glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
  374. return nil
  375. }
  376. // WriteTransactions stores the transactions associated with a specific block
  377. // into the given database. Beside writing the transaction, the function also
  378. // stores a metadata entry along with the transaction, detailing the position
  379. // of this within the blockchain.
  380. func WriteTransactions(db ethdb.Database, block *types.Block) error {
  381. batch := db.NewBatch()
  382. // Iterate over each transaction and encode it with its metadata
  383. for i, tx := range block.Transactions() {
  384. // Encode and queue up the transaction for storage
  385. data, err := rlp.EncodeToBytes(tx)
  386. if err != nil {
  387. return err
  388. }
  389. if err := batch.Put(tx.Hash().Bytes(), data); err != nil {
  390. return err
  391. }
  392. // Encode and queue up the transaction metadata for storage
  393. meta := struct {
  394. BlockHash common.Hash
  395. BlockIndex uint64
  396. Index uint64
  397. }{
  398. BlockHash: block.Hash(),
  399. BlockIndex: block.NumberU64(),
  400. Index: uint64(i),
  401. }
  402. data, err = rlp.EncodeToBytes(meta)
  403. if err != nil {
  404. return err
  405. }
  406. if err := batch.Put(append(tx.Hash().Bytes(), txMetaSuffix...), data); err != nil {
  407. return err
  408. }
  409. }
  410. // Write the scheduled data into the database
  411. if err := batch.Write(); err != nil {
  412. glog.Fatalf("failed to store transactions into database: %v", err)
  413. }
  414. return nil
  415. }
  416. // WriteReceipt stores a single transaction receipt into the database.
  417. func WriteReceipt(db ethdb.Database, receipt *types.Receipt) error {
  418. storageReceipt := (*types.ReceiptForStorage)(receipt)
  419. data, err := rlp.EncodeToBytes(storageReceipt)
  420. if err != nil {
  421. return err
  422. }
  423. return db.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data)
  424. }
  425. // WriteReceipts stores a batch of transaction receipts into the database.
  426. func WriteReceipts(db ethdb.Database, receipts types.Receipts) error {
  427. batch := db.NewBatch()
  428. // Iterate over all the receipts and queue them for database injection
  429. for _, receipt := range receipts {
  430. storageReceipt := (*types.ReceiptForStorage)(receipt)
  431. data, err := rlp.EncodeToBytes(storageReceipt)
  432. if err != nil {
  433. return err
  434. }
  435. if err := batch.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data); err != nil {
  436. return err
  437. }
  438. }
  439. // Write the scheduled data into the database
  440. if err := batch.Write(); err != nil {
  441. glog.Fatalf("failed to store receipts into database: %v", err)
  442. }
  443. return nil
  444. }
  445. // DeleteCanonicalHash removes the number to hash canonical mapping.
  446. func DeleteCanonicalHash(db ethdb.Database, 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 ethdb.Database, 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 ethdb.Database, 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 ethdb.Database, 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 ethdb.Database, 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 ethdb.Database, hash common.Hash, number uint64) {
  471. db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  472. }
  473. // DeleteTransaction removes all transaction data associated with a hash.
  474. func DeleteTransaction(db ethdb.Database, hash common.Hash) {
  475. db.Delete(hash.Bytes())
  476. db.Delete(append(hash.Bytes(), txMetaSuffix...))
  477. }
  478. // DeleteReceipt removes all receipt data associated with a transaction hash.
  479. func DeleteReceipt(db ethdb.Database, hash common.Hash) {
  480. db.Delete(append(receiptsPrefix, hash.Bytes()...))
  481. }
  482. // [deprecated by the header/block split, remove eventually]
  483. // GetBlockByHashOld returns the old combined block corresponding to the hash
  484. // or nil if not found. This method is only used by the upgrade mechanism to
  485. // access the old combined block representation. It will be dropped after the
  486. // network transitions to eth/63.
  487. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  488. data, _ := db.Get(append(oldBlockHashPrefix, hash[:]...))
  489. if len(data) == 0 {
  490. return nil
  491. }
  492. var block types.StorageBlock
  493. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  494. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  495. return nil
  496. }
  497. return (*types.Block)(&block)
  498. }
  499. // returns a formatted MIP mapped key by adding prefix, canonical number and level
  500. //
  501. // ex. fn(98, 1000) = (prefix || 1000 || 0)
  502. func mipmapKey(num, level uint64) []byte {
  503. lkey := make([]byte, 8)
  504. binary.BigEndian.PutUint64(lkey, level)
  505. key := new(big.Int).SetUint64(num / level * level)
  506. return append(mipmapPre, append(lkey, key.Bytes()...)...)
  507. }
  508. // WriteMapmapBloom writes each address included in the receipts' logs to the
  509. // MIP bloom bin.
  510. func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
  511. batch := db.NewBatch()
  512. for _, level := range MIPMapLevels {
  513. key := mipmapKey(number, level)
  514. bloomDat, _ := db.Get(key)
  515. bloom := types.BytesToBloom(bloomDat)
  516. for _, receipt := range receipts {
  517. for _, log := range receipt.Logs {
  518. bloom.Add(log.Address.Big())
  519. }
  520. }
  521. batch.Put(key, bloom.Bytes())
  522. }
  523. if err := batch.Write(); err != nil {
  524. return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
  525. }
  526. return nil
  527. }
  528. // GetMipmapBloom returns a bloom filter using the number and level as input
  529. // parameters. For available levels see MIPMapLevels.
  530. func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
  531. bloomDat, _ := db.Get(mipmapKey(number, level))
  532. return types.BytesToBloom(bloomDat)
  533. }
  534. // GetBlockChainVersion reads the version number from db.
  535. func GetBlockChainVersion(db ethdb.Database) int {
  536. var vsn uint
  537. enc, _ := db.Get([]byte("BlockchainVersion"))
  538. rlp.DecodeBytes(enc, &vsn)
  539. return int(vsn)
  540. }
  541. // WriteBlockChainVersion writes vsn as the version number to db.
  542. func WriteBlockChainVersion(db ethdb.Database, vsn int) {
  543. enc, _ := rlp.EncodeToBytes(uint(vsn))
  544. db.Put([]byte("BlockchainVersion"), enc)
  545. }
  546. // WriteChainConfig writes the chain config settings to the database.
  547. func WriteChainConfig(db ethdb.Database, hash common.Hash, cfg *ChainConfig) error {
  548. // short circuit and ignore if nil config. GetChainConfig
  549. // will return a default.
  550. if cfg == nil {
  551. return nil
  552. }
  553. jsonChainConfig, err := json.Marshal(cfg)
  554. if err != nil {
  555. return err
  556. }
  557. return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
  558. }
  559. // GetChainConfig will fetch the network settings based on the given hash.
  560. func GetChainConfig(db ethdb.Database, hash common.Hash) (*ChainConfig, error) {
  561. jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
  562. if len(jsonChainConfig) == 0 {
  563. return nil, ChainConfigNotFoundErr
  564. }
  565. var config ChainConfig
  566. if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
  567. return nil, err
  568. }
  569. return &config, nil
  570. }
  571. // FindCommonAncestor returns the last common ancestor of two block headers
  572. func FindCommonAncestor(db ethdb.Database, a, b *types.Header) *types.Header {
  573. for a.GetNumberU64() > b.GetNumberU64() {
  574. a = GetHeader(db, a.ParentHash, a.GetNumberU64()-1)
  575. if a == nil {
  576. return nil
  577. }
  578. }
  579. for a.GetNumberU64() < b.GetNumberU64() {
  580. b = GetHeader(db, b.ParentHash, b.GetNumberU64()-1)
  581. if b == nil {
  582. return nil
  583. }
  584. }
  585. for a.Hash() != b.Hash() {
  586. a = GetHeader(db, a.ParentHash, a.GetNumberU64()-1)
  587. if a == nil {
  588. return nil
  589. }
  590. b = GetHeader(db, b.ParentHash, b.GetNumberU64()-1)
  591. if b == nil {
  592. return nil
  593. }
  594. }
  595. return a
  596. }