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
- Peer Discovery: Nodes connect to known peers and discover others
- NAT Traversal: UDP/TCP hole punching establishes direct connections
- Route Selection: Automatically selects the best path (direct or relayed)
- Data Transfer: Encrypted communication between peers
§Examples
See the examples/ directory for complete working examples:
node.rs- Basic P2P nodenode_kcp_stream.rs- Using KCP for reliable transport
§See Also
rustp2p-core- Core NAT traversal functionalityrustp2p-reliable- Reliable transport layer
Modules§
Structs§
- Builder
- Builder for creating a P2P endpoint with custom configuration.
- Config
- Configuration for creating a P2P endpoint.
- Default
Interceptor - Default data interceptor that performs no interception.
- EndPoint
- The main endpoint for peer-to-peer communication.
- Group
Code - Group identifier for isolating P2P networks.
- Local
Interface - NetPacket
- NodeID
- Unique identifier for a peer in the P2P network.
- Punch
Model - Punch
Policy Set - This is middle representation for inner
- Recv
Metadata - Recv
Result - Recv
User Data - Route
Key - TcpTunnel
Config - TCP tunnel configuration.
- UdpTunnel
Config - UDP tunnel configuration.
Enums§
Constants§
Traits§
- Data
Interceptor - Trait for intercepting and preprocessing received data.