blockchain_reader.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // Copyright 2021 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. "math/big"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/consensus"
  21. "github.com/ethereum/go-ethereum/core/rawdb"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/state/snapshot"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/core/vm"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/ethereum/go-ethereum/params"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. )
  30. // CurrentHeader retrieves the current head header of the canonical chain. The
  31. // header is retrieved from the HeaderChain's internal cache.
  32. func (bc *BlockChain) CurrentHeader() *types.Header {
  33. return bc.hc.CurrentHeader()
  34. }
  35. // CurrentBlock retrieves the current head block of the canonical chain. The
  36. // block is retrieved from the blockchain's internal cache.
  37. func (bc *BlockChain) CurrentBlock() *types.Block {
  38. return bc.currentBlock.Load().(*types.Block)
  39. }
  40. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  41. // chain. The block is retrieved from the blockchain's internal cache.
  42. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  43. return bc.currentFastBlock.Load().(*types.Block)
  44. }
  45. // CurrentFinalizedBlock retrieves the current finalized block of the canonical
  46. // chain. The block is retrieved from the blockchain's internal cache.
  47. func (bc *BlockChain) CurrentFinalizedBlock() *types.Block {
  48. return bc.currentFinalizedBlock.Load().(*types.Block)
  49. }
  50. // CurrentSafeBlock retrieves the current safe block of the canonical
  51. // chain. The block is retrieved from the blockchain's internal cache.
  52. func (bc *BlockChain) CurrentSafeBlock() *types.Block {
  53. return bc.currentSafeBlock.Load().(*types.Block)
  54. }
  55. // HasHeader checks if a block header is present in the database or not, caching
  56. // it if present.
  57. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  58. return bc.hc.HasHeader(hash, number)
  59. }
  60. // GetHeader retrieves a block header from the database by hash and number,
  61. // caching it if found.
  62. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  63. return bc.hc.GetHeader(hash, number)
  64. }
  65. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  66. // found.
  67. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  68. return bc.hc.GetHeaderByHash(hash)
  69. }
  70. // GetHeaderByNumber retrieves a block header from the database by number,
  71. // caching it (associated with its hash) if found.
  72. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  73. return bc.hc.GetHeaderByNumber(number)
  74. }
  75. // GetHeadersFrom returns a contiguous segment of headers, in rlp-form, going
  76. // backwards from the given number.
  77. func (bc *BlockChain) GetHeadersFrom(number, count uint64) []rlp.RawValue {
  78. return bc.hc.GetHeadersFrom(number, count)
  79. }
  80. // GetBody retrieves a block body (transactions and uncles) from the database by
  81. // hash, caching it if found.
  82. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  83. // Short circuit if the body's already in the cache, retrieve otherwise
  84. if cached, ok := bc.bodyCache.Get(hash); ok {
  85. body := cached.(*types.Body)
  86. return body
  87. }
  88. number := bc.hc.GetBlockNumber(hash)
  89. if number == nil {
  90. return nil
  91. }
  92. body := rawdb.ReadBody(bc.db, hash, *number)
  93. if body == nil {
  94. return nil
  95. }
  96. // Cache the found body for next time and return
  97. bc.bodyCache.Add(hash, body)
  98. return body
  99. }
  100. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  101. // caching it if found.
  102. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  103. // Short circuit if the body's already in the cache, retrieve otherwise
  104. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  105. return cached.(rlp.RawValue)
  106. }
  107. number := bc.hc.GetBlockNumber(hash)
  108. if number == nil {
  109. return nil
  110. }
  111. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  112. if len(body) == 0 {
  113. return nil
  114. }
  115. // Cache the found body for next time and return
  116. bc.bodyRLPCache.Add(hash, body)
  117. return body
  118. }
  119. // HasBlock checks if a block is fully present in the database or not.
  120. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  121. if bc.blockCache.Contains(hash) {
  122. return true
  123. }
  124. if !bc.HasHeader(hash, number) {
  125. return false
  126. }
  127. return rawdb.HasBody(bc.db, hash, number)
  128. }
  129. // HasFastBlock checks if a fast block is fully present in the database or not.
  130. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  131. if !bc.HasBlock(hash, number) {
  132. return false
  133. }
  134. if bc.receiptsCache.Contains(hash) {
  135. return true
  136. }
  137. return rawdb.HasReceipts(bc.db, hash, number)
  138. }
  139. // GetBlock retrieves a block from the database by hash and number,
  140. // caching it if found.
  141. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  142. // Short circuit if the block's already in the cache, retrieve otherwise
  143. if block, ok := bc.blockCache.Get(hash); ok {
  144. return block.(*types.Block)
  145. }
  146. block := rawdb.ReadBlock(bc.db, hash, number)
  147. if block == nil {
  148. return nil
  149. }
  150. // Cache the found block for next time and return
  151. bc.blockCache.Add(block.Hash(), block)
  152. return block
  153. }
  154. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  155. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  156. number := bc.hc.GetBlockNumber(hash)
  157. if number == nil {
  158. return nil
  159. }
  160. return bc.GetBlock(hash, *number)
  161. }
  162. // GetBlockByNumber retrieves a block from the database by number, caching it
  163. // (associated with its hash) if found.
  164. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  165. hash := rawdb.ReadCanonicalHash(bc.db, number)
  166. if hash == (common.Hash{}) {
  167. return nil
  168. }
  169. return bc.GetBlock(hash, number)
  170. }
  171. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  172. // [deprecated by eth/62]
  173. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  174. number := bc.hc.GetBlockNumber(hash)
  175. if number == nil {
  176. return nil
  177. }
  178. for i := 0; i < n; i++ {
  179. block := bc.GetBlock(hash, *number)
  180. if block == nil {
  181. break
  182. }
  183. blocks = append(blocks, block)
  184. hash = block.ParentHash()
  185. *number--
  186. }
  187. return
  188. }
  189. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  190. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  191. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  192. return receipts.(types.Receipts)
  193. }
  194. number := rawdb.ReadHeaderNumber(bc.db, hash)
  195. if number == nil {
  196. return nil
  197. }
  198. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  199. if receipts == nil {
  200. return nil
  201. }
  202. bc.receiptsCache.Add(hash, receipts)
  203. return receipts
  204. }
  205. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  206. // a specific distance is reached.
  207. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  208. uncles := []*types.Header{}
  209. for i := 0; block != nil && i < length; i++ {
  210. uncles = append(uncles, block.Uncles()...)
  211. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  212. }
  213. return uncles
  214. }
  215. // GetCanonicalHash returns the canonical hash for a given block number
  216. func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash {
  217. return bc.hc.GetCanonicalHash(number)
  218. }
  219. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  220. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  221. // number of blocks to be individually checked before we reach the canonical chain.
  222. //
  223. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  224. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  225. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  226. }
  227. // GetTransactionLookup retrieves the lookup associate with the given transaction
  228. // hash from the cache or database.
  229. func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry {
  230. // Short circuit if the txlookup already in the cache, retrieve otherwise
  231. if lookup, exist := bc.txLookupCache.Get(hash); exist {
  232. return lookup.(*rawdb.LegacyTxLookupEntry)
  233. }
  234. tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash)
  235. if tx == nil {
  236. return nil
  237. }
  238. lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex}
  239. bc.txLookupCache.Add(hash, lookup)
  240. return lookup
  241. }
  242. // GetTd retrieves a block's total difficulty in the canonical chain from the
  243. // database by hash and number, caching it if found.
  244. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  245. return bc.hc.GetTd(hash, number)
  246. }
  247. // HasState checks if state trie is fully present in the database or not.
  248. func (bc *BlockChain) HasState(hash common.Hash) bool {
  249. _, err := bc.stateCache.OpenTrie(hash)
  250. return err == nil
  251. }
  252. // HasBlockAndState checks if a block and associated state trie is fully present
  253. // in the database or not, caching it if present.
  254. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  255. // Check first that the block itself is known
  256. block := bc.GetBlock(hash, number)
  257. if block == nil {
  258. return false
  259. }
  260. return bc.HasState(block.Root())
  261. }
  262. // TrieNode retrieves a blob of data associated with a trie node
  263. // either from ephemeral in-memory cache, or from persistent storage.
  264. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  265. return bc.stateCache.TrieDB().Node(hash)
  266. }
  267. // ContractCode retrieves a blob of data associated with a contract hash
  268. // either from ephemeral in-memory cache, or from persistent storage.
  269. func (bc *BlockChain) ContractCode(hash common.Hash) ([]byte, error) {
  270. return bc.stateCache.ContractCode(common.Hash{}, hash)
  271. }
  272. // ContractCodeWithPrefix retrieves a blob of data associated with a contract
  273. // hash either from ephemeral in-memory cache, or from persistent storage.
  274. //
  275. // If the code doesn't exist in the in-memory cache, check the storage with
  276. // new code scheme.
  277. func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) {
  278. type codeReader interface {
  279. ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error)
  280. }
  281. return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Hash{}, hash)
  282. }
  283. // State returns a new mutable state based on the current HEAD block.
  284. func (bc *BlockChain) State() (*state.StateDB, error) {
  285. return bc.StateAt(bc.CurrentBlock().Root())
  286. }
  287. // StateAt returns a new mutable state based on a particular point in time.
  288. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  289. return state.New(root, bc.stateCache, bc.snaps)
  290. }
  291. // Config retrieves the chain's fork configuration.
  292. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  293. // Engine retrieves the blockchain's consensus engine.
  294. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  295. // Snapshots returns the blockchain snapshot tree.
  296. func (bc *BlockChain) Snapshots() *snapshot.Tree {
  297. return bc.snaps
  298. }
  299. // Validator returns the current validator.
  300. func (bc *BlockChain) Validator() Validator {
  301. return bc.validator
  302. }
  303. // Processor returns the current processor.
  304. func (bc *BlockChain) Processor() Processor {
  305. return bc.processor
  306. }
  307. // StateCache returns the caching database underpinning the blockchain instance.
  308. func (bc *BlockChain) StateCache() state.Database {
  309. return bc.stateCache
  310. }
  311. // GasLimit returns the gas limit of the current HEAD block.
  312. func (bc *BlockChain) GasLimit() uint64 {
  313. return bc.CurrentBlock().GasLimit()
  314. }
  315. // Genesis retrieves the chain's genesis block.
  316. func (bc *BlockChain) Genesis() *types.Block {
  317. return bc.genesisBlock
  318. }
  319. // GetVMConfig returns the block chain VM config.
  320. func (bc *BlockChain) GetVMConfig() *vm.Config {
  321. return &bc.vmConfig
  322. }
  323. // SetTxLookupLimit is responsible for updating the txlookup limit to the
  324. // original one stored in db if the new mismatches with the old one.
  325. func (bc *BlockChain) SetTxLookupLimit(limit uint64) {
  326. bc.txLookupLimit = limit
  327. }
  328. // TxLookupLimit retrieves the txlookup limit used by blockchain to prune
  329. // stale transaction indices.
  330. func (bc *BlockChain) TxLookupLimit() uint64 {
  331. return bc.txLookupLimit
  332. }
  333. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  334. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  335. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  336. }
  337. // SubscribeChainEvent registers a subscription of ChainEvent.
  338. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  339. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  340. }
  341. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  342. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  343. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  344. }
  345. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  346. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  347. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  348. }
  349. // SubscribeLogsEvent registers a subscription of []*types.Log.
  350. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  351. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  352. }
  353. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  354. // block processing has started while false means it has stopped.
  355. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  356. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  357. }