github.com/core-coin/go-core/v2@v2.1.9/core/state_processor.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/core-coin/go-core/v2/common"
    23  	"github.com/core-coin/go-core/v2/consensus"
    24  	"github.com/core-coin/go-core/v2/core/state"
    25  	"github.com/core-coin/go-core/v2/core/types"
    26  	"github.com/core-coin/go-core/v2/core/vm"
    27  	"github.com/core-coin/go-core/v2/crypto"
    28  	"github.com/core-coin/go-core/v2/params"
    29  )
    30  
    31  // StateProcessor is a basic Processor, which takes care of transitioning
    32  // state from one point to another.
    33  //
    34  // StateProcessor implements Processor.
    35  type StateProcessor struct {
    36  	config *params.ChainConfig // Chain configuration options
    37  	bc     *BlockChain         // Canonical block chain
    38  	engine consensus.Engine    // Consensus engine used for block rewards
    39  }
    40  
    41  // NewStateProcessor initialises a new StateProcessor.
    42  func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
    43  	return &StateProcessor{
    44  		config: config,
    45  		bc:     bc,
    46  		engine: engine,
    47  	}
    48  }
    49  
    50  // Process processes the state changes according to the Core rules by running
    51  // the transaction messages using the statedb and applying any rewards to both
    52  // the processor (coinbase) and any included uncles.
    53  //
    54  // Process returns the receipts and logs accumulated during the process and
    55  // returns the amount of energy that was used in the process. If any of the
    56  // transactions failed to execute due to insufficient energy it will return an error.
    57  func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
    58  	var (
    59  		receipts   types.Receipts
    60  		usedEnergy = new(uint64)
    61  		header     = block.Header()
    62  		allLogs    []*types.Log
    63  		gp         = new(EnergyPool).AddEnergy(block.EnergyLimit())
    64  	)
    65  	blockContext := NewCVMBlockContext(header, p.bc, nil)
    66  	vmenv := vm.NewCVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
    67  	// Iterate over and process the individual transactions
    68  	for i, tx := range block.Transactions() {
    69  		msg, err := tx.AsMessage(types.MakeSigner(p.config.NetworkID))
    70  		if err != nil {
    71  			return nil, nil, 0, err
    72  		}
    73  		statedb.Prepare(tx.Hash(), block.Hash(), i)
    74  		receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedEnergy, vmenv)
    75  		if err != nil {
    76  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    77  		}
    78  		receipts = append(receipts, receipt)
    79  		allLogs = append(allLogs, receipt.Logs...)
    80  	}
    81  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
    82  	p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
    83  
    84  	return receipts, allLogs, *usedEnergy, nil
    85  }
    86  
    87  func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *EnergyPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedEnergy *uint64, cvm *vm.CVM) (*types.Receipt, error) {
    88  	// Create a new context to be used in the CVM environment
    89  	txContext := NewCVMTxContext(msg)
    90  
    91  	// Update the cvm with the new transaction context.
    92  	cvm.Reset(txContext, statedb)
    93  	// Apply the transaction to the current state (included in the env)
    94  	result, err := ApplyMessage(cvm, msg, gp)
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  	// Update the state with pending changes
    99  	var root []byte
   100  	statedb.Finalise(true)
   101  	*usedEnergy += result.UsedEnergy
   102  
   103  	// Create a new receipt for the transaction, storing the intermediate root and energy used by the tx
   104  	// based on the cip phase, we're passing whether the root touch-delete accounts.
   105  	receipt := types.NewReceipt(root, result.Failed(), *usedEnergy)
   106  	receipt.TxHash = tx.Hash()
   107  	receipt.EnergyUsed = result.UsedEnergy
   108  	// if the transaction created a contract, store the creation address in the receipt.
   109  	if msg.To() == nil {
   110  		receipt.ContractAddress = crypto.CreateAddress(cvm.TxContext.Origin, tx.Nonce())
   111  	}
   112  	// Set the receipt logs and create a bloom for filtering
   113  	receipt.Logs = statedb.GetLogs(tx.Hash())
   114  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   115  	receipt.BlockHash = statedb.BlockHash()
   116  	receipt.BlockNumber = header.Number
   117  	receipt.TransactionIndex = uint(statedb.TxIndex())
   118  
   119  	return receipt, err
   120  }
   121  
   122  // ApplyTransaction attempts to apply a transaction to the given state database
   123  // and uses the input parameters for its environment. It returns the receipt
   124  // for the transaction, energy used and an error if the transaction failed,
   125  // indicating the block was invalid.
   126  func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *EnergyPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedEnergy *uint64, cfg vm.Config) (*types.Receipt, error) {
   127  	msg, err := tx.AsMessage(types.MakeSigner(config.NetworkID))
   128  	if err != nil {
   129  		return nil, err
   130  	}
   131  	// Create a new context to be used in the CVM environment
   132  	blockContext := NewCVMBlockContext(header, bc, author)
   133  	vmenv := vm.NewCVM(blockContext, vm.TxContext{}, statedb, config, cfg)
   134  	return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedEnergy, vmenv)
   135  }