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