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