arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/l2db/l2db_test.go
db/l2db/l2db_test.goRaw
  1package l2db
  2
  3import (
  4	"math/big"
  5	"os"
  6	"testing"
  7	"time"
  8
  9	ethCommon "github.com/ethereum/go-ethereum/common"
 10	"github.com/hermeznetwork/hermez-node/common"
 11	dbUtils "github.com/hermeznetwork/hermez-node/db"
 12	"github.com/hermeznetwork/hermez-node/db/historydb"
 13	"github.com/hermeznetwork/hermez-node/log"
 14	"github.com/hermeznetwork/hermez-node/test"
 15	"github.com/jmoiron/sqlx"
 16	"github.com/stretchr/testify/assert"
 17)
 18
 19var l2DB *L2DB
 20var tokens []common.Token
 21var tokensUSD []historydb.TokenRead
 22
 23func TestMain(m *testing.M) {
 24	// init DB
 25	pass := os.Getenv("POSTGRES_PASS")
 26	db, err := dbUtils.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
 27	if err != nil {
 28		panic(err)
 29	}
 30	l2DB = NewL2DB(db, 10, 100, 24*time.Hour)
 31	tokens, tokensUSD = prepareHistoryDB(db)
 32	if err != nil {
 33		panic(err)
 34	}
 35	// Run tests
 36	result := m.Run()
 37	// Close DB
 38	if err := db.Close(); err != nil {
 39		log.Error("Error closing the history DB:", err)
 40	}
 41	os.Exit(result)
 42}
 43
 44func prepareHistoryDB(db *sqlx.DB) ([]common.Token, []historydb.TokenRead) {
 45	historyDB := historydb.NewHistoryDB(db)
 46	const fromBlock int64 = 1
 47	const toBlock int64 = 5
 48	// Clean historyDB
 49	if err := historyDB.Reorg(-1); err != nil {
 50		panic(err)
 51	}
 52	// Store blocks to historyDB
 53	blocks := test.GenBlocks(fromBlock, toBlock)
 54	if err := historyDB.AddBlocks(blocks); err != nil {
 55		panic(err)
 56	}
 57	// Store tokens to historyDB
 58	const nTokens = 5
 59	tokens := test.GenTokens(nTokens, blocks)
 60	if err := historyDB.AddTokens(tokens); err != nil {
 61		panic(err)
 62	}
 63	readTokens := []historydb.TokenRead{}
 64	for i, token := range tokens {
 65		readToken := historydb.TokenRead{
 66			TokenID:     token.TokenID,
 67			EthBlockNum: token.EthBlockNum,
 68			EthAddr:     token.EthAddr,
 69			Name:        token.Name,
 70			Symbol:      token.Symbol,
 71			Decimals:    token.Decimals,
 72		}
 73		if i%2 != 0 {
 74			value := float64(i) * 5.4321
 75			if err := historyDB.UpdateTokenValue(token.Symbol, value); err != nil {
 76				panic(err)
 77			}
 78			now := time.Now().UTC()
 79			readToken.USDUpdate = &now
 80			readToken.USD = &value
 81		}
 82		readTokens = append(readTokens, readToken)
 83	}
 84	return tokens, readTokens
 85}
 86
 87func TestAddTxTest(t *testing.T) {
 88	// Gen poolTxs
 89	const nInserts = 20
 90	test.CleanL2DB(l2DB.DB())
 91	txs := test.GenPoolTxs(nInserts, tokens)
 92	for _, tx := range txs {
 93		err := l2DB.AddTxTest(tx)
 94		assert.NoError(t, err)
 95		fetchedTx, err := l2DB.GetTx(tx.TxID)
 96		assert.NoError(t, err)
 97		assertReadTx(t, commonToRead(tx, tokens), fetchedTx)
 98	}
 99}
