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.

676 lines
20 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package l2db
  2. import (
  3. "math"
  4. "math/big"
  5. "os"
  6. "testing"
  7. "time"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. dbUtils "github.com/hermeznetwork/hermez-node/db"
  11. "github.com/hermeznetwork/hermez-node/db/historydb"
  12. "github.com/hermeznetwork/hermez-node/log"
  13. "github.com/hermeznetwork/hermez-node/test"
  14. "github.com/hermeznetwork/hermez-node/test/til"
  15. "github.com/hermeznetwork/tracerr"
  16. "github.com/iden3/go-iden3-crypto/babyjub"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. )
  20. var l2DB *L2DB
  21. var historyDB *historydb.HistoryDB
  22. var tc *til.Context
  23. var tokens map[common.TokenID]historydb.TokenWithUSD
  24. var tokensValue map[common.TokenID]float64
  25. var accs map[common.Idx]common.Account
  26. func TestMain(m *testing.M) {
  27. // init DB
  28. pass := os.Getenv("POSTGRES_PASS")
  29. db, err := dbUtils.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  30. if err != nil {
  31. panic(err)
  32. }
  33. l2DB = NewL2DB(db, 10, 1000, 24*time.Hour)
  34. test.WipeDB(l2DB.DB())
  35. historyDB = historydb.NewHistoryDB(db)
  36. // Run tests
  37. result := m.Run()
  38. // Close DB
  39. if err := db.Close(); err != nil {
  40. log.Error("Error closing the history DB:", err)
  41. }
  42. os.Exit(result)
  43. }
  44. func prepareHistoryDB(historyDB *historydb.HistoryDB) error {
  45. // Reset DB
  46. test.WipeDB(l2DB.DB())
  47. // Generate pool txs using til
  48. setBlockchain := `
  49. Type: Blockchain
  50. AddToken(1)
  51. AddToken(2)
  52. CreateAccountDeposit(1) A: 2000
  53. CreateAccountDeposit(2) A: 2000
  54. CreateAccountDeposit(1) B: 1000
  55. CreateAccountDeposit(2) B: 1000
  56. > batchL1
  57. > batchL1
  58. > block
  59. > block
  60. `
  61. tc = til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  62. tilCfgExtra := til.ConfigExtra{
  63. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  64. CoordUser: "A",
  65. }
  66. blocks, err := tc.GenerateBlocks(setBlockchain)
  67. if err != nil {
  68. return tracerr.Wrap(err)
  69. }
  70. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  71. if err != nil {
  72. return tracerr.Wrap(err)
  73. }
  74. tokens = make(map[common.TokenID]historydb.TokenWithUSD)
  75. tokensValue = make(map[common.TokenID]float64)
  76. accs = make(map[common.Idx]common.Account)
  77. value := 5 * 5.389329
  78. now := time.Now().UTC()
  79. // Add all blocks except for the last one
  80. for i := range blocks[:len(blocks)-1] {
  81. err = historyDB.AddBlockSCData(&blocks[i])
  82. if err != nil {
  83. return tracerr.Wrap(err)
  84. }
  85. for _, batch := range blocks[i].Rollup.Batches {
  86. for _, account := range batch.CreatedAccounts {
  87. accs[account.Idx] = account
  88. }
  89. }
  90. for _, token := range blocks[i].Rollup.AddedTokens {
  91. readToken := historydb.TokenWithUSD{
  92. TokenID: token.TokenID,
  93. EthBlockNum: token.EthBlockNum,
  94. EthAddr: token.EthAddr,
  95. Name: token.Name,
  96. Symbol: token.Symbol,
  97. Decimals: token.Decimals,
  98. }
  99. tokensValue[token.TokenID] = value / math.Pow(10, float64(token.Decimals))
  100. readToken.USDUpdate = &now
  101. readToken.USD = &value
  102. tokens[token.TokenID] = readToken
  103. }
  104. // Set value to the tokens (tokens have no symbol)
  105. tokenSymbol := ""
  106. err := historyDB.UpdateTokenValue(tokenSymbol, value)
  107. if err != nil {
  108. return tracerr.Wrap(err)
  109. }
  110. }
  111. return nil
  112. }
  113. func generatePoolL2Txs() ([]common.PoolL2Tx, error) {
  114. setPool := `
  115. Type: PoolL2
  116. PoolTransfer(1) A-B: 6 (4)
  117. PoolTransfer(2) A-B: 3 (1)
  118. PoolTransfer(1) B-A: 5 (2)
  119. PoolTransfer(2) B-A: 10 (3)
  120. PoolTransfer(1) A-B: 7 (2)
  121. PoolTransfer(2) A-B: 2 (1)
  122. PoolTransfer(1) B-A: 8 (2)
  123. PoolTransfer(2) B-A: 1 (1)
  124. PoolTransfer(1) A-B: 3 (1)
  125. PoolTransferToEthAddr(2) B-A: 5 (2)
  126. PoolTransferToBJJ(2) B-A: 5 (2)
  127. PoolExit(1) A: 5 (2)
  128. PoolExit(2) B: 3 (1)
  129. `
  130. poolL2Txs, err := tc.GeneratePoolL2Txs(setPool)
  131. if err != nil {
  132. return nil, tracerr.Wrap(err)
  133. }
  134. return poolL2Txs, nil
  135. }
  136. func TestAddTxTest(t *testing.T) {
  137. err := prepareHistoryDB(historyDB)
  138. if err != nil {
  139. log.Error("Error prepare historyDB", err)
  140. }
  141. poolL2Txs, err := generatePoolL2Txs()
  142. assert.NoError(t, err)
  143. for i := range poolL2Txs {
  144. err := l2DB.AddTxTest(&poolL2Txs[i])
  145. assert.NoError(t, err)
  146. fetchedTx, err := l2DB.GetTx(poolL2Txs[i].TxID)
  147. assert.NoError(t, err)
  148. assertTx(t, &poolL2Txs[i], fetchedTx)
  149. nameZone, offset := fetchedTx.Timestamp.Zone()
  150. assert.Equal(t, "UTC", nameZone)
  151. assert.Equal(t, 0, offset)
  152. }
  153. }
  154. func assertTx(t *testing.T, expected, actual *common.PoolL2Tx) {
  155. // Check that timestamp has been set within the last 3 seconds
  156. assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
  157. assert.GreaterOrEqual(t, time.Now().UTC().Unix(), actual.Timestamp.Unix())
  158. expected.Timestamp = actual.Timestamp
  159. // Check absolute fee
  160. // find token
  161. token := tokens[expected.TokenID]
  162. // If the token has value in USD setted
  163. if token.USDUpdate != nil {
  164. assert.Less(t, token.USDUpdate.Unix()-3, actual.AbsoluteFeeUpdate.Unix())
  165. expected.AbsoluteFeeUpdate = actual.AbsoluteFeeUpdate
  166. // Set expected fee
  167. f := new(big.Float).SetInt(expected.Amount)
  168. amountF, _ := f.Float64()
  169. expected.AbsoluteFee = *token.USD * amountF * expected.Fee.Percentage()
  170. test.AssertUSD(t, &expected.AbsoluteFee, &actual.AbsoluteFee)
  171. }
  172. assert.Equal(t, expected, actual)
  173. }
  174. // NO UPDATE: benchmarks will be done after impl is finished
  175. // func BenchmarkAddTxTest(b *testing.B) {
  176. // const nInserts = 20
  177. // test.WipeDB(l2DB.DB())
  178. // txs := test.GenPoolTxs(nInserts, tokens)
  179. // now := time.Now()
  180. // for _, tx := range txs {
  181. // _ = l2DB.AddTxTest(tx)
  182. // }
  183. // elapsedTime := time.Since(now)
  184. // log.Info("Time to insert 2048 txs:", elapsedTime)
  185. // }
  186. func TestGetPending(t *testing.T) {
  187. err := prepareHistoryDB(historyDB)
  188. if err != nil {
  189. log.Error("Error prepare historyDB", err)
  190. }
  191. poolL2Txs, err := generatePoolL2Txs()
  192. assert.NoError(t, err)
  193. var pendingTxs []*common.PoolL2Tx
  194. for i := range poolL2Txs {
  195. err := l2DB.AddTxTest(&poolL2Txs[i])
  196. assert.NoError(t, err)
  197. pendingTxs = append(pendingTxs, &poolL2Txs[i])
  198. }
  199. fetchedTxs, err := l2DB.GetPendingTxs()
  200. assert.NoError(t, err)
  201. assert.Equal(t, len(pendingTxs), len(fetchedTxs))
  202. for i := range fetchedTxs {
  203. assertTx(t, pendingTxs[i], &fetchedTxs[i])
  204. }
  205. }
  206. func TestStartForging(t *testing.T) {
  207. // Generate txs
  208. var fakeBatchNum common.BatchNum = 33
  209. err := prepareHistoryDB(historyDB)
  210. if err != nil {
  211. log.Error("Error prepare historyDB", err)
  212. }
  213. poolL2Txs, err := generatePoolL2Txs()
  214. assert.NoError(t, err)
  215. var startForgingTxIDs []common.TxID
  216. randomizer := 0
  217. // Add txs to DB
  218. for i := range poolL2Txs {
  219. err := l2DB.AddTxTest(&poolL2Txs[i])
  220. assert.NoError(t, err)
  221. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  222. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  223. }
  224. randomizer++
  225. }
  226. // Start forging txs
  227. err = l2DB.StartForging(startForgingTxIDs, fakeBatchNum)
  228. assert.NoError(t, err)
  229. // Fetch txs and check that they've been updated correctly
  230. for _, id := range startForgingTxIDs {
  231. fetchedTx, err := l2DB.GetTxAPI(id)
  232. assert.NoError(t, err)
  233. assert.Equal(t, common.PoolL2TxStateForging, fetchedTx.State)
  234. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  235. }
  236. }
  237. func TestDoneForging(t *testing.T) {
  238. // Generate txs
  239. var fakeBatchNum common.BatchNum = 33
  240. err := prepareHistoryDB(historyDB)
  241. if err != nil {
  242. log.Error("Error prepare historyDB", err)
  243. }
  244. poolL2Txs, err := generatePoolL2Txs()
  245. assert.NoError(t, err)
  246. var startForgingTxIDs []common.TxID
  247. randomizer := 0
  248. // Add txs to DB
  249. for i := range poolL2Txs {
  250. err := l2DB.AddTxTest(&poolL2Txs[i])
  251. assert.NoError(t, err)
  252. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  253. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  254. }
  255. randomizer++
  256. }
  257. // Start forging txs
  258. err = l2DB.StartForging(startForgingTxIDs, fakeBatchNum)
  259. assert.NoError(t, err)
  260. var doneForgingTxIDs []common.TxID
  261. randomizer = 0
  262. for _, txID := range startForgingTxIDs {
  263. if randomizer%2 == 0 {
  264. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  265. }
  266. randomizer++
  267. }
  268. // Done forging txs
  269. err = l2DB.DoneForging(doneForgingTxIDs, fakeBatchNum)
  270. assert.NoError(t, err)
  271. // Fetch txs and check that they've been updated correctly
  272. for _, id := range doneForgingTxIDs {
  273. fetchedTx, err := l2DB.GetTxAPI(id)
  274. assert.NoError(t, err)
  275. assert.Equal(t, common.PoolL2TxStateForged, fetchedTx.State)
  276. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  277. }
  278. }
  279. func TestInvalidate(t *testing.T) {
  280. // Generate txs
  281. var fakeBatchNum common.BatchNum = 33
  282. err := prepareHistoryDB(historyDB)
  283. if err != nil {
  284. log.Error("Error prepare historyDB", err)
  285. }
  286. poolL2Txs, err := generatePoolL2Txs()
  287. assert.NoError(t, err)
  288. var invalidTxIDs []common.TxID
  289. randomizer := 0
  290. // Add txs to DB
  291. for i := range poolL2Txs {
  292. err := l2DB.AddTxTest(&poolL2Txs[i])
  293. assert.NoError(t, err)
  294. if poolL2Txs[i].State != common.PoolL2TxStateInvalid && randomizer%2 == 0 {
  295. randomizer++
  296. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  297. }
  298. }
  299. // Invalidate txs
  300. err = l2DB.InvalidateTxs(invalidTxIDs, fakeBatchNum)
  301. assert.NoError(t, err)
  302. // Fetch txs and check that they've been updated correctly
  303. for _, id := range invalidTxIDs {
  304. fetchedTx, err := l2DB.GetTxAPI(id)
  305. assert.NoError(t, err)
  306. assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
  307. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  308. }
  309. }
  310. func TestInvalidateOldNonces(t *testing.T) {
  311. // Generate txs
  312. var fakeBatchNum common.BatchNum = 33
  313. err := prepareHistoryDB(historyDB)
  314. if err != nil {
  315. log.Error("Error prepare historyDB", err)
  316. }
  317. poolL2Txs, err := generatePoolL2Txs()
  318. assert.NoError(t, err)
  319. // Update Accounts currentNonce
  320. var updateAccounts []common.IdxNonce
  321. var currentNonce = common.Nonce(1)
  322. for i := range accs {
  323. updateAccounts = append(updateAccounts, common.IdxNonce{
  324. Idx: accs[i].Idx,
  325. Nonce: common.Nonce(currentNonce),
  326. })
  327. }
  328. // Add txs to DB
  329. var invalidTxIDs []common.TxID
  330. for i := range poolL2Txs {
  331. if poolL2Txs[i].Nonce < currentNonce {
  332. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  333. }
  334. err := l2DB.AddTxTest(&poolL2Txs[i])
  335. assert.NoError(t, err)
  336. }
  337. // sanity check
  338. require.Greater(t, len(invalidTxIDs), 0)
  339. err = l2DB.InvalidateOldNonces(updateAccounts, fakeBatchNum)
  340. assert.NoError(t, err)
  341. // Fetch txs and check that they've been updated correctly
  342. for _, id := range invalidTxIDs {
  343. fetchedTx, err := l2DB.GetTxAPI(id)
  344. require.NoError(t, err)
  345. assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
  346. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  347. }
  348. }
  349. // TestReorg: first part of the test with reorg
  350. // With invalidated transactions BEFORE reorgBatch
  351. // And forged transactions in reorgBatch
  352. func TestReorg(t *testing.T) {
  353. // Generate txs
  354. const lastValidBatch common.BatchNum = 20
  355. const reorgBatch common.BatchNum = lastValidBatch + 1
  356. err := prepareHistoryDB(historyDB)
  357. if err != nil {
  358. log.Error("Error prepare historyDB", err)
  359. }
  360. poolL2Txs, err := generatePoolL2Txs()
  361. assert.NoError(t, err)
  362. reorgedTxIDs := []common.TxID{}
  363. nonReorgedTxIDs := []common.TxID{}
  364. var startForgingTxIDs []common.TxID
  365. var invalidTxIDs []common.TxID
  366. var allTxRandomize []common.TxID
  367. randomizer := 0
  368. // Add txs to DB
  369. for i := range poolL2Txs {
  370. err := l2DB.AddTxTest(&poolL2Txs[i])
  371. assert.NoError(t, err)
  372. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  373. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  374. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  375. } else if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%3 == 0 {
  376. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  377. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  378. }
  379. randomizer++
  380. }
  381. // Start forging txs
  382. err = l2DB.StartForging(startForgingTxIDs, lastValidBatch)
  383. assert.NoError(t, err)
  384. var doneForgingTxIDs []common.TxID
  385. randomizer = 0
  386. for _, txID := range allTxRandomize {
  387. invalidTx := false
  388. for i := range invalidTxIDs {
  389. if invalidTxIDs[i] == txID {
  390. invalidTx = true
  391. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  392. }
  393. }
  394. if !invalidTx {
  395. if randomizer%2 == 0 {
  396. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  397. reorgedTxIDs = append(reorgedTxIDs, txID)
  398. } else {
  399. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  400. }
  401. randomizer++
  402. }
  403. }
  404. // Invalidate txs BEFORE reorgBatch --> nonReorg
  405. err = l2DB.InvalidateTxs(invalidTxIDs, lastValidBatch)
  406. assert.NoError(t, err)
  407. // Done forging txs in reorgBatch --> Reorg
  408. err = l2DB.DoneForging(doneForgingTxIDs, reorgBatch)
  409. assert.NoError(t, err)
  410. err = l2DB.Reorg(lastValidBatch)
  411. assert.NoError(t, err)
  412. for _, id := range reorgedTxIDs {
  413. tx, err := l2DB.GetTxAPI(id)
  414. assert.NoError(t, err)
  415. assert.Nil(t, tx.BatchNum)
  416. assert.Equal(t, common.PoolL2TxStatePending, tx.State)
  417. }
  418. for _, id := range nonReorgedTxIDs {
  419. fetchedTx, err := l2DB.GetTxAPI(id)
  420. assert.NoError(t, err)
  421. assert.Equal(t, lastValidBatch, *fetchedTx.BatchNum)
  422. }
  423. }
  424. // TestReorg: second part of test with reorg
  425. // With invalidated transactions in reorgBatch
  426. // And forged transactions BEFORE reorgBatch
  427. func TestReorg2(t *testing.T) {
  428. // Generate txs
  429. const lastValidBatch common.BatchNum = 20
  430. const reorgBatch common.BatchNum = lastValidBatch + 1
  431. err := prepareHistoryDB(historyDB)
  432. if err != nil {
  433. log.Error("Error prepare historyDB", err)
  434. }
  435. poolL2Txs, err := generatePoolL2Txs()
  436. assert.NoError(t, err)
  437. reorgedTxIDs := []common.TxID{}
  438. nonReorgedTxIDs := []common.TxID{}
  439. var startForgingTxIDs []common.TxID
  440. var invalidTxIDs []common.TxID
  441. var allTxRandomize []common.TxID
  442. randomizer := 0
  443. // Add txs to DB
  444. for i := range poolL2Txs {
  445. err := l2DB.AddTxTest(&poolL2Txs[i])
  446. assert.NoError(t, err)
  447. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  448. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  449. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  450. } else if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%3 == 0 {
  451. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  452. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  453. }
  454. randomizer++
  455. }
  456. // Start forging txs
  457. err = l2DB.StartForging(startForgingTxIDs, lastValidBatch)
  458. assert.NoError(t, err)
  459. var doneForgingTxIDs []common.TxID
  460. randomizer = 0
  461. for _, txID := range allTxRandomize {
  462. invalidTx := false
  463. for i := range invalidTxIDs {
  464. if invalidTxIDs[i] == txID {
  465. invalidTx = true
  466. reorgedTxIDs = append(reorgedTxIDs, txID)
  467. }
  468. }
  469. if !invalidTx {
  470. if randomizer%2 == 0 {
  471. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  472. }
  473. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  474. randomizer++
  475. }
  476. }
  477. // Done forging txs BEFORE reorgBatch --> nonReorg
  478. err = l2DB.DoneForging(doneForgingTxIDs, lastValidBatch)
  479. assert.NoError(t, err)
  480. // Invalidate txs in reorgBatch --> Reorg
  481. err = l2DB.InvalidateTxs(invalidTxIDs, reorgBatch)
  482. assert.NoError(t, err)
  483. err = l2DB.Reorg(lastValidBatch)
  484. assert.NoError(t, err)
  485. for _, id := range reorgedTxIDs {
  486. tx, err := l2DB.GetTxAPI(id)
  487. assert.NoError(t, err)
  488. assert.Nil(t, tx.BatchNum)
  489. assert.Equal(t, common.PoolL2TxStatePending, tx.State)
  490. }
  491. for _, id := range nonReorgedTxIDs {
  492. fetchedTx, err := l2DB.GetTxAPI(id)
  493. assert.NoError(t, err)
  494. assert.Equal(t, lastValidBatch, *fetchedTx.BatchNum)
  495. }
  496. }
  497. func TestPurge(t *testing.T) {
  498. // Generate txs
  499. err := prepareHistoryDB(historyDB)
  500. if err != nil {
  501. log.Error("Error prepare historyDB", err)
  502. }
  503. // generatePoolL2Txs
  504. generateTx := int(l2DB.maxTxs/8 + 1)
  505. var poolL2Tx []common.PoolL2Tx
  506. for i := 0; i < generateTx; i++ {
  507. poolL2TxAux, err := generatePoolL2Txs()
  508. assert.NoError(t, err)
  509. poolL2Tx = append(poolL2Tx, poolL2TxAux...)
  510. }
  511. afterTTLIDs := []common.TxID{}
  512. keepedIDs := []common.TxID{}
  513. var deletedIDs []common.TxID
  514. var invalidTxIDs []common.TxID
  515. var doneForgingTxIDs []common.TxID
  516. const toDeleteBatchNum common.BatchNum = 30
  517. safeBatchNum := toDeleteBatchNum + l2DB.safetyPeriod + 1
  518. // Add txs to the DB
  519. for i := 0; i < len(poolL2Tx); i++ {
  520. tx := poolL2Tx[i]
  521. if i%2 == 0 { // keep tx
  522. keepedIDs = append(keepedIDs, tx.TxID)
  523. } else { // delete after safety period
  524. if i%3 == 0 {
  525. doneForgingTxIDs = append(doneForgingTxIDs, tx.TxID)
  526. } else if i%5 == 0 {
  527. invalidTxIDs = append(invalidTxIDs, tx.TxID)
  528. } else {
  529. afterTTLIDs = append(afterTTLIDs, tx.TxID)
  530. }
  531. deletedIDs = append(deletedIDs, poolL2Tx[i].TxID)
  532. }
  533. err := l2DB.AddTxTest(&tx)
  534. assert.NoError(t, err)
  535. }
  536. // Set batchNum keeped txs
  537. for i := range keepedIDs {
  538. _, err = l2DB.db.Exec(
  539. "UPDATE tx_pool SET batch_num = $1 WHERE tx_id = $2;",
  540. safeBatchNum, keepedIDs[i],
  541. )
  542. assert.NoError(t, err)
  543. }
  544. // Start forging txs and set batchNum
  545. err = l2DB.StartForging(doneForgingTxIDs, toDeleteBatchNum)
  546. assert.NoError(t, err)
  547. // Done forging txs and set batchNum
  548. err = l2DB.DoneForging(doneForgingTxIDs, toDeleteBatchNum)
  549. assert.NoError(t, err)
  550. // Invalidate txs and set batchNum
  551. err = l2DB.InvalidateTxs(invalidTxIDs, toDeleteBatchNum)
  552. assert.NoError(t, err)
  553. // Update timestamp of afterTTL txs
  554. deleteTimestamp := time.Unix(time.Now().UTC().Unix()-int64(l2DB.ttl.Seconds()+float64(4*time.Second)), 0)
  555. for _, id := range afterTTLIDs {
  556. // Set timestamp
  557. _, err = l2DB.db.Exec(
  558. "UPDATE tx_pool SET timestamp = $1, state = $2 WHERE tx_id = $3;",
  559. deleteTimestamp, common.PoolL2TxStatePending, id,
  560. )
  561. assert.NoError(t, err)
  562. }
  563. // Purge txs
  564. err = l2DB.Purge(safeBatchNum)
  565. assert.NoError(t, err)
  566. // Check results
  567. for _, id := range deletedIDs {
  568. _, err := l2DB.GetTx(id)
  569. assert.Error(t, err)
  570. }
  571. for _, id := range keepedIDs {
  572. _, err := l2DB.GetTx(id)
  573. assert.NoError(t, err)
  574. }
  575. }
  576. func TestAuth(t *testing.T) {
  577. test.WipeDB(l2DB.DB())
  578. const nAuths = 5
  579. chainID := uint16(0)
  580. hermezContractAddr := ethCommon.HexToAddress("0xc344E203a046Da13b0B4467EB7B3629D0C99F6E6")
  581. // Generate authorizations
  582. auths := test.GenAuths(nAuths, chainID, hermezContractAddr)
  583. for i := 0; i < len(auths); i++ {
  584. // Add to the DB
  585. err := l2DB.AddAccountCreationAuth(auths[i])
  586. assert.NoError(t, err)
  587. // Fetch from DB
  588. auth, err := l2DB.GetAccountCreationAuth(auths[i].EthAddr)
  589. assert.NoError(t, err)
  590. // Check fetched vs generated
  591. assert.Equal(t, auths[i].EthAddr, auth.EthAddr)
  592. assert.Equal(t, auths[i].BJJ, auth.BJJ)
  593. assert.Equal(t, auths[i].Signature, auth.Signature)
  594. assert.Equal(t, auths[i].Timestamp.Unix(), auths[i].Timestamp.Unix())
  595. nameZone, offset := auths[i].Timestamp.Zone()
  596. assert.Equal(t, "UTC", nameZone)
  597. assert.Equal(t, 0, offset)
  598. }
  599. }
  600. func TestAddGet(t *testing.T) {
  601. err := prepareHistoryDB(historyDB)
  602. if err != nil {
  603. log.Error("Error prepare historyDB", err)
  604. }
  605. poolL2Txs, err := generatePoolL2Txs()
  606. assert.NoError(t, err)
  607. // We will work with only 3 txs
  608. require.GreaterOrEqual(t, len(poolL2Txs), 3)
  609. txs := poolL2Txs[:3]
  610. // NOTE: By changing the tx fields, the signature will no longer be
  611. // valid, but we are not checking the signautre here so it's OK.
  612. // 0. Has ToIdx >= 256 && ToEthAddr == 0 && ToBJJ == 0
  613. require.GreaterOrEqual(t, int(txs[0].ToIdx), 256)
  614. txs[0].ToEthAddr = ethCommon.Address{}
  615. txs[0].ToBJJ = babyjub.PublicKeyComp{}
  616. // 1. Has ToIdx >= 256 && ToEthAddr != 0 && ToBJJ != 0
  617. require.GreaterOrEqual(t, int(txs[1].ToIdx), 256)
  618. require.NotEqual(t, txs[1].ToEthAddr, ethCommon.Address{})
  619. require.NotEqual(t, txs[1].ToBJJ, babyjub.PublicKeyComp{})
  620. // 2. Has ToIdx == 0 && ToEthAddr != 0 && ToBJJ != 0
  621. txs[2].ToIdx = 0
  622. require.NotEqual(t, txs[2].ToEthAddr, ethCommon.Address{})
  623. require.NotEqual(t, txs[2].ToBJJ, babyjub.PublicKeyComp{})
  624. for i := 0; i < len(txs); i++ {
  625. require.NoError(t, txs[i].SetID())
  626. require.NoError(t, l2DB.AddTxTest(&txs[i]))
  627. }
  628. // Verify that the inserts haven't altered any field (specially
  629. // ToEthAddr and ToBJJ)
  630. for i := 0; i < len(txs); i++ {
  631. dbTx, err := l2DB.GetTx(txs[i].TxID)
  632. require.NoError(t, err)
  633. // Ignore Timestamp, AbsoluteFee, AbsoluteFeeUpdate
  634. txs[i].Timestamp = dbTx.Timestamp
  635. txs[i].AbsoluteFee = dbTx.AbsoluteFee
  636. txs[i].AbsoluteFeeUpdate = dbTx.AbsoluteFeeUpdate
  637. assert.Equal(t, txs[i], *dbTx)
  638. }
  639. }