database_util.go 17 KB

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