github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/core/state_processor.go (about) 1 // Copyright 2015 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 core 18 19 import ( 20 "fmt" 21 "math/big" 22 23 "github.com/tacshi/go-ethereum/common" 24 "github.com/tacshi/go-ethereum/consensus" 25 "github.com/tacshi/go-ethereum/consensus/misc" 26 "github.com/tacshi/go-ethereum/core/state" 27 "github.com/tacshi/go-ethereum/core/types" 28 "github.com/tacshi/go-ethereum/core/vm" 29 "github.com/tacshi/go-ethereum/params" 30 ) 31 32 // StateProcessor is a basic Processor, which takes care of transitioning 33 // state from one point to another. 34 // 35 // StateProcessor implements Processor. 36 type StateProcessor struct { 37 config *params.ChainConfig // Chain configuration options 38 bc *BlockChain // Canonical block chain 39 engine consensus.Engine // Consensus engine used for block rewards 40 } 41 42 // NewStateProcessor initialises a new StateProcessor. 43 func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor { 44 return &StateProcessor{ 45 config: config, 46 bc: bc, 47 engine: engine, 48 } 49 } 50 51 // Process processes the state changes according to the Ethereum rules by running 52 // the transaction messages using the statedb and applying any rewards to both 53 // the processor (coinbase) and any included uncles. 54 // 55 // Process returns the receipts and logs accumulated during the process and 56 // returns the amount of gas that was used in the process. If any of the 57 // transactions failed to execute due to insufficient gas it will return an error. 58 func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) { 59 var ( 60 receipts types.Receipts 61 usedGas = new(uint64) 62 header = block.Header() 63 blockHash = block.Hash() 64 blockNumber = block.Number() 65 allLogs []*types.Log 66 gp = new(GasPool).AddGas(block.GasLimit()) 67 ) 68 // Mutate the block and state according to any hard-fork specs 69 if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 { 70 misc.ApplyDAOHardFork(statedb) 71 } 72 blockContext := NewEVMBlockContext(header, p.bc, nil) 73 vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg) 74 // Iterate over and process the individual transactions 75 for i, tx := range block.Transactions() { 76 msg, err := TransactionToMessage(tx, types.MakeSigner(p.config, header.Number), header.BaseFee) 77 if err != nil { 78 return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err) 79 } 80 statedb.SetTxContext(tx.Hash(), i) 81 receipt, _, err := applyTransaction(msg, p.config, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv, nil) 82 if err != nil { 83 return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err) 84 } 85 receipts = append(receipts, receipt) 86 allLogs = append(allLogs, receipt.Logs...) 87 } 88 // Fail if Shanghai not enabled and len(withdrawals) is non-zero. 89 withdrawals := block.Withdrawals() 90 if len(withdrawals) > 0 && !p.config.IsShanghai(block.Time(), types.DeserializeHeaderExtraInformation(header).ArbOSFormatVersion) { 91 return nil, nil, 0, fmt.Errorf("withdrawals before shanghai") 92 } 93 // Finalize the block, applying any consensus engine specific extras (e.g. block rewards) 94 p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles(), withdrawals) 95 96 return receipts, allLogs, *usedGas, nil 97 } 98 99 func applyTransaction(msg *Message, config *params.ChainConfig, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM, resultFilter func(*ExecutionResult) error) (*types.Receipt, *ExecutionResult, error) { 100 // Create a new context to be used in the EVM environment. 101 txContext := NewEVMTxContext(msg) 102 evm.Reset(txContext, statedb) 103 104 // Apply the transaction to the current state (included in the env). 105 result, err := ApplyMessage(evm, msg, gp) 106 if err != nil { 107 return nil, nil, err 108 } 109 110 if resultFilter != nil { 111 err = resultFilter(result) 112 if err != nil { 113 return nil, nil, err 114 } 115 } 116 117 // Update the state with pending changes. 118 var root []byte 119 if config.IsByzantium(blockNumber) { 120 statedb.Finalise(true) 121 } else { 122 root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes() 123 } 124 *usedGas += result.UsedGas 125 126 // Create a new receipt for the transaction, storing the intermediate root and gas used 127 // by the tx. 128 receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas} 129 if result.Failed() { 130 receipt.Status = types.ReceiptStatusFailed 131 } else { 132 receipt.Status = types.ReceiptStatusSuccessful 133 } 134 receipt.TxHash = tx.Hash() 135 receipt.GasUsed = result.UsedGas 136 137 // If the transaction created a contract, store the creation address in the receipt. 138 if result.TopLevelDeployed != nil { 139 receipt.ContractAddress = *result.TopLevelDeployed 140 } 141 142 // Set the receipt logs and create the bloom filter. 143 receipt.Logs = statedb.GetLogs(tx.Hash(), blockNumber.Uint64(), blockHash) 144 receipt.Bloom = types.CreateBloom(types.Receipts{receipt}) 145 receipt.BlockHash = blockHash 146 receipt.BlockNumber = blockNumber 147 receipt.TransactionIndex = uint(statedb.TxIndex()) 148 evm.ProcessingHook.FillReceiptInfo(receipt) 149 return receipt, result, err 150 } 151 152 // ApplyTransaction attempts to apply a transaction to the given state database 153 // and uses the input parameters for its environment. It returns the receipt 154 // for the transaction, gas used and an error if the transaction failed, 155 // indicating the block was invalid. 156 func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, *ExecutionResult, error) { 157 return ApplyTransactionWithResultFilter(config, bc, author, gp, statedb, header, tx, usedGas, cfg, nil) 158 } 159 160 func ApplyTransactionWithResultFilter(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config, resultFilter func(*ExecutionResult) error) (*types.Receipt, *ExecutionResult, error) { 161 msg, err := TransactionToMessage(tx, types.MakeSigner(config, header.Number), header.BaseFee) 162 if err != nil { 163 return nil, nil, err 164 } 165 // Create a new context to be used in the EVM environment 166 blockContext := NewEVMBlockContext(header, bc, author) 167 vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg) 168 return applyTransaction(msg, config, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv, resultFilter) 169 }