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.

183 lines
5.7 KiB

  1. package l2db
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. eth "github.com/ethereum/go-ethereum/common"
  7. "github.com/gobuffalo/packr/v2"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/hermeznetwork/hermez-node/db"
  10. "github.com/jmoiron/sqlx"
  11. //nolint:errcheck // driver for postgres DB
  12. _ "github.com/lib/pq"
  13. migrate "github.com/rubenv/sql-migrate"
  14. "github.com/russross/meddler"
  15. )
  16. // TODO(Edu): Check DB consistency while there's concurrent use from Coordinator/TxSelector & API
  17. // L2DB stores L2 txs and authorization registers received by the coordinator and keeps them until they are no longer relevant
  18. // due to them being forged or invalid after a safety period
  19. type L2DB struct {
  20. db *sqlx.DB
  21. safetyPeriod uint16
  22. ttl time.Duration
  23. maxTxs uint32
  24. }
  25. // NewL2DB creates a L2DB.
  26. // More info on how to set dbDialect and dbArgs here: http://gorm.io/docs/connecting_to_the_database.html
  27. // safetyPeriod is the amount of blockchain blocks that must be waited before deleting anything (to avoid reorg problems).
  28. // maxTxs indicates the desired maximum amount of txs stored on the L2DB.
  29. // TTL indicates the maximum amount of time that a tx can be in the L2DB
  30. // (to prevent tx that won't ever be forged to stay there, will be used if maxTxs is exceeded).
  31. // autoPurgePeriod will be used as delay between calls to Purge. If the value is 0, it will be disabled.
  32. func NewL2DB(
  33. port int, host, user, password, dbname string,
  34. safetyPeriod uint16,
  35. maxTxs uint32,
  36. TTL time.Duration,
  37. ) (*L2DB, error) {
  38. // init meddler
  39. db.InitMeddler()
  40. meddler.Default = meddler.PostgreSQL
  41. // Stablish DB connection
  42. psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
  43. db, err := sqlx.Connect("postgres", psqlconn)
  44. if err != nil {
  45. return nil, err
  46. }
  47. // Run DB migrations
  48. migrations := &migrate.PackrMigrationSource{
  49. Box: packr.New("history-migrations", "./migrations"),
  50. }
  51. if _, err := migrate.Exec(db.DB, "postgres", migrations, migrate.Up); err != nil {
  52. return nil, err
  53. }
  54. return &L2DB{
  55. db: db,
  56. safetyPeriod: safetyPeriod,
  57. ttl: TTL,
  58. maxTxs: maxTxs,
  59. }, nil
  60. }
  61. // DB returns a pointer to the L2DB.db. This method should be used only for
  62. // internal testing purposes.
  63. func (l2db *L2DB) DB() *sqlx.DB {
  64. return l2db.db
  65. }
  66. // AddTx inserts a tx into the L2DB
  67. func (l2db *L2DB) AddTx(tx *common.PoolL2Tx) error {
  68. return meddler.Insert(l2db.db, "tx_pool", tx)
  69. }
  70. // AddAccountCreationAuth inserts an account creation authorization into the DB
  71. func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
  72. // TODO: impl
  73. return nil
  74. }
  75. // GetTx return the specified Tx
  76. func (l2db *L2DB) GetTx(txID common.TxID) (*common.PoolL2Tx, error) {
  77. tx := new(common.PoolL2Tx)
  78. return tx, meddler.QueryRow(
  79. l2db.db, tx,
  80. "SELECT * FROM tx_pool WHERE tx_id = $1;",
  81. txID,
  82. )
  83. }
  84. // GetPendingTxs return all the pending txs of the L2DB
  85. func (l2db *L2DB) GetPendingTxs() ([]*common.PoolL2Tx, error) {
  86. var txs []*common.PoolL2Tx
  87. err := meddler.QueryAll(
  88. l2db.db, &txs,
  89. "SELECT * FROM tx_pool WHERE state = $1",
  90. common.PoolL2TxStatePending,
  91. )
  92. return txs, err
  93. }
  94. // GetAccountCreationAuth return the authorization to make registers of an Ethereum address
  95. func (l2db *L2DB) GetAccountCreationAuth(ethAddr eth.Address) (*common.AccountCreationAuth, error) {
  96. // TODO: impl
  97. return nil, nil
  98. }
  99. // StartForging updates the state of the transactions that will begin the forging process.
  100. // The state of the txs referenced by txIDs will be changed from Pending -> Forging
  101. func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  102. query, args, err := sqlx.In(
  103. `UPDATE tx_pool
  104. SET state = ?, batch_num = ?
  105. WHERE state = ? AND tx_id IN (?);`,
  106. string(common.PoolL2TxStateForging),
  107. strconv.Itoa(int(batchNum)),
  108. string(common.PoolL2TxStatePending),
  109. txIDs,
  110. )
  111. if err != nil {
  112. return err
  113. }
  114. query = l2db.db.Rebind(query)
  115. _, err = l2db.db.Exec(query, args...)
  116. return err
  117. }
  118. // DoneForging updates the state of the transactions that have been forged
  119. // so the state of the txs referenced by txIDs will be changed from Forging -> Forged
  120. func (l2db *L2DB) DoneForging(txIDs []common.TxID) error {
  121. // TODO: impl
  122. return nil
  123. }
  124. // InvalidateTxs updates the state of the transactions that are invalid.
  125. // The state of the txs referenced by txIDs will be changed from * -> Invalid
  126. func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID) error {
  127. return nil
  128. }
  129. // CheckNonces invalidate txs with nonces that are smaller than their respective accounts nonces.
  130. // The state of the affected txs will be changed from Pending -> Invalid
  131. func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account) error {
  132. // TODO: impl
  133. return nil
  134. }
  135. // GetTxsByAbsoluteFeeUpdate return the txs that have an AbsoluteFee updated before olderThan
  136. func (l2db *L2DB) GetTxsByAbsoluteFeeUpdate(olderThan time.Time) ([]*common.PoolL2Tx, error) {
  137. // TODO: impl
  138. return nil, nil
  139. }
  140. // UpdateTxs update existing txs from the pool (TxID must exist)
  141. func (l2db *L2DB) UpdateTxs(txs []*common.PoolL2Tx) error {
  142. // TODO: impl
  143. return nil
  144. }
  145. // Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
  146. // The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
  147. func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
  148. // TODO: impl
  149. return nil
  150. }
  151. // Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
  152. // it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded
  153. func (l2db *L2DB) Purge() error {
  154. // TODO: impl
  155. return nil
  156. }
  157. // Close frees the resources used by the L2DB
  158. func (l2db *L2DB) Close() error {
  159. return l2db.db.Close()
  160. }