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.

489 lines
17 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/tracerr"
  14. "github.com/iden3/go-iden3-crypto/babyjub"
  15. "github.com/iden3/go-merkletree/db"
  16. "github.com/iden3/go-merkletree/db/pebble"
  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. // ProcessTxsConfig contains the config for ProcessTxs
  50. ProcessTxsConfig statedb.ProcessTxsConfig
  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. coordIdxsDB *pebble.PebbleStorage
  59. }
  60. // NewTxSelector returns a *TxSelector
  61. func NewTxSelector(coordAccount *CoordAccount, dbpath string,
  62. synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB) (*TxSelector, error) {
  63. localAccountsDB, err := statedb.NewLocalStateDB(dbpath,
  64. synchronizerStateDB, statedb.TypeTxSelector, 0) // without merkletree
  65. if err != nil {
  66. return nil, tracerr.Wrap(err)
  67. }
  68. coordIdxsDB, err := pebble.NewPebbleStorage(dbpath+PathCoordIdxsDB, false)
  69. if err != nil {
  70. return nil, tracerr.Wrap(err)
  71. }
  72. return &TxSelector{
  73. l2db: l2,
  74. localAccountsDB: localAccountsDB,
  75. coordAccount: coordAccount,
  76. coordIdxsDB: coordIdxsDB,
  77. }, nil
  78. }
  79. // LocalAccountsDB returns the LocalStateDB of the TxSelector
  80. func (txsel *TxSelector) LocalAccountsDB() *statedb.LocalStateDB {
  81. return txsel.localAccountsDB
  82. }
  83. // Reset tells the TxSelector to get it's internal AccountsDB
  84. // from the required `batchNum`
  85. func (txsel *TxSelector) Reset(batchNum common.BatchNum) error {
  86. err := txsel.localAccountsDB.Reset(batchNum, true)
  87. if err != nil {
  88. return tracerr.Wrap(err)
  89. }
  90. return nil
  91. }
  92. // AddCoordIdxs stores the given TokenID with the correspondent Idx to the
  93. // CoordIdxsDB
  94. func (txsel *TxSelector) AddCoordIdxs(idxs map[common.TokenID]common.Idx) error {
  95. tx, err := txsel.coordIdxsDB.NewTx()
  96. if err != nil {
  97. return tracerr.Wrap(err)
  98. }
  99. for tokenID, idx := range idxs {
  100. idxBytes, err := idx.Bytes()
  101. if err != nil {
  102. return tracerr.Wrap(err)
  103. }
  104. err = tx.Put(tokenID.Bytes(), idxBytes[:])
  105. if err != nil {
  106. return tracerr.Wrap(err)
  107. }
  108. }
  109. if err := tx.Commit(); err != nil {
  110. return tracerr.Wrap(err)
  111. }
  112. return nil
  113. }
  114. // GetCoordIdxs returns a map with the stored TokenID with the correspondent
  115. // Coordinator Idx
  116. func (txsel *TxSelector) GetCoordIdxs() (map[common.TokenID]common.Idx, error) {
  117. r := make(map[common.TokenID]common.Idx)
  118. err := txsel.coordIdxsDB.Iterate(func(tokenIDBytes []byte, idxBytes []byte) (bool, error) {
  119. idx, err := common.IdxFromBytes(idxBytes)
  120. if err != nil {
  121. return false, tracerr.Wrap(err)
  122. }
  123. tokenID, err := common.TokenIDFromBytes(tokenIDBytes)
  124. if err != nil {
  125. return false, tracerr.Wrap(err)
  126. }
  127. r[tokenID] = idx
  128. return true, nil
  129. })
  130. return r, tracerr.Wrap(err)
  131. }
  132. //nolint:unused
  133. func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
  134. // check if CoordinatorAccount for TokenID is already pending to create
  135. if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID, txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
  136. return nil, positionL1, nil
  137. }
  138. _, err := txsel.coordIdxsDB.Get(tokenID.Bytes())
  139. if tracerr.Unwrap(err) == db.ErrNotFound {
  140. // create L1CoordinatorTx to create new CoordAccount for TokenID
  141. l1CoordinatorTx := common.L1Tx{
  142. Position: positionL1,
  143. UserOrigin: false,
  144. FromEthAddr: txsel.coordAccount.Addr,
  145. FromBJJ: txsel.coordAccount.BJJ,
  146. TokenID: tokenID,
  147. DepositAmount: big.NewInt(0),
  148. Type: common.TxTypeCreateAccountDeposit,
  149. }
  150. positionL1++
  151. return &l1CoordinatorTx, positionL1, nil
  152. }
  153. if err != nil {
  154. return nil, positionL1, tracerr.Wrap(err)
  155. }
  156. // CoordAccount for TokenID already exists
  157. return nil, positionL1, nil
  158. }
  159. // GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs
  160. // for the next batch, from the L2DB pool.
  161. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  162. // L2Txs. An array of bytearrays with the signatures of the
  163. // AccountCreationAuthorization of the accounts of the users created by the
  164. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  165. // but there is a transactions to them and the authorization of account
  166. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  167. // included in the next batch.
  168. func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig,
  169. batchNum common.BatchNum) ([]common.Idx, [][]byte, []common.L1Tx, []common.PoolL2Tx, error) {
  170. coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, err := txsel.GetL1L2TxSelection(selectionConfig, batchNum,
  171. []common.L1Tx{})
  172. return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, tracerr.Wrap(err)
  173. }
  174. // GetL1L2TxSelection returns the selection of L1 + L2 txs.
  175. // It returns: the CoordinatorIdxs used to receive the fees of the selected
  176. // L2Txs. An array of bytearrays with the signatures of the
  177. // AccountCreationAuthorization of the accounts of the users created by the
  178. // Coordinator with L1CoordinatorTxs of those accounts that does not exist yet
  179. // but there is a transactions to them and the authorization of account
  180. // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
  181. // included in the next batch.
  182. func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
  183. batchNum common.BatchNum, l1Txs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx, []common.L1Tx,
  184. []common.PoolL2Tx, error) {
  185. // TODO WIP this method uses a 'cherry-pick' of internal calls of the
  186. // StateDB, a refactor of the StateDB to reorganize it internally is
  187. // planned once the main functionallities are covered, with that
  188. // refactor the TxSelector will be updated also
  189. // apply l1-user-tx to localAccountDB
  190. // create new leaves
  191. // update balances
  192. // update nonces
  193. // get existing CoordIdxs
  194. coordIdxsMap, err := txsel.GetCoordIdxs()
  195. if err != nil {
  196. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  197. }
  198. var coordIdxs []common.Idx
  199. for tokenID := range coordIdxsMap {
  200. coordIdxs = append(coordIdxs, coordIdxsMap[tokenID])
  201. }
  202. // get pending l2-tx from tx-pool
  203. l2TxsRaw, err := txsel.l2db.GetPendingTxs() // (batchID)
  204. if err != nil {
  205. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  206. }
  207. var validTxs txs
  208. var l1CoordinatorTxs []common.L1Tx
  209. positionL1 := len(l1Txs)
  210. // Process L1UserTxs
  211. for i := 0; i < len(l1Txs); i++ {
  212. // assumption: l1usertx are sorted by L1Tx.Position
  213. _, _, _, _, err := txsel.localAccountsDB.ProcessL1Tx(nil, &l1Txs[i])
  214. if err != nil {
  215. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  216. }
  217. }
  218. // get last idx from LocalStateDB
  219. // lastIdx := txsel.localStateDB.idx
  220. // update lastIdx with the L1UserTxs (of account creation)
  221. var accAuths [][]byte
  222. for i := 0; i < len(l2TxsRaw); i++ {
  223. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  224. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  225. // case of TxToEthAddr or TxToBJJ, check if
  226. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  227. // used; if not, check if tx.ToEthAddr is in
  228. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  229. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  230. // Exit type and is used.
  231. if l2TxsRaw[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  232. var accAuth *common.AccountCreationAuth
  233. validTxs, l1CoordinatorTxs, accAuth, positionL1, err =
  234. txsel.processTxToEthAddrBJJ(validTxs, l1CoordinatorTxs,
  235. positionL1, l2TxsRaw[i])
  236. if err != nil {
  237. log.Debug(err)
  238. continue
  239. }
  240. if accAuth != nil {
  241. accAuths = append(accAuths, accAuth.Signature)
  242. }
  243. } else if l2TxsRaw[i].ToIdx >= common.IdxUserThreshold {
  244. _, err = txsel.localAccountsDB.GetAccount(l2TxsRaw[i].ToIdx)
  245. if err != nil {
  246. // tx not valid
  247. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  248. "ToIdx", l2TxsRaw[i].ToIdx)
  249. continue
  250. }
  251. // TODO if EthAddr!=0 or BJJ!=0, check that ToIdxAccount.EthAddr or BJJ
  252. // Account found in the DB, include the l2Tx in the selection
  253. validTxs = append(validTxs, l2TxsRaw[i])
  254. } else if l2TxsRaw[i].ToIdx == common.Idx(1) {
  255. // valid txs (of Exit type)
  256. validTxs = append(validTxs, l2TxsRaw[i])
  257. }
  258. // TODO if needed add L1CoordinatorTx to create a Coordinator
  259. // account for the new TokenID
  260. // var newL1CoordTx *common.L1Tx
  261. // newL1CoordTx, positionL1, err = txsel.coordAccountForTokenID(l1CoordinatorTxs, l2TxsRaw[i].TokenID, positionL1)
  262. // if err != nil {
  263. // return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  264. // }
  265. // if newL1CoordTx != nil {
  266. // l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  267. // }
  268. }
  269. // Process L1CoordinatorTxs
  270. for i := 0; i < len(l1CoordinatorTxs); i++ {
  271. _, _, _, _, err := txsel.localAccountsDB.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
  272. if err != nil {
  273. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  274. }
  275. }
  276. txsel.localAccountsDB.AccumulatedFees = make(map[common.Idx]*big.Int)
  277. for _, idx := range coordIdxs {
  278. txsel.localAccountsDB.AccumulatedFees[idx] = big.NewInt(0)
  279. }
  280. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  281. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  282. // created in the current batch, at this point the Idx will be created
  283. coordIdxsMap, err = txsel.localAccountsDB.GetTokenIDsFromIdxs(coordIdxs)
  284. if err != nil {
  285. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  286. }
  287. // get most profitable L2-tx
  288. maxL2Txs := selectionConfig.ProcessTxsConfig.MaxTx - uint32(len(l1CoordinatorTxs)) // - len(l1UserTxs) // TODO if there are L1UserTxs take them in to account
  289. l2Txs := txsel.getL2Profitable(validTxs, maxL2Txs)
  290. // Process L2Txs
  291. for i := 0; i < len(l2Txs); i++ {
  292. _, _, _, err = txsel.localAccountsDB.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
  293. if err != nil {
  294. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  295. }
  296. }
  297. err = txsel.AddCoordIdxs(coordIdxsMap)
  298. if err != nil {
  299. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  300. }
  301. err = txsel.localAccountsDB.MakeCheckpoint()
  302. if err != nil {
  303. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  304. }
  305. return nil, accAuths, l1Txs, l1CoordinatorTxs, l2Txs, nil
  306. }
  307. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  308. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  309. // does not have an account yet, a new L1CoordinatorTx of type
  310. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  311. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  312. // array.
  313. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []common.L1Tx,
  314. positionL1 int, l2Tx common.PoolL2Tx) (txs, []common.L1Tx, *common.AccountCreationAuth, int, error) {
  315. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  316. // previous L2Tx in the current process already created a
  317. // L1CoordinatorTx of this type, in the DB there still seem that needs
  318. // to create a new L1CoordinatorTx, but as is already created, the tx
  319. // is valid
  320. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  321. validTxs = append(validTxs, l2Tx)
  322. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  323. }
  324. var accAuth *common.AccountCreationAuth
  325. if !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) &&
  326. !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
  327. // case: ToEthAddr != 0x00 neither 0xff
  328. if l2Tx.ToBJJ != common.EmptyBJJComp {
  329. // case: ToBJJ!=0:
  330. // if idx exist for EthAddr&BJJ use it
  331. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  332. l2Tx.ToBJJ, l2Tx.TokenID)
  333. if err == nil {
  334. // account for ToEthAddr&ToBJJ already exist,
  335. // there is no need to create a new one.
  336. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  337. validTxs = append(validTxs, l2Tx)
  338. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  339. }
  340. // if not, check if AccountCreationAuth exist for that
  341. // ToEthAddr
  342. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  343. if err != nil {
  344. // not found, l2Tx will not be added in the selection
  345. 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",
  346. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  347. }
  348. if accAuth.BJJ != l2Tx.ToBJJ {
  349. // if AccountCreationAuth.BJJ is not the same
  350. // than in the tx, tx is not accepted
  351. 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",
  352. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  353. }
  354. validTxs = append(validTxs, l2Tx)
  355. } else {
  356. // case: ToBJJ==0:
  357. // if idx exist for EthAddr use it
  358. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  359. if err == nil {
  360. // account for ToEthAddr already exist,
  361. // there is no need to create a new one.
  362. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  363. validTxs = append(validTxs, l2Tx)
  364. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  365. }
  366. // if not, check if AccountCreationAuth exist for that ToEthAddr
  367. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  368. if err != nil {
  369. // not found, l2Tx will not be added in the selection
  370. 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",
  371. l2Tx.ToIdx, l2Tx.ToEthAddr))
  372. }
  373. validTxs = append(validTxs, l2Tx)
  374. }
  375. // create L1CoordinatorTx for the accountCreation
  376. l1CoordinatorTx := common.L1Tx{
  377. Position: positionL1,
  378. UserOrigin: false,
  379. FromEthAddr: accAuth.EthAddr,
  380. FromBJJ: accAuth.BJJ,
  381. TokenID: l2Tx.TokenID,
  382. DepositAmount: big.NewInt(0),
  383. Type: common.TxTypeCreateAccountDeposit,
  384. }
  385. positionL1++
  386. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  387. } else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2Tx.ToBJJ != common.EmptyBJJComp {
  388. // if idx exist for EthAddr&BJJ use it
  389. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  390. l2Tx.TokenID)
  391. if err == nil {
  392. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  393. // there is no need to create a new one.
  394. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  395. validTxs = append(validTxs, l2Tx)
  396. return validTxs, l1CoordinatorTxs, nil, positionL1, nil
  397. }
  398. // if idx don't exist for EthAddr&BJJ,
  399. // coordinator can create a new account without
  400. // L1Authorization, as ToEthAddr==0xff
  401. // create L1CoordinatorTx for the accountCreation
  402. l1CoordinatorTx := common.L1Tx{
  403. Position: positionL1,
  404. UserOrigin: false,
  405. FromEthAddr: l2Tx.ToEthAddr,
  406. FromBJJ: l2Tx.ToBJJ,
  407. TokenID: l2Tx.TokenID,
  408. DepositAmount: big.NewInt(0),
  409. Type: common.TxTypeCreateAccountDeposit,
  410. }
  411. positionL1++
  412. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  413. }
  414. return validTxs, l1CoordinatorTxs, accAuth, positionL1, nil
  415. }
  416. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  417. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  418. for i := 0; i < len(l1CoordinatorTxs); i++ {
  419. if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) &&
  420. l1CoordinatorTxs[i].TokenID == tokenID &&
  421. l1CoordinatorTxs[i].FromBJJ == bjj {
  422. return true
  423. }
  424. }
  425. return false
  426. }
  427. // getL2Profitable returns the profitable selection of L2Txssorted by Nonce
  428. func (txsel *TxSelector) getL2Profitable(txs txs, max uint32) txs {
  429. sort.Sort(txs)
  430. if len(txs) < int(max) {
  431. return txs
  432. }
  433. txs = txs[:max]
  434. // sort l2Txs by Nonce. This can be done in many different ways, what
  435. // is needed is to output the txs where the Nonce of txs for each
  436. // Account is sorted, but the txs can not be grouped by sender Account
  437. // neither by Fee. This is because later on the Nonces will need to be
  438. // sequential for the zkproof generation.
  439. sort.SliceStable(txs, func(i, j int) bool {
  440. return txs[i].Nonce < txs[j].Nonce
  441. })
  442. return txs
  443. }