gitlab.com/flarenetwork/coreth@v0.1.1/eth/state_accessor.go (about) 1 // (c) 2021, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2021 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package eth 28 29 import ( 30 "errors" 31 "fmt" 32 "math/big" 33 "time" 34 35 "github.com/ethereum/go-ethereum/common" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/trie" 38 "gitlab.com/flarenetwork/coreth/core" 39 "gitlab.com/flarenetwork/coreth/core/state" 40 "gitlab.com/flarenetwork/coreth/core/types" 41 "gitlab.com/flarenetwork/coreth/core/vm" 42 ) 43 44 // stateAtBlock retrieves the state database associated with a certain block. 45 // If no state is locally available for the given block, a number of blocks 46 // are attempted to be reexecuted to generate the desired state. The optional 47 // base layer statedb can be passed then it's regarded as the statedb of the 48 // parent block. 49 func (eth *Ethereum) stateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool) (statedb *state.StateDB, err error) { 50 var ( 51 current *types.Block 52 database state.Database 53 report = true 54 origin = block.NumberU64() 55 ) 56 // Check the live database first if we have the state fully available, use that. 57 if checkLive { 58 statedb, err = eth.blockchain.StateAt(block.Root()) 59 if err == nil { 60 return statedb, nil 61 } 62 } 63 if base != nil { 64 // The optional base statedb is given, mark the start point as parent block 65 statedb, database, report = base, base.Database(), false 66 current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 67 } else { 68 // Otherwise try to reexec blocks until we find a state or reach our limit 69 current = block 70 71 // Create an ephemeral trie.Database for isolating the live one. Otherwise 72 // the internal junks created by tracing will be persisted into the disk. 73 database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16}) 74 75 // If we didn't check the dirty database, do check the clean one, otherwise 76 // we would rewind past a persisted block (specific corner case is chain 77 // tracing from the genesis). 78 if !checkLive { 79 statedb, err = state.New(current.Root(), database, nil) 80 if err == nil { 81 return statedb, nil 82 } 83 } 84 // Database does not have the state for the given block, try to regenerate 85 for i := uint64(0); i < reexec; i++ { 86 if current.NumberU64() == 0 { 87 return nil, errors.New("genesis state is missing") 88 } 89 parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1) 90 if parent == nil { 91 return nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1) 92 } 93 current = parent 94 95 statedb, err = state.New(current.Root(), database, nil) 96 if err == nil { 97 break 98 } 99 } 100 if err != nil { 101 switch err.(type) { 102 case *trie.MissingNodeError: 103 return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec) 104 default: 105 return nil, err 106 } 107 } 108 } 109 // State was available at historical point, regenerate 110 var ( 111 start = time.Now() 112 logged time.Time 113 parent common.Hash 114 ) 115 for current.NumberU64() < origin { 116 // Print progress logs if long enough time elapsed 117 if time.Since(logged) > 8*time.Second && report { 118 log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start)) 119 logged = time.Now() 120 } 121 // Retrieve the next block to regenerate and process it 122 next := current.NumberU64() + 1 123 if current = eth.blockchain.GetBlockByNumber(next); current == nil { 124 return nil, fmt.Errorf("block #%d not found", next) 125 } 126 _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{}) 127 if err != nil { 128 return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err) 129 } 130 // Finalize the state so any modifications are written to the trie 131 root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number())) 132 if err != nil { 133 return nil, err 134 } 135 statedb, err = state.New(root, database, nil) 136 if err != nil { 137 return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err) 138 } 139 database.TrieDB().Reference(root, common.Hash{}) 140 if parent != (common.Hash{}) { 141 database.TrieDB().Dereference(parent) 142 } 143 parent = root 144 } 145 if report { 146 nodes, imgs := database.TrieDB().Size() 147 log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs) 148 } 149 return statedb, nil 150 } 151 152 // stateAtTransaction returns the execution environment of a certain transaction. 153 func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) { 154 // Short circuit if it's genesis block. 155 if block.NumberU64() == 0 { 156 return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis") 157 } 158 // Create the parent state database 159 parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 160 if parent == nil { 161 return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash()) 162 } 163 // Lookup the statedb of parent block from the live database, 164 // otherwise regenerate it on the flight. 165 statedb, err := eth.stateAtBlock(parent, reexec, nil, true) 166 if err != nil { 167 return nil, vm.BlockContext{}, nil, err 168 } 169 if txIndex == 0 && len(block.Transactions()) == 0 { 170 return nil, vm.BlockContext{}, statedb, nil 171 } 172 // Recompute transactions up to the target index. 173 signer := types.MakeSigner(eth.blockchain.Config(), block.Number(), new(big.Int).SetUint64(block.Time())) 174 for idx, tx := range block.Transactions() { 175 // Assemble the transaction call message and return if the requested offset 176 msg, _ := tx.AsMessage(signer, block.BaseFee()) 177 txContext := core.NewEVMTxContext(msg) 178 context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil) 179 if idx == txIndex { 180 return msg, context, statedb, nil 181 } 182 // Not yet the searched for transaction, execute on top of the current state 183 vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{}) 184 statedb.Prepare(tx.Hash(), idx) 185 if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil { 186 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err) 187 } 188 // Ensure any modifications are committed to the state 189 // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect 190 statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number())) 191 } 192 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash()) 193 }