| Crates.io | saorsa-core |
| lib.rs | saorsa-core |
| version | 0.10.0 |
| created_at | 2025-06-30 11:55:25.693065+00 |
| updated_at | 2026-01-14 18:08:23.883051+00 |
| description | Saorsa - Core P2P networking library with DHT, QUIC transport, and four-word addresses |
| homepage | https://github.com/dirvine/saorsa-core-foundation |
| repository | https://github.com/dirvine/saorsa-core-foundation |
| max_upload_size | |
| id | 1731750 |
| size | 6,159,463 |
Core P2P networking library for Saorsa platform with DHT, QUIC transport, dual-stack endpoints (IPv6+IPv4), and four-word endpoint encoding.
Key design decisions are documented in docs/adr/:
| ADR | Title | Description |
|---|---|---|
| ADR-001 | Multi-Layer P2P Architecture | Layered design separating transport, DHT, identity, and application concerns |
| ADR-002 | Delegated Transport | Using ant-quic for QUIC transport, NAT traversal, and bootstrap cache |
| ADR-003 | Pure Post-Quantum Cryptography | ML-DSA-65 and ML-KEM-768 without classical fallbacks |
| ADR-004 | Four-Word Addresses | Human-readable addressing via word encoding |
| ADR-005 | S/Kademlia Witness Protocol | Byzantine fault-tolerant DHT operations |
| ADR-006 | EigenTrust Reputation | Iterative trust computation for Sybil resistance |
| ADR-007 | Adaptive Networking | Machine learning for dynamic routing optimization |
| ADR-008 | Bootstrap Cache Delegation | Delegating bootstrap to ant-quic with Sybil protection |
| ADR-009 | Sybil Protection | Multi-layered defense against identity attacks |
| ADR-010 | Entangled Attestation | Software integrity verification via attestation chains |
| ADR-011 | Geographic Placement | Region-aware storage for regulatory compliance |
| ADR-012 | Identity without PoW | Pure cryptographic identity using ML-DSA |
four-word-networking (IPv4+port encodes to 4 words; decoding returns both IP and port; IPv6 word count decided by the crate).Add this to your Cargo.toml:
[dependencies]
saorsa-core = "0.5.0"
use saorsa_core::{Network, NetworkConfig, NodeId};
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new network node
let config = NetworkConfig::default();
let mut network = Network::new(config).await?;
// Start the network
network.start().await?;
// Store some data
let key = b"example-key";
let value = b"example-value";
network.store(key, value.to_vec()).await?;
// Retrieve the data
if let Some(retrieved) = network.retrieve(key).await? {
println!("Retrieved: {:?}", retrieved);
}
Ok(())
}
saorsa-core v0.5.0+ includes full P2P NAT traversal support, enabling direct peer-to-peer connections:
use saorsa_core::messaging::{MessagingService, NetworkConfig, DhtClient};
use saorsa_core::identity::FourWordAddress;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create two messaging service instances with P2P NAT traversal (default)
let config = NetworkConfig::default(); // Includes P2P NAT traversal
let service1 = MessagingService::new_with_config(
FourWordAddress("peer-one-alpha".to_string()),
DhtClient::new()?,
config.clone(),
).await?;
let service2 = MessagingService::new_with_config(
FourWordAddress("peer-two-beta".to_string()),
DhtClient::new()?,
config,
).await?;
// Connect peers directly
let addr2 = service2.listen_addrs().await[0];
service1.connect_peer(&addr2).await?;
// Send P2P message
service1.send_direct_message(&addr2, b"Hello P2P!").await?;
Ok(())
}
NAT Traversal Modes:
Configuration Examples:
// Default P2P mode with concurrency limit of 10
let config = NetworkConfig::default();
// High-traffic P2P node
let config = NetworkConfig::p2p_node(50);
// Lightweight client
let config = NetworkConfig::client_only();
// Private network (no NAT traversal)
let config = NetworkConfig::no_nat_traversal();
four-word-networking crate's adaptive API.Network Layer: QUIC-based P2P networking with automatic NAT traversal (ant-quic 0.10.0+)
DHT: S/Kademlia-based DHT with RSPS optimization and witness attestations for Byzantine fault tolerance
Placement System: Intelligent shard placement with weighted selection algorithms
Identity: Post‑quantum cryptographic identities with ML‑DSA‑65 signatures (no PoW; no embedded four‑word address)
Storage: Local and distributed content storage with audit and repair
Geographic Routing: Location-aware message routing
Saorsa Core implements a pure post-quantum cryptographic approach for maximum security:
four-word-networking adaptive API; four‑words reserved for endpoints only.UserHandle for messaging identities; migrated mentions, presence, participants, search, reactions, and read/delivered receipts to use it.Application
↓
Network API
↓
Placement Engine → DHT + Geographic Routing
↓ ↓
↓ Audit & Repair
↓ ↓
QUIC Transport (ant-quic)
↓
Internet
Saorsa Core includes an advanced placement system for optimal distribution of erasure-coded shards across the network:
use saorsa_core::placement::{
PlacementEngine, PlacementConfig, GeographicLocation, NetworkRegion
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Configure placement system
let config = PlacementConfig {
replication_factor: (3, 8).into(), // Min 3, target 8 replicas
byzantine_tolerance: 2.into(), // Tolerate up to 2 Byzantine nodes
placement_timeout: Duration::from_secs(30),
geographic_diversity: true,
weights: OptimizationWeights {
trust_weight: 0.4, // EigenTrust reputation
performance_weight: 0.3, // Node performance metrics
capacity_weight: 0.2, // Available storage capacity
diversity_bonus: 0.1, // Geographic/network diversity
},
};
// Create placement engine
let mut engine = PlacementEngine::new(config);
// Place data with optimal shard distribution
let data = b"important data to store";
let decision = placement_orchestrator.place_data(
data.to_vec(),
8, // replication factor
Some(NetworkRegion::NorthAmerica),
).await?;
println!("Placed {} shards across {} nodes",
decision.shard_count,
decision.selected_nodes.len());
Ok(())
}
use saorsa_core::NetworkConfig;
let config = NetworkConfig {
listen_port: 9000,
bootstrap_nodes: vec![
"bootstrap1.example.com:9000".parse()?,
"bootstrap2.example.com:9000".parse()?,
],
enable_four_word_addresses: true,
dht_replication: 20,
storage_capacity: 1024 * 1024 * 1024, // 1GB
..Default::default()
};
default - Metrics and Prometheus integrationmetrics - Prometheus metrics and monitoringmocks - Test/dummy helpers for development (off by default)h2_greedy - Hyperbolic greedy routing helpers in APItest-utils - Test utilities including mock DHT for integration testsattestation - Entangled Attestation system for software integrity verificationNote: DHT, ant-quic QUIC transport, and post-quantum cryptography are always enabled. Four-word networking is a core feature.
Saorsa Core is designed for high performance:
Run benchmarks with:
cargo bench
Key benchmarks:
Saorsa Core implements defense-in-depth security designed for adversarial decentralized environments.
For complete security documentation, see docs/SECURITY_MODEL.md.
| Protection | Implementation |
|---|---|
| Node Monitoring | Automatic eviction after 3 consecutive failures |
| Reputation System | EigenTrust++ with multi-factor trust scoring |
| Sybil Resistance | IP diversity limits (/64: 1, /48: 3, /32: 10, ASN: 20) |
| Geographic Diversity | Minimum 3 regions for witness quorum |
| Byzantine Tolerance | f=2 in 3f+1 model (5 of 7 witnesses required) |
| Data Verification | Nonce-based attestation: BLAKE3(nonce |
| Entangled Attestation | Software integrity via EntangledId (Phase 1: soft enforcement) |
The Entangled Attestation system ensures nodes are running authorized software without relying on centralized authorities or proprietary hardware. A node's identity becomes mathematically "entangled" with its software:
EntangledId = BLAKE3(public_key || binary_hash || nonce)
Key Properties:
Enforcement Modes:
Off: Attestation disabled (development/testing)Soft: Invalid attestations logged but connections allowed (Phase 1)Hard: Invalid attestations rejected (future phases)Roadmap:
The network enforces geographic and infrastructure diversity to prevent centralization:
┌───────────────────────────────────────────────────┐
│ Geographic Witness Distribution │
├───────────────────────────────────────────────────┤
│ Region A Region B Region C ... │
│ (max 2) (max 2) (max 2) │
│ │ │ │ │
│ └─────────────┼─────────────┘ │
│ ▼ │
│ Quorum requires 3+ regions │
│ (prevents regional collusion) │
└───────────────────────────────────────────────────┘
Saorsa Core implements an advanced S/Kademlia witness system for Byzantine fault tolerance in DHT operations. This system ensures data integrity and prevents malicious nodes from corrupting stored data through cryptographically attested operations.
The witness protocol requires multiple independent nodes to cryptographically attest to DHT operations before they are considered valid. This prevents:
A key innovation in our witness protocol is geographic diversity enforcement using GeoIP data. Witnesses are selected to be geographically distributed, providing:
┌─────────────────────────────────────────────────────────┐
│ Geographic Witness Selection │
├─────────────────────────────────────────────────────────┤
│ │
│ Region A Region B Region C │
│ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │Witness1│ │Witness2│ │Witness3│ │
│ │ EU │ │ APAC │ │ NA │ │
│ └───┬────┘ └───┬────┘ └───┬────┘ │
│ │ │ │ │
│ └────────────┬────┴─────────────────┘ │
│ │ │
│ Attestation Quorum │
│ (Geographic spread prevents │
│ regional collusion) │
└─────────────────────────────────────────────────────────┘
use saorsa_core::dht::witness::{WitnessSelector, GeographicConfig};
// Configure witness selection with geographic constraints
let config = GeographicConfig {
min_regions: 3, // Minimum distinct regions
max_per_region: 2, // Maximum witnesses per region
prefer_low_latency: true, // Optimize for performance
exclude_same_asn: true, // Avoid same network provider
};
let selector = WitnessSelector::with_geographic_config(config);
// Select geographically diverse witnesses for a DHT key
let witnesses = selector.select_witnesses(
&key,
required_count,
&candidate_nodes,
).await?;
Each witness signs attestations using ML-DSA-65 post-quantum signatures:
use saorsa_core::dht::witness::{WitnessSigner, Attestation};
// Create a witness attestation
let attestation = Attestation {
operation_id: operation.id(),
key: key.clone(),
value_hash: blake3::hash(&value),
witness_id: my_node_id,
timestamp: SystemTime::now(),
geographic_region: my_region,
};
// Sign with ML-DSA-65 (post-quantum secure)
let signed = signer.sign_attestation(&attestation).await?;
use saorsa_core::dht::witness::WitnessVerifier;
// Verify a quorum of witness attestations
let verifier = WitnessVerifier::new(trust_provider);
// Verify attestations meet quorum requirements
let result = verifier.verify_quorum(
&attestations,
required_quorum, // e.g., 2/3 of witnesses
geographic_diversity, // require regional spread
).await?;
match result {
QuorumResult::Valid => {
// Operation is valid, proceed
}
QuorumResult::InsufficientWitnesses => {
// Not enough attestations, retry
}
QuorumResult::GeographicViolation => {
// Witnesses too concentrated, reselect
}
QuorumResult::InvalidSignatures => {
// Cryptographic verification failed
}
}
| Property | Guarantee |
|---|---|
| Byzantine Tolerance | Tolerates f malicious nodes in 3f+1 system |
| Geographic Spread | Minimum 3 distinct regions for attestation |
| Post-Quantum Security | ML-DSA-65 signatures (NIST Level 3) |
| Sybil Resistance | Geographic diversity prevents identity flooding |
| Forward Secrecy | Each operation uses unique attestation context |
| Non-Repudiation | Signed attestations provide audit trail |
Witness behavior feeds into the EigenTrust reputation system:
// Witness performance affects trust scores
trust_provider.record_witness_behavior(
witness_id,
WitnessBehavior::ValidAttestation,
);
// Low-trust nodes are excluded from witness selection
let eligible_witnesses = candidates
.iter()
.filter(|n| trust_provider.get_trust(&n.id) > MIN_WITNESS_TRUST)
.collect();
Saorsa Core provides a unique WebRTC-over-QUIC bridge that combines the real-time capabilities of WebRTC with the performance and reliability of QUIC transport. This allows for high-quality media streaming with improved NAT traversal and congestion control.
use saorsa_core::messaging::{
WebRtcQuicBridge, QuicMediaStreamManager, StreamConfig, StreamType, QosParameters
};
use saorsa_core::transport::ant_quic_adapter::P2PNetworkNode;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create network node
let node = Arc::new(P2PNetworkNode::new("127.0.0.1:0".parse()?).await?);
// Create WebRTC-QUIC bridge
let bridge = WebRtcQuicBridge::new(node).await?;
// Create stream manager for bandwidth management
let manager = QuicMediaStreamManager::new(2000); // 2 Mbps
manager.start_background_tasks().await?;
// Connect to peer
let peer_addr = "192.168.1.100:9000".parse()?;
let peer_id = bridge.connect_peer(peer_addr).await?;
// Configure audio stream
let audio_config = StreamConfig {
stream_type: StreamType::Audio,
codec: "opus".to_string(),
bitrate_kbps: 64,
sample_rate: Some(48000),
resolution: None,
};
bridge.add_stream(peer_id, StreamType::Audio, audio_config).await?;
// Configure video stream
let video_config = StreamConfig {
stream_type: StreamType::Video,
codec: "h264".to_string(),
bitrate_kbps: 1000,
sample_rate: None,
resolution: Some((1280, 720)),
};
bridge.add_stream(peer_id, StreamType::Video, video_config).await?;
// Set QoS parameters
manager.set_qos_params(StreamType::Audio, QosParameters::audio()).await;
manager.set_qos_params(StreamType::Video, QosParameters::video()).await;
// Start receiving packets
let mut receiver = bridge.start_receiving().await?;
// Handle incoming packets
tokio::spawn(async move {
while let Some((peer_id, packet)) = receiver.recv().await {
println!("Received {} packet from {}", packet.stream_type, peer_id);
// Process packet...
}
});
Ok(())
}
use saorsa_core::messaging::RtpPacket;
// Create and send RTP packets
async fn send_media_packets(
bridge: &WebRtcQuicBridge,
peer_id: PeerId,
) -> Result<()> {
// Audio packet (Opus codec)
let audio_packet = RtpPacket::new(
96, // Payload type (Opus)
1001, // Sequence number
48000, // Timestamp (48kHz sample rate)
0x12345678, // SSRC identifier
vec![0xAA; 160], // Opus frame data (20ms @ 48kHz)
StreamType::Audio,
);
bridge.send_rtp_packet(peer_id, audio_packet).await?;
// Video packet (H.264 codec)
let video_packet = RtpPacket::new(
97, // Payload type (H.264)
2001, // Sequence number
90000, // Timestamp (90kHz for video)
0x87654321, // SSRC identifier
vec![0xBB; 1200], // H.264 NAL unit
StreamType::Video,
);
bridge.send_rtp_packet(peer_id, video_packet).await?;
Ok(())
}
use saorsa_core::messaging::QosParameters;
// Configure QoS for different stream types
let audio_qos = QosParameters {
priority: 3, // Highest priority
max_latency_ms: 20, // Low latency for real-time audio
max_jitter_ms: 5, // Minimal jitter tolerance
target_bitrate_kbps: 64,
max_bitrate_kbps: 128,
min_bitrate_kbps: 32,
loss_threshold: 1.0, // 1% packet loss threshold
};
let video_qos = QosParameters {
priority: 2, // Medium priority
max_latency_ms: 100, // Higher latency tolerance
max_jitter_ms: 20, // More jitter tolerance
target_bitrate_kbps: 1000,
max_bitrate_kbps: 2000,
min_bitrate_kbps: 200,
loss_threshold: 3.0, // 3% packet loss threshold
};
manager.set_qos_params(StreamType::Audio, audio_qos).await;
manager.set_qos_params(StreamType::Video, video_qos).await;
// Check for bandwidth adaptation recommendations
if let Some(adjustment) = manager.check_bandwidth_adaptation().await {
match adjustment {
BandwidthAdjustment::Increase { current, recommended } => {
println!("Increase bandwidth: {} -> {} kbps", current, recommended);
// Adjust encoder settings...
}
BandwidthAdjustment::Decrease { current, recommended } => {
println!("Decrease bandwidth: {} -> {} kbps", current, recommended);
// Reduce quality or bitrate...
}
}
}
// Check transmission capacity
let can_send_hd = manager.can_transmit(1500).await; // 1.5KB HD frame
if !can_send_hd {
// Switch to lower resolution or quality
}
// Get peer statistics
if let Some(stats) = bridge.get_peer_stats(peer_id).await {
println!("Packets sent: {}", stats.packets_sent);
println!("Packets received: {}", stats.packets_received);
println!("Bytes transferred: {}", stats.bytes_sent);
println!("Active streams: {}", stats.streams.len());
}
// Get stream-specific statistics
let stream_stats = manager.get_all_stats().await;
for ((peer_id, stream_type), stats) in stream_stats {
println!("{:?} stream to {}:", stream_type, peer_id);
println!(" RTT: {}ms", stats.rtt_ms);
println!(" Loss: {:.2}%", stats.loss_percentage());
println!(" Throughput: {} kbps", stats.effective_bitrate_kbps());
}
// Configure multiple streams for comprehensive communication
bridge.add_stream(peer_id, StreamType::Audio, audio_config).await?;
bridge.add_stream(peer_id, StreamType::Video, video_config).await?;
bridge.add_stream(peer_id, StreamType::ScreenShare, screen_config).await?;
bridge.add_stream(peer_id, StreamType::Data, data_config).await?;
use saorsa_core::messaging::BridgeConfig;
let config = BridgeConfig {
jitter_buffer_size: 100, // 100 packets max
jitter_buffer_delay: Duration::from_millis(50), // 50ms buffer
peer_timeout: Duration::from_secs(30), // 30s peer timeout
cleanup_interval: Duration::from_secs(5), // Cleanup every 5s
max_packet_size: 1500, // MTU consideration
enable_adaptive_jitter: true, // Adaptive jitter buffering
};
let bridge = WebRtcQuicBridge::new_with_config(node, config).await?;
// Robust error handling
match bridge.send_rtp_packet(peer_id, packet).await {
Ok(_) => {
// Packet sent successfully
}
Err(e) => {
eprintln!("Failed to send packet: {}", e);
// Attempt reconnection if peer disconnected
if e.to_string().contains("not connected") {
match bridge.connect_peer(peer_addr).await {
Ok(new_peer_id) => {
// Reconfigure streams for new connection
configure_streams(&bridge, new_peer_id).await?;
}
Err(reconnect_err) => {
eprintln!("Reconnection failed: {}", reconnect_err);
}
}
}
}
}
Built-in media processing capabilities:
SQLite-based persistence with migrations:
use saorsa_core::storage::Database;
let db = Database::open("./data/node.db").await?;
db.store_message(&message).await?;
Location-aware networking:
# Standard build
cargo build --release
# With all features
cargo build --all-features
# Feature-specific build
cargo build --features "dht,quantum-resistant"
# Unit tests
cargo test
# Integration tests
cargo test --test '*'
# Property-based tests
cargo test --features "proptest"
cargo clippy --all-features -- -D warnings
cargo fmt --all
cargo fmt for formattingcargo clippy passesThis project is dual-licensed:
For commercial licensing, contact: david@saorsalabs.com
tokio - Async runtimefutures - Future utilitiesserde - Serializationanyhow - Error handlingtracing - Loggingant-quic (0.10.0+) - QUIC transport with P2P NAT traversalfour-word-networking - Human-readable addressesrustls - TLS supportsaorsa-pqc - Post-quantum cryptography (ML-DSA, ML-KEM, ChaCha20-Poly1305)blake3 - Hashingrand - Random number generationsqlx - Database operationslru - LRU cachingreed-solomon-erasure - Error correctionwebrtc - WebRTC implementationimage - Image processingsymphonia - Audio codecsrodio - Audio playbackSee Cargo.toml for complete dependency list.
See CHANGELOG.md for version history.
Saorsa Labs Limited - Building the decentralized future