ligerito 0.6.2

Ligerito polynomial commitment scheme over binary extension fields
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
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use crate::{
    transcript::{FiatShamir, Transcript},
    utils::{eval_sk_at_vks, evaluate_lagrange_basis, hash_row, verify_ligero},
    FinalizedLigeritoProof, VerifierConfig,
};
use binary_fields::BinaryFieldElement;

// Debug printing macros - only enabled in debug builds with std
#[cfg(all(feature = "std", debug_assertions))]
macro_rules! debug_println {
    ($($arg:tt)*) => { std::println!($($arg)*) }
}

#[cfg(not(all(feature = "std", debug_assertions)))]
macro_rules! debug_println {
    ($($arg:tt)*) => {};
}

use merkle_tree::{self, Hash};

const S: usize = 148;
const LOG_INV_RATE: usize = 2;

/// Helper to choose between parallel and sequential sumcheck poly induction
#[cfg(feature = "parallel")]
#[inline(always)]
fn induce_sumcheck_poly_auto<T, U>(
    n: usize,
    sks_vks: &[T],
    opened_rows: &[Vec<T>],
    v_challenges: &[U],
    sorted_queries: &[usize],
    alpha: U,
) -> (Vec<U>, U)
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    crate::sumcheck_polys::induce_sumcheck_poly_parallel(
        n,
        sks_vks,
        opened_rows,
        v_challenges,
        sorted_queries,
        alpha,
    )
}

#[cfg(not(feature = "parallel"))]
#[inline(always)]
fn induce_sumcheck_poly_auto<T, U>(
    n: usize,
    sks_vks: &[T],
    opened_rows: &[Vec<T>],
    v_challenges: &[U],
    sorted_queries: &[usize],
    alpha: U,
) -> (Vec<U>, U)
where
    T: BinaryFieldElement,
    U: BinaryFieldElement + From<T>,
{
    crate::sumcheck_polys::induce_sumcheck_poly(
        n,
        sks_vks,
        opened_rows,
        v_challenges,
        sorted_queries,
        alpha,
    )
}

/// Verify a Ligerito proof (default Merlin transcript)
pub fn verify<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    #[cfg(feature = "transcript-merlin")]
    let fs = FiatShamir::new_merlin();

    #[cfg(not(feature = "transcript-merlin"))]
    let fs = FiatShamir::new_sha256(0);

    verify_with_transcript(config, proof, fs)
}

