You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

590 lines
23 KiB

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