vm.go 20 KB

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