arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/txselector/txselector.go
txselector/txselector.goRaw
  1package txselector
  2
  3// current: very simple version of TxSelector
  4
  5import (
  6	"fmt"
  7	"math/big"
  8	"sort"
  9
 10	ethCommon "github.com/ethereum/go-ethereum/common"
 11	"github.com/hermeznetwork/hermez-node/common"
 12	"github.com/hermeznetwork/hermez-node/db/kvdb"
 13	"github.com/hermeznetwork/hermez-node/db/l2db"
 14	"github.com/hermeznetwork/hermez-node/db/statedb"
 15	"github.com/hermeznetwork/hermez-node/log"
 16	"github.com/hermeznetwork/hermez-node/txprocessor"
 17	"github.com/hermeznetwork/tracerr"
 18	"github.com/iden3/go-iden3-crypto/babyjub"
 19)
 20
 21// CoordAccount contains the data of the Coordinator account, that will be used
 22// to create new transactions of CreateAccountDeposit type to add new TokenID
 23// accounts for the Coordinator to receive the fees.
 24type CoordAccount struct {
 25	Addr                ethCommon.Address
 26	BJJ                 babyjub.PublicKeyComp
 27	AccountCreationAuth []byte // signature in byte array format
 28}
 29
 30// TxSelector implements all the functionalities to select the txs for the next
 31// batch
 32type TxSelector struct {
 33	l2db            *l2db.L2DB
 34	localAccountsDB *statedb.LocalStateDB
 35
 36	coordAccount *CoordAccount
 37}
 38
 39// NewTxSelector returns a *TxSelector
 40func NewTxSelector(coordAccount *CoordAccount, dbpath string,
 41	synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
 42	localAccountsDB, err := statedb.NewLocalStateDB(
 43		statedb.Config{
 44			Path:    dbpath,
 45			Keep:    kvdb.DefaultKeep,
 46			Type:    statedb.TypeTxSelector,
 47			NLevels: 0,
 48		},
 49		synchronizerStateDB) // without merkletree
 50	if err != nil {
 51		return nil, tracerr.Wrap(err)
 52	}
 53
 54	return &TxSelector{
 55		l2db:            l2,
 56		localAccountsDB: localAccountsDB,
 57		coordAccount:    coordAccount,
 58	}, nil
 59}
 60
 61// LocalAccountsDB returns the LocalStateDB of the TxSelector
 62func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
 63	return txsel.localAccountsDB
 64}
 65
 66// Reset tells the TxSelector to get it's internal AccountsDB
 67// from the required `batchNum`
 68func (txsel *TxSelector) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
 69	return tracerr.Wrap(txsel.localAccountsDB.Reset(batchNum, fromSynchronizer))
 70}
 71
 72func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
 73	return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr,
 74		txsel.coordAccount.BJJ, tokenID)
 75}
 76
 77// coordAccountForTokenID creates a new L1CoordinatorTx to create a new
 78// Coordinator account for the given TokenID in the case that the account does
 79// not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
 80// account in the given array of L1CoordinatorTxs. If a new Coordinator account
 81// needs to be created, a new L1CoordinatorTx will be returned from this
 82// function. After calling this method, if the l1CoordinatorTx is added to the
 83// selection, positionL1 must be increased 1.
 84func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
 85	tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
 86	// check if CoordinatorAccount for TokenID is already pending to create
 87	if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
 88		txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
 89		return nil, positionL1, nil
 90	}
 91	_, err := txsel.getCoordIdx(tokenID)
 92	if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
 93		// create L1CoordinatorTx to create new CoordAccount for
 94		// TokenID
 95		l1CoordinatorTx := common.L1Tx{
 96			Position:      positionL1,
 97			UserOrigin:    false,
 98			FromEthAddr:   txsel.coordAccount.Addr,
 99			FromBJJ:       txsel.coordAccount.BJJ,
100			TokenID:       tokenID,
101			Amount:        big.NewInt(0),
102			DepositAmount: big.NewInt(0),
103			Type:          common.TxTypeCreateAccountDeposit,
104		}
105
106		return &l1CoordinatorTx, positionL1, nil
107	}
108	if err != nil {
109		return nil, positionL1, tracerr.Wrap(err)
110	}
111	// CoordAccount for TokenID already exists
112	return nil, positionL1, nil
113}
114
115// GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
116// for the next batch, from the L2DB pool.
117// It returns: the CoordinatorIdxs used to receive the fees of the selected
118// L2Txs. An array of bytearrays with the signatures of the
119// AccountCreationAuthorization of the accounts of the users created by the
120// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
121// but there is a transactions to them and the authorization of account
122// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
123// included in the next batch.
124func (txsel *TxSelector) GetL2TxSelection(selectionConfig txprocessor.Config) ([]common.Idx,
125	[][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
126	metricGetL2TxSelection.Inc()
127	coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs,
128		discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, []common.L1Tx{})
129	return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs,
130		discardedL2Txs, tracerr.Wrap(err)
131}
132
133// GetL1L2TxSelection returns the selection of L1 + L2 txs.
134// It returns: the CoordinatorIdxs used to receive the fees of the selected
135// L2Txs. An array of bytearrays with the signatures of the
136// AccountCreationAuthorization of the accounts of the users created by the
137// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
138// but there is a transactions to them and the authorization of account
139// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
140// included in the next batch.
141func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig txprocessor.Config,
142	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
143	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
144	metricGetL1L2TxSelection.Inc()
145	coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
146		discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, l1UserTxs)
147	return coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
148		discardedL2Txs, tracerr.Wrap(err)
149}
150
151// getL1L2TxSelection returns the selection of L1 + L2 txs.
152// It returns: the CoordinatorIdxs used to receive the fees of the selected
153// L2Txs. An array of bytearrays with the signatures of the
154// AccountCreationAuthorization of the accounts of the users created by the
155// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
156// but there is a transactions to them and the authorization of account
157// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
158// included in the next batch.
159func (txsel *TxSelector) getL1L2TxSelection(selectionConfig txprocessor.Config,
160	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
161	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
162	// WIP.0: the TxSelector is not optimized and will need a redesign. The
163	// current version is implemented in order to have a functional
164	// implementation that can be used ASAP.
165
166	// Steps of this method:
167	// - ProcessL1Txs (User txs)
168	// - getPendingTxs (forgable directly with current state & not forgable
169	// yet)
170	// - split between l2TxsForgable & l2TxsNonForgable, where:
171	// 	- l2TxsForgable are the txs that are directly forgable with the
172	// 	current state
173	// 	- l2TxsNonForgable are the txs that are not directly forgable
174	// 	with the current state, but that may be forgable once the
175	// 	l2TxsForgable ones are processed
176	// - for l2TxsForgable, and if needed, for l2TxsNonForgable:
177	// 	- sort by Fee & Nonce
178	// 	- loop over l2Txs (txsel.processL2Txs)
179	// 	        - Fill tx.TokenID tx.Nonce
180	// 	        - Check enough Balance on sender
181	// 	        - Check Nonce
182	// 	        - Create CoordAccount L1CoordTx for TokenID if needed
183	// 	                - & ProcessL1Tx of L1CoordTx
184	// 	        - Check validity of receiver Account for ToEthAddr / ToBJJ
185	// 	        - Create UserAccount L1CoordTx if needed (and possible)
186	// 	        - If everything is fine, store l2Tx to validTxs & update NoncesMap
187	// - Prepare coordIdxsMap & AccumulatedFees
188	// - Distribute AccumulatedFees to CoordIdxs
189	// - MakeCheckpoint
190
191	txselStateDB := txsel.localAccountsDB.StateDB
192	tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig)
193	tp.AccumulatedFees = make(map[common.Idx]*big.Int)
194
195	// Process L1UserTxs
196	for i := 0; i < len(l1UserTxs); i++ {
197		// assumption: l1usertx are sorted by L1Tx.Position
198		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
199		if err != nil {
200			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
201		}
202	}
203
204	l2TxsFromDB, err := txsel.l2db.GetPendingTxs()
205	if err != nil {
206		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
207	}
208	l2TxsForgable, l2TxsNonForgable := splitL2ForgableAndNonForgable(tp, l2TxsFromDB)
209
210	// in case that length of l2TxsForgable is 0, no need to continue, there
211	// is no L2Txs to forge at all
212	if len(l2TxsForgable) == 0 {
213		var discardedL2Txs []common.PoolL2Tx
214		for i := 0; i < len(l2TxsNonForgable); i++ {
215			l2TxsNonForgable[i].Info =
216				"Tx not selected due impossibility to be forged with the current state"
217			discardedL2Txs = append(discardedL2Txs, l2TxsNonForgable[i])
218		}
219		err = tp.StateDB().MakeCheckpoint()
220		if err != nil {
221			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
222		}
223
224		metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
225		metricSelectedL1CoordinatorTxs.Set(0)
226		metricSelectedL2Txs.Set(0)
227		metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
228		return nil, nil, l1UserTxs, nil, nil, discardedL2Txs, nil
229	}
230
231	var accAuths [][]byte
232	var l1CoordinatorTxs []common.L1Tx
233	var validTxs, discardedL2Txs []common.PoolL2Tx
234	l2TxsForgable = sortL2Txs(l2TxsForgable)
235	accAuths, l1CoordinatorTxs, validTxs, discardedL2Txs, err =
236		txsel.processL2Txs(tp, selectionConfig, len(l1UserTxs),
237			l2TxsForgable, validTxs, discardedL2Txs)
238	if err != nil {
239		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
240	}
241
242	// if there is space for more txs get also the NonForgable txs, that may
243	// be unblocked once the Forgable ones are processed
244	if len(validTxs) < int(selectionConfig.MaxTx)-(len(l1UserTxs)+len(l1CoordinatorTxs)) {
245		l2TxsNonForgable = sortL2Txs(l2TxsNonForgable)
246		var accAuths2 [][]byte
247		var l1CoordinatorTxs2 []common.L1Tx
248		accAuths2, l1CoordinatorTxs2, validTxs, discardedL2Txs, err =
249			txsel.processL2Txs(tp, selectionConfig,
250				len(l1UserTxs)+len(l1CoordinatorTxs), l2TxsNonForgable,
251				validTxs, discardedL2Txs)
252		if err != nil {
253			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
254		}
255
256		accAuths = append(accAuths, accAuths2...)
257		l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTxs2...)
258	} else {
259		// if there is no space for NonForgable txs, put them at the
260		// discardedL2Txs array
261		for i := 0; i < len(l2TxsNonForgable); i++ {
262			l2TxsNonForgable[i].Info =
263				"Tx not selected due not available slots for L2Txs"
264			discardedL2Txs = append(discardedL2Txs, l2TxsNonForgable[i])
265		}
266	}
267
268	// get CoordIdxsMap for the TokenIDs
269	coordIdxsMap := make(map[common.TokenID]common.Idx)
270	for i := 0; i < len(validTxs); i++ {
271		// get TokenID from tx.Sender
272		accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
273		if err != nil {
274			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
275		}
276		tokenID := accSender.TokenID
277
278		coordIdx, err := txsel.getCoordIdx(tokenID)
279		if err != nil {
280			// if err is db.ErrNotFound, should not happen, as all
281			// the validTxs.TokenID should have a CoordinatorIdx
282			// created in the DB at this point
283			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
284		}
285		coordIdxsMap[tokenID] = coordIdx
286	}
287
288	var coordIdxs []common.Idx
289	for _, idx := range coordIdxsMap {
290		coordIdxs = append(coordIdxs, idx)
291	}
292	// sort CoordIdxs
293	sort.SliceStable(coordIdxs, func(i, j int) bool {
294		return coordIdxs[i] < coordIdxs[j]
295	})
296
297	// distribute the AccumulatedFees from the processed L2Txs into the
298	// Coordinator Idxs
299	for idx, accumulatedFee := range tp.AccumulatedFees {
300		cmp := accumulatedFee.Cmp(big.NewInt(0))
301		if cmp == 1 { // accumulatedFee>0
302			// send the fee to the Idx of the Coordinator for the TokenID
303			accCoord, err := txsel.localAccountsDB.GetAccount(idx)
304			if err != nil {
305				log.Errorw("Can not distribute accumulated fees to coordinator "+
306					"account: No coord Idx to receive fee", "idx", idx)
307				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
308			}
309			accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
310			_, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
311			if err != nil {
312				log.Error(err)
313				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
314			}
315		}
316	}
317
318	err = tp.StateDB().MakeCheckpoint()
319	if err != nil {
320		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
321	}
322
323	metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
324	metricSelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
325	metricSelectedL2Txs.Set(float64(len(validTxs)))
326	metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
327
328	return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
329}
330
331func (txsel *TxSelector) processL2Txs(tp *txprocessor.TxProcessor,
332	selectionConfig txprocessor.Config, nL1Txs int, l2Txs, validTxs, discardedL2Txs []common.PoolL2Tx) (
333	[][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
334	var l1CoordinatorTxs []common.L1Tx
335	positionL1 := nL1Txs
336	var accAuths [][]byte
337	// Iterate over l2Txs
338	// - check Nonces
339	// - check enough Balance for the Amount+Fee
340	// - if needed, create new L1CoordinatorTxs for unexisting ToIdx
341	// 	- keep used accAuths
342	// - put the valid txs into validTxs array
343	for i := 0; i < len(l2Txs); i++ {
344		// Check if there is space for more L2Txs in the selection
345		maxL2Txs := int(selectionConfig.MaxTx) - nL1Txs - len(l1CoordinatorTxs)
346		if len(validTxs) >= maxL2Txs {
347			// no more available slots for L2Txs, so mark this tx
348			// but also the rest of remaining txs as discarded
349			for j := i; j < len(l2Txs); j++ {
350				l2Txs[j].Info =
351					"Tx not selected due not available slots for L2Txs"
352				discardedL2Txs = append(discardedL2Txs, l2Txs[j])
353			}
354			break
355		}
356
357		// get Nonce & TokenID from the Account by l2Tx.FromIdx
358		accSender, err := tp.StateDB().GetAccount(l2Txs[i].FromIdx)
359		if err != nil {
360			return nil, nil, nil, nil, tracerr.Wrap(err)
361		}
362		l2Txs[i].TokenID = accSender.TokenID
363
364		// Check enough Balance on sender
365		enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
366		if !enoughBalance {
367			// not valid Amount with current Balance. Discard L2Tx,
368			// and update Info parameter of the tx, and add it to
369			// the discardedTxs array
370			l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not enough Balance at the sender. "+
371				"Current sender account Balance: %s, Amount+Fee: %s",
372				balance.String(), feeAndAmount.String())
373			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
374			continue
375		}
376
377		// Check if Nonce is correct
378		if l2Txs[i].Nonce != accSender.Nonce {
379			// not valid Nonce at tx. Discard L2Tx, and update Info
380			// parameter of the tx, and add it to the discardedTxs
381			// array
382			l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not current Nonce. "+
383				"Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, accSender.Nonce)
384			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
385			continue
386		}
387
388		// if TokenID does not exist yet, create new L1CoordinatorTx to
389		// create the CoordinatorAccount for that TokenID, to receive
390		// the fees. Only in the case that there does not exist yet a
391		// pending L1CoordinatorTx to create the account for the
392		// Coordinator for that TokenID
393		var newL1CoordTx *common.L1Tx
394		newL1CoordTx, positionL1, err =
395			txsel.coordAccountForTokenID(l1CoordinatorTxs,
396				accSender.TokenID, positionL1)
397		if err != nil {
398			return nil, nil, nil, nil, tracerr.Wrap(err)
399		}
400		if newL1CoordTx != nil {
401			// if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
402			// for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
403			if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1Txs ||
404				len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1Txs {
405				// discard L2Tx, and update Info parameter of
406				// the tx, and add it to the discardedTxs array
407				l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
408					"L1CoordinatorTx and there is not enough space for L1Coordinator"
409				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
410				continue
411			}
412			// increase positionL1
413			positionL1++
414			l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
415			accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
416
417			// process the L1CoordTx
418			_, _, _, _, err := tp.ProcessL1Tx(nil, newL1CoordTx)
419			if err != nil {
420				return nil, nil, nil, nil, tracerr.Wrap(err)
421			}
422		}
423
424		// If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
425		// if so, tx is used.  If tx.ToIdx==0, for an L2Tx will be the
426		// case of TxToEthAddr or TxToBJJ, check if
427		// tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
428		// used; if not, check if tx.ToEthAddr is in
429		// AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
430		// of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
431		// Exit type and is used.
432		if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
433			validL2Tx, l1CoordinatorTx, accAuth, err :=
434				txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
435					nL1Txs, l1CoordinatorTxs, positionL1, l2Txs[i])
436			if err != nil {
437				log.Debugw("txsel.processTxToEthAddrBJJ", "err", err)
438				// Discard L2Tx, and update Info parameter of
439				// the tx, and add it to the discardedTxs array
440				l2Txs[i].Info = fmt.Sprintf("Tx not selected (in processTxToEthAddrBJJ) due to %s",
441					err.Error())
442				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
443				continue
444			}
445			// if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
446			// for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
447			if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1Txs ||
448				len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1Txs {
449				// discard L2Tx, and update Info parameter of
450				// the tx, and add it to the discardedTxs array
451				l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
452					"L1CoordinatorTx and there is not enough space for L1Coordinator"
453				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
454				continue
455			}
456
457			if l1CoordinatorTx != nil && validL2Tx != nil {
458				// If ToEthAddr == 0xff.. this means that we
459				// are handling a TransferToBJJ, which doesn't
460				// require an authorization because it doesn't
461				// contain a valid ethereum address.
462				// Otherwise only create the account if we have
463				// the corresponding authorization
464				if validL2Tx.ToEthAddr == common.FFAddr {
465					accAuths = append(accAuths, common.EmptyEthSignature)
466					l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
467					positionL1++
468				} else if accAuth != nil {
469					accAuths = append(accAuths, accAuth.Signature)
470					l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
471					positionL1++
472				}
473
474				// process the L1CoordTx
475				_, _, _, _, err := tp.ProcessL1Tx(nil, l1CoordinatorTx)
476				if err != nil {
477					return nil, nil, nil, nil, tracerr.Wrap(err)
478				}
479			}
480			if validL2Tx == nil {
481				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
482				continue
483			}
484		} else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
485			receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
486			if err != nil {
487				// tx not valid
488				log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
489					"ToIdx", l2Txs[i].ToIdx)
490				// Discard L2Tx, and update Info parameter of
491				// the tx, and add it to the discardedTxs array
492				l2Txs[i].Info = fmt.Sprintf("Tx not selected due to tx.ToIdx not found in StateDB. "+
493					"ToIdx: %d", l2Txs[i].ToIdx)
494				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
495				continue
496			}
497			if l2Txs[i].ToEthAddr != common.EmptyAddr {
498				if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
499					log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
500						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
501						l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
502					// Discard L2Tx, and update Info
503					// parameter of the tx, and add it to
504					// the discardedTxs array
505					l2Txs[i].Info = fmt.Sprintf("Tx not selected because ToEthAddr "+
506						"does not correspond to the Account.EthAddr. "+
507						"tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
508						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
509					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
510					continue
511				}
512			}
513			if l2Txs[i].ToBJJ != common.EmptyBJJComp {
514				if l2Txs[i].ToBJJ != receiverAcc.BJJ {
515					log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
516						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
517						"account.BJJ", receiverAcc.BJJ)
518					// Discard L2Tx, and update Info
519					// parameter of the tx, and add it to
520					// the discardedTxs array
521					l2Txs[i].Info = fmt.Sprintf("Tx not selected because tx.ToBJJ "+
522						"does not correspond to the Account.BJJ. "+
523						"tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
524						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
525					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
526					continue
527				}
528			}
529		}
530
531		// get CoordIdxsMap for the TokenID of the current l2Txs[i]
532		// get TokenID from tx.Sender account
533		tokenID := accSender.TokenID
534		coordIdx, err := txsel.getCoordIdx(tokenID)
535		if err != nil {
536			// if err is db.ErrNotFound, should not happen, as all
537			// the validTxs.TokenID should have a CoordinatorIdx
538			// created in the DB at this point
539			return nil, nil, nil, nil,
540				tracerr.Wrap(fmt.Errorf("Could not get CoordIdx for TokenID=%d, "+
541					"due: %s", tokenID, err))
542		}
543		// prepare temp coordIdxsMap & AccumulatedFees for the call to
544		// ProcessL2Tx
545		coordIdxsMap := map[common.TokenID]common.Idx{tokenID: coordIdx}
546		// tp.AccumulatedFees = make(map[common.Idx]*big.Int)
547		if _, ok := tp.AccumulatedFees[coordIdx]; !ok {
548			tp.AccumulatedFees[coordIdx] = big.NewInt(0)
549		}
550
551		_, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
552		if err != nil {
553			log.Debugw("txselector.getL1L2TxSelection at ProcessL2Tx", "err", err)
554			// Discard L2Tx, and update Info parameter of the tx,
555			// and add it to the discardedTxs array
556			l2Txs[i].Info = fmt.Sprintf("Tx not selected (in ProcessL2Tx) due to %s",
557				err.Error())
558			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
559			continue
560		}
561
562		validTxs = append(validTxs, l2Txs[i])
563	} // after this loop, no checks to discard txs should be done
564
565	return accAuths, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
566}
567
568// processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
569// ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
570// does not have an account yet, a new L1CoordinatorTx of type
571// CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
572// l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
573// array.
574func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
575	selectionConfig txprocessor.Config, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
576	positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
577	*common.AccountCreationAuth, error) {
578	// if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
579	// previous L2Tx in the current process already created a
580	// L1CoordinatorTx of this type, in the DB there still seem that needs
581	// to create a new L1CoordinatorTx, but as is already created, the tx
582	// is valid
583	if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
584		return &l2Tx, nil, nil, nil
585	}
586
587	var l1CoordinatorTx *common.L1Tx
588	var accAuth *common.AccountCreationAuth
589	if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
590		// case: ToEthAddr != 0x00 neither 0xff
591		if l2Tx.ToBJJ != common.EmptyBJJComp {
592			// case: ToBJJ!=0:
593			// if idx exist for EthAddr&BJJ use it
594			_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
595				l2Tx.ToBJJ, l2Tx.TokenID)
596			if err == nil {
597				// account for ToEthAddr&ToBJJ already exist,
598				// there is no need to create a new one.
599				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
600				return &l2Tx, nil, nil, nil
601			}
602			// if not, check if AccountCreationAuth exist for that
603			// ToEthAddr
604			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
605			if err != nil {
606				// not found, l2Tx will not be added in the selection
607				return nil, nil, nil,
608					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found "+
609						"in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
610						l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
611			}
612			if accAuth.BJJ != l2Tx.ToBJJ {
613				// if AccountCreationAuth.BJJ is not the same
614				// than in the tx, tx is not accepted
615				return nil, nil, nil,
616					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, "+
617						"neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. "+
618						"ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
619						l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
620			}
621		} else {
622			// case: ToBJJ==0:
623			// if idx exist for EthAddr use it
624			_, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
625			if err == nil {
626				// account for ToEthAddr already exist,
627				// there is no need to create a new one.
628				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
629				return &l2Tx, nil, nil, nil
630			}
631			// if not, check if AccountCreationAuth exist for that ToEthAddr
632			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
633			if err != nil {
634				// not found, l2Tx will not be added in the selection
635				return nil, nil, nil,
636					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in "+
637						"StateDB, neither ToEthAddr found in "+
638						"AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
639						l2Tx.ToIdx, l2Tx.ToEthAddr))
640			}
641		}
642		// create L1CoordinatorTx for the accountCreation
643		l1CoordinatorTx = &common.L1Tx{
644			Position:      positionL1,
645			UserOrigin:    false,
646			FromEthAddr:   accAuth.EthAddr,
647			FromBJJ:       accAuth.BJJ,
648			TokenID:       l2Tx.TokenID,
649			Amount:        big.NewInt(0),
650			DepositAmount: big.NewInt(0),
651			Type:          common.TxTypeCreateAccountDeposit,
652		}
653	} else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
654		// if idx exist for EthAddr&BJJ use it
655		_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
656			l2Tx.TokenID)
657		if err == nil {
658			// account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
659			// there is no need to create a new one.
660			// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
661			return &l2Tx, nil, nil, nil
662		}
663		// if idx don't exist for EthAddr&BJJ, coordinator can create a
664		// new account without L1Authorization, as ToEthAddr==0xff
665		// create L1CoordinatorTx for the accountCreation
666		l1CoordinatorTx = &common.L1Tx{
667			Position:      positionL1,
668			UserOrigin:    false,
669			FromEthAddr:   l2Tx.ToEthAddr,
670			FromBJJ:       l2Tx.ToBJJ,
671			TokenID:       l2Tx.TokenID,
672			Amount:        big.NewInt(0),
673			DepositAmount: big.NewInt(0),
674			Type:          common.TxTypeCreateAccountDeposit,
675		}
676	}
677	// if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
678	// for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
679	if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1UserTxs ||
680		len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1UserTxs {
681		// L2Tx discarded
682		return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
683			"for L1CoordinatorTx to create a new account for receiver of L2Tx"))
684	}
685
686	return &l2Tx, l1CoordinatorTx, accAuth, nil
687}
688
689func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
690	addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
691	for i := 0; i < len(l1CoordinatorTxs); i++ {
692		if l1CoordinatorTxs[i].FromEthAddr == addr &&
693			l1CoordinatorTxs[i].TokenID == tokenID &&
694			l1CoordinatorTxs[i].FromBJJ == bjj {
695			return true
696		}
697	}
698	return false
699}
700
701// sortL2Txs sorts the PoolL2Txs by AbsoluteFee and then by Nonce
702func sortL2Txs(l2Txs []common.PoolL2Tx) []common.PoolL2Tx {
703	// Sort by absolute fee with SliceStable, so that txs with same
704	// AbsoluteFee are not rearranged and nonce order is kept in such case
705	sort.SliceStable(l2Txs, func(i, j int) bool {
706		return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
707	})
708
709	// sort l2Txs by Nonce. This can be done in many different ways, what
710	// is needed is to output the l2Txs where the Nonce of l2Txs for each
711	// Account is sorted, but the l2Txs can not be grouped by sender Account
712	// neither by Fee. This is because later on the Nonces will need to be
713	// sequential for the zkproof generation.
714	sort.Slice(l2Txs, func(i, j int) bool {
715		return l2Txs[i].Nonce < l2Txs[j].Nonce
716	})
717
718	return l2Txs
719}
720
721func splitL2ForgableAndNonForgable(tp *txprocessor.TxProcessor,
722	l2Txs []common.PoolL2Tx) ([]common.PoolL2Tx, []common.PoolL2Tx) {
723	var l2TxsForgable, l2TxsNonForgable []common.PoolL2Tx
724	for i := 0; i < len(l2Txs); i++ {
725		accSender, err := tp.StateDB().GetAccount(l2Txs[i].FromIdx)
726		if err != nil {
727			l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
728			continue
729		}
730
731		if l2Txs[i].Nonce != accSender.Nonce {
732			l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
733			continue
734		}
735		enoughBalance, _, _ := tp.CheckEnoughBalance(l2Txs[i])
736		if !enoughBalance {
737			l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
738			continue
739		}
740		l2TxsForgable = append(l2TxsForgable, l2Txs[i])
741	}
742	return l2TxsForgable, l2TxsNonForgable
743}