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