Skip to main content

Crate rustp2p

Crate rustp2p 

Source
Expand description

§rustp2p - Decentralized P2P Library

rustp2p is a decentralized peer-to-peer library written in Rust that provides simple and efficient NAT traversal and peer-to-peer communication. It supports both UDP and TCP hole punching, reliable transport over KCP, and secure encryption.

§Features

  • UDP Hole Punching: Works with both Cone NAT and Symmetric NAT
  • TCP Hole Punching: Supports NAT1 scenarios
  • Reliable Transport: Built-in KCP support for reliable UDP communication
  • Encryption: Supports AES-GCM and ChaCha20-Poly1305 encryption
  • Simple API: Easy-to-use builder pattern for configuration
  • Auto Route Discovery: Automatically finds the best path between peers

§Quick Start

Here’s a minimal example to get you started:

use rustp2p::Builder;
use std::net::Ipv4Addr;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    // Create a node with ID 10.0.0.1
    let node_id = Ipv4Addr::new(10, 0, 0, 1);
    let endpoint = Builder::new()
        .node_id(node_id.into())
        .udp_port(8080)
        .build()
        .await?;

    // Receive messages
    tokio::spawn(async move {
        loop {
            if let Ok((data, metadata)) = endpoint.recv_from().await {
                let src: Ipv4Addr = metadata.src_id().into();
                println!("Received from {}: {:?}", src, data.payload());
            }
        }
    });

    Ok(())
}

§Basic Usage

§Creating a P2P Node

Use the Builder to configure and create an EndPoint:

use rustp2p::{Builder, PeerNodeAddress};
use std::net::Ipv4Addr;
use std::str::FromStr;

let endpoint = Builder::new()
    .node_id(Ipv4Addr::new(10, 0, 0, 1).into())
    .udp_port(8080)
    .tcp_port(8080)
    // Add initial peers to connect to
    .peers(vec![
        PeerNodeAddress::from_str("udp://192.168.1.100:9090").unwrap()
    ])
    .build()
    .await?;

§Sending Messages

Send data to a peer using their node ID:

let peer_id = Ipv4Addr::new(10, 0, 0, 2);
endpoint.send_to(b"Hello, peer!", peer_id).await?;

§Receiving Messages

Receive data from any peer:

loop {
    match endpoint.recv_from().await {
        Ok((data, metadata)) => {
            let src: Ipv4Addr = metadata.src_id().into();
            println!("From {}: {:?}", src, data.payload());
        }
        Err(e) => {
            eprintln!("Error receiving: {}", e);
            break;
        }
    }
}

§Advanced Features

§Using Encryption

Enable secure communication with AES-GCM encryption:

use rustp2p::{Builder, cipher::Algorithm};
use std::net::Ipv4Addr;

let endpoint = Builder::new()
    .node_id(Ipv4Addr::new(10, 0, 0, 1).into())
    .udp_port(8080)
    .encryption(Algorithm::AesGcm("my-secret-password".to_string()))
    .build()
    .await?;

§Group Networking

Use group codes to create isolated P2P networks:

use rustp2p::{Builder, GroupCode};
use std::net::Ipv4Addr;

let endpoint = Builder::new()
    .node_id(Ipv4Addr::new(10, 0, 0, 1).into())
    .udp_port(8080)
    .group_code(GroupCode::try_from("12345").unwrap())
    .build()
    .await?;

§Broadcasting Messages

Send a message to all connected peers:

endpoint.broadcast(b"Hello everyone!").await?;

§Non-blocking Operations

Use try_* variants for non-blocking operations:

let peer_id = Ipv4Addr::new(10, 0, 0, 2);

// Non-blocking send
match endpoint.try_send_to(b"Quick message", peer_id) {
    Ok(_) => println!("Sent successfully"),
    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
        println!("Would block, try again later")
    }
    Err(e) => eprintln!("Error: {}", e),
}

// Non-blocking receive
match endpoint.try_recv_from() {
    Ok((data, metadata)) => {
        println!("Received: {:?}", data.payload());
    }
    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
        println!("No data available")
    }
    Err(e) => eprintln!("Error: {}", e),
}

§Architecture

The library is organized into several key components:

  • EndPoint: The main interface for sending and receiving data
  • Builder: Fluent API for configuring and creating endpoints
  • NodeID: Unique identifier for each peer (based on IPv4)
  • Tunnel: Underlying transport mechanism (UDP/TCP)
  • Cipher: Optional encryption layer

§How It Works

  1. Peer Discovery: Nodes connect to known peers and discover others
  2. NAT Traversal: UDP/TCP hole punching establishes direct connections
  3. Route Selection: Automatically selects the best path (direct or relayed)
  4. Data Transfer: Encrypted communication between peers

§Examples

See the examples/ directory for complete working examples:

  • node.rs - Basic P2P node
  • node_kcp_stream.rs - Using KCP for reliable transport

§See Also

Modules§

cipher
Encryption and decryption support for P2P communication.
node_id

Structs§

Builder
Builder for creating a P2P endpoint with custom configuration.
Config
Configuration for creating a P2P endpoint.
DefaultInterceptor
Default data interceptor that performs no interception.
EndPoint
The main endpoint for peer-to-peer communication.
GroupCode
Group identifier for isolating P2P networks.
LocalInterface
NetPacket
NodeID
Unique identifier for a peer in the P2P network.
PunchModel
PunchPolicySet
This is middle representation for inner
RecvMetadata
RecvResult
RecvUserData
RouteKey
TcpTunnelConfig
TCP tunnel configuration.
UdpTunnelConfig
UDP tunnel configuration.

Enums§

NatType
NodeAddress
PeerNodeAddress
PunchPolicy

Constants§

HEAD_LEN

Traits§

DataInterceptor
Trait for intercepting and preprocessing received data.