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: saorsalabs@gmail.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/// BGP-based GeoIP provider using open-source routing data
98pub mod bgp_geo_provider;
99
100/// User identity and privacy system
101pub mod identity;
102
103/// DHT-based storage for multi-device sync
104pub mod storage;
105
106// Re-export main API functions
107pub use api::{
108    GroupKeyPair,
109    MemberRef,
110    get_data,
111    get_identity,
112    get_presence,
113    // Group API
114    group_identity_canonical_sign_bytes,
115    group_identity_create,
116    group_identity_fetch,
117    group_identity_publish,
118    group_identity_update_members_signed,
119    identity_fetch,
120    register_headless,
121    // Identity API
122    register_identity,
123    // Presence API
124    register_presence,
125    set_active_device,
126    set_dht_client,
127    // Storage API
128    store_data,
129    store_dyad,
130    store_with_fec,
131};
132
133/// Chat system (Slack-like)
134pub mod chat;
135
136/// Rich messaging system (WhatsApp/Slack-style)
137pub mod messaging;
138
139/// Discuss system (Discourse-like)
140pub mod discuss;
141
142/// Projects system with hierarchical organization
143pub mod projects;
144
145/// Threshold cryptography for group operations
146pub mod threshold;
147
148/// Quantum-resistant cryptography
149pub mod quantum_crypto;
150
151/// Utility functions and types
152pub mod utils;
153
154/// Validation framework for input sanitization and rate limiting
155pub mod validation;
156
157/// Unified rate limiting engine
158pub mod rate_limit;
159
160/// Production hardening features
161pub mod production;
162
163/// Bootstrap cache for decentralized peer discovery
164pub mod bootstrap;
165
166/// Error types
167pub mod error;
168
169/// Peer record system for DHT-based peer discovery
170pub mod peer_record;
171
172/// Monotonic counter system for replay attack prevention
173pub mod monotonic_counter;
174
175/// Secure memory management for cryptographic operations
176pub mod secure_memory;
177
178/// Hierarchical key derivation system
179pub mod key_derivation;
180
181/// Encrypted key storage with Argon2id and ChaCha20-Poly1305
182pub mod encrypted_key_storage;
183
184/// Persistent state management with crash recovery
185pub mod persistent_state;
186
187/// Adaptive P2P network implementation
188pub mod adaptive;
189
190/// Configuration management system
191pub mod config;
192
193/// Health check system for monitoring and metrics
194pub mod health;
195
196/// Geographic-aware networking enhancements for P2P routing optimization
197pub mod geographic_enhanced_network;
198
199/// Placement Loop & Storage Orchestration System
200pub mod placement;
201
202/// Virtual disk for encrypted file storage
203pub mod virtual_disk;
204
205/// Entity-based system for unified identity, storage, and collaboration
206pub mod entities;
207
208/// Auto-upgrade system for cross-platform binary updates
209pub mod upgrade;
210
211/// Mock DHT for testing
212#[cfg(any(test, feature = "test-utils"))]
213pub mod mock_dht;
214
215// Re-export main types
216pub use address::{AddressBook, NetworkAddress};
217pub use address_book::{
218    address_book, get_user_by_four_words, get_user_four_words, register_user_address,
219};
220pub use identity::FourWordAddress;
221
222// New spec-compliant API exports
223pub use auth::{
224    DelegatedWriteAuth, MlsWriteAuth, PubKey, Sig, SingleWriteAuth, ThresholdWriteAuth, WriteAuth,
225};
226pub use bootstrap::{BootstrapCache, BootstrapManager, CacheConfig, ContactEntry};
227pub use dht::{Key, Record};
228pub use dht_network_manager::{
229    BootstrapNode, DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation,
230    DhtNetworkResult, DhtPeerInfo,
231};
232pub use encrypted_key_storage::{
233    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
234    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
235};
236pub use error::{P2PError, P2pResult as Result};
237pub use events::{Subscription, TopologyEvent, device_subscribe, dht_watch, subscribe_topology};
238pub use fwid::{FourWordsV1, Key as FwKey, fw_check, fw_to_key};
239pub use health::{
240    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
241    HealthServer, HealthStatus, PrometheusExporter,
242};
243pub use key_derivation::{
244    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
245    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
246};
247pub use monotonic_counter::{
248    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
249    SequenceValidationResult,
250};
251pub use network::{ConnectionStatus, NodeBuilder, NodeConfig, P2PEvent, P2PNode, PeerInfo};
252pub use telemetry::{Metrics, StreamClass, record_lookup, record_timeout, telemetry};
253// Back-compat exports for tests
254pub use config::Config;
255pub use network::P2PNode as Node;
256pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
257pub use persistent_state::{
258    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
259    StateChangeEvent, StateConfig, TransactionType, WalEntry,
260};
261pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
262pub use secure_memory::{
263    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
264    secure_string_with_capacity, secure_vec_with_capacity,
265};
266pub use validation::{
267    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
268    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
269    validate_message_size, validate_network_address, validate_peer_id,
270};
271
272// Join rate limiting for Sybil protection
273pub use rate_limit::{
274    JoinRateLimitError, JoinRateLimiter, JoinRateLimiterConfig, extract_ipv4_subnet_8,
275    extract_ipv4_subnet_16, extract_ipv4_subnet_24, extract_ipv6_subnet_32, extract_ipv6_subnet_48,
276    extract_ipv6_subnet_64,
277};
278
279// Enhanced identity removed
280
281// Storage exports
282pub use storage::{FileChunker, StorageManager}; // SyncManager temporarily disabled
283
284// Chat exports
285pub use chat::{Call, Channel, ChannelId, ChannelType, ChatManager, Message, MessageId, Thread};
286
287// Discuss exports
288pub use discuss::{
289    Badge, Category, CategoryId, DiscussManager, Poll, Reply, ReplyId, Topic, TopicId, UserStats,
290};
291
292// Projects exports
293pub use projects::{
294    Document, DocumentId, Folder, Project, ProjectAnalytics, ProjectId, ProjectsManager,
295    WorkflowState,
296};
297
298// Threshold exports
299pub use threshold::{
300    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
301};
302
303// Post-quantum cryptography exports (using ant-quic types exclusively)
304pub use quantum_crypto::{
305    CryptoCapabilities,
306    KemAlgorithm,
307    NegotiatedAlgorithms,
308    ProtocolVersion,
309    // Core types and errors (compatibility layer only)
310    QuantumCryptoError,
311    SignatureAlgorithm,
312    // Functions (compatibility layer only)
313    negotiate_algorithms,
314};
315
316// Saorsa-PQC exports (primary and only post-quantum crypto types)
317pub use quantum_crypto::{
318    // Symmetric encryption (quantum-resistant)
319    ChaCha20Poly1305Cipher,
320    // Encrypted message types
321    EncryptedMessage,
322    // Hybrid modes (classical + post-quantum)
323    HybridKem,
324    HybridKemCiphertext,
325    HybridKemPublicKey,
326    HybridKemSecretKey,
327    HybridPublicKeyEncryption,
328
329    // HybridSignature,
330    HybridSignaturePublicKey,
331    HybridSignatureSecretKey,
332    HybridSignatureValue,
333
334    MlDsa65,
335
336    MlDsaOperations,
337
338    // Use ant-quic types for better trait implementations
339    MlDsaPublicKey as AntMlDsaPublicKey,
340    MlDsaSecretKey as AntMlDsaSecretKey,
341    MlDsaSignature as AntMlDsaSignature,
342    // Algorithm implementations
343    MlKem768,
344    MlKemCiphertext,
345    // Core traits for operations
346    MlKemOperations,
347    // Key types
348    MlKemPublicKey,
349    MlKemSecretKey,
350    // Errors and results
351    PqcError,
352    SaorsaPqcResult,
353
354    SharedSecret,
355    SymmetricEncryptedMessage,
356
357    SymmetricError,
358    SymmetricKey,
359
360    // Library initialization
361    saorsa_pqc_init,
362};
363
364// Legacy ant-quic integration (for backward compatibility only)
365pub use quantum_crypto::ant_quic_integration::{
366    // Configuration functions (deprecated - migrate to saorsa-pqc)
367    create_default_pqc_config,
368    create_pqc_only_config,
369};
370
371// Legacy types (deprecated - migrate to saorsa-pqc equivalents)
372pub use quantum_crypto::types::{
373    FrostCommitment,
374    FrostGroupPublicKey,
375    FrostKeyShare,
376    // FROST threshold signatures (may need migration to saorsa-pqc later)
377    FrostPublicKey,
378    FrostSignature,
379    // Session and group management types (still needed)
380    GroupId,
381    HandshakeParameters,
382
383    ParticipantId,
384    PeerId as QuantumPeerId,
385    QuantumPeerIdentity,
386    SecureSession,
387    SessionId,
388    SessionState,
389};
390
391// Placement system exports
392pub use placement::{
393    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
394    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
395    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
396    WeightedPlacementStrategy,
397};
398
399// Network address types
400/// Peer identifier used throughout Saorsa
401///
402/// Currently implemented as a String for simplicity, but should be enhanced
403/// with cryptographic verification and validation in future versions.
404///
405/// TODO: Replace with a proper newtype that includes validation:
406/// - Non-empty string validation
407/// - Character set validation (alphanumeric + - _)
408/// - Length limits (max 256 characters)
409/// - Optional cryptographic verification
410pub type PeerId = String;
411
412/// Network address used for peer-to-peer communication
413///
414/// Supports both traditional IP:port format and human-readable four-word format.
415pub type Multiaddr = NetworkAddress;
416
417/// Saorsa Core version
418pub const VERSION: &str = env!("CARGO_PKG_VERSION");
419
420// Upgrade system exports
421pub use upgrade::{
422    ApplierConfig, ApplyResult, BackupMetadata, DownloadProgress, Downloader, DownloaderConfig,
423    PinnedKey, Platform as UpgradePlatform, PlatformBinary, Release, ReleaseChannel,
424    RollbackManager, SignatureVerifier, StagedUpdate, StagedUpdateManager, UpdateConfig,
425    UpdateConfigBuilder, UpdateInfo, UpdateManager, UpdateManifest, UpdatePolicy, UpgradeError,
426    UpgradeEvent, create_applier,
427};