github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/core/vm/interpreter.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  	"fmt"
    21  	"sync/atomic"
    22  
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/params"
    25  	"github.com/ethereum/go-ethereum/log"
    26  )
    27  
    28  // Config are the configuration options for the Interpreter
    29  type Config struct {
    30  	// Debug enabled debugging Interpreter options
    31  	Debug bool
    32  	// Tracer is the op code logger
    33  	Tracer Tracer
    34  	// NoRecursion disabled Interpreter call, callcode,
    35  	// delegate call and create.
    36  	NoRecursion bool
    37  	// Enable recording of SHA3/keccak preimages
    38  	EnablePreimageRecording bool
    39  	// JumpTable contains the EVM instruction table. This
    40  	// may be left uninitialised and will be set to the default
    41  	// table.
    42  	JumpTable [256]operation
    43  }
    44  
    45  // Interpreter is used to run Ethereum based contracts and will utilise the
    46  // passed environment to query external sources for state information.
    47  // The Interpreter will run the byte code VM based on the passed
    48  // configuration.
    49  type Interpreter struct {
    50  	evm      *EVM
    51  	cfg      Config
    52  	gasTable params.GasTable
    53  	intPool  *intPool
    54  
    55  	readOnly   bool   // Whether to throw on stateful modifications
    56  	returnData []byte // Last CALL's return data for subsequent reuse
    57  }
    58  
    59  // NewInterpreter returns a new instance of the Interpreter.
    60  func NewInterpreter(evm *EVM, cfg Config) *Interpreter {
    61  	// We use the STOP instruction whether to see
    62  	// the jump table was initialised. If it was not
    63  	// we'll set the default jump table.
    64  	if !cfg.JumpTable[STOP].valid {
    65  		switch {
    66  		case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
    67  			cfg.JumpTable = constantinopleInstructionSet
    68  		case evm.ChainConfig().IsByzantium(evm.BlockNumber):
    69  			cfg.JumpTable = byzantiumInstructionSet
    70  		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
    71  			cfg.JumpTable = homesteadInstructionSet
    72  		default:
    73  			cfg.JumpTable = frontierInstructionSet
    74  		}
    75  	}
    76  
    77  	return &Interpreter{
    78  		evm:      evm,
    79  		cfg:      cfg,
    80  		gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
    81  		intPool:  newIntPool(),
    82  	}
    83  }
    84  
    85  func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
    86  	if in.evm.chainRules.IsByzantium {
    87  		if in.readOnly {
    88  			// If the interpreter is operating in readonly mode, make sure no
    89  			// state-modifying operation is performed. The 3rd stack item
    90  			// for a call operation is the value. Transferring value from one
    91  			// account to the others means the state is modified and should also
    92  			// return with an error.
    93  			if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) {
    94  				return errWriteProtection
    95  			}
    96  		}
    97  	}
    98  	return nil
    99  }
   100  
   101  // Run loops and evaluates the contract's code with the given input data and returns
   102  // the return byte-slice and an error if one occurred.
   103  //
   104  // It's important to note that any errors returned by the interpreter should be
   105  // considered a revert-and-consume-all-gas operation except for
   106  // errExecutionReverted which means revert-and-keep-gas-left.
   107  func (in *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) {
   108  	// Increment the call depth which is restricted to 1024
   109  	in.evm.depth++
   110  	defer func() { in.evm.depth-- }()
   111  
   112  	log.Error("Interpreter.run","depth",in.evm.depth)
   113  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   114  	// as every returning call will return new data anyway.
   115  	in.returnData = nil
   116  
   117  	// Don't bother with the execution if there's no code.
   118  	if len(contract.Code) == 0 {
   119  		return nil, nil
   120  	}
   121  
   122  	var (
   123  		op    OpCode        // current opcode
   124  		mem   = NewMemory() // bound memory
   125  		stack = newstack()  // local stack
   126  		// For optimisation reason we're using uint64 as the program counter.
   127  		// It's theoretically possible to go above 2^64. The YP defines the PC
   128  		// to be uint256. Practically much less so feasible.
   129  		pc   = uint64(0) // program counter
   130  		cost uint64
   131  		// copies used by tracer
   132  		pcCopy  uint64 // needed for the deferred Tracer
   133  		gasCopy uint64 // for Tracer to log gas remaining before execution
   134  		logged  bool   // deferred Tracer should ignore already logged steps
   135  	)
   136  	contract.Input = input
   137  
   138  	if in.cfg.Debug {
   139  		defer func() {
   140  			if err != nil {
   141  				if !logged {
   142  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   143  				} else {
   144  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   145  				}
   146  			}
   147  		}()
   148  	}
   149  	// The Interpreter main run loop (contextual). This loop runs until either an
   150  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   151  	// the execution of one of the operations or until the done flag is set by the
   152  	// parent context.
   153  	index := 0
   154  	for atomic.LoadInt32(&in.evm.abort) == 0 {
   155  		if in.cfg.Debug {
   156  			// Capture pre-execution values for tracing.
   157  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   158  		}
   159  
   160  		// Get the operation from the jump table and validate the stack to ensure there are
   161  		// enough stack items available to perform the operation.
   162  		op = contract.GetOp(pc)
   163  		operation := in.cfg.JumpTable[op]
   164  		if !operation.valid {
   165  			return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
   166  		}
   167  		index++
   168  		log.Error("evm code","op",op,"index",index)
   169  		if err := operation.validateStack(stack); err != nil {
   170  			return nil, err
   171  		}
   172  		// If the operation is valid, enforce and write restrictions
   173  		if err := in.enforceRestrictions(op, operation, stack); err != nil {
   174  			return nil, err
   175  		}
   176  
   177  		var memorySize uint64
   178  		// calculate the new memory size and expand the memory to fit
   179  		// the operation
   180  		if operation.memorySize != nil {
   181  			memSize, overflow := bigUint64(operation.memorySize(stack))
   182  			if overflow {
   183  				return nil, errGasUintOverflow
   184  			}
   185  			// memory is expanded in words of 32 bytes. Gas
   186  			// is also calculated in words.
   187  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   188  				return nil, errGasUintOverflow
   189  			}
   190  		}
   191  		// consume the gas and return an error if not enough gas is available.
   192  		// cost is explicitly set so that the capture state defer method can get the proper cost
   193  		cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize)
   194  		if err != nil || !contract.UseGas(cost) {
   195  			return nil, ErrOutOfGas
   196  		}
   197  		if memorySize > 0 {
   198  			mem.Resize(memorySize)
   199  		}
   200  
   201  		if in.cfg.Debug {
   202  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   203  			logged = true
   204  		}
   205  
   206  		// execute the operation
   207  		res, err := operation.execute(&pc, in.evm, contract, mem, stack)
   208  		// verifyPool is a build flag. Pool verification makes sure the integrity
   209  		// of the integer pool by comparing values to a default value.
   210  		if verifyPool {
   211  			verifyIntegerPool(in.intPool)
   212  		}
   213  		// if the operation clears the return data (e.g. it has returning data)
   214  		// set the last return to the result of the operation.
   215  		if operation.returns {
   216  			in.returnData = res
   217  		}
   218  
   219  		switch {
   220  		case err != nil:
   221  			return nil, err
   222  		case operation.reverts:
   223  			return res, errExecutionReverted
   224  		case operation.halts:
   225  			return res, nil
   226  		case !operation.jumps:
   227  			pc++
   228  		}
   229  	}
   230  	return nil, nil
   231  }