github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/core/vm/evm.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package vm
    18  
    19  import (
    20  	"math/big"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/state"
    26  	"github.com/ethereum/go-ethereum/crypto"
    27  	"github.com/ethereum/go-ethereum/params"
    28  )
    29  
    30  // note: Quorum, States, and Value Transfer
    31  //
    32  // In Quorum there is a tricky issue in one specific case when there is call from private state to public state:
    33  // * The state db is selected based on the callee (public)
    34  // * With every call there is an associated value transfer -- in our case this is 0
    35  // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state
    36  // * However in our scenario the caller is private
    37  // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage
    38  //
    39  // The solution is to skip this transfer of 0 value under Quorum
    40  
    41  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    42  // deployed contract addresses (relevant after the account abstraction).
    43  var emptyCodeHash = crypto.Keccak256Hash(nil)
    44  
    45  type (
    46  	// CanTransferFunc is the signature of a transfer guard function
    47  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    48  	// TransferFunc is the signature of a transfer function
    49  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    50  	// GetHashFunc returns the nth block hash in the blockchain
    51  	// and is used by the BLOCKHASH EVM op code.
    52  	GetHashFunc func(uint64) common.Hash
    53  )
    54  
    55  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    56  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
    57  	if contract.CodeAddr != nil {
    58  		precompiles := PrecompiledContractsHomestead
    59  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
    60  			precompiles = PrecompiledContractsByzantium
    61  		}
    62  		if p := precompiles[*contract.CodeAddr]; p != nil {
    63  			return RunPrecompiledContract(p, input, contract)
    64  		}
    65  	}
    66  	for _, interpreter := range evm.interpreters {
    67  		if interpreter.CanRun(contract.Code) {
    68  			if evm.interpreter != interpreter {
    69  				// Ensure that the interpreter pointer is set back
    70  				// to its current value upon return.
    71  				defer func(i Interpreter) {
    72  					evm.interpreter = i
    73  				}(evm.interpreter)
    74  				evm.interpreter = interpreter
    75  			}
    76  			return interpreter.Run(contract, input, readOnly)
    77  		}
    78  	}
    79  	return nil, ErrNoCompatibleInterpreter
    80  }
    81  
    82  // Context provides the EVM with auxiliary information. Once provided
    83  // it shouldn't be modified.
    84  type Context struct {
    85  	// CanTransfer returns whether the account contains
    86  	// sufficient ether to transfer the value
    87  	CanTransfer CanTransferFunc
    88  	// Transfer transfers ether from one account to the other
    89  	Transfer TransferFunc
    90  	// GetHash returns the hash corresponding to n
    91  	GetHash GetHashFunc
    92  
    93  	// Message information
    94  	Origin   common.Address // Provides information for ORIGIN
    95  	GasPrice *big.Int       // Provides information for GASPRICE
    96  
    97  	// Block information
    98  	Coinbase    common.Address // Provides information for COINBASE
    99  	GasLimit    uint64         // Provides information for GASLIMIT
   100  	BlockNumber *big.Int       // Provides information for NUMBER
   101  	Time        *big.Int       // Provides information for TIME
   102  	Difficulty  *big.Int       // Provides information for DIFFICULTY
   103  }
   104  
   105  type PublicState StateDB
   106  type PrivateState StateDB
   107  
   108  // EVM is the Ethereum Virtual Machine base object and provides
   109  // the necessary tools to run a contract on the given state with
   110  // the provided context. It should be noted that any error
   111  // generated through any of the calls should be considered a
   112  // revert-state-and-consume-all-gas operation, no checks on
   113  // specific errors should ever be performed. The interpreter makes
   114  // sure that any errors generated are to be considered faulty code.
   115  //
   116  // The EVM should never be reused and is not thread safe.
   117  type EVM struct {
   118  	// Context provides auxiliary blockchain related information
   119  	Context
   120  	// StateDB gives access to the underlying state
   121  	StateDB StateDB
   122  	// Depth is the current call stack
   123  	depth int
   124  
   125  	// chainConfig contains information about the current chain
   126  	chainConfig *params.ChainConfig
   127  	// chain rules contains the chain rules for the current epoch
   128  	chainRules params.Rules
   129  	// virtual machine configuration options used to initialise the
   130  	// evm.
   131  	vmConfig Config
   132  	// global (to this context) ethereum virtual machine
   133  	// used throughout the execution of the tx.
   134  	interpreters []Interpreter
   135  	interpreter  Interpreter
   136  	// abort is used to abort the EVM calling operations
   137  	// NOTE: must be set atomically
   138  	abort int32
   139  	// callGasTemp holds the gas available for the current call. This is needed because the
   140  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   141  	// applied in opCall*.
   142  	callGasTemp uint64
   143  
   144  	// Quorum additions:
   145  	publicState       PublicState
   146  	privateState      PrivateState
   147  	states            [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025
   148  	currentStateDepth uint
   149  	// This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe
   150  	// be simplified). This is set by Quorum when it's inside a Private State -> Public State read.
   151  	quorumReadOnly bool
   152  	readOnlyDepth  uint
   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, privateState 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  		publicState:  statedb,
   167  		privateState: privateState,
   168  	}
   169  
   170  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   171  		// to be implemented by EVM-C and Wagon PRs.
   172  		// if vmConfig.EWASMInterpreter != "" {
   173  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   174  		//  path := extIntOpts[0]
   175  		//  options := []string{}
   176  		//  if len(extIntOpts) > 1 {
   177  		//    options = extIntOpts[1..]
   178  		//  }
   179  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   180  		// } else {
   181  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   182  		// }
   183  		panic("No supported ewasm interpreter yet.")
   184  	}
   185  
   186  	evm.Push(privateState)
   187  
   188  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   189  	// as we always want to have the built-in EVM as the failover option.
   190  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   191  	evm.interpreter = evm.interpreters[0]
   192  
   193  	return evm
   194  }
   195  
   196  // Cancel cancels any running EVM operation. This may be called concurrently and
   197  // it's safe to be called multiple times.
   198  func (evm *EVM) Cancel() {
   199  	atomic.StoreInt32(&evm.abort, 1)
   200  }
   201  
   202  // Interpreter returns the current interpreter
   203  func (evm *EVM) Interpreter() Interpreter {
   204  	return evm.interpreter
   205  }
   206  
   207  // Call executes the contract associated with the addr with the given input as
   208  // parameters. It also handles any necessary value transfer required and takes
   209  // the necessary steps to create accounts and reverses the state in case of an
   210  // execution error or failed value transfer.
   211  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   212  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   213  		return nil, gas, nil
   214  	}
   215  
   216  	evm.Push(getDualState(evm, addr))
   217  	defer func() { evm.Pop() }()
   218  
   219  	// Fail if we're trying to execute above the call depth limit
   220  	if evm.depth > int(params.CallCreateDepth) {
   221  		return nil, gas, ErrDepth
   222  	}
   223  	// Fail if we're trying to transfer more than the available balance
   224  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   225  		return nil, gas, ErrInsufficientBalance
   226  	}
   227  
   228  	var (
   229  		to       = AccountRef(addr)
   230  		snapshot = evm.StateDB.Snapshot()
   231  	)
   232  	if !evm.StateDB.Exist(addr) {
   233  		precompiles := PrecompiledContractsHomestead
   234  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   235  			precompiles = PrecompiledContractsByzantium
   236  		}
   237  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   238  			// Calling a non existing account, don't do anything, but ping the tracer
   239  			if evm.vmConfig.Debug && evm.depth == 0 {
   240  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   241  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   242  			}
   243  			return nil, gas, nil
   244  		}
   245  		evm.StateDB.CreateAccount(addr)
   246  	}
   247  	if evm.ChainConfig().IsQuorum {
   248  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   249  		if value.Sign() != 0 {
   250  			if evm.quorumReadOnly {
   251  				return nil, gas, ErrReadOnlyValueTransfer
   252  			}
   253  			evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   254  		}
   255  	} else {
   256  		evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   257  	}
   258  
   259  	// Initialise a new contract and set the code that is to be used by the EVM.
   260  	// The contract is a scoped environment for this execution context only.
   261  	contract := NewContract(caller, to, value, gas)
   262  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   263  
   264  	// Even if the account has no code, we need to continue because it might be a precompile
   265  	start := time.Now()
   266  
   267  	// Capture the tracer start/end events in debug mode
   268  	if evm.vmConfig.Debug && evm.depth == 0 {
   269  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   270  
   271  		defer func() { // Lazy evaluation of the parameters
   272  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   273  		}()
   274  	}
   275  	ret, err = run(evm, contract, input, false)
   276  
   277  	// When an error was returned by the EVM or when setting the creation code
   278  	// above we revert to the snapshot and consume any gas remaining. Additionally
   279  	// when we're in homestead this also counts for code storage gas errors.
   280  	if err != nil {
   281  		evm.StateDB.RevertToSnapshot(snapshot)
   282  		if err != errExecutionReverted {
   283  			contract.UseGas(contract.Gas)
   284  		}
   285  	}
   286  	return ret, contract.Gas, err
   287  }
   288  
   289  // CallCode executes the contract associated with the addr with the given input
   290  // as parameters. It also handles any necessary value transfer required and takes
   291  // the necessary steps to create accounts and reverses the state in case of an
   292  // execution error or failed value transfer.
   293  //
   294  // CallCode differs from Call in the sense that it executes the given address'
   295  // code with the caller as context.
   296  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   297  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   298  		return nil, gas, nil
   299  	}
   300  
   301  	evm.Push(getDualState(evm, addr))
   302  	defer func() { evm.Pop() }()
   303  
   304  	// Fail if we're trying to execute above the call depth limit
   305  	if evm.depth > int(params.CallCreateDepth) {
   306  		return nil, gas, ErrDepth
   307  	}
   308  	// Fail if we're trying to transfer more than the available balance
   309  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   310  		return nil, gas, ErrInsufficientBalance
   311  	}
   312  
   313  	var (
   314  		snapshot = evm.StateDB.Snapshot()
   315  		to       = AccountRef(caller.Address())
   316  	)
   317  	// initialise a new contract and set the code that is to be used by the
   318  	// EVM. The contract is a scoped environment for this execution context
   319  	// only.
   320  	contract := NewContract(caller, to, value, gas)
   321  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   322  
   323  	ret, err = run(evm, contract, input, false)
   324  	if err != nil {
   325  		evm.StateDB.RevertToSnapshot(snapshot)
   326  		if err != errExecutionReverted {
   327  			contract.UseGas(contract.Gas)
   328  		}
   329  	}
   330  	return ret, contract.Gas, err
   331  }
   332  
   333  // DelegateCall executes the contract associated with the addr with the given input
   334  // as parameters. It reverses the state in case of an execution error.
   335  //
   336  // DelegateCall differs from CallCode in the sense that it executes the given address'
   337  // code with the caller as context and the caller is set to the caller of the caller.
   338  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   339  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   340  		return nil, gas, nil
   341  	}
   342  
   343  	evm.Push(getDualState(evm, addr))
   344  	defer func() { evm.Pop() }()
   345  
   346  	// Fail if we're trying to execute above the call depth limit
   347  	if evm.depth > int(params.CallCreateDepth) {
   348  		return nil, gas, ErrDepth
   349  	}
   350  
   351  	var (
   352  		snapshot = evm.StateDB.Snapshot()
   353  		to       = AccountRef(caller.Address())
   354  	)
   355  
   356  	// Initialise a new contract and make initialise the delegate values
   357  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   358  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   359  
   360  	ret, err = run(evm, contract, input, false)
   361  	if err != nil {
   362  		evm.StateDB.RevertToSnapshot(snapshot)
   363  		if err != errExecutionReverted {
   364  			contract.UseGas(contract.Gas)
   365  		}
   366  	}
   367  	return ret, contract.Gas, err
   368  }
   369  
   370  // StaticCall executes the contract associated with the addr with the given input
   371  // as parameters while disallowing any modifications to the state during the call.
   372  // Opcodes that attempt to perform such modifications will result in exceptions
   373  // instead of performing the modifications.
   374  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   375  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   376  		return nil, gas, nil
   377  	}
   378  
   379  	// Fail if we're trying to execute above the call depth limit
   380  	if evm.depth > int(params.CallCreateDepth) {
   381  		return nil, gas, ErrDepth
   382  	}
   383  
   384  	var (
   385  		to       = AccountRef(addr)
   386  		stateDb  = getDualState(evm, addr)
   387  		snapshot = stateDb.Snapshot()
   388  	)
   389  	// Initialise a new contract and set the code that is to be used by the
   390  	// EVM. The contract is a scoped environment for this execution context
   391  	// only.
   392  	contract := NewContract(caller, to, new(big.Int), gas)
   393  	contract.SetCallCode(&addr, stateDb.GetCodeHash(addr), stateDb.GetCode(addr))
   394  
   395  	// When an error was returned by the EVM or when setting the creation code
   396  	// above we revert to the snapshot and consume any gas remaining. Additionally
   397  	// when we're in Homestead this also counts for code storage gas errors.
   398  	ret, err = run(evm, contract, input, true)
   399  	if err != nil {
   400  		stateDb.RevertToSnapshot(snapshot)
   401  		if err != errExecutionReverted {
   402  			contract.UseGas(contract.Gas)
   403  		}
   404  	}
   405  	return ret, contract.Gas, err
   406  }
   407  
   408  type codeAndHash struct {
   409  	code []byte
   410  	hash common.Hash
   411  }
   412  
   413  func (c *codeAndHash) Hash() common.Hash {
   414  	if c.hash == (common.Hash{}) {
   415  		c.hash = crypto.Keccak256Hash(c.code)
   416  	}
   417  	return c.hash
   418  }
   419  
   420  // create creates a new contract using code as deployment code.
   421  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   422  	// Depth check execution. Fail if we're trying to execute above the
   423  	// limit.
   424  	if evm.depth > int(params.CallCreateDepth) {
   425  		return nil, common.Address{}, gas, ErrDepth
   426  	}
   427  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   428  		return nil, common.Address{}, gas, ErrInsufficientBalance
   429  	}
   430  
   431  	// Quorum
   432  	// Get the right state in case of a dual state environment. If a sender
   433  	// is a transaction (depth == 0) use the public state to derive the address
   434  	// and increment the nonce of the public state. If the sender is a contract
   435  	// (depth > 0) use the private state to derive the nonce and increment the
   436  	// nonce on the private state only.
   437  	//
   438  	// If the transaction went to a public contract the private and public state
   439  	// are the same.
   440  	var creatorStateDb StateDB
   441  	if evm.depth > 0 {
   442  		creatorStateDb = evm.privateState
   443  	} else {
   444  		creatorStateDb = evm.publicState
   445  	}
   446  
   447  	nonce := creatorStateDb.GetNonce(caller.Address())
   448  	creatorStateDb.SetNonce(caller.Address(), nonce+1)
   449  
   450  	// Ensure there's no existing contract already at the designated address
   451  	contractHash := evm.StateDB.GetCodeHash(address)
   452  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   453  		return nil, common.Address{}, 0, ErrContractAddressCollision
   454  	}
   455  	// Create a new account on the state
   456  	snapshot := evm.StateDB.Snapshot()
   457  	evm.StateDB.CreateAccount(address)
   458  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   459  		evm.StateDB.SetNonce(address, 1)
   460  	}
   461  	if evm.ChainConfig().IsQuorum {
   462  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   463  		if value.Sign() != 0 {
   464  			if evm.quorumReadOnly {
   465  				return nil, common.Address{}, gas, ErrReadOnlyValueTransfer
   466  			}
   467  			evm.Transfer(evm.StateDB, caller.Address(), address, value)
   468  		}
   469  	} else {
   470  		evm.Transfer(evm.StateDB, caller.Address(), address, value)
   471  	}
   472  
   473  	// initialise a new contract and set the code that is to be used by the
   474  	// EVM. The contract is a scoped environment for this execution context
   475  	// only.
   476  	contract := NewContract(caller, AccountRef(address), value, gas)
   477  	contract.SetCodeOptionalHash(&address, codeAndHash)
   478  
   479  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   480  		return nil, address, gas, nil
   481  	}
   482  
   483  	if evm.vmConfig.Debug && evm.depth == 0 {
   484  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   485  	}
   486  	start := time.Now()
   487  
   488  	ret, err := run(evm, contract, nil, false)
   489  
   490  	var maxCodeSize int
   491  	if evm.ChainConfig().MaxCodeSize > 0 {
   492  		maxCodeSize = int(evm.ChainConfig().MaxCodeSize * 1024)
   493  	} else {
   494  		maxCodeSize = params.MaxCodeSize
   495  	}
   496  
   497  	// check whether the max code size has been exceeded, check maxcode size from chain config
   498  	// maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   499  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > maxCodeSize
   500  	// if the contract creation ran successfully and no errors were returned
   501  	// calculate the gas required to store the code. If the code could not
   502  	// be stored due to not enough gas set an error and let it be handled
   503  	// by the error checking condition below.
   504  	if err == nil && !maxCodeSizeExceeded {
   505  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   506  		if contract.UseGas(createDataGas) {
   507  			evm.StateDB.SetCode(address, ret)
   508  		} else {
   509  			err = ErrCodeStoreOutOfGas
   510  		}
   511  	}
   512  
   513  	// When an error was returned by the EVM or when setting the creation code
   514  	// above we revert to the snapshot and consume any gas remaining. Additionally
   515  	// when we're in homestead this also counts for code storage gas errors.
   516  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   517  		evm.StateDB.RevertToSnapshot(snapshot)
   518  		if err != errExecutionReverted {
   519  			contract.UseGas(contract.Gas)
   520  		}
   521  	}
   522  	// Assign err if contract code size exceeds the max while the err is still empty.
   523  	if maxCodeSizeExceeded && err == nil {
   524  		err = errMaxCodeSizeExceeded
   525  	}
   526  	if evm.vmConfig.Debug && evm.depth == 0 {
   527  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   528  	}
   529  	return ret, address, contract.Gas, err
   530  
   531  }
   532  
   533  // Create creates a new contract using code as deployment code.
   534  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   535  	// Quorum
   536  	// Get the right state in case of a dual state environment. If a sender
   537  	// is a transaction (depth == 0) use the public state to derive the address
   538  	// and increment the nonce of the public state. If the sender is a contract
   539  	// (depth > 0) use the private state to derive the nonce and increment the
   540  	// nonce on the private state only.
   541  	//
   542  	// If the transaction went to a public contract the private and public state
   543  	// are the same.
   544  	var creatorStateDb StateDB
   545  	if evm.depth > 0 {
   546  		creatorStateDb = evm.privateState
   547  	} else {
   548  		creatorStateDb = evm.publicState
   549  	}
   550  
   551  	// Ensure there's no existing contract already at the designated address
   552  	nonce := creatorStateDb.GetNonce(caller.Address())
   553  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   554  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   555  }
   556  
   557  // Create2 creates a new contract using code as deployment code.
   558  //
   559  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   560  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   561  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) {
   562  	codeAndHash := &codeAndHash{code: code}
   563  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   564  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   565  }
   566  
   567  // ChainConfig returns the environment's chain configuration
   568  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   569  
   570  func getDualState(env *EVM, addr common.Address) StateDB {
   571  	// priv: (a) -> (b)  (private)
   572  	// pub:   a  -> [b]  (private -> public)
   573  	// priv: (a) ->  b   (public)
   574  	state := env.StateDB
   575  
   576  	if env.PrivateState().Exist(addr) {
   577  		state = env.PrivateState()
   578  	} else if env.PublicState().Exist(addr) {
   579  		state = env.PublicState()
   580  	}
   581  
   582  	return state
   583  }
   584  
   585  func (env *EVM) PublicState() PublicState   { return env.publicState }
   586  func (env *EVM) PrivateState() PrivateState { return env.privateState }
   587  func (env *EVM) Push(statedb StateDB) {
   588  	// Quorum : the read only depth to be set up only once for the entire
   589  	// op code execution. This will be set first time transition from
   590  	// private state to public state happens
   591  	// statedb will be the state of the contract being called.
   592  	// if a private contract is calling a public contract make it readonly.
   593  	if !env.quorumReadOnly && env.privateState != statedb {
   594  		env.quorumReadOnly = true
   595  		env.readOnlyDepth = env.currentStateDepth
   596  	}
   597  
   598  	if castedStateDb, ok := statedb.(*state.StateDB); ok {
   599  		env.states[env.currentStateDepth] = castedStateDb
   600  		env.currentStateDepth++
   601  	}
   602  
   603  	env.StateDB = statedb
   604  }
   605  func (env *EVM) Pop() {
   606  	env.currentStateDepth--
   607  	if env.quorumReadOnly && env.currentStateDepth == env.readOnlyDepth {
   608  		env.quorumReadOnly = false
   609  	}
   610  	env.StateDB = env.states[env.currentStateDepth-1]
   611  }
   612  
   613  func (env *EVM) Depth() int { return env.depth }
   614  
   615  // We only need to revert the current state because when we call from private
   616  // public state it's read only, there wouldn't be anything to reset.
   617  // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged
   618  // read only.
   619  func (self *EVM) RevertToSnapshot(snapshot int) {
   620  	self.StateDB.RevertToSnapshot(snapshot)
   621  }