github.com/MetalBlockchain/subnet-evm@v0.4.9/core/vm/interpreter.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2014 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package vm 28 29 import ( 30 "hash" 31 32 "github.com/MetalBlockchain/subnet-evm/vmerrs" 33 "github.com/ethereum/go-ethereum/common" 34 "github.com/ethereum/go-ethereum/common/math" 35 "github.com/ethereum/go-ethereum/log" 36 ) 37 38 // Config are the configuration options for the Interpreter 39 type Config struct { 40 Debug bool // Enables debugging 41 Tracer EVMLogger // Opcode logger 42 NoBaseFee bool // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls) 43 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 44 45 JumpTable *JumpTable // EVM instruction table, automatically populated if unset 46 47 ExtraEips []int // Additional EIPS that are to be enabled 48 49 // AllowUnfinalizedQueries allow unfinalized queries 50 AllowUnfinalizedQueries bool 51 } 52 53 // ScopeContext contains the things that are per-call, such as stack and memory, 54 // but not transients like pc and gas 55 type ScopeContext struct { 56 Memory *Memory 57 Stack *Stack 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 // If jump table was not initialised we set the default one. 84 if cfg.JumpTable == nil { 85 switch { 86 case evm.chainRules.IsSubnetEVM: 87 cfg.JumpTable = &subnetEVMInstructionSet 88 case evm.chainRules.IsIstanbul: 89 cfg.JumpTable = &istanbulInstructionSet 90 case evm.chainRules.IsConstantinople: 91 cfg.JumpTable = &constantinopleInstructionSet 92 case evm.chainRules.IsByzantium: 93 cfg.JumpTable = &byzantiumInstructionSet 94 case evm.chainRules.IsEIP158: 95 cfg.JumpTable = &spuriousDragonInstructionSet 96 case evm.chainRules.IsEIP150: 97 cfg.JumpTable = &tangerineWhistleInstructionSet 98 case evm.chainRules.IsHomestead: 99 cfg.JumpTable = &homesteadInstructionSet 100 default: 101 cfg.JumpTable = &frontierInstructionSet 102 } 103 for i, eip := range cfg.ExtraEips { 104 copy := *cfg.JumpTable 105 if err := EnableEIP(eip, ©); err != nil { 106 // Disable it, so caller can check if it's activated or not 107 cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) 108 log.Error("EIP activation failed", "eip", eip, "error", err) 109 } 110 cfg.JumpTable = © 111 } 112 } 113 114 return &EVMInterpreter{ 115 evm: evm, 116 cfg: cfg, 117 } 118 } 119 120 // Run loops and evaluates the contract's code with the given input data and returns 121 // the return byte-slice and an error if one occurred. 122 // 123 // It's important to note that any errors returned by the interpreter should be 124 // considered a revert-and-consume-all-gas operation except for 125 // ErrExecutionReverted which means revert-and-keep-gas-left. 126 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 127 // Increment the call depth which is restricted to 1024 128 in.evm.depth++ 129 defer func() { in.evm.depth-- }() 130 131 // Make sure the readOnly is only set if we aren't in readOnly yet. 132 // This also makes sure that the readOnly flag isn't removed for child calls. 133 if readOnly && !in.readOnly { 134 in.readOnly = true 135 defer func() { in.readOnly = false }() 136 } 137 138 // Reset the previous call's return data. It's unimportant to preserve the old buffer 139 // as every returning call will return new data anyway. 140 in.returnData = nil 141 142 // Don't bother with the execution if there's no code. 143 // Note: this avoids invoking the tracer in any way for simple value 144 // transfers to EOA accounts. 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 callContext = &ScopeContext{ 154 Memory: mem, 155 Stack: stack, 156 Contract: contract, 157 } 158 // For optimisation reason we're using uint64 as the program counter. 159 // It's theoretically possible to go above 2^64. The YP defines the PC 160 // to be uint256. Practically much less so feasible. 161 pc = uint64(0) // program counter 162 cost uint64 163 // copies used by tracer 164 pcCopy uint64 // needed for the deferred EVMLogger 165 gasCopy uint64 // for EVMLogger to log gas remaining before execution 166 logged bool // deferred EVMLogger should ignore already logged steps 167 res []byte // result of the opcode execution function 168 ) 169 170 // Don't move this deferred function, it's placed before the capturestate-deferred method, 171 // so that it get's executed _after_: the capturestate needs the stacks before 172 // they are returned to the pools 173 defer func() { 174 returnStack(stack) 175 }() 176 contract.Input = input 177 178 if in.cfg.Debug { 179 defer func() { 180 if err != nil { 181 if !logged { 182 in.cfg.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 183 } else { 184 in.cfg.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err) 185 } 186 } 187 }() 188 } 189 // The Interpreter main run loop (contextual). This loop runs until either an 190 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 191 // the execution of one of the operations or until the done flag is set by the 192 // parent context. 193 for { 194 if in.cfg.Debug { 195 // Capture pre-execution values for tracing. 196 logged, pcCopy, gasCopy = false, pc, contract.Gas 197 } 198 // Get the operation from the jump table and validate the stack to ensure there are 199 // enough stack items available to perform the operation. 200 op = contract.GetOp(pc) 201 operation := in.cfg.JumpTable[op] 202 cost = operation.constantGas // For tracing 203 // Validate stack 204 if sLen := stack.len(); sLen < operation.minStack { 205 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 206 } else if sLen > operation.maxStack { 207 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 208 } 209 if !contract.UseGas(cost) { 210 return nil, vmerrs.ErrOutOfGas 211 } 212 213 if operation.dynamicGas != nil { 214 // All ops with a dynamic memory usage also has a dynamic gas cost. 215 var memorySize uint64 216 // calculate the new memory size and expand the memory to fit 217 // the operation 218 // Memory check needs to be done prior to evaluating the dynamic gas portion, 219 // to detect calculation overflows 220 if operation.memorySize != nil { 221 memSize, overflow := operation.memorySize(stack) 222 if overflow { 223 return nil, vmerrs.ErrGasUintOverflow 224 } 225 // memory is expanded in words of 32 bytes. Gas 226 // is also calculated in words. 227 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 228 return nil, vmerrs.ErrGasUintOverflow 229 } 230 } 231 // Consume the gas and return an error if not enough gas is available. 232 // cost is explicitly set so that the capture state defer method can get the proper cost 233 var dynamicCost uint64 234 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 235 cost += dynamicCost // for tracing 236 if err != nil || !contract.UseGas(dynamicCost) { 237 return nil, vmerrs.ErrOutOfGas 238 } 239 // Do tracing before memory expansion 240 if in.cfg.Debug { 241 in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 242 logged = true 243 } 244 if memorySize > 0 { 245 mem.Resize(memorySize) 246 } 247 } else if in.cfg.Debug { 248 in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 249 logged = true 250 } 251 252 // execute the operation 253 res, err = operation.execute(&pc, in, callContext) 254 if err != nil { 255 break 256 } 257 pc++ 258 } 259 if err == errStopToken { 260 err = nil // clear stop token error 261 } 262 263 return res, err 264 }