arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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	apiConnCon   *db.APIConnectionController
 29}
 30
 31// NewL2DB creates a L2DB.
 32// To create it, it's needed db connection, safety period expressed in batches,
 33// maxTxs that the DB should have and TTL (time to live) for pending txs.
 34func NewL2DB(
 35	db *sqlx.DB,
 36	safetyPeriod common.BatchNum,
 37	maxTxs uint32,
 38	TTL time.Duration,
 39	apiConnCon *db.APIConnectionController,
 40) *L2DB {
 41	return &L2DB{
 42		db:           db,
 43		safetyPeriod: safetyPeriod,
 44		ttl:          TTL,
 45		maxTxs:       maxTxs,
 46		apiConnCon:   apiConnCon,
 47	}
 48}
 49
 50// DB returns a pointer to the L2DB.db. This method should be used only for
 51// internal testing purposes.
 52func (l2db *L2DB) DB() *sqlx.DB {
 53	return l2db.db
 54}
 55
 56// AddAccountCreationAuth inserts an account creation authorization into the DB
 57func (l2db *L2DB) AddAccountCreationAuth(auth *common.AccountCreationAuth) error {
 58	_, err := l2db.db.Exec(
 59		`INSERT INTO account_creation_auth (eth_addr, bjj, signature)
 60		VALUES ($1, $2, $3);`,
 61		auth.EthAddr, auth.BJJ, auth.Signature,
 62	)
 63	return tracerr.Wrap(err)
 64}
 65
 66// GetAccountCreationAuth returns an account creation authorization from the DB
 67func (l2db *L2DB) GetAccountCreationAuth(addr ethCommon.Address) (*common.AccountCreationAuth, error) {
 68	auth := new(common.AccountCreationAuth)
 69	return auth, tracerr.Wrap(meddler.QueryRow(
 70		l2db.db, auth,
 71		"SELECT * FROM account_creation_auth WHERE eth_addr = $1;",
 72		addr,
 73	))
 74}
 75
 76// AddTx inserts a tx to the pool
 77func (l2db *L2DB) AddTx(tx *PoolL2TxWrite) error {
 78	row := l2db.db.QueryRow(
 79		"SELECT COUNT(*) FROM tx_pool WHERE state = $1;",
 80		common.PoolL2TxStatePending,
 81	)
 82	var totalTxs uint32
 83	if err := row.Scan(&totalTxs); err != nil {
 84		return tracerr.Wrap(err)
 85	}
 86	if totalTxs >= l2db.maxTxs {
 87		return tracerr.New(
 88			"The pool is at full capacity. More transactions are not accepted currently",
 89		)
 90	}
 91	return tracerr.Wrap(meddler.Insert(l2db.db, "tx_pool", tx))
 92}
 93
 94// UpdateTxsInfo updates the parameter Info of the pool transactions
 95func (l2db *L2DB) UpdateTxsInfo(txs []common.PoolL2Tx) error {
 96	if len(txs) == 0 {
 97		return nil
 98	}
 99	type txUpdate struct {
100		ID   common.TxID `db:"id"`
101		Info string      `db:"info"`
102	}
103	txUpdates := make([]txUpdate, len(txs))
104	for i := range txs {
105		txUpdates[i] = txUpdate{ID: txs[i].TxID, Info: txs[i].Info}
106	}
107	const query string = `
108		UPDATE tx_pool SET
109			info = tx_update.info
110		FROM (VALUES
111			(NULL::::BYTEA, NULL::::VARCHAR),
112			(:id, :info)
113		) as tx_update (id, info)
114		WHERE tx_pool.tx_id = tx_update.id;
115	`
116	if len(txUpdates) > 0 {
117		if _, err := sqlx.NamedExec(l2db.db, query, txUpdates); err != nil {
118			return tracerr.Wrap(err)
119		}
120	}
121
122	return nil
123}
124
125// AddTxTest inserts a tx into the L2DB. This is useful for test purposes,
126// but in production txs will only be inserted through the API
127func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
128	// transform tx from *common.PoolL2Tx to PoolL2TxWrite
129	insertTx := &PoolL2TxWrite{
130		TxID:      tx.TxID,
131		FromIdx:   tx.FromIdx,
132		TokenID:   tx.TokenID,
133		Amount:    tx.Amount,
134		Fee:       tx.Fee,
135		Nonce:     tx.Nonce,
136		State:     common.PoolL2TxStatePending,
137		Signature: tx.Signature,
138		RqAmount:  tx.RqAmount,
139		Type:      tx.Type,
140	}
141	if tx.ToIdx != 0 {
142		insertTx.ToIdx = &tx.ToIdx
143	}
144	nilAddr := ethCommon.BigToAddress(big.NewInt(0))
145	if tx.ToEthAddr != nilAddr {
146		insertTx.ToEthAddr = &tx.ToEthAddr
147	}
148	if tx.RqFromIdx != 0 {
149		insertTx.RqFromIdx = &tx.RqFromIdx
150	}
151	if tx.RqToIdx != 0 { // if true, all Rq... fields must be different to nil
152		insertTx.RqToIdx = &tx.RqToIdx
153		insertTx.RqTokenID = &tx.RqTokenID
154		insertTx.RqFee = &tx.RqFee
155		insertTx.RqNonce = &tx.RqNonce
156	}
157	if tx.RqToEthAddr != nilAddr {
158		insertTx.RqToEthAddr = &tx.RqToEthAddr
159	}
160	if tx.ToBJJ != common.EmptyBJJComp {
161		insertTx.ToBJJ = &tx.ToBJJ
162	}
163	if tx.RqToBJJ != common.EmptyBJJComp {
164		insertTx.RqToBJJ = &tx.RqToBJJ
165	}
166	f := new(big.Float).SetInt(tx.Amount)
167	amountF, _ := f.Float64()
168	insertTx.AmountFloat = amountF
169	// insert tx
170	return tracerr.Wrap(meddler.Insert(l2db.db, "tx_pool", insertTx))
171}
172
173// selectPoolTxCommon select part of queries to get common.PoolL2Tx
174const selectPoolTxCommon = `SELECT  tx_pool.tx_id, from_idx, to_idx, tx_pool.to_eth_addr, 
175tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce, 
176tx_pool.state, tx_pool.info, tx_pool.signature, tx_pool.timestamp, rq_from_idx, 
177rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount, 
178tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type, 
179fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f 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.db, 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.db, &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.db.Rebind(query)
222	_, err = l2db.db.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.db.Rebind(query)
245	_, err = l2db.db.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.db.Rebind(query)
267	_, err = l2db.db.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.db.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 doens't handle an extra
314	// individual argument.
315	query := fmt.Sprintf(invalidateOldNoncesQuery, batchNum)
316	if _, err := sqlx.NamedExec(l2db.db, 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.db.Exec(
326		`UPDATE tx_pool SET batch_num = NULL, state = $1 
327		WHERE (state = $2 OR state = $3) AND batch_num > $4`,
328		common.PoolL2TxStatePending,
329		common.PoolL2TxStateForged,
330		common.PoolL2TxStateInvalid,
331		lastValidBatch,
332	)
333	return tracerr.Wrap(err)
334}
335
336// Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
337// it also deletes pending txs that have been in the L2DB for longer than the ttl if maxTxs has been exceeded
338func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
339	now := time.Now().UTC().Unix()
340	_, err = l2db.db.Exec(
341		`DELETE FROM tx_pool WHERE (
342			batch_num < $1 AND (state = $2 OR state = $3)
343		) OR (
344			(SELECT count(*) FROM tx_pool WHERE state = $4) > $5 
345			AND timestamp < $6 AND state = $4
346		);`,
347		currentBatchNum-l2db.safetyPeriod,
348		common.PoolL2TxStateForged,
349		common.PoolL2TxStateInvalid,
350		common.PoolL2TxStatePending,
351		l2db.maxTxs,
352		time.Unix(now-int64(l2db.ttl.Seconds()), 0),
353	)
354	return tracerr.Wrap(err)
355}