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
use crate::{
    data_structures::finalize,
    ligero::ligero_commit,
    sumcheck_polys::induce_sumcheck_poly,
    transcript::{FiatShamir, Transcript},
    utils::{eval_sk_at_vks, partial_eval_multilinear},
    FinalLigeroProof, FinalizedLigeritoProof, LigeritoProof, ProverConfig,
    RecursiveLigeroCommitment, RecursiveLigeroProof, SumcheckTranscript,
};
use binary_fields::BinaryFieldElement;

#[cfg(feature = "parallel")]
use crate::sumcheck_polys::induce_sumcheck_poly_parallel;

/// 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: &[U],
    opened_rows: &[Vec<U>],
    v_challenges: &[U],
    sorted_queries: &[usize],
    alpha: U,
) -> (Vec<U>, U)
where
    T: BinaryFieldElement + Send + Sync,
    U: BinaryFieldElement + Send + Sync + From<T>,
{
    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: &[U],
    opened_rows: &[Vec<U>],
    v_challenges: &[U],
    sorted_queries: &[usize],
    alpha: U,
) -> (Vec<U>, U)
where
    T: BinaryFieldElement,
    U: BinaryFieldElement + From<T>,
{
    induce_sumcheck_poly(n, sks_vks, opened_rows, v_challenges, sorted_queries, alpha)
}

