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

drk: removed inverse query functionality

skoupidi пре 1 година
родитељ
комит
d5d831ab57
6 измењених фајлова са 26 додато и 275 уклоњено
  1. 22 108
      bin/drk/src/dao.rs
  2. 0 12
      bin/drk/src/lib.rs
  3. 1 79
      bin/drk/src/money.rs
  4. 1 5
      bin/drk/src/rpc.rs
  5. 1 13
      bin/drk/src/txs_history.rs
  6. 1 58
      bin/drk/src/walletdb.rs

+ 22 - 108
bin/drk/src/dao.rs

@@ -1104,9 +1104,10 @@ impl Drk {
         Ok(proposals)
     }
 
-    /// Auxiliary function to apply `DaoFunction::Mint` call data to the wallet,
-    /// and store its inverse query into the cache.
-    /// Returns a flag indicating if the provided call refers to our own wallet.
+    /// Auxiliary function to apply `DaoFunction::Mint` call data to
+    /// the wallet and update the provided scan cache.
+    /// Returns a flag indicating if the provided call refers to our
+    /// own wallet.
     async fn apply_dao_mint_data(
         &self,
         scan_cache: &mut ScanCache,
@@ -1139,9 +1140,10 @@ impl Drk {
         Ok(true)
     }
 
-    /// Auxiliary function to apply `DaoFunction::Propose` call data to the wallet,
-    /// and store its inverse query into the cache.
-    /// Returns a flag indicating if the provided call refers to our own wallet.
+    /// Auxiliary function to apply `DaoFunction::Propose` call data to
+    /// the wallet and update the provided scan cache.
+    /// Returns a flag indicating if the provided call refers to our
+    /// own wallet.
     async fn apply_dao_propose_data(
         &self,
         scan_cache: &mut ScanCache,
@@ -1206,9 +1208,10 @@ impl Drk {
         Ok(false)
     }
 
-    /// Auxiliary function to apply `DaoFunction::Vote` call data to the wallet,
-    /// and store its inverse query into the cache.
-    /// Returns a flag indicating if the provided call refers to our own wallet.
+    /// Auxiliary function to apply `DaoFunction::Vote` call data to
+    /// the wallet.
+    /// Returns a flag indicating if the provided call refers to our
+    /// own wallet.
     async fn apply_dao_vote_data(
         &self,
         scan_cache: &ScanCache,
@@ -1277,9 +1280,10 @@ impl Drk {
         Ok(true)
     }
 
-    /// Auxiliary function to apply `DaoFunction::Exec` call data to the wallet,
-    /// and store its inverse query into the cache.
-    /// Returns a flag indicating if the provided call refers to our own wallet.
+    /// Auxiliary function to apply `DaoFunction::Exec` call data to
+    /// the wallet and update the provided scan cache.
+    /// Returns a flag indicating if the provided call refers to our
+    /// own wallet.
     async fn apply_dao_exec_data(
         &self,
         scan_cache: &ScanCache,
@@ -1300,22 +1304,6 @@ impl Drk {
             *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
         );
 
-        // Create its inverse query
-        let inverse = match self.wallet.create_prepared_statement(
-            &format!(
-                "UPDATE {} SET {} = NULL WHERE {} = ?1;",
-                *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
-            ),
-            rusqlite::params![key],
-        ) {
-            Ok(q) => q,
-            Err(e) => {
-                return Err(Error::DatabaseError(format!(
-                    "[apply_dao_exec_data] Creating DAO proposal update inverse query failed: {e:?}"
-                )))
-            }
-        };
-
         // Execute the query
         if let Err(e) = self
             .wallet
@@ -1326,18 +1314,11 @@ impl Drk {
             )))
         }
 
-        // Store its inverse
-        if let Err(e) = self.wallet.cache_inverse(inverse) {
-            return Err(Error::DatabaseError(format!(
-                "[apply_dao_exec_data] Inserting inverse query into cache failed: {e:?}"
-            )))
-        }
-
         Ok(true)
     }
 
