github.com/dominant-strategies/go-quai@v0.28.2/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/dominant-strategies/go-quai/common"
    23  	"github.com/dominant-strategies/go-quai/consensus"
    24  	"github.com/dominant-strategies/go-quai/core/types"
    25  	"github.com/dominant-strategies/go-quai/core/vm"
    26  	"github.com/dominant-strategies/go-quai/log"
    27  	"github.com/dominant-strategies/go-quai/params"
    28  )
    29  
    30  // ChainContext supports retrieving headers and consensus parameters from the
    31  // current blockchain to be used during transaction processing.
    32  type ChainContext interface {
    33  	// Engine retrieves the chain's consensus engine.
    34  	Engine() consensus.Engine
    35  
    36  	// GetHeader returns the hash corresponding to their hash.
    37  	GetHeader(common.Hash, uint64) *types.Header
    38  }
    39  
    40  // NewEVMBlockContext creates a new context for use in the EVM.
    41  func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
    42  	var (
    43  		beneficiary common.Address
    44  		baseFee     *big.Int
    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  
    57  	timestamp := header.Time() // base case, should only be the case in genesis block or before forkBlock (in testnet)
    58  	if header.Number().Uint64() != 0 && header.Number().Uint64() > params.CarbonForkBlockNumber {
    59  		parent := chain.GetHeader(header.ParentHash(), header.Number().Uint64()-1)
    60  		if parent != nil {
    61  			timestamp = parent.Time()
    62  		} else {
    63  			log.Fatal("Parent is nil, panic", "headerHash", header.Hash(), "parentHash", header.ParentHash(), "number", header.Number().Uint64())
    64  		}
    65  	}
    66  
    67  	return vm.BlockContext{
    68  		CanTransfer: CanTransfer,
    69  		Transfer:    Transfer,
    70  		GetHash:     GetHashFn(header, chain),
    71  		Coinbase:    beneficiary,
    72  		BlockNumber: new(big.Int).Set(header.Number()),
    73  		Time:        new(big.Int).SetUint64(timestamp),
    74  		Difficulty:  new(big.Int).Set(header.Difficulty()),
    75  		BaseFee:     baseFee,
    76  		GasLimit:    header.GasLimit(),
    77  	}
    78  }
    79  
    80  // NewEVMTxContext creates a new transaction context for a single transaction.
    81  func NewEVMTxContext(msg Message) vm.TxContext {
    82  	return vm.TxContext{
    83  		Origin:        msg.From(),
    84  		GasPrice:      new(big.Int).Set(msg.GasPrice()),
    85  		ETXSender:     msg.ETXSender(),
    86  		TxType:        msg.Type(),
    87  		ETXGasLimit:   msg.ETXGasLimit(),
    88  		ETXGasPrice:   msg.ETXGasPrice(),
    89  		ETXGasTip:     msg.ETXGasTip(),
    90  		TXGasTip:      msg.GasTipCap(),
    91  		ETXData:       msg.ETXData(),
    92  		ETXAccessList: msg.ETXAccessList(),
    93  	}
    94  }
    95  
    96  // GetHashFn returns a GetHashFunc which retrieves header hashes by number
    97  func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
    98  	// Cache will initially contain [refHash.parent],
    99  	// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
   100  	var cache []common.Hash
   101  
   102  	return func(n uint64) common.Hash {
   103  		// If there's no hash cache yet, make one
   104  		if len(cache) == 0 {
   105  			cache = append(cache, ref.ParentHash())
   106  		}
   107  		if idx := ref.Number().Uint64() - n - 1; idx < uint64(len(cache)) {
   108  			return cache[idx]
   109  		}
   110  		// No luck in the cache, but we can start iterating from the last element we already know
   111  		lastKnownHash := cache[len(cache)-1]
   112  		lastKnownNumber := ref.Number().Uint64() - uint64(len(cache))
   113  
   114  		for {
   115  			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
   116  			if header == nil {
   117  				break
   118  			}
   119  			cache = append(cache, header.ParentHash())
   120  			lastKnownHash = header.ParentHash()
   121  			lastKnownNumber = header.Number().Uint64() - 1
   122  			if n == lastKnownNumber {
   123  				return lastKnownHash
   124  			}
   125  		}
   126  		return common.Hash{}
   127  	}
   128  }
   129  
   130  // CanTransfer checks whether there are enough funds in the address' account to make a transfer.
   131  // This does not take the necessary gas in to account to make the transfer valid.
   132  func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
   133  	internalAddr, err := addr.InternalAddress()
   134  	if err != nil {
   135  		return false
   136  	}
   137  	return db.GetBalance(internalAddr).Cmp(amount) >= 0
   138  }
   139  
   140  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   141  func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) error {
   142  	internalSender, err := sender.InternalAddress()
   143  	if err != nil {
   144  		return err
   145  	}
   146  	internalRecipient, err := recipient.InternalAddress()
   147  	if err != nil {
   148  		return err
   149  	}
   150  	db.SubBalance(internalSender, amount)
   151  	db.AddBalance(internalRecipient, amount)
   152  	return nil
   153  }