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.

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