/// Core verification logic after initial commitment root absorption.
///
/// Called by both `verify_with_transcript` and `verify_with_evaluations`.
fn verify_core<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
    fs: &mut impl Transcript,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    // OPTIMIZATION: Precompute basis evaluations once
    let cached_initial_sks: Vec<T> = eval_sk_at_vks(1 << config.initial_dim);
    let cached_recursive_sks: Vec<Vec<U>> = config
        .log_dims
        .iter()
        .map(|&dim| eval_sk_at_vks(1 << dim))
        .collect();

    // Get initial challenges in base field
    let partial_evals_0_t: Vec<T> = (0..config.initial_k).map(|_| fs.get_challenge()).collect();
    debug_println!("Verifier: Got initial challenges: {:?}", partial_evals_0_t);

    let partial_evals_0: Vec<U> = partial_evals_0_t.iter().map(|&x| U::from(x)).collect();

    // First recursive commitment
    fs.absorb_root(&proof.recursive_commitments[0].root);

    // Verify initial proof
    let depth = config.initial_dim + LOG_INV_RATE;
    let queries = fs.get_distinct_queries(1 << depth, S);

    let hashed_leaves: Vec<Hash> = proof
        .initial_ligero_proof
        .opened_rows
        .iter()
        .map(|row| hash_row(row))
        .collect();

    if !ligerito_merkle::verify(
        &proof.initial_ligero_cm.root,
        &proof.initial_ligero_proof.merkle_proof,
        depth,
        &hashed_leaves,
        &queries,
    ) {
        return Ok(false);
    }

    let alpha = fs.get_challenge::<U>();

    // Use cached basis
    let sks_vks = &cached_initial_sks;
    let (_, enforced_sum) = induce_sumcheck_poly_auto(
        config.initial_dim,
        sks_vks,
        &proof.initial_ligero_proof.opened_rows,
        &partial_evals_0,
        &queries,
        alpha,
    );

    let mut current_sum = enforced_sum;

    fs.absorb_elem(current_sum);

    let mut transcript_idx = 0;

    for i in 0..config.recursive_steps {
        let mut rs = Vec::with_capacity(config.ks[i]);

        // Sumcheck rounds
        for _ in 0..config.ks[i] {
            if transcript_idx >= proof.sumcheck_transcript.transcript.len() {
                return Ok(false);
            }

            let coeffs = proof.sumcheck_transcript.transcript[transcript_idx];
            let claimed_sum =
                evaluate_quadratic(coeffs, U::zero()).add(&evaluate_quadratic(coeffs, U::one()));

            if claimed_sum != current_sum {
                return Ok(false);
            }

            let ri = fs.get_challenge::<U>();
            rs.push(ri);
            current_sum = evaluate_quadratic(coeffs, ri);
            fs.absorb_elem(current_sum);

            transcript_idx += 1;
        }

        if i >= proof.recursive_commitments.len() {
            return Ok(false);
        }

        let root = &proof.recursive_commitments[i].root;

        // Final round
        if i == config.recursive_steps - 1 {
            fs.absorb_elems(&proof.final_ligero_proof.yr);

            let depth = config.log_dims[i] + LOG_INV_RATE;
            let queries = fs.get_distinct_queries(1 << depth, S);

            let hashed_final: Vec<Hash> = proof
                .final_ligero_proof
                .opened_rows
                .iter()
                .map(|row| hash_row(row))
                .collect();

            if !ligerito_merkle::verify(
                root,
                &proof.final_ligero_proof.merkle_proof,
                depth,
                &hashed_final,
                &queries,
            ) {
                return Ok(false);
            }

            // Ligero consistency check - for stateful verify_partial use verify_complete()
            verify_ligero(
                &queries,
                &proof.final_ligero_proof.opened_rows,
                &proof.final_ligero_proof.yr,
                &rs,
            );

            return Ok(true);
        }

        // Continue recursion
        if i + 1 >= proof.recursive_commitments.len() || i >= proof.recursive_proofs.len() {
            return Ok(false);
        }

        fs.absorb_root(&proof.recursive_commitments[i + 1].root);

        let depth = config.log_dims[i] + LOG_INV_RATE;
        let ligero_proof = &proof.recursive_proofs[i];
        let queries = fs.get_distinct_queries(1 << depth, S);

        let hashed_rec: Vec<Hash> = ligero_proof
            .opened_rows
            .iter()
            .map(|row| hash_row(row))
            .collect();

        if !ligerito_merkle::verify(
            root,
            &ligero_proof.merkle_proof,
            depth,
            &hashed_rec,
            &queries,
        ) {
            return Ok(false);
        }

        let alpha = fs.get_challenge::<U>();

        if i >= config.log_dims.len() {
            return Ok(false);
        }

        let sks_vks = &cached_recursive_sks[i];
        let (_, enforced_sum_next) = induce_sumcheck_poly_auto(
            config.log_dims[i],
            sks_vks,
            &ligero_proof.opened_rows,
            &rs,
            &queries,
            alpha,
        );

        let enforced_sum = enforced_sum_next;

        let glue_sum = current_sum.add(&enforced_sum);
        fs.absorb_elem(glue_sum);

        let beta = fs.get_challenge::<U>();
        current_sum = glue_sums(current_sum, enforced_sum, beta);
    }

    Ok(true)
}

/// Verify with custom transcript implementation
pub fn verify_with_transcript<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
    mut fs: impl Transcript,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    fs.absorb_root(&proof.initial_ligero_cm.root);
    verify_core(config, proof, &mut fs)
}

/// Evaluation proof result
pub struct EvalVerifyResult<U: BinaryFieldElement> {
    /// Ligerito proximity test passed
    pub proximity_valid: bool,
    /// Evaluation sumcheck challenges (the random point r)
    pub eval_challenges: Vec<U>,
    /// P(r) as derived from the eval sumcheck
    pub p_at_r: U,
}

/// Verify with evaluation claims (sumcheck-based evaluation proofs).
///
/// Runs the eval sumcheck (checking internal consistency of P(z_k) = v_k
/// claims), then the standard Ligerito proximity test. Both share the
/// Fiat-Shamir transcript.
///
/// Returns None if the evaluation sumcheck fails. Returns
/// Some(EvalVerifyResult) with the proximity test result, the random
/// point r, and the claimed P(r). The caller is responsible for
/// binding P(r) to the committed polynomial via an evaluation opening.
pub fn verify_with_evaluations<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
    claims: &[crate::eval_proof::EvalClaim<T>],
    mut fs: impl Transcript,
) -> crate::Result<Option<EvalVerifyResult<U>>>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    fs.absorb_root(&proof.initial_ligero_cm.root);

    // Eval sumcheck: verify P(z_k) = v_k
    let alphas: Vec<U> = (0..claims.len()).map(|_| fs.get_challenge()).collect();

    // Compute target: Σ α_k · v_k
    let target: U = claims
        .iter()
        .zip(alphas.iter())
        .map(|(c, &a)| a.mul(&U::from(c.value)))
        .fold(U::zero(), |acc, x| acc.add(&x));

    // Derive n from config, not from the proof — a malicious prover must not
    // control the number of sumcheck rounds.
    let n = config.poly_log_size();
    if proof.eval_rounds.len() != n {
        return Ok(None);
    }
    let eval_result = crate::eval_proof::eval_sumcheck_verify::<T, U>(
        &proof.eval_rounds,
        claims,
        &alphas,
        target,
        n,
        &mut fs,
    );

    let (eval_challenges, p_at_r) = match eval_result {
        Some(r) => r,
        None => return Ok(None),
    };

    // Continue with Ligerito proximity verification (same transcript state)
    let proximity_valid = verify_core(config, proof, &mut fs)?;

    Ok(Some(EvalVerifyResult {
        proximity_valid,
        eval_challenges,
        p_at_r,
    }))
}

