github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/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  	"hash"
    22  	"sync/atomic"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/common/math"
    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  	// Tracer is the op code logger
    34  	Tracer Tracer
    35  	// NoRecursion disabled Interpreter call, callcode,
    36  	// delegate call and create.
    37  	NoRecursion bool
    38  	// Enable recording of SHA3/keccak preimages
    39  	EnablePreimageRecording bool
    40  	// JumpTable contains the EVM instruction table. This
    41  	// may be left uninitialised and will be set to the default
    42  	// table.
    43  	JumpTable [256]operation
    44  
    45  	// Type of the EWASM interpreter
    46  	EWASMInterpreter string
    47  	// Type of the EVM interpreter
    48  	EVMInterpreter string
    49  }
    50  
    51  // Interpreter is used to run Ethereum based contracts and will utilise the
    52  // passed environment to query external sources for state information.
    53  // The Interpreter will run the byte code VM based on the passed
    54  // configuration.
    55  type Interpreter interface {
    56  	// Run loops and evaluates the contract's code with the given input data and returns
    57  	// the return byte-slice and an error if one occurred.
    58  	Run(contract *Contract, input []byte, static bool) ([]byte, error)
    59  	// CanRun tells if the contract, passed as an argument, can be
    60  	// run by the current interpreter. This is meant so that the
    61  	// caller can do something like:
    62  	//
    63  	// ```golang
    64  	// for _, interpreter := range interpreters {
    65  	//   if interpreter.CanRun(contract.code) {
    66  	//     interpreter.Run(contract.code, input)
    67  	//   }
    68  	// }
    69  	// ```
    70  	CanRun([]byte) bool
    71  }
    72  
    73  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    74  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    75  // because it doesn't copy the internal state, but also modifies the internal state.
    76  type keccakState interface {
    77  	hash.Hash
    78  	Read([]byte) (int, error)
    79  }
    80  
    81  // EVMInterpreter represents an EVM interpreter
    82  type EVMInterpreter struct {
    83  	evm      *EVM
    84  	cfg      Config
    85  	gasTable params.GasTable
    86  
    87  	intPool *intPool
    88  
    89  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    90  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    91  
    92  	readOnly   bool   // Whether to throw on stateful modifications
    93  	returnData []byte // Last CALL's return data for subsequent reuse
    94  }
    95  
    96  // NewEVMInterpreter returns a new instance of the Interpreter.
    97  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    98  	// We use the STOP instruction whether to see
    99  	// the jump table was initialised. If it was not
   100  	// we'll set the default jump table.
   101  	if !cfg.JumpTable[STOP].valid {
   102  		switch {
   103  		case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
   104  			cfg.JumpTable = constantinopleInstructionSet
   105  		case evm.ChainConfig().IsByzantium(evm.BlockNumber):
   106  			cfg.JumpTable = byzantiumInstructionSet
   107  		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
   108  			cfg.JumpTable = homesteadInstructionSet
   109  		default:
   110  			cfg.JumpTable = frontierInstructionSet
   111  		}
   112  	}
   113  
   114  	return &EVMInterpreter{
   115  		evm:      evm,
   116  		cfg:      cfg,
   117  		gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
   118  	}
   119  }
   120  
   121  // Run loops and evaluates the contract's code with the given input data and returns
   122  // the return byte-slice and an error if one occurred.
   123  //
   124  // It's important to note that any errors returned by the interpreter should be
   125  // considered a revert-and-consume-all-gas operation except for
   126  // errExecutionReverted which means revert-and-keep-gas-left.
   127  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   128  	if in.intPool == nil {
   129  		in.intPool = poolOfIntPools.get()
   130  		defer func() {
   131  			poolOfIntPools.put(in.intPool)
   132  			in.intPool = nil
   133  		}()
   134  	}
   135  
   136  	// Increment the call depth which is restricted to 1024
   137  	in.evm.depth++
   138  	defer func() { in.evm.depth-- }()
   139  
   140  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   141  	// This makes also sure that the readOnly flag isn't removed for child calls.
   142  	if readOnly && !in.readOnly {
   143  		in.readOnly = true
   144  		defer func() { in.readOnly = false }()
   145  	}
   146  
   147  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   148  	// as every returning call will return new data anyway.
   149  	in.returnData = nil
   150  
   151  	// Don't bother with the execution if there's no code.
   152  	if len(contract.Code) == 0 {
   153  		return nil, nil
   154  	}
   155  
   156  	var (
   157  		op    OpCode        // current opcode
   158  		mem   = NewMemory() // bound memory
   159  		stack = newstack()  // local stack
   160  		// For optimisation reason we're using uint64 as the program counter.
   161  		// It's theoretically possible to go above 2^64. The YP defines the PC
   162  		// to be uint256. Practically much less so feasible.
   163  		pc   = uint64(0) // program counter
   164  		cost uint64
   165  		// copies used by tracer
   166  		pcCopy  uint64 // needed for the deferred Tracer
   167  		gasCopy uint64 // for Tracer to log gas remaining before execution
   168  		logged  bool   // deferred Tracer should ignore already logged steps
   169  		res     []byte // result of the opcode execution function
   170  	)
   171  	contract.Input = input
   172  
   173  	// Reclaim the stack as an int pool when the execution stops
   174  	defer func() { in.intPool.put(stack.data...) }()
   175  
   176  	if in.cfg.Debug {
   177  		defer func() {
   178  			if err != nil {
   179  				if !logged {
   180  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   181  				} else {
   182  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   183  				}
   184  			}
   185  		}()
   186  	}
   187  	// The Interpreter main run loop (contextual). This loop runs until either an
   188  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   189  	// the execution of one of the operations or until the done flag is set by the
   190  	// parent context.
   191  	for atomic.LoadInt32(&in.evm.abort) == 0 {
   192  		if in.cfg.Debug {
   193  			// Capture pre-execution values for tracing.
   194  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   195  		}
   196  
   197  		// Get the operation from the jump table and validate the stack to ensure there are
   198  		// enough stack items available to perform the operation.
   199  		op = contract.GetOp(pc)
   200  		operation := in.cfg.JumpTable[op]
   201  		if !operation.valid {
   202  			return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
   203  		}
   204  		// Validate stack
   205  		if sLen := stack.len(); sLen < operation.minStack {
   206  			return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack)
   207  		} else if sLen > operation.maxStack {
   208  			return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack)
   209  		}
   210  		// If the operation is valid, enforce and write restrictions
   211  		if in.readOnly && in.evm.chainRules.IsByzantium {
   212  			// If the interpreter is operating in readonly mode, make sure no
   213  			// state-modifying operation is performed. The 3rd stack item
   214  			// for a call operation is the value. Transferring value from one
   215  			// account to the others means the state is modified and should also
   216  			// return with an error.
   217  			if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
   218  				return nil, errWriteProtection
   219  			}
   220  		}
   221  		// Static portion of gas
   222  		if !contract.UseGas(operation.constantGas) {
   223  			return nil, ErrOutOfGas
   224  		}
   225  
   226  		var memorySize uint64
   227  		// calculate the new memory size and expand the memory to fit
   228  		// the operation
   229  		// Memory check needs to be done prior to evaluating the dynamic gas portion,
   230  		// to detect calculation overflows
   231  		if operation.memorySize != nil {
   232  			memSize, overflow := operation.memorySize(stack)
   233  			if overflow {
   234  				return nil, errGasUintOverflow
   235  			}
   236  			// memory is expanded in words of 32 bytes. Gas
   237  			// is also calculated in words.
   238  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   239  				return nil, errGasUintOverflow
   240  			}
   241  		}
   242  		// Dynamic portion of gas
   243  		// consume the gas and return an error if not enough gas is available.
   244  		// cost is explicitly set so that the capture state defer method can get the proper cost
   245  		if operation.dynamicGas != nil {
   246  			cost, err = operation.dynamicGas(in.gasTable, in.evm, contract, stack, mem, memorySize)
   247  			if err != nil || !contract.UseGas(cost) {
   248  				return nil, ErrOutOfGas
   249  			}
   250  		}
   251  		if memorySize > 0 {
   252  			mem.Resize(memorySize)
   253  		}
   254  
   255  		if in.cfg.Debug {
   256  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   257  			logged = true
   258  		}
   259  
   260  		// execute the operation
   261  		res, err = operation.execute(&pc, in, contract, mem, stack)
   262  		// verifyPool is a build flag. Pool verification makes sure the integrity
   263  		// of the integer pool by comparing values to a default value.
   264  		if verifyPool {
   265  			verifyIntegerPool(in.intPool)
   266  		}
   267  		// if the operation clears the return data (e.g. it has returning data)
   268  		// set the last return to the result of the operation.
   269  		if operation.returns {
   270  			in.returnData = res
   271  		}
   272  
   273  		switch {
   274  		case err != nil:
   275  			return nil, err
   276  		case operation.reverts:
   277  			return res, errExecutionReverted
   278  		case operation.halts:
   279  			return res, nil
   280  		case !operation.jumps:
   281  			pc++
   282  		}
   283  	}
   284  	return nil, nil
   285  }
   286  
   287  // CanRun tells if the contract, passed as an argument, can be
   288  // run by the current interpreter.
   289  func (in *EVMInterpreter) CanRun(code []byte) bool {
   290  	return true
   291  }