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.

846 lines
24 KiB

  1. package historydb
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/hermeznetwork/hermez-node/db"
  10. "github.com/hermeznetwork/hermez-node/log"
  11. "github.com/iden3/go-iden3-crypto/babyjub"
  12. "github.com/jmoiron/sqlx"
  13. //nolint:errcheck // driver for postgres DB
  14. _ "github.com/lib/pq"
  15. "github.com/russross/meddler"
  16. )
  17. const (
  18. // OrderAsc indicates ascending order when using pagination
  19. OrderAsc = "ASC"
  20. // OrderDesc indicates descending order when using pagination
  21. OrderDesc = "DESC"
  22. )
  23. // TODO(Edu): Document here how HistoryDB is kept consistent
  24. // HistoryDB persist the historic of the rollup
  25. type HistoryDB struct {
  26. db *sqlx.DB
  27. }
  28. // BlockData contains the information of a Block
  29. type BlockData struct {
  30. Block *common.Block
  31. // Rollup
  32. // L1UserTxs that were submitted in the block
  33. L1UserTxs []common.L1Tx
  34. Batches []BatchData
  35. RegisteredTokens []common.Token
  36. RollupVars *common.RollupVars
  37. // Auction
  38. Bids []common.Bid
  39. Coordinators []common.Coordinator
  40. AuctionVars *common.AuctionVars
  41. WithdrawDelayerVars *common.WithdrawDelayerVars
  42. // TODO: enable when common.WithdrawalDelayerVars is Merged from Synchronizer PR
  43. // WithdrawalDelayerVars *common.WithdrawalDelayerVars
  44. }
  45. // BatchData contains the information of a Batch
  46. type BatchData struct {
  47. // L1UserTxs that were forged in the batch
  48. L1Batch bool // TODO: Remove once Batch.ForgeL1TxsNum is a pointer
  49. L1UserTxs []common.L1Tx
  50. L1CoordinatorTxs []common.L1Tx
  51. L2Txs []common.L2Tx
  52. CreatedAccounts []common.Account
  53. ExitTree []common.ExitInfo
  54. Batch *common.Batch
  55. }
  56. // NewBatchData creates an empty BatchData with the slices initialized.
  57. func NewBatchData() *BatchData {
  58. return &BatchData{
  59. L1Batch: false,
  60. L1UserTxs: make([]common.L1Tx, 0),
  61. L1CoordinatorTxs: make([]common.L1Tx, 0),
  62. L2Txs: make([]common.L2Tx, 0),
  63. CreatedAccounts: make([]common.Account, 0),
  64. ExitTree: make([]common.ExitInfo, 0),
  65. Batch: &common.Batch{},
  66. }
  67. }
  68. // NewHistoryDB initialize the DB
  69. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  70. return &HistoryDB{db: db}
  71. }
  72. // AddBlock insert a block into the DB
  73. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  74. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  75. return meddler.Insert(d, "block", block)
  76. }
  77. // AddBlocks inserts blocks into the DB
  78. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  79. return hdb.addBlocks(hdb.db, blocks)
  80. }
  81. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  82. return db.BulkInsert(
  83. d,
  84. `INSERT INTO block (
  85. eth_block_num,
  86. timestamp,
  87. hash
  88. ) VALUES %s;`,
  89. blocks[:],
  90. )
  91. }
  92. // GetBlock retrieve a block from the DB, given a block number
  93. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  94. block := &common.Block{}
  95. err := meddler.QueryRow(
  96. hdb.db, block,
  97. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  98. )
  99. return block, err
  100. }
  101. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  102. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  103. var blocks []*common.Block
  104. err := meddler.QueryAll(
  105. hdb.db, &blocks,
  106. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  107. from, to,
  108. )
  109. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  110. }
  111. // GetLastBlock retrieve the block with the highest block number from the DB
  112. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  113. block := &common.Block{}
  114. err := meddler.QueryRow(
  115. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  116. )
  117. return block, err
  118. }
  119. // AddBatch insert a Batch into the DB
  120. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  121. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  122. return meddler.Insert(d, "batch", batch)
  123. }
  124. // AddBatches insert Bids into the DB
  125. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  126. return hdb.addBatches(hdb.db, batches)
  127. }
  128. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  129. // TODO: Calculate and insert total_fees_usd
  130. return db.BulkInsert(
  131. d,
  132. `INSERT INTO batch (
  133. batch_num,
  134. eth_block_num,
  135. forger_addr,
  136. fees_collected,
  137. state_root,
  138. num_accounts,
  139. exit_root,
  140. forge_l1_txs_num,
  141. slot_num
  142. ) VALUES %s;`,
  143. batches[:],
  144. )
  145. }
  146. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  147. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  148. var batches []*common.Batch
  149. err := meddler.QueryAll(
  150. hdb.db, &batches,
  151. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
  152. from, to,
  153. )
  154. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  155. }
  156. // GetLastBatchNum returns the BatchNum of the latest forged batch
  157. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  158. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  159. var batchNum common.BatchNum
  160. return batchNum, row.Scan(&batchNum)
  161. }
  162. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB. If there's no
  163. // batch in the DB (nil, nil) is returned.
  164. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  165. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  166. lastL1TxsNum := new(int64)
  167. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  168. }
  169. // Reorg deletes all the information that was added into the DB after the
  170. // lastValidBlock. If lastValidBlock is negative, all block information is
  171. // deleted.
  172. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  173. var err error
  174. if lastValidBlock < 0 {
  175. _, err = hdb.db.Exec("DELETE FROM block;")
  176. } else {
  177. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  178. }
  179. return err
  180. }
  181. // SyncPoD stores all the data that can be changed / added on a block in the PoD SC
  182. func (hdb *HistoryDB) SyncPoD(
  183. blockNum uint64,
  184. bids []common.Bid,
  185. coordinators []common.Coordinator,
  186. vars *common.AuctionVars,
  187. ) error {
  188. return nil
  189. }
  190. // AddBids insert Bids into the DB
  191. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  192. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  193. // TODO: check the coordinator info
  194. return db.BulkInsert(
  195. d,
  196. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  197. bids[:],
  198. )
  199. }
  200. // GetBids return the bids
  201. func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
  202. var bids []*common.Bid
  203. err := meddler.QueryAll(
  204. hdb.db, &bids,
  205. "SELECT * FROM bid;",
  206. )
  207. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  208. }
  209. // AddCoordinators insert Coordinators into the DB
  210. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  211. return hdb.addCoordinators(hdb.db, coordinators)
  212. }
  213. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  214. return db.BulkInsert(
  215. d,
  216. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  217. coordinators[:],
  218. )
  219. }
  220. // AddExitTree insert Exit tree into the DB
  221. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  222. return hdb.addExitTree(hdb.db, exitTree)
  223. }
  224. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  225. return db.BulkInsert(
  226. d,
  227. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  228. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  229. exitTree[:],
  230. )
  231. }
  232. // AddToken insert a token into the DB
  233. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  234. return meddler.Insert(hdb.db, "token", token)
  235. }
  236. // AddTokens insert tokens into the DB
  237. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  238. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  239. return db.BulkInsert(
  240. d,
  241. `INSERT INTO token (
  242. token_id,
  243. eth_block_num,
  244. eth_addr,
  245. name,
  246. symbol,
  247. decimals
  248. ) VALUES %s;`,
  249. tokens[:],
  250. )
  251. }
  252. // UpdateTokenValue updates the USD value of a token
  253. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  254. _, err := hdb.db.Exec(
  255. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  256. value, tokenSymbol,
  257. )
  258. return err
  259. }
  260. // GetTokens returns a list of tokens from the DB
  261. func (hdb *HistoryDB) GetTokens() ([]TokenRead, error) {
  262. var tokens []*TokenRead
  263. err := meddler.QueryAll(
  264. hdb.db, &tokens,
  265. "SELECT * FROM token ORDER BY token_id;",
  266. )
  267. return db.SlicePtrsToSlice(tokens).([]TokenRead), err
  268. }
  269. // GetTokenSymbols returns all the token symbols from the DB
  270. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  271. var tokenSymbols []string
  272. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  273. if err != nil {
  274. return nil, err
  275. }
  276. sym := new(string)
  277. for rows.Next() {
  278. err = rows.Scan(sym)
  279. if err != nil {
  280. return nil, err
  281. }
  282. tokenSymbols = append(tokenSymbols, *sym)
  283. }
  284. return tokenSymbols, nil
  285. }
  286. // AddAccounts insert accounts into the DB
  287. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  288. return hdb.addAccounts(hdb.db, accounts)
  289. }
  290. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  291. return db.BulkInsert(
  292. d,
  293. `INSERT INTO account (
  294. idx,
  295. token_id,
  296. batch_num,
  297. bjj,
  298. eth_addr
  299. ) VALUES %s;`,
  300. accounts[:],
  301. )
  302. }
  303. // GetAccounts returns a list of accounts from the DB
  304. func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
  305. var accs []*common.Account
  306. err := meddler.QueryAll(
  307. hdb.db, &accs,
  308. "SELECT * FROM account ORDER BY idx;",
  309. )
  310. return db.SlicePtrsToSlice(accs).([]common.Account), err
  311. }
  312. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  313. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  314. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  315. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  316. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  317. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  318. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  319. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  320. txs := []txWrite{}
  321. for i := 0; i < len(l1txs); i++ {
  322. af := new(big.Float).SetInt(l1txs[i].Amount)
  323. amountFloat, _ := af.Float64()
  324. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  325. loadAmountFloat, _ := laf.Float64()
  326. txs = append(txs, txWrite{
  327. // Generic
  328. IsL1: true,
  329. TxID: l1txs[i].TxID,
  330. Type: l1txs[i].Type,
  331. Position: l1txs[i].Position,
  332. FromIdx: &l1txs[i].FromIdx,
  333. ToIdx: l1txs[i].ToIdx,
  334. Amount: l1txs[i].Amount,
  335. AmountFloat: amountFloat,
  336. TokenID: l1txs[i].TokenID,
  337. BatchNum: l1txs[i].BatchNum,
  338. EthBlockNum: l1txs[i].EthBlockNum,
  339. // L1
  340. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  341. UserOrigin: &l1txs[i].UserOrigin,
  342. FromEthAddr: &l1txs[i].FromEthAddr,
  343. FromBJJ: l1txs[i].FromBJJ,
  344. LoadAmount: l1txs[i].LoadAmount,
  345. LoadAmountFloat: &loadAmountFloat,
  346. })
  347. }
  348. return hdb.addTxs(d, txs)
  349. }
  350. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  351. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  352. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  353. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  354. txs := []txWrite{}
  355. for i := 0; i < len(l2txs); i++ {
  356. f := new(big.Float).SetInt(l2txs[i].Amount)
  357. amountFloat, _ := f.Float64()
  358. txs = append(txs, txWrite{
  359. // Generic
  360. IsL1: false,
  361. TxID: l2txs[i].TxID,
  362. Type: l2txs[i].Type,
  363. Position: l2txs[i].Position,
  364. FromIdx: &l2txs[i].FromIdx,
  365. ToIdx: l2txs[i].ToIdx,
  366. Amount: l2txs[i].Amount,
  367. AmountFloat: amountFloat,
  368. BatchNum: &l2txs[i].BatchNum,
  369. EthBlockNum: l2txs[i].EthBlockNum,
  370. // L2
  371. Fee: &l2txs[i].Fee,
  372. Nonce: &l2txs[i].Nonce,
  373. })
  374. }
  375. return hdb.addTxs(d, txs)
  376. }
  377. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  378. return db.BulkInsert(
  379. d,
  380. `INSERT INTO tx (
  381. is_l1,
  382. id,
  383. type,
  384. position,
  385. from_idx,
  386. to_idx,
  387. amount,
  388. amount_f,
  389. token_id,
  390. batch_num,
  391. eth_block_num,
  392. to_forge_l1_txs_num,
  393. user_origin,
  394. from_eth_addr,
  395. from_bjj,
  396. load_amount,
  397. load_amount_f,
  398. fee,
  399. nonce
  400. ) VALUES %s;`,
  401. txs[:],
  402. )
  403. }
  404. // // GetTxs returns a list of txs from the DB
  405. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  406. // var txs []*common.Tx
  407. // err := meddler.QueryAll(
  408. // hdb.db, &txs,
  409. // `SELECT * FROM tx
  410. // ORDER BY (batch_num, position) ASC`,
  411. // )
  412. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  413. // }
  414. // GetHistoryTx returns a tx from the DB given a TxID
  415. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*HistoryTx, error) {
  416. tx := &HistoryTx{}
  417. err := meddler.QueryRow(
  418. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  419. tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
  420. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  421. tx.from_eth_addr, tx.from_bjj, tx.load_amount,
  422. tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  423. token.token_id, token.eth_block_num AS token_block,
  424. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  425. token.usd_update, block.timestamp
  426. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  427. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  428. WHERE tx.id = $1;`, txID,
  429. )
  430. return tx, err
  431. }
  432. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  433. // and pagination info
  434. func (hdb *HistoryDB) GetHistoryTxs(
  435. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  436. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  437. fromItem, limit *uint, order string,
  438. ) ([]HistoryTx, *db.Pagination, error) {
  439. if ethAddr != nil && bjj != nil {
  440. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  441. }
  442. var query string
  443. var args []interface{}
  444. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  445. tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
  446. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  447. tx.from_eth_addr, tx.from_bjj, tx.load_amount,
  448. tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  449. token.token_id, token.eth_block_num AS token_block,
  450. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  451. token.usd_update, block.timestamp, count(*) OVER() AS total_items,
  452. MIN(tx.item_id) OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item
  453. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  454. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  455. // Apply filters
  456. nextIsAnd := false
  457. // ethAddr filter
  458. if ethAddr != nil {
  459. queryStr = `WITH acc AS
  460. (select idx from account where eth_addr = ?) ` + queryStr
  461. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  462. nextIsAnd = true
  463. args = append(args, ethAddr)
  464. } else if bjj != nil { // bjj filter
  465. queryStr = `WITH acc AS
  466. (select idx from account where bjj = ?) ` + queryStr
  467. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  468. nextIsAnd = true
  469. args = append(args, bjj)
  470. }
  471. // tokenID filter
  472. if tokenID != nil {
  473. if nextIsAnd {
  474. queryStr += "AND "
  475. } else {
  476. queryStr += "WHERE "
  477. }
  478. queryStr += "tx.token_id = ? "
  479. args = append(args, tokenID)
  480. nextIsAnd = true
  481. }
  482. // idx filter
  483. if idx != nil {
  484. if nextIsAnd {
  485. queryStr += "AND "
  486. } else {
  487. queryStr += "WHERE "
  488. }
  489. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  490. args = append(args, idx, idx)
  491. nextIsAnd = true
  492. }
  493. // batchNum filter
  494. if batchNum != nil {
  495. if nextIsAnd {
  496. queryStr += "AND "
  497. } else {
  498. queryStr += "WHERE "
  499. }
  500. queryStr += "tx.batch_num = ? "
  501. args = append(args, batchNum)
  502. nextIsAnd = true
  503. }
  504. // txType filter
  505. if txType != nil {
  506. if nextIsAnd {
  507. queryStr += "AND "
  508. } else {
  509. queryStr += "WHERE "
  510. }
  511. queryStr += "tx.type = ? "
  512. args = append(args, txType)
  513. nextIsAnd = true
  514. }
  515. if fromItem != nil {
  516. if nextIsAnd {
  517. queryStr += "AND "
  518. } else {
  519. queryStr += "WHERE "
  520. }
  521. if order == OrderAsc {
  522. queryStr += "tx.item_id >= ? "
  523. } else {
  524. queryStr += "tx.item_id <= ? "
  525. }
  526. args = append(args, fromItem)
  527. nextIsAnd = true
  528. }
  529. if nextIsAnd {
  530. queryStr += "AND "
  531. } else {
  532. queryStr += "WHERE "
  533. }
  534. queryStr += "tx.batch_num IS NOT NULL "
  535. // pagination
  536. queryStr += "ORDER BY tx.item_id "
  537. if order == OrderAsc {
  538. queryStr += " ASC "
  539. } else {
  540. queryStr += " DESC "
  541. }
  542. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  543. query = hdb.db.Rebind(queryStr)
  544. log.Debug(query)
  545. txsPtrs := []*HistoryTx{}
  546. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  547. return nil, nil, err
  548. }
  549. txs := db.SlicePtrsToSlice(txsPtrs).([]HistoryTx)
  550. if len(txs) == 0 {
  551. return nil, nil, sql.ErrNoRows
  552. }
  553. return txs, &db.Pagination{
  554. TotalItems: txs[0].TotalItems,
  555. FirstItem: txs[0].FirstItem,
  556. LastItem: txs[0].LastItem,
  557. }, nil
  558. }
  559. // GetExit returns a exit from the DB
  560. func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
  561. exit := &HistoryExit{}
  562. err := meddler.QueryRow(
  563. hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  564. token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  565. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  566. INNER JOIN token ON account.token_id = token.token_id
  567. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  568. )
  569. return exit, err
  570. }
  571. // GetExits returns a list of exits from the DB and pagination info
  572. func (hdb *HistoryDB) GetExits(
  573. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  574. tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
  575. fromItem, limit *uint, order string,
  576. ) ([]HistoryExit, *db.Pagination, error) {
  577. if ethAddr != nil && bjj != nil {
  578. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  579. }
  580. var query string
  581. var args []interface{}
  582. queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  583. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  584. token.usd_update, COUNT(*) OVER() AS total_items, MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
  585. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  586. INNER JOIN token ON account.token_id = token.token_id `
  587. // Apply filters
  588. nextIsAnd := false
  589. // ethAddr filter
  590. if ethAddr != nil {
  591. queryStr += "WHERE account.eth_addr = ? "
  592. nextIsAnd = true
  593. args = append(args, ethAddr)
  594. } else if bjj != nil { // bjj filter
  595. queryStr += "WHERE account.bjj = ? "
  596. nextIsAnd = true
  597. args = append(args, bjj)
  598. }
  599. // tokenID filter
  600. if tokenID != nil {
  601. if nextIsAnd {
  602. queryStr += "AND "
  603. } else {
  604. queryStr += "WHERE "
  605. }
  606. queryStr += "account.token_id = ? "
  607. args = append(args, tokenID)
  608. nextIsAnd = true
  609. }
  610. // idx filter
  611. if idx != nil {
  612. if nextIsAnd {
  613. queryStr += "AND "
  614. } else {
  615. queryStr += "WHERE "
  616. }
  617. queryStr += "exit_tree.account_idx = ? "
  618. args = append(args, idx)
  619. nextIsAnd = true
  620. }
  621. // batchNum filter
  622. if batchNum != nil {
  623. if nextIsAnd {
  624. queryStr += "AND "
  625. } else {
  626. queryStr += "WHERE "
  627. }
  628. queryStr += "exit_tree.batch_num = ? "
  629. args = append(args, batchNum)
  630. nextIsAnd = true
  631. }
  632. if fromItem != nil {
  633. if nextIsAnd {
  634. queryStr += "AND "
  635. } else {
  636. queryStr += "WHERE "
  637. }
  638. if order == OrderAsc {
  639. queryStr += "exit_tree.item_id >= ? "
  640. } else {
  641. queryStr += "exit_tree.item_id <= ? "
  642. }
  643. args = append(args, fromItem)
  644. // nextIsAnd = true
  645. }
  646. // pagination
  647. queryStr += "ORDER BY exit_tree.item_id "
  648. if order == OrderAsc {
  649. queryStr += " ASC "
  650. } else {
  651. queryStr += " DESC "
  652. }
  653. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  654. query = hdb.db.Rebind(queryStr)
  655. // log.Debug(query)
  656. exits := []*HistoryExit{}
  657. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  658. return nil, nil, err
  659. }
  660. if len(exits) == 0 {
  661. return nil, nil, sql.ErrNoRows
  662. }
  663. return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
  664. TotalItems: exits[0].TotalItems,
  665. FirstItem: exits[0].FirstItem,
  666. LastItem: exits[0].LastItem,
  667. }, nil
  668. }
  669. // // GetTx returns a tx from the DB
  670. // func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  671. // tx := new(common.Tx)
  672. // return tx, meddler.QueryRow(
  673. // hdb.db, tx,
  674. // "SELECT * FROM tx WHERE id = $1;",
  675. // txID,
  676. // )
  677. // }
  678. // // GetL1UserTxs gets L1 User Txs to be forged in a batch that will create an account
  679. // // TODO: This is currently not used. Figure out if it should be used somewhere or removed.
  680. // func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]*common.Tx, error) {
  681. // var txs []*common.Tx
  682. // err := meddler.QueryAll(
  683. // hdb.db, &txs,
  684. // "SELECT * FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;",
  685. // toForgeL1TxsNum,
  686. // )
  687. // return txs, err
  688. // }
  689. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  690. // GetLastTxsPosition for a given to_forge_l1_txs_num
  691. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  692. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  693. var lastL1TxsPosition int
  694. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  695. }
  696. // AddBlockSCData stores all the information of a block retrieved by the Synchronizer
  697. func (hdb *HistoryDB) AddBlockSCData(blockData *BlockData) (err error) {
  698. txn, err := hdb.db.Begin()
  699. if err != nil {
  700. return err
  701. }
  702. defer func() {
  703. if err != nil {
  704. errRollback := txn.Rollback()
  705. if errRollback != nil {
  706. log.Errorw("Rollback", "err", errRollback)
  707. }
  708. }
  709. }()
  710. // Add block
  711. err = hdb.addBlock(txn, blockData.Block)
  712. if err != nil {
  713. return err
  714. }
  715. // Add Coordinators
  716. if len(blockData.Coordinators) > 0 {
  717. err = hdb.addCoordinators(txn, blockData.Coordinators)
  718. if err != nil {
  719. return err
  720. }
  721. }
  722. // Add Bids
  723. if len(blockData.Bids) > 0 {
  724. err = hdb.addBids(txn, blockData.Bids)
  725. if err != nil {
  726. return err
  727. }
  728. }
  729. // Add Tokens
  730. if len(blockData.RegisteredTokens) > 0 {
  731. err = hdb.addTokens(txn, blockData.RegisteredTokens)
  732. if err != nil {
  733. return err
  734. }
  735. }
  736. // Add l1 Txs
  737. if len(blockData.L1UserTxs) > 0 {
  738. err = hdb.addL1Txs(txn, blockData.L1UserTxs)
  739. if err != nil {
  740. return err
  741. }
  742. }
  743. // Add Batches
  744. for _, batch := range blockData.Batches {
  745. // Add Batch: this will trigger an update on the DB
  746. // that will set the batch num of forged L1 txs in this batch
  747. err = hdb.addBatch(txn, batch.Batch)
  748. if err != nil {
  749. return err
  750. }
  751. // Add unforged l1 Txs
  752. if batch.L1Batch {
  753. if len(batch.L1CoordinatorTxs) > 0 {
  754. err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
  755. if err != nil {
  756. return err
  757. }
  758. }
  759. }
  760. // Add l2 Txs
  761. if len(batch.L2Txs) > 0 {
  762. err = hdb.addL2Txs(txn, batch.L2Txs)
  763. if err != nil {
  764. return err
  765. }
  766. }
  767. // Add accounts
  768. if len(batch.CreatedAccounts) > 0 {
  769. err = hdb.addAccounts(txn, batch.CreatedAccounts)
  770. if err != nil {
  771. return err
  772. }
  773. }
  774. // Add exit tree
  775. if len(batch.ExitTree) > 0 {
  776. err = hdb.addExitTree(txn, batch.ExitTree)
  777. if err != nil {
  778. return err
  779. }
  780. }
  781. // TODO: INSERT CONTRACTS VARS
  782. }
  783. return txn.Commit()
  784. }