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}
29
30// NewL2DB creates a L2DB.
31// To create it, it's needed db connection, safety period expressed in batches,
32// maxTxs that the DB should have and TTL (time to live) for pending txs.
33func NewL2DB(db *sqlx.DB, safetyPeriod common.BatchNum, maxTxs uint32, TTL time.Duration) *L2DB {
34 return &L2DB{
35 db: db,
36 safetyPeriod: safetyPeriod,
37 ttl: TTL,
38 maxTxs: maxTxs,
39 }
40}
41
42// DB returns a pointer to the L2DB.db. This method should be used only for
43// internal testing purposes.
44func (l2db *L2DB) DB() *sqlx.DB {
45 return l2db.db
46}
47
48// AddAccountCreationAuth inserts an account creation authorization into the DB
49func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
50 // return meddler.Insert(l2db.db, "account_creation_auth", auth)
51 _, err := l2db.db.Exec(
52 `INSERT INTO account_creation_auth (eth_addr, bjj, signature)
53 VALUES ($1, $2, $3);`,
54 auth.EthAddr, auth.BJJ, auth.Signature,
55 )
56 return tracerr.Wrap(err)
57}
58
59// GetAccountCreationAuth returns an account creation authorization from the DB
60func (l2db *L2DB) GetAccountCreationAuth(addr ethCommon.Address) (*common.AccountCreationAuth, error) {
61 auth := new(common.AccountCreationAuth)
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
69// GetAccountCreationAuthAPI returns an account creation authorization from the DB
70func (l2db *L2DB) GetAccountCreationAuthAPI(addr ethCommon.Address) (*AccountCreationAuthAPI, error) {
71 auth := new(AccountCreationAuthAPI)
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// AddTx inserts a tx to the pool
80func (l2db *L2DB) AddTx(tx *PoolL2TxWrite) error {
81 row := l2db.db.QueryRow(
82 "SELECT COUNT(*) FROM tx_pool WHERE state = $1;",
83 common.PoolL2TxStatePending,
84 )
85 var totalTxs uint32
86 if err := row.Scan(&totalTxs); err != nil {
87 return tracerr.Wrap(err)
88 }
89 if totalTxs >= l2db.maxTxs {
90 return tracerr.New(
91 "The pool is at full capacity. More transactions are not accepted currently",
92 )
93 }
94 return tracerr.Wrap(meddler.Insert(l2db.db, "tx_pool", tx))
95}
96
97// AddTxTest inserts a tx into the L2DB. This is useful for test purposes,
98// but in production txs will only be inserted through the API
99func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
100 // transform tx from *common.PoolL2Tx to PoolL2TxWrite
101 insertTx := &PoolL2TxWrite{
102 TxID: tx.TxID,
103 FromIdx: tx.FromIdx,
104 TokenID: tx.TokenID,
105 Amount: tx.Amount,
106 Fee: tx.Fee,
107 Nonce: tx.Nonce,
108 State: common.PoolL2TxStatePending,
109 Signature: tx.Signature,
110 RqAmount: tx.RqAmount,
111 Type: tx.Type,
112 }
113 if tx.ToIdx != 0 {
114 insertTx.ToIdx = &tx.ToIdx
115 }
116 nilAddr := ethCommon.BigToAddress(big.NewInt(0))
117 if tx.ToEthAddr != nilAddr {
118 insertTx.ToEthAddr = &tx.ToEthAddr
119 }
120 if tx.RqFromIdx != 0 {
121 insertTx.RqFromIdx = &tx.RqFromIdx
122 }
123 if tx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
124 insertTx.RqToIdx = &tx.RqToIdx
125 insertTx.RqTokenID = &tx.RqTokenID
126 insertTx.RqFee = &tx.RqFee
127 insertTx.RqNonce = &tx.RqNonce
128 }
129 if tx.RqToEthAddr != nilAddr {
130 insertTx.RqToEthAddr = &tx.RqToEthAddr
131 }
132 if tx.ToBJJ != common.EmptyBJJComp {
133 insertTx.ToBJJ = &tx.ToBJJ
134 }
135 if tx.RqToBJJ != common.EmptyBJJComp {
136 insertTx.RqToBJJ = &tx.RqToBJJ
137 }
138 f := new(big.Float).SetInt(tx.Amount)
139 amountF, _ := f.Float64()
140 insertTx.AmountFloat = amountF
141 // insert tx
142 return tracerr.Wrap(meddler.Insert(l2db.db, "tx_pool", insertTx))
143}
144
145// selectPoolTxAPI select part of queries to get PoolL2TxRead
146const selectPoolTxAPI = `SELECT tx_pool.tx_id, hez_idx(tx_pool.from_idx, token.symbol) AS from_idx, tx_pool.from_eth_addr,
147tx_pool.from_bjj, hez_idx(tx_pool.to_idx, token.symbol) AS to_idx, tx_pool.to_eth_addr,
148tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
149tx_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,
150hez_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,
151tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
152token.item_id AS token_item_id, token.eth_block_num, token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
153FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
154
155// selectPoolTxCommon select part of queries to get common.PoolL2Tx
156const selectPoolTxCommon = `SELECT tx_pool.tx_id, from_idx, to_idx, tx_pool.to_eth_addr,
157tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
158tx_pool.state, tx_pool.signature, tx_pool.timestamp, rq_from_idx,
159rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
160tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
161fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f AS fee_usd, token.usd_update
162FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
163
164// GetTx return the specified Tx in common.PoolL2Tx format
165func (l2db *L2DB) GetTx(txID common.TxID) (*common.PoolL2Tx, error) {
166 tx := new(common.PoolL2Tx)
167 return tx, tracerr.Wrap(meddler.QueryRow(
168 l2db.db, tx,
169 selectPoolTxCommon+"WHERE tx_id = $1;",
170 txID,
171 ))
172}
173
174// GetTxAPI return the specified Tx in PoolTxAPI format
175func (l2db *L2DB) GetTxAPI(txID common.TxID) (*PoolTxAPI, error) {
176 tx := new(PoolTxAPI)
177 return tx, tracerr.Wrap(meddler.QueryRow(
178 l2db.db, tx,
179 selectPoolTxAPI+"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) AND batch_num > $4`,
320 common.PoolL2TxStatePending,
321 common.PoolL2TxStateForged,
322 common.PoolL2TxStateInvalid,
323 lastValidBatch,
324 )
325 return tracerr.Wrap(err)
326}
327
328// Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
329// it also deletes pending txs that have been in the L2DB for longer than the ttl if maxTxs has been exceeded
330func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
331 now := time.Now().UTC().Unix()
332 _, err = l2db.db.Exec(
333 `DELETE FROM tx_pool WHERE (
334 batch_num < $1 AND (state = $2 OR state = $3)
335 ) OR (
336 (SELECT count(*) FROM tx_pool WHERE state = $4) > $5
337 AND timestamp < $6 AND state = $4
338 );`,
339 currentBatchNum-l2db.safetyPeriod,
340 common.PoolL2TxStateForged,
341 common.PoolL2TxStateInvalid,
342 common.PoolL2TxStatePending,
343 l2db.maxTxs,
344 time.Unix(now-int64(l2db.ttl.Seconds()), 0),
345 )
346 return tracerr.Wrap(err)
347}