lib-q-zkp 0.0.5

Post-quantum Zero-Knowledge Proofs for lib-Q
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! lib-Q ZKP - Post-quantum Zero-Knowledge Proofs
//!
//! This crate provides implementations of post-quantum zero-knowledge proofs.
//!
//! # zk-STARK Implementation
//!
//! This crate provides a high-level API for creating and verifying zk-STARK proofs.
//! The underlying implementation is based on Plonky3, adapted for lib-Q's post-quantum
//! security requirements using SHAKE256.
//!
//! ## Field Configuration
//!
//! The implementation uses **`Complex<Mersenne31>`** as the base field, which provides:
//! - **TWO_ADICITY = 32**: Sufficient for FRI protocol and efficient FFT operations
//! - **Post-quantum security**: All operations use NIST-approved primitives
//! - **Efficient arithmetic**: Optimized field operations for STARK proofs
//!
//! ## Example Usage
//!
//! ```rust,ignore
//! use lib_q_zkp::stark::{StarkProver, StarkVerifier, default_config};
//! use lib_q_stark_field::extension::Complex;
//! use lib_q_stark_mersenne31::Mersenne31;
//!
//! type Val = Complex<Mersenne31>;
//!
//! // Create prover and verifier with default configuration
//! let config = default_config();
//! let prover = StarkProver::new(config.clone());
//! let verifier = StarkVerifier::new(config);
//!
//! // Generate proof (requires AIR implementation)
//! // let proof = prover.prove(&air, trace, &public_values);
//!
//! // Verify proof
//! // verifier.verify(&air, &proof, &public_values)?;
//! ```
//!
//! ## Testing
//!
//! - **Recursive aggregation**: The test `test_recursive_verifier_trace_satisfies_constraints_then_prove_verify` (in `aggregation_tests`) runs the full prove → aggregate → verify pipeline. It is slow in dev (unoptimized); run with `--release` for completion in a few minutes. CI runs this test in release with a 15-minute timeout.
//! - **Merkle tree builder**: `tests/merkle_tree_builder_tests.rs` uses [`stark::fast_proof_config`] for prove/verify round-trips (fast FRI); wrong-root and cross-tree rejection use [`stark::default_config`] because minimal FRI is not sound for those negatives.
//! - **Merkle tree certificates**: Create/use and security checks (wrong root, wrong depth, cross-tree) are covered by `tests/merkle_certificate_tests.rs`. Additional Merkle and group-membership tests live in `air_integration` and `ip_soundness_tests`.

#![cfg_attr(not(feature = "std"), no_std)]
// Bounds on generic type parameters in aliases are not enforced by the type checker (Rust RFC
// follow-up); we still document constraints via `C: StarkGenericConfig` / `F: Field` on aliases.
#![allow(type_alias_bounds)]
#![deny(unsafe_code)]
#![deny(unused_qualifications)]
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::collapsible_if)]
#![allow(clippy::get_first)]
#![allow(clippy::iter_cloned_collect)]
#![allow(clippy::manual_is_multiple_of)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::unnecessary_lazy_evaluations)]

#[cfg(feature = "alloc")]
extern crate alloc;

// Re-export core types for public use
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::string::ToString;
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

pub use lib_q_core::Result;
/// Plonky3-derived components (Keccak AIR, lookup, batch STARK, etc.).
///
/// Enabled when any of `plonky` or the granular `plonky-*` features is on (each pulls in
/// `lib-q-plonky` with the corresponding sub-features; `plonky` enables the full set).
#[cfg(any(
    feature = "plonky",
    feature = "plonky-keccak-air",
    feature = "plonky-lookup",
    feature = "plonky-uni-stark",
    feature = "plonky-batch-stark",
))]
pub use lib_q_plonky as plonky;

/// zk-STARK implementation
#[cfg(feature = "zkp")]
pub mod stark;

/// Circuit builder for arithmetic constraints
#[cfg(feature = "zkp")]
pub mod circuit;

/// AIR implementations for common proof types
#[cfg(feature = "zkp")]
pub mod air;

/// Proof aggregation for combining multiple proofs
#[cfg(feature = "zkp")]
pub mod aggregation;

/// IP (Identity Protocol) integration
#[cfg(feature = "zkp")]
pub mod ip;

/// Poseidon Merkle tree builder (compatible with MerkleInclusionAir)
#[cfg(feature = "zkp")]
pub mod merkle;

/// High-level lib q API
#[cfg(feature = "zkp")]
pub mod api;

#[cfg(feature = "zkp")]
pub use api::{
    MerklePath,
    build_merkle_tree,
    prove_membership,
    prove_membership_with_config,
    prove_preimage,
    prove_preimage_nist,
    verify_membership,
    verify_membership_with_config,
    verify_membership_with_depth,
    verify_membership_with_depth_and_config,
    verify_preimage,
    verify_preimage_nist,
};

#[cfg(feature = "wasm")]
mod wasm;

