vm.go 21 KB

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