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	"bytes"
  7	"fmt"
  8	"math/big"
  9	"sort"
 10
 11	ethCommon "github.com/ethereum/go-ethereum/common"
 12	"github.com/hermeznetwork/hermez-node/common"
 13	"github.com/hermeznetwork/hermez-node/db/kvdb"
 14	"github.com/hermeznetwork/hermez-node/db/l2db"
 15	"github.com/hermeznetwork/hermez-node/db/statedb"
 16	"github.com/hermeznetwork/hermez-node/log"
 17	"github.com/hermeznetwork/hermez-node/txprocessor"
 18	"github.com/hermeznetwork/tracerr"
 19	"github.com/iden3/go-iden3-crypto/babyjub"
 20)
 21
 22// txs implements the interface Sort for an array of Tx
 23type txs []common.PoolL2Tx
 24
 25func (t txs) Len() int {
 26	return len(t)
 27}
 28func (t txs) Swap(i, j int) {
 29	t[i], t[j] = t[j], t[i]
 30}
 31func (t txs) Less(i, j int) bool {
 32	return t[i].AbsoluteFee > t[j].AbsoluteFee
 33}
 34
 35// CoordAccount contains the data of the Coordinator account, that will be used
 36// to create new transactions of CreateAccountDeposit type to add new TokenID
 37// accounts for the Coordinator to receive the fees.
 38type CoordAccount struct {
 39	Addr                ethCommon.Address
 40	BJJ                 babyjub.PublicKeyComp
 41	AccountCreationAuth []byte // signature in byte array format
 42}
 43
 44// SelectionConfig contains the parameters of configuration of the selection of
 45// transactions for the next batch
 46type SelectionConfig struct {
 47	// MaxL1UserTxs is the maximum L1-user-tx for a batch
 48	MaxL1UserTxs uint64
 49
 50	// TxProcessorConfig contains the config for ProcessTxs
 51	TxProcessorConfig txprocessor.Config
 52}
 53
 54// TxSelector implements all the functionalities to select the txs for the next
 55// batch
 56type TxSelector struct {
 57	l2db            *l2db.L2DB
 58	localAccountsDB *statedb.LocalStateDB
 59
 60	coordAccount *CoordAccount
 61}
 62
 63// NewTxSelector returns a *TxSelector
 64func NewTxSelector(coordAccount *CoordAccount, dbpath string,
 65	synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
 66	localAccountsDB, err := statedb.NewLocalStateDB(
 67		statedb.Config{
 68			Path:    dbpath,
 69			Keep:    kvdb.DefaultKeep,
 70			Type:    statedb.TypeTxSelector,
 71			NLevels: 0,
 72		},
 73		synchronizerStateDB) // without merkletree
 74	if err != nil {
 75		return nil, tracerr.Wrap(err)
 76	}
 77
 78	return &TxSelector{
 79		l2db:            l2,
 80		localAccountsDB: localAccountsDB,
 81		coordAccount:    coordAccount,
 82	}, nil
 83}
 84
 85// LocalAccountsDB returns the LocalStateDB of the TxSelector
 86func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
 87	return txsel.localAccountsDB
 88}
 89
 90// Reset tells the TxSelector to get it's internal AccountsDB
 91// from the required `batchNum`
 92func (txsel *TxSelector) Reset(batchNum common.BatchNum) error {
 93	err := txsel.localAccountsDB.Reset(batchNum, true)
 94	if err != nil {
 95		return tracerr.Wrap(err)
 96	}
 97	return nil
 98}
 99
