Forráskód Böngészése

fix bugs and add more debug messages

ghassmo 4 éve
szülő
commit
58a3b53928
6 módosított fájl, 89 hozzáadás és 29 törlés
  1. 15 15
      src/bin/cashierd.rs
  2. 34 2
      src/client.rs
  3. 13 3
      src/service/bridge.rs
  4. 8 0
      src/service/btc.rs
  5. 8 6
      src/service/sol.rs
  6. 11 3
      src/wallet/walletdb.rs

+ 15 - 15
src/bin/cashierd.rs

@@ -529,22 +529,22 @@ impl Cashierd {
         let bridge2 = self.bridge.clone();
         let bridge2 = self.bridge.clone();
         let listen_for_notification_from_bridge_task: smol::Task<Result<()>> = smol::spawn(
         let listen_for_notification_from_bridge_task: smol::Task<Result<()>> = smol::spawn(
             async move {
             async move {
-                loop {
-                    if let Some(token_notification) = bridge2.clone().listen().await {
-                        let token_notification = token_notification?;
-
-                        debug!(target: "CASHIER DAEMON", "Notification from birdge: {:?}", token_notification);
-
-                        client
-                            .send(
-                                token_notification.drk_pub_key,
-                                token_notification.received_balance,
-                                token_notification.token_id,
-                                true,
-                            )
-                            .await?;
-                    }
+                while let Some(token_notification) = bridge2.clone().listen().await
+                {
+                    debug!(target: "CASHIER DAEMON", "Notification from birdge: {:?}", token_notification);
+
+                    let token_notification = token_notification?;
+
+                    client
+                        .send(
+                            token_notification.drk_pub_key,
+                            token_notification.received_balance,
+                            token_notification.token_id,
+                            true,
+                        )
+                        .await?;
                 }
                 }
+                Ok(())
             },
             },
         );
         );
 
 

+ 34 - 2
src/client.rs

@@ -115,12 +115,17 @@ impl Client {
         pub_key: jubjub::SubgroupPoint,
         pub_key: jubjub::SubgroupPoint,
         amount: u64,
         amount: u64,
     ) -> Result<()> {
     ) -> Result<()> {
+
+        debug!(target: "CLIENT", "Start transfer {}", amount);
+
         if amount == 0 {
         if amount == 0 {
             return Err(ClientFailed::InvalidAmount(amount as u64).into());
             return Err(ClientFailed::InvalidAmount(amount as u64).into());
         }
         }
 
 
         self.send(pub_key, amount, asset_id, false).await?;
         self.send(pub_key, amount, asset_id, false).await?;
 
 
+        debug!(target: "CLIENT", "End transfer {}", amount);
+
         Ok(())
         Ok(())
     }
     }
 
 
@@ -131,12 +136,18 @@ impl Client {
         asset_id: jubjub::Fr,
         asset_id: jubjub::Fr,
         clear_input: bool,
         clear_input: bool,
     ) -> Result<()> {
     ) -> Result<()> {
+
+        debug!(target: "CLIENT", "Start send {}", amount);
+
         let slab = self
         let slab = self
             .build_slab_from_tx(pub_key, amount, asset_id, clear_input)
             .build_slab_from_tx(pub_key, amount, asset_id, clear_input)
             .await?;
             .await?;
 
 
         self.gateway.put_slab(slab).await?;
         self.gateway.put_slab(slab).await?;
 
 
+        
+        debug!(target: "CLIENT", "End send {}", amount);
+
         Ok(())
         Ok(())
     }
     }
 
 
@@ -147,6 +158,9 @@ impl Client {
         asset_id: jubjub::Fr,
         asset_id: jubjub::Fr,
         clear_input: bool,
         clear_input: bool,
     ) -> Result<Slab> {
     ) -> Result<Slab> {
+
+        debug!(target: "CLIENT", "Start build slab from tx");
+
         let mut clear_inputs: Vec<tx::TransactionBuilderClearInputInfo> = vec![];
         let mut clear_inputs: Vec<tx::TransactionBuilderClearInputInfo> = vec![];
         let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
         let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
         let mut outputs: Vec<tx::TransactionBuilderOutputInfo> = vec![];
         let mut outputs: Vec<tx::TransactionBuilderOutputInfo> = vec![];
@@ -182,6 +196,9 @@ impl Client {
         }
         }
 
 
         let slab = Slab::new(tx_data);
         let slab = Slab::new(tx_data);
