1#![allow(missing_docs)]
26
27use async_trait::async_trait;
28use serde::{Deserialize, Serialize};
29
30pub mod beta_distribution;
31pub mod churn;
32pub mod churn_prediction;
33pub mod client;
34pub mod coordinator;
35pub mod coordinator_extensions;
36pub mod dht_integration;
37pub mod eviction;
38pub mod gossip;
39pub mod hyperbolic;
40pub mod hyperbolic_enhanced;
41pub mod hyperbolic_greedy;
42pub mod identity;
43pub mod learning;
44pub mod monitoring;
45pub mod multi_armed_bandit;
46pub mod performance;
47pub mod q_learning_cache;
48pub mod replication;
49pub mod retrieval;
50pub mod routing;
51pub mod security;
52pub mod som;
53pub mod storage;
54pub mod transport;
55pub mod trust;
56
57pub use churn::{ChurnConfig, ChurnHandler, NodeMonitor, NodeState, RecoveryManager};
59pub use client::{
60 AdaptiveP2PClient, Client, ClientConfig, ClientProfile, NetworkStats as ClientNetworkStats,
61};
62pub use coordinator::{NetworkConfig, NetworkCoordinator};
63pub use dht_integration::{AdaptiveDHT, KademliaRoutingStrategy};
64pub use eviction::{
65 AdaptiveStrategy, CacheState, EvictionStrategy, EvictionStrategyType, FIFOStrategy,
66 LFUStrategy, LRUStrategy,
67};
68pub use gossip::AdaptiveGossipSub;
69pub use hyperbolic::{HyperbolicRoutingStrategy, HyperbolicSpace};
70pub use hyperbolic_enhanced::{
71 EnhancedHyperbolicCoordinate, EnhancedHyperbolicRoutingStrategy, EnhancedHyperbolicSpace,
72};
73pub use hyperbolic_greedy::{
74 Embedding, EmbeddingConfig, HyperbolicGreedyRouter, embed_snapshot, greedy_next,
75};
76pub use identity::{NodeIdentity, SignedMessage, StoredIdentity};
77pub use learning::{ChurnPredictor, QLearnCacheManager, ThompsonSampling};
78pub use monitoring::{
79 Alert, AlertManager, DashboardData, MonitoringConfig, MonitoringSystem, NetworkHealth,
80};
81pub use multi_armed_bandit::{
82 MABConfig, MABRoutingStrategy, MultiArmedBandit, RouteDecision, RouteId,
83};
84pub use performance::{
85 BatchProcessor, ConcurrencyLimiter, ConnectionPool, OptimizedSerializer, PerformanceCache,
86 PerformanceConfig,
87};
88pub use q_learning_cache::{
89 AccessInfo, CacheAction, CacheStatistics, QLearnCacheManager as QLearningCacheManager,
90 QLearningConfig, StateVector,
91};
92pub use replication::{ReplicaInfo, ReplicationManager, ReplicationStrategy};
93pub use retrieval::{RetrievalManager, RetrievalStrategy};
94pub use routing::AdaptiveRouter;
95pub use security::{
96 BlacklistManager, EclipseDetector, RateLimiter, SecurityAuditor, SecurityConfig,
97 SecurityManager,
98};
99pub use som::{FeatureExtractor, GridSize, SOMRoutingStrategy, SelfOrganizingMap, SomConfig};
100pub use storage::{ChunkManager, ContentStore, ReplicationConfig, StorageConfig};
101pub use transport::{ConnectionInfo, Transport, TransportManager, TransportProtocol};
102pub use trust::{
103 EigenTrustEngine, MockTrustProvider, NodeStatistics, NodeStatisticsUpdate,
104 TrustBasedRoutingStrategy,
105};
106
107pub type Result<T> = std::result::Result<T, AdaptiveNetworkError>;
109
110#[derive(Debug, thiserror::Error)]
112pub enum AdaptiveNetworkError {
113 #[error("Routing error: {0}")]
114 Routing(String),
115
116 #[error("Trust calculation error: {0}")]
117 Trust(String),
118
119 #[error("Learning system error: {0}")]
120 Learning(String),
121
122 #[error("Gossip error: {0}")]
123 Gossip(String),
124
125 #[error("Network error: {0}")]
126 Network(#[from] std::io::Error),
127
128 #[error("IO error: {0}")]
129 Io(std::io::Error),
130
131 #[error("Serialization error: {0}")]
132 Serialization(#[from] bincode::Error),
133
134 #[error("Other error: {0}")]
135 Other(String),
136}
137
138impl From<anyhow::Error> for AdaptiveNetworkError {
139 fn from(e: anyhow::Error) -> Self {
140 AdaptiveNetworkError::Io(std::io::Error::other(e.to_string()))
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
146pub struct ContentHash(pub [u8; 32]);
147
148impl ContentHash {
149 pub fn from(data: &[u8]) -> Self {
151 let mut hash = [0u8; 32];
152 if data.len() >= 32 {
153 hash.copy_from_slice(&data[..32]);
154 } else {
155 let hashed = blake3::hash(data);
156 hash.copy_from_slice(hashed.as_bytes());
157 }
158 Self(hash)
159 }
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct NetworkMessage {
165 pub id: String,
167 pub sender: NodeId,
169 pub content: Vec<u8>,
171 pub msg_type: ContentType,
173 pub timestamp: u64,
175}
176
177pub type NodeId = crate::peer_record::UserId;
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct NodeDescriptor {
183 pub id: NodeId,
184 pub public_key: ed25519_dalek::VerifyingKey,
185 pub addresses: Vec<String>,
186 pub hyperbolic: Option<HyperbolicCoordinate>,
187 pub som_position: Option<[f64; 4]>,
188 pub trust: f64,
189 pub capabilities: NodeCapabilities,
190}
191
192#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
194pub struct HyperbolicCoordinate {
195 pub r: f64, pub theta: f64, }
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct NodeCapabilities {
202 pub storage: u64, pub compute: u64, pub bandwidth: u64, }
206
207#[async_trait]
209pub trait AdaptiveNetworkNode: Send + Sync {
210 async fn join(&mut self, bootstrap: Vec<NodeDescriptor>) -> Result<()>;
212
213 async fn store(&self, data: Vec<u8>) -> Result<ContentHash>;
215
216 async fn retrieve(&self, hash: &ContentHash) -> Result<Vec<u8>>;
218
219 async fn publish(&self, topic: &str, message: Vec<u8>) -> Result<()>;
221
222 async fn subscribe(
224 &self,
225 topic: &str,
226 ) -> Result<Box<dyn futures::Stream<Item = Vec<u8>> + Send>>;
227
228 async fn node_info(&self) -> Result<NodeDescriptor>;
230
231 async fn network_stats(&self) -> Result<NetworkStats>;
233
234 async fn shutdown(self) -> Result<()>;
236}
237
238#[derive(Debug, Clone, Serialize, Deserialize)]
240pub struct NetworkStats {
241 pub connected_peers: usize,
242 pub routing_success_rate: f64,
243 pub average_trust_score: f64,
244 pub cache_hit_rate: f64,
245 pub churn_rate: f64,
246 pub total_storage: u64,
247 pub total_bandwidth: u64,
248}
249
250#[async_trait]
252pub trait RoutingStrategy: Send + Sync {
253 async fn find_path(&self, target: &NodeId) -> Result<Vec<NodeId>>;
255
256 fn route_score(&self, neighbor: &NodeId, target: &NodeId) -> f64;
258
259 fn update_metrics(&mut self, path: &[NodeId], success: bool);
261
262 async fn find_closest_nodes(
264 &self,
265 content_hash: &ContentHash,
266 _count: usize,
267 ) -> Result<Vec<NodeId>> {
268 let target = NodeId {
270 hash: content_hash.0,
271 };
272 self.find_path(&target).await
273 }
274}
275
276pub trait TrustProvider: Send + Sync {
278 fn get_trust(&self, node: &NodeId) -> f64;
280
281 fn update_trust(&self, from: &NodeId, to: &NodeId, success: bool);
283
284 fn get_global_trust(&self) -> std::collections::HashMap<NodeId, f64>;
286
287 fn remove_node(&self, node: &NodeId);
289
290 fn get_trust_score(&self, node: &NodeId) -> f64 {
292 self.get_trust(node)
293 }
294}
295
296#[async_trait]
298pub trait LearningSystem: Send + Sync {
299 async fn select_strategy(&self, context: &LearningContext) -> StrategyChoice;
301
302 async fn update(
304 &mut self,
305 context: &LearningContext,
306 choice: &StrategyChoice,
307 outcome: &Outcome,
308 );
309
310 async fn metrics(&self) -> LearningMetrics;
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct LearningContext {
317 pub content_type: ContentType,
318 pub network_conditions: NetworkConditions,
319 pub historical_performance: Vec<f64>,
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
324pub enum ContentType {
325 DHTLookup,
326 DataRetrieval,
327 ComputeRequest,
328 RealtimeMessage,
329 DiscoveryProbe,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct NetworkConditions {
335 pub connected_peers: usize,
336 pub avg_latency_ms: f64,
337 pub churn_rate: f64,
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
342pub enum StrategyChoice {
343 Kademlia,
344 Hyperbolic,
345 TrustPath,
346 SOMRegion,
347}
348
349#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct Outcome {
352 pub success: bool,
353 pub latency_ms: u64,
354 pub hops: usize,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
359pub struct LearningMetrics {
360 pub total_decisions: u64,
361 pub success_rate: f64,
362 pub avg_latency_ms: f64,
363 pub strategy_performance: std::collections::HashMap<StrategyChoice, f64>,
364}
365
366#[cfg(test)]
367mod timestamp_tests;
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn test_content_hash_serialization() {
375 let hash = ContentHash([42u8; 32]);
376 let serialized = bincode::serialize(&hash).unwrap();
377 let deserialized: ContentHash = bincode::deserialize(&serialized).unwrap();
378 assert_eq!(hash, deserialized);
379 }
380
381 #[test]
382 fn test_hyperbolic_coordinate_bounds() {
383 let coord = HyperbolicCoordinate {
384 r: 0.5,
385 theta: std::f64::consts::PI,
386 };
387 assert!(coord.r >= 0.0 && coord.r < 1.0);
388 assert!(coord.theta >= 0.0 && coord.theta < 2.0 * std::f64::consts::PI);
389 }
390}