scanned_blocks.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use rusqlite::types::Value;
  19. use crate::{
  20. convert_named_params,
  21. error::{WalletDbError, WalletDbResult},
  22. Drk,
  23. };
  24. // Wallet SQL table constant names. These have to represent the `wallet.sql`
  25. // SQL schema.
  26. const WALLET_SCANNED_BLOCKS_TABLE: &str = "scanned_blocks";
  27. const WALLET_SCANNED_BLOCKS_COL_HEIGH: &str = "height";
  28. const WALLET_SCANNED_BLOCKS_COL_HASH: &str = "hash";
  29. const WALLET_SCANNED_BLOCKS_COL_ROLLBACK_QUERY: &str = "rollback_query";
  30. impl Drk {
  31. /// Insert a scanned block information record into the wallet.
  32. pub fn put_scanned_block_record(
  33. &self,
  34. height: u32,
  35. hash: &str,
  36. rollback_query: &str,
  37. ) -> WalletDbResult<()> {
  38. let query = format!(
  39. "INSERT INTO {WALLET_SCANNED_BLOCKS_TABLE} ({WALLET_SCANNED_BLOCKS_COL_HEIGH}, {WALLET_SCANNED_BLOCKS_COL_HASH}, {WALLET_SCANNED_BLOCKS_COL_ROLLBACK_QUERY}) VALUES (?1, ?2, ?3);"
  40. );
  41. self.wallet.exec_sql(&query, rusqlite::params![height, hash, rollback_query])
  42. }
  43. /// Auxiliary function to parse a `WALLET_SCANNED_BLOCKS_TABLE` records.
  44. fn parse_scanned_block_record(&self, row: &[Value]) -> WalletDbResult<(u32, String, String)> {
  45. let Value::Integer(height) = row[0] else {
  46. return Err(WalletDbError::ParseColumnValueError);
  47. };
  48. let Ok(height) = u32::try_from(height) else {
  49. return Err(WalletDbError::ParseColumnValueError);
  50. };
  51. let Value::Text(ref hash) = row[1] else {
  52. return Err(WalletDbError::ParseColumnValueError);
  53. };
  54. let Value::Text(ref rollback_query) = row[2] else {
  55. return Err(WalletDbError::ParseColumnValueError);
  56. };
  57. Ok((height, hash.clone(), rollback_query.clone()))
  58. }
  59. /// Get a scanned block information record.
  60. pub fn get_scanned_block_record(&self, height: u32) -> WalletDbResult<(u32, String, String)> {
  61. let row = self.wallet.query_single(
  62. WALLET_SCANNED_BLOCKS_TABLE,
  63. &[],
  64. convert_named_params! {(WALLET_SCANNED_BLOCKS_COL_HEIGH, height)},
  65. )?;
  66. self.parse_scanned_block_record(&row)
  67. }
  68. /// Fetch all scanned block information record.
  69. pub fn get_scanned_block_records(&self) -> WalletDbResult<Vec<(u32, String, String)>> {
  70. let rows = self.wallet.query_multiple(WALLET_SCANNED_BLOCKS_TABLE, &[], &[])?;
  71. let mut ret = Vec::with_capacity(rows.len());
  72. for row in rows {
  73. ret.push(self.parse_scanned_block_record(&row)?);
  74. }
  75. Ok(ret)
  76. }
  77. /// Get the last scanned block height and hash from the wallet.
  78. /// If database is empty default (0, '-') is returned.
  79. pub fn get_last_scanned_block(&self) -> WalletDbResult<(u32, String)> {
  80. let query = format!(
  81. "SELECT * FROM {WALLET_SCANNED_BLOCKS_TABLE} ORDER BY {WALLET_SCANNED_BLOCKS_COL_HEIGH} DESC LIMIT 1;"
  82. );
  83. let ret = self.wallet.query_custom(&query, &[])?;
  84. if ret.is_empty() {
  85. return Ok((0, String::from("-")))
  86. }
  87. let (height, hash, _) = self.parse_scanned_block_record(&ret[0])?;
  88. Ok((height, hash))
  89. }
  90. /// Reset the scanned blocks information records in the wallet.
  91. pub fn reset_scanned_blocks(&self) -> WalletDbResult<()> {
  92. println!("Resetting scanned blocks");
  93. let query = format!("DELETE FROM {WALLET_SCANNED_BLOCKS_TABLE};");
  94. self.wallet.exec_sql(&query, &[])?;
  95. println!("Successfully reset scanned blocks");
  96. Ok(())
  97. }
  98. /// Reset state to provided block height.
  99. /// If genesis block height(0) was provided, perform a full reset.
  100. pub async fn reset_to_height(&self, height: u32) -> WalletDbResult<()> {
  101. println!("Resetting wallet state to block: {height}");
  102. // If genesis block height(0) was provided,
  103. // perform a full reset.
  104. if height == 0 {
  105. return self.reset().await
  106. }
  107. // Grab last scanned block height
  108. let (last, _) = self.get_last_scanned_block()?;
  109. // Check if requested height is after it
  110. if last <= height {
  111. println!("Requested block height is greater or equal to last scanned block");
  112. return Ok(())
  113. }
  114. // Iterate the range (height, last] in reverse to grab the corresponding blocks
  115. for height in (height + 1..=last).rev() {
  116. let (height, hash, query) = self.get_scanned_block_record(height)?;
  117. println!("Reverting block: {height} - {hash}");
  118. self.wallet.exec_batch_sql(&query)?;
  119. let query = format!("DELETE FROM {WALLET_SCANNED_BLOCKS_TABLE} WHERE {WALLET_SCANNED_BLOCKS_COL_HEIGH} = {height};");
  120. self.wallet.exec_batch_sql(&query)?;
  121. }
  122. println!("Successfully reset wallet state");
  123. Ok(())
  124. }
  125. }