vm.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. package vm
  2. import (
  3. "fmt"
  4. "math/big"
  5. "github.com/ethereum/go-ethereum/common"
  6. "github.com/ethereum/go-ethereum/crypto"
  7. "github.com/ethereum/go-ethereum/core/state"
  8. )
  9. type Vm struct {
  10. env Environment
  11. logTy byte
  12. logStr string
  13. err error
  14. // For logging
  15. debug bool
  16. BreakPoints []int64
  17. Stepping bool
  18. Fn string
  19. Recoverable bool
  20. }
  21. func New(env Environment) *Vm {
  22. lt := LogTyPretty
  23. return &Vm{debug: Debug, env: env, logTy: lt, Recoverable: true}
  24. }
  25. func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) {
  26. self.env.SetDepth(self.env.Depth() + 1)
  27. var (
  28. caller = context.caller
  29. code = context.Code
  30. value = context.value
  31. price = context.Price
  32. )
  33. self.Printf("(%d) (%x) %x (code=%d) gas: %v (d) %x", self.env.Depth(), caller.Address().Bytes()[:4], context.Address(), len(code), context.Gas, callData).Endl()
  34. if self.Recoverable {
  35. // Recover from any require exception
  36. defer func() {
  37. if r := recover(); r != nil {
  38. self.Printf(" %v", r).Endl()
  39. context.UseGas(context.Gas)
  40. ret = context.Return(nil)
  41. err = fmt.Errorf("%v", r)
  42. }
  43. }()
  44. }
  45. if context.CodeAddr != nil {
  46. if p := Precompiled[context.CodeAddr.Str()]; p != nil {
  47. return self.RunPrecompiled(p, callData, context)
  48. }
  49. }
  50. var (
  51. op OpCode
  52. destinations = analyseJumpDests(context.Code)
  53. mem = NewMemory()
  54. stack = newStack()
  55. pc uint64 = 0
  56. step = 0
  57. statedb = self.env.State()
  58. jump = func(from uint64, to *big.Int) {
  59. p := to.Uint64()
  60. nop := context.GetOp(p)
  61. if !destinations.Has(p) {
  62. panic(fmt.Sprintf("invalid jump destination (%v) %v", nop, p))
  63. }
  64. self.Printf(" ~> %v", to)
  65. pc = to.Uint64()
  66. self.Endl()
  67. }
  68. )
  69. // Don't bother with the execution if there's no code.
  70. if len(code) == 0 {
  71. return context.Return(nil), nil
  72. }
  73. for {
  74. // The base for all big integer arithmetic
  75. base := new(big.Int)
  76. step++
  77. // Get the memory location of pc
  78. op = context.GetOp(pc)
  79. self.Printf("(pc) %-3d -o- %-14s (m) %-4d (s) %-4d ", pc, op.String(), mem.Len(), stack.len())
  80. newMemSize, gas := self.calculateGasAndSize(context, caller, op, statedb, mem, stack)
  81. self.Printf("(g) %-3v (%v)", gas, context.Gas)
  82. if !context.UseGas(gas) {
  83. self.Endl()
  84. tmp := new(big.Int).Set(context.Gas)
  85. context.UseGas(context.Gas)
  86. return context.Return(nil), OOG(gas, tmp)
  87. }
  88. mem.Resize(newMemSize.Uint64())
  89. switch op {
  90. // 0x20 range
  91. case ADD:
  92. x, y := stack.pop(), stack.pop()
  93. self.Printf(" %v + %v", y, x)
  94. base.Add(x, y)
  95. U256(base)
  96. self.Printf(" = %v", base)
  97. // pop result back on the stack
  98. stack.push(base)
  99. case SUB:
  100. x, y := stack.pop(), stack.pop()
  101. self.Printf(" %v - %v", y, x)
  102. base.Sub(x, y)
  103. U256(base)
  104. self.Printf(" = %v", base)
  105. // pop result back on the stack
  106. stack.push(base)
  107. case MUL:
  108. x, y := stack.pop(), stack.pop()
  109. self.Printf(" %v * %v", y, x)
  110. base.Mul(x, y)
  111. U256(base)
  112. self.Printf(" = %v", base)
  113. // pop result back on the stack
  114. stack.push(base)
  115. case DIV:
  116. x, y := stack.pop(), stack.pop()
  117. self.Printf(" %v / %v", x, y)
  118. if y.Cmp(common.Big0) != 0 {
  119. base.Div(x, y)
  120. }
  121. U256(base)
  122. self.Printf(" = %v", 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. self.Printf(" %v / %v", x, y)
  128. if y.Cmp(common.Big0) == 0 {
  129. base.Set(common.Big0)
  130. } else {
  131. n := new(big.Int)
  132. if new(big.Int).Mul(x, y).Cmp(common.Big0) < 0 {
  133. n.SetInt64(-1)
  134. } else {
  135. n.SetInt64(1)
  136. }
  137. base.Div(x.Abs(x), y.Abs(y)).Mul(base, n)
  138. U256(base)
  139. }
  140. self.Printf(" = %v", base)
  141. stack.push(base)
  142. case MOD:
  143. x, y := stack.pop(), stack.pop()
  144. self.Printf(" %v %% %v", x, y)
  145. if y.Cmp(common.Big0) == 0 {
  146. base.Set(common.Big0)
  147. } else {
  148. base.Mod(x, y)
  149. }
  150. U256(base)
  151. self.Printf(" = %v", base)
  152. stack.push(base)
  153. case SMOD:
  154. x, y := S256(stack.pop()), S256(stack.pop())
  155. self.Printf(" %v %% %v", x, y)
  156. if y.Cmp(common.Big0) == 0 {
  157. base.Set(common.Big0)
  158. } else {
  159. n := new(big.Int)
  160. if x.Cmp(common.Big0) < 0 {
  161. n.SetInt64(-1)
  162. } else {
  163. n.SetInt64(1)
  164. }
  165. base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n)
  166. U256(base)
  167. }
  168. self.Printf(" = %v", base)
  169. stack.push(base)
  170. case EXP:
  171. x, y := stack.pop(), stack.pop()
  172. self.Printf(" %v ** %v", x, y)
  173. base.Exp(x, y, Pow256)
  174. U256(base)
  175. self.Printf(" = %v", base)
  176. stack.push(base)
  177. case SIGNEXTEND:
  178. back := stack.pop()
  179. if back.Cmp(big.NewInt(31)) < 0 {
  180. bit := uint(back.Uint64()*8 + 7)
  181. num := stack.pop()
  182. mask := new(big.Int).Lsh(common.Big1, bit)
  183. mask.Sub(mask, common.Big1)
  184. if common.BitTest(num, int(bit)) {
  185. num.Or(num, mask.Not(mask))
  186. } else {
  187. num.And(num, mask)
  188. }
  189. num = U256(num)
  190. self.Printf(" = %v", num)
  191. stack.push(num)
  192. }
  193. case NOT:
  194. stack.push(U256(new(big.Int).Not(stack.pop())))
  195. //base.Sub(Pow256, stack.pop()).Sub(base, common.Big1)
  196. //base = U256(base)
  197. //stack.push(base)
  198. case LT:
  199. x, y := stack.pop(), stack.pop()
  200. self.Printf(" %v < %v", x, y)
  201. // x < y
  202. if x.Cmp(y) < 0 {
  203. stack.push(common.BigTrue)
  204. } else {
  205. stack.push(common.BigFalse)
  206. }
  207. case GT:
  208. x, y := stack.pop(), stack.pop()
  209. self.Printf(" %v > %v", x, y)
  210. // x > y
  211. if x.Cmp(y) > 0 {
  212. stack.push(common.BigTrue)
  213. } else {
  214. stack.push(common.BigFalse)
  215. }
  216. case SLT:
  217. x, y := S256(stack.pop()), S256(stack.pop())
  218. self.Printf(" %v < %v", x, y)
  219. // x < y
  220. if x.Cmp(S256(y)) < 0 {
  221. stack.push(common.BigTrue)
  222. } else {
  223. stack.push(common.BigFalse)
  224. }
  225. case SGT:
  226. x, y := S256(stack.pop()), S256(stack.pop())
  227. self.Printf(" %v > %v", x, y)
  228. // x > y
  229. if x.Cmp(y) > 0 {
  230. stack.push(common.BigTrue)
  231. } else {
  232. stack.push(common.BigFalse)
  233. }
  234. case EQ:
  235. x, y := stack.pop(), stack.pop()
  236. self.Printf(" %v == %v", y, x)
  237. // x == y
  238. if x.Cmp(y) == 0 {
  239. stack.push(common.BigTrue)
  240. } else {
  241. stack.push(common.BigFalse)
  242. }
  243. case ISZERO:
  244. x := stack.pop()
  245. if x.Cmp(common.BigFalse) > 0 {
  246. stack.push(common.BigFalse)
  247. } else {
  248. stack.push(common.BigTrue)
  249. }
  250. // 0x10 range
  251. case AND:
  252. x, y := stack.pop(), stack.pop()
  253. self.Printf(" %v & %v", y, x)
  254. stack.push(base.And(x, y))
  255. case OR:
  256. x, y := stack.pop(), stack.pop()
  257. self.Printf(" %v | %v", x, y)
  258. stack.push(base.Or(x, y))
  259. case XOR:
  260. x, y := stack.pop(), stack.pop()
  261. self.Printf(" %v ^ %v", x, y)
  262. stack.push(base.Xor(x, y))
  263. case BYTE:
  264. th, val := stack.pop(), stack.pop()
  265. if th.Cmp(big.NewInt(32)) < 0 {
  266. byt := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))
  267. base.Set(byt)
  268. } else {
  269. base.Set(common.BigFalse)
  270. }
  271. self.Printf(" => 0x%x", base.Bytes())
  272. stack.push(base)
  273. case ADDMOD:
  274. x := stack.pop()
  275. y := stack.pop()
  276. z := stack.pop()
  277. if z.Cmp(Zero) > 0 {
  278. add := new(big.Int).Add(x, y)
  279. base.Mod(add, z)
  280. base = U256(base)
  281. }
  282. self.Printf(" %v + %v %% %v = %v", x, y, z, base)
  283. stack.push(base)
  284. case MULMOD:
  285. x := stack.pop()
  286. y := stack.pop()
  287. z := stack.pop()
  288. if z.Cmp(Zero) > 0 {
  289. mul := new(big.Int).Mul(x, y)
  290. base.Mod(mul, z)
  291. U256(base)
  292. }
  293. self.Printf(" %v + %v %% %v = %v", x, y, z, base)
  294. stack.push(base)
  295. // 0x20 range
  296. case SHA3:
  297. offset, size := stack.pop(), stack.pop()
  298. data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64()))
  299. stack.push(common.BigD(data))
  300. self.Printf(" => (%v) %x", size, data)
  301. // 0x30 range
  302. case ADDRESS:
  303. stack.push(common.Bytes2Big(context.Address().Bytes()))
  304. self.Printf(" => %x", context.Address())
  305. case BALANCE:
  306. addr := common.BigToAddress(stack.pop())
  307. balance := statedb.GetBalance(addr)
  308. stack.push(balance)
  309. self.Printf(" => %v (%x)", balance, addr)
  310. case ORIGIN:
  311. origin := self.env.Origin()
  312. stack.push(origin.Big())
  313. self.Printf(" => %x", origin)
  314. case CALLER:
  315. caller := context.caller.Address()
  316. stack.push(common.Bytes2Big(caller.Bytes()))
  317. self.Printf(" => %x", caller)
  318. case CALLVALUE:
  319. stack.push(value)
  320. self.Printf(" => %v", value)
  321. case CALLDATALOAD:
  322. var (
  323. offset = stack.pop()
  324. data = make([]byte, 32)
  325. lenData = big.NewInt(int64(len(callData)))
  326. )
  327. if lenData.Cmp(offset) >= 0 {
  328. length := new(big.Int).Add(offset, common.Big32)
  329. length = common.BigMin(length, lenData)
  330. copy(data, callData[offset.Int64():length.Int64()])
  331. }
  332. self.Printf(" => 0x%x", data)
  333. stack.push(common.BigD(data))
  334. case CALLDATASIZE:
  335. l := int64(len(callData))
  336. stack.push(big.NewInt(l))
  337. self.Printf(" => %d", l)
  338. case CALLDATACOPY:
  339. var (
  340. mOff = stack.pop()
  341. cOff = stack.pop()
  342. l = stack.pop()
  343. )
  344. data := getData(callData, cOff, l)
  345. mem.Set(mOff.Uint64(), l.Uint64(), data)
  346. self.Printf(" => [%v, %v, %v]", mOff, cOff, l)
  347. case CODESIZE, EXTCODESIZE:
  348. var code []byte
  349. if op == EXTCODESIZE {
  350. addr := common.BigToAddress(stack.pop())
  351. code = statedb.GetCode(addr)
  352. } else {
  353. code = context.Code
  354. }
  355. l := big.NewInt(int64(len(code)))
  356. stack.push(l)
  357. self.Printf(" => %d", l)
  358. case CODECOPY, EXTCODECOPY:
  359. var code []byte
  360. if op == EXTCODECOPY {
  361. addr := common.BigToAddress(stack.pop())
  362. code = statedb.GetCode(addr)
  363. } else {
  364. code = context.Code
  365. }
  366. var (
  367. mOff = stack.pop()
  368. cOff = stack.pop()
  369. l = stack.pop()
  370. )
  371. codeCopy := getData(code, cOff, l)
  372. mem.Set(mOff.Uint64(), l.Uint64(), codeCopy)
  373. self.Printf(" => [%v, %v, %v] %x", mOff, cOff, l, codeCopy)
  374. case GASPRICE:
  375. stack.push(context.Price)
  376. self.Printf(" => %x", context.Price)
  377. // 0x40 range
  378. case BLOCKHASH:
  379. num := stack.pop()
  380. n := new(big.Int).Sub(self.env.BlockNumber(), common.Big257)
  381. if num.Cmp(n) > 0 && num.Cmp(self.env.BlockNumber()) < 0 {
  382. stack.push(self.env.GetHash(num.Uint64()).Big())
  383. } else {
  384. stack.push(common.Big0)
  385. }
  386. self.Printf(" => 0x%x", stack.peek().Bytes())
  387. case COINBASE:
  388. coinbase := self.env.Coinbase()
  389. stack.push(coinbase.Big())
  390. self.Printf(" => 0x%x", coinbase)
  391. case TIMESTAMP:
  392. time := self.env.Time()
  393. stack.push(big.NewInt(time))
  394. self.Printf(" => 0x%x", time)
  395. case NUMBER:
  396. number := self.env.BlockNumber()
  397. stack.push(U256(number))
  398. self.Printf(" => 0x%x", number.Bytes())
  399. case DIFFICULTY:
  400. difficulty := self.env.Difficulty()
  401. stack.push(difficulty)
  402. self.Printf(" => 0x%x", difficulty.Bytes())
  403. case GASLIMIT:
  404. self.Printf(" => %v", self.env.GasLimit())
  405. stack.push(self.env.GasLimit())
  406. // 0x50 range
  407. 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:
  408. a := uint64(op - PUSH1 + 1)
  409. byts := context.GetRangeValue(pc+1, a)
  410. // push value to stack
  411. stack.push(common.BigD(byts))
  412. pc += a
  413. step += int(op) - int(PUSH1) + 1
  414. self.Printf(" => 0x%x", byts)
  415. case POP:
  416. stack.pop()
  417. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  418. n := int(op - DUP1 + 1)
  419. stack.dup(n)
  420. self.Printf(" => [%d] 0x%x", n, stack.peek().Bytes())
  421. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  422. n := int(op - SWAP1 + 2)
  423. stack.swap(n)
  424. self.Printf(" => [%d]", n)
  425. case LOG0, LOG1, LOG2, LOG3, LOG4:
  426. n := int(op - LOG0)
  427. topics := make([]common.Hash, n)
  428. mStart, mSize := stack.pop(), stack.pop()
  429. for i := 0; i < n; i++ {
  430. topics[i] = common.BigToHash(stack.pop()) //common.LeftPadBytes(stack.pop().Bytes(), 32)
  431. }
  432. data := mem.Get(mStart.Int64(), mSize.Int64())
  433. log := &Log{context.Address(), topics, data, self.env.BlockNumber().Uint64()}
  434. self.env.AddLog(log)
  435. self.Printf(" => %v", log)
  436. case MLOAD:
  437. offset := stack.pop()
  438. val := common.BigD(mem.Get(offset.Int64(), 32))
  439. stack.push(val)
  440. self.Printf(" => 0x%x", val.Bytes())
  441. case MSTORE: // Store the value at stack top-1 in to memory at location stack top
  442. // pop value of the stack
  443. mStart, val := stack.pop(), stack.pop()
  444. mem.Set(mStart.Uint64(), 32, common.BigToBytes(val, 256))
  445. self.Printf(" => 0x%x", val)
  446. case MSTORE8:
  447. off, val := stack.pop().Int64(), stack.pop().Int64()
  448. mem.store[off] = byte(val & 0xff)
  449. self.Printf(" => [%v] 0x%x", off, mem.store[off])
  450. case SLOAD:
  451. loc := common.BigToHash(stack.pop())
  452. val := common.Bytes2Big(statedb.GetState(context.Address(), loc))
  453. stack.push(val)
  454. self.Printf(" {0x%x : 0x%x}", loc, val.Bytes())
  455. case SSTORE:
  456. loc := common.BigToHash(stack.pop())
  457. val := stack.pop()
  458. statedb.SetState(context.Address(), loc, val)
  459. self.Printf(" {0x%x : 0x%x}", loc, val.Bytes())
  460. case JUMP:
  461. jump(pc, stack.pop())
  462. continue
  463. case JUMPI:
  464. pos, cond := stack.pop(), stack.pop()
  465. if cond.Cmp(common.BigTrue) >= 0 {
  466. jump(pc, pos)
  467. continue
  468. }
  469. self.Printf(" ~> false")
  470. case JUMPDEST:
  471. case PC:
  472. stack.push(big.NewInt(int64(pc)))
  473. case MSIZE:
  474. stack.push(big.NewInt(int64(mem.Len())))
  475. case GAS:
  476. stack.push(context.Gas)
  477. self.Printf(" => %x", context.Gas)
  478. // 0x60 range
  479. case CREATE:
  480. var (
  481. value = stack.pop()
  482. offset, size = stack.pop(), stack.pop()
  483. input = mem.Get(offset.Int64(), size.Int64())
  484. gas = new(big.Int).Set(context.Gas)
  485. addr common.Address
  486. )
  487. self.Endl()
  488. context.UseGas(context.Gas)
  489. ret, suberr, ref := self.env.Create(context, nil, input, gas, price, value)
  490. if suberr != nil {
  491. stack.push(common.BigFalse)
  492. self.Printf(" (*) 0x0 %v", suberr)
  493. } else {
  494. // gas < len(ret) * CreateDataGas == NO_CODE
  495. dataGas := big.NewInt(int64(len(ret)))
  496. dataGas.Mul(dataGas, GasCreateByte)
  497. if context.UseGas(dataGas) {
  498. ref.SetCode(ret)
  499. }
  500. addr = ref.Address()
  501. stack.push(addr.Big())
  502. }
  503. case CALL, CALLCODE:
  504. gas := stack.pop()
  505. // pop gas and value of the stack.
  506. addr, value := stack.pop(), stack.pop()
  507. value = U256(value)
  508. // pop input size and offset
  509. inOffset, inSize := stack.pop(), stack.pop()
  510. // pop return size and offset
  511. retOffset, retSize := stack.pop(), stack.pop()
  512. address := common.BigToAddress(addr)
  513. self.Printf(" => %x", address).Endl()
  514. // Get the arguments from the memory
  515. args := mem.Get(inOffset.Int64(), inSize.Int64())
  516. if len(value.Bytes()) > 0 {
  517. gas.Add(gas, GasStipend)
  518. }
  519. var (
  520. ret []byte
  521. err error
  522. )
  523. if op == CALLCODE {
  524. ret, err = self.env.CallCode(context, address, args, gas, price, value)
  525. } else {
  526. ret, err = self.env.Call(context, address, args, gas, price, value)
  527. }
  528. if err != nil {
  529. stack.push(common.BigFalse)
  530. self.Printf("%v").Endl()
  531. } else {
  532. stack.push(common.BigTrue)
  533. mem.Set(retOffset.Uint64(), retSize.Uint64(), ret)
  534. }
  535. self.Printf("resume %x (%v)", context.Address(), context.Gas)
  536. case RETURN:
  537. offset, size := stack.pop(), stack.pop()
  538. ret := mem.Get(offset.Int64(), size.Int64())
  539. self.Printf(" => [%v, %v] (%d) 0x%x", offset, size, len(ret), ret).Endl()
  540. return context.Return(ret), nil
  541. case SUICIDE:
  542. receiver := statedb.GetOrNewStateObject(common.BigToAddress(stack.pop()))
  543. balance := statedb.GetBalance(context.Address())
  544. self.Printf(" => (%x) %v", receiver.Address().Bytes()[:4], balance)
  545. receiver.AddBalance(balance)
  546. statedb.Delete(context.Address())
  547. fallthrough
  548. case STOP: // Stop the context
  549. self.Endl()
  550. return context.Return(nil), nil
  551. default:
  552. self.Printf("(pc) %-3v Invalid opcode %x\n", pc, op).Endl()
  553. panic(fmt.Errorf("Invalid opcode %x", op))
  554. }
  555. pc++
  556. self.Endl()
  557. }
  558. }
  559. func (self *Vm) calculateGasAndSize(context *Context, caller ContextRef, op OpCode, statedb *state.StateDB, mem *Memory, stack *stack) (*big.Int, *big.Int) {
  560. var (
  561. gas = new(big.Int)
  562. newMemSize *big.Int = new(big.Int)
  563. )
  564. baseCheck(op, stack, gas)
  565. // stack Check, memory resize & gas phase
  566. switch op {
  567. 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:
  568. gas.Set(GasFastestStep)
  569. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  570. n := int(op - SWAP1 + 2)
  571. stack.require(n)
  572. gas.Set(GasFastestStep)
  573. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  574. n := int(op - DUP1 + 1)
  575. stack.require(n)
  576. gas.Set(GasFastestStep)
  577. case LOG0, LOG1, LOG2, LOG3, LOG4:
  578. n := int(op - LOG0)
  579. stack.require(n + 2)
  580. mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
  581. gas.Add(gas, GasLogBase)
  582. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(n)), GasLogTopic))
  583. gas.Add(gas, new(big.Int).Mul(mSize, GasLogByte))
  584. newMemSize = calcMemSize(mStart, mSize)
  585. case EXP:
  586. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), GasExpByte))
  587. case SSTORE:
  588. stack.require(2)
  589. var g *big.Int
  590. y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
  591. val := statedb.GetState(context.Address(), common.BigToHash(x))
  592. if len(val) == 0 && len(y.Bytes()) > 0 {
  593. // 0 => non 0
  594. g = GasStorageAdd
  595. } else if len(val) > 0 && len(y.Bytes()) == 0 {
  596. statedb.Refund(self.env.Origin(), RefundStorage)
  597. g = GasStorageMod
  598. } else {
  599. // non 0 => non 0 (or 0 => 0)
  600. g = GasStorageMod
  601. }
  602. gas.Set(g)
  603. case SUICIDE:
  604. if !statedb.IsDeleted(context.Address()) {
  605. statedb.Refund(self.env.Origin(), RefundSuicide)
  606. }
  607. case MLOAD:
  608. newMemSize = calcMemSize(stack.peek(), u256(32))
  609. case MSTORE8:
  610. newMemSize = calcMemSize(stack.peek(), u256(1))
  611. case MSTORE:
  612. newMemSize = calcMemSize(stack.peek(), u256(32))
  613. case RETURN:
  614. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  615. case SHA3:
  616. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  617. words := toWordSize(stack.data[stack.len()-2])
  618. gas.Add(gas, words.Mul(words, GasSha3Word))
  619. case CALLDATACOPY:
  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, GasCopyWord))
  623. case CODECOPY:
  624. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  625. words := toWordSize(stack.data[stack.len()-3])
  626. gas.Add(gas, words.Mul(words, GasCopyWord))
  627. case EXTCODECOPY:
  628. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
  629. words := toWordSize(stack.data[stack.len()-4])
  630. gas.Add(gas, words.Mul(words, GasCopyWord))
  631. case CREATE:
  632. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
  633. case CALL, CALLCODE:
  634. gas.Add(gas, stack.data[stack.len()-1])
  635. if op == CALL {
  636. if self.env.State().GetStateObject(common.BigToAddress(stack.data[stack.len()-2])) == nil {
  637. gas.Add(gas, GasCallNewAccount)
  638. }
  639. }
  640. if len(stack.data[stack.len()-3].Bytes()) > 0 {
  641. gas.Add(gas, GasCallValueTransfer)
  642. }
  643. x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
  644. y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
  645. newMemSize = common.BigMax(x, y)
  646. }
  647. if newMemSize.Cmp(common.Big0) > 0 {
  648. newMemSizeWords := toWordSize(newMemSize)
  649. newMemSize.Mul(newMemSizeWords, u256(32))
  650. if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 {
  651. oldSize := toWordSize(big.NewInt(int64(mem.Len())))
  652. pow := new(big.Int).Exp(oldSize, common.Big2, Zero)
  653. linCoef := new(big.Int).Mul(oldSize, GasMemWord)
  654. quadCoef := new(big.Int).Div(pow, GasQuadCoeffDenom)
  655. oldTotalFee := new(big.Int).Add(linCoef, quadCoef)
  656. pow.Exp(newMemSizeWords, common.Big2, Zero)
  657. linCoef = new(big.Int).Mul(newMemSizeWords, GasMemWord)
  658. quadCoef = new(big.Int).Div(pow, GasQuadCoeffDenom)
  659. newTotalFee := new(big.Int).Add(linCoef, quadCoef)
  660. gas.Add(gas, new(big.Int).Sub(newTotalFee, oldTotalFee))
  661. }
  662. }
  663. return newMemSize, gas
  664. }
  665. func (self *Vm) RunPrecompiled(p *PrecompiledAccount, callData []byte, context *Context) (ret []byte, err error) {
  666. gas := p.Gas(len(callData))
  667. if context.UseGas(gas) {
  668. ret = p.Call(callData)
  669. self.Printf("NATIVE_FUNC => %x", ret)
  670. self.Endl()
  671. return context.Return(ret), nil
  672. } else {
  673. self.Printf("NATIVE_FUNC => failed").Endl()
  674. tmp := new(big.Int).Set(context.Gas)
  675. panic(OOG(gas, tmp).Error())
  676. }
  677. }
  678. func (self *Vm) Printf(format string, v ...interface{}) VirtualMachine {
  679. if self.debug {
  680. if self.logTy == LogTyPretty {
  681. self.logStr += fmt.Sprintf(format, v...)
  682. }
  683. }
  684. return self
  685. }
  686. func (self *Vm) Endl() VirtualMachine {
  687. if self.debug {
  688. if self.logTy == LogTyPretty {
  689. vmlogger.Infoln(self.logStr)
  690. self.logStr = ""
  691. }
  692. }
  693. return self
  694. }
  695. func (self *Vm) Env() Environment {
  696. return self.env
  697. }