github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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/scroll-tech/go-ethereum/common"
    24  	"github.com/scroll-tech/go-ethereum/consensus"
    25  	"github.com/scroll-tech/go-ethereum/consensus/misc"
    26  	"github.com/scroll-tech/go-ethereum/core/state"
    27  	"github.com/scroll-tech/go-ethereum/core/types"
    28  	"github.com/scroll-tech/go-ethereum/core/vm"
    29  	"github.com/scroll-tech/go-ethereum/crypto"
    30  	"github.com/scroll-tech/go-ethereum/params"
    31  	"github.com/scroll-tech/go-ethereum/rollup/fees"
    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  	// Mutate the block and state according to any hard-fork specs
    71  	if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
    72  		misc.ApplyDAOHardFork(statedb)
    73  	}
    74  	blockContext := NewEVMBlockContext(header, p.bc, p.config, nil)
    75  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
    76  	// Iterate over and process the individual transactions
    77  	for i, tx := range block.Transactions() {
    78  		msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number), header.BaseFee)
    79  		if err != nil {
    80  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    81  		}
    82  		statedb.Prepare(tx.Hash(), i)
    83  		receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
    84  		if err != nil {
    85  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    86  		}
    87  		receipts = append(receipts, receipt)
    88  		allLogs = append(allLogs, receipt.Logs...)
    89  	}
    90  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
    91  	p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
    92  
    93  	return receipts, allLogs, *usedGas, nil
    94  }
    95  
    96  func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
    97  	// Create a new context to be used in the EVM environment.
    98  	txContext := NewEVMTxContext(msg)
    99  	evm.Reset(txContext, statedb)
   100  
   101  	l1DataFee, err := fees.CalculateL1DataFee(tx, statedb)
   102  	if err != nil {
   103  		return nil, err
   104  	}
   105  
   106  	// Apply the transaction to the current state (included in the env).
   107  	result, err := ApplyMessage(evm, msg, gp, l1DataFee)
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  
   112  	// Update the state with pending changes.
   113  	var root []byte
   114  	if config.IsByzantium(blockNumber) {
   115  		statedb.Finalise(true)
   116  	} else {
   117  		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
   118  	}
   119  	*usedGas += result.UsedGas
   120  
   121  	// If the result contains a revert reason, return it.
   122  	returnVal := result.Return()
   123  	if len(result.Revert()) > 0 {
   124  		returnVal = result.Revert()
   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, ReturnValue: returnVal}
   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 msg.To() == nil {
   139  		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   140  	}
   141  
   142  	// Set the receipt logs and create the bloom filter.
   143  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
   144  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   145  	receipt.BlockHash = blockHash
   146  	receipt.BlockNumber = blockNumber
   147  	receipt.TransactionIndex = uint(statedb.TxIndex())
   148  	receipt.L1Fee = result.L1DataFee
   149  	return receipt, 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, error) {
   157  	msg, err := tx.AsMessage(types.MakeSigner(config, header.Number), header.BaseFee)
   158  	if err != nil {
   159  		return nil, err
   160  	}
   161  	// Create a new context to be used in the EVM environment
   162  	blockContext := NewEVMBlockContext(header, bc, config, author)
   163  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
   164  	return applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   165  }