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.

745 lines
29 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/metric"
  14. "github.com/hermeznetwork/hermez-node/txprocessor"
  15. "github.com/hermeznetwork/tracerr"
  16. "github.com/iden3/go-iden3-crypto/babyjub"
  17. )
  18. // CoordAccount contains the data of the Coordinator account, that will be used
  19. // to create new transactions of CreateAccountDeposit type to add new TokenID
  20. // accounts for the Coordinator to receive the fees.
  21. type CoordAccount struct {
  22. Addr ethCommon.Address
  23. BJJ babyjub.PublicKeyComp
  24. AccountCreationAuth []byte // signature in byte array format
  25. }
  26. // TxSelector implements all the functionalities to select the txs for the next
  27. // batch
  28. type TxSelector struct {
  29. l2db *l2db.L2DB
  30. localAccountsDB *statedb.LocalStateDB
  31. coordAccount *CoordAccount
  32. }
  33. // NewTxSelector returns a *TxSelector
  34. func NewTxSelector(coordAccount *CoordAccount, dbpath string,
  35. synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
  36. localAccountsDB, err := statedb.NewLocalStateDB(
  37. statedb.Config{
  38. Path: dbpath,
  39. Keep: kvdb.DefaultKeep,
  40. Type: statedb.TypeTxSelector,
  41. NLevels: 0,
  42. },
  43. synchronizerStateDB) // without merkletree
  44. if err != nil {
  45. return nil, tracerr.Wrap(err)
  46. }
  47. return &TxSelector{
  48. l2db: l2,
  49. localAccountsDB: localAccountsDB,
  50. coordAccount: coordAccount,
  51. }, nil
  52. }
  53. // LocalAccountsDB returns the LocalStateDB of the TxSelector
  54. func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
  55. return txsel.localAccountsDB
  56. }
  57. // Reset tells the TxSelector to get it's internal AccountsDB
  58. // from the required `batchNum`
  59. func (txsel *TxSelector) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
  60. return tracerr.Wrap(txsel.localAccountsDB.Reset(batchNum, fromSynchronizer))
  61. }
  62. func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
  63. return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr,
  64. txsel.coordAccount.BJJ, tokenID)
  65. }
  66. // coordAccountForTokenID creates a new L1CoordinatorTx to create a new
  67. // Coordinator account for the given TokenID in the case that the account does
  68. // not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
  69. // account in the given array of L1CoordinatorTxs. If a new Coordinator account
  70. // needs to be created, a new L1CoordinatorTx will be returned from this
  71. // function. After calling this method, if the l1CoordinatorTx is added to the
  72. // selection, positionL1 must be increased 1.
  73. func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
  74. tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
  75. // check if CoordinatorAccount for TokenID is already pending to create
  76. if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
  77. txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
  78. return nil, positionL1, nil
  79. }
  80. _, err := txsel.getCoordIdx(tokenID)
  81. if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
  82. // create L1CoordinatorTx to create new CoordAccount for
  83. // TokenID
  84. l1CoordinatorTx := common.L1Tx{
  85. Position: positionL1,
  86. UserOrigin: false,
  87. FromEthAddr: txsel.coordAccount.Addr,
  88. FromBJJ: txsel.coordAccount.BJJ,
  89. TokenID: tokenID,
  90. Amount: big.NewInt(0),
  91. DepositAmount: big.NewInt(0),
  92. Type: common.TxTypeCreateAccountDeposit,
  93. }
  94. return &l1CoordinatorTx, positionL1, nil
  95. }
  96. if err != nil {
  97. return nil, positionL1, tracerr.Wrap(err)
  98. }
  99. // CoordAccount for TokenID already exists
  100. return nil, positionL1, nil
  101. }
  102. // GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
  103. // for the next batch, from the L2DB pool.
  104. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  105. // L2Txs. An array of bytearrays with the signatures of the
  106. // AccountCreationAuthorization of the accounts of the users created by the
  107. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  108. // but there is a transactions to them and the authorization of account
  109. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  110. // included in the next batch.
  111. func (txsel *TxSelector) GetL2TxSelection(selectionConfig txprocessor.Config) ([]common.Idx,
  112. [][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  113. metric.GetL2TxSelection.Inc()
  114. coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs,
  115. discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, []common.L1Tx{})
  116. return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs,
  117. discardedL2Txs, tracerr.Wrap(err)
  118. }
  119. // GetL1L2TxSelection returns the selection of L1 + L2 txs.
  120. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  121. // L2Txs. An array of bytearrays with the signatures of the
  122. // AccountCreationAuthorization of the accounts of the users created by the
  123. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  124. // but there is a transactions to them and the authorization of account
  125. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  126. // included in the next batch.
  127. func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig txprocessor.Config,
  128. l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
  129. []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  130. metric.GetL1L2TxSelection.Inc()
  131. coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
  132. discardedL2Txs, err := txsel.getL1L2TxSelection(selectionConfig, l1UserTxs)
  133. return coordIdxs, accCreationAuths, l1UserTxs, l1CoordinatorTxs, l2Txs,
  134. discardedL2Txs, tracerr.Wrap(err)
  135. }
  136. // getL1L2TxSelection returns the selection of L1 + L2 txs.
  137. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  138. // L2Txs. An array of bytearrays with the signatures of the
  139. // AccountCreationAuthorization of the accounts of the users created by the
  140. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  141. // but there is a transactions to them and the authorization of account
  142. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  143. // included in the next batch.
  144. func (txsel *TxSelector) getL1L2TxSelection(selectionConfig txprocessor.Config,
  145. l1UserTxs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
  146. []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  147. // WIP.0: the TxSelector is not optimized and will need a redesign. The
  148. // current version is implemented in order to have a functional
  149. // implementation that can be used ASAP.
  150. // Steps of this method:
  151. // - ProcessL1Txs (User txs)
  152. // - getPendingTxs (forgable directly with current state & not forgable
  153. // yet)
  154. // - split between l2TxsForgable & l2TxsNonForgable, where:
  155. // - l2TxsForgable are the txs that are directly forgable with the
  156. // current state
  157. // - l2TxsNonForgable are the txs that are not directly forgable
  158. // with the current state, but that may be forgable once the
  159. // l2TxsForgable ones are processed
  160. // - for l2TxsForgable, and if needed, for l2TxsNonForgable:
  161. // - sort by Fee & Nonce
  162. // - loop over l2Txs (txsel.processL2Txs)
  163. // - Fill tx.TokenID tx.Nonce
  164. // - Check enough Balance on sender
  165. // - Check Nonce
  166. // - Create CoordAccount L1CoordTx for TokenID if needed
  167. // - & ProcessL1Tx of L1CoordTx
  168. // - Check validity of receiver Account for ToEthAddr / ToBJJ
  169. // - Create UserAccount L1CoordTx if needed (and possible)
  170. // - If everything is fine, store l2Tx to validTxs & update NoncesMap
  171. // - Prepare coordIdxsMap & AccumulatedFees
  172. // - Distribute AccumulatedFees to CoordIdxs
  173. // - MakeCheckpoint
  174. txselStateDB := txsel.localAccountsDB.StateDB
  175. tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig)
  176. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  177. // Process L1UserTxs
  178. for i := 0; i < len(l1UserTxs); i++ {
  179. // assumption: l1usertx are sorted by L1Tx.Position
  180. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1UserTxs[i])
  181. if err != nil {
  182. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  183. }
  184. }
  185. l2TxsFromDB, err := txsel.l2db.GetPendingTxs()
  186. if err != nil {
  187. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  188. }
  189. l2TxsForgable, l2TxsNonForgable := splitL2ForgableAndNonForgable(tp, l2TxsFromDB)
  190. // in case that length of l2TxsForgable is 0, no need to continue, there
  191. // is no L2Txs to forge at all
  192. if len(l2TxsForgable) == 0 {
  193. var discardedL2Txs []common.PoolL2Tx
  194. for i := 0; i < len(l2TxsNonForgable); i++ {
  195. l2TxsNonForgable[i].Info =
  196. "Tx not selected due impossibility to be forged with the current state"
  197. discardedL2Txs = append(discardedL2Txs, l2TxsNonForgable[i])
  198. }
  199. err = tp.StateDB().MakeCheckpoint()
  200. if err != nil {
  201. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  202. }
  203. metric.SelectedL1UserTxs.Set(float64(len(l1UserTxs)))
  204. metric.SelectedL1CoordinatorTxs.Set(0)
  205. metric.SelectedL2Txs.Set(0)
  206. metric.DiscardedL2Txs.Set(float64(len(discardedL2Txs)))
  207. return nil, nil, l1UserTxs, nil, nil, discardedL2Txs, nil
  208. }
  209. var accAuths [][]byte
  210. var l1CoordinatorTxs []common.L1Tx
  211. var validTxs, discardedL2Txs []common.PoolL2Tx
  212. l2TxsForgable = sortL2Txs(l2TxsForgable)
  213. accAuths, l1CoordinatorTxs, validTxs, discardedL2Txs, err =
  214. txsel.processL2Txs(tp, selectionConfig, len(l1UserTxs),
  215. l2TxsForgable, validTxs, discardedL2Txs)
  216. if err != nil {
  217. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  218. }
  219. // if there is space for more txs get also the NonForgable txs, that may
  220. // be unblocked once the Forgable ones are processed
  221. if len(validTxs) < int(selectionConfig.MaxTx)-(len(l1UserTxs)+len(l1CoordinatorTxs)) {
  222. l2TxsNonForgable = sortL2Txs(l2TxsNonForgable)
  223. var accAuths2 [][]byte
  224. var l1CoordinatorTxs2 []common.L1Tx
  225. accAuths2, l1CoordinatorTxs2, validTxs, discardedL2Txs, err =
  226. txsel.processL2Txs(tp, selectionConfig,
  227. len(l1UserTxs)+len(l1CoordinatorTxs), l2TxsNonForgable,
  228. validTxs, discardedL2Txs)
  229. if err != nil {
  230. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  231. }
  232. accAuths = append(accAuths, accAuths2...)
  233. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTxs2...)
  234. } else {
  235. // if there is no space for NonForgable txs, put them at the
  236. // discardedL2Txs array
  237. for i := 0; i < len(l2TxsNonForgable); i++ {
  238. l2TxsNonForgable[i].Info =
  239. "Tx not selected due not available slots for L2Txs"
  240. discardedL2Txs = append(discardedL2Txs, l2TxsNonForgable[i])
  241. }
  242. }
  243. // get CoordIdxsMap for the TokenIDs
  244. coordIdxsMap := make(map[common.TokenID]common.Idx)
  245. for i := 0; i < len(validTxs); i++ {
  246. // get TokenID from tx.Sender
  247. accSender, err := tp.StateDB().GetAccount(validTxs[i].FromIdx)
  248. if err != nil {
  249. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  250. }
  251. tokenID := accSender.TokenID
  252. coordIdx, err := txsel.getCoordIdx(tokenID)
  253. if err != nil {
  254. // if err is db.ErrNotFound, should not happen, as all
  255. // the validTxs.TokenID should have a CoordinatorIdx
  256. // created in the DB at this point
  257. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  258. }
  259. coordIdxsMap[tokenID] = coordIdx
  260. }
  261. var coordIdxs []common.Idx
  262. for _, idx := range coordIdxsMap {
  263. coordIdxs = append(coordIdxs, idx)
  264. }
  265. // sort CoordIdxs
  266. sort.SliceStable(coordIdxs, func(i, j int) bool {
  267. return coordIdxs[i] < coordIdxs[j]
  268. })
  269. // distribute the AccumulatedFees from the processed L2Txs into the
  270. // Coordinator Idxs
  271. for idx, accumulatedFee := range tp.AccumulatedFees {
  272. cmp := accumulatedFee.Cmp(big.NewInt(0))
  273. if cmp == 1 { // accumulatedFee>0
  274. // send the fee to the Idx of the Coordinator for the TokenID
  275. accCoord, err := txsel.localAccountsDB.GetAccount(idx)
  276. if err != nil {
  277. log.Errorw("Can not distribute accumulated fees to coordinator "+
  278. "account: No coord Idx to receive fee", "idx", idx)
  279. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  280. }
  281. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  282. _, err = txsel.localAccountsDB.UpdateAccount(idx, accCoord)
  283. if err != nil {
  284. log.Error(err)
  285. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  286. }
  287. }
  288. }
  289. err = tp.StateDB().MakeCheckpoint()
  290. if err != nil {
  291. return nil, nil, nil, nil, nil, nil, tracerr.Wrap(err)
  292. }
  293. metric.SelectedL1CoordinatorTxs.Set(float64(len(l1CoordinatorTxs)))
  294. metric.SelectedL1UserTxs.Set(float64(len(l1UserTxs)))
  295. metric.SelectedL2Txs.Set(float64(len(validTxs)))
  296. metric.DiscardedL2Txs.Set(float64(len(discardedL2Txs)))
  297. return coordIdxs, accAuths, l1UserTxs, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
  298. }
  299. func (txsel *TxSelector) processL2Txs(tp *txprocessor.TxProcessor,
  300. selectionConfig txprocessor.Config, nL1Txs int, l2Txs, validTxs, discardedL2Txs []common.PoolL2Tx) (
  301. [][]byte, []common.L1Tx, []common.PoolL2Tx, []common.PoolL2Tx, error) {
  302. var l1CoordinatorTxs []common.L1Tx
  303. positionL1 := nL1Txs
  304. var accAuths [][]byte
  305. // Iterate over l2Txs
  306. // - check Nonces
  307. // - check enough Balance for the Amount+Fee
  308. // - if needed, create new L1CoordinatorTxs for unexisting ToIdx
  309. // - keep used accAuths
  310. // - put the valid txs into validTxs array
  311. for i := 0; i < len(l2Txs); i++ {
  312. // Check if there is space for more L2Txs in the selection
  313. maxL2Txs := int(selectionConfig.MaxTx) - nL1Txs - len(l1CoordinatorTxs)
  314. if len(validTxs) >= maxL2Txs {
  315. // no more available slots for L2Txs, so mark this tx
  316. // but also the rest of remaining txs as discarded
  317. for j := i; j < len(l2Txs); j++ {
  318. l2Txs[j].Info =
  319. "Tx not selected due not available slots for L2Txs"
  320. discardedL2Txs = append(discardedL2Txs, l2Txs[j])
  321. }
  322. break
  323. }
  324. // get Nonce & TokenID from the Account by l2Tx.FromIdx
  325. accSender, err := tp.StateDB().GetAccount(l2Txs[i].FromIdx)
  326. if err != nil {
  327. return nil, nil, nil, nil, tracerr.Wrap(err)
  328. }
  329. l2Txs[i].TokenID = accSender.TokenID
  330. // Check enough Balance on sender
  331. enoughBalance, balance, feeAndAmount := tp.CheckEnoughBalance(l2Txs[i])
  332. if !enoughBalance {
  333. // not valid Amount with current Balance. Discard L2Tx,
  334. // and update Info parameter of the tx, and add it to
  335. // the discardedTxs array
  336. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not enough Balance at the sender. "+
  337. "Current sender account Balance: %s, Amount+Fee: %s",
  338. balance.String(), feeAndAmount.String())
  339. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  340. continue
  341. }
  342. // Check if Nonce is correct
  343. if l2Txs[i].Nonce != accSender.Nonce {
  344. // not valid Nonce at tx. Discard L2Tx, and update Info
  345. // parameter of the tx, and add it to the discardedTxs
  346. // array
  347. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to not current Nonce. "+
  348. "Tx.Nonce: %d, Account.Nonce: %d", l2Txs[i].Nonce, accSender.Nonce)
  349. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  350. continue
  351. }
  352. // if TokenID does not exist yet, create new L1CoordinatorTx to
  353. // create the CoordinatorAccount for that TokenID, to receive
  354. // the fees. Only in the case that there does not exist yet a
  355. // pending L1CoordinatorTx to create the account for the
  356. // Coordinator for that TokenID
  357. var newL1CoordTx *common.L1Tx
  358. newL1CoordTx, positionL1, err =
  359. txsel.coordAccountForTokenID(l1CoordinatorTxs,
  360. accSender.TokenID, positionL1)
  361. if err != nil {
  362. return nil, nil, nil, nil, tracerr.Wrap(err)
  363. }
  364. if newL1CoordTx != nil {
  365. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  366. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  367. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1Txs ||
  368. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1Txs {
  369. // discard L2Tx, and update Info parameter of
  370. // the tx, and add it to the discardedTxs array
  371. l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
  372. "L1CoordinatorTx and there is not enough space for L1Coordinator"
  373. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  374. continue
  375. }
  376. // increase positionL1
  377. positionL1++
  378. l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  379. accAuths = append(accAuths, txsel.coordAccount.AccountCreationAuth)
  380. // process the L1CoordTx
  381. _, _, _, _, err := tp.ProcessL1Tx(nil, newL1CoordTx)
  382. if err != nil {
  383. return nil, nil, nil, nil, tracerr.Wrap(err)
  384. }
  385. }
  386. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  387. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  388. // case of TxToEthAddr or TxToBJJ, check if
  389. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  390. // used; if not, check if tx.ToEthAddr is in
  391. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  392. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  393. // Exit type and is used.
  394. if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  395. validL2Tx, l1CoordinatorTx, accAuth, err :=
  396. txsel.processTxToEthAddrBJJ(validTxs, selectionConfig,
  397. nL1Txs, l1CoordinatorTxs, positionL1, l2Txs[i])
  398. if err != nil {
  399. log.Debugw("txsel.processTxToEthAddrBJJ", "err", err)
  400. // Discard L2Tx, and update Info parameter of
  401. // the tx, and add it to the discardedTxs array
  402. l2Txs[i].Info = fmt.Sprintf("Tx not selected (in processTxToEthAddrBJJ) due to %s",
  403. err.Error())
  404. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  405. continue
  406. }
  407. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  408. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  409. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1Txs ||
  410. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1Txs {
  411. // discard L2Tx, and update Info parameter of
  412. // the tx, and add it to the discardedTxs array
  413. l2Txs[i].Info = "Tx not selected because the L2Tx depends on a " +
  414. "L1CoordinatorTx and there is not enough space for L1Coordinator"
  415. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  416. continue
  417. }
  418. if l1CoordinatorTx != nil && validL2Tx != nil {
  419. // If ToEthAddr == 0xff.. this means that we
  420. // are handling a TransferToBJJ, which doesn't
  421. // require an authorization because it doesn't
  422. // contain a valid ethereum address.
  423. // Otherwise only create the account if we have
  424. // the corresponding authorization
  425. if validL2Tx.ToEthAddr == common.FFAddr {
  426. accAuths = append(accAuths, common.EmptyEthSignature)
  427. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  428. positionL1++
  429. } else if accAuth != nil {
  430. accAuths = append(accAuths, accAuth.Signature)
  431. l1CoordinatorTxs = append(l1CoordinatorTxs, *l1CoordinatorTx)
  432. positionL1++
  433. }
  434. // process the L1CoordTx
  435. _, _, _, _, err := tp.ProcessL1Tx(nil, l1CoordinatorTx)
  436. if err != nil {
  437. return nil, nil, nil, nil, tracerr.Wrap(err)
  438. }
  439. }
  440. if validL2Tx == nil {
  441. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  442. continue
  443. }
  444. } else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
  445. receiverAcc, err := txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
  446. if err != nil {
  447. // tx not valid
  448. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  449. "ToIdx", l2Txs[i].ToIdx)
  450. // Discard L2Tx, and update Info parameter of
  451. // the tx, and add it to the discardedTxs array
  452. l2Txs[i].Info = fmt.Sprintf("Tx not selected due to tx.ToIdx not found in StateDB. "+
  453. "ToIdx: %d", l2Txs[i].ToIdx)
  454. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  455. continue
  456. }
  457. if l2Txs[i].ToEthAddr != common.EmptyAddr {
  458. if l2Txs[i].ToEthAddr != receiverAcc.EthAddr {
  459. log.Debugw("invalid L2Tx: ToEthAddr does not correspond to the Account.EthAddr",
  460. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr",
  461. l2Txs[i].ToEthAddr, "account.EthAddr", receiverAcc.EthAddr)
  462. // Discard L2Tx, and update Info
  463. // parameter of the tx, and add it to
  464. // the discardedTxs array
  465. l2Txs[i].Info = fmt.Sprintf("Tx not selected because ToEthAddr "+
  466. "does not correspond to the Account.EthAddr. "+
  467. "tx.ToIdx: %d, tx.ToEthAddr: %s, account.EthAddr: %s",
  468. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, receiverAcc.EthAddr)
  469. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  470. continue
  471. }
  472. }
  473. if l2Txs[i].ToBJJ != common.EmptyBJJComp {
  474. if l2Txs[i].ToBJJ != receiverAcc.BJJ {
  475. log.Debugw("invalid L2Tx: ToBJJ does not correspond to the Account.BJJ",
  476. "ToIdx", l2Txs[i].ToIdx, "tx.ToEthAddr", l2Txs[i].ToBJJ,
  477. "account.BJJ", receiverAcc.BJJ)
  478. // Discard L2Tx, and update Info
  479. // parameter of the tx, and add it to
  480. // the discardedTxs array
  481. l2Txs[i].Info = fmt.Sprintf("Tx not selected because tx.ToBJJ "+
  482. "does not correspond to the Account.BJJ. "+
  483. "tx.ToIdx: %d, tx.ToEthAddr: %s, tx.ToBJJ: %s, account.BJJ: %s",
  484. l2Txs[i].ToIdx, l2Txs[i].ToEthAddr, l2Txs[i].ToBJJ, receiverAcc.BJJ)
  485. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  486. continue
  487. }
  488. }
  489. }
  490. // get CoordIdxsMap for the TokenID of the current l2Txs[i]
  491. // get TokenID from tx.Sender account
  492. tokenID := accSender.TokenID
  493. coordIdx, err := txsel.getCoordIdx(tokenID)
  494. if err != nil {
  495. // if err is db.ErrNotFound, should not happen, as all
  496. // the validTxs.TokenID should have a CoordinatorIdx
  497. // created in the DB at this point
  498. return nil, nil, nil, nil,
  499. tracerr.Wrap(fmt.Errorf("Could not get CoordIdx for TokenID=%d, "+
  500. "due: %s", tokenID, err))
  501. }
  502. // prepare temp coordIdxsMap & AccumulatedFees for the call to
  503. // ProcessL2Tx
  504. coordIdxsMap := map[common.TokenID]common.Idx{tokenID: coordIdx}
  505. // tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  506. if _, ok := tp.AccumulatedFees[coordIdx]; !ok {
  507. tp.AccumulatedFees[coordIdx] = big.NewInt(0)
  508. }
  509. _, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
  510. if err != nil {
  511. log.Debugw("txselector.getL1L2TxSelection at ProcessL2Tx", "err", err)
  512. // Discard L2Tx, and update Info parameter of the tx,
  513. // and add it to the discardedTxs array
  514. l2Txs[i].Info = fmt.Sprintf("Tx not selected (in ProcessL2Tx) due to %s",
  515. err.Error())
  516. discardedL2Txs = append(discardedL2Txs, l2Txs[i])
  517. continue
  518. }
  519. validTxs = append(validTxs, l2Txs[i])
  520. } // after this loop, no checks to discard txs should be done
  521. return accAuths, l1CoordinatorTxs, validTxs, discardedL2Txs, nil
  522. }
  523. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  524. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  525. // does not have an account yet, a new L1CoordinatorTx of type
  526. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  527. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  528. // array.
  529. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs []common.PoolL2Tx,
  530. selectionConfig txprocessor.Config, nL1UserTxs int, l1CoordinatorTxs []common.L1Tx,
  531. positionL1 int, l2Tx common.PoolL2Tx) (*common.PoolL2Tx, *common.L1Tx,
  532. *common.AccountCreationAuth, error) {
  533. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  534. // previous L2Tx in the current process already created a
  535. // L1CoordinatorTx of this type, in the DB there still seem that needs
  536. // to create a new L1CoordinatorTx, but as is already created, the tx
  537. // is valid
  538. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  539. return &l2Tx, nil, nil, nil
  540. }
  541. var l1CoordinatorTx *common.L1Tx
  542. var accAuth *common.AccountCreationAuth
  543. if l2Tx.ToEthAddr != common.EmptyAddr && l2Tx.ToEthAddr != common.FFAddr {
  544. // case: ToEthAddr != 0x00 neither 0xff
  545. if l2Tx.ToBJJ != common.EmptyBJJComp {
  546. // case: ToBJJ!=0:
  547. // if idx exist for EthAddr&BJJ use it
  548. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  549. l2Tx.ToBJJ, l2Tx.TokenID)
  550. if err == nil {
  551. // account for ToEthAddr&ToBJJ already exist,
  552. // there is no need to create a new one.
  553. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  554. return &l2Tx, nil, nil, nil
  555. }
  556. // if not, check if AccountCreationAuth exist for that
  557. // ToEthAddr
  558. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  559. if err != nil {
  560. // not found, l2Tx will not be added in the selection
  561. return nil, nil, nil,
  562. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found "+
  563. "in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  564. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  565. }
  566. if accAuth.BJJ != l2Tx.ToBJJ {
  567. // if AccountCreationAuth.BJJ is not the same
  568. // than in the tx, tx is not accepted
  569. return nil, nil, nil,
  570. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, "+
  571. "neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. "+
  572. "ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
  573. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  574. }
  575. } else {
  576. // case: ToBJJ==0:
  577. // if idx exist for EthAddr use it
  578. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  579. if err == nil {
  580. // account for ToEthAddr already exist,
  581. // there is no need to create a new one.
  582. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  583. return &l2Tx, nil, nil, nil
  584. }
  585. // if not, check if AccountCreationAuth exist for that ToEthAddr
  586. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  587. if err != nil {
  588. // not found, l2Tx will not be added in the selection
  589. return nil, nil, nil,
  590. tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in "+
  591. "StateDB, neither ToEthAddr found in "+
  592. "AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  593. l2Tx.ToIdx, l2Tx.ToEthAddr))
  594. }
  595. }
  596. // create L1CoordinatorTx for the accountCreation
  597. l1CoordinatorTx = &common.L1Tx{
  598. Position: positionL1,
  599. UserOrigin: false,
  600. FromEthAddr: accAuth.EthAddr,
  601. FromBJJ: accAuth.BJJ,
  602. TokenID: l2Tx.TokenID,
  603. Amount: big.NewInt(0),
  604. DepositAmount: big.NewInt(0),
  605. Type: common.TxTypeCreateAccountDeposit,
  606. }
  607. } else if l2Tx.ToEthAddr == common.FFAddr && l2Tx.ToBJJ != common.EmptyBJJComp {
  608. // if idx exist for EthAddr&BJJ use it
  609. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  610. l2Tx.TokenID)
  611. if err == nil {
  612. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  613. // there is no need to create a new one.
  614. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  615. return &l2Tx, nil, nil, nil
  616. }
  617. // if idx don't exist for EthAddr&BJJ, coordinator can create a
  618. // new account without L1Authorization, as ToEthAddr==0xff
  619. // create L1CoordinatorTx for the accountCreation
  620. l1CoordinatorTx = &common.L1Tx{
  621. Position: positionL1,
  622. UserOrigin: false,
  623. FromEthAddr: l2Tx.ToEthAddr,
  624. FromBJJ: l2Tx.ToBJJ,
  625. TokenID: l2Tx.TokenID,
  626. Amount: big.NewInt(0),
  627. DepositAmount: big.NewInt(0),
  628. Type: common.TxTypeCreateAccountDeposit,
  629. }
  630. }
  631. // if there is no space for the L1CoordinatorTx as MaxL1Tx, or no space
  632. // for L1CoordinatorTx + L2Tx as MaxTx, discard the L2Tx
  633. if len(l1CoordinatorTxs) >= int(selectionConfig.MaxL1Tx)-nL1UserTxs ||
  634. len(l1CoordinatorTxs)+1 >= int(selectionConfig.MaxTx)-nL1UserTxs {
  635. // L2Tx discarded
  636. return nil, nil, nil, tracerr.Wrap(fmt.Errorf("L2Tx discarded due to no available slots " +
  637. "for L1CoordinatorTx to create a new account for receiver of L2Tx"))
  638. }
  639. return &l2Tx, l1CoordinatorTx, accAuth, nil
  640. }
  641. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  642. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  643. for i := 0; i < len(l1CoordinatorTxs); i++ {
  644. if l1CoordinatorTxs[i].FromEthAddr == addr &&
  645. l1CoordinatorTxs[i].TokenID == tokenID &&
  646. l1CoordinatorTxs[i].FromBJJ == bjj {
  647. return true
  648. }
  649. }
  650. return false
  651. }
  652. // sortL2Txs sorts the PoolL2Txs by AbsoluteFee and then by Nonce
  653. func sortL2Txs(l2Txs []common.PoolL2Tx) []common.PoolL2Tx {
  654. // Sort by absolute fee with SliceStable, so that txs with same
  655. // AbsoluteFee are not rearranged and nonce order is kept in such case
  656. sort.SliceStable(l2Txs, func(i, j int) bool {
  657. return l2Txs[i].AbsoluteFee > l2Txs[j].AbsoluteFee
  658. })
  659. // sort l2Txs by Nonce. This can be done in many different ways, what
  660. // is needed is to output the l2Txs where the Nonce of l2Txs for each
  661. // Account is sorted, but the l2Txs can not be grouped by sender Account
  662. // neither by Fee. This is because later on the Nonces will need to be
  663. // sequential for the zkproof generation.
  664. sort.Slice(l2Txs, func(i, j int) bool {
  665. return l2Txs[i].Nonce < l2Txs[j].Nonce
  666. })
  667. return l2Txs
  668. }
  669. func splitL2ForgableAndNonForgable(tp *txprocessor.TxProcessor,
  670. l2Txs []common.PoolL2Tx) ([]common.PoolL2Tx, []common.PoolL2Tx) {
  671. var l2TxsForgable, l2TxsNonForgable []common.PoolL2Tx
  672. for i := 0; i < len(l2Txs); i++ {
  673. accSender, err := tp.StateDB().GetAccount(l2Txs[i].FromIdx)
  674. if err != nil {
  675. l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
  676. continue
  677. }
  678. if l2Txs[i].Nonce != accSender.Nonce {
  679. l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
  680. continue
  681. }
  682. enoughBalance, _, _ := tp.CheckEnoughBalance(l2Txs[i])
  683. if !enoughBalance {
  684. l2TxsNonForgable = append(l2TxsNonForgable, l2Txs[i])
  685. continue
  686. }
  687. l2TxsForgable = append(l2TxsForgable, l2Txs[i])
  688. }
  689. return l2TxsForgable, l2TxsNonForgable
  690. }