p2p_chat/network/layer/
providers.rs

1//! This module contains functions for interacting with the Kademlia DHT.
2use anyhow::Result;
3use tokio::sync::mpsc;
4
5use crate::cli::commands::UiNotification;
6use crate::mailbox::{make_mailbox_provider_key, make_recipient_mailbox_key};
7use crate::sync::SyncEvent;
8
9use super::NetworkLayer;
10
11impl NetworkLayer {
12    /// Sets the sender for synchronization events.
13    pub fn set_sync_event_sender(&mut self, sender: mpsc::UnboundedSender<SyncEvent>) {
14        self.sync_event_tx = Some(sender);
15    }
16
17    /// Sets the sender for UI notifications.
18    pub fn set_ui_notify_sender(&mut self, sender: mpsc::UnboundedSender<UiNotification>) {
19        self.ui_notify_tx = Some(sender);
20    }
21
22    /// Bootstraps the Kademlia DHT.
23    ///
24    /// # Errors
25    ///
26    /// This function will return an error if the bootstrap process fails.
27    pub fn bootstrap_dht(&mut self) -> Result<()> {
28        self.swarm.behaviour_mut().discovery.bootstrap()
29    }
30
31    /// Starts providing the general mailbox provider key in the Kademlia DHT.
32    ///
33    /// # Errors
34    ///
35    /// This function will return an error if the providing process fails to start.
36    pub fn start_providing_mailbox(&mut self) -> Result<()> {
37        let key = make_mailbox_provider_key();
38        self.swarm.behaviour_mut().discovery.start_providing(key)
39    }
40
41    /// Starts providing a key for a specific recipient in the Kademlia DHT.
42    ///
43    /// # Arguments
44    ///
45    /// * `recipient_hash` - The hash of the recipient's public key.
46    ///
47    /// # Errors
48    ///
49    /// This function will return an error if the providing process fails to start.
50    pub fn start_providing_for_recipient(&mut self, recipient_hash: [u8; 32]) -> Result<()> {
51        let key = make_recipient_mailbox_key(recipient_hash);
52        self.swarm.behaviour_mut().discovery.start_providing(key)
53    }
54}