-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathverifier.rs
825 lines (729 loc) · 32.7 KB
/
verifier.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
use super::{
config::BatchedMerkleTreeBackend,
domain::Domain,
fri::fri_decommit::FriDecommitment,
grinding,
proof::{options::ProofOptions, stark::StarkProof},
traits::{TransitionEvaluationContext, AIR},
};
use crate::{config::Commitment, proof::stark::DeepPolynomialOpening};
use lambdaworks_crypto::{fiat_shamir::is_transcript::IsTranscript, merkle_tree::proof::Proof};
use lambdaworks_math::{
fft::cpu::bit_reversing::reverse_index,
field::{
element::FieldElement,
traits::{IsFFTField, IsField, IsSubFieldOf},
},
traits::AsBytes,
};
#[cfg(not(feature = "test_fiat_shamir"))]
use log::error;
use std::marker::PhantomData;
#[cfg(feature = "instruments")]
use std::time::Instant;
/// A default STARK verifier implementing `IsStarkVerifier`.
pub struct Verifier<A: AIR> {
phantom: PhantomData<A>,
}
impl<A: AIR> IsStarkVerifier<A> for Verifier<A> {}
/// A container holding the complete list of challenges sent to the prover along with the seed used
/// to validate the proof-of-work nonce.
pub struct Challenges<A>
where
A: AIR,
{
/// The out-of-domain challenge.
pub z: FieldElement<A::FieldExtension>,
/// The composition polynomial coefficients corresponding to the boundary constraints terms.
pub boundary_coeffs: Vec<FieldElement<A::FieldExtension>>,
/// The composition polynomial coefficients corresponding to the transition constraints terms.
pub transition_coeffs: Vec<FieldElement<A::FieldExtension>>,
/// The deep composition polynomial coefficients corresponding to the trace polynomial terms.
pub trace_term_coeffs: Vec<Vec<FieldElement<A::FieldExtension>>>,
/// The deep composition polynomial coefficients corresponding to the composition polynomial parts terms.
pub gammas: Vec<FieldElement<A::FieldExtension>>,
/// The list of FRI commit phase folding challenges.
pub zetas: Vec<FieldElement<A::FieldExtension>>,
/// The list of FRI query phase index challenges.
pub iotas: Vec<usize>,
/// The challenges used to build the auxiliary trace.
pub rap_challenges: Vec<FieldElement<A::FieldExtension>>,
/// The seed used to verify the proof-of-work nonce.
pub grinding_seed: [u8; 32],
}
pub type DeepPolynomialEvaluations<F> = (Vec<FieldElement<F>>, Vec<FieldElement<F>>);
/// The functionality of a STARK verifier providing methods to run the STARK Verify protocol
/// https://lambdaclass.github.io/lambdaworks/starks/protocol.html
pub trait IsStarkVerifier<A: AIR> {
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 list of challenges sent to the prover.
fn step_1_replay_rounds_and_recover_challenges(
air: &A,
proof: &StarkProof<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
transcript: &mut impl IsTranscript<A::FieldExtension>,
) -> Challenges<A>
where
FieldElement<A::Field>: AsBytes,
FieldElement<A::FieldExtension>: AsBytes,
{
// ===================================
// ==========| Round 1 |==========
// ===================================
// <<<< Receive commitments:[tⱼ]
transcript.append_bytes(&proof.lde_trace_main_merkle_root);
let rap_challenges = air.build_rap_challenges(transcript);
if let Some(root) = proof.lde_trace_aux_merkle_root {
transcript.append_bytes(&root);
}
// ===================================
// ==========| Round 2 |==========
// ===================================
// <<<< Receive challenge: 𝛽
let beta = transcript.sample_field_element();
let num_boundary_constraints = air.boundary_constraints(&rap_challenges).constraints.len();
let num_transition_constraints = air.context().num_transition_constraints;
let mut coefficients: Vec<_> = (0..num_boundary_constraints + num_transition_constraints)
.map(|i| beta.pow(i))
.collect();
let transition_coeffs: Vec<_> = coefficients.drain(..num_transition_constraints).collect();
let boundary_coeffs = coefficients;
// <<<< Receive commitments: [H₁], [H₂]
transcript.append_bytes(&proof.composition_poly_root);
// ===================================
// ==========| Round 3 |==========
// ===================================
// >>>> Send challenge: z
let z = transcript.sample_z_ood(
&domain.lde_roots_of_unity_coset,
&domain.trace_roots_of_unity,
);
// <<<< Receive values: tⱼ(zgᵏ)
let trace_ood_evaluations_columns = proof.trace_ood_evaluations.columns();
for col in trace_ood_evaluations_columns.iter() {
for elem in col.iter() {
transcript.append_field_element(elem);
}
}
// <<<< Receive value: Hᵢ(z^N)
for element in proof.composition_poly_parts_ood_evaluation.iter() {
transcript.append_field_element(element);
}
// ===================================
// ==========| Round 4 |==========
// ===================================
let num_terms_composition_poly = proof.composition_poly_parts_ood_evaluation.len();
let num_terms_trace =
air.context().transition_offsets.len() * A::STEP_SIZE * air.context().trace_columns;
let gamma = transcript.sample_field_element();
// <<<< Receive challenges: 𝛾, 𝛾'
let mut deep_composition_coefficients: Vec<_> =
core::iter::successors(Some(FieldElement::one()), |x| Some(x * &gamma))
.take(num_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;
// FRI commit phase
let merkle_roots = &proof.fri_layers_merkle_roots;
let mut zetas = merkle_roots
.iter()
.map(|root| {
// >>>> Send challenge 𝜁ₖ
let element = transcript.sample_field_element();
// <<<< Receive commitment: [pₖ] (the first one is [p₀])
transcript.append_bytes(root);
element
})
.collect::<Vec<FieldElement<A::FieldExtension>>>();
// >>>> Send challenge 𝜁ₙ₋₁
zetas.push(transcript.sample_field_element());
// <<<< Receive value: pₙ
transcript.append_field_element(&proof.fri_last_value);
// Receive grinding value
let security_bits = air.context().proof_options.grinding_factor;
let mut grinding_seed = [0u8; 32];
if security_bits > 0 {
if let Some(nonce_value) = proof.nonce {
grinding_seed = transcript.state();
transcript.append_bytes(&nonce_value.to_be_bytes());
}
}
// FRI query phase
// <<<< Send challenges 𝜄ₛ (iota_s)
let number_of_queries = air.options().fri_number_of_queries;
let iotas = Self::sample_query_indexes(number_of_queries, domain, transcript);
Challenges {
z,
boundary_coeffs,
transition_coeffs,
trace_term_coeffs,
gammas,
zetas,
iotas,
rap_challenges,
grinding_seed,
}
}
/// Checks whether the purported evaluations of the composition polynomial parts and the trace
/// polynomials at the out-of-domain challenge are consistent.
/// See https://lambdaclass.github.io/lambdaworks/starks/protocol.html#step-2-verify-claimed-composition-polynomial
fn step_2_verify_claimed_composition_polynomial(
air: &A,
proof: &StarkProof<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
challenges: &Challenges<A>,
) -> bool {
let boundary_constraints = air.boundary_constraints(&challenges.rap_challenges);
let trace_length = air.trace_length();
let number_of_b_constraints = boundary_constraints.constraints.len();
#[allow(clippy::type_complexity)]
let (boundary_c_i_evaluations_num, mut boundary_c_i_evaluations_den): (
Vec<FieldElement<A::FieldExtension>>,
Vec<FieldElement<A::FieldExtension>>,
) = (0..number_of_b_constraints)
.map(|index| {
let step = boundary_constraints.constraints[index].step;
let is_aux = boundary_constraints.constraints[index].is_aux;
let point = &domain.trace_primitive_root.pow(step as u64);
let column_idx = boundary_constraints.constraints[index].col;
let trace_evaluation = if is_aux {
let column_idx = air.trace_layout().0 + column_idx;
&proof.trace_ood_evaluations.get_row(0)[column_idx]
} else {
&proof.trace_ood_evaluations.get_row(0)[column_idx]
};
let boundary_zerofier_challenges_z_den = -point + &challenges.z;
let boundary_quotient_ood_evaluation_num =
-&boundary_constraints.constraints[index].value + trace_evaluation;
(
boundary_quotient_ood_evaluation_num,
boundary_zerofier_challenges_z_den,
)
})
.collect::<Vec<_>>()
.into_iter()
.unzip();
FieldElement::inplace_batch_inverse(&mut boundary_c_i_evaluations_den).unwrap();
let boundary_quotient_ood_evaluation: FieldElement<A::FieldExtension> =
boundary_c_i_evaluations_num
.iter()
.zip(&boundary_c_i_evaluations_den)
.zip(&challenges.boundary_coeffs)
.map(|((num, den), beta)| num * den * beta)
.fold(FieldElement::<A::FieldExtension>::zero(), |acc, x| acc + x);
let periodic_values = air
.get_periodic_column_polynomials()
.iter()
.map(|poly| poly.evaluate(&challenges.z))
.collect::<Vec<FieldElement<A::FieldExtension>>>();
let num_main_trace_columns =
proof.trace_ood_evaluations.width - air.num_auxiliary_rap_columns();
let ood_frame =
(proof.trace_ood_evaluations).into_frame(num_main_trace_columns, A::STEP_SIZE);
let transition_evaluation_context = TransitionEvaluationContext::new_verifier(
&ood_frame,
&periodic_values,
&challenges.rap_challenges,
);
let transition_ood_frame_evaluations =
air.compute_transition(&transition_evaluation_context);
let mut denominators =
vec![FieldElement::<A::FieldExtension>::zero(); air.num_transition_constraints()];
air.transition_constraints().iter().for_each(|c| {
denominators[c.constraint_idx()] =
c.evaluate_zerofier(&challenges.z, &domain.trace_primitive_root, trace_length);
});
let transition_c_i_evaluations_sum = itertools::izip!(
transition_ood_frame_evaluations,
&challenges.transition_coeffs,
denominators
)
.fold(FieldElement::zero(), |acc, (eval, beta, denominator)| {
acc + beta * eval * &denominator
});
let composition_poly_ood_evaluation =
&boundary_quotient_ood_evaluation + transition_c_i_evaluations_sum;
let composition_poly_claimed_ood_evaluation = proof
.composition_poly_parts_ood_evaluation
.iter()
.rev()
.fold(FieldElement::zero(), |acc, coeff| {
acc * &challenges.z + coeff
});
composition_poly_claimed_ood_evaluation == composition_poly_ood_evaluation
}
/// Reconstructs the Deep composition polynomial evaluations at the challenge indices values using the provided
/// openings of the trace polynomials and the composition polynomial parts. It then uses these to verify that the
/// FRI decommitments are valid and correspond to the Deep composition polynomial.
fn step_3_verify_fri(
proof: &StarkProof<A::Field, A::FieldExtension>,
domain: &Domain<A::Field>,
challenges: &Challenges<A>,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let (deep_poly_evaluations, deep_poly_evaluations_sym) =
Self::reconstruct_deep_composition_poly_evaluations_for_all_queries(
challenges, domain, proof,
);
// verify FRI
let mut evaluation_point_inverse = challenges
.iotas
.iter()
.map(|iota| Self::query_challenge_to_evaluation_point(*iota, domain))
.collect::<Vec<FieldElement<A::Field>>>();
FieldElement::inplace_batch_inverse(&mut evaluation_point_inverse).unwrap();
proof
.query_list
.iter()
.zip(&challenges.iotas)
.zip(evaluation_point_inverse)
.enumerate()
.fold(true, |mut result, (i, ((proof_s, iota_s), eval))| {
result &= Self::verify_query_and_sym_openings(
proof,
&challenges.zetas,
*iota_s,
proof_s,
eval,
&deep_poly_evaluations[i],
&deep_poly_evaluations_sym[i],
);
result
})
}
/// Returns the field element element of the domain `domain` corresponding to the given FRI query index challenge `iota`.
fn query_challenge_to_evaluation_point(
iota: usize,
domain: &Domain<A::Field>,
) -> FieldElement<A::Field> {
domain.lde_roots_of_unity_coset
[reverse_index(iota * 2, domain.lde_roots_of_unity_coset.len() as u64)]
.clone()
}
/// Returns the symmetric field element element of the domain `domain` corresponding to the given FRI query index challenge `iota`.
fn query_challenge_to_evaluation_point_sym(
iota: usize,
domain: &Domain<A::Field>,
) -> FieldElement<A::Field> {
domain.lde_roots_of_unity_coset
[reverse_index(iota * 2 + 1, domain.lde_roots_of_unity_coset.len() as u64)]
.clone()
}
/// Verifies the validity of the opening proof.
fn verify_opening<E>(
proof: &Proof<Commitment>,
root: &Commitment,
index: usize,
value: &[FieldElement<E>],
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<E>: AsBytes + Sync + Send,
E: IsField,
A::Field: IsSubFieldOf<E>,
{
proof.verify::<BatchedMerkleTreeBackend<E>>(root, index, &value.to_owned())
}
/// Verify opening Open(tⱼ(D_LDE), 𝜐) and Open(tⱼ(D_LDE), -𝜐) for all trace polynomials tⱼ,
/// where 𝜐 and -𝜐 are the elements corresponding to the index challenge `iota`.
fn verify_trace_openings(
proof: &StarkProof<A::Field, A::FieldExtension>,
deep_poly_openings: &DeepPolynomialOpening<A::Field, A::FieldExtension>,
iota: usize,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let index = iota * 2;
let index_sym = iota * 2 + 1;
let mut result = true;
result &= Self::verify_opening::<A::Field>(
&deep_poly_openings.main_trace_polys.proof,
&proof.lde_trace_main_merkle_root,
index,
&deep_poly_openings.main_trace_polys.evaluations,
);
result &= Self::verify_opening::<A::Field>(
&deep_poly_openings.main_trace_polys.proof_sym,
&proof.lde_trace_main_merkle_root,
index_sym,
&deep_poly_openings.main_trace_polys.evaluations_sym,
);
match (
proof.lde_trace_aux_merkle_root,
&deep_poly_openings.aux_trace_polys,
) {
(None, Some(_)) => result = false,
(Some(_), None) => result = false,
(Some(aux_root), Some(aux_trace_polys_opening)) => {
result &= Self::verify_opening::<A::FieldExtension>(
&aux_trace_polys_opening.proof,
&aux_root,
index,
&aux_trace_polys_opening.evaluations,
);
result &= Self::verify_opening::<A::FieldExtension>(
&aux_trace_polys_opening.proof_sym,
&aux_root,
index_sym,
&aux_trace_polys_opening.evaluations_sym,
);
}
_ => {}
}
result
}
/// Verify opening Open(Hᵢ(D_LDE), 𝜐) and Open(Hᵢ(D_LDE), -𝜐) for all parts Hᵢof the composition
/// polynomial, where 𝜐 and -𝜐 are the elements corresponding to the index challenge `iota`.
fn verify_composition_poly_opening(
deep_poly_openings: &DeepPolynomialOpening<A::Field, A::FieldExtension>,
composition_poly_merkle_root: &Commitment,
iota: &usize,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let mut value = deep_poly_openings.composition_poly.evaluations.clone();
value.extend_from_slice(&deep_poly_openings.composition_poly.evaluations_sym);
deep_poly_openings
.composition_poly
.proof
.verify::<BatchedMerkleTreeBackend<A::FieldExtension>>(
composition_poly_merkle_root,
*iota,
&value,
)
}
/// Verifies the validity of the purported values of the trace polynomials and the composition polynomial
/// parts at the domain elements and their symmetric counterparts corresponding to all the FRI query
/// index challenges.
fn step_4_verify_trace_and_composition_openings(
proof: &StarkProof<A::Field, A::FieldExtension>,
challenges: &Challenges<A>,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
challenges.iotas.iter().zip(&proof.deep_poly_openings).fold(
true,
|mut result, (iota_n, deep_poly_opening)| {
result &= Self::verify_composition_poly_opening(
deep_poly_opening,
&proof.composition_poly_root,
iota_n,
);
result &= Self::verify_trace_openings(proof, deep_poly_opening, *iota_n);
result
},
)
}
/// Verifies the openings of a fold polynomial of an inner layer of FRI.
fn verify_fri_layer_openings(
merkle_root: &Commitment,
auth_path_sym: &Proof<Commitment>,
evaluation: &FieldElement<A::FieldExtension>,
evaluation_sym: &FieldElement<A::FieldExtension>,
iota: usize,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let evaluations = if iota % 2 == 1 {
vec![evaluation_sym.clone(), evaluation.clone()]
} else {
vec![evaluation.clone(), evaluation_sym.clone()]
};
auth_path_sym.verify::<BatchedMerkleTreeBackend<A::FieldExtension>>(
merkle_root,
iota >> 1,
&evaluations,
)
}
/// Verify a single FRI query
/// `zetas`: the vector of all challenges sent by the verifier to the prover at the commit
/// phase to fold polynomials.
/// `iota`: the index challenge of this FRI query. This index uniquely determines two elements 𝜐 and -𝜐
/// of the evaluation domain of FRI layer 0.
/// `evaluation_point_inv`: precomputed value of 𝜐⁻¹.
/// `deep_composition_evaluation`: precomputed value of p₀(𝜐), where p₀ is the deep composition polynomial.
/// `deep_composition_evaluation_sym`: precomputed value of p₀(-𝜐), where p₀ is the deep composition polynomial.
fn verify_query_and_sym_openings(
proof: &StarkProof<A::Field, A::FieldExtension>,
zetas: &[FieldElement<A::FieldExtension>],
iota: usize,
fri_decommitment: &FriDecommitment<A::FieldExtension>,
evaluation_point_inv: FieldElement<A::Field>,
deep_composition_evaluation: &FieldElement<A::FieldExtension>,
deep_composition_evaluation_sym: &FieldElement<A::FieldExtension>,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
let fri_layers_merkle_roots = &proof.fri_layers_merkle_roots;
let evaluation_point_vec: Vec<FieldElement<A::Field>> =
core::iter::successors(Some(evaluation_point_inv.square()), |evaluation_point| {
Some(evaluation_point.square())
})
.take(fri_layers_merkle_roots.len())
.collect();
let p0_eval = deep_composition_evaluation;
let p0_eval_sym = deep_composition_evaluation_sym;
// Reconstruct p₁(𝜐²)
let mut v =
(p0_eval + p0_eval_sym) + evaluation_point_inv * &zetas[0] * (p0_eval - p0_eval_sym);
let mut index = iota;
// For each FRI layer, starting from the layer 1: use the proof to verify the validity of values pᵢ(−𝜐^(2ⁱ)) (given by the prover) and
// pᵢ(𝜐^(2ⁱ)) (computed on the previous iteration by the verifier). Then use them to obtain pᵢ₊₁(𝜐^(2ⁱ⁺¹)).
// Finally, check that the final value coincides with the given by the prover.
fri_layers_merkle_roots
.iter()
.enumerate()
.zip(&fri_decommitment.layers_auth_paths)
.zip(&fri_decommitment.layers_evaluations_sym)
.zip(evaluation_point_vec)
.fold(
true,
|result,
(
(((i, merkle_root), auth_path_sym), evaluation_sym),
evaluation_point_inv,
)| {
// Verify opening Open(pᵢ(Dₖ), −𝜐^(2ⁱ)) and Open(pᵢ(Dₖ), 𝜐^(2ⁱ)).
// `v` is pᵢ(𝜐^(2ⁱ)).
// `evaluation_sym` is pᵢ(−𝜐^(2ⁱ)).
let openings_ok = Self::verify_fri_layer_openings(
merkle_root,
auth_path_sym,
&v,
evaluation_sym,
index,
);
// Update `v` with next value pᵢ₊₁(𝜐^(2ⁱ⁺¹)).
v = (&v + evaluation_sym) + evaluation_point_inv * &zetas[i + 1] * (&v - evaluation_sym);
// Update index for next iteration. The index of the squares in the next layer
// is obtained by halving the current index. This is due to the bit-reverse
// ordering of the elements in the Merkle tree.
index >>= 1;
if i < fri_decommitment.layers_evaluations_sym.len() - 1 {
result & openings_ok
} else {
// Check that final value is the given by the prover
result & (v == proof.fri_last_value) & openings_ok
}
},
)
}
fn reconstruct_deep_composition_poly_evaluations_for_all_queries(
challenges: &Challenges<A>,
domain: &Domain<A::Field>,
proof: &StarkProof<A::Field, A::FieldExtension>,
) -> DeepPolynomialEvaluations<A::FieldExtension> {
let mut deep_poly_evaluations = Vec::new();
let mut deep_poly_evaluations_sym = Vec::new();
for (i, iota) in challenges.iotas.iter().enumerate() {
let primitive_root =
&A::Field::get_primitive_root_of_unity(domain.root_order as u64).unwrap();
let mut evaluations: Vec<FieldElement<A::FieldExtension>> = proof.deep_poly_openings[i]
.main_trace_polys
.evaluations
.clone()
.into_iter()
.map(|x| x.to_extension())
.collect();
if let Some(aux_trace_polys) = &proof.deep_poly_openings[i].aux_trace_polys {
evaluations.extend_from_slice(&aux_trace_polys.evaluations);
}
let evaluation_point = Self::query_challenge_to_evaluation_point(*iota, domain);
deep_poly_evaluations.push(Self::reconstruct_deep_composition_poly_evaluation(
proof,
&evaluation_point,
primitive_root,
challenges,
&evaluations,
&proof.deep_poly_openings[i].composition_poly.evaluations,
));
let mut evaluations_sym: Vec<FieldElement<A::FieldExtension>> = proof
.deep_poly_openings[i]
.main_trace_polys
.evaluations_sym
.clone()
.into_iter()
.map(|x| x.to_extension())
.collect();
if let Some(aux_trace_polys) = &proof.deep_poly_openings[i].aux_trace_polys {
evaluations_sym.extend_from_slice(&aux_trace_polys.evaluations_sym);
}
let evaluation_point = Self::query_challenge_to_evaluation_point_sym(*iota, domain);
deep_poly_evaluations_sym.push(Self::reconstruct_deep_composition_poly_evaluation(
proof,
&evaluation_point,
primitive_root,
challenges,
&evaluations_sym,
&proof.deep_poly_openings[i].composition_poly.evaluations_sym,
));
}
(deep_poly_evaluations, deep_poly_evaluations_sym)
}
fn reconstruct_deep_composition_poly_evaluation(
proof: &StarkProof<A::Field, A::FieldExtension>,
evaluation_point: &FieldElement<A::Field>,
primitive_root: &FieldElement<A::Field>,
challenges: &Challenges<A>,
lde_trace_evaluations: &[FieldElement<A::FieldExtension>],
lde_composition_poly_parts_evaluation: &[FieldElement<A::FieldExtension>],
) -> FieldElement<A::FieldExtension> {
let ood_evaluations_table_height = proof.trace_ood_evaluations.height;
let ood_evaluations_table_width = proof.trace_ood_evaluations.width;
let trace_term_coeffs = &challenges.trace_term_coeffs;
debug_assert_eq!(
ood_evaluations_table_height * ood_evaluations_table_width,
trace_term_coeffs.len() * trace_term_coeffs[0].len()
);
let mut denoms_trace = (0..ood_evaluations_table_height)
.map(|row_idx| evaluation_point - primitive_root.pow(row_idx as u64) * &challenges.z)
.collect::<Vec<FieldElement<A::FieldExtension>>>();
FieldElement::inplace_batch_inverse(&mut denoms_trace).unwrap();
let trace_term = (0..ood_evaluations_table_width)
.zip(&challenges.trace_term_coeffs)
.fold(FieldElement::zero(), |trace_terms, (col_idx, coeff_row)| {
let trace_i = (0..ood_evaluations_table_height).zip(coeff_row).fold(
FieldElement::zero(),
|trace_t, (row_idx, coeff)| {
let poly_evaluation = (lde_trace_evaluations[col_idx].clone()
- proof.trace_ood_evaluations.get_row(row_idx)[col_idx].clone())
* &denoms_trace[row_idx];
trace_t + &poly_evaluation * coeff
},
);
trace_terms + trace_i
});
let number_of_parts = lde_composition_poly_parts_evaluation.len();
let z_pow = &challenges.z.pow(number_of_parts);
let denom_composition = (evaluation_point - z_pow).inv().unwrap();
let mut h_terms = FieldElement::zero();
for (j, h_i_upsilon) in lde_composition_poly_parts_evaluation.iter().enumerate() {
let h_i_zpower = &proof.composition_poly_parts_ood_evaluation[j];
let h_i_term = (h_i_upsilon - h_i_zpower) * &challenges.gammas[j];
h_terms += h_i_term;
}
h_terms *= denom_composition;
trace_term + h_terms
}
/// Verifies a STARK proof with public inputs `pub_inputs`.
/// Warning: the transcript must be safely initializated before passing it to this method.
fn verify(
proof: &StarkProof<A::Field, A::FieldExtension>,
pub_input: &A::PublicInputs,
proof_options: &ProofOptions,
mut transcript: impl IsTranscript<A::FieldExtension>,
) -> bool
where
FieldElement<A::Field>: AsBytes + Sync + Send,
FieldElement<A::FieldExtension>: AsBytes + Sync + Send,
{
// Verify there are enough queries
if proof.query_list.len() < proof_options.fri_number_of_queries {
return false;
}
#[cfg(feature = "instruments")]
println!("- Started step 1: Recover challenges");
#[cfg(feature = "instruments")]
let timer1 = Instant::now();
let air = A::new(proof.trace_length, pub_input, proof_options);
let domain = Domain::new(&air);
let challenges = Self::step_1_replay_rounds_and_recover_challenges(
&air,
proof,
&domain,
&mut transcript,
);
// verify grinding
let security_bits = air.context().proof_options.grinding_factor;
if security_bits > 0 {
let nonce_is_valid = proof.nonce.map_or(false, |nonce_value| {
grinding::is_valid_nonce(&challenges.grinding_seed, nonce_value, security_bits)
});
if !nonce_is_valid {
error!("Grinding factor not satisfied");
return false;
}
}
#[cfg(feature = "instruments")]
let elapsed1 = timer1.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed1);
#[cfg(feature = "instruments")]
println!("- Started step 2: Verify claimed polynomial");
#[cfg(feature = "instruments")]
let timer2 = Instant::now();
if !Self::step_2_verify_claimed_composition_polynomial(&air, proof, &domain, &challenges) {
error!("Composition Polynomial verification failed");
return false;
}
#[cfg(feature = "instruments")]
let elapsed2 = timer2.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed2);
#[cfg(feature = "instruments")]
println!("- Started step 3: Verify FRI");
#[cfg(feature = "instruments")]
let timer3 = Instant::now();
if !Self::step_3_verify_fri(proof, &domain, &challenges) {
error!("FRI verification failed");
return false;
}
#[cfg(feature = "instruments")]
let elapsed3 = timer3.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed3);
#[cfg(feature = "instruments")]
println!("- Started step 4: Verify deep composition polynomial");
#[cfg(feature = "instruments")]
let timer4 = Instant::now();
#[allow(clippy::let_and_return)]
if !Self::step_4_verify_trace_and_composition_openings(proof, &challenges) {
error!("DEEP Composition Polynomial verification failed");
return false;
}
#[cfg(feature = "instruments")]
let elapsed4 = timer4.elapsed();
#[cfg(feature = "instruments")]
println!(" Time spent: {:?}", elapsed4);
#[cfg(feature = "instruments")]
{
let total_time = elapsed1 + elapsed2 + elapsed3 + elapsed4;
println!(
" Fraction of verifying time per step: {:.4} {:.4} {:.4} {:.4}",
elapsed1.as_nanos() as f64 / total_time.as_nanos() as f64,
elapsed2.as_nanos() as f64 / total_time.as_nanos() as f64,
elapsed3.as_nanos() as f64 / total_time.as_nanos() as f64,
elapsed4.as_nanos() as f64 / total_time.as_nanos() as f64
);
}
true
}
}