-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathprover.rs
1696 lines (1486 loc) · 62.5 KB
/
prover.rs
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;
#[cfg(feature = "instruments")]
use std::time::Instant;
use lambdaworks_crypto::fiat_shamir::is_transcript::IsTranscript;
use lambdaworks_math::fft::cpu::bit_reversing::{in_place_bit_reverse_permute, reverse_index};
use lambdaworks_math::fft::errors::FFTError;
use lambdaworks_math::field::traits::{IsField, IsSubFieldOf};
use lambdaworks_math::traits::AsBytes;
use lambdaworks_math::{
field::{element::FieldElement, traits::IsFFTField},
polynomial::Polynomial,
};
use log::info;
#[cfg(feature = "parallel")]
use rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
#[cfg(debug_assertions)]
use crate::debug::validate_trace;
use crate::fri;
use crate::proof::stark::{DeepPolynomialOpenings, PolynomialOpenings};
use crate::table::Table;
use crate::trace::{columns2rows, LDETraceTable};
use super::config::{BatchedMerkleTree, Commitment};
use super::constraints::evaluator::ConstraintEvaluator;
use super::domain::Domain;
use super::fri::fri_decommit::FriDecommitment;
use super::grinding;
use super::proof::options::ProofOptions;
use super::proof::stark::{DeepPolynomialOpening, StarkProof};
use super::trace::TraceTable;
use super::traits::AIR;
/// A default STARK prover implementing `IsStarkProver`.
pub struct Prover<A: AIR> {
phantom: PhantomData<A>,
}
impl<A: AIR> IsStarkProver<A> for Prover<A> {}
#[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 + Send + Sync,
{
/// The result of the interpolation of the columns of the trace table.
pub(crate) trace_polys: Vec<Polynomial<FieldElement<F>>>,
/// The Merkle trees constructed to obtain the commitment of the entire trace table.
pub(crate) lde_trace_merkle_tree: BatchedMerkleTree<F>,
/// The root of the Merkle tree in `lde_trace_merkle_tree`.
pub(crate) lde_trace_merkle_root: Commitment,
}
/// A container for the results of the first round of the STARK Prove protocol.
pub struct Round1<A>
where
A: AIR,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
FieldElement<A::Field>: AsBytes + Sync + Send,
{
/// The table of evaluations over the LDE of the main and auxiliary trace tables.
pub(crate) lde_trace: LDETraceTable<A::Field, A::FieldExtension>,
/// The intermediate results of the commitment to the main trace table.
pub(crate) main: Round1CommitmentData<A::Field>,
/// The intermediate results of the commitment to the auxiliary trace table in case of RAP.
pub(crate) aux: Option<Round1CommitmentData<A::FieldExtension>>,
/// The challenges of the RAP round.
pub(crate) rap_challenges: Vec<FieldElement<A::FieldExtension>>,
}
impl<A> Round1<A>
where
A: AIR,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
FieldElement<A::Field>: AsBytes + Sync + Send,
{
/// Returns the full list of the polynomials interpolating the trace. It includes both
/// main and auxiliary trace polynomials. The main trace polynomials are casted to
/// polynomials with coefficients over `Self::FieldExtension`.
fn all_trace_polys(&self) -> Vec<Polynomial<FieldElement<A::FieldExtension>>> {
let mut trace_polys: Vec<_> = self
.main
.trace_polys
.clone()
.into_iter()
.map(|poly| poly.to_extension())
.collect();
if let Some(aux) = &self.aux {
trace_polys.extend_from_slice(&aux.trace_polys.to_owned())
}
trace_polys
}
}
/// A container for the results of the second round of the STARK Prove protocol.
pub struct Round2<F>
where
F: IsField,
FieldElement<F>: AsBytes + Sync + Send,
{
/// The list of polynomials `H₀, ..., Hₙ` such that `H = ∑ᵢXⁱH(Xⁿ)`, where H is the composition polynomial.
pub(crate) composition_poly_parts: Vec<Polynomial<FieldElement<F>>>,
/// 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,
{
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<A: AIR> {
/// Returns the Merkle tree and the commitment to the vectors `vectors`.
fn batch_commit_main(
vectors: &[Vec<FieldElement<A::Field>>],
) -> Option<(BatchedMerkleTree<A::Field>, Commitment)>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
{
let tree = BatchedMerkleTree::build(vectors)?;
let commitment = tree.root;
Some((tree, commitment))
}
/// Returns the Merkle tree and the commitment to the vectors `vectors`.
fn batch_commit_extension(
vectors: &[Vec<FieldElement<A::FieldExtension>>],
) -> Option<(BatchedMerkleTree<A::FieldExtension>, Commitment)>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let tree = BatchedMerkleTree::build(vectors)?;
let commitment = tree.root;
Some((tree, commitment))
}
/// Given a `TraceTable`, this method interpolates its columns, computes the commitment to the
/// table and appends it to the transcript.
/// Output: a touple of length 4 with the following:
/// • The polynomials interpolating the columns of `trace`.
/// • The evaluations of the above polynomials over the domain `domain`.
/// • The Merkle tree of evaluations of the above polynomials over the domain `domain`.
/// • The roots of the above Merkle trees.
#[allow(clippy::type_complexity)]
fn interpolate_and_commit_main(
trace: &TraceTable<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Option<(
Vec<Polynomial<FieldElement<A::Field>>>,
Vec<Vec<FieldElement<A::Field>>>,
BatchedMerkleTree<A::Field>,
Commitment,
)>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
// FieldElement<E>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
A::Field: IsSubFieldOf<A::FieldExtension>,
{
// Interpolate columns of `trace`.
let trace_polys = trace.compute_trace_polys_main::<A::Field>();
// Evaluate those polynomials t_j on the large domain D_LDE.
let lde_trace_evaluations =
Self::compute_lde_trace_evaluations::<A::Field>(&trace_polys, domain);
let mut lde_trace_permuted = lde_trace_evaluations.clone();
for col in lde_trace_permuted.iter_mut() {
in_place_bit_reverse_permute(col);
}
// Compute commitment.
let lde_trace_permuted_rows = columns2rows(lde_trace_permuted);
let (lde_trace_merkle_tree, lde_trace_merkle_root) =
Self::batch_commit_main(&lde_trace_permuted_rows)?;
// >>>> Send commitment.
transcript.append_bytes(&lde_trace_merkle_root);
Some((
trace_polys,
lde_trace_evaluations,
lde_trace_merkle_tree,
lde_trace_merkle_root,
))
}
/// Given a `TraceTable`, this method interpolates its columns, computes the commitment to the
/// table and appends it to the transcript.
/// Output: a touple of length 4 with the following:
/// • The polynomials interpolating the columns of `trace`.
/// • The evaluations of the above polynomials over the domain `domain`.
/// • The Merkle tree of evaluations of the above polynomials over the domain `domain`.
/// • The roots of the above Merkle trees.
#[allow(clippy::type_complexity)]
fn interpolate_and_commit_aux(
trace: &TraceTable<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Option<(
Vec<Polynomial<FieldElement<A::FieldExtension>>>,
Vec<Vec<FieldElement<A::FieldExtension>>>,
BatchedMerkleTree<A::FieldExtension>,
Commitment,
)>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
A::Field: IsSubFieldOf<A::FieldExtension> + IsFFTField,
{
// Interpolate columns of `trace`.
let trace_polys = trace.compute_trace_polys_aux::<A::Field>();
// Evaluate those polynomials t_j on the large domain D_LDE.
let lde_trace_evaluations = Self::compute_lde_trace_evaluations(&trace_polys, domain);
let mut lde_trace_permuted = lde_trace_evaluations.clone();
for col in lde_trace_permuted.iter_mut() {
in_place_bit_reverse_permute(col);
}
// Compute commitment.
let lde_trace_permuted_rows = columns2rows(lde_trace_permuted);
let (lde_trace_merkle_tree, lde_trace_merkle_root) =
Self::batch_commit_extension(&lde_trace_permuted_rows)?;
// >>>> Send commitment.
transcript.append_bytes(&lde_trace_merkle_root);
Some((
trace_polys,
lde_trace_evaluations,
lde_trace_merkle_tree,
lde_trace_merkle_root,
))
}
/// Evaluate polynomials `trace_polys` over the domain `domain`.
/// The i-th entry of the returned vector contains the evaluations of the i-th polynomial in `trace_polys`.
fn compute_lde_trace_evaluations<E>(
trace_polys: &[Polynomial<FieldElement<E>>],
domain: &Domain<A::Field>,
) -> Vec<Vec<FieldElement<E>>>
where
FieldElement<E>: Send + Sync,
FieldElement<A::Field>: Send + Sync,
E: IsSubFieldOf<A::FieldExtension>,
A::Field: IsSubFieldOf<E>,
{
#[cfg(not(feature = "parallel"))]
let trace_polys_iter = trace_polys.iter();
#[cfg(feature = "parallel")]
let trace_polys_iter = trace_polys.par_iter();
trace_polys_iter
.map(|poly| {
evaluate_polynomial_on_lde_domain(
poly,
domain.blowup_factor,
domain.interpolation_domain_size,
&domain.coset_offset,
)
})
.collect::<Result<Vec<Vec<FieldElement<E>>>, FFTError>>()
.unwrap()
}
/// Returns the result of the first round of the STARK Prove protocol.
fn round_1_randomized_air_with_preprocessing(
air: &A,
trace: &mut TraceTable<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Result<Round1<A>, ProvingError>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
A::FieldExtension: IsFFTField,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
let Some((trace_polys, evaluations, main_merkle_tree, main_merkle_root)) =
Self::interpolate_and_commit_main(trace, domain, transcript)
else {
return Err(ProvingError::EmptyCommitment);
};
let main = Round1CommitmentData::<A::Field> {
trace_polys,
lde_trace_merkle_tree: main_merkle_tree,
lde_trace_merkle_root: main_merkle_root,
};
let rap_challenges = air.build_rap_challenges(transcript);
let (aux, aux_evaluations) = if air.has_trace_interaction() {
air.build_auxiliary_trace(trace, &rap_challenges);
let Some((
aux_trace_polys,
aux_trace_polys_evaluations,
aux_merkle_tree,
aux_merkle_root,
)) = Self::interpolate_and_commit_aux(trace, domain, transcript)
else {
return Err(ProvingError::EmptyCommitment);
};
let aux_evaluations = aux_trace_polys_evaluations;
let aux = Some(Round1CommitmentData::<A::FieldExtension> {
trace_polys: aux_trace_polys,
lde_trace_merkle_tree: aux_merkle_tree,
lde_trace_merkle_root: aux_merkle_root,
});
(aux, aux_evaluations)
} else {
(None, Vec::new())
};
let lde_trace = LDETraceTable::from_columns(
evaluations,
aux_evaluations,
A::STEP_SIZE,
domain.blowup_factor,
);
Ok(Round1 {
lde_trace,
main,
aux,
rap_challenges,
})
}
/// 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<A::FieldExtension>>],
) -> Option<(BatchedMerkleTree<A::FieldExtension>, Commitment)>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
// TODO: Remove clones
let mut lde_composition_poly_evaluations = Vec::new();
for i in 0..lde_composition_poly_parts_evaluations[0].len() {
let mut row = Vec::new();
for evaluation in lde_composition_poly_parts_evaluations.iter() {
row.push(evaluation[i].clone());
}
lde_composition_poly_evaluations.push(row);
}
in_place_bit_reverse_permute(&mut lde_composition_poly_evaluations);
let mut lde_composition_poly_evaluations_merged = Vec::new();
for chunk in lde_composition_poly_evaluations.chunks(2) {
let (mut chunk0, chunk1) = (chunk[0].clone(), &chunk[1]);
chunk0.extend_from_slice(chunk1);
lde_composition_poly_evaluations_merged.push(chunk0);
}
Self::batch_commit_extension(&lde_composition_poly_evaluations_merged)
}
/// Returns the result of the second round of the STARK Prove protocol.
fn round_2_compute_composition_polynomial(
air: &A,
domain: &Domain<A::Field>,
round_1_result: &Round1<A>,
transition_coefficients: &[FieldElement<A::FieldExtension>],
boundary_coefficients: &[FieldElement<A::FieldExtension>],
) -> Result<Round2<A::FieldExtension>, ProvingError>
where
A: Send + Sync,
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
// Compute the evaluations of the composition polynomial on the LDE domain.
let evaluator = ConstraintEvaluator::new(air, &round_1_result.rap_challenges);
let constraint_evaluations = evaluator.evaluate(
air,
&round_1_result.lde_trace,
domain,
transition_coefficients,
boundary_coefficients,
&round_1_result.rap_challenges,
);
// Get coefficients of the composition poly H
let composition_poly =
Polynomial::interpolate_offset_fft(&constraint_evaluations, &domain.coset_offset)
.unwrap();
let number_of_parts = air.composition_poly_degree_bound() / air.trace_length();
let composition_poly_parts = composition_poly.break_in_parts(number_of_parts);
let lde_composition_poly_parts_evaluations: Vec<_> = composition_poly_parts
.iter()
.map(|part| {
evaluate_polynomial_on_lde_domain(
part,
domain.blowup_factor,
domain.interpolation_domain_size,
&domain.coset_offset,
)
.unwrap()
})
.collect();
let Some((composition_poly_merkle_tree, composition_poly_root)) =
Self::commit_composition_polynomial(&lde_composition_poly_parts_evaluations)
else {
return Err(ProvingError::EmptyCommitment);
};
Ok(Round2 {
lde_composition_poly_evaluations: lde_composition_poly_parts_evaluations,
composition_poly_parts,
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: &A,
domain: &Domain<A::Field>,
round_1_result: &Round1<A>,
round_2_result: &Round2<A::FieldExtension>,
z: &FieldElement<A::FieldExtension>,
) -> Round3<A::FieldExtension>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let z_power = z.pow(round_2_result.composition_poly_parts.len());
// Evaluate H_i in z^N for all i, where N is the number of parts the composition poly was
// broken into.
let composition_poly_parts_ood_evaluation: Vec<_> = round_2_result
.composition_poly_parts
.iter()
.map(|part| part.evaluate(&z_power))
.collect();
// Returns the Out of Domain Frame for the given trace polynomials, out of domain evaluation point (called `z` in the literature),
// frame offsets given by the AIR and primitive root used for interpolating the trace polynomials.
// An out of domain frame is nothing more than the evaluation of the trace polynomials in the points required by the
// verifier to check the consistency between the trace and the composition polynomial.
//
// In the fibonacci example, the ood frame is simply the evaluations `[t(z), t(z * g), t(z * g^2)]`, where `t` is the trace
// polynomial and `g` is the primitive root of unity used when interpolating `t`.
let trace_ood_evaluations =
crate::trace::get_trace_evaluations::<A::Field, A::FieldExtension>(
&round_1_result.main.trace_polys,
round_1_result
.aux
.as_ref()
.map(|aux| &aux.trace_polys)
.unwrap_or(&vec![]),
z,
&air.context().transition_offsets,
&domain.trace_primitive_root,
A::STEP_SIZE,
);
Round3 {
trace_ood_evaluations,
composition_poly_parts_ood_evaluation,
}
}
/// Returns the result of the fourth round of the STARK Prove protocol.
fn round_4_compute_and_run_fri_on_the_deep_composition_polynomial(
air: &A,
domain: &Domain<A::Field>,
round_1_result: &Round1<A>,
round_2_result: &Round2<A::FieldExtension>,
round_3_result: &Round3<A::FieldExtension>,
z: &FieldElement<A::FieldExtension>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Round4<A::Field, A::FieldExtension>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
let coset_offset_u64 = air.context().proof_options.coset_offset;
let coset_offset = FieldElement::<A::Field>::from(coset_offset_u64);
let gamma = transcript.sample_field_element();
let n_terms_composition_poly = round_2_result.lde_composition_poly_evaluations.len();
let num_terms_trace =
air.context().transition_offsets.len() * A::STEP_SIZE * air.context().trace_columns;
// <<<< Receive challenges: 𝛾, 𝛾'
let mut deep_composition_coefficients: Vec<_> =
core::iter::successors(Some(FieldElement::one()), |x| Some(x * &gamma))
.take(n_terms_composition_poly + num_terms_trace)
.collect();
let trace_term_coeffs: Vec<_> = deep_composition_coefficients
.drain(..num_terms_trace)
.collect::<Vec<_>>()
.chunks(air.context().transition_offsets.len() * A::STEP_SIZE)
.map(|chunk| chunk.to_vec())
.collect();
// <<<< Receive challenges: 𝛾ⱼ, 𝛾ⱼ'
let gammas = deep_composition_coefficients;
// Compute p₀ (deep composition polynomial)
let deep_composition_poly = Self::compute_deep_composition_poly(
&round_1_result.all_trace_polys(),
round_2_result,
round_3_result,
z,
&domain.trace_primitive_root,
&gammas,
&trace_term_coeffs,
);
let domain_size = domain.lde_roots_of_unity_coset.len();
// FRI commit and query phases
let (fri_last_value, fri_layers) = fri::commit_phase::<A::Field, A::FieldExtension>(
domain.root_order as usize,
deep_composition_poly,
transcript,
&coset_offset,
domain_size,
);
// grinding: generate nonce and append it to the transcript
let security_bits = air.context().proof_options.grinding_factor;
let mut nonce = None;
if security_bits > 0 {
let nonce_value = grinding::generate_nonce(&transcript.state(), security_bits)
.expect("nonce not found");
transcript.append_bytes(&nonce_value.to_be_bytes());
nonce = Some(nonce_value);
}
let number_of_queries = air.options().fri_number_of_queries;
let iotas = Self::sample_query_indexes(number_of_queries, domain, transcript);
let query_list = fri::query_phase(&fri_layers, &iotas);
let fri_layers_merkle_roots: Vec<_> = fri_layers
.iter()
.map(|layer| layer.merkle_tree.root)
.collect();
let deep_poly_openings =
Self::open_deep_composition_poly(domain, round_1_result, round_2_result, &iotas);
Round4 {
fri_last_value,
fri_layers_merkle_roots,
deep_poly_openings,
query_list,
nonce,
}
}
fn sample_query_indexes(
number_of_queries: usize,
domain: &Domain<A::Field>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Vec<usize> {
let domain_size = domain.lde_roots_of_unity_coset.len() as u64;
(0..number_of_queries)
.map(|_| (transcript.sample_u64(domain_size >> 1)) as usize)
.collect::<Vec<usize>>()
}
/// Returns the DEEP composition polynomial that the prover then commits to using
/// FRI. This polynomial is a linear combination of the trace polynomial and the
/// composition polynomial, with coefficients sampled by the verifier (i.e. using Fiat-Shamir).
#[allow(clippy::too_many_arguments)]
fn compute_deep_composition_poly(
trace_polys: &[Polynomial<FieldElement<A::FieldExtension>>],
round_2_result: &Round2<A::FieldExtension>,
round_3_result: &Round3<A::FieldExtension>,
z: &FieldElement<A::FieldExtension>,
primitive_root: &FieldElement<A::Field>,
composition_poly_gammas: &[FieldElement<A::FieldExtension>],
trace_terms_gammas: &[Vec<FieldElement<A::FieldExtension>>],
) -> Polynomial<FieldElement<A::FieldExtension>>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
let z_power = z.pow(round_2_result.composition_poly_parts.len());
// ∑ᵢ 𝛾ᵢ ( Hᵢ − Hᵢ(z^N) ) / ( X − z^N )
let mut h_terms = Polynomial::zero();
for (i, part) in round_2_result.composition_poly_parts.iter().enumerate() {
// h_i_eval is the evaluation of the i-th part of the composition polynomial at z^N,
// where N is the number of parts of the composition polynomial.
let h_i_eval = &round_3_result.composition_poly_parts_ood_evaluation[i];
let h_i_term = &composition_poly_gammas[i] * (part - h_i_eval);
h_terms = h_terms + h_i_term;
}
assert_eq!(h_terms.evaluate(&z_power), FieldElement::zero());
h_terms.ruffini_division_inplace(&z_power);
// Get trace evaluations needed for the trace terms of the deep composition polynomial
let trace_frame_evaluations = &round_3_result.trace_ood_evaluations;
// Compute the sum of all the trace terms of the deep composition polynomial.
// There is one term for every trace polynomial and for every row in the frame.
// ∑ ⱼₖ [ 𝛾ₖ ( tⱼ − tⱼ(z) ) / ( X − zgᵏ )]
let trace_evaluations_columns = &trace_frame_evaluations.columns();
#[cfg(feature = "parallel")]
let trace_terms = trace_polys
.par_iter()
.enumerate()
.fold(Polynomial::zero, |trace_terms, (i, t_j)| {
let gammas_i = &trace_terms_gammas[i];
let trace_evaluations_i = &trace_evaluations_columns[i];
Self::compute_trace_term(
&trace_terms,
t_j,
gammas_i,
trace_evaluations_i,
(z, primitive_root),
)
})
.reduce(Polynomial::zero, |a, b| a + b);
#[cfg(not(feature = "parallel"))]
let trace_terms =
trace_polys
.iter()
.enumerate()
.fold(Polynomial::zero(), |trace_terms, (i, t_j)| {
let gammas_i = &trace_terms_gammas[i];
let trace_evaluations_i = &trace_evaluations_columns[i];
Self::compute_trace_term(
&trace_terms,
t_j,
gammas_i,
trace_evaluations_i,
(z, primitive_root),
)
});
h_terms + trace_terms
}
// FIXME: FIX THIS DOCS!
/// Adds to `accumulator` the term corresponding to the trace polynomial `t_j` of the Deep
/// composition polynomial. That is, returns `accumulator + \sum_i \gamma_i \frac{ t_j - t_j(zg^i) }{ X - zg^i }`,
/// where `i` ranges from `T * j` to `T * j + T - 1`, where `T` is the number of offsets in every frame.
fn compute_trace_term(
accumulator: &Polynomial<FieldElement<A::FieldExtension>>,
trace_term_poly: &Polynomial<FieldElement<A::FieldExtension>>,
trace_terms_gammas: &[FieldElement<A::FieldExtension>],
trace_frame_evaluations: &[FieldElement<A::FieldExtension>],
(z, primitive_root): (&FieldElement<A::FieldExtension>, &FieldElement<A::Field>),
) -> Polynomial<FieldElement<A::FieldExtension>>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
let trace_int = trace_frame_evaluations
.iter()
.enumerate()
.zip(trace_terms_gammas)
.fold(
Polynomial::zero(),
|trace_agg, ((offset, trace_term_poly_evaluation), trace_gamma)| {
// @@@ this can be pre-computed
let z_shifted = primitive_root.pow(offset) * z;
let mut poly = trace_term_poly - trace_term_poly_evaluation;
poly.ruffini_division_inplace(&z_shifted);
trace_agg + poly * trace_gamma
},
);
accumulator + trace_int
}
/// Computes values and validity proofs of the evaluations of the composition polynomial parts
/// at the domain value corresponding to the FRI query challenge `index` and its symmetric
/// element.
fn open_composition_poly(
composition_poly_merkle_tree: &BatchedMerkleTree<A::FieldExtension>,
lde_composition_poly_evaluations: &[Vec<FieldElement<A::FieldExtension>>],
index: usize,
) -> PolynomialOpenings<A::FieldExtension>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let proof = composition_poly_merkle_tree
.get_proof_by_pos(index)
.unwrap();
let lde_composition_poly_parts_evaluation: Vec<_> = lde_composition_poly_evaluations
.iter()
.flat_map(|part| {
vec![
part[reverse_index(index * 2, part.len() as u64)].clone(),
part[reverse_index(index * 2 + 1, part.len() as u64)].clone(),
]
})
.collect();
PolynomialOpenings {
proof: proof.clone(),
proof_sym: proof,
evaluations: lde_composition_poly_parts_evaluation
.clone()
.into_iter()
.step_by(2)
.collect(),
evaluations_sym: lde_composition_poly_parts_evaluation
.into_iter()
.skip(1)
.step_by(2)
.collect(),
}
}
/// Computes values and validity proofs of the evaluations of the trace polynomials
/// at the domain value corresponding to the FRI query challenge `index` and its symmetric
/// element.
fn open_trace_polys<E>(
domain: &Domain<A::Field>,
tree: &BatchedMerkleTree<E>,
lde_trace: &Table<E>,
challenge: usize,
) -> PolynomialOpenings<E>
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<E>: AsBytes + Sync + Send,
A::Field: IsSubFieldOf<E>,
E: IsField,
{
let domain_size = domain.lde_roots_of_unity_coset.len();
let index = challenge * 2;
let index_sym = challenge * 2 + 1;
PolynomialOpenings {
proof: tree.get_proof_by_pos(index).unwrap(),
proof_sym: tree.get_proof_by_pos(index_sym).unwrap(),
evaluations: lde_trace
.get_row(reverse_index(index, domain_size as u64))
.to_vec(),
evaluations_sym: lde_trace
.get_row(reverse_index(index_sym, domain_size as u64))
.to_vec(),
}
}
/// Open the deep composition polynomial on a list of indexes and their symmetric elements.
fn open_deep_composition_poly(
domain: &Domain<A::Field>,
round_1_result: &Round1<A>,
round_2_result: &Round2<A::FieldExtension>,
indexes_to_open: &[usize],
) -> DeepPolynomialOpenings<A::Field, A::FieldExtension>
where
FieldElement<A::Field>: AsBytes + Send + Sync,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
let mut openings = Vec::new();
for index in indexes_to_open.iter() {
let main_trace_opening = Self::open_trace_polys::<A::Field>(
domain,
&round_1_result.main.lde_trace_merkle_tree,
&round_1_result.lde_trace.main_table,
*index,
);
let composition_openings = Self::open_composition_poly(
&round_2_result.composition_poly_merkle_tree,
&round_2_result.lde_composition_poly_evaluations,
*index,
);
let aux_trace_polys = round_1_result.aux.as_ref().map(|aux| {
Self::open_trace_polys::<A::FieldExtension>(
domain,
&aux.lde_trace_merkle_tree,
&round_1_result.lde_trace.aux_table,
*index,
)
});
openings.push(DeepPolynomialOpening {
composition_poly: composition_openings,
main_trace_polys: main_trace_opening,
aux_trace_polys,
});
}
openings
}
// FIXME remove unwrap() calls and return errors
/// Generates a STARK proof for the trace `main_trace` with public inputs `pub_inputs`.
/// Warning: the transcript must be safely initializated before passing it to this method.
fn prove(
trace: &mut TraceTable<A::Field, A::FieldExtension>,
pub_inputs: &A::PublicInputs,
proof_options: &ProofOptions,
mut transcript: impl IsTranscript<A::FieldExtension>,
) -> Result<StarkProof<A::Field, A::FieldExtension>, ProvingError>
where
A: Send + Sync,
FieldElement<A::Field>: AsBytes + Send + Sync,
A::FieldExtension: IsFFTField,
FieldElement<A::FieldExtension>: AsBytes + Send + Sync,
{
info!("Started proof generation...");
#[cfg(feature = "instruments")]
println!("- Started round 0: Air Initialization");
#[cfg(feature = "instruments")]
let timer0 = Instant::now();
let air = A::new(trace.num_rows(), pub_inputs, proof_options);
let domain = Domain::new(&air);
#[cfg(feature = "instruments")]
let elapsed0 = timer0.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed0);
// ===================================
// ==========| Round 1 |==========
// ===================================
#[cfg(feature = "instruments")]
println!("- Started round 1: RAP");
#[cfg(feature = "instruments")]
let timer1 = Instant::now();
let round_1_result =
Self::round_1_randomized_air_with_preprocessing(&air, trace, &domain, &mut transcript)?;
#[cfg(debug_assertions)]
validate_trace(
&air,
&round_1_result.main.trace_polys,
round_1_result
.aux
.as_ref()
.map(|a| &a.trace_polys)
.unwrap_or(&vec![]),
&domain,
&round_1_result.rap_challenges,
);
#[cfg(feature = "instruments")]
let elapsed1 = timer1.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed1);
// ===================================
// ==========| Round 2 |==========
// ===================================
#[cfg(feature = "instruments")]
println!("- Started round 2: Compute composition polynomial");
#[cfg(feature = "instruments")]
let timer2 = Instant::now();
// <<<< Receive challenge: 𝛽
let beta = transcript.sample_field_element();
let num_boundary_constraints = air
.boundary_constraints(&round_1_result.rap_challenges)
.constraints
.len();
let num_transition_constraints = air.context().num_transition_constraints;
let mut coefficients: Vec<_> =
core::iter::successors(Some(FieldElement::one()), |x| Some(x * &beta))
.take(num_boundary_constraints + num_transition_constraints)
.collect();
let transition_coefficients: Vec<_> =
coefficients.drain(..num_transition_constraints).collect();
let boundary_coefficients = coefficients;
let round_2_result = Self::round_2_compute_composition_polynomial(
&air,
&domain,
&round_1_result,
&transition_coefficients,
&boundary_coefficients,
)?;
// >>>> Send commitments: [H₁], [H₂]
transcript.append_bytes(&round_2_result.composition_poly_root);
#[cfg(feature = "instruments")]
let elapsed2 = timer2.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed2);
// ===================================
// ==========| Round 3 |==========
// ===================================
#[cfg(feature = "instruments")]
println!("- Started round 3: Evaluate polynomial in out of domain elements");
#[cfg(feature = "instruments")]
let timer3 = Instant::now();
// <<<< Receive challenge: z
let z = transcript.sample_z_ood(
&domain.lde_roots_of_unity_coset,
&domain.trace_roots_of_unity,
);
let round_3_result = Self::round_3_evaluate_polynomials_in_out_of_domain_element(
&air,
&domain,
&round_1_result,
&round_2_result,
&z,
);
// >>>> Send values: tⱼ(zgᵏ)
let trace_ood_evaluations_columns = round_3_result.trace_ood_evaluations.columns();
for col in trace_ood_evaluations_columns.iter() {
for elem in col.iter() {
transcript.append_field_element(elem);
}
}