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.

627 lines
16 KiB

  1. package historydb
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/hermeznetwork/hermez-node/common"
  8. "github.com/hermeznetwork/hermez-node/db"
  9. "github.com/iden3/go-iden3-crypto/babyjub"
  10. "github.com/jmoiron/sqlx"
  11. //nolint:errcheck // driver for postgres DB
  12. _ "github.com/lib/pq"
  13. "github.com/russross/meddler"
  14. )
  15. // TODO(Edu): Document here how HistoryDB is kept consistent
  16. // HistoryDB persist the historic of the rollup
  17. type HistoryDB struct {
  18. db *sqlx.DB
  19. }
  20. // BlockData contains the information of a Block
  21. type BlockData struct {
  22. block *common.Block
  23. // Rollup
  24. // L1UserTxs that were submitted in the block
  25. L1UserTxs []common.L1Tx
  26. Batches []BatchData
  27. RegisteredTokens []common.Token
  28. RollupVars *common.RollupVars
  29. // Auction
  30. Bids []common.Bid
  31. Coordinators []common.Coordinator
  32. AuctionVars *common.AuctionVars
  33. // WithdrawalDelayer
  34. // TODO: enable when common.WithdrawalDelayerVars is Merged from Synchronizer PR
  35. // WithdrawalDelayerVars *common.WithdrawalDelayerVars
  36. }
  37. // BatchData contains the information of a Batch
  38. type BatchData struct {
  39. // L1UserTxs that were forged in the batch
  40. L1Batch bool // TODO: Remove once Batch.ForgeL1TxsNum is a pointer
  41. L1UserTxs []common.L1Tx
  42. L1CoordinatorTxs []common.L1Tx
  43. L2Txs []common.L2Tx
  44. CreatedAccounts []common.Account
  45. ExitTree []common.ExitInfo
  46. Batch *common.Batch
  47. }
  48. // NewHistoryDB initialize the DB
  49. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  50. return &HistoryDB{db: db}
  51. }
  52. // AddBlock insert a block into the DB
  53. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  54. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  55. return meddler.Insert(d, "block", block)
  56. }
  57. // AddBlocks inserts blocks into the DB
  58. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  59. return hdb.addBlocks(hdb.db, blocks)
  60. }
  61. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  62. return db.BulkInsert(
  63. d,
  64. `INSERT INTO block (
  65. eth_block_num,
  66. timestamp,
  67. hash
  68. ) VALUES %s;`,
  69. blocks[:],
  70. )
  71. }
  72. // GetBlock retrieve a block from the DB, given a block number
  73. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  74. block := &common.Block{}
  75. err := meddler.QueryRow(
  76. hdb.db, block,
  77. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  78. )
  79. return block, err
  80. }
  81. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  82. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]*common.Block, error) {
  83. var blocks []*common.Block
  84. err := meddler.QueryAll(
  85. hdb.db, &blocks,
  86. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  87. from, to,
  88. )
  89. return blocks, err
  90. }
  91. // GetLastBlock retrieve the block with the highest block number from the DB
  92. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  93. block := &common.Block{}
  94. err := meddler.QueryRow(
  95. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  96. )
  97. return block, err
  98. }
  99. // AddBatch insert a Batch into the DB
  100. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  101. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  102. return meddler.Insert(d, "batch", batch)
  103. }
  104. // AddBatches insert Bids into the DB
  105. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  106. return hdb.addBatches(hdb.db, batches)
  107. }
  108. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  109. return db.BulkInsert(
  110. d,
  111. `INSERT INTO batch (
  112. batch_num,
  113. eth_block_num,
  114. forger_addr,
  115. fees_collected,
  116. state_root,
  117. num_accounts,
  118. exit_root,
  119. forge_l1_txs_num,
  120. slot_num
  121. ) VALUES %s;`,
  122. batches[:],
  123. )
  124. }
  125. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  126. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]*common.Batch, error) {
  127. var batches []*common.Batch
  128. err := meddler.QueryAll(
  129. hdb.db, &batches,
  130. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
  131. from, to,
  132. )
  133. return batches, err
  134. }
  135. // GetLastBatchNum returns the BatchNum of the latest forged batch
  136. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  137. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  138. var batchNum common.BatchNum
  139. return batchNum, row.Scan(&batchNum)
  140. }
  141. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB. If there's no
  142. // batch in the DB (nil, nil) is returned.
  143. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  144. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  145. lastL1TxsNum := new(int64)
  146. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  147. }
  148. // Reorg deletes all the information that was added into the DB after the
  149. // lastValidBlock. If lastValidBlock is negative, all block information is
  150. // deleted.
  151. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  152. var err error
  153. if lastValidBlock < 0 {
  154. _, err = hdb.db.Exec("DELETE FROM block;")
  155. } else {
  156. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  157. }
  158. return err
  159. }
  160. // SyncPoD stores all the data that can be changed / added on a block in the PoD SC
  161. func (hdb *HistoryDB) SyncPoD(
  162. blockNum uint64,
  163. bids []common.Bid,
  164. coordinators []common.Coordinator,
  165. vars *common.AuctionVars,
  166. ) error {
  167. return nil
  168. }
  169. // AddBids insert Bids into the DB
  170. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  171. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  172. // TODO: check the coordinator info
  173. return db.BulkInsert(
  174. d,
  175. "INSERT INTO bid (slot_num, forger_addr, bid_value, eth_block_num) VALUES %s;",
  176. bids[:],
  177. )
  178. }
  179. // GetBids return the bids
  180. func (hdb *HistoryDB) GetBids() ([]*common.Bid, error) {
  181. var bids []*common.Bid
  182. err := meddler.QueryAll(
  183. hdb.db, &bids,
  184. "SELECT * FROM bid;",
  185. )
  186. return bids, err
  187. }
  188. // AddCoordinators insert Coordinators into the DB
  189. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  190. return hdb.addCoordinators(hdb.db, coordinators)
  191. }
  192. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  193. return db.BulkInsert(
  194. d,
  195. "INSERT INTO coordinator (forger_addr, eth_block_num, withdraw_addr, url) VALUES %s;",
  196. coordinators[:],
  197. )
  198. }
  199. // AddExitTree insert Exit tree into the DB
  200. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  201. return hdb.addExitTree(hdb.db, exitTree)
  202. }
  203. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  204. return db.BulkInsert(
  205. d,
  206. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  207. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  208. exitTree[:],
  209. )
  210. }
  211. // AddToken insert a token into the DB
  212. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  213. return meddler.Insert(hdb.db, "token", token)
  214. }
  215. // AddTokens insert tokens into the DB
  216. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  217. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  218. return db.BulkInsert(
  219. d,
  220. `INSERT INTO token (
  221. token_id,
  222. eth_block_num,
  223. eth_addr,
  224. name,
  225. symbol,
  226. decimals,
  227. usd,
  228. usd_update
  229. ) VALUES %s;`,
  230. tokens[:],
  231. )
  232. }
  233. // UpdateTokenValue updates the USD value of a token
  234. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  235. _, err := hdb.db.Exec(
  236. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  237. value, tokenSymbol,
  238. )
  239. return err
  240. }
  241. // GetTokens returns a list of tokens from the DB
  242. func (hdb *HistoryDB) GetTokens() ([]*common.Token, error) {
  243. var tokens []*common.Token
  244. err := meddler.QueryAll(
  245. hdb.db, &tokens,
  246. "SELECT * FROM token ORDER BY token_id;",
  247. )
  248. return tokens, err
  249. }
  250. // GetTokenSymbols returns all the token symbols from the DB
  251. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  252. var tokenSymbols []string
  253. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  254. if err != nil {
  255. return nil, err
  256. }
  257. sym := new(string)
  258. for rows.Next() {
  259. err = rows.Scan(sym)
  260. if err != nil {
  261. return nil, err
  262. }
  263. tokenSymbols = append(tokenSymbols, *sym)
  264. }
  265. return tokenSymbols, nil
  266. }
  267. // AddAccounts insert accounts into the DB
  268. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  269. return hdb.addAccounts(hdb.db, accounts)
  270. }
  271. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  272. return db.BulkInsert(
  273. d,
  274. `INSERT INTO account (
  275. idx,
  276. token_id,
  277. batch_num,
  278. bjj,
  279. eth_addr
  280. ) VALUES %s;`,
  281. accounts[:],
  282. )
  283. }
  284. // GetAccounts returns a list of accounts from the DB
  285. func (hdb *HistoryDB) GetAccounts() ([]*common.Account, error) {
  286. var accs []*common.Account
  287. err := meddler.QueryAll(
  288. hdb.db, &accs,
  289. "SELECT * FROM account ORDER BY idx;",
  290. )
  291. return accs, err
  292. }
  293. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  294. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  295. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  296. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  297. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  298. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  299. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  300. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  301. txs := []common.Tx{}
  302. for _, tx := range l1txs {
  303. txs = append(txs, *(tx.Tx()))
  304. }
  305. return hdb.addTxs(d, txs)
  306. }
  307. // AddL2Txs inserts L2 txs to the DB. USD and FeeUSD will be set automatically before storing the tx.
  308. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  309. // addL2Txs inserts L2 txs to the DB. USD and FeeUSD will be set automatically before storing the tx.
  310. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  311. txs := []common.Tx{}
  312. for _, tx := range l2txs {
  313. txs = append(txs, *(tx.Tx()))
  314. }
  315. return hdb.addTxs(d, txs)
  316. }
  317. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []common.Tx) error {
  318. return db.BulkInsert(
  319. d,
  320. `INSERT INTO tx (
  321. is_l1,
  322. id,
  323. type,
  324. position,
  325. from_idx,
  326. to_idx,
  327. amount,
  328. amount_f,
  329. token_id,
  330. amount_usd,
  331. batch_num,
  332. eth_block_num,
  333. to_forge_l1_txs_num,
  334. user_origin,
  335. from_eth_addr,
  336. from_bjj,
  337. load_amount,
  338. load_amount_f,
  339. load_amount_usd,
  340. fee,
  341. fee_usd,
  342. nonce
  343. ) VALUES %s;`,
  344. txs[:],
  345. )
  346. }
  347. // GetTxs returns a list of txs from the DB
  348. func (hdb *HistoryDB) GetTxs() ([]*common.Tx, error) {
  349. var txs []*common.Tx
  350. err := meddler.QueryAll(
  351. hdb.db, &txs,
  352. `SELECT * FROM tx
  353. ORDER BY (batch_num, position) ASC`,
  354. )
  355. return txs, err
  356. }
  357. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  358. func (hdb *HistoryDB) GetHistoryTxs(
  359. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  360. tokenID, idx, batchNum *uint, txType *common.TxType,
  361. offset, limit *uint, last bool,
  362. ) ([]*HistoryTx, int, error) {
  363. if ethAddr != nil && bjj != nil {
  364. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  365. }
  366. var query string
  367. var args []interface{}
  368. queryStr := `SELECT tx.*, token.token_id, token.eth_block_num AS token_block,
  369. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  370. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  371. FROM tx
  372. INNER JOIN token ON tx.token_id = token.token_id
  373. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  374. // Apply filters
  375. nextIsAnd := false
  376. // ethAddr filter
  377. if ethAddr != nil {
  378. queryStr = `WITH acc AS
  379. (select idx from account where eth_addr = ?) ` + queryStr
  380. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  381. nextIsAnd = true
  382. args = append(args, ethAddr)
  383. } else if bjj != nil { // bjj filter
  384. queryStr = `WITH acc AS
  385. (select idx from account where bjj = ?) ` + queryStr
  386. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  387. nextIsAnd = true
  388. args = append(args, bjj)
  389. }
  390. // tokenID filter
  391. if tokenID != nil {
  392. if nextIsAnd {
  393. queryStr += "AND "
  394. } else {
  395. queryStr += "WHERE "
  396. }
  397. queryStr += "tx.token_id = ? "
  398. args = append(args, tokenID)
  399. nextIsAnd = true
  400. }
  401. // idx filter
  402. if idx != nil {
  403. if nextIsAnd {
  404. queryStr += "AND "
  405. } else {
  406. queryStr += "WHERE "
  407. }
  408. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  409. args = append(args, idx, idx)
  410. nextIsAnd = true
  411. }
  412. // batchNum filter
  413. if batchNum != nil {
  414. if nextIsAnd {
  415. queryStr += "AND "
  416. } else {
  417. queryStr += "WHERE "
  418. }
  419. queryStr += "tx.batch_num = ? "
  420. args = append(args, batchNum)
  421. nextIsAnd = true
  422. }
  423. // txType filter
  424. if txType != nil {
  425. if nextIsAnd {
  426. queryStr += "AND "
  427. } else {
  428. queryStr += "WHERE "
  429. }
  430. queryStr += "tx.type = ? "
  431. args = append(args, txType)
  432. // nextIsAnd = true
  433. }
  434. // pagination
  435. if last {
  436. queryStr += "ORDER BY (batch_num, position) DESC NULLS FIRST "
  437. } else {
  438. queryStr += "ORDER BY (batch_num, position) ASC NULLS LAST "
  439. queryStr += fmt.Sprintf("OFFSET %d ", *offset)
  440. }
  441. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  442. query = hdb.db.Rebind(queryStr)
  443. // log.Debug(query)
  444. txs := []*HistoryTx{}
  445. if err := meddler.QueryAll(hdb.db, &txs, query, args...); err != nil {
  446. return nil, 0, err
  447. }
  448. if len(txs) == 0 {
  449. return nil, 0, sql.ErrNoRows
  450. } else if last {
  451. tmp := []*HistoryTx{}
  452. for i := len(txs) - 1; i >= 0; i-- {
  453. tmp = append(tmp, txs[i])
  454. }
  455. txs = tmp
  456. }
  457. return txs, txs[0].TotalItems, nil
  458. }
  459. // GetTx returns a tx from the DB
  460. func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  461. tx := new(common.Tx)
  462. return tx, meddler.QueryRow(
  463. hdb.db, tx,
  464. "SELECT * FROM tx WHERE id = $1;",
  465. txID,
  466. )
  467. }
  468. // // GetL1UserTxs gets L1 User Txs to be forged in a batch that will create an account
  469. // // TODO: This is currently not used. Figure out if it should be used somewhere or removed.
  470. // func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]*common.Tx, error) {
  471. // var txs []*common.Tx
  472. // err := meddler.QueryAll(
  473. // hdb.db, &txs,
  474. // "SELECT * FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;",
  475. // toForgeL1TxsNum,
  476. // )
  477. // return txs, err
  478. // }
  479. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  480. // GetLastTxsPosition for a given to_forge_l1_txs_num
  481. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  482. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  483. var lastL1TxsPosition int
  484. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  485. }
  486. // AddBlockSCData stores all the information of a block retrieved by the Synchronizer
  487. func (hdb *HistoryDB) AddBlockSCData(blockData *BlockData) (err error) {
  488. txn, err := hdb.db.Begin()
  489. if err != nil {
  490. return err
  491. }
  492. defer func() {
  493. if err != nil {
  494. err = txn.Rollback()
  495. }
  496. }()
  497. // Add block
  498. err = hdb.addBlock(txn, blockData.block)
  499. if err != nil {
  500. return err
  501. }
  502. // Add l1 Txs
  503. if len(blockData.L1UserTxs) > 0 {
  504. err = hdb.addL1Txs(txn, blockData.L1UserTxs)
  505. if err != nil {
  506. return err
  507. }
  508. }
  509. // Add Tokens
  510. if len(blockData.RegisteredTokens) > 0 {
  511. err = hdb.addTokens(txn, blockData.RegisteredTokens)
  512. if err != nil {
  513. return err
  514. }
  515. }
  516. // Add Bids
  517. if len(blockData.Bids) > 0 {
  518. err = hdb.addBids(txn, blockData.Bids)
  519. if err != nil {
  520. return err
  521. }
  522. }
  523. // Add Coordinators
  524. if len(blockData.Coordinators) > 0 {
  525. err = hdb.addCoordinators(txn, blockData.Coordinators)
  526. if err != nil {
  527. return err
  528. }
  529. }
  530. // Add Batches
  531. for _, batch := range blockData.Batches {
  532. // Add Batch: this will trigger an update on the DB
  533. // that will set the batch num of forged L1 txs in this batch
  534. err = hdb.addBatch(txn, batch.Batch)
  535. if err != nil {
  536. return err
  537. }
  538. // Add unforged l1 Txs
  539. if batch.L1Batch {
  540. if len(batch.L1CoordinatorTxs) > 0 {
  541. err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
  542. if err != nil {
  543. return err
  544. }
  545. }
  546. }
  547. // Add l2 Txs
  548. if len(batch.L2Txs) > 0 {
  549. err = hdb.addL2Txs(txn, batch.L2Txs)
  550. if err != nil {
  551. return err
  552. }
  553. }
  554. // Add accounts
  555. if len(batch.CreatedAccounts) > 0 {
  556. err = hdb.addAccounts(txn, batch.CreatedAccounts)
  557. if err != nil {
  558. return err
  559. }
  560. }
  561. // Add exit tree
  562. if len(batch.ExitTree) > 0 {
  563. err = hdb.addExitTree(txn, batch.ExitTree)
  564. if err != nil {
  565. return err
  566. }
  567. }
  568. // TODO: INSERT CONTRACTS VARS
  569. }
  570. return txn.Commit()
  571. }