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.

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