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// SelectionConfig contains the parameters of configuration of the selection of
 31// transactions for the next batch
 32type SelectionConfig struct {
 33	// MaxL1UserTxs is the maximum L1-user-tx for a batch
 34	MaxL1UserTxs uint64
 35
 36	// TxProcessorConfig contains the config for ProcessTxs
 37	TxProcessorConfig txprocessor.Config
 38}
 39
 40// TxSelector implements all the functionalities to select the txs for the next
 41// batch
 42type TxSelector struct {
 43	l2db            *l2db.L2DB
 44	localAccountsDB *statedb.LocalStateDB
 45
 46	coordAccount *CoordAccount
 47}
 48
 49// NewTxSelector returns a *TxSelector
 50func NewTxSelector(coordAccount *CoordAccount, dbpath string,
 51	synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
 52	localAccountsDB, err := statedb.NewLocalStateDB(
 53		statedb.Config{
 54			Path:    dbpath,
 55			Keep:    kvdb.DefaultKeep,
 56			Type:    statedb.TypeTxSelector,
 57			NLevels: 0,
 58		},
 59		synchronizerStateDB) // without merkletree
 60	if err != nil {
 61		return nil, tracerr.Wrap(err)
 62	}
 63
 64	return &TxSelector{
 65		l2db:            l2,
 66		localAccountsDB: localAccountsDB,
 67		coordAccount:    coordAccount,
 68	}, nil
 69}
 70
 71// LocalAccountsDB returns the LocalStateDB of the TxSelector
 72func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
 73	return txsel.localAccountsDB
 74}
 75
 76// Reset tells the TxSelector to get it's internal AccountsDB
 77// from the required `batchNum`
 78func (txsel *TxSelector) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
 79	return tracerr.Wrap(txsel.localAccountsDB.Reset(batchNum, fromSynchronizer))
 80}
 81
 82func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
 83	return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr,
 84		txsel.coordAccount.BJJ, tokenID)
 85}
 86
 87// coordAccountForTokenID creates a new L1CoordinatorTx to create a new
 88// Coordinator account for the given TokenID in the case that the account does
 89// not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
 90// account in the given array of L1CoordinatorTxs. If a new Coordinator account
 91// needs to be created, a new L1CoordinatorTx will be returned from this
 92// function. After calling this method, if the l1CoordinatorTx is added to the
 93// selection, positionL1 must be increased 1.
 94func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
 95	tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
 96	// check if CoordinatorAccount for TokenID is already pending to create
 97	if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
 98		txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
 99		return nil, positionL1, nil