/// Core proving logic after initial commitment and root absorption.
///
/// Called by both `prove_with_transcript` (no eval claims) and
/// `prove_with_evaluations` (with eval claims prepended to the transcript).
fn prove_core<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
    wtns_0: crate::data_structures::RecursiveLigeroWitness<T>,
    cm_0: RecursiveLigeroCommitment,
    fs: &mut impl Transcript,
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    let mut proof = LigeritoProof::<T, U>::new();
    proof.initial_ligero_cm = Some(cm_0);

    // Get initial challenges - get them as T type (base field)
    let partial_evals_0: Vec<T> = (0..config.initial_k).map(|_| fs.get_challenge()).collect();

    // Partial evaluation of multilinear polynomial
    let mut f_evals = poly.to_vec();
    partial_eval_multilinear(&mut f_evals, &partial_evals_0);

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

    // First recursive step - convert to U type
    let f_evals_u: Vec<U> = f_evals.iter().map(|&x| U::from(x)).collect();
    let wtns_1 = ligero_commit(
        &f_evals_u,
        config.dims[0].0,
        config.dims[0].1,
        &config.reed_solomon_codes[0],
    );
    let cm_1 = RecursiveLigeroCommitment {
        root: wtns_1.tree.get_root(),
    };
    proof.recursive_commitments.push(cm_1.clone());
    fs.absorb_root(&cm_1.root);

    // Query selection
    let rows = wtns_0.mat.len();
    let queries = fs.get_distinct_queries(rows, config.num_queries); // Returns 0-based indices
    let alpha = fs.get_challenge::<U>();

    // Prepare for sumcheck
    let n = f_evals.len().trailing_zeros() as usize;
    let sks_vks: Vec<T> = eval_sk_at_vks(1 << n);

    // Use 0-based queries directly for array access
    let opened_rows: Vec<Vec<T>> = queries.iter().map(|&q| wtns_0.mat[q].clone()).collect();

    let mtree_proof = wtns_0.tree.prove(&queries); // prove() expects 0-based
    proof.initial_ligero_proof = Some(RecursiveLigeroProof {
        opened_rows: opened_rows.clone(),
        merkle_proof: mtree_proof,
    });

    // use sequential version - parallel has too much overhead in WASM
    let (basis_poly, enforced_sum) = induce_sumcheck_poly(
        n,
        &sks_vks,
        &opened_rows,
        &partial_evals_0_u,
        &queries,
        alpha,
    );

    let mut sumcheck_transcript = vec![];
    let mut current_poly = basis_poly;
    let mut current_sum = enforced_sum; // Use enforced_sum directly

    // First sumcheck round absorb
    fs.absorb_elem(current_sum);

    // Recursive rounds
    let mut wtns_prev = wtns_1;

    for i in 0..config.recursive_steps {
        let mut rs = Vec::new();

        // Sumcheck rounds
        for _ in 0..config.ks[i] {
            // Compute coefficients first (before getting challenge)
            let coeffs = compute_sumcheck_coefficients(&current_poly);
            sumcheck_transcript.push(coeffs);

            // Get challenge after providing coefficients
            let ri = fs.get_challenge::<U>();
            rs.push(ri);

            // Fold polynomial with the challenge
            current_poly = fold_polynomial_with_challenge(&current_poly, ri);

            // Update sum
            current_sum = evaluate_quadratic(coeffs, ri);
            fs.absorb_elem(current_sum);
        }

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

            let rows = wtns_prev.mat.len();
            let queries = fs.get_distinct_queries(rows, config.num_queries); // 0-based

            // Use 0-based queries directly for array access
            let opened_rows: Vec<Vec<U>> =
                queries.iter().map(|&q| wtns_prev.mat[q].clone()).collect();

            let mtree_proof = wtns_prev.tree.prove(&queries); // 0-based

            proof.final_ligero_proof = Some(FinalLigeroProof {
                yr: current_poly.clone(),
                opened_rows,
                merkle_proof: mtree_proof,
            });

            proof.sumcheck_transcript = Some(SumcheckTranscript {
                transcript: sumcheck_transcript,
            });

            return finalize(proof);
        }

        // Continue recursion
        let wtns_next = ligero_commit(
            &current_poly,
            config.dims[i + 1].0,
            config.dims[i + 1].1,
            &config.reed_solomon_codes[i + 1],
        );

        let cm_next = RecursiveLigeroCommitment {
            root: wtns_next.tree.get_root(),
        };
        proof.recursive_commitments.push(cm_next.clone());
        fs.absorb_root(&cm_next.root);

        let rows = wtns_prev.mat.len();
        let queries = fs.get_distinct_queries(rows, config.num_queries); // 0-based
        let alpha = fs.get_challenge::<U>();

        // Use 0-based queries directly for array access
        let opened_rows: Vec<Vec<U>> = queries.iter().map(|&q| wtns_prev.mat[q].clone()).collect();

        let mtree_proof = wtns_prev.tree.prove(&queries); // 0-based
        proof.recursive_proofs.push(RecursiveLigeroProof {
            opened_rows: opened_rows.clone(),
            merkle_proof: mtree_proof,
        });

        // Update for next round
        let n = current_poly.len().trailing_zeros() as usize;
        let sks_vks: Vec<U> = eval_sk_at_vks(1 << n);

        // Use parallel version when available for performance
        let (basis_poly, enforced_sum) =
            induce_sumcheck_poly_auto::<U, U>(n, &sks_vks, &opened_rows, &rs, &queries, alpha);

        // Glue sumcheck absorb
        let glue_sum = current_sum.add(&enforced_sum);
        fs.absorb_elem(glue_sum);

        // Glue polynomials
        let beta = fs.get_challenge::<U>();
        current_poly = glue_polynomials(&current_poly, &basis_poly, beta);
        current_sum = glue_sums(current_sum, enforced_sum, beta);

        wtns_prev = wtns_next;
    }

    unreachable!("Should have returned in final round");
}

/// Main prover function with configurable transcript
pub fn prove_with_transcript<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
    mut fs: impl Transcript,
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    config.validate()?;

    let wtns_0 = ligero_commit(
        poly,
        config.initial_dims.0,
        config.initial_dims.1,
        &config.initial_reed_solomon,
    );
    let cm_0 = RecursiveLigeroCommitment {
        root: wtns_0.tree.get_root(),
    };
    fs.absorb_root(&cm_0.root);

    prove_core(config, poly, wtns_0, cm_0, &mut fs)
}

