github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/gossip/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 gossip 18 19 import ( 20 "errors" 21 "fmt" 22 "time" 23 24 "github.com/unicornultrafoundation/go-u2u/common" 25 "github.com/unicornultrafoundation/go-u2u/core/state" 26 "github.com/unicornultrafoundation/go-u2u/core/types" 27 "github.com/unicornultrafoundation/go-u2u/core/vm" 28 "github.com/unicornultrafoundation/go-u2u/evmcore" 29 "github.com/unicornultrafoundation/go-u2u/log" 30 "github.com/unicornultrafoundation/go-u2u/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 func (eth *Service) stateAtBlock(evmblock *evmcore.EvmBlock, reexec uint64, base *state.StateDB, checkLive bool) (statedb *state.StateDB, err error) { 39 block := evmblock.EthBlock() 40 var ( 41 current *evmcore.EvmBlock 42 database state.Database 43 report = true 44 origin = block.NumberU64() 45 ) 46 // Check the live database first if we have the state fully available, use that. 47 if checkLive { 48 statedb, err = eth.EthAPI.state.StateAt(block.Root()) 49 if err == nil { 50 return statedb, nil 51 } 52 } 53 if base != nil { 54 // The optional base statedb is given, mark the start point as parent block 55 statedb, database, report = base, base.Database(), false 56 current = eth.EthAPI.state.GetBlock(block.ParentHash(), block.NumberU64()-1) 57 } else { 58 // Otherwise try to reexec blocks until we find a state or reach our limit 59 current = evmblock 60 61 // Create an ephemeral trie.Database for isolating the live one. Otherwise 62 // the internal junks created by tracing will be persisted into the disk. 63 database = state.NewDatabaseWithConfig(eth.EthAPI.ChainDb(), &trie.Config{Cache: 16}) 64 65 // If we didn't check the dirty database, do check the clean one, otherwise 66 // we would rewind past a persisted block (specific corner case is chain 67 // tracing from the genesis). 68 if !checkLive { 69 statedb, err = state.New(current.Root, database, nil) 70 if err == nil { 71 return statedb, nil 72 } 73 } 74 // Database does not have the state for the given block, try to regenerate 75 for i := uint64(0); i < reexec; i++ { 76 if current.NumberU64() == 0 { 77 return nil, errors.New("genesis state is missing") 78 } 79 parent := eth.EthAPI.state.GetBlock(current.ParentHash, current.NumberU64()-1) 80 if parent == nil { 81 return nil, fmt.Errorf("missing block %v %d", current.ParentHash, current.NumberU64()-1) 82 } 83 current = parent 84 85 statedb, err = state.New(current.Root, database, nil) 86 if err == nil { 87 break 88 } 89 } 90 if err != nil { 91 switch err.(type) { 92 case *trie.MissingNodeError: 93 return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec) 94 default: 95 return nil, err 96 } 97 } 98 } 99 // State was available at historical point, regenerate 100 var ( 101 start = time.Now() 102 logged time.Time 103 parent common.Hash 104 ) 105 for current.NumberU64() < origin { 106 // Print progress logs if long enough time elapsed 107 if time.Since(logged) > 8*time.Second && report { 108 log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start)) 109 logged = time.Now() 110 } 111 // Retrieve the next block to regenerate and process it 112 next := current.NumberU64() + 1 113 if current = eth.EthAPI.state.GetBlock(common.Hash{}, next); current == nil { 114 return nil, fmt.Errorf("block #%d not found", next) 115 } 116 evmProcessor := evmcore.NewStateProcessor(eth.EthAPI.ChainConfig(), eth.EthAPI.state) 117 var gasUsed uint64 = 0 118 _, _, _, err := evmProcessor.Process(current, statedb, vm.Config{}, &gasUsed, func(l *types.Log, _ *state.StateDB) {}) 119 if err != nil { 120 return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err) 121 } 122 // Finalize the state so any modifications are written to the trie 123 root, err := statedb.Commit(eth.EthAPI.ChainConfig().IsEIP158(current.Number)) 124 if err != nil { 125 return nil, err 126 } 127 statedb, err = state.New(root, database, nil) 128 if err != nil { 129 return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err) 130 } 131 database.TrieDB().Reference(root, common.Hash{}) 132 if parent != (common.Hash{}) { 133 database.TrieDB().Dereference(parent) 134 } 135 parent = root 136 } 137 if report { 138 nodes, imgs := database.TrieDB().Size() 139 log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs) 140 } 141 return statedb, nil 142 } 143 144 // stateAtTransaction returns the execution environment of a certain transaction. 145 func (eth *Service) stateAtTransaction(evmblock *evmcore.EvmBlock, txIndex int, reexec uint64) (evmcore.Message, vm.BlockContext, *state.StateDB, error) { 146 block := evmblock.EthBlock() 147 // Short circuit if it's genesis block. 148 if block.NumberU64() == 0 { 149 return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis") 150 } 151 // Create the parent state database 152 parent := eth.EthAPI.state.GetBlock(block.ParentHash(), block.NumberU64()-1) 153 if parent == nil { 154 return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash()) 155 } 156 // Lookup the statedb of parent block from the live database, 157 // otherwise regenerate it on the flight. 158 statedb, err := eth.stateAtBlock(parent, reexec, nil, true) 159 if err != nil { 160 return nil, vm.BlockContext{}, nil, err 161 } 162 if txIndex == 0 && len(block.Transactions()) == 0 { 163 return nil, vm.BlockContext{}, statedb, nil 164 } 165 // Recompute transactions up to the target index. 166 signer := types.MakeSigner(eth.EthAPI.ChainConfig(), block.Number()) 167 for idx, tx := range block.Transactions() { 168 // Assemble the transaction call message and return if the requested offset 169 msg, _ := tx.AsMessage(signer, block.BaseFee()) 170 txContext := evmcore.NewEVMTxContext(msg) 171 context := evmcore.NewEVMBlockContext(evmcore.ConvertFromEthHeader(block.Header()), eth.EthAPI.state, nil) 172 if idx == txIndex { 173 return msg, context, statedb, nil 174 } 175 // Not yet the searched for transaction, execute on top of the current state 176 vmenv := vm.NewEVM(context, txContext, statedb, eth.EthAPI.ChainConfig(), vm.Config{}) 177 statedb.Prepare(tx.Hash(), idx) 178 if _, err := evmcore.ApplyMessage(vmenv, msg, new(evmcore.GasPool).AddGas(tx.Gas())); err != nil { 179 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err) 180 } 181 // Ensure any modifications are committed to the state 182 // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect 183 statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number())) 184 } 185 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash()) 186 }