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