aboutsummaryrefslogtreecommitdiff
path: root/p2p/examples/chat.rs
blob: 99cde7b0cd3e509a27509fcc56bf25cef3604db2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
mod shared;

use std::sync::Arc;

use async_std::io;
use async_trait::async_trait;
use clap::Parser;
use smol::{channel, Executor};

use karyons_core::crypto::{KeyPair, KeyPairType};
use karyons_net::{Endpoint, Port};

use karyons_p2p::{
    protocol::{ArcProtocol, Protocol, ProtocolEvent, ProtocolID},
    ArcPeer, Backend, Config, P2pError, Version,
};

use shared::run_executor;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Optional list of bootstrap peers to start the seeding process.
    #[arg(short)]
    bootstrap_peers: Vec<Endpoint>,

    /// Optional list of peer endpoints for manual connections.
    #[arg(short)]
    peer_endpoints: Vec<Endpoint>,

    /// Optional endpoint for accepting incoming connections.
    #[arg(short)]
    listen_endpoint: Option<Endpoint>,

    /// Optional TCP/UDP port for the discovery service.
    #[arg(short)]
    discovery_port: Option<Port>,

    /// Username
    #[arg(long)]
    username: String,
}

pub struct ChatProtocol {
    username: String,
    peer: ArcPeer,
    executor: Arc<Executor<'static>>,
}

impl ChatProtocol {
    fn new(username: &str, peer: ArcPeer, executor: Arc<Executor<'static>>) -> ArcProtocol {
        Arc::new(Self {
            peer,
            username: username.to_string(),
            executor,
        })
    }
}

#[async_trait]
impl Protocol for ChatProtocol {
    async fn start(self: Arc<Self>) -> Result<(), P2pError> {
        let selfc = self.clone();
        let stdin = io::stdin();
        let task = self.executor.spawn(async move {
            loop {
                let mut input = String::new();
                stdin.read_line(&mut input).await.unwrap();
                let msg = format!("> {}: {}", selfc.username, input.trim());
                selfc.peer.broadcast(&Self::id(), &msg).await;
            }
        });

        let listener = self.peer.register_listener::<Self>().await;
        loop {
            let event = listener.recv().await.unwrap();

            match event {
                ProtocolEvent::Message(msg) => {
                    let msg = String::from_utf8(msg).unwrap();
                    println!("{msg}");
                }
                ProtocolEvent::Shutdown => {
                    break;
                }
            }
        }

        task.cancel().await;
        listener.cancel().await;
        Ok(())
    }

    fn version() -> Result<Version, P2pError> {
        "0.1.0, 0.1.0".parse()
    }

    fn id() -> ProtocolID {
        "CHAT".into()
    }
}

fn main() {
    env_logger::init();
    let cli = Cli::parse();

    // Create a PeerID based on the username.
    let key_pair = KeyPair::generate(&KeyPairType::Ed25519);

    // Create the configuration for the backend.
    let config = Config {
        listen_endpoint: cli.listen_endpoint,
        peer_endpoints: cli.peer_endpoints,
        bootstrap_peers: cli.bootstrap_peers,
        discovery_port: cli.discovery_port.unwrap_or(0),
        enable_tls: true,
        ..Default::default()
    };

    // Create a new Executor
    let ex = Arc::new(Executor::new());

    // Create a new Backend
    let backend = Backend::new(&key_pair, config, ex.clone());

    let (ctrlc_s, ctrlc_r) = channel::unbounded();
    let handle = move || ctrlc_s.try_send(()).unwrap();
    ctrlc::set_handler(handle).unwrap();

    let ex_cloned = ex.clone();
    run_executor(
        async {
            let username = cli.username;

            // Attach the ChatProtocol
            let c = move |peer| ChatProtocol::new(&username, peer, ex_cloned.clone());
            backend.attach_protocol::<ChatProtocol>(c).await.unwrap();

            // Run the backend
            backend.run().await.unwrap();

            // Wait for ctrlc signal
            ctrlc_r.recv().await.unwrap();

            // Shutdown the backend
            backend.shutdown().await;
        },
        ex,
    );
}