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