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