+
+        debug!(target: "CLIENT", "End build slab from tx");
+
         Ok(slab)
         Ok(slab)
     }
     }
 
 
@@ -191,6 +208,9 @@ impl Client {
         asset_id: jubjub::Fr,
         asset_id: jubjub::Fr,
         outputs: &mut Vec<tx::TransactionBuilderOutputInfo>,
         outputs: &mut Vec<tx::TransactionBuilderOutputInfo>,
     ) -> Result<Vec<tx::TransactionBuilderInputInfo>> {
     ) -> Result<Vec<tx::TransactionBuilderInputInfo>> {
+
+        debug!(target: "CLIENT", "Start build inputs");
+        
         let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
         let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
         let mut inputs_value: u64 = 0;
         let mut inputs_value: u64 = 0;
 
 
@@ -213,7 +233,7 @@ impl Client {
         }
         }
 
 
         if inputs_value < amount {
         if inputs_value < amount {
-            return Err(ClientFailed::NotEnoughValue(0).into());
+            return Err(ClientFailed::NotEnoughValue(inputs_value).into());
         }
         }
 
 
         if inputs_value > amount {
         if inputs_value > amount {
@@ -230,7 +250,10 @@ impl Client {
                 public: own_pub_key,
                 public: own_pub_key,
             });
             });
         }
         }
-        Ok(vec![])
+
+        debug!(target: "CLIENT", "End build inputs");
+
+        Ok(inputs)
     }
     }
 
 
     pub async fn connect_to_subscriber_from_cashier(
     pub async fn connect_to_subscriber_from_cashier(
@@ -375,10 +398,13 @@ impl State {
         notify: async_channel::Sender<(jubjub::SubgroupPoint, u64)>,
         notify: async_channel::Sender<(jubjub::SubgroupPoint, u64)>,
     ) -> Result<()> {
     ) -> Result<()> {
         // Extend our list of nullifiers with the ones from the update
         // Extend our list of nullifiers with the ones from the update
+
+        debug!(target: "CLIENT STATE", "Extend nullifiers");
         for nullifier in update.nullifiers {
         for nullifier in update.nullifiers {
             self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
             self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
         }
         }
 
 
+        debug!(target: "CLIENT STATE", "Update merkle tree and witness ");
         // Update merkle tree and witnesses
         // Update merkle tree and witnesses
         for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.iter()) {
         for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.iter()) {
             // Add the new coins to the merkle tree
             // Add the new coins to the merkle tree
@@ -415,8 +441,14 @@ impl State {
                         witness: witness.clone(),
                         witness: witness.clone(),
                     };
                     };
 
 
+
                     self.wallet.put_own_coins(own_coin)?;
                     self.wallet.put_own_coins(own_coin)?;
                     let pub_key = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
                     let pub_key = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+
+                    debug!(target: "CLIENT STATE", "Received a coin: amount {} from {}", note.value, pub_key);
+
+                    debug!(target: "CLIENT STATE", "Send a notification");
+
                     notify.send((pub_key, note.value)).await?;
                     notify.send((pub_key, note.value)).await?;
                 }
                 }
             }
             }

+ 13 - 3
src/service/bridge.rs

@@ -74,26 +74,36 @@ impl Bridge {
         client: Arc<dyn NetworkClient + Send + Sync>,
         client: Arc<dyn NetworkClient + Send + Sync>,
     ) -> Result<()> {
     ) -> Result<()> {
         debug!(target: "BRIDGE", "Add new client");
         debug!(target: "BRIDGE", "Add new client");
+
         let client2 = client.clone();
         let client2 = client.clone();
         let notifier = client2.get_notifier().await?;
         let notifier = client2.get_notifier().await?;
 
 
+        if !notifier.is_closed() {
+            self.notifiers.push(notifier);
+        }
+
         self.clients.lock().await.insert(network, client.clone());
         self.clients.lock().await.insert(network, client.clone());
 
 
-        self.notifiers.push(notifier.clone());
         Ok(())
         Ok(())
     }
     }
 
 
     pub async fn listen(self: Arc<Self>) -> Option<Result<TokenNotification>> {
     pub async fn listen(self: Arc<Self>) -> Option<Result<TokenNotification>> {
         if !self.notifiers.is_empty() {
         if !self.notifiers.is_empty() {
             debug!(target: "BRIDGE", "Start listening to new notification");
             debug!(target: "BRIDGE", "Start listening to new notification");
-            self.notifiers
+            let notification = self
+                .notifiers
                 .iter()
                 .iter()
                 .map(|n| n.recv())
                 .map(|n| n.recv())
                 .collect::<FuturesUnordered<async_channel::Recv<TokenNotification>>>()
                 .collect::<FuturesUnordered<async_channel::Recv<TokenNotification>>>()
                 .next()
                 .next()
                 .await
                 .await
-                .map(|o| o.map_err(Error::from))
+                .map(|o| o.map_err(Error::from));
+
+            debug!(target: "BRIDGE", "End listening to new notification");
+
+            notification
         } else {
         } else {
+            debug!(target: "BRIDGE", "TEST");
             None
             None
         }
         }
     }
     }

