aingle_cortex 0.6.3

Córtex API - REST/GraphQL/SPARQL interface for AIngle semantic graphs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! Proof verification using aingle_zk
//!
//! This module integrates with aingle_zk to verify different types of
//! zero-knowledge proofs.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::store::{ProofType, StoredProof};

/// Verification error types
#[derive(Debug, Error, Clone, Serialize, Deserialize)]
pub enum VerificationError {
    /// Proof not found in store
    #[error("Proof not found: {0}")]
    ProofNotFound(String),

    /// Invalid proof data format
    #[error("Invalid proof data: {0}")]
    InvalidProofData(String),

    /// Proof verification failed
    #[error("Verification failed: {0}")]
    VerificationFailed(String),

    /// Unsupported proof type
    #[error("Unsupported proof type: {0}")]
    UnsupportedProofType(String),

    /// Missing required data for verification
    #[error("Missing verification data: {0}")]
    MissingData(String),

    /// Deserialization error
    #[error("Deserialization error: {0}")]
    DeserializationError(String),

    /// ZK library error
    #[error("ZK error: {0}")]
    ZkError(String),
}

/// Result of proof verification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationResult {
    /// Whether the proof is valid
    pub valid: bool,
    /// Type of proof verified
    pub proof_type: ProofType,
    /// Timestamp of verification
    pub verified_at: DateTime<Utc>,
    /// Verification details/messages
    pub details: Vec<String>,
    /// Time taken to verify (microseconds)
    pub verification_time_us: u64,
}

impl VerificationResult {
    /// Create a successful verification result
    pub fn success(proof_type: ProofType, verification_time_us: u64) -> Self {
        Self {
            valid: true,
            proof_type,
            verified_at: Utc::now(),
            details: vec!["Proof verification succeeded".to_string()],
            verification_time_us,
        }
    }

    /// Create a failed verification result
    pub fn failure(proof_type: ProofType, reason: String, verification_time_us: u64) -> Self {
        Self {
            valid: false,
            proof_type,
            verified_at: Utc::now(),
            details: vec![format!("Verification failed: {}", reason)],
            verification_time_us,
        }
    }

    /// Add a detail message
    pub fn with_detail(mut self, detail: String) -> Self {
        self.details.push(detail);
        self
    }
}

/// Reconstruct a `ZkProof` from a `StoredProof` whose `data` field contains
/// only the raw `proof_data` JSON (without the ZkProof envelope).
fn reconstruct_zk_proof(proof: &StoredProof) -> Result<aingle_zk::ZkProof, VerificationError> {
    let mut proof_data: serde_json::Value = serde_json::from_slice(&proof.data)
        .map_err(|e| VerificationError::DeserializationError(e.to_string()))?;

    // Inject the ProofData serde tag ("type") if the client omitted it.
    // ProofData uses #[serde(tag = "type")] so deserialisation requires it.
    if let serde_json::Value::Object(ref mut map) = proof_data {
        if !map.contains_key("type") {
            let tag = cortex_to_proof_data_tag(&proof.proof_type);
            map.insert("type".into(), serde_json::Value::String(tag.into()));
        }
    }

    let zk_type = cortex_to_zk_proof_type(&proof.proof_type);

    let envelope = serde_json::json!({
        "proof_type": serde_json::to_value(&zk_type)
            .map_err(|e| VerificationError::DeserializationError(e.to_string()))?,
        "proof_data": proof_data,
        "timestamp": proof.created_at.timestamp() as u64,
        "metadata": null
    });

    serde_json::from_value(envelope)
        .map_err(|e| VerificationError::DeserializationError(
            format!("Failed to reconstruct ZkProof envelope: {e}")
        ))
}

/// Map Cortex `ProofType` → `aingle_zk::ProofType`.
fn cortex_to_zk_proof_type(pt: &ProofType) -> aingle_zk::ProofType {
    match pt {
        ProofType::Schnorr | ProofType::Knowledge | ProofType::HashOpening => {
            aingle_zk::ProofType::KnowledgeProof
        }
        ProofType::Equality => aingle_zk::ProofType::EqualityProof,
        ProofType::Membership => aingle_zk::ProofType::MembershipProof,
        ProofType::NonMembership => aingle_zk::ProofType::NonMembershipProof,
        ProofType::Range => aingle_zk::ProofType::RangeProof,
    }
}

