github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/kisexp/xdchain/common"
    26  	"github.com/kisexp/xdchain/core/state"
    27  	"github.com/kisexp/xdchain/core/types"
    28  	"github.com/kisexp/xdchain/crypto"
    29  	"github.com/kisexp/xdchain/log"
    30  	"github.com/kisexp/xdchain/params"
    31  	"github.com/kisexp/xdchain/trie"
    32  	"github.com/holiman/uint256"
    33  )
    34  
    35  // note: Quorum, States, and Value Transfer
    36  //
    37  // In Quorum there is a tricky issue in one specific case when there is call from private state to public state:
    38  // * The state db is selected based on the callee (public)
    39  // * With every call there is an associated value transfer -- in our case this is 0
    40  // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state
    41  // * However in our scenario the caller is private
    42  // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage
    43  //
    44  // The solution is to skip this transfer of 0 value under Quorum
    45  
    46  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    47  // deployed contract addresses (relevant after the account abstraction).
    48  var emptyCodeHash = crypto.Keccak256Hash(nil)
    49  
    50  type (
    51  	// CanTransferFunc is the signature of a transfer guard function
    52  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    53  	// TransferFunc is the signature of a transfer function
    54  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    55  	// GetHashFunc returns the n'th block hash in the blockchain
    56  	// and is used by the BLOCKHASH EVM op code.
    57  	GetHashFunc func(uint64) common.Hash
    58  )
    59  
    60  // ActivePrecompiles returns the addresses of the precompiles enabled with the current
    61  // configuration
    62  func (evm *EVM) ActivePrecompiles() []common.Address {
    63  	return append(evm.activePrecompiles(), evm.activeQuorumPrecompiles()...)
    64  }
    65  
    66  // (Quorum) moved upstream ActivePrecompiles() logic to new method activePrecompiles()
    67  // This functionality is part of an experimental feature so may be subject to future changes. Keeping the original code
    68  // untouched in a new method should flag any changes from future merges.
    69  func (evm *EVM) activePrecompiles() []common.Address {
    70  	switch {
    71  	case evm.chainRules.IsYoloV2:
    72  		return PrecompiledAddressesYoloV2
    73  	case evm.chainRules.IsIstanbul:
    74  		return PrecompiledAddressesIstanbul
    75  	case evm.chainRules.IsByzantium:
    76  		return PrecompiledAddressesByzantium
    77  	default:
    78  		return PrecompiledAddressesHomestead
    79  	}
    80  }
    81  
    82  func (evm *EVM) activeQuorumPrecompiles() []common.Address {
    83  	var p []common.Address
    84  	if evm.chainRules.IsPrivacyPrecompile {
    85  		p = append(p, common.QuorumPrivacyPrecompileContractAddress())
    86  	}
    87  	return p
    88  }
    89  
    90  func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) {
    91  	var precompiles map[common.Address]PrecompiledContract
    92  	switch {
    93  	case evm.chainRules.IsYoloV2:
    94  		precompiles = PrecompiledContractsYoloV2
    95  	case evm.chainRules.IsIstanbul:
    96  		precompiles = PrecompiledContractsIstanbul
    97  	case evm.chainRules.IsByzantium:
    98  		precompiles = PrecompiledContractsByzantium
    99  	default:
   100  		precompiles = PrecompiledContractsHomestead
   101  	}
   102  	p, ok := precompiles[addr]
   103  	return p, ok
   104  }
   105  
   106  // Quorum
   107  func (evm *EVM) quorumPrecompile(addr common.Address) (QuorumPrecompiledContract, bool) {
   108  	var quorumPrecompiles map[common.Address]QuorumPrecompiledContract
   109  	switch {
   110  	case evm.chainRules.IsPrivacyPrecompile:
   111  		quorumPrecompiles = QuorumPrecompiledContracts
   112  	}
   113  
   114  	p, ok := quorumPrecompiles[addr]
   115  	return p, ok
   116  }
   117  
   118  // End Quorum
   119  
   120  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
   121  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
   122  	// Quorum
   123  	if contract.CodeAddr != nil {
   124  		// Using CodeAddr is favour over contract.Address()
   125  		// During DelegateCall() CodeAddr is the address of the delegated account
   126  		address := *contract.CodeAddr
   127  		if _, ok := evm.affectedContracts[address]; !ok {
   128  			evm.affectedContracts[address] = MessageCall
   129  		}
   130  	}
   131  	// End Quorum
   132  	for _, interpreter := range evm.interpreters {
   133  		if interpreter.CanRun(contract.Code) {
   134  			if evm.interpreter != interpreter {
   135  				// Ensure that the interpreter pointer is set back
   136  				// to its current value upon return.
   137  				defer func(i Interpreter) {
   138  					evm.interpreter = i
   139  				}(evm.interpreter)
   140  				evm.interpreter = interpreter
   141  			}
   142  			return interpreter.Run(contract, input, readOnly)
   143  		}
   144  	}
   145  	return nil, errors.New("no compatible interpreter")
   146  }
   147  
   148  // BlockContext provides the EVM with auxiliary information. Once provided
   149  // it shouldn't be modified.
   150  type BlockContext struct {
   151  	// CanTransfer returns whether the account contains
   152  	// sufficient ether to transfer the value
   153  	CanTransfer CanTransferFunc
   154  	// Transfer transfers ether from one account to the other
   155  	Transfer TransferFunc
   156  	// GetHash returns the hash corresponding to n
   157  	GetHash GetHashFunc
   158  
   159  	// Block information
   160  	Coinbase    common.Address // Provides information for COINBASE
   161  	GasLimit    uint64         // Provides information for GASLIMIT
   162  	BlockNumber *big.Int       // Provides information for NUMBER
   163  	Time        *big.Int       // Provides information for TIME
   164  	Difficulty  *big.Int       // Provides information for DIFFICULTY
   165  }
   166  
   167  // TxContext provides the EVM with information about a transaction.
   168  // All fields can change between transactions.
   169  type TxContext struct {
   170  	// Message information
   171  	Origin   common.Address // Provides information for ORIGIN
   172  	GasPrice *big.Int       // Provides information for GASPRICE
   173  }
   174  type PublicState StateDB
   175  type PrivateState StateDB
   176  
   177  // EVM is the Ethereum Virtual Machine base object and provides
   178  // the necessary tools to run a contract on the given state with
   179  // the provided context. It should be noted that any error
   180  // generated through any of the calls should be considered a
   181  // revert-state-and-consume-all-gas operation, no checks on
   182  // specific errors should ever be performed. The interpreter makes
   183  // sure that any errors generated are to be considered faulty code.
   184  //
   185  // The EVM should never be reused and is not thread safe.
   186  type EVM struct {
   187  	// Context provides auxiliary blockchain related information
   188  	Context BlockContext
   189  	TxContext
   190  	// StateDB gives access to the underlying state
   191  	StateDB StateDB
   192  	// Depth is the current call stack
   193  	depth int
   194  
   195  	// chainConfig contains information about the current chain
   196  	chainConfig *params.ChainConfig
   197  	// chain rules contains the chain rules for the current epoch
   198  	chainRules params.Rules
   199  	// virtual machine configuration options used to initialise the
   200  	// evm.
   201  	vmConfig Config
   202  	// global (to this context) ethereum virtual machine
   203  	// used throughout the execution of the tx.
   204  	interpreters []Interpreter
   205  	interpreter  Interpreter
   206  	// abort is used to abort the EVM calling operations
   207  	// NOTE: must be set atomically
   208  	abort int32
   209  	// callGasTemp holds the gas available for the current call. This is needed because the
   210  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   211  	// applied in opCall*.
   212  	callGasTemp uint64
   213  
   214  	// Quorum additions:
   215  	publicState       PublicState
   216  	privateState      PrivateState
   217  	states            [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025
   218  	currentStateDepth uint
   219  
   220  	// This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe
   221  	// be simplified). This is set by Quorum when it's inside a Private State -> Public State read.
   222  	quorumReadOnly bool
   223  	readOnlyDepth  uint
   224  
   225  	// Quorum: these are for privacy enhancements and multitenancy
   226  	affectedContracts map[common.Address]AffectedReason // affected contract account address -> type
   227  	currentTx         *types.Transaction                // transaction currently being applied on this EVM
   228  
   229  	// Quorum: these are for privacy marker transactions
   230  	InnerApply          func(innerTx *types.Transaction) error //Quorum
   231  	InnerPrivateReceipt *types.Receipt                         //Quorum
   232  }
   233  
   234  // AffectedReason defines a type of operation that was applied to a contract.
   235  type AffectedReason byte
   236  
   237  const (
   238  	_        AffectedReason = iota
   239  	Creation AffectedReason = iota
   240  	MessageCall
   241  )
   242  
   243  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   244  // only ever be used *once*.
   245  func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb, privateState StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   246  	evm := &EVM{
   247  		Context:      blockCtx,
   248  		TxContext:    txCtx,
   249  		StateDB:      statedb,
   250  		vmConfig:     vmConfig,
   251  		chainConfig:  chainConfig,
   252  		chainRules:   chainConfig.Rules(blockCtx.BlockNumber),
   253  		interpreters: make([]Interpreter, 0, 1),
   254  
   255  		publicState:  statedb,
   256  		privateState: privateState,
   257  
   258  		affectedContracts: make(map[common.Address]AffectedReason),
   259  	}
   260  
   261  	if chainConfig.IsEWASM(blockCtx.BlockNumber) {
   262  		// to be implemented by EVM-C and Wagon PRs.
   263  		// if vmConfig.EWASMInterpreter != "" {
   264  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   265  		//  path := extIntOpts[0]
   266  		//  options := []string{}
   267  		//  if len(extIntOpts) > 1 {
   268  		//    options = extIntOpts[1..]
   269  		//  }
   270  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   271  		// } else {
   272  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   273  		// }
   274  		panic("No supported ewasm interpreter yet.")
   275  	}
   276  
   277  	evm.Push(privateState)
   278  
   279  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   280  	// as we always want to have the built-in EVM as the failover option.
   281  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   282  	evm.interpreter = evm.interpreters[0]
   283  
   284  	return evm
   285  }
   286  
   287  // Reset resets the EVM with a new transaction context.Reset
   288  // This is not threadsafe and should only be done very cautiously.
   289  func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) {
   290  	evm.TxContext = txCtx
   291  	evm.StateDB = statedb
   292  }
   293  
   294  // Cancel cancels any running EVM operation. This may be called concurrently and
   295  // it's safe to be called multiple times.
   296  func (evm *EVM) Cancel() {
   297  	atomic.StoreInt32(&evm.abort, 1)
   298  }
   299  
   300  // Cancelled returns true if Cancel has been called
   301  func (evm *EVM) Cancelled() bool {
   302  	return atomic.LoadInt32(&evm.abort) == 1
   303  }
   304  
   305  // Interpreter returns the current interpreter
   306  func (evm *EVM) Interpreter() Interpreter {
   307  	return evm.interpreter
   308  }
   309  
   310  // Call executes the contract associated with the addr with the given input as
   311  // parameters. It also handles any necessary value transfer required and takes
   312  // the necessary steps to create accounts and reverses the state in case of an
   313  // execution error or failed value transfer.
   314  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   315  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   316  		return nil, gas, nil
   317  	}
   318  
   319  	evm.Push(getDualState(evm, addr))
   320  	defer func() { evm.Pop() }()
   321  
   322  	// Fail if we're trying to execute above the call depth limit
   323  	if evm.depth > int(params.CallCreateDepth) {
   324  		return nil, gas, ErrDepth
   325  	}
   326  	// Fail if we're trying to transfer more than the available balance
   327  	if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   328  		return nil, gas, ErrInsufficientBalance
   329  	}
   330  	snapshot := evm.StateDB.Snapshot()
   331  	p, isPrecompile := evm.precompile(addr)
   332  	qp, isQuorumPrecompile := evm.quorumPrecompile(addr) // Quorum
   333  
   334  	if !evm.StateDB.Exist(addr) {
   335  		if !isPrecompile && !isQuorumPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   336  			// Calling a non existing account, don't do anything, but ping the tracer
   337  			if evm.vmConfig.Debug && evm.depth == 0 {
   338  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   339  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   340  			}
   341  			return nil, gas, nil
   342  		}
   343  		evm.StateDB.CreateAccount(addr)
   344  	}
   345  
   346  	// Quorum
   347  	if evm.ChainConfig().IsQuorum {
   348  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   349  		if value.Sign() != 0 {
   350  			if evm.quorumReadOnly {
   351  				return nil, gas, ErrReadOnlyValueTransfer
   352  			}
   353  			evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
   354  		}
   355  		// End Quorum
   356  	} else {
   357  		evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
   358  	}
   359  
   360  	// Capture the tracer start/end events in debug mode
   361  	if evm.vmConfig.Debug && evm.depth == 0 {
   362  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   363  		defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters
   364  			evm.vmConfig.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err)
   365  		}(gas, time.Now())
   366  	}
   367  
   368  	if isQuorumPrecompile {
   369  		ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
   370  	} else if isPrecompile {
   371  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   372  	} else {
   373  		// Initialise a new contract and set the code that is to be used by the EVM.
   374  		// The contract is a scoped environment for this execution context only.
   375  		code := evm.StateDB.GetCode(addr)
   376  		addrCopy := addr
   377  		// If the account has no code, we can abort here
   378  		// The depth-check is already done, and precompiles handled above
   379  		contract := NewContract(caller, AccountRef(addrCopy), value, gas)
   380  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code)
   381  		ret, err = run(evm, contract, input, false)
   382  		gas = contract.Gas
   383  	}
   384  	// When an error was returned by the EVM or when setting the creation code
   385  	// above we revert to the snapshot and consume any gas remaining. Additionally
   386  	// when we're in homestead this also counts for code storage gas errors.
   387  	if err != nil {
   388  		evm.StateDB.RevertToSnapshot(snapshot)
   389  		if err != ErrExecutionReverted {
   390  			gas = 0
   391  		}
   392  		// TODO: consider clearing up unused snapshots:
   393  		//} else {
   394  		//	evm.StateDB.DiscardSnapshot(snapshot)
   395  	}
   396  	return ret, gas, err
   397  }
   398  
   399  // CallCode executes the contract associated with the addr with the given input
   400  // as parameters. It also handles any necessary value transfer required and takes
   401  // the necessary steps to create accounts and reverses the state in case of an
   402  // execution error or failed value transfer.
   403  //
   404  // CallCode differs from Call in the sense that it executes the given address'
   405  // code with the caller as context.
   406  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   407  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   408  		return nil, gas, nil
   409  	}
   410  
   411  	// Quorum
   412  	evm.Push(getDualState(evm, addr))
   413  	defer func() { evm.Pop() }()
   414  	// End Quorum
   415  
   416  	// Fail if we're trying to execute above the call depth limit
   417  	if evm.depth > int(params.CallCreateDepth) {
   418  		return nil, gas, ErrDepth
   419  	}
   420  	// Fail if we're trying to transfer more than the available balance
   421  	// Note although it's noop to transfer X ether to caller itself. But
   422  	// if caller doesn't have enough balance, it would be an error to allow
   423  	// over-charging itself. So the check here is necessary.
   424  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   425  		return nil, gas, ErrInsufficientBalance
   426  	}
   427  	var snapshot = evm.StateDB.Snapshot()
   428  
   429  	// It is allowed to call precompiles, even via delegatecall
   430  	if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
   431  		ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
   432  	} else if p, isPrecompile := evm.precompile(addr); isPrecompile {
   433  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   434  	} else {
   435  		addrCopy := addr
   436  		// Initialise a new contract and set the code that is to be used by the EVM.
   437  		// The contract is a scoped environment for this execution context only.
   438  		contract := NewContract(caller, AccountRef(caller.Address()), value, gas)
   439  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   440  		ret, err = run(evm, contract, input, false)
   441  		gas = contract.Gas
   442  	}
   443  	if err != nil {
   444  		evm.StateDB.RevertToSnapshot(snapshot)
   445  		if err != ErrExecutionReverted {
   446  			gas = 0
   447  		}
   448  	}
   449  	return ret, gas, err
   450  }
   451  
   452  // DelegateCall executes the contract associated with the addr with the given input
   453  // as parameters. It reverses the state in case of an execution error.
   454  //
   455  // DelegateCall differs from CallCode in the sense that it executes the given address'
   456  // code with the caller as context and the caller is set to the caller of the caller.
   457  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   458  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   459  		return nil, gas, nil
   460  	}
   461  
   462  	// Quorum
   463  	evm.Push(getDualState(evm, addr))
   464  	defer func() { evm.Pop() }()
   465  	// End Quorum
   466  
   467  	// Fail if we're trying to execute above the call depth limit
   468  	if evm.depth > int(params.CallCreateDepth) {
   469  		return nil, gas, ErrDepth
   470  	}
   471  	var snapshot = evm.StateDB.Snapshot()
   472  
   473  	// It is allowed to call precompiles, even via delegatecall
   474  	if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
   475  		ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
   476  	} else if p, isPrecompile := evm.precompile(addr); isPrecompile {
   477  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   478  	} else {
   479  		addrCopy := addr
   480  		// Initialise a new contract and make initialise the delegate values
   481  		contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate()
   482  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   483  		ret, err = run(evm, contract, input, false)
   484  		gas = contract.Gas
   485  	}
   486  	if err != nil {
   487  		evm.StateDB.RevertToSnapshot(snapshot)
   488  		if err != ErrExecutionReverted {
   489  			gas = 0
   490  		}
   491  	}
   492  	return ret, gas, err
   493  }
   494  
   495  // StaticCall executes the contract associated with the addr with the given input
   496  // as parameters while disallowing any modifications to the state during the call.
   497  // Opcodes that attempt to perform such modifications will result in exceptions
   498  // instead of performing the modifications.
   499  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   500  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   501  		return nil, gas, nil
   502  	}
   503  	// Fail if we're trying to execute above the call depth limit
   504  	if evm.depth > int(params.CallCreateDepth) {
   505  		return nil, gas, ErrDepth
   506  	}
   507  	// Quorum
   508  	// use the right state (public or private)
   509  	stateDb := getDualState(evm, addr)
   510  	// End Quorum
   511  
   512  	// We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped.
   513  	// However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced
   514  	// after all empty accounts were deleted, so this is not required. However, if we omit this,
   515  	// then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json.
   516  	// We could change this, but for now it's left for legacy reasons
   517  	var snapshot = stateDb.Snapshot()
   518  
   519  	// We do an AddBalance of zero here, just in order to trigger a touch.
   520  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   521  	// but is the correct thing to do and matters on other networks, in tests, and potential
   522  	// future scenarios
   523  	stateDb.AddBalance(addr, big0)
   524  
   525  	if qp, isQuorumPrecompile := evm.quorumPrecompile(addr); isQuorumPrecompile { // Quorum
   526  		ret, gas, err = RunQuorumPrecompiledContract(evm, qp, input, gas)
   527  	} else if p, isPrecompile := evm.precompile(addr); isPrecompile {
   528  		ret, gas, err = RunPrecompiledContract(p, input, gas)
   529  	} else {
   530  		// At this point, we use a copy of address. If we don't, the go compiler will
   531  		// leak the 'contract' to the outer scope, and make allocation for 'contract'
   532  		// even if the actual execution ends on RunPrecompiled above.
   533  		addrCopy := addr
   534  		// Initialise a new contract and set the code that is to be used by the EVM.
   535  		// The contract is a scoped environment for this execution context only.
   536  		contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas)
   537  		contract.SetCallCode(&addrCopy, stateDb.GetCodeHash(addrCopy), stateDb.GetCode(addrCopy))
   538  		// When an error was returned by the EVM or when setting the creation code
   539  		// above we revert to the snapshot and consume any gas remaining. Additionally
   540  		// when we're in Homestead this also counts for code storage gas errors.
   541  		ret, err = run(evm, contract, input, true)
   542  		gas = contract.Gas
   543  	}
   544  	if err != nil {
   545  		stateDb.RevertToSnapshot(snapshot)
   546  		if err != ErrExecutionReverted {
   547  			gas = 0
   548  		}
   549  	}
   550  	return ret, gas, err
   551  }
   552  
   553  type codeAndHash struct {
   554  	code []byte
   555  	hash common.Hash
   556  }
   557  
   558  func (c *codeAndHash) Hash() common.Hash {
   559  	if c.hash == (common.Hash{}) {
   560  		c.hash = crypto.Keccak256Hash(c.code)
   561  	}
   562  	return c.hash
   563  }
   564  
   565  // create creates a new contract using code as deployment code.
   566  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   567  	// Depth check execution. Fail if we're trying to execute above the
   568  	// limit.
   569  	if evm.depth > int(params.CallCreateDepth) {
   570  		return nil, common.Address{}, gas, ErrDepth
   571  	}
   572  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   573  		return nil, common.Address{}, gas, ErrInsufficientBalance
   574  	}
   575  
   576  	// We add this to the access list _before_ taking a snapshot. Even if the creation fails,
   577  	// the access-list change should not be rolled back
   578  	if evm.chainRules.IsYoloV2 {
   579  		evm.StateDB.AddAddressToAccessList(address)
   580  	}
   581  
   582  	// Quorum
   583  	// Get the right state in case of a dual state environment. If a sender
   584  	// is a transaction (depth == 0) use the public state to derive the address
   585  	// and increment the nonce of the public state. If the sender is a contract
   586  	// (depth > 0) use the private state to derive the nonce and increment the
   587  	// nonce on the private state only.
   588  	//
   589  	// If the transaction went to a public contract the private and public state
   590  	// are the same.
   591  	var creatorStateDb StateDB
   592  	if evm.depth > 0 {
   593  		creatorStateDb = evm.privateState
   594  	} else {
   595  		creatorStateDb = evm.publicState
   596  	}
   597  
   598  	nonce := creatorStateDb.GetNonce(caller.Address())
   599  	creatorStateDb.SetNonce(caller.Address(), nonce+1)
   600  
   601  	// Ensure there's no existing contract already at the designated address
   602  	contractHash := evm.StateDB.GetCodeHash(address)
   603  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   604  		return nil, common.Address{}, 0, ErrContractAddressCollision
   605  	}
   606  	// Create a new account on the state
   607  	snapshot := evm.StateDB.Snapshot()
   608  	evm.StateDB.CreateAccount(address)
   609  	// Quorum
   610  	evm.affectedContracts[address] = Creation
   611  	// End Quorum
   612  	if evm.chainRules.IsEIP158 {
   613  		evm.StateDB.SetNonce(address, 1)
   614  	}
   615  	if nil != evm.currentTx && evm.currentTx.IsPrivate() && evm.currentTx.PrivacyMetadata() != nil {
   616  		// for calls (reading contract state) or finding the affected contracts there is no transaction
   617  		if evm.currentTx.PrivacyMetadata().PrivacyFlag.IsNotStandardPrivate() {
   618  			pm := state.NewStatePrivacyMetadata(common.BytesToEncryptedPayloadHash(evm.currentTx.Data()), evm.currentTx.PrivacyMetadata().PrivacyFlag)
   619  			evm.StateDB.SetPrivacyMetadata(address, pm)
   620  			log.Trace("Set Privacy Metadata", "key", address, "privacyMetadata", pm)
   621  		}
   622  	}
   623  	if evm.ChainConfig().IsQuorum {
   624  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   625  		if value.Sign() != 0 {
   626  			if evm.quorumReadOnly {
   627  				return nil, common.Address{}, gas, ErrReadOnlyValueTransfer
   628  			}
   629  			evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
   630  		}
   631  	} else {
   632  		evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
   633  	}
   634  
   635  	// Initialise a new contract and set the code that is to be used by the EVM.
   636  	// The contract is a scoped environment for this execution context only.
   637  	contract := NewContract(caller, AccountRef(address), value, gas)
   638  	contract.SetCodeOptionalHash(&address, codeAndHash)
   639  
   640  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   641  		return nil, address, gas, nil
   642  	}
   643  
   644  	if evm.vmConfig.Debug && evm.depth == 0 {
   645  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   646  	}
   647  	start := time.Now()
   648  
   649  	ret, err := run(evm, contract, nil, false)
   650  
   651  	maxCodeSize := evm.ChainConfig().GetMaxCodeSize(evm.Context.BlockNumber)
   652  	// check whether the max code size has been exceeded, check maxcode size from chain config
   653  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > maxCodeSize
   654  	// if the contract creation ran successfully and no errors were returned
   655  	// calculate the gas required to store the code. If the code could not
   656  	// be stored due to not enough gas set an error and let it be handled
   657  	// by the error checking condition below.
   658  	if err == nil && !maxCodeSizeExceeded {
   659  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   660  		if contract.UseGas(createDataGas) {
   661  			evm.StateDB.SetCode(address, ret)
   662  		} else {
   663  			err = ErrCodeStoreOutOfGas
   664  		}
   665  	}
   666  
   667  	// When an error was returned by the EVM or when setting the creation code
   668  	// above we revert to the snapshot and consume any gas remaining. Additionally
   669  	// when we're in homestead this also counts for code storage gas errors.
   670  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   671  		evm.StateDB.RevertToSnapshot(snapshot)
   672  		if err != ErrExecutionReverted {
   673  			contract.UseGas(contract.Gas)
   674  		}
   675  	}
   676  	// Assign err if contract code size exceeds the max while the err is still empty.
   677  	if maxCodeSizeExceeded && err == nil {
   678  		err = ErrMaxCodeSizeExceeded
   679  	}
   680  	if evm.vmConfig.Debug && evm.depth == 0 {
   681  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   682  	}
   683  	return ret, address, contract.Gas, err
   684  
   685  }
   686  
   687  // Create creates a new contract using code as deployment code.
   688  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   689  	// Quorum
   690  	// Get the right state in case of a dual state environment. If a sender
   691  	// is a transaction (depth == 0) use the public state to derive the address
   692  	// and increment the nonce of the public state. If the sender is a contract
   693  	// (depth > 0) use the private state to derive the nonce and increment the
   694  	// nonce on the private state only.
   695  	//
   696  	// If the transaction went to a public contract the private and public state
   697  	// are the same.
   698  	var creatorStateDb StateDB
   699  	if evm.depth > 0 {
   700  		creatorStateDb = evm.privateState
   701  	} else {
   702  		creatorStateDb = evm.publicState
   703  	}
   704  
   705  	// Ensure there's no existing contract already at the designated address
   706  	nonce := creatorStateDb.GetNonce(caller.Address())
   707  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   708  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   709  }
   710  
   711  // Create2 creates a new contract using code as deployment code.
   712  //
   713  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   714  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   715  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) {
   716  	codeAndHash := &codeAndHash{code: code}
   717  	contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes())
   718  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   719  }
   720  
   721  // ChainConfig returns the environment's chain configuration
   722  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   723  
   724  // Quorum functions for dual state
   725  func getDualState(evm *EVM, addr common.Address) StateDB {
   726  	// priv: (a) -> (b)  (private)
   727  	// pub:   a  -> [b]  (private -> public)
   728  	// priv: (a) ->  b   (public)
   729  	state := evm.StateDB
   730  
   731  	if evm.PrivateState().Exist(addr) {
   732  		state = evm.PrivateState()
   733  	} else if evm.PublicState().Exist(addr) {
   734  		state = evm.PublicState()
   735  	}
   736  
   737  	return state
   738  }
   739  
   740  func (evm *EVM) PublicState() PublicState           { return evm.publicState }
   741  func (evm *EVM) PrivateState() PrivateState         { return evm.privateState }
   742  func (evm *EVM) SetCurrentTX(tx *types.Transaction) { evm.currentTx = tx }
   743  func (evm *EVM) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
   744  	evm.currentTx.SetTxPrivacyMetadata(pm)
   745  }
   746  func (evm *EVM) Push(statedb StateDB) {
   747  	// Quorum : the read only depth to be set up only once for the entire
   748  	// op code execution. This will be set first time transition from
   749  	// private state to public state happens
   750  	// statedb will be the state of the contract being called.
   751  	// if a private contract is calling a public contract make it readonly.
   752  	if !evm.quorumReadOnly && evm.privateState != statedb {
   753  		evm.quorumReadOnly = true
   754  		evm.readOnlyDepth = evm.currentStateDepth
   755  	}
   756  
   757  	if castedStateDb, ok := statedb.(*state.StateDB); ok {
   758  		evm.states[evm.currentStateDepth] = castedStateDb
   759  		evm.currentStateDepth++
   760  	}
   761  
   762  	evm.StateDB = statedb
   763  }
   764  func (evm *EVM) Pop() {
   765  	evm.currentStateDepth--
   766  	if evm.quorumReadOnly && evm.currentStateDepth == evm.readOnlyDepth {
   767  		evm.quorumReadOnly = false
   768  	}
   769  	evm.StateDB = evm.states[evm.currentStateDepth-1]
   770  }
   771  
   772  func (evm *EVM) Depth() int { return evm.depth }
   773  
   774  // We only need to revert the current state because when we call from private
   775  // public state it's read only, there wouldn't be anything to reset.
   776  // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged
   777  // read only.
   778  func (evm *EVM) RevertToSnapshot(snapshot int) {
   779  	evm.StateDB.RevertToSnapshot(snapshot)
   780  }
   781  
   782  // Quorum
   783  //
   784  // Returns addresses of contracts which are newly created
   785  func (evm *EVM) CreatedContracts() []common.Address {
   786  	addr := make([]common.Address, 0, len(evm.affectedContracts))
   787  	for a, t := range evm.affectedContracts {
   788  		if t == Creation {
   789  			addr = append(addr, a)
   790  		}
   791  	}
   792  	return addr[:]
   793  }
   794  
   795  // Quorum
   796  //
   797  // AffectedContracts returns all affected contracts that are the results of
   798  // MessageCall transaction
   799  func (evm *EVM) AffectedContracts() []common.Address {
   800  	addr := make([]common.Address, 0, len(evm.affectedContracts))
   801  	for a, t := range evm.affectedContracts {
   802  		if t == MessageCall {
   803  			addr = append(addr, a)
   804  		}
   805  	}
   806  	return addr[:]
   807  }
   808  
   809  // Quorum
   810  //
   811  // Return MerkleRoot of all affected contracts (due to both creation and message call)
   812  func (evm *EVM) CalculateMerkleRoot() (common.Hash, error) {
   813  	combined := new(trie.Trie)
   814  	for addr := range evm.affectedContracts {
   815  		data, err := getDualState(evm, addr).GetRLPEncodedStateObject(addr)
   816  		if err != nil {
   817  			return common.Hash{}, err
   818  		}
   819  		if err := combined.TryUpdate(addr.Bytes(), data); err != nil {
   820  			return common.Hash{}, err
   821  		}
   822  	}
   823  	return combined.Hash(), nil
   824  }