+ 8 - 0
src/service/btc.rs

@@ -126,12 +126,19 @@ pub struct BtcClient {
     client: Arc<ElectrumClient>,
     client: Arc<ElectrumClient>,
     network: Network,
     network: Network,
     keypair: Keypair,
     keypair: Keypair,
+    notify_channel: (
+        async_channel::Sender<TokenNotification>,
+        async_channel::Receiver<TokenNotification>,
+    ),
+    
 }
 }
 
 
 impl BtcClient {
 impl BtcClient {
     pub async fn new(keypair: Vec<u8>, network: &str) -> Result<Arc<Self>> {
     pub async fn new(keypair: Vec<u8>, network: &str) -> Result<Arc<Self>> {
         let keypair: Keypair = deserialize(&keypair)?;
         let keypair: Keypair = deserialize(&keypair)?;
 
 
+        let notify_channel = async_channel::unbounded();
+
         let (network, url) = match network {
         let (network, url) = match network {
             "mainnet" => (Network::Bitcoin, "ssl://electrum.blockstream.info:50002"),
             "mainnet" => (Network::Bitcoin, "ssl://electrum.blockstream.info:50002"),
             "testnet" => (Network::Testnet, "ssl://electrum.blockstream.info:60002"),
             "testnet" => (Network::Testnet, "ssl://electrum.blockstream.info:60002"),
@@ -145,6 +152,7 @@ impl BtcClient {
             client: Arc::new(electrum_client),
             client: Arc::new(electrum_client),
             network,
             network,
             keypair,
             keypair,
+            notify_channel
         }))
         }))
     }
     }
 
 

+ 8 - 6
src/service/sol.rs

@@ -6,7 +6,7 @@ use async_native_tls::TlsConnector;
 use async_std::sync::{Arc, Mutex};
 use async_std::sync::{Arc, Mutex};
 use async_trait::async_trait;
 use async_trait::async_trait;
 use futures::{SinkExt, StreamExt};
 use futures::{SinkExt, StreamExt};
-use log::{debug, error};
+use log::{debug, error, warn};
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
 use serde::Serialize;
 use serde::Serialize;
 use serde_json::{json, Value};
 use serde_json::{json, Value};
@@ -55,7 +55,9 @@ impl SolClient {
         let main_keypair: Keypair = deserialize(&main_keypair)?;
         let main_keypair: Keypair = deserialize(&main_keypair)?;
         let notify_channel = async_channel::unbounded();
         let notify_channel = async_channel::unbounded();
 
 
-        debug!("Main SOL wallet pubkey: {:?}", &main_keypair.pubkey());
+        warn!(target: "SOL BRIDGE", "Main SOL wallet: {:?}", main_keypair.to_bytes());
+
+        debug!(target: "SOL BRIDGE", "Main SOL wallet pubkey: {:?}", &main_keypair.pubkey());
 
 
         let (rpc_server, wss_server) = match network {
         let (rpc_server, wss_server) = match network {
             "mainnet" => (
             "mainnet" => (
@@ -227,12 +229,13 @@ impl SolClient {
             ));
             ));
         }
         }
 
 