/// Prover with evaluation claims (sumcheck-based evaluation proofs).
///
/// Runs an evaluation sumcheck proving P(z_k) = v_k for each claim,
/// then the standard Ligerito proximity protocol. Both share the
/// Fiat-Shamir transcript — the Merkle root is absorbed before the
/// eval sumcheck, so eval challenges are transcript-bound to the
/// commitment. However, the eval sumcheck and proximity test are
/// independent protocols; full malicious-prover soundness requires
/// an evaluation opening that ties P(r) to the committed polynomial.
pub fn prove_with_evaluations<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
    claims: &[crate::eval_proof::EvalClaim<T>],
    mut fs: impl Transcript,
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    config.validate()?;

    let wtns_0 = ligero_commit(
        poly,
        config.initial_dims.0,
        config.initial_dims.1,
        &config.initial_reed_solomon,
    );
    let cm_0 = RecursiveLigeroCommitment {
        root: wtns_0.tree.get_root(),
    };
    fs.absorb_root(&cm_0.root);

    // Eval sumcheck: prove P(z_k) = v_k, transcript-bound to Merkle root
    let n = poly.len().trailing_zeros() as usize;
    let alphas: Vec<U> = (0..claims.len()).map(|_| fs.get_challenge()).collect();
    let (eval_rounds, _, _) =
        crate::eval_proof::eval_sumcheck_prove::<T, U>(poly, claims, &alphas, n, &mut fs);

    let mut proof = prove_core(config, poly, wtns_0, cm_0, &mut fs)?;
    proof.eval_rounds = eval_rounds;
    Ok(proof)
}

/// Main prover function using default Merlin transcript
pub fn prove<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    #[cfg(feature = "transcript-merlin")]
    let fs = FiatShamir::new_merlin();

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

    prove_with_transcript(config, poly, fs)
}

/// Prover function using Julia-compatible SHA256 transcript
pub fn prove_sha256<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    let fs = FiatShamir::new_sha256(1234);
    prove_with_transcript(config, poly, fs)
}

/// Prover function using BLAKE2b transcript (for Substrate runtime compatibility)
///
/// Proofs generated with this function must be verified using `verify_blake2b()`
/// or `verify_complete_blake2b()`.
#[cfg(feature = "transcript-blake2b")]
pub fn prove_blake2b<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    let fs = FiatShamir::new_blake2b();
    prove_with_transcript(config, poly, fs)
}

