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