accessors_chain.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. // Copyright 2018 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 rawdb
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/params"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. // ReadCanonicalHash retrieves the hash assigned to a canonical block number.
  30. func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash {
  31. data, _ := db.Ancient(freezerHashTable, number)
  32. if len(data) == 0 {
  33. data, _ = db.Get(headerHashKey(number))
  34. // In the background freezer is moving data from leveldb to flatten files.
  35. // So during the first check for ancient db, the data is not yet in there,
  36. // but when we reach into leveldb, the data was already moved. That would
  37. // result in a not found error.
  38. if len(data) == 0 {
  39. data, _ = db.Ancient(freezerHashTable, number)
  40. }
  41. }
  42. if len(data) == 0 {
  43. return common.Hash{}
  44. }
  45. return common.BytesToHash(data)
  46. }
  47. // WriteCanonicalHash stores the hash assigned to a canonical block number.
  48. func WriteCanonicalHash(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  49. if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil {
  50. log.Crit("Failed to store number to hash mapping", "err", err)
  51. }
  52. }
  53. // DeleteCanonicalHash removes the number to hash canonical mapping.
  54. func DeleteCanonicalHash(db ethdb.KeyValueWriter, number uint64) {
  55. if err := db.Delete(headerHashKey(number)); err != nil {
  56. log.Crit("Failed to delete number to hash mapping", "err", err)
  57. }
  58. }
  59. // ReadAllHashes retrieves all the hashes assigned to blocks at a certain heights,
  60. // both canonical and reorged forks included.
  61. func ReadAllHashes(db ethdb.Iteratee, number uint64) []common.Hash {
  62. prefix := headerKeyPrefix(number)
  63. hashes := make([]common.Hash, 0, 1)
  64. it := db.NewIterator(prefix, nil)
  65. defer it.Release()
  66. for it.Next() {
  67. if key := it.Key(); len(key) == len(prefix)+32 {
  68. hashes = append(hashes, common.BytesToHash(key[len(key)-32:]))
  69. }
  70. }
  71. return hashes
  72. }
  73. // ReadAllCanonicalHashes retrieves all canonical number and hash mappings at the
  74. // certain chain range. If the accumulated entries reaches the given threshold,
  75. // abort the iteration and return the semi-finish result.
  76. func ReadAllCanonicalHashes(db ethdb.Iteratee, from uint64, to uint64, limit int) ([]uint64, []common.Hash) {
  77. // Short circuit if the limit is 0.
  78. if limit == 0 {
  79. return nil, nil
  80. }
  81. var (
  82. numbers []uint64
  83. hashes []common.Hash
  84. )
  85. // Construct the key prefix of start point.
  86. start, end := headerHashKey(from), headerHashKey(to)
  87. it := db.NewIterator(nil, start)
  88. defer it.Release()
  89. for it.Next() {
  90. if bytes.Compare(it.Key(), end) >= 0 {
  91. break
  92. }
  93. if key := it.Key(); len(key) == len(headerPrefix)+8+1 && bytes.Equal(key[len(key)-1:], headerHashSuffix) {
  94. numbers = append(numbers, binary.BigEndian.Uint64(key[len(headerPrefix):len(headerPrefix)+8]))
  95. hashes = append(hashes, common.BytesToHash(it.Value()))
  96. // If the accumulated entries reaches the limit threshold, return.
  97. if len(numbers) >= limit {
  98. break
  99. }
  100. }
  101. }
  102. return numbers, hashes
  103. }
  104. // ReadHeaderNumber returns the header number assigned to a hash.
  105. func ReadHeaderNumber(db ethdb.KeyValueReader, hash common.Hash) *uint64 {
  106. data, _ := db.Get(headerNumberKey(hash))
  107. if len(data) != 8 {
  108. return nil
  109. }
  110. number := binary.BigEndian.Uint64(data)
  111. return &number
  112. }
  113. // WriteHeaderNumber stores the hash->number mapping.
  114. func WriteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  115. key := headerNumberKey(hash)
  116. enc := encodeBlockNumber(number)
  117. if err := db.Put(key, enc); err != nil {
  118. log.Crit("Failed to store hash to number mapping", "err", err)
  119. }
  120. }
  121. // DeleteHeaderNumber removes hash->number mapping.
  122. func DeleteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash) {
  123. if err := db.Delete(headerNumberKey(hash)); err != nil {
  124. log.Crit("Failed to delete hash to number mapping", "err", err)
  125. }
  126. }
  127. // ReadHeadHeaderHash retrieves the hash of the current canonical head header.
  128. func ReadHeadHeaderHash(db ethdb.KeyValueReader) common.Hash {
  129. data, _ := db.Get(headHeaderKey)
  130. if len(data) == 0 {
  131. return common.Hash{}
  132. }
  133. return common.BytesToHash(data)
  134. }
  135. // WriteHeadHeaderHash stores the hash of the current canonical head header.
  136. func WriteHeadHeaderHash(db ethdb.KeyValueWriter, hash common.Hash) {
  137. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  138. log.Crit("Failed to store last header's hash", "err", err)
  139. }
  140. }
  141. // ReadHeadBlockHash retrieves the hash of the current canonical head block.
  142. func ReadHeadBlockHash(db ethdb.KeyValueReader) common.Hash {
  143. data, _ := db.Get(headBlockKey)
  144. if len(data) == 0 {
  145. return common.Hash{}
  146. }
  147. return common.BytesToHash(data)
  148. }
  149. // WriteHeadBlockHash stores the head block's hash.
  150. func WriteHeadBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  151. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  152. log.Crit("Failed to store last block's hash", "err", err)
  153. }
  154. }
  155. // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block.
  156. func ReadHeadFastBlockHash(db ethdb.KeyValueReader) common.Hash {
  157. data, _ := db.Get(headFastBlockKey)
  158. if len(data) == 0 {
  159. return common.Hash{}
  160. }
  161. return common.BytesToHash(data)
  162. }
  163. // WriteHeadFastBlockHash stores the hash of the current fast-sync head block.
  164. func WriteHeadFastBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  165. if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil {
  166. log.Crit("Failed to store last fast block's hash", "err", err)
  167. }
  168. }
  169. // ReadFastTrieProgress retrieves the number of tries nodes fast synced to allow
  170. // reporting correct numbers across restarts.
  171. func ReadFastTrieProgress(db ethdb.KeyValueReader) uint64 {
  172. data, _ := db.Get(fastTrieProgressKey)
  173. if len(data) == 0 {
  174. return 0
  175. }
  176. return new(big.Int).SetBytes(data).Uint64()
  177. }
  178. // WriteFastTrieProgress stores the fast sync trie process counter to support
  179. // retrieving it across restarts.
  180. func WriteFastTrieProgress(db ethdb.KeyValueWriter, count uint64) {
  181. if err := db.Put(fastTrieProgressKey, new(big.Int).SetUint64(count).Bytes()); err != nil {
  182. log.Crit("Failed to store fast sync trie progress", "err", err)
  183. }
  184. }
  185. // ReadTxIndexTail retrieves the number of oldest indexed block
  186. // whose transaction indices has been indexed. If the corresponding entry
  187. // is non-existent in database it means the indexing has been finished.
  188. func ReadTxIndexTail(db ethdb.KeyValueReader) *uint64 {
  189. data, _ := db.Get(txIndexTailKey)
  190. if len(data) != 8 {
  191. return nil
  192. }
  193. number := binary.BigEndian.Uint64(data)
  194. return &number
  195. }
  196. // WriteTxIndexTail stores the number of oldest indexed block
  197. // into database.
  198. func WriteTxIndexTail(db ethdb.KeyValueWriter, number uint64) {
  199. if err := db.Put(txIndexTailKey, encodeBlockNumber(number)); err != nil {
  200. log.Crit("Failed to store the transaction index tail", "err", err)
  201. }
  202. }
  203. // ReadFastTxLookupLimit retrieves the tx lookup limit used in fast sync.
  204. func ReadFastTxLookupLimit(db ethdb.KeyValueReader) *uint64 {
  205. data, _ := db.Get(fastTxLookupLimitKey)
  206. if len(data) != 8 {
  207. return nil
  208. }
  209. number := binary.BigEndian.Uint64(data)
  210. return &number
  211. }
  212. // WriteFastTxLookupLimit stores the txlookup limit used in fast sync into database.
  213. func WriteFastTxLookupLimit(db ethdb.KeyValueWriter, number uint64) {
  214. if err := db.Put(fastTxLookupLimitKey, encodeBlockNumber(number)); err != nil {
  215. log.Crit("Failed to store transaction lookup limit for fast sync", "err", err)
  216. }
  217. }
  218. // ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
  219. func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  220. // First try to look up the data in ancient database. Extra hash
  221. // comparison is necessary since ancient database only maintains
  222. // the canonical data.
  223. data, _ := db.Ancient(freezerHeaderTable, number)
  224. if len(data) > 0 && crypto.Keccak256Hash(data) == hash {
  225. return data
  226. }
  227. // Then try to look up the data in leveldb.
  228. data, _ = db.Get(headerKey(number, hash))
  229. if len(data) > 0 {
  230. return data
  231. }
  232. // In the background freezer is moving data from leveldb to flatten files.
  233. // So during the first check for ancient db, the data is not yet in there,
  234. // but when we reach into leveldb, the data was already moved. That would
  235. // result in a not found error.
  236. data, _ = db.Ancient(freezerHeaderTable, number)
  237. if len(data) > 0 && crypto.Keccak256Hash(data) == hash {
  238. return data
  239. }
  240. return nil // Can't find the data anywhere.
  241. }
  242. // HasHeader verifies the existence of a block header corresponding to the hash.
  243. func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool {
  244. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  245. return true
  246. }
  247. if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
  248. return false
  249. }
  250. return true
  251. }
  252. // ReadHeader retrieves the block header corresponding to the hash.
  253. func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header {
  254. data := ReadHeaderRLP(db, hash, number)
  255. if len(data) == 0 {
  256. return nil
  257. }
  258. header := new(types.Header)
  259. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  260. log.Error("Invalid block header RLP", "hash", hash, "err", err)
  261. return nil
  262. }
  263. return header
  264. }
  265. // WriteHeader stores a block header into the database and also stores the hash-
  266. // to-number mapping.
  267. func WriteHeader(db ethdb.KeyValueWriter, header *types.Header) {
  268. var (
  269. hash = header.Hash()
  270. number = header.Number.Uint64()
  271. )
  272. // Write the hash -> number mapping
  273. WriteHeaderNumber(db, hash, number)
  274. // Write the encoded header
  275. data, err := rlp.EncodeToBytes(header)
  276. if err != nil {
  277. log.Crit("Failed to RLP encode header", "err", err)
  278. }
  279. key := headerKey(number, hash)
  280. if err := db.Put(key, data); err != nil {
  281. log.Crit("Failed to store header", "err", err)
  282. }
  283. }
  284. // DeleteHeader removes all block header data associated with a hash.
  285. func DeleteHeader(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  286. deleteHeaderWithoutNumber(db, hash, number)
  287. if err := db.Delete(headerNumberKey(hash)); err != nil {
  288. log.Crit("Failed to delete hash to number mapping", "err", err)
  289. }
  290. }
  291. // deleteHeaderWithoutNumber removes only the block header but does not remove
  292. // the hash to number mapping.
  293. func deleteHeaderWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  294. if err := db.Delete(headerKey(number, hash)); err != nil {
  295. log.Crit("Failed to delete header", "err", err)
  296. }
  297. }
  298. // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  299. func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  300. // First try to look up the data in ancient database. Extra hash
  301. // comparison is necessary since ancient database only maintains
  302. // the canonical data.
  303. data, _ := db.Ancient(freezerBodiesTable, number)
  304. if len(data) > 0 {
  305. h, _ := db.Ancient(freezerHashTable, number)
  306. if common.BytesToHash(h) == hash {
  307. return data
  308. }
  309. }
  310. // Then try to look up the data in leveldb.
  311. data, _ = db.Get(blockBodyKey(number, hash))
  312. if len(data) > 0 {
  313. return data
  314. }
  315. // In the background freezer is moving data from leveldb to flatten files.
  316. // So during the first check for ancient db, the data is not yet in there,
  317. // but when we reach into leveldb, the data was already moved. That would
  318. // result in a not found error.
  319. data, _ = db.Ancient(freezerBodiesTable, number)
  320. if len(data) > 0 {
  321. h, _ := db.Ancient(freezerHashTable, number)
  322. if common.BytesToHash(h) == hash {
  323. return data
  324. }
  325. }
  326. return nil // Can't find the data anywhere.
  327. }
  328. // ReadCanonicalBodyRLP retrieves the block body (transactions and uncles) for the canonical
  329. // block at number, in RLP encoding.
  330. func ReadCanonicalBodyRLP(db ethdb.Reader, number uint64) rlp.RawValue {
  331. // If it's an ancient one, we don't need the canonical hash
  332. data, _ := db.Ancient(freezerBodiesTable, number)
  333. if len(data) == 0 {
  334. // Need to get the hash
  335. data, _ = db.Get(blockBodyKey(number, ReadCanonicalHash(db, number)))
  336. // In the background freezer is moving data from leveldb to flatten files.
  337. // So during the first check for ancient db, the data is not yet in there,
  338. // but when we reach into leveldb, the data was already moved. That would
  339. // result in a not found error.
  340. if len(data) == 0 {
  341. data, _ = db.Ancient(freezerBodiesTable, number)
  342. }
  343. }
  344. return data
  345. }
  346. // WriteBodyRLP stores an RLP encoded block body into the database.
  347. func WriteBodyRLP(db ethdb.KeyValueWriter, hash common.Hash, number uint64, rlp rlp.RawValue) {
  348. if err := db.Put(blockBodyKey(number, hash), rlp); err != nil {
  349. log.Crit("Failed to store block body", "err", err)
  350. }
  351. }
  352. // HasBody verifies the existence of a block body corresponding to the hash.
  353. func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool {
  354. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  355. return true
  356. }
  357. if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
  358. return false
  359. }
  360. return true
  361. }
  362. // ReadBody retrieves the block body corresponding to the hash.
  363. func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body {
  364. data := ReadBodyRLP(db, hash, number)
  365. if len(data) == 0 {
  366. return nil
  367. }
  368. body := new(types.Body)
  369. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  370. log.Error("Invalid block body RLP", "hash", hash, "err", err)
  371. return nil
  372. }
  373. return body
  374. }
  375. // WriteBody stores a block body into the database.
  376. func WriteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64, body *types.Body) {
  377. data, err := rlp.EncodeToBytes(body)
  378. if err != nil {
  379. log.Crit("Failed to RLP encode body", "err", err)
  380. }
  381. WriteBodyRLP(db, hash, number, data)
  382. }
  383. // DeleteBody removes all block body data associated with a hash.
  384. func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  385. if err := db.Delete(blockBodyKey(number, hash)); err != nil {
  386. log.Crit("Failed to delete block body", "err", err)
  387. }
  388. }
  389. // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding.
  390. func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  391. // First try to look up the data in ancient database. Extra hash
  392. // comparison is necessary since ancient database only maintains
  393. // the canonical data.
  394. data, _ := db.Ancient(freezerDifficultyTable, number)
  395. if len(data) > 0 {
  396. h, _ := db.Ancient(freezerHashTable, number)
  397. if common.BytesToHash(h) == hash {
  398. return data
  399. }
  400. }
  401. // Then try to look up the data in leveldb.
  402. data, _ = db.Get(headerTDKey(number, hash))
  403. if len(data) > 0 {
  404. return data
  405. }
  406. // In the background freezer is moving data from leveldb to flatten files.
  407. // So during the first check for ancient db, the data is not yet in there,
  408. // but when we reach into leveldb, the data was already moved. That would
  409. // result in a not found error.
  410. data, _ = db.Ancient(freezerDifficultyTable, number)
  411. if len(data) > 0 {
  412. h, _ := db.Ancient(freezerHashTable, number)
  413. if common.BytesToHash(h) == hash {
  414. return data
  415. }
  416. }
  417. return nil // Can't find the data anywhere.
  418. }
  419. // ReadTd retrieves a block's total difficulty corresponding to the hash.
  420. func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int {
  421. data := ReadTdRLP(db, hash, number)
  422. if len(data) == 0 {
  423. return nil
  424. }
  425. td := new(big.Int)
  426. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  427. log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
  428. return nil
  429. }
  430. return td
  431. }
  432. // WriteTd stores the total difficulty of a block into the database.
  433. func WriteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64, td *big.Int) {
  434. data, err := rlp.EncodeToBytes(td)
  435. if err != nil {
  436. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  437. }
  438. if err := db.Put(headerTDKey(number, hash), data); err != nil {
  439. log.Crit("Failed to store block total difficulty", "err", err)
  440. }
  441. }
  442. // DeleteTd removes all block total difficulty data associated with a hash.
  443. func DeleteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  444. if err := db.Delete(headerTDKey(number, hash)); err != nil {
  445. log.Crit("Failed to delete block total difficulty", "err", err)
  446. }
  447. }
  448. // HasReceipts verifies the existence of all the transaction receipts belonging
  449. // to a block.
  450. func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool {
  451. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  452. return true
  453. }
  454. if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil {
  455. return false
  456. }
  457. return true
  458. }
  459. // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding.
  460. func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  461. // First try to look up the data in ancient database. Extra hash
  462. // comparison is necessary since ancient database only maintains
  463. // the canonical data.
  464. data, _ := db.Ancient(freezerReceiptTable, number)
  465. if len(data) > 0 {
  466. h, _ := db.Ancient(freezerHashTable, number)
  467. if common.BytesToHash(h) == hash {
  468. return data
  469. }
  470. }
  471. // Then try to look up the data in leveldb.
  472. data, _ = db.Get(blockReceiptsKey(number, hash))
  473. if len(data) > 0 {
  474. return data
  475. }
  476. // In the background freezer is moving data from leveldb to flatten files.
  477. // So during the first check for ancient db, the data is not yet in there,
  478. // but when we reach into leveldb, the data was already moved. That would
  479. // result in a not found error.
  480. data, _ = db.Ancient(freezerReceiptTable, number)
  481. if len(data) > 0 {
  482. h, _ := db.Ancient(freezerHashTable, number)
  483. if common.BytesToHash(h) == hash {
  484. return data
  485. }
  486. }
  487. return nil // Can't find the data anywhere.
  488. }
  489. // ReadRawReceipts retrieves all the transaction receipts belonging to a block.
  490. // The receipt metadata fields are not guaranteed to be populated, so they
  491. // should not be used. Use ReadReceipts instead if the metadata is needed.
  492. func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts {
  493. // Retrieve the flattened receipt slice
  494. data := ReadReceiptsRLP(db, hash, number)
  495. if len(data) == 0 {
  496. return nil
  497. }
  498. // Convert the receipts from their storage form to their internal representation
  499. storageReceipts := []*types.ReceiptForStorage{}
  500. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  501. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  502. return nil
  503. }
  504. receipts := make(types.Receipts, len(storageReceipts))
  505. for i, storageReceipt := range storageReceipts {
  506. receipts[i] = (*types.Receipt)(storageReceipt)
  507. }
  508. return receipts
  509. }
  510. // ReadReceipts retrieves all the transaction receipts belonging to a block, including
  511. // its correspoinding metadata fields. If it is unable to populate these metadata
  512. // fields then nil is returned.
  513. //
  514. // The current implementation populates these metadata fields by reading the receipts'
  515. // corresponding block body, so if the block body is not found it will return nil even
  516. // if the receipt itself is stored.
  517. func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
  518. // We're deriving many fields from the block body, retrieve beside the receipt
  519. receipts := ReadRawReceipts(db, hash, number)
  520. if receipts == nil {
  521. return nil
  522. }
  523. body := ReadBody(db, hash, number)
  524. if body == nil {
  525. log.Error("Missing body but have receipt", "hash", hash, "number", number)
  526. return nil
  527. }
  528. if err := receipts.DeriveFields(config, hash, number, body.Transactions); err != nil {
  529. log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err)
  530. return nil
  531. }
  532. return receipts
  533. }
  534. // WriteReceipts stores all the transaction receipts belonging to a block.
  535. func WriteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) {
  536. // Convert the receipts into their storage form and serialize them
  537. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  538. for i, receipt := range receipts {
  539. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  540. }
  541. bytes, err := rlp.EncodeToBytes(storageReceipts)
  542. if err != nil {
  543. log.Crit("Failed to encode block receipts", "err", err)
  544. }
  545. // Store the flattened receipt slice
  546. if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil {
  547. log.Crit("Failed to store block receipts", "err", err)
  548. }
  549. }
  550. // DeleteReceipts removes all receipt data associated with a block hash.
  551. func DeleteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  552. if err := db.Delete(blockReceiptsKey(number, hash)); err != nil {
  553. log.Crit("Failed to delete block receipts", "err", err)
  554. }
  555. }
  556. // ReadBlock retrieves an entire block corresponding to the hash, assembling it
  557. // back from the stored header and body. If either the header or body could not
  558. // be retrieved nil is returned.
  559. //
  560. // Note, due to concurrent download of header and block body the header and thus
  561. // canonical hash can be stored in the database but the body data not (yet).
  562. func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
  563. header := ReadHeader(db, hash, number)
  564. if header == nil {
  565. return nil
  566. }
  567. body := ReadBody(db, hash, number)
  568. if body == nil {
  569. return nil
  570. }
  571. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  572. }
  573. // WriteBlock serializes a block into the database, header and body separately.
  574. func WriteBlock(db ethdb.KeyValueWriter, block *types.Block) {
  575. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  576. WriteHeader(db, block.Header())
  577. }
  578. // WriteAncientBlock writes entire block data into ancient store and returns the total written size.
  579. func WriteAncientBlock(db ethdb.AncientWriter, block *types.Block, receipts types.Receipts, td *big.Int) int {
  580. // Encode all block components to RLP format.
  581. headerBlob, err := rlp.EncodeToBytes(block.Header())
  582. if err != nil {
  583. log.Crit("Failed to RLP encode block header", "err", err)
  584. }
  585. bodyBlob, err := rlp.EncodeToBytes(block.Body())
  586. if err != nil {
  587. log.Crit("Failed to RLP encode body", "err", err)
  588. }
  589. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  590. for i, receipt := range receipts {
  591. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  592. }
  593. receiptBlob, err := rlp.EncodeToBytes(storageReceipts)
  594. if err != nil {
  595. log.Crit("Failed to RLP encode block receipts", "err", err)
  596. }
  597. tdBlob, err := rlp.EncodeToBytes(td)
  598. if err != nil {
  599. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  600. }
  601. // Write all blob to flatten files.
  602. err = db.AppendAncient(block.NumberU64(), block.Hash().Bytes(), headerBlob, bodyBlob, receiptBlob, tdBlob)
  603. if err != nil {
  604. log.Crit("Failed to write block data to ancient store", "err", err)
  605. }
  606. return len(headerBlob) + len(bodyBlob) + len(receiptBlob) + len(tdBlob) + common.HashLength
  607. }
  608. // DeleteBlock removes all block data associated with a hash.
  609. func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  610. DeleteReceipts(db, hash, number)
  611. DeleteHeader(db, hash, number)
  612. DeleteBody(db, hash, number)
  613. DeleteTd(db, hash, number)
  614. }
  615. // DeleteBlockWithoutNumber removes all block data associated with a hash, except
  616. // the hash to number mapping.
  617. func DeleteBlockWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  618. DeleteReceipts(db, hash, number)
  619. deleteHeaderWithoutNumber(db, hash, number)
  620. DeleteBody(db, hash, number)
  621. DeleteTd(db, hash, number)
  622. }
  623. // FindCommonAncestor returns the last common ancestor of two block headers
  624. func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header {
  625. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  626. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  627. if a == nil {
  628. return nil
  629. }
  630. }
  631. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  632. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  633. if b == nil {
  634. return nil
  635. }
  636. }
  637. for a.Hash() != b.Hash() {
  638. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  639. if a == nil {
  640. return nil
  641. }
  642. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  643. if b == nil {
  644. return nil
  645. }
  646. }
  647. return a
  648. }