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