-    /// Append data related to DAO contract transactions into the wallet database,
-    /// and store their inverse queries into the cache.
+    /// Append data related to DAO contract transactions into the
+    /// wallet database and update the provided scan cache.
     /// Returns a flag indicating if the daos tree should be updated,
     /// one indicating if the proposals tree should be updated and
     /// another one indicating if provided data refer to our own
@@ -1387,8 +1368,7 @@ impl Drk {
         }
     }
 
-    /// Confirm already imported DAO metadata into the wallet,
-    /// and store its inverse query into the cache.
+    /// Confirm already imported DAO metadata into the wallet.
     /// Here we just write the leaf position, tx hash, and call index.
     /// Panics if the fields are None.
     pub async fn confirm_dao(
@@ -1419,27 +1399,11 @@ impl Drk {
             key,
         ];
 
-        // Create its inverse query
-        let inverse_query = format!(
-            "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
-            *DAO_DAOS_TABLE,
-            DAO_DAOS_COL_LEAF_POSITION,
-            DAO_DAOS_COL_TX_HASH,
-            DAO_DAOS_COL_CALL_INDEX,
-            DAO_DAOS_COL_BULLA
-        );
-        let inverse =
-            self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key])?;
-
         // Execute the query
-        self.wallet.exec_sql(&query, params)?;
-
-        // Store its inverse
-        self.wallet.cache_inverse(inverse)
+        self.wallet.exec_sql(&query, params)
     }
 
-    /// Import given DAO proposal into the wallet,
-    /// and store its inverse query into the cache.
+    /// Import given DAO proposal into the wallet.
     pub async fn put_dao_proposal(&self, proposal: &ProposalRecord) -> Result<()> {
         // Check that we already have the proposal DAO
         if let Err(e) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
@@ -1513,40 +1477,11 @@ impl Drk {
             exec_tx_hash,
         ];
 
-        // Create its inverse query
-        let inverse_query = format!(
-            "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
-            *DAO_PROPOSALS_TABLE,
-            DAO_PROPOSALS_COL_LEAF_POSITION,
-            DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
-            DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
-            DAO_PROPOSALS_COL_TX_HASH,
-            DAO_PROPOSALS_COL_CALL_INDEX,
-            DAO_PROPOSALS_COL_EXEC_TX_HASH,
-            DAO_PROPOSALS_COL_BULLA
-        );
-        let inverse =
-            match self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key]) {
-                Ok(q) => q,
-                Err(e) => {
-                    return Err(Error::DatabaseError(format!(
-                    "[put_dao_proposal] Creating DAO proposal insert inverse query failed: {e:?}"
-                )))
-                }
-            };
-
         // Execute the query
         if let Err(e) = self.wallet.exec_sql(&query, params) {
             return Err(Error::DatabaseError(format!(
                 "[put_dao_proposal] Proposal insert failed: {e:?}"
             )))
-        };
-
-        // Store its inverse
-        if let Err(e) = self.wallet.cache_inverse(inverse) {
-            return Err(Error::DatabaseError(format!(
-                "[put_dao_proposal] Inserting inverse query into cache failed: {e:?}"
-            )))
         }
 
         Ok(())
@@ -1573,8 +1508,7 @@ impl Drk {
         Ok(())
     }
 
