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
//! zk-STARK implementation
//!
//! This module provides a high-level interface to lib-Q's zk-STARK implementation.
//!
//! The STARK implementation is based on Plonky3, adapted for lib-Q's requirements:
//! - Uses SHAKE256 (NIST-approved post-quantum hash) instead of non-NIST hashes
//! - Supports `Complex<Mersenne31>` field for efficient arithmetic (TWO_ADICITY = 32)
//! - Implements the ethSTARK protocol for strong security guarantees

extern crate alloc;
use alloc::vec::Vec;
use core::result::Result;

use lib_q_stark::{
    Domain,
    Proof as StarkProof,
    StarkConfig,
    StarkGenericConfig,
    SymbolicAirBuilder,
    Val,
    VerificationError,
    get_log_num_quotient_chunks,
    prove,
    verify,
};
use lib_q_stark_air::Air;
use lib_q_stark_challenger::{
    CanObserve,
    CanSampleBits,
    ComplexFieldChallenger,
    FieldChallenger,
    GrindingChallenger,
    Shake256Challenger32,
};
use lib_q_stark_commit::{
    ExtensionMmcs,
    Pcs,
    PolynomialSpace,
};
use lib_q_stark_field::extension::Complex;
use lib_q_stark_field::{
    BasedVectorSpace,
    PrimeCharacteristicRing,
};
use lib_q_stark_fri::{
    FriDataExtractor,
    TwoAdicFriPcs,
};
use lib_q_stark_matrix::dense::RowMajorMatrix;
use lib_q_stark_merkle::MerkleTreeMmcs;
use lib_q_stark_mersenne31::{
    Mersenne31,
    Mersenne31ComplexRadix2Dit,
};
use lib_q_stark_shake256::Shake256Hash;
use lib_q_stark_symmetric::{
    CompressionFunctionFromHasher,
    SerializingHasher,
};

// Concrete config type aliases (used as return types for config factory functions).
// Public so that pub type DefaultConfig/ZkConfig/PoseidonConfig satisfy private_interfaces.
pub type ConfigVal = Complex<Mersenne31>;
pub type ConfigDft = Mersenne31ComplexRadix2Dit;
pub type DefaultValMmcs = MerkleTreeMmcs<
    <ConfigVal as lib_q_stark_field::Field>::Packing,
    u8,
    SerializingHasher<Shake256Hash>,
    CompressionFunctionFromHasher<Shake256Hash, 2, 32>,
    32,
>;
pub type DefaultChallengeMmcs = ExtensionMmcs<ConfigVal, ConfigVal, DefaultValMmcs>;
pub type DefaultPcs = TwoAdicFriPcs<ConfigVal, ConfigDft, DefaultValMmcs, DefaultChallengeMmcs>;
pub type DefaultConfig =
    StarkConfig<DefaultPcs, ConfigVal, ComplexFieldChallenger<Shake256Challenger32<Mersenne31>>>;

#[cfg(feature = "recursive-proofs-experimental")]
use lib_q_stark_merkle::PoseidonMmcs as PoseidonMmcsType;
#[cfg(feature = "recursive-proofs-experimental")]
pub type PoseidonChallengeMmcs = ExtensionMmcs<ConfigVal, ConfigVal, PoseidonMmcsType>;
#[cfg(feature = "recursive-proofs-experimental")]
pub type PoseidonPcs = TwoAdicFriPcs<ConfigVal, ConfigDft, PoseidonMmcsType, PoseidonChallengeMmcs>;
#[cfg(feature = "recursive-proofs-experimental")]
pub type PoseidonConfig =
    StarkConfig<PoseidonPcs, ConfigVal, ComplexFieldChallenger<Shake256Challenger32<Mersenne31>>>;

use lib_q_stark_fri::HidingFriPcs;
use lib_q_stark_merkle::MerkleTreeHidingMmcs;
pub type ZkValMmcs = MerkleTreeHidingMmcs<
    <ConfigVal as lib_q_stark_field::Field>::Packing,
    u8,
    SerializingHasher<Shake256Hash>,
    CompressionFunctionFromHasher<Shake256Hash, 2, 32>,
    lib_q_random::DeterministicRng,
    32,
    4,
>;
pub type ZkChallengeMmcs = ExtensionMmcs<ConfigVal, ConfigVal, ZkValMmcs>;
pub type ZkPcs =
    HidingFriPcs<ConfigVal, ConfigDft, ZkValMmcs, ZkChallengeMmcs, lib_q_random::DeterministicRng>;
pub type ZkConfig =
    StarkConfig<ZkPcs, ConfigVal, ComplexFieldChallenger<Shake256Challenger32<Mersenne31>>>;