#[cfg(feature = "zkp")]
pub use lib_q_stark::{
    Proof as StarkProof,
    StarkConfig,
    StarkGenericConfig,
    check_constraints,
    prove,
    verify,
};
#[cfg(feature = "zkp")]
pub use lib_q_stark_air::Air;
#[cfg(feature = "zkp")]
use lib_q_stark_field::extension::Complex;
#[cfg(feature = "zkp")]
use lib_q_stark_matrix::dense::RowMajorMatrix;
#[cfg(feature = "zkp")]
use lib_q_stark_mersenne31::Mersenne31;
#[cfg(feature = "zkp")]
pub use merkle::PoseidonMerkleTree;
#[cfg(feature = "zkp")]
use serde::{
    Deserialize,
    Serialize,
};

#[cfg(feature = "zkp")]
#[allow(unused_imports)]
use crate::air::TraceGenerator;

/// The field type used for ZKP operations
///
/// Uses `Complex<Mersenne31>` which provides TWO_ADICITY = 32, sufficient for
/// FRI protocol and efficient FFT operations.
#[cfg(feature = "zkp")]
pub type ZkpField = Complex<Mersenne31>;

/// Metadata specific to different proof types
///
/// This enum stores proof-specific parameters that are required for verification.
/// The metadata is serialized alongside the proof to make proofs self-describing.
///
/// All proofs must include appropriate metadata for their proof type.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "zkp", derive(Serialize, Deserialize))]
pub enum ProofMetadata {
    /// No metadata (default variant, but proofs should use specific metadata types)
    #[default]
    None,
    /// Merkle tree inclusion proof metadata
    MerkleInclusion {
        /// Depth of the Merkle tree (required for AIR reconstruction)
        tree_depth: u8,
    },
    /// Hash preimage proof metadata (Poseidon-128)
    HashPreimage {
        /// Output size in bytes
        output_size: u16,
    },
    /// NIST hash preimage proof metadata (cSHAKE256)
    HashPreimageNist {
        /// Output size in bytes (e.g. 32 for cSHAKE256)
        output_size: u16,
    },
    /// Circuit computation proof metadata
    Circuit {
        /// Number of witness values
        num_witnesses: u32,
        /// Number of public values
        num_public: u32,
    },
    /// Credential proof metadata for selective disclosure
    Credential {
        /// Serialized credential schema (attribute sizes in bytes)
        attribute_sizes: Vec<u16>,
        /// Reveal mask (which attributes are revealed: true = revealed, false = hidden)
        reveal_mask: Vec<bool>,
    },
    /// Identity Token ownership proof metadata
    Identity {
        /// ML-DSA security level: 44, 65, or 87
        dsa_level: u8,
    },
}

/// A zero-knowledge proof
#[derive(Debug, Clone)]
#[cfg_attr(feature = "zkp", derive(serde::Serialize, serde::Deserialize))]
pub struct ZkpProof {
    /// The proof data (serialized STARK proof)
    pub data: Vec<u8>,
    /// The proof type
    pub proof_type: ProofType,
    /// Security level
    pub security_level: u32,
    /// Proof-specific metadata (required for verification)
    pub metadata: ProofMetadata,
}

#[cfg(feature = "zkp")]
impl ZkpProof {
    /// Serialize a STARK proof into a ZkpProof with metadata
    ///
    /// All proofs must include metadata for proper verification.
    /// This method is used internally by the high-level API functions.
    pub fn from_stark_proof<C: StarkGenericConfig>(
        proof: &StarkProof<C>,
        metadata: ProofMetadata,
    ) -> Result<Self>
    where
        StarkProof<C>: Serialize,
    {
        let data = postcard::to_allocvec(proof).map_err(|_| lib_q_core::Error::InternalError {
            operation: "ZKP proof serialization".to_string(),
            details: "Failed to serialize STARK proof".to_string(),
        })?;
        Ok(Self {
            data,
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata,
        })
    }

    /// Deserialize a ZkpProof into a STARK proof
    pub fn to_stark_proof<C: StarkGenericConfig>(&self) -> Result<StarkProof<C>>
    where
        StarkProof<C>: for<'de> Deserialize<'de>,
    {
        postcard::from_bytes(&self.data).map_err(|_| lib_q_core::Error::InternalError {
            operation: "ZKP proof deserialization".to_string(),
            details: "Failed to deserialize STARK proof".to_string(),
        })
    }

    /// Get the tree depth from Merkle inclusion proof metadata
    ///
    /// Returns `Some(depth)` if this is a Merkle inclusion proof with metadata,
    /// `None` otherwise.
    pub fn merkle_tree_depth(&self) -> Option<u8> {
        match &self.metadata {
            ProofMetadata::MerkleInclusion { tree_depth } => Some(*tree_depth),
            _ => None,
        }
    }
}

/// Types of zero-knowledge proofs supported by lib-Q
///
/// Only NIST-approved post-quantum proof systems are included.
/// Classical schemes (SNARKs, Bulletproofs) are intentionally excluded.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "zkp", derive(serde::Serialize, serde::Deserialize))]
pub enum ProofType {
    /// zk-STARK proof (transparent, post-quantum secure)
    Stark,
}

