gitlab.com/flarenetwork/coreth@v0.1.1/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/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/crypto"
    35  	"gitlab.com/flarenetwork/coreth/consensus"
    36  	"gitlab.com/flarenetwork/coreth/consensus/misc"
    37  	"gitlab.com/flarenetwork/coreth/core/state"
    38  	"gitlab.com/flarenetwork/coreth/core/types"
    39  	"gitlab.com/flarenetwork/coreth/core/vm"
    40  	"gitlab.com/flarenetwork/coreth/params"
    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, 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  	)
    79  	// Mutate the block and state according to any hard-fork specs
    80  	if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
    81  		misc.ApplyDAOHardFork(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, new(big.Int).SetUint64(header.Time)), 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, p.bc, 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  	if err := p.engine.ExtraStateChange(block, statedb); err != nil {
   100  		return nil, nil, 0, err
   101  	}
   102  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
   103  	if err := p.engine.Finalize(p.bc, header, statedb, block.Transactions(), receipts, block.Uncles()); err != nil {
   104  		return nil, nil, 0, fmt.Errorf("engine finalization check failed: %w", err)
   105  	}
   106  
   107  	return receipts, allLogs, *usedGas, nil
   108  }
   109  
   110  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) {
   111  	// Create a new context to be used in the EVM environment.
   112  	txContext := NewEVMTxContext(msg)
   113  	evm.Reset(txContext, statedb)
   114  
   115  	// Apply the transaction to the current state (included in the env).
   116  	result, err := ApplyMessage(evm, msg, gp)
   117  	if err != nil {
   118  		return nil, err
   119  	}
   120  
   121  	// Update the state with pending changes.
   122  	var root []byte
   123  	if config.IsByzantium(blockNumber) {
   124  		statedb.Finalise(true)
   125  	} else {
   126  		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
   127  	}
   128  	*usedGas += result.UsedGas
   129  
   130  	// Create a new receipt for the transaction, storing the intermediate root and gas used
   131  	// by the tx.
   132  	receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
   133  	if result.Failed() {
   134  		receipt.Status = types.ReceiptStatusFailed
   135  	} else {
   136  		receipt.Status = types.ReceiptStatusSuccessful
   137  	}
   138  	receipt.TxHash = tx.Hash()
   139  	receipt.GasUsed = result.UsedGas
   140  
   141  	// If the transaction created a contract, store the creation address in the receipt.
   142  	if msg.To() == nil {
   143  		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   144  	}
   145  
   146  	// Set the receipt logs and create the bloom filter.
   147  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
   148  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   149  	receipt.BlockHash = blockHash
   150  	receipt.BlockNumber = blockNumber
   151  	receipt.TransactionIndex = uint(statedb.TxIndex())
   152  	return receipt, err
   153  }
   154  
   155  // ApplyTransaction attempts to apply a transaction to the given state database
   156  // and uses the input parameters for its environment. It returns the receipt
   157  // for the transaction, gas used and an error if the transaction failed,
   158  // indicating the block was invalid.
   159  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) {
   160  	msg, err := tx.AsMessage(types.MakeSigner(config, header.Number, new(big.Int).SetUint64(header.Time)), header.BaseFee)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  	// Create a new context to be used in the EVM environment
   165  	blockContext := NewEVMBlockContext(header, bc, author)
   166  	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
   167  	return applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   168  }