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.

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