hermez-node/db/l2db/l2db.go
db/l2db/l2db.goRaw
1package l2db
2
3import (
4 "math/big"
5 "time"
6
7 ethCommon "github.com/ethereum/go-ethereum/common"
8 "github.com/hermeznetwork/hermez-node/common"
9 "github.com/hermeznetwork/hermez-node/db"
10 "github.com/hermeznetwork/hermez-node/log"
11 "github.com/jmoiron/sqlx"
12
13 //nolint:errcheck // driver for postgres DB
14 _ "github.com/lib/pq"
15 "github.com/russross/meddler"
16)
17
18// TODO(Edu): Check DB consistency while there's concurrent use from Coordinator/TxSelector & API
19
20// L2DB stores L2 txs and authorization registers received by the coordinator and keeps them until they are no longer relevant
21// due to them being forged or invalid after a safety period
22type L2DB struct {
23 db *sqlx.DB
24 safetyPeriod common.BatchNum
25 ttl time.Duration
26 maxTxs uint32
27}
28
29// NewL2DB creates a L2DB.
30// To create it, it's needed db connection, safety period expressed in batches,
31// maxTxs that the DB should have and TTL (time to live) for pending txs.
32func NewL2DB(db *sqlx.DB, safetyPeriod common.BatchNum, maxTxs uint32, TTL time.Duration) *L2DB {
33 return &L2DB{
34 db: db,
35 safetyPeriod: safetyPeriod,
36 ttl: TTL,
37 maxTxs: maxTxs,
38 }
39}
40
41// DB returns a pointer to the L2DB.db. This method should be used only for
42// internal testing purposes.
43func (l2db *L2DB) DB() *sqlx.DB {
44 return l2db.db
45}
46
47// AddAccountCreationAuth inserts an account creation authorization into the DB
48func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
49 // return meddler.Insert(l2db.db, "account_creation_auth", auth)
50 _, err := l2db.db.Exec(
51 `INSERT INTO account_creation_auth (eth_addr, bjj, signature)
52 VALUES ($1, $2, $3);`,
53 auth.EthAddr, auth.BJJ, auth.Signature,
54 )
55 return err
56}
57
58// GetAccountCreationAuth returns an account creation authorization into the DB
59func (l2db *L2DB) GetAccountCreationAuth(addr ethCommon.Address) (*common.AccountCreationAuth, error) {
60 auth := new(common.AccountCreationAuth)
61 return auth, meddler.QueryRow(
62 l2db.db, auth,
63 "SELECT * FROM account_creation_auth WHERE eth_addr = $1;",
64 addr,
65 )
66}
67
68// AddTx inserts a tx to the pool
69func (l2db *L2DB) AddTx(tx *PoolL2TxWrite) error {
70 return meddler.Insert(l2db.db, "tx_pool", tx)
71}
72
73// AddTxTest inserts a tx into the L2DB. This is useful for test purposes,
74// but in production txs will only be inserted through the API
75func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
76 // transform tx from *common.PoolL2Tx to PoolL2TxWrite
77 insertTx := &PoolL2TxWrite{
78 TxID: tx.TxID,
79 FromIdx: tx.FromIdx,
80 ToBJJ: tx.ToBJJ,
81 TokenID: tx.TokenID,
82 Amount: tx.Amount,
83 Fee: tx.Fee,
84 Nonce: tx.Nonce,
85 State: common.PoolL2TxStatePending,
86 Signature: tx.Signature,
87 RqToBJJ: tx.RqToBJJ,
88 RqAmount: tx.RqAmount,
89 Type: tx.Type,
90 }
91 if tx.ToIdx != 0 {
92 insertTx.ToIdx = &tx.ToIdx
93 }
94 nilAddr := ethCommon.BigToAddress(big.NewInt(0))
95 if tx.ToEthAddr != nilAddr {
96 insertTx.ToEthAddr = &tx.ToEthAddr
97 }
98 if tx.RqFromIdx != 0 {
99 insertTx.RqFromIdx = &tx.RqFromIdx
100 }
101 if tx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
102 insertTx.RqToIdx = &tx.RqToIdx
103 insertTx.RqTokenID = &tx.RqTokenID
104 insertTx.RqFee = &tx.RqFee
105 insertTx.RqNonce = &tx.RqNonce
106 }
107 if tx.RqToEthAddr != nilAddr {
108 insertTx.RqToEthAddr = &tx.RqToEthAddr
109 }
110 f := new(big.Float).SetInt(tx.Amount)
111 amountF, _ := f.Float64()
112 insertTx.AmountFloat = amountF
113 // insert tx
114 return meddler.Insert(l2db.db, "tx_pool", insertTx)
115}
116
117// selectPoolTxRead select part of queries to get PoolL2TxRead
118const selectPoolTxRead = `SELECT tx_pool.tx_id, tx_pool.from_idx, tx_pool.to_idx, tx_pool.to_eth_addr,
119tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
120tx_pool.state, tx_pool.signature, tx_pool.timestamp, tx_pool.batch_num, tx_pool.rq_from_idx,
121tx_pool.rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
122tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
123token.eth_block_num, token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
124FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
125
126// selectPoolTxCommon select part of queries to get common.PoolL2Tx
127const selectPoolTxCommon = `SELECT tx_pool.tx_id, tx_pool.from_idx, tx_pool.to_idx, tx_pool.to_eth_addr,
128tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce,
129tx_pool.state, tx_pool.signature, tx_pool.timestamp, tx_pool.rq_from_idx,
130tx_pool.rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount,
131tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type,
132fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f AS fee_usd, token.usd_update
133FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
134
135// GetTx return the specified Tx
136func (l2db *L2DB) GetTx(txID common.TxID) (*PoolL2TxRead, error) {
137 tx := new(PoolL2TxRead)
138 return tx, meddler.QueryRow(
139 l2db.db, tx,
140 selectPoolTxRead+"WHERE tx_id = $1;",
141 txID,
142 )
143}
144
145// GetPendingTxs return all the pending txs of the L2DB, that have a non NULL AbsoluteFee
146func (l2db *L2DB) GetPendingTxs() ([]common.PoolL2Tx, error) {
147 var txs []*common.PoolL2Tx
148 err := meddler.QueryAll(
149 l2db.db, &txs,
150 selectPoolTxCommon+"WHERE state = $1",
151 common.PoolL2TxStatePending,
152 )
153 return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), err
154}
155
156// StartForging updates the state of the transactions that will begin the forging process.
157// The state of the txs referenced by txIDs will be changed from Pending -> Forging
158func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
159 query, args, err := sqlx.In(
160 `UPDATE tx_pool
161 SET state = ?, batch_num = ?
162 WHERE state = ? AND tx_id IN (?);`,
163 common.PoolL2TxStateForging,
164 batchNum,
165 common.PoolL2TxStatePending,
166 txIDs,
167 )
168 if err != nil {
169 return err
170 }
171 query = l2db.db.Rebind(query)
172 _, err = l2db.db.Exec(query, args...)
173 return err
174}
175
176// DoneForging updates the state of the transactions that have been forged
177// so the state of the txs referenced by txIDs will be changed from Forging -> Forged
178func (l2db *L2DB) DoneForging(txIDs []common.TxID, batchNum common.BatchNum) error {
179 query, args, err := sqlx.In(
180 `UPDATE tx_pool
181 SET state = ?, batch_num = ?
182 WHERE state = ? AND tx_id IN (?);`,
183 common.PoolL2TxStateForged,
184 batchNum,
185 common.PoolL2TxStateForging,
186 txIDs,
187 )
188 if err != nil {
189 return err
190 }
191 query = l2db.db.Rebind(query)
192 _, err = l2db.db.Exec(query, args...)
193 return err
194}
195
196// InvalidateTxs updates the state of the transactions that are invalid.
197// The state of the txs referenced by txIDs will be changed from * -> Invalid
198func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID, batchNum common.BatchNum) error {
199 query, args, err := sqlx.In(
200 `UPDATE tx_pool
201 SET state = ?, batch_num = ?
202 WHERE tx_id IN (?);`,
203 common.PoolL2TxStateInvalid,
204 batchNum,
205 txIDs,
206 )
207 if err != nil {
208 return err
209 }
210 query = l2db.db.Rebind(query)
211 _, err = l2db.db.Exec(query, args...)
212 return err
213}
214
215// CheckNonces invalidate txs with nonces that are smaller or equal than their respective accounts nonces.
216// The state of the affected txs will be changed from Pending -> Invalid
217func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account, batchNum common.BatchNum) (err error) {
218 txn, err := l2db.db.Begin()
219 if err != nil {
220 return err
221 }
222 defer func() {
223 // Rollback the transaction if there was an error.
224 if err != nil {
225 errRollback := txn.Rollback()
226 if errRollback != nil {
227 log.Errorw("Rollback", "err", errRollback)
228 }
229 }
230 }()
231 for i := 0; i < len(updatedAccounts); i++ {
232 _, err = txn.Exec(
233 `UPDATE tx_pool
234 SET state = $1, batch_num = $2
235 WHERE state = $3 AND from_idx = $4 AND nonce <= $5;`,
236 common.PoolL2TxStateInvalid,
237 batchNum,
238 common.PoolL2TxStatePending,
239 updatedAccounts[i].Idx,
240 updatedAccounts[i].Nonce,
241 )
242 if err != nil {
243 return err
244 }
245 }
246 return txn.Commit()
247}
248
249// Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
250// The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
251func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
252 _, err := l2db.db.Exec(
253 `UPDATE tx_pool SET batch_num = NULL, state = $1
254 WHERE (state = $2 OR state = $3) AND batch_num > $4`,
255 common.PoolL2TxStatePending,
256 common.PoolL2TxStateForged,
257 common.PoolL2TxStateInvalid,
258 lastValidBatch,
259 )
260 return err
261}
262
263// Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
264// it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded
265func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
266 txn, err := l2db.db.Begin()
267 if err != nil {
268 return err
269 }
270 defer func() {
271 // Rollback the transaction if there was an error.
272 if err != nil {
273 errRollback := txn.Rollback()
274 if errRollback != nil {
275 log.Errorw("Rollback", "err", errRollback)
276 }
277 }
278 }()
279 // Delete pending txs that have been in the pool after the TTL if maxTxs is reached
280 now := time.Now().UTC().Unix()
281 _, err = txn.Exec(
282 `DELETE FROM tx_pool WHERE (SELECT count(*) FROM tx_pool) > $1 AND timestamp < $2`,
283 l2db.maxTxs,
284 time.Unix(now-int64(l2db.ttl.Seconds()), 0),
285 )
286 if err != nil {
287 return err
288 }
289 // Delete txs that have been marked as forged / invalid after the safety period
290 _, err = txn.Exec(
291 `DELETE FROM tx_pool
292 WHERE batch_num < $1 AND (state = $2 OR state = $3)`,
293 currentBatchNum-l2db.safetyPeriod,
294 common.PoolL2TxStateForged,
295 common.PoolL2TxStateInvalid,
296 )
297 if err != nil {
298 return err
299 }
300 return txn.Commit()
301}