github.com/core-coin/go-core@v1.1.7/core/vm/interpreter.go (about)

     1  // Copyright 2014 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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/core-coin/go-core/common"
    24  	"github.com/core-coin/go-core/common/math"
    25  )
    26  
    27  // Config are the configuration options for the Interpreter
    28  type Config struct {
    29  	Debug                   bool   // Enables debugging
    30  	Tracer                  Tracer // Opcode logger
    31  	NoRecursion             bool   // Disables call, callcode, delegate call and create
    32  	EnablePreimageRecording bool   // Enables recording of SHA3/keccak preimages
    33  
    34  	JumpTable [256]*operation // CVM instruction table, automatically populated if unset
    35  
    36  	EWASMInterpreter string // External EWASM interpreter options
    37  	CVMInterpreter   string // External CVM interpreter options
    38  
    39  	ExtraCips []int // Additional CIPS that are to be enabled
    40  }
    41  
    42  // Interpreter is used to run Core 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 something 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  // callCtx contains the things that are per-call, such as stack and memory,
    65  // but not transients like pc and energy
    66  type callCtx struct {
    67  	memory   *Memory
    68  	stack    *Stack
    69  	rstack   *ReturnStack
    70  	contract *Contract
    71  }
    72  
    73  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    74  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    75  // because it doesn't copy the internal state, but also modifies the internal state.
    76  type keccakState interface {
    77  	hash.Hash
    78  	Read([]byte) (int, error)
    79  }
    80  
    81  // CVMInterpreter represents an CVM interpreter
    82  type CVMInterpreter struct {
    83  	cvm *CVM
    84  	cfg Config
    85  
    86  	hasher    keccakState // SHA3 hasher instance shared across opcodes
    87  	hasherBuf common.Hash // SHA3 hasher result array shared aross opcodes
    88  
    89  	readOnly   bool   // Whether to throw on stateful modifications
    90  	returnData []byte // Last CALL's return data for subsequent reuse
    91  }
    92  
    93  // NewCVMInterpreter returns a new instance of the Interpreter.
    94  func NewCVMInterpreter(cvm *CVM, cfg Config) *CVMInterpreter {
    95  	// We use the STOP instruction whether to see
    96  	// the jump table was initialised. If it was not
    97  	// we'll set the default jump table.
    98  	if cfg.JumpTable[STOP] == nil {
    99  		var jt JumpTable
   100  		switch {
   101  		default:
   102  			jt = InstructionSet
   103  		}
   104  		cfg.JumpTable = jt
   105  	}
   106  
   107  	return &CVMInterpreter{
   108  		cvm: cvm,
   109  		cfg: cfg,
   110  	}
   111  }
   112  
   113  // Run loops and evaluates the contract's code with the given input data and returns
   114  // the return byte-slice and an error if one occurred.
   115  //
   116  // It's important to note that any errors returned by the interpreter should be
   117  // considered a revert-and-consume-all-energy operation except for
   118  // ErrExecutionReverted which means revert-and-keep-energy-left.
   119  func (in *CVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   120  	// Increment the call depth which is restricted to 1024
   121  	in.cvm.depth++
   122  	defer func() { in.cvm.depth-- }()
   123  
   124  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   125  	// This makes also sure that the readOnly flag isn't removed for child calls.
   126  	if readOnly && !in.readOnly {
   127  		in.readOnly = true
   128  		defer func() { in.readOnly = false }()
   129  	}
   130  
   131  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   132  	// as every returning call will return new data anyway.
   133  	in.returnData = nil
   134  
   135  	// Don't bother with the execution if there's no code.
   136  	if len(contract.Code) == 0 {
   137  		return nil, nil
   138  	}
   139  
   140  	var (
   141  		op          OpCode             // current opcode
   142  		mem         = NewMemory()      // bound memory
   143  		stack       = newstack()       // local stack
   144  		returns     = newReturnStack() // local returns stack
   145  		callContext = &callCtx{
   146  			memory:   mem,
   147  			stack:    stack,
   148  			rstack:   returns,
   149  			contract: contract,
   150  		}
   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  		energyCopy uint64 // for Tracer to log energy remaining before execution
   159  		logged     bool   // deferred Tracer should ignore already logged steps
   160  		res        []byte // result of the opcode execution function
   161  	)
   162  	// Don't move this deferrred function, it's placed before the capturestate-deferred method,
   163  	// so that it get's executed _after_: the capturestate needs the stacks before
   164  	// they are returned to the pools
   165  	defer func() {
   166  		returnStack(stack)
   167  		returnRStack(returns)
   168  	}()
   169  	contract.Input = input
   170  
   171  	if in.cfg.Debug {
   172  		defer func() {
   173  			if err != nil {
   174  				if !logged {
   175  					in.cfg.Tracer.CaptureState(in.cvm, pcCopy, op, energyCopy, cost, mem, stack, returns, in.returnData, contract, in.cvm.depth, err)
   176  				} else {
   177  					in.cfg.Tracer.CaptureFault(in.cvm, pcCopy, op, energyCopy, cost, mem, stack, returns, contract, in.cvm.depth, err)
   178  				}
   179  			}
   180  		}()
   181  	}
   182  	// The Interpreter main run loop (contextual). This loop runs until either an
   183  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   184  	// the execution of one of the operations or until the done flag is set by the
   185  	// parent context.
   186  	steps := 0
   187  	for {
   188  		steps++
   189  		if steps%1000 == 0 && atomic.LoadInt32(&in.cvm.abort) != 0 {
   190  			break
   191  		}
   192  		if in.cfg.Debug {
   193  			// Capture pre-execution values for tracing.
   194  			logged, pcCopy, energyCopy = false, pc, contract.Energy
   195  		}
   196  
   197  		// Get the operation from the jump table and validate the stack to ensure there are
   198  		// enough stack items available to perform the operation.
   199  		op = contract.GetOp(pc)
   200  		operation := in.cfg.JumpTable[op]
   201  		if operation == nil {
   202  			return nil, &ErrInvalidOpCode{opcode: op}
   203  		}
   204  		// Validate stack
   205  		if sLen := stack.len(); sLen < operation.minStack {
   206  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   207  		} else if sLen > operation.maxStack {
   208  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   209  		}
   210  		// If the operation is valid, enforce and write restrictions
   211  		if in.readOnly {
   212  			// If the interpreter is operating in readonly mode, make sure no
   213  			// state-modifying operation is performed. The 3rd stack item
   214  			// for a call operation is the value. Transferring value from one
   215  			// account to the others means the state is modified and should also
   216  			// return with an error.
   217  			if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
   218  				return nil, ErrWriteProtection
   219  			}
   220  		}
   221  		// Static portion of energy
   222  		cost = operation.constantEnergy // For tracing
   223  		if !contract.UseEnergy(operation.constantEnergy) {
   224  			return nil, ErrOutOfEnergy
   225  		}
   226  
   227  		var memorySize uint64
   228  		// calculate the new memory size and expand the memory to fit
   229  		// the operation
   230  		// Memory check needs to be done prior to evaluating the dynamic energy portion,
   231  		// to detect calculation overflows
   232  		if operation.memorySize != nil {
   233  			memSize, overflow := operation.memorySize(stack)
   234  			if overflow {
   235  				return nil, ErrEnergyUintOverflow
   236  			}
   237  			// memory is expanded in words of 32 bytes. Energy
   238  			// is also calculated in words.
   239  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   240  				return nil, ErrEnergyUintOverflow
   241  			}
   242  		}
   243  		// Dynamic portion of energy
   244  		// consume the energy and return an error if not enough energy is available.
   245  		// cost is explicitly set so that the capture state defer method can get the proper cost
   246  		if operation.dynamicEnergy != nil {
   247  			var dynamicCost uint64
   248  			dynamicCost, err = operation.dynamicEnergy(in.cvm, contract, stack, mem, memorySize)
   249  			cost += dynamicCost // total cost, for debug tracing
   250  			if err != nil || !contract.UseEnergy(dynamicCost) {
   251  				return nil, ErrOutOfEnergy
   252  			}
   253  		}
   254  		if memorySize > 0 {
   255  			mem.Resize(memorySize)
   256  		}
   257  
   258  		if in.cfg.Debug {
   259  			in.cfg.Tracer.CaptureState(in.cvm, pc, op, energyCopy, cost, mem, stack, returns, in.returnData, contract, in.cvm.depth, err)
   260  			logged = true
   261  		}
   262  
   263  		// execute the operation
   264  		res, err = operation.execute(&pc, in, callContext)
   265  		// if the operation clears the return data (e.g. it has returning data)
   266  		// set the last return to the result of the operation.
   267  		if operation.returns {
   268  			in.returnData = common.CopyBytes(res)
   269  		}
   270  
   271  		switch {
   272  		case err != nil:
   273  			return nil, err
   274  		case operation.reverts:
   275  			return res, ErrExecutionReverted
   276  		case operation.halts:
   277  			return res, nil
   278  		case !operation.jumps:
   279  			pc++
   280  		}
   281  	}
   282  	return nil, nil
   283  }
   284  
   285  // CanRun tells if the contract, passed as an argument, can be
   286  // run by the current interpreter.
   287  func (in *CVMInterpreter) CanRun(code []byte) bool {
   288  	return true
   289  }