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.

613 lines
23 KiB

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