100
101func commonToRead(commonTx *common.PoolL2Tx, tokens []common.Token) *PoolL2TxRead {
102	readTx := &PoolL2TxRead{
103		TxID:      commonTx.TxID,
104		FromIdx:   commonTx.FromIdx,
105		ToBJJ:     commonTx.ToBJJ,
106		Amount:    commonTx.Amount,
107		Fee:       commonTx.Fee,
108		Nonce:     commonTx.Nonce,
109		State:     commonTx.State,
110		Signature: commonTx.Signature,
111		RqToBJJ:   commonTx.RqToBJJ,
112		RqAmount:  commonTx.RqAmount,
113		Type:      commonTx.Type,
114		Timestamp: commonTx.Timestamp,
115		TokenID:   commonTx.TokenID,
116	}
117	// token related fields
118	// find token
119	token := historydb.TokenRead{}
120	for _, tkn := range tokensUSD {
121		if tkn.TokenID == readTx.TokenID {
122			token = tkn
123			break
124		}
125	}
126	// set token related fields
127	readTx.TokenEthBlockNum = token.EthBlockNum
128	readTx.TokenEthAddr = token.EthAddr
129	readTx.TokenName = token.Name
130	readTx.TokenSymbol = token.Symbol
131	readTx.TokenDecimals = token.Decimals
132	readTx.TokenUSD = token.USD
133	readTx.TokenUSDUpdate = token.USDUpdate
134	// nullable fields
135	if commonTx.ToIdx != 0 {
136		readTx.ToIdx = &commonTx.ToIdx
137	}
138	nilAddr := ethCommon.BigToAddress(big.NewInt(0))
139	if commonTx.ToEthAddr != nilAddr {
140		readTx.ToEthAddr = &commonTx.ToEthAddr
141	}
142	if commonTx.RqFromIdx != 0 {
143		readTx.RqFromIdx = &commonTx.RqFromIdx
144	}
145	if commonTx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
146		readTx.RqToIdx = &commonTx.RqToIdx
147		readTx.RqTokenID = &commonTx.RqTokenID
148		readTx.RqFee = &commonTx.RqFee
149		readTx.RqNonce = &commonTx.RqNonce
150	}
151	if commonTx.RqToEthAddr != nilAddr {
152		readTx.RqToEthAddr = &commonTx.RqToEthAddr
153	}
154	return readTx
155}
156
157func assertReadTx(t *testing.T, expected, actual *PoolL2TxRead) {
158	// Check that timestamp has been set within the last 3 seconds
159	assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
160	assert.GreaterOrEqual(t, time.Now().UTC().Unix(), actual.Timestamp.Unix())
161	expected.Timestamp = actual.Timestamp
162	// Check token related stuff
163	if expected.TokenUSDUpdate != nil {
164		// Check that TokenUSDUpdate has been set within the last 3 seconds
165		assert.Less(t, time.Now().UTC().Unix()-3, actual.TokenUSDUpdate.Unix())
166		assert.GreaterOrEqual(t, time.Now().UTC().Unix(), actual.TokenUSDUpdate.Unix())
167		expected.TokenUSDUpdate = actual.TokenUSDUpdate
168	}
169	assert.Equal(t, expected, actual)
170}
171
172func assertTx(t *testing.T, expected, actual *common.PoolL2Tx) {
173	// Check that timestamp has been set within the last 3 seconds
174	assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
175	assert.GreaterOrEqual(t, time.Now().UTC().Unix(), actual.Timestamp.Unix())
176	expected.Timestamp = actual.Timestamp
177	// Check absolute fee
178	// find token
179	token := historydb.TokenRead{}
180	for _, tkn := range tokensUSD {
181		if expected.TokenID == tkn.TokenID {
182			token = tkn
183			break
184		}
185	}
186	// If the token has value in USD setted
187	if token.USDUpdate != nil {
188		assert.Equal(t, token.USDUpdate.Unix(), actual.AbsoluteFeeUpdate.Unix())
189		expected.AbsoluteFeeUpdate = actual.AbsoluteFeeUpdate
190		// Set expected fee
191		f := new(big.Float).SetInt(expected.Amount)
192		amountF, _ := f.Float64()
193		expected.AbsoluteFee = *token.USD * amountF * expected.Fee.Percentage()
194		test.AssertUSD(t, &expected.AbsoluteFee, &actual.AbsoluteFee)
195	}
196	assert.Equal(t, expected, actual)
197}
198
199func BenchmarkAddTxTest(b *testing.B) {
200	const nInserts = 20
201	test.CleanL2DB(l2DB.DB())
202	txs := test.GenPoolTxs(nInserts, tokens)
203	now := time.Now()
204	for _, tx := range txs {
205		_ = l2DB.AddTxTest(tx)
206	}
207	elapsedTime := time.Since(now)
208	log.Info("Time to insert 2048 txs:", elapsedTime)
209}
210
211func TestGetPending(t *testing.T) {
212	const nInserts = 20
213	test.CleanL2DB(l2DB.DB())
214	txs := test.GenPoolTxs(nInserts, tokens)
215	var pendingTxs []*common.PoolL2Tx
216	for _, tx := range txs {
217		err := l2DB.AddTxTest(tx)
218		assert.NoError(t, err)
219		if tx.State == common.PoolL2TxStatePending {
220			pendingTxs = append(pendingTxs, tx)
221		}
222	}
223	fetchedTxs, err := l2DB.GetPendingTxs()
224	assert.NoError(t, err)
225	assert.Equal(t, len(pendingTxs), len(fetchedTxs))
226	for i := range fetchedTxs {
227		assertTx(t, pendingTxs[i], &fetchedTxs[i])
228	}
229}
230
231func TestStartForging(t *testing.T) {
232	// Generate txs
233	const nInserts = 60
234	const fakeBatchNum common.BatchNum = 33
235	test.CleanL2DB(l2DB.DB())
236	txs := test.GenPoolTxs(nInserts, tokens)
237	var startForgingTxIDs []common.TxID
238	randomizer := 0
239	// Add txs to DB
240	for _, tx := range txs {
241		err := l2DB.AddTxTest(tx)
242		assert.NoError(t, err)
243		if tx.State == common.PoolL2TxStatePending && randomizer%2 == 0 {
244			randomizer++
245			startForgingTxIDs = append(startForgingTxIDs, tx.TxID)
246		}
247	}
248	// Start forging txs
249	err := l2DB.StartForging(startForgingTxIDs, fakeBatchNum)
250	assert.NoError(t, err)
251	// Fetch txs and check that they've been updated correctly
252	for _, id := range startForgingTxIDs {
253		fetchedTx, err := l2DB.GetTx(id)
254		assert.NoError(t, err)
255		assert.Equal(t, common.PoolL2TxStateForging, fetchedTx.State)
256		assert.Equal(t, fakeBatchNum, *fetchedTx.BatchNum)
257	}
258}
259
260func TestDoneForging(t *testing.T) {
261	// Generate txs
262	const nInserts = 60
263	const fakeBatchNum common.BatchNum = 33
264	test.CleanL2DB(l2DB.DB())
265	txs := test.GenPoolTxs(nInserts, tokens)
266	var doneForgingTxIDs []common.TxID
267	randomizer := 0
268	// Add txs to DB
269	for _, tx := range txs {
270		err := l2DB.AddTxTest(tx)
271		assert.NoError(t, err)
272		if tx.State == common.PoolL2TxStateForging && randomizer%2 == 0 {
273			randomizer++
274			doneForgingTxIDs = append(doneForgingTxIDs, tx.TxID)
275		}
276	}
277	// Start forging txs
278	err := l2DB.DoneForging(doneForgingTxIDs, fakeBatchNum)
279	assert.NoError(t, err)
280	// Fetch txs and check that they've been updated correctly
281	for _, id := range doneForgingTxIDs {
282		fetchedTx, err := l2DB.GetTx(id)
283		assert.NoError(t, err)
284		assert.Equal(t, common.PoolL2TxStateForged, fetchedTx.State)
285		assert.Equal(t, fakeBatchNum, *fetchedTx.BatchNum)
286	}
287}
288
289func TestInvalidate(t *testing.T) {
290	// Generate txs
291	const nInserts = 60
292	const fakeBatchNum common.BatchNum = 33
293	test.CleanL2DB(l2DB.DB())
294	txs := test.GenPoolTxs(nInserts, tokens)
295	var invalidTxIDs []common.TxID
296	randomizer := 0
297	// Add txs to DB
298	for _, tx := range txs {
299		err := l2DB.AddTxTest(tx)
300		assert.NoError(t, err)
301		if tx.State != common.PoolL2TxStateInvalid && randomizer%2 == 0 {
302			randomizer++
303			invalidTxIDs = append(invalidTxIDs, tx.TxID)
304		}
305	}
306	// Start forging txs
307	err := l2DB.InvalidateTxs(invalidTxIDs, fakeBatchNum)
308	assert.NoError(t, err)
309	// Fetch txs and check that they've been updated correctly
310	for _, id := range invalidTxIDs {
311		fetchedTx, err := l2DB.GetTx(id)
312		assert.NoError(t, err)
313		assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
314		assert.Equal(t, fakeBatchNum, *fetchedTx.BatchNum)
315	}
316}
317
318func TestCheckNonces(t *testing.T) {
319	// Generate txs
320	const nInserts = 60
321	const fakeBatchNum common.BatchNum = 33
322	test.CleanL2DB(l2DB.DB())
323	txs := test.GenPoolTxs(nInserts, tokens)
324	var invalidTxIDs []common.TxID
325	// Generate accounts
326	const nAccoutns = 2
327	const currentNonce = 2
328	accs := []common.Account{}
329	for i := 0; i < nAccoutns; i++ {
330		accs = append(accs, common.Account{
331			Idx:   common.Idx(i),
332			Nonce: currentNonce,
333		})
334	}
335	// Add txs to DB
336	for i := 0; i < len(txs); i++ {
337		if txs[i].State != common.PoolL2TxStateInvalid {
338			if i%2 == 0 { // Ensure transaction will be marked as invalid due to old nonce
339				txs[i].Nonce = accs[i%len(accs)].Nonce
340				txs[i].FromIdx = accs[i%len(accs)].Idx
341				invalidTxIDs = append(invalidTxIDs, txs[i].TxID)
342			} else { // Ensure transaction will NOT be marked as invalid due to old nonce
343				txs[i].Nonce = currentNonce + 1
344			}
345		}
346		err := l2DB.AddTxTest(txs[i])
347		assert.NoError(t, err)
348	}
349	// Start forging txs
350	err := l2DB.InvalidateTxs(invalidTxIDs, fakeBatchNum)
351	assert.NoError(t, err)
352	// Fetch txs and check that they've been updated correctly
353	for _, id := range invalidTxIDs {
354		fetchedTx, err := l2DB.GetTx(id)
355		assert.NoError(t, err)
356		assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
357		assert.Equal(t, fakeBatchNum, *fetchedTx.BatchNum)
358	}
359}
360
361func TestReorg(t *testing.T) {
362	// Generate txs
363	const nInserts = 20
364	const lastValidBatch common.BatchNum = 20
365	const reorgBatch common.BatchNum = lastValidBatch + 1
366	test.CleanL2DB(l2DB.DB())
367	txs := test.GenPoolTxs(nInserts, tokens)
368	// Add txs to the DB
369	reorgedTxIDs := []common.TxID{}
370	nonReorgedTxIDs := []common.TxID{}
371	for i := 0; i < len(txs); i++ {
372		err := l2DB.AddTxTest(txs[i])
373		assert.NoError(t, err)
374		var batchNum common.BatchNum
375		if txs[i].State == common.PoolL2TxStateForged || txs[i].State == common.PoolL2TxStateInvalid {
376			reorgedTxIDs = append(reorgedTxIDs, txs[i].TxID)
377			batchNum = reorgBatch
378		} else {
379			nonReorgedTxIDs = append(nonReorgedTxIDs, txs[i].TxID)
380			batchNum = lastValidBatch
381		}
382		_, err = l2DB.db.Exec(
383			"UPDATE tx_pool SET batch_num = $1 WHERE tx_id = $2;",
384			batchNum, txs[i].TxID,
385		)
386		assert.NoError(t, err)
387	}
388	err := l2DB.Reorg(lastValidBatch)
389	assert.NoError(t, err)
390	for _, id := range reorgedTxIDs {
391		tx, err := l2DB.GetTx(id)
392		assert.NoError(t, err)
393		assert.Nil(t, tx.BatchNum)
394		assert.Equal(t, common.PoolL2TxStatePending, tx.State)
395	}
396	for _, id := range nonReorgedTxIDs {
397		fetchedTx, err := l2DB.GetTx(id)
398		assert.NoError(t, err)
399		assert.Equal(t, lastValidBatch, *fetchedTx.BatchNum)
400	}
401}
402
403func TestPurge(t *testing.T) {
404	// Generate txs
405	nInserts := l2DB.maxTxs + 20
406	test.CleanL2DB(l2DB.DB())
407	txs := test.GenPoolTxs(int(nInserts), tokens)
408	deletedIDs := []common.TxID{}
409	keepedIDs := []common.TxID{}
410	const toDeleteBatchNum common.BatchNum = 30
411	safeBatchNum := toDeleteBatchNum + l2DB.safetyPeriod + 1
412	// Add txs to the DB
413	for i := 0; i < int(l2DB.maxTxs); i++ {
414		var batchNum common.BatchNum
415		if i%2 == 0 { // keep tx
416			batchNum = safeBatchNum
417			keepedIDs = append(keepedIDs, txs[i].TxID)
418		} else { // delete after safety period
419			batchNum = toDeleteBatchNum
420			if i%3 == 0 {
421				txs[i].State = common.PoolL2TxStateForged
422			} else {
423				txs[i].State = common.PoolL2TxStateInvalid
424			}
425			deletedIDs = append(deletedIDs, txs[i].TxID)
426		}
427		err := l2DB.AddTxTest(txs[i])
428		assert.NoError(t, err)
429		// Set batchNum
430		_, err = l2DB.db.Exec(
431			"UPDATE tx_pool SET batch_num = $1 WHERE tx_id = $2;",
432			batchNum, txs[i].TxID,
433		)
434		assert.NoError(t, err)
435	}
436	for i := int(l2DB.maxTxs); i < len(txs); i++ {
437		// Delete after TTL
438		deletedIDs = append(deletedIDs, txs[i].TxID)
439		err := l2DB.AddTxTest(txs[i])
440		assert.NoError(t, err)
441		// Set timestamp
442		deleteTimestamp := time.Unix(time.Now().UTC().Unix()-int64(l2DB.ttl.Seconds()+float64(4*time.Second)), 0)
443		_, err = l2DB.db.Exec(
444			"UPDATE tx_pool SET timestamp = $1 WHERE tx_id = $2;",
445			deleteTimestamp, txs[i].TxID,
446		)
447		assert.NoError(t, err)
448	}
449	// Purge txs
450	err := l2DB.Purge(safeBatchNum)
451	assert.NoError(t, err)
452	// Check results
453	for _, id := range deletedIDs {
454		tx, err := l2DB.GetTx(id)
455		if err == nil {
456			log.Debug(tx)
457		}
458		assert.Error(t, err)
459	}
460	for _, id := range keepedIDs {
461		_, err := l2DB.GetTx(id)
462		assert.NoError(t, err)
463	}
464}
465
466func TestAuth(t *testing.T) {
467	test.CleanL2DB(l2DB.DB())
468	const nAuths = 5
469	// Generate authorizations
470	auths := test.GenAuths(nAuths)
471	for i := 0; i < len(auths); i++ {
472		// Add to the DB
473		err := l2DB.AddAccountCreationAuth(auths[i])
474		assert.NoError(t, err)
475		// Fetch from DB
476		auth, err := l2DB.GetAccountCreationAuth(auths[i].EthAddr)
477		assert.NoError(t, err)
478		// Check fetched vs generated
479		assert.Equal(t, auths[i].EthAddr, auth.EthAddr)
480		assert.Equal(t, auths[i].BJJ, auth.BJJ)
481		assert.Equal(t, auths[i].Signature, auth.Signature)
482		assert.Equal(t, auths[i].Timestamp.Unix(), auths[i].Timestamp.Unix())
483	}
484}