-    /// Import given DAO vote into the wallet,
-    /// and store its inverse query into the cache.
+    /// Import given DAO vote into the wallet.
     pub async fn put_dao_vote(&self, vote: &VoteRecord) -> WalletDbResult<()> {
         println!("Importing DAO vote into wallet");
 
@@ -1604,29 +1538,9 @@ impl Drk {
             serialize_async(&vote.nullifiers).await,
         ];
 
-        // Create its inverse query.
-        // Since we don't know the record ID we will remove it
-        // using all its fields.
-        let inverse_query = format!(
-            "DELETE FROM {} WHERE {} = ?1 AND {} = ?2 AND {} = ?3 AND {} = ?4 AND {} = ?5 AND {} = ?6 AND {} = ?7 AND {} = ?8;",
-            *DAO_VOTES_TABLE,
-            DAO_VOTES_COL_PROPOSAL_BULLA,
-            DAO_VOTES_COL_VOTE_OPTION,
-            DAO_VOTES_COL_YES_VOTE_BLIND,
-            DAO_VOTES_COL_ALL_VOTE_VALUE,
-            DAO_VOTES_COL_ALL_VOTE_BLIND,
-            DAO_VOTES_COL_TX_HASH,
-            DAO_VOTES_COL_CALL_INDEX,
-            DAO_VOTES_COL_NULLIFIERS,
-        );
-        let inverse = self.wallet.create_prepared_statement(&inverse_query, params)?;
-
         // Execute the query
         self.wallet.exec_sql(&query, params)?;
 
-        // Store its inverse
-        self.wallet.cache_inverse(inverse)?;
-
         println!("DAO vote added to wallet");
 
         Ok(())

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

@@ -137,16 +137,4 @@ impl Drk {
         println!("Successfully reset full wallet state");
         Ok(())
     }
-
-    /// Auxiliary function to reset `walletdb` inverse cache state.
-    pub async fn reset_inverse_cache(&self) -> Result<()> {
-        // Reset `walletdb` inverse cache
-        if let Err(e) = self.wallet.clear_inverse_cache() {
-            return Err(Error::DatabaseError(format!(
-                "[reset_inverse_cache] Clearing wallet inverse cache failed: {e:?}"
-            )))
-        }
-
-        Ok(())
-    }
 }

+ 1 - 79
bin/drk/src/money.rs

@@ -783,10 +783,6 @@ impl Drk {
             MONEY_COINS_COL_MEMO,
         );
 
-        // This is its inverse query
-        let inverse_query =
-            format!("DELETE FROM {} WHERE {} = ?1;", *MONEY_COINS_TABLE, MONEY_COINS_COL_COIN);
-
         // Handle our own coins
         for coin in coins {
             println!("OwnCoin: {:?}", coin.coin);
@@ -796,18 +792,6 @@ impl Drk {
             // Push to our own coins nullifiers cache
             owncoins_nullifiers.insert(coin.nullifier().to_bytes(), key);
 
-            // Create its inverse query
-            let inverse =
-                match self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key])
-                {
-                    Ok(q) => q,
-                    Err(e) => {
-                        return Err(Error::DatabaseError(format!(
-                    "[handle_money_call_owncoins] Creating Money coin insert inverse query failed: {e:?}"
-                )))
-                    }
-                };
-
             // Execute the query
             let params = rusqlite::params![
                 key,
@@ -829,13 +813,6 @@ impl Drk {
                     "[handle_money_call_owncoins] Inserting Money coin failed: {e:?}"
                 )))
             }
-
-            // Store its inverse
-            if let Err(e) = self.wallet.cache_inverse(inverse) {
-                return Err(Error::DatabaseError(format!(
-                    "[handle_money_call_owncoins] Inserting inverse query into cache failed: {e:?}"
-                )))
-            }
         }
 
         Ok(())
@@ -855,49 +832,23 @@ impl Drk {
             *MONEY_TOKENS_TABLE, MONEY_TOKENS_COL_IS_FROZEN, MONEY_TOKENS_COL_TOKEN_ID,
         );
 
