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.

492 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. // TODO: User L1 txs that create txs will have fromAccountIndex equal to the idx of the
  135. // created account. Once this is done this test will be broken and will need to be updated here.
  136. // At the moment they are null
  137. if l1.Type != common.TxTypeCreateAccountDeposit &&
  138. l1.Type != common.TxTypeCreateAccountDepositTransfer {
  139. idxStr := idxToHez(l1.FromIdx, token.Symbol)
  140. tx.FromIdx = &idxStr
  141. }
  142. // If tx has a normal ToIdx (>255), set FromEthAddr and FromBJJ
  143. if l1.ToIdx >= common.UserThreshold {
  144. // find account
  145. for _, acc := range accs {
  146. if l1.ToIdx == acc.Idx {
  147. toEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  148. tx.ToEthAddr = &toEthAddr
  149. toBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  150. tx.ToBJJ = &toBJJ
  151. break
  152. }
  153. }
  154. }
  155. // If the token has USD value setted
  156. if token.USD != nil {
  157. af := new(big.Float).SetInt(l1.Amount)
  158. amountFloat, _ := af.Float64()
  159. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  160. if usd != 0 {
  161. tx.HistoricUSD = &usd
  162. }
  163. laf := new(big.Float).SetInt(l1.DepositAmount)
  164. depositAmountFloat, _ := laf.Float64()
  165. depositUSD := *token.USD * depositAmountFloat / math.Pow(10, float64(token.Decimals))
  166. if depositAmountFloat != 0 {
  167. tx.L1Info.HistoricDepositAmountUSD = &depositUSD
  168. }
  169. }
  170. txs = append(txs, tx)
  171. }
  172. // common.L2Tx ==> testTx
  173. for i := 0; i < len(l2s); i++ {
  174. token := getTokenByIdx(l2s[i].FromIdx, tokens, accs)
  175. // l1.FromIdx can't be nil
  176. fromIdx := idxToHez(l2s[i].FromIdx, token.Symbol)
  177. tx := testTx{
  178. IsL1: "L2",
  179. TxID: l2s[i].TxID,
  180. Type: l2s[i].Type,
  181. Position: l2s[i].Position,
  182. ToIdx: idxToHez(l2s[i].ToIdx, token.Symbol),
  183. FromIdx: &fromIdx,
  184. Amount: l2s[i].Amount.String(),
  185. BatchNum: &l2s[i].BatchNum,
  186. Timestamp: getTimestamp(l2s[i].EthBlockNum, blocks),
  187. L2Info: &testL2Info{
  188. Nonce: l2s[i].Nonce,
  189. Fee: l2s[i].Fee,
  190. },
  191. Token: token,
  192. }
  193. // If FromIdx is not nil
  194. if l2s[i].FromIdx != 0 {
  195. idxStr := idxToHez(l2s[i].FromIdx, token.Symbol)
  196. tx.FromIdx = &idxStr
  197. }
  198. // Set FromEthAddr and FromBJJ (FromIdx it's always >255)
  199. for _, acc := range accs {
  200. if l2s[i].FromIdx == acc.Idx {
  201. fromEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  202. tx.FromEthAddr = &fromEthAddr
  203. fromBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  204. tx.FromBJJ = &fromBJJ
  205. break
  206. }
  207. }
  208. // If tx has a normal ToIdx (>255), set FromEthAddr and FromBJJ
  209. if l2s[i].ToIdx >= common.UserThreshold {
  210. // find account
  211. for _, acc := range accs {
  212. if l2s[i].ToIdx == acc.Idx {
  213. toEthAddr := string(apitypes.NewHezEthAddr(acc.EthAddr))
  214. tx.ToEthAddr = &toEthAddr
  215. toBJJ := string(apitypes.NewHezBJJ(acc.BJJ))
  216. tx.ToBJJ = &toBJJ
  217. break
  218. }
  219. }
  220. }
  221. // If the token has USD value setted
  222. if token.USD != nil {
  223. af := new(big.Float).SetInt(l2s[i].Amount)
  224. amountFloat, _ := af.Float64()
  225. usd := *token.USD * amountFloat / math.Pow(10, float64(token.Decimals))
  226. if usd != 0 {
  227. tx.HistoricUSD = &usd
  228. feeUSD := usd * l2s[i].Fee.Percentage()
  229. if feeUSD != 0 {
  230. tx.L2Info.HistoricFeeUSD = &feeUSD
  231. }
  232. }
  233. }
  234. txs = append(txs, tx)
  235. }
  236. // Sort txs
  237. sortedTxs := txsSort(txs)
  238. sort.Sort(sortedTxs)
  239. return []testTx(sortedTxs)
  240. }
  241. func TestGetHistoryTxs(t *testing.T) {
  242. endpoint := apiURL + "transactions-history"
  243. fetchedTxs := []testTx{}
  244. appendIter := func(intr interface{}) {
  245. for i := 0; i < len(intr.(*testTxsResponse).Txs); i++ {
  246. tmp, err := copystructure.Copy(intr.(*testTxsResponse).Txs[i])
  247. if err != nil {
  248. panic(err)
  249. }
  250. fetchedTxs = append(fetchedTxs, tmp.(testTx))
  251. }
  252. }
  253. // Get all (no filters)
  254. limit := 20
  255. path := fmt.Sprintf("%s?limit=%d", endpoint, limit)
  256. err := doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  257. assert.NoError(t, err)
  258. assertTxs(t, tc.txs, fetchedTxs)
  259. // Get by ethAddr
  260. account := tc.accounts[2]
  261. fetchedTxs = []testTx{}
  262. limit = 7
  263. path = fmt.Sprintf(
  264. "%s?hezEthereumAddress=%s&limit=%d",
  265. endpoint, account.EthAddr, limit,
  266. )
  267. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  268. assert.NoError(t, err)
  269. accountTxs := []testTx{}
  270. for i := 0; i < len(tc.txs); i++ {
  271. tx := tc.txs[i]
  272. if (tx.FromIdx != nil && *tx.FromIdx == string(account.Idx)) ||
  273. tx.ToIdx == string(account.Idx) ||
  274. (tx.FromEthAddr != nil && *tx.FromEthAddr == string(account.EthAddr)) ||
  275. (tx.ToEthAddr != nil && *tx.ToEthAddr == string(account.EthAddr)) ||
  276. (tx.FromBJJ != nil && *tx.FromBJJ == string(account.PublicKey)) ||
  277. (tx.ToBJJ != nil && *tx.ToBJJ == string(account.PublicKey)) {
  278. accountTxs = append(accountTxs, tx)
  279. }
  280. }
  281. assertTxs(t, accountTxs, fetchedTxs)
  282. // Get by bjj
  283. fetchedTxs = []testTx{}
  284. limit = 6
  285. path = fmt.Sprintf(
  286. "%s?BJJ=%s&limit=%d",
  287. endpoint, account.PublicKey, limit,
  288. )
  289. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  290. assert.NoError(t, err)
  291. assertTxs(t, accountTxs, fetchedTxs)
  292. // Get by tokenID
  293. fetchedTxs = []testTx{}
  294. limit = 5
  295. tokenID := tc.txs[0].Token.TokenID
  296. path = fmt.Sprintf(
  297. "%s?tokenId=%d&limit=%d",
  298. endpoint, tokenID, limit,
  299. )
  300. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  301. assert.NoError(t, err)
  302. tokenIDTxs := []testTx{}
  303. for i := 0; i < len(tc.txs); i++ {
  304. if tc.txs[i].Token.TokenID == tokenID {
  305. tokenIDTxs = append(tokenIDTxs, tc.txs[i])
  306. }
  307. }
  308. assertTxs(t, tokenIDTxs, fetchedTxs)
  309. // idx
  310. fetchedTxs = []testTx{}
  311. limit = 4
  312. idxStr := tc.txs[0].ToIdx
  313. idx, err := stringToIdx(idxStr, "")
  314. assert.NoError(t, err)
  315. path = fmt.Sprintf(
  316. "%s?accountIndex=%s&limit=%d",
  317. endpoint, idxStr, limit,
  318. )
  319. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  320. assert.NoError(t, err)
  321. idxTxs := []testTx{}
  322. for i := 0; i < len(tc.txs); i++ {
  323. var fromIdx *common.Idx
  324. if tc.txs[i].FromIdx != nil {
  325. fromIdx, err = stringToIdx(*tc.txs[i].FromIdx, "")
  326. assert.NoError(t, err)
  327. if *fromIdx == *idx {
  328. idxTxs = append(idxTxs, tc.txs[i])
  329. continue
  330. }
  331. }
  332. toIdx, err := stringToIdx((tc.txs[i].ToIdx), "")
  333. assert.NoError(t, err)
  334. if *toIdx == *idx {
  335. idxTxs = append(idxTxs, tc.txs[i])
  336. }
  337. }
  338. assertTxs(t, idxTxs, fetchedTxs)
  339. // batchNum
  340. fetchedTxs = []testTx{}
  341. limit = 3
  342. batchNum := tc.txs[0].BatchNum
  343. path = fmt.Sprintf(
  344. "%s?batchNum=%d&limit=%d",
  345. endpoint, *batchNum, limit,
  346. )
  347. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  348. assert.NoError(t, err)
  349. batchNumTxs := []testTx{}
  350. for i := 0; i < len(tc.txs); i++ {
  351. if tc.txs[i].BatchNum != nil &&
  352. *tc.txs[i].BatchNum == *batchNum {
  353. batchNumTxs = append(batchNumTxs, tc.txs[i])
  354. }
  355. }
  356. assertTxs(t, batchNumTxs, fetchedTxs)
  357. // type
  358. txTypes := []common.TxType{
  359. // Uncomment once test gen is fixed
  360. common.TxTypeExit,
  361. common.TxTypeTransfer,
  362. common.TxTypeDeposit,
  363. common.TxTypeCreateAccountDeposit,
  364. common.TxTypeCreateAccountDepositTransfer,
  365. common.TxTypeDepositTransfer,
  366. common.TxTypeForceTransfer,
  367. common.TxTypeForceExit,
  368. }
  369. for _, txType := range txTypes {
  370. fetchedTxs = []testTx{}
  371. limit = 2
  372. path = fmt.Sprintf(
  373. "%s?type=%s&limit=%d",
  374. endpoint, txType, limit,
  375. )
  376. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  377. assert.NoError(t, err)
  378. txTypeTxs := []testTx{}
  379. for i := 0; i < len(tc.txs); i++ {
  380. if tc.txs[i].Type == txType {
  381. txTypeTxs = append(txTypeTxs, tc.txs[i])
  382. }
  383. }
  384. assertTxs(t, txTypeTxs, fetchedTxs)
  385. }
  386. // Multiple filters
  387. fetchedTxs = []testTx{}
  388. limit = 1
  389. path = fmt.Sprintf(
  390. "%s?batchNum=%d&tokenId=%d&limit=%d",
  391. endpoint, *batchNum, tokenID, limit,
  392. )
  393. err = doGoodReqPaginated(path, historydb.OrderAsc, &testTxsResponse{}, appendIter)
  394. assert.NoError(t, err)
  395. mixedTxs := []testTx{}
  396. for i := 0; i < len(tc.txs); i++ {
  397. if tc.txs[i].BatchNum != nil {
  398. if *tc.txs[i].BatchNum == *batchNum && tc.txs[i].Token.TokenID == tokenID {
  399. mixedTxs = append(mixedTxs, tc.txs[i])
  400. }
  401. }
  402. }
  403. assertTxs(t, mixedTxs, fetchedTxs)
  404. // All, in reverse order
  405. fetchedTxs = []testTx{}
  406. limit = 5
  407. path = fmt.Sprintf("%s?limit=%d", endpoint, limit)
  408. err = doGoodReqPaginated(path, historydb.OrderDesc, &testTxsResponse{}, appendIter)
  409. assert.NoError(t, err)
  410. flipedTxs := []testTx{}
  411. for i := 0; i < len(tc.txs); i++ {
  412. flipedTxs = append(flipedTxs, tc.txs[len(tc.txs)-1-i])
  413. }
  414. assertTxs(t, flipedTxs, fetchedTxs)
  415. // Empty array
  416. fetchedTxs = []testTx{}
  417. path = fmt.Sprintf("%s?batchNum=999999", endpoint)
  418. err = doGoodReqPaginated(path, historydb.OrderDesc, &testTxsResponse{}, appendIter)
  419. assert.NoError(t, err)
  420. assertTxs(t, []testTx{}, fetchedTxs)
  421. // 400
  422. path = fmt.Sprintf(
  423. "%s?accountIndex=%s&hezEthereumAddress=%s",
  424. endpoint, idx, account.EthAddr,
  425. )
  426. err = doBadReq("GET", path, nil, 400)
  427. assert.NoError(t, err)
  428. path = fmt.Sprintf("%s?tokenId=X", endpoint)
  429. err = doBadReq("GET", path, nil, 400)
  430. assert.NoError(t, err)
  431. }
  432. func TestGetHistoryTx(t *testing.T) {
  433. // Get all txs by their ID
  434. endpoint := apiURL + "transactions-history/"
  435. fetchedTxs := []testTx{}
  436. for _, tx := range tc.txs {
  437. fetchedTx := testTx{}
  438. err := doGoodReq("GET", endpoint+tx.TxID.String(), nil, &fetchedTx)
  439. assert.NoError(t, err)
  440. fetchedTxs = append(fetchedTxs, fetchedTx)
  441. }
  442. assertTxs(t, tc.txs, fetchedTxs)
  443. // 400
  444. err := doBadReq("GET", endpoint+"0x001", nil, 400)
  445. assert.NoError(t, err)
  446. // 404
  447. err = doBadReq("GET", endpoint+"0x00000000000001e240004700", nil, 404)
  448. assert.NoError(t, err)
  449. }
  450. func assertTxs(t *testing.T, expected, actual []testTx) {
  451. require.Equal(t, len(expected), len(actual))
  452. for i := 0; i < len(actual); i++ { //nolint len(actual) won't change within the loop
  453. assert.Equal(t, expected[i].BatchNum, actual[i].BatchNum)
  454. assert.Equal(t, expected[i].Position, actual[i].Position)
  455. actual[i].ItemID = 0
  456. actual[i].Token.ItemID = 0
  457. assert.Equal(t, expected[i].Timestamp.Unix(), actual[i].Timestamp.Unix())
  458. expected[i].Timestamp = actual[i].Timestamp
  459. if expected[i].Token.USDUpdate == nil {
  460. assert.Equal(t, expected[i].Token.USDUpdate, actual[i].Token.USDUpdate)
  461. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  462. } else {
  463. assert.Equal(t, expected[i].Token.USDUpdate.Unix(), actual[i].Token.USDUpdate.Unix())
  464. expected[i].Token.USDUpdate = actual[i].Token.USDUpdate
  465. }
  466. test.AssertUSD(t, expected[i].HistoricUSD, actual[i].HistoricUSD)
  467. if expected[i].L2Info != nil {
  468. test.AssertUSD(t, expected[i].L2Info.HistoricFeeUSD, actual[i].L2Info.HistoricFeeUSD)
  469. } else {
  470. test.AssertUSD(t, expected[i].L1Info.HistoricDepositAmountUSD, actual[i].L1Info.HistoricDepositAmountUSD)
  471. }
  472. assert.Equal(t, expected[i], actual[i])
  473. }
  474. }