/// FRI query parameters used when replaying the verifier (e.g. for recursive aggregation).
#[derive(Clone, Debug)]
pub struct FriQueryParams {
    pub num_queries: usize,
    pub log_blowup: usize,
    pub log_final_poly_len: usize,
    pub proof_of_work_bits: usize,
}

// Generic type aliases for StarkVerifier (`C: StarkGenericConfig` on the alias is stable Rust).
type PcsCommitment<C: StarkGenericConfig> =
    <C::Pcs as Pcs<C::Challenge, C::Challenger>>::Commitment;

type CommitmentRounds<C: StarkGenericConfig> = Vec<(
    PcsCommitment<C>,
    Vec<(Domain<C>, Vec<(C::Challenge, Vec<C::Challenge>)>)>,
)>;

type QuotientRounds<C: StarkGenericConfig> =
    Vec<(Domain<C>, Vec<(C::Challenge, Vec<C::Challenge>)>)>;

/// zk-STARK prover
///
/// This is a high-level wrapper around the STARK proving functionality.
/// It provides a convenient interface for generating STARK proofs with a given configuration.
///
/// # Example
///
/// ```rust,ignore
/// use lib_q_zkp::stark::{StarkProver, default_config};
/// use Complex;
/// use Mersenne31;
///
/// type Val = Complex<Mersenne31>;
///
/// let config = default_config();
/// let prover = StarkProver::new(config);
/// // air: implements Air trait
/// // trace: RowMajorMatrix<Val>
/// // public_values: &[Val]
/// let proof = prover.prove(&air, trace, &public_values);
/// ```
pub struct StarkProver<C: StarkGenericConfig> {
    config: C,
}

impl<C: StarkGenericConfig> StarkProver<C> {
    /// Create a new zk-STARK prover with the given configuration
    pub fn new(config: C) -> Self {
        Self { config }
    }

    /// Generate a STARK proof for the given AIR, trace, and public values
    ///
    /// # Arguments
    ///
    /// * `air` - The Algebraic Intermediate Representation defining the constraints
    /// * `trace` - The witness trace matrix (contains secret data)
    /// * `public_values` - Public values known to both prover and verifier
    ///
    /// # Returns
    ///
    /// A STARK proof that can be verified without revealing the witness trace
    #[cfg(not(debug_assertions))]
    pub fn prove<A>(
        &self,
        air: &A,
        trace: RowMajorMatrix<Val<C>>,
        public_values: &[Val<C>],
    ) -> Result<StarkProof<C>, lib_q_stark::ProverError>
    where
        A: Air<SymbolicAirBuilder<Val<C>>>
            + for<'a> Air<lib_q_stark::ProverConstraintFolder<'a, C>>,
    {
        prove(&self.config, air, trace, public_values)
    }

    #[cfg(debug_assertions)]
    pub fn prove<A>(
        &self,
        air: &A,
        trace: RowMajorMatrix<Val<C>>,
        public_values: &[Val<C>],
    ) -> Result<StarkProof<C>, lib_q_stark::ProverError>
    where
        A: Air<SymbolicAirBuilder<Val<C>>>
            + for<'a> Air<lib_q_stark::ProverConstraintFolder<'a, C>>
            + for<'a> Air<lib_q_stark::DebugConstraintBuilder<'a, Val<C>>>,
    {
        prove(&self.config, air, trace, public_values)
    }

    /// Get a reference to the underlying configuration
    pub fn config(&self) -> &C {
        &self.config
    }
}

/// zk-STARK verifier
///
/// This is a high-level wrapper around the STARK verification functionality.
/// It provides a convenient interface for verifying STARK proofs with a given configuration.
///
/// # Example
///
/// ```rust,ignore
/// use lib_q_zkp::stark::{StarkVerifier, default_config};
/// use Complex;
/// use Mersenne31;
///
/// type Val = Complex<Mersenne31>;
///
/// let config = default_config();
/// let verifier = StarkVerifier::new(config);
/// // air: implements Air trait (same as used in proof generation)
/// // proof: StarkProof<Config>
/// // public_values: &[Val]
/// verifier.verify(&air, &proof, &public_values)?;
/// ```
pub struct StarkVerifier<C: StarkGenericConfig> {
    config: C,
}

impl<C: StarkGenericConfig> StarkVerifier<C> {
    /// Create a new zk-STARK verifier with the given configuration
    pub fn new(config: C) -> Self {
        Self { config }
    }

    /// Verify a STARK proof for the given AIR and public values
    ///
    /// # Arguments
    ///
    /// * `air` - The Algebraic Intermediate Representation that was used to generate the proof
    /// * `proof` - The STARK proof to verify
    /// * `public_values` - Public values that were used during proof generation
    ///
    /// # Returns
    ///
    /// `Ok(())` if the proof is valid, `Err(VerificationError)` otherwise
    pub fn verify<A>(
        &self,
        air: &A,
        proof: &StarkProof<C>,
        public_values: &[Val<C>],
    ) -> Result<(), VerificationError<lib_q_stark::PcsError<C>>>
    where
        A: Air<SymbolicAirBuilder<Val<C>>>
            + for<'a> Air<lib_q_stark::VerifierConstraintFolder<'a, C>>,
    {
        verify(&self.config, air, proof, public_values)
    }

