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//! - Built-in MCP server for AI capabilities
31//! - Four-word human-readable addresses
32//!
33//! ## Example
34//!
35//! ```rust,ignore
36//! use saorsa_core::{P2PNode, NodeConfig, NetworkAddress};
37//! use std::str::FromStr;
38//!
39//! #[tokio::main]
40//! async fn main() -> anyhow::Result<()> {
41//!     let addr = "127.0.0.1:9000".parse::<NetworkAddress>()?;
42//!     let node = P2PNode::builder()
43//!         .listen_on(addr)
44//!         .with_mcp_server()
45//!         .build()
46//!         .await?;
47//!     
48//!     node.run().await?;
49//!     Ok(())
50//! }
51//! ```
52
53#![allow(missing_docs)]
54#![allow(missing_debug_implementations)]
55#![warn(rust_2018_idioms)]
56
57/// Network address types
58pub mod address;
59
60/// Network core functionality
61pub mod network;
62
63/// Distributed Hash Table implementation
64pub mod dht;
65
66/// DHT Network Integration Manager
67pub mod dht_network_manager;
68
69/// Transport layer (QUIC, TCP)
70pub mod transport;
71
72/// Model Context Protocol server
73pub mod mcp;
74
75/// Security and cryptography
76pub mod security;
77
78/// User identity and privacy system
79pub mod identity;
80
81/// DHT-based storage for multi-device sync
82pub mod storage;
83
84/// Chat system (Slack-like)
85pub mod chat;
86
87/// Rich messaging system (WhatsApp/Slack-style)
88pub mod messaging;
89
90/// Discuss system (Discourse-like)
91pub mod discuss;
92
93/// Projects system with hierarchical organization
94pub mod projects;
95
96/// Threshold cryptography for group operations
97pub mod threshold;
98
99/// Quantum-resistant cryptography
100pub mod quantum_crypto;
101
102/// Utility functions and types
103pub mod utils;
104
105/// Validation framework for input sanitization and rate limiting
106pub mod validation;
107
108/// Production hardening features
109pub mod production;
110
111/// Bootstrap cache for decentralized peer discovery
112pub mod bootstrap;
113
114/// Error types
115pub mod error;
116
117/// Peer record system for DHT-based peer discovery
118pub mod peer_record;
119
120/// Enhanced cryptographic signature verification system
121pub mod crypto_verify;
122
123/// Monotonic counter system for replay attack prevention
124pub mod monotonic_counter;
125
126/// Secure memory management for cryptographic operations
127pub mod secure_memory;
128
129/// Hierarchical key derivation system
130pub mod key_derivation;
131
132/// Encrypted key storage with Argon2id and AES-256-GCM
133pub mod encrypted_key_storage;
134
135/// Persistent state management with crash recovery
136pub mod persistent_state;
137
138/// Identity management system with Ed25519/X25519 key pairs
139pub mod identity_manager;
140
141/// Adaptive P2P network implementation
142pub mod adaptive;
143
144/// Configuration management system
145pub mod config;
146
147/// Health check system for monitoring and metrics
148pub mod health;
149
150/// Geographic-aware networking enhancements for P2P routing optimization
151pub mod geographic_enhanced_network;
152
153/// Placement Loop & Storage Orchestration System
154pub mod placement;
155
156// Re-export main types
157pub use address::{AddressBook, NetworkAddress};
158pub use bootstrap::{BootstrapCache, BootstrapManager, CacheConfig, ContactEntry};
159pub use crypto_verify::{
160    BatchVerificationRequest, BatchVerificationResult, EnhancedSignatureVerification,
161    EnhancedSignatureVerifier, VerificationStats,
162};
163pub use dht::{Key, Record};
164pub use dht_network_manager::{
165    BootstrapNode, DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation,
166    DhtNetworkResult, DhtPeerInfo,
167};
168pub use encrypted_key_storage::{
169    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
170    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
171};
172pub use error::{P2PError, P2pResult as Result};
173pub use health::{
174    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
175    HealthServer, HealthStatus, PrometheusExporter,
176};
177pub use identity_manager::{
178    Identity, IdentityCreationParams, IdentityKeyPair, IdentityManager, IdentityState,
179    IdentityStats, IdentitySyncPackage, IdentityUpdate, IdentityVerification,
180    RevocationCertificate, RevocationReason,
181};
182pub use key_derivation::{
183    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
184    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
185};
186pub use mcp::{MCPServer, MCPService, Tool};
187pub use monotonic_counter::{
188    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
189    SequenceValidationResult,
190};
191pub use network::{NodeBuilder, NodeConfig, P2PEvent, P2PNode};
192pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
193pub use persistent_state::{
194    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
195    StateChangeEvent, StateConfig, TransactionType, WalEntry,
196};
197pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
198pub use secure_memory::{
199    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
200    secure_string_with_capacity, secure_vec_with_capacity,
201};
202pub use validation::{
203    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
204    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
205    validate_message_size, validate_network_address, validate_peer_id,
206};
207
208// Enhanced identity exports
209pub use identity::enhanced::{
210    Department, EnhancedIdentity, EnhancedIdentityManager, Organization, Permission, Team,
211};
212
213// Storage exports
214pub use storage::{FileChunker, StorageManager}; // SyncManager temporarily disabled
215
216// Chat exports
217pub use chat::{Call, Channel, ChannelId, ChannelType, ChatManager, Message, MessageId, Thread};
218
219// Discuss exports
220pub use discuss::{
221    Badge, Category, CategoryId, DiscussManager, Poll, Reply, ReplyId, Topic, TopicId, UserStats,
222};
223
224// Projects exports
225pub use projects::{
226    Document, DocumentId, Folder, Project, ProjectAnalytics, ProjectId, ProjectsManager,
227    WorkflowState,
228};
229
230// Threshold exports
231pub use threshold::{
232    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
233};
234
235// Post-quantum cryptography exports (using ant-quic types exclusively)
236pub use quantum_crypto::{
237    CryptoCapabilities,
238    KemAlgorithm,
239    NegotiatedAlgorithms,
240    ProtocolVersion,
241    // Core types and errors (compatibility layer only)
242    QuantumCryptoError,
243    SignatureAlgorithm,
244    // Functions (compatibility layer only)
245    negotiate_algorithms,
246};
247
248// Saorsa-PQC exports (primary and only post-quantum crypto types)
249pub use quantum_crypto::{
250    // Symmetric encryption (quantum-resistant)
251    ChaCha20Poly1305Cipher,
252    // Encrypted message types
253    EncryptedMessage,
254    // Hybrid modes (classical + post-quantum)
255    HybridKem,
256    HybridKemCiphertext,
257    HybridKemPublicKey,
258    HybridKemSecretKey,
259    HybridPublicKeyEncryption,
260
261    HybridSignature,
262    HybridSignaturePublicKey,
263    HybridSignatureSecretKey,
264    HybridSignatureValue,
265
266    MlDsa65,
267
268    MlDsaOperations,
269
270    MlDsaPublicKey,
271    MlDsaSecretKey,
272    MlDsaSignature,
273    // Algorithm implementations
274    MlKem768,
275    MlKemCiphertext,
276    // Core traits for operations
277    MlKemOperations,
278    // Key types
279    MlKemPublicKey,
280    MlKemSecretKey,
281    // Errors and results
282    PqcError,
283    SaorsaPqcResult,
284
285    SharedSecret,
286    SymmetricEncryptedMessage,
287
288    SymmetricError,
289    SymmetricKey,
290
291    // Library initialization
292    saorsa_pqc_init,
293};
294
295// Legacy ant-quic integration (for backward compatibility only)
296pub use quantum_crypto::ant_quic_integration::{
297    // Configuration functions (deprecated - migrate to saorsa-pqc)
298    create_default_pqc_config,
299    create_pqc_only_config,
300};
301
302// Legacy types (deprecated - migrate to saorsa-pqc equivalents)
303pub use quantum_crypto::types::{
304    Ed25519PrivateKey, // DEPRECATED: Use saorsa-pqc types instead
305    // Deprecated encryption types - migrate to saorsa-pqc
306    Ed25519PublicKey, // DEPRECATED: Use saorsa-pqc types instead
307    Ed25519Signature, // DEPRECATED: Use saorsa-pqc types instead
308
309    FrostCommitment,
310    FrostGroupPublicKey,
311    FrostKeyShare,
312    // FROST threshold signatures (may need migration to saorsa-pqc later)
313    FrostPublicKey,
314    FrostSignature,
315    // Session and group management types (still needed)
316    GroupId,
317    HandshakeParameters,
318
319    ParticipantId,
320    PeerId as QuantumPeerId,
321    QuantumPeerIdentity,
322    SecureSession,
323    SessionId,
324    SessionState,
325};
326
327// Placement system exports
328pub use placement::{
329    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
330    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
331    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
332    WeightedPlacementStrategy,
333};
334
335// Network address types
336/// Peer identifier used throughout Saorsa
337///
338/// Currently implemented as a String for simplicity, but can be enhanced
339/// with cryptographic verification in future versions.
340pub type PeerId = String;
341
342/// Network address used for peer-to-peer communication
343///
344/// Supports both traditional IP:port format and human-readable four-word format.
345pub type Multiaddr = NetworkAddress;
346
347/// Saorsa Core version
348pub const VERSION: &str = env!("CARGO_PKG_VERSION");
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn test_version() {
356        assert!(!VERSION.is_empty());
357    }
358}