Преглед изворни кода

drk: drop wallet info table and retrieve last scanned block from the corresponding scanned blocks table

skoupidi пре 1 година
родитељ
комит
26ff0a55cd
4 измењених фајлова са 37 додато и 66 уклоњено
  1. 0 48
      bin/drk/src/lib.rs
  2. 2 11
      bin/drk/src/rpc.rs
  3. 35 1
      bin/drk/src/scanned_blocks.rs
  4. 0 6
      bin/drk/wallet.sql

+ 0 - 48
bin/drk/src/lib.rs

@@ -18,7 +18,6 @@
 
 use std::{fs, sync::Arc};
 
-use rusqlite::types::Value;
 use url::Url;
 
 use darkfi::{rpc::client::RpcClient, util::path::expand_path, Error, Result};
@@ -61,12 +60,6 @@ pub mod scanned_blocks;
 pub mod walletdb;
 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_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 {
     /// Wallet database operations handler
@@ -111,50 +104,9 @@ impl Drk {
         // 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().await.is_err() {
-            let query = format!(
-                "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, "-"])?;
-        }
-
         Ok(())
     }
 
-    /// 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, {} = ?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, hash])
-    }
-
-    /// 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);
-        };
-        let Ok(height) = u32::try_from(height) else {
-            return Err(WalletDbError::ParseColumnValueError);
-        };
-
-        let Value::Text(ref hash) = ret[1] else {
-            return Err(WalletDbError::ParseColumnValueError);
-        };
-
-        Ok((height, hash.clone()))
-    }
-
     /// Auxiliary function to reset `walletdb` inverse cache state.
     /// Additionally, set current trees state inverse queries.
     /// We keep the entire trees state as two distinct inverse queries,

+ 2 - 11
bin/drk/src/rpc.rs

@@ -74,7 +74,7 @@ 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().await {
+        let last_scanned = match self.get_last_scanned_block() {
             Ok((l, _)) => l,
             Err(e) => {
                 return Err(Error::DatabaseError(format!(
@@ -249,15 +249,6 @@ impl Drk {
         // Store this block rollback query
         self.store_inverse_cache(block.header.height, &block.hash().to_string())?;
 
-        // Write this block height into `last_scanned_block`
-        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:?}"
-            )))
-        }
-
         Ok(())
     }
 
@@ -267,7 +258,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().await?;
+        let (mut height, _) = self.get_last_scanned_block()?;
         // If last scanned block is genesis (0) or reset flag
         // has been provided we reset, otherwise continue with
         // the next block height

+ 35 - 1
bin/drk/src/scanned_blocks.rs

@@ -20,7 +20,11 @@ use rusqlite::types::Value;
 
 use darkfi::{Error, Result};
 
-use crate::{convert_named_params, error::WalletDbResult, Drk};
+use crate::{
+    convert_named_params,
+    error::{WalletDbError, WalletDbResult},
+    Drk,
+};
 
 // Wallet SQL table constant names. These have to represent the `wallet.sql`
 // SQL schema.
@@ -82,6 +86,36 @@ impl Drk {
         Ok((height, hash.clone(), rollback_query.clone()))
     }
 
+    /// Get the last scanned block height and hash from the wallet.
+    /// If database is empty default (0, '-') is returned.
+    pub fn get_last_scanned_block(&self) -> WalletDbResult<(u32, String)> {
+        let query = format!(
+            "SELECT {}, {} FROM {} ORDER BY {} DESC LIMIT 1;",
+            WALLET_SCANNED_BLOCKS_COL_HEIGH,
+            WALLET_SCANNED_BLOCKS_COL_HASH,
+            WALLET_SCANNED_BLOCKS_TABLE,
+            WALLET_SCANNED_BLOCKS_COL_HEIGH,
+        );
+        let ret = self.wallet.query_custom(&query, &[])?;
+
+        if ret.is_empty() {
+            return Ok((0, String::from("-")))
+        }
+
+        let Value::Integer(height) = ret[0][0] else {
+            return Err(WalletDbError::ParseColumnValueError);
+        };
+        let Ok(height) = u32::try_from(height) else {
+            return Err(WalletDbError::ParseColumnValueError);
+        };
+
+        let Value::Text(ref hash) = ret[0][1] else {
+            return Err(WalletDbError::ParseColumnValueError);
+        };
+
+        Ok((height, hash.clone()))
+    }
+
     /// Reset the scanned blocks information records in the wallet.
     pub fn reset_scanned_blocks(&self) -> WalletDbResult<()> {
         println!("Resetting scanned blocks");

+ 0 - 6
bin/drk/wallet.sql

@@ -3,12 +3,6 @@
 
 PRAGMA foreign_keys = ON;
 
--- Arbitrary info that is potentially useful
-CREATE TABLE IF NOT EXISTS wallet_info (
-	last_scanned_block_height INTEGER NOT NULL,
-	last_scanned_block_hash TEXT NOT NULL
-);
-
 -- Scanned blocks information
 CREATE TABLE IF NOT EXISTS scanned_blocks (
 	height INTEGER PRIMARY KEY NOT NULL,