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