interpreter.go 11 KB

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