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