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.

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