vm.go 21 KB

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