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.

507 lines
15 KiB

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