p2p_chat/net/
mod.rs

1//! This module provides the networking capabilities for the application.
2//!
3//! It is responsible for building the `libp2p` transport and defining the
4//! network behaviours for chat, discovery, and mailboxes.
5pub mod chat;
6pub mod discovery;
7pub mod mailbox;
8
9use anyhow::Result;
10use libp2p::{
11    core::{transport::Boxed, upgrade::Version},
12    identity, noise, tcp, yamux, PeerId, Transport,
13};
14
15// Type alias for the transport.
16type BoxedTransport = Boxed<(PeerId, libp2p::core::muxing::StreamMuxerBox)>;
17
18pub use chat::ChatBehaviour;
19pub use discovery::DiscoveryBehaviour;
20pub use mailbox::MailboxBehaviour;
21
22/// Builds the `libp2p` transport.
23///
24/// This function creates a TCP-based transport that is secured with Noise
25/// and multiplexed with Yamux.
26///
27/// # Arguments
28///
29/// * `keypair` - The `identity::Keypair` of the local node.
30///
31/// # Errors
32///
33/// This function will return an error if the transport cannot be built.
34pub fn build_transport(keypair: &identity::Keypair) -> Result<BoxedTransport> {
35    let tcp = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true));
36    let noise = noise::Config::new(keypair)?;
37    let yamux = yamux::Config::default();
38
39    let transport = tcp
40        .upgrade(Version::V1)
41        .authenticate(noise)
42        .multiplex(yamux)
43        .boxed();
44
45    Ok(transport)
46}