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