database_util.go 18 KB

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