/// Map Cortex `ProofType` → `ProofData` serde tag value.
fn cortex_to_proof_data_tag(pt: &ProofType) -> &'static str {
    match pt {
        ProofType::Schnorr | ProofType::Knowledge => "Knowledge",
        ProofType::HashOpening => "HashOpening",
        ProofType::Equality => "Equality",
        ProofType::Membership | ProofType::NonMembership => "Membership",
        ProofType::Range => "Knowledge",
    }
}

/// Proof verifier that integrates with aingle_zk
pub struct ProofVerifier {
    /// Configuration for verification
    config: VerifierConfig,
}

/// Configuration for proof verification
#[derive(Debug, Clone)]
pub struct VerifierConfig {
    /// Maximum proof size in bytes
    pub max_proof_size: usize,
    /// Timeout for verification in seconds
    pub timeout_seconds: u64,
    /// Enable strict verification mode
    pub strict_mode: bool,
}

impl Default for VerifierConfig {
    fn default() -> Self {
        Self {
            max_proof_size: 10 * 1024 * 1024, // 10 MB
            timeout_seconds: 30,
            strict_mode: false,
        }
    }
}

impl ProofVerifier {
    /// Create a new proof verifier
    pub fn new() -> Self {
        Self::with_config(VerifierConfig::default())
    }

    /// Create a verifier with custom configuration
    pub fn with_config(config: VerifierConfig) -> Self {
        Self { config }
    }

    /// Verify a stored proof
    pub async fn verify(
        &self,
        proof: &StoredProof,
    ) -> Result<VerificationResult, VerificationError> {
        let start = std::time::Instant::now();

        // Check proof size
        if proof.data.len() > self.config.max_proof_size {
            return Err(VerificationError::InvalidProofData(format!(
                "Proof size {} exceeds maximum {}",
                proof.data.len(),
                self.config.max_proof_size
            )));
        }

        // Deserialize the proof data into aingle_zk::ZkProof.
        // The stored data may be just the raw proof_data (without the ZkProof
        // envelope) when submitted via the REST API, since submit() only
        // persists request.proof_data. Try full envelope first, then
        // reconstruct from StoredProof.proof_type + raw proof data.
        let zk_proof: aingle_zk::ZkProof = serde_json::from_slice(&proof.data)
            .or_else(|_| reconstruct_zk_proof(proof))?;

        // Verify based on proof type
        let valid = match proof.proof_type {
            ProofType::Schnorr => self.verify_schnorr(&zk_proof).await?,
            ProofType::Equality => self.verify_equality(&zk_proof).await?,
            ProofType::Membership => self.verify_membership(&zk_proof).await?,
            ProofType::NonMembership => self.verify_non_membership(&zk_proof).await?,
            ProofType::Range => self.verify_range(&zk_proof).await?,
            ProofType::HashOpening => self.verify_hash_opening(&zk_proof).await?,
            ProofType::Knowledge => self.verify_knowledge(&zk_proof).await?,
        };

        let elapsed = start.elapsed();
        let verification_time_us = elapsed.as_micros() as u64;

        if valid {
            Ok(VerificationResult::success(
                proof.proof_type.clone(),
                verification_time_us,
            ))
        } else {
            Ok(VerificationResult::failure(
                proof.proof_type.clone(),
                "Proof verification returned false".to_string(),
                verification_time_us,
            ))
        }
    }

    /// Batch verify multiple proofs
    pub async fn batch_verify(
        &self,
        proofs: &[StoredProof],
    ) -> Vec<Result<VerificationResult, VerificationError>> {
        let mut results = Vec::new();
        for proof in proofs {
            results.push(self.verify(proof).await);
        }
        results
    }

    // Private verification methods for each proof type

