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