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.

1264 lines
43 KiB

10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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 state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "testing"
  7. "time"
  8. acm "github.com/tendermint/tendermint/account"
  9. . "github.com/tendermint/tendermint/common"
  10. dbm "github.com/tendermint/tendermint/db"
  11. "github.com/tendermint/tendermint/events"
  12. ptypes "github.com/tendermint/tendermint/permission/types"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. /*
  16. Permission Tests:
  17. - SendTx:
  18. x - 1 input, no perm, call perm, create perm
  19. x - 1 input, perm
  20. x - 2 inputs, one with perm one without
  21. - CallTx, CALL
  22. x - 1 input, no perm, send perm, create perm
  23. x - 1 input, perm
  24. x - contract runs call but doesn't have call perm
  25. x - contract runs call and has call perm
  26. x - contract runs call (with perm), runs contract that runs call (without perm)
  27. x - contract runs call (with perm), runs contract that runs call (with perm)
  28. - CallTx for Create, CREATE
  29. x - 1 input, no perm, send perm, call perm
  30. x - 1 input, perm
  31. x - contract runs create but doesn't have create perm
  32. x - contract runs create but has perm
  33. x - contract runs call with empty address (has call and create perm)
  34. - NameTx
  35. - no perm, send perm, call perm
  36. - with perm
  37. - BondTx
  38. x - 1 input, no perm
  39. x - 1 input, perm
  40. x - 1 bonder with perm, input without send or bond
  41. x - 1 bonder with perm, input with send
  42. x - 1 bonder with perm, input with bond
  43. x - 2 inputs, one with perm one without
  44. - SendTx for new account
  45. x - 1 input, 1 unknown ouput, input with send, not create (fail)
  46. x - 1 input, 1 unknown ouput, input with send and create (pass)
  47. x - 2 inputs, 1 unknown ouput, both inputs with send, one with create, one without (fail)
  48. x - 2 inputs, 1 known output, 1 unknown ouput, one input with create, one without (fail)
  49. x - 2 inputs, 1 unknown ouput, both inputs with send, both inputs with create (pass )
  50. x - 2 inputs, 1 known output, 1 unknown ouput, both inputs with create, (pass)
  51. - CALL for new account
  52. x - unknown output, without create (fail)
  53. x - unknown output, with create (pass)
  54. - SNative (CallTx, CALL):
  55. - for each of CallTx, Call
  56. x - call each snative without permission, fails
  57. x - call each snative with permission, pass
  58. - list:
  59. x - base: has,set,unset
  60. x - globals: set
  61. x - roles: has, add, rm
  62. */
  63. // keys
  64. var user = makeUsers(10)
  65. var chainID = "testchain"
  66. func makeUsers(n int) []*acm.PrivAccount {
  67. accounts := []*acm.PrivAccount{}
  68. for i := 0; i < n; i++ {
  69. secret := []byte("mysecret" + strconv.Itoa(i))
  70. user := acm.GenPrivAccountFromSecret(secret)
  71. accounts = append(accounts, user)
  72. }
  73. return accounts
  74. }
  75. var (
  76. PermsAllFalse = ptypes.ZeroAccountPermissions
  77. )
  78. func newBaseGenDoc(globalPerm, accountPerm ptypes.AccountPermissions) GenesisDoc {
  79. genAccounts := []GenesisAccount{}
  80. for _, u := range user[:5] {
  81. accountPermCopy := accountPerm // Create new instance for custom overridability.
  82. genAccounts = append(genAccounts, GenesisAccount{
  83. Address: u.Address,
  84. Amount: 1000000,
  85. Permissions: &accountPermCopy,
  86. })
  87. }
  88. return GenesisDoc{
  89. GenesisTime: time.Now(),
  90. ChainID: chainID,
  91. Params: &GenesisParams{
  92. GlobalPermissions: &globalPerm,
  93. },
  94. Accounts: genAccounts,
  95. Validators: []GenesisValidator{
  96. GenesisValidator{
  97. PubKey: user[0].PubKey.(acm.PubKeyEd25519),
  98. Amount: 10,
  99. UnbondTo: []BasicAccount{
  100. BasicAccount{
  101. Address: user[0].Address,
  102. },
  103. },
  104. },
  105. },
  106. }
  107. }
  108. func TestSendFails(t *testing.T) {
  109. stateDB := dbm.GetDB("state")
  110. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  111. genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true)
  112. genDoc.Accounts[2].Permissions.Base.Set(ptypes.Call, true)
  113. genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true)
  114. st := MakeGenesisState(stateDB, &genDoc)
  115. blockCache := NewBlockCache(st)
  116. //-------------------
  117. // send txs
  118. // simple send tx should fail
  119. tx := types.NewSendTx()
  120. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  121. t.Fatal(err)
  122. }
  123. tx.AddOutput(user[1].Address, 5)
  124. tx.SignInput(chainID, 0, user[0])
  125. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  126. t.Fatal("Expected error")
  127. } else {
  128. fmt.Println(err)
  129. }
  130. // simple send tx with call perm should fail
  131. tx = types.NewSendTx()
  132. if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil {
  133. t.Fatal(err)
  134. }
  135. tx.AddOutput(user[4].Address, 5)
  136. tx.SignInput(chainID, 0, user[2])
  137. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  138. t.Fatal("Expected error")
  139. } else {
  140. fmt.Println(err)
  141. }
  142. // simple send tx with create perm should fail
  143. tx = types.NewSendTx()
  144. if err := tx.AddInput(blockCache, user[3].PubKey, 5); err != nil {
  145. t.Fatal(err)
  146. }
  147. tx.AddOutput(user[4].Address, 5)
  148. tx.SignInput(chainID, 0, user[3])
  149. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  150. t.Fatal("Expected error")
  151. } else {
  152. fmt.Println(err)
  153. }
  154. // simple send tx to unknown account without create_account perm should fail
  155. acc := blockCache.GetAccount(user[3].Address)
  156. acc.Permissions.Base.Set(ptypes.Send, true)
  157. blockCache.UpdateAccount(acc)
  158. tx = types.NewSendTx()
  159. if err := tx.AddInput(blockCache, user[3].PubKey, 5); err != nil {
  160. t.Fatal(err)
  161. }
  162. tx.AddOutput(user[6].Address, 5)
  163. tx.SignInput(chainID, 0, user[3])
  164. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  165. t.Fatal("Expected error")
  166. } else {
  167. fmt.Println(err)
  168. }
  169. }
  170. func TestName(t *testing.T) {
  171. stateDB := dbm.GetDB("state")
  172. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  173. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true)
  174. genDoc.Accounts[1].Permissions.Base.Set(ptypes.Name, true)
  175. st := MakeGenesisState(stateDB, &genDoc)
  176. blockCache := NewBlockCache(st)
  177. //-------------------
  178. // name txs
  179. // simple name tx without perm should fail
  180. tx, err := types.NewNameTx(st, user[0].PubKey, "somename", "somedata", 10000, 100)
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. tx.Sign(chainID, user[0])
  185. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  186. t.Fatal("Expected error")
  187. } else {
  188. fmt.Println(err)
  189. }
  190. // simple name tx with perm should pass
  191. tx, err = types.NewNameTx(st, user[1].PubKey, "somename", "somedata", 10000, 100)
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. tx.Sign(chainID, user[1])
  196. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  197. t.Fatal(err)
  198. }
  199. }
  200. func TestCallFails(t *testing.T) {
  201. stateDB := dbm.GetDB("state")
  202. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  203. genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true)
  204. genDoc.Accounts[2].Permissions.Base.Set(ptypes.Call, true)
  205. genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true)
  206. st := MakeGenesisState(stateDB, &genDoc)
  207. blockCache := NewBlockCache(st)
  208. //-------------------
  209. // call txs
  210. // simple call tx should fail
  211. tx, _ := types.NewCallTx(blockCache, user[0].PubKey, user[4].Address, nil, 100, 100, 100)
  212. tx.Sign(chainID, user[0])
  213. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  214. t.Fatal("Expected error")
  215. } else {
  216. fmt.Println(err)
  217. }
  218. // simple call tx with send permission should fail
  219. tx, _ = types.NewCallTx(blockCache, user[1].PubKey, user[4].Address, nil, 100, 100, 100)
  220. tx.Sign(chainID, user[1])
  221. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  222. t.Fatal("Expected error")
  223. } else {
  224. fmt.Println(err)
  225. }
  226. // simple call tx with create permission should fail
  227. tx, _ = types.NewCallTx(blockCache, user[3].PubKey, user[4].Address, nil, 100, 100, 100)
  228. tx.Sign(chainID, user[3])
  229. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  230. t.Fatal("Expected error")
  231. } else {
  232. fmt.Println(err)
  233. }
  234. //-------------------
  235. // create txs
  236. // simple call create tx should fail
  237. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, nil, nil, 100, 100, 100)
  238. tx.Sign(chainID, user[0])
  239. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  240. t.Fatal("Expected error")
  241. } else {
  242. fmt.Println(err)
  243. }
  244. // simple call create tx with send perm should fail
  245. tx, _ = types.NewCallTx(blockCache, user[1].PubKey, nil, nil, 100, 100, 100)
  246. tx.Sign(chainID, user[1])
  247. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  248. t.Fatal("Expected error")
  249. } else {
  250. fmt.Println(err)
  251. }
  252. // simple call create tx with call perm should fail
  253. tx, _ = types.NewCallTx(blockCache, user[2].PubKey, nil, nil, 100, 100, 100)
  254. tx.Sign(chainID, user[2])
  255. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  256. t.Fatal("Expected error")
  257. } else {
  258. fmt.Println(err)
  259. }
  260. }
  261. func TestSendPermission(t *testing.T) {
  262. stateDB := dbm.GetDB("state")
  263. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  264. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission
  265. st := MakeGenesisState(stateDB, &genDoc)
  266. blockCache := NewBlockCache(st)
  267. // A single input, having the permission, should succeed
  268. tx := types.NewSendTx()
  269. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  270. t.Fatal(err)
  271. }
  272. tx.AddOutput(user[1].Address, 5)
  273. tx.SignInput(chainID, 0, user[0])
  274. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  275. t.Fatal("Transaction failed", err)
  276. }
  277. // Two inputs, one with permission, one without, should fail
  278. tx = types.NewSendTx()
  279. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  280. t.Fatal(err)
  281. }
  282. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  283. t.Fatal(err)
  284. }
  285. tx.AddOutput(user[2].Address, 10)
  286. tx.SignInput(chainID, 0, user[0])
  287. tx.SignInput(chainID, 1, user[1])
  288. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  289. t.Fatal("Expected error")
  290. } else {
  291. fmt.Println(err)
  292. }
  293. }
  294. func TestCallPermission(t *testing.T) {
  295. stateDB := dbm.GetDB("state")
  296. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  297. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission
  298. st := MakeGenesisState(stateDB, &genDoc)
  299. blockCache := NewBlockCache(st)
  300. //------------------------------
  301. // call to simple contract
  302. fmt.Println("\n##### SIMPLE CONTRACT")
  303. // create simple contract
  304. simpleContractAddr := NewContractAddress(user[0].Address, 100)
  305. simpleAcc := &acm.Account{
  306. Address: simpleContractAddr,
  307. Balance: 0,
  308. Code: []byte{0x60},
  309. Sequence: 0,
  310. StorageRoot: Zero256.Bytes(),
  311. Permissions: ptypes.ZeroAccountPermissions,
  312. }
  313. st.UpdateAccount(simpleAcc)
  314. // A single input, having the permission, should succeed
  315. tx, _ := types.NewCallTx(blockCache, user[0].PubKey, simpleContractAddr, nil, 100, 100, 100)
  316. tx.Sign(chainID, user[0])
  317. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  318. t.Fatal("Transaction failed", err)
  319. }
  320. //----------------------------------------------------------
  321. // call to contract that calls simple contract - without perm
  322. fmt.Println("\n##### CALL TO SIMPLE CONTRACT (FAIL)")
  323. // create contract that calls the simple contract
  324. contractCode := callContractCode(simpleContractAddr)
  325. caller1ContractAddr := NewContractAddress(user[0].Address, 101)
  326. caller1Acc := &acm.Account{
  327. Address: caller1ContractAddr,
  328. Balance: 10000,
  329. Code: contractCode,
  330. Sequence: 0,
  331. StorageRoot: Zero256.Bytes(),
  332. Permissions: ptypes.ZeroAccountPermissions,
  333. }
  334. blockCache.UpdateAccount(caller1Acc)
  335. // A single input, having the permission, but the contract doesn't have permission
  336. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100)
  337. tx.Sign(chainID, user[0])
  338. // we need to subscribe to the Receive event to detect the exception
  339. _, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(caller1ContractAddr)) //
  340. if exception == "" {
  341. t.Fatal("Expected exception")
  342. }
  343. //----------------------------------------------------------
  344. // call to contract that calls simple contract - with perm
  345. fmt.Println("\n##### CALL TO SIMPLE CONTRACT (PASS)")
  346. // A single input, having the permission, and the contract has permission
  347. caller1Acc.Permissions.Base.Set(ptypes.Call, true)
  348. blockCache.UpdateAccount(caller1Acc)
  349. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100)
  350. tx.Sign(chainID, user[0])
  351. // we need to subscribe to the Receive event to detect the exception
  352. _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(caller1ContractAddr)) //
  353. if exception != "" {
  354. t.Fatal("Unexpected exception:", exception)
  355. }
  356. //----------------------------------------------------------
  357. // call to contract that calls contract that calls simple contract - without perm
  358. // caller1Contract calls simpleContract. caller2Contract calls caller1Contract.
  359. // caller1Contract does not have call perms, but caller2Contract does.
  360. fmt.Println("\n##### CALL TO CONTRACT CALLING SIMPLE CONTRACT (FAIL)")
  361. contractCode2 := callContractCode(caller1ContractAddr)
  362. caller2ContractAddr := NewContractAddress(user[0].Address, 102)
  363. caller2Acc := &acm.Account{
  364. Address: caller2ContractAddr,
  365. Balance: 1000,
  366. Code: contractCode2,
  367. Sequence: 0,
  368. StorageRoot: Zero256.Bytes(),
  369. Permissions: ptypes.ZeroAccountPermissions,
  370. }
  371. caller1Acc.Permissions.Base.Set(ptypes.Call, false)
  372. caller2Acc.Permissions.Base.Set(ptypes.Call, true)
  373. blockCache.UpdateAccount(caller1Acc)
  374. blockCache.UpdateAccount(caller2Acc)
  375. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100)
  376. tx.Sign(chainID, user[0])
  377. // we need to subscribe to the Receive event to detect the exception
  378. _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(caller1ContractAddr)) //
  379. if exception == "" {
  380. t.Fatal("Expected exception")
  381. }
  382. //----------------------------------------------------------
  383. // call to contract that calls contract that calls simple contract - without perm
  384. // caller1Contract calls simpleContract. caller2Contract calls caller1Contract.
  385. // both caller1 and caller2 have permission
  386. fmt.Println("\n##### CALL TO CONTRACT CALLING SIMPLE CONTRACT (PASS)")
  387. caller1Acc.Permissions.Base.Set(ptypes.Call, true)
  388. blockCache.UpdateAccount(caller1Acc)
  389. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100)
  390. tx.Sign(chainID, user[0])
  391. // we need to subscribe to the Receive event to detect the exception
  392. _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(caller1ContractAddr)) //
  393. if exception != "" {
  394. t.Fatal("Unexpected exception", exception)
  395. }
  396. }
  397. func TestCreatePermission(t *testing.T) {
  398. stateDB := dbm.GetDB("state")
  399. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  400. genDoc.Accounts[0].Permissions.Base.Set(ptypes.CreateContract, true) // give the 0 account permission
  401. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission
  402. st := MakeGenesisState(stateDB, &genDoc)
  403. blockCache := NewBlockCache(st)
  404. //------------------------------
  405. // create a simple contract
  406. fmt.Println("\n##### CREATE SIMPLE CONTRACT")
  407. contractCode := []byte{0x60}
  408. createCode := wrapContractForCreate(contractCode)
  409. // A single input, having the permission, should succeed
  410. tx, _ := types.NewCallTx(blockCache, user[0].PubKey, nil, createCode, 100, 100, 100)
  411. tx.Sign(chainID, user[0])
  412. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  413. t.Fatal("Transaction failed", err)
  414. }
  415. // ensure the contract is there
  416. contractAddr := NewContractAddress(tx.Input.Address, tx.Input.Sequence)
  417. contractAcc := blockCache.GetAccount(contractAddr)
  418. if contractAcc == nil {
  419. t.Fatalf("failed to create contract %X", contractAddr)
  420. }
  421. if bytes.Compare(contractAcc.Code, contractCode) != 0 {
  422. t.Fatalf("contract does not have correct code. Got %X, expected %X", contractAcc.Code, contractCode)
  423. }
  424. //------------------------------
  425. // create contract that uses the CREATE op
  426. fmt.Println("\n##### CREATE FACTORY")
  427. contractCode = []byte{0x60}
  428. createCode = wrapContractForCreate(contractCode)
  429. factoryCode := createContractCode()
  430. createFactoryCode := wrapContractForCreate(factoryCode)
  431. // A single input, having the permission, should succeed
  432. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, nil, createFactoryCode, 100, 100, 100)
  433. tx.Sign(chainID, user[0])
  434. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  435. t.Fatal("Transaction failed", err)
  436. }
  437. // ensure the contract is there
  438. contractAddr = NewContractAddress(tx.Input.Address, tx.Input.Sequence)
  439. contractAcc = blockCache.GetAccount(contractAddr)
  440. if contractAcc == nil {
  441. t.Fatalf("failed to create contract %X", contractAddr)
  442. }
  443. if bytes.Compare(contractAcc.Code, factoryCode) != 0 {
  444. t.Fatalf("contract does not have correct code. Got %X, expected %X", contractAcc.Code, factoryCode)
  445. }
  446. //------------------------------
  447. // call the contract (should FAIL)
  448. fmt.Println("\n###### CALL THE FACTORY (FAIL)")
  449. // A single input, having the permission, should succeed
  450. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100)
  451. tx.Sign(chainID, user[0])
  452. // we need to subscribe to the Receive event to detect the exception
  453. _, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(contractAddr)) //
  454. if exception == "" {
  455. t.Fatal("expected exception")
  456. }
  457. //------------------------------
  458. // call the contract (should PASS)
  459. fmt.Println("\n###### CALL THE FACTORY (PASS)")
  460. contractAcc.Permissions.Base.Set(ptypes.CreateContract, true)
  461. blockCache.UpdateAccount(contractAcc)
  462. // A single input, having the permission, should succeed
  463. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100)
  464. tx.Sign(chainID, user[0])
  465. // we need to subscribe to the Receive event to detect the exception
  466. _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(contractAddr)) //
  467. if exception != "" {
  468. t.Fatal("unexpected exception", exception)
  469. }
  470. //--------------------------------
  471. fmt.Println("\n##### CALL to empty address")
  472. zeroAddr := LeftPadBytes([]byte{}, 20)
  473. code := callContractCode(zeroAddr)
  474. contractAddr = NewContractAddress(user[0].Address, 110)
  475. contractAcc = &acm.Account{
  476. Address: contractAddr,
  477. Balance: 1000,
  478. Code: code,
  479. Sequence: 0,
  480. StorageRoot: Zero256.Bytes(),
  481. Permissions: ptypes.ZeroAccountPermissions,
  482. }
  483. contractAcc.Permissions.Base.Set(ptypes.Call, true)
  484. contractAcc.Permissions.Base.Set(ptypes.CreateContract, true)
  485. blockCache.UpdateAccount(contractAcc)
  486. // this should call the 0 address but not create ...
  487. tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 10000, 100)
  488. tx.Sign(chainID, user[0])
  489. // we need to subscribe to the Receive event to detect the exception
  490. _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(zeroAddr)) //
  491. if exception != "" {
  492. t.Fatal("unexpected exception", exception)
  493. }
  494. zeroAcc := blockCache.GetAccount(zeroAddr)
  495. if len(zeroAcc.Code) != 0 {
  496. t.Fatal("the zero account was given code from a CALL!")
  497. }
  498. }
  499. func TestBondPermission(t *testing.T) {
  500. stateDB := dbm.GetDB("state")
  501. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  502. st := MakeGenesisState(stateDB, &genDoc)
  503. blockCache := NewBlockCache(st)
  504. var bondAcc *acm.Account
  505. //------------------------------
  506. // one bonder without permission should fail
  507. tx, _ := types.NewBondTx(user[1].PubKey)
  508. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  509. t.Fatal(err)
  510. }
  511. tx.AddOutput(user[1].Address, 5)
  512. tx.SignInput(chainID, 0, user[1])
  513. tx.SignBond(chainID, user[1])
  514. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  515. t.Fatal("Expected error")
  516. } else {
  517. fmt.Println(err)
  518. }
  519. //------------------------------
  520. // one bonder with permission should pass
  521. bondAcc = blockCache.GetAccount(user[1].Address)
  522. bondAcc.Permissions.Base.Set(ptypes.Bond, true)
  523. blockCache.UpdateAccount(bondAcc)
  524. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  525. t.Fatal("Unexpected error", err)
  526. }
  527. // reset state (we can only bond with an account once ..)
  528. genDoc = newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  529. st = MakeGenesisState(stateDB, &genDoc)
  530. blockCache = NewBlockCache(st)
  531. bondAcc = blockCache.GetAccount(user[1].Address)
  532. bondAcc.Permissions.Base.Set(ptypes.Bond, true)
  533. blockCache.UpdateAccount(bondAcc)
  534. //------------------------------
  535. // one bonder with permission and an input without send should fail
  536. tx, _ = types.NewBondTx(user[1].PubKey)
  537. if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil {
  538. t.Fatal(err)
  539. }
  540. tx.AddOutput(user[1].Address, 5)
  541. tx.SignInput(chainID, 0, user[2])
  542. tx.SignBond(chainID, user[1])
  543. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  544. t.Fatal("Expected error")
  545. } else {
  546. fmt.Println(err)
  547. }
  548. // reset state (we can only bond with an account once ..)
  549. genDoc = newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  550. st = MakeGenesisState(stateDB, &genDoc)
  551. blockCache = NewBlockCache(st)
  552. bondAcc = blockCache.GetAccount(user[1].Address)
  553. bondAcc.Permissions.Base.Set(ptypes.Bond, true)
  554. blockCache.UpdateAccount(bondAcc)
  555. //------------------------------
  556. // one bonder with permission and an input with send should pass
  557. sendAcc := blockCache.GetAccount(user[2].Address)
  558. sendAcc.Permissions.Base.Set(ptypes.Send, true)
  559. blockCache.UpdateAccount(sendAcc)
  560. tx, _ = types.NewBondTx(user[1].PubKey)
  561. if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil {
  562. t.Fatal(err)
  563. }
  564. tx.AddOutput(user[1].Address, 5)
  565. tx.SignInput(chainID, 0, user[2])
  566. tx.SignBond(chainID, user[1])
  567. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  568. t.Fatal("Unexpected error", err)
  569. }
  570. // reset state (we can only bond with an account once ..)
  571. genDoc = newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  572. st = MakeGenesisState(stateDB, &genDoc)
  573. blockCache = NewBlockCache(st)
  574. bondAcc = blockCache.GetAccount(user[1].Address)
  575. bondAcc.Permissions.Base.Set(ptypes.Bond, true)
  576. blockCache.UpdateAccount(bondAcc)
  577. //------------------------------
  578. // one bonder with permission and an input with bond should pass
  579. sendAcc.Permissions.Base.Set(ptypes.Bond, true)
  580. blockCache.UpdateAccount(sendAcc)
  581. tx, _ = types.NewBondTx(user[1].PubKey)
  582. if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil {
  583. t.Fatal(err)
  584. }
  585. tx.AddOutput(user[1].Address, 5)
  586. tx.SignInput(chainID, 0, user[2])
  587. tx.SignBond(chainID, user[1])
  588. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  589. t.Fatal("Unexpected error", err)
  590. }
  591. // reset state (we can only bond with an account once ..)
  592. genDoc = newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  593. st = MakeGenesisState(stateDB, &genDoc)
  594. blockCache = NewBlockCache(st)
  595. bondAcc = blockCache.GetAccount(user[1].Address)
  596. bondAcc.Permissions.Base.Set(ptypes.Bond, true)
  597. blockCache.UpdateAccount(bondAcc)
  598. //------------------------------
  599. // one bonder with permission and an input from that bonder and an input without send or bond should fail
  600. tx, _ = types.NewBondTx(user[1].PubKey)
  601. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  602. t.Fatal(err)
  603. }
  604. if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil {
  605. t.Fatal(err)
  606. }
  607. tx.AddOutput(user[1].Address, 5)
  608. tx.SignInput(chainID, 0, user[1])
  609. tx.SignInput(chainID, 1, user[2])
  610. tx.SignBond(chainID, user[1])
  611. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  612. t.Fatal("Expected error")
  613. }
  614. }
  615. func TestCreateAccountPermission(t *testing.T) {
  616. stateDB := dbm.GetDB("state")
  617. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  618. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission
  619. genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission
  620. genDoc.Accounts[0].Permissions.Base.Set(ptypes.CreateAccount, true) // give the 0 account permission
  621. st := MakeGenesisState(stateDB, &genDoc)
  622. blockCache := NewBlockCache(st)
  623. //----------------------------------------------------------
  624. // SendTx to unknown account
  625. // A single input, having the permission, should succeed
  626. tx := types.NewSendTx()
  627. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  628. t.Fatal(err)
  629. }
  630. tx.AddOutput(user[6].Address, 5)
  631. tx.SignInput(chainID, 0, user[0])
  632. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  633. t.Fatal("Transaction failed", err)
  634. }
  635. // Two inputs, both with send, one with create, one without, should fail
  636. tx = types.NewSendTx()
  637. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  638. t.Fatal(err)
  639. }
  640. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  641. t.Fatal(err)
  642. }
  643. tx.AddOutput(user[7].Address, 10)
  644. tx.SignInput(chainID, 0, user[0])
  645. tx.SignInput(chainID, 1, user[1])
  646. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  647. t.Fatal("Expected error")
  648. } else {
  649. fmt.Println(err)
  650. }
  651. // Two inputs, both with send, one with create, one without, two ouputs (one known, one unknown) should fail
  652. tx = types.NewSendTx()
  653. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  654. t.Fatal(err)
  655. }
  656. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  657. t.Fatal(err)
  658. }
  659. tx.AddOutput(user[7].Address, 4)
  660. tx.AddOutput(user[4].Address, 6)
  661. tx.SignInput(chainID, 0, user[0])
  662. tx.SignInput(chainID, 1, user[1])
  663. if err := ExecTx(blockCache, tx, true, nil); err == nil {
  664. t.Fatal("Expected error")
  665. } else {
  666. fmt.Println(err)
  667. }
  668. // Two inputs, both with send, both with create, should pass
  669. acc := blockCache.GetAccount(user[1].Address)
  670. acc.Permissions.Base.Set(ptypes.CreateAccount, true)
  671. blockCache.UpdateAccount(acc)
  672. tx = types.NewSendTx()
  673. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  674. t.Fatal(err)
  675. }
  676. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  677. t.Fatal(err)
  678. }
  679. tx.AddOutput(user[7].Address, 10)
  680. tx.SignInput(chainID, 0, user[0])
  681. tx.SignInput(chainID, 1, user[1])
  682. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  683. t.Fatal("Unexpected error", err)
  684. }
  685. // Two inputs, both with send, both with create, two outputs (one known, one unknown) should pass
  686. tx = types.NewSendTx()
  687. if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil {
  688. t.Fatal(err)
  689. }
  690. if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil {
  691. t.Fatal(err)
  692. }
  693. tx.AddOutput(user[7].Address, 7)
  694. tx.AddOutput(user[4].Address, 3)
  695. tx.SignInput(chainID, 0, user[0])
  696. tx.SignInput(chainID, 1, user[1])
  697. if err := ExecTx(blockCache, tx, true, nil); err != nil {
  698. t.Fatal("Unexpected error", err)
  699. }
  700. //----------------------------------------------------------
  701. // CALL to unknown account
  702. acc = blockCache.GetAccount(user[0].Address)
  703. acc.Permissions.Base.Set(ptypes.Call, true)
  704. blockCache.UpdateAccount(acc)
  705. // call to contract that calls unknown account - without create_account perm
  706. // create contract that calls the simple contract
  707. contractCode := callContractCode(user[9].Address)
  708. caller1ContractAddr := NewContractAddress(user[4].Address, 101)
  709. caller1Acc := &acm.Account{
  710. Address: caller1ContractAddr,
  711. Balance: 0,
  712. Code: contractCode,
  713. Sequence: 0,
  714. StorageRoot: Zero256.Bytes(),
  715. Permissions: ptypes.ZeroAccountPermissions,
  716. }
  717. blockCache.UpdateAccount(caller1Acc)
  718. // A single input, having the permission, but the contract doesn't have permission
  719. txCall, _ := types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100)
  720. txCall.Sign(chainID, user[0])
  721. // we need to subscribe to the Receive event to detect the exception
  722. _, exception := execTxWaitEvent(t, blockCache, txCall, types.EventStringAccReceive(caller1ContractAddr)) //
  723. if exception == "" {
  724. t.Fatal("Expected exception")
  725. }
  726. // NOTE: for a contract to be able to CreateAccount, it must be able to call
  727. // NOTE: for a user to be able to CreateAccount, it must be able to send!
  728. caller1Acc.Permissions.Base.Set(ptypes.CreateAccount, true)
  729. caller1Acc.Permissions.Base.Set(ptypes.Call, true)
  730. blockCache.UpdateAccount(caller1Acc)
  731. // A single input, having the permission, but the contract doesn't have permission
  732. txCall, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100)
  733. txCall.Sign(chainID, user[0])
  734. // we need to subscribe to the Receive event to detect the exception
  735. _, exception = execTxWaitEvent(t, blockCache, txCall, types.EventStringAccReceive(caller1ContractAddr)) //
  736. if exception != "" {
  737. t.Fatal("Unexpected exception", exception)
  738. }
  739. }
  740. // holla at my boy
  741. var DougAddress = append([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, []byte("THISISDOUG")...)
  742. func TestSNativeCALL(t *testing.T) {
  743. stateDB := dbm.GetDB("state")
  744. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  745. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission
  746. genDoc.Accounts[3].Permissions.Base.Set(ptypes.Bond, true) // some arbitrary permission to play with
  747. genDoc.Accounts[3].Permissions.AddRole("bumble")
  748. genDoc.Accounts[3].Permissions.AddRole("bee")
  749. st := MakeGenesisState(stateDB, &genDoc)
  750. blockCache := NewBlockCache(st)
  751. //----------------------------------------------------------
  752. // Test CALL to SNative contracts
  753. // make the main contract once
  754. doug := &acm.Account{
  755. Address: DougAddress,
  756. Balance: 0,
  757. Code: nil,
  758. Sequence: 0,
  759. StorageRoot: Zero256.Bytes(),
  760. Permissions: ptypes.ZeroAccountPermissions,
  761. }
  762. doug.Permissions.Base.Set(ptypes.Call, true)
  763. //doug.Permissions.Base.Set(ptypes.HasBase, true)
  764. blockCache.UpdateAccount(doug)
  765. fmt.Println("\n#### HasBase")
  766. // HasBase
  767. snativeAddress, data := snativePermTestInputCALL("has_base", user[3], ptypes.Bond, false)
  768. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  769. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  770. // return value should be true or false as a 32 byte array...
  771. if !IsZeros(ret[:31]) || ret[31] != byte(1) {
  772. return fmt.Errorf("Expected 1. Got %X", ret)
  773. }
  774. return nil
  775. })
  776. fmt.Println("\n#### SetBase")
  777. // SetBase
  778. snativeAddress, data = snativePermTestInputCALL("set_base", user[3], ptypes.Bond, false)
  779. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  780. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  781. snativeAddress, data = snativePermTestInputCALL("has_base", user[3], ptypes.Bond, false)
  782. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  783. // return value should be true or false as a 32 byte array...
  784. if !IsZeros(ret) {
  785. return fmt.Errorf("Expected 0. Got %X", ret)
  786. }
  787. return nil
  788. })
  789. snativeAddress, data = snativePermTestInputCALL("set_base", user[3], ptypes.CreateContract, true)
  790. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  791. snativeAddress, data = snativePermTestInputCALL("has_base", user[3], ptypes.CreateContract, false)
  792. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  793. // return value should be true or false as a 32 byte array...
  794. if !IsZeros(ret[:31]) || ret[31] != byte(1) {
  795. return fmt.Errorf("Expected 1. Got %X", ret)
  796. }
  797. return nil
  798. })
  799. fmt.Println("\n#### UnsetBase")
  800. // UnsetBase
  801. snativeAddress, data = snativePermTestInputCALL("unset_base", user[3], ptypes.CreateContract, false)
  802. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  803. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  804. snativeAddress, data = snativePermTestInputCALL("has_base", user[3], ptypes.CreateContract, false)
  805. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  806. if !IsZeros(ret) {
  807. return fmt.Errorf("Expected 0. Got %X", ret)
  808. }
  809. return nil
  810. })
  811. fmt.Println("\n#### SetGlobal")
  812. // SetGlobalPerm
  813. snativeAddress, data = snativePermTestInputCALL("set_global", user[3], ptypes.CreateContract, true)
  814. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  815. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  816. snativeAddress, data = snativePermTestInputCALL("has_base", user[3], ptypes.CreateContract, false)
  817. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  818. // return value should be true or false as a 32 byte array...
  819. if !IsZeros(ret[:31]) || ret[31] != byte(1) {
  820. return fmt.Errorf("Expected 1. Got %X", ret)
  821. }
  822. return nil
  823. })
  824. fmt.Println("\n#### HasRole")
  825. // HasRole
  826. snativeAddress, data = snativeRoleTestInputCALL("has_role", user[3], "bumble")
  827. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  828. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  829. if !IsZeros(ret[:31]) || ret[31] != byte(1) {
  830. return fmt.Errorf("Expected 1. Got %X", ret)
  831. }
  832. return nil
  833. })
  834. fmt.Println("\n#### AddRole")
  835. // AddRole
  836. snativeAddress, data = snativeRoleTestInputCALL("has_role", user[3], "chuck")
  837. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  838. if !IsZeros(ret) {
  839. return fmt.Errorf("Expected 0. Got %X", ret)
  840. }
  841. return nil
  842. })
  843. snativeAddress, data = snativeRoleTestInputCALL("add_role", user[3], "chuck")
  844. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  845. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  846. snativeAddress, data = snativeRoleTestInputCALL("has_role", user[3], "chuck")
  847. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  848. if !IsZeros(ret[:31]) || ret[31] != byte(1) {
  849. return fmt.Errorf("Expected 1. Got %X", ret)
  850. }
  851. return nil
  852. })
  853. fmt.Println("\n#### RmRole")
  854. // RmRole
  855. snativeAddress, data = snativeRoleTestInputCALL("rm_role", user[3], "chuck")
  856. testSNativeCALLExpectFail(t, blockCache, doug, snativeAddress, data)
  857. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error { return nil })
  858. snativeAddress, data = snativeRoleTestInputCALL("has_role", user[3], "chuck")
  859. testSNativeCALLExpectPass(t, blockCache, doug, snativeAddress, data, func(ret []byte) error {
  860. if !IsZeros(ret) {
  861. return fmt.Errorf("Expected 0. Got %X", ret)
  862. }
  863. return nil
  864. })
  865. }
  866. func TestSNativeTx(t *testing.T) {
  867. stateDB := dbm.GetDB("state")
  868. genDoc := newBaseGenDoc(PermsAllFalse, PermsAllFalse)
  869. genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission
  870. genDoc.Accounts[3].Permissions.Base.Set(ptypes.Bond, true) // some arbitrary permission to play with
  871. genDoc.Accounts[3].Permissions.AddRole("bumble")
  872. genDoc.Accounts[3].Permissions.AddRole("bee")
  873. st := MakeGenesisState(stateDB, &genDoc)
  874. blockCache := NewBlockCache(st)
  875. //----------------------------------------------------------
  876. // Test SNativeTx
  877. fmt.Println("\n#### SetBase")
  878. // SetBase
  879. snativeArgs := snativePermTestInputTx("set_base", user[3], ptypes.Bond, false)
  880. testSNativeTxExpectFail(t, blockCache, snativeArgs)
  881. testSNativeTxExpectPass(t, blockCache, ptypes.SetBase, snativeArgs)
  882. acc := blockCache.GetAccount(user[3].Address)
  883. if v, _ := acc.Permissions.Base.Get(ptypes.Bond); v {
  884. t.Fatal("expected permission to be set false")
  885. }
  886. snativeArgs = snativePermTestInputTx("set_base", user[3], ptypes.CreateContract, true)
  887. testSNativeTxExpectPass(t, blockCache, ptypes.SetBase, snativeArgs)
  888. acc = blockCache.GetAccount(user[3].Address)
  889. if v, _ := acc.Permissions.Base.Get(ptypes.CreateContract); !v {
  890. t.Fatal("expected permission to be set true")
  891. }
  892. fmt.Println("\n#### UnsetBase")
  893. // UnsetBase
  894. snativeArgs = snativePermTestInputTx("unset_base", user[3], ptypes.CreateContract, false)
  895. testSNativeTxExpectFail(t, blockCache, snativeArgs)
  896. testSNativeTxExpectPass(t, blockCache, ptypes.UnsetBase, snativeArgs)
  897. acc = blockCache.GetAccount(user[3].Address)
  898. if v, _ := acc.Permissions.Base.Get(ptypes.CreateContract); v {
  899. t.Fatal("expected permission to be set false")
  900. }
  901. fmt.Println("\n#### SetGlobal")
  902. // SetGlobalPerm
  903. snativeArgs = snativePermTestInputTx("set_global", user[3], ptypes.CreateContract, true)
  904. testSNativeTxExpectFail(t, blockCache, snativeArgs)
  905. testSNativeTxExpectPass(t, blockCache, ptypes.SetGlobal, snativeArgs)
  906. acc = blockCache.GetAccount(ptypes.GlobalPermissionsAddress)
  907. if v, _ := acc.Permissions.Base.Get(ptypes.CreateContract); !v {
  908. t.Fatal("expected permission to be set true")
  909. }
  910. fmt.Println("\n#### AddRole")
  911. // AddRole
  912. snativeArgs = snativeRoleTestInputTx("add_role", user[3], "chuck")
  913. testSNativeTxExpectFail(t, blockCache, snativeArgs)
  914. testSNativeTxExpectPass(t, blockCache, ptypes.AddRole, snativeArgs)
  915. acc = blockCache.GetAccount(user[3].Address)
  916. if v := acc.Permissions.HasRole("chuck"); !v {
  917. t.Fatal("expected role to be added")
  918. }
  919. fmt.Println("\n#### RmRole")
  920. // RmRole
  921. snativeArgs = snativeRoleTestInputTx("rm_role", user[3], "chuck")
  922. testSNativeTxExpectFail(t, blockCache, snativeArgs)
  923. testSNativeTxExpectPass(t, blockCache, ptypes.RmRole, snativeArgs)
  924. acc = blockCache.GetAccount(user[3].Address)
  925. if v := acc.Permissions.HasRole("chuck"); v {
  926. t.Fatal("expected role to be removed")
  927. }
  928. }
  929. //-------------------------------------------------------------------------------------
  930. // helpers
  931. var ExceptionTimeOut = "timed out waiting for event"
  932. // run ExecTx and wait for the Receive event on given addr
  933. // returns the msg data and an error/exception
  934. func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx types.Tx, eventid string) (interface{}, string) {
  935. evsw := events.NewEventSwitch()
  936. evsw.Start()
  937. ch := make(chan interface{})
  938. evsw.AddListenerForEvent("test", eventid, func(msg interface{}) {
  939. ch <- msg
  940. })
  941. evc := events.NewEventCache(evsw)
  942. go func() {
  943. if err := ExecTx(blockCache, tx, true, evc); err != nil {
  944. ch <- err.Error()
  945. }
  946. evc.Flush()
  947. }()
  948. ticker := time.NewTicker(5 * time.Second)
  949. var msg interface{}
  950. select {
  951. case msg = <-ch:
  952. case <-ticker.C:
  953. return nil, ExceptionTimeOut
  954. }
  955. switch ev := msg.(type) {
  956. case types.EventMsgCallTx:
  957. return ev, ev.Exception
  958. case types.EventMsgCall:
  959. return ev, ev.Exception
  960. case string:
  961. return nil, ev
  962. default:
  963. return ev, ""
  964. }
  965. }
  966. // give a contract perms for an snative, call it, it calls the snative, but shouldn't have permission
  967. func testSNativeCALLExpectFail(t *testing.T, blockCache *BlockCache, doug *acm.Account, snativeAddress, data []byte) {
  968. testSNativeCALL(t, false, blockCache, doug, snativeAddress, data, nil)
  969. }
  970. // give a contract perms for an snative, call it, it calls the snative, ensure the check funciton (f) succeeds
  971. func testSNativeCALLExpectPass(t *testing.T, blockCache *BlockCache, doug *acm.Account, snativeAddress, data []byte, f func([]byte) error) {
  972. testSNativeCALL(t, true, blockCache, doug, snativeAddress, data, f)
  973. }
  974. func testSNativeCALL(t *testing.T, expectPass bool, blockCache *BlockCache, doug *acm.Account, snativeAddress, data []byte, f func([]byte) error) {
  975. if expectPass {
  976. perm, err := ptypes.PermStringToFlag(TrimmedString(snativeAddress))
  977. if err != nil {
  978. t.Fatal(err)
  979. }
  980. doug.Permissions.Base.Set(perm, true)
  981. }
  982. var addr []byte
  983. contractCode := callContractCode(snativeAddress)
  984. doug.Code = contractCode
  985. blockCache.UpdateAccount(doug)
  986. addr = doug.Address
  987. tx, _ := types.NewCallTx(blockCache, user[0].PubKey, addr, data, 100, 10000, 100)
  988. tx.Sign(chainID, user[0])
  989. fmt.Println("subscribing to", types.EventStringAccReceive(snativeAddress))
  990. ev, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccReceive(snativeAddress))
  991. if exception == ExceptionTimeOut {
  992. t.Fatal("Timed out waiting for event")
  993. }
  994. if expectPass {
  995. if exception != "" {
  996. t.Fatal("Unexpected exception", exception)
  997. }
  998. evv := ev.(types.EventMsgCall)
  999. ret := evv.Return
  1000. if err := f(ret); err != nil {
  1001. t.Fatal(err)
  1002. }
  1003. } else {
  1004. if exception == "" {
  1005. t.Fatal("Expected exception")
  1006. }
  1007. }
  1008. }
  1009. func testSNativeTxExpectFail(t *testing.T, blockCache *BlockCache, snativeArgs ptypes.PermArgs) {
  1010. testSNativeTx(t, false, blockCache, 0, snativeArgs)
  1011. }
  1012. func testSNativeTxExpectPass(t *testing.T, blockCache *BlockCache, perm ptypes.PermFlag, snativeArgs ptypes.PermArgs) {
  1013. testSNativeTx(t, true, blockCache, perm, snativeArgs)
  1014. }
  1015. func testSNativeTx(t *testing.T, expectPass bool, blockCache *BlockCache, perm ptypes.PermFlag, snativeArgs ptypes.PermArgs) {
  1016. if expectPass {
  1017. acc := blockCache.GetAccount(user[0].Address)
  1018. acc.Permissions.Base.Set(perm, true)
  1019. blockCache.UpdateAccount(acc)
  1020. }
  1021. tx, _ := types.NewPermissionsTx(blockCache, user[0].PubKey, snativeArgs)
  1022. tx.Sign(chainID, user[0])
  1023. err := ExecTx(blockCache, tx, true, nil)
  1024. if expectPass {
  1025. if err != nil {
  1026. t.Fatal("Unexpected exception", err)
  1027. }
  1028. } else {
  1029. if err == nil {
  1030. t.Fatal("Expected exception")
  1031. }
  1032. }
  1033. }
  1034. func boolToWord256(v bool) Word256 {
  1035. var vint byte
  1036. if v {
  1037. vint = 0x1
  1038. } else {
  1039. vint = 0x0
  1040. }
  1041. return LeftPadWord256([]byte{vint})
  1042. }
  1043. func snativePermTestInputCALL(name string, user *acm.PrivAccount, perm ptypes.PermFlag, val bool) (addr []byte, data []byte) {
  1044. addr = LeftPadWord256([]byte(name)).Postfix(20)
  1045. switch name {
  1046. case "has_base", "unset_base":
  1047. data = LeftPadBytes(user.Address, 32)
  1048. data = append(data, Uint64ToWord256(uint64(perm)).Bytes()...)
  1049. case "set_base":
  1050. data = LeftPadBytes(user.Address, 32)
  1051. data = append(data, Uint64ToWord256(uint64(perm)).Bytes()...)
  1052. data = append(data, boolToWord256(val).Bytes()...)
  1053. case "set_global":
  1054. data = Uint64ToWord256(uint64(perm)).Bytes()
  1055. data = append(data, boolToWord256(val).Bytes()...)
  1056. }
  1057. return
  1058. }
  1059. func snativePermTestInputTx(name string, user *acm.PrivAccount, perm ptypes.PermFlag, val bool) (snativeArgs ptypes.PermArgs) {
  1060. switch name {
  1061. case "has_base":
  1062. snativeArgs = &ptypes.HasBaseArgs{user.Address, perm}
  1063. case "unset_base":
  1064. snativeArgs = &ptypes.UnsetBaseArgs{user.Address, perm}
  1065. case "set_base":
  1066. snativeArgs = &ptypes.SetBaseArgs{user.Address, perm, val}
  1067. case "set_global":
  1068. snativeArgs = &ptypes.SetGlobalArgs{perm, val}
  1069. }
  1070. return
  1071. }
  1072. func snativeRoleTestInputCALL(name string, user *acm.PrivAccount, role string) (addr []byte, data []byte) {
  1073. addr = LeftPadWord256([]byte(name)).Postfix(20)
  1074. data = LeftPadBytes(user.Address, 32)
  1075. data = append(data, LeftPadBytes([]byte(role), 32)...)
  1076. return
  1077. }
  1078. func snativeRoleTestInputTx(name string, user *acm.PrivAccount, role string) (snativeArgs ptypes.PermArgs) {
  1079. switch name {
  1080. case "has_role":
  1081. snativeArgs = &ptypes.HasRoleArgs{user.Address, role}
  1082. case "add_role":
  1083. snativeArgs = &ptypes.AddRoleArgs{user.Address, role}
  1084. case "rm_role":
  1085. snativeArgs = &ptypes.RmRoleArgs{user.Address, role}
  1086. }
  1087. return
  1088. }
  1089. // convenience function for contract that calls a given address
  1090. func callContractCode(contractAddr []byte) []byte {
  1091. // calldatacopy into mem and use as input to call
  1092. memOff, inputOff := byte(0x0), byte(0x0)
  1093. contractCode := []byte{0x36, 0x60, inputOff, 0x60, memOff, 0x37}
  1094. gas1, gas2 := byte(0x1), byte(0x1)
  1095. value := byte(0x1)
  1096. inOff := byte(0x0)
  1097. retOff, retSize := byte(0x0), byte(0x20)
  1098. // this is the code we want to run (call a contract and return)
  1099. contractCode = append(contractCode, []byte{0x60, retSize, 0x60, retOff, 0x36, 0x60, inOff, 0x60, value, 0x73}...)
  1100. contractCode = append(contractCode, contractAddr...)
  1101. contractCode = append(contractCode, []byte{0x61, gas1, gas2, 0xf1, 0x60, 0x20, 0x60, 0x0, 0xf3}...)
  1102. return contractCode
  1103. }
  1104. // convenience function for contract that is a factory for the code that comes as call data
  1105. func createContractCode() []byte {
  1106. // TODO: gas ...
  1107. // calldatacopy the calldatasize
  1108. memOff, inputOff := byte(0x0), byte(0x0)
  1109. contractCode := []byte{0x60, memOff, 0x60, inputOff, 0x36, 0x37}
  1110. // create
  1111. value := byte(0x1)
  1112. contractCode = append(contractCode, []byte{0x60, value, 0x36, 0x60, memOff, 0xf0}...)
  1113. return contractCode
  1114. }
  1115. // wrap a contract in create code
  1116. func wrapContractForCreate(contractCode []byte) []byte {
  1117. // the is the code we need to return the contractCode when the contract is initialized
  1118. lenCode := len(contractCode)
  1119. // push code to the stack
  1120. code := append([]byte{0x7f}, RightPadWord256(contractCode).Bytes()...)
  1121. // store it in memory
  1122. code = append(code, []byte{0x60, 0x0, 0x52}...)
  1123. // return whats in memory
  1124. code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...)
  1125. // return init code, contract code, expected return
  1126. return code
  1127. }