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.

487 lines
15 KiB

  1. package api
  2. import (
  3. "fmt"
  4. "math"
  5. "math/big"
  6. "sort"
  7. "testing"
  8. "time"
  9. "github.com/hermeznetwork/hermez-node/apitypes"
  10. "github.com/hermeznetwork/hermez-node/common"
  11. "github.com/hermeznetwork/hermez-node/db/historydb"
  12. "github.com/hermeznetwork/hermez-node/test"
  13. "github.com/mitchellh/copystructure"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. )
  17. type testL1Info struct {
  18. ToForgeL1TxsNum *int64 `json:"toForgeL1TransactionsNum"`
  19. UserOrigin bool `json:"userOrigin"`
  20. DepositAmount string `json:"depositAmount"`
  21. AmountSuccess bool `json:"amountSuccess"`
  22. DepositAmountSuccess bool `json:"depositAmountSuccess"`
  23. HistoricDepositAmountUSD *float64 `json:"historicDepositAmountUSD"`
  24. EthBlockNum int64 `json:"ethereumBlockNum"`
  25. }
  26. type testL2Info struct {
  27. Fee common.FeeSelector `json:"fee"`
  28. HistoricFeeUSD *float64 `json:"historicFeeUSD"`
  29. Nonce common.Nonce `json:"nonce"`
  30. }
  31. type testTx struct {
  32. IsL1 string `json:"L1orL2"`
  33. TxID common.TxID `json:"id"`
  34. ItemID uint64 `json:"itemId"`
  35. Type common.TxType `json:"type"`
  36. Position int `json:"position"`
  37. FromIdx *string `json:"fromAccountIndex"`
  38. FromEthAddr *string `json:"fromHezEthereumAddress"`
  39. FromBJJ *string `json:"fromBJJ"`
  40. ToIdx string `json:"toAccountIndex"`
  41. ToEthAddr *string `json:"toHezEthereumAddress"`
  42. ToBJJ *string `json:"toBJJ"`
  43. Amount string `json:"amount"`
  44. BatchNum *common.BatchNum `json:"batchNum"`
  45. HistoricUSD *float64 `json:"historicUSD"`
  46. Timestamp time.Time `json:"timestamp"`
  47. L1Info *testL1Info `json:"L1Info"`
  48. L2Info *testL2Info `json:"L2Info"`
  49. Token historydb.TokenWithUSD `json:"token"`
  50. }
  51. type txsSort []testTx
  52. func (t txsSort) Len() int { return len(t) }
  53. func (t txsSort) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
  54. func (t txsSort) Less(i, j int) bool {
  55. // i not forged yet
  56. isf := t[i]
  57. jsf := t[j]
  58. if isf.BatchNum == nil {
  59. if jsf.BatchNum != nil { // j is already forged
  60. return false
  61. }
  62. // Both aren't forged, is i in a smaller position?
  63. return isf.Position < jsf.Position
  64. }
  65. // i is forged
  66. if jsf.BatchNum == nil {
  67. return false // j is not forged
  68. }
  69. // Both are forged
  70. if *isf.BatchNum == *jsf.BatchNum {
  71. // At the same batch, is i in a smaller position?
  72. return isf.Position < jsf.Position
  73. }
  74. // At different batches, is i in a smaller batch?
  75. return *isf.BatchNum < *jsf.BatchNum
  76. }
  77. type testTxsResponse struct {
  78. Txs []testTx `json:"transactions"`
  79. PendingItems uint64 `json:"pendingItems"`
  80. }
  81. func (t testTxsResponse) GetPending() (pendingItems, lastItemID uint64) {
  82. if len(t.Txs) == 0 {
  83. return 0, 0
  84. }
  85. pendingItems = t.PendingItems
  86. lastItemID = t.Txs[len(t.Txs)-1].ItemID
  87. return pendingItems, lastItemID
  88. }
  89. func (t testTxsResponse) Len() int {
  90. return len(t.Txs)
  91. }
  92. func (t testTxsResponse) New() Pendinger { return &testTxsResponse{} }
  93. func genTestTxs(
  94. l1s []common.L1Tx,
  95. l2s []common.L2Tx,
  96. accs []common.Account,
  97. tokens []historydb.TokenWithUSD,
  98. blocks []common.Block,
  99. ) []testTx {
  100. txs := []testTx{}
  101. // common.L1Tx ==> testTx
  102. for _, l1 := range l1s {
  103. token := getTokenByID(l1.TokenID, tokens)
  104. // l1.FromEthAddr and l1.FromBJJ can't be nil
  105. fromEthAddr := string(apitypes.NewHezEthAddr(l1.FromEthAddr))
  106. fromBJJ := string(apitypes.NewHezBJJ(l1.FromBJJ))
  107. tx := testTx{
  108. IsL1: "L1",
  109. TxID: l1.TxID,
  110. Type: l1.Type,
  111. Position: l1.Position,
  112. FromEthAddr: &fromEthAddr,
  113. FromBJJ: &fromBJJ,
  114. ToIdx: idxToHez(l1.ToIdx, token.Symbol),
  115. Amount: l1.Amount.String(),
  116. BatchNum: l1.BatchNum,
  117. Timestamp: getTimestamp(l1.EthBlockNum, blocks),
  118. L1Info: &testL1Info{
  119. ToForgeL1TxsNum: l1.ToForgeL1TxsNum,
  120. UserOrigin: l1.UserOrigin,
  121. DepositAmount: l1.DepositAmount.String(),
  122. AmountSuccess: true,
  123. DepositAmountSuccess: true,
  124. EthBlockNum: l1.EthBlockNum,
  125. },
  126. Token: token,
  127. }
  128. // set BatchNum for user txs
  129. if tx.L1Info.ToForgeL1TxsNum != nil {
  130. // WARNING: this is an asumption, and the test input data can brake it easily
  131. bn := common.BatchNum(*tx.L1Info.ToForgeL1TxsNum + 2)
  132. tx.BatchNum = &bn
  133. }
  134. // If FromIdx is not nil
  135. idxStr := idxToHez(l1.EffectiveFromIdx, token.Symbol)
  136. tx.FromIdx = &idxStr
  137. // If tx has a normal ToIdx (>255), set FromEthAddr and FromBJJ
  138. if l1.ToIdx >= common.UserThreshold {
  139. // find account
  140. for _, acc := range accs {
  141. if l1.ToIdx == acc.Idx {
  142. toEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  143. tx.ToEthAddr = &toEthAddr
  144. toBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  145. tx.ToBJJ = &toBJJ
  146. break
  147. }
  148. }
  149. }
  150. // If the token has USD value setted
  151. if token.USD != nil {
  152. af := new(big.Float).SetInt(l1.Amount)
  153. amountFloat, _ := af.Float64()
  154. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  155. if usd != 0 {
  156. tx.HistoricUSD = &usd
  157. }
  158. laf := new(big.Float).SetInt(l1.DepositAmount)
  159. depositAmountFloat, _ := laf.Float64()
  160. depositUSD := *token.USD * depositAmountFloat / math.Pow(10, float64(token.Decimals))
  161. if depositAmountFloat != 0 {
  162. tx.L1Info.HistoricDepositAmountUSD = &depositUSD
  163. }
  164. }
  165. txs = append(txs, tx)
  166. }
  167. // common.L2Tx ==> testTx
  168. for i := 0; i < len(l2s); i++ {
  169. token := getTokenByIdx(l2s[i].FromIdx, tokens, accs)
  170. // l1.FromIdx can't be nil
  171. fromIdx := idxToHez(l2s[i].FromIdx, token.Symbol)
  172. tx := testTx{
  173. IsL1: "L2",
  174. TxID: l2s[i].TxID,
  175. Type: l2s[i].Type,
  176. Position: l2s[i].Position,
  177. ToIdx: idxToHez(l2s[i].ToIdx, token.Symbol),
  178. FromIdx: &fromIdx,
  179. Amount: l2s[i].Amount.String(),
  180. BatchNum: &l2s[i].BatchNum,
  181. Timestamp: getTimestamp(l2s[i].EthBlockNum, blocks),
  182. L2Info: &testL2Info{
  183. Nonce: l2s[i].Nonce,
  184. Fee: l2s[i].Fee,
  185. },
  186. Token: token,
  187. }
  188. // If FromIdx is not nil
  189. if l2s[i].FromIdx != 0 {
  190. idxStr := idxToHez(l2s[i].FromIdx, token.Symbol)
  191. tx.FromIdx = &idxStr
  192. }
  193. // Set FromEthAddr and FromBJJ (FromIdx it's always >255)
  194. for _, acc := range accs {
  195. if l2s[i].FromIdx == acc.Idx {
  196. fromEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  197. tx.FromEthAddr = &fromEthAddr
  198. fromBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  199. tx.FromBJJ = &fromBJJ
  200. break
  201. }
  202. }
  203. // If tx has a normal ToIdx (>255), set FromEthAddr and FromBJJ
  204. if l2s[i].ToIdx >= common.UserThreshold {
  205. // find account
  206. for _, acc := range accs {
  207. if l2s[i].ToIdx == acc.Idx {
  208. toEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  209. tx.ToEthAddr = &toEthAddr
  210. toBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  211. tx.ToBJJ = &toBJJ
  212. break
  213. }
  214. }
  215. }
  216. // If the token has USD value setted
  217. if token.USD != nil {
  218. af := new(big.Float).SetInt(l2s[i].Amount)
  219. amountFloat, _ := af.Float64()
  220. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  221. if usd != 0 {
  222. tx.HistoricUSD = &usd
  223. feeUSD := usd * l2s[i].Fee.Percentage()
  224. if feeUSD != 0 {
  225. tx.L2Info.HistoricFeeUSD = &feeUSD
  226. }
  227. }
  228. }
  229. txs = append(txs, tx)
  230. }
  231. // Sort txs
  232. sortedTxs := txsSort(txs)
  233. sort.Sort(sortedTxs)
  234. return []testTx(sortedTxs)
  235. }
  236. func TestGetHistoryTxs(t *testing.T) {
  237. endpoint := apiURL + "transactions-history"
  238. fetchedTxs := []testTx{}
  239. appendIter := func(intr interface{}) {
  240. for i := 0; i < len(intr.(*testTxsResponse).Txs); i++ {
  241. tmp, err := copystructure.Copy(intr.(*testTxsResponse).Txs[i])
  242. if err != nil {
  243. panic(err)
  244. }
  245. fetchedTxs = append(fetchedTxs, tmp.(testTx))
  246. }
  247. }
  248. // Get all (no filters)
  249. limit := 20
  250. path := fmt.Sprintf("%s?limit=%d", endpoint, limit)
  251. err := doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  252. assert.NoError(t, err)
  253. assertTxs(t, tc.txs, fetchedTxs)
  254. // Get by ethAddr
  255. account := tc.accounts[2]
  256. fetchedTxs = []testTx{}
  257. limit = 7
  258. path = fmt.Sprintf(
  259. "%s?hezEthereumAddress=%s&limit=%d",
  260. endpoint, account.EthAddr, limit,
  261. )
  262. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  263. assert.NoError(t, err)
  264. accountTxs := []testTx{}
  265. for i := 0; i < len(tc.txs); i++ {
  266. tx := tc.txs[i]
  267. if (tx.FromIdx != nil && *tx.FromIdx == string(account.Idx)) ||
  268. tx.ToIdx == string(account.Idx) ||
  269. (tx.FromEthAddr != nil && *tx.FromEthAddr == string(account.EthAddr)) ||
  270. (tx.ToEthAddr != nil && *tx.ToEthAddr == string(account.EthAddr)) ||
  271. (tx.FromBJJ != nil && *tx.FromBJJ == string(account.PublicKey)) ||
  272. (tx.ToBJJ != nil && *tx.ToBJJ == string(account.PublicKey)) {
  273. accountTxs = append(accountTxs, tx)
  274. }
  275. }
  276. assertTxs(t, accountTxs, fetchedTxs)
  277. // Get by bjj
  278. fetchedTxs = []testTx{}
  279. limit = 6
  280. path = fmt.Sprintf(
  281. "%s?BJJ=%s&limit=%d",
  282. endpoint, account.PublicKey, limit,
  283. )
  284. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  285. assert.NoError(t, err)
  286. assertTxs(t, accountTxs, fetchedTxs)
  287. // Get by tokenID
  288. fetchedTxs = []testTx{}
  289. limit = 5
  290. tokenID := tc.txs[0].Token.TokenID
  291. path = fmt.Sprintf(
  292. "%s?tokenId=%d&limit=%d",
  293. endpoint, tokenID, limit,
  294. )
  295. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  296. assert.NoError(t, err)
  297. tokenIDTxs := []testTx{}
  298. for i := 0; i < len(tc.txs); i++ {
  299. if tc.txs[i].Token.TokenID == tokenID {
  300. tokenIDTxs = append(tokenIDTxs, tc.txs[i])
  301. }
  302. }
  303. assertTxs(t, tokenIDTxs, fetchedTxs)
  304. // idx
  305. fetchedTxs = []testTx{}
  306. limit = 4
  307. idxStr := tc.txs[0].ToIdx
  308. idx, err := stringToIdx(idxStr, "")
  309. assert.NoError(t, err)
  310. path = fmt.Sprintf(
  311. "%s?accountIndex=%s&limit=%d",
  312. endpoint, idxStr, limit,
  313. )
  314. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  315. assert.NoError(t, err)
  316. idxTxs := []testTx{}
  317. for i := 0; i < len(tc.txs); i++ {
  318. var fromIdx *common.Idx
  319. if tc.txs[i].FromIdx != nil {
  320. fromIdx, err = stringToIdx(*tc.txs[i].FromIdx, "")
  321. assert.NoError(t, err)
  322. if *fromIdx == *idx {
  323. idxTxs = append(idxTxs, tc.txs[i])
  324. continue
  325. }
  326. }
  327. toIdx, err := stringToIdx((tc.txs[i].ToIdx), "")
  328. assert.NoError(t, err)
  329. if *toIdx == *idx {
  330. idxTxs = append(idxTxs, tc.txs[i])
  331. }
  332. }
  333. assertTxs(t, idxTxs, fetchedTxs)
  334. // batchNum
  335. fetchedTxs = []testTx{}
  336. limit = 3
  337. batchNum := tc.txs[0].BatchNum
  338. path = fmt.Sprintf(
  339. "%s?batchNum=%d&limit=%d",
  340. endpoint, *batchNum, limit,
  341. )
  342. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  343. assert.NoError(t, err)
  344. batchNumTxs := []testTx{}
  345. for i := 0; i < len(tc.txs); i++ {
  346. if tc.txs[i].BatchNum != nil &&
  347. *tc.txs[i].BatchNum == *batchNum {
  348. batchNumTxs = append(batchNumTxs, tc.txs[i])
  349. }
  350. }
  351. assertTxs(t, batchNumTxs, fetchedTxs)
  352. // type
  353. txTypes := []common.TxType{
  354. // Uncomment once test gen is fixed
  355. common.TxTypeExit,
  356. common.TxTypeTransfer,
  357. common.TxTypeDeposit,
  358. common.TxTypeCreateAccountDeposit,
  359. common.TxTypeCreateAccountDepositTransfer,
  360. common.TxTypeDepositTransfer,
  361. common.TxTypeForceTransfer,
  362. common.TxTypeForceExit,
  363. }
  364. for _, txType := range txTypes {
  365. fetchedTxs = []testTx{}
  366. limit = 2
  367. path = fmt.Sprintf(
  368. "%s?type=%s&limit=%d",
  369. endpoint, txType, limit,
  370. )
  371. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  372. assert.NoError(t, err)
  373. txTypeTxs := []testTx{}
  374. for i := 0; i < len(tc.txs); i++ {
  375. if tc.txs[i].Type == txType {
  376. txTypeTxs = append(txTypeTxs, tc.txs[i])
  377. }
  378. }
  379. assertTxs(t, txTypeTxs, fetchedTxs)
  380. }
  381. // Multiple filters
  382. fetchedTxs = []testTx{}
  383. limit = 1
  384. path = fmt.Sprintf(
  385. "%s?batchNum=%d&tokenId=%d&limit=%d",
  386. endpoint, *batchNum, tokenID, limit,
  387. )
  388. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  389. assert.NoError(t, err)
  390. mixedTxs := []testTx{}
  391. for i := 0; i < len(tc.txs); i++ {
  392. if tc.txs[i].BatchNum != nil {
  393. if *tc.txs[i].BatchNum == *batchNum && tc.txs[i].Token.TokenID == tokenID {
  394. mixedTxs = append(mixedTxs, tc.txs[i])
  395. }
  396. }
  397. }
  398. assertTxs(t, mixedTxs, fetchedTxs)
  399. // All, in reverse order
  400. fetchedTxs = []testTx{}
  401. limit = 5
  402. path = fmt.Sprintf("%s?limit=%d", endpoint, limit)
  403. err = doGoodReqPaginated(path, historydb.OrderDesc, &testTxsResponse{}, appendIter)
  404. assert.NoError(t, err)
  405. flipedTxs := []testTx{}
  406. for i := 0; i < len(tc.txs); i++ {
  407. flipedTxs = append(flipedTxs, tc.txs[len(tc.txs)-1-i])
  408. }
  409. assertTxs(t, flipedTxs, fetchedTxs)
  410. // Empty array
  411. fetchedTxs = []testTx{}
  412. path = fmt.Sprintf("%s?batchNum=999999", endpoint)
  413. err = doGoodReqPaginated(path, historydb.OrderDesc, &testTxsResponse{}, appendIter)
  414. assert.NoError(t, err)
  415. assertTxs(t, []testTx{}, fetchedTxs)
  416. // 400
  417. path = fmt.Sprintf(
  418. "%s?accountIndex=%s&hezEthereumAddress=%s",
  419. endpoint, idx, account.EthAddr,
  420. )
  421. err = doBadReq("GET", path, nil, 400)
  422. assert.NoError(t, err)
  423. path = fmt.Sprintf("%s?tokenId=X", endpoint)
  424. err = doBadReq("GET", path, nil, 400)
  425. assert.NoError(t, err)
  426. }
  427. func TestGetHistoryTx(t *testing.T) {
  428. // Get all txs by their ID
  429. endpoint := apiURL + "transactions-history/"
  430. fetchedTxs := []testTx{}
  431. for _, tx := range tc.txs {
  432. fetchedTx := testTx{}
  433. err := doGoodReq("GET", endpoint+tx.TxID.String(), nil, &fetchedTx)
  434. assert.NoError(t, err)
  435. fetchedTxs = append(fetchedTxs, fetchedTx)
  436. }
  437. assertTxs(t, tc.txs, fetchedTxs)
  438. // 400, due invalid TxID
  439. err := doBadReq("GET", endpoint+"0x001", nil, 400)
  440. assert.NoError(t, err)
  441. // 404, due nonexistent TxID in DB
  442. err = doBadReq("GET", endpoint+"0x00eb5e95e1ce5e9f6c4ed402d415e8d0bdd7664769cfd2064d28da04a2c76be432", nil, 404)
  443. assert.NoError(t, err)
  444. }
  445. func assertTxs(t *testing.T, expected, actual []testTx) {
  446. require.Equal(t, len(expected), len(actual))
  447. for i := 0; i < len(actual); i++ { //nolint len(actual) won't change within the loop
  448. assert.Equal(t, expected[i].BatchNum, actual[i].BatchNum)
  449. assert.Equal(t, expected[i].Position, actual[i].Position)
  450. actual[i].ItemID = 0
  451. actual[i].Token.ItemID = 0
  452. assert.Equal(t, expected[i].Timestamp.Unix(), actual[i].Timestamp.Unix())
  453. expected[i].Timestamp = actual[i].Timestamp
  454. if expected[i].Token.USDUpdate == nil {
  455. assert.Equal(t, expected[i].Token.USDUpdate, actual[i].Token.USDUpdate)
  456. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  457. } else {
  458. assert.Equal(t, expected[i].Token.USDUpdate.Unix(), actual[i].Token.USDUpdate.Unix())
  459. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  460. }
  461. test.AssertUSD(t, expected[i].HistoricUSD, actual[i].HistoricUSD)
  462. if expected[i].L2Info != nil {
  463. test.AssertUSD(t, expected[i].L2Info.HistoricFeeUSD, actual[i].L2Info.HistoricFeeUSD)
  464. } else {
  465. test.AssertUSD(t, expected[i].L1Info.HistoricDepositAmountUSD, actual[i].L1Info.HistoricDepositAmountUSD)
  466. }
  467. assert.Equal(t, expected[i], actual[i])
  468. }
  469. }