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.

476 lines
16 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. func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig,
  162. batchNum common.BatchNum) ([]common.Idx, [][]byte, []common.L1Tx, []common.PoolL2Tx, error) {
  163. coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, err := txsel.GetL1L2TxSelection(selectionConfig, batchNum,
  164. []common.L1Tx{})
  165. return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, tracerr.Wrap(err)
  166. }
  167. // GetL1L2TxSelection returns the selection of L1 + L2 txs
  168. func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
  169. batchNum common.BatchNum, l1Txs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx, []common.L1Tx,
  170. []common.PoolL2Tx, error) {
  171. // TODO WIP this method uses a 'cherry-pick' of internal calls of the
  172. // StateDB, a refactor of the StateDB to reorganize it internally is
  173. // planned once the main functionallities are covered, with that
  174. // refactor the TxSelector will be updated also
  175. // apply l1-user-tx to localAccountDB
  176. // create new leaves
  177. // update balances
  178. // update nonces
  179. // get existing CoordIdxs
  180. coordIdxsMap, err := txsel.GetCoordIdxs()
  181. if err != nil {
  182. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  183. }
  184. var coordIdxs []common.Idx
  185. for tokenID := range coordIdxsMap {
  186. coordIdxs = append(coordIdxs, coordIdxsMap[tokenID])
  187. }
  188. // get pending l2-tx from tx-pool
  189. l2TxsRaw, err := txsel.l2db.GetPendingTxs() // (batchID)
  190. if err != nil {
  191. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  192. }
  193. var validTxs txs
  194. var l1CoordinatorTxs []common.L1Tx
  195. positionL1 := len(l1Txs)
  196. // Process L1UserTxs
  197. for i := 0; i < len(l1Txs); i++ {
  198. // assumption: l1usertx are sorted by L1Tx.Position
  199. _, _, _, _, err := txsel.localAccountsDB.ProcessL1Tx(nil, &l1Txs[i])
  200. if err != nil {
  201. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  202. }
  203. }
  204. // get last idx from LocalStateDB
  205. // lastIdx := txsel.localStateDB.idx
  206. // update lastIdx with the L1UserTxs (of account creation)
  207. for i := 0; i < len(l2TxsRaw); i++ {
  208. // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
  209. // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
  210. // case of TxToEthAddr or TxToBJJ, check if
  211. // tx.ToEthAddr/tx.ToBJJ exist in localAccountsDB, if yes tx is
  212. // used; if not, check if tx.ToEthAddr is in
  213. // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
  214. // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
  215. // Exit type and is used.
  216. if l2TxsRaw[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
  217. validTxs, l1CoordinatorTxs, positionL1, err =
  218. txsel.processTxToEthAddrBJJ(validTxs, l1CoordinatorTxs,
  219. positionL1, l2TxsRaw[i])
  220. if err != nil {
  221. log.Debug(err)
  222. continue
  223. }
  224. } else if l2TxsRaw[i].ToIdx >= common.IdxUserThreshold {
  225. _, err = txsel.localAccountsDB.GetAccount(l2TxsRaw[i].ToIdx)
  226. if err != nil {
  227. // tx not valid
  228. log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
  229. "ToIdx", l2TxsRaw[i].ToIdx)
  230. continue
  231. }
  232. // TODO if EthAddr!=0 or BJJ!=0, check that ToIdxAccount.EthAddr or BJJ
  233. // Account found in the DB, include the l2Tx in the selection
  234. validTxs = append(validTxs, l2TxsRaw[i])
  235. } else if l2TxsRaw[i].ToIdx == common.Idx(1) {
  236. // valid txs (of Exit type)
  237. validTxs = append(validTxs, l2TxsRaw[i])
  238. }
  239. // TODO if needed add L1CoordinatorTx to create a Coordinator
  240. // account for the new TokenID
  241. // var newL1CoordTx *common.L1Tx
  242. // newL1CoordTx, positionL1, err = txsel.coordAccountForTokenID(l1CoordinatorTxs, l2TxsRaw[i].TokenID, positionL1)
  243. // if err != nil {
  244. // return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  245. // }
  246. // if newL1CoordTx != nil {
  247. // l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
  248. // }
  249. }
  250. // Process L1CoordinatorTxs
  251. for i := 0; i < len(l1CoordinatorTxs); i++ {
  252. fmt.Println("PRINT", i, &l1CoordinatorTxs[i])
  253. _, _, _, _, err := txsel.localAccountsDB.ProcessL1Tx(nil, &l1CoordinatorTxs[i])
  254. if err != nil {
  255. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  256. }
  257. }
  258. txsel.localAccountsDB.AccumulatedFees = make(map[common.Idx]*big.Int)
  259. for _, idx := range coordIdxs {
  260. txsel.localAccountsDB.AccumulatedFees[idx] = big.NewInt(0)
  261. }
  262. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  263. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  264. // created in the current batch, at this point the Idx will be created
  265. coordIdxsMap, err = txsel.localAccountsDB.GetTokenIDsFromIdxs(coordIdxs)
  266. if err != nil {
  267. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  268. }
  269. // get most profitable L2-tx
  270. maxL2Txs := selectionConfig.ProcessTxsConfig.MaxTx - uint32(len(l1CoordinatorTxs)) // - len(l1UserTxs) // TODO if there are L1UserTxs take them in to account
  271. l2Txs := txsel.getL2Profitable(validTxs, maxL2Txs)
  272. // Process L2Txs
  273. for i := 0; i < len(l2Txs); i++ {
  274. _, _, _, err = txsel.localAccountsDB.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
  275. if err != nil {
  276. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  277. }
  278. }
  279. err = txsel.AddCoordIdxs(coordIdxsMap)
  280. if err != nil {
  281. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  282. }
  283. err = txsel.localAccountsDB.MakeCheckpoint()
  284. if err != nil {
  285. return nil, nil, nil, nil, nil, tracerr.Wrap(err)
  286. }
  287. // TODO
  288. auths := make([][]byte, len(l1CoordinatorTxs))
  289. for i := range auths {
  290. auths[i] = make([]byte, 65)
  291. }
  292. return nil, auths, l1Txs, l1CoordinatorTxs, l2Txs, nil
  293. }
  294. // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
  295. // ToIdx==0, which can be the tx type of ToEthAddr or ToBJJ. If the receiver
  296. // does not have an account yet, a new L1CoordinatorTx of type
  297. // CreateAccountDeposit (with 0 as DepositAmount) is created and added to the
  298. // l1CoordinatorTxs array, and then the PoolL2Tx is added into the validTxs
  299. // array.
  300. func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []common.L1Tx,
  301. positionL1 int, l2Tx common.PoolL2Tx) (txs, []common.L1Tx, int, error) {
  302. // if L2Tx needs a new L1CoordinatorTx of CreateAccount type, and a
  303. // previous L2Tx in the current process already created a
  304. // L1CoordinatorTx of this type, in the DB there still seem that needs
  305. // to create a new L1CoordinatorTx, but as is already created, the tx
  306. // is valid
  307. if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2Tx.TokenID, l2Tx.ToEthAddr, l2Tx.ToBJJ) {
  308. validTxs = append(validTxs, l2Tx)
  309. return validTxs, l1CoordinatorTxs, positionL1, nil
  310. }
  311. if !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) &&
  312. !bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
  313. // case: ToEthAddr != 0x00 neither 0xff
  314. var accAuth *common.AccountCreationAuth
  315. if l2Tx.ToBJJ != common.EmptyBJJComp {
  316. // case: ToBJJ!=0:
  317. // if idx exist for EthAddr&BJJ use it
  318. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
  319. l2Tx.ToBJJ, l2Tx.TokenID)
  320. if err == nil {
  321. // account for ToEthAddr&ToBJJ already exist,
  322. // there is no need to create a new one.
  323. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  324. validTxs = append(validTxs, l2Tx)
  325. return validTxs, l1CoordinatorTxs, positionL1, nil
  326. }
  327. // if not, check if AccountCreationAuth exist for that
  328. // ToEthAddr
  329. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  330. if err != nil {
  331. // not found, l2Tx will not be added in the selection
  332. return validTxs, l1CoordinatorTxs, positionL1, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  333. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex()))
  334. }
  335. if accAuth.BJJ != l2Tx.ToBJJ {
  336. // if AccountCreationAuth.BJJ is not the same
  337. // than in the tx, tx is not accepted
  338. return validTxs, l1CoordinatorTxs, 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",
  339. l2Tx.ToIdx, l2Tx.ToEthAddr.Hex(), l2Tx.ToBJJ.String()))
  340. }
  341. validTxs = append(validTxs, l2Tx)
  342. } else {
  343. // case: ToBJJ==0:
  344. // if idx exist for EthAddr use it
  345. _, err := txsel.localAccountsDB.GetIdxByEthAddr(l2Tx.ToEthAddr, l2Tx.TokenID)
  346. if err == nil {
  347. // account for ToEthAddr already exist,
  348. // there is no need to create a new one.
  349. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  350. validTxs = append(validTxs, l2Tx)
  351. return validTxs, l1CoordinatorTxs, positionL1, nil
  352. }
  353. // if not, check if AccountCreationAuth exist for that ToEthAddr
  354. accAuth, err = txsel.l2db.GetAccountCreationAuth(l2Tx.ToEthAddr)
  355. if err != nil {
  356. // not found, l2Tx will not be added in the selection
  357. return validTxs, l1CoordinatorTxs, positionL1, tracerr.Wrap(fmt.Errorf("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB. ToIdx: %d, ToEthAddr: %s",
  358. l2Tx.ToIdx, l2Tx.ToEthAddr))
  359. }
  360. validTxs = append(validTxs, l2Tx)
  361. }
  362. // create L1CoordinatorTx for the accountCreation
  363. l1CoordinatorTx := common.L1Tx{
  364. Position: positionL1,
  365. UserOrigin: false,
  366. FromEthAddr: accAuth.EthAddr,
  367. FromBJJ: accAuth.BJJ,
  368. TokenID: l2Tx.TokenID,
  369. DepositAmount: big.NewInt(0),
  370. Type: common.TxTypeCreateAccountDeposit,
  371. }
  372. positionL1++
  373. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  374. } else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2Tx.ToBJJ != common.EmptyBJJComp {
  375. // if idx exist for EthAddr&BJJ use it
  376. _, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
  377. l2Tx.TokenID)
  378. if err == nil {
  379. // account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
  380. // there is no need to create a new one.
  381. // tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
  382. validTxs = append(validTxs, l2Tx)
  383. return validTxs, l1CoordinatorTxs, positionL1, nil
  384. }
  385. // if idx don't exist for EthAddr&BJJ,
  386. // coordinator can create a new account without
  387. // L1Authorization, as ToEthAddr==0xff
  388. // create L1CoordinatorTx for the accountCreation
  389. l1CoordinatorTx := common.L1Tx{
  390. Position: positionL1,
  391. UserOrigin: false,
  392. FromEthAddr: l2Tx.ToEthAddr,
  393. FromBJJ: l2Tx.ToBJJ,
  394. TokenID: l2Tx.TokenID,
  395. DepositAmount: big.NewInt(0),
  396. Type: common.TxTypeCreateAccountDeposit,
  397. }
  398. positionL1++
  399. l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
  400. }
  401. return validTxs, l1CoordinatorTxs, positionL1, nil
  402. }
  403. func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID,
  404. addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
  405. for i := 0; i < len(l1CoordinatorTxs); i++ {
  406. if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) &&
  407. l1CoordinatorTxs[i].TokenID == tokenID &&
  408. l1CoordinatorTxs[i].FromBJJ == bjj {
  409. return true
  410. }
  411. }
  412. return false
  413. }
  414. // getL2Profitable returns the profitable selection of L2Txssorted by Nonce
  415. func (txsel *TxSelector) getL2Profitable(txs txs, max uint32) txs {
  416. sort.Sort(txs)
  417. if len(txs) < int(max) {
  418. return txs
  419. }
  420. txs = txs[:max]
  421. // sort l2Txs by Nonce. This can be done in many different ways, what
  422. // is needed is to output the txs where the Nonce of txs for each
  423. // Account is sorted, but the txs can not be grouped by sender Account
  424. // neither by Fee. This is because later on the Nonces will need to be
  425. // sequential for the zkproof generation.
  426. sort.SliceStable(txs, func(i, j int) bool {
  427. return txs[i].Nonce < txs[j].Nonce
  428. })
  429. return txs
  430. }