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