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