github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/core/vm/interpreter.go (about)

     1  // Copyright 2014 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package vm
    18  
    19  import (
    20  	"hash"
    21  	"sync/atomic"
    22  
    23  	"github.com/SmartMeshFoundation/Spectrum/common"
    24  	"github.com/SmartMeshFoundation/Spectrum/common/math"
    25  )
    26  
    27  // Config are the configuration options for the Interpreter
    28  type Config struct {
    29  	// Debug enabled debugging Interpreter options
    30  	Debug bool
    31  	// EnableJit enabled the JIT VM
    32  	EnableJit bool
    33  	// ForceJit forces the JIT VM
    34  	ForceJit bool
    35  	// Tracer is the op code logger
    36  	Tracer EVMLogger
    37  	// NoRecursion disabled Interpreter call, callcode,
    38  	// delegate call and create.
    39  	NoRecursion bool
    40  	// Disable gas metering
    41  	DisableGasMetering bool
    42  	// Enable recording of SHA3/keccak preimages
    43  	EnablePreimageRecording bool
    44  	// JumpTable contains the EVM instruction table. This
    45  	// may be left uninitialised and will be set to the default
    46  	// table.
    47  	JumpTable *JumpTable
    48  }
    49  
    50  // ScopeContext contains the things that are per-call, such as stack and memory,
    51  // but not transients like pc and gas
    52  type ScopeContext struct {
    53  	Memory   *Memory
    54  	Stack    *Stack
    55  	Contract *Contract
    56  }
    57  
    58  type keccakState interface {
    59  	hash.Hash
    60  	Read([]byte) (int, error)
    61  }
    62  
    63  // Interpreter is used to run Ethereum based contracts and will utilise the
    64  // passed evmironment to query external sources for state information.
    65  // The Interpreter will run the byte code VM or JIT VM based on the passed
    66  // configuration.
    67  type Interpreter struct {
    68  	evm       *EVM
    69  	cfg       Config
    70  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    71  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    72  
    73  	readOnly   bool   // Whether to throw on stateful modifications
    74  	returnData []byte // Last CALL's return data for subsequent reuse
    75  }
    76  
    77  // NewInterpreter returns a new instance of the Interpreter.
    78  func NewInterpreter(evm *EVM, cfg Config) *Interpreter {
    79  	// We use the STOP instruction whether to see
    80  	// the jump table was initialised. If it was not
    81  	// we'll set the default jump table.
    82  	if cfg.JumpTable == nil {
    83  		switch {
    84  		case evm.ChainConfig().IsSip004(evm.BlockNumber):
    85  			cfg.JumpTable = &si004InstructionSet
    86  		case evm.ChainConfig().IsByzantium(evm.BlockNumber):
    87  			cfg.JumpTable = &byzantiumInstructionSet
    88  		case evm.chainRules.IsEIP158:
    89  			cfg.JumpTable = &spuriousDragonInstructionSet
    90  		case evm.chainRules.IsEIP150:
    91  			cfg.JumpTable = &tangerineWhistleInstructionSet
    92  		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
    93  			cfg.JumpTable = &homesteadInstructionSet
    94  		default:
    95  			cfg.JumpTable = &frontierInstructionSet
    96  		}
    97  	}
    98  
    99  	return &Interpreter{
   100  		evm: evm,
   101  		cfg: cfg,
   102  	}
   103  }
   104  
   105  //func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
   106  //	if in.evm.chainRules.IsByzantium {
   107  //		if in.readOnly {
   108  //			// If the interpreter is operating in readonly mode, make sure no
   109  //			// state-modifying operation is performed. The 3rd stack item
   110  //			// for a call operation is the value. Transferring value from one
   111  //			// account to the others means the state is modified and should also
   112  //			// return with an error.
   113  //			if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) {
   114  //				return errWriteProtection
   115  //			}
   116  //		}
   117  //	}
   118  //	return nil
   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 *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) {
   128  
   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 also makes 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  	// Don't bother with the execution if there's no code.
   144  	if len(contract.Code) == 0 {
   145  		return nil, nil
   146  	}
   147  
   148  	var (
   149  		op          OpCode        // current opcode
   150  		mem         = NewMemory() // bound memory
   151  		stack       = newstack()  // local stack
   152  		callContext = &ScopeContext{
   153  			Memory:   mem,
   154  			Stack:    stack,
   155  			Contract: contract,
   156  		}
   157  		// For optimisation reason we're using uint64 as the program counter.
   158  		// It's theoretically possible to go above 2^64. The YP defines the PC
   159  		// to be uint256. Practically much less so feasible.
   160  		pc   = uint64(0) // program counter
   161  		cost uint64
   162  		// copies used by tracer
   163  		pcCopy  uint64 // needed for the deferred EVMLogger
   164  		gasCopy uint64 // for EVMLogger to log gas remaining before execution
   165  		logged  bool   // deferred EVMLogger should ignore already logged steps
   166  		res     []byte // result of the opcode execution function
   167  	)
   168  	// Don't move this deferrred function, it's placed before the capturestate-deferred method,
   169  	// so that it get's executed _after_: the capturestate needs the stacks before
   170  	// they are returned to the pools
   171  	defer func() {
   172  		returnStack(stack)
   173  	}()
   174  	contract.Input = input
   175  
   176  	if in.cfg.Debug {
   177  		defer func() {
   178  			if err != nil {
   179  				if !logged {
   180  					in.cfg.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   181  				} else {
   182  					in.cfg.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, 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  	steps := 0
   192  	for {
   193  		steps++
   194  		if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 {
   195  			break
   196  		}
   197  		if in.cfg.Debug {
   198  			// Capture pre-execution values for tracing.
   199  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   200  		}
   201  
   202  		// Get the operation from the jump table and validate the stack to ensure there are
   203  		// enough stack items available to perform the operation.
   204  		op = contract.GetOp(pc)
   205  		operation := in.cfg.JumpTable[op]
   206  		if operation == nil {
   207  			return nil, &ErrInvalidOpCode{opcode: op}
   208  		}
   209  		// Validate stack
   210  		if sLen := stack.len(); sLen < operation.minStack {
   211  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   212  		} else if sLen > operation.maxStack {
   213  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   214  		}
   215  		// If the operation is valid, enforce write restrictions
   216  		if in.readOnly && in.evm.chainRules.IsByzantium {
   217  			// If the interpreter is operating in readonly mode, make sure no
   218  			// state-modifying operation is performed. The 3rd stack item
   219  			// for a call operation is the value. Transferring value from one
   220  			// account to the others means the state is modified and should also
   221  			// return with an error.
   222  			if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
   223  				return nil, ErrWriteProtection
   224  			}
   225  		}
   226  
   227  		// Static portion of gas
   228  		if !in.cfg.DisableGasMetering {
   229  			cost = operation.constantGas // For tracing
   230  			//fmt.Println("-run1>>>",op,cost)
   231  			if !contract.UseGas(operation.constantGas) {
   232  				return nil, ErrOutOfGas
   233  			}
   234  		}
   235  		var memorySize uint64
   236  		// calculate the new memory size and expand the memory to fit
   237  		// the operation
   238  		// Memory check needs to be done prior to evaluating the dynamic gas portion,
   239  		// to detect calculation overflows
   240  		if operation.memorySize != nil {
   241  			memSize, overflow := operation.memorySize(stack)
   242  			if overflow {
   243  				return nil, ErrGasUintOverflow
   244  			}
   245  			// memory is expanded in words of 32 bytes. Gas
   246  			// is also calculated in words.
   247  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   248  				return nil, ErrGasUintOverflow
   249  			}
   250  		}
   251  		// Dynamic portion of gas
   252  		// consume the gas and return an error if not enough gas is available.
   253  		// cost is explicitly set so that the capture state defer method can get the proper cost
   254  		if !in.cfg.DisableGasMetering {
   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  				//fmt.Println("-run2>>>",op,cost,dynamicCost)
   260  				if err != nil || !contract.UseGas(dynamicCost) {
   261  					return nil, ErrOutOfGas
   262  				}
   263  			}
   264  		}
   265  		if memorySize > 0 {
   266  			mem.Resize(memorySize)
   267  		}
   268  
   269  		if in.cfg.Debug {
   270  			in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   271  			logged = true
   272  		}
   273  
   274  		// execute the operation
   275  		res, err = operation.execute(&pc, in, callContext)
   276  		// if the operation clears the return data (e.g. it has returning data)
   277  		// set the last return to the result of the operation.
   278  		if operation.returns {
   279  			in.returnData = res
   280  		}
   281  
   282  		switch {
   283  		case err != nil:
   284  			return nil, err
   285  		case operation.reverts:
   286  			return res, ErrExecutionReverted
   287  		case operation.halts:
   288  			return res, nil
   289  		case !operation.jumps:
   290  			pc++
   291  		}
   292  	}
   293  	return nil, nil
   294  }