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