arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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// selectPoolTxAPI select part of queries to get PoolL2TxRead
118const selectPoolTxAPI = `SELECT  tx_pool.tx_id, hez_idx(tx_pool.from_idx, token.symbol) AS from_idx, tx_pool.from_eth_addr, 
119tx_pool.from_bjj, hez_idx(tx_pool.to_idx, token.symbol) AS to_idx, tx_pool.to_eth_addr, 
120tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce, 
121tx_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, 
122hez_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, 
123tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type, 
124token.item_id AS token_item_id, token.eth_block_num, token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update 
125FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
126
127// selectPoolTxCommon select part of queries to get common.PoolL2Tx
128const selectPoolTxCommon = `SELECT  tx_pool.tx_id, from_idx, to_idx, tx_pool.to_eth_addr, 
129tx_pool.to_bjj, tx_pool.token_id, tx_pool.amount, tx_pool.fee, tx_pool.nonce, 
130tx_pool.state, tx_pool.signature, tx_pool.timestamp, rq_from_idx, 
131rq_to_idx, tx_pool.rq_to_eth_addr, tx_pool.rq_to_bjj, tx_pool.rq_token_id, tx_pool.rq_amount, 
132tx_pool.rq_fee, tx_pool.rq_nonce, tx_pool.tx_type, 
133fee_percentage(tx_pool.fee::NUMERIC) * token.usd * tx_pool.amount_f AS fee_usd, token.usd_update  
134FROM tx_pool INNER JOIN token ON tx_pool.token_id = token.token_id `
135
136// GetTx  return the specified Tx in common.PoolL2Tx format
137func (l2db *L2DB) GetTx(txID common.TxID) (*common.PoolL2Tx, error) {
138	tx := new(common.PoolL2Tx)
139	return tx, meddler.QueryRow(
140		l2db.db, tx,
141		selectPoolTxCommon+"WHERE tx_id = $1;",
142		txID,
143	)
144}
145
146// GetTxAPI return the specified Tx in PoolTxAPI format
147func (l2db *L2DB) GetTxAPI(txID common.TxID) (*PoolTxAPI, error) {
148	tx := new(PoolTxAPI)
149	return tx, meddler.QueryRow(
150		l2db.db, tx,
151		selectPoolTxAPI+"WHERE tx_id = $1;",
152		txID,
153	)
154}
155
156// GetPendingTxs return all the pending txs of the L2DB, that have a non NULL AbsoluteFee
157func (l2db *L2DB) GetPendingTxs() ([]common.PoolL2Tx, error) {
158	var txs []*common.PoolL2Tx
159	err := meddler.QueryAll(
160		l2db.db, &txs,
161		selectPoolTxCommon+"WHERE state = $1",
162		common.PoolL2TxStatePending,
163	)
164	return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), err
165}
166
167// StartForging updates the state of the transactions that will begin the forging process.
168// The state of the txs referenced by txIDs will be changed from Pending -> Forging
169func (l2db *L2DB) StartForging(txIDs []common.TxID, batchNum common.BatchNum) error {
170	query, args, err := sqlx.In(
171		`UPDATE tx_pool
172		SET state = ?, batch_num = ?
173		WHERE state = ? AND tx_id IN (?);`,
174		common.PoolL2TxStateForging,
175		batchNum,
176		common.PoolL2TxStatePending,
177		txIDs,
178	)
179	if err != nil {
180		return err
181	}
182	query = l2db.db.Rebind(query)
183	_, err = l2db.db.Exec(query, args...)
184	return err
185}
186
187// DoneForging updates the state of the transactions that have been forged
188// so the state of the txs referenced by txIDs will be changed from Forging -> Forged
189func (l2db *L2DB) DoneForging(txIDs []common.TxID, batchNum common.BatchNum) error {
190	query, args, err := sqlx.In(
191		`UPDATE tx_pool
192		SET state = ?, batch_num = ?
193		WHERE state = ? AND tx_id IN (?);`,
194		common.PoolL2TxStateForged,
195		batchNum,
196		common.PoolL2TxStateForging,
197		txIDs,
198	)
199	if err != nil {
200		return err
201	}
202	query = l2db.db.Rebind(query)
203	_, err = l2db.db.Exec(query, args...)
204	return err
205}
206
207// InvalidateTxs updates the state of the transactions that are invalid.
208// The state of the txs referenced by txIDs will be changed from * -> Invalid
209func (l2db *L2DB) InvalidateTxs(txIDs []common.TxID, batchNum common.BatchNum) error {
210	query, args, err := sqlx.In(
211		`UPDATE tx_pool
212		SET state = ?, batch_num = ?
213		WHERE tx_id IN (?);`,
214		common.PoolL2TxStateInvalid,
215		batchNum,
216		txIDs,
217	)
218	if err != nil {
219		return err
220	}
221	query = l2db.db.Rebind(query)
222	_, err = l2db.db.Exec(query, args...)
223	return err
224}
225
226// CheckNonces invalidate txs with nonces that are smaller or equal than their respective accounts nonces.
227// The state of the affected txs will be changed from Pending -> Invalid
228func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account, batchNum common.BatchNum) (err error) {
229	txn, err := l2db.db.Begin()
230	if err != nil {
231		return err
232	}
233	defer func() {
234		// Rollback the transaction if there was an error.
235		if err != nil {
236			errRollback := txn.Rollback()
237			if errRollback != nil {
238				log.Errorw("Rollback", "err", errRollback)
239			}
240		}
241	}()
242	for i := 0; i < len(updatedAccounts); i++ {
243		_, err = txn.Exec(
244			`UPDATE tx_pool
245			SET state = $1, batch_num = $2
246			WHERE state = $3 AND from_idx = $4 AND nonce <= $5;`,
247			common.PoolL2TxStateInvalid,
248			batchNum,
249			common.PoolL2TxStatePending,
250			updatedAccounts[i].Idx,
251			updatedAccounts[i].Nonce,
252		)
253		if err != nil {
254			return err
255		}
256	}
257	return txn.Commit()
258}
259
260// Reorg updates the state of txs that were updated in a batch that has been discarted due to a blockchain reorg.
261// The state of the affected txs can change form Forged -> Pending or from Invalid -> Pending
262func (l2db *L2DB) Reorg(lastValidBatch common.BatchNum) error {
263	_, err := l2db.db.Exec(
264		`UPDATE tx_pool SET batch_num = NULL, state = $1 
265		WHERE (state = $2 OR state = $3) AND batch_num > $4`,
266		common.PoolL2TxStatePending,
267		common.PoolL2TxStateForged,
268		common.PoolL2TxStateInvalid,
269		lastValidBatch,
270	)
271	return err
272}
273
274// Purge deletes transactions that have been forged or marked as invalid for longer than the safety period
275// it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded
276func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) {
277	txn, err := l2db.db.Begin()
278	if err != nil {
279		return err
280	}
281	defer func() {
282		// Rollback the transaction if there was an error.
283		if err != nil {
284			errRollback := txn.Rollback()
285			if errRollback != nil {
286				log.Errorw("Rollback", "err", errRollback)
287			}
288		}
289	}()
290	// Delete pending txs that have been in the pool after the TTL if maxTxs is reached
291	now := time.Now().UTC().Unix()
292	_, err = txn.Exec(
293		`DELETE FROM tx_pool WHERE (SELECT count(*) FROM tx_pool) > $1 AND timestamp < $2`,
294		l2db.maxTxs,
295		time.Unix(now-int64(l2db.ttl.Seconds()), 0),
296	)
297	if err != nil {
298		return err
299	}
300	// Delete txs that have been marked as forged / invalid after the safety period
301	_, err = txn.Exec(
302		`DELETE FROM tx_pool 
303		WHERE batch_num < $1 AND (state = $2 OR state = $3)`,
304		currentBatchNum-l2db.safetyPeriod,
305		common.PoolL2TxStateForged,
306		common.PoolL2TxStateInvalid,
307	)
308	if err != nil {
309		return err
310	}
311	return txn.Commit()
312}