/// Prover for creating zero-knowledge proofs
#[cfg(feature = "zkp")]
pub struct ZkpProver {
    // Using default config for now - can be extended to support custom configs
}

#[cfg(not(feature = "zkp"))]
pub struct ZkpProver;

/// Verifier for verifying zero-knowledge proofs
#[cfg(feature = "zkp")]
pub struct ZkpVerifier {
    // Using default config for now - can be extended to support custom configs
}

#[cfg(not(feature = "zkp"))]
pub struct ZkpVerifier;

#[cfg(feature = "zkp")]
impl ZkpProver {
    /// Create a new ZKP prover
    pub fn new() -> Self {
        Self {}
    }

    /// Prove knowledge of a secret value without revealing it
    ///
    /// This generates a STARK proof that the prover knows a preimage `secret_value`
    /// whose **Poseidon-128** hash equals the public commitment. The proof uses
    /// Poseidon for constraint encoding (industry-standard for STARKs; e.g. StarkWare,
    /// RISC Zero, Succinct). For a NIST-only hash, use [`prove_secret_value_nist`](ZkpProver::prove_secret_value_nist).
    ///
    /// # Arguments
    ///
    /// * `secret_value` - The secret preimage to prove knowledge of
    /// * `public_statement` - Additional public data (currently unused; reserved for future use)
    ///
    /// # Returns
    ///
    /// A zero-knowledge proof that can be verified without revealing the secret
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use lib_q_zkp::{ZkpProver, ZkpVerifier};
    ///
    /// let mut prover = ZkpProver::new();
    /// let secret = b"my secret password";
    /// let public = b"challenge";
    ///
    /// let proof = prover.prove_secret_value(secret, public)?;
    /// ```
    pub fn prove_secret_value(
        &mut self,
        secret_value: &[u8],
        _public_statement: &[u8],
    ) -> Result<ZkpProof> {
        use crate::air::{
            HashPreimageAir,
            TraceGenerator,
        };
        use crate::stark::{
            StarkProver,
            default_config,
        };

        // Validate input size
        if secret_value.is_empty() {
            return Err(lib_q_core::Error::InvalidState {
                operation: "prove_secret_value".to_string(),
                reason: "Secret value cannot be empty".to_string(),
            });
        }

        if secret_value.len() > air::hash_preimage::MAX_PREIMAGE_SIZE {
            return Err(lib_q_core::Error::InvalidState {
                operation: "prove_secret_value".to_string(),
                reason: "Secret value exceeds maximum size".to_string(),
            });
        }

        // Create the hash preimage AIR
        let air = HashPreimageAir::new();

        // Generate trace from the secret preimage
        let input = secret_value.to_vec();
        let trace: RowMajorMatrix<ZkpField> =
            air.generate_trace(&input)
                .map_err(|e| lib_q_core::Error::InternalError {
                    operation: "prove_secret_value".to_string(),
                    details: e.to_string(),
                })?;

        // Get public values (the hash output)
        let public_values: Vec<ZkpField> = air.public_values(&input);

        // Create prover with default config
        let config = default_config();
        let prover = StarkProver::new(config);

        // Generate STARK proof
        let proof = prover.prove(&air, trace, &public_values).map_err(|e| {
            lib_q_core::Error::InternalError {
                operation: "STARK proof generation".to_string(),
                details: e.to_string(),
            }
        })?;

        // Store output size in proof metadata
        let metadata = ProofMetadata::HashPreimage { output_size: 1u16 };

        // Serialize into ZkpProof
        ZkpProof::from_stark_proof(&proof, metadata)
    }

    /// Prove knowledge of a secret value using NIST cSHAKE256 (100% NIST compliance)
    ///
    /// Same semantics as [`prove_secret_value`](ZkpProver::prove_secret_value) but uses
    /// cSHAKE256 with domain `b"HashPreimageNistAir"` for the commitment. Use this when
    /// NIST-only hashes are required; prover cost is higher than Poseidon-based proofs.
    ///
    /// # Arguments
    ///
    /// * `secret_value` - The secret preimage to prove knowledge of
    /// * `_public_statement` - Reserved for future use
    pub fn prove_secret_value_nist(
        &mut self,
        secret_value: &[u8],
        _public_statement: &[u8],
    ) -> Result<ZkpProof> {
        use crate::air::{
            HASH_OUTPUT_BYTES,
            HashPreimageNistAir,
            TraceGenerator,
        };
        use crate::stark::{
            StarkProver,
            default_config,
        };

        if secret_value.is_empty() {
            return Err(lib_q_core::Error::InvalidState {
                operation: "prove_secret_value_nist".to_string(),
                reason: "Secret value cannot be empty".to_string(),
            });
        }
        if secret_value.len() > air::hash_preimage_nist::MAX_PREIMAGE_SIZE {
            return Err(lib_q_core::Error::InvalidState {
                operation: "prove_secret_value_nist".to_string(),
                reason: "Secret value exceeds maximum size".to_string(),
            });
        }

        let air = HashPreimageNistAir::new();
        let input = secret_value.to_vec();
        let trace: RowMajorMatrix<ZkpField> =
            air.generate_trace(&input)
                .map_err(|e| lib_q_core::Error::InternalError {
                    operation: "prove_secret_value_nist".to_string(),
                    details: e.to_string(),
                })?;

        let public_values: Vec<ZkpField> = air.public_values(&input);
        let config = default_config();
        let prover = StarkProver::new(config);

        let proof = prover.prove(&air, trace, &public_values).map_err(|e| {
            lib_q_core::Error::InternalError {
                operation: "STARK proof generation (NIST)".to_string(),
                details: e.to_string(),
            }
        })?;

        let metadata = ProofMetadata::HashPreimageNist {
            output_size: HASH_OUTPUT_BYTES as u16,
        };
        ZkpProof::from_stark_proof(&proof, metadata)
    }