-        // This is its inverse query
-        let inverse_query = format!(
-            "UPDATE {} SET {} = 0 WHERE {} = ?1;",
-            *MONEY_TOKENS_TABLE, MONEY_TOKENS_COL_IS_FROZEN, MONEY_TOKENS_COL_TOKEN_ID,
-        );
-
         for token_id in freezes {
             // Grab token record key
             let key = serialize_async(token_id).await;
 
-            // Create its inverse query
-            let inverse =
-                match self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key])
-                {
-                    Ok(q) => q,
-                    Err(e) => {
-                        return Err(Error::DatabaseError(format!(
-                    "[handle_money_call_freezes] Creating Money token freeze inverse query failed: {e:?}"
-                )))
-                    }
-                };
-
             // Execute the query
             if let Err(e) = self.wallet.exec_sql(&query, rusqlite::params![key]) {
                 return Err(Error::DatabaseError(format!(
                     "[handle_money_call_freezes] Update Money token freeze failed: {e:?}"
                 )))
             }
-
-            // Store its inverse
-            if let Err(e) = self.wallet.cache_inverse(inverse) {
-                return Err(Error::DatabaseError(format!(
-                    "[handle_money_call_freezes] Inserting inverse query into cache failed: {e:?}"
-                )))
-            }
         }
 
         Ok(())
     }
 
     /// Append data related to Money contract transactions into the
