github.com/theQRL/go-zond@v0.2.1/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/theQRL/go-zond/common"
    24  	"github.com/theQRL/go-zond/consensus"
    25  	"github.com/theQRL/go-zond/core/state"
    26  	"github.com/theQRL/go-zond/core/types"
    27  	"github.com/theQRL/go-zond/core/vm"
    28  	"github.com/theQRL/go-zond/crypto"
    29  	"github.com/theQRL/go-zond/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 the
    53  // processor (coinbase).
    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  	var (
    69  		context = NewZVMBlockContext(header, p.bc, nil)
    70  		vmenv   = vm.NewZVM(context, vm.TxContext{}, statedb, p.config, cfg)
    71  		signer  = types.MakeSigner(p.config)
    72  	)
    73  
    74  	// Iterate over and process the individual transactions
    75  	for i, tx := range block.Transactions() {
    76  		msg, err := TransactionToMessage(tx, signer, header.BaseFee)
    77  		if err != nil {
    78  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    79  		}
    80  		statedb.SetTxContext(tx.Hash(), i)
    81  		receipt, err := applyTransaction(msg, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
    82  		if err != nil {
    83  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    84  		}
    85  		receipts = append(receipts, receipt)
    86  		allLogs = append(allLogs, receipt.Logs...)
    87  	}
    88  
    89  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
    90  	p.engine.Finalize(p.bc, header, statedb, block.Body())
    91  
    92  	return receipts, allLogs, *usedGas, nil
    93  }
    94  
    95  func applyTransaction(msg *Message, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, zvm *vm.ZVM) (*types.Receipt, error) {
    96  	// Create a new context to be used in the ZVM environment.
    97  	txContext := NewZVMTxContext(msg)
    98  	zvm.Reset(txContext, statedb)
    99  
   100  	// Apply the transaction to the current state (included in the env).
   101  	result, err := ApplyMessage(zvm, msg, gp)
   102  	if err != nil {
   103  		return nil, err
   104  	}
   105  
   106  	// Update the state with pending changes.
   107  	var root []byte
   108  	statedb.Finalise(true)
   109  	*usedGas += result.UsedGas
   110  
   111  	// Create a new receipt for the transaction, storing the intermediate root and gas used
   112  	// by the tx.
   113  	receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
   114  	if result.Failed() {
   115  		receipt.Status = types.ReceiptStatusFailed
   116  	} else {
   117  		receipt.Status = types.ReceiptStatusSuccessful
   118  	}
   119  	receipt.TxHash = tx.Hash()
   120  	receipt.GasUsed = result.UsedGas
   121  
   122  	// If the transaction created a contract, store the creation address in the receipt.
   123  	if msg.To == nil {
   124  		receipt.ContractAddress = crypto.CreateAddress(zvm.TxContext.Origin, tx.Nonce())
   125  	}
   126  
   127  	// Set the receipt logs and create the bloom filter.
   128  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockNumber.Uint64(), blockHash)
   129  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   130  	receipt.BlockHash = blockHash
   131  	receipt.BlockNumber = blockNumber
   132  	receipt.TransactionIndex = uint(statedb.TxIndex())
   133  	return receipt, err
   134  }
   135  
   136  // ApplyTransaction attempts to apply a transaction to the given state database
   137  // and uses the input parameters for its environment. It returns the receipt
   138  // for the transaction, gas used and an error if the transaction failed,
   139  // indicating the block was invalid.
   140  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) {
   141  	msg, err := TransactionToMessage(tx, types.MakeSigner(config), header.BaseFee)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  	// Create a new context to be used in the ZVM environment
   146  	blockContext := NewZVMBlockContext(header, bc, author)
   147  	vmenv := vm.NewZVM(blockContext, vm.TxContext{}, statedb, config, cfg)
   148  	return applyTransaction(msg, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   149  }