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