Sfoglia il codice sorgente

Return GetBalanceRes when scriptpubkey balance is confirmed

Janus 5 anni fa
parent
commit
a85b840af0
2 ha cambiato i file con 30 aggiunte e 22 eliminazioni
  1. 22 15
      src/service/btc.rs
  2. 8 7
      src/service/cashier.rs

+ 22 - 15
src/service/btc.rs

@@ -2,7 +2,6 @@ use crate::{Error, Result};
 use rand::distributions::Alphanumeric;
 use rand::{thread_rng, Rng};
 
-use async_executor::Executor;
 use async_std::sync::Arc;
 use bitcoin::blockdata::script::Script;
 use bitcoin::network::constants::Network;
@@ -66,49 +65,57 @@ impl BitcoinKeys {
         }))
     }
 
-    pub async fn start_subscribe(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "BTC", "Subscribe");
+    pub async fn start_subscribe(self: Arc<Self>) -> Result<Option<electrum_client::GetBalanceRes>> {
+        debug!(target: "deposit", "BTC: Subscribe to scriptpubkey");
 
         // Check if script is already subscribed
         if let Some(status) = self.btc_client.script_subscribe(&self.script).unwrap() {
-            let subscribe_status_task =
-                executor.spawn(self.subscribe_status_loop(status, executor.clone()));
-            debug!(target: "BTC", "Subscribed to scripthash");
-            let _ = subscribe_status_task.cancel().await;
-            Ok(())
+            let subscribe_status_task = self.subscribe_status_loop(status).await?;
+            debug!(target: "deposit", "Subscribed to scriptpubkey");
+
+            match subscribe_status_task {
+                Some(status) => {
+                    Ok(Some(status))
+                },
+                _ => {
+                    Ok(None)
+                },
+            }
         } else {
-            return Err(Error::ServicesError("received wrong command"));
+            return Err(Error::ServicesError("Did not subscribe to scriptpubkey"));
         }
     }
 
     async fn subscribe_status_loop(
         self: Arc<Self>,
         status_start: electrum_client::ScriptStatus,
-        _executor: Arc<Executor<'_>>,
     ) -> Result<Option<electrum_client::GetBalanceRes>> {
+        debug!(target: "deposit", "awaiting balance: Start!");
         loop {
             let check = self.btc_client.script_pop(&self.script).unwrap();
             match check {
-
                 Some(status) => {
                     // Script has a notification update
                     if status != status_start {
                         let balance = self.btc_client.script_get_balance(&self.script).unwrap();
                         if balance.confirmed > 0 {
+                            debug!(target: "deposit", "BTC Balance: Confirmed!");
                             return Ok(Some(balance))
                         } else {
+                            debug!(target: "deposit", "BTC Balance: Unconfirmed!");
                             continue
                         }
-
                     } else {
+                        debug!(target: "deposit", "ScriptPubKey status has not changed");
                         continue
                     }
                 }
-
-                None => break,
+                None => {
+                    debug!(target: "deposit", "Scriptpubkey does not exist in script notifications!");
+                    return Ok(None)
+                },
             }
         }
-        Ok(None)
     }
 
     // This should do a db lookup to return the same obj

+ 8 - 7
src/service/cashier.rs

@@ -34,7 +34,7 @@ pub struct CashierService {
     addr: SocketAddr,
     wallet: CashierDbPtr,
     btc_client: Arc<ElectrumClient>,
-    client: Client,
+    client: Arc<Client>,
 }
 
 impl CashierService {
@@ -62,13 +62,13 @@ impl CashierService {
         let rocks = Rocks::new(&cashier_database_path)?;
 
         // TODO find a way to start the connection and subscribe to gateway
-        let client = Client::new(
+        let client = Arc::new(Client::new(
             cashier_secret,
             rocks,
             gateway_addrs,
             params_paths,
             client_wallet_path.clone(),
-        )?;
+        )?);
 
         Ok(Arc::new(CashierService {
             addr,
@@ -140,13 +140,14 @@ impl CashierService {
                 Ok(msg) => {
                     let cashier_wallet = self.wallet.clone();
                     let btc_client = self.btc_client.clone();
+                    let client = self.client.clone();
                     let _ = executor
                         .spawn(Self::handle_request(
                             msg,
                             btc_client,
+                            client,
                             cashier_wallet,
                             send_queue.clone(),
-                            executor.clone(),
                         ))
                         .detach();
                 }
@@ -160,9 +161,9 @@ impl CashierService {
     async fn handle_request(
         msg: (PeerId, Request),
         btc_client: Arc<ElectrumClient>,
+        _client: Arc<Client>,
         cashier_wallet: CashierDbPtr,
         send_queue: async_channel::Sender<(PeerId, Reply)>,
-        executor: Arc<Executor<'_>>,
     ) -> Result<()> {
         let request = msg.1;
         let peer = msg.0;
@@ -172,7 +173,7 @@ impl CashierService {
                 // Exchange zk_pubkey for bitcoin address
                 let zkpub = request.get_payload();
 
-                //check if key has already been issued
+                //TODO: check if key has already been issued
                 let _check = cashier_wallet.get_keys_by_dkey(&zkpub);
 
                 // Generate bitcoin Address
@@ -197,7 +198,7 @@ impl CashierService {
                 // start scheduler for checking balance
                 debug!(target: "BTC", "Subscribing");
 
-                let _ = btc_keys.start_subscribe(executor.clone()).await?;
+                let _ = btc_keys.start_subscribe().await?;
 
                 //self.mint_dbtc(deserialize(&zkpub).unwrap(), 100);