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