/// Debug version of prove with detailed logging
pub fn prove_debug<T, U>(
    config: &ProverConfig<T, U>,
    poly: &[T],
) -> crate::Result<FinalizedLigeritoProof<T, U>>
where
    T: BinaryFieldElement + Send + Sync + bytemuck::Pod + 'static,
    U: BinaryFieldElement + Send + Sync + From<T> + bytemuck::Pod + 'static,
{
    println!("\n=== PROVER DEBUG ===");

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

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

    let mut proof = LigeritoProof::<T, U>::new();

    // Initial commitment
    println!("Creating initial commitment...");
    let wtns_0 = ligero_commit(
        poly,
        config.initial_dims.0,
        config.initial_dims.1,
        &config.initial_reed_solomon,
    );
    let cm_0 = RecursiveLigeroCommitment {
        root: wtns_0.tree.get_root(),
    };
    proof.initial_ligero_cm = Some(cm_0.clone());
    fs.absorb_root(&cm_0.root);
    println!("Initial commitment root: {:?}", cm_0.root);

    // Get initial challenges
    let partial_evals_0: Vec<T> = (0..config.initial_k)
        .map(|i| {
            let challenge = fs.get_challenge();
            println!("Initial challenge {}: {:?}", i, challenge);
            challenge
        })
        .collect();

    // Partial evaluation
    println!("\nPerforming partial evaluation...");
    let mut f_evals = poly.to_vec();
    partial_eval_multilinear(&mut f_evals, &partial_evals_0);
    println!("Partial eval complete, new size: {}", f_evals.len());

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

    // First recursive step
    println!("\nFirst recursive step...");
    let wtns_1 = ligero_commit(
        &f_evals_u,
        config.dims[0].0,
        config.dims[0].1,
        &config.reed_solomon_codes[0],
    );
    let cm_1 = RecursiveLigeroCommitment {
        root: wtns_1.tree.get_root(),
    };
    proof.recursive_commitments.push(cm_1.clone());
    fs.absorb_root(&cm_1.root);

    // Query selection
    let rows = wtns_0.mat.len();
    println!("\nSelecting queries from {} rows...", rows);
    let queries = fs.get_distinct_queries(rows, config.num_queries);
    println!(
        "Selected queries (0-based): {:?}",
        &queries[..queries.len().min(5)]
    );

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

    // Prepare for sumcheck
    let n = f_evals.len().trailing_zeros() as usize;
    println!("\nPreparing sumcheck, n = {}", n);
    let sks_vks: Vec<T> = eval_sk_at_vks(1 << n);

    let opened_rows: Vec<Vec<T>> = queries.iter().map(|&q| wtns_0.mat[q].clone()).collect();

    let mtree_proof = wtns_0.tree.prove(&queries);
    proof.initial_ligero_proof = Some(RecursiveLigeroProof {
        opened_rows: opened_rows.clone(),
        merkle_proof: mtree_proof,
    });

    println!("\nInducing sumcheck polynomial...");
    let (basis_poly, enforced_sum) = induce_sumcheck_poly(
        n,
        &sks_vks,
        &opened_rows,
        &partial_evals_0_u,
        &queries,
        alpha,
    );
    println!("Enforced sum: {:?}", enforced_sum);

    let mut sumcheck_transcript = vec![];
    let mut current_poly = basis_poly;
    let mut current_sum = enforced_sum;

    // First sumcheck round absorb
    fs.absorb_elem(current_sum);

    // Process recursive rounds
    let mut wtns_prev = wtns_1;

    for i in 0..config.recursive_steps {
        println!(
            "\n--- Recursive step {}/{} ---",
            i + 1,
            config.recursive_steps
        );
        let mut rs = Vec::new();

        // Sumcheck rounds
        for j in 0..config.ks[i] {
            // Compute coefficients first (before getting challenge)
            let coeffs = compute_sumcheck_coefficients(&current_poly);
            println!("  Round {}: coeffs = {:?}", j, coeffs);
            sumcheck_transcript.push(coeffs);

            // Get challenge after providing coefficients
            let ri = fs.get_challenge::<U>();
            println!("  Challenge: {:?}", ri);
            rs.push(ri);

            // Fold polynomial with the challenge
            current_poly = fold_polynomial_with_challenge(&current_poly, ri);

            // Update sum
            current_sum = evaluate_quadratic(coeffs, ri);
            println!("  New sum: {:?}", current_sum);
            fs.absorb_elem(current_sum);
        }

        // Final round
        if i == config.recursive_steps - 1 {
            println!("\nFinal round - creating proof...");
            fs.absorb_elems(&current_poly);

            let rows = wtns_prev.mat.len();
            let queries = fs.get_distinct_queries(rows, config.num_queries);

            let opened_rows: Vec<Vec<U>> =
                queries.iter().map(|&q| wtns_prev.mat[q].clone()).collect();

            let mtree_proof = wtns_prev.tree.prove(&queries);

            proof.final_ligero_proof = Some(FinalLigeroProof {
                yr: current_poly.clone(),
                opened_rows,
                merkle_proof: mtree_proof,
            });

            proof.sumcheck_transcript = Some(SumcheckTranscript {
                transcript: sumcheck_transcript,
            });

            println!("Proof generation complete!");
            return finalize(proof);
        }

        // Continue recursion
        println!("\nContinuing recursion...");
        let wtns_next = ligero_commit(
            &current_poly,
            config.dims[i + 1].0,
            config.dims[i + 1].1,
            &config.reed_solomon_codes[i + 1],
        );

        let cm_next = RecursiveLigeroCommitment {
            root: wtns_next.tree.get_root(),
        };
        proof.recursive_commitments.push(cm_next.clone());
        fs.absorb_root(&cm_next.root);

        let rows = wtns_prev.mat.len();
        let queries = fs.get_distinct_queries(rows, config.num_queries);
        let alpha = fs.get_challenge::<U>();

        let opened_rows: Vec<Vec<U>> = queries.iter().map(|&q| wtns_prev.mat[q].clone()).collect();

        let mtree_proof = wtns_prev.tree.prove(&queries);
        proof.recursive_proofs.push(RecursiveLigeroProof {
            opened_rows: opened_rows.clone(),
            merkle_proof: mtree_proof,
        });

        // Update for next round
        let n = current_poly.len().trailing_zeros() as usize;
        let sks_vks: Vec<U> = eval_sk_at_vks(1 << n);

        println!("\nInducing next sumcheck polynomial...");
        let (basis_poly, enforced_sum) =
            induce_sumcheck_poly(n, &sks_vks, &opened_rows, &rs, &queries, alpha);
        println!("Next enforced sum: {:?}", enforced_sum);

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

        // Glue polynomials
        let beta = fs.get_challenge::<U>();
        println!("Beta challenge: {:?}", beta);
        current_poly = glue_polynomials(&current_poly, &basis_poly, beta);
        current_sum = glue_sums(current_sum, enforced_sum, beta);
        println!("Updated current sum: {:?}", current_sum);

        wtns_prev = wtns_next;
    }

    unreachable!("Should have returned in final round");
}

