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.

675 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. PoolTransfer(2) B-A: 5 (2)
  126. PoolExit(1) A: 5 (2)
  127. PoolExit(2) B: 3 (1)
  128. `
  129. poolL2Txs, err := tc.GeneratePoolL2Txs(setPool)
  130. if err != nil {
  131. return nil, tracerr.Wrap(err)
  132. }
  133. return poolL2Txs, nil
  134. }
  135. func TestAddTxTest(t *testing.T) {
  136. err := prepareHistoryDB(historyDB)
  137. if err != nil {
  138. log.Error("Error prepare historyDB", err)
  139. }
  140. poolL2Txs, err := generatePoolL2Txs()
  141. assert.NoError(t, err)
  142. for i := range poolL2Txs {
  143. err := l2DB.AddTxTest(&poolL2Txs[i])
  144. assert.NoError(t, err)
  145. fetchedTx, err := l2DB.GetTx(poolL2Txs[i].TxID)
  146. assert.NoError(t, err)
  147. assertTx(t, &poolL2Txs[i], fetchedTx)
  148. nameZone, offset := fetchedTx.Timestamp.Zone()
  149. assert.Equal(t, "UTC", nameZone)
  150. assert.Equal(t, 0, offset)
  151. }
  152. }
  153. func assertTx(t *testing.T, expected, actual *common.PoolL2Tx) {
  154. // Check that timestamp has been set within the last 3 seconds
  155. assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
  156. assert.GreaterOrEqual(t, time.Now().UTC().Unix(), actual.Timestamp.Unix())
  157. expected.Timestamp = actual.Timestamp
  158. // Check absolute fee
  159. // find token
  160. token := tokens[expected.TokenID]
  161. // If the token has value in USD setted
  162. if token.USDUpdate != nil {
  163. assert.Less(t, token.USDUpdate.Unix()-3, actual.AbsoluteFeeUpdate.Unix())
  164. expected.AbsoluteFeeUpdate = actual.AbsoluteFeeUpdate
  165. // Set expected fee
  166. f := new(big.Float).SetInt(expected.Amount)
  167. amountF, _ := f.Float64()
  168. expected.AbsoluteFee = *token.USD * amountF * expected.Fee.Percentage()
  169. test.AssertUSD(t, &expected.AbsoluteFee, &actual.AbsoluteFee)
  170. }
  171. assert.Equal(t, expected, actual)
  172. }
  173. // NO UPDATE: benchmarks will be done after impl is finished
  174. // func BenchmarkAddTxTest(b *testing.B) {
  175. // const nInserts = 20
  176. // test.WipeDB(l2DB.DB())
  177. // txs := test.GenPoolTxs(nInserts, tokens)
  178. // now := time.Now()
  179. // for _, tx := range txs {
  180. // _ = l2DB.AddTxTest(tx)
  181. // }
  182. // elapsedTime := time.Since(now)
  183. // log.Info("Time to insert 2048 txs:", elapsedTime)
  184. // }
  185. func TestGetPending(t *testing.T) {
  186. err := prepareHistoryDB(historyDB)
  187. if err != nil {
  188. log.Error("Error prepare historyDB", err)
  189. }
  190. poolL2Txs, err := generatePoolL2Txs()
  191. assert.NoError(t, err)
  192. var pendingTxs []*common.PoolL2Tx
  193. for i := range poolL2Txs {
  194. err := l2DB.AddTxTest(&poolL2Txs[i])
  195. assert.NoError(t, err)
  196. pendingTxs = append(pendingTxs, &poolL2Txs[i])
  197. }
  198. fetchedTxs, err := l2DB.GetPendingTxs()
  199. assert.NoError(t, err)
  200. assert.Equal(t, len(pendingTxs), len(fetchedTxs))
  201. for i := range fetchedTxs {
  202. assertTx(t, pendingTxs[i], &fetchedTxs[i])
  203. }
  204. }
  205. func TestStartForging(t *testing.T) {
  206. // Generate txs
  207. var fakeBatchNum common.BatchNum = 33
  208. err := prepareHistoryDB(historyDB)
  209. if err != nil {
  210. log.Error("Error prepare historyDB", err)
  211. }
  212. poolL2Txs, err := generatePoolL2Txs()
  213. assert.NoError(t, err)
  214. var startForgingTxIDs []common.TxID
  215. randomizer := 0
  216. // Add txs to DB
  217. for i := range poolL2Txs {
  218. err := l2DB.AddTxTest(&poolL2Txs[i])
  219. assert.NoError(t, err)
  220. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  221. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  222. }
  223. randomizer++
  224. }
  225. // Start forging txs
  226. err = l2DB.StartForging(startForgingTxIDs, fakeBatchNum)
  227. assert.NoError(t, err)
  228. // Fetch txs and check that they've been updated correctly
  229. for _, id := range startForgingTxIDs {
  230. fetchedTx, err := l2DB.GetTxAPI(id)
  231. assert.NoError(t, err)
  232. assert.Equal(t, common.PoolL2TxStateForging, fetchedTx.State)
  233. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  234. }
  235. }
  236. func TestDoneForging(t *testing.T) {
  237. // Generate txs
  238. var fakeBatchNum common.BatchNum = 33
  239. err := prepareHistoryDB(historyDB)
  240. if err != nil {
  241. log.Error("Error prepare historyDB", err)
  242. }
  243. poolL2Txs, err := generatePoolL2Txs()
  244. assert.NoError(t, err)
  245. var startForgingTxIDs []common.TxID
  246. randomizer := 0
  247. // Add txs to DB
  248. for i := range poolL2Txs {
  249. err := l2DB.AddTxTest(&poolL2Txs[i])
  250. assert.NoError(t, err)
  251. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  252. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  253. }
  254. randomizer++
  255. }
  256. // Start forging txs
  257. err = l2DB.StartForging(startForgingTxIDs, fakeBatchNum)
  258. assert.NoError(t, err)
  259. var doneForgingTxIDs []common.TxID
  260. randomizer = 0
  261. for _, txID := range startForgingTxIDs {
  262. if randomizer%2 == 0 {
  263. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  264. }
  265. randomizer++
  266. }
  267. // Done forging txs
  268. err = l2DB.DoneForging(doneForgingTxIDs, fakeBatchNum)
  269. assert.NoError(t, err)
  270. // Fetch txs and check that they've been updated correctly
  271. for _, id := range doneForgingTxIDs {
  272. fetchedTx, err := l2DB.GetTxAPI(id)
  273. assert.NoError(t, err)
  274. assert.Equal(t, common.PoolL2TxStateForged, fetchedTx.State)
  275. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  276. }
  277. }
  278. func TestInvalidate(t *testing.T) {
  279. // Generate txs
  280. var fakeBatchNum common.BatchNum = 33
  281. err := prepareHistoryDB(historyDB)
  282. if err != nil {
  283. log.Error("Error prepare historyDB", err)
  284. }
  285. poolL2Txs, err := generatePoolL2Txs()
  286. assert.NoError(t, err)
  287. var invalidTxIDs []common.TxID
  288. randomizer := 0
  289. // Add txs to DB
  290. for i := range poolL2Txs {
  291. err := l2DB.AddTxTest(&poolL2Txs[i])
  292. assert.NoError(t, err)
  293. if poolL2Txs[i].State != common.PoolL2TxStateInvalid && randomizer%2 == 0 {
  294. randomizer++
  295. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  296. }
  297. }
  298. // Invalidate txs
  299. err = l2DB.InvalidateTxs(invalidTxIDs, fakeBatchNum)
  300. assert.NoError(t, err)
  301. // Fetch txs and check that they've been updated correctly
  302. for _, id := range invalidTxIDs {
  303. fetchedTx, err := l2DB.GetTxAPI(id)
  304. assert.NoError(t, err)
  305. assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
  306. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  307. }
  308. }
  309. func TestInvalidateOldNonces(t *testing.T) {
  310. // Generate txs
  311. var fakeBatchNum common.BatchNum = 33
  312. err := prepareHistoryDB(historyDB)
  313. if err != nil {
  314. log.Error("Error prepare historyDB", err)
  315. }
  316. poolL2Txs, err := generatePoolL2Txs()
  317. assert.NoError(t, err)
  318. // Update Accounts currentNonce
  319. var updateAccounts []common.IdxNonce
  320. var currentNonce = common.Nonce(1)
  321. for i := range accs {
  322. updateAccounts = append(updateAccounts, common.IdxNonce{
  323. Idx: accs[i].Idx,
  324. Nonce: common.Nonce(currentNonce),
  325. })
  326. }
  327. // Add txs to DB
  328. var invalidTxIDs []common.TxID
  329. for i := range poolL2Txs {
  330. if poolL2Txs[i].Nonce < currentNonce {
  331. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  332. }
  333. err := l2DB.AddTxTest(&poolL2Txs[i])
  334. assert.NoError(t, err)
  335. }
  336. // sanity check
  337. require.Greater(t, len(invalidTxIDs), 0)
  338. err = l2DB.InvalidateOldNonces(updateAccounts, fakeBatchNum)
  339. assert.NoError(t, err)
  340. // Fetch txs and check that they've been updated correctly
  341. for _, id := range invalidTxIDs {
  342. fetchedTx, err := l2DB.GetTxAPI(id)
  343. require.NoError(t, err)
  344. assert.Equal(t, common.PoolL2TxStateInvalid, fetchedTx.State)
  345. assert.Equal(t, &fakeBatchNum, fetchedTx.BatchNum)
  346. }
  347. }
  348. // TestReorg: first part of the test with reorg
  349. // With invalidated transactions BEFORE reorgBatch
  350. // And forged transactions in reorgBatch
  351. func TestReorg(t *testing.T) {
  352. // Generate txs
  353. const lastValidBatch common.BatchNum = 20
  354. const reorgBatch common.BatchNum = lastValidBatch + 1
  355. err := prepareHistoryDB(historyDB)
  356. if err != nil {
  357. log.Error("Error prepare historyDB", err)
  358. }
  359. poolL2Txs, err := generatePoolL2Txs()
  360. assert.NoError(t, err)
  361. reorgedTxIDs := []common.TxID{}
  362. nonReorgedTxIDs := []common.TxID{}
  363. var startForgingTxIDs []common.TxID
  364. var invalidTxIDs []common.TxID
  365. var allTxRandomize []common.TxID
  366. randomizer := 0
  367. // Add txs to DB
  368. for i := range poolL2Txs {
  369. err := l2DB.AddTxTest(&poolL2Txs[i])
  370. assert.NoError(t, err)
  371. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  372. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  373. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  374. } else if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%3 == 0 {
  375. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  376. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  377. }
  378. randomizer++
  379. }
  380. // Start forging txs
  381. err = l2DB.StartForging(startForgingTxIDs, lastValidBatch)
  382. assert.NoError(t, err)
  383. var doneForgingTxIDs []common.TxID
  384. randomizer = 0
  385. for _, txID := range allTxRandomize {
  386. invalidTx := false
  387. for i := range invalidTxIDs {
  388. if invalidTxIDs[i] == txID {
  389. invalidTx = true
  390. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  391. }
  392. }
  393. if !invalidTx {
  394. if randomizer%2 == 0 {
  395. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  396. reorgedTxIDs = append(reorgedTxIDs, txID)
  397. } else {
  398. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  399. }
  400. randomizer++
  401. }
  402. }
  403. // Invalidate txs BEFORE reorgBatch --> nonReorg
  404. err = l2DB.InvalidateTxs(invalidTxIDs, lastValidBatch)
  405. assert.NoError(t, err)
  406. // Done forging txs in reorgBatch --> Reorg
  407. err = l2DB.DoneForging(doneForgingTxIDs, reorgBatch)
  408. assert.NoError(t, err)
  409. err = l2DB.Reorg(lastValidBatch)
  410. assert.NoError(t, err)
  411. for _, id := range reorgedTxIDs {
  412. tx, err := l2DB.GetTxAPI(id)
  413. assert.NoError(t, err)
  414. assert.Nil(t, tx.BatchNum)
  415. assert.Equal(t, common.PoolL2TxStatePending, tx.State)
  416. }
  417. for _, id := range nonReorgedTxIDs {
  418. fetchedTx, err := l2DB.GetTxAPI(id)
  419. assert.NoError(t, err)
  420. assert.Equal(t, lastValidBatch, *fetchedTx.BatchNum)
  421. }
  422. }
  423. // TestReorg: second part of test with reorg
  424. // With invalidated transactions in reorgBatch
  425. // And forged transactions BEFORE reorgBatch
  426. func TestReorg2(t *testing.T) {
  427. // Generate txs
  428. const lastValidBatch common.BatchNum = 20
  429. const reorgBatch common.BatchNum = lastValidBatch + 1
  430. err := prepareHistoryDB(historyDB)
  431. if err != nil {
  432. log.Error("Error prepare historyDB", err)
  433. }
  434. poolL2Txs, err := generatePoolL2Txs()
  435. assert.NoError(t, err)
  436. reorgedTxIDs := []common.TxID{}
  437. nonReorgedTxIDs := []common.TxID{}
  438. var startForgingTxIDs []common.TxID
  439. var invalidTxIDs []common.TxID
  440. var allTxRandomize []common.TxID
  441. randomizer := 0
  442. // Add txs to DB
  443. for i := range poolL2Txs {
  444. err := l2DB.AddTxTest(&poolL2Txs[i])
  445. assert.NoError(t, err)
  446. if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%2 == 0 {
  447. startForgingTxIDs = append(startForgingTxIDs, poolL2Txs[i].TxID)
  448. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  449. } else if poolL2Txs[i].State == common.PoolL2TxStatePending && randomizer%3 == 0 {
  450. invalidTxIDs = append(invalidTxIDs, poolL2Txs[i].TxID)
  451. allTxRandomize = append(allTxRandomize, poolL2Txs[i].TxID)
  452. }
  453. randomizer++
  454. }
  455. // Start forging txs
  456. err = l2DB.StartForging(startForgingTxIDs, lastValidBatch)
  457. assert.NoError(t, err)
  458. var doneForgingTxIDs []common.TxID
  459. randomizer = 0
  460. for _, txID := range allTxRandomize {
  461. invalidTx := false
  462. for i := range invalidTxIDs {
  463. if invalidTxIDs[i] == txID {
  464. invalidTx = true
  465. reorgedTxIDs = append(reorgedTxIDs, txID)
  466. }
  467. }
  468. if !invalidTx {
  469. if randomizer%2 == 0 {
  470. doneForgingTxIDs = append(doneForgingTxIDs, txID)
  471. }
  472. nonReorgedTxIDs = append(nonReorgedTxIDs, txID)
  473. randomizer++
  474. }
  475. }
  476. // Done forging txs BEFORE reorgBatch --> nonReorg
  477. err = l2DB.DoneForging(doneForgingTxIDs, lastValidBatch)
  478. assert.NoError(t, err)
  479. // Invalidate txs in reorgBatch --> Reorg
  480. err = l2DB.InvalidateTxs(invalidTxIDs, reorgBatch)
  481. assert.NoError(t, err)
  482. err = l2DB.Reorg(lastValidBatch)
  483. assert.NoError(t, err)
  484. for _, id := range reorgedTxIDs {
  485. tx, err := l2DB.GetTxAPI(id)
  486. assert.NoError(t, err)
  487. assert.Nil(t, tx.BatchNum)
  488. assert.Equal(t, common.PoolL2TxStatePending, tx.State)
  489. }
  490. for _, id := range nonReorgedTxIDs {
  491. fetchedTx, err := l2DB.GetTxAPI(id)
  492. assert.NoError(t, err)
  493. assert.Equal(t, lastValidBatch, *fetchedTx.BatchNum)
  494. }
  495. }
  496. func TestPurge(t *testing.T) {
  497. // Generate txs
  498. err := prepareHistoryDB(historyDB)
  499. if err != nil {
  500. log.Error("Error prepare historyDB", err)
  501. }
  502. // generatePoolL2Txs
  503. generateTx := int(l2DB.maxTxs/8 + 1)
  504. var poolL2Tx []common.PoolL2Tx
  505. for i := 0; i < generateTx; i++ {
  506. poolL2TxAux, err := generatePoolL2Txs()
  507. assert.NoError(t, err)
  508. poolL2Tx = append(poolL2Tx, poolL2TxAux...)
  509. }
  510. afterTTLIDs := []common.TxID{}
  511. keepedIDs := []common.TxID{}
  512. var deletedIDs []common.TxID
  513. var invalidTxIDs []common.TxID
  514. var doneForgingTxIDs []common.TxID
  515. const toDeleteBatchNum common.BatchNum = 30
  516. safeBatchNum := toDeleteBatchNum + l2DB.safetyPeriod + 1
  517. // Add txs to the DB
  518. for i := 0; i < len(poolL2Tx); i++ {
  519. tx := poolL2Tx[i]
  520. if i%2 == 0 { // keep tx
  521. keepedIDs = append(keepedIDs, tx.TxID)
  522. } else { // delete after safety period
  523. if i%3 == 0 {
  524. doneForgingTxIDs = append(doneForgingTxIDs, tx.TxID)
  525. } else if i%5 == 0 {
  526. invalidTxIDs = append(invalidTxIDs, tx.TxID)
  527. } else {
  528. afterTTLIDs = append(afterTTLIDs, tx.TxID)
  529. }
  530. deletedIDs = append(deletedIDs, poolL2Tx[i].TxID)
  531. }
  532. err := l2DB.AddTxTest(&tx)
  533. assert.NoError(t, err)
  534. }
  535. // Set batchNum keeped txs
  536. for i := range keepedIDs {
  537. _, err = l2DB.db.Exec(
  538. "UPDATE tx_pool SET batch_num = $1 WHERE tx_id = $2;",
  539. safeBatchNum, keepedIDs[i],
  540. )
  541. assert.NoError(t, err)
  542. }
  543. // Start forging txs and set batchNum
  544. err = l2DB.StartForging(doneForgingTxIDs, toDeleteBatchNum)
  545. assert.NoError(t, err)
  546. // Done forging txs and set batchNum
  547. err = l2DB.DoneForging(doneForgingTxIDs, toDeleteBatchNum)
  548. assert.NoError(t, err)
  549. // Invalidate txs and set batchNum
  550. err = l2DB.InvalidateTxs(invalidTxIDs, toDeleteBatchNum)
  551. assert.NoError(t, err)
  552. // Update timestamp of afterTTL txs
  553. deleteTimestamp := time.Unix(time.Now().UTC().Unix()-int64(l2DB.ttl.Seconds()+float64(4*time.Second)), 0)
  554. for _, id := range afterTTLIDs {
  555. // Set timestamp
  556. _, err = l2DB.db.Exec(
  557. "UPDATE tx_pool SET timestamp = $1, state = $2 WHERE tx_id = $3;",
  558. deleteTimestamp, common.PoolL2TxStatePending, id,
  559. )
  560. assert.NoError(t, err)
  561. }
  562. // Purge txs
  563. err = l2DB.Purge(safeBatchNum)
  564. assert.NoError(t, err)
  565. // Check results
  566. for _, id := range deletedIDs {
  567. _, err := l2DB.GetTx(id)
  568. assert.Error(t, err)
  569. }
  570. for _, id := range keepedIDs {
  571. _, err := l2DB.GetTx(id)
  572. assert.NoError(t, err)
  573. }
  574. }
  575. func TestAuth(t *testing.T) {
  576. test.WipeDB(l2DB.DB())
  577. const nAuths = 5
  578. chainID := uint16(0)
  579. hermezContractAddr := ethCommon.HexToAddress("0xc344E203a046Da13b0B4467EB7B3629D0C99F6E6")
  580. // Generate authorizations
  581. auths := test.GenAuths(nAuths, chainID, hermezContractAddr)
  582. for i := 0; i < len(auths); i++ {
  583. // Add to the DB
  584. err := l2DB.AddAccountCreationAuth(auths[i])
  585. assert.NoError(t, err)
  586. // Fetch from DB
  587. auth, err := l2DB.GetAccountCreationAuth(auths[i].EthAddr)
  588. assert.NoError(t, err)
  589. // Check fetched vs generated
  590. assert.Equal(t, auths[i].EthAddr, auth.EthAddr)
  591. assert.Equal(t, auths[i].BJJ, auth.BJJ)
  592. assert.Equal(t, auths[i].Signature, auth.Signature)
  593. assert.Equal(t, auths[i].Timestamp.Unix(), auths[i].Timestamp.Unix())
  594. nameZone, offset := auths[i].Timestamp.Zone()
  595. assert.Equal(t, "UTC", nameZone)
  596. assert.Equal(t, 0, offset)
  597. }
  598. }
  599. func TestAddGet(t *testing.T) {
  600. err := prepareHistoryDB(historyDB)
  601. if err != nil {
  602. log.Error("Error prepare historyDB", err)
  603. }
  604. poolL2Txs, err := generatePoolL2Txs()
  605. assert.NoError(t, err)
  606. // We will work with only 3 txs
  607. require.GreaterOrEqual(t, len(poolL2Txs), 3)
  608. txs := poolL2Txs[:3]
  609. // NOTE: By changing the tx fields, the signature will no longer be
  610. // valid, but we are not checking the signautre here so it's OK.
  611. // 0. Has ToIdx >= 256 && ToEthAddr == 0 && ToBJJ == 0
  612. require.GreaterOrEqual(t, int(txs[0].ToIdx), 256)
  613. txs[0].ToEthAddr = ethCommon.Address{}
  614. txs[0].ToBJJ = babyjub.PublicKeyComp{}
  615. // 1. Has ToIdx >= 256 && ToEthAddr != 0 && ToBJJ != 0
  616. require.GreaterOrEqual(t, int(txs[1].ToIdx), 256)
  617. require.NotEqual(t, txs[1].ToEthAddr, ethCommon.Address{})
  618. require.NotEqual(t, txs[1].ToBJJ, babyjub.PublicKeyComp{})
  619. // 2. Has ToIdx == 0 && ToEthAddr != 0 && ToBJJ != 0
  620. txs[2].ToIdx = 0
  621. require.NotEqual(t, txs[2].ToEthAddr, ethCommon.Address{})
  622. require.NotEqual(t, txs[2].ToBJJ, babyjub.PublicKeyComp{})
  623. for i := 0; i < len(txs); i++ {
  624. require.NoError(t, txs[i].SetID())
  625. require.NoError(t, l2DB.AddTxTest(&txs[i]))
  626. }
  627. // Verify that the inserts haven't altered any field (specially
  628. // ToEthAddr and ToBJJ)
  629. for i := 0; i < len(txs); i++ {
  630. dbTx, err := l2DB.GetTx(txs[i].TxID)
  631. require.NoError(t, err)
  632. // Ignore Timestamp, AbsoluteFee, AbsoluteFeeUpdate
  633. txs[i].Timestamp = dbTx.Timestamp
  634. txs[i].AbsoluteFee = dbTx.AbsoluteFee
  635. txs[i].AbsoluteFeeUpdate = dbTx.AbsoluteFeeUpdate
  636. assert.Equal(t, txs[i], *dbTx)
  637. }
  638. }