    /// Derive Fiat–Shamir challenges by replaying the verifier transcript.
    ///
    /// Returns `(zeta, zeta_next, alpha, betas)` so that callers (e.g. aggregation)
    /// can serialize proofs with real challenges. Only supports proofs without
    /// preprocessed trace (`preprocessed_width == 0`).
    #[allow(clippy::type_complexity)]
    pub fn derive_challenges<A>(
        &self,
        air: &A,
        proof: &StarkProof<C>,
        public_values: &[Val<C>],
    ) -> Result<
        (
            C::Challenge,
            C::Challenge,
            C::Challenge,
            Vec<C::Challenge>,
        ),
        VerificationError<lib_q_stark::PcsError<C>>,
    >
    where
        A: Air<SymbolicAirBuilder<Val<C>>>
            + for<'a> Air<lib_q_stark::VerifierConstraintFolder<'a, C>>,
        <<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof:
            FriDataExtractor<Challenge = C::Challenge>,
        C::Challenger: CanObserve<Val<C>>
            + CanObserve<<C::Pcs as Pcs<C::Challenge, C::Challenger>>::Commitment>
            + CanObserve<
                <<<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof as FriDataExtractor>::Commitment,
            >,
    {
        let config = &self.config;
        let pcs = config.pcs();
        let commitments = &proof.commitments;
        let opened_values = &proof.opened_values;
        let opening_proof = &proof.opening_proof;
        let degree_bits = proof.degree_bits;

        let preprocessed_width = air
            .preprocessed_trace()
            .as_ref()
            .map(|m| m.width)
            .unwrap_or(0);
        if preprocessed_width > 0 {
            return Err(VerificationError::InvalidProofShape);
        }

        let degree = 1 << degree_bits;
        if degree == 0 {
            return Err(VerificationError::InvalidProofShape);
        }

        let trace_domain: Domain<C> = pcs.natural_domain_for_degree(degree);
        let init_trace_domain = pcs.natural_domain_for_degree(degree >> config.is_zk());

        let log_num_quotient_chunks = get_log_num_quotient_chunks::<Val<C>, A>(
            air,
            preprocessed_width,
            public_values.len(),
            config.is_zk(),
        );
        let num_quotient_chunks = 1 << (log_num_quotient_chunks + config.is_zk());

        if (opened_values.random.is_some() != C::Pcs::ZK) ||
            (commitments.random.is_some() != C::Pcs::ZK)
        {
            return Err(VerificationError::RandomizationError);
        }

        let air_width = A::width(air);
        let valid_shape = opened_values.trace_local.len() == air_width &&
            opened_values.trace_next.len() == air_width &&
            opened_values.quotient_chunks.len() == num_quotient_chunks &&
            opened_values
                .quotient_chunks
                .iter()
                .all(|qc| qc.len() == C::Challenge::DIMENSION) &&
            opened_values
                .random
                .as_ref()
                .is_none_or(|r| r.len() == C::Challenge::DIMENSION);
        if !valid_shape {
            return Err(VerificationError::InvalidProofShape);
        }

        let quotient_domain =
            trace_domain.create_disjoint_domain(1 << (degree_bits + log_num_quotient_chunks));
        let quotient_chunks_domains = quotient_domain.split_domains(num_quotient_chunks);
        let randomized_quotient_chunks_domains: Vec<Domain<C>> = quotient_chunks_domains
            .iter()
            .map(|d: &Domain<C>| pcs.natural_domain_for_degree(d.size() << config.is_zk()))
            .collect();

        let mut challenger = config.initialise_challenger();

        challenger.observe(Val::<C>::from_usize(degree_bits));
        challenger.observe(Val::<C>::from_usize(degree_bits - config.is_zk()));
        challenger.observe(Val::<C>::from_usize(preprocessed_width));
        challenger.observe(Val::<C>::from_usize(A::width(air)));
        challenger.observe(commitments.trace.clone());
        challenger.observe_slice(public_values);

        let alpha = challenger.sample_algebra_element();
        challenger.observe(commitments.quotient_chunks.clone());
        if let Some(ref r_commit) = commitments.random {
            challenger.observe(r_commit.clone());
        }

        let zeta = challenger.sample_algebra_element();
        let zeta_next = init_trace_domain
            .next_point(zeta)
            .ok_or(VerificationError::NextPointUnavailable)?;

        let mut coms_to_verify: CommitmentRounds<C> =
            if let Some(ref random_commit) = commitments.random {
                let random_values = opened_values
                    .random
                    .as_ref()
                    .ok_or(VerificationError::RandomizationError)?;
                alloc::vec![(
                    random_commit.clone(),
                    alloc::vec![(trace_domain, alloc::vec![(zeta, random_values.clone())],)],
                )]
            } else {
                alloc::vec![]
            };

        coms_to_verify.push((
            commitments.trace.clone(),
            alloc::vec![(
                trace_domain,
                alloc::vec![
                    (zeta, opened_values.trace_local.clone()),
                    (zeta_next, opened_values.trace_next.clone()),
                ],
            )],
        ));

        let quotient_rounds: QuotientRounds<C> = randomized_quotient_chunks_domains
            .iter()
            .zip(opened_values.quotient_chunks.iter())
            .map(|(domain, values)| (*domain, alloc::vec![(zeta, values.clone())]))
            .collect();
        coms_to_verify.push((commitments.quotient_chunks.clone(), quotient_rounds));

        for (_, round) in &coms_to_verify {
            for (_, mat) in round {
                for (_, point) in mat {
                    for opening in point {
                        challenger.observe_algebra_element(*opening);
                    }
                }
            }
        }

        let _alpha_fri = challenger.sample_algebra_element::<C::Challenge>();

        let betas: Vec<C::Challenge> = opening_proof
            .commit_phase_commits()
            .iter()
            .map(|comm| {
                challenger.observe(comm.clone());
                challenger.sample_algebra_element()
            })
            .collect();

        Ok((zeta, zeta_next, alpha, betas))
    }

