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.

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