github.com/theQRL/go-zond@v0.1.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  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  
    24  	"github.com/theQRL/go-zond/common"
    25  	"github.com/theQRL/go-zond/consensus"
    26  	"github.com/theQRL/go-zond/consensus/misc"
    27  	"github.com/theQRL/go-zond/consensus/misc/eip4844"
    28  	"github.com/theQRL/go-zond/core/state"
    29  	"github.com/theQRL/go-zond/core/types"
    30  	"github.com/theQRL/go-zond/core/vm"
    31  	"github.com/theQRL/go-zond/crypto"
    32  	"github.com/theQRL/go-zond/params"
    33  )
    34  
    35  // StateProcessor is a basic Processor, which takes care of transitioning
    36  // state from one point to another.
    37  //
    38  // StateProcessor implements Processor.
    39  type StateProcessor struct {
    40  	config *params.ChainConfig // Chain configuration options
    41  	bc     *BlockChain         // Canonical block chain
    42  	engine consensus.Engine    // Consensus engine used for block rewards
    43  }
    44  
    45  // NewStateProcessor initialises a new StateProcessor.
    46  func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
    47  	return &StateProcessor{
    48  		config: config,
    49  		bc:     bc,
    50  		engine: engine,
    51  	}
    52  }
    53  
    54  // Process processes the state changes according to the Ethereum rules by running
    55  // the transaction messages using the statedb and applying any rewards to both
    56  // the processor (coinbase) and any included uncles.
    57  //
    58  // Process returns the receipts and logs accumulated during the process and
    59  // returns the amount of gas that was used in the process. If any of the
    60  // transactions failed to execute due to insufficient gas it will return an error.
    61  func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
    62  	var (
    63  		receipts    types.Receipts
    64  		usedGas     = new(uint64)
    65  		header      = block.Header()
    66  		blockHash   = block.Hash()
    67  		blockNumber = block.Number()
    68  		allLogs     []*types.Log
    69  		gp          = new(GasPool).AddGas(block.GasLimit())
    70  	)
    71  	// Mutate the block and state according to any hard-fork specs
    72  	if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
    73  		misc.ApplyDAOHardFork(statedb)
    74  	}
    75  	var (
    76  		context = NewEVMBlockContext(header, p.bc, nil)
    77  		vmenv   = vm.NewEVM(context, vm.TxContext{}, statedb, p.config, cfg)
    78  		signer  = types.MakeSigner(p.config, header.Number, header.Time)
    79  	)
    80  	if beaconRoot := block.BeaconRoot(); beaconRoot != nil {
    81  		ProcessBeaconBlockRoot(*beaconRoot, vmenv, statedb)
    82  	}
    83  	// Iterate over and process the individual transactions
    84  	for i, tx := range block.Transactions() {
    85  		msg, err := TransactionToMessage(tx, signer, header.BaseFee)
    86  		if err != nil {
    87  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    88  		}
    89  		statedb.SetTxContext(tx.Hash(), i)
    90  		receipt, err := applyTransaction(msg, p.config, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
    91  		if err != nil {
    92  			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
    93  		}
    94  		receipts = append(receipts, receipt)
    95  		allLogs = append(allLogs, receipt.Logs...)
    96  	}
    97  	// Fail if Shanghai not enabled and len(withdrawals) is non-zero.
    98  	withdrawals := block.Withdrawals()
    99  	if len(withdrawals) > 0 && !p.config.IsShanghai(block.Number(), block.Time()) {
   100  		return nil, nil, 0, errors.New("withdrawals before shanghai")
   101  	}
   102  	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
   103  	p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles(), withdrawals)
   104  
   105  	return receipts, allLogs, *usedGas, nil
   106  }
   107  
   108  func applyTransaction(msg *Message, config *params.ChainConfig, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
   109  	// Create a new context to be used in the EVM environment.
   110  	txContext := NewEVMTxContext(msg)
   111  	evm.Reset(txContext, statedb)
   112  
   113  	// Apply the transaction to the current state (included in the env).
   114  	result, err := ApplyMessage(evm, msg, gp)
   115  	if err != nil {
   116  		return nil, err
   117  	}
   118  
   119  	// Update the state with pending changes.
   120  	var root []byte
   121  	if config.IsByzantium(blockNumber) {
   122  		statedb.Finalise(true)
   123  	} else {
   124  		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
   125  	}
   126  	*usedGas += result.UsedGas
   127  
   128  	// Create a new receipt for the transaction, storing the intermediate root and gas used
   129  	// by the tx.
   130  	receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
   131  	if result.Failed() {
   132  		receipt.Status = types.ReceiptStatusFailed
   133  	} else {
   134  		receipt.Status = types.ReceiptStatusSuccessful
   135  	}
   136  	receipt.TxHash = tx.Hash()
   137  	receipt.GasUsed = result.UsedGas
   138  
   139  	if tx.Type() == types.BlobTxType {
   140  		receipt.BlobGasUsed = uint64(len(tx.BlobHashes()) * params.BlobTxBlobGasPerBlob)
   141  		receipt.BlobGasPrice = eip4844.CalcBlobFee(*evm.Context.ExcessBlobGas)
   142  	}
   143  
   144  	// If the transaction created a contract, store the creation address in the receipt.
   145  	if msg.To == nil {
   146  		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   147  	}
   148  
   149  	// Set the receipt logs and create the bloom filter.
   150  	receipt.Logs = statedb.GetLogs(tx.Hash(), blockNumber.Uint64(), blockHash)
   151  	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   152  	receipt.BlockHash = blockHash
   153  	receipt.BlockNumber = blockNumber
   154  	receipt.TransactionIndex = uint(statedb.TxIndex())
   155  	return receipt, err
   156  }
   157  
   158  // ApplyTransaction attempts to apply a transaction to the given state database
   159  // and uses the input parameters for its environment. It returns the receipt
   160  // for the transaction, gas used and an error if the transaction failed,
   161  // indicating the block was invalid.
   162  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) {
   163  	msg, err := TransactionToMessage(tx, types.MakeSigner(config, header.Number, header.Time), header.BaseFee)
   164  	if err != nil {
   165  		return nil, err
   166  	}
   167  	// Create a new context to be used in the EVM environment
   168  	blockContext := NewEVMBlockContext(header, bc, author)
   169  	vmenv := vm.NewEVM(blockContext, vm.TxContext{BlobHashes: tx.BlobHashes()}, statedb, config, cfg)
   170  	return applyTransaction(msg, config, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
   171  }
   172  
   173  // ProcessBeaconBlockRoot applies the EIP-4788 system call to the beacon block root
   174  // contract. This method is exported to be used in tests.
   175  func ProcessBeaconBlockRoot(beaconRoot common.Hash, vmenv *vm.EVM, statedb *state.StateDB) {
   176  	// If EIP-4788 is enabled, we need to invoke the beaconroot storage contract with
   177  	// the new root
   178  	msg := &Message{
   179  		From:      params.SystemAddress,
   180  		GasLimit:  30_000_000,
   181  		GasPrice:  common.Big0,
   182  		GasFeeCap: common.Big0,
   183  		GasTipCap: common.Big0,
   184  		To:        &params.BeaconRootsStorageAddress,
   185  		Data:      beaconRoot[:],
   186  	}
   187  	vmenv.Reset(NewEVMTxContext(msg), statedb)
   188  	statedb.AddAddressToAccessList(params.BeaconRootsStorageAddress)
   189  	_, _, _ = vmenv.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.Big0)
   190  	statedb.Finalise(true)
   191  }