    /// Derive FRI query positions by replaying the Fiat–Shamir challenger through commitments,
    /// FRI betas, final polynomial, and PoW, then sampling `num_queries` indices.
    ///
    /// Returns the same query indices the verifier would use when verifying the proof.
    /// Call with the same FRI params used to produce the proof (e.g. from config).
    pub fn derive_query_positions<A>(
        &self,
        air: &A,
        proof: &StarkProof<C>,
        public_values: &[Val<C>],
        fri_params: &FriQueryParams,
    ) -> Result<Vec<usize>, VerificationError<lib_q_stark::PcsError<C>>>
    where
        A: Air<SymbolicAirBuilder<Val<C>>>
            + for<'a> Air<lib_q_stark::VerifierConstraintFolder<'a, C>>,
        <<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof:
            FriDataExtractor<Challenge = C::Challenge>,
        C::Challenger: CanObserve<Val<C>>
            + CanObserve<<C::Pcs as Pcs<C::Challenge, C::Challenger>>::Commitment>
            + CanObserve<
                <<<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof as FriDataExtractor>::Commitment,
            >
            + GrindingChallenger<
                Witness = <<<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof as FriDataExtractor>::Witness,
            >,
        <<<C as StarkGenericConfig>::Pcs as Pcs<C::Challenge, C::Challenger>>::Proof as FriDataExtractor>::Witness: Clone,
    {
        let config = &self.config;
        let pcs = config.pcs();
        let commitments = &proof.commitments;
        let opened_values = &proof.opened_values;
        let opening_proof = &proof.opening_proof;
        let degree_bits = proof.degree_bits;

        let preprocessed_width = air
            .preprocessed_trace()
            .as_ref()
            .map(|m| m.width)
            .unwrap_or(0);
        if preprocessed_width > 0 {
            return Err(VerificationError::InvalidProofShape);
        }

        let degree = 1 << degree_bits;
        if degree == 0 {
            return Err(VerificationError::InvalidProofShape);
        }

        let log_num_quotient_chunks = get_log_num_quotient_chunks::<Val<C>, A>(
            air,
            preprocessed_width,
            public_values.len(),
            config.is_zk(),
        );
        let num_quotient_chunks = 1 << (log_num_quotient_chunks + config.is_zk());

        if (opened_values.random.is_some() != C::Pcs::ZK) ||
            (commitments.random.is_some() != C::Pcs::ZK)
        {
            return Err(VerificationError::RandomizationError);
        }

        let air_width = A::width(air);
        let valid_shape = opened_values.trace_local.len() == air_width &&
            opened_values.trace_next.len() == air_width &&
            opened_values.quotient_chunks.len() == num_quotient_chunks &&
            opened_values
                .quotient_chunks
                .iter()
                .all(|qc| qc.len() == C::Challenge::DIMENSION) &&
            opened_values
                .random
                .as_ref()
                .is_none_or(|r| r.len() == C::Challenge::DIMENSION);
        if !valid_shape {
            return Err(VerificationError::InvalidProofShape);
        }

        let trace_domain: Domain<C> = pcs.natural_domain_for_degree(degree);
        let init_trace_domain = pcs.natural_domain_for_degree(degree >> config.is_zk());
        let quotient_domain =
            trace_domain.create_disjoint_domain(1 << (degree_bits + log_num_quotient_chunks));
        let quotient_chunks_domains = quotient_domain.split_domains(num_quotient_chunks);
        let randomized_quotient_chunks_domains: Vec<Domain<C>> = quotient_chunks_domains
            .iter()
            .map(|d: &Domain<C>| pcs.natural_domain_for_degree(d.size() << config.is_zk()))
            .collect();

        let mut challenger = config.initialise_challenger();

        challenger.observe(Val::<C>::from_usize(degree_bits));
        challenger.observe(Val::<C>::from_usize(degree_bits - config.is_zk()));
        challenger.observe(Val::<C>::from_usize(preprocessed_width));
        challenger.observe(Val::<C>::from_usize(A::width(air)));
        challenger.observe(commitments.trace.clone());
        challenger.observe_slice(public_values);

        let _alpha: Val<C> = challenger.sample_algebra_element();
        challenger.observe(commitments.quotient_chunks.clone());
        if let Some(ref r_commit) = commitments.random {
            challenger.observe(r_commit.clone());
        }

        let zeta = challenger.sample_algebra_element();
        let _zeta_next = init_trace_domain
            .next_point(zeta)
            .ok_or(VerificationError::NextPointUnavailable)?;

        let mut coms_to_verify: CommitmentRounds<C> =
            if let Some(ref random_commit) = commitments.random {
                let random_values = opened_values
                    .random
                    .as_ref()
                    .ok_or(VerificationError::RandomizationError)?;
                alloc::vec![(
                    random_commit.clone(),
                    alloc::vec![(trace_domain, alloc::vec![(zeta, random_values.clone())],)],
                )]
            } else {
                alloc::vec![]
            };

        coms_to_verify.push((
            commitments.trace.clone(),
            alloc::vec![(
                trace_domain,
                alloc::vec![
                    (zeta, opened_values.trace_local.clone()),
                    (
                        init_trace_domain
                            .next_point(zeta)
                            .ok_or(VerificationError::NextPointUnavailable)?,
                        opened_values.trace_next.clone(),
                    ),
                ],
            )],
        ));

        let quotient_rounds: QuotientRounds<C> = randomized_quotient_chunks_domains
            .iter()
            .zip(opened_values.quotient_chunks.iter())
            .map(|(domain, values)| (*domain, alloc::vec![(zeta, values.clone())]))
            .collect();
        coms_to_verify.push((commitments.quotient_chunks.clone(), quotient_rounds));

        for (_, round) in &coms_to_verify {
            for (_, mat) in round {
                for (_, point) in mat {
                    for opening in point {
                        challenger.observe_algebra_element(*opening);
                    }
                }
            }
        }

        let _alpha_fri = challenger.sample_algebra_element::<C::Challenge>();

        for comm in opening_proof.commit_phase_commits() {
            challenger.observe(comm.clone());
            let _beta: C::Challenge = challenger.sample_algebra_element();
        }

        for coeff in opening_proof.final_poly() {
            challenger.observe_algebra_element(*coeff);
        }

        if !challenger.check_witness(
            fri_params.proof_of_work_bits,
            opening_proof.pow_witness().clone(),
        ) {
            return Err(VerificationError::InvalidProofShape);
        }

        let log_global_max_height = opening_proof.commit_phase_commits().len() +
            fri_params.log_blowup +
            fri_params.log_final_poly_len;
        const EXTRA_QUERY_INDEX_BITS: usize = 0;

        let mut positions = Vec::with_capacity(fri_params.num_queries);
        for _ in 0..fri_params.num_queries {
            let index = challenger.sample_bits(log_global_max_height + EXTRA_QUERY_INDEX_BITS);
            positions.push(index);
        }

        Ok(positions)
    }