+        let send_notification = self.notify_channel.0.clone();
+
         if mint.is_some() {
         if mint.is_some() {
             let amnt = cur_balance - prev_balance;
             let amnt = cur_balance - prev_balance;
             let ui_amnt = amnt / u64::pow(10, decimals as u32);
             let ui_amnt = amnt / u64::pow(10, decimals as u32);
 
 
-            self.notify_channel
-                .0
+            send_notification
                 .send(TokenNotification {
                 .send(TokenNotification {
                     network: NetworkName::Solana,
                     network: NetworkName::Solana,
                     token_id: generate_id(&mint.unwrap().to_string(), &NetworkName::Solana)?,
                     token_id: generate_id(&mint.unwrap().to_string(), &NetworkName::Solana)?,
@@ -248,8 +251,7 @@ impl SolClient {
             let amnt = cur_balance - prev_balance;
             let amnt = cur_balance - prev_balance;
             let ui_amnt = lamports_to_sol(amnt);
             let ui_amnt = lamports_to_sol(amnt);
 
 
-            self.notify_channel
-                .0
+            send_notification
                 .send(TokenNotification {
                 .send(TokenNotification {
                     network: NetworkName::Solana,
                     network: NetworkName::Solana,
                     token_id: generate_id(SOL_NATIVE_TOKEN_ID, &NetworkName::Solana)?,
                     token_id: generate_id(SOL_NATIVE_TOKEN_ID, &NetworkName::Solana)?,

+ 11 - 3
src/wallet/walletdb.rs

@@ -108,7 +108,7 @@ impl WalletDb {
     }
     }
 
 
     pub fn get_keypairs(&self) -> Result<Vec<Keypair>> {
     pub fn get_keypairs(&self) -> Result<Vec<Keypair>> {
-        debug!(target: "WALLETDB", "Returning keys...");
+        debug!(target: "WALLETDB", "Returning keypairs...");
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
         conn.pragma_update(None, "key", &self.password)?;
         conn.pragma_update(None, "key", &self.password)?;
         let mut stmt = conn.prepare("SELECT * FROM keys")?;
         let mut stmt = conn.prepare("SELECT * FROM keys")?;
@@ -130,7 +130,9 @@ impl WalletDb {
     }
     }
 
 
     pub fn get_own_coins(&self) -> Result<OwnCoins> {
     pub fn get_own_coins(&self) -> Result<OwnCoins> {
-        // open connection
+
+        debug!(target: "WALLETDB", "Get own coins");
+
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
         // unlock database
         // unlock database
         conn.pragma_update(None, "key", &self.password)?;
         conn.pragma_update(None, "key", &self.password)?;
@@ -202,6 +204,9 @@ impl WalletDb {
 
 
     pub fn put_own_coins(&self, own_coin: OwnCoin) -> Result<()> {
     pub fn put_own_coins(&self, own_coin: OwnCoin) -> Result<()> {
         // prepare the values
         // prepare the values
+
+        debug!(target: "WALLETDB", "Put own coins");
+
         let coin = self.get_value_serialized(&own_coin.coin.repr)?;
         let coin = self.get_value_serialized(&own_coin.coin.repr)?;
         let serial = self.get_value_serialized(&own_coin.note.serial)?;
         let serial = self.get_value_serialized(&own_coin.note.serial)?;
         let coin_blind = self.get_value_serialized(&own_coin.note.coin_blind)?;
         let coin_blind = self.get_value_serialized(&own_coin.note.coin_blind)?;
@@ -269,6 +274,9 @@ impl WalletDb {
         coin_id: u64,
         coin_id: u64,
         witness: IncrementalWitness<MerkleNode>,
         witness: IncrementalWitness<MerkleNode>,
     ) -> Result<()> {
     ) -> Result<()> {
+
+        debug!(target: "WALLETDB", "Updating witness");
+
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
         conn.pragma_update(None, "key", &self.password)?;
         conn.pragma_update(None, "key", &self.password)?;
 
 
@@ -297,7 +305,7 @@ impl WalletDb {
     }
     }
 
 
     pub fn get_cashier_public_keys(&self) -> Result<Vec<jubjub::SubgroupPoint>> {
     pub fn get_cashier_public_keys(&self) -> Result<Vec<jubjub::SubgroupPoint>> {
-        debug!(target: "WALLETDB", "Returning keys...");
+        debug!(target: "WALLETDB", "Returning Cashier Public key...");
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
         conn.pragma_update(None, "key", &self.password)?;
         conn.pragma_update(None, "key", &self.password)?;
         let mut stmt = conn.prepare("SELECT key_public FROM cashier")?;
         let mut stmt = conn.prepare("SELECT key_public FROM cashier")?;