github.com/ccm-chain/ccmchain@v1.0.0/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  	"errors"
    21  	"math/big"
    22  	"sync/atomic"
    23  	"time"
    24  
    25  	"github.com/ccm-chain/ccmchain/common"
    26  	"github.com/ccm-chain/ccmchain/crypto"
    27  	"github.com/ccm-chain/ccmchain/params"
    28  	"github.com/holiman/uint256"
    29  )
    30  
    31  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    32  // deployed contract addresses (relevant after the account abstraction).
    33  var emptyCodeHash = crypto.Keccak256Hash(nil)
    34  
    35  type (
    36  	// CanTransferFunc is the signature of a transfer guard function
    37  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    38  	// TransferFunc is the signature of a transfer function
    39  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    40  	// GetHashFunc returns the n'th block hash in the blockchain
    41  	// and is used by the BLOCKHASH EVM op code.
    42  	GetHashFunc func(uint64) common.Hash
    43  )
    44  
    45  func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) {
    46  	var precompiles map[common.Address]PrecompiledContract
    47  	switch {
    48  	case evm.chainRules.IsByzantium:
    49  		precompiles = PrecompiledContractsByzantium
    50  	default:
    51  		precompiles = PrecompiledContractsHomestead
    52  	}
    53  	p, ok := precompiles[addr]
    54  	return p, ok
    55  }
    56  
    57  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    58  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
    59  	for _, interpreter := range evm.interpreters {
    60  		if interpreter.CanRun(contract.Code) {
    61  			if evm.interpreter != interpreter {
    62  				// Ensure that the interpreter pointer is set back
    63  				// to its current value upon return.
    64  				defer func(i Interpreter) {
    65  					evm.interpreter = i
    66  				}(evm.interpreter)
    67  				evm.interpreter = interpreter
    68  			}
    69  			return interpreter.Run(contract, input, readOnly)
    70  		}
    71  	}
    72  	return nil, errors.New("no compatible interpreter")
    73  }
    74  
    75  // Context provides the EVM with auxiliary information. Once provided
    76  // it shouldn't be modified.
    77  type Context struct {
    78  	// CanTransfer returns whether the account contains
    79  	// sufficient ether to transfer the value
    80  	CanTransfer CanTransferFunc
    81  	// Transfer transfers ether from one account to the other
    82  	Transfer TransferFunc
    83  	// GetHash returns the hash corresponding to n
    84  	GetHash GetHashFunc
    85  
    86  	// Message information
    87  	Origin   common.Address // Provides information for ORIGIN
    88  	GasPrice *big.Int       // Provides information for GASPRICE
    89  
    90  	// Block information
    91  	Coinbase    common.Address // Provides information for COINBASE
    92  	GasLimit    uint64         // Provides information for GASLIMIT
    93  	BlockNumber *big.Int       // Provides information for NUMBER
    94  	Time        *big.Int       // Provides information for TIME
    95  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    96  }
    97  
    98  // EVM is the Ethereum Virtual Machine base object and provides
    99  // the necessary tools to run a contract on the given state with
   100  // the provided context. It should be noted that any error
   101  // generated through any of the calls should be considered a
   102  // revert-state-and-consume-all-gas operation, no checks on
   103  // specific errors should ever be performed. The interpreter makes
   104  // sure that any errors generated are to be considered faulty code.
   105  //
   106  // The EVM should never be reused and is not thread safe.
   107  type EVM struct {
   108  	// Context provides auxiliary blockchain related information
   109  	Context
   110  	// StateDB gives access to the underlying state
   111  	StateDB StateDB
   112  	// Depth is the current call stack
   113  	depth int
   114  
   115  	// chainConfig contains information about the current chain
   116  	chainConfig *params.ChainConfig
   117  	// chain rules contains the chain rules for the current epoch
   118  	chainRules params.Rules
   119  	// virtual machine configuration options used to initialise the
   120  	// evm.
   121  	vmConfig Config
   122  	// global (to this context) ethereum virtual machine
   123  	// used throughout the execution of the tx.
   124  	interpreters []Interpreter
   125  	interpreter  Interpreter
   126  	// abort is used to abort the EVM calling operations
   127  	// NOTE: must be set atomically
   128  	abort int32
   129  	// callGasTemp holds the gas available for the current call. This is needed because the
   130  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   131  	// applied in opCall*.
   132  	callGasTemp uint64
   133  }
   134  
   135  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   136  // only ever be used *once*.
   137  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   138  	evm := &EVM{
   139  		Context:      ctx,
   140  		StateDB:      statedb,
   141  		vmConfig:     vmConfig,
   142  		chainConfig:  chainConfig,
   143  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   144  		interpreters: make([]Interpreter, 0, 1),
   145  	}
   146  
   147  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   148  		// to be implemented by EVM-C and Wagon PRs.
   149  		// if vmConfig.EWASMInterpreter != "" {
   150  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   151  		//  path := extIntOpts[0]
   152  		//  options := []string{}
   153  		//  if len(extIntOpts) > 1 {
   154  		//    options = extIntOpts[1..]
   155  		//  }
   156  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   157  		// } else {
   158  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   159  		// }
   160  		panic("No supported ewasm interpreter yet.")
   161  	}
   162  
   163  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   164  	// as we always want to have the built-in EVM as the failover option.
   165  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   166  	evm.interpreter = evm.interpreters[0]
   167  
   168  	return evm
   169  }
   170  
   171  // Cancel cancels any running EVM operation. This may be called concurrently and
   172  // it's safe to be called multiple times.
   173  func (evm *EVM) Cancel() {
   174  	atomic.StoreInt32(&evm.abort, 1)
   175  }
   176  
   177  // Cancelled returns true if Cancel has been called
   178  func (evm *EVM) Cancelled() bool {
   179  	return atomic.LoadInt32(&evm.abort) == 1
   180  }
   181  
   182  // Interpreter returns the current interpreter
   183  func (evm *EVM) Interpreter() Interpreter {
   184  	return evm.interpreter
   185  }
   186  
   187  // Call executes the contract associated with the addr with the given input as
   188  // parameters. It also handles any necessary value transfer required and takes
   189  // the necessary steps to create accounts and reverses the state in case of an
   190  // execution error or failed value transfer.
   191  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   192  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   193  		return nil, gas, nil
   194  	}
   195  	// Fail if we're trying to execute above the call depth limit
   196  	if evm.depth > int(params.CallCreateDepth) {
   197  		return nil, gas, ErrDepth
   198  	}
   199  	// Fail if we're trying to transfer more than the available balance
   200  	if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   201  		return nil, gas, ErrInsufficientBalance
   202  	}
   203  	snapshot := evm.StateDB.Snapshot()
   204  	p, isPrecompile := evm.precompile(addr)
   205  
   206  	if !evm.StateDB.Exist(addr) {
   207  		if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   208  			// Calling a non existing account, don't do anything, but ping the tracer
   209  			if evm.vmConfig.Debug && evm.depth == 0 {
   210  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   211  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   212  			}
   213  			return nil, gas, nil
   214  		}
   215  		evm.StateDB.CreateAccount(addr)
   216  	}
   217  	evm.Transfer(evm.StateDB, caller.Address(), addr, value)
   218  
   219  	// Capture the tracer start/end events in debug mode
   220  	if evm.vmConfig.Debug && evm.depth == 0 {
   221  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   222  		defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters
   223  			evm.vmConfig.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err)
   224  		}(gas, time.Now())
   225  	}
   226  
   227  	if isPrecompile {
   228  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   229  	} else {
   230  		// Initialise a new contract and set the code that is to be used by the EVM.
   231  		// The contract is a scoped environment for this execution context only.
   232  		code := evm.StateDB.GetCode(addr)
   233  		if len(code) == 0 {
   234  			ret, err = nil, nil // gas is unchanged
   235  		} else {
   236  			addrCopy := addr
   237  			// If the account has no code, we can abort here
   238  			// The depth-check is already done, and precompiles handled above
   239  			contract := NewContract(caller, AccountRef(addrCopy), value, gas)
   240  			contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code)
   241  			ret, err = run(evm, contract, input, false)
   242  			gas = contract.Gas
   243  		}
   244  	}
   245  	// When an error was returned by the EVM or when setting the creation code
   246  	// above we revert to the snapshot and consume any gas remaining. Additionally
   247  	// when we're in homestead this also counts for code storage gas errors.
   248  	if err != nil {
   249  		evm.StateDB.RevertToSnapshot(snapshot)
   250  		if err != ErrExecutionReverted {
   251  			gas = 0
   252  		}
   253  		// TODO: consider clearing up unused snapshots:
   254  		//} else {
   255  		//	evm.StateDB.DiscardSnapshot(snapshot)
   256  	}
   257  	return ret, gas, err
   258  }
   259  
   260  // CallCode executes the contract associated with the addr with the given input
   261  // as parameters. It also handles any necessary value transfer required and takes
   262  // the necessary steps to create accounts and reverses the state in case of an
   263  // execution error or failed value transfer.
   264  //
   265  // CallCode differs from Call in the sense that it executes the given address'
   266  // code with the caller as context.
   267  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   268  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   269  		return nil, gas, nil
   270  	}
   271  	// Fail if we're trying to execute above the call depth limit
   272  	if evm.depth > int(params.CallCreateDepth) {
   273  		return nil, gas, ErrDepth
   274  	}
   275  	// Fail if we're trying to transfer more than the available balance
   276  	// Note although it's noop to transfer X ether to caller itself. But
   277  	// if caller doesn't have enough balance, it would be an error to allow
   278  	// over-charging itself. So the check here is necessary.
   279  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   280  		return nil, gas, ErrInsufficientBalance
   281  	}
   282  	var snapshot = evm.StateDB.Snapshot()
   283  
   284  	// It is allowed to call precompiles, even via delegatecall
   285  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   286  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   287  	} else {
   288  		addrCopy := addr
   289  		// Initialise a new contract and set the code that is to be used by the EVM.
   290  		// The contract is a scoped environment for this execution context only.
   291  		contract := NewContract(caller, AccountRef(caller.Address()), value, gas)
   292  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   293  		ret, err = run(evm, contract, input, false)
   294  		gas = contract.Gas
   295  	}
   296  	if err != nil {
   297  		evm.StateDB.RevertToSnapshot(snapshot)
   298  		if err != ErrExecutionReverted {
   299  			gas = 0
   300  		}
   301  	}
   302  	return ret, gas, err
   303  }
   304  
   305  // DelegateCall executes the contract associated with the addr with the given input
   306  // as parameters. It reverses the state in case of an execution error.
   307  //
   308  // DelegateCall differs from CallCode in the sense that it executes the given address'
   309  // code with the caller as context and the caller is set to the caller of the caller.
   310  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   311  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   312  		return nil, gas, nil
   313  	}
   314  	// Fail if we're trying to execute above the call depth limit
   315  	if evm.depth > int(params.CallCreateDepth) {
   316  		return nil, gas, ErrDepth
   317  	}
   318  	var snapshot = evm.StateDB.Snapshot()
   319  
   320  	// It is allowed to call precompiles, even via delegatecall
   321  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   322  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   323  	} else {
   324  		addrCopy := addr
   325  		// Initialise a new contract and make initialise the delegate values
   326  		contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate()
   327  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   328  		ret, err = run(evm, contract, input, false)
   329  		gas = contract.Gas
   330  	}
   331  	if err != nil {
   332  		evm.StateDB.RevertToSnapshot(snapshot)
   333  		if err != ErrExecutionReverted {
   334  			gas = 0
   335  		}
   336  	}
   337  	return ret, gas, err
   338  }
   339  
   340  // StaticCall executes the contract associated with the addr with the given input
   341  // as parameters while disallowing any modifications to the state during the call.
   342  // Opcodes that attempt to perform such modifications will result in exceptions
   343  // instead of performing the modifications.
   344  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   345  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   346  		return nil, gas, nil
   347  	}
   348  	// Fail if we're trying to execute above the call depth limit
   349  	if evm.depth > int(params.CallCreateDepth) {
   350  		return nil, gas, ErrDepth
   351  	}
   352  	// We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped.
   353  	// However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced
   354  	// after all empty accounts were deleted, so this is not required. However, if we omit this,
   355  	// then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json.
   356  	// We could change this, but for now it's left for legacy reasons
   357  	var snapshot = evm.StateDB.Snapshot()
   358  
   359  	// We do an AddBalance of zero here, just in order to trigger a touch.
   360  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   361  	// but is the correct thing to do and matters on other networks, in tests, and potential
   362  	// future scenarios
   363  	evm.StateDB.AddBalance(addr, big0)
   364  
   365  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   366  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   367  	} else {
   368  		// At this point, we use a copy of address. If we don't, the go compiler will
   369  		// leak the 'contract' to the outer scope, and make allocation for 'contract'
   370  		// even if the actual execution ends on RunPrecompiled above.
   371  		addrCopy := addr
   372  		// Initialise a new contract and set the code that is to be used by the EVM.
   373  		// The contract is a scoped environment for this execution context only.
   374  		contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas)
   375  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   376  		// When an error was returned by the EVM or when setting the creation code
   377  		// above we revert to the snapshot and consume any gas remaining. Additionally
   378  		// when we're in Homestead this also counts for code storage gas errors.
   379  		ret, err = run(evm, contract, input, true)
   380  		gas = contract.Gas
   381  	}
   382  	if err != nil {
   383  		evm.StateDB.RevertToSnapshot(snapshot)
   384  		if err != ErrExecutionReverted {
   385  			gas = 0
   386  		}
   387  	}
   388  	return ret, gas, err
   389  }
   390  
   391  type codeAndHash struct {
   392  	code []byte
   393  	hash common.Hash
   394  }
   395  
   396  func (c *codeAndHash) Hash() common.Hash {
   397  	if c.hash == (common.Hash{}) {
   398  		c.hash = crypto.Keccak256Hash(c.code)
   399  	}
   400  	return c.hash
   401  }
   402  
   403  // create creates a new contract using code as deployment code.
   404  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   405  	// Depth check execution. Fail if we're trying to execute above the
   406  	// limit.
   407  	if evm.depth > int(params.CallCreateDepth) {
   408  		return nil, common.Address{}, gas, ErrDepth
   409  	}
   410  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   411  		return nil, common.Address{}, gas, ErrInsufficientBalance
   412  	}
   413  	nonce := evm.StateDB.GetNonce(caller.Address())
   414  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   415  
   416  	// Ensure there's no existing contract already at the designated address
   417  	contractHash := evm.StateDB.GetCodeHash(address)
   418  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   419  		return nil, common.Address{}, 0, ErrContractAddressCollision
   420  	}
   421  	// Create a new account on the state
   422  	snapshot := evm.StateDB.Snapshot()
   423  	evm.StateDB.CreateAccount(address)
   424  	if evm.chainRules.IsEIP158 {
   425  		evm.StateDB.SetNonce(address, 1)
   426  	}
   427  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   428  
   429  	// Initialise a new contract and set the code that is to be used by the EVM.
   430  	// The contract is a scoped environment for this execution context only.
   431  	contract := NewContract(caller, AccountRef(address), value, gas)
   432  	contract.SetCodeOptionalHash(&address, codeAndHash)
   433  
   434  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   435  		return nil, address, gas, nil
   436  	}
   437  
   438  	if evm.vmConfig.Debug && evm.depth == 0 {
   439  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   440  	}
   441  	start := time.Now()
   442  
   443  	ret, err := run(evm, contract, nil, false)
   444  
   445  	// check whether the max code size has been exceeded
   446  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize
   447  	// if the contract creation ran successfully and no errors were returned
   448  	// calculate the gas required to store the code. If the code could not
   449  	// be stored due to not enough gas set an error and let it be handled
   450  	// by the error checking condition below.
   451  	if err == nil && !maxCodeSizeExceeded {
   452  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   453  		if contract.UseGas(createDataGas) {
   454  			evm.StateDB.SetCode(address, ret)
   455  		} else {
   456  			err = ErrCodeStoreOutOfGas
   457  		}
   458  	}
   459  
   460  	// When an error was returned by the EVM or when setting the creation code
   461  	// above we revert to the snapshot and consume any gas remaining. Additionally
   462  	// when we're in homestead this also counts for code storage gas errors.
   463  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   464  		evm.StateDB.RevertToSnapshot(snapshot)
   465  		if err != ErrExecutionReverted {
   466  			contract.UseGas(contract.Gas)
   467  		}
   468  	}
   469  	// Assign err if contract code size exceeds the max while the err is still empty.
   470  	if maxCodeSizeExceeded && err == nil {
   471  		err = ErrMaxCodeSizeExceeded
   472  	}
   473  	if evm.vmConfig.Debug && evm.depth == 0 {
   474  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   475  	}
   476  	return ret, address, contract.Gas, err
   477  
   478  }
   479  
   480  // Create creates a new contract using code as deployment code.
   481  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   482  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   483  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   484  }
   485  
   486  // Create2 creates a new contract using code as deployment code.
   487  //
   488  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   489  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   490  func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   491  	codeAndHash := &codeAndHash{code: code}
   492  	contractAddr = crypto.CreateAddress2(caller.Address(), common.Hash(salt.Bytes32()), codeAndHash.Hash().Bytes())
   493  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   494  }
   495  
   496  // ChainConfig returns the environment's chain configuration
   497  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }