github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/eth/state_accessor.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 eth 18 19 import ( 20 "errors" 21 "fmt" 22 "time" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/core" 26 "github.com/ethereum/go-ethereum/core/state" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/core/vm" 29 "github.com/ethereum/go-ethereum/log" 30 "github.com/ethereum/go-ethereum/trie" 31 ) 32 33 // StateAtBlock retrieves the state database associated with a certain block. 34 // If no state is locally available for the given block, a number of blocks 35 // are attempted to be reexecuted to generate the desired state. The optional 36 // base layer statedb can be passed then it's regarded as the statedb of the 37 // parent block. 38 // Parameters: 39 // - block: The block for which we want the state (== state at the stateRoot of the parent) 40 // - reexec: The maximum number of blocks to reprocess trying to obtain the desired state 41 // - base: If the caller is tracing multiple blocks, the caller can provide the parent state 42 // continuously from the callsite. 43 // - checklive: if true, then the live 'blockchain' state database is used. If the caller want to 44 // perform Commit or other 'save-to-disk' changes, this should be set to false to avoid 45 // storing trash persistently 46 // - preferDisk: this arg can be used by the caller to signal that even though the 'base' is provided, 47 // it would be preferrable to start from a fresh state, if we have it on disk. 48 func (eth *Ethereum) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) { 49 var ( 50 current *types.Block 51 database state.Database 52 report = true 53 origin = block.NumberU64() 54 ) 55 // Check the live database first if we have the state fully available, use that. 56 if checkLive { 57 statedb, err = eth.blockchain.StateAt(block.Root()) 58 if err == nil { 59 return statedb, nil 60 } 61 } 62 if base != nil { 63 if preferDisk { 64 // Create an ephemeral trie.Database for isolating the live one. Otherwise 65 // the internal junks created by tracing will be persisted into the disk. 66 database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16}) 67 if statedb, err = state.New(block.Root(), database, nil); err == nil { 68 log.Info("Found disk backend for state trie", "root", block.Root(), "number", block.Number()) 69 return statedb, nil 70 } 71 } 72 // The optional base statedb is given, mark the start point as parent block 73 statedb, database, report = base, base.Database(), false 74 current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 75 } else { 76 // Otherwise try to reexec blocks until we find a state or reach our limit 77 current = block 78 79 // Create an ephemeral trie.Database for isolating the live one. Otherwise 80 // the internal junks created by tracing will be persisted into the disk. 81 database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16}) 82 83 // If we didn't check the dirty database, do check the clean one, otherwise 84 // we would rewind past a persisted block (specific corner case is chain 85 // tracing from the genesis). 86 if !checkLive { 87 statedb, err = state.New(current.Root(), database, nil) 88 if err == nil { 89 return statedb, nil 90 } 91 } 92 // Database does not have the state for the given block, try to regenerate 93 for i := uint64(0); i < reexec; i++ { 94 if current.NumberU64() == 0 { 95 return nil, errors.New("genesis state is missing") 96 } 97 parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1) 98 if parent == nil { 99 return nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1) 100 } 101 current = parent 102 103 statedb, err = state.New(current.Root(), database, nil) 104 if err == nil { 105 break 106 } 107 } 108 if err != nil { 109 switch err.(type) { 110 case *trie.MissingNodeError: 111 return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec) 112 default: 113 return nil, err 114 } 115 } 116 } 117 // State was available at historical point, regenerate 118 var ( 119 start = time.Now() 120 logged time.Time 121 parent common.Hash 122 ) 123 for current.NumberU64() < origin { 124 // Print progress logs if long enough time elapsed 125 if time.Since(logged) > 8*time.Second && report { 126 log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start)) 127 logged = time.Now() 128 } 129 // Retrieve the next block to regenerate and process it 130 next := current.NumberU64() + 1 131 if current = eth.blockchain.GetBlockByNumber(next); current == nil { 132 return nil, fmt.Errorf("block #%d not found", next) 133 } 134 135 _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{}, nil) 136 137 if err != nil { 138 return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err) 139 } 140 // Finalize the state so any modifications are written to the trie 141 root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number())) 142 if err != nil { 143 return nil, fmt.Errorf("stateAtBlock commit failed, number %d root %v: %w", 144 current.NumberU64(), current.Root().Hex(), err) 145 } 146 statedb, err = state.New(root, database, nil) 147 if err != nil { 148 return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err) 149 } 150 database.TrieDB().Reference(root, common.Hash{}) 151 if parent != (common.Hash{}) { 152 database.TrieDB().Dereference(parent) 153 } 154 parent = root 155 } 156 if report { 157 nodes, imgs := database.TrieDB().Size() 158 log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs) 159 } 160 return statedb, nil 161 } 162 163 // stateAtTransaction returns the execution environment of a certain transaction. 164 func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) { 165 // Short circuit if it's genesis block. 166 if block.NumberU64() == 0 { 167 return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis") 168 } 169 // Create the parent state database 170 parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 171 if parent == nil { 172 return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash()) 173 } 174 // Lookup the statedb of parent block from the live database, 175 // otherwise regenerate it on the flight. 176 statedb, err := eth.StateAtBlock(parent, reexec, nil, true, false) 177 if err != nil { 178 return nil, vm.BlockContext{}, nil, err 179 } 180 if txIndex == 0 && len(block.Transactions()) == 0 { 181 return nil, vm.BlockContext{}, statedb, nil 182 } 183 // Recompute transactions up to the target index. 184 signer := types.MakeSigner(eth.blockchain.Config(), block.Number()) 185 for idx, tx := range block.Transactions() { 186 // Assemble the transaction call message and return if the requested offset 187 msg, _ := tx.AsMessage(signer, block.BaseFee()) 188 txContext := core.NewEVMTxContext(msg) 189 context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil) 190 if idx == txIndex { 191 return msg, context, statedb, nil 192 } 193 // Not yet the searched for transaction, execute on top of the current state 194 vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{}) 195 statedb.Prepare(tx.Hash(), idx) 196 197 if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()), nil); err != nil { 198 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err) 199 } 200 201 // Ensure any modifications are committed to the state 202 // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect 203 statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number())) 204 } 205 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash()) 206 }