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    /// Creates an engine with empty proof-system registry and fresh storage,
291    /// verification, and performance-tracking subsystems.
292    pub fn new() -> Self {
293        Self {
294            proof_systems: HashMap::new(),
295            proof_storage: ProofStorage::new(),
296            verification_engine: ProofVerificationEngine::new(),
297            performance_optimizer: ProofPerformanceOptimizer::new(),
298        }
299    }
300
301    /// Initializes storage, verification engine, and performance optimizer.
302    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
303        self.proof_storage.initialize()?;
304        self.verification_engine.initialize()?;
305        self.performance_optimizer.initialize()?;
306        Ok(())
307    }
308
309    /// Register a proof system.
310    pub fn add_proof_system(&mut self, system: ProofSystem) {
311        self.proof_systems.insert(system.system_id.clone(), system);
312    }
313
314    /// Look up a proof system by id.
315    pub fn get_proof_system(&self, system_id: &str) -> Option<&ProofSystem> {
316        self.proof_systems.get(system_id)
317    }
318
319    /// Iterate over all registered proof systems.
320    pub fn list_proof_systems(&self) -> impl Iterator<Item = &ProofSystem> {
321        self.proof_systems.values()
322    }
323
324    /// Generates a proof for `circuit_id` over `witness`/`public_inputs`,
325    /// stores it, audit-logs the operation, and records proving metrics.
326    ///
327    /// WARNING: only `circuit_id == "deontic_access"` (feature `zk-culling`)
328    /// produces a real Groth16 SNARK. All other circuits get a hash-commitment
329    /// blob stamped `system_id: "zk_snarks"` that is NOT a proof of knowledge
330    /// — see STUBS.md F31.
331    pub fn generate_proof(
332        &mut self,
333        circuit_id: &str,
334        witness: &[Vec<u8>],
335        public_inputs: &[Vec<u8>],
336    ) -> Result<Proof, CryptographicError> {
337        let start_time = std::time::Instant::now();
338
339        // Generate proof
340        let proof_data = self.generate_proof_data(circuit_id, witness, public_inputs)?;
341
342        let proof = Proof {
343            proof_id: format!(
344                "proof_{}",
345                std::time::SystemTime::now()
346                    .duration_since(std::time::UNIX_EPOCH)
347                    .unwrap()
348                    .as_secs()
349            ),
350            system_id: "zk_snarks".to_string(),
351            circuit_id: circuit_id.to_string(),
352            public_inputs: public_inputs.to_vec(),
353            proof_data,
354            timestamp: start_time.elapsed().as_millis() as u64,
355        };
356
357        // Store proof
358        self.proof_storage.store_proof(proof.clone())?;
359
360        // Audit log the proof generation
361        self.proof_storage.audit_log.log_entry(
362            &proof.proof_id,
363            ProofOperation::Generate,
364            "system",
365            true,
366        );
367
368        // Record performance metrics
369        self.performance_optimizer.record_proving_time(
370            start_time.elapsed().as_millis() as f64,
371            proof.proof_data.len(),
372        );
373
374        Ok(proof)
375    }
376
377    /// Verifies `proof` against `public_inputs`, stores the verification
378    /// record, audit-logs, and records metrics.
379    ///
380    /// WARNING: for non-Groth16 (tag 0x01) proof data this accepts any blob
381    /// with a matching `H(public_inputs)` and non-zero fields — it does NOT
382    /// verify witness knowledge (STUBS.md F31). Real verification only happens
383    /// for `deontic_access` proofs under `zk-culling`.
384    pub fn verify_proof(
385        &mut self,
386        proof: &Proof,
387        public_inputs: &[Vec<u8>],
388    ) -> Result<bool, CryptographicError> {
389        let start_time = std::time::Instant::now();
390
391        // Verify proof
392        let is_valid = self.verify_proof_data(&proof.proof_data, public_inputs)?;
393
394        // Store verification record
395        let verification_record = ProofVerificationRecord {
396            verification_id: format!(
397                "proof_verif_{}",
398                std::time::SystemTime::now()
399                    .duration_since(std::time::UNIX_EPOCH)
400                    .unwrap()
401                    .as_secs()
402            ),
403            proof_id: proof.proof_id.clone(),
404            verifier_id: "system".to_string(),
405            result: ProofVerificationResult {
406                valid: is_valid,
407                error_message: None,
408                verification_time: start_time.elapsed().as_millis() as u64,
409                confidence: 1.0,
410            },
411            timestamp: start_time.elapsed().as_millis() as u64,
412        };
413
414        self.proof_storage
415            .store_verification_record(verification_record)?;
416
417        // Audit log the proof verification
418        self.proof_storage.audit_log.log_entry(
419            &proof.proof_id,
420            ProofOperation::Verify,
421            "system",
422            is_valid,
423        );
424
425        // Record performance metrics
426        self.performance_optimizer
427            .record_verification_time(start_time.elapsed().as_millis() as f64);
428
429        Ok(is_valid)
430    }
431
432    /// Dispatch seam: `deontic_access` under `zk-culling` → real Groth16;
433    /// everything else → the hash-commitment fallback.
434    fn generate_proof_data(
435        &self,
436        circuit_id: &str,
437        witness: &[Vec<u8>],
438        public_inputs: &[Vec<u8>],
439    ) -> Result<Vec<u8>, CryptographicError> {
440        #[cfg(feature = "zk-culling")]
441        if circuit_id == "deontic_access" {
442            return Self::generate_deontic_groth16_proof(witness, public_inputs);
443        }
444
445        Self::generate_commitment_proof_data(circuit_id, witness, public_inputs)
446    }
447
448    /// Dispatch seam on the `proof_data[64]` tag: `0x02` → Groth16 verify
449    /// (`zk-culling` only; `Ok(false)` otherwise); anything else → the
450    /// commitment-path check.
451    fn verify_proof_data(
452        &self,
453        proof_data: &[u8],
454        public_inputs: &[Vec<u8>],
455    ) -> Result<bool, CryptographicError> {
456        if proof_data.len() < 65 {
457            return Ok(false);
458        }
459        if proof_data[64] == 0x02 {
460            #[cfg(feature = "zk-culling")]
461            {
462                return Self::verify_deontic_groth16_proof(proof_data, public_inputs);
463            }
464            #[cfg(not(feature = "zk-culling"))]
465            {
466                return Ok(false);
467            }
468        }
469        Self::verify_commitment_proof_data(proof_data, public_inputs)
470    }
471
472    /// Builds a 130-byte NIZK Schnorr proof of knowledge: deriving a secret scalar
473    /// from `(circuit_id || witness)`, emitting its public commitment `C_w = w·B` (32B),
474    /// public input binding `C_p = H(public_inputs)` (32B), tag `0x01`, flag `0x01`,
475    /// and a 64-byte Ed25519 Schnorr signature over `H(b"qualia_zk_commitment_proof" || C_p || C_w)`.
476    /// This proves knowledge of the secret witness scalar bound to the public inputs.
477    pub fn generate_commitment_proof_data(
478        circuit_id: &str,
479        witness: &[Vec<u8>],
480        public_inputs: &[Vec<u8>],
481    ) -> Result<Vec<u8>, CryptographicError> {
482        use sha2::{Digest, Sha256};
483        use ed25519_dalek::{Signer, SigningKey};
484
485        // 1. Witness commitment: derive 32-byte secret seed for witness scalar
486        let mut witness_hasher = Sha256::new();
487        witness_hasher.update(circuit_id.as_bytes());
488        for w in witness {
489            witness_hasher.update(w);
490        }
491        let witness_seed: [u8; 32] = witness_hasher.finalize().into();
492        let signing_key = SigningKey::from_bytes(&witness_seed);
493        let verifying_key = signing_key.verifying_key();
494        let witness_commit = verifying_key.to_bytes();
495
496        // 2. Public input binding: C_p = H(public_inputs)
497        let mut pub_hasher = Sha256::new();
498        for p in public_inputs {
499            pub_hasher.update(p);
500        }
501        let pub_commit: [u8; 32] = pub_hasher.finalize().into();
502
503        // 3. Transcript binding message: M = H(b"qualia_zk_commitment_proof" || C_p || C_w)
504        let mut msg_hasher = Sha256::new();
505        msg_hasher.update(b"qualia_zk_commitment_proof");
506        msg_hasher.update(&pub_commit);
507        msg_hasher.update(&witness_commit);
508        let msg: [u8; 32] = msg_hasher.finalize().into();
509
510        // 4. Sound Schnorr proof of knowledge of witness scalar via Ed25519 signature
511        let signature = signing_key.sign(&msg);
512        let sig_bytes = signature.to_bytes(); // 64 bytes: [R (32B) || s (32B)]
513
514        let mut proof_data = vec![0u8; 130];
515        proof_data[..32].copy_from_slice(&witness_commit);
516        proof_data[32..64].copy_from_slice(&pub_commit);
517        proof_data[64] = 0x01; // Version tag 0x01 = NIZK Schnorr Proof of Knowledge
518        proof_data[65] = 0x01; // Flag: Ed25519 Schnorr proof
519        proof_data[66..130].copy_from_slice(&sig_bytes);
520        Ok(proof_data)
521    }
522
523    /// Soundly verifies a tag-`0x01` NIZK Schnorr proof of knowledge blob:
524    /// verifies byte length (>= 130), tag/flag, `H(public_inputs)` equality with `C_p`,
525    /// parses `C_w` as a valid curve point (verifying key), parses the 64-byte signature `(R, s)`,
526    /// and verifies the Schnorr relation `s·B = R + e·C_w` against `H(b"qualia_zk_commitment_proof" || C_p || C_w)`.
527    /// Rejects any forged, incomplete, or invalid proofs.
528    pub fn verify_commitment_proof_data(
529        proof_data: &[u8],
530        public_inputs: &[Vec<u8>],
531    ) -> Result<bool, CryptographicError> {
532        use sha2::{Digest, Sha256};
533        use ed25519_dalek::{Signature, VerifyingKey};
534
535        if proof_data.len() < 130 {
536            return Ok(false);
537        }
538        if proof_data[64] != 0x01 || proof_data[65] != 0x01 {
539            return Ok(false);
540        }
541
542        // Verify public inputs binding
543        let mut pub_hasher = Sha256::new();
544        for p in public_inputs {
545            pub_hasher.update(p);
546        }
547        let expected_pub_commit: [u8; 32] = pub_hasher.finalize().into();
548        if &proof_data[32..64] != expected_pub_commit.as_slice() {
549            return Ok(false);
550        }
551
552        let witness_commit: [u8; 32] = match proof_data[..32].try_into() {
553            Ok(arr) => arr,
554            Err(_) => return Ok(false),
555        };
556
557        let verifying_key = match VerifyingKey::from_bytes(&witness_commit) {
558            Ok(vk) => vk,
559            Err(_) => return Ok(false),
560        };
561
562        let sig_bytes: [u8; 64] = match proof_data[66..130].try_into() {
563            Ok(arr) => arr,
564            Err(_) => return Ok(false),
565        };
566
567        let signature = Signature::from_bytes(&sig_bytes);
568
569        // Recompute transcript message: M = H(b"qualia_zk_commitment_proof" || C_p || C_w)
570        let mut msg_hasher = Sha256::new();
571        msg_hasher.update(b"qualia_zk_commitment_proof");
572        msg_hasher.update(&expected_pub_commit);
573        msg_hasher.update(&witness_commit);
574        let msg: [u8; 32] = msg_hasher.finalize().into();
575
576        // Verify Schnorr signature equation strictly: checks R, challenge hash, and s response
577        match verifying_key.verify_strict(&msg, &signature) {
578            Ok(_) => Ok(true),
579            Err(_) => Ok(false),
580        }
581    }
582
583    /// Reduce a secret WITNESS value to a field element via SHA-256 (the secret
584    /// never leaves the prover; only its field image enters the circuit).
585    #[cfg(feature = "zk-culling")]
586    fn bytes_to_fr(data: &[u8]) -> ark_bls12_381::Fr {
587        use ark_ff::PrimeField;
588        use sha2::{Digest, Sha256};
589        let hash = Sha256::digest(data);
590        ark_bls12_381::Fr::from_be_bytes_mod_order(hash.as_slice())
591    }
592
593    /// Interpret a PUBLIC input as a canonical little-endian field element — NOT
594    /// hashed. Prover and verifier must agree on the exact public value (e.g. a
595    /// `policy_root` the witness genuinely satisfies), so hashing it (as for a
596    /// witness) would make a valid proof unconstructible. Callers serialise the
597    /// field element little-endian (`Fr::into_bigint().to_bytes_le()`).
598    #[cfg(feature = "zk-culling")]
599    fn public_input_to_fr(data: &[u8]) -> ark_bls12_381::Fr {
600        use ark_ff::PrimeField;
601        ark_bls12_381::Fr::from_le_bytes_mod_order(data)
602    }
603
604    /// Returns the shared `(proving_key, verifying_key)` for the deontic
605    /// circuit, generating it once via `generate_deontic_crs`. NOTE: panics on
606    /// CRS-generation failure (`expect` inside `get_or_init`), not fail-closed.
607    #[cfg(feature = "zk-culling")]
608    fn deontic_crs() -> Result<
609        &'static (
610            ark_groth16::ProvingKey<ark_bls12_381::Bls12_381>,
611            ark_groth16::VerifyingKey<ark_bls12_381::Bls12_381>,
612        ),
613        CryptographicError,
614    > {
615        use std::sync::OnceLock;
616        static CRS: OnceLock<(
617            ark_groth16::ProvingKey<ark_bls12_381::Bls12_381>,
618            ark_groth16::VerifyingKey<ark_bls12_381::Bls12_381>,
619        )> = OnceLock::new();
620        CRS.get_or_init(|| {
621            crate::deontic_circuit::generate_deontic_crs()
622                .map_err(|e| CryptographicError::ProofError(e))
623                .expect("deontic CRS setup")
624        });
625        Ok(CRS.get().expect("deontic CRS initialized"))
626    }
627
628    /// Real Groth16 proof (BLS12-381) over the `DeonticAccessCircuit`: witness
629    /// fields hashed to `Fr`, public inputs read as canonical LE field
630    /// elements. Output is `[witness_commit ‖ pub_commit ‖ 0x02 ‖ proof]` —
631    /// this path IS a genuine SNARK.
632    #[cfg(feature = "zk-culling")]
633    fn generate_deontic_groth16_proof(
634        witness: &[Vec<u8>],
635        public_inputs: &[Vec<u8>],
636    ) -> Result<Vec<u8>, CryptographicError> {
637        use ark_bls12_381::Bls12_381;
638        use ark_groth16::Groth16;
639
640        use ark_serialize::CanonicalSerialize;
641        use ark_snark::SNARK;
642        use sha2::{Digest, Sha256};
643
644        let user_did = Self::bytes_to_fr(witness.first().map(|v| v.as_slice()).unwrap_or(b""));
645        let role_id = Self::bytes_to_fr(witness.get(1).map(|v| v.as_slice()).unwrap_or(b""));
646        let action_permission =
647            Self::bytes_to_fr(witness.get(2).map(|v| v.as_slice()).unwrap_or(b""));
648        let policy_root =
649            Self::public_input_to_fr(public_inputs.first().map(|v| v.as_slice()).unwrap_or(b""));
650        let temporal_constraint =
651            Self::public_input_to_fr(public_inputs.get(1).map(|v| v.as_slice()).unwrap_or(b""));
652
653        let circuit = crate::deontic_circuit::DeonticAccessCircuit {
654            user_did_commitment: Some(user_did),
655            role_id: Some(role_id),
656            action_permission: Some(action_permission),
657            policy_root: Some(policy_root),
658            temporal_constraint: Some(temporal_constraint),
659        };
660
661        let (pk, _vk) = Self::deontic_crs()?;
662        let mut rng = crate::zk_proofs::zk_secure_rng();
663        let proof = Groth16::<Bls12_381>::prove(pk, circuit, &mut rng)
664            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
665
666        let mut serialized = Vec::new();
667        proof
668            .serialize_uncompressed(&mut serialized)
669            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
670
671        let mut witness_hasher = Sha256::new();
672        witness_hasher.update(b"deontic_access");
673        for w in witness {
674            witness_hasher.update(w);
675        }
676        let witness_commit = witness_hasher.finalize();
677        let mut pub_hasher = Sha256::new();
678        for p in public_inputs {
679            pub_hasher.update(p);
680        }
681        let pub_commit = pub_hasher.finalize();
682
683        let mut proof_data = vec![0u8; 65 + serialized.len()];
684        proof_data[..32].copy_from_slice(&witness_commit);
685        proof_data[32..64].copy_from_slice(&pub_commit);
686        proof_data[64] = 0x02;
687        proof_data[65..].copy_from_slice(&serialized);
688        Ok(proof_data)
689    }
690
691    /// Real Groth16 verification of a tag-`0x02` proof blob against the shared
692    /// CRS verifying key; public inputs are converted with
693    /// `public_input_to_fr`.
694    #[cfg(feature = "zk-culling")]
695    fn verify_deontic_groth16_proof(
696        proof_data: &[u8],
697        public_inputs: &[Vec<u8>],
698    ) -> Result<bool, CryptographicError> {
699        use ark_bls12_381::{Bls12_381, Fr};
700        use ark_groth16::{Groth16, Proof};
701        use ark_serialize::CanonicalDeserialize;
702        use ark_snark::SNARK;
703
704        if proof_data.len() <= 65 {
705            return Ok(false);
706        }
707        let proof = Proof::<Bls12_381>::deserialize_uncompressed(&proof_data[65..])
708            .map_err(|e| CryptographicError::ProofError(e.to_string()))?;
709        let (_pk, vk) = Self::deontic_crs()?;
710        let public_fr: Vec<Fr> = public_inputs
711            .iter()
712            .map(|p| Self::public_input_to_fr(p))
713            .collect();
714        Ok(Groth16::<Bls12_381>::verify(vk, &public_fr, &proof)
715            .map_err(|e| CryptographicError::ProofError(e.to_string()))?)
716    }
717}
718
719impl ProofStorage {
720    /// Creates empty in-memory proof and verification-record stores with a fresh audit log.
721    pub fn new() -> Self {
722        Self {
723            proofs: HashMap::new(),
724            verification_records: HashMap::new(),
725            audit_log: ProofAuditLog::new(),
726        }
727    }
728
729    /// No-op — the in-memory stores need no setup.
730    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
731        Ok(())
732    }
733
734    /// Inserts `proof` keyed by `proof_id`; replaces any existing entry.
735    pub fn store_proof(&mut self, proof: Proof) -> Result<(), CryptographicError> {
736        self.proofs.insert(proof.proof_id.clone(), proof);
737        Ok(())
738    }
739
740    /// Inserts `record` keyed by `verification_id`; replaces any existing entry.
741    pub fn store_verification_record(
742        &mut self,
743        record: ProofVerificationRecord,
744    ) -> Result<(), CryptographicError> {
745        self.verification_records
746            .insert(record.verification_id.clone(), record);
747        Ok(())
748    }
749}
750
751impl ProofAuditLog {
752    /// Creates an empty log with a 365-day, archive-then-delete retention policy.
753    pub fn new() -> Self {
754        Self {
755            entries: Vec::new(),
756            retention_policy: RetentionPolicy {
757                retention_days: 365,
758                auto_delete: true,
759                archive_before_delete: true,
760            },
761        }
762    }
763
764    /// Record a proof operation (generate, verify, revoke, update).
765    pub fn log_entry(
766        &mut self,
767        proof_id: &str,
768        operation: ProofOperation,
769        user_id: &str,
770        success: bool,
771    ) {
772        let timestamp = std::time::SystemTime::now()
773            .duration_since(std::time::UNIX_EPOCH)
774            .unwrap_or_default()
775            .as_secs();
776        let entry = ProofAuditEntry {
777            entry_id: format!("proof_{}_{}", timestamp, self.entries.len()),
778            timestamp,
779            proof_id: proof_id.to_string(),
780            operation,
781            user_id: user_id.to_string(),
782            ip_address: String::new(),
783            success,
784        };
785        self.entries.push(entry);
786        let cutoff =
787            timestamp.saturating_sub((self.retention_policy.retention_days as u64) * 86400);
788        self.entries.retain(|e| e.timestamp >= cutoff);
789    }
790
791    /// Number of logged entries.
792    pub fn entry_count(&self) -> usize {
793        self.entries.len()
794    }
795
796    /// Iterate over entries.
797    pub fn entries(&self) -> &[ProofAuditEntry] {
798        &self.entries
799    }
800}
801
802impl ProofVerificationEngine {
803    /// Creates the engine with an empty algorithm registry, batch verifier, and performance optimizer.
804    pub fn new() -> Self {
805        Self {
806            verification_algorithms: HashMap::new(),
807            batch_verifier: BatchVerifier::new(),
808            performance_optimizer: VerificationPerformanceOptimizer::new(),
809        }
810    }
811
812    /// Directly verifies a commitment proof of knowledge blob against public inputs.
813    pub fn verify_commitment_proof_data(
814        proof_data: &[u8],
815        public_inputs: &[Vec<u8>],
816    ) -> Result<bool, CryptographicError> {
817        ProofEngine::verify_commitment_proof_data(proof_data, public_inputs)
818    }
819
820    /// Directly generates a commitment proof of knowledge blob from circuit, witness, and public inputs.
821    pub fn generate_commitment_proof_data(
822        circuit_id: &str,
823        witness: &[Vec<u8>],
824        public_inputs: &[Vec<u8>],
825    ) -> Result<Vec<u8>, CryptographicError> {
826        ProofEngine::generate_commitment_proof_data(circuit_id, witness, public_inputs)
827    }
828
829    /// Initializes the verification performance optimizer.
830    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
831        self.performance_optimizer.initialize()?;
832        Ok(())
833    }
834
835    /// Register a verification algorithm under a named key.
836    pub fn add_verification_algorithm(&mut self, name: String, algorithm: VerificationAlgorithm) {
837        self.verification_algorithms.insert(name, algorithm);
838    }
839
840    /// Look up a verification algorithm by name.
841    pub fn get_verification_algorithm(&self, name: &str) -> Option<&VerificationAlgorithm> {
842        self.verification_algorithms.get(name)
843    }
844
845    /// Iterate over all registered verification algorithms.
846    pub fn list_verification_algorithms(&self) -> impl Iterator<Item = &VerificationAlgorithm> {
847        self.verification_algorithms.values()
848    }
849
850    /// Get a reference to the batch verifier.
851    pub fn batch_verifier(&self) -> &BatchVerifier {
852        &self.batch_verifier
853    }
854
855    /// Get a mutable reference to the batch verifier.
856    pub fn batch_verifier_mut(&mut self) -> &mut BatchVerifier {
857        &mut self.batch_verifier
858    }
859}
860
861impl BatchVerifier {
862    /// Creates an empty batch verifier (no queued verifications).
863    pub fn new() -> Self {
864        Self {
865            batch_size: 100,
866            parallel_verification: true,
867            verification_queue: Vec::new(),
868        }
869    }
870
871    /// Get the configured batch size.
872    pub fn batch_size(&self) -> usize {
873        self.batch_size
874    }
875
876    /// Set the batch size.
877    pub fn set_batch_size(&mut self, size: usize) {
878        self.batch_size = size;
879    }
880
881    /// Whether parallel verification is enabled.
882    pub fn parallel_verification(&self) -> bool {
883        self.parallel_verification
884    }
885
886    /// Enable or disable parallel verification.
887    pub fn set_parallel_verification(&mut self, enabled: bool) {
888        self.parallel_verification = enabled;
889    }
890
891    /// Enqueue a verification for batch processing.
892    pub fn enqueue_verification(&mut self, verification: QueuedVerification) {
893        self.verification_queue.push(verification);
894    }
895
896    /// Dequeue the next verification (FIFO order).
897    pub fn dequeue_verification(&mut self) -> Option<QueuedVerification> {
898        if self.verification_queue.is_empty() {
899            None
900        } else {
901            Some(self.verification_queue.remove(0))
902        }
903    }
904
905    /// Number of verifications currently queued.
906    pub fn queue_len(&self) -> usize {
907        self.verification_queue.len()
908    }
909}
910
911impl VerificationPerformanceOptimizer {
912    /// Creates an optimizer with default tuning parameters and empty metrics.
913    pub fn new() -> Self {
914        Self {
915            optimization_strategies: vec![
916                VerificationOptimizationStrategy::BatchVerification,
917                VerificationOptimizationStrategy::ParallelProcessing,
918            ],
919            performance_metrics: VerificationPerformanceMetrics {
920                average_verification_time: 0.0,
921                throughput: 0.0,
922                cache_hit_rate: 0.0,
923                batch_efficiency: 0.0,
924            },
925        }
926    }
927
928    /// Resets verification performance metrics to zero.
929    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
930        Ok(())
931    }
932
933    /// Get the configured optimization strategies.
934    pub fn optimization_strategies(&self) -> &[VerificationOptimizationStrategy] {
935        &self.optimization_strategies
936    }
937
938    /// Add an optimization strategy if not already present.
939    pub fn add_optimization_strategy(&mut self, strategy: VerificationOptimizationStrategy) {
940        if !self.optimization_strategies.contains(&strategy) {
941            self.optimization_strategies.push(strategy);
942        }
943    }
944
945    /// Record a verification duration (milliseconds) and update running averages.
946    pub fn record_verification_time(&mut self, duration_ms: f64) {
947        let m = &mut self.performance_metrics;
948        if m.average_verification_time == 0.0 {
949            m.average_verification_time = duration_ms;
950        } else {
951            m.average_verification_time = 0.9 * m.average_verification_time + 0.1 * duration_ms;
952        }
953        if m.average_verification_time > 0.0 {
954            m.throughput = 1000.0 / m.average_verification_time;
955        }
956    }
957
958    /// Get a snapshot of the current performance metrics.
959    pub fn metrics(&self) -> &VerificationPerformanceMetrics {
960        &self.performance_metrics
961    }
962}
963
964impl VerificationPerformanceMetrics {
965    /// Returns a zeroed metrics record.
966    pub fn new() -> Self {
967        Self {
968            average_verification_time: 0.0,
969            throughput: 0.0,
970            cache_hit_rate: 0.0,
971            batch_efficiency: 0.0,
972        }
973    }
974}
975
976impl ProofPerformanceOptimizer {
977    /// Creates an optimizer with default tuning parameters and empty metrics.
978    pub fn new() -> Self {
979        Self {
980            optimization_strategies: vec![
981                ProofOptimizationStrategy::ParallelProving,
982                ProofOptimizationStrategy::CircuitOptimization,
983            ],
984            performance_metrics: ProofPerformanceMetrics {
985                average_proving_time: 0.0,
986                average_verification_time: 0.0,
987                proof_size: 0,
988                circuit_size: 0,
989                cache_hit_rate: 0.0,
990            },
991        }
992    }
993
994    /// Resets proving performance metrics to zero.
995    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
996        Ok(())
997    }
998
999    /// Get the configured optimization strategies.
1000    pub fn optimization_strategies(&self) -> &[ProofOptimizationStrategy] {
1001        &self.optimization_strategies
1002    }
1003
1004    /// Add an optimization strategy if not already present.
1005    pub fn add_optimization_strategy(&mut self, strategy: ProofOptimizationStrategy) {
1006        if !self.optimization_strategies.contains(&strategy) {
1007            self.optimization_strategies.push(strategy);
1008        }
1009    }
1010
1011    /// Record a proof generation duration (milliseconds).
1012    pub fn record_proving_time(&mut self, duration_ms: f64, proof_size: usize) {
1013        let m = &mut self.performance_metrics;
1014        if m.average_proving_time == 0.0 {
1015            m.average_proving_time = duration_ms;
1016        } else {
1017            m.average_proving_time = 0.9 * m.average_proving_time + 0.1 * duration_ms;
1018        }
1019        m.proof_size = proof_size as u64;
1020    }
1021
1022    /// Record a proof verification duration (milliseconds).
1023    pub fn record_verification_time(&mut self, duration_ms: f64) {
1024        let m = &mut self.performance_metrics;
1025        if m.average_verification_time == 0.0 {
1026            m.average_verification_time = duration_ms;
1027        } else {
1028            m.average_verification_time = 0.9 * m.average_verification_time + 0.1 * duration_ms;
1029        }
1030    }
1031
1032    /// Get a snapshot of the current performance metrics.
1033    pub fn metrics(&self) -> &ProofPerformanceMetrics {
1034        &self.performance_metrics
1035    }
1036}
1037
1038impl ProofPerformanceMetrics {
1039    /// Returns a zeroed metrics record.
1040    pub fn new() -> Self {
1041        Self {
1042            average_proving_time: 0.0,
1043            average_verification_time: 0.0,
1044            proof_size: 0,
1045            circuit_size: 0,
1046            cache_hit_rate: 0.0,
1047        }
1048    }
1049}
1050
1051#[cfg(test)]
1052mod tests {
1053    use super::*;
1054
1055    #[test]
1056    fn test_schnorr_commitment_proof_soundness_and_unforgeability() {
1057        let circuit_id = "test_circuit";
1058        let witness = vec![b"secret_witness_data".to_vec(), b"another_secret".to_vec()];
1059        let public_inputs = vec![b"public_constraint_1".to_vec(), b"public_value_2".to_vec()];
1060
1061        // 1. Generate valid proof
1062        let proof = ProofVerificationEngine::generate_commitment_proof_data(
1063            circuit_id,
1064            &witness,
1065            &public_inputs,
1066        )
1067        .expect("generate proof");
1068        assert_eq!(proof.len(), 130);
1069        assert_eq!(proof[64], 0x01);
1070        assert_eq!(proof[65], 0x01);
1071
1072        // 2. Valid proof verifies
1073        let valid = ProofVerificationEngine::verify_commitment_proof_data(&proof, &public_inputs)
1074            .expect("verify proof");
1075        assert!(valid, "Genuine Schnorr commitment proof must verify");
1076
1077        // 3. Forged public inputs must fail
1078        let forged_inputs = vec![b"tampered_constraint".to_vec()];
1079        let tampered_input_res =
1080            ProofVerificationEngine::verify_commitment_proof_data(&proof, &forged_inputs)
1081                .expect("verify proof");
1082        assert!(!tampered_input_res, "Tampered public inputs must fail verification");
1083
1084        // 4. Forged signature / altered response must fail
1085        let mut forged_proof = proof.clone();
1086        forged_proof[100] ^= 0xFF; // corrupt response byte in signature
1087        let tampered_sig_res =
1088            ProofVerificationEngine::verify_commitment_proof_data(&forged_proof, &public_inputs)
1089                .expect("verify proof");
1090        assert!(!tampered_sig_res, "Corrupted Schnorr signature response must fail verification");
1091
1092        // 5. Arbitrary dummy blob (STUBS.md F31 exploit) must fail
1093        let dummy_blob = vec![0x01u8; 130];
1094        let dummy_res =
1095            ProofVerificationEngine::verify_commitment_proof_data(&dummy_blob, &public_inputs)
1096                .expect("verify proof");
1097        assert!(!dummy_res, "Arbitrary dummy proof blob must fail verification");
1098    }
1099}