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.

669 lines
26 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. // 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 txprocessor.Config,
  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. // Steps of this method:
  150. // - getPendingTxs
  151. // - ProcessL1Txs
  152. // - getProfitable (sort by fee & nonce)
  153. // - loop over l2Txs
  154. // - Fill tx.TokenID tx.Nonce
  155. // - Check enough Balance on sender
  156. // - Check Nonce
  157. // - Create CoordAccount L1CoordTx for TokenID if needed
  158. // - & ProcessL1Tx of L1CoordTx
  159. // - Check validity of receiver Account for ToEthAddr / ToBJJ
  160. // - Create UserAccount L1CoordTx if needed (and possible)
  161. // - If everything is fine, store l2Tx to validTxs & update NoncesMap
  162. // - Prepare coordIdxsMap & AccumulatedFees
  163. // - Distribute AccumulatedFees to CoordIdxs
  164. // - MakeCheckpoint
  165. // get pending l2-tx from tx-pool
  166. l2TxsRaw, err := txsel.l2db.GetPendingTxs()
  167. if err != nil {
  168. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  169. }
  170. txselStateDB := txsel.localAccountsDB.StateDB
  171. tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig)
  172. // Process L1UserTxs
  173. for i := 0; i < len(l1UserTxs); i++ {
  174. // assumption: l1usertx are sorted by L1Tx.Position
  175. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
  176. if err != nil {
  177. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  178. }
  179. }
  180. var l1CoordinatorTxs []common.L1Tx
  181. positionL1 := len(l1UserTxs)
  182. var accAuths [][]byte
  183. // Sort l2TxsRaw (cropping at MaxTx at this point).
  184. // discardedL2Txs contains an array of the L2Txs that have not been
  185. // selected in this Batch.
  186. l2Txs, discardedL2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.MaxTx-uint32(len(l1UserTxs)))
  187. for i := range discardedL2Txs {
  188. discardedL2Txs[i].Info =
  189. "Tx not selected due to low absolute fee (does not fit inside the profitable set)"
  190. }
  191. var validTxs []common.PoolL2Tx
  192. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  193. // Iterate over l2Txs
  194. // - check Nonces
  195. // - check enough Balance for the Amount+Fee
  196. // - if needed, create new L1CoordinatorTxs for unexisting ToIdx
  197. // - keep used accAuths
  198. // - put the valid txs into validTxs array
  199. for i := 0; i < len(l2Txs); i++ {
  200. // Check if there is space for more L2Txs in the selection
  201. maxL2Txs := int(selectionConfig.MaxTx) -
  202. len(l1UserTxs) - len(l1CoordinatorTxs)
  203. if len(validTxs) >= maxL2Txs {
  204. // no more available slots for L2Txs
  205. l2Txs[i].Info =
  206. "Tx not selected due not available slots for L2Txs"
  207. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  208. continue
  209. }
  210. // get Nonce & TokenID from the Account by l2Tx.FromIdx
  211. accSender, err := tp.StateDB().GetAccount(l2Txs[i].FromIdx)
  212. if err != nil {
  213. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  214. }
  215. l2Txs[i].TokenID = accSender.TokenID
  216. // Check enough Balance on sender
  217. enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
  218. if !enoughBalance {
  219. // not valid Amount with current Balance. Discard L2Tx,
  220. // and update Info parameter of the tx, and add it to
  221. // the discardedTxs array
  222. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not enough Balance at the sender. "+
  223. "Current sender account Balance: %s, Amount+Fee: %s",
  224. balance.String(), feeAndAmount.String())
  225. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  226. continue
  227. }
  228. // Check if Nonce is correct
  229. if l2Txs[i].Nonce != accSender.Nonce {
  230. // not valid Nonce at tx. Discard L2Tx, and update Info
  231. // parameter of the tx, and add it to the discardedTxs
  232. // array
  233. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not current Nonce. "+
  234. "Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, accSender.Nonce)
  235. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  236. continue
  237. }
  238. // if TokenID does not exist yet, create new L1CoordinatorTx to
  239. // create the CoordinatorAccount for that TokenID, to receive
  240. // the fees. Only in the case that there does not exist yet a
  241. // pending L1CoordinatorTx to create the account for the
  242. // Coordinator for that TokenID
  243. var newL1CoordTx *common.L1Tx
  244. newL1CoordTx, positionL1, err =
  245. txsel.coordAccountForTokenID(l1CoordinatorTxs,
  246. accSender.TokenID, positionL1)
  247. if err != nil {
  248. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  249. }
  250. if newL1CoordTx != nil {
  251. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  252. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  253. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-len(l1UserTxs) ||
  254. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-len(l1UserTxs) {
  255. // discard L2Tx, and update Info parameter of
  256. // the tx, and add it to the discardedTxs array
  257. l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
  258. "L1CoordinatorTx and there is not enough space for L1Coordinator"
  259. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  260. continue
  261. }
  262. // increase positionL1
  263. positionL1++
  264. l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  265. accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
  266. // process the L1CoordTx
  267. _, _, _, _, err := tp.ProcessL1Tx(nil, newL1CoordTx)
  268. if err != nil {
  269. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  270. }
  271. }
  272. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  273. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  274. // case of TxToEthAddr or TxToBJJ, check if
  275. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  276. // used; if not, check if tx.ToEthAddr is in
  277. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  278. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  279. // Exit type and is used.
  280. if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  281. validL2Tx, l1CoordinatorTx, accAuth, err :=
  282. txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
  283. len(l1UserTxs), l1CoordinatorTxs, positionL1, l2Txs[i])
  284. if err != nil {
  285. log.Debugw("txsel.processTxToEthAddrBJJ", "err", err)
  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 (in processTxToEthAddrBJJ) due to %s",
  289. err.Error())
  290. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  291. continue
  292. }
  293. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  294. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  295. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-len(l1UserTxs) ||
  296. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-len(l1UserTxs) {
  297. // discard L2Tx, and update Info parameter of
  298. // the tx, and add it to the discardedTxs array
  299. l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
  300. "L1CoordinatorTx and there is not enough space for L1Coordinator"
  301. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  302. continue
  303. }
  304. if l1CoordinatorTx != nil && validL2Tx != nil {
  305. // If ToEthAddr == 0xff.. this means that we
  306. // are handling a TransferToBJJ, which doesn't
  307. // require an authorization because it doesn't
  308. // contain a valid ethereum address.
  309. // Otherwise only create the account if we have
  310. // the corresponding authorization
  311. if validL2Tx.ToEthAddr == common.FFAddr {
  312. accAuths = append(accAuths, common.EmptyEthSignature)
  313. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  314. positionL1++
  315. } else if accAuth != nil {
  316. accAuths = append(accAuths, accAuth.Signature)
  317. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  318. positionL1++
  319. }
  320. // process the L1CoordTx
  321. _, _, _, _, err := tp.ProcessL1Tx(nil, l1CoordinatorTx)
  322. if err != nil {
  323. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  324. }
  325. }
  326. if validL2Tx == nil {
  327. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  328. continue
  329. }
  330. } else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
  331. receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
  332. if err != nil {
  333. // tx not valid
  334. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  335. "ToIdx", l2Txs[i].ToIdx)
  336. // Discard L2Tx, and update Info parameter of
  337. // the tx, and add it to the discardedTxs array
  338. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to tx.ToIdx not found in StateDB. "+
  339. "ToIdx: %d", l2Txs[i].ToIdx)
  340. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  341. continue
  342. }
  343. if l2Txs[i].ToEthAddr != common.EmptyAddr {
  344. if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
  345. log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
  346. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
  347. l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
  348. // Discard L2Tx, and update Info
  349. // parameter of the tx, and add it to
  350. // the discardedTxs array
  351. l2Txs[i].Info = fmt.Sprintf("Tx not selected because ToEthAddr "+
  352. "does not correspond to the Account.EthAddr. "+
  353. "tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
  354. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
  355. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  356. continue
  357. }
  358. }
  359. if l2Txs[i].ToBJJ != common.EmptyBJJComp {
  360. if l2Txs[i].ToBJJ != receiverAcc.BJJ {
  361. log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
  362. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
  363. "account.BJJ", receiverAcc.BJJ)
  364. // Discard L2Tx, and update Info
  365. // parameter of the tx, and add it to
  366. // the discardedTxs array
  367. l2Txs[i].Info = fmt.Sprintf("Tx not selected because tx.ToBJJ "+
  368. "does not correspond to the Account.BJJ. "+
  369. "tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
  370. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
  371. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  372. continue
  373. }
  374. }
  375. }
  376. // get CoordIdxsMap for the TokenID of the current l2Txs[i]
  377. // get TokenID from tx.Sender account
  378. tokenID := accSender.TokenID
  379. coordIdx, err := txsel.getCoordIdx(tokenID)
  380. if err != nil {
  381. // if err is db.ErrNotFound, should not happen, as all
  382. // the validTxs.TokenID should have a CoordinatorIdx
  383. // created in the DB at this point
  384. return nil, nil, nil, nil, nil, nil,
  385. tracerr.Wrap(fmt.Errorf("Could not get CoordIdx for TokenID=%d, "+
  386. "due: %s", tokenID, err))
  387. }
  388. // prepare temp coordIdxsMap & AccumulatedFees for the call to
  389. // ProcessL2Tx
  390. coordIdxsMap := map[common.TokenID]common.Idx{tokenID: coordIdx}
  391. // tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  392. if _, ok := tp.AccumulatedFees[coordIdx]; !ok {
  393. tp.AccumulatedFees[coordIdx] = big.NewInt(0)
  394. }
  395. _, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
  396. if err != nil {
  397. log.Debugw("txselector.getL1L2TxSelection at ProcessL2Tx", "err", err)
  398. // Discard L2Tx, and update Info parameter of the tx,
  399. // and add it to the discardedTxs array
  400. l2Txs[i].Info = fmt.Sprintf("Tx not selected (in ProcessL2Tx) due to %s",
  401. err.Error())
  402. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  403. continue
  404. }
  405. validTxs = append(validTxs, l2Txs[i])
  406. } // after this loop, no checks to discard txs should be done
  407. // get CoordIdxsMap for the TokenIDs
  408. coordIdxsMap := make(map[common.TokenID]common.Idx)
  409. for i := 0; i < len(validTxs); i++ {
  410. // get TokenID from tx.Sender
  411. accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
  412. if err != nil {
  413. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  414. }
  415. tokenID := accSender.TokenID
  416. coordIdx, err := txsel.getCoordIdx(tokenID)
  417. if err != nil {
  418. // if err is db.ErrNotFound, should not happen, as all
  419. // the validTxs.TokenID should have a CoordinatorIdx
  420. // created in the DB at this point
  421. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  422. }
  423. coordIdxsMap[tokenID] = coordIdx
  424. }
  425. var coordIdxs []common.Idx
  426. for _, idx := range coordIdxsMap {
  427. coordIdxs = append(coordIdxs, idx)
  428. }
  429. // sort CoordIdxs
  430. sort.SliceStable(coordIdxs, func(i, j int) bool {
  431. return coordIdxs[i] < coordIdxs[j]
  432. })
  433. // distribute the AccumulatedFees from the processed L2Txs into the
  434. // Coordinator Idxs
  435. for idx, accumulatedFee := range tp.AccumulatedFees {
  436. cmp := accumulatedFee.Cmp(big.NewInt(0))
  437. if cmp == 1 { // accumulatedFee>0
  438. // send the fee to the Idx of the Coordinator for the TokenID
  439. accCoord, err := txsel.localAccountsDB.GetAccount(idx)
  440. if err != nil {
  441. log.Errorw("Can not distribute accumulated fees to coordinator "+
  442. "account: No coord Idx to receive fee", "idx", idx)
  443. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  444. }
  445. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  446. _, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
  447. if err != nil {
  448. log.Error(err)
  449. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  450. }
  451. }
  452. }
  453. err = tp.StateDB().MakeCheckpoint()
  454. if err != nil {
  455. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  456. }
  457. metricSelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
  458. metricSelectedL1UserTxs.Set(float64(len(l1UserTxs)))
  459. metricSelectedL2Txs.Set(float64(len(validTxs)))
  460. metricDiscardedL2Txs.Set(float64(len(discardedL2Txs)))
  461. // return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
  462. return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
  463. }
  464. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  465. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  466. // does not have an account yet, a new L1CoordinatorTx of type
  467. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  468. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  469. // array.
  470. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
  471. selectionConfig txprocessor.Config, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
  472. positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
  473. *common.AccountCreationAuth, error) {
  474. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  475. // previous L2Tx in the current process already created a
  476. // L1CoordinatorTx of this type, in the DB there still seem that needs
  477. // to create a new L1CoordinatorTx, but as is already created, the tx
  478. // is valid
  479. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  480. return &l2Tx, nil, nil, nil
  481. }
  482. var l1CoordinatorTx *common.L1Tx
  483. var accAuth *common.AccountCreationAuth
  484. if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
  485. // case: ToEthAddr != 0x00 neither 0xff
  486. if l2Tx.ToBJJ != common.EmptyBJJComp {
  487. // case: ToBJJ!=0:
  488. // if idx exist for EthAddr&BJJ use it
  489. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  490. l2Tx.ToBJJ, l2Tx.TokenID)
  491. if err == nil {
  492. // account for ToEthAddr&ToBJJ already exist,
  493. // there is no need to create a new one.
  494. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  495. return &l2Tx, nil, nil, nil
  496. }
  497. // if not, check if AccountCreationAuth exist for that
  498. // ToEthAddr
  499. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  500. if err != nil {
  501. // not found, l2Tx will not be added in the selection
  502. return nil, nil, nil,
  503. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found "+
  504. "in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  505. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  506. }
  507. if accAuth.BJJ != l2Tx.ToBJJ {
  508. // if AccountCreationAuth.BJJ is not the same
  509. // than in the tx, tx is not accepted
  510. return nil, nil, nil,
  511. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, "+
  512. "neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. "+
  513. "ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
  514. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  515. }
  516. } else {
  517. // case: ToBJJ==0:
  518. // if idx exist for EthAddr use it
  519. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  520. if err == nil {
  521. // account for ToEthAddr already exist,
  522. // there is no need to create a new one.
  523. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  524. return &l2Tx, nil, nil, nil
  525. }
  526. // if not, check if AccountCreationAuth exist for that ToEthAddr
  527. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  528. if err != nil {
  529. // not found, l2Tx will not be added in the selection
  530. return nil, nil, nil,
  531. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in "+
  532. "StateDB, neither ToEthAddr found in "+
  533. "AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  534. l2Tx.ToIdx, l2Tx.ToEthAddr))
  535. }
  536. }
  537. // create L1CoordinatorTx for the accountCreation
  538. l1CoordinatorTx = &common.L1Tx{
  539. Position: positionL1,
  540. UserOrigin: false,
  541. FromEthAddr: accAuth.EthAddr,
  542. FromBJJ: accAuth.BJJ,
  543. TokenID: l2Tx.TokenID,
  544. Amount: big.NewInt(0),
  545. DepositAmount: big.NewInt(0),
  546. Type: common.TxTypeCreateAccountDeposit,
  547. }
  548. } else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
  549. // if idx exist for EthAddr&BJJ use it
  550. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  551. l2Tx.TokenID)
  552. if err == nil {
  553. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  554. // there is no need to create a new one.
  555. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  556. return &l2Tx, nil, nil, nil
  557. }
  558. // if idx don't exist for EthAddr&BJJ, coordinator can create a
  559. // new account without L1Authorization, as ToEthAddr==0xff
  560. // create L1CoordinatorTx for the accountCreation
  561. l1CoordinatorTx = &common.L1Tx{
  562. Position: positionL1,
  563. UserOrigin: false,
  564. FromEthAddr: l2Tx.ToEthAddr,
  565. FromBJJ: l2Tx.ToBJJ,
  566. TokenID: l2Tx.TokenID,
  567. Amount: big.NewInt(0),
  568. DepositAmount: big.NewInt(0),
  569. Type: common.TxTypeCreateAccountDeposit,
  570. }
  571. }
  572. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  573. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  574. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1UserTxs ||
  575. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1UserTxs {
  576. // L2Tx discarded
  577. return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
  578. "for L1CoordinatorTx to create a new account for receiver of L2Tx"))
  579. }
  580. return &l2Tx, l1CoordinatorTx, accAuth, nil
  581. }
  582. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  583. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  584. for i := 0; i < len(l1CoordinatorTxs); i++ {
  585. if l1CoordinatorTxs[i].FromEthAddr == addr &&
  586. l1CoordinatorTxs[i].TokenID == tokenID &&
  587. l1CoordinatorTxs[i].FromBJJ == bjj {
  588. return true
  589. }
  590. }
  591. return false
  592. }
  593. // getL2Profitable returns the profitable selection of L2Txssorted by Nonce
  594. func (txsel *TxSelector) getL2Profitable(l2Txs []common.PoolL2Tx, max uint32) ([]common.PoolL2Tx,
  595. []common.PoolL2Tx) {
  596. // First sort by nonce so that txs from the same account are sorted so
  597. // that they could be applied in succession.
  598. sort.Slice(l2Txs, func(i, j int) bool {
  599. return l2Txs[i].Nonce < l2Txs[j].Nonce
  600. })
  601. // Sort by absolute fee with SliceStable, so that txs with same
  602. // AbsoluteFee are not rearranged and nonce order is kept in such case
  603. sort.SliceStable(l2Txs, func(i, j int) bool {
  604. return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
  605. })
  606. discardedL2Txs := []common.PoolL2Tx{}
  607. if len(l2Txs) > int(max) {
  608. discardedL2Txs = l2Txs[max:]
  609. l2Txs = l2Txs[:max]
  610. }
  611. // sort l2Txs by Nonce. This can be done in many different ways, what
  612. // is needed is to output the l2Txs where the Nonce of l2Txs for each
  613. // Account is sorted, but the l2Txs can not be grouped by sender Account
  614. // neither by Fee. This is because later on the Nonces will need to be
  615. // sequential for the zkproof generation.
  616. sort.Slice(l2Txs, func(i, j int) bool {
  617. return l2Txs[i].Nonce < l2Txs[j].Nonce
  618. })
  619. return l2Txs, discardedL2Txs
  620. }