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.

301 lines
9.5 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
  1. package l2db
  2. import (
  3. "math/big"
  4. "time"
  5. ethCommon "github.com/ethereum/go-ethereum/common"
  6. "github.com/hermeznetwork/hermez-node/common"
  7. "github.com/hermeznetwork/hermez-node/db"
  8. "github.com/hermeznetwork/hermez-node/log"
  9. "github.com/jmoiron/sqlx"
  10. //nolint:errcheck // driver for postgres DB
  11. _ "github.com/lib/pq"
  12. "github.com/russross/meddler"
  13. )
  14. // TODO(Edu): Check DB consistency while there's concurrent use from Coordinator/TxSelector & API
  15. // L2DB stores L2 txs and authorization registers received by the coordinator and keeps them until they are no longer relevant
  16. // due to them being forged or invalid after a safety period
  17. type L2DB struct {
  18. db *sqlx.DB
  19. safetyPeriod common.BatchNum
  20. ttl time.Duration
  21. maxTxs uint32
  22. }
  23. // NewL2DB creates a L2DB.
  24. // To create it, it's needed db connection, safety period expressed in batches,
  25. // maxTxs that the DB should have and TTL (time to live) for pending txs.
  26. func NewL2DB(db *sqlx.DB, safetyPeriod common.BatchNum, maxTxs uint32, TTL time.Duration) *L2DB {
  27. return &L2DB{
  28. db: db,
  29. safetyPeriod: safetyPeriod,
  30. ttl: TTL,
  31. maxTxs: maxTxs,
  32. }
  33. }
  34. // DB returns a pointer to the L2DB.db. This method should be used only for
  35. // internal testing purposes.
  36. func (l2db *L2DB) DB() *sqlx.DB {
  37. return l2db.db
  38. }
  39. // AddAccountCreationAuth inserts an account creation authorization into the DB
  40. func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
  41. // return meddler.Insert(l2db.db, "account_creation_auth", auth)
  42. _, err := l2db.db.Exec(
  43. `INSERT INTO account_creation_auth (eth_addr, bjj, signature)
  44. VALUES ($1, $2, $3);`,
  45. auth.EthAddr, auth.BJJ, auth.Signature,
  46. )
  47. return err
  48. }
  49. // GetAccountCreationAuth returns an account creation authorization into the DB
  50. func (l2db *L2DB) GetAccountCreationAuth(addr ethCommon.Address) (*common.AccountCreationAuth, error) {
  51. auth := new(common.AccountCreationAuth)
  52. return auth, meddler.QueryRow(
  53. l2db.db, auth,
  54. "SELECT * FROM account_creation_auth WHERE eth_addr = $1;",
  55. addr,
  56. )
  57. }
  58. // AddTx inserts a tx to the pool
  59. func (l2db *L2DB) AddTx(tx *PoolL2TxWrite) error {
  60. return meddler.Insert(l2db.db, "tx_pool", tx)
  61. }
  62. // AddTxTest inserts a tx into the L2DB. This is useful for test purposes,
  63. // but in production txs will only be inserted through the API
  64. func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
  65. // transform tx from *common.PoolL2Tx to PoolL2TxWrite
  66. insertTx := &PoolL2TxWrite{
  67. TxID: tx.TxID,
  68. FromIdx: tx.FromIdx,
  69. ToBJJ: tx.ToBJJ,
  70. TokenID: tx.TokenID,
  71. Amount: tx.Amount,
  72. Fee: tx.Fee,
  73. Nonce: tx.Nonce,
  74. State: common.PoolL2TxStatePending,
  75. Signature: tx.Signature,
  76. RqToBJJ: tx.RqToBJJ,
  77. RqAmount: tx.RqAmount,
  78. Type: tx.Type,
  79. }
  80. if tx.ToIdx != 0 {
  81. insertTx.ToIdx = &tx.ToIdx
  82. }
  83. nilAddr := ethCommon.BigToAddress(big.NewInt(0))
  84. if tx.ToEthAddr != nilAddr {
  85. insertTx.ToEthAddr = &tx.ToEthAddr
  86. }
  87. if tx.RqFromIdx != 0 {
  88. insertTx.RqFromIdx = &tx.RqFromIdx
  89. }
  90. if tx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
  91. insertTx.RqToIdx = &tx.RqToIdx
  92. insertTx.RqTokenID = &tx.RqTokenID
  93. insertTx.RqFee = &tx.RqFee
  94. insertTx.RqNonce = &tx.RqNonce
  95. }
  96. if tx.RqToEthAddr != nilAddr {
  97. insertTx.RqToEthAddr = &tx.RqToEthAddr
  98. }
  99. f := new(big.Float).SetInt(tx.Amount)
  100. amountF, _ := f.Float64()
  101. insertTx.AmountFloat = amountF
  102. // insert tx
  103. return meddler.Insert(l2db.db, "tx_pool", insertTx)
  104. }
  105. // selectPoolTxRead select part of queries to get PoolL2TxRead
  106. const selectPoolTxRead = `SELECT tx_pool.tx_id, tx_pool.from_idx, tx_pool.to_idx, tx_pool.to_eth_addr,
  107. tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
  108. tx_pool.state, tx_pool.signature, tx_pool.timestamp, tx_pool.batch_num, tx_pool.rq_from_idx,
  109. tx_pool.rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
  110. tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
  111. token.eth_block_num, token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  112. FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
  113. // selectPoolTxCommon select part of queries to get common.PoolL2Tx
  114. const selectPoolTxCommon = `SELECT tx_pool.tx_id, tx_pool.from_idx, tx_pool.to_idx, tx_pool.to_eth_addr,
  115. tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
  116. tx_pool.state, tx_pool.signature, tx_pool.timestamp, tx_pool.rq_from_idx,
  117. tx_pool.rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
  118. tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
  119. fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f AS fee_usd, token.usd_update
  120. FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
  121. // GetTx return the specified Tx
  122. func (l2db *L2DB) GetTx(txID common.TxID) (*PoolL2TxRead, error) {
  123. tx := new(PoolL2TxRead)
  124. return tx, meddler.QueryRow(
  125. l2db.db, tx,
  126. selectPoolTxRead+"WHERE tx_id = $1;",
  127. txID,
  128. )
  129. }
  130. // GetPendingTxs return all the pending txs of the L2DB, that have a non NULL AbsoluteFee
  131. func (l2db *L2DB) GetPendingTxs() ([]common.PoolL2Tx, error) {
  132. var txs []*common.PoolL2Tx
  133. err := meddler.QueryAll(
  134. l2db.db, &txs,
  135. selectPoolTxCommon+"WHERE state = $1",
  136. common.PoolL2TxStatePending,
  137. )
  138. return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), err
  139. }
  140. // StartForging updates the state of the transactions that will begin the forging process.
  141. // The state of the txs referenced by txIDs will be changed from Pending -> Forging
  142. func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  143. query, args, err := sqlx.In(
  144. `UPDATE tx_pool
  145. SET state = ?, batch_num = ?
  146. WHERE state = ? AND tx_id IN (?);`,
  147. common.PoolL2TxStateForging,
  148. batchNum,
  149. common.PoolL2TxStatePending,
  150. txIDs,
  151. )
  152. if err != nil {
  153. return err
  154. }
  155. query = l2db.db.Rebind(query)
  156. _, err = l2db.db.Exec(query, args...)
  157. return err
  158. }
  159. // DoneForging updates the state of the transactions that have been forged
  160. // so the state of the txs referenced by txIDs will be changed from Forging -> Forged
  161. func (l2db *L2DB) DoneForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  162. query, args, err := sqlx.In(
  163. `UPDATE tx_pool
  164. SET state = ?, batch_num = ?
  165. WHERE state = ? AND tx_id IN (?);`,
  166. common.PoolL2TxStateForged,
  167. batchNum,
  168. common.PoolL2TxStateForging,
  169. txIDs,
  170. )
  171. if err != nil {
  172. return err
  173. }
  174. query = l2db.db.Rebind(query)
  175. _, err = l2db.db.Exec(query, args...)
  176. return err
  177. }
  178. // InvalidateTxs updates the state of the transactions that are invalid.
  179. // The state of the txs referenced by txIDs will be changed from * -> Invalid
  180. func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID, batchNum common.BatchNum) error {
  181. query, args, err := sqlx.In(
  182. `UPDATE tx_pool
  183. SET state = ?, batch_num = ?
  184. WHERE tx_id IN (?);`,
  185. common.PoolL2TxStateInvalid,
  186. batchNum,
  187. txIDs,
  188. )
  189. if err != nil {
  190. return err
  191. }
  192. query = l2db.db.Rebind(query)
  193. _, err = l2db.db.Exec(query, args...)
  194. return err
  195. }
  196. // CheckNonces invalidate txs with nonces that are smaller or equal than their respective accounts nonces.
  197. // The state of the affected txs will be changed from Pending -> Invalid
  198. func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account, batchNum common.BatchNum) (err error) {
  199. txn, err := l2db.db.Begin()
  200. if err != nil {
  201. return err
  202. }
  203. defer func() {
  204. // Rollback the transaction if there was an error.
  205. if err != nil {
  206. errRollback := txn.Rollback()
  207. if errRollback != nil {
  208. log.Errorw("Rollback", "err", errRollback)
  209. }
  210. }
  211. }()
  212. for i := 0; i < len(updatedAccounts); i++ {
  213. _, err = txn.Exec(
  214. `UPDATE tx_pool
  215. SET state = $1, batch_num = $2
  216. WHERE state = $3 AND from_idx = $4 AND nonce <= $5;`,
  217. common.PoolL2TxStateInvalid,
  218. batchNum,
  219. common.PoolL2TxStatePending,
  220. updatedAccounts[i].Idx,
  221. updatedAccounts[i].Nonce,
  222. )
  223. if err != nil {
  224. return err
  225. }
  226. }
  227. return txn.Commit()
  228. }
  229. // Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
  230. // The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
  231. func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
  232. _, err := l2db.db.Exec(
  233. `UPDATE tx_pool SET batch_num = NULL, state = $1
  234. WHERE (state = $2 OR state = $3) AND batch_num > $4`,
  235. common.PoolL2TxStatePending,
  236. common.PoolL2TxStateForged,
  237. common.PoolL2TxStateInvalid,
  238. lastValidBatch,
  239. )
  240. return err
  241. }
  242. // Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
  243. // it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded
  244. func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
  245. txn, err := l2db.db.Begin()
  246. if err != nil {
  247. return err
  248. }
  249. defer func() {
  250. // Rollback the transaction if there was an error.
  251. if err != nil {
  252. errRollback := txn.Rollback()
  253. if errRollback != nil {
  254. log.Errorw("Rollback", "err", errRollback)
  255. }
  256. }
  257. }()
  258. // Delete pending txs that have been in the pool after the TTL if maxTxs is reached
  259. now := time.Now().UTC().Unix()
  260. _, err = txn.Exec(
  261. `DELETE FROM tx_pool WHERE (SELECT count(*) FROM tx_pool) > $1 AND timestamp < $2`,
  262. l2db.maxTxs,
  263. time.Unix(now-int64(l2db.ttl.Seconds()), 0),
  264. )
  265. if err != nil {
  266. return err
  267. }
  268. // Delete txs that have been marked as forged / invalid after the safety period
  269. _, err = txn.Exec(
  270. `DELETE FROM tx_pool
  271. WHERE batch_num < $1 AND (state = $2 OR state = $3)`,
  272. currentBatchNum-l2db.safetyPeriod,
  273. common.PoolL2TxStateForged,
  274. common.PoolL2TxStateInvalid,
  275. )
  276. if err != nil {
  277. return err
  278. }
  279. return txn.Commit()
  280. }