// Helper functions

fn compute_sumcheck_coefficients<F: BinaryFieldElement>(poly: &[F]) -> (F, F, F) {
    let n = poly.len() / 2;

    let mut s0 = F::zero();
    let mut s1 = F::zero();
    let mut s2 = F::zero();

    for i in 0..n {
        let p0 = poly[2 * i];
        let p1 = poly[2 * i + 1];

        s0 = s0.add(&p0);
        s1 = s1.add(&p0.add(&p1));
        s2 = s2.add(&p1);
    }

    (s0, s1, s2)
}

fn fold_polynomial_with_challenge<F: BinaryFieldElement>(poly: &[F], r: F) -> Vec<F> {
    let n = poly.len() / 2;
    let mut new_poly = vec![F::zero(); n];

    for i in 0..n {
        let p0 = poly[2 * i];
        let p1 = poly[2 * i + 1];
        new_poly[i] = p0.add(&r.mul(&p1.add(&p0)));
    }

    new_poly
}

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))
}

fn glue_polynomials<F: BinaryFieldElement>(f: &[F], g: &[F], beta: F) -> Vec<F> {
    assert_eq!(f.len(), g.len());

    f.iter()
        .zip(g.iter())
        .map(|(&fi, &gi)| fi.add(&beta.mul(&gi)))
        .collect()
}

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

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

    #[test]
    fn test_evaluate_quadratic() {
        // for binary field sumcheck, we use linear polynomials: f(x) = s0 + s1*x
        // where s1 = s0 + s2, so f(0) = s0 and f(1) = s0 + s1 = s2
        let coeffs = (
            BinaryElem32::from(1), // s0
            BinaryElem32::from(3), // s1 = s0 + s2
            BinaryElem32::from(2), // s2
        );

        // test at x = 0: f(0) = s0
        let val0 = evaluate_quadratic(coeffs, BinaryElem32::zero());
        assert_eq!(val0, BinaryElem32::from(1));

        // test at x = 1: f(1) = s0 + s1*1 = s0 + s1
        let val1 = evaluate_quadratic(coeffs, BinaryElem32::one());
        // in binary field: 1 XOR 3 = 2
        assert_eq!(val1, BinaryElem32::from(2));
    }

    #[test]
    fn test_glue_polynomials() {
        let f = vec![BinaryElem32::from(1), BinaryElem32::from(2)];
        let g = vec![BinaryElem32::from(3), BinaryElem32::from(4)];
        let beta = BinaryElem32::from(5);

        let result = glue_polynomials(&f, &g, beta);

        assert_eq!(result.len(), 2);
        assert_eq!(
            result[0],
            BinaryElem32::from(1).add(&beta.mul(&BinaryElem32::from(3)))
        );
        assert_eq!(
            result[1],
            BinaryElem32::from(2).add(&beta.mul(&BinaryElem32::from(4)))
        );
    }

    #[test]
    fn test_simple_prove() {
        let config = hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);

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

        // This should not panic
        let proof = prove(&config, &poly);
        assert!(proof.is_ok(), "Simple proof generation should succeed");
    }

    #[test]
    fn test_sumcheck_consistency_in_prover() {
        let config = hardcoded_config_12(PhantomData::<BinaryElem32>, PhantomData::<BinaryElem128>);

        let poly = vec![BinaryElem32::zero(); 1 << 12];
        let proof = prove(&config, &poly);
        assert!(proof.is_ok(), "Zero polynomial proof should succeed");

        let mut poly = vec![BinaryElem32::zero(); 1 << 12];
        poly[0] = BinaryElem32::one();
        poly[1] = BinaryElem32::from(2);
        let proof = prove(&config, &poly);
        assert!(proof.is_ok(), "Simple pattern proof should succeed");
    }

    #[test]
    fn test_prove_with_evaluations() {
        use crate::eval_proof::EvalClaim;

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

        // polynomial with known values
        let mut poly = vec![BinaryElem32::zero(); 1 << 12];
        poly[0] = BinaryElem32::from(42);
        poly[7] = BinaryElem32::from(99);
        poly[100] = BinaryElem32::from(255);

        // claim: P(0) = 42, P(7) = 99, P(100) = 255
        let claims = vec![
            EvalClaim {
                index: 0,
                value: BinaryElem32::from(42),
            },
            EvalClaim {
                index: 7,
                value: BinaryElem32::from(99),
            },
            EvalClaim {
                index: 100,
                value: BinaryElem32::from(255),
            },
        ];

        // prove
        let fs = FiatShamir::new_sha256(0);
        let proof = prove_with_evaluations(&config, &poly, &claims, fs);
        assert!(proof.is_ok(), "prove_with_evaluations should succeed");
        let proof = proof.unwrap();
        assert_eq!(
            proof.eval_rounds.len(),
            12,
            "should have 12 eval sumcheck rounds for 2^12 poly"
        );

        // verify
        let fs = FiatShamir::new_sha256(0);
        let result = crate::verifier::verify_with_evaluations::<BinaryElem32, BinaryElem128>(
            &verifier_config,
            &proof,
            &claims,
            fs,
        );
        assert!(result.is_ok(), "verify_with_evaluations should not error");
        let result = result.unwrap();
        assert!(result.is_some(), "eval sumcheck should pass");
        let result = result.unwrap();
        assert!(result.proximity_valid, "proximity test should pass");
    }

    #[test]
    fn test_prove_with_evaluations_wrong_claim_fails() {
        use crate::eval_proof::EvalClaim;

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

        let mut poly = vec![BinaryElem32::zero(); 1 << 12];
        poly[5] = BinaryElem32::from(77);

        // wrong claim: P(5) = 88 (actual is 77)
        let claims = vec![EvalClaim {
            index: 5,
            value: BinaryElem32::from(88),
        }];

        // prove (prover uses actual polynomial, eval sumcheck computes from actual values)
        let fs = FiatShamir::new_sha256(0);
        let proof = prove_with_evaluations(&config, &poly, &claims, fs).unwrap();

        // verify with wrong claim — eval sumcheck should fail
        let fs = FiatShamir::new_sha256(0);
        let result = crate::verifier::verify_with_evaluations::<BinaryElem32, BinaryElem128>(
            &verifier_config,
            &proof,
            &claims,
            fs,
        )
        .unwrap();

        // the eval sumcheck should reject because target (α·88) ≠ actual sum (α·77)
        assert!(
            result.is_none(),
            "wrong eval claim should fail verification"
        );
    }
}