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.

587 lines
23 KiB

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