github.com/myafeier/go-ethereum@v1.6.8-0.20170719123245-3e0dbe0eaa72/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"
    24  	"github.com/ethereum/go-ethereum/common/math"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/params"
    27  )
    28  
    29  // Config are the configuration options for the Interpreter
    30  type Config struct {
    31  	// Debug enabled debugging Interpreter options
    32  	Debug bool
    33  	// EnableJit enabled the JIT VM
    34  	EnableJit bool
    35  	// ForceJit forces the JIT VM
    36  	ForceJit bool
    37  	// Tracer is the op code logger
    38  	Tracer Tracer
    39  	// NoRecursion disabled Interpreter call, callcode,
    40  	// delegate call and create.
    41  	NoRecursion bool
    42  	// Disable gas metering
    43  	DisableGasMetering bool
    44  	// Enable recording of SHA3/keccak preimages
    45  	EnablePreimageRecording bool
    46  	// JumpTable contains the EVM instruction table. This
    47  	// may me left uninitialised and will be set the default
    48  	// table.
    49  	JumpTable [256]operation
    50  }
    51  
    52  // Interpreter is used to run Ethereum based contracts and will utilise the
    53  // passed evmironment to query external sources for state information.
    54  // The Interpreter will run the byte code VM or JIT VM based on the passed
    55  // configuration.
    56  type Interpreter struct {
    57  	evm      *EVM
    58  	cfg      Config
    59  	gasTable params.GasTable
    60  	intPool  *intPool
    61  
    62  	readonly bool
    63  }
    64  
    65  // NewInterpreter returns a new instance of the Interpreter.
    66  func NewInterpreter(evm *EVM, cfg Config) *Interpreter {
    67  	// We use the STOP instruction whether to see
    68  	// the jump table was initialised. If it was not
    69  	// we'll set the default jump table.
    70  	if !cfg.JumpTable[STOP].valid {
    71  		switch {
    72  		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
    73  			cfg.JumpTable = homesteadInstructionSet
    74  		default:
    75  			cfg.JumpTable = frontierInstructionSet
    76  		}
    77  	}
    78  
    79  	return &Interpreter{
    80  		evm:      evm,
    81  		cfg:      cfg,
    82  		gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
    83  		intPool:  newIntPool(),
    84  	}
    85  }
    86  
    87  func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
    88  	return nil
    89  }
    90  
    91  // Run loops and evaluates the contract's code with the given input data and returns
    92  // the return byte-slice and an error if one occurred.
    93  //
    94  // It's important to note that any errors returned by the interpreter should be
    95  // considered a revert-and-consume-all-gas operation. No error specific checks
    96  // should be handled to reduce complexity and errors further down the in.
    97  func (in *Interpreter) Run(snapshot int, contract *Contract, input []byte) (ret []byte, err error) {
    98  	in.evm.depth++
    99  	defer func() { in.evm.depth-- }()
   100  
   101  	// Don't bother with the execution if there's no code.
   102  	if len(contract.Code) == 0 {
   103  		return nil, nil
   104  	}
   105  
   106  	codehash := contract.CodeHash // codehash is used when doing jump dest caching
   107  	if codehash == (common.Hash{}) {
   108  		codehash = crypto.Keccak256Hash(contract.Code)
   109  	}
   110  
   111  	var (
   112  		op    OpCode        // current opcode
   113  		mem   = NewMemory() // bound memory
   114  		stack = newstack()  // local stack
   115  		// For optimisation reason we're using uint64 as the program counter.
   116  		// It's theoretically possible to go above 2^64. The YP defines the PC
   117  		// to be uint256. Practically much less so feasible.
   118  		pc   = uint64(0) // program counter
   119  		cost uint64
   120  	)
   121  	contract.Input = input
   122  
   123  	defer func() {
   124  		if err != nil && in.cfg.Debug {
   125  			in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err)
   126  		}
   127  	}()
   128  
   129  	// The Interpreter main run loop (contextual). This loop runs until either an
   130  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   131  	// the execution of one of the operations or until the done flag is set by the
   132  	// parent context.
   133  	for atomic.LoadInt32(&in.evm.abort) == 0 {
   134  		// Get the memory location of pc
   135  		op = contract.GetOp(pc)
   136  
   137  		// get the operation from the jump table matching the opcode
   138  		operation := in.cfg.JumpTable[op]
   139  		if err := in.enforceRestrictions(op, operation, stack); err != nil {
   140  			return nil, err
   141  		}
   142  
   143  		// if the op is invalid abort the process and return an error
   144  		if !operation.valid {
   145  			return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
   146  		}
   147  
   148  		// validate the stack and make sure there enough stack items available
   149  		// to perform the operation
   150  		if err := operation.validateStack(stack); err != nil {
   151  			return nil, err
   152  		}
   153  
   154  		var memorySize uint64
   155  		// calculate the new memory size and expand the memory to fit
   156  		// the operation
   157  		if operation.memorySize != nil {
   158  			memSize, overflow := bigUint64(operation.memorySize(stack))
   159  			if overflow {
   160  				return nil, errGasUintOverflow
   161  			}
   162  			// memory is expanded in words of 32 bytes. Gas
   163  			// is also calculated in words.
   164  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   165  				return nil, errGasUintOverflow
   166  			}
   167  		}
   168  
   169  		if !in.cfg.DisableGasMetering {
   170  			// consume the gas and return an error if not enough gas is available.
   171  			// cost is explicitly set so that the capture state defer method cas get the proper cost
   172  			cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize)
   173  			if err != nil || !contract.UseGas(cost) {
   174  				return nil, ErrOutOfGas
   175  			}
   176  		}
   177  		if memorySize > 0 {
   178  			mem.Resize(memorySize)
   179  		}
   180  
   181  		if in.cfg.Debug {
   182  			in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err)
   183  		}
   184  
   185  		// execute the operation
   186  		res, err := operation.execute(&pc, in.evm, contract, mem, stack)
   187  		// verifyPool is a build flag. Pool verification makes sure the integrity
   188  		// of the integer pool by comparing values to a default value.
   189  		if verifyPool {
   190  			verifyIntegerPool(in.intPool)
   191  		}
   192  
   193  		switch {
   194  		case err != nil:
   195  			return nil, err
   196  		case operation.halts:
   197  			return res, nil
   198  		case !operation.jumps:
   199  			pc++
   200  		}
   201  		// if the operation returned a value make sure that is also set
   202  		// the last return data.
   203  		if res != nil {
   204  			mem.lastReturn = ret
   205  		}
   206  	}
   207  	return nil, nil
   208  }