vm.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. "math/big"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. )
  27. // Config are the configuration options for the EVM
  28. type Config struct {
  29. Debug bool
  30. EnableJit bool
  31. ForceJit bool
  32. Tracer Tracer
  33. }
  34. // EVM is used to run Ethereum based contracts and will utilise the
  35. // passed environment to query external sources for state information.
  36. // The EVM will run the byte code VM or JIT VM based on the passed
  37. // configuration.
  38. type EVM struct {
  39. env Environment
  40. jumpTable vmJumpTable
  41. cfg Config
  42. gasTable params.GasTable
  43. }
  44. // New returns a new instance of the EVM.
  45. func New(env Environment, cfg Config) *EVM {
  46. return &EVM{
  47. env: env,
  48. jumpTable: newJumpTable(env.RuleSet(), env.BlockNumber()),
  49. cfg: cfg,
  50. gasTable: env.RuleSet().GasTable(env.BlockNumber()),
  51. }
  52. }
  53. // Run loops and evaluates the contract's code with the given input data
  54. func (evm *EVM) Run(contract *Contract, input []byte) (ret []byte, err error) {
  55. evm.env.SetDepth(evm.env.Depth() + 1)
  56. defer evm.env.SetDepth(evm.env.Depth() - 1)
  57. if contract.CodeAddr != nil {
  58. if p := Precompiled[contract.CodeAddr.Str()]; p != nil {
  59. return evm.RunPrecompiled(p, input, contract)
  60. }
  61. }
  62. // Don't bother with the execution if there's no code.
  63. if len(contract.Code) == 0 {
  64. return nil, nil
  65. }
  66. codehash := contract.CodeHash // codehash is used when doing jump dest caching
  67. if codehash == (common.Hash{}) {
  68. codehash = crypto.Keccak256Hash(contract.Code)
  69. }
  70. var program *Program
  71. if evm.cfg.EnableJit {
  72. // If the JIT is enabled check the status of the JIT program,
  73. // if it doesn't exist compile a new program in a separate
  74. // goroutine or wait for compilation to finish if the JIT is
  75. // forced.
  76. switch GetProgramStatus(codehash) {
  77. case progReady:
  78. return RunProgram(GetProgram(codehash), evm.env, contract, input)
  79. case progUnknown:
  80. if evm.cfg.ForceJit {
  81. // Create and compile program
  82. program = NewProgram(contract.Code)
  83. perr := CompileProgram(program)
  84. if perr == nil {
  85. return RunProgram(program, evm.env, contract, input)
  86. }
  87. glog.V(logger.Info).Infoln("error compiling program", err)
  88. } else {
  89. // create and compile the program. Compilation
  90. // is done in a separate goroutine
  91. program = NewProgram(contract.Code)
  92. go func() {
  93. err := CompileProgram(program)
  94. if err != nil {
  95. glog.V(logger.Info).Infoln("error compiling program", err)
  96. return
  97. }
  98. }()
  99. }
  100. }
  101. }
  102. var (
  103. caller = contract.caller
  104. code = contract.Code
  105. instrCount = 0
  106. op OpCode // current opcode
  107. mem = NewMemory() // bound memory
  108. stack = newstack() // local stack
  109. statedb = evm.env.Db() // current state
  110. // For optimisation reason we're using uint64 as the program counter.
  111. // It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
  112. pc = uint64(0) // program counter
  113. // jump evaluates and checks whether the given jump destination is a valid one
  114. // if valid move the `pc` otherwise return an error.
  115. jump = func(from uint64, to *big.Int) error {
  116. if !contract.jumpdests.has(codehash, code, to) {
  117. nop := contract.GetOp(to.Uint64())
  118. return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
  119. }
  120. pc = to.Uint64()
  121. return nil
  122. }
  123. newMemSize *big.Int
  124. cost *big.Int
  125. )
  126. contract.Input = input
  127. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  128. defer func() {
  129. if err != nil && evm.cfg.Debug {
  130. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.Depth(), err)
  131. }
  132. }()
  133. if glog.V(logger.Debug) {
  134. glog.Infof("running byte VM %x\n", codehash[:4])
  135. tstart := time.Now()
  136. defer func() {
  137. glog.Infof("byte VM %x done. time: %v instrc: %v\n", codehash[:4], time.Since(tstart), instrCount)
  138. }()
  139. }
  140. for ; ; instrCount++ {
  141. /*
  142. if EnableJit && it%100 == 0 {
  143. if program != nil && progStatus(atomic.LoadInt32(&program.status)) == progReady {
  144. // move execution
  145. fmt.Println("moved", it)
  146. glog.V(logger.Info).Infoln("Moved execution to JIT")
  147. return runProgram(program, pc, mem, stack, evm.env, contract, input)
  148. }
  149. }
  150. */
  151. // Get the memory location of pc
  152. op = contract.GetOp(pc)
  153. // calculate the new memory size and gas price for the current executing opcode
  154. newMemSize, cost, err = calculateGasAndSize(evm.gasTable, evm.env, contract, caller, op, statedb, mem, stack)
  155. if err != nil {
  156. return nil, err
  157. }
  158. // Use the calculated gas. When insufficient gas is present, use all gas and return an
  159. // Out Of Gas error
  160. if !contract.UseGas(cost) {
  161. return nil, OutOfGasError
  162. }
  163. // Resize the memory calculated previously
  164. mem.Resize(newMemSize.Uint64())
  165. // Add a log message
  166. if evm.cfg.Debug {
  167. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.Depth(), nil)
  168. }
  169. if opPtr := evm.jumpTable[op]; opPtr.valid {
  170. if opPtr.fn != nil {
  171. opPtr.fn(instruction{}, &pc, evm.env, contract, mem, stack)
  172. } else {
  173. switch op {
  174. case PC:
  175. opPc(instruction{data: new(big.Int).SetUint64(pc)}, &pc, evm.env, contract, mem, stack)
  176. case JUMP:
  177. if err := jump(pc, stack.pop()); err != nil {
  178. return nil, err
  179. }
  180. continue
  181. case JUMPI:
  182. pos, cond := stack.pop(), stack.pop()
  183. if cond.Cmp(common.BigTrue) >= 0 {
  184. if err := jump(pc, pos); err != nil {
  185. return nil, err
  186. }
  187. continue
  188. }
  189. case RETURN:
  190. offset, size := stack.pop(), stack.pop()
  191. ret := mem.GetPtr(offset.Int64(), size.Int64())
  192. return ret, nil
  193. case SUICIDE:
  194. opSuicide(instruction{}, nil, evm.env, contract, mem, stack)
  195. fallthrough
  196. case STOP: // Stop the contract
  197. return nil, nil
  198. }
  199. }
  200. } else {
  201. return nil, fmt.Errorf("Invalid opcode %x", op)
  202. }
  203. pc++
  204. }
  205. }
  206. // calculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
  207. // the operation. This does not reduce gas or resizes the memory.
  208. func calculateGasAndSize(gasTable params.GasTable, env Environment, contract *Contract, caller ContractRef, op OpCode, statedb Database, mem *Memory, stack *Stack) (*big.Int, *big.Int, error) {
  209. var (
  210. gas = new(big.Int)
  211. newMemSize *big.Int = new(big.Int)
  212. )
  213. err := baseCheck(op, stack, gas)
  214. if err != nil {
  215. return nil, nil, err
  216. }
  217. // stack Check, memory resize & gas phase
  218. switch op {
  219. case SUICIDE:
  220. // if suicide is not nil: homestead gas fork
  221. if gasTable.CreateBySuicide != nil {
  222. gas.Set(gasTable.Suicide)
  223. if !env.Db().Exist(common.BigToAddress(stack.data[len(stack.data)-1])) {
  224. gas.Add(gas, gasTable.CreateBySuicide)
  225. }
  226. }
  227. if !statedb.HasSuicided(contract.Address()) {
  228. statedb.AddRefund(params.SuicideRefundGas)
  229. }
  230. case EXTCODESIZE:
  231. gas.Set(gasTable.ExtcodeSize)
  232. case BALANCE:
  233. gas.Set(gasTable.Balance)
  234. case SLOAD:
  235. gas.Set(gasTable.SLoad)
  236. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  237. n := int(op - SWAP1 + 2)
  238. err := stack.require(n)
  239. if err != nil {
  240. return nil, nil, err
  241. }
  242. gas.Set(GasFastestStep)
  243. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  244. n := int(op - DUP1 + 1)
  245. err := stack.require(n)
  246. if err != nil {
  247. return nil, nil, err
  248. }
  249. gas.Set(GasFastestStep)
  250. case LOG0, LOG1, LOG2, LOG3, LOG4:
  251. n := int(op - LOG0)
  252. err := stack.require(n + 2)
  253. if err != nil {
  254. return nil, nil, err
  255. }
  256. mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
  257. gas.Add(gas, params.LogGas)
  258. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(n)), params.LogTopicGas))
  259. gas.Add(gas, new(big.Int).Mul(mSize, params.LogDataGas))
  260. newMemSize = calcMemSize(mStart, mSize)
  261. quadMemGas(mem, newMemSize, gas)
  262. case EXP:
  263. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), params.ExpByteGas))
  264. case SSTORE:
  265. err := stack.require(2)
  266. if err != nil {
  267. return nil, nil, err
  268. }
  269. var g *big.Int
  270. y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
  271. val := statedb.GetState(contract.Address(), common.BigToHash(x))
  272. // This checks for 3 scenario's and calculates gas accordingly
  273. // 1. From a zero-value address to a non-zero value (NEW VALUE)
  274. // 2. From a non-zero value address to a zero-value address (DELETE)
  275. // 3. From a non-zero to a non-zero (CHANGE)
  276. if common.EmptyHash(val) && !common.EmptyHash(common.BigToHash(y)) {
  277. // 0 => non 0
  278. g = params.SstoreSetGas
  279. } else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
  280. statedb.AddRefund(params.SstoreRefundGas)
  281. g = params.SstoreClearGas
  282. } else {
  283. // non 0 => non 0 (or 0 => 0)
  284. g = params.SstoreResetGas
  285. }
  286. gas.Set(g)
  287. case MLOAD:
  288. newMemSize = calcMemSize(stack.peek(), u256(32))
  289. quadMemGas(mem, newMemSize, gas)
  290. case MSTORE8:
  291. newMemSize = calcMemSize(stack.peek(), u256(1))
  292. quadMemGas(mem, newMemSize, gas)
  293. case MSTORE:
  294. newMemSize = calcMemSize(stack.peek(), u256(32))
  295. quadMemGas(mem, newMemSize, gas)
  296. case RETURN:
  297. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  298. quadMemGas(mem, newMemSize, gas)
  299. case SHA3:
  300. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  301. words := toWordSize(stack.data[stack.len()-2])
  302. gas.Add(gas, words.Mul(words, params.Sha3WordGas))
  303. quadMemGas(mem, newMemSize, gas)
  304. case CALLDATACOPY:
  305. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  306. words := toWordSize(stack.data[stack.len()-3])
  307. gas.Add(gas, words.Mul(words, params.CopyGas))
  308. quadMemGas(mem, newMemSize, gas)
  309. case CODECOPY:
  310. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  311. words := toWordSize(stack.data[stack.len()-3])
  312. gas.Add(gas, words.Mul(words, params.CopyGas))
  313. quadMemGas(mem, newMemSize, gas)
  314. case EXTCODECOPY:
  315. gas.Set(gasTable.ExtcodeCopy)
  316. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
  317. words := toWordSize(stack.data[stack.len()-4])
  318. gas.Add(gas, words.Mul(words, params.CopyGas))
  319. quadMemGas(mem, newMemSize, gas)
  320. case CREATE:
  321. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
  322. quadMemGas(mem, newMemSize, gas)
  323. case CALL, CALLCODE:
  324. gas.Set(gasTable.Calls)
  325. if op == CALL {
  326. if !env.Db().Exist(common.BigToAddress(stack.data[stack.len()-2])) {
  327. gas.Add(gas, params.CallNewAccountGas)
  328. }
  329. }
  330. if len(stack.data[stack.len()-3].Bytes()) > 0 {
  331. gas.Add(gas, params.CallValueTransferGas)
  332. }
  333. x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
  334. y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
  335. newMemSize = common.BigMax(x, y)
  336. quadMemGas(mem, newMemSize, gas)
  337. cg := callGas(gasTable, contract.Gas, gas, stack.data[stack.len()-1])
  338. // Replace the stack item with the new gas calculation. This means that
  339. // either the original item is left on the stack or the item is replaced by:
  340. // (availableGas - gas) * 63 / 64
  341. // We replace the stack item so that it's available when the opCall instruction is
  342. // called. This information is otherwise lost due to the dependency on *current*
  343. // available gas.
  344. stack.data[stack.len()-1] = cg
  345. gas.Add(gas, cg)
  346. case DELEGATECALL:
  347. gas.Set(gasTable.Calls)
  348. x := calcMemSize(stack.data[stack.len()-5], stack.data[stack.len()-6])
  349. y := calcMemSize(stack.data[stack.len()-3], stack.data[stack.len()-4])
  350. newMemSize = common.BigMax(x, y)
  351. quadMemGas(mem, newMemSize, gas)
  352. cg := callGas(gasTable, contract.Gas, gas, stack.data[stack.len()-1])
  353. // Replace the stack item with the new gas calculation. This means that
  354. // either the original item is left on the stack or the item is replaced by:
  355. // (availableGas - gas) * 63 / 64
  356. // We replace the stack item so that it's available when the opCall instruction is
  357. // called.
  358. stack.data[stack.len()-1] = cg
  359. gas.Add(gas, cg)
  360. }
  361. return newMemSize, gas, nil
  362. }
  363. // RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
  364. func (evm *EVM) RunPrecompiled(p *PrecompiledAccount, input []byte, contract *Contract) (ret []byte, err error) {
  365. gas := p.Gas(len(input))
  366. if contract.UseGas(gas) {
  367. ret = p.Call(input)
  368. return ret, nil
  369. } else {
  370. return nil, OutOfGasError
  371. }
  372. }