quantrs2_device/photonic/
protocols.rs

1//! Photonic Quantum Communication Protocols
2//!
3//! This module implements quantum communication protocols specifically designed for
4//! photonic systems, including quantum key distribution, teleportation, and networking.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::time::{Duration, Instant};
9use thiserror::Error;
10
11use super::continuous_variable::{CVResult, Complex, GaussianState};
12use super::gate_based::{PhotonicQubitEncoding, PhotonicQubitState};
13use super::{PhotonicMode, PhotonicSystemType};
14use crate::DeviceResult;
15use scirs2_core::random::prelude::*;
16
17/// Photonic protocol errors
18#[derive(Error, Debug)]
19pub enum PhotonicProtocolError {
20    #[error("Protocol execution failed: {0}")]
21    ExecutionFailed(String),
22    #[error("Authentication failed: {0}")]
23    AuthenticationFailed(String),
24    #[error("Security violation: {0}")]
25    SecurityViolation(String),
26    #[error("Network communication error: {0}")]
27    NetworkError(String),
28    #[error("Protocol not supported: {0}")]
29    UnsupportedProtocol(String),
30}
31
32/// Types of photonic quantum protocols
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub enum PhotonicProtocolType {
35    /// Quantum Key Distribution
36    QKD { variant: QKDVariant },
37    /// Quantum Teleportation
38    Teleportation,
39    /// Quantum State Distribution
40    StateDistribution,
41    /// Quantum Clock Synchronization
42    ClockSynchronization,
43    /// Quantum Sensing Networks
44    SensingNetwork,
45    /// Quantum Internet Protocols
46    QuantumInternet { protocol_version: String },
47}
48
49/// QKD protocol variants
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub enum QKDVariant {
52    /// BB84 protocol
53    BB84,
54    /// B92 protocol
55    B92,
56    /// SARG04 protocol
57    SARG04,
58    /// Continuous Variable QKD
59    CVQKD { modulation: CVModulation },
60    /// Measurement Device Independent QKD
61    MDIQKD,
62    /// Twin Field QKD
63    TwinField,
64}
65
66/// CV QKD modulation schemes
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum CVModulation {
69    /// Gaussian modulation
70    Gaussian { variance: f64 },
71    /// Discrete modulation
72    Discrete { constellation_size: usize },
73    /// Heterodyne detection
74    Heterodyne,
75    /// Homodyne detection
76    Homodyne,
77}
78
79/// Protocol execution context
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct ProtocolContext {
82    /// Protocol identifier
83    pub protocol_id: String,
84    /// Participating parties
85    pub parties: Vec<ProtocolParty>,
86    /// Security parameters
87    pub security_params: SecurityParameters,
88    /// Network configuration
89    pub network_config: NetworkConfiguration,
90    /// Start time
91    #[serde(with = "instant_serde")]
92    pub start_time: Instant,
93}
94
95/// Party in a quantum protocol
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct ProtocolParty {
98    /// Party identifier
99    pub party_id: String,
100    /// Role in protocol
101    pub role: PartyRole,
102    /// Communication endpoints
103    pub endpoints: Vec<String>,
104    /// Capabilities
105    pub capabilities: PartyCapabilities,
106}
107
108/// Role of a party in quantum protocols
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub enum PartyRole {
111    /// Alice (sender)
112    Alice,
113    /// Bob (receiver)
114    Bob,
115    /// Charlie (trusted third party)
116    Charlie,
117    /// Eve (eavesdropper - for security analysis)
118    Eve,
119    /// Network node
120    NetworkNode { node_id: String },
121}
122
123/// Capabilities of a protocol party
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct PartyCapabilities {
126    /// Supported encodings
127    pub encodings: Vec<PhotonicQubitEncoding>,
128    /// Detection efficiency
129    pub detection_efficiency: f64,
130    /// Maximum transmission rate
131    pub max_rate: f64,
132    /// Supported wavelengths
133    pub wavelengths: Vec<f64>,
134    /// Distance limitations
135    pub max_distance: Option<f64>,
136}
137
138/// Security parameters for protocols
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct SecurityParameters {
141    /// Required security level (bits)
142    pub security_level: usize,
143    /// Error tolerance
144    pub error_tolerance: f64,
145    /// Privacy amplification parameters
146    pub privacy_amplification: PrivacyAmplificationParams,
147    /// Authentication method
148    pub authentication: AuthenticationMethod,
149}
150
151/// Privacy amplification parameters
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct PrivacyAmplificationParams {
154    /// Hash function family
155    pub hash_family: String,
156    /// Compression ratio
157    pub compression_ratio: f64,
158    /// Number of rounds
159    pub rounds: usize,
160}
161
162/// Authentication methods
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub enum AuthenticationMethod {
165    /// Classical authentication
166    Classical { algorithm: String },
167    /// Quantum authentication
168    Quantum { protocol: String },
169    /// Post-quantum cryptography
170    PostQuantum { algorithm: String },
171}
172
173/// Network configuration
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct NetworkConfiguration {
176    /// Topology type
177    pub topology: NetworkTopology,
178    /// Channel characteristics
179    pub channels: Vec<QuantumChannel>,
180    /// Routing configuration
181    pub routing: RoutingConfig,
182}
183
184/// Network topology types
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub enum NetworkTopology {
187    /// Point-to-point
188    PointToPoint,
189    /// Star network
190    Star { hub: String },
191    /// Ring network
192    Ring,
193    /// Mesh network
194    Mesh,
195    /// Tree network
196    Tree { root: String },
197}
198
199/// Quantum communication channel
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct QuantumChannel {
202    /// Channel identifier
203    pub channel_id: String,
204    /// Source party
205    pub source: String,
206    /// Destination party
207    pub destination: String,
208    /// Channel characteristics
209    pub characteristics: ChannelCharacteristics,
210}
211
212/// Physical characteristics of quantum channels
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct ChannelCharacteristics {
215    /// Loss rate (dB/km)
216    pub loss_rate: f64,
217    /// Dark count rate
218    pub dark_count_rate: f64,
219    /// Channel length (km)
220    pub length: f64,
221    /// Wavelength (nm)
222    pub wavelength: f64,
223    /// Detector efficiency
224    pub detector_efficiency: f64,
225}
226
227/// Routing configuration
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct RoutingConfig {
230    /// Routing algorithm
231    pub algorithm: RoutingAlgorithm,
232    /// Maximum hops
233    pub max_hops: usize,
234    /// Load balancing enabled
235    pub load_balancing: bool,
236}
237
238/// Routing algorithms
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240pub enum RoutingAlgorithm {
241    /// Shortest path
242    ShortestPath,
243    /// Minimum loss
244    MinimumLoss,
245    /// Load balanced
246    LoadBalanced,
247    /// Quantum-aware routing
248    QuantumAware,
249}
250
251/// Protocol execution result
252#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct ProtocolResult {
254    /// Whether protocol succeeded
255    pub success: bool,
256    /// Generated key (for QKD)
257    pub key: Option<Vec<u8>>,
258    /// Transmitted state (for teleportation)
259    pub transmitted_state: Option<PhotonicQubitState>,
260    /// Protocol metrics
261    pub metrics: ProtocolMetrics,
262    /// Security analysis
263    pub security_analysis: SecurityAnalysis,
264}
265
266/// Protocol performance metrics
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ProtocolMetrics {
269    /// Execution time
270    pub execution_time: Duration,
271    /// Key rate (bits/second)
272    pub key_rate: Option<f64>,
273    /// Error rate
274    pub error_rate: f64,
275    /// Fidelity
276    pub fidelity: f64,
277    /// Throughput
278    pub throughput: f64,
279}
280
281/// Security analysis results
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct SecurityAnalysis {
284    /// Information leakage estimate
285    pub information_leakage: f64,
286    /// Eavesdropping detection
287    pub eavesdropping_detected: bool,
288    /// Security proof validity
289    pub security_proof_valid: bool,
290    /// Achieved security level
291    pub achieved_security: f64,
292}
293
294/// Photonic protocol engine
295pub struct PhotonicProtocolEngine {
296    /// Active protocols
297    pub active_protocols: HashMap<String, ProtocolContext>,
298    /// Protocol statistics
299    pub statistics: ProtocolStatistics,
300    /// Security monitor
301    pub security_monitor: SecurityMonitor,
302}
303
304/// Protocol execution statistics
305#[derive(Debug, Clone, Serialize, Deserialize)]
306pub struct ProtocolStatistics {
307    /// Total protocols executed
308    pub total_protocols: usize,
309    /// Success rate
310    pub success_rate: f64,
311    /// Average key rate
312    pub average_key_rate: f64,
313    /// Average fidelity
314    pub average_fidelity: f64,
315    /// Security violations detected
316    pub security_violations: usize,
317}
318
319/// Security monitoring system
320#[derive(Debug, Clone)]
321pub struct SecurityMonitor {
322    /// Threat detection enabled
323    pub threat_detection: bool,
324    /// Anomaly detection threshold
325    pub anomaly_threshold: f64,
326    /// Security events
327    pub security_events: Vec<SecurityEvent>,
328}
329
330/// Security event record
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct SecurityEvent {
333    /// Event timestamp
334    #[serde(with = "instant_serde")]
335    pub timestamp: Instant,
336    /// Event type
337    pub event_type: SecurityEventType,
338    /// Severity level
339    pub severity: SecuritySeverity,
340    /// Description
341    pub description: String,
342    /// Affected protocols
343    pub affected_protocols: Vec<String>,
344}
345
346mod instant_serde {
347    use serde::{Deserialize, Deserializer, Serialize, Serializer};
348    use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
349
350    pub fn serialize<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
351    where
352        S: Serializer,
353    {
354        let duration_since_epoch = SystemTime::now()
355            .duration_since(UNIX_EPOCH)
356            .unwrap_or_default();
357        duration_since_epoch.as_secs().serialize(serializer)
358    }
359
360    pub fn deserialize<'de, D>(deserializer: D) -> Result<Instant, D::Error>
361    where
362        D: Deserializer<'de>,
363    {
364        let secs = u64::deserialize(deserializer)?;
365        Ok(Instant::now()) // Simplified
366    }
367}
368
369/// Types of security events
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371pub enum SecurityEventType {
372    /// Eavesdropping attempt detected
373    EavesdroppingDetected,
374    /// Anomalous error rate
375    AnomalousErrorRate,
376    /// Authentication failure
377    AuthenticationFailure,
378    /// Protocol violation
379    ProtocolViolation,
380    /// Network intrusion
381    NetworkIntrusion,
382}
383
384/// Security event severity levels
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386pub enum SecuritySeverity {
387    Low,
388    Medium,
389    High,
390    Critical,
391}
392
393impl PhotonicProtocolEngine {
394    pub fn new() -> Self {
395        Self {
396            active_protocols: HashMap::new(),
397            statistics: ProtocolStatistics {
398                total_protocols: 0,
399                success_rate: 0.0,
400                average_key_rate: 0.0,
401                average_fidelity: 0.0,
402                security_violations: 0,
403            },
404            security_monitor: SecurityMonitor {
405                threat_detection: true,
406                anomaly_threshold: 0.05,
407                security_events: Vec::new(),
408            },
409        }
410    }
411
412    /// Execute a quantum protocol
413    pub fn execute_protocol(
414        &mut self,
415        protocol_type: PhotonicProtocolType,
416        context: ProtocolContext,
417    ) -> Result<ProtocolResult, PhotonicProtocolError> {
418        let start_time = Instant::now();
419
420        // Register protocol
421        self.active_protocols
422            .insert(context.protocol_id.clone(), context.clone());
423
424        // Execute based on protocol type
425        let result = match protocol_type {
426            PhotonicProtocolType::QKD { variant } => self.execute_qkd_protocol(variant, &context),
427            PhotonicProtocolType::Teleportation => self.execute_teleportation_protocol(&context),
428            PhotonicProtocolType::StateDistribution => {
429                self.execute_state_distribution_protocol(&context)
430            }
431            PhotonicProtocolType::ClockSynchronization => {
432                self.execute_clock_sync_protocol(&context)
433            }
434            PhotonicProtocolType::SensingNetwork => self.execute_sensing_protocol(&context),
435            PhotonicProtocolType::QuantumInternet { protocol_version } => {
436                self.execute_quantum_internet_protocol(&context, &protocol_version)
437            }
438        }?;
439
440        // Update statistics
441        self.update_statistics(&result);
442
443        // Remove from active protocols
444        self.active_protocols.remove(&context.protocol_id);
445
446        Ok(result)
447    }
448
449    /// Execute QKD protocol
450    fn execute_qkd_protocol(
451        &mut self,
452        variant: QKDVariant,
453        context: &ProtocolContext,
454    ) -> Result<ProtocolResult, PhotonicProtocolError> {
455        match variant {
456            QKDVariant::BB84 => self.execute_bb84(context),
457            QKDVariant::CVQKD { modulation } => self.execute_cvqkd(context, modulation),
458            _ => Err(PhotonicProtocolError::UnsupportedProtocol(format!(
459                "QKD variant {variant:?} not implemented"
460            ))),
461        }
462    }
463
464    /// Execute BB84 protocol
465    fn execute_bb84(
466        &mut self,
467        context: &ProtocolContext,
468    ) -> Result<ProtocolResult, PhotonicProtocolError> {
469        let start_time = Instant::now();
470
471        // Simulate BB84 protocol execution
472        let key_length = 256; // bits
473        let mut raw_key = Vec::new();
474        let mut error_count = 0;
475
476        // Simulate photon transmission and measurement
477        for _ in 0..key_length * 2 {
478            // Send 2x for basis reconciliation
479            let bit = thread_rng().gen::<bool>();
480            let basis = thread_rng().gen::<bool>(); // 0: rectilinear, 1: diagonal
481
482            // Simulate channel loss and errors
483            let channel_loss = 0.05; // 5% loss
484            let error_rate = 0.01; // 1% error rate
485
486            if thread_rng().gen::<f64>() > channel_loss {
487                let received_bit = if thread_rng().gen::<f64>() < error_rate {
488                    !bit // Flip bit due to error
489                } else {
490                    bit
491                };
492
493                if thread_rng().gen::<bool>() {
494                    // Bob chooses same basis 50% of time
495                    raw_key.push(received_bit as u8);
496                    if received_bit != bit {
497                        error_count += 1;
498                    }
499                }
500            }
501        }
502
503        // Trim to desired key length
504        raw_key.truncate(key_length);
505        let final_error_rate = error_count as f64 / raw_key.len() as f64;
506
507        // Security analysis
508        let security_analysis = SecurityAnalysis {
509            information_leakage: final_error_rate * 0.5, // Simplified estimate
510            eavesdropping_detected: final_error_rate > 0.11, // BB84 threshold
511            security_proof_valid: final_error_rate <= 0.11,
512            achieved_security: if final_error_rate <= 0.11 {
513                context.security_params.security_level as f64
514            } else {
515                0.0
516            },
517        };
518
519        let metrics = ProtocolMetrics {
520            execution_time: start_time.elapsed(),
521            key_rate: Some(raw_key.len() as f64 / start_time.elapsed().as_secs_f64()),
522            error_rate: final_error_rate,
523            fidelity: 1.0 - final_error_rate,
524            throughput: raw_key.len() as f64,
525        };
526
527        Ok(ProtocolResult {
528            success: security_analysis.security_proof_valid,
529            key: if security_analysis.security_proof_valid {
530                Some(raw_key)
531            } else {
532                None
533            },
534            transmitted_state: None,
535            metrics,
536            security_analysis,
537        })
538    }
539
540    /// Execute CV-QKD protocol
541    fn execute_cvqkd(
542        &mut self,
543        context: &ProtocolContext,
544        modulation: CVModulation,
545    ) -> Result<ProtocolResult, PhotonicProtocolError> {
546        let start_time = Instant::now();
547
548        // Simulate CV-QKD protocol
549        let key_length = 256;
550        let mut key = Vec::new();
551
552        // Generate coherent states for CV-QKD
553        for _ in 0..key_length {
554            let x_quad = match modulation {
555                CVModulation::Gaussian { variance } => {
556                    // Generate Gaussian distributed quadrature
557                    self.generate_gaussian_random(0.0, variance)
558                }
559                CVModulation::Discrete { constellation_size } => {
560                    // Generate discrete constellation point
561                    let point = (thread_rng().gen::<f64>() * constellation_size as f64) as usize;
562                    (point as f64 - constellation_size as f64 / 2.0) * 0.5
563                }
564                _ => thread_rng().gen::<f64>() - 0.5,
565            };
566
567            // Quantize to bits (simplified)
568            key.push(u8::from(x_quad > 0.0));
569        }
570
571        let error_rate = 0.02; // Lower error rate for CV-QKD
572        let security_analysis = SecurityAnalysis {
573            information_leakage: error_rate * 0.3,
574            eavesdropping_detected: error_rate > 0.05,
575            security_proof_valid: error_rate <= 0.05,
576            achieved_security: if error_rate <= 0.05 {
577                context.security_params.security_level as f64
578            } else {
579                0.0
580            },
581        };
582
583        let metrics = ProtocolMetrics {
584            execution_time: start_time.elapsed(),
585            key_rate: Some(key.len() as f64 / start_time.elapsed().as_secs_f64()),
586            error_rate,
587            fidelity: 1.0 - error_rate,
588            throughput: key.len() as f64,
589        };
590
591        Ok(ProtocolResult {
592            success: security_analysis.security_proof_valid,
593            key: if security_analysis.security_proof_valid {
594                Some(key)
595            } else {
596                None
597            },
598            transmitted_state: None,
599            metrics,
600            security_analysis,
601        })
602    }
603
604    /// Execute teleportation protocol
605    fn execute_teleportation_protocol(
606        &self,
607        context: &ProtocolContext,
608    ) -> Result<ProtocolResult, PhotonicProtocolError> {
609        let start_time = Instant::now();
610
611        // Simulate quantum teleportation
612        let input_state = PhotonicQubitState::plus(PhotonicQubitEncoding::Polarization);
613        let fidelity: f64 = 0.95; // Typical teleportation fidelity
614
615        let mut output_state = input_state;
616        output_state.amplitude_0 *= fidelity.sqrt();
617        output_state.amplitude_1 *= fidelity.sqrt();
618
619        let metrics = ProtocolMetrics {
620            execution_time: start_time.elapsed(),
621            key_rate: None,
622            error_rate: 1.0 - fidelity,
623            fidelity,
624            throughput: 1.0, // One qubit teleported
625        };
626
627        let security_analysis = SecurityAnalysis {
628            information_leakage: 0.0, // Perfect security in principle
629            eavesdropping_detected: false,
630            security_proof_valid: true,
631            achieved_security: f64::INFINITY, // Information-theoretic security
632        };
633
634        Ok(ProtocolResult {
635            success: fidelity > 0.9,
636            key: None,
637            transmitted_state: Some(output_state),
638            metrics,
639            security_analysis,
640        })
641    }
642
643    /// Execute other protocols (placeholder implementations)
644    const fn execute_state_distribution_protocol(
645        &self,
646        context: &ProtocolContext,
647    ) -> Result<ProtocolResult, PhotonicProtocolError> {
648        // Placeholder implementation
649        Ok(self.create_placeholder_result(context))
650    }
651
652    const fn execute_clock_sync_protocol(
653        &self,
654        context: &ProtocolContext,
655    ) -> Result<ProtocolResult, PhotonicProtocolError> {
656        // Placeholder implementation
657        Ok(self.create_placeholder_result(context))
658    }
659
660    const fn execute_sensing_protocol(
661        &self,
662        context: &ProtocolContext,
663    ) -> Result<ProtocolResult, PhotonicProtocolError> {
664        // Placeholder implementation
665        Ok(self.create_placeholder_result(context))
666    }
667
668    const fn execute_quantum_internet_protocol(
669        &self,
670        context: &ProtocolContext,
671        _protocol_version: &str,
672    ) -> Result<ProtocolResult, PhotonicProtocolError> {
673        // Placeholder implementation
674        Ok(self.create_placeholder_result(context))
675    }
676
677    /// Create placeholder result for unimplemented protocols
678    const fn create_placeholder_result(&self, _context: &ProtocolContext) -> ProtocolResult {
679        ProtocolResult {
680            success: true,
681            key: None,
682            transmitted_state: None,
683            metrics: ProtocolMetrics {
684                execution_time: Duration::from_millis(100),
685                key_rate: None,
686                error_rate: 0.01,
687                fidelity: 0.99,
688                throughput: 1.0,
689            },
690            security_analysis: SecurityAnalysis {
691                information_leakage: 0.01,
692                eavesdropping_detected: false,
693                security_proof_valid: true,
694                achieved_security: 128.0,
695            },
696        }
697    }
698
699    /// Update protocol statistics
700    fn update_statistics(&mut self, result: &ProtocolResult) {
701        self.statistics.total_protocols += 1;
702
703        let success_count = if result.success { 1.0 } else { 0.0 };
704        self.statistics.success_rate = self
705            .statistics
706            .success_rate
707            .mul_add((self.statistics.total_protocols - 1) as f64, success_count)
708            / self.statistics.total_protocols as f64;
709
710        if let Some(key_rate) = result.metrics.key_rate {
711            self.statistics.average_key_rate = self
712                .statistics
713                .average_key_rate
714                .mul_add((self.statistics.total_protocols - 1) as f64, key_rate)
715                / self.statistics.total_protocols as f64;
716        }
717
718        self.statistics.average_fidelity = self.statistics.average_fidelity.mul_add(
719            (self.statistics.total_protocols - 1) as f64,
720            result.metrics.fidelity,
721        ) / self.statistics.total_protocols as f64;
722
723        if result.security_analysis.eavesdropping_detected {
724            self.statistics.security_violations += 1;
725        }
726    }
727
728    /// Generate Gaussian random number (simplified)
729    fn generate_gaussian_random(&self, mean: f64, variance: f64) -> f64 {
730        // Simple Box-Muller transform
731        let u1 = thread_rng().gen::<f64>();
732        let u2 = thread_rng().gen::<f64>();
733        let z = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();
734        variance.sqrt().mul_add(z, mean)
735    }
736
737    /// Get protocol statistics
738    pub const fn get_statistics(&self) -> &ProtocolStatistics {
739        &self.statistics
740    }
741
742    /// Get active protocols
743    pub fn get_active_protocols(&self) -> Vec<String> {
744        self.active_protocols.keys().cloned().collect()
745    }
746}
747
748impl Default for PhotonicProtocolEngine {
749    fn default() -> Self {
750        Self::new()
751    }
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757
758    #[test]
759    fn test_protocol_engine_creation() {
760        let engine = PhotonicProtocolEngine::new();
761        assert_eq!(engine.statistics.total_protocols, 0);
762        assert_eq!(engine.active_protocols.len(), 0);
763    }
764
765    #[test]
766    fn test_bb84_protocol() {
767        let mut engine = PhotonicProtocolEngine::new();
768
769        let context = ProtocolContext {
770            protocol_id: "test_bb84".to_string(),
771            parties: vec![],
772            security_params: SecurityParameters {
773                security_level: 128,
774                error_tolerance: 0.11,
775                privacy_amplification: PrivacyAmplificationParams {
776                    hash_family: "SHA256".to_string(),
777                    compression_ratio: 0.5,
778                    rounds: 1,
779                },
780                authentication: AuthenticationMethod::Classical {
781                    algorithm: "HMAC".to_string(),
782                },
783            },
784            network_config: NetworkConfiguration {
785                topology: NetworkTopology::PointToPoint,
786                channels: vec![],
787                routing: RoutingConfig {
788                    algorithm: RoutingAlgorithm::ShortestPath,
789                    max_hops: 1,
790                    load_balancing: false,
791                },
792            },
793            start_time: Instant::now(),
794        };
795
796        let result = engine
797            .execute_protocol(
798                PhotonicProtocolType::QKD {
799                    variant: QKDVariant::BB84,
800                },
801                context,
802            )
803            .expect("BB84 protocol execution should succeed");
804
805        assert!(result.metrics.fidelity > 0.0);
806        assert!(result.metrics.execution_time > Duration::ZERO);
807    }
808
809    #[test]
810    fn test_teleportation_protocol() {
811        let mut engine = PhotonicProtocolEngine::new();
812
813        let context = ProtocolContext {
814            protocol_id: "test_teleport".to_string(),
815            parties: vec![],
816            security_params: SecurityParameters {
817                security_level: 128,
818                error_tolerance: 0.05,
819                privacy_amplification: PrivacyAmplificationParams {
820                    hash_family: "SHA256".to_string(),
821                    compression_ratio: 0.5,
822                    rounds: 1,
823                },
824                authentication: AuthenticationMethod::Quantum {
825                    protocol: "QAUTH".to_string(),
826                },
827            },
828            network_config: NetworkConfiguration {
829                topology: NetworkTopology::PointToPoint,
830                channels: vec![],
831                routing: RoutingConfig {
832                    algorithm: RoutingAlgorithm::QuantumAware,
833                    max_hops: 1,
834                    load_balancing: false,
835                },
836            },
837            start_time: Instant::now(),
838        };
839
840        let result = engine
841            .execute_protocol(PhotonicProtocolType::Teleportation, context)
842            .expect("teleportation protocol execution should succeed");
843
844        assert!(result.success);
845        assert!(result.transmitted_state.is_some());
846        assert!(result.metrics.fidelity > 0.9);
847    }
848
849    #[test]
850    fn test_cvqkd_protocol() {
851        let mut engine = PhotonicProtocolEngine::new();
852
853        let context = ProtocolContext {
854            protocol_id: "test_cvqkd".to_string(),
855            parties: vec![],
856            security_params: SecurityParameters {
857                security_level: 256,
858                error_tolerance: 0.05,
859                privacy_amplification: PrivacyAmplificationParams {
860                    hash_family: "SHA3".to_string(),
861                    compression_ratio: 0.7,
862                    rounds: 2,
863                },
864                authentication: AuthenticationMethod::PostQuantum {
865                    algorithm: "Dilithium".to_string(),
866                },
867            },
868            network_config: NetworkConfiguration {
869                topology: NetworkTopology::PointToPoint,
870                channels: vec![],
871                routing: RoutingConfig {
872                    algorithm: RoutingAlgorithm::MinimumLoss,
873                    max_hops: 1,
874                    load_balancing: false,
875                },
876            },
877            start_time: Instant::now(),
878        };
879
880        let result = engine
881            .execute_protocol(
882                PhotonicProtocolType::QKD {
883                    variant: QKDVariant::CVQKD {
884                        modulation: CVModulation::Gaussian { variance: 1.0 },
885                    },
886                },
887                context,
888            )
889            .expect("CV-QKD protocol execution should succeed");
890
891        assert!(result.key.is_some());
892        assert!(result.metrics.key_rate.is_some());
893    }
894}