    /// Get a reference to the underlying configuration
    pub fn config(&self) -> &C {
        &self.config
    }
}

/// Creates a production-ready default STARK configuration
///
/// This configuration uses:
/// - **SHAKE256** for all hash operations (NIST-approved, post-quantum secure)
/// - **`Complex<Mersenne31>`** field (TWO_ADICITY = 32) for efficient arithmetic
/// - Production FRI parameters (100 queries, 16 proof-of-work bits)
///
/// # Example
///
/// ```rust,ignore
/// use lib_q_zkp::stark::{default_config, StarkProver, StarkVerifier};
///
/// let config = default_config();
/// let prover = StarkProver::new(config.clone());
/// let verifier = StarkVerifier::new(config);
/// ```
pub fn default_config() -> DefaultConfig {
    use lib_q_stark_fri::FriParameters;

    type ValMmcs = DefaultValMmcs;
    type ChallengeMmcs = DefaultChallengeMmcs;
    type Dft = ConfigDft;
    type Pcs = DefaultPcs;
    type MyHash = SerializingHasher<Shake256Hash>;
    type MyCompress = CompressionFunctionFromHasher<Shake256Hash, 2, 32>;
    type BaseChallenger = Shake256Challenger32<Mersenne31>;
    type Challenger = ComplexFieldChallenger<BaseChallenger>;

    let shake256 = Shake256Hash {};
    let hash = MyHash::new(shake256);
    let compress = MyCompress::new(shake256);
    let val_mmcs = ValMmcs::new(hash, compress);
    let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
    let dft = Dft::default();
    let fri_params = FriParameters {
        log_blowup: 2,
        log_final_poly_len: 0,
        num_queries: 100,
        proof_of_work_bits: 16,
        mmcs: challenge_mmcs,
    };
    let pcs = Pcs::new(dft, val_mmcs, fri_params);
    let base_challenger = BaseChallenger::from_hasher(Vec::new(), Shake256Hash);
    let challenger = Challenger::new(base_challenger);

    StarkConfig::new(pcs, challenger)
}

