github.com/ontio/ontology@v1.14.4/vm/evm/interpreter.go (about)

     1  // Copyright (C) 2021 The Ontology Authors
     2  // Copyright 2014 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package evm
    19  
    20  import (
    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/log"
    27  	"github.com/ontio/ontology/vm/evm/errors"
    28  )
    29  
    30  // Config are the configuration options for the Interpreter
    31  type Config struct {
    32  	Debug                   bool   // Enables debugging
    33  	Tracer                  Tracer // Opcode logger
    34  	NoRecursion             bool   // Disables call, callcode, delegate call and create
    35  	EnablePreimageRecording bool   // Enables recording of SHA3/keccak preimages
    36  
    37  	JumpTable [256]*operation // EVM instruction table, automatically populated if unset
    38  
    39  	ExtraEips []int // Additional EIPS that are to be enabled
    40  }
    41  
    42  // Interpreter is used to run Ethereum 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  }
    51  
    52  // callCtx contains the things that are per-call, such as stack and memory,
    53  // but not transients like pc and gas
    54  type callCtx struct {
    55  	memory   *Memory
    56  	stack    *Stack
    57  	rstack   *ReturnStack
    58  	contract *Contract
    59  }
    60  
    61  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    62  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    63  // because it doesn't copy the internal state, but also modifies the internal state.
    64  type keccakState interface {
    65  	hash.Hash
    66  	Read([]byte) (int, error)
    67  }
    68  
    69  // EVMInterpreter represents an EVM interpreter
    70  type EVMInterpreter struct {
    71  	evm *EVM
    72  	cfg Config
    73  
    74  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    75  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    76  
    77  	readOnly   bool   // Whether to throw on stateful modifications
    78  	returnData []byte // Last CALL's return data for subsequent reuse
    79  }
    80  
    81  // NewEVMInterpreter returns a new instance of the Interpreter.
    82  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    83  	// We use the STOP instruction whether to see
    84  	// the jump table was initialised. If it was not
    85  	// we'll set the default jump table.
    86  	if cfg.JumpTable[STOP] == nil {
    87  		var jt JumpTable
    88  		switch {
    89  		case evm.chainRules.IsYoloV2:
    90  			jt = yoloV2InstructionSet
    91  		case evm.chainRules.IsIstanbul:
    92  			jt = istanbulInstructionSet
    93  		case evm.chainRules.IsConstantinople:
    94  			jt = constantinopleInstructionSet
    95  		case evm.chainRules.IsByzantium:
    96  			jt = byzantiumInstructionSet
    97  		case evm.chainRules.IsEIP158:
    98  			jt = spuriousDragonInstructionSet
    99  		case evm.chainRules.IsEIP150:
   100  			jt = tangerineWhistleInstructionSet
   101  		case evm.chainRules.IsHomestead:
   102  			jt = homesteadInstructionSet
   103  		default:
   104  			jt = frontierInstructionSet
   105  		}
   106  		for i, eip := range cfg.ExtraEips {
   107  			if err := EnableEIP(eip, &jt); err != nil {
   108  				// Disable it, so caller can check if it's activated or not
   109  				cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
   110  				log.Error("EIP activation failed", "eip", eip, "error", err)
   111  			}
   112  		}
   113  		cfg.JumpTable = jt
   114  	}
   115  
   116  	return &EVMInterpreter{
   117  		evm: evm,
   118  		cfg: cfg,
   119  	}
   120  }
   121  
   122  // Run loops and evaluates the contract's code with the given input data and returns
   123  // the return byte-slice and an error if one occurred.
   124  //
   125  // It's important to note that any errors returned by the interpreter should be
   126  // considered a revert-and-consume-all-gas operation except for
   127  // ErrExecutionReverted which means revert-and-keep-gas-left.
   128  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   129  	// Increment the call depth which is restricted to 1024
   130  	in.evm.depth++
   131  	defer func() { in.evm.depth-- }()
   132  
   133  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   134  	// This makes also sure that the readOnly flag isn't removed for child calls.
   135  	if readOnly && !in.readOnly {
   136  		in.readOnly = true
   137  		defer func() { in.readOnly = false }()
   138  	}
   139  
   140  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   141  	// as every returning call will return new data anyway.
   142  	in.returnData = nil
   143  
   144  	// Don't bother with the execution if there's no code.
   145  	if len(contract.Code) == 0 {
   146  		return nil, nil
   147  	}
   148  
   149  	var (
   150  		op          OpCode             // current opcode
   151  		mem         = NewMemory()      // bound memory
   152  		stack       = newstack()       // local stack
   153  		returns     = newReturnStack() // local returns stack
   154  		callContext = &callCtx{
   155  			memory:   mem,
   156  			stack:    stack,
   157  			rstack:   returns,
   158  			contract: contract,
   159  		}
   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  	// Don't move this deferrred function, it's placed before the capturestate-deferred method,
   172  	// so that it get's executed _after_: the capturestate needs the stacks before
   173  	// they are returned to the pools
   174  	defer func() {
   175  		returnStack(stack)
   176  		returnRStack(returns)
   177  	}()
   178  	contract.Input = input
   179  
   180  	if in.cfg.Debug {
   181  		defer func() {
   182  			if err != nil {
   183  				if !logged {
   184  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, in.returnData, contract, in.evm.depth, err)
   185  				} else {
   186  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
   187  				}
   188  			}
   189  		}()
   190  	}
   191  	// The Interpreter main run loop (contextual). This loop runs until either an
   192  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   193  	// the execution of one of the operations or until the done flag is set by the
   194  	// parent context.
   195  	steps := 0
   196  	for {
   197  		steps++
   198  		if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 {
   199  			break
   200  		}
   201  		if in.cfg.Debug {
   202  			// Capture pre-execution values for tracing.
   203  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   204  		}
   205  
   206  		// Get the operation from the jump table and validate the stack to ensure there are
   207  		// enough stack items available to perform the operation.
   208  		op = contract.GetOp(pc)
   209  		operation := in.cfg.JumpTable[op]
   210  		if operation == nil {
   211  			return nil, &ErrInvalidOpCode{opcode: op}
   212  		}
   213  		// Validate stack
   214  		if sLen := stack.len(); sLen < operation.minStack {
   215  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   216  		} else if sLen > operation.maxStack {
   217  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   218  		}
   219  		// If the operation is valid, enforce and write restrictions
   220  		if in.readOnly && in.evm.chainRules.IsByzantium {
   221  			// If the interpreter is operating in readonly mode, make sure no
   222  			// state-modifying operation is performed. The 3rd stack item
   223  			// for a call operation is the value. Transferring value from one
   224  			// account to the others means the state is modified and should also
   225  			// return with an error.
   226  			if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
   227  				return nil, errors.ErrWriteProtection
   228  			}
   229  		}
   230  		// Static portion of gas
   231  		cost = operation.constantGas // For tracing
   232  		if !contract.UseGas(operation.constantGas) {
   233  			return nil, errors.ErrOutOfGas
   234  		}
   235  
   236  		var memorySize uint64
   237  		// calculate the new memory size and expand the memory to fit
   238  		// the operation
   239  		// Memory check needs to be done prior to evaluating the dynamic gas portion,
   240  		// to detect calculation overflows
   241  		if operation.memorySize != nil {
   242  			memSize, overflow := operation.memorySize(stack)
   243  			if overflow {
   244  				return nil, errors.ErrGasUintOverflow
   245  			}
   246  			// memory is expanded in words of 32 bytes. Gas
   247  			// is also calculated in words.
   248  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   249  				return nil, errors.ErrGasUintOverflow
   250  			}
   251  		}
   252  		// Dynamic portion of gas
   253  		// consume the gas and return an error if not enough gas is available.
   254  		// cost is explicitly set so that the capture state defer method can get the proper cost
   255  		if operation.dynamicGas != nil {
   256  			var dynamicCost uint64
   257  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   258  			cost += dynamicCost // total cost, for debug tracing
   259  			if err != nil || !contract.UseGas(dynamicCost) {
   260  				return nil, errors.ErrOutOfGas
   261  			}
   262  		}
   263  		if memorySize > 0 {
   264  			mem.Resize(memorySize)
   265  		}
   266  
   267  		if in.cfg.Debug {
   268  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, returns, in.returnData, contract, in.evm.depth, err)
   269  			logged = true
   270  		}
   271  
   272  		// execute the operation
   273  		res, err = operation.execute(&pc, in, callContext)
   274  		// if the operation clears the return data (e.g. it has returning data)
   275  		// set the last return to the result of the operation.
   276  		if operation.returns {
   277  			in.returnData = res
   278  		}
   279  
   280  		switch {
   281  		case err != nil:
   282  			return nil, err
   283  		case operation.reverts:
   284  			return res, errors.ErrExecutionReverted
   285  		case operation.halts:
   286  			return res, nil
   287  		case !operation.jumps:
   288  			pc++
   289  		}
   290  	}
   291  	return nil, nil
   292  }