-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprover.rs
More file actions
2236 lines (2023 loc) · 90 KB
/
Copy pathprover.rs
File metadata and controls
2236 lines (2023 loc) · 90 KB
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
use std::marker::PhantomData;
use std::sync::Arc;
#[cfg(feature = "instruments")]
use std::time::Instant;
use crypto::fiat_shamir::is_transcript::IsStarkTranscript;
use crypto::merkle_tree::traits::IsMerkleTreeBackend;
use math::fft::cpu::bit_reversing::{in_place_bit_reverse_permute, reverse_index};
use math::fft::cpu::bowers_fft::LayerTwiddles;
use math::fft::errors::FFTError;
use log::info;
use math::field::traits::{IsField, IsSubFieldOf};
use math::traits::AsBytes;
use math::{
field::{element::FieldElement, traits::IsFFTField},
polynomial::Polynomial,
};
#[cfg(feature = "parallel")]
use rayon::prelude::{
IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator,
IntoParallelRefMutIterator, ParallelIterator,
};
#[cfg(feature = "debug-checks")]
use crate::debug::validate_trace;
use crate::domain::new_domain;
use crate::fri;
use crate::lookup::LOGUP_NUM_CHALLENGES;
use crate::proof::stark::{DeepPolynomialOpenings, PolynomialOpenings};
use crate::table::Table;
use crate::trace::LDETraceTable;
use super::config::{BatchedMerkleTree, BatchedMerkleTreeBackend, Commitment};
use super::constraints::evaluator::ConstraintEvaluator;
use super::domain::Domain;
use super::fri::fri_decommit::FriDecommitment;
use super::grinding;
use super::lookup::BusPublicInputs;
use super::proof::stark::{DeepPolynomialOpening, MultiProof, StarkProof};
use super::trace::TraceTable;
use super::traits::AIR;
/// A triple of (AIR, TraceTable, PublicInputs) for proving.
type AirTracePair<'a, Field, FieldExtension, PI> = (
&'a dyn AIR<Field = Field, FieldExtension = FieldExtension, PublicInputs = PI>,
&'a mut TraceTable<Field, FieldExtension>,
&'a PI,
);
/// A default STARK prover implementing `IsStarkProver`.
pub struct Prover<
Field: IsSubFieldOf<FieldExtension> + IsFFTField + Send + Sync,
FieldExtension: Send + Sync + IsField,
PI,
> {
p: PhantomData<(Field, FieldExtension, PI)>,
}
impl<
Field: IsSubFieldOf<FieldExtension> + IsFFTField + Send + Sync,
FieldExtension: Send + Sync + IsField,
PI,
> IsStarkProver<Field, FieldExtension, PI> for Prover<Field, FieldExtension, PI>
{
}
#[derive(Debug)]
pub enum ProvingError {
WrongParameter(String),
EmptyCommitment,
}
/// A container for the intermediate results of the commitments to a trace table, main or auxiliary in case of RAP,
/// in the first round of the STARK Prove protocol.
pub struct Round1CommitmentData<F>
where
F: IsField,
FieldElement<F>: AsBytes,
{
/// The Merkle trees constructed to obtain the commitment of the entire trace table.
/// For preprocessed tables, this contains only the multiplicity columns.
/// Wrapped in Arc to share with Round1Metadata without deep-cloning (~64MB per table).
pub(crate) lde_trace_merkle_tree: Arc<BatchedMerkleTree<F>>,
/// The root of the Merkle tree in `lde_trace_merkle_tree`.
pub(crate) lde_trace_merkle_root: Commitment,
/// For preprocessed tables: Merkle tree over precomputed columns only.
pub(crate) precomputed_merkle_tree: Option<Arc<BatchedMerkleTree<F>>>,
/// For preprocessed tables: root of the precomputed Merkle tree.
pub(crate) precomputed_merkle_root: Option<Commitment>,
/// For preprocessed tables: number of precomputed columns (for splitting during opening).
pub(crate) num_precomputed_cols: usize,
}
/// A container for the results of the first round of the STARK Prove protocol.
pub struct Round1<Field, FieldExtension>
where
Field: IsSubFieldOf<FieldExtension> + IsFFTField,
FieldExtension: IsField,
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
/// The table of evaluations over the LDE of the main and auxiliary trace tables.
pub(crate) lde_trace: LDETraceTable<Field, FieldExtension>,
/// The intermediate results of the commitment to the main trace table.
pub(crate) main: Round1CommitmentData<Field>,
/// The intermediate results of the commitment to the auxiliary trace table in case of RAP.
pub(crate) aux: Option<Round1CommitmentData<FieldExtension>>,
/// The challenges of the RAP round.
pub(crate) rap_challenges: Vec<FieldElement<FieldExtension>>,
/// Bus interaction public inputs (initial and final aux column values).
pub(crate) bus_public_inputs: Option<BusPublicInputs<FieldExtension>>,
}
/// Intermediate results from committing a main trace in Phase A of sequential proving.
/// Holds the Merkle tree/root for the main trace and optionally for precomputed columns.
struct MainCommitData<Field: IsFFTField>
where
FieldElement<Field>: AsBytes,
{
main_tree: Arc<BatchedMerkleTree<Field>>,
main_root: Commitment,
precomputed_tree: Option<Arc<BatchedMerkleTree<Field>>>,
precomputed_root: Option<Commitment>,
num_precomputed_cols: usize,
}
/// Metadata from Round 1 commitments — stores Merkle trees and roots, but not LDE evaluations.
/// LDE evaluations are recomputed from the trace in Rounds 2-4; Merkle trees are retained
/// to avoid expensive Keccak re-hashing.
pub struct Round1Metadata<Field, FieldExtension>
where
Field: IsFFTField + IsSubFieldOf<FieldExtension>,
FieldExtension: IsField,
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
/// Merkle tree of the main trace (multiplicities for preprocessed tables).
/// Wrapped in Arc to share with Round1CommitmentData without deep-cloning.
main_merkle_tree: Arc<BatchedMerkleTree<Field>>,
/// Root of the main trace Merkle tree.
main_merkle_root: Commitment,
/// For preprocessed tables: Merkle tree over precomputed columns.
precomputed_merkle_tree: Option<Arc<BatchedMerkleTree<Field>>>,
/// For preprocessed tables: root of the precomputed Merkle tree.
precomputed_merkle_root: Option<Commitment>,
/// For preprocessed tables: number of precomputed columns.
num_precomputed_cols: usize,
/// Merkle tree of the auxiliary trace (None if no aux trace).
aux_merkle_tree: Option<Arc<BatchedMerkleTree<FieldExtension>>>,
/// Root of the auxiliary trace Merkle tree (None if no aux trace).
aux_merkle_root: Option<Commitment>,
/// The RAP challenges used for auxiliary trace construction.
rap_challenges: Vec<FieldElement<FieldExtension>>,
/// Bus interaction public inputs (initial and final aux column values).
bus_public_inputs: Option<BusPublicInputs<FieldExtension>>,
}
/// Pre-computed twiddle factors and coset weights for a given domain size.
///
/// Shared across all columns of the same table, and across all phases (A, C, Rounds 2-4)
/// in sequential proving. This eliminates redundant root-of-unity generation:
/// many redundant `get_twiddles` calls reduced to one pair per distinct domain.
///
/// The `coset_weights` vector stores `[n_inv, n_inv*g, n_inv*g², ..., n_inv*g^{n-1}]`
/// where `g` is the coset offset and `n_inv = 1/n`. These are used in the iFFT+coset-shift
/// step of `expand_pool_to_lde`.
pub struct LdeTwiddles<F: IsFFTField> {
inv: LayerTwiddles<F>,
fwd: LayerTwiddles<F>,
coset_weights: Vec<FieldElement<F>>,
}
impl<F: IsFFTField> LdeTwiddles<F> {
/// Construct twiddles and coset weights for a domain of the given size and blowup factor.
fn new(domain: &Domain<F>) -> Self {
let domain_size = domain.interpolation_domain_size;
let lde_size = domain_size * domain.blowup_factor;
let domain_size_inv = FieldElement::<F>::from(domain_size as u64)
.inv()
.expect("domain_size is power of two");
let offset = &domain.coset_offset;
let coset_weights = {
let mut w = Vec::with_capacity(domain_size);
let mut offset_power = domain_size_inv;
for _ in 0..domain_size {
w.push(offset_power.clone());
offset_power = offset * &offset_power;
}
w
};
Self {
inv: LayerTwiddles::<F>::new_inverse(domain_size.trailing_zeros() as u64)
.expect("valid inverse twiddles"),
fwd: LayerTwiddles::<F>::new(lde_size.trailing_zeros() as u64)
.expect("valid forward twiddles"),
coset_weights,
}
}
}
/// Number of tables to process concurrently in `multi_prove`.
/// Default: num_cores / 3 (benchmarked optimal on both M3 Pro and EPYC 9454P).
/// Override with `TABLE_PARALLELISM` env var.
fn table_parallelism() -> usize {
#[cfg(feature = "parallel")]
{
std::env::var("TABLE_PARALLELISM")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or_else(|| {
let cores = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
(cores / 3).max(1)
})
}
#[cfg(not(feature = "parallel"))]
{
1
}
}
/// A set of LDE column buffer pools for one concurrent table slot.
struct PoolSet<F: IsField, E: IsField> {
main: Vec<Vec<FieldElement<F>>>,
aux: Vec<Vec<FieldElement<E>>>,
}
/// A container for the results of the second round of the STARK Prove protocol.
pub struct Round2<F>
where
F: IsField,
FieldElement<F>: AsBytes,
{
/// Evaluations of the composition polynomial parts over the LDE domain.
pub(crate) lde_composition_poly_evaluations: Vec<Vec<FieldElement<F>>>,
/// The Merkle tree built to compute the commitment to the composition polynomial parts.
pub(crate) composition_poly_merkle_tree: BatchedMerkleTree<F>,
/// The commitment to the composition polynomial parts.
pub(crate) composition_poly_root: Commitment,
}
/// A container for the results of the third round of the STARK Prove protocol.
pub struct Round3<F: IsField> {
/// Evaluations of the trace polynomials, main ans auxiliary, at the out-of-domain challenge.
trace_ood_evaluations: Table<F>,
/// Evaluations of the composition polynomial parts at the out-of-domain challenge.
composition_poly_parts_ood_evaluation: Vec<FieldElement<F>>,
}
/// A container for the results of the fourth round of the STARK Prove protocol.
pub struct Round4<F: IsSubFieldOf<E>, E: IsField> {
/// The final value resulting from folding the Deep composition polynomial all the way down to a constant value.
fri_last_value: FieldElement<E>,
/// The commitments to the fold polynomials of the inner layers of FRI.
fri_layers_merkle_roots: Vec<Commitment>,
/// The values and proofs of validity of the evaluations of the trace polynomials and the composition polynomials
/// parts at the domain values corresponding to the FRI query challenges and their symmetric counterparts.
deep_poly_openings: DeepPolynomialOpenings<F, E>,
/// The values and proofs of validity of the evaluations of the fold polynomials of the inner
/// layers of FRI at the values corresponding to the symmetrics of the FRI query challenges.
query_list: Vec<FriDecommitment<E>>,
/// The proof of work nonce.
nonce: Option<u64>,
}
/// Returns the evaluations of the polynomial `p` over the lde domain defined by the given
/// `blowup_factor`, `domain_size` and `offset`. The number of evaluations returned is `domain_size
/// * blowup_factor`. The domain generator used is the one given by the implementation of `F` as `IsFFTField`.
pub fn evaluate_polynomial_on_lde_domain<F, E>(
p: &Polynomial<FieldElement<E>>,
blowup_factor: usize,
domain_size: usize,
offset: &FieldElement<F>,
) -> Result<Vec<FieldElement<E>>, FFTError>
where
F: IsFFTField + IsSubFieldOf<E>,
E: IsField + Send + Sync,
{
let evaluations = Polynomial::evaluate_offset_fft(p, blowup_factor, Some(domain_size), offset)?;
let step = evaluations.len() / (domain_size * blowup_factor);
match step {
1 => Ok(evaluations),
_ => Ok(evaluations.into_iter().step_by(step).collect()),
}
}
/// The functionality of a STARK prover providing methods to run the STARK Prove protocol
/// https://lambdaclass.github.io/lambdaworks/starks/protocol.html
/// The default implementation is complete and is compatible with Stone prover
/// https://github.com/starkware-libs/stone-prover
pub trait IsStarkProver<
Field: IsSubFieldOf<FieldExtension> + IsFFTField + Send + Sync,
FieldExtension: Send + Sync + IsField,
PI,
>
{
/// Returns the Merkle tree and the commitment to the vectors `vectors`.
fn batch_commit_extension(
vectors: &[Vec<FieldElement<FieldExtension>>],
) -> Option<(BatchedMerkleTree<FieldExtension>, Commitment)>
where
FieldElement<Field>: AsBytes + Sync + Send,
FieldElement<FieldExtension>: AsBytes + Sync + Send,
{
let tree = BatchedMerkleTree::build(vectors)?;
let commitment = tree.root;
Some((tree, commitment))
}
/// Builds a Merkle tree commitment from column-major LDE evaluations with
/// bit-reverse permutation, without cloning the full evaluation matrix.
///
/// For each row index `i`, we hash `col_0[br(i)] || col_1[br(i)] || ...`
/// where `br(i)` is the bit-reversal of `i`. This produces the same Merkle
/// tree as the old clone + bit-reverse + columns2rows + batch_commit flow,
/// but avoids allocating the cloned and transposed matrices entirely.
fn commit_columns_bit_reversed<E>(
columns: &[Vec<FieldElement<E>>],
) -> Option<(BatchedMerkleTree<E>, Commitment)>
where
FieldElement<E>: AsBytes + Sync + Send,
E: IsField,
{
if columns.is_empty() || columns[0].is_empty() {
return None;
}
let num_rows = columns[0].len();
let num_cols = columns.len();
#[cfg(feature = "parallel")]
let hashed_leaves: Vec<Commitment> = {
(0..num_rows)
.into_par_iter()
.map_init(
|| vec![FieldElement::<E>::zero(); num_cols],
|row_buf, row_idx| {
let br_idx = reverse_index(row_idx, num_rows as u64);
for col_idx in 0..num_cols {
row_buf[col_idx] = columns[col_idx][br_idx].clone();
}
BatchedMerkleTreeBackend::<E>::hash_data(&*row_buf)
},
)
.collect()
};
#[cfg(not(feature = "parallel"))]
let hashed_leaves: Vec<Commitment> = {
let mut row_buf = vec![FieldElement::<E>::zero(); num_cols];
(0..num_rows)
.map(|row_idx| {
let br_idx = reverse_index(row_idx, num_rows as u64);
for col_idx in 0..num_cols {
row_buf[col_idx] = columns[col_idx][br_idx].clone();
}
BatchedMerkleTreeBackend::<E>::hash_data(&row_buf)
})
.collect()
};
let tree = BatchedMerkleTree::<E>::build_from_hashed_leaves(hashed_leaves)?;
let root = tree.root;
Some((tree, root))
}
/// Compute the LDE commitment for a subset of columns from a trace (for testing).
///
/// This helper computes the same commitment the prover generates internally,
/// useful for setting up soundness test scenarios.
fn compute_precomputed_commitment_for_testing(
trace: &TraceTable<Field, FieldExtension>,
air: &impl AIR<Field = Field, FieldExtension = FieldExtension, PublicInputs = PI>,
num_precomputed_cols: usize,
) -> Option<Commitment>
where
FieldElement<Field>: AsBytes + Sync + Send,
FieldElement<FieldExtension>: AsBytes + Sync + Send,
{
let domain = Domain::new(air, trace.num_rows());
let columns = trace.columns_main();
let precomputed: Vec<_> = columns.into_iter().take(num_precomputed_cols).collect();
let twiddles = LdeTwiddles::new(&domain);
let evals =
Self::compute_lde_from_columns_cached::<Field>(&precomputed, &domain, &twiddles);
let (_, commitment) = Self::commit_columns_bit_reversed(&evals)?;
Some(commitment)
}
/// Compute LDE evaluations with pre-computed twiddle factors and coset weights.
///
/// Accepts shared [`LdeTwiddles`] to avoid redundant twiddle generation and weight
/// computation across phases (A, C, Rounds 2-4).
fn compute_lde_from_columns_cached<E>(
columns: &[Vec<FieldElement<E>>],
domain: &Domain<Field>,
twiddles: &LdeTwiddles<Field>,
) -> Vec<Vec<FieldElement<E>>>
where
E: IsSubFieldOf<FieldExtension> + Send + Sync,
Field: IsSubFieldOf<E>,
FieldElement<E>: Send + Sync,
{
if columns.is_empty() {
return Vec::new();
}
#[cfg(not(feature = "parallel"))]
let columns_iter = columns.iter();
#[cfg(feature = "parallel")]
let columns_iter = columns.par_iter();
columns_iter
.map(|col| {
Polynomial::coset_lde_full::<Field>(
col,
domain.blowup_factor,
&twiddles.coset_weights,
&twiddles.inv,
&twiddles.fwd,
)
})
.collect::<Result<Vec<Vec<FieldElement<E>>>, _>>()
.expect("coset LDE computation")
}
/// Expand pool buffers in-place from N column evaluations to N×blowup LDE evaluations.
///
/// The pool buffers already contain column data extracted via `extract_columns_*_into`.
/// This performs iFFT + coset shift + FFT in-place, eliminating the T1 transpose copy.
/// Coset weights are pre-cached in `LdeTwiddles` to avoid recomputation across phases.
fn expand_pool_to_lde<E>(
pool: &mut [Vec<FieldElement<E>>],
num_cols: usize,
domain: &Domain<Field>,
twiddles: &LdeTwiddles<Field>,
) where
Field: IsSubFieldOf<E>,
E: IsSubFieldOf<FieldExtension> + IsField + Send + Sync,
FieldElement<E>: Send + Sync,
{
if num_cols == 0 {
return;
}
#[cfg(feature = "parallel")]
let iter = pool[..num_cols].par_iter_mut();
#[cfg(not(feature = "parallel"))]
let iter = pool[..num_cols].iter_mut();
iter.for_each(|buf| {
Polynomial::coset_lde_full_expand::<Field>(
buf,
domain.blowup_factor,
&twiddles.coset_weights,
&twiddles.inv,
&twiddles.fwd,
)
.expect("coset LDE expansion");
});
}
/// Compute main LDE, commit, return tree and root.
/// Uses the provided pool buffers to avoid allocation; the pool retains capacity for reuse.
#[allow(clippy::type_complexity)]
fn commit_main_trace(
trace: &TraceTable<Field, FieldExtension>,
domain: &Domain<Field>,
twiddles: &LdeTwiddles<Field>,
main_pool: &mut [Vec<FieldElement<Field>>],
) -> Result<
(
BatchedMerkleTree<Field>,
Commitment,
Option<BatchedMerkleTree<Field>>,
Option<Commitment>,
usize,
),
ProvingError,
>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
let num_cols = trace.num_main_columns;
trace.extract_columns_main_into(main_pool);
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
Self::expand_pool_to_lde::<Field>(main_pool, num_cols, domain, twiddles);
#[cfg(feature = "instruments")]
let main_lde_dur = t_sub.elapsed();
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
let (tree, root) = Self::commit_columns_bit_reversed(&main_pool[..num_cols])
.ok_or(ProvingError::EmptyCommitment)?;
#[cfg(feature = "instruments")]
crate::instruments::accum_r1_main(main_lde_dur, t_sub.elapsed());
// Pool buffers retain capacity; tree is returned to caller
Ok((tree, root, None, None, 0))
}
/// Commit preprocessed trace: precomputed and multiplicity columns get separate trees.
/// Uses pool buffers to avoid allocation.
#[allow(clippy::type_complexity)]
fn commit_preprocessed_trace(
trace: &TraceTable<Field, FieldExtension>,
domain: &Domain<Field>,
precomputed_commitment: Commitment,
num_precomputed_cols: usize,
twiddles: &LdeTwiddles<Field>,
main_pool: &mut [Vec<FieldElement<Field>>],
) -> Result<
(
BatchedMerkleTree<Field>,
Commitment,
Option<BatchedMerkleTree<Field>>,
Option<Commitment>,
usize,
),
ProvingError,
>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
let num_cols = trace.num_main_columns;
trace.extract_columns_main_into(main_pool);
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
Self::expand_pool_to_lde::<Field>(main_pool, num_cols, domain, twiddles);
#[cfg(feature = "instruments")]
let main_lde_dur = t_sub.elapsed();
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
let (precomputed_tree, precomputed_root) =
Self::commit_columns_bit_reversed(&main_pool[..num_precomputed_cols])
.ok_or(ProvingError::EmptyCommitment)?;
let (mult_tree, mult_root) =
Self::commit_columns_bit_reversed(&main_pool[num_precomputed_cols..num_cols])
.ok_or(ProvingError::EmptyCommitment)?;
#[cfg(feature = "instruments")]
crate::instruments::accum_r1_main(main_lde_dur, t_sub.elapsed());
debug_assert_eq!(
precomputed_root, precomputed_commitment,
"Prover's precomputed commitment doesn't match hardcoded AIR commitment"
);
// Pool buffers retain capacity; trees are returned to caller
Ok((
mult_tree,
mult_root,
Some(precomputed_tree),
Some(precomputed_root),
num_precomputed_cols,
))
}
/// Reconstruct a full Round1 struct by recomputing LDE evaluations and using
/// the stored Merkle trees from metadata. Uses pool buffers to avoid allocation.
///
/// The Merkle trees were already built during Phase A/C and are reused here,
/// eliminating redundant Keccak hashing.
fn reconstruct_round1(
air: &dyn AIR<Field = Field, FieldExtension = FieldExtension, PublicInputs = PI>,
trace: &TraceTable<Field, FieldExtension>,
domain: &Domain<Field>,
metadata: &Round1Metadata<Field, FieldExtension>,
twiddles: &LdeTwiddles<Field>,
main_pool: &mut [Vec<FieldElement<Field>>],
aux_pool: &mut [Vec<FieldElement<FieldExtension>>],
) -> Result<Round1<Field, FieldExtension>, ProvingError>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
// Recompute main LDE into pool buffers (extract columns directly, no T1 transpose)
let num_main_cols = trace.num_main_columns;
trace.extract_columns_main_into(main_pool);
Self::expand_pool_to_lde::<Field>(main_pool, num_main_cols, domain, twiddles);
// Use stored Merkle trees from Phase A/C via Arc (pointer copy, no deep clone)
let main = Round1CommitmentData::<Field> {
lde_trace_merkle_tree: Arc::clone(&metadata.main_merkle_tree),
lde_trace_merkle_root: metadata.main_merkle_root,
precomputed_merkle_tree: metadata.precomputed_merkle_tree.as_ref().map(Arc::clone),
precomputed_merkle_root: metadata.precomputed_merkle_root,
num_precomputed_cols: metadata.num_precomputed_cols,
};
// Recompute aux LDE into pool buffers, use stored aux Merkle tree
let (aux, num_aux_cols) = if air.has_aux_trace() {
let n_aux = trace.num_aux_columns;
trace.extract_columns_aux_into(aux_pool);
Self::expand_pool_to_lde::<FieldExtension>(aux_pool, n_aux, domain, twiddles);
// Safe: has_aux_trace() is true only when Phase C stored aux tree/root
let aux_commitment = Round1CommitmentData::<FieldExtension> {
lde_trace_merkle_tree: Arc::clone(
metadata
.aux_merkle_tree
.as_ref()
.expect("aux tree must exist when has_trace_interaction"),
),
lde_trace_merkle_root: metadata
.aux_merkle_root
.expect("aux root must exist when has_trace_interaction"),
precomputed_merkle_tree: None,
precomputed_merkle_root: None,
num_precomputed_cols: 0,
};
(Some(aux_commitment), n_aux)
} else {
(None, 0)
};
// Take column Vecs from pool (zero-copy move) instead of cloning.
// After prove_rounds_2_to_4, columns are returned to the pool via into_columns.
let main_cols: Vec<_> = main_pool[..num_main_cols]
.iter_mut()
.map(std::mem::take)
.collect();
let aux_cols: Vec<_> = aux_pool[..num_aux_cols]
.iter_mut()
.map(std::mem::take)
.collect();
let lde_trace =
LDETraceTable::from_columns(main_cols, aux_cols, air.step_size(), domain.blowup_factor);
Ok(Round1 {
lde_trace,
main,
aux,
rap_challenges: metadata.rap_challenges.clone(),
bus_public_inputs: metadata.bus_public_inputs.clone(),
})
}
/// Reconstruct Round1 for every table, print the bus balance report, and
/// validate each trace. Called once after Phase C commits.
#[cfg(feature = "debug-checks")]
fn run_debug_checks(
air_trace_pairs: &[AirTracePair<'_, Field, FieldExtension, PI>],
metadatas: &[Round1Metadata<Field, FieldExtension>],
domains: &[Domain<Field>],
twiddle_caches: &[Arc<LdeTwiddles<Field>>],
main_pool: &mut [Vec<FieldElement<Field>>],
aux_pool: &mut [Vec<FieldElement<FieldExtension>>],
) where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
PI: Send + Sync + Clone,
{
let mut temp_results: Vec<Round1<Field, FieldExtension>> =
Vec::with_capacity(air_trace_pairs.len());
for (((air, trace, _), metadata), (domain, twiddles)) in air_trace_pairs
.iter()
.zip(metadatas.iter())
.zip(domains.iter().zip(twiddle_caches.iter()))
{
let result = Self::reconstruct_round1(
*air,
*trace,
domain,
metadata,
&**twiddles,
main_pool,
aux_pool,
)
.expect("reconstruct_round1 failed in debug-checks");
temp_results.push(result);
}
let all_bus_public_inputs: Vec<Option<BusPublicInputs<FieldExtension>>> = temp_results
.iter()
.map(|r| r.bus_public_inputs.clone())
.collect();
print_bus_balance_report(&all_bus_public_inputs);
for (((air, trace, pub_inputs), round_1_result), domain) in air_trace_pairs
.iter()
.zip(temp_results.iter())
.zip(domains.iter())
{
validate_trace(
*air,
*pub_inputs,
*trace,
domain,
&round_1_result.rap_challenges,
round_1_result.bus_public_inputs.as_ref(),
);
}
}
/// Returns the Merkle tree and the commitment to the evaluations of the parts of the
/// composition polynomial.
fn commit_composition_polynomial(
lde_composition_poly_parts_evaluations: &[Vec<FieldElement<FieldExtension>>],
) -> Option<(BatchedMerkleTree<FieldExtension>, Commitment)>
where
FieldElement<Field>: AsBytes + Sync + Send,
FieldElement<FieldExtension>: AsBytes + Sync + Send,
{
let num_parts = lde_composition_poly_parts_evaluations.len();
if num_parts == 0 {
return None;
}
let num_rows = lde_composition_poly_parts_evaluations[0].len();
if num_rows == 0 {
return None;
}
let num_leaves = num_rows / 2;
debug_assert!(
num_rows.is_power_of_two(),
"num_rows must be a power of two for reverse_index to be correct"
);
debug_assert!(
num_rows.is_power_of_two(),
"num_rows must be a power of two for reverse_index"
);
// Skip the transpose + merge by computing leaf data inline.
// Each leaf = row_pair[2*i] ++ row_pair[2*i+1] after bit-reverse.
// Build the merged leaf data and hash in one pass.
#[cfg(feature = "parallel")]
let iter = (0..num_leaves).into_par_iter();
#[cfg(not(feature = "parallel"))]
let iter = 0..num_leaves;
let hashed_leaves: Vec<Commitment> = iter
.map(|leaf_idx| {
let br_0 = reverse_index(2 * leaf_idx, num_rows as u64);
let br_1 = reverse_index(2 * leaf_idx + 1, num_rows as u64);
let mut leaf = Vec::with_capacity(2 * num_parts);
for part in lde_composition_poly_parts_evaluations.iter() {
leaf.push(part[br_0].clone());
}
for part in lde_composition_poly_parts_evaluations.iter() {
leaf.push(part[br_1].clone());
}
BatchedMerkleTreeBackend::<FieldExtension>::hash_data(&leaf)
})
.collect();
let tree = BatchedMerkleTree::<FieldExtension>::build_from_hashed_leaves(hashed_leaves)?;
let root = tree.root;
Some((tree, root))
}
/// Algebraically decompose H(x) = H₀(x²) + x·H₁(x²) on the LDE coset, then
/// extend each half to the full LDE domain. This replaces the expensive
/// iFFT(2N) + break_in_parts + FFT(2N)×2 pipeline with:
/// O(N) pointwise ops + iFFT(N)×2 + FFT(2N)×2
///
/// The identity used:
/// H₀(x²) = (H(x) + H(-x)) / 2
/// H₁(x²) = (H(x) - H(-x)) / (2x)
///
/// On the LDE coset {g·ω^i | i=0..2N-1}, we have -g·ω^i = g·ω^{i+N}
/// since ω^N = -1 for a 2N-th root of unity ω.
fn decompose_and_extend_d2(
constraint_evaluations: &[FieldElement<FieldExtension>],
domain: &Domain<Field>,
) -> Vec<Vec<FieldElement<FieldExtension>>>
where
FieldElement<Field>: AsBytes + Sync + Send,
FieldElement<FieldExtension>: AsBytes + Sync + Send,
{
let two_n = constraint_evaluations.len();
let n = two_n / 2;
debug_assert_eq!(two_n, n * 2);
// Step 1: Compute 1/(2·g·ω^i) for i=0..N-1 via batch inversion.
// The LDE coset points are g·ω^i = domain.lde_roots_of_unity_coset[i].
// Compute entirely in base field — mixed F×E multiplication when used with extension values.
let two_base = FieldElement::<Field>::from(2u64);
let mut inv_2x: Vec<FieldElement<Field>> = (0..n)
.map(|i| &two_base * &domain.lde_roots_of_unity_coset[i])
.collect();
FieldElement::inplace_batch_inverse(&mut inv_2x).expect("Coset points are non-zero");
// Step 2: Pointwise decomposition.
// H₀((g·ω^i)²) = (evals[i] + evals[i+N]) / 2
// H₁((g·ω^i)²) = (evals[i] - evals[i+N]) / (2·g·ω^i)
let two_inv = two_base.inv().expect("2 is non-zero in the field");
let (h0_evals, h1_evals) = {
#[cfg(feature = "parallel")]
{
let (h0, h1): (Vec<_>, Vec<_>) = (0..n)
.into_par_iter()
.map(|i| {
let sum = &constraint_evaluations[i] + &constraint_evaluations[i + n];
let diff = &constraint_evaluations[i] - &constraint_evaluations[i + n];
// F × E → E (base field scalar on left for mixed multiplication)
(&two_inv * &sum, &inv_2x[i] * &diff)
})
.unzip();
(h0, h1)
}
#[cfg(not(feature = "parallel"))]
{
let mut h0 = Vec::with_capacity(n);
let mut h1 = Vec::with_capacity(n);
for i in 0..n {
let sum = &constraint_evaluations[i] + &constraint_evaluations[i + n];
let diff = &constraint_evaluations[i] - &constraint_evaluations[i + n];
h0.push(&two_inv * &sum);
h1.push(&inv_2x[i] * &diff);
}
(h0, h1)
}
};
// Step 3: Extend each part from N evals on g²-coset to 2N evals on g-coset.
// The squared coset offset is g² (= coset_offset²).
let coset_offset_squared = &domain.coset_offset * &domain.coset_offset;
#[cfg(feature = "parallel")]
let (lde_h0, lde_h1) = rayon::join(
|| Self::extend_half_to_lde(&h0_evals, &coset_offset_squared, domain),
|| Self::extend_half_to_lde(&h1_evals, &coset_offset_squared, domain),
);
#[cfg(not(feature = "parallel"))]
let (lde_h0, lde_h1) = (
Self::extend_half_to_lde(&h0_evals, &coset_offset_squared, domain),
Self::extend_half_to_lde(&h1_evals, &coset_offset_squared, domain),
);
vec![lde_h0, lde_h1]
}
/// Given N evaluations of a degree-<N polynomial on the g²-coset,
/// extend to 2N evaluations on the g-coset (the full LDE domain).
/// This is: iFFT(N, offset=g²) → coefficients → FFT(2N, offset=g).
fn extend_half_to_lde(
half_evals: &[FieldElement<FieldExtension>],
squared_offset: &FieldElement<Field>,
domain: &Domain<Field>,
) -> Vec<FieldElement<FieldExtension>>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
// iFFT on the N-point squared coset to get coefficients
let poly = Polynomial::interpolate_offset_fft(half_evals, squared_offset)
.expect("iFFT should succeed");
// Evaluate on the full LDE domain (2N points on the g-coset)
evaluate_polynomial_on_lde_domain(
&poly,
domain.blowup_factor,
domain.interpolation_domain_size,
&domain.coset_offset,
)
.expect("LDE evaluation should succeed")
}
/// Returns the result of the second round of the STARK Prove protocol.
fn round_2_compute_composition_polynomial(
air: &dyn AIR<Field = Field, FieldExtension = FieldExtension, PublicInputs = PI>,
pub_inputs: &PI,
domain: &Domain<Field>,
round_1_result: &Round1<Field, FieldExtension>,
transition_coefficients: &[FieldElement<FieldExtension>],
boundary_coefficients: &[FieldElement<FieldExtension>],
) -> Result<Round2<FieldExtension>, ProvingError>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
// Compute the evaluations of the composition polynomial on the LDE domain.
let trace_length = domain.interpolation_domain_size;
let evaluator = ConstraintEvaluator::new(
air,
pub_inputs,
&round_1_result.rap_challenges,
round_1_result.bus_public_inputs.as_ref(),
trace_length,
);
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
let constraint_evaluations = evaluator.evaluate(
air,
&round_1_result.lde_trace,
domain,
transition_coefficients,
boundary_coefficients,
&round_1_result.rap_challenges,
);
#[cfg(feature = "instruments")]
let constraints_dur = t_sub.elapsed();
let number_of_parts = air.composition_poly_degree_bound(trace_length) / trace_length;
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
let lde_composition_poly_parts_evaluations = if number_of_parts == 2 {
// Direct quotient decomposition: avoid full-size iFFT by algebraically
// splitting H(x) = H₀(x²) + x·H₁(x²) using:
// H₀(x²) = (H(x) + H(-x)) / 2
// H₁(x²) = (H(x) - H(-x)) / (2x)
// On the LDE coset {g·ω^i}, we have -g·ω^i = g·ω^{i+N} since ω^N = -1.
Self::decompose_and_extend_d2(&constraint_evaluations, domain)
} else if number_of_parts == 1 {
// Degree bound equals trace length: constraint evals are the LDE directly.
vec![constraint_evaluations]
} else {
// Fallback for any future AIR with d > 2.
let composition_poly =
Polynomial::interpolate_offset_fft(&constraint_evaluations, &domain.coset_offset)
.unwrap();
let composition_poly_parts = composition_poly.break_in_parts(number_of_parts);
composition_poly_parts
.iter()
.map(|part| {
evaluate_polynomial_on_lde_domain(
part,
domain.blowup_factor,
domain.interpolation_domain_size,
&domain.coset_offset,
)
.unwrap()
})
.collect()
};
#[cfg(feature = "instruments")]
let fft_dur = t_sub.elapsed();
#[cfg(feature = "instruments")]
let t_sub = Instant::now();
let Some((composition_poly_merkle_tree, composition_poly_root)) =
Self::commit_composition_polynomial(&lde_composition_poly_parts_evaluations)
else {
return Err(ProvingError::EmptyCommitment);
};
#[cfg(feature = "instruments")]
let merkle_dur = t_sub.elapsed();
#[cfg(feature = "instruments")]
crate::instruments::store_r2_sub(constraints_dur, fft_dur, merkle_dur);
Ok(Round2 {
lde_composition_poly_evaluations: lde_composition_poly_parts_evaluations,
composition_poly_merkle_tree,
composition_poly_root,
})
}
/// Returns the result of the third round of the STARK Prove protocol.
fn round_3_evaluate_polynomials_in_out_of_domain_element(
air: &dyn AIR<Field = Field, FieldExtension = FieldExtension, PublicInputs = PI>,
domain: &Domain<Field>,
round_1_result: &Round1<Field, FieldExtension>,
round_2_result: &Round2<FieldExtension>,
z: &FieldElement<FieldExtension>,
) -> Round3<FieldExtension>
where
FieldElement<Field>: AsBytes,
FieldElement<FieldExtension>: AsBytes,
{
let num_parts = round_2_result.lde_composition_poly_evaluations.len();
let z_power = z.pow(num_parts);
let domain_size = domain.interpolation_domain_size;
let blowup_factor = domain.blowup_factor;
// === Composition poly parts: barycentric evaluation at z^num_parts ===
// Extract trace-size coset points from the LDE coset (stride = blowup_factor)
// Keep coset points in base field — mixed F×E arithmetic is cheaper than E×E.
let coset_points: Vec<FieldElement<Field>> = (0..domain_size)
.map(|i| domain.lde_roots_of_unity_coset[i * blowup_factor].clone())
.collect();
// Keep coset_offset_pow_n and g_n_inv in base field F — the barycentric
// functions use F×E→E mixed arithmetic, avoiding field conversions.
let coset_offset_pow_n: FieldElement<Field> = domain.coset_offset.pow(domain_size);
let domain_size_inv: FieldElement<Field> = FieldElement::<Field>::from(domain_size as u64)
.inv()
.expect("domain_size is a power of two, hence non-zero in the field");
let g_n_inv: FieldElement<Field> = coset_offset_pow_n
.inv()
.expect("coset_offset_pow_n is non-zero");
// Precompute inv_denoms for z^num_parts (shared across all composition poly parts)
let comp_z_pow_n = z_power.pow(domain_size);
let comp_inv_denoms = math::polynomial::barycentric_inv_denoms(&z_power, &coset_points);
let composition_poly_parts_ood_evaluation: Vec<_> = round_2_result
.lde_composition_poly_evaluations
.iter()
.map(|lde_evals| {
// Extract trace-size evaluations (stride = blowup_factor)