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.

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