8 releases

0.4.0 Oct 5, 2024
0.3.0 Sep 16, 2024
0.2.0 Jun 25, 2024
0.1.5 May 14, 2024
0.1.0 Dec 4, 2023

#1553 in Network programming

Download history 9/week @ 2024-06-30 13/week @ 2024-07-07 13/week @ 2024-07-28 211/week @ 2024-09-15 27/week @ 2024-09-22 100/week @ 2024-09-29 89/week @ 2024-10-06 20/week @ 2024-10-13

241 downloads per month

Apache-2.0 OR MIT

35KB
933 lines

P2P

A p2p networking library

Example

const ALPN: &[u8] = b"/p2p/ping/1";

#[derive(Debug, Deserialize, Serialize)]
pub struct Ping(u16);

#[derive(Debug, Deserialize, Serialize)]
pub struct Pong(u16);

pub struct PingPong;

impl Protocol for PingPong {
    const ID: u16 = 0;
    const REQ_BUF: usize = 1024;
    const RES_BUF: usize = 1024;
    type Request = Ping;
    type Response = Pong;
}

impl RequestHandler<Self> for PingPong {
    fn request(
        &self,
        _peer_id: PeerId,
        request: <Self as Protocol>::Request,
        response: oneshot::Sender<<Self as Protocol>::Response>,
    ) -> Result<()> {
        response
            .send(Pong(request.0))
            .map_err(|_| anyhow::anyhow!("response channel closed"))?;
        Ok(())
    }
}

let mut builder = ProtocolHandler::builder();
builder.register_request_handler(PingPong);
let handler = builder.build();

let mut builder = Endpoint::builder(ALPN.to_vec());
builder.handler(handler);
let endpoint = builder.build().await?;
let pong = endpoint.request::<PingPong>(&peer, &Ping(42)).await?;
assert_eq!(pong.0, 42);

License

Apache-2.0 + MIT

Dependencies

~41–75MB
~1.5M SLoC