p2p_chat/app/
mailbox.rs

1//! This module contains the primary entry point for running a mailbox node.
2use crate::crypto::{Identity, StorageEncryption};
3use crate::mailbox::MailboxNode;
4use crate::network::NetworkLayer;
5use anyhow::Result;
6use libp2p::Multiaddr;
7use std::str::FromStr;
8use std::sync::Arc;
9use std::time::Duration;
10
11/// Runs a mailbox node.
12///
13/// This function initializes and runs a mailbox node, which is responsible for
14/// storing and forwarding messages for other peers in the network.
15///
16/// # Arguments
17///
18/// * `identity` - The identity of the node.
19/// * `db` - The database instance for storing mailbox data.
20/// * `encryption` - The encryption key for the storage.
21/// * `port` - The port to listen on for incoming connections.
22///
23/// # Errors
24///
25/// This function will return an error if the mailbox node fails to start.
26pub async fn run(
27    identity: Arc<Identity>,
28    db: sled::Db,
29    encryption: Option<StorageEncryption>,
30    port: u16,
31) -> Result<()> {
32    println!("📬 Starting mailbox node");
33
34    let mut mailbox_node = MailboxNode::new(
35        identity.clone(),
36        db,
37        encryption,
38        1000,
39        Duration::from_secs(7 * 24 * 60 * 60),
40    )?;
41
42    let stats = mailbox_node.get_stats();
43    println!("Mailbox configuration:");
44    println!(
45        "  Max storage per user: {} messages",
46        stats.max_storage_per_user
47    );
48    println!("  Retention period: {:?}", stats.retention_period);
49    println!();
50
51    let listen_addr = Multiaddr::from_str(&format!("/ip4/0.0.0.0/tcp/{}", port))?;
52
53    let mailbox_storage = mailbox_node.storage.clone();
54    let (mut network_layer, _network_handle) = NetworkLayer::new_with_mailbox_storage(
55        identity,
56        listen_addr,
57        true,
58        Some(mailbox_storage),
59        vec![],
60    )?;
61
62    network_layer.bootstrap_dht()?;
63
64    mailbox_node.run_with_network(network_layer).await
65}