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.

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