-    /// wallet database, and store their inverse queries into the
-    /// cache.
+    /// wallet database and update the provided scan cache.
     /// Returns a flag indicating if the money tree should be updated
     /// and one indicating if provided data refer to our own wallet.
     pub async fn apply_tx_money_data(
@@ -1023,43 +974,14 @@ impl Drk {
             MONEY_COINS_COL_COIN
         );
 
-        // Create its inverse query
-        let inverse_query = format!(
-            "UPDATE {} SET {} = 0, {} = '-' WHERE {} = ?1;",
-            *MONEY_COINS_TABLE,
-            MONEY_COINS_COL_IS_SPENT,
-            MONEY_COINS_COL_SPENT_TX_HASH,
-            MONEY_COINS_COL_COIN
-        );
-
         // Mark spent own coins
         for ownoin in spent_owncoins {
-            // Create its inverse query
-            let inverse = match self
-                .wallet
-                .create_prepared_statement(&inverse_query, rusqlite::params![ownoin])
-            {
-                Ok(i) => i,
-                Err(e) => {
-                    return Err(Error::DatabaseError(format!(
-                        "[mark_spent_coins] Creating inverse query failed: {e:?}"
-                    )))
-                }
-            };
-
             // Execute the query
             if let Err(e) = self.wallet.exec_sql(&query, rusqlite::params![spent_tx_hash, ownoin]) {
                 return Err(Error::DatabaseError(format!(
                     "[mark_spent_coins] Marking spent coin failed: {e:?}"
                 )))
             }
-
-            // Store its inverse
-            if let Err(e) = self.wallet.cache_inverse(inverse) {
-                return Err(Error::DatabaseError(format!(
-                    "[mark_spent_coins] Storing inverse query failed: {e:?}"
-                )))
-            }
         }
 
         Ok(true)

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

@@ -286,12 +286,8 @@ impl Drk {
     }
 
     /// `scan_block` will go over over transactions in a block and handle their calls
-    /// based on the called contract. Additionally, will update `last_scanned_block` to
-    /// the provided block height and will store its height, hash and inverse query.
+    /// based on the called contract.
     async fn scan_block(&self, scan_cache: &mut ScanCache, block: &BlockInfo) -> Result<()> {
-        // Reset wallet inverse cache state
-        self.reset_inverse_cache().await?;
-
         // Keep track of the trees we need to update and our wallet
         // transactions.
         let mut update_money_tree = false;

+ 1 - 13
bin/drk/src/txs_history.rs

@@ -47,23 +47,11 @@ impl Drk {
             "INSERT OR REPLACE INTO {WALLET_TXS_HISTORY_TABLE} ({WALLET_TXS_HISTORY_COL_TX_HASH}, {WALLET_TXS_HISTORY_COL_STATUS}, {WALLET_TXS_HISTORY_COL_TX}) VALUES (?1, ?2, ?3);"
         );
 
-        // Create its inverse query
-        let tx_hash = tx.hash().to_string();
-        // We only need to set the transaction status to "Reverted"
-        let inverse = self.wallet.create_prepared_statement(
-            &format!(
-                "UPDATE {WALLET_TXS_HISTORY_TABLE} SET {WALLET_TXS_HISTORY_COL_STATUS} = ?1 WHERE {WALLET_TXS_HISTORY_COL_TX_HASH} = ?2;"
-            ),
-            rusqlite::params!["Reverted", tx_hash],
-        )?;
-
         // Execute the query
+        let tx_hash = tx.hash().to_string();
         self.wallet
             .exec_sql(&query, rusqlite::params![tx_hash, status, &serialize_async(tx).await,])?;
 
-        // Store its inverse
-        self.wallet.cache_inverse(inverse)?;
-
         Ok(tx_hash)
     }
 

+ 1 - 58
bin/drk/src/walletdb.rs

@@ -35,9 +35,6 @@ pub type WalletPtr = Arc<WalletDb>;
 pub struct WalletDb {
     /// Connection to the SQLite database.
     pub conn: Mutex<Connection>,
-    /// Inverse queries cache, in case we want to rollback
-    /// executed queries, stored as raw SQL strings.
-    inverse_cache: Mutex<Vec<String>>,
 }
 
 impl WalletDb {
@@ -62,7 +59,7 @@ impl WalletDb {
         };
 
         debug!(target: "walletdb::new", "[WalletDb] Opened Sqlite connection at \"{path:?}\"");
-        Ok(Arc::new(Self { conn: Mutex::new(conn), inverse_cache: Mutex::new(vec![]) }))
+        Ok(Arc::new(Self { conn: Mutex::new(conn) }))
     }
 
     /// This function executes a given SQL query that contains multiple SQL statements,
@@ -334,60 +331,6 @@ impl WalletDb {
 
         Ok(result)
     }
-
-    /// Auxiliary function to store provided inverse query into our cache.
-    pub fn cache_inverse(&self, query: String) -> WalletDbResult<()> {
-        debug!(target: "walletdb::cache_inverse", "[WalletDb] Storing query:\n{query}");
-        let Ok(mut cache) = self.inverse_cache.lock() else {
-            return Err(WalletDbError::FailedToAquireLock)
-        };
-
-        // Push the query into the cache
-        cache.push(query);
-
-        // Drop cache lock
-        drop(cache);
-
-        Ok(())
-    }
-
-    /// Auxiliary function to retrieve cached inverse queries into a single SQL execution block.
-    /// The final query will contain the queries in reverse order, and cache is cleared afterwards.
-    pub fn grab_inverse_cache_block(&self) -> WalletDbResult<String> {
-        // Grab cache lock
-        debug!(target: "walletdb::grab_inverse_block", "[WalletDb] Grabbing cached inverse queries");
-        let Ok(cache) = self.inverse_cache.lock() else {
-            return Err(WalletDbError::FailedToAquireLock)
-        };
-
-        // Build the full SQL block query
-        let mut inverse_batch = String::from("BEGIN;");
-        for query in cache.iter().rev() {
-            inverse_batch += query;
-        }
-        inverse_batch += "END;";
-
-        // Drop the lock
-        drop(cache);
-
-        Ok(inverse_batch)
-    }
-
-    /// Auxiliary function to clear inverse queries cache.
-    pub fn clear_inverse_cache(&self) -> WalletDbResult<()> {
-        // Grab cache lock
-        let Ok(mut cache) = self.inverse_cache.lock() else {
-            return Err(WalletDbError::FailedToAquireLock)
-        };
-
-        // Clear cache
-        *cache = vec![];
-
-        // Drop the lock
-        drop(cache);
-
-        Ok(())
-    }
 }
 
 /// Custom implementation of rusqlite::named_params! to use `expr` instead of `literal` as `$param_name`,