database_util.go 23 KB

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