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.

464 lines
18 KiB

  1. package txselector
  2. // current: very simple version of TxSelector
  3. import (
  4. "bytes"
  5. "fmt"
  6. "math/big"
  7. "sort"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  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. "github.com/iden3/go-merkletree/db"
  17. )
  18. const (
  19. // PathCoordIdxsDB defines the path of the key-value db where the
  20. // CoordIdxs will be stored
  21. PathCoordIdxsDB = "/coordidxs"
  22. )
  23. // txs implements the interface Sort for an array of Tx
  24. type txs []common.PoolL2Tx
  25. func (t txs) Len() int {
  26. return len(t)
  27. }
  28. func (t txs) Swap(i, j int) {
  29. t[i], t[j] = t[j], t[i]
  30. }
  31. func (t txs) Less(i, j int) bool {
  32. return t[i].AbsoluteFee > t[j].AbsoluteFee
  33. }
  34. // CoordAccount contains the data of the Coordinator account, that will be used
  35. // to create new transactions of CreateAccountDeposit type to add new TokenID
  36. // accounts for the Coordinator to receive the fees.
  37. type CoordAccount struct {
  38. Addr ethCommon.Address
  39. BJJ babyjub.PublicKeyComp
  40. AccountCreationAuth []byte
  41. }
  42. // SelectionConfig contains the parameters of configuration of the selection of
  43. // transactions for the next batch
  44. type SelectionConfig struct {
  45. // MaxL1UserTxs is the maximum L1-user-tx for a batch
  46. MaxL1UserTxs uint64
  47. // MaxL1CoordinatorTxs is the maximum L1-coordinator-tx for a batch
  48. MaxL1CoordinatorTxs uint64
  49. // TxProcessorConfig contains the config for ProcessTxs
  50. TxProcessorConfig txprocessor.Config
  51. }
  52. // TxSelector implements all the functionalities to select the txs for the next
  53. // batch
  54. type TxSelector struct {
  55. l2db *l2db.L2DB
  56. localAccountsDB *statedb.LocalStateDB
  57. coordAccount *CoordAccount
  58. }
  59. // NewTxSelector returns a *TxSelector
  60. func NewTxSelector(coordAccount *CoordAccount, dbpath string,
  61. synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
  62. localAccountsDB, err := statedb.NewLocalStateDB(dbpath, 128,
  63. synchronizerStateDB, statedb.TypeTxSelector, 0) // without merkletree
  64. if err != nil {
  65. return nil, tracerr.Wrap(err)
  66. }
  67. return &TxSelector{
  68. l2db: l2,
  69. localAccountsDB: localAccountsDB,
  70. coordAccount: coordAccount,
  71. }, nil
  72. }
  73. // LocalAccountsDB returns the LocalStateDB of the TxSelector
  74. func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
  75. return txsel.localAccountsDB
  76. }
  77. // Reset tells the TxSelector to get it's internal AccountsDB
  78. // from the required `batchNum`
  79. func (txsel *TxSelector) Reset(batchNum common.BatchNum) error {
  80. err := txsel.localAccountsDB.Reset(batchNum, true)
  81. if err != nil {
  82. return tracerr.Wrap(err)
  83. }
  84. return nil
  85. }
  86. func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
  87. return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr, txsel.coordAccount.BJJ, tokenID)
  88. }
  89. // coordAccountForTokenID creates a new L1CoordinatorTx to create a new
  90. // Coordinator account for the given TokenID in the case that the account does
  91. // not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
  92. // account in the given array of L1CoordinatorTxs. If a new Coordinator account
  93. // needs to be created, a new L1CoordinatorTx will be returned from this
  94. // function.
  95. //nolint:unused
  96. func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
  97. tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
  98. // check if CoordinatorAccount for TokenID is already pending to create
  99. if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
  100. txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
  101. return nil, positionL1, nil
  102. }
  103. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr, txsel.coordAccount.BJJ, tokenID)
  104. if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
  105. // create L1CoordinatorTx to create new CoordAccount for
  106. // TokenID
  107. l1CoordinatorTx := common.L1Tx{
  108. Position: positionL1,
  109. UserOrigin: false,
  110. FromEthAddr: txsel.coordAccount.Addr,
  111. FromBJJ: txsel.coordAccount.BJJ,
  112. TokenID: tokenID,
  113. Amount: big.NewInt(0),
  114. DepositAmount: big.NewInt(0),
  115. Type: common.TxTypeCreateAccountDeposit,
  116. }
  117. positionL1++
  118. return &l1CoordinatorTx, positionL1, nil
  119. }
  120. if err != nil {
  121. return nil, positionL1, tracerr.Wrap(err)
  122. }
  123. // CoordAccount for TokenID already exists
  124. return nil, positionL1, nil
  125. }
  126. // GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
  127. // for the next batch, from the L2DB pool.
  128. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  129. // L2Txs. An array of bytearrays with the signatures of the
  130. // AccountCreationAuthorization of the accounts of the users created by the
  131. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  132. // but there is a transactions to them and the authorization of account
  133. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  134. // included in the next batch.
  135. func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig,
  136. batchNum common.BatchNum) ([]common.Idx, [][]byte, []common.L1Tx, []common.PoolL2Tx, error) {
  137. coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, err :=
  138. txsel.GetL1L2TxSelection(selectionConfig, batchNum, []common.L1Tx{})
  139. return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, tracerr.Wrap(err)
  140. }
  141. // GetL1L2TxSelection returns the selection of L1 + L2 txs.
  142. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  143. // L2Txs. An array of bytearrays with the signatures of the
  144. // AccountCreationAuthorization of the accounts of the users created by the
  145. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  146. // but there is a transactions to them and the authorization of account
  147. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  148. // included in the next batch.
  149. func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
  150. batchNum common.BatchNum, l1Txs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
  151. []common.L1Tx, []common.PoolL2Tx, error) {
  152. // TODO WIP this method uses a 'cherry-pick' of internal calls of the
  153. // StateDB, a refactor of the StateDB to reorganize it internally is
  154. // planned once the main functionallities are covered, with that
  155. // refactor the TxSelector will be updated also
  156. // get pending l2-tx from tx-pool
  157. l2TxsRaw, err := txsel.l2db.GetPendingTxs()
  158. if err != nil {
  159. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  160. }
  161. txselStateDB := txsel.localAccountsDB.StateDB
  162. tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig.TxProcessorConfig)
  163. // Process L1UserTxs
  164. for i := 0; i < len(l1Txs); i++ {
  165. // assumption: l1usertx are sorted by L1Tx.Position
  166. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1Txs[i])
  167. if err != nil {
  168. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  169. }
  170. }
  171. var l1CoordinatorTxs []common.L1Tx
  172. positionL1 := len(l1Txs)
  173. var accAuths [][]byte
  174. // sort l2TxsRaw (cropping at MaxTx at this point)
  175. l2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.TxProcessorConfig.MaxTx)
  176. // TODO for L1CoordinatorTxs check that always len(l1UserTxs)+len(l1CoordinatorTxs)<MaxL1Txs
  177. // iterate over l2Txs
  178. // - if tx.TokenID does not exist at CoordsIdxDB
  179. // - create new L1CoordinatorTx, for Coordinator to receive the fee of the new TokenID
  180. for i := 0; i < len(l2Txs); i++ {
  181. // check if l2Tx.TokenID does not exist at CoordsIdxDB
  182. _, err = txsel.getCoordIdx(l2Txs[i].TokenID) // TODO already used inside coordAccountForTokenID, this will be removed
  183. if tracerr.Unwrap(err) != db.ErrNotFound {
  184. // if TokenID does not exist yet, create new
  185. // L1CoordinatorTx to create the CoordinatorAccount for
  186. // that TokenID, to receive the fees. Only in the case
  187. // that there does not exist yet a pending
  188. // L1CoordinatorTx to create the account for the
  189. // Coordinator for that TokenID
  190. // TODO TMP
  191. // var newL1CoordTx *common.L1Tx
  192. // newL1CoordTx, positionL1, err =
  193. // txsel.coordAccountForTokenID(l1CoordinatorTxs,
  194. // l2TxsRaw[i].TokenID, positionL1)
  195. // if err != nil {
  196. // return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  197. // }
  198. // if newL1CoordTx != nil {
  199. // l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  200. // }
  201. } else if err != nil {
  202. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  203. }
  204. }
  205. var validTxs txs
  206. // iterate over l2TxsRaw
  207. // - if needed, create new L1CoordinatorTxs for unexisting ToIdx
  208. // - keep used accAuths
  209. // - put the valid txs into validTxs array
  210. for i := 0; i < len(l2Txs); i++ {
  211. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  212. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  213. // case of TxToEthAddr or TxToBJJ, check if
  214. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  215. // used; if not, check if tx.ToEthAddr is in
  216. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  217. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  218. // Exit type and is used.
  219. if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  220. var accAuth *common.AccountCreationAuth
  221. validTxs, l1CoordinatorTxs, accAuth, positionL1, err =
  222. txsel.processTxToEthAddrBJJ(validTxs, l1CoordinatorTxs,
  223. positionL1, l2Txs[i])
  224. if err != nil {
  225. log.Debug(err)
  226. continue
  227. }
  228. if accAuth != nil {
  229. accAuths = append(accAuths, accAuth.Signature)
  230. }
  231. } else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
  232. _, err = txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
  233. if err != nil {
  234. // tx not valid
  235. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  236. "ToIdx", l2Txs[i].ToIdx)
  237. continue
  238. }
  239. // TODO if EthAddr!=0 or BJJ!=0, check that ToIdxAccount.EthAddr or BJJ
  240. // Account found in the DB, include the l2Tx in the selection
  241. validTxs = append(validTxs, l2Txs[i])
  242. } else if l2Txs[i].ToIdx == common.Idx(1) {
  243. // valid txs (of Exit type)
  244. validTxs = append(validTxs, l2Txs[i])
  245. }
  246. }
  247. // Process L1CoordinatorTxs
  248. for i := 0; i < len(l1CoordinatorTxs); i++ {
  249. _, _, _, _, err := tp.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
  250. if err != nil {
  251. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  252. }
  253. }
  254. // get CoordIdxsMap for the TokenIDs
  255. coordIdxsMap := make(map[common.TokenID]common.Idx)
  256. // TODO TMP (related to L#260
  257. // for i := 0; i < len(l2Txs); i++ {
  258. // coordIdx, err := txsel.getCoordIdx(l2Txs[i].TokenID)
  259. // if err != nil {
  260. // // if err is db.ErrNotFound, should not happen, as all
  261. // // the l2Txs.TokenID should have a CoordinatorIdx
  262. // // created in the DB at this point
  263. // return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  264. // }
  265. // coordIdxsMap[l2Txs[i].TokenID] = coordIdx
  266. // }
  267. var coordIdxs []common.Idx
  268. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  269. for _, idx := range coordIdxsMap {
  270. tp.AccumulatedFees[idx] = big.NewInt(0)
  271. coordIdxs = append(coordIdxs, idx)
  272. }
  273. // get most profitable L2-tx
  274. maxL2Txs := selectionConfig.TxProcessorConfig.MaxTx - uint32(len(l1CoordinatorTxs)) // - len(l1UserTxs) // TODO if there are L1UserTxs take them in to account
  275. selectedL2Txs := txsel.getL2Profitable(l2Txs, maxL2Txs) // TODO this will only need to crop the lasts, as are already sorted
  276. for i := 0; i < len(selectedL2Txs); i++ {
  277. _, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &selectedL2Txs[i])
  278. if err != nil {
  279. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  280. }
  281. }
  282. return coordIdxs, accAuths, l1Txs, l1CoordinatorTxs, selectedL2Txs, nil
  283. }
  284. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  285. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  286. // does not have an account yet, a new L1CoordinatorTx of type
  287. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  288. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  289. // array.
  290. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []common.L1Tx,
  291. positionL1 int, l2Tx common.PoolL2Tx) (txs, []common.L1Tx, *common.AccountCreationAuth, int, error) {
  292. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  293. // previous L2Tx in the current process already created a
  294. // L1CoordinatorTx of this type, in the DB there still seem that needs
  295. // to create a new L1CoordinatorTx, but as is already created, the tx
  296. // is valid
  297. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  298. validTxs = append(validTxs, l2Tx)
  299. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  300. }
  301. var accAuth *common.AccountCreationAuth
  302. if !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) &&
  303. !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
  304. // case: ToEthAddr != 0x00 neither 0xff
  305. if l2Tx.ToBJJ != common.EmptyBJJComp {
  306. // case: ToBJJ!=0:
  307. // if idx exist for EthAddr&BJJ use it
  308. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  309. l2Tx.ToBJJ, l2Tx.TokenID)
  310. if err == nil {
  311. // account for ToEthAddr&ToBJJ already exist,
  312. // there is no need to create a new one.
  313. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  314. validTxs = append(validTxs, l2Tx)
  315. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  316. }
  317. // if not, check if AccountCreationAuth exist for that
  318. // ToEthAddr
  319. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  320. if err != nil {
  321. // not found, l2Tx will not be added in the selection
  322. return validTxs, l1CoordinatorTxs, nil, positionL1, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  323. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  324. }
  325. if accAuth.BJJ != l2Tx.ToBJJ {
  326. // if AccountCreationAuth.BJJ is not the same
  327. // than in the tx, tx is not accepted
  328. return validTxs, l1CoordinatorTxs, nil, positionL1, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s, ToBJJ: %s",
  329. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  330. }
  331. validTxs = append(validTxs, l2Tx)
  332. } else {
  333. // case: ToBJJ==0:
  334. // if idx exist for EthAddr use it
  335. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  336. if err == nil {
  337. // account for ToEthAddr already exist,
  338. // there is no need to create a new one.
  339. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  340. validTxs = append(validTxs, l2Tx)
  341. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  342. }
  343. // if not, check if AccountCreationAuth exist for that ToEthAddr
  344. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  345. if err != nil {
  346. // not found, l2Tx will not be added in the selection
  347. return validTxs, l1CoordinatorTxs, nil, positionL1, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  348. l2Tx.ToIdx, l2Tx.ToEthAddr))
  349. }
  350. validTxs = append(validTxs, l2Tx)
  351. }
  352. // create L1CoordinatorTx for the accountCreation
  353. l1CoordinatorTx := common.L1Tx{
  354. Position: positionL1,
  355. UserOrigin: false,
  356. FromEthAddr: accAuth.EthAddr,
  357. FromBJJ: accAuth.BJJ,
  358. TokenID: l2Tx.TokenID,
  359. Amount: big.NewInt(0),
  360. DepositAmount: big.NewInt(0),
  361. Type: common.TxTypeCreateAccountDeposit,
  362. }
  363. positionL1++
  364. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  365. } else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2Tx.ToBJJ != common.EmptyBJJComp {
  366. // if idx exist for EthAddr&BJJ use it
  367. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  368. l2Tx.TokenID)
  369. if err == nil {
  370. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  371. // there is no need to create a new one.
  372. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  373. validTxs = append(validTxs, l2Tx)
  374. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  375. }
  376. // if idx don't exist for EthAddr&BJJ,
  377. // coordinator can create a new account without
  378. // L1Authorization, as ToEthAddr==0xff
  379. // create L1CoordinatorTx for the accountCreation
  380. l1CoordinatorTx := common.L1Tx{
  381. Position: positionL1,
  382. UserOrigin: false,
  383. FromEthAddr: l2Tx.ToEthAddr,
  384. FromBJJ: l2Tx.ToBJJ,
  385. TokenID: l2Tx.TokenID,
  386. Amount: big.NewInt(0),
  387. DepositAmount: big.NewInt(0),
  388. Type: common.TxTypeCreateAccountDeposit,
  389. }
  390. positionL1++
  391. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  392. }
  393. return validTxs, l1CoordinatorTxs, accAuth, positionL1, nil
  394. }
  395. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  396. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  397. for i := 0; i < len(l1CoordinatorTxs); i++ {
  398. if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) &&
  399. l1CoordinatorTxs[i].TokenID == tokenID &&
  400. l1CoordinatorTxs[i].FromBJJ == bjj {
  401. return true
  402. }
  403. }
  404. return false
  405. }
  406. // getL2Profitable returns the profitable selection of L2Txssorted by Nonce
  407. func (txsel *TxSelector) getL2Profitable(txs txs, max uint32) txs {
  408. sort.Sort(txs)
  409. if len(txs) < int(max) {
  410. return txs
  411. }
  412. txs = txs[:max]
  413. // sort l2Txs by Nonce. This can be done in many different ways, what
  414. // is needed is to output the txs where the Nonce of txs for each
  415. // Account is sorted, but the txs can not be grouped by sender Account
  416. // neither by Fee. This is because later on the Nonces will need to be
  417. // sequential for the zkproof generation.
  418. sort.SliceStable(txs, func(i, j int) bool {
  419. return txs[i].Nonce < txs[j].Nonce
  420. })
  421. return txs
  422. }