github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/cmd/evm/internal/t8ntool/execution.go (about) 1 // Copyright 2020 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 t8ntool 18 19 import ( 20 "fmt" 21 "math/big" 22 "os" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/common/math" 26 "github.com/ethereum/go-ethereum/consensus/ethash" 27 "github.com/ethereum/go-ethereum/consensus/misc" 28 "github.com/ethereum/go-ethereum/core" 29 "github.com/ethereum/go-ethereum/core/rawdb" 30 "github.com/ethereum/go-ethereum/core/state" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/core/vm" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/ethdb" 35 "github.com/ethereum/go-ethereum/log" 36 "github.com/ethereum/go-ethereum/params" 37 "github.com/ethereum/go-ethereum/rlp" 38 "github.com/ethereum/go-ethereum/trie" 39 "golang.org/x/crypto/sha3" 40 ) 41 42 type Prestate struct { 43 Env stEnv `json:"env"` 44 Pre core.GenesisAlloc `json:"pre"` 45 } 46 47 // ExecutionResult contains the execution status after running a state test, any 48 // error that might have occurred and a dump of the final state if requested. 49 type ExecutionResult struct { 50 StateRoot common.Hash `json:"stateRoot"` 51 TxRoot common.Hash `json:"txRoot"` 52 ReceiptRoot common.Hash `json:"receiptsRoot"` 53 LogsHash common.Hash `json:"logsHash"` 54 Bloom types.Bloom `json:"logsBloom" gencodec:"required"` 55 Receipts types.Receipts `json:"receipts"` 56 Rejected []*rejectedTx `json:"rejected,omitempty"` 57 Difficulty *math.HexOrDecimal256 `json:"currentDifficulty" gencodec:"required"` 58 GasUsed math.HexOrDecimal64 `json:"gasUsed"` 59 } 60 61 type ommer struct { 62 Delta uint64 `json:"delta"` 63 Address common.Address `json:"address"` 64 } 65 66 //go:generate go run github.com/fjl/gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go 67 type stEnv struct { 68 Coinbase common.Address `json:"currentCoinbase" gencodec:"required"` 69 Difficulty *big.Int `json:"currentDifficulty"` 70 Random *big.Int `json:"currentRandom"` 71 ParentDifficulty *big.Int `json:"parentDifficulty"` 72 GasLimit uint64 `json:"currentGasLimit" gencodec:"required"` 73 Number uint64 `json:"currentNumber" gencodec:"required"` 74 Timestamp uint64 `json:"currentTimestamp" gencodec:"required"` 75 ParentTimestamp uint64 `json:"parentTimestamp,omitempty"` 76 BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"` 77 Ommers []ommer `json:"ommers,omitempty"` 78 BaseFee *big.Int `json:"currentBaseFee,omitempty"` 79 ParentUncleHash common.Hash `json:"parentUncleHash"` 80 } 81 82 type stEnvMarshaling struct { 83 Coinbase common.UnprefixedAddress 84 Difficulty *math.HexOrDecimal256 85 Random *math.HexOrDecimal256 86 ParentDifficulty *math.HexOrDecimal256 87 GasLimit math.HexOrDecimal64 88 Number math.HexOrDecimal64 89 Timestamp math.HexOrDecimal64 90 ParentTimestamp math.HexOrDecimal64 91 BaseFee *math.HexOrDecimal256 92 } 93 94 type rejectedTx struct { 95 Index int `json:"index"` 96 Err string `json:"error"` 97 } 98 99 // Apply applies a set of transactions to a pre-state 100 func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig, 101 txs types.Transactions, miningReward int64, 102 getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error)) (*state.StateDB, *ExecutionResult, error) { 103 104 // Capture errors for BLOCKHASH operation, if we haven't been supplied the 105 // required blockhashes 106 var hashError error 107 getHash := func(num uint64) common.Hash { 108 if pre.Env.BlockHashes == nil { 109 hashError = fmt.Errorf("getHash(%d) invoked, no blockhashes provided", num) 110 return common.Hash{} 111 } 112 h, ok := pre.Env.BlockHashes[math.HexOrDecimal64(num)] 113 if !ok { 114 hashError = fmt.Errorf("getHash(%d) invoked, blockhash for that block not provided", num) 115 } 116 return h 117 } 118 var ( 119 statedb = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre) 120 signer = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number)) 121 gaspool = new(core.GasPool) 122 blockHash = common.Hash{0x13, 0x37} 123 rejectedTxs []*rejectedTx 124 includedTxs types.Transactions 125 gasUsed = uint64(0) 126 receipts = make(types.Receipts, 0) 127 txIndex = 0 128 ) 129 gaspool.AddGas(pre.Env.GasLimit) 130 vmContext := vm.BlockContext{ 131 CanTransfer: core.CanTransfer, 132 Transfer: core.Transfer, 133 Coinbase: pre.Env.Coinbase, 134 BlockNumber: new(big.Int).SetUint64(pre.Env.Number), 135 Time: new(big.Int).SetUint64(pre.Env.Timestamp), 136 Difficulty: pre.Env.Difficulty, 137 GasLimit: pre.Env.GasLimit, 138 GetHash: getHash, 139 } 140 // If currentBaseFee is defined, add it to the vmContext. 141 if pre.Env.BaseFee != nil { 142 vmContext.BaseFee = new(big.Int).Set(pre.Env.BaseFee) 143 } 144 // If random is defined, add it to the vmContext. 145 if pre.Env.Random != nil { 146 rnd := common.BigToHash(pre.Env.Random) 147 vmContext.Random = &rnd 148 } 149 // If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's 150 // done in StateProcessor.Process(block, ...), right before transactions are applied. 151 if chainConfig.DAOForkSupport && 152 chainConfig.DAOForkBlock != nil && 153 chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 { 154 misc.ApplyDAOHardFork(statedb) 155 } 156 157 for i, tx := range txs { 158 msg, err := tx.AsMessage(signer, pre.Env.BaseFee) 159 if err != nil { 160 log.Warn("rejected tx", "index", i, "hash", tx.Hash(), "error", err) 161 rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()}) 162 continue 163 } 164 tracer, err := getTracerFn(txIndex, tx.Hash()) 165 if err != nil { 166 return nil, nil, err 167 } 168 vmConfig.Tracer = tracer 169 vmConfig.Debug = (tracer != nil) 170 statedb.Prepare(tx.Hash(), txIndex) 171 txContext := core.NewEVMTxContext(msg) 172 snapshot := statedb.Snapshot() 173 evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig) 174 175 // (ret []byte, usedGas uint64, failed bool, err error) 176 msgResult, err := core.ApplyMessage(evm, msg, gaspool) 177 if err != nil { 178 statedb.RevertToSnapshot(snapshot) 179 log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From(), "error", err) 180 rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()}) 181 continue 182 } 183 includedTxs = append(includedTxs, tx) 184 if hashError != nil { 185 return nil, nil, NewError(ErrorMissingBlockhash, hashError) 186 } 187 gasUsed += msgResult.UsedGas 188 189 // Receipt: 190 { 191 var root []byte 192 if chainConfig.IsByzantium(vmContext.BlockNumber) { 193 statedb.Finalise(true) 194 } else { 195 root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes() 196 } 197 198 // Create a new receipt for the transaction, storing the intermediate root and 199 // gas used by the tx. 200 receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: gasUsed} 201 if msgResult.Failed() { 202 receipt.Status = types.ReceiptStatusFailed 203 } else { 204 receipt.Status = types.ReceiptStatusSuccessful 205 } 206 receipt.TxHash = tx.Hash() 207 receipt.GasUsed = msgResult.UsedGas 208 209 // If the transaction created a contract, store the creation address in the receipt. 210 if msg.To() == nil { 211 receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce()) 212 } 213 214 // Set the receipt logs and create the bloom filter. 215 receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash) 216 receipt.Bloom = types.CreateBloom(types.Receipts{receipt}) 217 // These three are non-consensus fields: 218 //receipt.BlockHash 219 //receipt.BlockNumber 220 receipt.TransactionIndex = uint(txIndex) 221 receipts = append(receipts, receipt) 222 } 223 224 txIndex++ 225 } 226 statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)) 227 // Add mining reward? 228 if miningReward > 0 { 229 // Add mining reward. The mining reward may be `0`, which only makes a difference in the cases 230 // where 231 // - the coinbase suicided, or 232 // - there are only 'bad' transactions, which aren't executed. In those cases, 233 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 234 var ( 235 blockReward = big.NewInt(miningReward) 236 minerReward = new(big.Int).Set(blockReward) 237 perOmmer = new(big.Int).Div(blockReward, big.NewInt(32)) 238 ) 239 for _, ommer := range pre.Env.Ommers { 240 // Add 1/32th for each ommer included 241 minerReward.Add(minerReward, perOmmer) 242 // Add (8-delta)/8 243 reward := big.NewInt(8) 244 reward.Sub(reward, big.NewInt(0).SetUint64(ommer.Delta)) 245 reward.Mul(reward, blockReward) 246 reward.Div(reward, big.NewInt(8)) 247 statedb.AddBalance(ommer.Address, reward) 248 } 249 statedb.AddBalance(pre.Env.Coinbase, minerReward) 250 } 251 // Commit block 252 root, err := statedb.Commit(chainConfig.IsEIP158(vmContext.BlockNumber)) 253 if err != nil { 254 fmt.Fprintf(os.Stderr, "Could not commit state: %v", err) 255 return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not commit state: %v", err)) 256 } 257 execRs := &ExecutionResult{ 258 StateRoot: root, 259 TxRoot: types.DeriveSha(includedTxs, trie.NewStackTrie(nil)), 260 ReceiptRoot: types.DeriveSha(receipts, trie.NewStackTrie(nil)), 261 Bloom: types.CreateBloom(receipts), 262 LogsHash: rlpHash(statedb.Logs()), 263 Receipts: receipts, 264 Rejected: rejectedTxs, 265 Difficulty: (*math.HexOrDecimal256)(vmContext.Difficulty), 266 GasUsed: (math.HexOrDecimal64)(gasUsed), 267 } 268 return statedb, execRs, nil 269 } 270 271 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB { 272 sdb := state.NewDatabase(db) 273 statedb, _ := state.New(common.Hash{}, sdb, nil) 274 for addr, a := range accounts { 275 statedb.SetCode(addr, a.Code) 276 statedb.SetNonce(addr, a.Nonce) 277 statedb.SetBalance(addr, a.Balance) 278 for k, v := range a.Storage { 279 statedb.SetState(addr, k, v) 280 } 281 } 282 // Commit and re-open to start with a clean state. 283 root, _ := statedb.Commit(false) 284 statedb, _ = state.New(root, sdb, nil) 285 return statedb 286 } 287 288 func rlpHash(x interface{}) (h common.Hash) { 289 hw := sha3.NewLegacyKeccak256() 290 rlp.Encode(hw, x) 291 hw.Sum(h[:0]) 292 return h 293 } 294 295 // calcDifficulty is based on ethash.CalcDifficulty. This method is used in case 296 // the caller does not provide an explicit difficulty, but instead provides only 297 // parent timestamp + difficulty. 298 // Note: this method only works for ethash engine. 299 func calcDifficulty(config *params.ChainConfig, number, currentTime, parentTime uint64, 300 parentDifficulty *big.Int, parentUncleHash common.Hash) *big.Int { 301 uncleHash := parentUncleHash 302 if uncleHash == (common.Hash{}) { 303 uncleHash = types.EmptyUncleHash 304 } 305 parent := &types.Header{ 306 ParentHash: common.Hash{}, 307 UncleHash: uncleHash, 308 Difficulty: parentDifficulty, 309 Number: new(big.Int).SetUint64(number - 1), 310 Time: parentTime, 311 } 312 return ethash.CalcDifficulty(config, currentTime, parent) 313 }