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// Re-export main types
171pub use address::{AddressBook, NetworkAddress};
172
173// New spec-compliant API exports
174pub use auth::{
175    DelegatedWriteAuth, MlsWriteAuth, PubKey, Sig, SingleWriteAuth, ThresholdWriteAuth, WriteAuth,
176};
177pub use bootstrap::{BootstrapCache, BootstrapManager, CacheConfig, ContactEntry};
178pub use dht::{Key, Record};
179pub use dht_network_manager::{
180    BootstrapNode, DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation,
181    DhtNetworkResult, DhtPeerInfo,
182};
183pub use encrypted_key_storage::{
184    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
185    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
186};
187pub use error::{P2PError, P2pResult as Result};
188pub use events::{Subscription, TopologyEvent, device_subscribe, dht_watch, subscribe_topology};
189pub use fwid::{FourWordsV1, Key as FwKey, fw_check, fw_to_key};
190pub use health::{
191    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
192    HealthServer, HealthStatus, PrometheusExporter,
193};
194pub use key_derivation::{
195    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
196    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
197};
198pub use monotonic_counter::{
199    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
200    SequenceValidationResult,
201};
202pub use network::{NodeBuilder, NodeConfig, P2PEvent, P2PNode};
203pub use telemetry::{Metrics, StreamClass, record_lookup, record_timeout, telemetry};
204// Back-compat exports for tests
205pub use config::Config;
206pub use network::P2PNode as Node;
207pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
208pub use persistent_state::{
209    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
210    StateChangeEvent, StateConfig, TransactionType, WalEntry,
211};
212pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
213pub use secure_memory::{
214    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
215    secure_string_with_capacity, secure_vec_with_capacity,
216};
217pub use validation::{
218    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
219    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
220    validate_message_size, validate_network_address, validate_peer_id,
221};
222
223// Enhanced identity removed
224
225// Storage exports
226pub use storage::{FileChunker, StorageManager}; // SyncManager temporarily disabled
227
228// Chat exports
229pub use chat::{Call, Channel, ChannelId, ChannelType, ChatManager, Message, MessageId, Thread};
230
231// Discuss exports
232pub use discuss::{
233    Badge, Category, CategoryId, DiscussManager, Poll, Reply, ReplyId, Topic, TopicId, UserStats,
234};
235
236// Projects exports
237pub use projects::{
238    Document, DocumentId, Folder, Project, ProjectAnalytics, ProjectId, ProjectsManager,
239    WorkflowState,
240};
241
242// Threshold exports
243pub use threshold::{
244    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
245};
246
247// Post-quantum cryptography exports (using ant-quic types exclusively)
248pub use quantum_crypto::{
249    CryptoCapabilities,
250    KemAlgorithm,
251    NegotiatedAlgorithms,
252    ProtocolVersion,
253    // Core types and errors (compatibility layer only)
254    QuantumCryptoError,
255    SignatureAlgorithm,
256    // Functions (compatibility layer only)
257    negotiate_algorithms,
258};
259
260// Saorsa-PQC exports (primary and only post-quantum crypto types)
261pub use quantum_crypto::{
262    // Symmetric encryption (quantum-resistant)
263    ChaCha20Poly1305Cipher,
264    // Encrypted message types
265    EncryptedMessage,
266    // Hybrid modes (classical + post-quantum)
267    HybridKem,
268    HybridKemCiphertext,
269    HybridKemPublicKey,
270    HybridKemSecretKey,
271    HybridPublicKeyEncryption,
272
273    // HybridSignature,
274    HybridSignaturePublicKey,
275    HybridSignatureSecretKey,
276    HybridSignatureValue,
277
278    MlDsa65,
279
280    MlDsaOperations,
281
282    // Use ant-quic types for better trait implementations
283    MlDsaPublicKey as AntMlDsaPublicKey,
284    MlDsaSecretKey as AntMlDsaSecretKey,
285    MlDsaSignature as AntMlDsaSignature,
286    // Algorithm implementations
287    MlKem768,
288    MlKemCiphertext,
289    // Core traits for operations
290    MlKemOperations,
291    // Key types
292    MlKemPublicKey,
293    MlKemSecretKey,
294    // Errors and results
295    PqcError,
296    SaorsaPqcResult,
297
298    SharedSecret,
299    SymmetricEncryptedMessage,
300
301    SymmetricError,
302    SymmetricKey,
303
304    // Library initialization
305    saorsa_pqc_init,
306};
307
308// Legacy ant-quic integration (for backward compatibility only)
309pub use quantum_crypto::ant_quic_integration::{
310    // Configuration functions (deprecated - migrate to saorsa-pqc)
311    create_default_pqc_config,
312    create_pqc_only_config,
313};
314
315// Legacy types (deprecated - migrate to saorsa-pqc equivalents)
316pub use quantum_crypto::types::{
317    FrostCommitment,
318    FrostGroupPublicKey,
319    FrostKeyShare,
320    // FROST threshold signatures (may need migration to saorsa-pqc later)
321    FrostPublicKey,
322    FrostSignature,
323    // Session and group management types (still needed)
324    GroupId,
325    HandshakeParameters,
326
327    ParticipantId,
328    PeerId as QuantumPeerId,
329    QuantumPeerIdentity,
330    SecureSession,
331    SessionId,
332    SessionState,
333};
334
335// Placement system exports
336pub use placement::{
337    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
338    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
339    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
340    WeightedPlacementStrategy,
341};
342
343// Network address types
344/// Peer identifier used throughout Saorsa
345///
346/// Currently implemented as a String for simplicity, but can be enhanced
347/// with cryptographic verification in future versions.
348pub type PeerId = String;
349
350/// Network address used for peer-to-peer communication
351///
352/// Supports both traditional IP:port format and human-readable four-word format.
353pub type Multiaddr = NetworkAddress;
354
355/// Saorsa Core version
356pub const VERSION: &str = env!("CARGO_PKG_VERSION");