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