github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/core/vm/evm.go (about)

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