github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/core/vm/interpreter.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package vm 19 20 import ( 21 "fmt" 22 "hash" 23 "sync/atomic" 24 25 "github.com/AigarNetwork/aigar/common" 26 "github.com/AigarNetwork/aigar/common/math" 27 "github.com/AigarNetwork/aigar/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 45 // Interpreter is used to run Ethereum based contracts and will utilise the 46 // passed environment to query external sources for state information. 47 // The Interpreter will run the byte code VM based on the passed 48 // configuration. 49 type Interpreter interface { 50 // Run loops and evaluates the contract's code with the given input data and returns 51 // the return byte-slice and an error if one occurred. 52 Run(contract *Contract, input []byte, static bool) ([]byte, error) 53 // CanRun tells if the contract, passed as an argument, can be 54 // run by the current interpreter. This is meant so that the 55 // caller can do something like: 56 // 57 // ```golang 58 // for _, interpreter := range interpreters { 59 // if interpreter.CanRun(contract.code) { 60 // interpreter.Run(contract.code, input) 61 // } 62 // } 63 // ``` 64 CanRun([]byte) bool 65 } 66 67 // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports 68 // Read to get a variable amount of data from the hash state. Read is faster than Sum 69 // because it doesn't copy the internal state, but also modifies the internal state. 70 type keccakState interface { 71 hash.Hash 72 Read([]byte) (int, error) 73 } 74 75 // EVMInterpreter represents an EVM interpreter 76 type EVMInterpreter struct { 77 evm *EVM 78 cfg Config 79 80 intPool *intPool 81 82 hasher keccakState // Keccak256 hasher instance shared across opcodes 83 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 84 85 readOnly bool // Whether to throw on stateful modifications 86 returnData []byte // Last CALL's return data for subsequent reuse 87 } 88 89 // NewEVMInterpreter returns a new instance of the Interpreter. 90 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 91 // We use the STOP instruction whether to see 92 // the jump table was initialised. If it was not 93 // we'll set the default jump table. 94 if !cfg.JumpTable[STOP].valid { 95 var jt JumpTable 96 switch { 97 case evm.chainRules.IsIstanbul: 98 jt = istanbulInstructionSet 99 case evm.chainRules.IsConstantinople: 100 jt = constantinopleInstructionSet 101 case evm.chainRules.IsByzantium: 102 jt = byzantiumInstructionSet 103 case evm.chainRules.IsEIP158: 104 jt = spuriousDragonInstructionSet 105 case evm.chainRules.IsEIP150: 106 jt = tangerineWhistleInstructionSet 107 case evm.chainRules.IsHomestead: 108 jt = homesteadInstructionSet 109 default: 110 jt = frontierInstructionSet 111 } 112 for i, eip := range cfg.ExtraEips { 113 if err := EnableEIP(eip, &jt); err != nil { 114 // Disable it, so caller can check if it's activated or not 115 cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) 116 log.Error("EIP activation failed", "eip", eip, "error", err) 117 } 118 } 119 cfg.JumpTable = jt 120 } 121 122 return &EVMInterpreter{ 123 evm: evm, 124 cfg: cfg, 125 } 126 } 127 128 // Run loops and evaluates the contract's code with the given input data and returns 129 // the return byte-slice and an error if one occurred. 130 // 131 // It's important to note that any errors returned by the interpreter should be 132 // considered a revert-and-consume-all-gas operation except for 133 // errExecutionReverted which means revert-and-keep-gas-left. 134 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 135 if in.intPool == nil { 136 in.intPool = poolOfIntPools.get() 137 defer func() { 138 poolOfIntPools.put(in.intPool) 139 in.intPool = nil 140 }() 141 } 142 143 // Increment the call depth which is restricted to 1024 144 in.evm.depth++ 145 defer func() { in.evm.depth-- }() 146 147 // Make sure the readOnly is only set if we aren't in readOnly yet. 148 // This makes also sure that the readOnly flag isn't removed for child calls. 149 if readOnly && !in.readOnly { 150 in.readOnly = true 151 defer func() { in.readOnly = false }() 152 } 153 154 // Reset the previous call's return data. It's unimportant to preserve the old buffer 155 // as every returning call will return new data anyway. 156 in.returnData = nil 157 158 // Don't bother with the execution if there's no code. 159 if len(contract.Code) == 0 { 160 return nil, nil 161 } 162 163 var ( 164 op OpCode // current opcode 165 mem = NewMemory() // bound memory 166 stack = newstack() // local stack 167 // For optimisation reason we're using uint64 as the program counter. 168 // It's theoretically possible to go above 2^64. The YP defines the PC 169 // to be uint256. Practically much less so feasible. 170 pc = uint64(0) // program counter 171 cost uint64 172 // copies used by tracer 173 pcCopy uint64 // needed for the deferred Tracer 174 gasCopy uint64 // for Tracer to log gas remaining before execution 175 logged bool // deferred Tracer should ignore already logged steps 176 res []byte // result of the opcode execution function 177 ) 178 contract.Input = input 179 180 // Reclaim the stack as an int pool when the execution stops 181 defer func() { in.intPool.put(stack.data...) }() 182 183 if in.cfg.Debug { 184 defer func() { 185 if err != nil { 186 if !logged { 187 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 188 } else { 189 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 190 } 191 } 192 }() 193 } 194 // The Interpreter main run loop (contextual). This loop runs until either an 195 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 196 // the execution of one of the operations or until the done flag is set by the 197 // parent context. 198 for atomic.LoadInt32(&in.evm.abort) == 0 { 199 if in.cfg.Debug { 200 // Capture pre-execution values for tracing. 201 logged, pcCopy, gasCopy = false, pc, contract.Gas 202 } 203 204 // Get the operation from the jump table and validate the stack to ensure there are 205 // enough stack items available to perform the operation. 206 op = contract.GetOp(pc) 207 operation := in.cfg.JumpTable[op] 208 if !operation.valid { 209 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 210 } 211 // Validate stack 212 if sLen := stack.len(); sLen < operation.minStack { 213 return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack) 214 } else if sLen > operation.maxStack { 215 return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack) 216 } 217 // If the operation is valid, enforce and write restrictions 218 if in.readOnly && in.evm.chainRules.IsByzantium { 219 // If the interpreter is operating in readonly mode, make sure no 220 // state-modifying operation is performed. The 3rd stack item 221 // for a call operation is the value. Transferring value from one 222 // account to the others means the state is modified and should also 223 // return with an error. 224 if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) { 225 return nil, errWriteProtection 226 } 227 } 228 // Static portion of gas 229 cost = operation.constantGas // For tracing 230 if !contract.UseGas(operation.constantGas) { 231 return nil, ErrOutOfGas 232 } 233 234 var memorySize uint64 235 // calculate the new memory size and expand the memory to fit 236 // the operation 237 // Memory check needs to be done prior to evaluating the dynamic gas portion, 238 // to detect calculation overflows 239 if operation.memorySize != nil { 240 memSize, overflow := operation.memorySize(stack) 241 if overflow { 242 return nil, errGasUintOverflow 243 } 244 // memory is expanded in words of 32 bytes. Gas 245 // is also calculated in words. 246 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 247 return nil, errGasUintOverflow 248 } 249 } 250 // Dynamic portion of gas 251 // consume the gas and return an error if not enough gas is available. 252 // cost is explicitly set so that the capture state defer method can get the proper cost 253 if operation.dynamicGas != nil { 254 var dynamicCost uint64 255 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 256 cost += dynamicCost // total cost, for debug tracing 257 if err != nil || !contract.UseGas(dynamicCost) { 258 return nil, ErrOutOfGas 259 } 260 } 261 if memorySize > 0 { 262 mem.Resize(memorySize) 263 } 264 265 if in.cfg.Debug { 266 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 267 logged = true 268 } 269 270 // execute the operation 271 res, err = operation.execute(&pc, in, contract, mem, stack) 272 // verifyPool is a build flag. Pool verification makes sure the integrity 273 // of the integer pool by comparing values to a default value. 274 if verifyPool { 275 verifyIntegerPool(in.intPool) 276 } 277 // if the operation clears the return data (e.g. it has returning data) 278 // set the last return to the result of the operation. 279 if operation.returns { 280 in.returnData = res 281 } 282 283 switch { 284 case err != nil: 285 return nil, err 286 case operation.reverts: 287 return res, errExecutionReverted 288 case operation.halts: 289 return res, nil 290 case !operation.jumps: 291 pc++ 292 } 293 } 294 return nil, nil 295 } 296 297 // CanRun tells if the contract, passed as an argument, can be 298 // run by the current interpreter. 299 func (in *EVMInterpreter) CanRun(code []byte) bool { 300 return true 301 }