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