github.com/edxfund/validator@v1.8.16-0.20181020093046-c1def72855da/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 "sync/atomic" 22 23 "github.com/EDXFund/Validator/common/math" 24 "github.com/EDXFund/Validator/params" 25 ) 26 27 // Config are the configuration options for the Interpreter 28 type Config struct { 29 // Debug enabled debugging Interpreter options 30 Debug bool 31 // Tracer is the op code logger 32 Tracer Tracer 33 // NoRecursion disabled Interpreter call, callcode, 34 // delegate call and create. 35 NoRecursion bool 36 // Enable recording of SHA3/keccak preimages 37 EnablePreimageRecording bool 38 // JumpTable contains the EVM instruction table. This 39 // may be left uninitialised and will be set to the default 40 // table. 41 JumpTable [256]operation 42 } 43 44 // Interpreter is used to run Ethereum based contracts and will utilise the 45 // passed environment to query external sources for state information. 46 // The Interpreter will run the byte code VM based on the passed 47 // configuration. 48 type Interpreter interface { 49 // Run loops and evaluates the contract's code with the given input data and returns 50 // the return byte-slice and an error if one occurred. 51 Run(contract *Contract, input []byte, static bool) ([]byte, error) 52 // CanRun tells if the contract, passed as an argument, can be 53 // run by the current interpreter. This is meant so that the 54 // caller can do something like: 55 // 56 // ```golang 57 // for _, interpreter := range interpreters { 58 // if interpreter.CanRun(contract.code) { 59 // interpreter.Run(contract.code, input) 60 // } 61 // } 62 // ``` 63 CanRun([]byte) bool 64 } 65 66 // EVMInterpreter represents an EVM interpreter 67 type EVMInterpreter struct { 68 evm *EVM 69 cfg Config 70 gasTable params.GasTable 71 intPool *intPool 72 73 readOnly bool // Whether to throw on stateful modifications 74 returnData []byte // Last CALL's return data for subsequent reuse 75 } 76 77 // NewEVMInterpreter returns a new instance of the Interpreter. 78 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 79 // We use the STOP instruction whether to see 80 // the jump table was initialised. If it was not 81 // we'll set the default jump table. 82 if !cfg.JumpTable[STOP].valid { 83 switch { 84 case evm.ChainConfig().IsConstantinople(evm.BlockNumber): 85 cfg.JumpTable = constantinopleInstructionSet 86 case evm.ChainConfig().IsByzantium(evm.BlockNumber): 87 cfg.JumpTable = byzantiumInstructionSet 88 case evm.ChainConfig().IsHomestead(evm.BlockNumber): 89 cfg.JumpTable = homesteadInstructionSet 90 default: 91 cfg.JumpTable = frontierInstructionSet 92 } 93 } 94 95 return &EVMInterpreter{ 96 evm: evm, 97 cfg: cfg, 98 gasTable: evm.ChainConfig().GasTable(evm.BlockNumber), 99 } 100 } 101 102 func (in *EVMInterpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error { 103 if in.evm.chainRules.IsByzantium { 104 if in.readOnly { 105 // If the interpreter is operating in readonly mode, make sure no 106 // state-modifying operation is performed. The 3rd stack item 107 // for a call operation is the value. Transferring value from one 108 // account to the others means the state is modified and should also 109 // return with an error. 110 if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) { 111 return errWriteProtection 112 } 113 } 114 } 115 return nil 116 } 117 118 // Run loops and evaluates the contract's code with the given input data and returns 119 // the return byte-slice and an error if one occurred. 120 // 121 // It's important to note that any errors returned by the interpreter should be 122 // considered a revert-and-consume-all-gas operation except for 123 // errExecutionReverted which means revert-and-keep-gas-left. 124 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 125 if in.intPool == nil { 126 in.intPool = poolOfIntPools.get() 127 defer func() { 128 poolOfIntPools.put(in.intPool) 129 in.intPool = nil 130 }() 131 } 132 133 // Increment the call depth which is restricted to 1024 134 in.evm.depth++ 135 defer func() { in.evm.depth-- }() 136 137 // Make sure the readOnly is only set if we aren't in readOnly yet. 138 // This makes also sure that the readOnly flag isn't removed for child calls. 139 if readOnly && !in.readOnly { 140 in.readOnly = true 141 defer func() { in.readOnly = false }() 142 } 143 144 // Reset the previous call's return data. It's unimportant to preserve the old buffer 145 // as every returning call will return new data anyway. 146 in.returnData = nil 147 148 // Don't bother with the execution if there's no code. 149 if len(contract.Code) == 0 { 150 return nil, nil 151 } 152 153 var ( 154 op OpCode // current opcode 155 mem = NewMemory() // bound memory 156 stack = newstack() // local stack 157 // For optimisation reason we're using uint64 as the program counter. 158 // It's theoretically possible to go above 2^64. The YP defines the PC 159 // to be uint256. Practically much less so feasible. 160 pc = uint64(0) // program counter 161 cost uint64 162 // copies used by tracer 163 pcCopy uint64 // needed for the deferred Tracer 164 gasCopy uint64 // for Tracer to log gas remaining before execution 165 logged bool // deferred Tracer should ignore already logged steps 166 ) 167 contract.Input = input 168 169 // Reclaim the stack as an int pool when the execution stops 170 defer func() { in.intPool.put(stack.data...) }() 171 172 if in.cfg.Debug { 173 defer func() { 174 if err != nil { 175 if !logged { 176 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 177 } else { 178 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 179 } 180 } 181 }() 182 } 183 // The Interpreter main run loop (contextual). This loop runs until either an 184 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 185 // the execution of one of the operations or until the done flag is set by the 186 // parent context. 187 for atomic.LoadInt32(&in.evm.abort) == 0 { 188 if in.cfg.Debug { 189 // Capture pre-execution values for tracing. 190 logged, pcCopy, gasCopy = false, pc, contract.Gas 191 } 192 193 // Get the operation from the jump table and validate the stack to ensure there are 194 // enough stack items available to perform the operation. 195 op = contract.GetOp(pc) 196 operation := in.cfg.JumpTable[op] 197 if !operation.valid { 198 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 199 } 200 if err := operation.validateStack(stack); err != nil { 201 return nil, err 202 } 203 // If the operation is valid, enforce and write restrictions 204 if err := in.enforceRestrictions(op, operation, stack); err != nil { 205 return nil, err 206 } 207 208 var memorySize uint64 209 // calculate the new memory size and expand the memory to fit 210 // the operation 211 if operation.memorySize != nil { 212 memSize, overflow := bigUint64(operation.memorySize(stack)) 213 if overflow { 214 return nil, errGasUintOverflow 215 } 216 // memory is expanded in words of 32 bytes. Gas 217 // is also calculated in words. 218 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 219 return nil, errGasUintOverflow 220 } 221 } 222 // consume the gas and return an error if not enough gas is available. 223 // cost is explicitly set so that the capture state defer method can get the proper cost 224 cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize) 225 if err != nil || !contract.UseGas(cost) { 226 return nil, ErrOutOfGas 227 } 228 if memorySize > 0 { 229 mem.Resize(memorySize) 230 } 231 232 if in.cfg.Debug { 233 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 234 logged = true 235 } 236 237 // execute the operation 238 res, err := operation.execute(&pc, in, contract, mem, stack) 239 // verifyPool is a build flag. Pool verification makes sure the integrity 240 // of the integer pool by comparing values to a default value. 241 if verifyPool { 242 verifyIntegerPool(in.intPool) 243 } 244 // if the operation clears the return data (e.g. it has returning data) 245 // set the last return to the result of the operation. 246 if operation.returns { 247 in.returnData = res 248 } 249 250 switch { 251 case err != nil: 252 return nil, err 253 case operation.reverts: 254 return res, errExecutionReverted 255 case operation.halts: 256 return res, nil 257 case !operation.jumps: 258 pc++ 259 } 260 } 261 return nil, nil 262 } 263 264 // CanRun tells if the contract, passed as an argument, can be 265 // run by the current interpreter. 266 func (in *EVMInterpreter) CanRun(code []byte) bool { 267 return true 268 }