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;
192pub mod control;
193
194/// Health check system for monitoring and metrics
195pub mod health;
196
197/// Geographic-aware networking enhancements for P2P routing optimization
198pub mod geographic_enhanced_network;
199
200/// Placement Loop & Storage Orchestration System
201pub mod placement;
202
203/// Virtual disk for encrypted file storage
204pub mod virtual_disk;
205
206/// Entity-based system for unified identity, storage, and collaboration
207pub mod entities;
208
209/// Auto-upgrade system for cross-platform binary updates
210pub mod upgrade;
211
212/// Mock DHT for testing
213#[cfg(any(test, feature = "test-utils"))]
214pub mod mock_dht;
215
216// Re-export main types
217pub use address::{AddressBook, NetworkAddress};
218pub use address_book::{
219    address_book, get_user_by_four_words, get_user_four_words, register_user_address,
220};
221pub use identity::FourWordAddress;
222
223// New spec-compliant API exports
224pub use auth::{
225    DelegatedWriteAuth, MlsWriteAuth, PubKey, Sig, SingleWriteAuth, ThresholdWriteAuth, WriteAuth,
226};
227pub use bootstrap::{BootstrapCache, BootstrapManager, CacheConfig, ContactEntry};
228pub use dht::{Key, Record};
229pub use dht_network_manager::{
230    BootstrapNode, DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation,
231    DhtNetworkResult, DhtPeerInfo,
232};
233pub use encrypted_key_storage::{
234    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
235    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
236};
237pub use error::{P2PError, P2pResult as Result};
238pub use events::{Subscription, TopologyEvent, device_subscribe, dht_watch, subscribe_topology};
239pub use fwid::{FourWordsV1, Key as FwKey, fw_check, fw_to_key};
240pub use health::{
241    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
242    HealthServer, HealthStatus, PrometheusExporter,
243};
244pub use key_derivation::{
245    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
246    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
247};
248pub use monotonic_counter::{
249    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
250    SequenceValidationResult,
251};
252pub use network::{ConnectionStatus, NodeBuilder, NodeConfig, P2PEvent, P2PNode, PeerInfo};
253pub use telemetry::{Metrics, StreamClass, record_lookup, record_timeout, telemetry};
254// Back-compat exports for tests
255pub use config::Config;
256pub use network::P2PNode as Node;
257pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
258pub use persistent_state::{
259    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
260    StateChangeEvent, StateConfig, TransactionType, WalEntry,
261};
262pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
263pub use secure_memory::{
264    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
265    secure_string_with_capacity, secure_vec_with_capacity,
266};
267pub use validation::{
268    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
269    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
270    validate_message_size, validate_network_address, validate_peer_id,
271};
272
273// Join rate limiting for Sybil protection
274pub use rate_limit::{
275    JoinRateLimitError, JoinRateLimiter, JoinRateLimiterConfig, extract_ipv4_subnet_8,
276    extract_ipv4_subnet_16, extract_ipv4_subnet_24, extract_ipv6_subnet_32, extract_ipv6_subnet_48,
277    extract_ipv6_subnet_64,
278};
279
280// Security and anti-Sybil exports (includes testnet configurations)
281pub use dht::node_age_verifier::{
282    AgeVerificationResult, NodeAgeCategory, NodeAgeConfig, NodeAgeRecord, NodeAgeStats,
283    NodeAgeVerifier, OperationType,
284};
285pub use security::{
286    DiversityStats, GeoInfo, GeoProvider, IPAnalysis, IPDiversityConfig, IPDiversityEnforcer,
287    IPv4NodeID, IPv6NodeID, NodeReputation, ReputationManager, StubGeoProvider,
288};
289
290// Enhanced identity removed
291
292// Storage exports
293pub use storage::{FileChunker, StorageManager}; // SyncManager temporarily disabled
294
295// Chat exports
296pub use chat::{Call, Channel, ChannelId, ChannelType, ChatManager, Message, MessageId, Thread};
297
298// Discuss exports
299pub use discuss::{
300    Badge, Category, CategoryId, DiscussManager, Poll, Reply, ReplyId, Topic, TopicId, UserStats,
301};
302
303// Projects exports
304pub use projects::{
305    Document, DocumentId, Folder, Project, ProjectAnalytics, ProjectId, ProjectsManager,
306    WorkflowState,
307};
308
309// Threshold exports
310pub use threshold::{
311    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
312};
313
314// Post-quantum cryptography exports (using ant-quic types exclusively)
315pub use quantum_crypto::{
316    CryptoCapabilities,
317    KemAlgorithm,
318    NegotiatedAlgorithms,
319    ProtocolVersion,
320    // Core types and errors (compatibility layer only)
321    QuantumCryptoError,
322    SignatureAlgorithm,
323    // Functions (compatibility layer only)
324    negotiate_algorithms,
325};
326
327// Saorsa-PQC exports (primary and only post-quantum crypto types)
328pub use quantum_crypto::{
329    // Symmetric encryption (quantum-resistant)
330    ChaCha20Poly1305Cipher,
331    // Encrypted message types
332    EncryptedMessage,
333    // Hybrid modes (classical + post-quantum)
334    HybridKem,
335    HybridKemCiphertext,
336    HybridKemPublicKey,
337    HybridKemSecretKey,
338    HybridPublicKeyEncryption,
339
340    // HybridSignature,
341    HybridSignaturePublicKey,
342    HybridSignatureSecretKey,
343    HybridSignatureValue,
344
345    MlDsa65,
346
347    MlDsaOperations,
348
349    // Use ant-quic types for better trait implementations
350    MlDsaPublicKey as AntMlDsaPublicKey,
351    MlDsaSecretKey as AntMlDsaSecretKey,
352    MlDsaSignature as AntMlDsaSignature,
353    // Algorithm implementations
354    MlKem768,
355    MlKemCiphertext,
356    // Core traits for operations
357    MlKemOperations,
358    // Key types
359    MlKemPublicKey,
360    MlKemSecretKey,
361    // Errors and results
362    PqcError,
363    SaorsaPqcResult,
364
365    SharedSecret,
366    SymmetricEncryptedMessage,
367
368    SymmetricError,
369    SymmetricKey,
370
371    // Library initialization
372    saorsa_pqc_init,
373};
374
375// Legacy ant-quic integration (for backward compatibility only)
376pub use quantum_crypto::ant_quic_integration::{
377    // Configuration functions (deprecated - migrate to saorsa-pqc)
378    create_default_pqc_config,
379    create_pqc_only_config,
380};
381
382// Legacy types (deprecated - migrate to saorsa-pqc equivalents)
383pub use quantum_crypto::types::{
384    FrostCommitment,
385    FrostGroupPublicKey,
386    FrostKeyShare,
387    // FROST threshold signatures (may need migration to saorsa-pqc later)
388    FrostPublicKey,
389    FrostSignature,
390    // Session and group management types (still needed)
391    GroupId,
392    HandshakeParameters,
393
394    ParticipantId,
395    PeerId as QuantumPeerId,
396    QuantumPeerIdentity,
397    SecureSession,
398    SessionId,
399    SessionState,
400};
401
402// Placement system exports
403pub use placement::{
404    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
405    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
406    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
407    WeightedPlacementStrategy,
408};
409
410// Network address types
411/// Peer identifier used throughout Saorsa
412///
413/// Currently implemented as a String for simplicity, but should be enhanced
414/// with cryptographic verification and validation in future versions.
415///
416/// TODO: Replace with a proper newtype that includes validation:
417/// - Non-empty string validation
418/// - Character set validation (alphanumeric + - _)
419/// - Length limits (max 256 characters)
420/// - Optional cryptographic verification
421pub type PeerId = String;
422
423/// Network address used for peer-to-peer communication
424///
425/// Supports both traditional IP:port format and human-readable four-word format.
426pub type Multiaddr = NetworkAddress;
427
428/// Saorsa Core version
429pub const VERSION: &str = env!("CARGO_PKG_VERSION");
430
431// Upgrade system exports
432pub use upgrade::{
433    ApplierConfig, ApplyResult, BackupMetadata, DownloadProgress, Downloader, DownloaderConfig,
434    PinnedKey, Platform as UpgradePlatform, PlatformBinary, Release, ReleaseChannel,
435    RollbackManager, SignatureVerifier, StagedUpdate, StagedUpdateManager, UpdateConfig,
436    UpdateConfigBuilder, UpdateInfo, UpdateManager, UpdateManifest, UpdatePolicy, UpgradeError,
437    UpgradeEvent, create_applier,
438};