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.

181 lines
5.0 KiB

  1. package historydb
  2. import (
  3. "fmt"
  4. "github.com/gobuffalo/packr/v2"
  5. "github.com/hermeznetwork/hermez-node/common"
  6. "github.com/hermeznetwork/hermez-node/db"
  7. "github.com/jmoiron/sqlx"
  8. _ "github.com/lib/pq" // driver for postgres DB
  9. migrate "github.com/rubenv/sql-migrate"
  10. "github.com/russross/meddler"
  11. )
  12. // HistoryDB persist the historic of the rollup
  13. type HistoryDB struct {
  14. db *sqlx.DB
  15. }
  16. // NewHistoryDB initialize the DB
  17. func NewHistoryDB(port int, host, user, password, dbname string) (*HistoryDB, error) {
  18. // Connect to DB
  19. psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
  20. hdb, err := sqlx.Connect("postgres", psqlconn)
  21. if err != nil {
  22. return nil, err
  23. }
  24. // Init meddler
  25. db.InitMeddler()
  26. meddler.Default = meddler.PostgreSQL
  27. // Run DB migrations
  28. migrations := &migrate.PackrMigrationSource{
  29. Box: packr.New("history-migrations", "./migrations"),
  30. }
  31. if _, err := migrate.Exec(hdb.DB, "postgres", migrations, migrate.Up); err != nil {
  32. return nil, err
  33. }
  34. return &HistoryDB{hdb}, nil
  35. }
  36. // AddBlock insert a block into the DB
  37. func (hdb *HistoryDB) AddBlock(block *common.Block) error {
  38. return meddler.Insert(hdb.db, "block", block)
  39. }
  40. // GetBlock retrieve a block from the DB, given a block number
  41. func (hdb *HistoryDB) GetBlock(blockNum uint64) (*common.Block, error) {
  42. block := &common.Block{}
  43. err := meddler.QueryRow(
  44. hdb.db, block,
  45. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  46. )
  47. return block, err
  48. }
  49. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  50. func (hdb *HistoryDB) GetBlocks(from, to uint64) ([]*common.Block, error) {
  51. var blocks []*common.Block
  52. err := meddler.QueryAll(
  53. hdb.db, &blocks,
  54. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2",
  55. from, to,
  56. )
  57. return blocks, err
  58. }
  59. // GetLastBlock retrieve the block with the highest block number from the DB
  60. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  61. block := &common.Block{}
  62. err := meddler.QueryRow(
  63. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  64. )
  65. return block, err
  66. }
  67. // addBatches insert Bids into the DB
  68. func (hdb *HistoryDB) addBatches(batches []common.Batch) error {
  69. return db.BulkInsert(
  70. hdb.db,
  71. `INSERT INTO batch (
  72. batch_num,
  73. eth_block_num,
  74. forger_addr,
  75. fees_collected,
  76. state_root,
  77. num_accounts,
  78. exit_root,
  79. forge_l1_txs_num,
  80. slot_num
  81. ) VALUES %s;`,
  82. batches[:],
  83. )
  84. }
  85. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  86. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]*common.Batch, error) {
  87. var batches []*common.Batch
  88. err := meddler.QueryAll(
  89. hdb.db, &batches,
  90. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2",
  91. from, to,
  92. )
  93. return batches, err
  94. }
  95. // GetLastBatchNum returns the BatchNum of the latest forged batch
  96. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  97. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  98. var batchNum common.BatchNum
  99. return batchNum, row.Scan(&batchNum)
  100. }
  101. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB
  102. func (hdb *HistoryDB) GetLastL1TxsNum() (uint32, error) {
  103. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  104. var lastL1TxsNum uint32
  105. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  106. }
  107. // Reorg deletes all the information that was added into the DB after the lastValidBlock
  108. func (hdb *HistoryDB) Reorg(lastValidBlock uint64) error {
  109. _, err := hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  110. return err
  111. }
  112. // SyncRollup stores all the data that can be changed / added on a block in the Rollup SC
  113. func (hdb *HistoryDB) SyncRollup(
  114. blockNum uint64,
  115. l1txs []common.L1Tx,
  116. l2txs []common.L2Tx,
  117. registeredAccounts []common.Account,
  118. exitTree common.ExitInfo,
  119. withdrawals common.ExitInfo,
  120. registeredTokens []common.Token,
  121. batches []common.Batch,
  122. vars *common.RollupVars,
  123. ) error {
  124. // TODO: make all in a single DB commit
  125. if err := hdb.addBatches(batches); err != nil {
  126. return err
  127. }
  128. return nil
  129. }
  130. // SyncPoD stores all the data that can be changed / added on a block in the PoD SC
  131. func (hdb *HistoryDB) SyncPoD(
  132. blockNum uint64,
  133. bids []common.Bid,
  134. coordinators []common.Coordinator,
  135. vars *common.AuctionVars,
  136. ) error {
  137. return nil
  138. }
  139. // addBids insert Bids into the DB
  140. func (hdb *HistoryDB) addBids(bids []common.Bid) error {
  141. // TODO: check the coordinator info
  142. return db.BulkInsert(
  143. hdb.db,
  144. "INSERT INTO bid (slot_num, forger_addr, bid_value, eth_block_num) VALUES %s",
  145. bids[:],
  146. )
  147. }
  148. // GetBidsBySlot return the bids for a specific slot
  149. func (hdb *HistoryDB) GetBidsBySlot(slotNum common.SlotNum) ([]*common.Bid, error) {
  150. var bids []*common.Bid
  151. err := meddler.QueryAll(
  152. hdb.db, &bids,
  153. "SELECT * FROM bid WHERE $1 = slot_num;",
  154. slotNum,
  155. )
  156. return bids, err
  157. }
  158. // Close frees the resources used by HistoryDB
  159. func (hdb *HistoryDB) Close() error {
  160. return hdb.db.Close()
  161. }