vm.go 21 KB

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