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