/// STARK configuration for **tests and local development only**.
///
/// Same construction as [`default_config`], but FRI uses
/// [`lib_q_stark_fri::create_test_fri_params`] (2 queries, 1 proof-of-work bit) so proving
/// and verification complete quickly. **Do not use for production**; proofs are not
/// production-sound and are incompatible with verifiers configured for [`default_config`].
///
/// Soundness is far below production; do not use this config to assert that verification
/// **rejects** wrong public inputs (e.g. wrong Merkle root). For those negative tests, use
/// [`default_config`] on prover and verifier.
pub fn fast_proof_config() -> DefaultConfig {
    use lib_q_stark_fri::create_test_fri_params;

    type ValMmcs = DefaultValMmcs;
    type ChallengeMmcs = DefaultChallengeMmcs;
    type Dft = ConfigDft;
    type Pcs = DefaultPcs;
    type MyHash = SerializingHasher<Shake256Hash>;
    type MyCompress = CompressionFunctionFromHasher<Shake256Hash, 2, 32>;
    type BaseChallenger = Shake256Challenger32<Mersenne31>;
    type Challenger = ComplexFieldChallenger<BaseChallenger>;

    let shake256 = Shake256Hash {};
    let hash = MyHash::new(shake256);
    let compress = MyCompress::new(shake256);
    let val_mmcs = ValMmcs::new(hash, compress);
    let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
    let dft = Dft::default();
    let fri_params = create_test_fri_params(challenge_mmcs, 0);
    let pcs = Pcs::new(dft, val_mmcs, fri_params);
    let base_challenger = BaseChallenger::from_hasher(Vec::new(), Shake256Hash);
    let challenger = Challenger::new(base_challenger);

    StarkConfig::new(pcs, challenger)
}

/// STARK config that uses Poseidon-based Merkle trees (PoseidonMmcs).
/// Use this as the outer config when producing recursive proofs so that Merkle paths
/// are compatible with MerkleInclusionAir (Poseidon constraints in-circuit).
#[cfg(feature = "recursive-proofs-experimental")]
pub fn poseidon_config() -> PoseidonConfig {
    use lib_q_stark_fri::FriParameters;
    use lib_q_stark_merkle::{
        PoseidonMmcs,
        poseidon_mmcs_instance,
    };

    type ValMmcs = PoseidonMmcs;
    type ChallengeMmcs = PoseidonChallengeMmcs;
    type Dft = ConfigDft;
    type Pcs = PoseidonPcs;
    type BaseChallenger = Shake256Challenger32<Mersenne31>;
    type Challenger = ComplexFieldChallenger<BaseChallenger>;

    let (hash, compress) = poseidon_mmcs_instance();
    let val_mmcs = ValMmcs::new(hash, compress);
    let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
    let dft = Dft::default();
    let fri_params = FriParameters {
        log_blowup: 2,
        log_final_poly_len: 0,
        num_queries: 100,
        proof_of_work_bits: 16,
        mmcs: challenge_mmcs,
    };
    let pcs = Pcs::new(dft, val_mmcs, fri_params);
    let base_challenger = BaseChallenger::from_hasher(Vec::new(), Shake256Hash);
    let challenger = Challenger::new(base_challenger);

    StarkConfig::new(pcs, challenger)
}

