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