github.com/MetalBlockchain/subnet-evm@v0.4.9/core/state_processor.go (about)

     1  // (c) 2019-2021, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package core
    28  
    29  import (
    30  	"fmt"
    31  	"math/big"
    32  
    33  	"github.com/MetalBlockchain/subnet-evm/consensus"
    34  	"github.com/MetalBlockchain/subnet-evm/core/state"
    35  	"github.com/MetalBlockchain/subnet-evm/core/types"
    36  	"github.com/MetalBlockchain/subnet-evm/core/vm"
    37  	"github.com/MetalBlockchain/subnet-evm/params"
    38  	"github.com/ethereum/go-ethereum/common"
    39  	"github.com/ethereum/go-ethereum/crypto"
    40  )
    41  
    42  // StateProcessor is a basic Processor, which takes care of transitioning
    43  // state from one point to another.
    44  //
    45  // StateProcessor implements Processor.
    46  type StateProcessor struct {
    47  	config *params.ChainConfig // Chain configuration options
    48  	bc     *BlockChain         // Canonical block chain
    49  	engine consensus.Engine    // Consensus engine used for block rewards
    50  }
    51  
    52  // NewStateProcessor initialises a new StateProcessor.
    53  func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
    54  	return &StateProcessor{
    55  		config: config,
    56  		bc:     bc,
    57  		engine: engine,
    58  	}
    59  }
    60  
    61  // Process processes the state changes according to the Ethereum rules by running
    62  // the transaction messages using the statedb and applying any rewards to both
    63  // the processor (coinbase) and any included uncles.
    64  //
    65  // Process returns the receipts and logs accumulated during the process and
    66  // returns the amount of gas that was used in the process. If any of the
    67  // transactions failed to execute due to insufficient gas it will return an error.
    68  func (p *StateProcessor) Process(block *types.Block, parent *types.Header, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
    69  	var (
    70  		receipts    types.Receipts
    71  		usedGas     = new(uint64)
    72  		header      = block.Header()
    73  		blockHash   = block.Hash()
    74  		blockNumber = block.Number()
    75  		allLogs     []*types.Log
    76  		gp          = new(GasPool).AddGas(block.GasLimit())
    77  		timestamp   = new(big.Int).SetUint64(header.Time)
    78  	)
    79  
    80  	// Configure any stateful precompiles that should go into effect during this block.
    81  	p.config.CheckConfigurePrecompiles(new(big.Int).SetUint64(parent.Time), block, statedb)
    82  
    83  	blockContext := NewEVMBlockContext(header, p.bc, nil)
    84  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
    85  	// Iterate over and process the individual transactions
    86  	for i, tx := range block.Transactions() {
    87  		msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number, timestamp), header.BaseFee)
    88  		if err != nil {
    89  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    90  		}
    91  		statedb.Prepare(tx.Hash(), i)
    92  		receipt, err := applyTransaction(msg, p.config, nil, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
    93  		if err != nil {
    94  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    95  		}
    96  		receipts = append(receipts, receipt)
    97  		allLogs = append(allLogs, receipt.Logs...)
    98  	}
    99  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
   100  	if err := p.engine.Finalize(p.bc, block, parent, statedb, receipts); err != nil {
   101  		return nil, nil, 0, fmt.Errorf("engine finalization check failed: %w", err)
   102  	}
   103  
   104  	return receipts, allLogs, *usedGas, nil
   105  }
   106  
   107  func applyTransaction(msg types.Message, config *params.ChainConfig, 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) {
   108  	// Create a new context to be used in the EVM environment.
   109  	txContext := NewEVMTxContext(msg)
   110  	evm.Reset(txContext, statedb)
   111  
   112  	// Apply the transaction to the current state (included in the env).
   113  	result, err := ApplyMessage(evm, msg, gp)
   114  	if err != nil {
   115  		return nil, err
   116  	}
   117  
   118  	// Update the state with pending changes.
   119  	var root []byte
   120  	if config.IsByzantium(blockNumber) {
   121  		statedb.Finalise(true)
   122  	} else {
   123  		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
   124  	}
   125  	*usedGas += result.UsedGas
   126  
   127  	// Create a new receipt for the transaction, storing the intermediate root and gas used
   128  	// by the tx.
   129  	receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
   130  	if result.Failed() {
   131  		receipt.Status = types.ReceiptStatusFailed
   132  	} else {
   133  		receipt.Status = types.ReceiptStatusSuccessful
   134  	}
   135  	receipt.TxHash = tx.Hash()
   136  	receipt.GasUsed = result.UsedGas
   137  
   138  	// If the transaction created a contract, store the creation address in the receipt.
   139  	if msg.To() == nil {
   140  		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   141  	}
   142  
   143  	// Set the receipt logs and create the bloom filter.
   144  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
   145  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   146  	receipt.BlockHash = blockHash
   147  	receipt.BlockNumber = blockNumber
   148  	receipt.TransactionIndex = uint(statedb.TxIndex())
   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, new(big.Int).SetUint64(header.Time)), 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, author)
   163  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
   164  	return applyTransaction(msg, config, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   165  }