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
151func (txsel *TxSelector) getL1L2TxSelection(selectionConfig txprocessor.Config,
152	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
153	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
154	// WIP.0: the TxSelector is not optimized and will need a redesign. The
155	// current version is implemented in order to have a functional
156	// implementation that can be used asap.
157	//
158	// WIP.1: this method uses a 'cherry-pick' of internal calls of the
159	// StateDB, a refactor of the StateDB to reorganize it internally is
160	// planned once the main functionallities are covered, with that
161	// refactor the TxSelector will be updated also.
162
163	// get pending l2-tx from tx-pool
164	l2TxsRaw, err := txsel.l2db.GetPendingTxs()
165	if err != nil {
166		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
167	}
168
169	txselStateDB := txsel.localAccountsDB.StateDB
170	tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig)
171
172	// Process L1UserTxs
173	for i := 0; i < len(l1UserTxs); i++ {
174		// assumption: l1usertx are sorted by L1Tx.Position
175		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
176		if err != nil {
177			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
178		}
179	}
180
181	var l1CoordinatorTxs []common.L1Tx
182	positionL1 := len(l1UserTxs)
183	var accAuths [][]byte
184
185	// Sort l2TxsRaw (cropping at MaxTx at this point).
186	// discardedL2Txs contains an array of the L2Txs that have not been
187	// selected in this Batch.
188	l2Txs0, discardedL2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.MaxTx)
189	for i := range discardedL2Txs {
190		discardedL2Txs[i].Info = "Tx not selected due to low absolute fee (does not fit inside the profitable set)"
191	}
192
193	noncesMap := make(map[common.Idx]common.Nonce)
194	var l2Txs []common.PoolL2Tx
195	// iterate over l2Txs
196	// - if tx.TokenID does not exist at CoordsIdxDB
197	// 	- create new L1CoordinatorTx creating a CoordAccount, for
198	// 	Coordinator to receive the fee of the new TokenID
199	for i := 0; i < len(l2Txs0); i++ {
200		accSender, err := tp.StateDB().GetAccount(l2Txs0[i].FromIdx)
201		if err != nil {
202			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
203		}
204		l2Txs0[i].TokenID = accSender.TokenID
205		// populate the noncesMap used at the next iteration
206		noncesMap[l2Txs0[i].FromIdx] = accSender.Nonce
207
208		// if TokenID does not exist yet, create new L1CoordinatorTx to
209		// create the CoordinatorAccount for that TokenID, to receive
210		// the fees. Only in the case that there does not exist yet a
211		// pending L1CoordinatorTx to create the account for the
212		// Coordinator for that TokenID
213		var newL1CoordTx *common.L1Tx
214		newL1CoordTx, positionL1, err =
215			txsel.coordAccountForTokenID(l1CoordinatorTxs,
216				accSender.TokenID, positionL1)
217		if err != nil {
218			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
219		}
220		if newL1CoordTx != nil {
221			// if there is no space for the L1CoordinatorTx, discard the L2Tx
222			if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-len(l1UserTxs) {
223				// discard L2Tx, and update Info parameter of
224				// the tx, and add it to the discardedTxs array
225				l2Txs0[i].Info = "Tx not selected because the L2Tx depends on a " +
226					"L1CoordinatorTx and there is not enough space for L1Coordinator"
227				discardedL2Txs = append(discardedL2Txs, l2Txs0[i])
228				continue
229			}
230			// increase positionL1
231			positionL1++
232			l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
233			accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
234		}
235		l2Txs = append(l2Txs, l2Txs0[i])
236	}
237
238	var validTxs []common.PoolL2Tx
239	// iterate over l2TxsRaw
240	// - check Nonces
241	// - check enough Balance for the Amount+Fee
242	// - if needed, create new L1CoordinatorTxs for unexisting ToIdx
243	// 	- keep used accAuths
244	// - put the valid txs into validTxs array
245	for i := 0; i < len(l2Txs); i++ {
246		enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
247		if !enoughBalance {
248			// not valid Amount with current Balance. Discard L2Tx,
249			// and update Info parameter of the tx, and add it to
250			// the discardedTxs array
251			l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not enough Balance at the sender. "+
252				"Current sender account Balance: %s, Amount+Fee: %s",
253				balance.String(), feeAndAmount.String())
254			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
255			continue
256		}
257		// check if Nonce is correct
258		nonce := noncesMap[l2Txs[i].FromIdx]
259		if l2Txs[i].Nonce != nonce {
260			// not valid Nonce at tx. Discard L2Tx, and update Info
261			// parameter of the tx, and add it to the discardedTxs
262			// array
263			l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not current Nonce. "+
264				"Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, nonce)
265			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
266			continue
267		}
268
269		// If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
270		// if so, tx is used.  If tx.ToIdx==0, for an L2Tx will be the
271		// case of TxToEthAddr or TxToBJJ, check if
272		// tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
273		// used; if not, check if tx.ToEthAddr is in
274		// AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
275		// of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
276		// Exit type and is used.
277		if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
278			validL2Tx, l1CoordinatorTx, accAuth, err :=
279				txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
280					len(l1UserTxs), l1CoordinatorTxs, positionL1, l2Txs[i])
281			if err != nil {
282				log.Debugw("txsel.processTxToEthAddrBJJ", "err", err)
283				// Discard L2Tx, and update Info parameter of
284				// the tx, and add it to the discardedTxs array
285				l2Txs[i].Info = fmt.Sprintf("Tx not selected (in processTxToEthAddrBJJ) due to %s",
286					err.Error())
287				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
288				continue
289			}
290			if l1CoordinatorTx != nil {
291				// If ToEthAddr == 0xff.. this means that we
292				// are handling a TransferToBJJ, which doesn't
293				// require an authorization because it doesn't
294				// contain a valid ethereum address.
295				// Otherwise only create the account if we have
296				// the corresponding authorization
297				if validL2Tx.ToEthAddr == common.FFAddr {
298					accAuths = append(accAuths, common.EmptyEthSignature)
299					l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
300					positionL1++
301				} else if accAuth != nil {
302					accAuths = append(accAuths, accAuth.Signature)
303					l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
304					positionL1++
305				}
306			}
307			if validL2Tx != nil {
308				validTxs = append(validTxs, *validL2Tx)
309			}
310		} else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
311			receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
312			if err != nil {
313				// tx not valid
314				log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
315					"ToIdx", l2Txs[i].ToIdx)
316				// Discard L2Tx, and update Info parameter of
317				// the tx, and add it to the discardedTxs array
318				l2Txs[i].Info = fmt.Sprintf("Tx not selected due to tx.ToIdx not found in StateDB. "+
319					"ToIdx: %d", l2Txs[i].ToIdx)
320				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
321				continue
322			}
323			if l2Txs[i].ToEthAddr != common.EmptyAddr {
324				if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
325					log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
326						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
327						l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
328					// Discard L2Tx, and update Info
329					// parameter of the tx, and add it to
330					// the discardedTxs array
331					l2Txs[i].Info = fmt.Sprintf("Tx not selected because ToEthAddr "+
332						"does not correspond to the Account.EthAddr. "+
333						"tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
334						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
335					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
336					continue
337				}
338			}
339			if l2Txs[i].ToBJJ != common.EmptyBJJComp {
340				if l2Txs[i].ToBJJ != receiverAcc.BJJ {
341					log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
342						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
343						"account.BJJ", receiverAcc.BJJ)
344					// Discard L2Tx, and update Info
345					// parameter of the tx, and add it to
346					// the discardedTxs array
347					l2Txs[i].Info = fmt.Sprintf("Tx not selected because tx.ToBJJ "+
348						"does not correspond to the Account.BJJ. "+
349						"tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
350						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
351					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
352					continue
353				}
354			}
355
356			// Account found in the DB, include the l2Tx in the selection
357			validTxs = append(validTxs, l2Txs[i])
358		} else if l2Txs[i].ToIdx == common.Idx(1) {
359			// valid txs (of Exit type)
360			validTxs = append(validTxs, l2Txs[i])
361		}
362		noncesMap[l2Txs[i].FromIdx]++
363	}
364
365	// Process L1CoordinatorTxs
366	for i := 0; i < len(l1CoordinatorTxs); i++ {
367		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
368		if err != nil {
369			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
370		}
371	}
372
373	// get CoordIdxsMap for the TokenIDs
374	coordIdxsMap := make(map[common.TokenID]common.Idx)
375	for i := 0; i < len(validTxs); i++ {
376		// get TokenID from tx.Sender
377		accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
378		if err != nil {
379			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
380		}
381		tokenID := accSender.TokenID
382
383		coordIdx, err := txsel.getCoordIdx(tokenID)
384		if err != nil {
385			// if err is db.ErrNotFound, should not happen, as all
386			// the validTxs.TokenID should have a CoordinatorIdx
387			// created in the DB at this point
388			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
389		}
390		coordIdxsMap[tokenID] = coordIdx
391	}
392
393	var coordIdxs []common.Idx
394	tp.AccumulatedFees = make(map[common.Idx]*big.Int)
395	for _, idx := range coordIdxsMap {
396		tp.AccumulatedFees[idx] = big.NewInt(0)
397		coordIdxs = append(coordIdxs, idx)
398	}
399	// sort CoordIdxs
400	sort.SliceStable(coordIdxs, func(i, j int) bool {
401		return coordIdxs[i] < coordIdxs[j]
402	})
403
404	// get most profitable L2-tx
405	maxL2Txs := int(selectionConfig.MaxTx) -
406		len(l1UserTxs) - len(l1CoordinatorTxs)
407
408	selectedL2Txs := validTxs
409	if len(validTxs) > maxL2Txs {
410		selectedL2Txs = selectedL2Txs[:maxL2Txs]
411	}
412	var finalL2Txs []common.PoolL2Tx
413	for i := 0; i < len(selectedL2Txs); i++ {
414		_, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &selectedL2Txs[i])
415		if err != nil {
416			// the error can be due not valid tx data, or due other
417			// cases (such as StateDB error). At this initial
418			// version of the TxSelector, we discard the L2Tx and
419			// log the error, assuming that this will be iterated in
420			// a near future.
421			return nil, nil, nil, nil, nil, nil,
422				tracerr.Wrap(fmt.Errorf("TxSelector: txprocessor.ProcessL2Tx: %w", err))
423		}
424		finalL2Txs = append(finalL2Txs, selectedL2Txs[i])
425	}
426
427	// distribute the AccumulatedFees from the processed L2Txs into the
428	// Coordinator Idxs
429	for idx, accumulatedFee := range tp.AccumulatedFees {
430		cmp := accumulatedFee.Cmp(big.NewInt(0))
431		if cmp == 1 { // accumulatedFee>0
432			// send the fee to the Idx of the Coordinator for the TokenID
433			accCoord, err := txsel.localAccountsDB.GetAccount(idx)
434			if err != nil {
435				log.Errorw("Can not distribute accumulated fees to coordinator "+
436					"account: No coord Idx to receive fee", "idx", idx)
437				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
438			}
439			accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
440			_, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
441			if err != nil {
442				log.Error(err)
443				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
444			}
445		}
446	}
447
448	err = tp.StateDB().MakeCheckpoint()
449	if err != nil {
450		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
451	}
452
453	metricSelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
454	metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
455	metricSelectedL2Txs.Set(float64(len(finalL2Txs)))
456	metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
457
458	return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, finalL2Txs, discardedL2Txs, nil
459}
460
461// processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
462// ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
463// does not have an account yet, a new L1CoordinatorTx of type
464// CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
465// l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
466// array.
467func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
468	selectionConfig txprocessor.Config, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
469	positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
470	*common.AccountCreationAuth, error) {
471	// if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
472	// previous L2Tx in the current process already created a
473	// L1CoordinatorTx of this type, in the DB there still seem that needs
474	// to create a new L1CoordinatorTx, but as is already created, the tx
475	// is valid
476	if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
477		return &l2Tx, nil, nil, nil
478	}
479
480	var l1CoordinatorTx *common.L1Tx
481	var accAuth *common.AccountCreationAuth
482	if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
483		// case: ToEthAddr != 0x00 neither 0xff
484		if l2Tx.ToBJJ != common.EmptyBJJComp {
485			// case: ToBJJ!=0:
486			// if idx exist for EthAddr&BJJ use it
487			_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
488				l2Tx.ToBJJ, l2Tx.TokenID)
489			if err == nil {
490				// account for ToEthAddr&ToBJJ already exist,
491				// there is no need to create a new one.
492				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
493				return &l2Tx, nil, nil, nil
494			}
495			// if not, check if AccountCreationAuth exist for that
496			// ToEthAddr
497			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
498			if err != nil {
499				// not found, l2Tx will not be added in the selection
500				return nil, nil, nil,
501					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found "+
502						"in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
503						l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
504			}
505			if accAuth.BJJ != l2Tx.ToBJJ {
506				// if AccountCreationAuth.BJJ is not the same
507				// than in the tx, tx is not accepted
508				return nil, nil, nil,
509					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, "+
510						"neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. "+
511						"ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
512						l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
513			}
514		} else {
515			// case: ToBJJ==0:
516			// if idx exist for EthAddr use it
517			_, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
518			if err == nil {
519				// account for ToEthAddr already exist,
520				// there is no need to create a new one.
521				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
522				return &l2Tx, nil, nil, nil
523			}
524			// if not, check if AccountCreationAuth exist for that ToEthAddr
525			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
526			if err != nil {
527				// not found, l2Tx will not be added in the selection
528				return nil, nil, nil,
529					tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in "+
530						"StateDB, neither ToEthAddr found in "+
531						"AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
532						l2Tx.ToIdx, l2Tx.ToEthAddr))
533			}
534		}
535		// create L1CoordinatorTx for the accountCreation
536		l1CoordinatorTx = &common.L1Tx{
537			Position:      positionL1,
538			UserOrigin:    false,
539			FromEthAddr:   accAuth.EthAddr,
540			FromBJJ:       accAuth.BJJ,
541			TokenID:       l2Tx.TokenID,
542			Amount:        big.NewInt(0),
543			DepositAmount: big.NewInt(0),
544			Type:          common.TxTypeCreateAccountDeposit,
545		}
546	} else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
547		// if idx exist for EthAddr&BJJ use it
548		_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
549			l2Tx.TokenID)
550		if err == nil {
551			// account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
552			// there is no need to create a new one.
553			// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
554			return &l2Tx, nil, nil, nil
555		}
556		// if idx don't exist for EthAddr&BJJ, coordinator can create a
557		// new account without L1Authorization, as ToEthAddr==0xff
558		// create L1CoordinatorTx for the accountCreation
559		l1CoordinatorTx = &common.L1Tx{
560			Position:      positionL1,
561			UserOrigin:    false,
562			FromEthAddr:   l2Tx.ToEthAddr,
563			FromBJJ:       l2Tx.ToBJJ,
564			TokenID:       l2Tx.TokenID,
565			Amount:        big.NewInt(0),
566			DepositAmount: big.NewInt(0),
567			Type:          common.TxTypeCreateAccountDeposit,
568		}
569	}
570	if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1UserTxs {
571		// L2Tx discarded
572		return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
573			"for L1CoordinatorTx to create a new account for receiver of L2Tx"))
574	}
575
576	return &l2Tx, l1CoordinatorTx, accAuth, nil
577}
578
579func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
580	addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
581	for i := 0; i < len(l1CoordinatorTxs); i++ {
582		if l1CoordinatorTxs[i].FromEthAddr == addr &&
583			l1CoordinatorTxs[i].TokenID == tokenID &&
584			l1CoordinatorTxs[i].FromBJJ == bjj {
585			return true
586		}
587	}
588	return false
589}
590
591// getL2Profitable returns the profitable selection of L2Txssorted by Nonce
592func (txsel *TxSelector) getL2Profitable(l2Txs []common.PoolL2Tx, max uint32) ([]common.PoolL2Tx,
593	[]common.PoolL2Tx) {
594	// First sort by nonce so that txs from the same account are sorted so
595	// that they could be applied in succession.
596	sort.Slice(l2Txs, func(i, j int) bool {
597		return l2Txs[i].Nonce < l2Txs[j].Nonce
598	})
599	// Sort by absolute fee with SliceStable, so that txs with same
600	// AbsoluteFee are not rearranged and nonce order is kept in such case
601	sort.SliceStable(l2Txs, func(i, j int) bool {
602		return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
603	})
604
605	discardedL2Txs := []common.PoolL2Tx{}
606	if len(l2Txs) > int(max) {
607		discardedL2Txs = l2Txs[max:]
608		l2Txs = l2Txs[:max]
609	}
610
611	// sort l2Txs by Nonce. This can be done in many different ways, what
612	// is needed is to output the l2Txs where the Nonce of l2Txs for each
613	// Account is sorted, but the l2Txs can not be grouped by sender Account
614	// neither by Fee. This is because later on the Nonces will need to be
615	// sequential for the zkproof generation.
616	sort.Slice(l2Txs, func(i, j int) bool {
617		return l2Txs[i].Nonce < l2Txs[j].Nonce
618	})
619
620	return l2Txs, discardedL2Txs
621}