Explorar o código

drk: keep last scanned block hash along with its height

skoupidi hai 1 ano
pai
achega
fae10e8657
Modificáronse 4 ficheiros con 35 adicións e 26 borrados
  1. 25 19
      bin/drk/src/lib.rs
  2. 1 1
      bin/drk/src/main.rs
  3. 7 5
      bin/drk/src/rpc.rs
  4. 2 1
      bin/drk/wallet.sql

+ 25 - 19
bin/drk/src/lib.rs

@@ -61,7 +61,8 @@ use walletdb::{WalletDb, WalletPtr};
 // Wallet SQL table constant names. These have to represent the `wallet.sql`
 // SQL schema.
 const WALLET_INFO_TABLE: &str = "wallet_info";
-const WALLET_INFO_COL_LAST_SCANNED_BLOCK: &str = "last_scanned_block";
+const WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT: &str = "last_scanned_block_height";
+const WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH: &str = "last_scanned_block_hash";
 
 /// CLI-util structure
 pub struct Drk {
@@ -103,39 +104,40 @@ impl Drk {
     }
 
     /// Initialize wallet with tables for `Drk`.
-    pub fn initialize_wallet(&self) -> WalletDbResult<()> {
+    pub async fn initialize_wallet(&self) -> WalletDbResult<()> {
         // Initialize wallet schema
         self.wallet.exec_batch_sql(include_str!("../wallet.sql"))?;
 
         // We maintain the last scanned block as part of the wallet
         // info table.
-        if self.last_scanned_block().is_err() {
+        if self.last_scanned_block().await.is_err() {
             let query = format!(
-                "INSERT INTO {} ({}) VALUES (?1);",
-                WALLET_INFO_TABLE, WALLET_INFO_COL_LAST_SCANNED_BLOCK
+                "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
+                WALLET_INFO_TABLE,
+                WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT,
+                WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH
             );
-            self.wallet.exec_sql(&query, rusqlite::params![0])?;
+            self.wallet.exec_sql(&query, rusqlite::params![0, "-"])?;
         }
 
         Ok(())
     }
 
-    /// Update the last scanned block height in the wallet.
-    pub fn update_last_scanned_block(&self, height: u32) -> WalletDbResult<()> {
+    /// Update the last scanned block height and hash in the wallet.
+    pub fn update_last_scanned_block(&self, height: u32, hash: &str) -> WalletDbResult<()> {
         let query = format!(
-            "UPDATE {} SET {} = ?1;",
-            WALLET_INFO_TABLE, WALLET_INFO_COL_LAST_SCANNED_BLOCK
+            "UPDATE {} SET {} = ?1, {} = ?2;",
+            WALLET_INFO_TABLE,
+            WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT,
+            WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH
         );
-        self.wallet.exec_sql(&query, rusqlite::params![height])
+        self.wallet.exec_sql(&query, rusqlite::params![height, hash])
     }
 
-    /// Get the last scanned block height from the wallet.
-    pub fn last_scanned_block(&self) -> WalletDbResult<u32> {
-        let ret = self.wallet.query_single(
-            WALLET_INFO_TABLE,
-            &[WALLET_INFO_COL_LAST_SCANNED_BLOCK],
-            &[],
-        )?;
+    /// Get the last scanned block height and hash from the wallet.
+    pub async fn last_scanned_block(&self) -> WalletDbResult<(u32, String)> {
+        let ret = self.wallet.query_single(WALLET_INFO_TABLE, &[], &[])?;
+
         let Value::Integer(height) = ret[0] else {
             return Err(WalletDbError::ParseColumnValueError);
         };
@@ -143,6 +145,10 @@ impl Drk {
             return Err(WalletDbError::ParseColumnValueError);
         };
 
-        Ok(height)
+        let Value::Text(ref hash) = ret[1] else {
+            return Err(WalletDbError::ParseColumnValueError);
+        };
+
+        Ok((height, hash.clone()))
     }
 }

+ 1 - 1
bin/drk/src/main.rs

@@ -671,7 +671,7 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
             .await;
 
             if initialize {
-                if let Err(e) = drk.initialize_wallet() {
+                if let Err(e) = drk.initialize_wallet().await {
                     eprintln!("Error initializing wallet: {e:?}");
                     exit(2);
                 }

+ 7 - 5
bin/drk/src/rpc.rs

@@ -74,8 +74,8 @@ impl Drk {
             .darkfid_daemon_request("blockchain.last_known_block", &JsonValue::Array(vec![]))
             .await?;
         last_known = *rep.get::<f64>().unwrap() as u32;
-        let last_scanned = match self.last_scanned_block() {
-            Ok(l) => l,
+        let last_scanned = match self.last_scanned_block().await {
+            Ok((l, _)) => l,
             Err(e) => {
                 return Err(Error::DatabaseError(format!(
                     "[subscribe_blocks] Retrieving last scanned block failed: {e:?}"
@@ -83,7 +83,7 @@ impl Drk {
             }
         };
 
-        // when no other block has been created.
+        // When no other block has been created
         if last_known != last_scanned {
             eprintln!("Warning: Last scanned block is not the last known block.");
             eprintln!("You should first fully scan the blockchain, and then subscribe");
@@ -244,7 +244,9 @@ impl Drk {
         }
 
         // Write this block height into `last_scanned_block`
-        if let Err(e) = self.update_last_scanned_block(block.header.height) {
+        if let Err(e) =
+            self.update_last_scanned_block(block.header.height, &block.hash().to_string())
+        {
             return Err(Error::DatabaseError(format!(
                 "[scan_block] Update last scanned block failed: {e:?}"
             )))
@@ -259,7 +261,7 @@ impl Drk {
     /// it looks for a checkpoint in the wallet to reset and start scanning from.
     pub async fn scan_blocks(&self, reset: bool) -> WalletDbResult<()> {
         // Grab last scanned block height
-        let mut height = self.last_scanned_block()?;
+        let (mut height, _) = self.last_scanned_block().await?;
         // If last scanned block is genesis (0) or reset flag
         // has been provided we reset, otherwise continue with
         // the next block height

+ 2 - 1
bin/drk/wallet.sql

@@ -5,7 +5,8 @@ PRAGMA foreign_keys = ON;
 
 -- Arbitrary info that is potentially useful
 CREATE TABLE IF NOT EXISTS wallet_info (
-	last_scanned_block INTEGER NOT NULL
+	last_scanned_block_height INTEGER NOT NULL,
+	last_scanned_block_hash TEXT NOT NULL
 );
 
 -- Transactions history