github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/core/vm/interpreter.go (about)

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