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