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.

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