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.

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