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.

1370 lines
40 KiB

  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "math"
  11. "math/big"
  12. "net/http"
  13. "os"
  14. "sort"
  15. "strconv"
  16. "testing"
  17. "time"
  18. ethCommon "github.com/ethereum/go-ethereum/common"
  19. swagger "github.com/getkin/kin-openapi/openapi3filter"
  20. "github.com/gin-gonic/gin"
  21. "github.com/hermeznetwork/hermez-node/common"
  22. "github.com/hermeznetwork/hermez-node/db"
  23. "github.com/hermeznetwork/hermez-node/db/historydb"
  24. "github.com/hermeznetwork/hermez-node/db/l2db"
  25. "github.com/hermeznetwork/hermez-node/db/statedb"
  26. "github.com/hermeznetwork/hermez-node/eth"
  27. "github.com/hermeznetwork/hermez-node/log"
  28. "github.com/hermeznetwork/hermez-node/test"
  29. "github.com/iden3/go-iden3-crypto/babyjub"
  30. "github.com/mitchellh/copystructure"
  31. "github.com/stretchr/testify/assert"
  32. "github.com/stretchr/testify/require"
  33. )
  34. const apiPort = ":4010"
  35. const apiURL = "http://localhost" + apiPort + "/"
  36. type testCommon struct {
  37. blocks []common.Block
  38. tokens []historydb.TokenWithUSD
  39. batches []testBatch
  40. coordinators []historydb.CoordinatorAPI
  41. usrAddr string
  42. usrBjj string
  43. accs []common.Account
  44. usrTxs []historyTxAPI
  45. allTxs []historyTxAPI
  46. exits []exitAPI
  47. usrExits []exitAPI
  48. poolTxsToSend []receivedPoolTx
  49. poolTxsToReceive []sendPoolTx
  50. auths []accountCreationAuthAPI
  51. router *swagger.Router
  52. }
  53. // TxSortFields represents the fields needed to sort L1 and L2 transactions
  54. type txSortFields struct {
  55. BatchNum *common.BatchNum
  56. Position int
  57. }
  58. // TxSortFielder is a interface that allows sorting L1 and L2 transactions in a combined way
  59. type txSortFielder interface {
  60. SortFields() txSortFields
  61. L1() *common.L1Tx
  62. L2() *common.L2Tx
  63. }
  64. // TxsSort array of TxSortFielder
  65. type txsSort []txSortFielder
  66. func (t txsSort) Len() int { return len(t) }
  67. func (t txsSort) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
  68. func (t txsSort) Less(i, j int) bool {
  69. // i not forged yet
  70. isf := t[i].SortFields()
  71. jsf := t[j].SortFields()
  72. if isf.BatchNum == nil {
  73. if jsf.BatchNum != nil { // j is already forged
  74. return false
  75. }
  76. // Both aren't forged, is i in a smaller position?
  77. return isf.Position < jsf.Position
  78. }
  79. // i is forged
  80. if jsf.BatchNum == nil {
  81. return false // j is not forged
  82. }
  83. // Both are forged
  84. if *isf.BatchNum == *jsf.BatchNum {
  85. // At the same batch, is i in a smaller position?
  86. return isf.Position < jsf.Position
  87. }
  88. // At different batches, is i in a smaller batch?
  89. return *isf.BatchNum < *jsf.BatchNum
  90. }
  91. type wrappedL1 common.L1Tx
  92. // SortFields implements TxSortFielder
  93. func (tx *wrappedL1) SortFields() txSortFields {
  94. return txSortFields{
  95. BatchNum: tx.BatchNum,
  96. Position: tx.Position,
  97. }
  98. }
  99. // L1 implements TxSortFielder
  100. func (tx *wrappedL1) L1() *common.L1Tx {
  101. l1tx := common.L1Tx(*tx)
  102. return &l1tx
  103. }
  104. // L2 implements TxSortFielder
  105. func (tx *wrappedL1) L2() *common.L2Tx { return nil }
  106. type wrappedL2 common.L2Tx
  107. // SortFields implements TxSortFielder
  108. func (tx *wrappedL2) SortFields() txSortFields {
  109. return txSortFields{
  110. BatchNum: &tx.BatchNum,
  111. Position: tx.Position,
  112. }
  113. }
  114. // L1 implements TxSortFielder
  115. func (tx *wrappedL2) L1() *common.L1Tx { return nil }
  116. // L2 implements TxSortFielder
  117. func (tx *wrappedL2) L2() *common.L2Tx {
  118. l2tx := common.L2Tx(*tx)
  119. return &l2tx
  120. }
  121. var tc testCommon
  122. var config configAPI
  123. func TestMain(m *testing.M) {
  124. // Init swagger
  125. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  126. // Init DBs
  127. // HistoryDB
  128. pass := os.Getenv("POSTGRES_PASS")
  129. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  130. if err != nil {
  131. panic(err)
  132. }
  133. hdb := historydb.NewHistoryDB(database)
  134. err = hdb.Reorg(-1)
  135. if err != nil {
  136. panic(err)
  137. }
  138. // StateDB
  139. dir, err := ioutil.TempDir("", "tmpdb")
  140. if err != nil {
  141. panic(err)
  142. }
  143. defer func() {
  144. if err := os.RemoveAll(dir); err != nil {
  145. panic(err)
  146. }
  147. }()
  148. sdb, err := statedb.NewStateDB(dir, statedb.TypeTxSelector, 0)
  149. if err != nil {
  150. panic(err)
  151. }
  152. // L2DB
  153. l2DB := l2db.NewL2DB(database, 10, 100, 24*time.Hour)
  154. test.CleanL2DB(l2DB.DB())
  155. config.RollupConstants.ExchangeMultiplier = eth.RollupConstExchangeMultiplier
  156. config.RollupConstants.ExitIdx = eth.RollupConstExitIDx
  157. config.RollupConstants.ReservedIdx = eth.RollupConstReservedIDx
  158. config.RollupConstants.LimitLoadAmount, _ = new(big.Int).SetString("340282366920938463463374607431768211456", 10)
  159. config.RollupConstants.LimitL2TransferAmount, _ = new(big.Int).SetString("6277101735386680763835789423207666416102355444464034512896", 10)
  160. config.RollupConstants.LimitTokens = eth.RollupConstLimitTokens
  161. config.RollupConstants.L1CoordinatorTotalBytes = eth.RollupConstL1CoordinatorTotalBytes
  162. config.RollupConstants.L1UserTotalBytes = eth.RollupConstL1UserTotalBytes
  163. config.RollupConstants.MaxL1UserTx = eth.RollupConstMaxL1UserTx
  164. config.RollupConstants.MaxL1Tx = eth.RollupConstMaxL1Tx
  165. config.RollupConstants.InputSHAConstantBytes = eth.RollupConstInputSHAConstantBytes
  166. config.RollupConstants.NumBuckets = eth.RollupConstNumBuckets
  167. config.RollupConstants.MaxWithdrawalDelay = eth.RollupConstMaxWithdrawalDelay
  168. var rollupPublicConstants eth.RollupPublicConstants
  169. rollupPublicConstants.AbsoluteMaxL1L2BatchTimeout = 240
  170. rollupPublicConstants.HermezAuctionContract = ethCommon.HexToAddress("0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e")
  171. rollupPublicConstants.HermezGovernanceDAOAddress = ethCommon.HexToAddress("0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4")
  172. rollupPublicConstants.SafetyAddress = ethCommon.HexToAddress("0xE5904695748fe4A84b40b3fc79De2277660BD1D3")
  173. rollupPublicConstants.TokenHEZ = ethCommon.HexToAddress("0xf784709d2317D872237C4bC22f867d1BAe2913AB")
  174. rollupPublicConstants.WithdrawDelayerContract = ethCommon.HexToAddress("0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe")
  175. var verifier eth.RollupVerifierStruct
  176. verifier.MaxTx = 512
  177. verifier.NLevels = 32
  178. rollupPublicConstants.Verifiers = append(rollupPublicConstants.Verifiers, verifier)
  179. var auctionConstants eth.AuctionConstants
  180. auctionConstants.BlocksPerSlot = 40
  181. auctionConstants.GenesisBlockNum = 100
  182. auctionConstants.GovernanceAddress = ethCommon.HexToAddress("0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4")
  183. auctionConstants.InitialMinimalBidding, _ = new(big.Int).SetString("10000000000000000000", 10)
  184. auctionConstants.HermezRollup = ethCommon.HexToAddress("0xEa960515F8b4C237730F028cBAcF0a28E7F45dE0")
  185. auctionConstants.TokenHEZ = ethCommon.HexToAddress("0xf784709d2317D872237C4bC22f867d1BAe2913AB")
  186. var wdelayerConstants eth.WDelayerConstants
  187. wdelayerConstants.HermezRollup = ethCommon.HexToAddress("0xEa960515F8b4C237730F028cBAcF0a28E7F45dE0")
  188. wdelayerConstants.MaxEmergencyModeTime = uint64(1000000)
  189. wdelayerConstants.MaxWithdrawalDelay = uint64(10000000)
  190. config.RollupConstants.PublicConstants = rollupPublicConstants
  191. config.AuctionConstants = auctionConstants
  192. config.WDelayerConstants = wdelayerConstants
  193. // Init API
  194. api := gin.Default()
  195. if err := SetAPIEndpoints(
  196. true,
  197. true,
  198. api,
  199. hdb,
  200. sdb,
  201. l2DB,
  202. &config,
  203. ); err != nil {
  204. panic(err)
  205. }
  206. // Start server
  207. server := &http.Server{Addr: apiPort, Handler: api}
  208. go func() {
  209. if err := server.ListenAndServe(); err != nil &&
  210. err != http.ErrServerClosed {
  211. panic(err)
  212. }
  213. }()
  214. // Populate DBs
  215. // Clean DB
  216. err = h.Reorg(0)
  217. if err != nil {
  218. panic(err)
  219. }
  220. // Gen blocks and add them to DB
  221. const nBlocks = 5
  222. blocks := test.GenBlocks(1, nBlocks+1)
  223. err = h.AddBlocks(blocks)
  224. if err != nil {
  225. panic(err)
  226. }
  227. // Gen tokens and add them to DB
  228. const nTokens = 10
  229. tokens := test.GenTokens(nTokens, blocks)
  230. err = h.AddTokens(tokens)
  231. if err != nil {
  232. panic(err)
  233. }
  234. // Set token value
  235. tokensUSD := []historydb.TokenWithUSD{}
  236. for i, tkn := range tokens {
  237. token := historydb.TokenWithUSD{
  238. TokenID: tkn.TokenID,
  239. EthBlockNum: tkn.EthBlockNum,
  240. EthAddr: tkn.EthAddr,
  241. Name: tkn.Name,
  242. Symbol: tkn.Symbol,
  243. Decimals: tkn.Decimals,
  244. }
  245. // Set value of 50% of the tokens
  246. if i%2 != 0 {
  247. value := float64(i) * 1.234567
  248. now := time.Now().UTC()
  249. token.USD = &value
  250. token.USDUpdate = &now
  251. err = h.UpdateTokenValue(token.Symbol, value)
  252. if err != nil {
  253. panic(err)
  254. }
  255. }
  256. tokensUSD = append(tokensUSD, token)
  257. }
  258. // Gen batches and add them to DB
  259. const nBatches = 10
  260. batches := test.GenBatches(nBatches, blocks)
  261. err = h.AddBatches(batches)
  262. if err != nil {
  263. panic(err)
  264. }
  265. // Gen accounts and add them to HistoryDB and StateDB
  266. const totalAccounts = 40
  267. const userAccounts = 4
  268. usrAddr := ethCommon.BigToAddress(big.NewInt(4896847))
  269. privK := babyjub.NewRandPrivKey()
  270. usrBjj := privK.Public()
  271. accs := test.GenAccounts(totalAccounts, userAccounts, tokens, &usrAddr, usrBjj, batches)
  272. err = h.AddAccounts(accs)
  273. if err != nil {
  274. panic(err)
  275. }
  276. for i := 0; i < len(accs); i++ {
  277. if _, err := s.CreateAccount(accs[i].Idx, &accs[i]); err != nil {
  278. panic(err)
  279. }
  280. }
  281. // Gen exits and add them to DB
  282. const totalExits = 40
  283. exits := test.GenExitTree(totalExits, batches, accs)
  284. err = h.AddExitTree(exits)
  285. if err != nil {
  286. panic(err)
  287. }
  288. // Gen L1Txs and add them to DB
  289. const totalL1Txs = 40
  290. const userL1Txs = 4
  291. usrL1Txs, othrL1Txs := test.GenL1Txs(256, totalL1Txs, userL1Txs, &usrAddr, accs, tokens, blocks, batches)
  292. // Gen L2Txs and add them to DB
  293. const totalL2Txs = 20
  294. const userL2Txs = 4
  295. usrL2Txs, othrL2Txs := test.GenL2Txs(256+totalL1Txs, totalL2Txs, userL2Txs, &usrAddr, accs, tokens, blocks, batches)
  296. // Order txs
  297. sortedTxs := []txSortFielder{}
  298. for i := 0; i < len(usrL1Txs); i++ {
  299. wL1 := wrappedL1(usrL1Txs[i])
  300. sortedTxs = append(sortedTxs, &wL1)
  301. }
  302. for i := 0; i < len(othrL1Txs); i++ {
  303. wL1 := wrappedL1(othrL1Txs[i])
  304. sortedTxs = append(sortedTxs, &wL1)
  305. }
  306. for i := 0; i < len(usrL2Txs); i++ {
  307. wL2 := wrappedL2(usrL2Txs[i])
  308. sortedTxs = append(sortedTxs, &wL2)
  309. }
  310. for i := 0; i < len(othrL2Txs); i++ {
  311. wL2 := wrappedL2(othrL2Txs[i])
  312. sortedTxs = append(sortedTxs, &wL2)
  313. }
  314. sort.Sort(txsSort(sortedTxs))
  315. // Add txs to DB and prepare them for test commons
  316. usrTxs := []historyTxAPI{}
  317. allTxs := []historyTxAPI{}
  318. getTimestamp := func(blockNum int64) time.Time {
  319. for i := 0; i < len(blocks); i++ {
  320. if blocks[i].EthBlockNum == blockNum {
  321. return blocks[i].Timestamp
  322. }
  323. }
  324. panic("timesamp not found")
  325. }
  326. getToken := func(id common.TokenID) historydb.TokenWithUSD {
  327. for i := 0; i < len(tokensUSD); i++ {
  328. if tokensUSD[i].TokenID == id {
  329. return tokensUSD[i]
  330. }
  331. }
  332. panic("token not found")
  333. }
  334. getTokenByIdx := func(idx common.Idx) historydb.TokenWithUSD {
  335. for _, acc := range accs {
  336. if idx == acc.Idx {
  337. return getToken(acc.TokenID)
  338. }
  339. }
  340. panic("token not found")
  341. }
  342. usrIdxs := []string{}
  343. for _, acc := range accs {
  344. if acc.EthAddr == usrAddr || acc.PublicKey == usrBjj {
  345. for _, token := range tokens {
  346. if token.TokenID == acc.TokenID {
  347. usrIdxs = append(usrIdxs, idxToHez(acc.Idx, token.Symbol))
  348. }
  349. }
  350. }
  351. }
  352. isUsrTx := func(tx historyTxAPI) bool {
  353. for _, idx := range usrIdxs {
  354. if tx.FromIdx != nil && *tx.FromIdx == idx {
  355. return true
  356. }
  357. if tx.ToIdx == idx {
  358. return true
  359. }
  360. }
  361. return false
  362. }
  363. for _, genericTx := range sortedTxs {
  364. l1 := genericTx.L1()
  365. l2 := genericTx.L2()
  366. if l1 != nil {
  367. // Add L1 tx to DB
  368. err = h.AddL1Txs([]common.L1Tx{*l1})
  369. if err != nil {
  370. panic(err)
  371. }
  372. // L1Tx ==> historyTxAPI
  373. token := getToken(l1.TokenID)
  374. tx := historyTxAPI{
  375. IsL1: "L1",
  376. TxID: l1.TxID,
  377. Type: l1.Type,
  378. Position: l1.Position,
  379. ToIdx: idxToHez(l1.ToIdx, token.Symbol),
  380. Amount: l1.Amount.String(),
  381. BatchNum: l1.BatchNum,
  382. Timestamp: getTimestamp(l1.EthBlockNum),
  383. L1Info: &l1Info{
  384. ToForgeL1TxsNum: l1.ToForgeL1TxsNum,
  385. UserOrigin: l1.UserOrigin,
  386. FromEthAddr: ethAddrToHez(l1.FromEthAddr),
  387. FromBJJ: bjjToString(l1.FromBJJ),
  388. LoadAmount: l1.LoadAmount.String(),
  389. EthBlockNum: l1.EthBlockNum,
  390. },
  391. Token: token,
  392. }
  393. if l1.FromIdx != 0 {
  394. idxStr := idxToHez(l1.FromIdx, token.Symbol)
  395. tx.FromIdx = &idxStr
  396. }
  397. if token.USD != nil {
  398. af := new(big.Float).SetInt(l1.Amount)
  399. amountFloat, _ := af.Float64()
  400. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  401. tx.HistoricUSD = &usd
  402. laf := new(big.Float).SetInt(l1.LoadAmount)
  403. loadAmountFloat, _ := laf.Float64()
  404. loadUSD := *token.USD * loadAmountFloat / math.Pow(10, float64(token.Decimals))
  405. tx.L1Info.HistoricLoadAmountUSD = &loadUSD
  406. }
  407. allTxs = append(allTxs, tx)
  408. if isUsrTx(tx) {
  409. usrTxs = append(usrTxs, tx)
  410. }
  411. } else {
  412. // Add L2 tx to DB
  413. err = h.AddL2Txs([]common.L2Tx{*l2})
  414. if err != nil {
  415. panic(err)
  416. }
  417. // L2Tx ==> historyTxAPI
  418. var tokenID common.TokenID
  419. found := false
  420. for _, acc := range accs {
  421. if acc.Idx == l2.FromIdx {
  422. found = true
  423. tokenID = acc.TokenID
  424. break
  425. }
  426. }
  427. if !found {
  428. panic("tokenID not found")
  429. }
  430. token := getToken(tokenID)
  431. tx := historyTxAPI{
  432. IsL1: "L2",
  433. TxID: l2.TxID,
  434. Type: l2.Type,
  435. Position: l2.Position,
  436. ToIdx: idxToHez(l2.ToIdx, token.Symbol),
  437. Amount: l2.Amount.String(),
  438. BatchNum: &l2.BatchNum,
  439. Timestamp: getTimestamp(l2.EthBlockNum),
  440. L2Info: &l2Info{
  441. Nonce: l2.Nonce,
  442. Fee: l2.Fee,
  443. },
  444. Token: token,
  445. }
  446. if l2.FromIdx != 0 {
  447. idxStr := idxToHez(l2.FromIdx, token.Symbol)
  448. tx.FromIdx = &idxStr
  449. }
  450. if token.USD != nil {
  451. af := new(big.Float).SetInt(l2.Amount)
  452. amountFloat, _ := af.Float64()
  453. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  454. tx.HistoricUSD = &usd
  455. feeUSD := usd * l2.Fee.Percentage()
  456. tx.HistoricUSD = &usd
  457. tx.L2Info.HistoricFeeUSD = &feeUSD
  458. }
  459. allTxs = append(allTxs, tx)
  460. if isUsrTx(tx) {
  461. usrTxs = append(usrTxs, tx)
  462. }
  463. }
  464. }
  465. // Transform exits to API
  466. exitsToAPIExits := func(exits []common.ExitInfo, accs []common.Account, tokens []common.Token) []exitAPI {
  467. historyExits := []historydb.HistoryExit{}
  468. for _, exit := range exits {
  469. token := getTokenByIdx(exit.AccountIdx)
  470. historyExits = append(historyExits, historydb.HistoryExit{
  471. BatchNum: exit.BatchNum,
  472. AccountIdx: exit.AccountIdx,
  473. MerkleProof: exit.MerkleProof,
  474. Balance: exit.Balance,
  475. InstantWithdrawn: exit.InstantWithdrawn,
  476. DelayedWithdrawRequest: exit.DelayedWithdrawRequest,
  477. DelayedWithdrawn: exit.DelayedWithdrawn,
  478. TokenID: token.TokenID,
  479. TokenEthBlockNum: token.EthBlockNum,
  480. TokenEthAddr: token.EthAddr,
  481. TokenName: token.Name,
  482. TokenSymbol: token.Symbol,
  483. TokenDecimals: token.Decimals,
  484. TokenUSD: token.USD,
  485. TokenUSDUpdate: token.USDUpdate,
  486. })
  487. }
  488. return historyExitsToAPI(historyExits)
  489. }
  490. apiExits := exitsToAPIExits(exits, accs, tokens)
  491. // sort.Sort(apiExits)
  492. usrExits := []exitAPI{}
  493. for _, exit := range apiExits {
  494. for _, idx := range usrIdxs {
  495. if idx == exit.AccountIdx {
  496. usrExits = append(usrExits, exit)
  497. }
  498. }
  499. }
  500. // Prepare pool Txs
  501. // Generate common.PoolL2Tx
  502. // WARNING: this should be replaced once transakcio is ready
  503. poolTxs := []common.PoolL2Tx{}
  504. amount := new(big.Int)
  505. amount, ok := amount.SetString("100000000000000", 10)
  506. if !ok {
  507. panic("bad amount")
  508. }
  509. poolTx := common.PoolL2Tx{
  510. FromIdx: accs[0].Idx,
  511. ToIdx: accs[1].Idx,
  512. Amount: amount,
  513. TokenID: accs[0].TokenID,
  514. Nonce: 6,
  515. }
  516. if _, err := common.NewPoolL2Tx(&poolTx); err != nil {
  517. panic(err)
  518. }
  519. h, err := poolTx.HashToSign()
  520. if err != nil {
  521. panic(err)
  522. }
  523. poolTx.Signature = privK.SignPoseidon(h).Compress()
  524. poolTxs = append(poolTxs, poolTx)
  525. // Transform to API formats
  526. poolTxsToSend := []receivedPoolTx{}
  527. poolTxsToReceive := []sendPoolTx{}
  528. for _, poolTx := range poolTxs {
  529. // common.PoolL2Tx ==> receivedPoolTx
  530. token := getToken(poolTx.TokenID)
  531. genSendTx := receivedPoolTx{
  532. TxID: poolTx.TxID,
  533. Type: poolTx.Type,
  534. TokenID: poolTx.TokenID,
  535. FromIdx: idxToHez(poolTx.FromIdx, token.Symbol),
  536. Amount: poolTx.Amount.String(),
  537. Fee: poolTx.Fee,
  538. Nonce: poolTx.Nonce,
  539. Signature: poolTx.Signature,
  540. RqFee: &poolTx.RqFee,
  541. RqNonce: &poolTx.RqNonce,
  542. }
  543. // common.PoolL2Tx ==> receivedPoolTx
  544. genReceiveTx := sendPoolTx{
  545. TxID: poolTx.TxID,
  546. Type: poolTx.Type,
  547. FromIdx: idxToHez(poolTx.FromIdx, token.Symbol),
  548. Amount: poolTx.Amount.String(),
  549. Fee: poolTx.Fee,
  550. Nonce: poolTx.Nonce,
  551. State: poolTx.State,
  552. Signature: poolTx.Signature,
  553. Timestamp: poolTx.Timestamp,
  554. // BatchNum: poolTx.BatchNum,
  555. RqFee: &poolTx.RqFee,
  556. RqNonce: &poolTx.RqNonce,
  557. Token: token,
  558. }
  559. if poolTx.ToIdx != 0 {
  560. toIdx := idxToHez(poolTx.ToIdx, token.Symbol)
  561. genSendTx.ToIdx = &toIdx
  562. genReceiveTx.ToIdx = &toIdx
  563. }
  564. if poolTx.ToEthAddr != common.EmptyAddr {
  565. toEth := ethAddrToHez(poolTx.ToEthAddr)
  566. genSendTx.ToEthAddr = &toEth
  567. genReceiveTx.ToEthAddr = &toEth
  568. }
  569. if poolTx.ToBJJ != nil {
  570. toBJJ := bjjToString(poolTx.ToBJJ)
  571. genSendTx.ToBJJ = &toBJJ
  572. genReceiveTx.ToBJJ = &toBJJ
  573. }
  574. if poolTx.RqFromIdx != 0 {
  575. rqFromIdx := idxToHez(poolTx.RqFromIdx, token.Symbol)
  576. genSendTx.RqFromIdx = &rqFromIdx
  577. genReceiveTx.RqFromIdx = &rqFromIdx
  578. genSendTx.RqTokenID = &token.TokenID
  579. genReceiveTx.RqTokenID = &token.TokenID
  580. rqAmount := poolTx.RqAmount.String()
  581. genSendTx.RqAmount = &rqAmount
  582. genReceiveTx.RqAmount = &rqAmount
  583. if poolTx.RqToIdx != 0 {
  584. rqToIdx := idxToHez(poolTx.RqToIdx, token.Symbol)
  585. genSendTx.RqToIdx = &rqToIdx
  586. genReceiveTx.RqToIdx = &rqToIdx
  587. }
  588. if poolTx.RqToEthAddr != common.EmptyAddr {
  589. rqToEth := ethAddrToHez(poolTx.RqToEthAddr)
  590. genSendTx.RqToEthAddr = &rqToEth
  591. genReceiveTx.RqToEthAddr = &rqToEth
  592. }
  593. if poolTx.RqToBJJ != nil {
  594. rqToBJJ := bjjToString(poolTx.RqToBJJ)
  595. genSendTx.RqToBJJ = &rqToBJJ
  596. genReceiveTx.RqToBJJ = &rqToBJJ
  597. }
  598. }
  599. poolTxsToSend = append(poolTxsToSend, genSendTx)
  600. poolTxsToReceive = append(poolTxsToReceive, genReceiveTx)
  601. }
  602. // Coordinators
  603. const nCoords = 10
  604. coords := test.GenCoordinators(nCoords, blocks)
  605. err = hdb.AddCoordinators(coords)
  606. if err != nil {
  607. panic(err)
  608. }
  609. fromItem := uint(0)
  610. limit := uint(99999)
  611. coordinators, _, err := hdb.GetCoordinatorsAPI(&fromItem, &limit, historydb.OrderAsc)
  612. if err != nil {
  613. panic(err)
  614. }
  615. // Account creation auth
  616. const nAuths = 5
  617. auths := test.GenAuths(nAuths)
  618. // Transform auths to API format
  619. apiAuths := []accountCreationAuthAPI{}
  620. for _, auth := range auths {
  621. apiAuth := accountCreationAuthToAPI(auth)
  622. apiAuths = append(apiAuths, *apiAuth)
  623. }
  624. // Set testCommon
  625. tc = testCommon{
  626. blocks: blocks,
  627. tokens: tokensUSD,
  628. batches: genTestBatches(blocks, batches),
  629. coordinators: coordinators,
  630. usrAddr: ethAddrToHez(usrAddr),
  631. usrBjj: bjjToString(usrBjj),
  632. accs: accs,
  633. usrTxs: usrTxs,
  634. allTxs: allTxs,
  635. exits: apiExits,
  636. usrExits: usrExits,
  637. poolTxsToSend: poolTxsToSend,
  638. poolTxsToReceive: poolTxsToReceive,
  639. auths: apiAuths,
  640. router: router,
  641. }
  642. // Fake server
  643. if os.Getenv("FAKE_SERVER") == "yes" {
  644. for {
  645. log.Info("Running fake server until ^C is received")
  646. time.Sleep(10 * time.Second)
  647. }
  648. }
  649. // Run tests
  650. result := m.Run()
  651. // Stop server
  652. if err := server.Shutdown(context.Background()); err != nil {
  653. panic(err)
  654. }
  655. if err := database.Close(); err != nil {
  656. panic(err)
  657. }
  658. if err := os.RemoveAll(dir); err != nil {
  659. panic(err)
  660. }
  661. os.Exit(result)
  662. }
  663. func TestGetHistoryTxs(t *testing.T) {
  664. endpoint := apiURL + "transactions-history"
  665. fetchedTxs := []historyTxAPI{}
  666. appendIter := func(intr interface{}) {
  667. for i := 0; i < len(intr.(*historyTxsAPI).Txs); i++ {
  668. tmp, err := copystructure.Copy(intr.(*historyTxsAPI).Txs[i])
  669. if err != nil {
  670. panic(err)
  671. }
  672. fetchedTxs = append(fetchedTxs, tmp.(historyTxAPI))
  673. }
  674. }
  675. // Get all (no filters)
  676. limit := 8
  677. path := fmt.Sprintf("%s?limit=%d&fromItem=", endpoint, limit)
  678. err := doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  679. assert.NoError(t, err)
  680. assertHistoryTxAPIs(t, tc.allTxs, fetchedTxs)
  681. // Uncomment once tx generation for tests is fixed
  682. // // Get by ethAddr
  683. // fetchedTxs = []historyTxAPI{}
  684. // limit = 7
  685. // path = fmt.Sprintf(
  686. // "%s?hermezEthereumAddress=%s&limit=%d&fromItem=",
  687. // endpoint, tc.usrAddr, limit,
  688. // )
  689. // err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  690. // assert.NoError(t, err)
  691. // assertHistoryTxAPIs(t, tc.usrTxs, fetchedTxs)
  692. // // Get by bjj
  693. // fetchedTxs = []historyTxAPI{}
  694. // limit = 6
  695. // path = fmt.Sprintf(
  696. // "%s?BJJ=%s&limit=%d&fromItem=",
  697. // endpoint, tc.usrBjj, limit,
  698. // )
  699. // err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  700. // assert.NoError(t, err)
  701. // assertHistoryTxAPIs(t, tc.usrTxs, fetchedTxs)
  702. // Get by tokenID
  703. fetchedTxs = []historyTxAPI{}
  704. limit = 5
  705. tokenID := tc.allTxs[0].Token.TokenID
  706. path = fmt.Sprintf(
  707. "%s?tokenId=%d&limit=%d&fromItem=",
  708. endpoint, tokenID, limit,
  709. )
  710. err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  711. assert.NoError(t, err)
  712. tokenIDTxs := []historyTxAPI{}
  713. for i := 0; i < len(tc.allTxs); i++ {
  714. if tc.allTxs[i].Token.TokenID == tokenID {
  715. tokenIDTxs = append(tokenIDTxs, tc.allTxs[i])
  716. }
  717. }
  718. assertHistoryTxAPIs(t, tokenIDTxs, fetchedTxs)
  719. // idx
  720. fetchedTxs = []historyTxAPI{}
  721. limit = 4
  722. idx := tc.allTxs[0].ToIdx
  723. path = fmt.Sprintf(
  724. "%s?accountIndex=%s&limit=%d&fromItem=",
  725. endpoint, idx, limit,
  726. )
  727. err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  728. assert.NoError(t, err)
  729. idxTxs := []historyTxAPI{}
  730. for i := 0; i < len(tc.allTxs); i++ {
  731. if (tc.allTxs[i].FromIdx != nil && (*tc.allTxs[i].FromIdx)[6:] == idx[6:]) ||
  732. tc.allTxs[i].ToIdx[6:] == idx[6:] {
  733. idxTxs = append(idxTxs, tc.allTxs[i])
  734. }
  735. }
  736. assertHistoryTxAPIs(t, idxTxs, fetchedTxs)
  737. // batchNum
  738. fetchedTxs = []historyTxAPI{}
  739. limit = 3
  740. batchNum := tc.allTxs[0].BatchNum
  741. path = fmt.Sprintf(
  742. "%s?batchNum=%d&limit=%d&fromItem=",
  743. endpoint, *batchNum, limit,
  744. )
  745. err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  746. assert.NoError(t, err)
  747. batchNumTxs := []historyTxAPI{}
  748. for i := 0; i < len(tc.allTxs); i++ {
  749. if tc.allTxs[i].BatchNum != nil &&
  750. *tc.allTxs[i].BatchNum == *batchNum {
  751. batchNumTxs = append(batchNumTxs, tc.allTxs[i])
  752. }
  753. }
  754. assertHistoryTxAPIs(t, batchNumTxs, fetchedTxs)
  755. // type
  756. txTypes := []common.TxType{
  757. // Uncomment once test gen is fixed
  758. // common.TxTypeExit,
  759. // common.TxTypeTransfer,
  760. // common.TxTypeDeposit,
  761. common.TxTypeCreateAccountDeposit,
  762. // common.TxTypeCreateAccountDepositTransfer,
  763. // common.TxTypeDepositTransfer,
  764. common.TxTypeForceTransfer,
  765. // common.TxTypeForceExit,
  766. // common.TxTypeTransferToEthAddr,
  767. // common.TxTypeTransferToBJJ,
  768. }
  769. for _, txType := range txTypes {
  770. fetchedTxs = []historyTxAPI{}
  771. limit = 2
  772. path = fmt.Sprintf(
  773. "%s?type=%s&limit=%d&fromItem=",
  774. endpoint, txType, limit,
  775. )
  776. err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  777. assert.NoError(t, err)
  778. txTypeTxs := []historyTxAPI{}
  779. for i := 0; i < len(tc.allTxs); i++ {
  780. if tc.allTxs[i].Type == txType {
  781. txTypeTxs = append(txTypeTxs, tc.allTxs[i])
  782. }
  783. }
  784. assertHistoryTxAPIs(t, txTypeTxs, fetchedTxs)
  785. }
  786. // Multiple filters
  787. fetchedTxs = []historyTxAPI{}
  788. limit = 1
  789. path = fmt.Sprintf(
  790. "%s?batchNum=%d&tokenId=%d&limit=%d&fromItem=",
  791. endpoint, *batchNum, tokenID, limit,
  792. )
  793. err = doGoodReqPaginated(path, historydb.OrderAsc, &historyTxsAPI{}, appendIter)
  794. assert.NoError(t, err)
  795. mixedTxs := []historyTxAPI{}
  796. for i := 0; i < len(tc.allTxs); i++ {
  797. if tc.allTxs[i].BatchNum != nil {
  798. if *tc.allTxs[i].BatchNum == *batchNum && tc.allTxs[i].Token.TokenID == tokenID {
  799. mixedTxs = append(mixedTxs, tc.allTxs[i])
  800. }
  801. }
  802. }
  803. assertHistoryTxAPIs(t, mixedTxs, fetchedTxs)
  804. // All, in reverse order
  805. fetchedTxs = []historyTxAPI{}
  806. limit = 5
  807. path = fmt.Sprintf("%s?limit=%d&fromItem=", endpoint, limit)
  808. err = doGoodReqPaginated(path, historydb.OrderDesc, &historyTxsAPI{}, appendIter)
  809. assert.NoError(t, err)
  810. flipedTxs := []historyTxAPI{}
  811. for i := 0; i < len(tc.allTxs); i++ {
  812. flipedTxs = append(flipedTxs, tc.allTxs[len(tc.allTxs)-1-i])
  813. }
  814. assertHistoryTxAPIs(t, flipedTxs, fetchedTxs)
  815. // 400
  816. path = fmt.Sprintf(
  817. "%s?accountIndex=%s&hermezEthereumAddress=%s",
  818. endpoint, idx, tc.usrAddr,
  819. )
  820. err = doBadReq("GET", path, nil, 400)
  821. assert.NoError(t, err)
  822. path = fmt.Sprintf("%s?tokenId=X", endpoint)
  823. err = doBadReq("GET", path, nil, 400)
  824. assert.NoError(t, err)
  825. // 404
  826. path = fmt.Sprintf("%s?batchNum=999999", endpoint)
  827. err = doBadReq("GET", path, nil, 404)
  828. assert.NoError(t, err)
  829. path = fmt.Sprintf("%s?limit=1000&fromItem=999999", endpoint)
  830. err = doBadReq("GET", path, nil, 404)
  831. assert.NoError(t, err)
  832. }
  833. func TestGetHistoryTx(t *testing.T) {
  834. // Get all txs by their ID
  835. endpoint := apiURL + "transactions-history/"
  836. fetchedTxs := []historyTxAPI{}
  837. for _, tx := range tc.allTxs {
  838. fetchedTx := historyTxAPI{}
  839. assert.NoError(t, doGoodReq("GET", endpoint+tx.TxID.String(), nil, &fetchedTx))
  840. fetchedTxs = append(fetchedTxs, fetchedTx)
  841. }
  842. assertHistoryTxAPIs(t, tc.allTxs, fetchedTxs)
  843. // 400
  844. err := doBadReq("GET", endpoint+"0x001", nil, 400)
  845. assert.NoError(t, err)
  846. // 404
  847. err = doBadReq("GET", endpoint+"0x00000000000001e240004700", nil, 404)
  848. assert.NoError(t, err)
  849. }
  850. func assertHistoryTxAPIs(t *testing.T, expected, actual []historyTxAPI) {
  851. require.Equal(t, len(expected), len(actual))
  852. for i := 0; i < len(actual); i++ { //nolint len(actual) won't change within the loop
  853. actual[i].ItemID = 0
  854. assert.Equal(t, expected[i].Timestamp.Unix(), actual[i].Timestamp.Unix())
  855. expected[i].Timestamp = actual[i].Timestamp
  856. if expected[i].Token.USDUpdate == nil {
  857. assert.Equal(t, expected[i].Token.USDUpdate, actual[i].Token.USDUpdate)
  858. } else {
  859. assert.Equal(t, expected[i].Token.USDUpdate.Unix(), actual[i].Token.USDUpdate.Unix())
  860. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  861. }
  862. test.AssertUSD(t, expected[i].HistoricUSD, actual[i].HistoricUSD)
  863. if expected[i].L2Info != nil {
  864. test.AssertUSD(t, expected[i].L2Info.HistoricFeeUSD, actual[i].L2Info.HistoricFeeUSD)
  865. } else {
  866. test.AssertUSD(t, expected[i].L1Info.HistoricLoadAmountUSD, actual[i].L1Info.HistoricLoadAmountUSD)
  867. }
  868. assert.Equal(t, expected[i], actual[i])
  869. }
  870. }
  871. func TestGetExits(t *testing.T) {
  872. endpoint := apiURL + "exits"
  873. fetchedExits := []exitAPI{}
  874. appendIter := func(intr interface{}) {
  875. for i := 0; i < len(intr.(*exitsAPI).Exits); i++ {
  876. tmp, err := copystructure.Copy(intr.(*exitsAPI).Exits[i])
  877. if err != nil {
  878. panic(err)
  879. }
  880. fetchedExits = append(fetchedExits, tmp.(exitAPI))
  881. }
  882. }
  883. // Get all (no filters)
  884. limit := 8
  885. path := fmt.Sprintf("%s?limit=%d&fromItem=", endpoint, limit)
  886. err := doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  887. assert.NoError(t, err)
  888. assertExitAPIs(t, tc.exits, fetchedExits)
  889. // Get by ethAddr
  890. fetchedExits = []exitAPI{}
  891. limit = 7
  892. path = fmt.Sprintf(
  893. "%s?hermezEthereumAddress=%s&limit=%d&fromItem=",
  894. endpoint, tc.usrAddr, limit,
  895. )
  896. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  897. assert.NoError(t, err)
  898. assertExitAPIs(t, tc.usrExits, fetchedExits)
  899. // Get by bjj
  900. fetchedExits = []exitAPI{}
  901. limit = 6
  902. path = fmt.Sprintf(
  903. "%s?BJJ=%s&limit=%d&fromItem=",
  904. endpoint, tc.usrBjj, limit,
  905. )
  906. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  907. assert.NoError(t, err)
  908. assertExitAPIs(t, tc.usrExits, fetchedExits)
  909. // Get by tokenID
  910. fetchedExits = []exitAPI{}
  911. limit = 5
  912. tokenID := tc.exits[0].Token.TokenID
  913. path = fmt.Sprintf(
  914. "%s?tokenId=%d&limit=%d&fromItem=",
  915. endpoint, tokenID, limit,
  916. )
  917. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  918. assert.NoError(t, err)
  919. tokenIDExits := []exitAPI{}
  920. for i := 0; i < len(tc.exits); i++ {
  921. if tc.exits[i].Token.TokenID == tokenID {
  922. tokenIDExits = append(tokenIDExits, tc.exits[i])
  923. }
  924. }
  925. assertExitAPIs(t, tokenIDExits, fetchedExits)
  926. // idx
  927. fetchedExits = []exitAPI{}
  928. limit = 4
  929. idx := tc.exits[0].AccountIdx
  930. path = fmt.Sprintf(
  931. "%s?accountIndex=%s&limit=%d&fromItem=",
  932. endpoint, idx, limit,
  933. )
  934. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  935. assert.NoError(t, err)
  936. idxExits := []exitAPI{}
  937. for i := 0; i < len(tc.exits); i++ {
  938. if tc.exits[i].AccountIdx[6:] == idx[6:] {
  939. idxExits = append(idxExits, tc.exits[i])
  940. }
  941. }
  942. assertExitAPIs(t, idxExits, fetchedExits)
  943. // batchNum
  944. fetchedExits = []exitAPI{}
  945. limit = 3
  946. batchNum := tc.exits[0].BatchNum
  947. path = fmt.Sprintf(
  948. "%s?batchNum=%d&limit=%d&fromItem=",
  949. endpoint, batchNum, limit,
  950. )
  951. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  952. assert.NoError(t, err)
  953. batchNumExits := []exitAPI{}
  954. for i := 0; i < len(tc.exits); i++ {
  955. if tc.exits[i].BatchNum == batchNum {
  956. batchNumExits = append(batchNumExits, tc.exits[i])
  957. }
  958. }
  959. assertExitAPIs(t, batchNumExits, fetchedExits)
  960. // Multiple filters
  961. fetchedExits = []exitAPI{}
  962. limit = 1
  963. path = fmt.Sprintf(
  964. "%s?batchNum=%d&tokeId=%d&limit=%d&fromItem=",
  965. endpoint, batchNum, tokenID, limit,
  966. )
  967. err = doGoodReqPaginated(path, historydb.OrderAsc, &exitsAPI{}, appendIter)
  968. assert.NoError(t, err)
  969. mixedExits := []exitAPI{}
  970. flipedExits := []exitAPI{}
  971. for i := 0; i < len(tc.exits); i++ {
  972. if tc.exits[i].BatchNum == batchNum && tc.exits[i].Token.TokenID == tokenID {
  973. mixedExits = append(mixedExits, tc.exits[i])
  974. }
  975. flipedExits = append(flipedExits, tc.exits[len(tc.exits)-1-i])
  976. }
  977. assertExitAPIs(t, mixedExits, fetchedExits)
  978. // All, in reverse order
  979. fetchedExits = []exitAPI{}
  980. limit = 5
  981. path = fmt.Sprintf("%s?limit=%d&fromItem=", endpoint, limit)
  982. err = doGoodReqPaginated(path, historydb.OrderDesc, &exitsAPI{}, appendIter)
  983. assert.NoError(t, err)
  984. assertExitAPIs(t, flipedExits, fetchedExits)
  985. // 400
  986. path = fmt.Sprintf(
  987. "%s?accountIndex=%s&hermezEthereumAddress=%s",
  988. endpoint, idx, tc.usrAddr,
  989. )
  990. err = doBadReq("GET", path, nil, 400)
  991. assert.NoError(t, err)
  992. path = fmt.Sprintf("%s?tokenId=X", endpoint)
  993. err = doBadReq("GET", path, nil, 400)
  994. assert.NoError(t, err)
  995. // 404
  996. path = fmt.Sprintf("%s?batchNum=999999", endpoint)
  997. err = doBadReq("GET", path, nil, 404)
  998. assert.NoError(t, err)
  999. path = fmt.Sprintf("%s?limit=1000&fromItem=999999", endpoint)
  1000. err = doBadReq("GET", path, nil, 404)
  1001. assert.NoError(t, err)
  1002. }
  1003. func TestGetExit(t *testing.T) {
  1004. // Get all txs by their ID
  1005. endpoint := apiURL + "exits/"
  1006. fetchedExits := []exitAPI{}
  1007. for _, exit := range tc.exits {
  1008. fetchedExit := exitAPI{}
  1009. assert.NoError(
  1010. t, doGoodReq(
  1011. "GET",
  1012. fmt.Sprintf("%s%d/%s", endpoint, exit.BatchNum, exit.AccountIdx),
  1013. nil, &fetchedExit,
  1014. ),
  1015. )
  1016. fetchedExits = append(fetchedExits, fetchedExit)
  1017. }
  1018. assertExitAPIs(t, tc.exits, fetchedExits)
  1019. // 400
  1020. err := doBadReq("GET", endpoint+"1/haz:BOOM:1", nil, 400)
  1021. assert.NoError(t, err)
  1022. err = doBadReq("GET", endpoint+"-1/hez:BOOM:1", nil, 400)
  1023. assert.NoError(t, err)
  1024. // 404
  1025. err = doBadReq("GET", endpoint+"494/hez:XXX:1", nil, 404)
  1026. assert.NoError(t, err)
  1027. }
  1028. func assertExitAPIs(t *testing.T, expected, actual []exitAPI) {
  1029. require.Equal(t, len(expected), len(actual))
  1030. for i := 0; i < len(actual); i++ { //nolint len(actual) won't change within the loop
  1031. actual[i].ItemID = 0
  1032. if expected[i].Token.USDUpdate == nil {
  1033. assert.Equal(t, expected[i].Token.USDUpdate, actual[i].Token.USDUpdate)
  1034. } else {
  1035. assert.Equal(t, expected[i].Token.USDUpdate.Unix(), actual[i].Token.USDUpdate.Unix())
  1036. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  1037. }
  1038. assert.Equal(t, expected[i], actual[i])
  1039. }
  1040. }
  1041. func TestGetConfig(t *testing.T) {
  1042. endpoint := apiURL + "config"
  1043. var configTest configAPI
  1044. assert.NoError(t, doGoodReq("GET", endpoint, nil, &configTest))
  1045. assert.Equal(t, config, configTest)
  1046. assert.Equal(t, cg, &configTest)
  1047. }
  1048. func TestPoolTxs(t *testing.T) {
  1049. // POST
  1050. endpoint := apiURL + "transactions-pool"
  1051. fetchedTxID := common.TxID{}
  1052. for _, tx := range tc.poolTxsToSend {
  1053. jsonTxBytes, err := json.Marshal(tx)
  1054. assert.NoError(t, err)
  1055. jsonTxReader := bytes.NewReader(jsonTxBytes)
  1056. assert.NoError(
  1057. t, doGoodReq(
  1058. "POST",
  1059. endpoint,
  1060. jsonTxReader, &fetchedTxID,
  1061. ),
  1062. )
  1063. assert.Equal(t, tx.TxID, fetchedTxID)
  1064. }
  1065. // 400
  1066. // Wrong signature
  1067. badTx := tc.poolTxsToSend[0]
  1068. badTx.FromIdx = "hez:foo:1000"
  1069. jsonTxBytes, err := json.Marshal(badTx)
  1070. assert.NoError(t, err)
  1071. jsonTxReader := bytes.NewReader(jsonTxBytes)
  1072. err = doBadReq("POST", endpoint, jsonTxReader, 400)
  1073. assert.NoError(t, err)
  1074. // Wrong to
  1075. badTx = tc.poolTxsToSend[0]
  1076. ethAddr := "hez:0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
  1077. badTx.ToEthAddr = &ethAddr
  1078. badTx.ToIdx = nil
  1079. jsonTxBytes, err = json.Marshal(badTx)
  1080. assert.NoError(t, err)
  1081. jsonTxReader = bytes.NewReader(jsonTxBytes)
  1082. err = doBadReq("POST", endpoint, jsonTxReader, 400)
  1083. assert.NoError(t, err)
  1084. // Wrong rq
  1085. badTx = tc.poolTxsToSend[0]
  1086. rqFromIdx := "hez:foo:30"
  1087. badTx.RqFromIdx = &rqFromIdx
  1088. jsonTxBytes, err = json.Marshal(badTx)
  1089. assert.NoError(t, err)
  1090. jsonTxReader = bytes.NewReader(jsonTxBytes)
  1091. err = doBadReq("POST", endpoint, jsonTxReader, 400)
  1092. assert.NoError(t, err)
  1093. // GET
  1094. endpoint += "/"
  1095. for _, tx := range tc.poolTxsToReceive {
  1096. fetchedTx := sendPoolTx{}
  1097. assert.NoError(
  1098. t, doGoodReq(
  1099. "GET",
  1100. endpoint+tx.TxID.String(),
  1101. nil, &fetchedTx,
  1102. ),
  1103. )
  1104. assertPoolTx(t, tx, fetchedTx)
  1105. }
  1106. // 400
  1107. err = doBadReq("GET", endpoint+"0xG20000000156660000000090", nil, 400)
  1108. assert.NoError(t, err)
  1109. // 404
  1110. err = doBadReq("GET", endpoint+"0x020000000156660000000090", nil, 404)
  1111. assert.NoError(t, err)
  1112. }
  1113. func assertPoolTx(t *testing.T, expected, actual sendPoolTx) {
  1114. // state should be pending
  1115. assert.Equal(t, common.PoolL2TxStatePending, actual.State)
  1116. expected.State = actual.State
  1117. // timestamp should be very close to now
  1118. assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
  1119. expected.Timestamp = actual.Timestamp
  1120. // token timestamp
  1121. if expected.Token.USDUpdate == nil {
  1122. assert.Equal(t, expected.Token.USDUpdate, actual.Token.USDUpdate)
  1123. } else {
  1124. assert.Equal(t, expected.Token.USDUpdate.Unix(), actual.Token.USDUpdate.Unix())
  1125. expected.Token.USDUpdate = actual.Token.USDUpdate
  1126. }
  1127. assert.Equal(t, expected, actual)
  1128. }
  1129. func TestAccountCreationAuth(t *testing.T) {
  1130. // POST
  1131. endpoint := apiURL + "account-creation-authorization"
  1132. for _, auth := range tc.auths {
  1133. jsonAuthBytes, err := json.Marshal(auth)
  1134. assert.NoError(t, err)
  1135. jsonAuthReader := bytes.NewReader(jsonAuthBytes)
  1136. fmt.Println(string(jsonAuthBytes))
  1137. assert.NoError(
  1138. t, doGoodReq(
  1139. "POST",
  1140. endpoint,
  1141. jsonAuthReader, nil,
  1142. ),
  1143. )
  1144. }
  1145. // GET
  1146. endpoint += "/"
  1147. for _, auth := range tc.auths {
  1148. fetchedAuth := accountCreationAuthAPI{}
  1149. assert.NoError(
  1150. t, doGoodReq(
  1151. "GET",
  1152. endpoint+auth.EthAddr,
  1153. nil, &fetchedAuth,
  1154. ),
  1155. )
  1156. assertAuth(t, auth, fetchedAuth)
  1157. }
  1158. // POST
  1159. // 400
  1160. // Wrong addr
  1161. badAuth := tc.auths[0]
  1162. badAuth.EthAddr = ethAddrToHez(ethCommon.BigToAddress(big.NewInt(1)))
  1163. jsonAuthBytes, err := json.Marshal(badAuth)
  1164. assert.NoError(t, err)
  1165. jsonAuthReader := bytes.NewReader(jsonAuthBytes)
  1166. err = doBadReq("POST", endpoint, jsonAuthReader, 400)
  1167. assert.NoError(t, err)
  1168. // Wrong signature
  1169. badAuth = tc.auths[0]
  1170. badAuth.Signature = badAuth.Signature[:len(badAuth.Signature)-1]
  1171. badAuth.Signature += "F"
  1172. jsonAuthBytes, err = json.Marshal(badAuth)
  1173. assert.NoError(t, err)
  1174. jsonAuthReader = bytes.NewReader(jsonAuthBytes)
  1175. err = doBadReq("POST", endpoint, jsonAuthReader, 400)
  1176. assert.NoError(t, err)
  1177. // GET
  1178. // 400
  1179. err = doBadReq("GET", endpoint+"hez:0xFooBar", nil, 400)
  1180. assert.NoError(t, err)
  1181. // 404
  1182. err = doBadReq("GET", endpoint+"hez:0x0000000000000000000000000000000000000001", nil, 404)
  1183. assert.NoError(t, err)
  1184. }
  1185. func assertAuth(t *testing.T, expected, actual accountCreationAuthAPI) {
  1186. // timestamp should be very close to now
  1187. assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
  1188. expected.Timestamp = actual.Timestamp
  1189. assert.Equal(t, expected, actual)
  1190. }
  1191. func doGoodReqPaginated(
  1192. path, order string,
  1193. iterStruct db.Paginationer,
  1194. appendIter func(res interface{}),
  1195. ) error {
  1196. next := 0
  1197. for {
  1198. // Call API to get this iteration items
  1199. iterPath := path
  1200. if next == 0 && order == historydb.OrderDesc {
  1201. // Fetch first item in reverse order
  1202. iterPath += "99999"
  1203. } else {
  1204. // Fetch from next item or 0 if it's ascending order
  1205. iterPath += strconv.Itoa(next)
  1206. }
  1207. if err := doGoodReq("GET", iterPath+"&order="+order, nil, iterStruct); err != nil {
  1208. return err
  1209. }
  1210. appendIter(iterStruct)
  1211. // Keep iterating?
  1212. pag := iterStruct.GetPagination()
  1213. if order == historydb.OrderAsc {
  1214. if pag.LastReturnedItem == pag.LastItem { // No
  1215. break
  1216. } else { // Yes
  1217. next = pag.LastReturnedItem + 1
  1218. }
  1219. } else {
  1220. if pag.FirstReturnedItem == pag.FirstItem { // No
  1221. break
  1222. } else { // Yes
  1223. next = pag.FirstReturnedItem - 1
  1224. }
  1225. }
  1226. }
  1227. return nil
  1228. }
  1229. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  1230. ctx := context.Background()
  1231. client := &http.Client{}
  1232. httpReq, err := http.NewRequest(method, path, reqBody)
  1233. if err != nil {
  1234. return err
  1235. }
  1236. if reqBody != nil {
  1237. httpReq.Header.Add("Content-Type", "application/json")
  1238. }
  1239. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  1240. if err != nil {
  1241. return err
  1242. }
  1243. // Validate request against swagger spec
  1244. requestValidationInput := &swagger.RequestValidationInput{
  1245. Request: httpReq,
  1246. PathParams: pathParams,
  1247. Route: route,
  1248. }
  1249. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  1250. return err
  1251. }
  1252. // Do API call
  1253. resp, err := client.Do(httpReq)
  1254. if err != nil {
  1255. return err
  1256. }
  1257. if resp.Body == nil && returnStruct != nil {
  1258. return errors.New("Nil body")
  1259. }
  1260. //nolint
  1261. defer resp.Body.Close()
  1262. body, err := ioutil.ReadAll(resp.Body)
  1263. if err != nil {
  1264. return err
  1265. }
  1266. if resp.StatusCode != 200 {
  1267. return fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body))
  1268. }
  1269. if returnStruct == nil {
  1270. return nil
  1271. }
  1272. // Unmarshal body into return struct
  1273. if err := json.Unmarshal(body, returnStruct); err != nil {
  1274. log.Error("invalid json: " + string(body))
  1275. return err
  1276. }
  1277. // Validate response against swagger spec
  1278. responseValidationInput := &swagger.ResponseValidationInput{
  1279. RequestValidationInput: requestValidationInput,
  1280. Status: resp.StatusCode,
  1281. Header: resp.Header,
  1282. }
  1283. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  1284. return swagger.ValidateResponse(ctx, responseValidationInput)
  1285. }
  1286. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  1287. ctx := context.Background()
  1288. client := &http.Client{}
  1289. httpReq, _ := http.NewRequest(method, path, reqBody)
  1290. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  1291. if err != nil {
  1292. return err
  1293. }
  1294. // Validate request against swagger spec
  1295. requestValidationInput := &swagger.RequestValidationInput{
  1296. Request: httpReq,
  1297. PathParams: pathParams,
  1298. Route: route,
  1299. }
  1300. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  1301. if expectedResponseCode != 400 {
  1302. return err
  1303. }
  1304. log.Warn("The request does not match the API spec")
  1305. }
  1306. // Do API call
  1307. resp, err := client.Do(httpReq)
  1308. if err != nil {
  1309. return err
  1310. }
  1311. if resp.Body == nil {
  1312. return errors.New("Nil body")
  1313. }
  1314. //nolint
  1315. defer resp.Body.Close()
  1316. body, err := ioutil.ReadAll(resp.Body)
  1317. if err != nil {
  1318. return err
  1319. }
  1320. if resp.StatusCode != expectedResponseCode {
  1321. return fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body))
  1322. }
  1323. // Validate response against swagger spec
  1324. responseValidationInput := &swagger.ResponseValidationInput{
  1325. RequestValidationInput: requestValidationInput,
  1326. Status: resp.StatusCode,
  1327. Header: resp.Header,
  1328. }
  1329. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  1330. return swagger.ValidateResponse(ctx, responseValidationInput)
  1331. }