genesis_protocol/
network.rs

1//! 🌐 Network Discovery and Topology
2//!
3//! This module implements network discovery, topology management, and
4//! organism networking capabilities for the Genesis Protocol.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::net::SocketAddr;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11/// Network discovery and management system
12#[derive(Debug, Clone)]
13pub struct NetworkDiscovery {
14    /// Known organisms in the network
15    pub known_organisms: HashMap<String, OrganismNode>,
16    /// Network topology
17    pub topology: NetworkTopology,
18    /// Discovery metrics
19    pub discovery_metrics: DiscoveryMetrics,
20    /// Network configuration
21    pub config: NetworkConfig,
22}
23
24/// Network topology manager
25#[derive(Debug, Clone)]
26pub struct NetworkTopology {
27    /// Network nodes
28    pub nodes: HashMap<String, NetworkNode>,
29    /// Network connections
30    pub connections: HashMap<String, NetworkConnection>,
31    /// Network clusters
32    pub clusters: HashMap<String, NetworkCluster>,
33    /// Topology metrics
34    pub metrics: TopologyMetrics,
35}
36
37/// Individual organism node in the network
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct OrganismNode {
40    /// Organism ID
41    pub organism_id: String,
42    /// Network address
43    pub address: SocketAddr,
44    /// Node capabilities
45    pub capabilities: NodeCapabilities,
46    /// Node status
47    pub status: NodeStatus,
48    /// Last seen timestamp
49    pub last_seen: u64,
50    /// Connection quality
51    pub connection_quality: f64,
52    /// Trust level
53    pub trust_level: f64,
54    /// Performance metrics
55    pub performance: NodePerformance,
56}
57
58/// Network node (can represent multiple organisms)
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct NetworkNode {
61    /// Node ID
62    pub node_id: String,
63    /// Node address
64    pub address: SocketAddr,
65    /// Organisms hosted on this node
66    pub organisms: Vec<String>,
67    /// Node type
68    pub node_type: NodeType,
69    /// Node capabilities
70    pub capabilities: NodeCapabilities,
71    /// Node status
72    pub status: NodeStatus,
73    /// Resource usage
74    pub resource_usage: ResourceUsage,
75}
76
77/// Network connection between nodes
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct NetworkConnection {
80    /// Connection ID
81    pub connection_id: String,
82    /// Source node
83    pub source_node: String,
84    /// Target node
85    pub target_node: String,
86    /// Connection type
87    pub connection_type: ConnectionType,
88    /// Connection quality metrics
89    pub quality: ConnectionQuality,
90    /// Connection established time
91    pub established_at: u64,
92}
93
94/// Network cluster (group of related nodes)
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct NetworkCluster {
97    /// Cluster ID
98    pub cluster_id: String,
99    /// Cluster members
100    pub members: Vec<String>,
101    /// Cluster purpose
102    pub purpose: String,
103    /// Cluster coordination node
104    pub coordinator: Option<String>,
105    /// Cluster health
106    pub health: f64,
107}
108
109/// Node capabilities
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct NodeCapabilities {
112    /// Maximum organisms supported
113    pub max_organisms: usize,
114    /// Maximum connections
115    pub max_connections: usize,
116    /// Supported protocols
117    pub protocols: Vec<String>,
118    /// Computing resources
119    pub computing_power: f64,
120    /// Memory capacity
121    pub memory_capacity: u64,
122    /// Network bandwidth
123    pub bandwidth: u64,
124}
125
126/// Node status
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
128pub enum NodeStatus {
129    /// Node is online and active
130    Online,
131    /// Node is offline
132    Offline,
133    /// Node is connecting
134    Connecting,
135    /// Node is disconnecting
136    Disconnecting,
137    /// Node is under maintenance
138    Maintenance,
139    /// Node is experiencing issues
140    Degraded,
141}
142
143/// Node type
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub enum NodeType {
146    /// Full node (hosts organisms)
147    Full,
148    /// Relay node (forwards messages)
149    Relay,
150    /// Gateway node (connects to external networks)
151    Gateway,
152    /// Bootstrap node (helps with discovery)
153    Bootstrap,
154    /// Archive node (stores historical data)
155    Archive,
156}
157
158/// Connection type
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub enum ConnectionType {
161    /// Direct peer-to-peer connection
162    Direct,
163    /// Relayed connection through intermediary
164    Relayed,
165    /// Gateway connection to external network
166    Gateway,
167    /// Cluster internal connection
168    Cluster,
169}
170
171/// Connection quality metrics
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct ConnectionQuality {
174    /// Round-trip time (milliseconds)
175    pub rtt: f64,
176    /// Packet loss rate (0.0-1.0)
177    pub packet_loss: f64,
178    /// Bandwidth (bytes per second)
179    pub bandwidth: u64,
180    /// Reliability score (0.0-1.0)
181    pub reliability: f64,
182    /// Connection stability
183    pub stability: f64,
184}
185
186/// Node performance metrics
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct NodePerformance {
189    /// Messages processed per second
190    pub messages_per_second: f64,
191    /// Average response time (milliseconds)
192    pub avg_response_time: f64,
193    /// Uptime percentage
194    pub uptime: f64,
195    /// Error rate (0.0-1.0)
196    pub error_rate: f64,
197}
198
199/// Resource usage
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct ResourceUsage {
202    /// CPU usage percentage
203    pub cpu_usage: f64,
204    /// Memory usage percentage
205    pub memory_usage: f64,
206    /// Network usage percentage
207    pub network_usage: f64,
208    /// Storage usage percentage
209    pub storage_usage: f64,
210}
211
212/// Network configuration
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct NetworkConfig {
215    /// Discovery interval (seconds)
216    pub discovery_interval: u64,
217    /// Maximum discovery attempts
218    pub max_discovery_attempts: u32,
219    /// Connection timeout (seconds)
220    pub connection_timeout: u64,
221    /// Heartbeat interval (seconds)
222    pub heartbeat_interval: u64,
223    /// Trust threshold
224    pub trust_threshold: f64,
225    /// Default port for communication
226    pub default_port: u16,
227}
228
229/// Discovery metrics
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct DiscoveryMetrics {
232    /// Total discovered organisms
233    pub total_discovered: usize,
234    /// Active connections
235    pub active_connections: usize,
236    /// Failed connection attempts
237    pub failed_connections: u64,
238    /// Average discovery time (milliseconds)
239    pub avg_discovery_time: f64,
240    /// Network coverage percentage
241    pub network_coverage: f64,
242}
243
244/// Topology metrics
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct TopologyMetrics {
247    /// Total nodes in network
248    pub total_nodes: usize,
249    /// Total connections
250    pub total_connections: usize,
251    /// Network diameter (max hops between any two nodes)
252    pub network_diameter: usize,
253    /// Average clustering coefficient
254    pub clustering_coefficient: f64,
255    /// Network density
256    pub network_density: f64,
257}
258
259impl NetworkDiscovery {
260    /// Create new network discovery system
261    pub fn new() -> Result<Self, NetworkError> {
262        Ok(NetworkDiscovery {
263            known_organisms: HashMap::new(),
264            topology: NetworkTopology::new(),
265            discovery_metrics: DiscoveryMetrics::new(),
266            config: NetworkConfig::default(),
267        })
268    }
269
270    /// Discover organisms in the network
271    pub async fn discover_organisms(&mut self) -> Result<Vec<String>, NetworkError> {
272        let mut discovered = Vec::new();
273        
274        // Simulate network discovery process
275        // In real implementation, this would:
276        // 1. Broadcast discovery messages
277        // 2. Listen for responses
278        // 3. Validate responding organisms
279        // 4. Add them to known organisms
280        
281        // For now, simulate discovery
282        for i in 0..rand::random::<usize>() % 5 + 1 {
283            let organism_id = format!("discovered_tron_{}", i);
284            let address = format!("127.0.0.1:{}", 8000 + i).parse().unwrap();
285            
286            let organism_node = OrganismNode {
287                organism_id: organism_id.clone(),
288                address,
289                capabilities: NodeCapabilities::default(),
290                status: NodeStatus::Online,
291                last_seen: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
292                connection_quality: 0.8,
293                trust_level: 0.5,
294                performance: NodePerformance::default(),
295            };
296            
297            self.known_organisms.insert(organism_id.clone(), organism_node);
298            discovered.push(organism_id);
299        }
300        
301        self.discovery_metrics.total_discovered = self.known_organisms.len();
302        
303        Ok(discovered)
304    }
305
306    /// Connect to an organism
307    pub async fn connect_to_organism(&mut self, organism_id: &str) -> Result<(), NetworkError> {
308        if let Some(organism) = self.known_organisms.get_mut(organism_id) {
309            if organism.status == NodeStatus::Offline {
310                return Err(NetworkError::OrganismOffline(organism_id.to_string()));
311            }
312            
313            // Simulate connection process
314            organism.status = NodeStatus::Connecting;
315            
316            // Simulate connection delay
317            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
318            
319            organism.status = NodeStatus::Online;
320            organism.connection_quality = 0.9;
321            organism.last_seen = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
322            
323            self.discovery_metrics.active_connections += 1;
324            
325            Ok(())
326        } else {
327            Err(NetworkError::OrganismNotFound(organism_id.to_string()))
328        }
329    }
330
331    /// Update network topology
332    pub fn update_topology(&mut self) {
333        // Update topology based on known organisms
334        self.topology.update_from_organisms(&self.known_organisms);
335        
336        // Calculate topology metrics
337        self.topology.calculate_metrics();
338    }
339
340    /// Get network statistics
341    pub fn get_network_stats(&self) -> NetworkStats {
342        NetworkStats {
343            total_organisms: self.known_organisms.len(),
344            online_organisms: self.known_organisms.values()
345                .filter(|o| o.status == NodeStatus::Online)
346                .count(),
347            total_nodes: self.topology.nodes.len(),
348            total_connections: self.topology.connections.len(),
349            network_health: self.calculate_network_health(),
350            average_connection_quality: self.calculate_average_connection_quality(),
351        }
352    }
353
354    /// Calculate overall network health
355    fn calculate_network_health(&self) -> f64 {
356        if self.known_organisms.is_empty() {
357            return 0.0;
358        }
359        
360        let total_quality: f64 = self.known_organisms.values()
361            .map(|o| o.connection_quality)
362            .sum();
363        
364        let online_count = self.known_organisms.values()
365            .filter(|o| o.status == NodeStatus::Online)
366            .count();
367        
368        let availability = online_count as f64 / self.known_organisms.len() as f64;
369        let average_quality = total_quality / self.known_organisms.len() as f64;
370        
371        (availability + average_quality) / 2.0
372    }
373
374    /// Calculate average connection quality
375    fn calculate_average_connection_quality(&self) -> f64 {
376        if self.known_organisms.is_empty() {
377            return 0.0;
378        }
379        
380        let total_quality: f64 = self.known_organisms.values()
381            .map(|o| o.connection_quality)
382            .sum();
383        
384        total_quality / self.known_organisms.len() as f64
385    }
386}
387
388impl NetworkTopology {
389    pub fn new() -> Self {
390        NetworkTopology {
391            nodes: HashMap::new(),
392            connections: HashMap::new(),
393            clusters: HashMap::new(),
394            metrics: TopologyMetrics::new(),
395        }
396    }
397
398    /// Update topology from organism information
399    pub fn update_from_organisms(&mut self, organisms: &HashMap<String, OrganismNode>) {
400        // Create nodes from organisms
401        for (organism_id, organism) in organisms {
402            let node = NetworkNode {
403                node_id: organism_id.clone(),
404                address: organism.address,
405                organisms: vec![organism_id.clone()],
406                node_type: NodeType::Full,
407                capabilities: organism.capabilities.clone(),
408                status: organism.status.clone(),
409                resource_usage: ResourceUsage::default(),
410            };
411            
412            self.nodes.insert(organism_id.clone(), node);
413        }
414        
415        // Create connections between nodes (simplified)
416        self.create_connections();
417    }
418
419    /// Create connections between nodes
420    fn create_connections(&mut self) {
421        let node_ids: Vec<String> = self.nodes.keys().cloned().collect();
422        
423        for i in 0..node_ids.len() {
424            for j in i + 1..node_ids.len() {
425                let connection_id = format!("conn_{}_{}", i, j);
426                let connection = NetworkConnection {
427                    connection_id: connection_id.clone(),
428                    source_node: node_ids[i].clone(),
429                    target_node: node_ids[j].clone(),
430                    connection_type: ConnectionType::Direct,
431                    quality: ConnectionQuality::default(),
432                    established_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
433                };
434                
435                self.connections.insert(connection_id, connection);
436            }
437        }
438    }
439
440    /// Calculate topology metrics
441    pub fn calculate_metrics(&mut self) {
442        self.metrics.total_nodes = self.nodes.len();
443        self.metrics.total_connections = self.connections.len();
444        
445        // Calculate network density
446        let max_connections = if self.nodes.len() > 1 {
447            self.nodes.len() * (self.nodes.len() - 1) / 2
448        } else {
449            1
450        };
451        
452        self.metrics.network_density = self.connections.len() as f64 / max_connections as f64;
453        
454        // Simplified clustering coefficient
455        self.metrics.clustering_coefficient = 0.7; // Placeholder
456        
457        // Simplified network diameter
458        self.metrics.network_diameter = (self.nodes.len() as f64).sqrt() as usize;
459    }
460}
461
462impl Default for NodeCapabilities {
463    fn default() -> Self {
464        NodeCapabilities {
465            max_organisms: 100,
466            max_connections: 1000,
467            protocols: vec!["genesis-neural".to_string()],
468            computing_power: 1.0,
469            memory_capacity: 1_000_000_000, // 1GB
470            bandwidth: 100_000_000,         // 100MB/s
471        }
472    }
473}
474
475impl Default for NodePerformance {
476    fn default() -> Self {
477        NodePerformance {
478            messages_per_second: 1000.0,
479            avg_response_time: 10.0,
480            uptime: 99.9,
481            error_rate: 0.001,
482        }
483    }
484}
485
486impl Default for ResourceUsage {
487    fn default() -> Self {
488        ResourceUsage {
489            cpu_usage: 25.0,
490            memory_usage: 30.0,
491            network_usage: 15.0,
492            storage_usage: 10.0,
493        }
494    }
495}
496
497impl Default for ConnectionQuality {
498    fn default() -> Self {
499        ConnectionQuality {
500            rtt: 10.0,
501            packet_loss: 0.001,
502            bandwidth: 100_000_000,
503            reliability: 0.999,
504            stability: 0.95,
505        }
506    }
507}
508
509impl Default for NetworkConfig {
510    fn default() -> Self {
511        NetworkConfig {
512            discovery_interval: 30,
513            max_discovery_attempts: 3,
514            connection_timeout: 10,
515            heartbeat_interval: 5,
516            trust_threshold: 0.7,
517            default_port: 8000,
518        }
519    }
520}
521
522impl DiscoveryMetrics {
523    fn new() -> Self {
524        DiscoveryMetrics {
525            total_discovered: 0,
526            active_connections: 0,
527            failed_connections: 0,
528            avg_discovery_time: 0.0,
529            network_coverage: 0.0,
530        }
531    }
532}
533
534impl TopologyMetrics {
535    fn new() -> Self {
536        TopologyMetrics {
537            total_nodes: 0,
538            total_connections: 0,
539            network_diameter: 0,
540            clustering_coefficient: 0.0,
541            network_density: 0.0,
542        }
543    }
544}
545
546/// Network statistics
547#[derive(Debug, Clone, Serialize, Deserialize)]
548pub struct NetworkStats {
549    pub total_organisms: usize,
550    pub online_organisms: usize,
551    pub total_nodes: usize,
552    pub total_connections: usize,
553    pub network_health: f64,
554    pub average_connection_quality: f64,
555}
556
557/// Network-related errors
558#[derive(Debug, thiserror::Error)]
559pub enum NetworkError {
560    #[error("Organism not found: {0}")]
561    OrganismNotFound(String),
562    #[error("Organism offline: {0}")]
563    OrganismOffline(String),
564    #[error("Connection failed: {0}")]
565    ConnectionFailed(String),
566    #[error("Discovery failed: {0}")]
567    DiscoveryFailed(String),
568    #[error("Network timeout")]
569    NetworkTimeout,
570    #[error("Invalid address: {0}")]
571    InvalidAddress(String),
572    #[error("Protocol not supported: {0}")]
573    ProtocolNotSupported(String),
574    #[error("Network overloaded")]
575    NetworkOverloaded,
576}
577
578#[cfg(test)]
579mod tests {
580    use super::*;
581
582    #[test]
583    fn test_network_discovery_creation() {
584        let discovery = NetworkDiscovery::new().unwrap();
585        assert_eq!(discovery.known_organisms.len(), 0);
586        assert_eq!(discovery.topology.nodes.len(), 0);
587    }
588
589    #[tokio::test]
590    async fn test_organism_discovery() {
591        let mut discovery = NetworkDiscovery::new().unwrap();
592        
593        let discovered = discovery.discover_organisms().await.unwrap();
594        assert!(discovered.len() > 0);
595        assert_eq!(discovery.known_organisms.len(), discovered.len());
596        
597        for organism_id in &discovered {
598            assert!(discovery.known_organisms.contains_key(organism_id));
599        }
600    }
601
602    #[tokio::test]
603    async fn test_organism_connection() {
604        let mut discovery = NetworkDiscovery::new().unwrap();
605        
606        let discovered = discovery.discover_organisms().await.unwrap();
607        if let Some(organism_id) = discovered.first() {
608            let result = discovery.connect_to_organism(organism_id).await;
609            assert!(result.is_ok());
610            assert_eq!(discovery.known_organisms[organism_id].status, NodeStatus::Online);
611        }
612    }
613
614    #[test]
615    fn test_topology_update() {
616        let mut discovery = NetworkDiscovery::new().unwrap();
617        
618        // Add some organisms
619        let organism1 = OrganismNode {
620            organism_id: "tron_1".to_string(),
621            address: "127.0.0.1:8000".parse().unwrap(),
622            capabilities: NodeCapabilities::default(),
623            status: NodeStatus::Online,
624            last_seen: 0,
625            connection_quality: 0.8,
626            trust_level: 0.7,
627            performance: NodePerformance::default(),
628        };
629        
630        discovery.known_organisms.insert("tron_1".to_string(), organism1);
631        
632        discovery.update_topology();
633        
634        assert_eq!(discovery.topology.nodes.len(), 1);
635    }
636
637    #[test]
638    fn test_network_stats() {
639        let mut discovery = NetworkDiscovery::new().unwrap();
640        
641        // Add organisms
642        for i in 0..3 {
643            let organism = OrganismNode {
644                organism_id: format!("tron_{}", i),
645                address: format!("127.0.0.1:{}", 8000 + i).parse().unwrap(),
646                capabilities: NodeCapabilities::default(),
647                status: NodeStatus::Online,
648                last_seen: 0,
649                connection_quality: 0.8,
650                trust_level: 0.7,
651                performance: NodePerformance::default(),
652            };
653            
654            discovery.known_organisms.insert(format!("tron_{}", i), organism);
655        }
656        
657        let stats = discovery.get_network_stats();
658        assert_eq!(stats.total_organisms, 3);
659        assert_eq!(stats.online_organisms, 3);
660        assert!(stats.network_health > 0.0);
661    }
662}