github.com/ethereum/go-ethereum@v1.16.1/core/evm.go (about)

     1  // Copyright 2016 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  	"math/big"
    21  
    22  	"github.com/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/consensus"
    24  	"github.com/ethereum/go-ethereum/consensus/misc/eip4844"
    25  	"github.com/ethereum/go-ethereum/core/tracing"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/core/vm"
    28  	"github.com/ethereum/go-ethereum/params"
    29  	"github.com/holiman/uint256"
    30  )
    31  
    32  // ChainContext supports retrieving headers and consensus parameters from the
    33  // current blockchain to be used during transaction processing.
    34  type ChainContext interface {
    35  	// Engine retrieves the chain's consensus engine.
    36  	Engine() consensus.Engine
    37  
    38  	// GetHeader returns the header corresponding to the hash/number argument pair.
    39  	GetHeader(common.Hash, uint64) *types.Header
    40  
    41  	// Config returns the chain's configuration.
    42  	Config() *params.ChainConfig
    43  }
    44  
    45  // NewEVMBlockContext creates a new context for use in the EVM.
    46  func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
    47  	var (
    48  		beneficiary common.Address
    49  		baseFee     *big.Int
    50  		blobBaseFee *big.Int
    51  		random      *common.Hash
    52  	)
    53  
    54  	// If we don't have an explicit author (i.e. not mining), extract from the header
    55  	if author == nil {
    56  		beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
    57  	} else {
    58  		beneficiary = *author
    59  	}
    60  	if header.BaseFee != nil {
    61  		baseFee = new(big.Int).Set(header.BaseFee)
    62  	}
    63  	if header.ExcessBlobGas != nil {
    64  		blobBaseFee = eip4844.CalcBlobFee(chain.Config(), header)
    65  	}
    66  	if header.Difficulty.Sign() == 0 {
    67  		random = &header.MixDigest
    68  	}
    69  	return vm.BlockContext{
    70  		CanTransfer: CanTransfer,
    71  		Transfer:    Transfer,
    72  		GetHash:     GetHashFn(header, chain),
    73  		Coinbase:    beneficiary,
    74  		BlockNumber: new(big.Int).Set(header.Number),
    75  		Time:        header.Time,
    76  		Difficulty:  new(big.Int).Set(header.Difficulty),
    77  		BaseFee:     baseFee,
    78  		BlobBaseFee: blobBaseFee,
    79  		GasLimit:    header.GasLimit,
    80  		Random:      random,
    81  	}
    82  }
    83  
    84  // NewEVMTxContext creates a new transaction context for a single transaction.
    85  func NewEVMTxContext(msg *Message) vm.TxContext {
    86  	ctx := vm.TxContext{
    87  		Origin:     msg.From,
    88  		GasPrice:   new(big.Int).Set(msg.GasPrice),
    89  		BlobHashes: msg.BlobHashes,
    90  	}
    91  	if msg.BlobGasFeeCap != nil {
    92  		ctx.BlobFeeCap = new(big.Int).Set(msg.BlobGasFeeCap)
    93  	}
    94  	return ctx
    95  }
    96  
    97  // GetHashFn returns a GetHashFunc which retrieves header hashes by number
    98  func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
    99  	// Cache will initially contain [refHash.parent],
   100  	// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
   101  	var cache []common.Hash
   102  
   103  	return func(n uint64) common.Hash {
   104  		if ref.Number.Uint64() <= n {
   105  			// This situation can happen if we're doing tracing and using
   106  			// block overrides.
   107  			return common.Hash{}
   108  		}
   109  		// If there's no hash cache yet, make one
   110  		if len(cache) == 0 {
   111  			cache = append(cache, ref.ParentHash)
   112  		}
   113  		if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
   114  			return cache[idx]
   115  		}
   116  		// No luck in the cache, but we can start iterating from the last element we already know
   117  		lastKnownHash := cache[len(cache)-1]
   118  		lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
   119  
   120  		for {
   121  			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
   122  			if header == nil {
   123  				break
   124  			}
   125  			cache = append(cache, header.ParentHash)
   126  			lastKnownHash = header.ParentHash
   127  			lastKnownNumber = header.Number.Uint64() - 1
   128  			if n == lastKnownNumber {
   129  				return lastKnownHash
   130  			}
   131  		}
   132  		return common.Hash{}
   133  	}
   134  }
   135  
   136  // CanTransfer checks whether there are enough funds in the address' account to make a transfer.
   137  // This does not take the necessary gas in to account to make the transfer valid.
   138  func CanTransfer(db vm.StateDB, addr common.Address, amount *uint256.Int) bool {
   139  	return db.GetBalance(addr).Cmp(amount) >= 0
   140  }
   141  
   142  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   143  func Transfer(db vm.StateDB, sender, recipient common.Address, amount *uint256.Int) {
   144  	db.SubBalance(sender, amount, tracing.BalanceChangeTransfer)
   145  	db.AddBalance(recipient, amount, tracing.BalanceChangeTransfer)
   146  }