Skip to main content

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/// Prelude module for convenient imports
60///
61/// Use `use saorsa_core::prelude::*;` to import commonly used types.
62pub mod prelude;
63
64/// Network address types
65pub mod address;
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 handle: shared QUIC + peer + event state
77pub mod transport_handle;
78
79/// Transport layer (QUIC, TCP)
80pub mod transport;
81
82/// Authentication system for multi-writer records
83pub mod auth;
84
85/// Async event bus for watches and state changes
86pub mod events;
87/// MLS verifier adapter and proof format
88pub mod mls;
89/// Shared simple structs
90pub mod types;
91
92/// Telemetry for metrics and health signals
93pub mod telemetry;
94
95// MCP removed; will be redesigned later
96
97/// Security and cryptography
98pub mod security;
99
100/// BGP-based GeoIP provider using open-source routing data
101pub mod bgp_geo_provider;
102
103/// User identity and privacy system
104pub mod identity;
105
106/// Threshold cryptography for group operations
107pub mod threshold;
108
109/// Quantum-resistant cryptography
110pub mod quantum_crypto;
111
112/// Utility functions and types
113pub mod utils;
114
115/// Validation framework for input sanitization and rate limiting
116pub mod validation;
117
118/// Unified rate limiting engine
119pub mod rate_limit;
120
121/// Production hardening features
122pub mod production;
123
124/// Bootstrap cache for decentralized peer discovery
125pub mod bootstrap;
126
127/// Error types
128pub mod error;
129
130/// Peer record system for DHT-based peer discovery
131pub mod peer_record;
132
133/// Monotonic counter system for replay attack prevention
134pub mod monotonic_counter;
135
136/// Secure memory management for cryptographic operations
137pub mod secure_memory;
138
139/// Hierarchical key derivation system
140pub mod key_derivation;
141
142/// Encrypted key storage with Argon2id and ChaCha20-Poly1305
143pub mod encrypted_key_storage;
144
145/// Persistent state management with crash recovery
146pub mod persistent_state;
147
148/// Adaptive P2P network implementation
149pub mod adaptive;
150
151/// Configuration management system
152pub mod config;
153pub mod control;
154
155/// Health check system for monitoring and metrics
156pub mod health;
157
158/// Geographic-aware networking enhancements for P2P routing optimization
159pub mod geographic_enhanced_network;
160
161/// Placement Loop & Storage Orchestration System
162pub mod placement;
163
164/// Auto-upgrade system for cross-platform binary updates
165pub mod upgrade;
166
167// Re-export main types
168pub use address::{AddressBook, NetworkAddress};
169pub use identity::FourWordAddress;
170
171// New spec-compliant API exports
172pub use auth::{
173    DelegatedWriteAuth, MlsWriteAuth, PubKey, Sig, SingleWriteAuth, ThresholdWriteAuth, WriteAuth,
174};
175pub use bootstrap::{BootstrapConfig, BootstrapManager, CacheConfig, ContactEntry, QualityMetrics};
176pub use dht::{Key, Record};
177pub use dht_network_manager::{
178    DhtNetworkConfig, DhtNetworkEvent, DhtNetworkManager, DhtNetworkOperation, DhtNetworkResult,
179    DhtPeerInfo, PeerStoreOutcome,
180};
181pub use encrypted_key_storage::{
182    Argon2Config, DerivationPriority as KeyDerivationPriority, EncryptedKeyStorageManager,
183    KeyMetadata, PasswordValidation, SecurityLevel, StorageStats,
184};
185pub use error::{P2PError, P2pResult as Result, PeerFailureReason};
186pub use events::{Subscription, TopologyEvent, device_subscribe, dht_watch, subscribe_topology};
187pub use fwid::{FourWordsV1, Key as FwKey, fw_check, fw_to_key};
188pub use health::{
189    ComponentChecker, ComponentHealth, HealthEndpoints, HealthManager, HealthResponse,
190    HealthServer, HealthStatus, PrometheusExporter,
191};
192pub use key_derivation::{
193    BatchDerivationRequest, BatchDerivationResult, DerivationPath, DerivationPriority,
194    DerivationStats, DerivedKey, HierarchicalKeyDerivation, MasterSeed,
195};
196pub use monotonic_counter::{
197    BatchUpdateRequest, BatchUpdateResult, CounterStats, MonotonicCounterSystem, PeerCounter,
198    SequenceValidationResult,
199};
200pub use network::{
201    ConnectionStatus, NetworkSender, NodeBuilder, NodeConfig, P2PEvent, P2PNode, PeerInfo,
202    PeerResponse,
203};
204pub use transport_handle::TransportHandle;
205// Trust system exports for saorsa-node integration
206pub use adaptive::{EigenTrustEngine, NodeStatistics, NodeStatisticsUpdate, TrustProvider};
207pub use telemetry::{Metrics, StreamClass, record_lookup, record_timeout, telemetry};
208// Back-compat exports for tests
209pub use config::Config;
210pub use network::P2PNode as Node;
211pub use peer_record::{EndpointId, NatType, PeerDHTRecord, PeerEndpoint, SignatureCache, UserId};
212pub use persistent_state::{
213    FlushStrategy, IntegrityReport, PersistentStateManager, RecoveryMode, RecoveryStats,
214    StateChangeEvent, StateConfig, TransactionType, WalEntry,
215};
216pub use production::{ProductionConfig, ResourceManager, ResourceMetrics};
217pub use secure_memory::{
218    PoolStats, SecureMemory, SecureMemoryPool, SecureString, SecureVec, allocate_secure,
219    secure_string_with_capacity, secure_vec_with_capacity,
220};
221pub use validation::{
222    RateLimitConfig, RateLimiter, Sanitize, Validate, ValidationContext, ValidationError,
223    sanitize_string, validate_dht_key, validate_dht_value, validate_file_path,
224    validate_message_size, validate_network_address, validate_peer_id,
225};
226
227// Join rate limiting for Sybil protection
228pub use rate_limit::{
229    JoinRateLimitError, JoinRateLimiter, JoinRateLimiterConfig, extract_ipv4_subnet_8,
230    extract_ipv4_subnet_16, extract_ipv4_subnet_24, extract_ipv6_subnet_32, extract_ipv6_subnet_48,
231    extract_ipv6_subnet_64,
232};
233
234// Security and anti-Sybil exports (includes testnet configurations)
235pub use dht::node_age_verifier::{
236    AgeVerificationResult, NodeAgeCategory, NodeAgeConfig, NodeAgeRecord, NodeAgeStats,
237    NodeAgeVerifier, OperationType,
238};
239pub use security::{
240    DiversityStats, GeoInfo, GeoProvider, IPAnalysis, IPDiversityConfig, IPDiversityEnforcer,
241    IPv4NodeID, IPv6NodeID, NodeReputation, ReputationManager, StubGeoProvider,
242};
243
244// Enhanced identity removed
245
246// Threshold exports
247pub use threshold::{
248    GroupMetadata, ParticipantInfo, ThresholdGroup, ThresholdGroupManager, ThresholdSignature,
249};
250
251// Post-quantum cryptography exports (using ant-quic types exclusively)
252pub use quantum_crypto::{
253    CryptoCapabilities,
254    KemAlgorithm,
255    NegotiatedAlgorithms,
256    ProtocolVersion,
257    // Core types and errors (compatibility layer only)
258    QuantumCryptoError,
259    SignatureAlgorithm,
260    // Functions (compatibility layer only)
261    negotiate_algorithms,
262};
263
264// Saorsa-PQC exports (primary post-quantum crypto types)
265pub use quantum_crypto::{
266    // Symmetric encryption (quantum-resistant)
267    ChaCha20Poly1305Cipher,
268    // Encrypted message types
269    EncryptedMessage,
270    // Algorithm implementations
271    MlDsa65,
272    MlDsaOperations,
273    // Use ant-quic types for better trait implementations
274    MlDsaPublicKey as AntMlDsaPublicKey,
275    MlDsaSecretKey as AntMlDsaSecretKey,
276    MlDsaSignature as AntMlDsaSignature,
277    MlKem768,
278    MlKemCiphertext,
279    // Core traits for operations
280    MlKemOperations,
281    // Key types
282    MlKemPublicKey,
283    MlKemSecretKey,
284    // Errors and results
285    PqcError,
286    SaorsaPqcResult,
287    SharedSecret,
288    SymmetricEncryptedMessage,
289    SymmetricError,
290    SymmetricKey,
291    // Configuration functions
292    create_default_pqc_config,
293    create_pqc_only_config,
294    // Library initialization
295    saorsa_pqc_init,
296};
297
298// Session and identity types
299pub use quantum_crypto::types::{
300    // FROST threshold signatures
301    FrostCommitment,
302    FrostGroupPublicKey,
303    FrostKeyShare,
304    FrostPublicKey,
305    FrostSignature,
306    // Session and group management types
307    GroupId,
308    HandshakeParameters,
309    ParticipantId,
310    PeerId as QuantumPeerId,
311    QuantumPeerIdentity,
312    SecureSession,
313    SessionId,
314    SessionState,
315};
316
317// Placement system exports
318pub use crate::placement::{
319    AuditSystem, DataPointer, DhtRecord, DiversityEnforcer, GeographicLocation, GroupBeacon,
320    NetworkRegion, NodeAd, PlacementConfig, PlacementDecision, PlacementEngine, PlacementMetrics,
321    PlacementOrchestrator, RegisterPointer, RepairSystem, StorageOrchestrator,
322    WeightedPlacementStrategy,
323};
324
325// Network address types
326/// Peer identifier used throughout Saorsa
327///
328/// Currently implemented as a String for simplicity, but should be enhanced
329/// with cryptographic verification and validation in future versions.
330///
331/// TODO: Replace with a proper newtype that includes validation:
332/// - Non-empty string validation
333/// - Character set validation (alphanumeric + - _)
334/// - Length limits (max 256 characters)
335/// - Optional cryptographic verification
336pub type PeerId = String;
337
338/// Network address used for peer-to-peer communication
339///
340/// Supports both traditional IP:port format and human-readable four-word format.
341pub type Multiaddr = NetworkAddress;
342
343/// Saorsa Core version
344pub const VERSION: &str = env!("CARGO_PKG_VERSION");
345
346/// Default capacity for broadcast and mpsc event channels throughout the system.
347pub const DEFAULT_EVENT_CHANNEL_CAPACITY: usize = 1000;
348
349// Upgrade system exports
350pub use upgrade::{
351    ApplierConfig, ApplyResult, BackupMetadata, DownloadProgress, Downloader, DownloaderConfig,
352    PinnedKey, Platform as UpgradePlatform, PlatformBinary, Release, ReleaseChannel,
353    RollbackManager, SignatureVerifier, StagedUpdate, StagedUpdateManager, UpdateConfig,
354    UpdateConfigBuilder, UpdateInfo, UpdateManager, UpdateManifest, UpdatePolicy, UpgradeError,
355    UpgradeEvent, create_applier,
356};