You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

843 lines
22 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package vm
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. . "github.com/tendermint/tendermint/common"
  8. "github.com/tendermint/tendermint/events"
  9. "github.com/tendermint/tendermint/types"
  10. "github.com/tendermint/tendermint/vm/sha3"
  11. )
  12. var (
  13. ErrUnknownAddress = errors.New("Unknown address")
  14. ErrInsufficientBalance = errors.New("Insufficient balance")
  15. ErrInvalidJumpDest = errors.New("Invalid jump dest")
  16. ErrInsufficientGas = errors.New("Insuffient gas")
  17. ErrMemoryOutOfBounds = errors.New("Memory out of bounds")
  18. ErrCodeOutOfBounds = errors.New("Code out of bounds")
  19. ErrInputOutOfBounds = errors.New("Input out of bounds")
  20. ErrCallStackOverflow = errors.New("Call stack overflow")
  21. ErrCallStackUnderflow = errors.New("Call stack underflow")
  22. ErrDataStackOverflow = errors.New("Data stack overflow")
  23. ErrDataStackUnderflow = errors.New("Data stack underflow")
  24. ErrInvalidContract = errors.New("Invalid contract")
  25. )
  26. type Debug bool
  27. const (
  28. dataStackCapacity = 1024
  29. callStackCapacity = 100 // TODO ensure usage.
  30. memoryCapacity = 1024 * 1024 // 1 MB
  31. dbg Debug = true
  32. )
  33. func (d Debug) Printf(s string, a ...interface{}) {
  34. if d {
  35. fmt.Printf(s, a...)
  36. }
  37. }
  38. type VM struct {
  39. appState AppState
  40. params Params
  41. origin Word256
  42. txid []byte
  43. callDepth int
  44. evc events.Fireable
  45. }
  46. func NewVM(appState AppState, params Params, origin Word256, txid []byte) *VM {
  47. return &VM{
  48. appState: appState,
  49. params: params,
  50. origin: origin,
  51. callDepth: 0,
  52. txid: txid,
  53. }
  54. }
  55. // satisfies events.Eventable
  56. func (vm *VM) SetFireable(evc events.Fireable) {
  57. vm.evc = evc
  58. }
  59. // CONTRACT appState is aware of caller and callee, so we can just mutate them.
  60. // value: To be transferred from caller to callee. Refunded upon error.
  61. // gas: Available gas. No refunds for gas.
  62. func (vm *VM) Call(caller, callee *Account, code, input []byte, value uint64, gas *uint64) (output []byte, err error) {
  63. if len(code) == 0 {
  64. panic("Call() requires code")
  65. }
  66. if err = transfer(caller, callee, value); err != nil {
  67. return
  68. }
  69. vm.callDepth += 1
  70. output, err = vm.call(caller, callee, code, input, value, gas)
  71. vm.callDepth -= 1
  72. exception := ""
  73. if err != nil {
  74. exception = err.Error()
  75. err := transfer(callee, caller, value)
  76. if err != nil {
  77. panic("Could not return value to caller")
  78. }
  79. }
  80. // if callDepth is 0 the event is fired from ExecTx (along with the Input event)
  81. // otherwise, we fire from here.
  82. if vm.callDepth != 0 && vm.evc != nil {
  83. vm.evc.FireEvent(types.EventStringAccReceive(callee.Address.Postfix(20)), types.EventMsgCall{
  84. &types.CallData{caller.Address.Postfix(20), callee.Address.Postfix(20), input, value, *gas},
  85. vm.origin.Postfix(20),
  86. vm.txid,
  87. output,
  88. exception,
  89. })
  90. }
  91. return
  92. }
  93. // Just like Call() but does not transfer 'value' or modify the callDepth.
  94. func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, gas *uint64) (output []byte, err error) {
  95. dbg.Printf("(%d) (%X) %X (code=%d) gas: %v (d) %X\n", vm.callDepth, caller.Address[:4], callee.Address, len(callee.Code), *gas, input)
  96. var (
  97. pc uint64 = 0
  98. stack = NewStack(dataStackCapacity, gas, &err)
  99. memory = make([]byte, memoryCapacity)
  100. ok = false // convenience
  101. )
  102. for {
  103. // If there is an error, return
  104. if err != nil {
  105. return nil, err
  106. }
  107. var op = codeGetOp(code, pc)
  108. dbg.Printf("(pc) %-3d (op) %-14s (st) %-4d ", pc, op.String(), stack.Len())
  109. switch op {
  110. case STOP: // 0x00
  111. return nil, nil
  112. case ADD: // 0x01
  113. x, y := stack.Pop(), stack.Pop()
  114. xb := new(big.Int).SetBytes(x[:])
  115. yb := new(big.Int).SetBytes(y[:])
  116. sum := new(big.Int).Add(xb, yb)
  117. res := LeftPadWord256(U256(sum).Bytes())
  118. stack.Push(res)
  119. dbg.Printf(" %v + %v = %v (%X)\n", xb, yb, sum, res)
  120. case MUL: // 0x02
  121. x, y := stack.Pop(), stack.Pop()
  122. xb := new(big.Int).SetBytes(x[:])
  123. yb := new(big.Int).SetBytes(y[:])
  124. prod := new(big.Int).Mul(xb, yb)
  125. res := LeftPadWord256(U256(prod).Bytes())
  126. stack.Push(res)
  127. dbg.Printf(" %v * %v = %v (%X)\n", xb, yb, prod, res)
  128. case SUB: // 0x03
  129. x, y := stack.Pop(), stack.Pop()
  130. xb := new(big.Int).SetBytes(x[:])
  131. yb := new(big.Int).SetBytes(y[:])
  132. diff := new(big.Int).Sub(xb, yb)
  133. res := LeftPadWord256(U256(diff).Bytes())
  134. stack.Push(res)
  135. dbg.Printf(" %v - %v = %v (%X)\n", xb, yb, diff, res)
  136. case DIV: // 0x04
  137. x, y := stack.Pop(), stack.Pop()
  138. if y.IsZero() {
  139. stack.Push(Zero256)
  140. dbg.Printf(" %x / %x = %v\n", x, y, 0)
  141. } else {
  142. xb := new(big.Int).SetBytes(x[:])
  143. yb := new(big.Int).SetBytes(y[:])
  144. div := new(big.Int).Div(xb, yb)
  145. res := LeftPadWord256(U256(div).Bytes())
  146. stack.Push(res)
  147. dbg.Printf(" %v / %v = %v (%X)\n", xb, yb, div, res)
  148. }
  149. case SDIV: // 0x05
  150. x, y := stack.Pop(), stack.Pop()
  151. if y.IsZero() {
  152. stack.Push(Zero256)
  153. dbg.Printf(" %x / %x = %v\n", x, y, 0)
  154. } else {
  155. xb := S256(new(big.Int).SetBytes(x[:]))
  156. yb := S256(new(big.Int).SetBytes(y[:]))
  157. div := new(big.Int).Div(xb, yb)
  158. res := LeftPadWord256(U256(div).Bytes())
  159. stack.Push(res)
  160. dbg.Printf(" %v / %v = %v (%X)\n", xb, yb, div, res)
  161. }
  162. case MOD: // 0x06
  163. x, y := stack.Pop(), stack.Pop()
  164. if y.IsZero() {
  165. stack.Push(Zero256)
  166. dbg.Printf(" %v %% %v = %v\n", x, y, 0)
  167. } else {
  168. xb := new(big.Int).SetBytes(x[:])
  169. yb := new(big.Int).SetBytes(y[:])
  170. mod := new(big.Int).Mod(xb, yb)
  171. res := LeftPadWord256(U256(mod).Bytes())
  172. stack.Push(res)
  173. dbg.Printf(" %v %% %v = %v (%X)\n", xb, yb, mod, res)
  174. }
  175. case SMOD: // 0x07
  176. x, y := stack.Pop(), stack.Pop()
  177. if y.IsZero() {
  178. stack.Push(Zero256)
  179. dbg.Printf(" %v %% %v = %v\n", x, y, 0)
  180. } else {
  181. xb := S256(new(big.Int).SetBytes(x[:]))
  182. yb := S256(new(big.Int).SetBytes(y[:]))
  183. mod := new(big.Int).Mod(xb, yb)
  184. res := LeftPadWord256(U256(mod).Bytes())
  185. stack.Push(res)
  186. dbg.Printf(" %v %% %v = %v (%X)\n", xb, yb, mod, res)
  187. }
  188. case ADDMOD: // 0x08
  189. x, y, z := stack.Pop(), stack.Pop(), stack.Pop()
  190. if z.IsZero() {
  191. stack.Push(Zero256)
  192. dbg.Printf(" %v %% %v = %v\n", x, y, 0)
  193. } else {
  194. xb := new(big.Int).SetBytes(x[:])
  195. yb := new(big.Int).SetBytes(y[:])
  196. zb := new(big.Int).SetBytes(z[:])
  197. add := new(big.Int).Add(xb, yb)
  198. mod := new(big.Int).Mod(add, zb)
  199. res := LeftPadWord256(U256(mod).Bytes())
  200. stack.Push(res)
  201. dbg.Printf(" %v + %v %% %v = %v (%X)\n",
  202. xb, yb, zb, mod, res)
  203. }
  204. case MULMOD: // 0x09
  205. x, y, z := stack.Pop(), stack.Pop(), stack.Pop()
  206. if z.IsZero() {
  207. stack.Push(Zero256)
  208. dbg.Printf(" %v %% %v = %v\n", x, y, 0)
  209. } else {
  210. xb := new(big.Int).SetBytes(x[:])
  211. yb := new(big.Int).SetBytes(y[:])
  212. zb := new(big.Int).SetBytes(z[:])
  213. mul := new(big.Int).Mul(xb, yb)
  214. mod := new(big.Int).Mod(mul, zb)
  215. res := LeftPadWord256(U256(mod).Bytes())
  216. stack.Push(res)
  217. dbg.Printf(" %v * %v %% %v = %v (%X)\n",
  218. xb, yb, zb, mod, res)
  219. }
  220. case EXP: // 0x0A
  221. x, y := stack.Pop(), stack.Pop()
  222. xb := new(big.Int).SetBytes(x[:])
  223. yb := new(big.Int).SetBytes(y[:])
  224. pow := new(big.Int).Exp(xb, yb, big.NewInt(0))
  225. res := LeftPadWord256(U256(pow).Bytes())
  226. stack.Push(res)
  227. dbg.Printf(" %v ** %v = %v (%X)\n", xb, yb, pow, res)
  228. case SIGNEXTEND: // 0x0B
  229. back := stack.Pop()
  230. backb := new(big.Int).SetBytes(back[:])
  231. if backb.Cmp(big.NewInt(31)) < 0 {
  232. bit := uint(backb.Uint64()*8 + 7)
  233. num := stack.Pop()
  234. numb := new(big.Int).SetBytes(num[:])
  235. mask := new(big.Int).Lsh(big.NewInt(1), bit)
  236. mask.Sub(mask, big.NewInt(1))
  237. if numb.Bit(int(bit)) == 1 {
  238. numb.Or(numb, mask.Not(mask))
  239. } else {
  240. numb.Add(numb, mask)
  241. }
  242. res := LeftPadWord256(U256(numb).Bytes())
  243. dbg.Printf(" = %v (%X)", numb, res)
  244. stack.Push(res)
  245. }
  246. case LT: // 0x10
  247. x, y := stack.Pop(), stack.Pop()
  248. xb := new(big.Int).SetBytes(x[:])
  249. yb := new(big.Int).SetBytes(y[:])
  250. if xb.Cmp(yb) < 0 {
  251. stack.Push64(1)
  252. dbg.Printf(" %v < %v = %v\n", xb, yb, 1)
  253. } else {
  254. stack.Push(Zero256)
  255. dbg.Printf(" %v < %v = %v\n", xb, yb, 0)
  256. }
  257. case GT: // 0x11
  258. x, y := stack.Pop(), stack.Pop()
  259. xb := new(big.Int).SetBytes(x[:])
  260. yb := new(big.Int).SetBytes(y[:])
  261. if xb.Cmp(yb) > 0 {
  262. stack.Push64(1)
  263. dbg.Printf(" %v > %v = %v\n", xb, yb, 1)
  264. } else {
  265. stack.Push(Zero256)
  266. dbg.Printf(" %v > %v = %v\n", xb, yb, 0)
  267. }
  268. case SLT: // 0x12
  269. x, y := stack.Pop(), stack.Pop()
  270. xb := S256(new(big.Int).SetBytes(x[:]))
  271. yb := S256(new(big.Int).SetBytes(y[:]))
  272. if xb.Cmp(yb) < 0 {
  273. stack.Push64(1)
  274. dbg.Printf(" %v < %v = %v\n", xb, yb, 1)
  275. } else {
  276. stack.Push(Zero256)
  277. dbg.Printf(" %v < %v = %v\n", xb, yb, 0)
  278. }
  279. case SGT: // 0x13
  280. x, y := stack.Pop(), stack.Pop()
  281. xb := S256(new(big.Int).SetBytes(x[:]))
  282. yb := S256(new(big.Int).SetBytes(y[:]))
  283. if xb.Cmp(yb) > 0 {
  284. stack.Push64(1)
  285. dbg.Printf(" %v > %v = %v\n", xb, yb, 1)
  286. } else {
  287. stack.Push(Zero256)
  288. dbg.Printf(" %v > %v = %v\n", xb, yb, 0)
  289. }
  290. case EQ: // 0x14
  291. x, y := stack.Pop(), stack.Pop()
  292. if bytes.Equal(x[:], y[:]) {
  293. stack.Push64(1)
  294. dbg.Printf(" %X == %X = %v\n", x, y, 1)
  295. } else {
  296. stack.Push(Zero256)
  297. dbg.Printf(" %X == %X = %v\n", x, y, 0)
  298. }
  299. case ISZERO: // 0x15
  300. x := stack.Pop()
  301. if x.IsZero() {
  302. stack.Push64(1)
  303. dbg.Printf(" %v == 0 = %v\n", x, 1)
  304. } else {
  305. stack.Push(Zero256)
  306. dbg.Printf(" %v == 0 = %v\n", x, 0)
  307. }
  308. case AND: // 0x16
  309. x, y := stack.Pop(), stack.Pop()
  310. z := [32]byte{}
  311. for i := 0; i < 32; i++ {
  312. z[i] = x[i] & y[i]
  313. }
  314. stack.Push(z)
  315. dbg.Printf(" %X & %X = %X\n", x, y, z)
  316. case OR: // 0x17
  317. x, y := stack.Pop(), stack.Pop()
  318. z := [32]byte{}
  319. for i := 0; i < 32; i++ {
  320. z[i] = x[i] | y[i]
  321. }
  322. stack.Push(z)
  323. dbg.Printf(" %X | %X = %X\n", x, y, z)
  324. case XOR: // 0x18
  325. x, y := stack.Pop(), stack.Pop()
  326. z := [32]byte{}
  327. for i := 0; i < 32; i++ {
  328. z[i] = x[i] ^ y[i]
  329. }
  330. stack.Push(z)
  331. dbg.Printf(" %X ^ %X = %X\n", x, y, z)
  332. case NOT: // 0x19
  333. x := stack.Pop()
  334. z := [32]byte{}
  335. for i := 0; i < 32; i++ {
  336. z[i] = ^x[i]
  337. }
  338. stack.Push(z)
  339. dbg.Printf(" !%X = %X\n", x, z)
  340. case BYTE: // 0x1A
  341. idx, val := stack.Pop64(), stack.Pop()
  342. res := byte(0)
  343. if idx < 32 {
  344. res = val[idx]
  345. }
  346. stack.Push64(uint64(res))
  347. dbg.Printf(" => 0x%X\n", res)
  348. case SHA3: // 0x20
  349. if ok = useGas(gas, GasSha3); !ok {
  350. return nil, firstErr(err, ErrInsufficientGas)
  351. }
  352. offset, size := stack.Pop64(), stack.Pop64()
  353. data, ok := subslice(memory, offset, size)
  354. if !ok {
  355. return nil, firstErr(err, ErrMemoryOutOfBounds)
  356. }
  357. data = sha3.Sha3(data)
  358. stack.PushBytes(data)
  359. dbg.Printf(" => (%v) %X\n", size, data)
  360. case ADDRESS: // 0x30
  361. stack.Push(callee.Address)
  362. dbg.Printf(" => %X\n", callee.Address)
  363. case BALANCE: // 0x31
  364. addr := stack.Pop()
  365. if ok = useGas(gas, GasGetAccount); !ok {
  366. return nil, firstErr(err, ErrInsufficientGas)
  367. }
  368. acc := vm.appState.GetAccount(addr)
  369. if acc == nil {
  370. return nil, firstErr(err, ErrUnknownAddress)
  371. }
  372. balance := acc.Balance
  373. stack.Push64(balance)
  374. dbg.Printf(" => %v (%X)\n", balance, addr)
  375. case ORIGIN: // 0x32
  376. stack.Push(vm.origin)
  377. dbg.Printf(" => %X\n", vm.origin)
  378. case CALLER: // 0x33
  379. stack.Push(caller.Address)
  380. dbg.Printf(" => %X\n", caller.Address)
  381. case CALLVALUE: // 0x34
  382. stack.Push64(value)
  383. dbg.Printf(" => %v\n", value)
  384. case CALLDATALOAD: // 0x35
  385. offset := stack.Pop64()
  386. data, ok := subslice(input, offset, 32)
  387. if !ok {
  388. return nil, firstErr(err, ErrInputOutOfBounds)
  389. }
  390. res := LeftPadWord256(data)
  391. stack.Push(res)
  392. dbg.Printf(" => 0x%X\n", res)
  393. case CALLDATASIZE: // 0x36
  394. stack.Push64(uint64(len(input)))
  395. dbg.Printf(" => %d\n", len(input))
  396. case CALLDATACOPY: // 0x37
  397. memOff := stack.Pop64()
  398. inputOff := stack.Pop64()
  399. length := stack.Pop64()
  400. data, ok := subslice(input, inputOff, length)
  401. if !ok {
  402. return nil, firstErr(err, ErrInputOutOfBounds)
  403. }
  404. dest, ok := subslice(memory, memOff, length)
  405. if !ok {
  406. return nil, firstErr(err, ErrMemoryOutOfBounds)
  407. }
  408. copy(dest, data)
  409. dbg.Printf(" => [%v, %v, %v] %X\n", memOff, inputOff, length, data)
  410. case CODESIZE: // 0x38
  411. l := uint64(len(code))
  412. stack.Push64(l)
  413. dbg.Printf(" => %d\n", l)
  414. case CODECOPY: // 0x39
  415. memOff := stack.Pop64()
  416. codeOff := stack.Pop64()
  417. length := stack.Pop64()
  418. data, ok := subslice(code, codeOff, length)
  419. if !ok {
  420. return nil, firstErr(err, ErrCodeOutOfBounds)
  421. }
  422. dest, ok := subslice(memory, memOff, length)
  423. if !ok {
  424. return nil, firstErr(err, ErrMemoryOutOfBounds)
  425. }
  426. copy(dest, data)
  427. dbg.Printf(" => [%v, %v, %v] %X\n", memOff, codeOff, length, data)
  428. case GASPRICE_DEPRECATED: // 0x3A
  429. stack.Push(Zero256)
  430. dbg.Printf(" => %X (GASPRICE IS DEPRECATED)\n")
  431. case EXTCODESIZE: // 0x3B
  432. addr := stack.Pop()
  433. if ok = useGas(gas, GasGetAccount); !ok {
  434. return nil, firstErr(err, ErrInsufficientGas)
  435. }
  436. acc := vm.appState.GetAccount(addr)
  437. if acc == nil {
  438. return nil, firstErr(err, ErrUnknownAddress)
  439. }
  440. code := acc.Code
  441. l := uint64(len(code))
  442. stack.Push64(l)
  443. dbg.Printf(" => %d\n", l)
  444. case EXTCODECOPY: // 0x3C
  445. addr := stack.Pop()
  446. if ok = useGas(gas, GasGetAccount); !ok {
  447. return nil, firstErr(err, ErrInsufficientGas)
  448. }
  449. acc := vm.appState.GetAccount(addr)
  450. if acc == nil {
  451. return nil, firstErr(err, ErrUnknownAddress)
  452. }
  453. code := acc.Code
  454. memOff := stack.Pop64()
  455. codeOff := stack.Pop64()
  456. length := stack.Pop64()
  457. data, ok := subslice(code, codeOff, length)
  458. if !ok {
  459. return nil, firstErr(err, ErrCodeOutOfBounds)
  460. }
  461. dest, ok := subslice(memory, memOff, length)
  462. if !ok {
  463. return nil, firstErr(err, ErrMemoryOutOfBounds)
  464. }
  465. copy(dest, data)
  466. dbg.Printf(" => [%v, %v, %v] %X\n", memOff, codeOff, length, data)
  467. case BLOCKHASH: // 0x40
  468. stack.Push(Zero256)
  469. dbg.Printf(" => 0x%X (NOT SUPPORTED)\n", stack.Peek().Bytes())
  470. case COINBASE: // 0x41
  471. stack.Push(Zero256)
  472. dbg.Printf(" => 0x%X (NOT SUPPORTED)\n", stack.Peek().Bytes())
  473. case TIMESTAMP: // 0x42
  474. time := vm.params.BlockTime
  475. stack.Push64(uint64(time))
  476. dbg.Printf(" => 0x%X\n", time)
  477. case BLOCKHEIGHT: // 0x43
  478. number := uint64(vm.params.BlockHeight)
  479. stack.Push64(number)
  480. dbg.Printf(" => 0x%X\n", number)
  481. case GASLIMIT: // 0x45
  482. stack.Push64(vm.params.GasLimit)
  483. dbg.Printf(" => %v\n", vm.params.GasLimit)
  484. case POP: // 0x50
  485. stack.Pop()
  486. dbg.Printf(" => %v\n", vm.params.GasLimit)
  487. case MLOAD: // 0x51
  488. offset := stack.Pop64()
  489. data, ok := subslice(memory, offset, 32)
  490. if !ok {
  491. return nil, firstErr(err, ErrMemoryOutOfBounds)
  492. }
  493. stack.Push(LeftPadWord256(data))
  494. dbg.Printf(" => 0x%X\n", data)
  495. case MSTORE: // 0x52
  496. offset, data := stack.Pop64(), stack.Pop()
  497. dest, ok := subslice(memory, offset, 32)
  498. if !ok {
  499. return nil, firstErr(err, ErrMemoryOutOfBounds)
  500. }
  501. copy(dest, data[:])
  502. dbg.Printf(" => 0x%X\n", data)
  503. case MSTORE8: // 0x53
  504. offset, val := stack.Pop64(), byte(stack.Pop64()&0xFF)
  505. if len(memory) <= int(offset) {
  506. return nil, firstErr(err, ErrMemoryOutOfBounds)
  507. }
  508. memory[offset] = val
  509. dbg.Printf(" => [%v] 0x%X\n", offset, val)
  510. case SLOAD: // 0x54
  511. loc := stack.Pop()
  512. data := vm.appState.GetStorage(callee.Address, loc)
  513. stack.Push(data)
  514. dbg.Printf(" {0x%X : 0x%X}\n", loc, data)
  515. case SSTORE: // 0x55
  516. loc, data := stack.Pop(), stack.Pop()
  517. vm.appState.SetStorage(callee.Address, loc, data)
  518. useGas(gas, GasStorageUpdate)
  519. dbg.Printf(" {0x%X : 0x%X}\n", loc, data)
  520. case JUMP: // 0x56
  521. err = jump(code, stack.Pop64(), &pc)
  522. continue
  523. case JUMPI: // 0x57
  524. pos, cond := stack.Pop64(), stack.Pop()
  525. if !cond.IsZero() {
  526. err = jump(code, pos, &pc)
  527. continue
  528. }
  529. dbg.Printf(" ~> false\n")
  530. case PC: // 0x58
  531. stack.Push64(pc)
  532. case MSIZE: // 0x59
  533. stack.Push64(uint64(len(memory)))
  534. case GAS: // 0x5A
  535. stack.Push64(*gas)
  536. dbg.Printf(" => %X\n", *gas)
  537. case JUMPDEST: // 0x5B
  538. dbg.Printf("\n")
  539. // Do nothing
  540. 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:
  541. a := uint64(op - PUSH1 + 1)
  542. codeSegment, ok := subslice(code, pc+1, a)
  543. if !ok {
  544. return nil, firstErr(err, ErrCodeOutOfBounds)
  545. }
  546. res := LeftPadWord256(codeSegment)
  547. stack.Push(res)
  548. pc += a
  549. dbg.Printf(" => 0x%X\n", res)
  550. stack.Print(10)
  551. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  552. n := int(op - DUP1 + 1)
  553. stack.Dup(n)
  554. dbg.Printf(" => [%d] 0x%X\n", n, stack.Peek().Bytes())
  555. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  556. n := int(op - SWAP1 + 2)
  557. stack.Swap(n)
  558. dbg.Printf(" => [%d] %X\n", n, stack.Peek())
  559. stack.Print(10)
  560. case LOG0, LOG1, LOG2, LOG3, LOG4:
  561. n := int(op - LOG0)
  562. topics := make([]Word256, n)
  563. offset, size := stack.Pop64(), stack.Pop64()
  564. for i := 0; i < n; i++ {
  565. topics[i] = stack.Pop()
  566. }
  567. data, ok := subslice(memory, offset, size)
  568. if !ok {
  569. return nil, firstErr(err, ErrMemoryOutOfBounds)
  570. }
  571. log := &Log{
  572. callee.Address,
  573. topics,
  574. data,
  575. vm.params.BlockHeight,
  576. }
  577. vm.appState.AddLog(log)
  578. dbg.Printf(" => %v\n", log)
  579. case CREATE: // 0xF0
  580. contractValue := stack.Pop64()
  581. offset, size := stack.Pop64(), stack.Pop64()
  582. input, ok := subslice(memory, offset, size)
  583. if !ok {
  584. return nil, firstErr(err, ErrMemoryOutOfBounds)
  585. }
  586. // Check balance
  587. if callee.Balance < contractValue {
  588. return nil, firstErr(err, ErrInsufficientBalance)
  589. }
  590. // TODO charge for gas to create account _ the code length * GasCreateByte
  591. newAccount := vm.appState.CreateAccount(callee)
  592. // Run the input to get the contract code.
  593. ret, err_ := vm.Call(callee, newAccount, input, input, contractValue, gas)
  594. if err_ != nil {
  595. stack.Push(Zero256)
  596. } else {
  597. newAccount.Code = ret // Set the code
  598. stack.Push(newAccount.Address)
  599. }
  600. case CALL, CALLCODE: // 0xF1, 0xF2
  601. gasLimit := stack.Pop64()
  602. addr, value := stack.Pop(), stack.Pop64()
  603. inOffset, inSize := stack.Pop64(), stack.Pop64() // inputs
  604. retOffset, retSize := stack.Pop64(), stack.Pop64() // outputs
  605. dbg.Printf(" => %X\n", addr)
  606. // Get the arguments from the memory
  607. args, ok := subslice(memory, inOffset, inSize)
  608. if !ok {
  609. return nil, firstErr(err, ErrMemoryOutOfBounds)
  610. }
  611. // Ensure that gasLimit is reasonable
  612. if *gas < gasLimit {
  613. return nil, firstErr(err, ErrInsufficientGas)
  614. } else {
  615. *gas -= gasLimit
  616. // NOTE: we will return any used gas later.
  617. }
  618. // Begin execution
  619. var ret []byte
  620. var err error
  621. if nativeContract := nativeContracts[addr]; nativeContract != nil {
  622. // Native contract
  623. ret, err = nativeContract(args, &gasLimit)
  624. } else {
  625. // EVM contract
  626. if ok = useGas(gas, GasGetAccount); !ok {
  627. return nil, firstErr(err, ErrInsufficientGas)
  628. }
  629. acc := vm.appState.GetAccount(addr)
  630. if acc == nil {
  631. return nil, firstErr(err, ErrUnknownAddress)
  632. }
  633. if op == CALLCODE {
  634. ret, err = vm.Call(callee, callee, acc.Code, args, value, gas)
  635. } else {
  636. ret, err = vm.Call(callee, acc, acc.Code, args, value, gas)
  637. }
  638. }
  639. // Push result
  640. if err != nil {
  641. stack.Push(Zero256)
  642. } else {
  643. stack.Push(One256)
  644. dest, ok := subslice(memory, retOffset, retSize)
  645. if !ok {
  646. return nil, firstErr(err, ErrMemoryOutOfBounds)
  647. }
  648. copy(dest, ret)
  649. }
  650. // Handle remaining gas.
  651. *gas += gasLimit
  652. dbg.Printf("resume %X (%v)\n", callee.Address, gas)
  653. case RETURN: // 0xF3
  654. offset, size := stack.Pop64(), stack.Pop64()
  655. ret, ok := subslice(memory, offset, size)
  656. if !ok {
  657. return nil, firstErr(err, ErrMemoryOutOfBounds)
  658. }
  659. dbg.Printf(" => [%v, %v] (%d) 0x%X\n", offset, size, len(ret), ret)
  660. return ret, nil
  661. case SUICIDE: // 0xFF
  662. addr := stack.Pop()
  663. if ok = useGas(gas, GasGetAccount); !ok {
  664. return nil, firstErr(err, ErrInsufficientGas)
  665. }
  666. // TODO if the receiver is , then make it the fee.
  667. receiver := vm.appState.GetAccount(addr)
  668. if receiver == nil {
  669. return nil, firstErr(err, ErrUnknownAddress)
  670. }
  671. balance := callee.Balance
  672. receiver.Balance += balance
  673. vm.appState.UpdateAccount(receiver)
  674. vm.appState.RemoveAccount(callee)
  675. dbg.Printf(" => (%X) %v\n", addr[:4], balance)
  676. fallthrough
  677. default:
  678. dbg.Printf("(pc) %-3v Invalid opcode %X\n", pc, op)
  679. panic(fmt.Errorf("Invalid opcode %X", op))
  680. }
  681. pc++
  682. }
  683. }
  684. func subslice(data []byte, offset, length uint64) (ret []byte, ok bool) {
  685. size := uint64(len(data))
  686. if size < offset {
  687. return nil, false
  688. } else if size < offset+length {
  689. ret, ok = data[offset:], true
  690. ret = RightPadBytes(ret, 32)
  691. } else {
  692. ret, ok = data[offset:offset+length], true
  693. }
  694. return
  695. }
  696. func rightMostBytes(data []byte, n int) []byte {
  697. size := MinInt(len(data), n)
  698. offset := len(data) - size
  699. return data[offset:]
  700. }
  701. func codeGetOp(code []byte, n uint64) OpCode {
  702. if uint64(len(code)) <= n {
  703. return OpCode(0) // stop
  704. } else {
  705. return OpCode(code[n])
  706. }
  707. }
  708. func jump(code []byte, to uint64, pc *uint64) (err error) {
  709. dest := codeGetOp(code, to)
  710. if dest != JUMPDEST {
  711. dbg.Printf(" ~> %v invalid jump dest %v\n", to, dest)
  712. return ErrInvalidJumpDest
  713. }
  714. dbg.Printf(" ~> %v\n", to)
  715. *pc = to
  716. return nil
  717. }
  718. func firstErr(errA, errB error) error {
  719. if errA != nil {
  720. return errA
  721. } else {
  722. return errB
  723. }
  724. }
  725. func useGas(gas *uint64, gasToUse uint64) bool {
  726. if *gas > gasToUse {
  727. *gas -= gasToUse
  728. return true
  729. } else {
  730. return false
  731. }
  732. }
  733. func transfer(from, to *Account, amount uint64) error {
  734. if from.Balance < amount {
  735. return ErrInsufficientBalance
  736. } else {
  737. from.Balance -= amount
  738. to.Balance += amount
  739. return nil
  740. }
  741. }