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.

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