github.com/theQRL/go-zond@v0.2.1/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  	"github.com/theQRL/go-zond/common"
    21  	"github.com/theQRL/go-zond/common/math"
    22  	"github.com/theQRL/go-zond/crypto"
    23  	"github.com/theQRL/go-zond/log"
    24  )
    25  
    26  // Config are the configuration options for the Interpreter
    27  type Config struct {
    28  	Tracer                  ZVMLogger // Opcode logger
    29  	NoBaseFee               bool      // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
    30  	EnablePreimageRecording bool      // Enables recording of SHA3/keccak preimages
    31  	ExtraEips               []int     // Additional EIPS that are to be enabled
    32  }
    33  
    34  // ScopeContext contains the things that are per-call, such as stack and memory,
    35  // but not transients like pc and gas
    36  type ScopeContext struct {
    37  	Memory   *Memory
    38  	Stack    *Stack
    39  	Contract *Contract
    40  }
    41  
    42  // ZVMInterpreter represents an ZVM interpreter
    43  type ZVMInterpreter struct {
    44  	zvm   *ZVM
    45  	table *JumpTable
    46  
    47  	hasher    crypto.KeccakState // Keccak256 hasher instance shared across opcodes
    48  	hasherBuf common.Hash        // Keccak256 hasher result array shared across opcodes
    49  
    50  	readOnly   bool   // Whether to throw on stateful modifications
    51  	returnData []byte // Last CALL's return data for subsequent reuse
    52  }
    53  
    54  // NewZVMInterpreter returns a new instance of the Interpreter.
    55  func NewZVMInterpreter(zvm *ZVM) *ZVMInterpreter {
    56  	// If jump table was not initialised we set the default one.
    57  	table := &shanghaiInstructionSet
    58  	var extraEips []int
    59  	if len(zvm.Config.ExtraEips) > 0 {
    60  		// Deep-copy jumptable to prevent modification of opcodes in other tables
    61  		table = copyJumpTable(table)
    62  	}
    63  	for _, eip := range zvm.Config.ExtraEips {
    64  		if err := EnableEIP(eip, table); err != nil {
    65  			// Disable it, so caller can check if it's activated or not
    66  			log.Error("EIP activation failed", "eip", eip, "error", err)
    67  		} else {
    68  			extraEips = append(extraEips, eip)
    69  		}
    70  	}
    71  	zvm.Config.ExtraEips = extraEips
    72  	return &ZVMInterpreter{zvm: zvm, table: table}
    73  }
    74  
    75  // Run loops and evaluates the contract's code with the given input data and returns
    76  // the return byte-slice and an error if one occurred.
    77  //
    78  // It's important to note that any errors returned by the interpreter should be
    79  // considered a revert-and-consume-all-gas operation except for
    80  // ErrExecutionReverted which means revert-and-keep-gas-left.
    81  func (in *ZVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
    82  	// Increment the call depth which is restricted to 1024
    83  	in.zvm.depth++
    84  	defer func() { in.zvm.depth-- }()
    85  
    86  	// Make sure the readOnly is only set if we aren't in readOnly yet.
    87  	// This also makes sure that the readOnly flag isn't removed for child calls.
    88  	if readOnly && !in.readOnly {
    89  		in.readOnly = true
    90  		defer func() { in.readOnly = false }()
    91  	}
    92  
    93  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
    94  	// as every returning call will return new data anyway.
    95  	in.returnData = nil
    96  
    97  	// Don't bother with the execution if there's no code.
    98  	if len(contract.Code) == 0 {
    99  		return nil, nil
   100  	}
   101  
   102  	var (
   103  		op          OpCode        // current opcode
   104  		mem         = NewMemory() // bound memory
   105  		stack       = newstack()  // local stack
   106  		callContext = &ScopeContext{
   107  			Memory:   mem,
   108  			Stack:    stack,
   109  			Contract: contract,
   110  		}
   111  		// For optimisation reason we're using uint64 as the program counter.
   112  		// It's theoretically possible to go above 2^64. The YP defines the PC
   113  		// to be uint256. Practically much less so feasible.
   114  		pc   = uint64(0) // program counter
   115  		cost uint64
   116  		// copies used by tracer
   117  		pcCopy  uint64 // needed for the deferred ZVMLogger
   118  		gasCopy uint64 // for ZVMLogger to log gas remaining before execution
   119  		logged  bool   // deferred ZVMLogger should ignore already logged steps
   120  		res     []byte // result of the opcode execution function
   121  		debug   = in.zvm.Config.Tracer != nil
   122  	)
   123  	// Don't move this deferred function, it's placed before the capturestate-deferred method,
   124  	// so that it get's executed _after_: the capturestate needs the stacks before
   125  	// they are returned to the pools
   126  	defer func() {
   127  		returnStack(stack)
   128  	}()
   129  	contract.Input = input
   130  
   131  	if debug {
   132  		defer func() {
   133  			if err != nil {
   134  				if !logged {
   135  					in.zvm.Config.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.zvm.depth, err)
   136  				} else {
   137  					in.zvm.Config.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.zvm.depth, err)
   138  				}
   139  			}
   140  		}()
   141  	}
   142  	// The Interpreter main run loop (contextual). This loop runs until either an
   143  	// explicit STOP or RETURN is executed, an error occurred during the execution
   144  	// of one of the operations or until the done flag is set by the parent context.
   145  	for {
   146  		if debug {
   147  			// Capture pre-execution values for tracing.
   148  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   149  		}
   150  		// Get the operation from the jump table and validate the stack to ensure there are
   151  		// enough stack items available to perform the operation.
   152  		op = contract.GetOp(pc)
   153  		operation := in.table[op]
   154  		cost = operation.constantGas // For tracing
   155  		// Validate stack
   156  		if sLen := stack.len(); sLen < operation.minStack {
   157  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   158  		} else if sLen > operation.maxStack {
   159  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   160  		}
   161  		if !contract.UseGas(cost) {
   162  			return nil, ErrOutOfGas
   163  		}
   164  		if operation.dynamicGas != nil {
   165  			// All ops with a dynamic memory usage also has a dynamic gas cost.
   166  			var memorySize uint64
   167  			// calculate the new memory size and expand the memory to fit
   168  			// the operation
   169  			// Memory check needs to be done prior to evaluating the dynamic gas portion,
   170  			// to detect calculation overflows
   171  			if operation.memorySize != nil {
   172  				memSize, overflow := operation.memorySize(stack)
   173  				if overflow {
   174  					return nil, ErrGasUintOverflow
   175  				}
   176  				// memory is expanded in words of 32 bytes. Gas
   177  				// is also calculated in words.
   178  				if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   179  					return nil, ErrGasUintOverflow
   180  				}
   181  			}
   182  			// Consume the gas and return an error if not enough gas is available.
   183  			// cost is explicitly set so that the capture state defer method can get the proper cost
   184  			var dynamicCost uint64
   185  			dynamicCost, err = operation.dynamicGas(in.zvm, contract, stack, mem, memorySize)
   186  			cost += dynamicCost // for tracing
   187  			if err != nil || !contract.UseGas(dynamicCost) {
   188  				return nil, ErrOutOfGas
   189  			}
   190  			// Do tracing before memory expansion
   191  			if debug {
   192  				in.zvm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.zvm.depth, err)
   193  				logged = true
   194  			}
   195  			if memorySize > 0 {
   196  				mem.Resize(memorySize)
   197  			}
   198  		} else if debug {
   199  			in.zvm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.zvm.depth, err)
   200  			logged = true
   201  		}
   202  		// execute the operation
   203  		res, err = operation.execute(&pc, in, callContext)
   204  		if err != nil {
   205  			break
   206  		}
   207  		pc++
   208  	}
   209  
   210  	if err == errStopToken {
   211  		err = nil // clear stop token error
   212  	}
   213  
   214  	return res, err
   215  }