/// SHA256-based verification for compatibility
pub fn verify_sha256<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_sha256(1234);
    verify_with_transcript(config, proof, fs)
}

// Helper functions

#[inline(always)]
fn evaluate_quadratic<F: BinaryFieldElement>(coeffs: (F, F, F), x: F) -> F {
    let (s0, s1, _s2) = coeffs;
    // For binary field sumcheck, we need a univariate polynomial where:
    // f(0) = s0 (sum when xi=0)
    // f(1) = s2 (sum when xi=1)
    // and s1 = s0 + s2 (total sum)
    //
    // The degree-1 polynomial through (0,s0) and (1,s2) is:
    // f(x) = s0*(1-x) + s2*x = s0 + (s2-s0)*x
    // In binary fields where -s0 = s0:
    // f(x) = s0 + (s2+s0)*x = s0 + s1*x (since s1 = s0+s2)
    //
    // But wait, that gives f(0) = s0 and f(1) = s0+s1 = s0+s0+s2 = s2 (since s0+s0=0 in binary)
    // Let's verify: f(1) = s0 + s1*1 = s0 + (s0+s2) = s2. Good!
    s0.add(&s1.mul(&x))
}

#[inline(always)]
fn glue_sums<F: BinaryFieldElement>(sum_f: F, sum_g: F, beta: F) -> F {
    sum_f.add(&beta.mul(&sum_g))
}

