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.

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