100	}
101	_, err := txsel.getCoordIdx(tokenID)
102	if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
103		// create L1CoordinatorTx to create new CoordAccount for
104		// TokenID
105		l1CoordinatorTx := common.L1Tx{
106			Position:      positionL1,
107			UserOrigin:    false,
108			FromEthAddr:   txsel.coordAccount.Addr,
109			FromBJJ:       txsel.coordAccount.BJJ,
110			TokenID:       tokenID,
111			Amount:        big.NewInt(0),
112			DepositAmount: big.NewInt(0),
113			Type:          common.TxTypeCreateAccountDeposit,
114		}
115
116		return &l1CoordinatorTx, positionL1, nil
117	}
118	if err != nil {
119		return nil, positionL1, tracerr.Wrap(err)
120	}
121	// CoordAccount for TokenID already exists
122	return nil, positionL1, nil
123}
124
125// GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
126// for the next batch, from the L2DB pool.
127// It returns: the CoordinatorIdxs used to receive the fees of the selected
128// L2Txs. An array of bytearrays with the signatures of the
129// AccountCreationAuthorization of the accounts of the users created by the
130// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
131// but there is a transactions to them and the authorization of account
132// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
133// included in the next batch.
134func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig) ([]common.Idx,
135	[][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
136	metricGetL2TxSelection.Inc()
137	coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs,
138		discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, []common.L1Tx{})
139	return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs,
140		discardedL2Txs, tracerr.Wrap(err)
141}
142
143// GetL1L2TxSelection returns the selection of L1 + L2 txs.
144// It returns: the CoordinatorIdxs used to receive the fees of the selected
145// L2Txs. An array of bytearrays with the signatures of the
146// AccountCreationAuthorization of the accounts of the users created by the
147// Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
148// but there is a transactions to them and the authorization of account
149// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
150// included in the next batch.
151func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
152	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
153	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
154	metricGetL1L2TxSelection.Inc()
155	coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
156		discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, l1UserTxs)
157	return coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
158		discardedL2Txs, tracerr.Wrap(err)
159}
160
161func (txsel *TxSelector) getL1L2TxSelection(selectionConfig *SelectionConfig,
162	l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
163	[]common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
164	// WIP.0: the TxSelector is not optimized and will need a redesign. The
165	// current version is implemented in order to have a functional
166	// implementation that can be used asap.
167	//
168	// WIP.1: this method uses a 'cherry-pick' of internal calls of the
169	// StateDB, a refactor of the StateDB to reorganize it internally is
170	// planned once the main functionallities are covered, with that
171	// refactor the TxSelector will be updated also.
172
173	// get pending l2-tx from tx-pool
174	l2TxsRaw, err := txsel.l2db.GetPendingTxs()
175	if err != nil {
176		return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
177	}
178
179	txselStateDB := txsel.localAccountsDB.StateDB
180	tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig.TxProcessorConfig)
181
182	// Process L1UserTxs
183	for i := 0; i < len(l1UserTxs); i++ {
184		// assumption: l1usertx are sorted by L1Tx.Position
185		_, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
186		if err != nil {
187			return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
188		}
189	}
190
191	// discardedL2Txs contains an array of the L2Txs that have not been selected in this Batch
192
193	var l1CoordinatorTxs []common.L1Tx
194	positionL1 := len(l1UserTxs)
195	var accAuths [][]byte
196
197	// sort l2TxsRaw (cropping at MaxTx at this point)
198	l2Txs0, discardedL2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.TxProcessorConfig.MaxTx)
199	for i := range discardedL2Txs {
200		discardedL2Txs[i].Info = "Tx not selected due to low absolute fee"
201	}
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	metricSelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
468	metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
469	metricSelectedL2Txs.Set(float64(len(finalL2Txs)))
470	metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
471
472	return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, finalL2Txs, discardedL2Txs, nil
473}
474
475// processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
476// ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
477// does not have an account yet, a new L1CoordinatorTx of type
478// CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
479// l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
480// array.
481func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
482	selectionConfig *SelectionConfig, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
483	positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
484	*common.AccountCreationAuth, error) {
485	// if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
486	// previous L2Tx in the current process already created a
487	// L1CoordinatorTx of this type, in the DB there still seem that needs
488	// to create a new L1CoordinatorTx, but as is already created, the tx
489	// is valid
490	if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
491		return &l2Tx, nil, nil, nil
492	}
493
494	var l1CoordinatorTx *common.L1Tx
495	var accAuth *common.AccountCreationAuth
496	if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
497		// case: ToEthAddr != 0x00 neither 0xff
498		if l2Tx.ToBJJ != common.EmptyBJJComp {
499			// case: ToBJJ!=0:
500			// if idx exist for EthAddr&BJJ use it
501			_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
502				l2Tx.ToBJJ, l2Tx.TokenID)
503			if err == nil {
504				// account for ToEthAddr&ToBJJ already exist,
505				// there is no need to create a new one.
506				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
507				return &l2Tx, nil, nil, nil
508			}
509			// if not, check if AccountCreationAuth exist for that
510			// ToEthAddr
511			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
512			if err != nil {
513				// not found, l2Tx will not be added in the selection
514				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",
515					l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
516			}
517			if accAuth.BJJ != l2Tx.ToBJJ {
518				// if AccountCreationAuth.BJJ is not the same
519				// than in the tx, tx is not accepted
520				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",
521					l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
522			}
523		} else {
524			// case: ToBJJ==0:
525			// if idx exist for EthAddr use it
526			_, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
527			if err == nil {
528				// account for ToEthAddr already exist,
529				// there is no need to create a new one.
530				// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
531				return &l2Tx, nil, nil, nil
532			}
533			// if not, check if AccountCreationAuth exist for that ToEthAddr
534			accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
535			if err != nil {
536				// not found, l2Tx will not be added in the selection
537				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",
538					l2Tx.ToIdx, l2Tx.ToEthAddr))
539			}
540		}
541		// create L1CoordinatorTx for the accountCreation
542		l1CoordinatorTx = &common.L1Tx{
543			Position:      positionL1,
544			UserOrigin:    false,
545			FromEthAddr:   accAuth.EthAddr,
546			FromBJJ:       accAuth.BJJ,
547			TokenID:       l2Tx.TokenID,
548			Amount:        big.NewInt(0),
549			DepositAmount: big.NewInt(0),
550			Type:          common.TxTypeCreateAccountDeposit,
551		}
552	} else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
553		// if idx exist for EthAddr&BJJ use it
554		_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
555			l2Tx.TokenID)
556		if err == nil {
557			// account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
558			// there is no need to create a new one.
559			// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
560			return &l2Tx, nil, nil, nil
561		}
562		// if idx don't exist for EthAddr&BJJ, coordinator can create a
563		// new account without L1Authorization, as ToEthAddr==0xff
564		// create L1CoordinatorTx for the accountCreation
565		l1CoordinatorTx = &common.L1Tx{
566			Position:      positionL1,
567			UserOrigin:    false,
568			FromEthAddr:   l2Tx.ToEthAddr,
569			FromBJJ:       l2Tx.ToBJJ,
570			TokenID:       l2Tx.TokenID,
571			Amount:        big.NewInt(0),
572			DepositAmount: big.NewInt(0),
573			Type:          common.TxTypeCreateAccountDeposit,
574		}
575	}
576	if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1UserTxs)-nL1UserTxs {
577		// L2Tx discarded
578		return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
579			"for L1CoordinatorTx to create a new account for receiver of L2Tx"))
580	}
581
582	return &l2Tx, l1CoordinatorTx, accAuth, nil
583}
584
585func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
586	addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
587	for i := 0; i < len(l1CoordinatorTxs); i++ {
588		if l1CoordinatorTxs[i].FromEthAddr == addr &&
589			l1CoordinatorTxs[i].TokenID == tokenID &&
590			l1CoordinatorTxs[i].FromBJJ == bjj {
591			return true
592		}
593	}
594	return false
595}
596
597// getL2Profitable returns the profitable selection of L2Txssorted by Nonce
598func (txsel *TxSelector) getL2Profitable(l2Txs []common.PoolL2Tx, max uint32) ([]common.PoolL2Tx,
599	[]common.PoolL2Tx) {
600	// First sort by nonce so that txs from the same account are sorted so
601	// that they could be applied in succession.
602	sort.Slice(l2Txs, func(i, j int) bool {
603		return l2Txs[i].Nonce < l2Txs[j].Nonce
604	})
605	// Sort by absolute fee with SliceStable, so that txs with same
606	// AbsoluteFee are not rearranged and nonce order is kept in such case
607	sort.SliceStable(l2Txs, func(i, j int) bool {
608		return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
609	})
610
611	discardedL2Txs := []common.PoolL2Tx{}
612	if len(l2Txs) > int(max) {
613		discardedL2Txs = l2Txs[max:]
614		l2Txs = l2Txs[:max]
615	}
616
617	// sort l2Txs by Nonce. This can be done in many different ways, what
618	// is needed is to output the l2Txs where the Nonce of l2Txs for each
619	// Account is sorted, but the l2Txs can not be grouped by sender Account
620	// neither by Fee. This is because later on the Nonces will need to be
621	// sequential for the zkproof generation.
622	sort.Slice(l2Txs, func(i, j int) bool {
623		return l2Txs[i].Nonce < l2Txs[j].Nonce
624	})
625
626	return l2Txs, discardedL2Txs
627}