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