github.com/dominant-strategies/go-quai@v0.28.2/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 "hash" 21 "sync/atomic" 22 23 "github.com/dominant-strategies/go-quai/common" 24 "github.com/dominant-strategies/go-quai/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 NoBaseFee bool // Forces the baseFee to 0 (needed for 0 price calls) 33 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 34 35 JumpTable [256]*operation // EVM instruction table, automatically populated if unset 36 } 37 38 // ScopeContext contains the things that are per-call, such as stack and memory, 39 // but not transients like pc and gas 40 type ScopeContext struct { 41 Memory *Memory 42 Stack *Stack 43 Contract *Contract 44 } 45 46 // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports 47 // Read to get a variable amount of data from the hash state. Read is faster than Sum 48 // because it doesn't copy the internal state, but also modifies the internal state. 49 type keccakState interface { 50 hash.Hash 51 Read([]byte) (int, error) 52 } 53 54 // EVMInterpreter represents an EVM interpreter 55 type EVMInterpreter struct { 56 evm *EVM 57 cfg Config 58 59 hasher keccakState // Keccak256 hasher instance shared across opcodes 60 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 61 62 readOnly bool // Whether to throw on stateful modifications 63 returnData []byte // Last CALL's return data for subsequent reuse 64 } 65 66 // NewEVMInterpreter returns a new instance of the Interpreter. 67 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 68 // We use the STOP instruction whether to see 69 // the jump table was initialised. If it was not 70 // we'll set the default jump table. 71 if cfg.JumpTable[STOP] == nil { 72 jt := instructionSet 73 cfg.JumpTable = jt 74 } 75 76 return &EVMInterpreter{ 77 evm: evm, 78 cfg: cfg, 79 } 80 } 81 82 // Run loops and evaluates the contract's code with the given input data and returns 83 // the return byte-slice and an error if one occurred. 84 // 85 // It's important to note that any errors returned by the interpreter should be 86 // considered a revert-and-consume-all-gas operation except for 87 // ErrExecutionReverted which means revert-and-keep-gas-left. 88 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 89 90 // Increment the call depth which is restricted to 1024 91 in.evm.depth++ 92 defer func() { in.evm.depth-- }() 93 94 // Make sure the readOnly is only set if we aren't in readOnly yet. 95 // This also makes sure that the readOnly flag isn't removed for child calls. 96 if readOnly && !in.readOnly { 97 in.readOnly = true 98 defer func() { in.readOnly = false }() 99 } 100 101 // Reset the previous call's return data. It's unimportant to preserve the old buffer 102 // as every returning call will return new data anyway. 103 in.returnData = nil 104 105 // Don't bother with the execution if there's no code. 106 if len(contract.Code) == 0 { 107 return nil, nil 108 } 109 110 var ( 111 op OpCode // current opcode 112 mem = NewMemory() // bound memory 113 stack = newstack() // local stack 114 callContext = &ScopeContext{ 115 Memory: mem, 116 Stack: stack, 117 Contract: contract, 118 } 119 // For optimisation reason we're using uint64 as the program counter. 120 // It's theoretically possible to go above 2^64. The YP defines the PC 121 // to be uint256. Practically much less so feasible. 122 pc = uint64(0) // program counter 123 cost uint64 124 // copies used by tracer 125 pcCopy uint64 // needed for the deferred Tracer 126 gasCopy uint64 // for Tracer to log gas remaining before execution 127 logged bool // deferred Tracer should ignore already logged steps 128 res []byte // result of the opcode execution function 129 ) 130 // Don't move this deferrred function, it's placed before the capturestate-deferred method, 131 // so that it get's executed _after_: the capturestate needs the stacks before 132 // they are returned to the pools 133 defer func() { 134 returnStack(stack) 135 }() 136 contract.Input = input 137 138 if in.cfg.Debug { 139 defer func() { 140 if err != nil { 141 if !logged { 142 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 143 } else { 144 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err) 145 } 146 } 147 }() 148 } 149 // The Interpreter main run loop (contextual). This loop runs until either an 150 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 151 // the execution of one of the operations or until the done flag is set by the 152 // parent context. 153 steps := 0 154 for { 155 steps++ 156 if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 { 157 break 158 } 159 if in.cfg.Debug { 160 // Capture pre-execution values for tracing. 161 logged, pcCopy, gasCopy = false, pc, contract.Gas 162 } 163 164 // Get the operation from the jump table and validate the stack to ensure there are 165 // enough stack items available to perform the operation. 166 op = contract.GetOp(pc) 167 operation := in.cfg.JumpTable[op] 168 if operation == nil { 169 return nil, &ErrInvalidOpCode{opcode: op} 170 } 171 // Validate stack 172 if sLen := stack.len(); sLen < operation.minStack { 173 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 174 } else if sLen > operation.maxStack { 175 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 176 } 177 // If the operation is valid, enforce write restrictions 178 if in.readOnly { 179 // If the interpreter is operating in readonly mode, make sure no 180 // state-modifying operation is performed. The 3rd stack item 181 // for a call operation is the value. Transferring value from one 182 // account to the others means the state is modified and should also 183 // return with an error. 184 if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) { 185 return nil, ErrWriteProtection 186 } 187 } 188 // Static portion of gas 189 cost = operation.constantGas // For tracing 190 if !contract.UseGas(operation.constantGas) { 191 return nil, ErrOutOfGas 192 } 193 194 var memorySize uint64 195 // calculate the new memory size and expand the memory to fit 196 // the operation 197 // Memory check needs to be done prior to evaluating the dynamic gas portion, 198 // to detect calculation overflows 199 if operation.memorySize != nil { 200 memSize, overflow := operation.memorySize(stack) 201 if overflow { 202 return nil, ErrGasUintOverflow 203 } 204 // memory is expanded in words of 32 bytes. Gas 205 // is also calculated in words. 206 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 207 return nil, ErrGasUintOverflow 208 } 209 } 210 // Dynamic portion of gas 211 // consume the gas and return an error if not enough gas is available. 212 // cost is explicitly set so that the capture state defer method can get the proper cost 213 if operation.dynamicGas != nil { 214 var dynamicCost uint64 215 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 216 cost += dynamicCost // total cost, for debug tracing 217 if err != nil || !contract.UseGas(dynamicCost) { 218 return nil, ErrOutOfGas 219 } 220 } 221 if memorySize > 0 { 222 mem.Resize(memorySize) 223 } 224 225 if in.cfg.Debug { 226 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 227 logged = true 228 } 229 230 // execute the operation 231 res, err = operation.execute(&pc, in, callContext) 232 // if the operation clears the return data (e.g. it has returning data) 233 // set the last return to the result of the operation. 234 if operation.returns { 235 in.returnData = res 236 } 237 238 switch { 239 case err != nil: 240 return nil, err 241 case operation.reverts: 242 return res, ErrExecutionReverted 243 case operation.halts: 244 return res, nil 245 case !operation.jumps: 246 pc++ 247 } 248 } 249 return nil, nil 250 }