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.

365 lines
11 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
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. "fmt"
  4. "math/big"
  5. "time"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/hermeznetwork/hermez-node/common"
  8. "github.com/hermeznetwork/hermez-node/db"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/jmoiron/sqlx"
  11. //nolint:errcheck // driver for postgres DB
  12. _ "github.com/lib/pq"
  13. "github.com/russross/meddler"
  14. )
  15. // TODO(Edu): Check DB consistency while there's concurrent use from Coordinator/TxSelector & API
  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 common.BatchNum
  21. ttl time.Duration
  22. maxTxs uint32 // limit of txs that are accepted in the pool
  23. minFeeUSD float64
  24. apiConnCon *db.APIConnectionController
  25. }
  26. // NewL2DB creates a L2DB.
  27. // To create it, it's needed db connection, safety period expressed in batches,
  28. // maxTxs that the DB should have and TTL (time to live) for pending txs.
  29. func NewL2DB(
  30. db *sqlx.DB,
  31. safetyPeriod common.BatchNum,
  32. maxTxs uint32,
  33. minFeeUSD float64,
  34. TTL time.Duration,
  35. apiConnCon *db.APIConnectionController,
  36. ) *L2DB {
  37. return &L2DB{
  38. db: db,
  39. safetyPeriod: safetyPeriod,
  40. ttl: TTL,
  41. maxTxs: maxTxs,
  42. minFeeUSD: minFeeUSD,
  43. apiConnCon: apiConnCon,
  44. }
  45. }
  46. // DB returns a pointer to the L2DB.db. This method should be used only for
  47. // internal testing purposes.
  48. func (l2db *L2DB) DB() *sqlx.DB {
  49. return l2db.db
  50. }
  51. // MinFeeUSD returns the minimum fee in USD that is required to accept txs into
  52. // the pool
  53. func (l2db *L2DB) MinFeeUSD() float64 {
  54. return l2db.minFeeUSD
  55. }
  56. // AddAccountCreationAuth inserts an account creation authorization into the DB
  57. func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
  58. _, err := l2db.db.Exec(
  59. `INSERT INTO account_creation_auth (eth_addr, bjj, signature)
  60. VALUES ($1, $2, $3);`,
  61. auth.EthAddr, auth.BJJ, auth.Signature,
  62. )
  63. return tracerr.Wrap(err)
  64. }
  65. // GetAccountCreationAuth returns an account creation authorization from the DB
  66. func (l2db *L2DB) GetAccountCreationAuth(addr ethCommon.Address) (*common.AccountCreationAuth, error) {
  67. auth := new(common.AccountCreationAuth)
  68. return auth, tracerr.Wrap(meddler.QueryRow(
  69. l2db.db, auth,
  70. "SELECT * FROM account_creation_auth WHERE eth_addr = $1;",
  71. addr,
  72. ))
  73. }
  74. // UpdateTxsInfo updates the parameter Info of the pool transactions
  75. func (l2db *L2DB) UpdateTxsInfo(txs []common.PoolL2Tx) error {
  76. if len(txs) == 0 {
  77. return nil
  78. }
  79. type txUpdate struct {
  80. ID common.TxID `db:"id"`
  81. Info string `db:"info"`
  82. }
  83. txUpdates := make([]txUpdate, len(txs))
  84. for i := range txs {
  85. txUpdates[i] = txUpdate{ID: txs[i].TxID, Info: txs[i].Info}
  86. }
  87. const query string = `
  88. UPDATE tx_pool SET
  89. info = tx_update.info
  90. FROM (VALUES
  91. (NULL::::BYTEA, NULL::::VARCHAR),
  92. (:id, :info)
  93. ) as tx_update (id, info)
  94. WHERE tx_pool.tx_id = tx_update.id;
  95. `
  96. if len(txUpdates) > 0 {
  97. if _, err := sqlx.NamedExec(l2db.db, query, txUpdates); err != nil {
  98. return tracerr.Wrap(err)
  99. }
  100. }
  101. return nil
  102. }
  103. // NewPoolL2TxWriteFromPoolL2Tx creates a new PoolL2TxWrite from a PoolL2Tx
  104. func NewPoolL2TxWriteFromPoolL2Tx(tx *common.PoolL2Tx) *PoolL2TxWrite {
  105. // transform tx from *common.PoolL2Tx to PoolL2TxWrite
  106. insertTx := &PoolL2TxWrite{
  107. TxID: tx.TxID,
  108. FromIdx: tx.FromIdx,
  109. TokenID: tx.TokenID,
  110. Amount: tx.Amount,
  111. Fee: tx.Fee,
  112. Nonce: tx.Nonce,
  113. State: common.PoolL2TxStatePending,
  114. Signature: tx.Signature,
  115. RqAmount: tx.RqAmount,
  116. Type: tx.Type,
  117. }
  118. if tx.ToIdx != 0 {
  119. insertTx.ToIdx = &tx.ToIdx
  120. }
  121. nilAddr := ethCommon.BigToAddress(big.NewInt(0))
  122. if tx.ToEthAddr != nilAddr {
  123. insertTx.ToEthAddr = &tx.ToEthAddr
  124. }
  125. if tx.RqFromIdx != 0 {
  126. insertTx.RqFromIdx = &tx.RqFromIdx
  127. }
  128. if tx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
  129. insertTx.RqToIdx = &tx.RqToIdx
  130. insertTx.RqTokenID = &tx.RqTokenID
  131. insertTx.RqFee = &tx.RqFee
  132. insertTx.RqNonce = &tx.RqNonce
  133. }
  134. if tx.RqToEthAddr != nilAddr {
  135. insertTx.RqToEthAddr = &tx.RqToEthAddr
  136. }
  137. if tx.ToBJJ != common.EmptyBJJComp {
  138. insertTx.ToBJJ = &tx.ToBJJ
  139. }
  140. if tx.RqToBJJ != common.EmptyBJJComp {
  141. insertTx.RqToBJJ = &tx.RqToBJJ
  142. }
  143. f := new(big.Float).SetInt(tx.Amount)
  144. amountF, _ := f.Float64()
  145. insertTx.AmountFloat = amountF
  146. return insertTx
  147. }
  148. // AddTxTest inserts a tx into the L2DB. This is useful for test purposes,
  149. // but in production txs will only be inserted through the API
  150. func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
  151. insertTx := NewPoolL2TxWriteFromPoolL2Tx(tx)
  152. // insert tx
  153. return tracerr.Wrap(meddler.Insert(l2db.db, "tx_pool", insertTx))
  154. }
  155. // selectPoolTxCommon select part of queries to get common.PoolL2Tx
  156. const selectPoolTxCommon = `SELECT tx_pool.tx_id, from_idx, to_idx, tx_pool.to_eth_addr,
  157. tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
  158. tx_pool.state, tx_pool.info, tx_pool.signature, tx_pool.timestamp, rq_from_idx,
  159. rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
  160. tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
  161. (fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f) /
  162. (10.0 ^ token.decimals::NUMERIC) AS fee_usd, token.usd_update
  163. FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
  164. // GetTx return the specified Tx in common.PoolL2Tx format
  165. func (l2db *L2DB) GetTx(txID common.TxID) (*common.PoolL2Tx, error) {
  166. tx := new(common.PoolL2Tx)
  167. return tx, tracerr.Wrap(meddler.QueryRow(
  168. l2db.db, tx,
  169. selectPoolTxCommon+"WHERE tx_id = $1;",
  170. txID,
  171. ))
  172. }
  173. // GetPendingTxs return all the pending txs of the L2DB, that have a non NULL AbsoluteFee
  174. func (l2db *L2DB) GetPendingTxs() ([]common.PoolL2Tx, error) {
  175. var txs []*common.PoolL2Tx
  176. err := meddler.QueryAll(
  177. l2db.db, &txs,
  178. selectPoolTxCommon+"WHERE state = $1",
  179. common.PoolL2TxStatePending,
  180. )
  181. return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), tracerr.Wrap(err)
  182. }
  183. // StartForging updates the state of the transactions that will begin the forging process.
  184. // The state of the txs referenced by txIDs will be changed from Pending -> Forging
  185. func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  186. if len(txIDs) == 0 {
  187. return nil
  188. }
  189. query, args, err := sqlx.In(
  190. `UPDATE tx_pool
  191. SET state = ?, batch_num = ?
  192. WHERE state = ? AND tx_id IN (?);`,
  193. common.PoolL2TxStateForging,
  194. batchNum,
  195. common.PoolL2TxStatePending,
  196. txIDs,
  197. )
  198. if err != nil {
  199. return tracerr.Wrap(err)
  200. }
  201. query = l2db.db.Rebind(query)
  202. _, err = l2db.db.Exec(query, args...)
  203. return tracerr.Wrap(err)
  204. }
  205. // DoneForging updates the state of the transactions that have been forged
  206. // so the state of the txs referenced by txIDs will be changed from Forging -> Forged
  207. func (l2db *L2DB) DoneForging(txIDs []common.TxID, batchNum common.BatchNum) error {
  208. if len(txIDs) == 0 {
  209. return nil
  210. }
  211. query, args, err := sqlx.In(
  212. `UPDATE tx_pool
  213. SET state = ?, batch_num = ?
  214. WHERE state = ? AND tx_id IN (?);`,
  215. common.PoolL2TxStateForged,
  216. batchNum,
  217. common.PoolL2TxStateForging,
  218. txIDs,
  219. )
  220. if err != nil {
  221. return tracerr.Wrap(err)
  222. }
  223. query = l2db.db.Rebind(query)
  224. _, err = l2db.db.Exec(query, args...)
  225. return tracerr.Wrap(err)
  226. }
  227. // InvalidateTxs updates the state of the transactions that are invalid.
  228. // The state of the txs referenced by txIDs will be changed from * -> Invalid
  229. func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID, batchNum common.BatchNum) error {
  230. if len(txIDs) == 0 {
  231. return nil
  232. }
  233. query, args, err := sqlx.In(
  234. `UPDATE tx_pool
  235. SET state = ?, batch_num = ?
  236. WHERE tx_id IN (?);`,
  237. common.PoolL2TxStateInvalid,
  238. batchNum,
  239. txIDs,
  240. )
  241. if err != nil {
  242. return tracerr.Wrap(err)
  243. }
  244. query = l2db.db.Rebind(query)
  245. _, err = l2db.db.Exec(query, args...)
  246. return tracerr.Wrap(err)
  247. }
  248. // GetPendingUniqueFromIdxs returns from all the pending transactions, the set
  249. // of unique FromIdx
  250. func (l2db *L2DB) GetPendingUniqueFromIdxs() ([]common.Idx, error) {
  251. var idxs []common.Idx
  252. rows, err := l2db.db.Query(`SELECT DISTINCT from_idx FROM tx_pool
  253. WHERE state = $1;`, common.PoolL2TxStatePending)
  254. if err != nil {
  255. return nil, tracerr.Wrap(err)
  256. }
  257. defer db.RowsClose(rows)
  258. var idx common.Idx
  259. for rows.Next() {
  260. err = rows.Scan(&idx)
  261. if err != nil {
  262. return nil, tracerr.Wrap(err)
  263. }
  264. idxs = append(idxs, idx)
  265. }
  266. return idxs, nil
  267. }
  268. var invalidateOldNoncesQuery = fmt.Sprintf(`
  269. UPDATE tx_pool SET
  270. state = '%s',
  271. batch_num = %%d
  272. FROM (VALUES
  273. (NULL::::BIGINT, NULL::::BIGINT),
  274. (:idx, :nonce)
  275. ) as updated_acc (idx, nonce)
  276. WHERE tx_pool.state = '%s' AND
  277. tx_pool.from_idx = updated_acc.idx AND
  278. tx_pool.nonce < updated_acc.nonce;
  279. `, common.PoolL2TxStateInvalid, common.PoolL2TxStatePending)
  280. // InvalidateOldNonces invalidate txs with nonces that are smaller or equal than their
  281. // respective accounts nonces. The state of the affected txs will be changed
  282. // from Pending to Invalid
  283. func (l2db *L2DB) InvalidateOldNonces(updatedAccounts []common.IdxNonce, batchNum common.BatchNum) (err error) {
  284. if len(updatedAccounts) == 0 {
  285. return nil
  286. }
  287. // Fill the batch_num in the query with Sprintf because we are using a
  288. // named query which works with slices, and doens't handle an extra
  289. // individual argument.
  290. query := fmt.Sprintf(invalidateOldNoncesQuery, batchNum)
  291. if _, err := sqlx.NamedExec(l2db.db, query, updatedAccounts); err != nil {
  292. return tracerr.Wrap(err)
  293. }
  294. return nil
  295. }
  296. // Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
  297. // The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
  298. func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
  299. _, err := l2db.db.Exec(
  300. `UPDATE tx_pool SET batch_num = NULL, state = $1
  301. WHERE (state = $2 OR state = $3 OR state = $4) AND batch_num > $5`,
  302. common.PoolL2TxStatePending,
  303. common.PoolL2TxStateForging,
  304. common.PoolL2TxStateForged,
  305. common.PoolL2TxStateInvalid,
  306. lastValidBatch,
  307. )
  308. return tracerr.Wrap(err)
  309. }
  310. // Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
  311. // it also deletes pending txs that have been in the L2DB for longer than the ttl if maxTxs has been exceeded
  312. func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
  313. now := time.Now().UTC().Unix()
  314. _, err = l2db.db.Exec(
  315. `DELETE FROM tx_pool WHERE (
  316. batch_num < $1 AND (state = $2 OR state = $3)
  317. ) OR (
  318. (SELECT count(*) FROM tx_pool WHERE state = $4) > $5
  319. AND timestamp < $6 AND state = $4
  320. );`,
  321. currentBatchNum-l2db.safetyPeriod,
  322. common.PoolL2TxStateForged,
  323. common.PoolL2TxStateInvalid,
  324. common.PoolL2TxStatePending,
  325. l2db.maxTxs,
  326. time.Unix(now-int64(l2db.ttl.Seconds()), 0),
  327. )
  328. return tracerr.Wrap(err)
  329. }
  330. // PurgeByExternalDelete deletes all pending transactions marked with true in
  331. // the `external_delete` column. An external process can set this column to
  332. // true to instruct the coordinator to delete the tx when possible.
  333. func (l2db *L2DB) PurgeByExternalDelete() error {
  334. _, err := l2db.db.Exec(
  335. `DELETE from tx_pool WHERE (external_delete = true AND state = $1);`,
  336. common.PoolL2TxStatePending,
  337. )
  338. return tracerr.Wrap(err)
  339. }