accessors_chain.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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/log"
  24. "github.com/ethereum/go-ethereum/rlp"
  25. )
  26. // ReadCanonicalHash retrieves the hash assigned to a canonical block number.
  27. func ReadCanonicalHash(db DatabaseReader, number uint64) common.Hash {
  28. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...))
  29. if len(data) == 0 {
  30. return common.Hash{}
  31. }
  32. return common.BytesToHash(data)
  33. }
  34. // WriteCanonicalHash stores the hash assigned to a canonical block number.
  35. func WriteCanonicalHash(db DatabaseWriter, hash common.Hash, number uint64) {
  36. key := append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...)
  37. if err := db.Put(key, 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 DatabaseDeleter, number uint64) {
  43. if err := db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...)); 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 DatabaseReader, hash common.Hash) *uint64 {
  49. data, _ := db.Get(append(headerNumberPrefix, hash.Bytes()...))
  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 DatabaseReader) 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 DatabaseWriter, 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 DatabaseReader) 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 DatabaseWriter, 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 DatabaseReader) 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 DatabaseWriter, 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 DatabaseReader) 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 DatabaseWriter, 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 DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
  116. data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  117. return data
  118. }
  119. // HasHeader verifies the existence of a block header corresponding to the hash.
  120. func HasHeader(db DatabaseReader, hash common.Hash, number uint64) bool {
  121. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  122. if has, err := db.Has(key); !has || err != nil {
  123. return false
  124. }
  125. return true
  126. }
  127. // ReadHeader retrieves the block header corresponding to the hash.
  128. func ReadHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header {
  129. data := ReadHeaderRLP(db, hash, number)
  130. if len(data) == 0 {
  131. return nil
  132. }
  133. header := new(types.Header)
  134. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  135. log.Error("Invalid block header RLP", "hash", hash, "err", err)
  136. return nil
  137. }
  138. return header
  139. }
  140. // WriteHeader stores a block header into the database and also stores the hash-
  141. // to-number mapping.
  142. func WriteHeader(db DatabaseWriter, header *types.Header) {
  143. // Write the hash -> number mapping
  144. var (
  145. hash = header.Hash().Bytes()
  146. number = header.Number.Uint64()
  147. encoded = encodeBlockNumber(number)
  148. )
  149. key := append(headerNumberPrefix, hash...)
  150. if err := db.Put(key, encoded); err != nil {
  151. log.Crit("Failed to store hash to number mapping", "err", err)
  152. }
  153. // Write the encoded header
  154. data, err := rlp.EncodeToBytes(header)
  155. if err != nil {
  156. log.Crit("Failed to RLP encode header", "err", err)
  157. }
  158. key = append(append(headerPrefix, encoded...), hash...)
  159. if err := db.Put(key, data); err != nil {
  160. log.Crit("Failed to store header", "err", err)
  161. }
  162. }
  163. // DeleteHeader removes all block header data associated with a hash.
  164. func DeleteHeader(db DatabaseDeleter, hash common.Hash, number uint64) {
  165. if err := db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)); err != nil {
  166. log.Crit("Failed to delete header", "err", err)
  167. }
  168. if err := db.Delete(append(headerNumberPrefix, hash.Bytes()...)); err != nil {
  169. log.Crit("Failed to delete hash to number mapping", "err", err)
  170. }
  171. }
  172. // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  173. func ReadBodyRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
  174. data, _ := db.Get(append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
  175. return data
  176. }
  177. // WriteBodyRLP stores an RLP encoded block body into the database.
  178. func WriteBodyRLP(db DatabaseWriter, hash common.Hash, number uint64, rlp rlp.RawValue) {
  179. key := append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  180. if err := db.Put(key, rlp); err != nil {
  181. log.Crit("Failed to store block body", "err", err)
  182. }
  183. }
  184. // HasBody verifies the existence of a block body corresponding to the hash.
  185. func HasBody(db DatabaseReader, hash common.Hash, number uint64) bool {
  186. key := append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  187. if has, err := db.Has(key); !has || err != nil {
  188. return false
  189. }
  190. return true
  191. }
  192. // ReadBody retrieves the block body corresponding to the hash.
  193. func ReadBody(db DatabaseReader, hash common.Hash, number uint64) *types.Body {
  194. data := ReadBodyRLP(db, hash, number)
  195. if len(data) == 0 {
  196. return nil
  197. }
  198. body := new(types.Body)
  199. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  200. log.Error("Invalid block body RLP", "hash", hash, "err", err)
  201. return nil
  202. }
  203. return body
  204. }
  205. // WriteBody storea a block body into the database.
  206. func WriteBody(db DatabaseWriter, hash common.Hash, number uint64, body *types.Body) {
  207. data, err := rlp.EncodeToBytes(body)
  208. if err != nil {
  209. log.Crit("Failed to RLP encode body", "err", err)
  210. }
  211. WriteBodyRLP(db, hash, number, data)
  212. }
  213. // DeleteBody removes all block body data associated with a hash.
  214. func DeleteBody(db DatabaseDeleter, hash common.Hash, number uint64) {
  215. if err := db.Delete(append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)); err != nil {
  216. log.Crit("Failed to delete block body", "err", err)
  217. }
  218. }
  219. // ReadTd retrieves a block's total difficulty corresponding to the hash.
  220. func ReadTd(db DatabaseReader, hash common.Hash, number uint64) *big.Int {
  221. data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), headerTDSuffix...))
  222. if len(data) == 0 {
  223. return nil
  224. }
  225. td := new(big.Int)
  226. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  227. log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
  228. return nil
  229. }
  230. return td
  231. }
  232. // WriteTd stores the total difficulty of a block into the database.
  233. func WriteTd(db DatabaseWriter, hash common.Hash, number uint64, td *big.Int) {
  234. data, err := rlp.EncodeToBytes(td)
  235. if err != nil {
  236. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  237. }
  238. key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), headerTDSuffix...)
  239. if err := db.Put(key, data); err != nil {
  240. log.Crit("Failed to store block total difficulty", "err", err)
  241. }
  242. }
  243. // DeleteTd removes all block total difficulty data associated with a hash.
  244. func DeleteTd(db DatabaseDeleter, hash common.Hash, number uint64) {
  245. if err := db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), headerTDSuffix...)); err != nil {
  246. log.Crit("Failed to delete block total difficulty", "err", err)
  247. }
  248. }
  249. // ReadReceipts retrieves all the transaction receipts belonging to a block.
  250. func ReadReceipts(db DatabaseReader, hash common.Hash, number uint64) types.Receipts {
  251. // Retrieve the flattened receipt slice
  252. data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
  253. if len(data) == 0 {
  254. return nil
  255. }
  256. // Convert the revceipts from their storage form to their internal representation
  257. storageReceipts := []*types.ReceiptForStorage{}
  258. if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
  259. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  260. return nil
  261. }
  262. receipts := make(types.Receipts, len(storageReceipts))
  263. for i, receipt := range storageReceipts {
  264. receipts[i] = (*types.Receipt)(receipt)
  265. }
  266. return receipts
  267. }
  268. // WriteReceipts stores all the transaction receipts belonging to a block.
  269. func WriteReceipts(db DatabaseWriter, hash common.Hash, number uint64, receipts types.Receipts) {
  270. // Convert the receipts into their storage form and serialize them
  271. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  272. for i, receipt := range receipts {
  273. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  274. }
  275. bytes, err := rlp.EncodeToBytes(storageReceipts)
  276. if err != nil {
  277. log.Crit("Failed to encode block receipts", "err", err)
  278. }
  279. // Store the flattened receipt slice
  280. key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
  281. if err := db.Put(key, bytes); err != nil {
  282. log.Crit("Failed to store block receipts", "err", err)
  283. }
  284. }
  285. // DeleteReceipts removes all receipt data associated with a block hash.
  286. func DeleteReceipts(db DatabaseDeleter, hash common.Hash, number uint64) {
  287. if err := db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)); err != nil {
  288. log.Crit("Failed to delete block receipts", "err", err)
  289. }
  290. }
  291. // ReadBlock retrieves an entire block corresponding to the hash, assembling it
  292. // back from the stored header and body. If either the header or body could not
  293. // be retrieved nil is returned.
  294. //
  295. // Note, due to concurrent download of header and block body the header and thus
  296. // canonical hash can be stored in the database but the body data not (yet).
  297. func ReadBlock(db DatabaseReader, hash common.Hash, number uint64) *types.Block {
  298. header := ReadHeader(db, hash, number)
  299. if header == nil {
  300. return nil
  301. }
  302. body := ReadBody(db, hash, number)
  303. if body == nil {
  304. return nil
  305. }
  306. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  307. }
  308. // WriteBlock serializes a block into the database, header and body separately.
  309. func WriteBlock(db DatabaseWriter, block *types.Block) {
  310. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  311. WriteHeader(db, block.Header())
  312. }
  313. // DeleteBlock removes all block data associated with a hash.
  314. func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) {
  315. DeleteReceipts(db, hash, number)
  316. DeleteHeader(db, hash, number)
  317. DeleteBody(db, hash, number)
  318. DeleteTd(db, hash, number)
  319. }
  320. // FindCommonAncestor returns the last common ancestor of two block headers
  321. func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header {
  322. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  323. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  324. if a == nil {
  325. return nil
  326. }
  327. }
  328. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  329. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  330. if b == nil {
  331. return nil
  332. }
  333. }
  334. for a.Hash() != b.Hash() {
  335. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  336. if a == nil {
  337. return nil
  338. }
  339. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  340. if b == nil {
  341. return nil
  342. }
  343. }
  344. return a
  345. }