github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/consensus"
    26  	"github.com/ethereum/go-ethereum/consensus/misc"
    27  	"github.com/ethereum/go-ethereum/core/state"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/core/vm"
    30  	"github.com/ethereum/go-ethereum/crypto"
    31  	"github.com/ethereum/go-ethereum/params"
    32  )
    33  
    34  // StateProcessor is a basic Processor, which takes care of transitioning
    35  // state from one point to another.
    36  //
    37  // StateProcessor implements Processor.
    38  type StateProcessor struct {
    39  	config *params.ChainConfig // Chain configuration options
    40  	bc     *BlockChain         // Canonical block chain
    41  	engine consensus.Engine    // Consensus engine used for block rewards
    42  }
    43  
    44  // NewStateProcessor initialises a new StateProcessor.
    45  func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
    46  	return &StateProcessor{
    47  		config: config,
    48  		bc:     bc,
    49  		engine: engine,
    50  	}
    51  }
    52  
    53  // Process processes the state changes according to the Ethereum rules by running
    54  // the transaction messages using the statedb and applying any rewards to both
    55  // the processor (coinbase) and any included uncles.
    56  //
    57  // Process returns the receipts and logs accumulated during the process and
    58  // returns the amount of gas that was used in the process. If any of the
    59  // transactions failed to execute due to insufficient gas it will return an error.
    60  func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
    61  	var (
    62  		receipts    types.Receipts
    63  		usedGas     = new(uint64)
    64  		header      = block.Header()
    65  		blockHash   = block.Hash()
    66  		blockNumber = block.Number()
    67  		allLogs     []*types.Log
    68  		gp          = new(GasPool).AddGas(block.GasLimit())
    69  	)
    70  
    71  	// Mutate the block and state according to any hard-fork specs
    72  	if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
    73  		misc.ApplyDAOHardFork(statedb)
    74  	}
    75  	var (
    76  		context = NewEVMBlockContext(header, p.bc, nil)
    77  		vmenv   = vm.NewEVM(context, vm.TxContext{}, statedb, p.config, cfg)
    78  		signer  = types.MakeSigner(p.config, header.Number, header.Time)
    79  	)
    80  	if beaconRoot := block.BeaconRoot(); beaconRoot != nil {
    81  		ProcessBeaconBlockRoot(*beaconRoot, vmenv, statedb)
    82  	}
    83  	// Iterate over and process the individual transactions
    84  	for i, tx := range block.Transactions() {
    85  		msg, err := TransactionToMessage(tx, signer, header.BaseFee)
    86  		if err != nil {
    87  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    88  		}
    89  		statedb.SetTxContext(tx.Hash(), i)
    90  
    91  		receipt, err := ApplyTransactionWithEVM(msg, p.config, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
    92  		if err != nil {
    93  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    94  		}
    95  		receipts = append(receipts, receipt)
    96  		allLogs = append(allLogs, receipt.Logs...)
    97  	}
    98  	// Fail if Shanghai not enabled and len(withdrawals) is non-zero.
    99  	withdrawals := block.Withdrawals()
   100  	if len(withdrawals) > 0 && !p.config.IsShanghai(block.Number(), block.Time()) {
   101  		return nil, nil, 0, errors.New("withdrawals before shanghai")
   102  	}
   103  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
   104  	p.engine.Finalize(p.bc, header, statedb, block.Body())
   105  
   106  	return receipts, allLogs, *usedGas, nil
   107  }
   108  
   109  // ApplyTransactionWithEVM attempts to apply a transaction to the given state database
   110  // and uses the input parameters for its environment similar to ApplyTransaction. However,
   111  // this method takes an already created EVM instance as input.
   112  func ApplyTransactionWithEVM(msg *Message, config *params.ChainConfig, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (receipt *types.Receipt, err error) {
   113  	if evm.Config.Tracer != nil && evm.Config.Tracer.OnTxStart != nil {
   114  		evm.Config.Tracer.OnTxStart(evm.GetVMContext(), tx, msg.From)
   115  		if evm.Config.Tracer.OnTxEnd != nil {
   116  			defer func() {
   117  				evm.Config.Tracer.OnTxEnd(receipt, err)
   118  			}()
   119  		}
   120  	}
   121  	// Create a new context to be used in the EVM environment.
   122  	txContext := NewEVMTxContext(msg)
   123  	evm.Reset(txContext, statedb)
   124  
   125  	// Apply the transaction to the current state (included in the env).
   126  	result, err := ApplyMessage(evm, msg, gp)
   127  	if err != nil {
   128  		return nil, err
   129  	}
   130  
   131  	// Update the state with pending changes.
   132  	var root []byte
   133  	if config.IsByzantium(blockNumber) {
   134  		statedb.Finalise(true)
   135  	} else {
   136  		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
   137  	}
   138  	*usedGas += result.UsedGas
   139  
   140  	// Create a new receipt for the transaction, storing the intermediate root and gas used
   141  	// by the tx.
   142  	receipt = &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
   143  	if result.Failed() {
   144  		receipt.Status = types.ReceiptStatusFailed
   145  	} else {
   146  		receipt.Status = types.ReceiptStatusSuccessful
   147  	}
   148  	receipt.TxHash = tx.Hash()
   149  	receipt.GasUsed = result.UsedGas
   150  
   151  	if tx.Type() == types.BlobTxType {
   152  		receipt.BlobGasUsed = uint64(len(tx.BlobHashes()) * params.BlobTxBlobGasPerBlob)
   153  		receipt.BlobGasPrice = evm.Context.BlobBaseFee
   154  	}
   155  
   156  	// If the transaction created a contract, store the creation address in the receipt.
   157  	if msg.To == nil {
   158  		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   159  	}
   160  
   161  	// Set the receipt logs and create the bloom filter.
   162  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockNumber.Uint64(), blockHash)
   163  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   164  	receipt.BlockHash = blockHash
   165  	receipt.BlockNumber = blockNumber
   166  	receipt.TransactionIndex = uint(statedb.TxIndex())
   167  	return receipt, err
   168  }
   169  
   170  // ApplyTransaction attempts to apply a transaction to the given state database
   171  // and uses the input parameters for its environment. It returns the receipt
   172  // for the transaction, gas used and an error if the transaction failed,
   173  // indicating the block was invalid.
   174  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, error) {
   175  	msg, err := TransactionToMessage(tx, types.MakeSigner(config, header.Number, header.Time), header.BaseFee)
   176  	if err != nil {
   177  		return nil, err
   178  	}
   179  	// Create a new context to be used in the EVM environment
   180  	blockContext := NewEVMBlockContext(header, bc, author)
   181  	txContext := NewEVMTxContext(msg)
   182  	vmenv := vm.NewEVM(blockContext, txContext, statedb, config, cfg)
   183  	return ApplyTransactionWithEVM(msg, config, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   184  }
   185  
   186  // ProcessBeaconBlockRoot applies the EIP-4788 system call to the beacon block root
   187  // contract. This method is exported to be used in tests.
   188  func ProcessBeaconBlockRoot(beaconRoot common.Hash, vmenv *vm.EVM, statedb *state.StateDB) {
   189  	if vmenv.Config.Tracer != nil && vmenv.Config.Tracer.OnSystemCallStart != nil {
   190  		vmenv.Config.Tracer.OnSystemCallStart()
   191  	}
   192  	if vmenv.Config.Tracer != nil && vmenv.Config.Tracer.OnSystemCallEnd != nil {
   193  		defer vmenv.Config.Tracer.OnSystemCallEnd()
   194  	}
   195  
   196  	// If EIP-4788 is enabled, we need to invoke the beaconroot storage contract with
   197  	// the new root
   198  	msg := &Message{
   199  		From:      params.SystemAddress,
   200  		GasLimit:  30_000_000,
   201  		GasPrice:  common.Big0,
   202  		GasFeeCap: common.Big0,
   203  		GasTipCap: common.Big0,
   204  		To:        &params.BeaconRootsAddress,
   205  		Data:      beaconRoot[:],
   206  	}
   207  	vmenv.Reset(NewEVMTxContext(msg), statedb)
   208  	statedb.AddAddressToAccessList(params.BeaconRootsAddress)
   209  	_, _, _ = vmenv.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.U2560)
   210  	statedb.Finalise(true)
   211  }