/// Debug version to find where verification fails - FIXED VERSION
pub fn verify_debug<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    debug_println!("\n=== VERIFICATION DEBUG ===");

    // OPTIMIZATION: Precompute basis evaluations once
    let cached_initial_sks: Vec<T> = eval_sk_at_vks(1 << config.initial_dim);
    let cached_recursive_sks: Vec<Vec<U>> = config
        .log_dims
        .iter()
        .map(|&dim| eval_sk_at_vks(1 << dim))
        .collect();

    // Initialize transcript
    #[cfg(feature = "transcript-merlin")]
    let mut fs = FiatShamir::new_merlin();

    #[cfg(not(feature = "transcript-merlin"))]
    let mut fs = FiatShamir::new_sha256(0);

    // Absorb initial commitment
    fs.absorb_root(&proof.initial_ligero_cm.root);
    debug_println!("Absorbed initial root: {:?}", proof.initial_ligero_cm.root);

    // Get initial challenges in base field to match prover
    let partial_evals_0_t: Vec<T> = (0..config.initial_k).map(|_| fs.get_challenge()).collect();
    debug_println!("Got {} base field challenges", partial_evals_0_t.len());
    debug_println!(
        "Verifier debug: Got initial challenges: {:?}",
        partial_evals_0_t
    );

    // Convert to extension field for computations
    let partial_evals_0: Vec<U> = partial_evals_0_t.iter().map(|&x| U::from(x)).collect();

    debug_println!(
        "Partial evaluations (extension field): {:?}",
        partial_evals_0
    );

    // Test Lagrange basis computation
    let gr = evaluate_lagrange_basis(&partial_evals_0);
    debug_println!(
        "Lagrange basis length: {}, first few values: {:?}",
        gr.len(),
        &gr[..gr.len().min(4)]
    );

    // Absorb first recursive commitment
    if proof.recursive_commitments.is_empty() {
        debug_println!("ERROR: No recursive commitments!");
        return Ok(false);
    }
    debug_println!(
        "Verifier: Absorbing recursive commitment root: {:?}",
        proof.recursive_commitments[0].root.root
    );
    fs.absorb_root(&proof.recursive_commitments[0].root);
    debug_println!("Absorbed recursive commitment 0");

    // Verify initial Merkle proof
    let depth = config.initial_dim + LOG_INV_RATE;
    debug_println!("Verifier: About to get queries after absorbing recursive commitment");
    let queries = fs.get_distinct_queries(1 << depth, S);
    debug_println!(
        "Initial proof: depth={}, num_leaves={}, queries={:?}",
        depth,
        1 << depth,
        &queries[..queries.len().min(5)]
    );

    // Hash opened rows for Merkle verification
    let hashed_leaves: Vec<Hash> = proof
        .initial_ligero_proof
        .opened_rows
        .iter()
        .map(|row| hash_row(row))
        .collect();
    debug_println!("Hashed {} opened rows", hashed_leaves.len());
    debug_println!(
        "Opened rows per query match: {}",
        hashed_leaves.len() == queries.len()
    );

    // Debug: Print first few hashes and queries
    debug_println!("First 3 queries: {:?}", &queries[..3.min(queries.len())]);
    debug_println!(
        "First 3 opened rows: {:?}",
        &proof.initial_ligero_proof.opened_rows
            [..3.min(proof.initial_ligero_proof.opened_rows.len())]
    );
    debug_println!(
        "First 3 row hashes: {:?}",
        &hashed_leaves[..3.min(hashed_leaves.len())]
    );
    debug_println!("Tree root: {:?}", proof.initial_ligero_cm.root);

    let merkle_result = ligerito_merkle::verify(
        &proof.initial_ligero_cm.root,
        &proof.initial_ligero_proof.merkle_proof,
        depth,
        &hashed_leaves,
        &queries,
    );
    debug_println!("Initial Merkle verification: {}", merkle_result);

    if !merkle_result {
        debug_println!("FAILED: Initial Merkle proof verification");

        // Additional debug info
        debug_println!(
            "Proof siblings: {}",
            proof.initial_ligero_proof.merkle_proof.siblings.len()
        );
        debug_println!("Expected depth: {}", depth);
        debug_println!("Number of queries: {}", queries.len());
        debug_println!("First few queries: {:?}", &queries[..queries.len().min(10)]);

        return Ok(false);
    }

    let alpha = fs.get_challenge::<U>();
    debug_println!("Got alpha challenge: {:?}", alpha);

    // Use the same fixed sumcheck function as prover
    let sks_vks = &cached_initial_sks;
    debug_println!("Computed {} sks_vks", sks_vks.len());

    let (basis_poly, enforced_sum) = induce_sumcheck_poly_auto(
        config.initial_dim,
        sks_vks,
        &proof.initial_ligero_proof.opened_rows,
        &partial_evals_0,
        &queries,
        alpha,
    );

    // Check consistency
    let basis_sum = basis_poly.iter().fold(U::zero(), |acc, &x| acc.add(&x));
    if basis_sum != enforced_sum {
        debug_println!("VERIFICATION FAILED: Initial basis polynomial sum mismatch");
        debug_println!("  Expected (enforced_sum): {:?}", enforced_sum);
        debug_println!("  Actual (basis_sum): {:?}", basis_sum);
        return Ok(false);
    } else {
        debug_println!("✓ Initial sumcheck consistency check passed");
    }

    // Use the enforced_sum from sumcheck computation
    let mut current_sum = enforced_sum;
    debug_println!("Using current_sum (enforced_sum): {:?}", current_sum);

    // Initial sumcheck absorb
    fs.absorb_elem(current_sum);

    // Process recursive rounds
    let mut transcript_idx = 0;

    for i in 0..config.recursive_steps {
        debug_println!("\nRecursive step {}/{}", i + 1, config.recursive_steps);
        let mut rs = Vec::with_capacity(config.ks[i]);

        // Verify sumcheck rounds
        for j in 0..config.ks[i] {
            // Bounds check for transcript access
            if transcript_idx >= proof.sumcheck_transcript.transcript.len() {
                debug_println!(
                    "ERROR: Transcript index {} >= transcript length {}",
                    transcript_idx,
                    proof.sumcheck_transcript.transcript.len()
                );
                return Ok(false);
            }

            let coeffs = proof.sumcheck_transcript.transcript[transcript_idx];
            let s0 = evaluate_quadratic(coeffs, U::zero());
            let s1 = evaluate_quadratic(coeffs, U::one());
            let claimed_sum = s0.add(&s1);

            debug_println!("  Round {}: coeffs={:?}", j, coeffs);
            debug_println!("    s0 (at 0) = {:?}", s0);
            debug_println!("    s1 (at 1) = {:?}", s1);
            debug_println!("    claimed_sum (s0+s1) = {:?}", claimed_sum);
            debug_println!("    current_sum = {:?}", current_sum);

            if claimed_sum != current_sum {
                debug_println!("  FAILED: Sumcheck mismatch!");
                return Ok(false);
            }

            let ri = fs.get_challenge::<U>();
            rs.push(ri);
            current_sum = evaluate_quadratic(coeffs, ri);
            fs.absorb_elem(current_sum);
            debug_println!("    Next current_sum = {:?}", current_sum);

            transcript_idx += 1;
        }

        // Bounds check for recursive commitments
        if i >= proof.recursive_commitments.len() {
            debug_println!(
                "ERROR: Recursive commitment index {} >= length {}",
                i,
                proof.recursive_commitments.len()
            );
            return Ok(false);
        }

        let root = &proof.recursive_commitments[i].root;

        // Final round verification
        if i == config.recursive_steps - 1 {
            debug_println!("\nFinal round verification:");
            fs.absorb_elems(&proof.final_ligero_proof.yr);
            debug_println!("Absorbed {} yr values", proof.final_ligero_proof.yr.len());

            let depth = config.log_dims[i] + LOG_INV_RATE;
            let queries = fs.get_distinct_queries(1 << depth, S);
            debug_println!(
                "Final: depth={}, queries={:?}",
                depth,
                &queries[..queries.len().min(5)]
            );

            // Hash final opened rows
            let hashed_final: Vec<Hash> = proof
                .final_ligero_proof
                .opened_rows
                .iter()
                .map(|row| hash_row(row))
                .collect();

            let final_merkle_result = ligerito_merkle::verify(
                root,
                &proof.final_ligero_proof.merkle_proof,
                depth,
                &hashed_final,
                &queries,
            );
            debug_println!("Final Merkle verification: {}", final_merkle_result);

            if !final_merkle_result {
                debug_println!("FAILED: Final Merkle proof verification");
                return Ok(false);
            }

            // Ligero consistency check - for stateful verify_partial use verify_complete()
            debug_println!("Calling verify_ligero...");
            verify_ligero(
                &queries,
                &proof.final_ligero_proof.opened_rows,
                &proof.final_ligero_proof.yr,
                &rs,
            );
            debug_println!("✓ verify_ligero passed");
            debug_println!("Final round: all checks passed");
            return Ok(true);
        }

        // Continue recursion for non-final rounds
        if i + 1 >= proof.recursive_commitments.len() {
            debug_println!("ERROR: Missing recursive commitment {}", i + 1);
            return Ok(false);
        }

        fs.absorb_root(&proof.recursive_commitments[i + 1].root);
        debug_println!("Absorbed recursive commitment {}", i + 1);

        let depth = config.log_dims[i] + LOG_INV_RATE;

        // Bounds check for recursive proofs
        if i >= proof.recursive_proofs.len() {
            debug_println!("ERROR: Missing recursive proof {}", i);
            return Ok(false);
        }

        let ligero_proof = &proof.recursive_proofs[i];
        let queries = fs.get_distinct_queries(1 << depth, S);
        debug_println!(
            "Recursive {}: depth={}, queries={:?}",
            i,
            depth,
            &queries[..queries.len().min(5)]
        );

        // Hash recursive opened rows
        let hashed_rec: Vec<Hash> = ligero_proof
            .opened_rows
            .iter()
            .map(|row| hash_row(row))
            .collect();

        let rec_merkle_result = ligerito_merkle::verify(
            root,
            &ligero_proof.merkle_proof,
            depth,
            &hashed_rec,
            &queries,
        );
        debug_println!("Recursive {} Merkle verification: {}", i, rec_merkle_result);

        if !rec_merkle_result {
            debug_println!("FAILED: Recursive {} Merkle proof verification", i);
            return Ok(false);
        }

        let alpha = fs.get_challenge::<U>();
        debug_println!("Got alpha for next round");

        // Bounds check for log_dims
        if i >= config.log_dims.len() {
            debug_println!("ERROR: Missing log_dims[{}]", i);
            return Ok(false);
        }

        // Use the same fixed sumcheck function as prover
        let sks_vks = &cached_recursive_sks[i];
        let (basis_poly_next, enforced_sum_next) = induce_sumcheck_poly_auto(
            config.log_dims[i],
            sks_vks,
            &ligero_proof.opened_rows,
            &rs,
            &queries,
            alpha,
        );

        // Check consistency for recursive round too
        let basis_sum_next = basis_poly_next
            .iter()
            .fold(U::zero(), |acc, &x| acc.add(&x));
        if basis_sum_next != enforced_sum_next {
            debug_println!(
                "VERIFICATION FAILED: Recursive basis polynomial sum mismatch at round {}",
                i
            );
            debug_println!("  Expected (enforced_sum): {:?}", enforced_sum_next);
            debug_println!("  Actual (basis_sum): {:?}", basis_sum_next);
            return Ok(false);
        } else {
            debug_println!("✓ Recursive round {} sumcheck consistency check passed", i);
        }

        let enforced_sum = enforced_sum_next;
        debug_println!("Induced next sumcheck, enforced_sum: {:?}", enforced_sum);

        // Glue verification
        let glue_sum = current_sum.add(&enforced_sum);
        fs.absorb_elem(glue_sum);
        debug_println!("Glue sum: {:?}", glue_sum);

        let beta = fs.get_challenge::<U>();
        current_sum = glue_sums(current_sum, enforced_sum, beta);
        debug_println!("Updated current_sum: {:?}", current_sum);
    }

    debug_println!("\nAll verification steps completed successfully!");
    Ok(true)
}