    async fn verify_schnorr(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        // Use aingle_zk's ProofVerifier
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_equality(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_membership(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        // For membership proofs, we need the actual data
        // This is a structural verification - the proof format is valid
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_non_membership(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        // Non-membership proofs also require data
        // Here we verify the proof structure
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_range(&self, zk_proof: &aingle_zk::ZkProof) -> Result<bool, VerificationError> {
        // Range proofs (bulletproofs) verification
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_hash_opening(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        // Hash commitment opening verification
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    async fn verify_knowledge(
        &self,
        zk_proof: &aingle_zk::ZkProof,
    ) -> Result<bool, VerificationError> {
        // Knowledge proof verification (Schnorr-like)
        aingle_zk::ProofVerifier::verify(zk_proof)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    /// Verify membership proof with actual data
    pub async fn verify_membership_with_data(
        &self,
        zk_proof: &aingle_zk::ZkProof,
        data: &[u8],
    ) -> Result<bool, VerificationError> {
        aingle_zk::ProofVerifier::verify_membership(zk_proof, data)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }

    /// Verify hash opening with actual data
    pub async fn verify_hash_opening_with_data(
        &self,
        zk_proof: &aingle_zk::ZkProof,
        data: &[u8],
    ) -> Result<bool, VerificationError> {
        aingle_zk::ProofVerifier::verify_hash_opening(zk_proof, data)
            .map_err(|e| VerificationError::ZkError(e.to_string()))
    }
}

impl Default for ProofVerifier {
    fn default() -> Self {
        Self::new()
    }
}

/// Batch verification helper
pub struct BatchVerificationHelper {
    verifier: ProofVerifier,
    results: Vec<VerificationResult>,
}

impl BatchVerificationHelper {
    /// Create a new batch verification helper
    pub fn new(verifier: ProofVerifier) -> Self {
        Self {
            verifier,
            results: Vec::new(),
        }
    }

    /// Add a proof to verify
    pub async fn add(&mut self, proof: &StoredProof) -> Result<(), VerificationError> {
        let result = self.verifier.verify(proof).await?;
        self.results.push(result);
        Ok(())
    }

    /// Get all verification results
    pub fn results(&self) -> &[VerificationResult] {
        &self.results
    }

    /// Check if all proofs are valid
    pub fn all_valid(&self) -> bool {
        self.results.iter().all(|r| r.valid)
    }

    /// Get count of valid proofs
    pub fn valid_count(&self) -> usize {
        self.results.iter().filter(|r| r.valid).count()
    }

    /// Get count of invalid proofs
    pub fn invalid_count(&self) -> usize {
        self.results.iter().filter(|r| !r.valid).count()
    }

    /// Get total verification time
    pub fn total_time_us(&self) -> u64 {
        self.results.iter().map(|r| r.verification_time_us).sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proofs::store::ProofMetadata;

    fn create_test_proof(proof_type: ProofType, valid: bool) -> StoredProof {
        // Create a valid ZkProof structure from aingle_zk
        let zk_proof = if valid {
            // Create a simple hash opening proof
            let commitment = aingle_zk::HashCommitment::commit(b"test data");
            aingle_zk::ZkProof::hash_opening(&commitment)
        } else {
            // Create invalid proof with wrong data
            aingle_zk::ZkProof::hash_opening(&aingle_zk::HashCommitment {
                hash: [0u8; 32],
                salt: [0u8; 32],
            })
        };

        let proof_json = serde_json::to_vec(&zk_proof).unwrap();
        StoredProof::new(proof_type, proof_json, ProofMetadata::default())
    }

    #[tokio::test]
    async fn test_verify_valid_proof() {
        let verifier = ProofVerifier::new();
        let proof = create_test_proof(ProofType::HashOpening, true);

        let result = verifier.verify(&proof).await;
        assert!(result.is_ok());

        let result = result.unwrap();
        assert!(result.valid);
        assert_eq!(result.proof_type, ProofType::HashOpening);
        assert!(!result.details.is_empty());
    }

    #[tokio::test]
    async fn test_verify_invalid_proof() {
        let verifier = ProofVerifier::new();
        let proof = create_test_proof(ProofType::HashOpening, false);

        let result = verifier.verify(&proof).await;
        assert!(result.is_ok());

        let result = result.unwrap();
        assert!(!result.valid);
    }

    #[tokio::test]
    async fn test_batch_verify() {
        let verifier = ProofVerifier::new();
        let proofs = vec![
            create_test_proof(ProofType::HashOpening, true),
            create_test_proof(ProofType::HashOpening, true),
        ];

        let results = verifier.batch_verify(&proofs).await;
        assert_eq!(results.len(), 2);
        assert!(results[0].is_ok());
        assert!(results[1].is_ok());
    }

    #[tokio::test]
    async fn test_batch_verification_helper() {
        let verifier = ProofVerifier::new();
        let mut helper = BatchVerificationHelper::new(verifier);

        let proof1 = create_test_proof(ProofType::Knowledge, true);
        let proof2 = create_test_proof(ProofType::Knowledge, true);

        helper.add(&proof1).await.unwrap();
        helper.add(&proof2).await.unwrap();

        assert_eq!(helper.results().len(), 2);
        assert!(helper.all_valid());
        assert_eq!(helper.valid_count(), 2);
        assert_eq!(helper.invalid_count(), 0);
        assert!(helper.total_time_us() > 0);
    }

    #[tokio::test]
    async fn test_verification_result_creation() {
        let success = VerificationResult::success(ProofType::Schnorr, 1000);
        assert!(success.valid);
        assert_eq!(success.verification_time_us, 1000);

        let failure =
            VerificationResult::failure(ProofType::Equality, "Test failure".to_string(), 2000);
        assert!(!failure.valid);
        assert_eq!(failure.verification_time_us, 2000);
        assert!(failure.details.iter().any(|d| d.contains("Test failure")));
    }

    #[tokio::test]
    async fn test_verifier_config() {
        let config = VerifierConfig {
            max_proof_size: 1024,
            timeout_seconds: 10,
            strict_mode: true,
        };

        let verifier = ProofVerifier::with_config(config.clone());
        assert_eq!(verifier.config.max_proof_size, 1024);
        assert_eq!(verifier.config.timeout_seconds, 10);
        assert!(verifier.config.strict_mode);
    }

    /// Simulates the real REST API path: submit() stores only proof_data
    /// (without the ZkProof envelope), and verify() must reconstruct it.
    #[tokio::test]
    async fn test_verify_proof_stored_without_envelope() {
        let verifier = ProofVerifier::new();

        // Create a valid hash-opening proof via aingle_zk
        let commitment = aingle_zk::HashCommitment::commit(b"test data");
        let zk_proof = aingle_zk::ZkProof::hash_opening(&commitment);

        // Store ONLY the proof_data portion (what submit() actually does)
        let proof_data_only = serde_json::to_vec(&zk_proof.proof_data).unwrap();
        let stored = StoredProof::new(
            ProofType::HashOpening,
            proof_data_only,
            ProofMetadata::default(),
        );

        // This is the exact path that was failing with 422
        let result = verifier.verify(&stored).await;
        assert!(result.is_ok(), "verify() should reconstruct ZkProof envelope: {:?}", result.err());
        assert!(result.unwrap().valid);
    }

    /// Verify reconstruction works when client sends raw fields without serde tag.
    #[tokio::test]
    async fn test_verify_proof_without_type_tag() {
        let verifier = ProofVerifier::new();

        // Client sends proof_data as raw JSON without the ProofData "type" tag
        let commitment = aingle_zk::HashCommitment::commit(b"test data");
        let raw = serde_json::json!({
            "commitment": commitment.hash,
            "salt": commitment.salt,
        });
        let raw_bytes = serde_json::to_vec(&raw).unwrap();

        let stored = StoredProof::new(
            ProofType::HashOpening,
            raw_bytes,
            ProofMetadata::default(),
        );

        let result = verifier.verify(&stored).await;
        assert!(result.is_ok(), "verify() should inject type tag: {:?}", result.err());
        assert!(result.unwrap().valid);
    }

    #[tokio::test]
    async fn test_proof_size_limit() {
        let config = VerifierConfig {
            max_proof_size: 10, // Very small limit
            timeout_seconds: 30,
            strict_mode: false,
        };
        let verifier = ProofVerifier::with_config(config);

        let proof = create_test_proof(ProofType::Knowledge, true);
        let result = verifier.verify(&proof).await;

        assert!(result.is_err());
        match result {
            Err(VerificationError::InvalidProofData(msg)) => {
                assert!(msg.contains("exceeds maximum"));
            }
            _ => panic!("Expected InvalidProofData error"),
        }
    }
}