    /// Prove a computation using a circuit
    ///
    /// This generates a STARK proof that the prover knows witness values that
    /// satisfy all constraints in the arithmetic circuit.
    ///
    /// # Arguments
    ///
    /// * `circuit` - The arithmetic circuit defining the computation
    /// * `witness` - The witness values (private inputs)
    /// * `public` - The public input values
    ///
    /// # Returns
    ///
    /// A zero-knowledge proof of computation correctness
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use lib_q_zkp::{ZkpProver, circuit::CircuitBuilder};
    /// use lib_q_stark_field::extension::Complex;
    /// use lib_q_stark_mersenne31::Mersenne31;
    ///
    /// type Val = Complex<Mersenne31>;
    ///
    /// // Build a circuit: prove knowledge of a, b such that a * b = public_output
    /// let mut builder = CircuitBuilder::<Val>::new(2, 1);
    /// let a = builder.wire(0);
    /// let b = builder.wire(1);
    /// let output = builder.wire(2);
    /// let product = builder.mul(a, b);
    /// builder.assert_eq(product, output);
    /// let circuit = builder.build();
    ///
    /// // Generate proof
    /// let witness = vec![Val::from(3u32), Val::from(4u32)];
    /// let public = vec![Val::from(12u32)];
    ///
    /// let mut prover = ZkpProver::new();
    /// let proof = prover.prove_computation(&circuit, &witness, &public)?;
    /// ```
    pub fn prove_computation(
        &mut self,
        circuit: &circuit::ArithmeticCircuit<ZkpField>,
        witness: &[ZkpField],
        public: &[ZkpField],
    ) -> Result<ZkpProof> {
        use crate::circuit::CircuitAir;
        use crate::stark::{
            StarkProver,
            default_config,
        };

        // Create the circuit AIR
        let air = CircuitAir::new(circuit.clone());

        // Generate trace from witness and public values
        let trace = air.generate_trace(witness, public)?;

        // Create prover with default config
        let config = default_config();
        let prover = StarkProver::new(config);

        // Generate STARK proof
        let proof =
            prover
                .prove(&air, trace, public)
                .map_err(|e| lib_q_core::Error::InternalError {
                    operation: "STARK proof generation".to_string(),
                    details: e.to_string(),
                })?;

        // Store circuit parameters in proof metadata
        let metadata = ProofMetadata::Circuit {
            num_witnesses: witness.len().min(u32::MAX as usize) as u32,
            num_public: public.len().min(u32::MAX as usize) as u32,
        };

        // Serialize into ZkpProof
        ZkpProof::from_stark_proof(&proof, metadata)
    }
}

#[cfg(not(feature = "zkp"))]
impl ZkpProver {
    /// Create a new ZKP prover
    pub fn new() -> Self {
        Self {}
    }

    /// Prove knowledge of a secret value without revealing it
    pub fn prove_secret_value(
        &mut self,
        _secret_value: &[u8],
        _public_statement: &[u8],
    ) -> Result<ZkpProof> {
        Err(lib_q_core::Error::NotImplemented {
            feature: "ZKP feature not enabled".to_string(),
        })
    }

    /// Prove knowledge of a secret value (NIST variant)
    pub fn prove_secret_value_nist(
        &mut self,
        _secret_value: &[u8],
        _public_statement: &[u8],
    ) -> Result<ZkpProof> {
        Err(lib_q_core::Error::NotImplemented {
            feature: "ZKP feature not enabled".to_string(),
        })
    }
}

/// Crate-private helper for NIST secret value verification. Used by both
/// `ZkpVerifier::verify` and `ZkpVerifier::verify_secret_value_nist`.
#[cfg(feature = "zkp")]
fn verify_secret_value_nist_impl(proof: &ZkpProof, expected_hash: &[u8]) -> Result<bool> {
    use crate::air::{
        HashPreimageNistAir,
        expected_hash_to_public_values,
    };
    use crate::stark::{
        StarkVerifier,
        default_config,
    };

    if proof.proof_type != ProofType::Stark {
        return Ok(false);
    }
    if proof.data.is_empty() {
        return Ok(false);
    }

    let ProofMetadata::HashPreimageNist { .. } = &proof.metadata else {
        return Ok(false);
    };

    let air = HashPreimageNistAir::new();
    let public_values = expected_hash_to_public_values::<ZkpField>(expected_hash);

    let stark_proof = match proof.to_stark_proof() {
        Ok(p) => p,
        Err(_) => return Ok(false),
    };

    let config = default_config();
    let verifier = StarkVerifier::new(config);

    match verifier.verify(&air, &stark_proof, &public_values) {
        Ok(()) => Ok(true),
        Err(_) => Ok(false),
    }
}