/// Stateful verifier with full protocol compliance
///
/// This verifier maintains `SumcheckVerifierInstance` state throughout verification,
/// enabling the verify_partial check from the Julia/ashutosh1206 reference implementation.
///
/// Use this when you need 100% protocol-compliant verification. The simpler `verify()`
/// function provides equivalent security via `verify_ligero` consistency checks.
pub fn verify_complete_with_transcript<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
    mut fs: impl Transcript,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    use crate::sumcheck_verifier::SumcheckVerifierInstance;

    // OPTIMIZATION: Precompute basis evaluations once
    let cached_initial_sks: Vec<T> = eval_sk_at_vks(1 << config.initial_dim);
    let cached_recursive_sks: Vec<Vec<U>> = config
        .log_dims
        .iter()
        .map(|&dim| eval_sk_at_vks(1 << dim))
        .collect();

    // absorb initial commitment
    fs.absorb_root(&proof.initial_ligero_cm.root);

    // get initial challenges in base field
    let partial_evals_0_t: Vec<T> = (0..config.initial_k).map(|_| fs.get_challenge()).collect();

    // convert to extension field
    let partial_evals_0: Vec<U> = partial_evals_0_t.iter().map(|&x| U::from(x)).collect();

    // absorb first recursive commitment
    if proof.recursive_commitments.is_empty() {
        return Ok(false);
    }
    fs.absorb_root(&proof.recursive_commitments[0].root);

    // verify initial merkle proof
    let depth = config.initial_dim + LOG_INV_RATE;
    let queries = fs.get_distinct_queries(1 << depth, S);

    let hashed_leaves: Vec<Hash> = proof
        .initial_ligero_proof
        .opened_rows
        .iter()
        .map(|row| hash_row(row))
        .collect();

    if !ligerito_merkle::verify(
        &proof.initial_ligero_cm.root,
        &proof.initial_ligero_proof.merkle_proof,
        depth,
        &hashed_leaves,
        &queries,
    ) {
        return Ok(false);
    }

    let alpha = fs.get_challenge::<U>();

    // induce initial sumcheck polynomial
    let sks_vks = &cached_initial_sks;
    let (basis_poly, enforced_sum) = induce_sumcheck_poly_auto(
        config.initial_dim,
        sks_vks,
        &proof.initial_ligero_proof.opened_rows,
        &partial_evals_0,
        &queries,
        alpha,
    );

    // verify consistency
    let basis_sum = basis_poly.iter().fold(U::zero(), |acc, &x| acc.add(&x));
    if basis_sum != enforced_sum {
        return Ok(false);
    }

    // create stateful sumcheck verifier instance
    let mut sumcheck_verifier = SumcheckVerifierInstance::new(
        basis_poly,
        enforced_sum,
        proof.sumcheck_transcript.transcript.clone(),
    );

    // absorb the initial sum (this matches the prover's behavior)
    fs.absorb_elem(sumcheck_verifier.sum);

    // process recursive rounds
    for i in 0..config.recursive_steps {
        let mut rs = Vec::with_capacity(config.ks[i]);

        // sumcheck folding rounds
        for _ in 0..config.ks[i] {
            let ri = fs.get_challenge::<U>();
            #[cfg(feature = "std")]
            sumcheck_verifier
                .fold(ri)
                .map_err(|e| crate::LigeritoError::SumcheckError(format!("{:?}", e)))?;
            #[cfg(not(feature = "std"))]
            sumcheck_verifier
                .fold(ri)
                .map_err(|_| crate::LigeritoError::SumcheckError)?;
            // absorb the new sum after folding
            fs.absorb_elem(sumcheck_verifier.sum);
            rs.push(ri);
        }

        if i >= proof.recursive_commitments.len() {
            return Ok(false);
        }

        let root = &proof.recursive_commitments[i].root;

        // final round verification
        if i == config.recursive_steps - 1 {
            fs.absorb_elems(&proof.final_ligero_proof.yr);

            let depth = config.log_dims[i] + LOG_INV_RATE;
            let queries = fs.get_distinct_queries(1 << depth, S);

            let hashed_final: Vec<Hash> = proof
                .final_ligero_proof
                .opened_rows
                .iter()
                .map(|row| hash_row(row))
                .collect();

            if !ligerito_merkle::verify(
                root,
                &proof.final_ligero_proof.merkle_proof,
                depth,
                &hashed_final,
                &queries,
            ) {
                return Ok(false);
            }

            // Ligero consistency check (equivalent to verify_partial via Reed-Solomon distance)
            verify_ligero(
                &queries,
                &proof.final_ligero_proof.opened_rows,
                &proof.final_ligero_proof.yr,
                &rs,
            );

            return Ok(true);
        }

        // continue recursion for non-final rounds
        if i + 1 >= proof.recursive_commitments.len() {
            return Ok(false);
        }

        fs.absorb_root(&proof.recursive_commitments[i + 1].root);

        let depth = config.log_dims[i] + LOG_INV_RATE;

        if i >= proof.recursive_proofs.len() {
            return Ok(false);
        }

        let ligero_proof = &proof.recursive_proofs[i];
        let queries = fs.get_distinct_queries(1 << depth, S);

        let hashed_rec: Vec<Hash> = ligero_proof
            .opened_rows
            .iter()
            .map(|row| hash_row(row))
            .collect();

        if !ligerito_merkle::verify(
            root,
            &ligero_proof.merkle_proof,
            depth,
            &hashed_rec,
            &queries,
        ) {
            return Ok(false);
        }

        let alpha = fs.get_challenge::<U>();

        if i >= config.log_dims.len() {
            return Ok(false);
        }

        // induce next sumcheck polynomial
        let sks_vks = &cached_recursive_sks[i];
        let (basis_poly_next, enforced_sum_next) = induce_sumcheck_poly_auto(
            config.log_dims[i],
            sks_vks,
            &ligero_proof.opened_rows,
            &rs,
            &queries,
            alpha,
        );

        // verify consistency
        let basis_sum_next = basis_poly_next
            .iter()
            .fold(U::zero(), |acc, &x| acc.add(&x));
        if basis_sum_next != enforced_sum_next {
            return Ok(false);
        }

        // compute glue sum before introducing (current_sum + new_sum)
        let glue_sum = sumcheck_verifier.sum.add(&enforced_sum_next);
        fs.absorb_elem(glue_sum);

        // introduce new basis polynomial
        #[cfg(feature = "std")]
        sumcheck_verifier
            .introduce_new(basis_poly_next, enforced_sum_next)
            .map_err(|e| crate::LigeritoError::SumcheckError(format!("{:?}", e)))?;
        #[cfg(not(feature = "std"))]
        sumcheck_verifier
            .introduce_new(basis_poly_next, enforced_sum_next)
            .map_err(|_| crate::LigeritoError::SumcheckError)?;

        let beta = fs.get_challenge::<U>();
        #[cfg(feature = "std")]
        sumcheck_verifier
            .glue(beta)
            .map_err(|e| crate::LigeritoError::SumcheckError(format!("{:?}", e)))?;
        #[cfg(not(feature = "std"))]
        sumcheck_verifier
            .glue(beta)
            .map_err(|_| crate::LigeritoError::SumcheckError)?;
    }

    Ok(true)
}

