vm.go 14 KB

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