genesis_protocol/
neural.rs

1//! 🧠 Neural Communication System
2//!
3//! This module implements the revolutionary neural communication protocol that
4//! enables direct mind-to-mind communication between TRON organisms with
5//! sub-millisecond latency using biological neurotransmitter simulation.
6
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::time::{SystemTime, UNIX_EPOCH};
10use tokio::sync::mpsc;
11use uuid::Uuid;
12
13/// Neural message for organism communication
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct NeuralMessage {
16    /// Unique message identifier
17    pub message_id: String,
18    /// ID of sending organism
19    pub sender_id: String,
20    /// ID of receiving organism
21    pub receiver_id: String,
22    /// Type of neural message
23    pub message_type: MessageType,
24    /// Neurotransmitter used for transmission
25    pub neurotransmitter: NeurotransmitterType,
26    /// Message payload
27    pub payload: Vec<u8>,
28    /// Message creation timestamp (nanoseconds)
29    pub timestamp: u64,
30    /// Time to live (seconds)
31    pub ttl: u64,
32    /// Cryptographic signature
33    pub signature: Vec<u8>,
34    /// Message urgency level (0.0-1.0)
35    pub urgency: f64,
36    /// Message priority (0-255)
37    pub priority: u8,
38    /// Routing information
39    pub routing: RoutingInfo,
40}
41
42/// Types of neural messages
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub enum MessageType {
45    /// Shared consciousness and awareness
46    Consciousness,
47    /// Environmental stimulus input
48    Stimulus,
49    /// Behavioral response output
50    Response,
51    /// Genetic/evolution information
52    Evolution,
53    /// Collective intelligence coordination
54    Collective,
55    /// Reproduction and mating signals
56    Reproduction,
57    /// Cell death/cleanup signal
58    Apoptosis,
59    /// Learning and knowledge sharing
60    Learning,
61    /// Memory synchronization
62    Memory,
63    /// Emotional state communication
64    Emotion,
65    /// Social interaction
66    Social,
67    /// Warning/alert signals
68    Warning,
69    /// Resource sharing information
70    Resource,
71    /// System maintenance
72    Maintenance,
73}
74
75/// Biological neurotransmitter types
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub enum NeurotransmitterType {
78    /// Excitatory neurotransmitter - general communication
79    Glutamate,
80    /// Inhibitory neurotransmitter - suppression signals
81    GABA,
82    /// Reward and motivation signals
83    Dopamine,
84    /// Mood and wellbeing regulation
85    Serotonin,
86    /// Attention and learning enhancement
87    Acetylcholine,
88    /// Stress and alertness signals
89    Norepinephrine,
90    /// Social bonding and trust
91    Oxytocin,
92    /// Pain relief and pleasure
93    Endorphin,
94    /// Memory formation and consolidation
95    Histamine,
96    /// Sleep and arousal regulation
97    Adenosine,
98}
99
100/// Message routing information
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct RoutingInfo {
103    /// Direct connection or multi-hop
104    pub direct: bool,
105    /// Hop count for multi-hop messages
106    pub hop_count: u8,
107    /// Path taken through network
108    pub path: Vec<String>,
109    /// Quality of service requirements
110    pub qos: QualityOfService,
111}
112
113/// Quality of service parameters
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct QualityOfService {
116    /// Maximum acceptable latency (nanoseconds)
117    pub max_latency: u64,
118    /// Reliability requirement (0.0-1.0)
119    pub reliability: f64,
120    /// Bandwidth requirement (bytes/second)
121    pub bandwidth: u64,
122    /// Encryption requirement
123    pub encryption: bool,
124}
125
126/// Synaptic connection between organisms
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct Synapse {
129    /// Unique connection identifier
130    pub connection_id: String,
131    /// Presynaptic organism (sender)
132    pub presynaptic_id: String,
133    /// Postsynaptic organism (receiver)
134    pub postsynaptic_id: String,
135    /// Connection strength (0.0-1.0)
136    pub strength: f64,
137    /// Primary neurotransmitter type
138    pub neurotransmitter_type: NeurotransmitterType,
139    /// Last activity timestamp
140    pub last_activity: u64,
141    /// Total messages transmitted
142    pub total_messages: u64,
143    /// Message success rate
144    pub success_rate: f64,
145    /// Connection creation time
146    pub created_at: u64,
147    /// Synaptic plasticity (ability to change)
148    pub plasticity: f64,
149    /// Connection latency statistics
150    pub latency_stats: LatencyStats,
151    /// Connection state
152    pub state: SynapseState,
153    /// Bidirectional capability
154    pub bidirectional: bool,
155}
156
157/// Synaptic connection states
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum SynapseState {
160    /// Connection is being established
161    Establishing,
162    /// Connection is active and ready
163    Active,
164    /// Connection is temporarily disabled
165    Inactive,
166    /// Connection is being strengthened
167    Potentiating,
168    /// Connection is being weakened
169    Depressing,
170    /// Connection is being terminated
171    Terminating,
172    /// Connection is closed
173    Closed,
174}
175
176/// Latency measurement statistics
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct LatencyStats {
179    /// Minimum recorded latency (nanoseconds)
180    pub min_latency: u64,
181    /// Maximum recorded latency (nanoseconds)
182    pub max_latency: u64,
183    /// Average latency (nanoseconds)
184    pub avg_latency: u64,
185    /// Latest latency measurement
186    pub last_latency: u64,
187    /// Number of latency measurements
188    pub measurement_count: u64,
189    /// Latency variance
190    pub variance: f64,
191}
192
193impl Synapse {
194    /// Establish a new synaptic connection
195    pub fn establish(from_id: &str, to_id: &str) -> Result<Self, SynapseError> {
196        let from_safe = if from_id.len() >= 8 { &from_id[..8] } else { from_id };
197        let to_safe = if to_id.len() >= 8 { &to_id[..8] } else { to_id };
198        let connection_id = format!("synapse_{}_{}_{}",
199            from_safe,
200            to_safe,
201            &Uuid::new_v4().to_string()[..8]
202        );
203        
204        Ok(Synapse {
205            connection_id,
206            presynaptic_id: from_id.to_string(),
207            postsynaptic_id: to_id.to_string(),
208            strength: 0.5, // Start with medium strength
209            neurotransmitter_type: NeurotransmitterType::Glutamate, // Default excitatory
210            last_activity: 0,
211            total_messages: 0,
212            success_rate: 1.0,
213            created_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
214            plasticity: 0.8, // High plasticity initially
215            latency_stats: LatencyStats::new(),
216            state: SynapseState::Establishing,
217            bidirectional: true,
218        })
219    }
220    
221    /// Transmit a neural message through this synapse
222    pub async fn transmit(&self, message: NeuralMessage) -> Result<(), SynapseError> {
223        // Validate synapse state
224        if self.state != SynapseState::Active && self.state != SynapseState::Establishing {
225            return Err(SynapseError::SynapseInactive);
226        }
227        
228        // Validate message
229        if !self.validate_message(&message) {
230            return Err(SynapseError::InvalidMessage);
231        }
232        
233        let transmission_start = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64;
234        
235        // Simulate biological neurotransmitter release delay
236        let delay = self.calculate_transmission_delay(&message);
237        if delay > 0 {
238            tokio::time::sleep(tokio::time::Duration::from_nanos(delay)).await;
239        }
240        
241        // Simulate actual message transmission
242        // In a real implementation, this would send over network
243        self.simulate_network_transmission(&message).await?;
244        
245        let transmission_end = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64;
246        let latency = transmission_end - transmission_start;
247        
248        // Update latency statistics
249        // Note: In real implementation, this would require &mut self
250        let sender_safe = if message.sender_id.len() >= 8 { &message.sender_id[..8] } else { &message.sender_id };
251        let receiver_safe = if message.receiver_id.len() >= 8 { &message.receiver_id[..8] } else { &message.receiver_id };
252        tracing::debug!(
253            "Neural message transmitted: {} -> {} in {}ns",
254            sender_safe,
255            receiver_safe,
256            latency
257        );
258        
259        // Verify latency target
260        if latency > crate::TARGET_NEURAL_LATENCY_NS {
261            tracing::warn!(
262                "Neural transmission exceeded target latency: {}ns > {}ns",
263                latency,
264                crate::TARGET_NEURAL_LATENCY_NS
265            );
266        }
267        
268        Ok(())
269    }
270    
271    /// Strengthen the synaptic connection
272    pub fn strengthen(&mut self, factor: f64) {
273        if self.plasticity > 0.0 && self.state == SynapseState::Active {
274            self.state = SynapseState::Potentiating;
275            self.strength += factor * self.plasticity;
276            if self.strength > 1.0 {
277                self.strength = 1.0;
278            }
279            
280            // Reduce plasticity slightly (Hebbian learning)
281            self.plasticity *= 0.995;
282            
283            // Return to active state
284            self.state = SynapseState::Active;
285        }
286    }
287    
288    /// Weaken the synaptic connection
289    pub fn weaken(&mut self, factor: f64) {
290        if self.plasticity > 0.0 && self.state == SynapseState::Active {
291            self.state = SynapseState::Depressing;
292            self.strength -= factor * self.plasticity;
293            if self.strength < 0.0 {
294                self.strength = 0.0;
295            }
296            
297            // Reduce plasticity slightly
298            self.plasticity *= 0.995;
299            
300            // Return to active state or close if too weak
301            if self.strength < 0.1 {
302                self.state = SynapseState::Closed;
303            } else {
304                self.state = SynapseState::Active;
305            }
306        }
307    }
308    
309    /// Calculate biological transmission delay
310    fn calculate_transmission_delay(&self, message: &NeuralMessage) -> u64 {
311        // Base delay depends on neurotransmitter type (biological realistic values)
312        let base_delay = match message.neurotransmitter {
313            NeurotransmitterType::Glutamate => 500,        // 0.5 microseconds
314            NeurotransmitterType::GABA => 1_000,           // 1 microsecond
315            NeurotransmitterType::Dopamine => 2_000,       // 2 microseconds
316            NeurotransmitterType::Serotonin => 5_000,      // 5 microseconds
317            NeurotransmitterType::Acetylcholine => 1_500,  // 1.5 microseconds
318            NeurotransmitterType::Norepinephrine => 2_500, // 2.5 microseconds
319            NeurotransmitterType::Oxytocin => 10_000,      // 10 microseconds
320            NeurotransmitterType::Endorphin => 15_000,     // 15 microseconds
321            NeurotransmitterType::Histamine => 3_000,      // 3 microseconds
322            NeurotransmitterType::Adenosine => 8_000,      // 8 microseconds
323        };
324        
325        // Adjust based on synapse strength (stronger = faster)
326        let strength_factor = 2.0 - self.strength;
327        let adjusted_delay = (base_delay as f64 * strength_factor) as u64;
328        
329        // Adjust based on message urgency (urgent = faster)
330        let urgency_factor = 2.0 - message.urgency;
331        let final_delay = (adjusted_delay as f64 * urgency_factor) as u64;
332        
333        // Add small random jitter for biological realism
334        let jitter = rand::random::<u64>() % 100; // Up to 100ns jitter
335        final_delay + jitter
336    }
337    
338    /// Validate neural message
339    fn validate_message(&self, message: &NeuralMessage) -> bool {
340        // Check sender/receiver match
341        if message.sender_id != self.presynaptic_id {
342            return false;
343        }
344        
345        if message.receiver_id != self.postsynaptic_id {
346            return false;
347        }
348        
349        // Check message age
350        let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64;
351        if current_time - message.timestamp > (message.ttl * 1_000_000_000) {
352            return false; // Message expired
353        }
354        
355        // Check message size (prevent DoS)
356        if message.payload.len() > 1_048_576 { // 1MB limit
357            return false;
358        }
359        
360        true
361    }
362    
363    /// Simulate network transmission
364    async fn simulate_network_transmission(&self, message: &NeuralMessage) -> Result<(), SynapseError> {
365        // In real implementation, this would:
366        // 1. Serialize message
367        // 2. Send over network (TCP/UDP/custom protocol)
368        // 3. Handle network errors and retransmission
369        // 4. Update connection statistics
370        
371        // For now, simulate minimal delay
372        let network_delay = if message.routing.direct {
373            100 // 100ns for direct connection
374        } else {
375            message.routing.hop_count as u64 * 500 // 500ns per hop
376        };
377        
378        if network_delay > 0 {
379            tokio::time::sleep(tokio::time::Duration::from_nanos(network_delay)).await;
380        }
381        
382        // Simulate occasional network failures
383        if rand::random::<f64>() < 0.001 { // 0.1% failure rate
384            return Err(SynapseError::NetworkError("Simulated network failure".to_string()));
385        }
386        
387        Ok(())
388    }
389    
390    /// Update latency statistics
391    pub fn update_latency_stats(&mut self, latency: u64) {
392        self.latency_stats.add_measurement(latency);
393    }
394    
395    /// Get connection performance metrics
396    pub fn get_performance_metrics(&self) -> SynapsePerformance {
397        SynapsePerformance {
398            connection_id: self.connection_id.clone(),
399            strength: self.strength,
400            success_rate: self.success_rate,
401            total_messages: self.total_messages,
402            avg_latency: self.latency_stats.avg_latency,
403            min_latency: self.latency_stats.min_latency,
404            max_latency: self.latency_stats.max_latency,
405            plasticity: self.plasticity,
406            state: self.state.clone(),
407            uptime_seconds: SystemTime::now()
408                .duration_since(UNIX_EPOCH)
409                .unwrap()
410                .as_secs() - self.created_at,
411        }
412    }
413}
414
415impl LatencyStats {
416    pub fn new() -> Self {
417        LatencyStats {
418            min_latency: u64::MAX,
419            max_latency: 0,
420            avg_latency: 0,
421            last_latency: 0,
422            measurement_count: 0,
423            variance: 0.0,
424        }
425    }
426    
427    pub fn add_measurement(&mut self, latency: u64) {
428        self.last_latency = latency;
429        self.measurement_count += 1;
430        
431        if latency < self.min_latency {
432            self.min_latency = latency;
433        }
434        
435        if latency > self.max_latency {
436            self.max_latency = latency;
437        }
438        
439        // Update running average
440        self.avg_latency = ((self.avg_latency * (self.measurement_count - 1)) + latency) / self.measurement_count;
441        
442        // Update variance (simplified calculation)
443        let diff = latency as f64 - self.avg_latency as f64;
444        self.variance = ((self.variance * (self.measurement_count - 1) as f64) + (diff * diff)) / self.measurement_count as f64;
445    }
446}
447
448/// Neural protocol for organism communication
449pub struct NeuralProtocol {
450    /// Organism ID this protocol belongs to
451    pub organism_id: String,
452    /// Active synaptic connections
453    pub synapses: HashMap<String, Synapse>,
454    /// Incoming message queue
455    pub message_queue: HashMap<String, Vec<NeuralMessage>>,
456    /// Current neural activity level
457    pub neural_activity: f64,
458    /// Consciousness level
459    pub consciousness_level: f64,
460    /// Message sender channel
461    pub message_sender: mpsc::UnboundedSender<NeuralMessage>,
462    /// Message receiver channel
463    pub message_receiver: mpsc::UnboundedReceiver<NeuralMessage>,
464    /// Protocol statistics
465    pub stats: ProtocolStats,
466}
467
468/// Protocol performance statistics
469#[derive(Debug, Clone, Default)]
470pub struct ProtocolStats {
471    /// Total messages sent
472    pub messages_sent: u64,
473    /// Total messages received
474    pub messages_received: u64,
475    /// Total failed transmissions
476    pub transmission_failures: u64,
477    /// Average processing time per message
478    pub avg_processing_time: u64,
479    /// Total protocol uptime
480    pub uptime_seconds: u64,
481    /// Peak neural activity recorded
482    pub peak_neural_activity: f64,
483    /// Peak consciousness level recorded
484    pub peak_consciousness: f64,
485}
486
487impl NeuralProtocol {
488    /// Create new neural protocol for organism
489    pub fn new(organism_id: String) -> Self {
490        let (sender, receiver) = mpsc::unbounded_channel();
491        
492        NeuralProtocol {
493            organism_id,
494            synapses: HashMap::new(),
495            message_queue: HashMap::new(),
496            neural_activity: 0.1,
497            consciousness_level: 0.0,
498            message_sender: sender,
499            message_receiver: receiver,
500            stats: ProtocolStats::default(),
501        }
502    }
503    
504    /// Establish synaptic connection to target organism
505    pub async fn establish_synapse(
506        &mut self,
507        target_id: &str,
508        neurotransmitter: NeurotransmitterType
509    ) -> Result<String, SynapseError> {
510        if self.synapses.len() >= crate::MAX_SYNAPSES_PER_ORGANISM {
511            return Err(SynapseError::TooManySynapses);
512        }
513        
514        let mut synapse = Synapse::establish(&self.organism_id, target_id)?;
515        synapse.neurotransmitter_type = neurotransmitter;
516        synapse.state = SynapseState::Active;
517        
518        let connection_id = synapse.connection_id.clone();
519        self.synapses.insert(target_id.to_string(), synapse);
520        
521        // Update neural activity
522        self.neural_activity += 0.05;
523        if self.neural_activity > 1.0 {
524            self.neural_activity = 1.0;
525        }
526        
527        if self.neural_activity > self.stats.peak_neural_activity {
528            self.stats.peak_neural_activity = self.neural_activity;
529        }
530        
531        tracing::info!(
532            "Synapse established: {} -> {} ({})",
533            self.organism_id[..8].to_string(),
534            target_id[..8].to_string(),
535            connection_id[..16].to_string()
536        );
537        
538        Ok(connection_id)
539    }
540    
541    /// Send neural message to target organism
542    pub async fn send_neural_message(
543        &mut self,
544        target_id: &str,
545        message_type: MessageType,
546        payload: Vec<u8>
547    ) -> Result<(), SynapseError> {
548        if let Some(synapse) = self.synapses.get(target_id) {
549            let message = NeuralMessage {
550                message_id: Uuid::new_v4().to_string(),
551                sender_id: self.organism_id.clone(),
552                receiver_id: target_id.to_string(),
553                message_type,
554                neurotransmitter: synapse.neurotransmitter_type.clone(),
555                payload,
556                timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64,
557                ttl: 300, // 5 minutes
558                signature: Vec::new(), // TODO: Sign with organism's DNA
559                urgency: 0.5,
560                priority: 128,
561                routing: RoutingInfo {
562                    direct: true,
563                    hop_count: 1,
564                    path: vec![self.organism_id.clone(), target_id.to_string()],
565                    qos: QualityOfService {
566                        max_latency: crate::TARGET_NEURAL_LATENCY_NS,
567                        reliability: 0.99,
568                        bandwidth: 1_000_000, // 1MB/s
569                        encryption: true,
570                    },
571                },
572            };
573            
574            let transmission_start = SystemTime::now();
575            
576            synapse.transmit(message).await?;
577            
578            let transmission_time = transmission_start.elapsed().unwrap().as_nanos() as u64;
579            
580            // Update statistics
581            self.stats.messages_sent += 1;
582            self.stats.avg_processing_time = 
583                ((self.stats.avg_processing_time * (self.stats.messages_sent - 1)) + transmission_time) 
584                / self.stats.messages_sent;
585            
586            Ok(())
587        } else {
588            Err(SynapseError::SynapseNotFound(target_id.to_string()))
589        }
590    }
591    
592    /// Process incoming neural messages
593    pub async fn process_messages(&mut self) -> Result<Vec<NeuralMessage>, SynapseError> {
594        let mut processed_messages = Vec::new();
595        
596        // Process all queued messages
597        while let Ok(message) = self.message_receiver.try_recv() {
598            let processing_start = SystemTime::now();
599            
600            // Update consciousness based on message type
601            self.update_consciousness(&message);
602            
603            // Store message for processing
604            processed_messages.push(message);
605            
606            let processing_time = processing_start.elapsed().unwrap().as_nanos() as u64;
607            
608            // Update statistics
609            self.stats.messages_received += 1;
610            self.stats.avg_processing_time = 
611                ((self.stats.avg_processing_time * self.stats.messages_received) + processing_time) 
612                / (self.stats.messages_received + 1);
613        }
614        
615        Ok(processed_messages)
616    }
617    
618    /// Update consciousness level based on neural activity
619    fn update_consciousness(&mut self, message: &NeuralMessage) {
620        let consciousness_boost = match message.message_type {
621            MessageType::Consciousness => 0.1,
622            MessageType::Learning => 0.05,
623            MessageType::Collective => 0.03,
624            MessageType::Emotion => 0.04,
625            MessageType::Social => 0.02,
626            _ => 0.01,
627        };
628        
629        self.consciousness_level += consciousness_boost;
630        self.neural_activity += consciousness_boost * 0.5;
631        
632        // Apply consciousness and neural activity decay
633        self.consciousness_level *= 0.999;
634        self.neural_activity *= 0.995;
635        
636        // Cap values
637        if self.consciousness_level > 1.0 {
638            self.consciousness_level = 1.0;
639        }
640        if self.neural_activity > 1.0 {
641            self.neural_activity = 1.0;
642        }
643        
644        // Update peak tracking
645        if self.consciousness_level > self.stats.peak_consciousness {
646            self.stats.peak_consciousness = self.consciousness_level;
647        }
648        if self.neural_activity > self.stats.peak_neural_activity {
649            self.stats.peak_neural_activity = self.neural_activity;
650        }
651    }
652    
653    /// Get neural status
654    pub fn get_neural_status(&self) -> NeuralStatus {
655        NeuralStatus {
656            organism_id: self.organism_id.clone(),
657            synapse_count: self.synapses.len(),
658            neural_activity: self.neural_activity,
659            consciousness_level: self.consciousness_level,
660            message_queue_size: self.message_queue.values().map(|v| v.len()).sum(),
661            average_synapse_strength: if self.synapses.is_empty() {
662                0.0
663            } else {
664                self.synapses.values().map(|s| s.strength).sum::<f64>() / self.synapses.len() as f64
665            },
666            total_messages_sent: self.stats.messages_sent,
667            total_messages_received: self.stats.messages_received,
668            avg_processing_time: self.stats.avg_processing_time,
669        }
670    }
671    
672    /// Cleanup inactive synapses
673    pub fn cleanup_synapses(&mut self) -> usize {
674        let initial_count = self.synapses.len();
675        
676        self.synapses.retain(|_, synapse| {
677            // Only remove explicitly closed synapses for now
678            synapse.state != SynapseState::Closed
679        });
680        
681        initial_count - self.synapses.len()
682    }
683}
684
685/// Neural status information
686#[derive(Debug, Clone, Serialize, Deserialize)]
687pub struct NeuralStatus {
688    pub organism_id: String,
689    pub synapse_count: usize,
690    pub neural_activity: f64,
691    pub consciousness_level: f64,
692    pub message_queue_size: usize,
693    pub average_synapse_strength: f64,
694    pub total_messages_sent: u64,
695    pub total_messages_received: u64,
696    pub avg_processing_time: u64,
697}
698
699/// Synapse performance metrics
700#[derive(Debug, Clone, Serialize, Deserialize)]
701pub struct SynapsePerformance {
702    pub connection_id: String,
703    pub strength: f64,
704    pub success_rate: f64,
705    pub total_messages: u64,
706    pub avg_latency: u64,
707    pub min_latency: u64,
708    pub max_latency: u64,
709    pub plasticity: f64,
710    pub state: SynapseState,
711    pub uptime_seconds: u64,
712}
713
714/// Neural communication errors
715#[derive(Debug, thiserror::Error)]
716pub enum SynapseError {
717    #[error("Synapse not found: {0}")]
718    SynapseNotFound(String),
719    #[error("Invalid message format")]
720    InvalidMessage,
721    #[error("Transmission failed: {0}")]
722    TransmissionFailed(String),
723    #[error("Connection refused")]
724    ConnectionRefused,
725    #[error("Synapse inactive")]
726    SynapseInactive,
727    #[error("Too many synapses")]
728    TooManySynapses,
729    #[error("Network error: {0}")]
730    NetworkError(String),
731    #[error("Message expired")]
732    MessageExpired,
733    #[error("Message too large")]
734    MessageTooLarge,
735    #[error("Neurotransmitter mismatch")]
736    NeurotransmitterMismatch,
737    #[error("Insufficient strength")]
738    InsufficientStrength,
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744
745    #[test]
746    fn test_synapse_creation() {
747        let synapse = Synapse::establish("tron_1", "tron_2").unwrap();
748        assert!(!synapse.connection_id.is_empty());
749        assert_eq!(synapse.presynaptic_id, "tron_1");
750        assert_eq!(synapse.postsynaptic_id, "tron_2");
751        assert_eq!(synapse.strength, 0.5);
752        assert_eq!(synapse.state, SynapseState::Establishing);
753    }
754
755    #[tokio::test]
756    async fn test_neural_message_transmission() {
757        let mut synapse = Synapse::establish("tron_1", "tron_2").unwrap();
758        synapse.state = SynapseState::Active;
759        
760        let message = NeuralMessage {
761            message_id: Uuid::new_v4().to_string(),
762            sender_id: "tron_1".to_string(),
763            receiver_id: "tron_2".to_string(),
764            message_type: MessageType::Consciousness,
765            neurotransmitter: NeurotransmitterType::Glutamate,
766            payload: b"Hello, digital mind!".to_vec(),
767            timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64,
768            ttl: 300,
769            signature: Vec::new(),
770            urgency: 0.5,
771            priority: 128,
772            routing: RoutingInfo {
773                direct: true,
774                hop_count: 1,
775                path: vec!["tron_1".to_string(), "tron_2".to_string()],
776                qos: QualityOfService {
777                    max_latency: 10_000,
778                    reliability: 0.99,
779                    bandwidth: 1_000_000,
780                    encryption: true,
781                },
782            },
783        };
784        
785        let result = synapse.transmit(message).await;
786        assert!(result.is_ok());
787    }
788
789    #[test]
790    fn test_synapse_strengthening() {
791        let mut synapse = Synapse::establish("tron_1", "tron_2").unwrap();
792        synapse.state = SynapseState::Active;
793        let initial_strength = synapse.strength;
794        
795        synapse.strengthen(0.1);
796        assert!(synapse.strength > initial_strength);
797        assert!(synapse.plasticity < 0.8); // Should decrease slightly
798    }
799
800    #[test]
801    fn test_synapse_weakening() {
802        let mut synapse = Synapse::establish("tron_1", "tron_2").unwrap();
803        synapse.state = SynapseState::Active;
804        let initial_strength = synapse.strength;
805        
806        synapse.weaken(0.1);
807        assert!(synapse.strength < initial_strength);
808    }
809
810    #[tokio::test]
811    async fn test_neural_protocol() {
812        let mut protocol = NeuralProtocol::new("tron_1".to_string());
813        
814        let synapse_id = protocol.establish_synapse(
815            "tron_2",
816            NeurotransmitterType::Dopamine
817        ).await.unwrap();
818        
819        assert!(!synapse_id.is_empty());
820        assert!(protocol.synapses.contains_key("tron_2"));
821        assert!(protocol.neural_activity > 0.1);
822        
823        let result = protocol.send_neural_message(
824            "tron_2",
825            MessageType::Consciousness,
826            b"Neural test message".to_vec()
827        ).await;
828        
829        assert!(result.is_ok());
830        assert_eq!(protocol.stats.messages_sent, 1);
831    }
832
833    #[test]
834    fn test_latency_stats() {
835        let mut stats = LatencyStats::new();
836        
837        stats.add_measurement(1000);
838        stats.add_measurement(2000);
839        stats.add_measurement(1500);
840        
841        assert_eq!(stats.measurement_count, 3);
842        assert_eq!(stats.min_latency, 1000);
843        assert_eq!(stats.max_latency, 2000);
844        assert_eq!(stats.avg_latency, 1500);
845    }
846
847    #[test]
848    fn test_transmission_delay_calculation() {
849        let synapse = Synapse::establish("tron_1", "tron_2").unwrap();
850        
851        let message = NeuralMessage {
852            message_id: Uuid::new_v4().to_string(),
853            sender_id: "tron_1".to_string(),
854            receiver_id: "tron_2".to_string(),
855            message_type: MessageType::Consciousness,
856            neurotransmitter: NeurotransmitterType::Glutamate,
857            payload: Vec::new(),
858            timestamp: 0,
859            ttl: 300,
860            signature: Vec::new(),
861            urgency: 1.0, // Maximum urgency
862            priority: 255,
863            routing: RoutingInfo {
864                direct: true,
865                hop_count: 1,
866                path: vec!["tron_1".to_string(), "tron_2".to_string()],
867                qos: QualityOfService {
868                    max_latency: 10_000,
869                    reliability: 0.99,
870                    bandwidth: 1_000_000,
871                    encryption: true,
872                },
873            },
874        };
875        
876        let delay = synapse.calculate_transmission_delay(&message);
877        
878        // Should be less than base delay due to high urgency and medium strength
879        assert!(delay < 1000); // Should be less than 1 microsecond
880    }
881
882    #[test]
883    fn test_message_validation() {
884        let synapse = Synapse::establish("tron_1", "tron_2").unwrap();
885        
886        let valid_message = NeuralMessage {
887            message_id: Uuid::new_v4().to_string(),
888            sender_id: "tron_1".to_string(),
889            receiver_id: "tron_2".to_string(),
890            message_type: MessageType::Consciousness,
891            neurotransmitter: NeurotransmitterType::Glutamate,
892            payload: b"test".to_vec(),
893            timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64,
894            ttl: 300,
895            signature: Vec::new(),
896            urgency: 0.5,
897            priority: 128,
898            routing: RoutingInfo {
899                direct: true,
900                hop_count: 1,
901                path: vec!["tron_1".to_string(), "tron_2".to_string()],
902                qos: QualityOfService {
903                    max_latency: 10_000,
904                    reliability: 0.99,
905                    bandwidth: 1_000_000,
906                    encryption: true,
907                },
908            },
909        };
910        
911        assert!(synapse.validate_message(&valid_message));
912        
913        // Test invalid sender
914        let mut invalid_message = valid_message.clone();
915        invalid_message.sender_id = "wrong_sender".to_string();
916        assert!(!synapse.validate_message(&invalid_message));
917    }
918
919    #[tokio::test]
920    async fn test_neural_protocol_cleanup() {
921        let mut protocol = NeuralProtocol::new("tron_1".to_string());
922        
923        // Create some synapses
924        protocol.establish_synapse("tron_2", NeurotransmitterType::Glutamate).await.unwrap();
925        protocol.establish_synapse("tron_3", NeurotransmitterType::GABA).await.unwrap();
926        
927        // Close one synapse
928        if let Some(synapse) = protocol.synapses.get_mut("tron_2") {
929            synapse.state = SynapseState::Closed;
930        }
931        
932        let cleaned = protocol.cleanup_synapses();
933        assert_eq!(cleaned, 1);
934        assert_eq!(protocol.synapses.len(), 1);
935        assert!(protocol.synapses.contains_key("tron_3"));
936    }
937}