modality_network_node/
swarm.rs

1use anyhow::Result;
2
3use libp2p::ping;
4use libp2p::request_response;
5use libp2p::swarm;
6use libp2p::{identify, identity};
7use libp2p::{swarm::NetworkBehaviour, swarm::Swarm, SwarmBuilder};
8use std::time::Duration;
9
10use crate::reqres;
11
12#[derive(NetworkBehaviour)]
13pub struct NodeBehaviour {
14    // pub stream: libp2p_stream::Behaviour,
15    pub ping: ping::Behaviour,
16    pub identify: identify::Behaviour,
17    pub reqres: reqres::Behaviour,
18    // gossipsub: gossipsub::Behaviour,
19}
20
21pub type NodeSwarm = Swarm<NodeBehaviour>;
22
23pub async fn create_swarm(local_key: identity::Keypair) -> Result<NodeSwarm> {
24    // let stream_behaviour = libp2p_stream::Behaviour::new();
25
26    let identify_behaviour = identify::Behaviour::new(
27        identify::Config::new("/ipfs/id/1.0.0".into(), local_key.public())
28            .with_interval(std::time::Duration::from_secs(60)), // do this so we can get timeouts for dropped WebRTC connections
29    );
30    let ping_behaviour = ping::Behaviour::new(ping::Config::new());
31
32    let reqres_behaviour = reqres::Behaviour::new(
33        [(swarm::StreamProtocol::new(reqres::PROTOCOL), request_response::ProtocolSupport::Full)],
34        request_response::Config::default()
35    );
36
37    let behaviour = NodeBehaviour {
38        // stream: stream_behaviour,
39        ping: ping_behaviour,
40        identify: identify_behaviour,
41        reqres: reqres_behaviour,
42    };
43    let swarm = create_swarm_with_behaviours(local_key, behaviour).await?;
44    Ok(swarm)
45}
46
47pub async fn create_swarm_with_behaviours(
48    local_key: identity::Keypair,
49    behaviour: NodeBehaviour,
50) -> Result<NodeSwarm> {
51    let swarm0 = SwarmBuilder::with_existing_identity(local_key);
52    let swarm1 = swarm0.with_tokio();
53    let swarm2 = swarm1.with_tcp(
54        libp2p::tcp::Config::default(),
55        libp2p::noise::Config::new,
56        libp2p::yamux::Config::default,
57    )?;
58    let swarm3 = swarm2
59        .with_websocket(libp2p::noise::Config::new, libp2p::yamux::Config::default)
60        .await?;
61    let swarm4 = swarm3
62        .with_behaviour(|_key| behaviour)?
63        .with_swarm_config(|cfg| {
64            cfg.with_idle_connection_timeout(Duration::from_secs(60))
65        });
66    let swarm = swarm4.build();
67    Ok(swarm)
68}