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.

626 lines
24 KiB

Update coordinator to work better under real net - cli / node - Update handler of SIGINT so that after 3 SIGINTs, the process terminates unconditionally - coordinator - Store stats without pointer - In all functions that send a variable via channel, check for context done to avoid deadlock (due to no process reading from the channel, which has no queue) when the node is stopped. - Abstract `canForge` so that it can be used outside of the `Coordinator` - In `canForge` check the blockNumber in current and next slot. - Update tests due to smart contract changes in slot handling, and minimum bid defaults - TxManager - Add consts, vars and stats to allow evaluating `canForge` - Add `canForge` method (not used yet) - Store batch and nonces status (last success and last pending) - Track nonces internally instead of relying on the ethereum node (this is required to work with ganache when there are pending txs) - Handle the (common) case of the receipt not being found after the tx is sent. - Don't start the main loop until we get an initial messae fo the stats and vars (so that in the loop the stats and vars are set to synchronizer values) - When a tx fails, check and discard all the failed transactions before sending the message to stop the pipeline. This will avoid sending consecutive messages of stop the pipeline when multiple txs are detected to be failed consecutively. Also, future txs of the same pipeline after a discarded txs are discarded, and their nonces reused. - Robust handling of nonces: - If geth returns nonce is too low, increase it - If geth returns nonce too hight, decrease it - If geth returns underpriced, increase gas price - If geth returns replace underpriced, increase gas price - Add support for resending transactions after a timeout - Store `BatchInfos` in a queue - Pipeline - When an error is found, stop forging batches and send a message to the coordinator to stop the pipeline with information of the failed batch number so that in a restart, non-failed batches are not repated. - When doing a reset of the stateDB, if possible reset from the local checkpoint instead of resetting from the synchronizer. This allows resetting from a batch that is valid but not yet sent / synced. - Every time a pipeline is started, assign it a number from a counter. This allows the TxManager to ignore batches from stopped pipelines, via a message sent by the coordinator. - Avoid forging when we haven't reached the rollup genesis block number. - Add config parameter `StartSlotBlocksDelay`: StartSlotBlocksDelay is the number of blocks of delay to wait before starting the pipeline when we reach a slot in which we can forge. - When detecting a reorg, only reset the pipeline if the batch from which the pipeline started changed and wasn't sent by us. - Add config parameter `ScheduleBatchBlocksAheadCheck`: ScheduleBatchBlocksAheadCheck is the number of blocks ahead in which the forger address is checked to be allowed to forge (apart from checking the next block), used to decide when to stop scheduling new batches (by stopping the pipeline). For example, if we are at block 10 and ScheduleBatchBlocksAheadCheck is 5, eventhough at block 11 we canForge, the pipeline will be stopped if we can't forge at block 15. This value should be the expected number of blocks it takes between scheduling a batch and having it mined. - Add config parameter `SendBatchBlocksMarginCheck`: SendBatchBlocksMarginCheck is the number of margin blocks ahead in which the coordinator is also checked to be allowed to forge, apart from the next block; used to decide when to stop sending batches to the smart contract. For example, if we are at block 10 and SendBatchBlocksMarginCheck is 5, eventhough at block 11 we canForge, the batch will be discarded if we can't forge at block 15. - Add config parameter `TxResendTimeout`: TxResendTimeout is the timeout after which a non-mined ethereum transaction will be resent (reusing the nonce) with a newly calculated gas price - Add config parameter `MaxGasPrice`: MaxGasPrice is the maximum gas price allowed for ethereum transactions - Add config parameter `NoReuseNonce`: NoReuseNonce disables reusing nonces of pending transactions for new replacement transactions. This is useful for testing with Ganache. - Extend BatchInfo with more useful information for debugging - eth / ethereum client - Add necessary methods to create the auth object for transactions manually so that we can set the nonce, gas price, gas limit, etc manually - Update `RollupForgeBatch` to take an auth object as input (so that the coordinator can set parameters manually) - synchronizer - In stats, add `NextSlot` - In stats, store full last batch instead of just last batch number - Instead of calculating a nextSlot from scratch every time, update the current struct (only updating the forger info if we are Synced) - Afer every processed batch, check that the calculated StateDB MTRoot matches the StateRoot found in the forgeBatch event.
3 years ago
  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. // CoordAccount contains the data of the Coordinator account, that will be used
  18. // to create new transactions of CreateAccountDeposit type to add new TokenID
  19. // accounts for the Coordinator to receive the fees.
  20. type CoordAccount struct {
  21. Addr ethCommon.Address
  22. BJJ babyjub.PublicKeyComp
  23. AccountCreationAuth []byte // signature in byte array format
  24. }
  25. // TxSelector implements all the functionalities to select the txs for the next
  26. // batch
  27. type TxSelector struct {
  28. l2db *l2db.L2DB
  29. localAccountsDB *statedb.LocalStateDB
  30. coordAccount *CoordAccount
  31. }
  32. // NewTxSelector returns a *TxSelector
  33. func NewTxSelector(coordAccount *CoordAccount, dbpath string,
  34. synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
  35. localAccountsDB, err := statedb.NewLocalStateDB(
  36. statedb.Config{
  37. Path: dbpath,
  38. Keep: kvdb.DefaultKeep,
  39. Type: statedb.TypeTxSelector,
  40. NLevels: 0,
  41. },
  42. synchronizerStateDB) // without merkletree
  43. if err != nil {
  44. return nil, tracerr.Wrap(err)
  45. }
  46. return &TxSelector{
  47. l2db: l2,
  48. localAccountsDB: localAccountsDB,
  49. coordAccount: coordAccount,
  50. }, nil
  51. }
  52. // LocalAccountsDB returns the LocalStateDB of the TxSelector
  53. func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
  54. return txsel.localAccountsDB
  55. }
  56. // Reset tells the TxSelector to get it's internal AccountsDB
  57. // from the required `batchNum`
  58. func (txsel *TxSelector) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
  59. return tracerr.Wrap(txsel.localAccountsDB.Reset(batchNum, fromSynchronizer))
  60. }
  61. func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
  62. return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr,
  63. txsel.coordAccount.BJJ, tokenID)
  64. }
  65. // coordAccountForTokenID creates a new L1CoordinatorTx to create a new
  66. // Coordinator account for the given TokenID in the case that the account does
  67. // not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
  68. // account in the given array of L1CoordinatorTxs. If a new Coordinator account
  69. // needs to be created, a new L1CoordinatorTx will be returned from this
  70. // function. After calling this method, if the l1CoordinatorTx is added to the
  71. // selection, positionL1 must be increased 1.
  72. func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
  73. tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
  74. // check if CoordinatorAccount for TokenID is already pending to create
  75. if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
  76. txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
  77. return nil, positionL1, nil
  78. }
  79. _, err := txsel.getCoordIdx(tokenID)
  80. if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
  81. // create L1CoordinatorTx to create new CoordAccount for
  82. // TokenID
  83. l1CoordinatorTx := common.L1Tx{
  84. Position: positionL1,
  85. UserOrigin: false,
  86. FromEthAddr: txsel.coordAccount.Addr,
  87. FromBJJ: txsel.coordAccount.BJJ,
  88. TokenID: tokenID,
  89. Amount: big.NewInt(0),
  90. DepositAmount: big.NewInt(0),
  91. Type: common.TxTypeCreateAccountDeposit,
  92. }
  93. return &l1CoordinatorTx, positionL1, nil
  94. }
  95. if err != nil {
  96. return nil, positionL1, tracerr.Wrap(err)
  97. }
  98. // CoordAccount for TokenID already exists
  99. return nil, positionL1, nil
  100. }
  101. // GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
  102. // for the next batch, from the L2DB pool.
  103. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  104. // L2Txs. An array of bytearrays with the signatures of the
  105. // AccountCreationAuthorization of the accounts of the users created by the
  106. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  107. // but there is a transactions to them and the authorization of account
  108. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  109. // included in the next batch.
  110. func (txsel *TxSelector) GetL2TxSelection(selectionConfig txprocessor.Config) ([]common.Idx,
  111. [][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  112. metricGetL2TxSelection.Inc()
  113. coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs,
  114. discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, []common.L1Tx{})
  115. return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs,
  116. discardedL2Txs, tracerr.Wrap(err)
  117. }
  118. // GetL1L2TxSelection returns the selection of L1 + L2 txs.
  119. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  120. // L2Txs. An array of bytearrays with the signatures of the
  121. // AccountCreationAuthorization of the accounts of the users created by the
  122. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  123. // but there is a transactions to them and the authorization of account
  124. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  125. // included in the next batch.
  126. func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig txprocessor.Config,
  127. l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
  128. []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  129. metricGetL1L2TxSelection.Inc()
  130. coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
  131. discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, l1UserTxs)
  132. return coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
  133. discardedL2Txs, tracerr.Wrap(err)
  134. }
  135. func (txsel *TxSelector) getL1L2TxSelection(selectionConfig txprocessor.Config,
  136. l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
  137. []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  138. // WIP.0: the TxSelector is not optimized and will need a redesign. The
  139. // current version is implemented in order to have a functional
  140. // implementation that can be used asap.
  141. //
  142. // WIP.1: this method uses a 'cherry-pick' of internal calls of the
  143. // StateDB, a refactor of the StateDB to reorganize it internally is
  144. // planned once the main functionallities are covered, with that
  145. // refactor the TxSelector will be updated also.
  146. // get pending l2-tx from tx-pool
  147. l2TxsRaw, err := txsel.l2db.GetPendingTxs()
  148. if err != nil {
  149. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  150. }
  151. txselStateDB := txsel.localAccountsDB.StateDB
  152. tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig)
  153. // Process L1UserTxs
  154. for i := 0; i < len(l1UserTxs); i++ {
  155. // assumption: l1usertx are sorted by L1Tx.Position
  156. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
  157. if err != nil {
  158. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  159. }
  160. }
  161. var l1CoordinatorTxs []common.L1Tx
  162. positionL1 := len(l1UserTxs)
  163. var accAuths [][]byte
  164. // Sort l2TxsRaw (cropping at MaxTx at this point).
  165. // discardedL2Txs contains an array of the L2Txs that have not been
  166. // selected in this Batch.
  167. l2Txs0, discardedL2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.MaxTx)
  168. for i := range discardedL2Txs {
  169. discardedL2Txs[i].Info = "Tx not selected due to low absolute fee (does not fit inside the profitable set)"
  170. }
  171. noncesMap := make(map[common.Idx]common.Nonce)
  172. var l2Txs []common.PoolL2Tx
  173. // iterate over l2Txs
  174. // - if tx.TokenID does not exist at CoordsIdxDB
  175. // - create new L1CoordinatorTx creating a CoordAccount, for
  176. // Coordinator to receive the fee of the new TokenID
  177. for i := 0; i < len(l2Txs0); i++ {
  178. accSender, err := tp.StateDB().GetAccount(l2Txs0[i].FromIdx)
  179. if err != nil {
  180. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  181. }
  182. l2Txs0[i].TokenID = accSender.TokenID
  183. // populate the noncesMap used at the next iteration
  184. noncesMap[l2Txs0[i].FromIdx] = accSender.Nonce
  185. // if TokenID does not exist yet, create new L1CoordinatorTx to
  186. // create the CoordinatorAccount for that TokenID, to receive
  187. // the fees. Only in the case that there does not exist yet a
  188. // pending L1CoordinatorTx to create the account for the
  189. // Coordinator for that TokenID
  190. var newL1CoordTx *common.L1Tx
  191. newL1CoordTx, positionL1, err =
  192. txsel.coordAccountForTokenID(l1CoordinatorTxs,
  193. accSender.TokenID, positionL1)
  194. if err != nil {
  195. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  196. }
  197. if newL1CoordTx != nil {
  198. // if there is no space for the L1CoordinatorTx, discard the L2Tx
  199. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-len(l1UserTxs) {
  200. // discard L2Tx, and update Info parameter of
  201. // the tx, and add it to the discardedTxs array
  202. l2Txs0[i].Info = "Tx not selected because the L2Tx depends on a " +
  203. "L1CoordinatorTx and there is not enough space for L1Coordinator"
  204. discardedL2Txs = append(discardedL2Txs, l2Txs0[i])
  205. continue
  206. }
  207. // increase positionL1
  208. positionL1++
  209. l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  210. accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
  211. }
  212. l2Txs = append(l2Txs, l2Txs0[i])
  213. }
  214. var validTxs []common.PoolL2Tx
  215. // iterate over l2TxsRaw
  216. // - check Nonces
  217. // - check enough Balance for the Amount+Fee
  218. // - if needed, create new L1CoordinatorTxs for unexisting ToIdx
  219. // - keep used accAuths
  220. // - put the valid txs into validTxs array
  221. for i := 0; i < len(l2Txs); i++ {
  222. enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
  223. if !enoughBalance {
  224. // not valid Amount with current Balance. Discard L2Tx,
  225. // and update Info parameter of the tx, and add it to
  226. // the discardedTxs array
  227. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not enough Balance at the sender. "+
  228. "Current sender account Balance: %s, Amount+Fee: %s",
  229. 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. // not valid Nonce at tx. Discard L2Tx, and update Info
  237. // parameter of the tx, and add it to the discardedTxs
  238. // array
  239. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not current Nonce. "+
  240. "Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, nonce)
  241. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  242. continue
  243. }
  244. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  245. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  246. // case of TxToEthAddr or TxToBJJ, check if
  247. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  248. // used; if not, check if tx.ToEthAddr is in
  249. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  250. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  251. // Exit type and is used.
  252. if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  253. validL2Tx, l1CoordinatorTx, accAuth, err :=
  254. txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
  255. len(l1UserTxs), l1CoordinatorTxs, positionL1, l2Txs[i])
  256. if err != nil {
  257. log.Debugw("txsel.processTxToEthAddrBJJ", "err", err)
  258. // Discard L2Tx, and update Info parameter of
  259. // the tx, and add it to the discardedTxs array
  260. l2Txs[i].Info = fmt.Sprintf("Tx not selected (in processTxToEthAddrBJJ) due to %s",
  261. err.Error())
  262. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  263. continue
  264. }
  265. if l1CoordinatorTx != nil {
  266. // If ToEthAddr == 0xff.. this means that we
  267. // are handling a TransferToBJJ, which doesn't
  268. // require an authorization because it doesn't
  269. // contain a valid ethereum address.
  270. // Otherwise only create the account if we have
  271. // the corresponding authorization
  272. if validL2Tx.ToEthAddr == common.FFAddr {
  273. accAuths = append(accAuths, common.EmptyEthSignature)
  274. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  275. positionL1++
  276. } else if accAuth != nil {
  277. accAuths = append(accAuths, accAuth.Signature)
  278. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  279. positionL1++
  280. }
  281. }
  282. if validL2Tx != nil {
  283. validTxs = append(validTxs, *validL2Tx)
  284. }
  285. } else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
  286. receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
  287. if err != nil {
  288. // tx not valid
  289. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  290. "ToIdx", l2Txs[i].ToIdx)
  291. // Discard L2Tx, and update Info parameter of
  292. // the tx, and add it to the discardedTxs array
  293. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to tx.ToIdx not found in StateDB. "+
  294. "ToIdx: %d", l2Txs[i].ToIdx)
  295. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  296. continue
  297. }
  298. if l2Txs[i].ToEthAddr != common.EmptyAddr {
  299. if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
  300. log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
  301. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
  302. l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
  303. // Discard L2Tx, and update Info
  304. // parameter of the tx, and add it to
  305. // the discardedTxs array
  306. l2Txs[i].Info = fmt.Sprintf("Tx not selected because ToEthAddr "+
  307. "does not correspond to the Account.EthAddr. "+
  308. "tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
  309. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
  310. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  311. continue
  312. }
  313. }
  314. if l2Txs[i].ToBJJ != common.EmptyBJJComp {
  315. if l2Txs[i].ToBJJ != receiverAcc.BJJ {
  316. log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
  317. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
  318. "account.BJJ", receiverAcc.BJJ)
  319. // Discard L2Tx, and update Info
  320. // parameter of the tx, and add it to
  321. // the discardedTxs array
  322. l2Txs[i].Info = fmt.Sprintf("Tx not selected because tx.ToBJJ "+
  323. "does not correspond to the Account.BJJ. "+
  324. "tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
  325. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
  326. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  327. continue
  328. }
  329. }
  330. // Account found in the DB, include the l2Tx in the selection
  331. validTxs = append(validTxs, l2Txs[i])
  332. } else if l2Txs[i].ToIdx == common.Idx(1) {
  333. // valid txs (of Exit type)
  334. validTxs = append(validTxs, l2Txs[i])
  335. }
  336. noncesMap[l2Txs[i].FromIdx]++
  337. }
  338. // Process L1CoordinatorTxs
  339. for i := 0; i < len(l1CoordinatorTxs); i++ {
  340. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
  341. if err != nil {
  342. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  343. }
  344. }
  345. // get CoordIdxsMap for the TokenIDs
  346. coordIdxsMap := make(map[common.TokenID]common.Idx)
  347. for i := 0; i < len(validTxs); i++ {
  348. // get TokenID from tx.Sender
  349. accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
  350. if err != nil {
  351. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  352. }
  353. tokenID := accSender.TokenID
  354. coordIdx, err := txsel.getCoordIdx(tokenID)
  355. if err != nil {
  356. // if err is db.ErrNotFound, should not happen, as all
  357. // the validTxs.TokenID should have a CoordinatorIdx
  358. // created in the DB at this point
  359. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  360. }
  361. coordIdxsMap[tokenID] = coordIdx
  362. }
  363. var coordIdxs []common.Idx
  364. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  365. for _, idx := range coordIdxsMap {
  366. tp.AccumulatedFees[idx] = big.NewInt(0)
  367. coordIdxs = append(coordIdxs, idx)
  368. }
  369. // sort CoordIdxs
  370. sort.SliceStable(coordIdxs, func(i, j int) bool {
  371. return coordIdxs[i] < coordIdxs[j]
  372. })
  373. // get most profitable L2-tx
  374. maxL2Txs := int(selectionConfig.MaxTx) -
  375. len(l1UserTxs) - len(l1CoordinatorTxs)
  376. selectedL2Txs := validTxs
  377. if len(validTxs) > maxL2Txs {
  378. selectedL2Txs = selectedL2Txs[:maxL2Txs]
  379. }
  380. var finalL2Txs []common.PoolL2Tx
  381. for i := 0; i < len(selectedL2Txs); i++ {
  382. _, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &selectedL2Txs[i])
  383. if err != nil {
  384. // the error can be due not valid tx data, or due other
  385. // cases (such as StateDB error). At this initial
  386. // version of the TxSelector, we discard the L2Tx and
  387. // log the error, assuming that this will be iterated in
  388. // a near future.
  389. log.Error(err)
  390. // Discard L2Tx, and update Info parameter of the tx,
  391. // and add it to the discardedTxs array
  392. selectedL2Txs[i].Info = fmt.Sprintf("Tx not selected (in ProcessL2Tx) due to %s", err.Error())
  393. discardedL2Txs = append(discardedL2Txs, selectedL2Txs[i])
  394. noncesMap[selectedL2Txs[i].FromIdx]--
  395. continue
  396. }
  397. finalL2Txs = append(finalL2Txs, selectedL2Txs[i])
  398. }
  399. // distribute the AccumulatedFees from the processed L2Txs into the
  400. // Coordinator Idxs
  401. for idx, accumulatedFee := range tp.AccumulatedFees {
  402. cmp := accumulatedFee.Cmp(big.NewInt(0))
  403. if cmp == 1 { // accumulatedFee>0
  404. // send the fee to the Idx of the Coordinator for the TokenID
  405. accCoord, err := txsel.localAccountsDB.GetAccount(idx)
  406. if err != nil {
  407. log.Errorw("Can not distribute accumulated fees to coordinator "+
  408. "account: No coord Idx to receive fee", "idx", idx)
  409. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  410. }
  411. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  412. _, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
  413. if err != nil {
  414. log.Error(err)
  415. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  416. }
  417. }
  418. }
  419. err = tp.StateDB().MakeCheckpoint()
  420. if err != nil {
  421. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  422. }
  423. metricSelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
  424. metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
  425. metricSelectedL2Txs.Set(float64(len(finalL2Txs)))
  426. metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
  427. return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, finalL2Txs, discardedL2Txs, nil
  428. }
  429. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  430. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  431. // does not have an account yet, a new L1CoordinatorTx of type
  432. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  433. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  434. // array.
  435. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
  436. selectionConfig txprocessor.Config, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
  437. positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
  438. *common.AccountCreationAuth, error) {
  439. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  440. // previous L2Tx in the current process already created a
  441. // L1CoordinatorTx of this type, in the DB there still seem that needs
  442. // to create a new L1CoordinatorTx, but as is already created, the tx
  443. // is valid
  444. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  445. return &l2Tx, nil, nil, nil
  446. }
  447. var l1CoordinatorTx *common.L1Tx
  448. var accAuth *common.AccountCreationAuth
  449. if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
  450. // case: ToEthAddr != 0x00 neither 0xff
  451. if l2Tx.ToBJJ != common.EmptyBJJComp {
  452. // case: ToBJJ!=0:
  453. // if idx exist for EthAddr&BJJ use it
  454. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  455. l2Tx.ToBJJ, l2Tx.TokenID)
  456. if err == nil {
  457. // account for ToEthAddr&ToBJJ already exist,
  458. // there is no need to create a new one.
  459. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  460. return &l2Tx, nil, nil, nil
  461. }
  462. // if not, check if AccountCreationAuth exist for that
  463. // ToEthAddr
  464. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  465. if err != nil {
  466. // not found, l2Tx will not be added in the selection
  467. return nil, nil, nil,
  468. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found "+
  469. "in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  470. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  471. }
  472. if accAuth.BJJ != l2Tx.ToBJJ {
  473. // if AccountCreationAuth.BJJ is not the same
  474. // than in the tx, tx is not accepted
  475. return nil, nil, nil,
  476. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, "+
  477. "neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. "+
  478. "ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
  479. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  480. }
  481. } else {
  482. // case: ToBJJ==0:
  483. // if idx exist for EthAddr use it
  484. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  485. if err == nil {
  486. // account for ToEthAddr already exist,
  487. // there is no need to create a new one.
  488. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  489. return &l2Tx, nil, nil, nil
  490. }
  491. // if not, check if AccountCreationAuth exist for that ToEthAddr
  492. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  493. if err != nil {
  494. // not found, l2Tx will not be added in the selection
  495. return nil, nil, nil,
  496. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in "+
  497. "StateDB, neither ToEthAddr found in "+
  498. "AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  499. l2Tx.ToIdx, l2Tx.ToEthAddr))
  500. }
  501. }
  502. // create L1CoordinatorTx for the accountCreation
  503. l1CoordinatorTx = &common.L1Tx{
  504. Position: positionL1,
  505. UserOrigin: false,
  506. FromEthAddr: accAuth.EthAddr,
  507. FromBJJ: accAuth.BJJ,
  508. TokenID: l2Tx.TokenID,
  509. Amount: big.NewInt(0),
  510. DepositAmount: big.NewInt(0),
  511. Type: common.TxTypeCreateAccountDeposit,
  512. }
  513. } else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
  514. // if idx exist for EthAddr&BJJ use it
  515. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  516. l2Tx.TokenID)
  517. if err == nil {
  518. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  519. // there is no need to create a new one.
  520. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  521. return &l2Tx, nil, nil, nil
  522. }
  523. // if idx don't exist for EthAddr&BJJ, coordinator can create a
  524. // new account without L1Authorization, as ToEthAddr==0xff
  525. // create L1CoordinatorTx for the accountCreation
  526. l1CoordinatorTx = &common.L1Tx{
  527. Position: positionL1,
  528. UserOrigin: false,
  529. FromEthAddr: l2Tx.ToEthAddr,
  530. FromBJJ: l2Tx.ToBJJ,
  531. TokenID: l2Tx.TokenID,
  532. Amount: big.NewInt(0),
  533. DepositAmount: big.NewInt(0),
  534. Type: common.TxTypeCreateAccountDeposit,
  535. }
  536. }
  537. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1UserTxs {
  538. // L2Tx discarded
  539. return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
  540. "for L1CoordinatorTx to create a new account for receiver of L2Tx"))
  541. }
  542. return &l2Tx, l1CoordinatorTx, accAuth, nil
  543. }
  544. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  545. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  546. for i := 0; i < len(l1CoordinatorTxs); i++ {
  547. if l1CoordinatorTxs[i].FromEthAddr == addr &&
  548. l1CoordinatorTxs[i].TokenID == tokenID &&
  549. l1CoordinatorTxs[i].FromBJJ == bjj {
  550. return true
  551. }
  552. }
  553. return false
  554. }
  555. // getL2Profitable returns the profitable selection of L2Txssorted by Nonce
  556. func (txsel *TxSelector) getL2Profitable(l2Txs []common.PoolL2Tx, max uint32) ([]common.PoolL2Tx,
  557. []common.PoolL2Tx) {
  558. // First sort by nonce so that txs from the same account are sorted so
  559. // that they could be applied in succession.
  560. sort.Slice(l2Txs, func(i, j int) bool {
  561. return l2Txs[i].Nonce < l2Txs[j].Nonce
  562. })
  563. // Sort by absolute fee with SliceStable, so that txs with same
  564. // AbsoluteFee are not rearranged and nonce order is kept in such case
  565. sort.SliceStable(l2Txs, func(i, j int) bool {
  566. return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
  567. })
  568. discardedL2Txs := []common.PoolL2Tx{}
  569. if len(l2Txs) > int(max) {
  570. discardedL2Txs = l2Txs[max:]
  571. l2Txs = l2Txs[:max]
  572. }
  573. // sort l2Txs by Nonce. This can be done in many different ways, what
  574. // is needed is to output the l2Txs where the Nonce of l2Txs for each
  575. // Account is sorted, but the l2Txs can not be grouped by sender Account
  576. // neither by Fee. This is because later on the Nonces will need to be
  577. // sequential for the zkproof generation.
  578. sort.Slice(l2Txs, func(i, j int) bool {
  579. return l2Txs[i].Nonce < l2Txs[j].Nonce
  580. })
  581. return l2Txs, discardedL2Txs
  582. }