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