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