github.com/dim4egster/coreth@v0.10.2/core/evm.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2016 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package core
    28  
    29  import (
    30  	"math/big"
    31  
    32  	"github.com/dim4egster/coreth/consensus"
    33  	"github.com/dim4egster/coreth/core/types"
    34  	"github.com/dim4egster/coreth/core/vm"
    35  	"github.com/ethereum/go-ethereum/common"
    36  	//"github.com/ethereum/go-ethereum/log"
    37  )
    38  
    39  // ChainContext supports retrieving headers and consensus parameters from the
    40  // current blockchain to be used during transaction processing.
    41  type ChainContext interface {
    42  	// Engine retrieves the chain's consensus engine.
    43  	Engine() consensus.Engine
    44  
    45  	// GetHeader returns the header corresponding to the hash/number argument pair.
    46  	GetHeader(common.Hash, uint64) *types.Header
    47  }
    48  
    49  // NewEVMBlockContext creates a new context for use in the EVM.
    50  func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
    51  	var (
    52  		beneficiary common.Address
    53  		baseFee     *big.Int
    54  	)
    55  
    56  	// If we don't have an explicit author (i.e. not mining), extract from the header
    57  	if author == nil {
    58  		beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
    59  	} else {
    60  		beneficiary = *author
    61  	}
    62  	if header.BaseFee != nil {
    63  		baseFee = new(big.Int).Set(header.BaseFee)
    64  	}
    65  	return vm.BlockContext{
    66  		CanTransfer:       CanTransfer,
    67  		CanTransferMC:     CanTransferMC,
    68  		Transfer:          Transfer,
    69  		TransferMultiCoin: TransferMultiCoin,
    70  		GetHash:           GetHashFn(header, chain),
    71  		Coinbase:          beneficiary,
    72  		BlockNumber:       new(big.Int).Set(header.Number),
    73  		Time:              new(big.Int).SetUint64(header.Time),
    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  	}
    86  }
    87  
    88  // GetHashFn returns a GetHashFunc which retrieves header hashes by number
    89  func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
    90  	// Cache will initially contain [refHash.parent],
    91  	// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
    92  	var cache []common.Hash
    93  
    94  	return func(n uint64) common.Hash {
    95  		if ref.Number.Uint64() <= n {
    96  			// This situation can happen if we're doing tracing and using
    97  			// block overrides.
    98  			return common.Hash{}
    99  		}
   100  		// If there's no hash cache yet, make one
   101  		if len(cache) == 0 {
   102  			cache = append(cache, ref.ParentHash)
   103  		}
   104  		if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
   105  			return cache[idx]
   106  		}
   107  		// No luck in the cache, but we can start iterating from the last element we already know
   108  		lastKnownHash := cache[len(cache)-1]
   109  		lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
   110  
   111  		for {
   112  			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
   113  			if header == nil {
   114  				break
   115  			}
   116  			cache = append(cache, header.ParentHash)
   117  			lastKnownHash = header.ParentHash
   118  			lastKnownNumber = header.Number.Uint64() - 1
   119  			if n == lastKnownNumber {
   120  				return lastKnownHash
   121  			}
   122  		}
   123  		return common.Hash{}
   124  	}
   125  }
   126  
   127  // CanTransfer checks whether there are enough funds in the address' account to make a transfer.
   128  // This does not take the necessary gas in to account to make the transfer valid.
   129  func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
   130  	return db.GetBalance(addr).Cmp(amount) >= 0
   131  }
   132  
   133  func CanTransferMC(db vm.StateDB, addr common.Address, to common.Address, coinID common.Hash, amount *big.Int) bool {
   134  	return db.GetBalanceMultiCoin(addr, coinID).Cmp(amount) >= 0
   135  }
   136  
   137  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   138  func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
   139  	db.SubBalance(sender, amount)
   140  	db.AddBalance(recipient, amount)
   141  }
   142  
   143  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   144  func TransferMultiCoin(db vm.StateDB, sender, recipient common.Address, coinID common.Hash, amount *big.Int) {
   145  	db.SubBalanceMultiCoin(sender, coinID, amount)
   146  	db.AddBalanceMultiCoin(recipient, coinID, amount)
   147  }