interpreter.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. "hash"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/common/math"
  21. "github.com/ethereum/go-ethereum/log"
  22. )
  23. // Config are the configuration options for the Interpreter
  24. type Config struct {
  25. Debug bool // Enables debugging
  26. Tracer EVMLogger // Opcode logger
  27. NoBaseFee bool // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
  28. EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages
  29. JumpTable *JumpTable // EVM instruction table, automatically populated if unset
  30. ExtraEips []int // Additional EIPS that are to be enabled
  31. }
  32. // ScopeContext contains the things that are per-call, such as stack and memory,
  33. // but not transients like pc and gas
  34. type ScopeContext struct {
  35. Memory *Memory
  36. Stack *Stack
  37. Contract *Contract
  38. }
  39. // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  40. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  41. // because it doesn't copy the internal state, but also modifies the internal state.
  42. type keccakState interface {
  43. hash.Hash
  44. Read([]byte) (int, error)
  45. }
  46. // EVMInterpreter represents an EVM interpreter
  47. type EVMInterpreter struct {
  48. evm *EVM
  49. cfg Config
  50. hasher keccakState // Keccak256 hasher instance shared across opcodes
  51. hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
  52. readOnly bool // Whether to throw on stateful modifications
  53. returnData []byte // Last CALL's return data for subsequent reuse
  54. }
  55. // NewEVMInterpreter returns a new instance of the Interpreter.
  56. func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
  57. // If jump table was not initialised we set the default one.
  58. if cfg.JumpTable == nil {
  59. switch {
  60. case evm.chainRules.IsMerge:
  61. cfg.JumpTable = &mergeInstructionSet
  62. case evm.chainRules.IsLondon:
  63. cfg.JumpTable = &londonInstructionSet
  64. case evm.chainRules.IsBerlin:
  65. cfg.JumpTable = &berlinInstructionSet
  66. case evm.chainRules.IsIstanbul:
  67. cfg.JumpTable = &istanbulInstructionSet
  68. case evm.chainRules.IsConstantinople:
  69. cfg.JumpTable = &constantinopleInstructionSet
  70. case evm.chainRules.IsByzantium:
  71. cfg.JumpTable = &byzantiumInstructionSet
  72. case evm.chainRules.IsEIP158:
  73. cfg.JumpTable = &spuriousDragonInstructionSet
  74. case evm.chainRules.IsEIP150:
  75. cfg.JumpTable = &tangerineWhistleInstructionSet
  76. case evm.chainRules.IsHomestead:
  77. cfg.JumpTable = &homesteadInstructionSet
  78. default:
  79. cfg.JumpTable = &frontierInstructionSet
  80. }
  81. for i, eip := range cfg.ExtraEips {
  82. copy := *cfg.JumpTable
  83. if err := EnableEIP(eip, &copy); err != nil {
  84. // Disable it, so caller can check if it's activated or not
  85. cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
  86. log.Error("EIP activation failed", "eip", eip, "error", err)
  87. }
  88. cfg.JumpTable = &copy
  89. }
  90. }
  91. return &EVMInterpreter{
  92. evm: evm,
  93. cfg: cfg,
  94. }
  95. }
  96. // Run loops and evaluates the contract's code with the given input data and returns
  97. // the return byte-slice and an error if one occurred.
  98. //
  99. // It's important to note that any errors returned by the interpreter should be
  100. // considered a revert-and-consume-all-gas operation except for
  101. // ErrExecutionReverted which means revert-and-keep-gas-left.
  102. func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
  103. // Increment the call depth which is restricted to 1024
  104. in.evm.depth++
  105. defer func() { in.evm.depth-- }()
  106. // Make sure the readOnly is only set if we aren't in readOnly yet.
  107. // This also makes sure that the readOnly flag isn't removed for child calls.
  108. if readOnly && !in.readOnly {
  109. in.readOnly = true
  110. defer func() { in.readOnly = false }()
  111. }
  112. // Reset the previous call's return data. It's unimportant to preserve the old buffer
  113. // as every returning call will return new data anyway.
  114. in.returnData = nil
  115. // Don't bother with the execution if there's no code.
  116. if len(contract.Code) == 0 {
  117. return nil, nil
  118. }
  119. var (
  120. op OpCode // current opcode
  121. mem = NewMemory() // bound memory
  122. stack = newstack() // local stack
  123. callContext = &ScopeContext{
  124. Memory: mem,
  125. Stack: stack,
  126. Contract: contract,
  127. }
  128. // For optimisation reason we're using uint64 as the program counter.
  129. // It's theoretically possible to go above 2^64. The YP defines the PC
  130. // to be uint256. Practically much less so feasible.
  131. pc = uint64(0) // program counter
  132. cost uint64
  133. // copies used by tracer
  134. pcCopy uint64 // needed for the deferred EVMLogger
  135. gasCopy uint64 // for EVMLogger to log gas remaining before execution
  136. logged bool // deferred EVMLogger should ignore already logged steps
  137. res []byte // result of the opcode execution function
  138. )
  139. // Don't move this deferred function, it's placed before the capturestate-deferred method,
  140. // so that it get's executed _after_: the capturestate needs the stacks before
  141. // they are returned to the pools
  142. defer func() {
  143. returnStack(stack)
  144. }()
  145. contract.Input = input
  146. if in.cfg.Debug {
  147. defer func() {
  148. if err != nil {
  149. if !logged {
  150. in.cfg.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
  151. } else {
  152. in.cfg.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err)
  153. }
  154. }
  155. }()
  156. }
  157. // The Interpreter main run loop (contextual). This loop runs until either an
  158. // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
  159. // the execution of one of the operations or until the done flag is set by the
  160. // parent context.
  161. for {
  162. if in.cfg.Debug {
  163. // Capture pre-execution values for tracing.
  164. logged, pcCopy, gasCopy = false, pc, contract.Gas
  165. }
  166. // Get the operation from the jump table and validate the stack to ensure there are
  167. // enough stack items available to perform the operation.
  168. op = contract.GetOp(pc)
  169. operation := in.cfg.JumpTable[op]
  170. cost = operation.constantGas // For tracing
  171. // Validate stack
  172. if sLen := stack.len(); sLen < operation.minStack {
  173. return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
  174. } else if sLen > operation.maxStack {
  175. return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
  176. }
  177. if !contract.UseGas(cost) {
  178. return nil, ErrOutOfGas
  179. }
  180. if operation.dynamicGas != nil {
  181. // All ops with a dynamic memory usage also has a dynamic gas cost.
  182. var memorySize uint64
  183. // calculate the new memory size and expand the memory to fit
  184. // the operation
  185. // Memory check needs to be done prior to evaluating the dynamic gas portion,
  186. // to detect calculation overflows
  187. if operation.memorySize != nil {
  188. memSize, overflow := operation.memorySize(stack)
  189. if overflow {
  190. return nil, ErrGasUintOverflow
  191. }
  192. // memory is expanded in words of 32 bytes. Gas
  193. // is also calculated in words.
  194. if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
  195. return nil, ErrGasUintOverflow
  196. }
  197. }
  198. // Consume the gas and return an error if not enough gas is available.
  199. // cost is explicitly set so that the capture state defer method can get the proper cost
  200. var dynamicCost uint64
  201. dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
  202. cost += dynamicCost // for tracing
  203. if err != nil || !contract.UseGas(dynamicCost) {
  204. return nil, ErrOutOfGas
  205. }
  206. // Do tracing before memory expansion
  207. if in.cfg.Debug {
  208. in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
  209. logged = true
  210. }
  211. if memorySize > 0 {
  212. mem.Resize(memorySize)
  213. }
  214. } else if in.cfg.Debug {
  215. in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
  216. logged = true
  217. }
  218. // execute the operation
  219. res, err = operation.execute(&pc, in, callContext)
  220. if err != nil {
  221. break
  222. }
  223. pc++
  224. }
  225. if err == errStopToken {
  226. err = nil // clear stop token error
  227. }
  228. return res, err
  229. }