github.com/newbtp/btp@v0.0.0-20190709081714-e4aafa07224e/core/vm/interpreter.go (about)

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