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