vm.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 implements the Ethereum Virtual Machine.
  17. package vm
  18. import (
  19. "fmt"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/params"
  27. )
  28. // Vm implements VirtualMachine
  29. type Vm struct {
  30. env Environment
  31. }
  32. // New returns a new Virtual Machine
  33. func New(env Environment) *Vm {
  34. return &Vm{env: env}
  35. }
  36. // Run loops and evaluates the contract's code with the given input data
  37. func (self *Vm) Run(context *Context, input []byte) (ret []byte, err error) {
  38. self.env.SetDepth(self.env.Depth() + 1)
  39. defer self.env.SetDepth(self.env.Depth() - 1)
  40. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  41. defer func() {
  42. if err != nil {
  43. // In case of a VM exception (known exceptions) all gas consumed (panics NOT included).
  44. context.UseGas(context.Gas)
  45. ret = context.Return(nil)
  46. }
  47. }()
  48. if context.CodeAddr != nil {
  49. if p := Precompiled[context.CodeAddr.Str()]; p != nil {
  50. return self.RunPrecompiled(p, input, context)
  51. }
  52. }
  53. var (
  54. codehash = crypto.Sha3Hash(context.Code) // codehash is used when doing jump dest caching
  55. program *Program
  56. )
  57. if EnableJit {
  58. // Fetch program status.
  59. // * If ready run using JIT
  60. // * If unknown, compile in a seperate goroutine
  61. // * If forced wait for compilation and run once done
  62. if status := GetProgramStatus(codehash); status == progReady {
  63. return RunProgram(GetProgram(codehash), self.env, context, input)
  64. } else if status == progUnknown {
  65. if ForceJit {
  66. // Create and compile program
  67. program = NewProgram(context.Code)
  68. perr := CompileProgram(program)
  69. if perr == nil {
  70. return RunProgram(program, self.env, context, input)
  71. }
  72. glog.V(logger.Info).Infoln("error compiling program", err)
  73. } else {
  74. // create and compile the program. Compilation
  75. // is done in a seperate goroutine
  76. program = NewProgram(context.Code)
  77. go func() {
  78. err := CompileProgram(program)
  79. if err != nil {
  80. glog.V(logger.Info).Infoln("error compiling program", err)
  81. return
  82. }
  83. }()
  84. }
  85. }
  86. }
  87. var (
  88. caller = context.caller
  89. code = context.Code
  90. value = context.value
  91. price = context.Price
  92. op OpCode // current opcode
  93. mem = NewMemory() // bound memory
  94. stack = newstack() // local stack
  95. statedb = self.env.State() // current state
  96. // For optimisation reason we're using uint64 as the program counter.
  97. // It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Pratically much less so feasible.
  98. pc = uint64(0) // program counter
  99. // jump evaluates and checks whether the given jump destination is a valid one
  100. // if valid move the `pc` otherwise return an error.
  101. jump = func(from uint64, to *big.Int) error {
  102. if !context.jumpdests.has(codehash, code, to) {
  103. nop := context.GetOp(to.Uint64())
  104. return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
  105. }
  106. pc = to.Uint64()
  107. return nil
  108. }
  109. newMemSize *big.Int
  110. cost *big.Int
  111. )
  112. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  113. defer func() {
  114. if err != nil {
  115. self.log(pc, op, context.Gas, cost, mem, stack, context, err)
  116. }
  117. }()
  118. // Don't bother with the execution if there's no code.
  119. if len(code) == 0 {
  120. return context.Return(nil), nil
  121. }
  122. for {
  123. // Overhead of the atomic read might not be worth it
  124. /* TODO this still causes a few issues in the tests
  125. if program != nil && progStatus(atomic.LoadInt32(&program.status)) == progReady {
  126. // move execution
  127. glog.V(logger.Info).Infoln("Moved execution to JIT")
  128. return runProgram(program, pc, mem, stack, self.env, context, input)
  129. }
  130. */
  131. // The base for all big integer arithmetic
  132. base := new(big.Int)
  133. // Get the memory location of pc
  134. op = context.GetOp(pc)
  135. // calculate the new memory size and gas price for the current executing opcode
  136. newMemSize, cost, err = calculateGasAndSize(self.env, context, caller, op, statedb, mem, stack)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // Use the calculated gas. When insufficient gas is present, use all gas and return an
  141. // Out Of Gas error
  142. if !context.UseGas(cost) {
  143. return nil, OutOfGasError
  144. }
  145. // Resize the memory calculated previously
  146. mem.Resize(newMemSize.Uint64())
  147. // Add a log message
  148. self.log(pc, op, context.Gas, cost, mem, stack, context, nil)
  149. switch op {
  150. case ADD:
  151. x, y := stack.pop(), stack.pop()
  152. base.Add(x, y)
  153. U256(base)
  154. // pop result back on the stack
  155. stack.push(base)
  156. case SUB:
  157. x, y := stack.pop(), stack.pop()
  158. base.Sub(x, y)
  159. U256(base)
  160. // pop result back on the stack
  161. stack.push(base)
  162. case MUL:
  163. x, y := stack.pop(), stack.pop()
  164. base.Mul(x, y)
  165. U256(base)
  166. // pop result back on the stack
  167. stack.push(base)
  168. case DIV:
  169. x, y := stack.pop(), stack.pop()
  170. if y.Cmp(common.Big0) != 0 {
  171. base.Div(x, y)
  172. }
  173. U256(base)
  174. // pop result back on the stack
  175. stack.push(base)
  176. case SDIV:
  177. x, y := S256(stack.pop()), S256(stack.pop())
  178. if y.Cmp(common.Big0) == 0 {
  179. base.Set(common.Big0)
  180. } else {
  181. n := new(big.Int)
  182. if new(big.Int).Mul(x, y).Cmp(common.Big0) < 0 {
  183. n.SetInt64(-1)
  184. } else {
  185. n.SetInt64(1)
  186. }
  187. base.Div(x.Abs(x), y.Abs(y)).Mul(base, n)
  188. U256(base)
  189. }
  190. stack.push(base)
  191. case MOD:
  192. x, y := stack.pop(), stack.pop()
  193. if y.Cmp(common.Big0) == 0 {
  194. base.Set(common.Big0)
  195. } else {
  196. base.Mod(x, y)
  197. }
  198. U256(base)
  199. stack.push(base)
  200. case SMOD:
  201. x, y := S256(stack.pop()), S256(stack.pop())
  202. if y.Cmp(common.Big0) == 0 {
  203. base.Set(common.Big0)
  204. } else {
  205. n := new(big.Int)
  206. if x.Cmp(common.Big0) < 0 {
  207. n.SetInt64(-1)
  208. } else {
  209. n.SetInt64(1)
  210. }
  211. base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n)
  212. U256(base)
  213. }
  214. stack.push(base)
  215. case EXP:
  216. x, y := stack.pop(), stack.pop()
  217. base.Exp(x, y, Pow256)
  218. U256(base)
  219. stack.push(base)
  220. case SIGNEXTEND:
  221. back := stack.pop()
  222. if back.Cmp(big.NewInt(31)) < 0 {
  223. bit := uint(back.Uint64()*8 + 7)
  224. num := stack.pop()
  225. mask := new(big.Int).Lsh(common.Big1, bit)
  226. mask.Sub(mask, common.Big1)
  227. if common.BitTest(num, int(bit)) {
  228. num.Or(num, mask.Not(mask))
  229. } else {
  230. num.And(num, mask)
  231. }
  232. num = U256(num)
  233. stack.push(num)
  234. }
  235. case NOT:
  236. stack.push(U256(new(big.Int).Not(stack.pop())))
  237. case LT:
  238. x, y := stack.pop(), stack.pop()
  239. // x < y
  240. if x.Cmp(y) < 0 {
  241. stack.push(common.BigTrue)
  242. } else {
  243. stack.push(common.BigFalse)
  244. }
  245. case GT:
  246. x, y := stack.pop(), stack.pop()
  247. // x > y
  248. if x.Cmp(y) > 0 {
  249. stack.push(common.BigTrue)
  250. } else {
  251. stack.push(common.BigFalse)
  252. }
  253. case SLT:
  254. x, y := S256(stack.pop()), S256(stack.pop())
  255. // x < y
  256. if x.Cmp(S256(y)) < 0 {
  257. stack.push(common.BigTrue)
  258. } else {
  259. stack.push(common.BigFalse)
  260. }
  261. case SGT:
  262. x, y := S256(stack.pop()), S256(stack.pop())
  263. // x > y
  264. if x.Cmp(y) > 0 {
  265. stack.push(common.BigTrue)
  266. } else {
  267. stack.push(common.BigFalse)
  268. }
  269. case EQ:
  270. x, y := stack.pop(), stack.pop()
  271. // x == y
  272. if x.Cmp(y) == 0 {
  273. stack.push(common.BigTrue)
  274. } else {
  275. stack.push(common.BigFalse)
  276. }
  277. case ISZERO:
  278. x := stack.pop()
  279. if x.Cmp(common.BigFalse) > 0 {
  280. stack.push(common.BigFalse)
  281. } else {
  282. stack.push(common.BigTrue)
  283. }
  284. case AND:
  285. x, y := stack.pop(), stack.pop()
  286. stack.push(base.And(x, y))
  287. case OR:
  288. x, y := stack.pop(), stack.pop()
  289. stack.push(base.Or(x, y))
  290. case XOR:
  291. x, y := stack.pop(), stack.pop()
  292. stack.push(base.Xor(x, y))
  293. case BYTE:
  294. th, val := stack.pop(), stack.pop()
  295. if th.Cmp(big.NewInt(32)) < 0 {
  296. byt := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))
  297. base.Set(byt)
  298. } else {
  299. base.Set(common.BigFalse)
  300. }
  301. stack.push(base)
  302. case ADDMOD:
  303. x := stack.pop()
  304. y := stack.pop()
  305. z := stack.pop()
  306. if z.Cmp(Zero) > 0 {
  307. add := new(big.Int).Add(x, y)
  308. base.Mod(add, z)
  309. base = U256(base)
  310. }
  311. stack.push(base)
  312. case MULMOD:
  313. x := stack.pop()
  314. y := stack.pop()
  315. z := stack.pop()
  316. if z.Cmp(Zero) > 0 {
  317. mul := new(big.Int).Mul(x, y)
  318. base.Mod(mul, z)
  319. U256(base)
  320. }
  321. stack.push(base)
  322. case SHA3:
  323. offset, size := stack.pop(), stack.pop()
  324. data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64()))
  325. stack.push(common.BigD(data))
  326. case ADDRESS:
  327. stack.push(common.Bytes2Big(context.Address().Bytes()))
  328. case BALANCE:
  329. addr := common.BigToAddress(stack.pop())
  330. balance := statedb.GetBalance(addr)
  331. stack.push(new(big.Int).Set(balance))
  332. case ORIGIN:
  333. origin := self.env.Origin()
  334. stack.push(origin.Big())
  335. case CALLER:
  336. caller := context.caller.Address()
  337. stack.push(common.Bytes2Big(caller.Bytes()))
  338. case CALLVALUE:
  339. stack.push(new(big.Int).Set(value))
  340. case CALLDATALOAD:
  341. data := getData(input, stack.pop(), common.Big32)
  342. stack.push(common.Bytes2Big(data))
  343. case CALLDATASIZE:
  344. l := int64(len(input))
  345. stack.push(big.NewInt(l))
  346. case CALLDATACOPY:
  347. var (
  348. mOff = stack.pop()
  349. cOff = stack.pop()
  350. l = stack.pop()
  351. )
  352. data := getData(input, cOff, l)
  353. mem.Set(mOff.Uint64(), l.Uint64(), data)
  354. case CODESIZE, EXTCODESIZE:
  355. var code []byte
  356. if op == EXTCODESIZE {
  357. addr := common.BigToAddress(stack.pop())
  358. code = statedb.GetCode(addr)
  359. } else {
  360. code = context.Code
  361. }
  362. l := big.NewInt(int64(len(code)))
  363. stack.push(l)
  364. case CODECOPY, EXTCODECOPY:
  365. var code []byte
  366. if op == EXTCODECOPY {
  367. addr := common.BigToAddress(stack.pop())
  368. code = statedb.GetCode(addr)
  369. } else {
  370. code = context.Code
  371. }
  372. var (
  373. mOff = stack.pop()
  374. cOff = stack.pop()
  375. l = stack.pop()
  376. )
  377. codeCopy := getData(code, cOff, l)
  378. mem.Set(mOff.Uint64(), l.Uint64(), codeCopy)
  379. case GASPRICE:
  380. stack.push(new(big.Int).Set(context.Price))
  381. case BLOCKHASH:
  382. num := stack.pop()
  383. n := new(big.Int).Sub(self.env.BlockNumber(), common.Big257)
  384. if num.Cmp(n) > 0 && num.Cmp(self.env.BlockNumber()) < 0 {
  385. stack.push(self.env.GetHash(num.Uint64()).Big())
  386. } else {
  387. stack.push(common.Big0)
  388. }
  389. case COINBASE:
  390. coinbase := self.env.Coinbase()
  391. stack.push(coinbase.Big())
  392. case TIMESTAMP:
  393. time := self.env.Time()
  394. stack.push(new(big.Int).SetUint64(time))
  395. case NUMBER:
  396. number := self.env.BlockNumber()
  397. stack.push(U256(number))
  398. case DIFFICULTY:
  399. difficulty := self.env.Difficulty()
  400. stack.push(new(big.Int).Set(difficulty))
  401. case GASLIMIT:
  402. stack.push(new(big.Int).Set(self.env.GasLimit()))
  403. case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
  404. size := uint64(op - PUSH1 + 1)
  405. byts := getData(code, new(big.Int).SetUint64(pc+1), new(big.Int).SetUint64(size))
  406. // push value to stack
  407. stack.push(common.Bytes2Big(byts))
  408. pc += size
  409. case POP:
  410. stack.pop()
  411. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  412. n := int(op - DUP1 + 1)
  413. stack.dup(n)
  414. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  415. n := int(op - SWAP1 + 2)
  416. stack.swap(n)
  417. case LOG0, LOG1, LOG2, LOG3, LOG4:
  418. n := int(op - LOG0)
  419. topics := make([]common.Hash, n)
  420. mStart, mSize := stack.pop(), stack.pop()
  421. for i := 0; i < n; i++ {
  422. topics[i] = common.BigToHash(stack.pop())
  423. }
  424. data := mem.Get(mStart.Int64(), mSize.Int64())
  425. log := state.NewLog(context.Address(), topics, data, self.env.BlockNumber().Uint64())
  426. self.env.AddLog(log)
  427. case MLOAD:
  428. offset := stack.pop()
  429. val := common.BigD(mem.Get(offset.Int64(), 32))
  430. stack.push(val)
  431. case MSTORE:
  432. // pop value of the stack
  433. mStart, val := stack.pop(), stack.pop()
  434. mem.Set(mStart.Uint64(), 32, common.BigToBytes(val, 256))
  435. case MSTORE8:
  436. off, val := stack.pop().Int64(), stack.pop().Int64()
  437. mem.store[off] = byte(val & 0xff)
  438. case SLOAD:
  439. loc := common.BigToHash(stack.pop())
  440. val := statedb.GetState(context.Address(), loc).Big()
  441. stack.push(val)
  442. case SSTORE:
  443. loc := common.BigToHash(stack.pop())
  444. val := stack.pop()
  445. statedb.SetState(context.Address(), loc, common.BigToHash(val))
  446. case JUMP:
  447. if err := jump(pc, stack.pop()); err != nil {
  448. return nil, err
  449. }
  450. continue
  451. case JUMPI:
  452. pos, cond := stack.pop(), stack.pop()
  453. if cond.Cmp(common.BigTrue) >= 0 {
  454. if err := jump(pc, pos); err != nil {
  455. return nil, err
  456. }
  457. continue
  458. }
  459. case JUMPDEST:
  460. case PC:
  461. stack.push(new(big.Int).SetUint64(pc))
  462. case MSIZE:
  463. stack.push(big.NewInt(int64(mem.Len())))
  464. case GAS:
  465. stack.push(new(big.Int).Set(context.Gas))
  466. case CREATE:
  467. var (
  468. value = stack.pop()
  469. offset, size = stack.pop(), stack.pop()
  470. input = mem.Get(offset.Int64(), size.Int64())
  471. gas = new(big.Int).Set(context.Gas)
  472. addr common.Address
  473. )
  474. context.UseGas(context.Gas)
  475. ret, suberr, ref := self.env.Create(context, input, gas, price, value)
  476. if suberr != nil {
  477. stack.push(common.BigFalse)
  478. } else {
  479. // gas < len(ret) * CreateDataGas == NO_CODE
  480. dataGas := big.NewInt(int64(len(ret)))
  481. dataGas.Mul(dataGas, params.CreateDataGas)
  482. if context.UseGas(dataGas) {
  483. ref.SetCode(ret)
  484. }
  485. addr = ref.Address()
  486. stack.push(addr.Big())
  487. }
  488. case CALL, CALLCODE:
  489. gas := stack.pop()
  490. // pop gas and value of the stack.
  491. addr, value := stack.pop(), stack.pop()
  492. value = U256(value)
  493. // pop input size and offset
  494. inOffset, inSize := stack.pop(), stack.pop()
  495. // pop return size and offset
  496. retOffset, retSize := stack.pop(), stack.pop()
  497. address := common.BigToAddress(addr)
  498. // Get the arguments from the memory
  499. args := mem.Get(inOffset.Int64(), inSize.Int64())
  500. if len(value.Bytes()) > 0 {
  501. gas.Add(gas, params.CallStipend)
  502. }
  503. var (
  504. ret []byte
  505. err error
  506. )
  507. if op == CALLCODE {
  508. ret, err = self.env.CallCode(context, address, args, gas, price, value)
  509. } else {
  510. ret, err = self.env.Call(context, address, args, gas, price, value)
  511. }
  512. if err != nil {
  513. stack.push(common.BigFalse)
  514. } else {
  515. stack.push(common.BigTrue)
  516. mem.Set(retOffset.Uint64(), retSize.Uint64(), ret)
  517. }
  518. case RETURN:
  519. offset, size := stack.pop(), stack.pop()
  520. ret := mem.GetPtr(offset.Int64(), size.Int64())
  521. return context.Return(ret), nil
  522. case SUICIDE:
  523. receiver := statedb.GetOrNewStateObject(common.BigToAddress(stack.pop()))
  524. balance := statedb.GetBalance(context.Address())
  525. receiver.AddBalance(balance)
  526. statedb.Delete(context.Address())
  527. fallthrough
  528. case STOP: // Stop the context
  529. return context.Return(nil), nil
  530. default:
  531. return nil, fmt.Errorf("Invalid opcode %x", op)
  532. }
  533. pc++
  534. }
  535. }
  536. // calculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
  537. // the operation. This does not reduce gas or resizes the memory.
  538. func calculateGasAndSize(env Environment, context *Context, caller ContextRef, op OpCode, statedb *state.StateDB, mem *Memory, stack *stack) (*big.Int, *big.Int, error) {
  539. var (
  540. gas = new(big.Int)
  541. newMemSize *big.Int = new(big.Int)
  542. )
  543. err := baseCheck(op, stack, gas)
  544. if err != nil {
  545. return nil, nil, err
  546. }
  547. // stack Check, memory resize & gas phase
  548. switch op {
  549. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  550. n := int(op - SWAP1 + 2)
  551. err := stack.require(n)
  552. if err != nil {
  553. return nil, nil, err
  554. }
  555. gas.Set(GasFastestStep)
  556. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  557. n := int(op - DUP1 + 1)
  558. err := stack.require(n)
  559. if err != nil {
  560. return nil, nil, err
  561. }
  562. gas.Set(GasFastestStep)
  563. case LOG0, LOG1, LOG2, LOG3, LOG4:
  564. n := int(op - LOG0)
  565. err := stack.require(n + 2)
  566. if err != nil {
  567. return nil, nil, err
  568. }
  569. mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
  570. gas.Add(gas, params.LogGas)
  571. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(n)), params.LogTopicGas))
  572. gas.Add(gas, new(big.Int).Mul(mSize, params.LogDataGas))
  573. newMemSize = calcMemSize(mStart, mSize)
  574. case EXP:
  575. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), params.ExpByteGas))
  576. case SSTORE:
  577. err := stack.require(2)
  578. if err != nil {
  579. return nil, nil, err
  580. }
  581. var g *big.Int
  582. y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
  583. val := statedb.GetState(context.Address(), common.BigToHash(x))
  584. // This checks for 3 scenario's and calculates gas accordingly
  585. // 1. From a zero-value address to a non-zero value (NEW VALUE)
  586. // 2. From a non-zero value address to a zero-value address (DELETE)
  587. // 3. From a nen-zero to a non-zero (CHANGE)
  588. if common.EmptyHash(val) && !common.EmptyHash(common.BigToHash(y)) {
  589. // 0 => non 0
  590. g = params.SstoreSetGas
  591. } else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
  592. statedb.Refund(params.SstoreRefundGas)
  593. g = params.SstoreClearGas
  594. } else {
  595. // non 0 => non 0 (or 0 => 0)
  596. g = params.SstoreClearGas
  597. }
  598. gas.Set(g)
  599. case SUICIDE:
  600. if !statedb.IsDeleted(context.Address()) {
  601. statedb.Refund(params.SuicideRefundGas)
  602. }
  603. case MLOAD:
  604. newMemSize = calcMemSize(stack.peek(), u256(32))
  605. case MSTORE8:
  606. newMemSize = calcMemSize(stack.peek(), u256(1))
  607. case MSTORE:
  608. newMemSize = calcMemSize(stack.peek(), u256(32))
  609. case RETURN:
  610. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  611. case SHA3:
  612. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  613. words := toWordSize(stack.data[stack.len()-2])
  614. gas.Add(gas, words.Mul(words, params.Sha3WordGas))
  615. case CALLDATACOPY:
  616. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  617. words := toWordSize(stack.data[stack.len()-3])
  618. gas.Add(gas, words.Mul(words, params.CopyGas))
  619. case CODECOPY:
  620. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  621. words := toWordSize(stack.data[stack.len()-3])
  622. gas.Add(gas, words.Mul(words, params.CopyGas))
  623. case EXTCODECOPY:
  624. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
  625. words := toWordSize(stack.data[stack.len()-4])
  626. gas.Add(gas, words.Mul(words, params.CopyGas))
  627. case CREATE:
  628. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
  629. case CALL, CALLCODE:
  630. gas.Add(gas, stack.data[stack.len()-1])
  631. if op == CALL {
  632. if env.State().GetStateObject(common.BigToAddress(stack.data[stack.len()-2])) == nil {
  633. gas.Add(gas, params.CallNewAccountGas)
  634. }
  635. }
  636. if len(stack.data[stack.len()-3].Bytes()) > 0 {
  637. gas.Add(gas, params.CallValueTransferGas)
  638. }
  639. x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
  640. y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
  641. newMemSize = common.BigMax(x, y)
  642. }
  643. if newMemSize.Cmp(common.Big0) > 0 {
  644. newMemSizeWords := toWordSize(newMemSize)
  645. newMemSize.Mul(newMemSizeWords, u256(32))
  646. if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 {
  647. oldSize := toWordSize(big.NewInt(int64(mem.Len())))
  648. pow := new(big.Int).Exp(oldSize, common.Big2, Zero)
  649. linCoef := new(big.Int).Mul(oldSize, params.MemoryGas)
  650. quadCoef := new(big.Int).Div(pow, params.QuadCoeffDiv)
  651. oldTotalFee := new(big.Int).Add(linCoef, quadCoef)
  652. pow.Exp(newMemSizeWords, common.Big2, Zero)
  653. linCoef = new(big.Int).Mul(newMemSizeWords, params.MemoryGas)
  654. quadCoef = new(big.Int).Div(pow, params.QuadCoeffDiv)
  655. newTotalFee := new(big.Int).Add(linCoef, quadCoef)
  656. fee := new(big.Int).Sub(newTotalFee, oldTotalFee)
  657. gas.Add(gas, fee)
  658. }
  659. }
  660. return newMemSize, gas, nil
  661. }
  662. // RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
  663. func (self *Vm) RunPrecompiled(p *PrecompiledAccount, input []byte, context *Context) (ret []byte, err error) {
  664. gas := p.Gas(len(input))
  665. if context.UseGas(gas) {
  666. ret = p.Call(input)
  667. return context.Return(ret), nil
  668. } else {
  669. return nil, OutOfGasError
  670. }
  671. }
  672. // log emits a log event to the environment for each opcode encountered. This is not to be confused with the
  673. // LOG* opcode.
  674. func (self *Vm) log(pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, stack *stack, context *Context, err error) {
  675. if Debug {
  676. mem := make([]byte, len(memory.Data()))
  677. copy(mem, memory.Data())
  678. stck := make([]*big.Int, len(stack.Data()))
  679. copy(stck, stack.Data())
  680. object := context.self.(*state.StateObject)
  681. storage := make(map[common.Hash][]byte)
  682. object.EachStorage(func(k, v []byte) {
  683. storage[common.BytesToHash(k)] = v
  684. })
  685. self.env.AddStructLog(StructLog{pc, op, new(big.Int).Set(gas), cost, mem, stck, storage, err})
  686. }
  687. }
  688. // Environment returns the current workable state of the VM
  689. func (self *Vm) Env() Environment {
  690. return self.env
  691. }