vm.go 14 KB

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