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.

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