github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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 "github.com/tacshi/go-ethereum/common" 21 "github.com/tacshi/go-ethereum/common/math" 22 "github.com/tacshi/go-ethereum/crypto" 23 "github.com/tacshi/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 *EVM 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 *EVM) *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 in.evm.ProcessingHook.PushCaller(contract.Caller()) 110 defer func() { in.evm.depth-- }() 111 defer func() { in.evm.ProcessingHook.PopCaller() }() 112 113 // Make sure the readOnly is only set if we aren't in readOnly yet. 114 // This also makes sure that the readOnly flag isn't removed for child calls. 115 if readOnly && !in.readOnly { 116 in.readOnly = true 117 defer func() { in.readOnly = false }() 118 } 119 120 // Reset the previous call's return data. It's unimportant to preserve the old buffer 121 // as every returning call will return new data anyway. 122 in.returnData = nil 123 124 // Don't bother with the execution if there's no code. 125 if len(contract.Code) == 0 { 126 return nil, nil 127 } 128 129 var ( 130 op OpCode // current opcode 131 mem = NewMemory() // bound memory 132 stack = newstack() // local stack 133 callContext = &ScopeContext{ 134 Memory: mem, 135 Stack: stack, 136 Contract: contract, 137 } 138 // For optimisation reason we're using uint64 as the program counter. 139 // It's theoretically possible to go above 2^64. The YP defines the PC 140 // to be uint256. Practically much less so feasible. 141 pc = uint64(0) // program counter 142 cost uint64 143 // copies used by tracer 144 pcCopy uint64 // needed for the deferred EVMLogger 145 gasCopy uint64 // for EVMLogger to log gas remaining before execution 146 logged bool // deferred EVMLogger should ignore already logged steps 147 res []byte // result of the opcode execution function 148 ) 149 // Don't move this deferred function, it's placed before the capturestate-deferred method, 150 // so that it get's executed _after_: the capturestate needs the stacks before 151 // they are returned to the pools 152 defer func() { 153 returnStack(stack) 154 }() 155 contract.Input = input 156 157 if in.evm.Config.Debug { 158 defer func() { 159 if err != nil { 160 if !logged { 161 in.evm.Config.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 162 } else { 163 in.evm.Config.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err) 164 } 165 } 166 }() 167 } 168 // The Interpreter main run loop (contextual). This loop runs until either an 169 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 170 // the execution of one of the operations or until the done flag is set by the 171 // parent context. 172 for { 173 if in.evm.Config.Debug { 174 // Capture pre-execution values for tracing. 175 logged, pcCopy, gasCopy = false, pc, contract.Gas 176 } 177 // Get the operation from the jump table and validate the stack to ensure there are 178 // enough stack items available to perform the operation. 179 op = contract.GetOp(pc) 180 operation := in.table[op] 181 cost = operation.constantGas // For tracing 182 // Validate stack 183 if sLen := stack.len(); sLen < operation.minStack { 184 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 185 } else if sLen > operation.maxStack { 186 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 187 } 188 if !contract.UseGas(cost) { 189 return nil, ErrOutOfGas 190 } 191 if operation.dynamicGas != nil { 192 // All ops with a dynamic memory usage also has a dynamic gas cost. 193 var memorySize uint64 194 // calculate the new memory size and expand the memory to fit 195 // the operation 196 // Memory check needs to be done prior to evaluating the dynamic gas portion, 197 // to detect calculation overflows 198 if operation.memorySize != nil { 199 memSize, overflow := operation.memorySize(stack) 200 if overflow { 201 return nil, ErrGasUintOverflow 202 } 203 // memory is expanded in words of 32 bytes. Gas 204 // is also calculated in words. 205 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 206 return nil, ErrGasUintOverflow 207 } 208 } 209 // Consume the gas and return an error if not enough gas is available. 210 // cost is explicitly set so that the capture state defer method can get the proper cost 211 var dynamicCost uint64 212 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 213 cost += dynamicCost // for tracing 214 if err != nil || !contract.UseGas(dynamicCost) { 215 return nil, ErrOutOfGas 216 } 217 // Do tracing before memory expansion 218 if in.evm.Config.Debug { 219 in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 220 logged = true 221 } 222 if memorySize > 0 { 223 mem.Resize(memorySize) 224 } 225 } else if in.evm.Config.Debug { 226 in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 227 logged = true 228 } 229 // execute the operation 230 res, err = operation.execute(&pc, in, callContext) 231 if err != nil { 232 break 233 } 234 pc++ 235 } 236 237 if err == errStopToken { 238 err = nil // clear stop token error 239 } 240 241 return res, err 242 }