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