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