#[cfg(feature = "zkp")]
impl ZkpVerifier {
    /// Create a new ZKP verifier
    pub fn new() -> Self {
        Self {}
    }

    /// Verify a zero-knowledge proof of secret value knowledge
    ///
    /// This verifies a proof generated by `ZkpProver::prove_secret_value`. The
    /// expected hash is the **Poseidon** commitment (same encoding as used in proving).
    /// For NIST proofs use [`verify_secret_value_nist`](ZkpVerifier::verify_secret_value_nist).
    ///
    /// # Arguments
    ///
    /// * `proof` - The proof to verify
    /// * `public_hash` - The expected Poseidon hash output (bytes encoding used by the prover)
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the proof is valid, `Ok(false)` or `Err` otherwise
    pub fn verify_secret_value(&self, proof: &ZkpProof, public_hash: &[u8]) -> Result<bool> {
        use lib_q_poseidon::{
            Poseidon,
            Poseidon128,
        };

        use crate::air::{
            HashPreimageAir,
            bytes_to_poseidon_field,
            poseidon_slice_to_field,
        };
        use crate::stark::{
            StarkVerifier,
            default_config,
        };

        if proof.proof_type != ProofType::Stark {
            return Ok(false);
        }

        if proof.data.is_empty() {
            return Ok(false);
        }

        // Proof must contain output size metadata
        let ProofMetadata::HashPreimage { output_size } = &proof.metadata else {
            // Missing metadata - proof is invalid
            return Ok(false);
        };

        // Create the same AIR used for proving (output_size in metadata retained for compatibility)
        let _ = output_size;
        let air = HashPreimageAir::new();

        // Convert expected hash bytes to Poseidon field elements, then hash to get public values
        // The public values are the Poseidon hash output (field elements), matching what
        // HashPreimageAir::public_values() returns during proving
        let expected_field_elements = bytes_to_poseidon_field(public_hash);
        let poseidon_hash = Poseidon128.hash(&expected_field_elements);

        // Convert Poseidon hash output to public values (field elements)
        let public_values = poseidon_slice_to_field(&poseidon_hash);

        // Deserialize the STARK proof
        let stark_proof = proof.to_stark_proof()?;

        // Create verifier with default config
        let config = default_config();
        let verifier = StarkVerifier::new(config);

        // Verify the proof
        match verifier.verify(&air, &stark_proof, &public_values) {
            Ok(()) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Verify a NIST (cSHAKE256) secret value proof
    ///
    /// Verifies a proof from [`prove_secret_value_nist`](ZkpProver::prove_secret_value_nist).
    /// `expected_hash` is the raw 32-byte cSHAKE256 output (same as used in proving).
    pub fn verify_secret_value_nist(&self, proof: &ZkpProof, expected_hash: &[u8]) -> Result<bool> {
        verify_secret_value_nist_impl(proof, expected_hash)
    }

    /// Verify a zero-knowledge proof of computation
    ///
    /// This verifies a proof generated by `ZkpProver::prove_computation`.
    ///
    /// # Arguments
    ///
    /// * `proof` - The proof to verify
    /// * `circuit` - The arithmetic circuit that was proven
    /// * `public` - The public input values
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the proof is valid, `Ok(false)` or `Err` otherwise
    pub fn verify_computation(
        &self,
        proof: &ZkpProof,
        circuit: &circuit::ArithmeticCircuit<ZkpField>,
        public: &[ZkpField],
    ) -> Result<bool> {
        use crate::circuit::CircuitAir;
        use crate::stark::{
            StarkVerifier,
            default_config,
        };

        if proof.proof_type != ProofType::Stark {
            return Ok(false);
        }

        if proof.data.is_empty() {
            return Ok(false);
        }

        // Create the same AIR used for proving
        let air = CircuitAir::new(circuit.clone());

        // Deserialize the STARK proof
        let stark_proof = proof.to_stark_proof()?;

        // Create verifier with default config
        let config = default_config();
        let verifier = StarkVerifier::new(config);

        // Verify the proof
        match verifier.verify(&air, &stark_proof, public) {
            Ok(()) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Verify a zero-knowledge proof.
    ///
    /// Performs full cryptographic (STARK) verification for proof types whose public
    /// inputs are fully described by a byte slice:
    ///
    /// - `ProofMetadata::HashPreimage`: `public_statement` is the expected hash output
    ///   (same semantics as `verify_secret_value`).
    /// - `ProofMetadata::HashPreimageNist`: `public_statement` is the expected cSHAKE256
    ///   hash output (same semantics as `verify_secret_value_nist`).
    /// - `ProofMetadata::MerkleInclusion`: `public_statement` is the expected Merkle
    ///   root hash (same semantics as `api::verify_membership`).
    ///
    /// Returns `Ok(false)` for `Circuit`, `Credential`, `Identity`, and `None`
    /// metadata variants. Those proof types require a type-specific verifier that accepts
    /// the additional inputs needed to reconstruct verification state.
    ///
    /// `batch_verify` delegates to this method, so the same rules apply in bulk.
    pub fn verify(&self, proof: ZkpProof, public_statement: &[u8]) -> Result<bool> {
        if proof.proof_type != ProofType::Stark {
            return Ok(false);
        }
        if proof.data.is_empty() {
            return Ok(false);
        }
        match &proof.metadata {
            ProofMetadata::HashPreimage { .. } => {
                self.verify_secret_value(&proof, public_statement)
            }
            ProofMetadata::HashPreimageNist { .. } => {
                verify_secret_value_nist_impl(&proof, public_statement)
            }
            ProofMetadata::MerkleInclusion { .. } => verify_membership(&proof, public_statement),
            _ => Ok(false),
        }
    }

    /// Batch verify multiple proofs
    ///
    /// # Arguments
    ///
    /// * `proofs` - The proofs to verify
    /// * `publics` - The public statements for each proof
    ///
    /// # Returns
    ///
    /// `true` if all proofs are valid, `false` otherwise
    pub fn batch_verify(&self, proofs: &[ZkpProof], publics: &[&[u8]]) -> Result<bool> {
        if proofs.len() != publics.len() {
            return Err(lib_q_core::Error::InvalidState {
                operation: "batch_verify".to_string(),
                reason: "Number of proofs must match number of public statements".to_string(),
            });
        }

        for (proof, public) in proofs.iter().zip(publics.iter()) {
            match self.verify(proof.clone(), public) {
                Ok(true) => continue,
                Ok(false) => return Ok(false),
                Err(e) => return Err(e),
            }
        }

        Ok(true)
    }
}

#[cfg(not(feature = "zkp"))]
impl ZkpVerifier {
    /// Create a new ZKP verifier
    pub fn new() -> Self {
        Self {}
    }

    /// Verify a zero-knowledge proof
    pub fn verify(&self, _proof: ZkpProof, _public_statement: &[u8]) -> Result<bool> {
        Err(lib_q_core::Error::NotImplemented {
            feature: "ZKP feature not enabled".to_string(),
        })
    }

    /// Verify a NIST secret value proof
    pub fn verify_secret_value_nist(
        &self,
        _proof: &ZkpProof,
        _expected_hash: &[u8],
    ) -> Result<bool> {
        Err(lib_q_core::Error::NotImplemented {
            feature: "ZKP feature not enabled".to_string(),
        })
    }

    /// Batch verify multiple proofs
    pub fn batch_verify(&self, _proofs: &[ZkpProof], _publics: &[&[u8]]) -> Result<bool> {
        Err(lib_q_core::Error::NotImplemented {
            feature: "ZKP feature not enabled".to_string(),
        })
    }
}

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

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

/// Get available ZKP algorithms (STARK when zkp feature is enabled).
pub fn available_algorithms() -> Vec<&'static str> {
    let algorithms = vec![
        #[cfg(feature = "zkp")]
        "stark",
    ];

    algorithms
}

/// Create a ZKP instance by algorithm name
pub fn create_zkp(algorithm: &str) -> Result<Box<dyn core::any::Any>> {
    match algorithm {
        #[cfg(feature = "zkp")]
        "stark" => Ok(Box::new(ZkpProver::new())),

        _ => Err(lib_q_core::Error::InvalidAlgorithm {
            algorithm: "Unknown ZKP algorithm",
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zkp_prover_creation() {
        let _prover = ZkpProver::new();
        // Just check that creation doesn't panic
    }

    #[test]
    fn test_zkp_verifier_creation() {
        let _verifier = ZkpVerifier::new();
        // Just check that creation doesn't panic
    }

    #[test]
    fn test_zkp_proof_creation() {
        let mut prover = ZkpProver::new();
        let secret_value = b"secret_value";
        let public_statement = b"public_statement";

        // Now that prove_secret_value is implemented, it should succeed
        let result = prover.prove_secret_value(secret_value, public_statement);
        // The proof generation should succeed (though it may take some time)
        assert!(
            result.is_ok(),
            "Proof generation should succeed: {:?}",
            result.err()
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_nist_secret_value_round_trip() {
        use digest::{
            ExtendableOutput,
            Update,
        };
        use lib_q_sha3::CShake256;

        use crate::air::hash_preimage_nist::CSHAKE_DOMAIN;

        let secret = b"nist_secret_value";
        let mut prover = ZkpProver::new();
        let proof = prover
            .prove_secret_value_nist(secret, b"")
            .expect("prove_secret_value_nist");
        let mut expected_hash = [0u8; 32];
        {
            let mut hasher = CShake256::new_with_function_name(&[], CSHAKE_DOMAIN);
            hasher.update(secret);
            hasher.finalize_xof_into(&mut expected_hash);
        }
        let verifier = ZkpVerifier::new();
        assert!(
            verifier
                .verify_secret_value_nist(&proof, &expected_hash)
                .unwrap(),
            "NIST proof should verify with correct expected hash"
        );
        // Generic verify() must dispatch to verify_secret_value_nist for HashPreimageNist
        assert!(
            verifier.verify(proof.clone(), &expected_hash).unwrap(),
            "verify() must accept NIST proof with correct expected hash"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_nist_proof_rejected_by_poseidon_verifier() {
        use digest::{
            ExtendableOutput,
            Update,
        };
        use lib_q_sha3::CShake256;

        use crate::air::hash_preimage_nist::CSHAKE_DOMAIN;

        let secret = b"nist_only";
        let mut prover = ZkpProver::new();
        let proof = prover
            .prove_secret_value_nist(secret, b"")
            .expect("NIST prove");
        let mut expected_hash = [0u8; 32];
        let mut hasher = CShake256::new_with_function_name(&[], CSHAKE_DOMAIN);
        hasher.update(secret);
        hasher.finalize_xof_into(&mut expected_hash);
        let verifier = ZkpVerifier::new();
        assert!(
            !verifier
                .verify_secret_value(&proof, &expected_hash)
                .unwrap(),
            "NIST proof must not be accepted by Poseidon verifier"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_poseidon_proof_rejected_by_nist_verifier() {
        let secret = b"poseidon_only";
        let mut prover = ZkpProver::new();
        let proof = prover
            .prove_secret_value(secret, b"")
            .expect("Poseidon prove");
        let verifier = ZkpVerifier::new();
        assert!(
            !verifier
                .verify_secret_value_nist(&proof, &[0u8; 32])
                .unwrap(),
            "Poseidon proof must not be accepted by NIST verifier"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_unknown_metadata() {
        use lib_q_stark_field::PrimeCharacteristicRing;
        use lib_q_stark_mersenne31::Mersenne31;

        use crate::air::{
            ArithmeticAir,
            TraceGenerator,
        };
        use crate::stark::{
            StarkProver,
            default_config,
        };

        let air = ArithmeticAir::new(1).expect("ArithmeticAir");
        let one = <ZkpField as PrimeCharacteristicRing>::ONE;
        let seven = ZkpField::from(Mersenne31::new(7));
        let input = alloc::vec![(one, seven)];
        let trace = air.generate_trace(&input).expect("trace generation");
        let public_values = air.public_values(&input);
        let proof_inner = StarkProver::new(default_config())
            .prove(&air, trace, &public_values)
            .expect("prove");
        let proof_bytes = postcard::to_allocvec(&proof_inner).expect("serialize STARK proof");

        let proof = ZkpProof {
            data: proof_bytes,
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::None,
        };

        let verifier = ZkpVerifier::new();
        assert_eq!(
            verifier.verify(proof, b"public_statement").unwrap(),
            false,
            "ProofMetadata::None must return false -- use a type-specific verifier"
        );
    }

    #[test]
    fn test_batch_verify_mismatched_lengths() {
        let verifier = ZkpVerifier::new();
        let proofs = vec![ZkpProof {
            data: vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::None,
        }];
        let publics: &[&[u8]] = &[b"public1" as &[u8], b"public2" as &[u8]];

        let result = verifier.batch_verify(&proofs, publics);
        assert!(result.is_err());
        if let Err(lib_q_core::Error::InvalidState { .. }) = result {
            // Expected
        } else {
            panic!("Expected InvalidState error");
        }
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_proof_metadata_merkle() {
        let metadata = ProofMetadata::MerkleInclusion { tree_depth: 8 };
        let proof = ZkpProof {
            data: vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata,
        };
        assert_eq!(proof.merkle_tree_depth(), Some(8));
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_proof_metadata_none() {
        let proof = ZkpProof {
            data: vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::None,
        };
        assert_eq!(proof.merkle_tree_depth(), None);
    }

    #[test]
    fn test_available_algorithms() {
        let algorithms = available_algorithms();
        #[cfg(feature = "zkp")]
        assert!(!algorithms.is_empty(), "zkp feature enables STARK");
        #[cfg(not(feature = "zkp"))]
        let _ = algorithms;
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_create_zkp() {
        let algorithms = available_algorithms();
        assert!(!algorithms.is_empty());
        let algorithm = algorithms[0];
        assert!(create_zkp(algorithm).is_ok());
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_forged_proof_with_hash_preimage_metadata() {
        let proof = ZkpProof {
            data: alloc::vec![
                0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD,
                0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF,
                0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA,
                0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD,
                0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF, 0xAA, 0xDE, 0xAD, 0xBE, 0xEF,
            ],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimage { output_size: 1 },
        };
        let verifier = ZkpVerifier::new();
        let result = verifier.verify(proof, b"expected_hash");
        assert!(
            matches!(result, Ok(false) | Err(_)),
            "forged HashPreimage proof must not return Ok(true)"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_forged_proof_with_merkle_metadata() {
        let proof = ZkpProof {
            data: alloc::vec![
                0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE,
                0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE,
                0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE,
                0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE,
                0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE, 0xCA, 0xFE, 0xBA, 0xBE,
            ],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::MerkleInclusion { tree_depth: 4 },
        };
        let verifier = ZkpVerifier::new();
        let result = verifier.verify(proof, b"wrong_root");
        assert!(
            matches!(result, Ok(false) | Err(_)),
            "forged MerkleInclusion proof must not return Ok(true)"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_circuit_metadata_proof() {
        let proof = ZkpProof {
            data: alloc::vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::Circuit {
                num_witnesses: 2,
                num_public: 1,
            },
        };
        let verifier = ZkpVerifier::new();
        assert_eq!(
            verifier.verify(proof, b"anything").unwrap(),
            false,
            "Circuit proofs must be rejected by generic verify; use verify_computation"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_credential_metadata_proof() {
        let proof = ZkpProof {
            data: alloc::vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::Credential {
                attribute_sizes: alloc::vec![8, 4],
                reveal_mask: alloc::vec![true, false],
            },
        };
        let verifier = ZkpVerifier::new();
        assert_eq!(
            verifier.verify(proof, b"anything").unwrap(),
            false,
            "Credential proofs must be rejected by generic verify; use ip::verify_credential_proof"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_rejects_identity_metadata_proof() {
        let proof = ZkpProof {
            data: alloc::vec![0u8; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::Identity { dsa_level: 65 },
        };
        let verifier = ZkpVerifier::new();
        assert_eq!(
            verifier.verify(proof, b"anything").unwrap(),
            false,
            "Identity proofs must be rejected by generic verify; use ip::verify_it_ownership"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_empty_data_is_rejected() {
        let proof = ZkpProof {
            data: alloc::vec![],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimage { output_size: 1 },
        };
        let verifier = ZkpVerifier::new();
        assert_eq!(
            verifier.verify(proof, b"anything").unwrap(),
            false,
            "empty proof data must be rejected regardless of metadata"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_proof_type_only_stark_exists() {
        let _stark = ProofType::Stark;
        // ProofType::Snark and ProofType::Bulletproof have been removed.
        // Only NIST-approved post-quantum proof systems are supported.
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_batch_verify_rejects_forged_hash_preimage_proof() {
        let forged = ZkpProof {
            data: alloc::vec![0xFF; 64],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimage { output_size: 1 },
        };
        let verifier = ZkpVerifier::new();
        let proofs = alloc::vec![forged];
        let publics: &[&[u8]] = &[b"anything"];
        let result = verifier.batch_verify(&proofs, publics);
        assert!(
            matches!(result, Ok(false) | Err(_)),
            "batch_verify must not accept a forged proof"
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_prove_secret_value_rejects_empty_and_oversized_input() {
        let mut prover = ZkpProver::new();
        let empty = prover.prove_secret_value(b"", b"");
        assert!(empty.is_err());

        let oversized = vec![0u8; air::hash_preimage::MAX_PREIMAGE_SIZE + 1];
        let too_large = prover.prove_secret_value(&oversized, b"");
        assert!(too_large.is_err());
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_prove_secret_value_nist_rejects_empty_and_oversized_input() {
        let mut prover = ZkpProver::new();
        let empty = prover.prove_secret_value_nist(b"", b"");
        assert!(empty.is_err());

        let oversized = vec![0u8; air::hash_preimage_nist::MAX_PREIMAGE_SIZE + 1];
        let too_large = prover.prove_secret_value_nist(&oversized, b"");
        assert!(too_large.is_err());
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_secret_value_rejects_invalid_proof_shape_inputs() {
        let verifier = ZkpVerifier::new();
        let non_stark = ZkpProof {
            data: vec![1u8; 16],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimageNist { output_size: 32 },
        };
        assert!(!verifier.verify_secret_value(&non_stark, b"hash").unwrap());

        let empty = ZkpProof {
            data: vec![],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimage { output_size: 1 },
        };
        assert!(!verifier.verify_secret_value(&empty, b"hash").unwrap());
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_secret_value_nist_rejects_wrong_metadata_and_bad_bytes() {
        let verifier = ZkpVerifier::new();
        let wrong_meta = ZkpProof {
            data: vec![1u8; 16],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimage { output_size: 1 },
        };
        assert!(
            !verifier
                .verify_secret_value_nist(&wrong_meta, &[0u8; 32])
                .unwrap()
        );

        let malformed_stark = ZkpProof {
            data: vec![0xAA; 16],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::HashPreimageNist { output_size: 32 },
        };
        assert!(
            !verifier
                .verify_secret_value_nist(&malformed_stark, &[0u8; 32])
                .unwrap()
        );
    }

    #[cfg(feature = "zkp")]
    #[test]
    fn test_verify_computation_rejects_empty_or_non_stark_data() {
        use crate::circuit::CircuitBuilder;

        let verifier = ZkpVerifier::new();
        let circuit = CircuitBuilder::<ZkpField>::new(1, 0).build();

        let empty = ZkpProof {
            data: vec![],
            proof_type: ProofType::Stark,
            security_level: 1,
            metadata: ProofMetadata::Circuit {
                num_witnesses: 1,
                num_public: 0,
            },
        };
        assert!(!verifier.verify_computation(&empty, &circuit, &[]).unwrap());
    }
}