/// Same PCS and challenger construction as [`poseidon_config`], but FRI uses
/// [`lib_q_stark_fri::create_test_fri_params`] (2 queries, 1 proof-of-work bit) so recursive
/// aggregation tests finish quickly. **Not for production**; incompatible with verifiers
/// expecting [`poseidon_config`] FRI parameters.
#[cfg(feature = "recursive-proofs-experimental")]
pub fn poseidon_test_config() -> PoseidonConfig {
    use lib_q_stark_fri::create_test_fri_params;
    use lib_q_stark_merkle::{
        PoseidonMmcs,
        poseidon_mmcs_instance,
    };

    type ValMmcs = PoseidonMmcs;
    type ChallengeMmcs = PoseidonChallengeMmcs;
    type Dft = ConfigDft;
    type Pcs = PoseidonPcs;
    type BaseChallenger = Shake256Challenger32<Mersenne31>;
    type Challenger = ComplexFieldChallenger<BaseChallenger>;

    let (hash, compress) = poseidon_mmcs_instance();
    let val_mmcs = ValMmcs::new(hash, compress);
    let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
    let dft = Dft::default();
    let fri_params = create_test_fri_params(challenge_mmcs, 0);
    let pcs = Pcs::new(dft, val_mmcs, fri_params);
    let base_challenger = BaseChallenger::from_hasher(Vec::new(), Shake256Hash);
    let challenger = Challenger::new(base_challenger);

    StarkConfig::new(pcs, challenger)
}

/// Default FRI parameters used by `default_config()` (for security parameter tests).
/// Returns (log_blowup, num_queries, proof_of_work_bits).
#[doc(hidden)]
pub const fn default_fri_params_for_tests() -> (usize, usize, usize) {
    (2, 100, 16)
}

/// ZK config for tests: uses HidingFriPcs so proofs are randomized (statistical ZK).
/// Not for production; uses test FRI params (few queries, low PoW).
pub fn zk_config() -> ZkConfig {
    zk_config_with_seeds(0, 1)
}

/// Same as `zk_config()` but with explicit RNG seeds (for tests that need distinct proofs).
#[doc(hidden)]
pub fn zk_config_with_seeds(val_mmcs_seed: u64, pcs_seed: u64) -> ZkConfig {
    use lib_q_stark_fri::create_test_fri_params_zk;

    type ValMmcs = ZkValMmcs;
    type ChallengeMmcs = ZkChallengeMmcs;
    type Dft = ConfigDft;
    type Pcs = ZkPcs;
    type MyHash = SerializingHasher<Shake256Hash>;
    type MyCompress = CompressionFunctionFromHasher<Shake256Hash, 2, 32>;
    type BaseChallenger = Shake256Challenger32<Mersenne31>;
    type Challenger = ComplexFieldChallenger<BaseChallenger>;

    let shake256 = Shake256Hash {};
    let hash = MyHash::new(shake256);
    let compress = MyCompress::new(shake256);
    let val_mmcs = ValMmcs::new(
        hash,
        compress,
        lib_q_random::DeterministicRng::seed_from_u64(val_mmcs_seed),
    );
    let challenge_mmcs = ChallengeMmcs::new(val_mmcs.clone());
    let dft = Dft::default();
    let fri_params = create_test_fri_params_zk(challenge_mmcs);
    let pcs = Pcs::new(
        dft,
        val_mmcs,
        fri_params,
        4,
        lib_q_random::DeterministicRng::seed_from_u64(pcs_seed),
    );
    let base_challenger = BaseChallenger::from_hasher(Vec::new(), Shake256Hash);
    let challenger = Challenger::new(base_challenger);

    StarkConfig::new(pcs, challenger)
}

#[cfg(test)]
mod tests {
    extern crate alloc;
    use alloc::vec;

    use super::*;
    use crate::air::{
        ArithmeticAir,
        TraceGenerator,
    };

    fn sample_arithmetic_proof() -> (ArithmeticAir, StarkProof<DefaultConfig>, Vec<ConfigVal>) {
        let air = ArithmeticAir::new(1).expect("ArithmeticAir");
        let input = vec![(ConfigVal::ONE, ConfigVal::ONE)];
        let trace = air.generate_trace(&input).expect("trace");
        let public_values = air.public_values(&input);
        let proof = StarkProver::new(default_config())
            .prove(&air, trace, &public_values)
            .expect("proof generation");
        (air, proof, public_values)
    }

    #[test]
    fn test_stark_prover_creation() {
        let config = default_config();
        let _prover = StarkProver::new(config);
        // Just verify that creation doesn't panic
    }

    #[test]
    fn test_stark_verifier_creation() {
        let config = default_config();
        let _verifier = StarkVerifier::new(config);
        // Just verify that creation doesn't panic
    }

    #[test]
    fn test_default_config() {
        let _config = default_config();
        // Just verify that config creation doesn't panic
    }

    #[test]
    fn test_default_fri_params_for_tests_values() {
        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        assert_eq!(log_blowup, 2);
        assert_eq!(num_queries, 100);
        assert_eq!(proof_of_work_bits, 16);
    }