100func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
101	return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr,
102		txsel.coordAccount.BJJ, tokenID)
103}
104
105// coordAccountForTokenID creates a new L1CoordinatorTx to create a new
106// Coordinator account for the given TokenID in the case that the account does
107// not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
108// account in the given array of L1CoordinatorTxs. If a new Coordinator account
109// needs to be created, a new L1CoordinatorTx will be returned from this
110// function. After calling this method, if the l1CoordinatorTx is added to the
111// selection, positionL1 must be increased 1.
112func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
113	tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
114	// check if CoordinatorAccount for TokenID is already pending to create
115	if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
116		txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
117		return nil, positionL1, nil
118	}
119	_, err := txsel.getCoordIdx(tokenID)
120	if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
121		// create L1CoordinatorTx to create new CoordAccount for
122		// TokenID
123		l1CoordinatorTx := common.L1Tx{
124			Position:      positionL1,
125			UserOrigin:    false,
126			FromEthAddr:   txsel.coordAccount.Addr,
127			FromBJJ:       txsel.coordAccount.BJJ,
128			TokenID:       tokenID,
129			Amount:        big.NewInt(0),
130			DepositAmount: big.NewInt(0),
131			Type:          common.TxTypeCreateAccountDeposit,
132		}
133
134		return &l1CoordinatorTx, positionL1, nil
135	}
136	if err != nil {
137		return nil, positionL1, tracerr.Wrap(err)
138	}
139	// CoordAccount for TokenID already exists
140	return nil, positionL1, nil
141}
142
143// GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
144// for the next batch, from the L2DB pool.
145// It returns: the CoordinatorIdxs used to receive the fees of the selected
146// L2Txs. An array of bytearrays with the signatures of the
147// AccountCreationAuthorization of the accounts of the users created by the
148// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
149// but there is a transactions to them and the authorization of account
150// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
151// included in the next batch.
152func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig) ([]common.Idx,
153	[][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
154	coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, discardedL2Txs, err :=
155		txsel.GetL1L2TxSelection(selectionConfig, []common.L1Tx{})
156	return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, discardedL2Txs, tracerr.Wrap(err)
157}
158
159// GetL1L2TxSelection returns the selection of L1 + L2 txs.
160// It returns: the CoordinatorIdxs used to receive the fees of the selected
161// L2Txs. An array of bytearrays with the signatures of the
162// AccountCreationAuthorization of the accounts of the users created by the
163// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
164// but there is a transactions to them and the authorization of account
165// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
166// included in the next batch.
167func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
168	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
169	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
170	// WIP.0: the TxSelector is not optimized and will need a redesign. The
171	// current version is implemented in order to have a functional
172	// implementation that can be used asap.
173	//
174	// WIP.1: this method uses a 'cherry-pick' of internal calls of the
175	// StateDB, a refactor of the StateDB to reorganize it internally is
176	// planned once the main functionallities are covered, with that
177	// refactor the TxSelector will be updated also.
178
179	// get pending l2-tx from tx-pool
180	l2TxsRaw, err := txsel.l2db.GetPendingTxs()
181	if err != nil {
182		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
183	}
184
185	txselStateDB := txsel.localAccountsDB.StateDB
186	tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig.TxProcessorConfig)
187
188	// Process L1UserTxs
189	for i := 0; i < len(l1UserTxs); i++ {
190		// assumption: l1usertx are sorted by L1Tx.Position
191		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
192		if err != nil {
193			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
194		}
195	}
196
197	// discardedL2Txs contains an array of the L2Txs that have not been selected in this Batch
198	var discardedL2Txs []common.PoolL2Tx
199
200	var l1CoordinatorTxs []common.L1Tx
201	positionL1 := len(l1UserTxs)
202	var accAuths [][]byte
203
204	// sort l2TxsRaw (cropping at MaxTx at this point)
205	l2Txs0 := txsel.getL2Profitable(l2TxsRaw, selectionConfig.TxProcessorConfig.MaxTx)
206
207	noncesMap := make(map[common.Idx]common.Nonce)
208	var l2Txs []common.PoolL2Tx
209	// iterate over l2Txs
210	// - if tx.TokenID does not exist at CoordsIdxDB
211	// 	- create new L1CoordinatorTx creating a CoordAccount, for
212	// 	Coordinator to receive the fee of the new TokenID
213	for i := 0; i < len(l2Txs0); i++ {
214		accSender, err := tp.StateDB().GetAccount(l2Txs0[i].FromIdx)
215		if err != nil {
216			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
217		}
218		l2Txs0[i].TokenID = accSender.TokenID
219		// populate the noncesMap used at the next iteration
220		noncesMap[l2Txs0[i].FromIdx] = accSender.Nonce
221
222		// if TokenID does not exist yet, create new L1CoordinatorTx to
223		// create the CoordinatorAccount for that TokenID, to receive
224		// the fees. Only in the case that there does not exist yet a
225		// pending L1CoordinatorTx to create the account for the
226		// Coordinator for that TokenID
227		var newL1CoordTx *common.L1Tx
228		newL1CoordTx, positionL1, err =
229			txsel.coordAccountForTokenID(l1CoordinatorTxs,
230				accSender.TokenID, positionL1)
231		if err != nil {
232			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
233		}
234		if newL1CoordTx != nil {
235			// if there is no space for the L1CoordinatorTx, discard the L2Tx
236			if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1UserTxs)-len(l1UserTxs) {
237				// discard L2Tx, and update Info parameter of
238				// the tx, and add it to the discardedTxs array
239				l2Txs0[i].Info = "Tx not selected due the L2Tx depends on a L1CoordinatorTx and there is not enough space for L1Coordinator"
240				discardedL2Txs = append(discardedL2Txs, l2Txs0[i])
241				continue
242			}
243			// increase positionL1
244			positionL1++
245			l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
246			accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
247		}
248		l2Txs = append(l2Txs, l2Txs0[i])
249	}
250
251	var validTxs []common.PoolL2Tx
252	// iterate over l2TxsRaw
253	// - check Nonces
254	// - check enough Balance for the Amount+Fee
255	// - if needed, create new L1CoordinatorTxs for unexisting ToIdx
256	// 	- keep used accAuths
257	// - put the valid txs into validTxs array
258	for i := 0; i < len(l2Txs); i++ {
259		enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
260		if !enoughBalance {
261			// not valid Amount with current Balance. Discard L2Tx,
262			// and update Info parameter of the tx, and add it to
263			// the discardedTxs array
264			l2Txs[i].Info = fmt.Sprintf("Tx not selected due not enough Balance at the sender. Current sender account Balance: %s, Amount+Fee: %s", balance.String(), feeAndAmount.String())
265			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
266			continue
267		}
268		// check if Nonce is correct
269		nonce := noncesMap[l2Txs[i].FromIdx]
270		if l2Txs[i].Nonce == nonce {
271			noncesMap[l2Txs[i].FromIdx]++
272		} else {
273			// not valid Nonce at tx. Discard L2Tx, and update Info
274			// parameter of the tx, and add it to the discardedTxs
275			// array
276			l2Txs[i].Info = fmt.Sprintf("Tx not selected due not current Nonce. Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, nonce)
277			discardedL2Txs = append(discardedL2Txs, l2Txs[i])
278			continue
279		}
280
281		// If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
282		// if so, tx is used.  If tx.ToIdx==0, for an L2Tx will be the
283		// case of TxToEthAddr or TxToBJJ, check if
284		// tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
285		// used; if not, check if tx.ToEthAddr is in
286		// AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
287		// of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
288		// Exit type and is used.
289		if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
290			validL2Tx, l1CoordinatorTx, accAuth, err :=
291				txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
292					len(l1UserTxs), l1CoordinatorTxs, positionL1, l2Txs[i])
293			if err != nil {
294				log.Debug(err)
295				// Discard L2Tx, and update Info parameter of
296				// the tx, and add it to the discardedTxs array
297				l2Txs[i].Info = fmt.Sprintf("Tx not selected (in processTxToEthAddrBJJ) due %s", err.Error())
298				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
299				continue
300			}
301			if accAuth != nil && l1CoordinatorTx != nil {
302				accAuths = append(accAuths, accAuth.Signature)
303				l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
304				positionL1++
305			}
306			if validL2Tx != nil {
307				validTxs = append(validTxs, *validL2Tx)
308			}
309		} else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
310			receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
311			if err != nil {
312				// tx not valid
313				log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
314					"ToIdx", l2Txs[i].ToIdx)
315				// Discard L2Tx, and update Info parameter of
316				// the tx, and add it to the discardedTxs array
317				l2Txs[i].Info = fmt.Sprintf("Tx not selected due tx.ToIdx not found in StateDB. ToIdx: %d",
318					l2Txs[i].ToIdx)
319				discardedL2Txs = append(discardedL2Txs, l2Txs[i])
320				continue
321			}
322			if l2Txs[i].ToEthAddr != common.EmptyAddr {
323				if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
324					log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
325						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
326						l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
327					// Discard L2Tx, and update Info
328					// parameter of the tx, and add it to
329					// the discardedTxs array
330					l2Txs[i].Info = fmt.Sprintf("Tx not selected due ToEthAddr does not correspond to the Account.EthAddr. tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
331						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
332					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
333					continue
334				}
335			}
336			if l2Txs[i].ToBJJ != common.EmptyBJJComp {
337				if l2Txs[i].ToBJJ != receiverAcc.BJJ {
338					log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
339						"ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
340						"account.BJJ", receiverAcc.BJJ)
341					// Discard L2Tx, and update Info
342					// parameter of the tx, and add it to
343					// the discardedTxs array
344					l2Txs[i].Info = fmt.Sprintf("Tx not selected due tx.ToBJJ does not correspond to the Account.BJJ. tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
345						l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
346					discardedL2Txs = append(discardedL2Txs, l2Txs[i])
347					continue
348				}
349			}
350
351			// Account found in the DB, include the l2Tx in the selection
352			validTxs = append(validTxs, l2Txs[i])
353		} else if l2Txs[i].ToIdx == common.Idx(1) {
354			// valid txs (of Exit type)
355			validTxs = append(validTxs, l2Txs[i])
356		}
357	}
358
359	// Process L1CoordinatorTxs
360	for i := 0; i < len(l1CoordinatorTxs); i++ {
361		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
362		if err != nil {
363			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
364		}
365	}
366
367	// get CoordIdxsMap for the TokenIDs
368	coordIdxsMap := make(map[common.TokenID]common.Idx)
369	for i := 0; i < len(validTxs); i++ {
370		// get TokenID from tx.Sender
371		accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
372		if err != nil {
373			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
374		}
375		tokenID := accSender.TokenID
376
377		coordIdx, err := txsel.getCoordIdx(tokenID)
378		if err != nil {
379			// if err is db.ErrNotFound, should not happen, as all
380			// the validTxs.TokenID should have a CoordinatorIdx
381			// created in the DB at this point
382			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
383		}
384		coordIdxsMap[tokenID] = coordIdx
385	}
386
387	var coordIdxs []common.Idx
388	tp.AccumulatedFees = make(map[common.Idx]*big.Int)
389	for _, idx := range coordIdxsMap {
390		tp.AccumulatedFees[idx] = big.NewInt(0)
391		coordIdxs = append(coordIdxs, idx)
392	}
393	// sort CoordIdxs
394	sort.SliceStable(coordIdxs, func(i, j int) bool {
395		return coordIdxs[i] < coordIdxs[j]
396	})
397
398	// get most profitable L2-tx
399	maxL2Txs := int(selectionConfig.TxProcessorConfig.MaxTx) -
400		len(l1UserTxs) - len(l1CoordinatorTxs)
401
402	selectedL2Txs := validTxs
403	if len(validTxs) > maxL2Txs {
404		selectedL2Txs = selectedL2Txs[:maxL2Txs]
405	}
406	var finalL2Txs []common.PoolL2Tx
407	for i := 0; i < len(selectedL2Txs); i++ {
408		_, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &selectedL2Txs[i])
409		if err != nil {
410			// the error can be due not valid tx data, or due other
411			// cases (such as StateDB error). At this initial
412			// version of the TxSelector, we discard the L2Tx and
413			// log the error, assuming that this will be iterated
414			// in a near future.
415			log.Error(err)
416			// Discard L2Tx, and update Info parameter of the tx,
417			// and add it to the discardedTxs array
418			selectedL2Txs[i].Info = fmt.Sprintf("Tx not selected (in ProcessL2Tx) due %s", err.Error())
419			discardedL2Txs = append(discardedL2Txs, selectedL2Txs[i])
420			continue
421		}
422		finalL2Txs = append(finalL2Txs, selectedL2Txs[i])
423	}
424
425	// distribute the AccumulatedFees from the processed L2Txs into the
426	// Coordinator Idxs
427	for idx, accumulatedFee := range tp.AccumulatedFees {
428		cmp := accumulatedFee.Cmp(big.NewInt(0))
429		if cmp == 1 { // accumulatedFee>0
430			// send the fee to the Idx of the Coordinator for the TokenID
431			accCoord, err := txsel.localAccountsDB.GetAccount(idx)
432			if err != nil {
433				log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx)
434				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
435			}
436			accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
437			_, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
438			if err != nil {
439				log.Error(err)
440				return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
441			}
442		}
443	}
444
445	err = tp.StateDB().MakeCheckpoint()
446	if err != nil {
447		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
448	}
449
450	return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, finalL2Txs, discardedL2Txs, nil
451}
452
453// processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
454// ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
455// does not have an account yet, a new L1CoordinatorTx of type
456// CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
457// l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
458// array.
459func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
460	selectionConfig *SelectionConfig, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
461	positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
462	*common.AccountCreationAuth, error) {
463	// if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
464	// previous L2Tx in the current process already created a
465	// L1CoordinatorTx of this type, in the DB there still seem that needs
466	// to create a new L1CoordinatorTx, but as is already created, the tx
467	// is valid
468	if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
469		return &l2Tx, nil, nil, nil
470	}
471
472	var l1CoordinatorTx *common.L1Tx
473	var accAuth *common.AccountCreationAuth
474	if !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) &&
475		!bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
476		// case: ToEthAddr != 0x00 neither 0xff
477		if l2Tx.ToBJJ != common.EmptyBJJComp {
478			// case: ToBJJ!=0:
479			// if idx exist for EthAddr&BJJ use it
480			_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
481				l2Tx.ToBJJ, l2Tx.TokenID)
482			if err == nil {
483				// account for ToEthAddr&ToBJJ already exist,
484				// there is no need to create a new one.
485				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
486				return &l2Tx, nil, nil, nil
487			}
488			// if not, check if AccountCreationAuth exist for that
489			// ToEthAddr
490			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
491			if err != nil {
492				// not found, l2Tx will not be added in the selection
493				return nil, nil, nil, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
494					l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
495			}
496			if accAuth.BJJ != l2Tx.ToBJJ {
497				// if AccountCreationAuth.BJJ is not the same
498				// than in the tx, tx is not accepted
499				return nil, nil, nil, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
500					l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
501			}
502		} else {
503			// case: ToBJJ==0:
504			// if idx exist for EthAddr use it
505			_, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
506			if err == nil {
507				// account for ToEthAddr already exist,
508				// there is no need to create a new one.
509				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
510				return &l2Tx, nil, nil, nil
511			}
512			// if not, check if AccountCreationAuth exist for that ToEthAddr
513			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
514			if err != nil {
515				// not found, l2Tx will not be added in the selection
516				return nil, nil, nil, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
517					l2Tx.ToIdx, l2Tx.ToEthAddr))
518			}
519		}
520		// create L1CoordinatorTx for the accountCreation
521		l1CoordinatorTx = &common.L1Tx{
522			Position:      positionL1,
523			UserOrigin:    false,
524			FromEthAddr:   accAuth.EthAddr,
525			FromBJJ:       accAuth.BJJ,
526			TokenID:       l2Tx.TokenID,
527			Amount:        big.NewInt(0),
528			DepositAmount: big.NewInt(0),
529			Type:          common.TxTypeCreateAccountDeposit,
530		}
531	} else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) &&
532		l2Tx.ToBJJ != common.EmptyBJJComp {
533		// if idx exist for EthAddr&BJJ use it
534		_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
535			l2Tx.TokenID)
536		if err == nil {
537			// account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
538			// there is no need to create a new one.
539			// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
540			return &l2Tx, nil, nil, nil
541		}
542		// if idx don't exist for EthAddr&BJJ, coordinator can create a
543		// new account without L1Authorization, as ToEthAddr==0xff
544		// create L1CoordinatorTx for the accountCreation
545		l1CoordinatorTx = &common.L1Tx{
546			Position:      positionL1,
547			UserOrigin:    false,
548			FromEthAddr:   l2Tx.ToEthAddr,
549			FromBJJ:       l2Tx.ToBJJ,
550			TokenID:       l2Tx.TokenID,
551			Amount:        big.NewInt(0),
552			DepositAmount: big.NewInt(0),
553			Type:          common.TxTypeCreateAccountDeposit,
554		}
555	}
556	if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1UserTxs)-nL1UserTxs {
557		// L2Tx discarded
558		return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due not slots for L1CoordinatorTx to create a new account for receiver of L2Tx"))
559	}
560
561	return &l2Tx, l1CoordinatorTx, accAuth, nil
562}
563
564func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
565	addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
566	for i := 0; i < len(l1CoordinatorTxs); i++ {
567		if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) &&
568			l1CoordinatorTxs[i].TokenID == tokenID &&
569			l1CoordinatorTxs[i].FromBJJ == bjj {
570			return true
571		}
572	}
573	return false
574}
575
576// getL2Profitable returns the profitable selection of L2Txssorted by Nonce
577func (txsel *TxSelector) getL2Profitable(l2Txs []common.PoolL2Tx, max uint32) []common.PoolL2Tx {
578	sort.Sort(txs(l2Txs))
579	if len(l2Txs) < int(max) {
580		return l2Txs
581	}
582	l2Txs = l2Txs[:max]
583
584	// sort l2Txs by Nonce. This can be done in many different ways, what
585	// is needed is to output the l2Txs where the Nonce of l2Txs for each
586	// Account is sorted, but the l2Txs can not be grouped by sender Account
587	// neither by Fee. This is because later on the Nonces will need to be
588	// sequential for the zkproof generation.
589	sort.SliceStable(l2Txs, func(i, j int) bool {
590		return l2Txs[i].Nonce < l2Txs[j].Nonce
591	})
592
593	return l2Txs
594}