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