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.

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