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.

312 lines
10 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. // selectPoolTxAPI select part of queries to get PoolL2TxRead
  106. const selectPoolTxAPI = `SELECT tx_pool.tx_id, hez_idx(tx_pool.from_idx, token.symbol) AS from_idx, tx_pool.from_eth_addr,
  107. tx_pool.from_bjj, hez_idx(tx_pool.to_idx, token.symbol) AS to_idx, tx_pool.to_eth_addr,
  108. tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
  109. tx_pool.state, tx_pool.signature, tx_pool.timestamp, tx_pool.batch_num, hez_idx(tx_pool.rq_from_idx, token.symbol) AS rq_from_idx,
  110. hez_idx(tx_pool.rq_to_idx, token.symbol) AS rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
  111. tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
  112. token.item_id AS token_item_id, token.eth_block_num, token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  113. FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
  114. // selectPoolTxCommon select part of queries to get common.PoolL2Tx
  115. const selectPoolTxCommon = `SELECT tx_pool.tx_id, from_idx, to_idx, tx_pool.to_eth_addr,
  116. tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
  117. tx_pool.state, tx_pool.signature, tx_pool.timestamp, rq_from_idx,
  118. rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
  119. tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
  120. fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f AS fee_usd, token.usd_update
  121. FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
  122. // GetTx return the specified Tx in common.PoolL2Tx format
  123. func (l2db *L2DB) GetTx(txID common.TxID) (*common.PoolL2Tx, error) {
  124. tx := new(common.PoolL2Tx)
  125. return tx, meddler.QueryRow(
  126. l2db.db, tx,
  127. selectPoolTxCommon+"WHERE tx_id = $1;",
  128. txID,
  129. )
  130. }
  131. // GetTxAPI return the specified Tx in PoolTxAPI format
  132. func (l2db *L2DB) GetTxAPI(txID common.TxID) (*PoolTxAPI, error) {
  133. tx := new(PoolTxAPI)
  134. return tx, meddler.QueryRow(
  135. l2db.db, tx,
  136. selectPoolTxAPI+"WHERE tx_id = $1;",
  137. txID,
  138. )
  139. }
  140. // GetPendingTxs return all the pending txs of the L2DB, that have a non NULL AbsoluteFee
  141. func (l2db *L2DB) GetPendingTxs() ([]common.PoolL2Tx, error) {
  142. var txs []*common.PoolL2Tx
  143. err := meddler.QueryAll(
  144. l2db.db, &txs,
  145. selectPoolTxCommon+"WHERE state = $1",
  146. common.PoolL2TxStatePending,
  147. )
  148. return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), err
  149. }
  150. // StartForging updates the state of the transactions that will begin the forging process.
  151. // The state of the txs referenced by txIDs will be changed from Pending -> Forging
  152. func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  153. query, args, err := sqlx.In(
  154. `UPDATE tx_pool
  155. SET state = ?, batch_num = ?
  156. WHERE state = ? AND tx_id IN (?);`,
  157. common.PoolL2TxStateForging,
  158. batchNum,
  159. common.PoolL2TxStatePending,
  160. txIDs,
  161. )
  162. if err != nil {
  163. return err
  164. }
  165. query = l2db.db.Rebind(query)
  166. _, err = l2db.db.Exec(query, args...)
  167. return err
  168. }
  169. // DoneForging updates the state of the transactions that have been forged
  170. // so the state of the txs referenced by txIDs will be changed from Forging -> Forged
  171. func (l2db *L2DB) DoneForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  172. query, args, err := sqlx.In(
  173. `UPDATE tx_pool
  174. SET state = ?, batch_num = ?
  175. WHERE state = ? AND tx_id IN (?);`,
  176. common.PoolL2TxStateForged,
  177. batchNum,
  178. common.PoolL2TxStateForging,
  179. txIDs,
  180. )
  181. if err != nil {
  182. return err
  183. }
  184. query = l2db.db.Rebind(query)
  185. _, err = l2db.db.Exec(query, args...)
  186. return err
  187. }
  188. // InvalidateTxs updates the state of the transactions that are invalid.
  189. // The state of the txs referenced by txIDs will be changed from * -> Invalid
  190. func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID, batchNum common.BatchNum) error {
  191. query, args, err := sqlx.In(
  192. `UPDATE tx_pool
  193. SET state = ?, batch_num = ?
  194. WHERE tx_id IN (?);`,
  195. common.PoolL2TxStateInvalid,
  196. batchNum,
  197. txIDs,
  198. )
  199. if err != nil {
  200. return err
  201. }
  202. query = l2db.db.Rebind(query)
  203. _, err = l2db.db.Exec(query, args...)
  204. return err
  205. }
  206. // CheckNonces invalidate txs with nonces that are smaller or equal than their respective accounts nonces.
  207. // The state of the affected txs will be changed from Pending -> Invalid
  208. func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account, batchNum common.BatchNum) (err error) {
  209. txn, err := l2db.db.Begin()
  210. if err != nil {
  211. return err
  212. }
  213. defer func() {
  214. // Rollback the transaction if there was an error.
  215. if err != nil {
  216. errRollback := txn.Rollback()
  217. if errRollback != nil {
  218. log.Errorw("Rollback", "err", errRollback)
  219. }
  220. }
  221. }()
  222. for i := 0; i < len(updatedAccounts); i++ {
  223. _, err = txn.Exec(
  224. `UPDATE tx_pool
  225. SET state = $1, batch_num = $2
  226. WHERE state = $3 AND from_idx = $4 AND nonce <= $5;`,
  227. common.PoolL2TxStateInvalid,
  228. batchNum,
  229. common.PoolL2TxStatePending,
  230. updatedAccounts[i].Idx,
  231. updatedAccounts[i].Nonce,
  232. )
  233. if err != nil {
  234. return err
  235. }
  236. }
  237. return txn.Commit()
  238. }
  239. // Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
  240. // The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
  241. func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
  242. _, err := l2db.db.Exec(
  243. `UPDATE tx_pool SET batch_num = NULL, state = $1
  244. WHERE (state = $2 OR state = $3) AND batch_num > $4`,
  245. common.PoolL2TxStatePending,
  246. common.PoolL2TxStateForged,
  247. common.PoolL2TxStateInvalid,
  248. lastValidBatch,
  249. )
  250. return err
  251. }
  252. // Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
  253. // it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded
  254. func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
  255. txn, err := l2db.db.Begin()
  256. if err != nil {
  257. return err
  258. }
  259. defer func() {
  260. // Rollback the transaction if there was an error.
  261. if err != nil {
  262. errRollback := txn.Rollback()
  263. if errRollback != nil {
  264. log.Errorw("Rollback", "err", errRollback)
  265. }
  266. }
  267. }()
  268. // Delete pending txs that have been in the pool after the TTL if maxTxs is reached
  269. now := time.Now().UTC().Unix()
  270. _, err = txn.Exec(
  271. `DELETE FROM tx_pool WHERE (SELECT count(*) FROM tx_pool) > $1 AND timestamp < $2`,
  272. l2db.maxTxs,
  273. time.Unix(now-int64(l2db.ttl.Seconds()), 0),
  274. )
  275. if err != nil {
  276. return err
  277. }
  278. // Delete txs that have been marked as forged / invalid after the safety period
  279. _, err = txn.Exec(
  280. `DELETE FROM tx_pool
  281. WHERE batch_num < $1 AND (state = $2 OR state = $3)`,
  282. currentBatchNum-l2db.safetyPeriod,
  283. common.PoolL2TxStateForged,
  284. common.PoolL2TxStateInvalid,
  285. )
  286. if err != nil {
  287. return err
  288. }
  289. return txn.Commit()
  290. }