Skip to main content

qualia_core_db/specialized_libs/cryptographic_library/
proofs.rs

1// Part of the cryptographic_library module (split from the former mod.rs monolith
2// per CLAUDE.md §11 — pure code motion, no behaviour change).
3use super::*;
4
5/// Proof engine for zero-knowledge proofs
6pub struct ProofEngine {
7    proof_systems: HashMap<String, ProofSystem>,
8    proof_storage: ProofStorage,
9    verification_engine: ProofVerificationEngine,
10    performance_optimizer: ProofPerformanceOptimizer,
11}
12
13/// Proof system
14#[derive(Debug, Clone)]
15pub struct ProofSystem {
16    pub system_id: String,
17    pub system_type: ProofSystemType,
18    pub circuit_builder: CircuitBuilder,
19    pub prover: Prover,
20    pub verifier: Verifier,
21}
22
23/// Proof system types
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub enum ProofSystemType {
26    ZkSnarks,
27    ZkStarks,
28    Bulletproofs,
29    SigmaProtocols,
30    Custom(String),
31}
32
33/// Circuit builder
34#[derive(Debug, Clone)]
35pub struct CircuitBuilder {
36    pub builder_id: String,
37    pub circuit_type: CircuitType,
38    pub constraints: Vec<CircuitConstraint>,
39    pub variables: Vec<CircuitVariable>,
40}
41
42/// Circuit types
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub enum CircuitType {
45    Arithmetic,
46    Boolean,
47    Hash,
48    Signature,
49    Custom(String),
50}
51
52/// Circuit constraint
53#[derive(Debug, Clone)]
54pub struct CircuitConstraint {
55    pub constraint_id: String,
56    pub constraint_type: ConstraintType,
57    pub left_hand: CircuitExpression,
58    pub right_hand: CircuitExpression,
59}
60
61/// Constraint types
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub enum ConstraintType {
64    Equality,
65    Inequality,
66    Boolean,
67    Custom(String),
68}
69
70/// Circuit expression
71#[derive(Debug, Clone)]
72pub enum CircuitExpression {
73    Variable(String),
74    Constant(Vec<u8>),
75    Add(Box<CircuitExpression>, Box<CircuitExpression>),
76    Mul(Box<CircuitExpression>, Box<CircuitExpression>),
77    Sub(Box<CircuitExpression>, Box<CircuitExpression>),
78    Div(Box<CircuitExpression>, Box<CircuitExpression>),
79}
80
81/// Circuit variable
82#[derive(Debug, Clone)]
83pub struct CircuitVariable {
84    pub variable_id: String,
85    pub variable_type: VariableType,
86    pub value: Option<Vec<u8>>,
87}
88
89/// Variable types
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91pub enum VariableType {
92    Public,
93    Private,
94    Constant,
95    Witness,
96}
97
98/// Prover
99#[derive(Debug, Clone)]
100pub struct Prover {
101    pub prover_id: String,
102    pub proving_key: Vec<u8>,
103    pub proving_algorithm: ProvingAlgorithm,
104}
105
106/// Proving algorithms
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108pub enum ProvingAlgorithm {
109    Groth16,
110    PLONK,
111    Marlin,
112    Halo2,
113    Custom(String),
114}
115
116/// Verifier
117#[derive(Debug, Clone)]
118pub struct Verifier {
119    pub verifier_id: String,
120    pub verification_key: Vec<u8>,
121    pub verification_algorithm: VerificationAlgorithm,
122}
123
124/// Verification algorithms
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub enum VerificationAlgorithm {
127    Groth16,
128    PLONK,
129    Marlin,
130    Halo2,
131    Custom(String),
132}
133
134/// Proof storage
135pub struct ProofStorage {
136    proofs: HashMap<String, Proof>,
137    verification_records: HashMap<String, ProofVerificationRecord>,
138    audit_log: ProofAuditLog,
139}
140
141/// Proof record
142#[derive(Debug, Clone)]
143pub struct ProofRecord {
144    pub proof_id: String,
145    pub system_id: String,
146    pub circuit_id: String,
147    pub public_inputs: Vec<Vec<u8>>,
148    pub proof_data: Vec<u8>,
149    pub timestamp: u64,
150    pub metadata: ProofMetadata,
151}
152
153/// Proof metadata
154#[derive(Debug, Clone)]
155pub struct ProofMetadata {
156    pub prover_id: String,
157    pub purpose: String,
158    pub context: Vec<String>,
159    pub validity_period: Option<(u64, u64)>,
160    pub security_level: SecurityLevel,
161}
162
163/// Proof verification record
164#[derive(Debug, Clone)]
165pub struct ProofVerificationRecord {
166    pub verification_id: String,
167    pub proof_id: String,
168    pub verifier_id: String,
169    pub result: ProofVerificationResult,
170    pub timestamp: u64,
171}
172
173/// Proof verification result
174#[derive(Debug, Clone)]
175pub struct ProofVerificationResult {
176    pub valid: bool,
177    pub error_message: Option<String>,
178    pub verification_time: u64,
179    pub confidence: f64,
180}
181
182/// Proof audit log
183pub struct ProofAuditLog {
184    entries: Vec<ProofAuditEntry>,
185    retention_policy: RetentionPolicy,
186}
187
188/// Proof audit entry
189#[derive(Debug, Clone)]
190pub struct ProofAuditEntry {
191    pub entry_id: String,
192    pub timestamp: u64,
193    pub proof_id: String,
194    pub operation: ProofOperation,
195    pub user_id: String,
196    pub ip_address: String,
197    pub success: bool,
198}
199
200/// Proof operations
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub enum ProofOperation {
203    Generate,
204    Verify,
205    Revoke,
206    Update,
207}
208
209/// Proof verification engine
210pub struct ProofVerificationEngine {
211    verification_algorithms: HashMap<String, VerificationAlgorithm>,
212    batch_verifier: BatchVerifier,
213    performance_optimizer: VerificationPerformanceOptimizer,
214}
215
216/// Batch verifier
217pub struct BatchVerifier {
218    batch_size: usize,
219    parallel_verification: bool,
220    verification_queue: Vec<QueuedVerification>,
221}
222
223/// Queued verification
224#[derive(Debug, Clone)]
225pub struct QueuedVerification {
226    pub verification_id: String,
227    pub proof_id: String,
228    pub priority: VerificationPriority,
229    pub queued_at: u64,
230}
231
232/// Verification priorities
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub enum VerificationPriority {
235    Low,
236    Normal,
237    High,
238    Critical,
239}
240
241/// Verification performance optimizer
242pub struct VerificationPerformanceOptimizer {
243    optimization_strategies: Vec<VerificationOptimizationStrategy>,
244    performance_metrics: VerificationPerformanceMetrics,
245}
246
247/// Verification optimization strategies
248#[derive(Debug, Clone, PartialEq)]
249pub enum VerificationOptimizationStrategy {
250    BatchVerification,
251    ParallelProcessing,
252    Caching,
253    HardwareAcceleration,
254}
255
256/// Verification performance metrics
257#[derive(Debug, Clone)]
258pub struct VerificationPerformanceMetrics {
259    pub average_verification_time: f64,
260    pub throughput: f64,
261    pub cache_hit_rate: f64,
262    pub batch_efficiency: f64,
263}
264
265/// Proof performance optimizer
266pub struct ProofPerformanceOptimizer {
267    optimization_strategies: Vec<ProofOptimizationStrategy>,
268    performance_metrics: ProofPerformanceMetrics,
269}
270
271/// Proof optimization strategies
272#[derive(Debug, Clone, PartialEq)]
273pub enum ProofOptimizationStrategy {
274    ParallelProving,
275    CircuitOptimization,
276    Precomputation,
277    HardwareAcceleration,
278}
279
280/// Proof performance metrics
281#[derive(Debug, Clone)]
282pub struct ProofPerformanceMetrics {
283    pub average_proving_time: f64,
284    pub average_verification_time: f64,
285    pub proof_size: u64,
286    pub circuit_size: u64,
287    pub cache_hit_rate: f64,
288}
289impl ProofEngine {
290    pub fn new() -> Self {
291        Self {
292            proof_systems: HashMap::new(),
293            proof_storage: ProofStorage::new(),
294            verification_engine: ProofVerificationEngine::new(),
295            performance_optimizer: ProofPerformanceOptimizer::new(),
296        }
297    }
298
299    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
300        self.proof_storage.initialize()?;
301        self.verification_engine.initialize()?;
302        self.performance_optimizer.initialize()?;
303        Ok(())
304    }
305
306    /// Register a proof system.
307    pub fn add_proof_system(&mut self, system: ProofSystem) {
308        self.proof_systems.insert(system.system_id.clone(), system);
309    }
310
311    /// Look up a proof system by id.
312    pub fn get_proof_system(&self, system_id: &str) -> Option<&ProofSystem> {
313        self.proof_systems.get(system_id)
314    }
315
316    /// Iterate over all registered proof systems.
317    pub fn list_proof_systems(&self) -> impl Iterator<Item = &ProofSystem> {
318        self.proof_systems.values()
319    }
320
321    pub fn generate_proof(
322        &mut self,
323        circuit_id: &str,
324        witness: &[Vec<u8>],
325        public_inputs: &[Vec<u8>],
326    ) -> Result<Proof, CryptographicError> {
327        let start_time = std::time::Instant::now();
328
329        // Generate proof
330        let proof_data = self.generate_proof_data(circuit_id, witness, public_inputs)?;
331
332        let proof = Proof {
333            proof_id: format!(
334                "proof_{}",
335                std::time::SystemTime::now()
336                    .duration_since(std::time::UNIX_EPOCH)
337                    .unwrap()
338                    .as_secs()
339            ),
340            system_id: "zk_snarks".to_string(),
341            circuit_id: circuit_id.to_string(),
342            public_inputs: public_inputs.to_vec(),
343            proof_data,
344            timestamp: start_time.elapsed().as_millis() as u64,
345        };
346
347        // Store proof
348        self.proof_storage.store_proof(proof.clone())?;
349
350        // Audit log the proof generation
351        self.proof_storage.audit_log.log_entry(
352            &proof.proof_id,
353            ProofOperation::Generate,
354            "system",
355            true,
356        );
357
358        // Record performance metrics
359        self.performance_optimizer.record_proving_time(
360            start_time.elapsed().as_millis() as f64,
361            proof.proof_data.len(),
362        );
363
364        Ok(proof)
365    }
366
367    pub fn verify_proof(
368        &mut self,
369        proof: &Proof,
370        public_inputs: &[Vec<u8>],
371    ) -> Result<bool, CryptographicError> {
372        let start_time = std::time::Instant::now();
373
374        // Verify proof
375        let is_valid = self.verify_proof_data(&proof.proof_data, public_inputs)?;
376
377        // Store verification record
378        let verification_record = ProofVerificationRecord {
379            verification_id: format!(
380                "proof_verif_{}",
381                std::time::SystemTime::now()
382                    .duration_since(std::time::UNIX_EPOCH)
383                    .unwrap()
384                    .as_secs()
385            ),
386            proof_id: proof.proof_id.clone(),
387            verifier_id: "system".to_string(),
388            result: ProofVerificationResult {
389                valid: is_valid,
390                error_message: None,
391                verification_time: start_time.elapsed().as_millis() as u64,
392                confidence: 1.0,
393            },
394            timestamp: start_time.elapsed().as_millis() as u64,
395        };
396
397        self.proof_storage
398            .store_verification_record(verification_record)?;
399
400        // Audit log the proof verification
401        self.proof_storage.audit_log.log_entry(
402            &proof.proof_id,
403            ProofOperation::Verify,
404            "system",
405            is_valid,
406        );
407
408        // Record performance metrics
409        self.performance_optimizer
410            .record_verification_time(start_time.elapsed().as_millis() as f64);
411
412        Ok(is_valid)
413    }
414
415    fn generate_proof_data(
416        &self,
417        circuit_id: &str,
418        witness: &[Vec<u8>],
419        public_inputs: &[Vec<u8>],
420    ) -> Result<Vec<u8>, CryptographicError> {
421        #[cfg(feature = "zk-culling")]
422        if circuit_id == "deontic_access" {
423            return Self::generate_deontic_groth16_proof(witness, public_inputs);
424        }
425
426        Self::generate_commitment_proof_data(circuit_id, witness, public_inputs)
427    }
428
429    fn verify_proof_data(
430        &self,
431        proof_data: &[u8],
432        public_inputs: &[Vec<u8>],
433    ) -> Result<bool, CryptographicError> {
434        if proof_data.len() < 65 {
435            return Ok(false);
436        }
437        if proof_data[64] == 0x02 {
438            #[cfg(feature = "zk-culling")]
439            {
440                return Self::verify_deontic_groth16_proof(proof_data, public_inputs);
441            }
442            #[cfg(not(feature = "zk-culling"))]
443            {
444                return Ok(false);
445            }
446        }
447        Self::verify_commitment_proof_data(proof_data, public_inputs)
448    }
449
450    fn generate_commitment_proof_data(
451        circuit_id: &str,
452        witness: &[Vec<u8>],
453        public_inputs: &[Vec<u8>],
454    ) -> Result<Vec<u8>, CryptographicError> {
455        use sha2::{Digest, Sha256};
456        // Commitment: H(circuit_id || witness_bytes) stored in proof_data[0..32]
457        // Public input binding: H(public_inputs) stored in proof_data[32..64]
458        // Proof version tag in proof_data[64..128]
459        let mut witness_hasher = Sha256::new();
460        witness_hasher.update(circuit_id.as_bytes());
461        for w in witness {
462            witness_hasher.update(w);
463        }
464        let witness_commit = witness_hasher.finalize();
465
466        let mut pub_hasher = Sha256::new();
467        for p in public_inputs {
468            pub_hasher.update(p);
469        }
470        let pub_commit = pub_hasher.finalize();
471
472        let mut proof_data = vec![0u8; 128];
473        proof_data[..32].copy_from_slice(&witness_commit);
474        proof_data[32..64].copy_from_slice(&pub_commit);
475        // Version tag 0x01 = SHA-256 commitment stub
476        proof_data[64] = 0x01;
477        proof_data[65] = 0x00;
478        Ok(proof_data)
479    }
480
481    fn verify_commitment_proof_data(
482        proof_data: &[u8],
483        public_inputs: &[Vec<u8>],
484    ) -> Result<bool, CryptographicError> {
485        use sha2::{Digest, Sha256};
486        if proof_data.len() < 128 {
487            return Ok(false);
488        }
489        if proof_data[64] != 0x01 {
490            return Ok(false);
491        }
492        let mut pub_hasher = Sha256::new();
493        for p in public_inputs {
494            pub_hasher.update(p);
495        }
496        let expected_pub_commit = pub_hasher.finalize();
497        Ok(&proof_data[32..64] == expected_pub_commit.as_slice())
498    }
499
500    /// Reduce a secret WITNESS value to a field element via SHA-256 (the secret
501    /// never leaves the prover; only its field image enters the circuit).
502    #[cfg(feature = "zk-culling")]
503    fn bytes_to_fr(data: &[u8]) -> ark_bls12_381::Fr {
504        use ark_ff::PrimeField;
505        use sha2::{Digest, Sha256};
506        let hash = Sha256::digest(data);
507        ark_bls12_381::Fr::from_be_bytes_mod_order(hash.as_slice())
508    }
509
510    /// Interpret a PUBLIC input as a canonical little-endian field element — NOT
511    /// hashed. Prover and verifier must agree on the exact public value (e.g. a
512    /// `policy_root` the witness genuinely satisfies), so hashing it (as for a
513    /// witness) would make a valid proof unconstructible. Callers serialise the
514    /// field element little-endian (`Fr::into_bigint().to_bytes_le()`).
515    #[cfg(feature = "zk-culling")]
516    fn public_input_to_fr(data: &[u8]) -> ark_bls12_381::Fr {
517        use ark_ff::PrimeField;
518        ark_bls12_381::Fr::from_le_bytes_mod_order(data)
519    }
520
521    #[cfg(feature = "zk-culling")]
522    fn deontic_crs() -> Result<
523        &'static (
524            ark_groth16::ProvingKey<ark_bls12_381::Bls12_381>,
525            ark_groth16::VerifyingKey<ark_bls12_381::Bls12_381>,
526        ),
527        CryptographicError,
528    > {
529        use std::sync::OnceLock;
530        static CRS: OnceLock<(
531            ark_groth16::ProvingKey<ark_bls12_381::Bls12_381>,
532            ark_groth16::VerifyingKey<ark_bls12_381::Bls12_381>,
533        )> = OnceLock::new();
534        CRS.get_or_init(|| {
535            crate::deontic_circuit::generate_deontic_crs()
536                .map_err(|e| CryptographicError::ProofError(e))
537                .expect("deontic CRS setup")
538        });
539        Ok(CRS.get().expect("deontic CRS initialized"))
540    }
541
542    #[cfg(feature = "zk-culling")]
543    fn generate_deontic_groth16_proof(
544        witness: &[Vec<u8>],
545        public_inputs: &[Vec<u8>],
546    ) -> Result<Vec<u8>, CryptographicError> {
547        use ark_bls12_381::Bls12_381;
548        use ark_groth16::Groth16;
549
550        use ark_serialize::CanonicalSerialize;
551        use ark_snark::SNARK;
552        use sha2::{Digest, Sha256};
553
554        let user_did = Self::bytes_to_fr(witness.first().map(|v| v.as_slice()).unwrap_or(b""));
555        let role_id = Self::bytes_to_fr(witness.get(1).map(|v| v.as_slice()).unwrap_or(b""));
556        let action_permission =
557            Self::bytes_to_fr(witness.get(2).map(|v| v.as_slice()).unwrap_or(b""));
558        let policy_root =
559            Self::public_input_to_fr(public_inputs.first().map(|v| v.as_slice()).unwrap_or(b""));
560        let temporal_constraint =
561            Self::public_input_to_fr(public_inputs.get(1).map(|v| v.as_slice()).unwrap_or(b""));
562
563        let circuit = crate::deontic_circuit::DeonticAccessCircuit {
564            user_did_commitment: Some(user_did),
565            role_id: Some(role_id),
566            action_permission: Some(action_permission),
567            policy_root: Some(policy_root),
568            temporal_constraint: Some(temporal_constraint),
569        };
570
571        let (pk, _vk) = Self::deontic_crs()?;
572        let mut rng = ark_std::rand::rngs::OsRng;
573        let proof = Groth16::<Bls12_381>::prove(pk, circuit, &mut rng)
574            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
575
576        let mut serialized = Vec::new();
577        proof
578            .serialize_uncompressed(&mut serialized)
579            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
580
581        let mut witness_hasher = Sha256::new();
582        witness_hasher.update(b"deontic_access");
583        for w in witness {
584            witness_hasher.update(w);
585        }
586        let witness_commit = witness_hasher.finalize();
587        let mut pub_hasher = Sha256::new();
588        for p in public_inputs {
589            pub_hasher.update(p);
590        }
591        let pub_commit = pub_hasher.finalize();
592
593        let mut proof_data = vec![0u8; 65 + serialized.len()];
594        proof_data[..32].copy_from_slice(&witness_commit);
595        proof_data[32..64].copy_from_slice(&pub_commit);
596        proof_data[64] = 0x02;
597        proof_data[65..].copy_from_slice(&serialized);
598        Ok(proof_data)
599    }
600
601    #[cfg(feature = "zk-culling")]
602    fn verify_deontic_groth16_proof(
603        proof_data: &[u8],
604        public_inputs: &[Vec<u8>],
605    ) -> Result<bool, CryptographicError> {
606        use ark_bls12_381::{Bls12_381, Fr};
607        use ark_groth16::{Groth16, Proof};
608        use ark_serialize::CanonicalDeserialize;
609        use ark_snark::SNARK;
610
611        if proof_data.len() <= 65 {
612            return Ok(false);
613        }
614        let proof = Proof::<Bls12_381>::deserialize_uncompressed(&proof_data[65..])
615            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
616        let (_pk, vk) = Self::deontic_crs()?;
617        let public_fr: Vec<Fr> = public_inputs
618            .iter()
619            .map(|p| Self::public_input_to_fr(p))
620            .collect();
621        Ok(Groth16::<Bls12_381>::verify(vk, &public_fr, &proof)
622            .map_err(|e| CryptographicError::ProofError(e.to_string()))?)
623    }
624}
625
626impl ProofStorage {
627    pub fn new() -> Self {
628        Self {
629            proofs: HashMap::new(),
630            verification_records: HashMap::new(),
631            audit_log: ProofAuditLog::new(),
632        }
633    }
634
635    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
636        Ok(())
637    }
638
639    pub fn store_proof(&mut self, proof: Proof) -> Result<(), CryptographicError> {
640        self.proofs.insert(proof.proof_id.clone(), proof);
641        Ok(())
642    }
643
644    pub fn store_verification_record(
645        &mut self,
646        record: ProofVerificationRecord,
647    ) -> Result<(), CryptographicError> {
648        self.verification_records
649            .insert(record.verification_id.clone(), record);
650        Ok(())
651    }
652}
653
654impl ProofAuditLog {
655    pub fn new() -> Self {
656        Self {
657            entries: Vec::new(),
658            retention_policy: RetentionPolicy {
659                retention_days: 365,
660                auto_delete: true,
661                archive_before_delete: true,
662            },
663        }
664    }
665
666    /// Record a proof operation (generate, verify, revoke, update).
667    pub fn log_entry(
668        &mut self,
669        proof_id: &str,
670        operation: ProofOperation,
671        user_id: &str,
672        success: bool,
673    ) {
674        let timestamp = std::time::SystemTime::now()
675            .duration_since(std::time::UNIX_EPOCH)
676            .unwrap_or_default()
677            .as_secs();
678        let entry = ProofAuditEntry {
679            entry_id: format!("proof_{}_{}", timestamp, self.entries.len()),
680            timestamp,
681            proof_id: proof_id.to_string(),
682            operation,
683            user_id: user_id.to_string(),
684            ip_address: String::new(),
685            success,
686        };
687        self.entries.push(entry);
688        let cutoff =
689            timestamp.saturating_sub((self.retention_policy.retention_days as u64) * 86400);
690        self.entries.retain(|e| e.timestamp >= cutoff);
691    }
692
693    /// Number of logged entries.
694    pub fn entry_count(&self) -> usize {
695        self.entries.len()
696    }
697
698    /// Iterate over entries.
699    pub fn entries(&self) -> &[ProofAuditEntry] {
700        &self.entries
701    }
702}
703
704impl ProofVerificationEngine {
705    pub fn new() -> Self {
706        Self {
707            verification_algorithms: HashMap::new(),
708            batch_verifier: BatchVerifier::new(),
709            performance_optimizer: VerificationPerformanceOptimizer::new(),
710        }
711    }
712
713    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
714        self.performance_optimizer.initialize()?;
715        Ok(())
716    }
717
718    /// Register a verification algorithm under a named key.
719    pub fn add_verification_algorithm(&mut self, name: String, algorithm: VerificationAlgorithm) {
720        self.verification_algorithms.insert(name, algorithm);
721    }
722
723    /// Look up a verification algorithm by name.
724    pub fn get_verification_algorithm(&self, name: &str) -> Option<&VerificationAlgorithm> {
725        self.verification_algorithms.get(name)
726    }
727
728    /// Iterate over all registered verification algorithms.
729    pub fn list_verification_algorithms(&self) -> impl Iterator<Item = &VerificationAlgorithm> {
730        self.verification_algorithms.values()
731    }
732
733    /// Get a reference to the batch verifier.
734    pub fn batch_verifier(&self) -> &BatchVerifier {
735        &self.batch_verifier
736    }
737
738    /// Get a mutable reference to the batch verifier.
739    pub fn batch_verifier_mut(&mut self) -> &mut BatchVerifier {
740        &mut self.batch_verifier
741    }
742}
743
744impl BatchVerifier {
745    pub fn new() -> Self {
746        Self {
747            batch_size: 100,
748            parallel_verification: true,
749            verification_queue: Vec::new(),
750        }
751    }
752
753    /// Get the configured batch size.
754    pub fn batch_size(&self) -> usize {
755        self.batch_size
756    }
757
758    /// Set the batch size.
759    pub fn set_batch_size(&mut self, size: usize) {
760        self.batch_size = size;
761    }
762
763    /// Whether parallel verification is enabled.
764    pub fn parallel_verification(&self) -> bool {
765        self.parallel_verification
766    }
767
768    /// Enable or disable parallel verification.
769    pub fn set_parallel_verification(&mut self, enabled: bool) {
770        self.parallel_verification = enabled;
771    }
772
773    /// Enqueue a verification for batch processing.
774    pub fn enqueue_verification(&mut self, verification: QueuedVerification) {
775        self.verification_queue.push(verification);
776    }
777
778    /// Dequeue the next verification (FIFO order).
779    pub fn dequeue_verification(&mut self) -> Option<QueuedVerification> {
780        if self.verification_queue.is_empty() {
781            None
782        } else {
783            Some(self.verification_queue.remove(0))
784        }
785    }
786
787    /// Number of verifications currently queued.
788    pub fn queue_len(&self) -> usize {
789        self.verification_queue.len()
790    }
791}
792
793impl VerificationPerformanceOptimizer {
794    pub fn new() -> Self {
795        Self {
796            optimization_strategies: vec![
797                VerificationOptimizationStrategy::BatchVerification,
798                VerificationOptimizationStrategy::ParallelProcessing,
799            ],
800            performance_metrics: VerificationPerformanceMetrics {
801                average_verification_time: 0.0,
802                throughput: 0.0,
803                cache_hit_rate: 0.0,
804                batch_efficiency: 0.0,
805            },
806        }
807    }
808
809    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
810        Ok(())
811    }
812
813    /// Get the configured optimization strategies.
814    pub fn optimization_strategies(&self) -> &[VerificationOptimizationStrategy] {
815        &self.optimization_strategies
816    }
817
818    /// Add an optimization strategy if not already present.
819    pub fn add_optimization_strategy(&mut self, strategy: VerificationOptimizationStrategy) {
820        if !self.optimization_strategies.contains(&strategy) {
821            self.optimization_strategies.push(strategy);
822        }
823    }
824
825    /// Record a verification duration (milliseconds) and update running averages.
826    pub fn record_verification_time(&mut self, duration_ms: f64) {
827        let m = &mut self.performance_metrics;
828        if m.average_verification_time == 0.0 {
829            m.average_verification_time = duration_ms;
830        } else {
831            m.average_verification_time = 0.9 * m.average_verification_time + 0.1 * duration_ms;
832        }
833        if m.average_verification_time > 0.0 {
834            m.throughput = 1000.0 / m.average_verification_time;
835        }
836    }
837
838    /// Get a snapshot of the current performance metrics.
839    pub fn metrics(&self) -> &VerificationPerformanceMetrics {
840        &self.performance_metrics
841    }
842}
843
844impl VerificationPerformanceMetrics {
845    pub fn new() -> Self {
846        Self {
847            average_verification_time: 0.0,
848            throughput: 0.0,
849            cache_hit_rate: 0.0,
850            batch_efficiency: 0.0,
851        }
852    }
853}
854
855impl ProofPerformanceOptimizer {
856    pub fn new() -> Self {
857        Self {
858            optimization_strategies: vec![
859                ProofOptimizationStrategy::ParallelProving,
860                ProofOptimizationStrategy::CircuitOptimization,
861            ],
862            performance_metrics: ProofPerformanceMetrics {
863                average_proving_time: 0.0,
864                average_verification_time: 0.0,
865                proof_size: 0,
866                circuit_size: 0,
867                cache_hit_rate: 0.0,
868            },
869        }
870    }
871
872    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
873        Ok(())
874    }
875
876    /// Get the configured optimization strategies.
877    pub fn optimization_strategies(&self) -> &[ProofOptimizationStrategy] {
878        &self.optimization_strategies
879    }
880
881    /// Add an optimization strategy if not already present.
882    pub fn add_optimization_strategy(&mut self, strategy: ProofOptimizationStrategy) {
883        if !self.optimization_strategies.contains(&strategy) {
884            self.optimization_strategies.push(strategy);
885        }
886    }
887
888    /// Record a proof generation duration (milliseconds).
889    pub fn record_proving_time(&mut self, duration_ms: f64, proof_size: usize) {
890        let m = &mut self.performance_metrics;
891        if m.average_proving_time == 0.0 {
892            m.average_proving_time = duration_ms;
893        } else {
894            m.average_proving_time = 0.9 * m.average_proving_time + 0.1 * duration_ms;
895        }
896        m.proof_size = proof_size as u64;
897    }
898
899    /// Record a proof verification duration (milliseconds).
900    pub fn record_verification_time(&mut self, duration_ms: f64) {
901        let m = &mut self.performance_metrics;
902        if m.average_verification_time == 0.0 {
903            m.average_verification_time = duration_ms;
904        } else {
905            m.average_verification_time = 0.9 * m.average_verification_time + 0.1 * duration_ms;
906        }
907    }
908
909    /// Get a snapshot of the current performance metrics.
910    pub fn metrics(&self) -> &ProofPerformanceMetrics {
911        &self.performance_metrics
912    }
913}
914
915impl ProofPerformanceMetrics {
916    pub fn new() -> Self {
917        Self {
918            average_proving_time: 0.0,
919            average_verification_time: 0.0,
920            proof_size: 0,
921            circuit_size: 0,
922            cache_hit_rate: 0.0,
923        }
924    }
925}