github.com/luckypickle/go-ethereum-vet@v1.14.2/core/vm/evm.go (about)

     1  // Copyright 2014 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 vm
    18  
    19  import (
    20  	"math/big"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/luckypickle/go-ethereum-vet/common"
    25  	"github.com/luckypickle/go-ethereum-vet/crypto"
    26  	"github.com/luckypickle/go-ethereum-vet/params"
    27  )
    28  
    29  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    30  // deployed contract addresses (relevant after the account abstraction).
    31  var emptyCodeHash = crypto.Keccak256Hash(nil)
    32  
    33  type (
    34  	// CanTransferFunc is the signature of a transfer guard function
    35  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    36  	// TransferFunc is the signature of a transfer function
    37  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    38  	// GetHashFunc returns the nth block hash in the blockchain
    39  	// and is used by the BLOCKHASH EVM op code.
    40  	GetHashFunc func(uint64) common.Hash
    41  )
    42  
    43  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    44  func run(evm *EVM, contract *Contract, input []byte) ([]byte, error) {
    45  	if contract.CodeAddr != nil {
    46  		precompiles := PrecompiledContractsHomestead
    47  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
    48  			precompiles = PrecompiledContractsByzantium
    49  		}
    50  		if p := precompiles[*contract.CodeAddr]; p != nil {
    51  			return RunPrecompiledContract(p, input, contract)
    52  		}
    53  	}
    54  	for _, interpreter := range evm.interpreters {
    55  		if interpreter.CanRun(contract.Code) {
    56  			if evm.interpreter != interpreter {
    57  				// Ensure that the interpreter pointer is set back
    58  				// to its current value upon return.
    59  				defer func(i Interpreter) {
    60  					evm.interpreter = i
    61  				}(evm.interpreter)
    62  				evm.interpreter = interpreter
    63  			}
    64  			return interpreter.Run(contract, input)
    65  		}
    66  	}
    67  	return nil, ErrNoCompatibleInterpreter
    68  }
    69  
    70  // Context provides the EVM with auxiliary information. Once provided
    71  // it shouldn't be modified.
    72  type Context struct {
    73  	// CanTransfer returns whether the account contains
    74  	// sufficient ether to transfer the value
    75  	CanTransfer CanTransferFunc
    76  	// Transfer transfers ether from one account to the other
    77  	Transfer TransferFunc
    78  	// GetHash returns the hash corresponding to n
    79  	GetHash GetHashFunc
    80  
    81  	// Message information
    82  	Origin   common.Address // Provides information for ORIGIN
    83  	GasPrice *big.Int       // Provides information for GASPRICE
    84  
    85  	// Block information
    86  	Coinbase    common.Address // Provides information for COINBASE
    87  	GasLimit    uint64         // Provides information for GASLIMIT
    88  	BlockNumber *big.Int       // Provides information for NUMBER
    89  	Time        *big.Int       // Provides information for TIME
    90  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    91  }
    92  
    93  // EVM is the Ethereum Virtual Machine base object and provides
    94  // the necessary tools to run a contract on the given state with
    95  // the provided context. It should be noted that any error
    96  // generated through any of the calls should be considered a
    97  // revert-state-and-consume-all-gas operation, no checks on
    98  // specific errors should ever be performed. The interpreter makes
    99  // sure that any errors generated are to be considered faulty code.
   100  //
   101  // The EVM should never be reused and is not thread safe.
   102  type EVM struct {
   103  	// Context provides auxiliary blockchain related information
   104  	Context
   105  	// StateDB gives access to the underlying state
   106  	StateDB StateDB
   107  	// Depth is the current call stack
   108  	depth int
   109  
   110  	// chainConfig contains information about the current chain
   111  	chainConfig *params.ChainConfig
   112  	// chain rules contains the chain rules for the current epoch
   113  	chainRules params.Rules
   114  	// virtual machine configuration options used to initialise the
   115  	// evm.
   116  	vmConfig Config
   117  	// global (to this context) ethereum virtual machine
   118  	// used throughout the execution of the tx.
   119  	interpreters []Interpreter
   120  	interpreter  Interpreter
   121  	// abort is used to abort the EVM calling operations
   122  	// NOTE: must be set atomically
   123  	abort int32
   124  	// callGasTemp holds the gas available for the current call. This is needed because the
   125  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   126  	// applied in opCall*.
   127  	callGasTemp uint64
   128  }
   129  
   130  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   131  // only ever be used *once*.
   132  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   133  	evm := &EVM{
   134  		Context:      ctx,
   135  		StateDB:      statedb,
   136  		vmConfig:     vmConfig,
   137  		chainConfig:  chainConfig,
   138  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   139  		interpreters: make([]Interpreter, 1),
   140  	}
   141  
   142  	evm.interpreters[0] = NewEVMInterpreter(evm, vmConfig)
   143  	evm.interpreter = evm.interpreters[0]
   144  
   145  	return evm
   146  }
   147  
   148  // Cancel cancels any running EVM operation. This may be called concurrently and
   149  // it's safe to be called multiple times.
   150  func (evm *EVM) Cancel() {
   151  	atomic.StoreInt32(&evm.abort, 1)
   152  }
   153  
   154  // Interpreter returns the current interpreter
   155  func (evm *EVM) Interpreter() Interpreter {
   156  	return evm.interpreter
   157  }
   158  
   159  // Call executes the contract associated with the addr with the given input as
   160  // parameters. It also handles any necessary value transfer required and takes
   161  // the necessary steps to create accounts and reverses the state in case of an
   162  // execution error or failed value transfer.
   163  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   164  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   165  		return nil, gas, nil
   166  	}
   167  
   168  	// Fail if we're trying to execute above the call depth limit
   169  	if evm.depth > int(params.CallCreateDepth) {
   170  		return nil, gas, ErrDepth
   171  	}
   172  	// Fail if we're trying to transfer more than the available balance
   173  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   174  		return nil, gas, ErrInsufficientBalance
   175  	}
   176  
   177  	var (
   178  		to       = AccountRef(addr)
   179  		snapshot = evm.StateDB.Snapshot()
   180  	)
   181  	if !evm.StateDB.Exist(addr) {
   182  		precompiles := PrecompiledContractsHomestead
   183  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   184  			precompiles = PrecompiledContractsByzantium
   185  		}
   186  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   187  			// Calling a non existing account, don't do anything, but ping the tracer
   188  			if evm.vmConfig.Debug && evm.depth == 0 {
   189  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   190  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   191  			}
   192  			return nil, gas, nil
   193  		}
   194  		evm.StateDB.CreateAccount(addr)
   195  	}
   196  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   197  
   198  	// Initialise a new contract and set the code that is to be used by the EVM.
   199  	// The contract is a scoped environment for this execution context only.
   200  	contract := NewContract(caller, to, value, gas)
   201  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   202  
   203  	start := time.Now()
   204  
   205  	// Capture the tracer start/end events in debug mode
   206  	if evm.vmConfig.Debug && evm.depth == 0 {
   207  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   208  
   209  		defer func() { // Lazy evaluation of the parameters
   210  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   211  		}()
   212  	}
   213  	ret, err = run(evm, contract, input)
   214  
   215  	// When an error was returned by the EVM or when setting the creation code
   216  	// above we revert to the snapshot and consume any gas remaining. Additionally
   217  	// when we're in homestead this also counts for code storage gas errors.
   218  	if err != nil {
   219  		evm.StateDB.RevertToSnapshot(snapshot)
   220  		if err != errExecutionReverted {
   221  			contract.UseGas(contract.Gas)
   222  		}
   223  	}
   224  	return ret, contract.Gas, err
   225  }
   226  
   227  // CallCode executes the contract associated with the addr with the given input
   228  // as parameters. It also handles any necessary value transfer required and takes
   229  // the necessary steps to create accounts and reverses the state in case of an
   230  // execution error or failed value transfer.
   231  //
   232  // CallCode differs from Call in the sense that it executes the given address'
   233  // code with the caller as context.
   234  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   235  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   236  		return nil, gas, nil
   237  	}
   238  
   239  	// Fail if we're trying to execute above the call depth limit
   240  	if evm.depth > int(params.CallCreateDepth) {
   241  		return nil, gas, ErrDepth
   242  	}
   243  	// Fail if we're trying to transfer more than the available balance
   244  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   245  		return nil, gas, ErrInsufficientBalance
   246  	}
   247  
   248  	var (
   249  		snapshot = evm.StateDB.Snapshot()
   250  		to       = AccountRef(caller.Address())
   251  	)
   252  	// initialise a new contract and set the code that is to be used by the
   253  	// EVM. The contract is a scoped environment for this execution context
   254  	// only.
   255  	contract := NewContract(caller, to, value, gas)
   256  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   257  
   258  	ret, err = run(evm, contract, input)
   259  	if err != nil {
   260  		evm.StateDB.RevertToSnapshot(snapshot)
   261  		if err != errExecutionReverted {
   262  			contract.UseGas(contract.Gas)
   263  		}
   264  	}
   265  	return ret, contract.Gas, err
   266  }
   267  
   268  // DelegateCall executes the contract associated with the addr with the given input
   269  // as parameters. It reverses the state in case of an execution error.
   270  //
   271  // DelegateCall differs from CallCode in the sense that it executes the given address'
   272  // code with the caller as context and the caller is set to the caller of the caller.
   273  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   274  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   275  		return nil, gas, nil
   276  	}
   277  	// Fail if we're trying to execute above the call depth limit
   278  	if evm.depth > int(params.CallCreateDepth) {
   279  		return nil, gas, ErrDepth
   280  	}
   281  
   282  	var (
   283  		snapshot = evm.StateDB.Snapshot()
   284  		to       = AccountRef(caller.Address())
   285  	)
   286  
   287  	// Initialise a new contract and make initialise the delegate values
   288  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   289  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   290  
   291  	ret, err = run(evm, contract, input)
   292  	if err != nil {
   293  		evm.StateDB.RevertToSnapshot(snapshot)
   294  		if err != errExecutionReverted {
   295  			contract.UseGas(contract.Gas)
   296  		}
   297  	}
   298  	return ret, contract.Gas, err
   299  }
   300  
   301  // StaticCall executes the contract associated with the addr with the given input
   302  // as parameters while disallowing any modifications to the state during the call.
   303  // Opcodes that attempt to perform such modifications will result in exceptions
   304  // instead of performing the modifications.
   305  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   306  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   307  		return nil, gas, nil
   308  	}
   309  	// Fail if we're trying to execute above the call depth limit
   310  	if evm.depth > int(params.CallCreateDepth) {
   311  		return nil, gas, ErrDepth
   312  	}
   313  	// Make sure the readonly is only set if we aren't in readonly yet
   314  	// this makes also sure that the readonly flag isn't removed for
   315  	// child calls.
   316  	if !evm.interpreter.IsReadOnly() {
   317  		evm.interpreter.SetReadOnly(true)
   318  		defer func() { evm.interpreter.SetReadOnly(false) }()
   319  	}
   320  
   321  	var (
   322  		to       = AccountRef(addr)
   323  		snapshot = evm.StateDB.Snapshot()
   324  	)
   325  	// Initialise a new contract and set the code that is to be used by the
   326  	// EVM. The contract is a scoped environment for this execution context
   327  	// only.
   328  	contract := NewContract(caller, to, new(big.Int), gas)
   329  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   330  
   331  	// When an error was returned by the EVM or when setting the creation code
   332  	// above we revert to the snapshot and consume any gas remaining. Additionally
   333  	// when we're in Homestead this also counts for code storage gas errors.
   334  	ret, err = run(evm, contract, input)
   335  	if err != nil {
   336  		evm.StateDB.RevertToSnapshot(snapshot)
   337  		if err != errExecutionReverted {
   338  			contract.UseGas(contract.Gas)
   339  		}
   340  	}
   341  	return ret, contract.Gas, err
   342  }
   343  
   344  // create creates a new contract using code as deployment code.
   345  func (evm *EVM) create(caller ContractRef, code []byte, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   346  	// Depth check execution. Fail if we're trying to execute above the
   347  	// limit.
   348  	if evm.depth > int(params.CallCreateDepth) {
   349  		return nil, common.Address{}, gas, ErrDepth
   350  	}
   351  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   352  		return nil, common.Address{}, gas, ErrInsufficientBalance
   353  	}
   354  	nonce := evm.StateDB.GetNonce(caller.Address())
   355  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   356  
   357  	// Ensure there's no existing contract already at the designated address
   358  	contractHash := evm.StateDB.GetCodeHash(address)
   359  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   360  		return nil, common.Address{}, 0, ErrContractAddressCollision
   361  	}
   362  	// Create a new account on the state
   363  	snapshot := evm.StateDB.Snapshot()
   364  	evm.StateDB.CreateAccount(address)
   365  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   366  		evm.StateDB.SetNonce(address, 1)
   367  	}
   368  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   369  
   370  	// initialise a new contract and set the code that is to be used by the
   371  	// EVM. The contract is a scoped environment for this execution context
   372  	// only.
   373  	contract := NewContract(caller, AccountRef(address), value, gas)
   374  	contract.SetCallCode(&address, crypto.Keccak256Hash(code), code)
   375  
   376  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   377  		return nil, address, gas, nil
   378  	}
   379  
   380  	if evm.vmConfig.Debug && evm.depth == 0 {
   381  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, code, gas, value)
   382  	}
   383  	start := time.Now()
   384  
   385  	ret, err := run(evm, contract, nil)
   386  
   387  	// check whether the max code size has been exceeded
   388  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   389  	// if the contract creation ran successfully and no errors were returned
   390  	// calculate the gas required to store the code. If the code could not
   391  	// be stored due to not enough gas set an error and let it be handled
   392  	// by the error checking condition below.
   393  	if err == nil && !maxCodeSizeExceeded {
   394  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   395  		if contract.UseGas(createDataGas) {
   396  			evm.StateDB.SetCode(address, ret)
   397  		} else {
   398  			err = ErrCodeStoreOutOfGas
   399  		}
   400  	}
   401  
   402  	// When an error was returned by the EVM or when setting the creation code
   403  	// above we revert to the snapshot and consume any gas remaining. Additionally
   404  	// when we're in homestead this also counts for code storage gas errors.
   405  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   406  		evm.StateDB.RevertToSnapshot(snapshot)
   407  		if err != errExecutionReverted {
   408  			contract.UseGas(contract.Gas)
   409  		}
   410  	}
   411  	// Assign err if contract code size exceeds the max while the err is still empty.
   412  	if maxCodeSizeExceeded && err == nil {
   413  		err = errMaxCodeSizeExceeded
   414  	}
   415  	if evm.vmConfig.Debug && evm.depth == 0 {
   416  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   417  	}
   418  	return ret, address, contract.Gas, err
   419  
   420  }
   421  
   422  // Create creates a new contract using code as deployment code.
   423  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   424  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   425  	return evm.create(caller, code, gas, value, contractAddr)
   426  }
   427  
   428  // Create2 creates a new contract using code as deployment code.
   429  //
   430  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   431  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   432  func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   433  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), code)
   434  	return evm.create(caller, code, gas, endowment, contractAddr)
   435  }
   436  
   437  // ChainConfig returns the environment's chain configuration
   438  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }