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