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