/// complete verifier with default transcript
#[cfg(feature = "transcript-merlin")]
pub fn verify_complete<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_merlin();
    verify_complete_with_transcript(config, proof, fs)
}

/// complete verifier with default transcript (SHA256 when Merlin not available)
#[cfg(not(feature = "transcript-merlin"))]
pub fn verify_complete<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_sha256(0);
    verify_complete_with_transcript(config, proof, fs)
}

/// complete verifier with SHA256 transcript (Julia-compatible)
pub fn verify_complete_sha256<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_sha256(1234);
    verify_complete_with_transcript(config, proof, fs)
}

/// complete verifier with BLAKE2b transcript (optimized for Substrate runtimes)
///
/// Uses `sp_io::hashing::blake2_256` in no_std for efficient host function calls.
/// Proofs must be generated with `prove_blake2b()` to be compatible.
#[cfg(feature = "transcript-blake2b")]
pub fn verify_blake2b<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_blake2b();
    verify_with_transcript(config, proof, fs)
}

/// complete verifier with BLAKE2b transcript
#[cfg(feature = "transcript-blake2b")]
pub fn verify_complete_blake2b<T, U>(
    config: &VerifierConfig,
    proof: &FinalizedLigeritoProof<T, U>,
) -> crate::Result<bool>
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    let fs = FiatShamir::new_blake2b();
    verify_complete_with_transcript(config, proof, fs)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::configs::{hardcoded_config_12, hardcoded_config_12_verifier};
    use crate::prover::prove;
    use ligerito_binary_fields::{BinaryElem128, BinaryElem32};
    use std::marker::PhantomData;

    #[test]
    fn test_verify_simple_proof() {
        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        // Test with simple polynomial
        let poly = vec![BinaryElem32::one(); 1 << 12];

        let proof = prove(&prover_config, &poly).expect("Proof generation failed");
        let result = verify(&verifier_config, &proof).expect("Verification failed");

        assert!(result, "Verification should succeed for valid proof");
    }

    #[test]
    fn test_verify_zero_polynomial() {
        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        // Test with zero polynomial
        let poly = vec![BinaryElem32::zero(); 1 << 12];

        let proof = prove(&prover_config, &poly).expect("Proof generation failed");
        let result = verify(&verifier_config, &proof).expect("Verification failed");

        assert!(result, "Verification should succeed for zero polynomial");
    }

    #[test]
    fn test_verify_with_sha256() {
        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        // Test with patterned polynomial
        let mut poly = vec![BinaryElem32::zero(); 1 << 12];
        poly[0] = BinaryElem32::one();
        poly[1] = BinaryElem32::from(2);

        let proof = crate::prover::prove_sha256(&prover_config, &poly)
            .expect("SHA256 proof generation failed");
        let result = verify_sha256(&verifier_config, &proof).expect("SHA256 verification failed");

        assert!(result, "SHA256 verification should succeed");
    }

    #[test]
    fn test_debug_verification() {
        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        // Use a non-constant polynomial to avoid degenerate case
        let poly: Vec<BinaryElem32> = (0..(1 << 12))
            .map(|i| BinaryElem32::from((i * 7 + 13) as u32)) // Some pattern to ensure diversity
            .collect();

        let proof = prove(&prover_config, &poly).expect("Proof generation failed");
        let result = verify_debug(&verifier_config, &proof).expect("Debug verification failed");

        assert!(result, "Debug verification should succeed");
    }

    #[test]
    fn test_helper_functions() {
        // test evaluate_quadratic (actually linear for binary sumcheck)
        // f(x) = s0 + s1*x where s1 = s0 + s2
        let coeffs = (
            BinaryElem128::from(1), // s0
            BinaryElem128::from(3), // s1 = s0 + s2
            BinaryElem128::from(2), // s2
        );

        let val0 = evaluate_quadratic(coeffs, BinaryElem128::zero());
        assert_eq!(val0, BinaryElem128::from(1));

        let val1 = evaluate_quadratic(coeffs, BinaryElem128::one());
        // f(1) = s0 + s1 = 1 XOR 3 = 2
        assert_eq!(val1, BinaryElem128::from(2));

        // Test glue_sums
        let sum_f = BinaryElem128::from(5);
        let sum_g = BinaryElem128::from(7);
        let beta = BinaryElem128::from(3);

        let glued = glue_sums(sum_f, sum_g, beta);
        let expected = sum_f.add(&beta.mul(&sum_g));
        assert_eq!(glued, expected);
    }

    #[test]
    #[cfg(feature = "transcript-blake2b")]
    fn test_blake2b_transcript_compatibility() {
        use crate::prover::prove_blake2b;

        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        // Test with patterned polynomial
        let poly: Vec<BinaryElem32> = (0..(1 << 12))
            .map(|i| BinaryElem32::from((i * 7 + 13) as u32))
            .collect();

        // Prove with Blake2b
        let proof = prove_blake2b(&prover_config, &poly).expect("Blake2b proof generation failed");

        // Verify with Blake2b
        let result = verify_blake2b(&verifier_config, &proof).expect("Blake2b verification failed");

        assert!(
            result,
            "Blake2b verification should succeed for valid proof"
        );

        // Also test complete verifier
        let proof2 = prove_blake2b(&prover_config, &poly).expect("Blake2b proof generation failed");
        let result2 = verify_complete_blake2b(&verifier_config, &proof2)
            .expect("Blake2b complete verification failed");

        assert!(result2, "Blake2b complete verification should succeed");
    }

    #[test]
    #[cfg(feature = "transcript-blake2b")]
    fn test_sha256_transcript_compatibility() {
        // This test verifies that SHA256 proofs cannot be verified with Blake2b
        // (and vice versa) - they are NOT compatible
        use crate::prover::prove_sha256;

        let prover_config =
            hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);
        let verifier_config = hardcoded_config_12_verifier();

        let poly: Vec<BinaryElem32> = (0..(1 << 12))
            .map(|i| BinaryElem32::from((i * 7 + 13) as u32))
            .collect();

        // Prove with SHA256
        let sha_proof =
            prove_sha256(&prover_config, &poly).expect("SHA256 proof generation failed");

        // Trying to verify SHA256 proof with Blake2b should fail
        let result = verify_blake2b(&verifier_config, &sha_proof)
            .expect("Verification call should not panic");

        assert!(
            !result,
            "SHA256 proof should NOT verify with Blake2b transcript"
        );
    }
}