github.com/klaytn/klaytn@v1.10.2/blockchain/evm.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2016 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from core/evm.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package blockchain
    22  
    23  import (
    24  	"math/big"
    25  
    26  	"github.com/klaytn/klaytn/blockchain/types"
    27  	"github.com/klaytn/klaytn/blockchain/vm"
    28  	"github.com/klaytn/klaytn/common"
    29  	"github.com/klaytn/klaytn/consensus"
    30  	"github.com/klaytn/klaytn/params"
    31  )
    32  
    33  // ChainContext supports retrieving headers and consensus parameters from the
    34  // current blockchain to be used during transaction processing.
    35  type ChainContext interface {
    36  	// Engine retrieves the chain's consensus engine.
    37  	Engine() consensus.Engine
    38  
    39  	// GetHeader returns the hash corresponding to their hash.
    40  	GetHeader(common.Hash, uint64) *types.Header
    41  }
    42  
    43  // NewEVMContext creates a new context for use in the EVM.
    44  func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author *common.Address) vm.Context {
    45  	// If we don't have an explicit author (i.e. not mining), extract from the header
    46  	var (
    47  		beneficiary       common.Address
    48  		baseFee           *big.Int
    49  		effectiveGasPrice *big.Int
    50  	)
    51  
    52  	if author == nil {
    53  		beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
    54  	} else {
    55  		beneficiary = *author
    56  	}
    57  
    58  	if header.BaseFee != nil {
    59  		baseFee = header.BaseFee
    60  		effectiveGasPrice = header.BaseFee
    61  	} else {
    62  		// before magma hardfork, base fee is 0, effectiveGasPrice is unitPrice
    63  		baseFee = new(big.Int).SetUint64(params.ZeroBaseFee)
    64  		effectiveGasPrice = msg.GasPrice()
    65  	}
    66  
    67  	return vm.Context{
    68  		CanTransfer: CanTransfer,
    69  		Transfer:    Transfer,
    70  		GetHash:     GetHashFn(header, chain),
    71  		Origin:      msg.ValidatedSender(),
    72  		Coinbase:    beneficiary,
    73  		BlockNumber: new(big.Int).Set(header.Number),
    74  		Time:        new(big.Int).Set(header.Time),
    75  		BlockScore:  new(big.Int).Set(header.BlockScore),
    76  		GasPrice:    new(big.Int).Set(effectiveGasPrice),
    77  		BaseFee:     baseFee,
    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  	return func(n uint64) common.Hash {
    88  		// If there's no hash cache yet, make one
    89  		if len(cache) == 0 {
    90  			cache = append(cache, ref.ParentHash)
    91  		}
    92  		if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
    93  			return cache[idx]
    94  		}
    95  		// No luck in the cache, but we can start iterating from the last element we already know
    96  		lastKnownHash := cache[len(cache)-1]
    97  
    98  		lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
    99  
   100  		for {
   101  			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
   102  			if header == nil {
   103  				break
   104  			}
   105  			cache = append(cache, header.ParentHash)
   106  			lastKnownHash = header.ParentHash
   107  			lastKnownNumber = header.Number.Uint64() - 1
   108  			if n == lastKnownNumber {
   109  				return lastKnownHash
   110  			}
   111  		}
   112  		return common.Hash{}
   113  	}
   114  }
   115  
   116  // CanTransfer checks whether there are enough funds in the address' account to make a transfer.
   117  // This does not take the necessary gas in to account to make the transfer valid.
   118  func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
   119  	return db.GetBalance(addr).Cmp(amount) >= 0
   120  }
   121  
   122  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   123  func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
   124  	db.SubBalance(sender, amount)
   125  	db.AddBalance(recipient, amount)
   126  }