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.

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