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