saorsa_core/
lib.rs

1// Copyright 2024 Saorsa Labs Limited
2//
3// This software is dual-licensed under:
4// - GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)
5// - Commercial License
6//
7// For AGPL-3.0 license, see LICENSE-AGPL-3.0
8// For commercial licensing, contact: david@saorsalabs.com
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under these licenses is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
14// Enforce no unwrap/expect/panic in production code only (tests can use them)
15#![cfg_attr(not(test), warn(clippy::unwrap_used))]
16#![cfg_attr(not(test), warn(clippy::expect_used))]
17#![cfg_attr(not(test), warn(clippy::panic))]
18// Allow unused_async as many functions are async for API consistency
19#![allow(clippy::unused_async)]
20
21//! # Saorsa Core
22//!
23//! A next-generation peer-to-peer networking foundation built in Rust.
24//!
25//! ## Features
26//!
27//! - QUIC-based transport with NAT traversal
28//! - IPv4-first with simple addressing
29//! - Kademlia DHT for distributed routing
30//! - Four-word human-readable addresses
31//!
32//! ## Example
33//!
34//! ```rust,ignore
35//! use saorsa_core::{P2PNode, NodeConfig, NetworkAddress};
36//! use std::str::FromStr;
37//!
38//! #[tokio::main]
39//! async fn main() -> anyhow::Result<()> {
40//!     let addr = "127.0.0.1:9000".parse::<NetworkAddress>()?;
41//!     let node = P2PNode::builder()
42//!         .listen_on(addr)
43//!         .with_mcp_server()
44//!         .build()
45//!         .await?;
46//!
47//!     node.run().await?;
48//!     Ok(())
49//! }
50//! ```
51
52#![allow(missing_docs)]
53#![allow(missing_debug_implementations)]
54#![warn(rust_2018_idioms)]
55
56/// Four-word identifier system
57pub mod fwid;
58
59/// Public API matching the spec
60pub mod api;
61
62/// Network address types
63pub mod address;
64/// User directory mapping (UserId <-> FourWordAddress)
65pub mod address_book;
66
67/// Network core functionality
68pub mod network;
69
70/// Distributed Hash Table implementation
71pub mod dht;
72
73/// DHT Network Integration Manager
74pub mod dht_network_manager;
75
76/// Transport layer (QUIC, TCP)
77pub mod transport;
78
79/// Authentication system for multi-writer records
80pub mod auth;
81
82/// Async event bus for watches and state changes
83pub mod events;
84/// MLS verifier adapter and proof format
85pub mod mls;
86/// Shared simple structs
87pub mod types;
88
89/// Telemetry for metrics and health signals
90pub mod telemetry;
91
92// MCP removed; will be redesigned later
93
94/// Security and cryptography
95pub mod security;
96
97/// Entangled Attestation system for software integrity verification
98pub mod attestation;
99
100/// BGP-based GeoIP provider using open-source routing data
101pub mod bgp_geo_provider;
102
103/// User identity and privacy system
104pub mod identity;
105
106/// DHT-based storage for multi-device sync
107pub mod storage;
108
109// Re-export main API functions
110pub use api::{
111    GroupKeyPair,
112    MemberRef,
113    clear_dht_client,
114    get_data,
115    get_identity,
116    get_presence,
117    // Group API
118    group_identity_canonical_sign_bytes,
119    group_identity_create,
120    group_identity_fetch,
121    group_identity_publish,
122    group_identity_update_members_signed,
123    identity_fetch,
124    register_headless,
125    // Identity API
126    register_identity,
127    // Presence API
128    register_presence,
129    set_active_device,
130    set_dht_client,
131    // Storage API
132    store_data,
133    store_dyad,
134    store_with_fec,
135};
136
137/// Chat system (Slack-like)
138pub mod chat;
139
140/// Rich messaging system (WhatsApp/Slack-style)
141pub mod messaging;
142
143/// Discuss system (Discourse-like)
144pub mod discuss;
145
146/// Projects system with hierarchical organization
147pub mod projects;
148
149/// Threshold cryptography for group operations
150pub mod threshold;
151
152/// Quantum-resistant cryptography
153pub mod quantum_crypto;
154
155/// Utility functions and types
156pub mod utils;
157
158/// Validation framework for input sanitization and rate limiting
159pub mod validation;
160
161/// Unified rate limiting engine
162pub mod rate_limit;
163
164/// Production hardening features
165pub mod production;
166
167/// Bootstrap cache for decentralized peer discovery
168pub mod bootstrap;
169
170/// Error types
171pub mod error;
172
173/// Peer record system for DHT-based peer discovery
174pub mod peer_record;
175
176/// Monotonic counter system for replay attack prevention
177pub mod monotonic_counter;
178
179/// Secure memory management for cryptographic operations
180pub mod secure_memory;
181
182/// Hierarchical key derivation system
183pub mod key_derivation;
184
185/// Encrypted key storage with Argon2id and ChaCha20-Poly1305
186pub mod encrypted_key_storage;
187
188/// Persistent state management with crash recovery
189pub mod persistent_state;
190
191/// Adaptive P2P network implementation
192pub mod adaptive;
193
194/// Configuration management system
195pub mod config;
196pub mod control;
197
198/// Health check system for monitoring and metrics
199pub mod health;
200
201/// Geographic-aware networking enhancements for P2P routing optimization
202pub mod geographic_enhanced_network;
203
204/// Placement Loop & Storage Orchestration System
205pub mod placement;
206
207/// Auto-upgrade system for cross-platform binary updates
208pub mod upgrade;
209
210// Re-export main types
211pub use address::{AddressBook, NetworkAddress};
212pub use address_book::{
213    address_book, get_user_by_four_words, get_user_four_words, register_user_address,
214};
215pub use identity::FourWordAddress;
216
217// New spec-compliant API exports
218pub use auth::{
219    DelegatedWriteAuth, MlsWriteAuth, PubKey, Sig, SingleWriteAuth, ThresholdWriteAuth, WriteAuth,
220};
221pub use bootstrap::{BootstrapCache, BootstrapManager, CacheConfig, ContactEntry};
222pub use dht::{Key, Record};
223pub use dht_network_manager::{
224    BootstrapNode, DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation,
225    DhtNetworkResult, DhtPeerInfo,
226};
227pub use encrypted_key_storage::{
228    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
229    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
230};
231pub use error::{P2PError, P2pResult as Result};
232pub use events::{Subscription, TopologyEvent, device_subscribe, dht_watch, subscribe_topology};
233pub use fwid::{FourWordsV1, Key as FwKey, fw_check, fw_to_key};
234pub use health::{
235    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
236    HealthServer, HealthStatus, PrometheusExporter,
237};
238pub use key_derivation::{
239    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
240    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
241};
242pub use monotonic_counter::{
243    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
244    SequenceValidationResult,
245};
246pub use network::{ConnectionStatus, NodeBuilder, NodeConfig, P2PEvent, P2PNode, PeerInfo};
247pub use telemetry::{Metrics, StreamClass, record_lookup, record_timeout, telemetry};
248// Back-compat exports for tests
249pub use config::Config;
250pub use network::P2PNode as Node;
251pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
252pub use persistent_state::{
253    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
254    StateChangeEvent, StateConfig, TransactionType, WalEntry,
255};
256pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
257pub use secure_memory::{
258    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
259    secure_string_with_capacity, secure_vec_with_capacity,
260};
261pub use validation::{
262    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
263    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
264    validate_message_size, validate_network_address, validate_peer_id,
265};
266
267// Join rate limiting for Sybil protection
268pub use rate_limit::{
269    JoinRateLimitError, JoinRateLimiter, JoinRateLimiterConfig, extract_ipv4_subnet_8,
270    extract_ipv4_subnet_16, extract_ipv4_subnet_24, extract_ipv6_subnet_32, extract_ipv6_subnet_48,
271    extract_ipv6_subnet_64,
272};
273
274// Security and anti-Sybil exports (includes testnet configurations)
275pub use dht::node_age_verifier::{
276    AgeVerificationResult, NodeAgeCategory, NodeAgeConfig, NodeAgeRecord, NodeAgeStats,
277    NodeAgeVerifier, OperationType,
278};
279pub use security::{
280    DiversityStats, GeoInfo, GeoProvider, IPAnalysis, IPDiversityConfig, IPDiversityEnforcer,
281    IPv4NodeID, IPv6NodeID, NodeReputation, ReputationManager, StubGeoProvider,
282};
283
284// Enhanced identity removed
285
286// Storage exports
287pub use storage::{FileChunker, StorageManager}; // SyncManager temporarily disabled
288
289// Chat exports
290pub use chat::{Call, Channel, ChannelId, ChannelType, ChatManager, Message, MessageId, Thread};
291
292// Discuss exports
293pub use discuss::{
294    Badge, Category, CategoryId, DiscussManager, Poll, Reply, ReplyId, Topic, TopicId, UserStats,
295};
296
297// Projects exports
298pub use projects::{
299    Document, DocumentId, Folder, Project, ProjectAnalytics, ProjectId, ProjectsManager,
300    WorkflowState,
301};
302
303// Threshold exports
304pub use threshold::{
305    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
306};
307
308// Post-quantum cryptography exports (using ant-quic types exclusively)
309pub use quantum_crypto::{
310    CryptoCapabilities,
311    KemAlgorithm,
312    NegotiatedAlgorithms,
313    ProtocolVersion,
314    // Core types and errors (compatibility layer only)
315    QuantumCryptoError,
316    SignatureAlgorithm,
317    // Functions (compatibility layer only)
318    negotiate_algorithms,
319};
320
321// Saorsa-PQC exports (primary and only post-quantum crypto types)
322pub use quantum_crypto::{
323    // Symmetric encryption (quantum-resistant)
324    ChaCha20Poly1305Cipher,
325    // Encrypted message types
326    EncryptedMessage,
327    // Hybrid modes (classical + post-quantum)
328    HybridKem,
329    HybridKemCiphertext,
330    HybridKemPublicKey,
331    HybridKemSecretKey,
332    HybridPublicKeyEncryption,
333
334    // HybridSignature,
335    HybridSignaturePublicKey,
336    HybridSignatureSecretKey,
337    HybridSignatureValue,
338
339    MlDsa65,
340
341    MlDsaOperations,
342
343    // Use ant-quic types for better trait implementations
344    MlDsaPublicKey as AntMlDsaPublicKey,
345    MlDsaSecretKey as AntMlDsaSecretKey,
346    MlDsaSignature as AntMlDsaSignature,
347    // Algorithm implementations
348    MlKem768,
349    MlKemCiphertext,
350    // Core traits for operations
351    MlKemOperations,
352    // Key types
353    MlKemPublicKey,
354    MlKemSecretKey,
355    // Errors and results
356    PqcError,
357    SaorsaPqcResult,
358
359    SharedSecret,
360    SymmetricEncryptedMessage,
361
362    SymmetricError,
363    SymmetricKey,
364
365    // Library initialization
366    saorsa_pqc_init,
367};
368
369// Legacy ant-quic integration (for backward compatibility only)
370pub use quantum_crypto::ant_quic_integration::{
371    // Configuration functions (deprecated - migrate to saorsa-pqc)
372    create_default_pqc_config,
373    create_pqc_only_config,
374};
375
376// Legacy types (deprecated - migrate to saorsa-pqc equivalents)
377pub use quantum_crypto::types::{
378    FrostCommitment,
379    FrostGroupPublicKey,
380    FrostKeyShare,
381    // FROST threshold signatures (may need migration to saorsa-pqc later)
382    FrostPublicKey,
383    FrostSignature,
384    // Session and group management types (still needed)
385    GroupId,
386    HandshakeParameters,
387
388    ParticipantId,
389    PeerId as QuantumPeerId,
390    QuantumPeerIdentity,
391    SecureSession,
392    SessionId,
393    SessionState,
394};
395
396// Placement system exports
397pub use placement::{
398    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
399    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
400    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
401    WeightedPlacementStrategy,
402};
403
404// Network address types
405/// Peer identifier used throughout Saorsa
406///
407/// Currently implemented as a String for simplicity, but should be enhanced
408/// with cryptographic verification and validation in future versions.
409///
410/// TODO: Replace with a proper newtype that includes validation:
411/// - Non-empty string validation
412/// - Character set validation (alphanumeric + - _)
413/// - Length limits (max 256 characters)
414/// - Optional cryptographic verification
415pub type PeerId = String;
416
417/// Network address used for peer-to-peer communication
418///
419/// Supports both traditional IP:port format and human-readable four-word format.
420pub type Multiaddr = NetworkAddress;
421
422/// Saorsa Core version
423pub const VERSION: &str = env!("CARGO_PKG_VERSION");
424
425// Attestation system exports
426pub use attestation::{
427    AttestationConfig, AttestationError, AttestationResult, EnforcementMode, EntangledId,
428    SunsetTimestamp,
429};
430
431// Upgrade system exports
432pub use upgrade::{
433    ApplierConfig, ApplyResult, BackupMetadata, DownloadProgress, Downloader, DownloaderConfig,
434    PinnedKey, Platform as UpgradePlatform, PlatformBinary, Release, ReleaseChannel,
435    RollbackManager, SignatureVerifier, StagedUpdate, StagedUpdateManager, UpdateConfig,
436    UpdateConfigBuilder, UpdateInfo, UpdateManager, UpdateManifest, UpdatePolicy, UpgradeError,
437    UpgradeEvent, create_applier,
438};