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.

609 lines
16 KiB

4 years ago
  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(tokenID common.TokenID, value float64) error {
  235. _, err := hdb.db.Exec(
  236. "UPDATE token SET usd = $1 WHERE token_id = $2;",
  237. value, tokenID,
  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. // AddAccounts insert accounts into the DB
  251. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  252. return hdb.addAccounts(hdb.db, accounts)
  253. }
  254. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  255. return db.BulkInsert(
  256. d,
  257. `INSERT INTO account (
  258. idx,
  259. token_id,
  260. batch_num,
  261. bjj,
  262. eth_addr
  263. ) VALUES %s;`,
  264. accounts[:],
  265. )
  266. }
  267. // GetAccounts returns a list of accounts from the DB
  268. func (hdb *HistoryDB) GetAccounts() ([]*common.Account, error) {
  269. var accs []*common.Account
  270. err := meddler.QueryAll(
  271. hdb.db, &accs,
  272. "SELECT * FROM account ORDER BY idx;",
  273. )
  274. return accs, err
  275. }
  276. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  277. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  278. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  279. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  280. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  281. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  282. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  283. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  284. txs := []common.Tx{}
  285. for _, tx := range l1txs {
  286. txs = append(txs, *(tx.Tx()))
  287. }
  288. return hdb.addTxs(d, txs)
  289. }
  290. // AddL2Txs inserts L2 txs to the DB. USD and FeeUSD will be set automatically before storing the tx.
  291. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  292. // addL2Txs inserts L2 txs to the DB. USD and FeeUSD will be set automatically before storing the tx.
  293. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  294. txs := []common.Tx{}
  295. for _, tx := range l2txs {
  296. txs = append(txs, *(tx.Tx()))
  297. }
  298. return hdb.addTxs(d, txs)
  299. }
  300. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []common.Tx) error {
  301. return db.BulkInsert(
  302. d,
  303. `INSERT INTO tx (
  304. is_l1,
  305. id,
  306. type,
  307. position,
  308. from_idx,
  309. to_idx,
  310. amount,
  311. amount_f,
  312. token_id,
  313. amount_usd,
  314. batch_num,
  315. eth_block_num,
  316. to_forge_l1_txs_num,
  317. user_origin,
  318. from_eth_addr,
  319. from_bjj,
  320. load_amount,
  321. load_amount_f,
  322. load_amount_usd,
  323. fee,
  324. fee_usd,
  325. nonce
  326. ) VALUES %s;`,
  327. txs[:],
  328. )
  329. }
  330. // GetTxs returns a list of txs from the DB
  331. func (hdb *HistoryDB) GetTxs() ([]*common.Tx, error) {
  332. var txs []*common.Tx
  333. err := meddler.QueryAll(
  334. hdb.db, &txs,
  335. `SELECT * FROM tx
  336. ORDER BY (batch_num, position) ASC`,
  337. )
  338. return txs, err
  339. }
  340. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  341. func (hdb *HistoryDB) GetHistoryTxs(
  342. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  343. tokenID, idx, batchNum *uint, txType *common.TxType,
  344. offset, limit *uint, last bool,
  345. ) ([]*HistoryTx, int, error) {
  346. if ethAddr != nil && bjj != nil {
  347. return nil, 0, errors.New("ethAddr and bjj are incompatible")
  348. }
  349. var query string
  350. var args []interface{}
  351. queryStr := `SELECT tx.*, token.token_id, token.eth_block_num AS token_block,
  352. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  353. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  354. FROM tx
  355. INNER JOIN token ON tx.token_id = token.token_id
  356. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  357. // Apply filters
  358. nextIsAnd := false
  359. // ethAddr filter
  360. if ethAddr != nil {
  361. queryStr = `WITH acc AS
  362. (select idx from account where eth_addr = ?) ` + queryStr
  363. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  364. nextIsAnd = true
  365. args = append(args, ethAddr)
  366. } else if bjj != nil { // bjj filter
  367. queryStr = `WITH acc AS
  368. (select idx from account where bjj = ?) ` + queryStr
  369. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  370. nextIsAnd = true
  371. args = append(args, bjj)
  372. }
  373. // tokenID filter
  374. if tokenID != nil {
  375. if nextIsAnd {
  376. queryStr += "AND "
  377. } else {
  378. queryStr += "WHERE "
  379. }
  380. queryStr += "tx.token_id = ? "
  381. args = append(args, tokenID)
  382. nextIsAnd = true
  383. }
  384. // idx filter
  385. if idx != nil {
  386. if nextIsAnd {
  387. queryStr += "AND "
  388. } else {
  389. queryStr += "WHERE "
  390. }
  391. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  392. args = append(args, idx, idx)
  393. nextIsAnd = true
  394. }
  395. // batchNum filter
  396. if batchNum != nil {
  397. if nextIsAnd {
  398. queryStr += "AND "
  399. } else {
  400. queryStr += "WHERE "
  401. }
  402. queryStr += "tx.batch_num = ? "
  403. args = append(args, batchNum)
  404. nextIsAnd = true
  405. }
  406. // txType filter
  407. if txType != nil {
  408. if nextIsAnd {
  409. queryStr += "AND "
  410. } else {
  411. queryStr += "WHERE "
  412. }
  413. queryStr += "tx.type = ? "
  414. args = append(args, txType)
  415. // nextIsAnd = true
  416. }
  417. // pagination
  418. if last {
  419. queryStr += "ORDER BY (batch_num, position) DESC NULLS FIRST "
  420. } else {
  421. queryStr += "ORDER BY (batch_num, position) ASC NULLS LAST "
  422. queryStr += fmt.Sprintf("OFFSET %d ", *offset)
  423. }
  424. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  425. query = hdb.db.Rebind(queryStr)
  426. // log.Debug(query)
  427. txs := []*HistoryTx{}
  428. if err := meddler.QueryAll(hdb.db, &txs, query, args...); err != nil {
  429. return nil, 0, err
  430. }
  431. if len(txs) == 0 {
  432. return nil, 0, sql.ErrNoRows
  433. } else if last {
  434. tmp := []*HistoryTx{}
  435. for i := len(txs) - 1; i >= 0; i-- {
  436. tmp = append(tmp, txs[i])
  437. }
  438. txs = tmp
  439. }
  440. return txs, txs[0].TotalItems, nil
  441. }
  442. // GetTx returns a tx from the DB
  443. func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  444. tx := new(common.Tx)
  445. return tx, meddler.QueryRow(
  446. hdb.db, tx,
  447. "SELECT * FROM tx WHERE id = $1;",
  448. txID,
  449. )
  450. }
  451. // // GetL1UserTxs gets L1 User Txs to be forged in a batch that will create an account
  452. // // TODO: This is currently not used. Figure out if it should be used somewhere or removed.
  453. // func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]*common.Tx, error) {
  454. // var txs []*common.Tx
  455. // err := meddler.QueryAll(
  456. // hdb.db, &txs,
  457. // "SELECT * FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;",
  458. // toForgeL1TxsNum,
  459. // )
  460. // return txs, err
  461. // }
  462. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  463. // GetLastTxsPosition for a given to_forge_l1_txs_num
  464. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  465. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  466. var lastL1TxsPosition int
  467. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  468. }
  469. // AddBlockSCData stores all the information of a block retrieved by the Synchronizer
  470. func (hdb *HistoryDB) AddBlockSCData(blockData *BlockData) (err error) {
  471. txn, err := hdb.db.Begin()
  472. if err != nil {
  473. return err
  474. }
  475. defer func() {
  476. if err != nil {
  477. err = txn.Rollback()
  478. }
  479. }()
  480. // Add block
  481. err = hdb.addBlock(txn, blockData.block)
  482. if err != nil {
  483. return err
  484. }
  485. // Add l1 Txs
  486. if len(blockData.L1UserTxs) > 0 {
  487. err = hdb.addL1Txs(txn, blockData.L1UserTxs)
  488. if err != nil {
  489. return err
  490. }
  491. }
  492. // Add Tokens
  493. if len(blockData.RegisteredTokens) > 0 {
  494. err = hdb.addTokens(txn, blockData.RegisteredTokens)
  495. if err != nil {
  496. return err
  497. }
  498. }
  499. // Add Bids
  500. if len(blockData.Bids) > 0 {
  501. err = hdb.addBids(txn, blockData.Bids)
  502. if err != nil {
  503. return err
  504. }
  505. }
  506. // Add Coordinators
  507. if len(blockData.Coordinators) > 0 {
  508. err = hdb.addCoordinators(txn, blockData.Coordinators)
  509. if err != nil {
  510. return err
  511. }
  512. }
  513. // Add Batches
  514. for _, batch := range blockData.Batches {
  515. // Add Batch: this will trigger an update on the DB
  516. // that will set the batch num of forged L1 txs in this batch
  517. err = hdb.addBatch(txn, batch.Batch)
  518. if err != nil {
  519. return err
  520. }
  521. // Add unforged l1 Txs
  522. if batch.L1Batch {
  523. if len(batch.L1CoordinatorTxs) > 0 {
  524. err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
  525. if err != nil {
  526. return err
  527. }
  528. }
  529. }
  530. // Add l2 Txs
  531. if len(batch.L2Txs) > 0 {
  532. err = hdb.addL2Txs(txn, batch.L2Txs)
  533. if err != nil {
  534. return err
  535. }
  536. }
  537. // Add accounts
  538. if len(batch.CreatedAccounts) > 0 {
  539. err = hdb.addAccounts(txn, batch.CreatedAccounts)
  540. if err != nil {
  541. return err
  542. }
  543. }
  544. // Add exit tree
  545. if len(batch.ExitTree) > 0 {
  546. err = hdb.addExitTree(txn, batch.ExitTree)
  547. if err != nil {
  548. return err
  549. }
  550. }
  551. // TODO: INSERT CONTRACTS VARS
  552. }
  553. return txn.Commit()
  554. }