    #[test]
    fn test_zk_config_builders_create_zk_configs() {
        let zk_a = zk_config();
        let zk_b = zk_config_with_seeds(11, 29);
        assert_eq!(zk_a.is_zk(), 1);
        assert_eq!(zk_b.is_zk(), 1);
    }

    #[test]
    fn test_prover_and_verifier_config_accessors() {
        let prover = StarkProver::new(default_config());
        let verifier = StarkVerifier::new(default_config());
        assert_eq!(prover.config().is_zk(), 0);
        assert_eq!(verifier.config().is_zk(), 0);
    }

    #[test]
    fn test_stark_prove_and_verify_roundtrip() {
        let (air, proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        verifier
            .verify(&air, &proof, &public_values)
            .expect("proof should verify");
    }

    #[test]
    fn test_derive_challenges_and_query_positions() {
        let (air, proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());

        let (_zeta, _zeta_next, _alpha, betas) = verifier
            .derive_challenges(&air, &proof, &public_values)
            .expect("derive_challenges");

        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        assert!(betas.len() <= num_queries);
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            proof_of_work_bits,
        };
        let positions = verifier
            .derive_query_positions(&air, &proof, &public_values, &fri_params)
            .expect("derive_query_positions");
        assert_eq!(positions.len(), num_queries);
    }

    #[test]
    fn test_derive_query_positions_rejects_wrong_public_values_shape() {
        let (air, proof, _public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            proof_of_work_bits,
        };
        let wrong_public_values = vec![ConfigVal::ZERO; 2];
        let result =
            verifier.derive_query_positions(&air, &proof, &wrong_public_values, &fri_params);
        assert!(result.is_err());
    }

    #[test]
    fn test_derive_challenges_rejects_random_commitment_mismatch() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());

        proof.commitments.random = Some(proof.commitments.trace.clone());
        let result = verifier.derive_challenges(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }

    #[test]
    fn test_derive_challenges_rejects_random_values_mismatch() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());

        proof.opened_values.random = Some(vec![ConfigVal::ZERO]);
        let result = verifier.derive_challenges(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }

    #[test]
    fn test_derive_challenges_rejects_invalid_trace_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());

        let _ = proof.opened_values.trace_local.pop();
        let result = verifier.derive_challenges(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_derive_challenges_rejects_invalid_quotient_chunk_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());

        proof.opened_values.quotient_chunks.clear();
        let result = verifier.derive_challenges(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_derive_query_positions_rejects_random_commitment_mismatch() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            proof_of_work_bits,
        };

        proof.commitments.random = Some(proof.commitments.trace.clone());
        let result = verifier.derive_query_positions(&air, &proof, &public_values, &fri_params);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }

    #[test]
    fn test_derive_query_positions_rejects_random_values_without_commitment() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            proof_of_work_bits,
        };

        proof.opened_values.random = Some(vec![ConfigVal::ZERO]);
        let result = verifier.derive_query_positions(&air, &proof, &public_values, &fri_params);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }

    #[test]
    fn test_derive_query_positions_rejects_invalid_trace_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let (log_blowup, num_queries, proof_of_work_bits) = default_fri_params_for_tests();
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            proof_of_work_bits,
        };

        let _ = proof.opened_values.trace_next.pop();
        let result = verifier.derive_query_positions(&air, &proof, &public_values, &fri_params);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_derive_query_positions_rejects_invalid_pow_witness() {
        let (air, proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let (log_blowup, num_queries, _proof_of_work_bits) = default_fri_params_for_tests();
        let fri_params = FriQueryParams {
            num_queries,
            log_blowup,
            log_final_poly_len: 0,
            // Tighten PoW bits while staying in-field (<= 30 for Mersenne31).
            proof_of_work_bits: 30,
        };

        let result = verifier.derive_query_positions(&air, &proof, &public_values, &fri_params);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_verify_rejects_invalid_trace_local_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let _ = proof.opened_values.trace_local.pop();
        let result = verifier.verify(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_verify_rejects_invalid_trace_next_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        let _ = proof.opened_values.trace_next.pop();
        let result = verifier.verify(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_verify_rejects_invalid_quotient_chunk_shape() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        proof.opened_values.quotient_chunks.clear();
        let result = verifier.verify(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::InvalidProofShape)));
    }

    #[test]
    fn test_verify_rejects_random_commitment_mismatch() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        proof.commitments.random = Some(proof.commitments.trace.clone());
        let result = verifier.verify(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }

    #[test]
    fn test_verify_rejects_random_values_mismatch() {
        let (air, mut proof, public_values) = sample_arithmetic_proof();
        let verifier = StarkVerifier::new(default_config());
        proof.opened_values.random = Some(vec![ConfigVal::ZERO]);
        let result = verifier.verify(&air, &proof, &public_values);
        assert!(matches!(result, Err(VerificationError::RandomizationError)));
    }
}