accessors_chain.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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/ethdb"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/params"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. // ReadCanonicalHash retrieves the hash assigned to a canonical block number.
  29. func ReadCanonicalHash(db ethdb.AncientReader, number uint64) common.Hash {
  30. data, _ := db.Ancient("hashes", number)
  31. if len(data) == 0 {
  32. data, _ = db.Get(headerHashKey(number))
  33. }
  34. if len(data) == 0 {
  35. return common.Hash{}
  36. }
  37. return common.BytesToHash(data)
  38. }
  39. // WriteCanonicalHash stores the hash assigned to a canonical block number.
  40. func WriteCanonicalHash(db ethdb.Writer, hash common.Hash, number uint64) {
  41. if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil {
  42. log.Crit("Failed to store number to hash mapping", "err", err)
  43. }
  44. }
  45. // DeleteCanonicalHash removes the number to hash canonical mapping.
  46. func DeleteCanonicalHash(db ethdb.Writer, number uint64) {
  47. if err := db.Delete(headerHashKey(number)); err != nil {
  48. log.Crit("Failed to delete number to hash mapping", "err", err)
  49. }
  50. }
  51. // readAllHashes retrieves all the hashes assigned to blocks at a certain heights,
  52. // both canonical and reorged forks included.
  53. //
  54. // This method is a helper for the chain reader. It should never be exposed to the
  55. // outside world.
  56. func readAllHashes(db ethdb.Iteratee, number uint64) []common.Hash {
  57. prefix := headerKeyPrefix(number)
  58. hashes := make([]common.Hash, 0, 1)
  59. it := db.NewIteratorWithPrefix(prefix)
  60. for it.Next() {
  61. if key := it.Key(); len(key) == len(prefix)+32 {
  62. hashes = append(hashes, common.BytesToHash(key[len(key)-32:]))
  63. }
  64. }
  65. return hashes
  66. }
  67. // ReadHeaderNumber returns the header number assigned to a hash.
  68. func ReadHeaderNumber(db ethdb.Reader, hash common.Hash) *uint64 {
  69. data, _ := db.Get(headerNumberKey(hash))
  70. if len(data) != 8 {
  71. return nil
  72. }
  73. number := binary.BigEndian.Uint64(data)
  74. return &number
  75. }
  76. // ReadHeadHeaderHash retrieves the hash of the current canonical head header.
  77. func ReadHeadHeaderHash(db ethdb.Reader) common.Hash {
  78. data, _ := db.Get(headHeaderKey)
  79. if len(data) == 0 {
  80. return common.Hash{}
  81. }
  82. return common.BytesToHash(data)
  83. }
  84. // WriteHeadHeaderHash stores the hash of the current canonical head header.
  85. func WriteHeadHeaderHash(db ethdb.Writer, hash common.Hash) {
  86. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  87. log.Crit("Failed to store last header's hash", "err", err)
  88. }
  89. }
  90. // ReadHeadBlockHash retrieves the hash of the current canonical head block.
  91. func ReadHeadBlockHash(db ethdb.Reader) common.Hash {
  92. data, _ := db.Get(headBlockKey)
  93. if len(data) == 0 {
  94. return common.Hash{}
  95. }
  96. return common.BytesToHash(data)
  97. }
  98. // WriteHeadBlockHash stores the head block's hash.
  99. func WriteHeadBlockHash(db ethdb.Writer, hash common.Hash) {
  100. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  101. log.Crit("Failed to store last block's hash", "err", err)
  102. }
  103. }
  104. // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block.
  105. func ReadHeadFastBlockHash(db ethdb.Reader) common.Hash {
  106. data, _ := db.Get(headFastBlockKey)
  107. if len(data) == 0 {
  108. return common.Hash{}
  109. }
  110. return common.BytesToHash(data)
  111. }
  112. // WriteHeadFastBlockHash stores the hash of the current fast-sync head block.
  113. func WriteHeadFastBlockHash(db ethdb.Writer, hash common.Hash) {
  114. if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil {
  115. log.Crit("Failed to store last fast block's hash", "err", err)
  116. }
  117. }
  118. // ReadFastTrieProgress retrieves the number of tries nodes fast synced to allow
  119. // reporting correct numbers across restarts.
  120. func ReadFastTrieProgress(db ethdb.Reader) uint64 {
  121. data, _ := db.Get(fastTrieProgressKey)
  122. if len(data) == 0 {
  123. return 0
  124. }
  125. return new(big.Int).SetBytes(data).Uint64()
  126. }
  127. // WriteFastTrieProgress stores the fast sync trie process counter to support
  128. // retrieving it across restarts.
  129. func WriteFastTrieProgress(db ethdb.Writer, count uint64) {
  130. if err := db.Put(fastTrieProgressKey, new(big.Int).SetUint64(count).Bytes()); err != nil {
  131. log.Crit("Failed to store fast sync trie progress", "err", err)
  132. }
  133. }
  134. // ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
  135. func ReadHeaderRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
  136. data, _ := db.Ancient("headers", number)
  137. if len(data) == 0 {
  138. data, _ = db.Get(headerKey(number, hash))
  139. }
  140. return data
  141. }
  142. // HasHeader verifies the existence of a block header corresponding to the hash.
  143. func HasHeader(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
  144. if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
  145. return true
  146. }
  147. if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
  148. return false
  149. }
  150. return true
  151. }
  152. // ReadHeader retrieves the block header corresponding to the hash.
  153. func ReadHeader(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Header {
  154. data := ReadHeaderRLP(db, hash, number)
  155. if len(data) == 0 {
  156. return nil
  157. }
  158. header := new(types.Header)
  159. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  160. log.Error("Invalid block header RLP", "hash", hash, "err", err)
  161. return nil
  162. }
  163. return header
  164. }
  165. // WriteHeader stores a block header into the database and also stores the hash-
  166. // to-number mapping.
  167. func WriteHeader(db ethdb.Writer, header *types.Header) {
  168. // Write the hash -> number mapping
  169. var (
  170. hash = header.Hash()
  171. number = header.Number.Uint64()
  172. encoded = encodeBlockNumber(number)
  173. )
  174. key := headerNumberKey(hash)
  175. if err := db.Put(key, encoded); err != nil {
  176. log.Crit("Failed to store hash to number mapping", "err", err)
  177. }
  178. // Write the encoded header
  179. data, err := rlp.EncodeToBytes(header)
  180. if err != nil {
  181. log.Crit("Failed to RLP encode header", "err", err)
  182. }
  183. key = headerKey(number, hash)
  184. if err := db.Put(key, data); err != nil {
  185. log.Crit("Failed to store header", "err", err)
  186. }
  187. }
  188. // DeleteHeader removes all block header data associated with a hash.
  189. func DeleteHeader(db ethdb.Writer, hash common.Hash, number uint64) {
  190. deleteHeaderWithoutNumber(db, hash, number)
  191. if err := db.Delete(headerNumberKey(hash)); err != nil {
  192. log.Crit("Failed to delete hash to number mapping", "err", err)
  193. }
  194. }
  195. // deleteHeaderWithoutNumber removes only the block header but does not remove
  196. // the hash to number mapping.
  197. func deleteHeaderWithoutNumber(db ethdb.Writer, hash common.Hash, number uint64) {
  198. if err := db.Delete(headerKey(number, hash)); err != nil {
  199. log.Crit("Failed to delete header", "err", err)
  200. }
  201. }
  202. // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  203. func ReadBodyRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
  204. data, _ := db.Ancient("bodies", number)
  205. if len(data) == 0 {
  206. data, _ = db.Get(blockBodyKey(number, hash))
  207. }
  208. return data
  209. }
  210. // WriteBodyRLP stores an RLP encoded block body into the database.
  211. func WriteBodyRLP(db ethdb.Writer, hash common.Hash, number uint64, rlp rlp.RawValue) {
  212. if err := db.Put(blockBodyKey(number, hash), rlp); err != nil {
  213. log.Crit("Failed to store block body", "err", err)
  214. }
  215. }
  216. // HasBody verifies the existence of a block body corresponding to the hash.
  217. func HasBody(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
  218. if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
  219. return true
  220. }
  221. if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
  222. return false
  223. }
  224. return true
  225. }
  226. // ReadBody retrieves the block body corresponding to the hash.
  227. func ReadBody(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Body {
  228. data := ReadBodyRLP(db, hash, number)
  229. if len(data) == 0 {
  230. return nil
  231. }
  232. body := new(types.Body)
  233. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  234. log.Error("Invalid block body RLP", "hash", hash, "err", err)
  235. return nil
  236. }
  237. return body
  238. }
  239. // WriteBody stores a block body into the database.
  240. func WriteBody(db ethdb.Writer, hash common.Hash, number uint64, body *types.Body) {
  241. data, err := rlp.EncodeToBytes(body)
  242. if err != nil {
  243. log.Crit("Failed to RLP encode body", "err", err)
  244. }
  245. WriteBodyRLP(db, hash, number, data)
  246. }
  247. // DeleteBody removes all block body data associated with a hash.
  248. func DeleteBody(db ethdb.Writer, hash common.Hash, number uint64) {
  249. if err := db.Delete(blockBodyKey(number, hash)); err != nil {
  250. log.Crit("Failed to delete block body", "err", err)
  251. }
  252. }
  253. // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding.
  254. func ReadTdRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
  255. data, _ := db.Ancient("diffs", number)
  256. if len(data) == 0 {
  257. data, _ = db.Get(headerTDKey(number, hash))
  258. }
  259. return data
  260. }
  261. // ReadTd retrieves a block's total difficulty corresponding to the hash.
  262. func ReadTd(db ethdb.AncientReader, hash common.Hash, number uint64) *big.Int {
  263. data := ReadTdRLP(db, hash, number)
  264. if len(data) == 0 {
  265. return nil
  266. }
  267. td := new(big.Int)
  268. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  269. log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
  270. return nil
  271. }
  272. return td
  273. }
  274. // WriteTd stores the total difficulty of a block into the database.
  275. func WriteTd(db ethdb.Writer, hash common.Hash, number uint64, td *big.Int) {
  276. data, err := rlp.EncodeToBytes(td)
  277. if err != nil {
  278. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  279. }
  280. if err := db.Put(headerTDKey(number, hash), data); err != nil {
  281. log.Crit("Failed to store block total difficulty", "err", err)
  282. }
  283. }
  284. // DeleteTd removes all block total difficulty data associated with a hash.
  285. func DeleteTd(db ethdb.Writer, hash common.Hash, number uint64) {
  286. if err := db.Delete(headerTDKey(number, hash)); err != nil {
  287. log.Crit("Failed to delete block total difficulty", "err", err)
  288. }
  289. }
  290. // HasReceipts verifies the existence of all the transaction receipts belonging
  291. // to a block.
  292. func HasReceipts(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
  293. if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
  294. return true
  295. }
  296. if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil {
  297. return false
  298. }
  299. return true
  300. }
  301. // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding.
  302. func ReadReceiptsRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
  303. data, _ := db.Ancient("receipts", number)
  304. if len(data) == 0 {
  305. data, _ = db.Get(blockReceiptsKey(number, hash))
  306. }
  307. return data
  308. }
  309. // ReadRawReceipts retrieves all the transaction receipts belonging to a block.
  310. // The receipt metadata fields are not guaranteed to be populated, so they
  311. // should not be used. Use ReadReceipts instead if the metadata is needed.
  312. func ReadRawReceipts(db ethdb.AncientReader, hash common.Hash, number uint64) types.Receipts {
  313. // Retrieve the flattened receipt slice
  314. data := ReadReceiptsRLP(db, hash, number)
  315. if len(data) == 0 {
  316. return nil
  317. }
  318. // Convert the receipts from their storage form to their internal representation
  319. storageReceipts := []*types.ReceiptForStorage{}
  320. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  321. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  322. return nil
  323. }
  324. receipts := make(types.Receipts, len(storageReceipts))
  325. for i, storageReceipt := range storageReceipts {
  326. receipts[i] = (*types.Receipt)(storageReceipt)
  327. }
  328. return receipts
  329. }
  330. // ReadReceipts retrieves all the transaction receipts belonging to a block, including
  331. // its correspoinding metadata fields. If it is unable to populate these metadata
  332. // fields then nil is returned.
  333. //
  334. // The current implementation populates these metadata fields by reading the receipts'
  335. // corresponding block body, so if the block body is not found it will return nil even
  336. // if the receipt itself is stored.
  337. func ReadReceipts(db ethdb.AncientReader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
  338. // We're deriving many fields from the block body, retrieve beside the receipt
  339. receipts := ReadRawReceipts(db, hash, number)
  340. if receipts == nil {
  341. return nil
  342. }
  343. body := ReadBody(db, hash, number)
  344. if body == nil {
  345. log.Error("Missing body but have receipt", "hash", hash, "number", number)
  346. return nil
  347. }
  348. if err := receipts.DeriveFields(config, hash, number, body.Transactions); err != nil {
  349. log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err)
  350. return nil
  351. }
  352. return receipts
  353. }
  354. // WriteReceipts stores all the transaction receipts belonging to a block.
  355. func WriteReceipts(db ethdb.Writer, hash common.Hash, number uint64, receipts types.Receipts) {
  356. // Convert the receipts into their storage form and serialize them
  357. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  358. for i, receipt := range receipts {
  359. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  360. }
  361. bytes, err := rlp.EncodeToBytes(storageReceipts)
  362. if err != nil {
  363. log.Crit("Failed to encode block receipts", "err", err)
  364. }
  365. // Store the flattened receipt slice
  366. if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil {
  367. log.Crit("Failed to store block receipts", "err", err)
  368. }
  369. }
  370. // DeleteReceipts removes all receipt data associated with a block hash.
  371. func DeleteReceipts(db ethdb.Writer, hash common.Hash, number uint64) {
  372. if err := db.Delete(blockReceiptsKey(number, hash)); err != nil {
  373. log.Crit("Failed to delete block receipts", "err", err)
  374. }
  375. }
  376. // ReadBlock retrieves an entire block corresponding to the hash, assembling it
  377. // back from the stored header and body. If either the header or body could not
  378. // be retrieved nil is returned.
  379. //
  380. // Note, due to concurrent download of header and block body the header and thus
  381. // canonical hash can be stored in the database but the body data not (yet).
  382. func ReadBlock(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Block {
  383. header := ReadHeader(db, hash, number)
  384. if header == nil {
  385. return nil
  386. }
  387. body := ReadBody(db, hash, number)
  388. if body == nil {
  389. return nil
  390. }
  391. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  392. }
  393. // WriteBlock serializes a block into the database, header and body separately.
  394. func WriteBlock(db ethdb.Writer, block *types.Block) {
  395. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  396. WriteHeader(db, block.Header())
  397. }
  398. // DeleteBlock removes all block data associated with a hash.
  399. func DeleteBlock(db ethdb.Writer, hash common.Hash, number uint64) {
  400. DeleteReceipts(db, hash, number)
  401. DeleteHeader(db, hash, number)
  402. DeleteBody(db, hash, number)
  403. DeleteTd(db, hash, number)
  404. }
  405. // deleteBlockWithoutNumber removes all block data associated with a hash, except
  406. // the hash to number mapping.
  407. func deleteBlockWithoutNumber(db ethdb.Writer, hash common.Hash, number uint64) {
  408. DeleteReceipts(db, hash, number)
  409. deleteHeaderWithoutNumber(db, hash, number)
  410. DeleteBody(db, hash, number)
  411. DeleteTd(db, hash, number)
  412. }
  413. // FindCommonAncestor returns the last common ancestor of two block headers
  414. func FindCommonAncestor(db ethdb.AncientReader, a, b *types.Header) *types.Header {
  415. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  416. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  417. if a == nil {
  418. return nil
  419. }
  420. }
  421. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  422. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  423. if b == nil {
  424. return nil
  425. }
  426. }
  427. for a.Hash() != b.Hash() {
  428. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  429. if a == nil {
  430. return nil
  431. }
  432. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  433. if b == nil {
  434. return nil
  435. }
  436. }
  437. return a
  438. }