database_util.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. var (
  30. headHeaderKey = []byte("LastHeader")
  31. headBlockKey = []byte("LastBlock")
  32. headFastKey = []byte("LastFast")
  33. blockPrefix = []byte("block-")
  34. blockNumPrefix = []byte("block-num-")
  35. headerSuffix = []byte("-header")
  36. bodySuffix = []byte("-body")
  37. tdSuffix = []byte("-td")
  38. txMetaSuffix = []byte{0x01}
  39. receiptsPrefix = []byte("receipts-")
  40. blockReceiptsPrefix = []byte("receipts-block-")
  41. mipmapPre = []byte("mipmap-log-bloom-")
  42. MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
  43. blockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually]
  44. )
  45. // GetCanonicalHash retrieves a hash assigned to a canonical block number.
  46. func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
  47. data, _ := db.Get(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  48. if len(data) == 0 {
  49. return common.Hash{}
  50. }
  51. return common.BytesToHash(data)
  52. }
  53. // GetHeadHeaderHash retrieves the hash of the current canonical head block's
  54. // header. The difference between this and GetHeadBlockHash is that whereas the
  55. // last block hash is only updated upon a full block import, the last header
  56. // hash is updated already at header import, allowing head tracking for the
  57. // light synchronization mechanism.
  58. func GetHeadHeaderHash(db ethdb.Database) common.Hash {
  59. data, _ := db.Get(headHeaderKey)
  60. if len(data) == 0 {
  61. return common.Hash{}
  62. }
  63. return common.BytesToHash(data)
  64. }
  65. // GetHeadBlockHash retrieves the hash of the current canonical head block.
  66. func GetHeadBlockHash(db ethdb.Database) common.Hash {
  67. data, _ := db.Get(headBlockKey)
  68. if len(data) == 0 {
  69. return common.Hash{}
  70. }
  71. return common.BytesToHash(data)
  72. }
  73. // GetHeadFastBlockHash retrieves the hash of the current canonical head block during
  74. // fast synchronization. The difference between this and GetHeadBlockHash is that
  75. // whereas the last block hash is only updated upon a full block import, the last
  76. // fast hash is updated when importing pre-processed blocks.
  77. func GetHeadFastBlockHash(db ethdb.Database) common.Hash {
  78. data, _ := db.Get(headFastKey)
  79. if len(data) == 0 {
  80. return common.Hash{}
  81. }
  82. return common.BytesToHash(data)
  83. }
  84. // GetHeadBlockNum retrieves the block number of the current canonical head block.
  85. func GetHeadBlockNum(db ethdb.Database) *big.Int {
  86. data, _ := db.Get(headBlockKey)
  87. if len(data) == 0 {
  88. return nil
  89. }
  90. header := new(types.Header)
  91. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  92. glog.V(logger.Error).Infof("invalid block header RLP for head block: %v", err)
  93. return nil
  94. }
  95. return header.Number
  96. }
  97. // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
  98. // if the header's not found.
  99. func GetHeaderRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  100. data, _ := db.Get(append(append(blockPrefix, hash[:]...), headerSuffix...))
  101. return data
  102. }
  103. // GetHeader retrieves the block header corresponding to the hash, nil if none
  104. // found.
  105. func GetHeader(db ethdb.Database, hash common.Hash) *types.Header {
  106. data := GetHeaderRLP(db, hash)
  107. if len(data) == 0 {
  108. return nil
  109. }
  110. header := new(types.Header)
  111. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  112. glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
  113. return nil
  114. }
  115. return header
  116. }
  117. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  118. func GetBodyRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  119. data, _ := db.Get(append(append(blockPrefix, hash[:]...), bodySuffix...))
  120. return data
  121. }
  122. // GetBody retrieves the block body (transactons, uncles) corresponding to the
  123. // hash, nil if none found.
  124. func GetBody(db ethdb.Database, hash common.Hash) *types.Body {
  125. data := GetBodyRLP(db, hash)
  126. if len(data) == 0 {
  127. return nil
  128. }
  129. body := new(types.Body)
  130. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  131. glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
  132. return nil
  133. }
  134. return body
  135. }
  136. // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
  137. // none found.
  138. func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
  139. data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  140. if len(data) == 0 {
  141. return nil
  142. }
  143. td := new(big.Int)
  144. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  145. glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
  146. return nil
  147. }
  148. return td
  149. }
  150. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  151. // back from the stored header and body.
  152. func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
  153. // Retrieve the block header and body contents
  154. header := GetHeader(db, hash)
  155. if header == nil {
  156. return nil
  157. }
  158. body := GetBody(db, hash)
  159. if body == nil {
  160. return nil
  161. }
  162. // Reassemble the block and return
  163. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  164. }
  165. // GetBlockReceipts retrieves the receipts generated by the transactions included
  166. // in a block given by its hash.
  167. func GetBlockReceipts(db ethdb.Database, hash common.Hash) types.Receipts {
  168. data, _ := db.Get(append(blockReceiptsPrefix, hash[:]...))
  169. if len(data) == 0 {
  170. return nil
  171. }
  172. storageReceipts := []*types.ReceiptForStorage{}
  173. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  174. glog.V(logger.Error).Infof("invalid receipt array RLP for hash %x: %v", hash, err)
  175. return nil
  176. }
  177. receipts := make(types.Receipts, len(storageReceipts))
  178. for i, receipt := range storageReceipts {
  179. receipts[i] = (*types.Receipt)(receipt)
  180. }
  181. return receipts
  182. }
  183. // GetTransaction retrieves a specific transaction from the database, along with
  184. // its added positional metadata.
  185. func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
  186. // Retrieve the transaction itself from the database
  187. data, _ := db.Get(hash.Bytes())
  188. if len(data) == 0 {
  189. return nil, common.Hash{}, 0, 0
  190. }
  191. var tx types.Transaction
  192. if err := rlp.DecodeBytes(data, &tx); err != nil {
  193. return nil, common.Hash{}, 0, 0
  194. }
  195. // Retrieve the blockchain positional metadata
  196. data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
  197. if len(data) == 0 {
  198. return nil, common.Hash{}, 0, 0
  199. }
  200. var meta struct {
  201. BlockHash common.Hash
  202. BlockIndex uint64
  203. Index uint64
  204. }
  205. if err := rlp.DecodeBytes(data, &meta); err != nil {
  206. return nil, common.Hash{}, 0, 0
  207. }
  208. return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
  209. }
  210. // GetReceipt returns a receipt by hash
  211. func GetReceipt(db ethdb.Database, txHash common.Hash) *types.Receipt {
  212. data, _ := db.Get(append(receiptsPrefix, txHash[:]...))
  213. if len(data) == 0 {
  214. return nil
  215. }
  216. var receipt types.ReceiptForStorage
  217. err := rlp.DecodeBytes(data, &receipt)
  218. if err != nil {
  219. glog.V(logger.Core).Infoln("GetReceipt err:", err)
  220. }
  221. return (*types.Receipt)(&receipt)
  222. }
  223. // WriteCanonicalHash stores the canonical hash for the given block number.
  224. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  225. key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
  226. if err := db.Put(key, hash.Bytes()); err != nil {
  227. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  228. return err
  229. }
  230. return nil
  231. }
  232. // WriteHeadHeaderHash stores the head header's hash.
  233. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  234. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  235. glog.Fatalf("failed to store last header's hash into database: %v", err)
  236. return err
  237. }
  238. return nil
  239. }
  240. // WriteHeadBlockHash stores the head block's hash.
  241. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  242. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  243. glog.Fatalf("failed to store last block's hash into database: %v", err)
  244. return err
  245. }
  246. return nil
  247. }
  248. // WriteHeadFastBlockHash stores the fast head block's hash.
  249. func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
  250. if err := db.Put(headFastKey, hash.Bytes()); err != nil {
  251. glog.Fatalf("failed to store last fast block's hash into database: %v", err)
  252. return err
  253. }
  254. return nil
  255. }
  256. // WriteHeader serializes a block header into the database.
  257. func WriteHeader(db ethdb.Database, header *types.Header) error {
  258. data, err := rlp.EncodeToBytes(header)
  259. if err != nil {
  260. return err
  261. }
  262. key := append(append(blockPrefix, header.Hash().Bytes()...), headerSuffix...)
  263. if err := db.Put(key, data); err != nil {
  264. glog.Fatalf("failed to store header into database: %v", err)
  265. return err
  266. }
  267. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, header.Hash().Bytes()[:4])
  268. return nil
  269. }
  270. // WriteBody serializes the body of a block into the database.
  271. func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
  272. data, err := rlp.EncodeToBytes(body)
  273. if err != nil {
  274. return err
  275. }
  276. key := append(append(blockPrefix, hash.Bytes()...), bodySuffix...)
  277. if err := db.Put(key, data); err != nil {
  278. glog.Fatalf("failed to store block body into database: %v", err)
  279. return err
  280. }
  281. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  282. return nil
  283. }
  284. // WriteTd serializes the total difficulty of a block into the database.
  285. func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
  286. data, err := rlp.EncodeToBytes(td)
  287. if err != nil {
  288. return err
  289. }
  290. key := append(append(blockPrefix, hash.Bytes()...), tdSuffix...)
  291. if err := db.Put(key, data); err != nil {
  292. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  293. return err
  294. }
  295. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  296. return nil
  297. }
  298. // WriteBlock serializes a block into the database, header and body separately.
  299. func WriteBlock(db ethdb.Database, block *types.Block) error {
  300. // Store the body first to retain database consistency
  301. if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  302. return err
  303. }
  304. // Store the header too, signaling full block ownership
  305. if err := WriteHeader(db, block.Header()); err != nil {
  306. return err
  307. }
  308. return nil
  309. }
  310. // WriteBlockReceipts stores all the transaction receipts belonging to a block
  311. // as a single receipt slice. This is used during chain reorganisations for
  312. // rescheduling dropped transactions.
  313. func WriteBlockReceipts(db ethdb.Database, hash common.Hash, receipts types.Receipts) error {
  314. // Convert the receipts into their storage form and serialize them
  315. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  316. for i, receipt := range receipts {
  317. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  318. }
  319. bytes, err := rlp.EncodeToBytes(storageReceipts)
  320. if err != nil {
  321. return err
  322. }
  323. // Store the flattened receipt slice
  324. if err := db.Put(append(blockReceiptsPrefix, hash.Bytes()...), bytes); err != nil {
  325. glog.Fatalf("failed to store block receipts into database: %v", err)
  326. return err
  327. }
  328. glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
  329. return nil
  330. }
  331. // WriteTransactions stores the transactions associated with a specific block
  332. // into the given database. Beside writing the transaction, the function also
  333. // stores a metadata entry along with the transaction, detailing the position
  334. // of this within the blockchain.
  335. func WriteTransactions(db ethdb.Database, block *types.Block) error {
  336. batch := db.NewBatch()
  337. // Iterate over each transaction and encode it with its metadata
  338. for i, tx := range block.Transactions() {
  339. // Encode and queue up the transaction for storage
  340. data, err := rlp.EncodeToBytes(tx)
  341. if err != nil {
  342. return err
  343. }
  344. if err := batch.Put(tx.Hash().Bytes(), data); err != nil {
  345. return err
  346. }
  347. // Encode and queue up the transaction metadata for storage
  348. meta := struct {
  349. BlockHash common.Hash
  350. BlockIndex uint64
  351. Index uint64
  352. }{
  353. BlockHash: block.Hash(),
  354. BlockIndex: block.NumberU64(),
  355. Index: uint64(i),
  356. }
  357. data, err = rlp.EncodeToBytes(meta)
  358. if err != nil {
  359. return err
  360. }
  361. if err := batch.Put(append(tx.Hash().Bytes(), txMetaSuffix...), data); err != nil {
  362. return err
  363. }
  364. }
  365. // Write the scheduled data into the database
  366. if err := batch.Write(); err != nil {
  367. glog.Fatalf("failed to store transactions into database: %v", err)
  368. return err
  369. }
  370. return nil
  371. }
  372. // WriteReceipts stores a batch of transaction receipts into the database.
  373. func WriteReceipts(db ethdb.Database, receipts types.Receipts) error {
  374. batch := db.NewBatch()
  375. // Iterate over all the receipts and queue them for database injection
  376. for _, receipt := range receipts {
  377. storageReceipt := (*types.ReceiptForStorage)(receipt)
  378. data, err := rlp.EncodeToBytes(storageReceipt)
  379. if err != nil {
  380. return err
  381. }
  382. if err := batch.Put(append(receiptsPrefix, receipt.TxHash.Bytes()...), data); err != nil {
  383. return err
  384. }
  385. }
  386. // Write the scheduled data into the database
  387. if err := batch.Write(); err != nil {
  388. glog.Fatalf("failed to store receipts into database: %v", err)
  389. return err
  390. }
  391. return nil
  392. }
  393. // DeleteCanonicalHash removes the number to hash canonical mapping.
  394. func DeleteCanonicalHash(db ethdb.Database, number uint64) {
  395. db.Delete(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  396. }
  397. // DeleteHeader removes all block header data associated with a hash.
  398. func DeleteHeader(db ethdb.Database, hash common.Hash) {
  399. db.Delete(append(append(blockPrefix, hash.Bytes()...), headerSuffix...))
  400. }
  401. // DeleteBody removes all block body data associated with a hash.
  402. func DeleteBody(db ethdb.Database, hash common.Hash) {
  403. db.Delete(append(append(blockPrefix, hash.Bytes()...), bodySuffix...))
  404. }
  405. // DeleteTd removes all block total difficulty data associated with a hash.
  406. func DeleteTd(db ethdb.Database, hash common.Hash) {
  407. db.Delete(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  408. }
  409. // DeleteBlock removes all block data associated with a hash.
  410. func DeleteBlock(db ethdb.Database, hash common.Hash) {
  411. DeleteBlockReceipts(db, hash)
  412. DeleteHeader(db, hash)
  413. DeleteBody(db, hash)
  414. DeleteTd(db, hash)
  415. }
  416. // DeleteBlockReceipts removes all receipt data associated with a block hash.
  417. func DeleteBlockReceipts(db ethdb.Database, hash common.Hash) {
  418. db.Delete(append(blockReceiptsPrefix, hash.Bytes()...))
  419. }
  420. // DeleteTransaction removes all transaction data associated with a hash.
  421. func DeleteTransaction(db ethdb.Database, hash common.Hash) {
  422. db.Delete(hash.Bytes())
  423. db.Delete(append(hash.Bytes(), txMetaSuffix...))
  424. }
  425. // DeleteReceipt removes all receipt data associated with a transaction hash.
  426. func DeleteReceipt(db ethdb.Database, hash common.Hash) {
  427. db.Delete(append(receiptsPrefix, hash.Bytes()...))
  428. }
  429. // [deprecated by the header/block split, remove eventually]
  430. // GetBlockByHashOld returns the old combined block corresponding to the hash
  431. // or nil if not found. This method is only used by the upgrade mechanism to
  432. // access the old combined block representation. It will be dropped after the
  433. // network transitions to eth/63.
  434. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  435. data, _ := db.Get(append(blockHashPrefix, hash[:]...))
  436. if len(data) == 0 {
  437. return nil
  438. }
  439. var block types.StorageBlock
  440. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  441. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  442. return nil
  443. }
  444. return (*types.Block)(&block)
  445. }
  446. // returns a formatted MIP mapped key by adding prefix, canonical number and level
  447. //
  448. // ex. fn(98, 1000) = (prefix || 1000 || 0)
  449. func mipmapKey(num, level uint64) []byte {
  450. lkey := make([]byte, 8)
  451. binary.BigEndian.PutUint64(lkey, level)
  452. key := new(big.Int).SetUint64(num / level * level)
  453. return append(mipmapPre, append(lkey, key.Bytes()...)...)
  454. }
  455. // WriteMapmapBloom writes each address included in the receipts' logs to the
  456. // MIP bloom bin.
  457. func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
  458. batch := db.NewBatch()
  459. for _, level := range MIPMapLevels {
  460. key := mipmapKey(number, level)
  461. bloomDat, _ := db.Get(key)
  462. bloom := types.BytesToBloom(bloomDat)
  463. for _, receipt := range receipts {
  464. for _, log := range receipt.Logs {
  465. bloom.Add(log.Address.Big())
  466. }
  467. }
  468. batch.Put(key, bloom.Bytes())
  469. }
  470. if err := batch.Write(); err != nil {
  471. return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
  472. }
  473. return nil
  474. }
  475. // GetMipmapBloom returns a bloom filter using the number and level as input
  476. // parameters. For available levels see MIPMapLevels.
  477. func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
  478. bloomDat, _ := db.Get(mipmapKey(number, level))
  479. return types.BytesToBloom(bloomDat)
  480. }
  481. // GetBlockChainVersion reads the version number from db.
  482. func GetBlockChainVersion(db ethdb.Database) int {
  483. var vsn uint
  484. enc, _ := db.Get([]byte("BlockchainVersion"))
  485. rlp.DecodeBytes(enc, &vsn)
  486. return int(vsn)
  487. }
  488. // WriteBlockChainVersion writes vsn as the version number to db.
  489. func WriteBlockChainVersion(db ethdb.Database, vsn int) {
  490. enc, _ := rlp.EncodeToBytes(uint(vsn))
  491. db.Put([]byte("BlockchainVersion"), enc)
  492. }