accessors_chain.go 14 KB

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