aboutsummaryrefslogtreecommitdiff
path: root/p2p/examples/peer.rs
blob: f805d68c65eff8f06985013e23380f5c587a0647 (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
use std::sync::Arc;

use clap::Parser;
use easy_parallel::Parallel;
use smol::{channel, future, Executor};

use karyons_net::{Endpoint, Port};

use karyons_p2p::{Backend, Config, PeerID};

#[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>,

    /// Optional user id
    #[arg(long)]
    userid: Option<String>,
}

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

    let peer_id = match cli.userid {
        Some(userid) => PeerID::new(userid.as_bytes()),
        None => PeerID::random(),
    };

    // 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),
        ..Default::default()
    };

    // Create a new Backend
    let backend = Backend::new(peer_id, config);

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

    let (signal, shutdown) = channel::unbounded::<()>();

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

    let task = async {
        // Run the backend
        backend.run(ex.clone()).await.unwrap();

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

        // Shutdown the backend
        backend.shutdown().await;

        drop(signal);
    };

    // Run four executor threads.
    Parallel::new()
        .each(0..4, |_| future::block_on(ex.run(shutdown.recv())))
        .finish(|| future::block_on(task));
}