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    // Core types and errors (compatibility layer only)
236    QuantumCryptoError, CryptoCapabilities, ProtocolVersion,
237    KemAlgorithm, SignatureAlgorithm, NegotiatedAlgorithms,
238    // Functions (compatibility layer only)
239    negotiate_algorithms,
240};
241
242// Ant-QUIC PQC exports (primary and only post-quantum crypto types)
243pub use quantum_crypto::ant_quic_integration::{
244    // Configuration
245    PqcConfig, PqcConfigBuilder, PqcMode, HybridPreference,
246    create_default_pqc_config, create_pqc_only_config,
247    
248    // ML-DSA (post-quantum signatures) from ant-quic - ONLY THESE
249    MlDsaPublicKey, MlDsaSecretKey, MlDsaSignature, MlDsa65,
250    generate_ml_dsa_keypair, ml_dsa_sign, ml_dsa_verify,
251    
252    // ML-KEM (post-quantum key encapsulation) from ant-quic - ONLY THESE
253    MlKemPublicKey, MlKemSecretKey, MlKemCiphertext, MlKem768,
254    PqcSharedSecret as SharedSecret, generate_ml_kem_keypair,
255    ml_kem_encapsulate, ml_kem_decapsulate,
256};
257
258// Additional quantum crypto types (from our types module for non-PQC compatibility)
259pub use quantum_crypto::types::{
260    GroupId, ParticipantId, PeerId as QuantumPeerId, SessionId,
261    QuantumPeerIdentity, SecureSession, SessionState, HandshakeParameters,
262    // Note: HybridSignature, PublicKeySet, PrivateKeySet removed to avoid conflicts with ant-quic
263    Ed25519PublicKey, Ed25519PrivateKey, Ed25519Signature,
264    FrostPublicKey, FrostGroupPublicKey, FrostKeyShare, FrostCommitment, FrostSignature,
265};
266
267// Placement system exports
268pub use placement::{
269    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
270    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
271    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
272    WeightedPlacementStrategy,
273};
274
275// Network address types
276/// Peer identifier used throughout Saorsa
277///
278/// Currently implemented as a String for simplicity, but can be enhanced
279/// with cryptographic verification in future versions.
280pub type PeerId = String;
281
282/// Network address used for peer-to-peer communication
283///
284/// Supports both traditional IP:port format and human-readable four-word format.
285pub type Multiaddr = NetworkAddress;
286
287/// Saorsa Core version
288pub const VERSION: &str = env!("CARGO_PKG_VERSION");
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn test_version() {
296        assert!(!VERSION.is_empty());
297    }
298}