winter_verifier/lib.rs
1// Copyright (c) Facebook, Inc. and its affiliates.
2//
3// This source code is licensed under the MIT license found in the
4// LICENSE file in the root directory of this source tree.
5
6//! This crate contains Winterfell STARK verifier.
7//!
8//! This verifier can be used to verify STARK proofs generated by the Winterfell STARK prover.
9//!
10//! # Usage
11//! To verify a proof that a computation was executed correctly, you'll need to do the following:
12//!
13//! 1. Define an *algebraic intermediate representation* (AIR) for you computation. This can be done
14//! by implementing [Air] trait.
15//! 2. Execute [verify()] function and supply the AIR of your computation together with the [Proof]
16//! and related public inputs as parameters.
17//!
18//! # Performance
19//! Proof verification is extremely fast and is nearly independent of the complexity of the
20//! computation being verified. In vast majority of cases proofs can be verified in 3 - 5 ms
21//! on a modern mid-range laptop CPU (using a single core).
22//!
23//! There is one exception, however: if a computation requires a lot of `sequence` assertions
24//! (see [Assertion] for more info), the verification time will grow linearly in the number of
25//! asserted values. But for the impact to be noticeable, the number of asserted values would
26//! need to be in tens of thousands. And even for hundreds of thousands of asserted values, the
27//! verification time should not exceed 50 ms.
28
29#![no_std]
30
31#[macro_use]
32extern crate alloc;
33
34use alloc::vec::Vec;
35use core::cmp;
36
37pub use air::{
38 proof::Proof, Air, AirContext, Assertion, BoundaryConstraint, BoundaryConstraintGroup,
39 ConstraintCompositionCoefficients, ConstraintDivisor, DeepCompositionCoefficients,
40 EvaluationFrame, FieldExtension, ProofOptions, TraceInfo, TransitionConstraintDegree,
41};
42pub use crypto;
43use crypto::{ElementHasher, Hasher, RandomCoin, VectorCommitment};
44use fri::FriVerifier;
45pub use math;
46use math::{
47 fields::{CubeExtension, QuadExtension},
48 FieldElement, ToElements,
49};
50pub use utils::{
51 ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, SliceReader,
52};
53
54mod channel;
55use channel::VerifierChannel;
56
57mod evaluator;
58use evaluator::evaluate_constraints;
59
60mod composer;
61use composer::DeepComposer;
62
63mod errors;
64pub use errors::VerifierError;
65
66// VERIFIER
67// ================================================================================================
68
69/// Verifies that the specified computation was executed correctly against the specified inputs.
70///
71/// Specifically, for a computation specified by `AIR` and `HashFn` type parameter, verifies that
72/// the provided `proof` attests to the correct execution of the computation against public inputs
73/// specified by `pub_inputs`. If the verification is successful, `Ok(())` is returned.
74///
75/// # Errors
76/// Returns an error if combination of the provided proof and public inputs does not attest to
77/// a correct execution of the computation. This could happen for many various reasons, including:
78/// - The specified proof was generated for a different computation.
79/// - The specified proof was generated for this computation but for different public inputs.
80/// - The specified proof was generated with parameters not providing an acceptable security level.
81pub fn verify<AIR, HashFn, RandCoin, VC>(
82 proof: Proof,
83 pub_inputs: AIR::PublicInputs,
84 acceptable_options: &AcceptableOptions,
85) -> Result<(), VerifierError>
86where
87 AIR: Air,
88 HashFn: ElementHasher<BaseField = AIR::BaseField>,
89 RandCoin: RandomCoin<BaseField = AIR::BaseField, Hasher = HashFn>,
90 VC: VectorCommitment<HashFn>,
91{
92 // check that `proof` was generated with an acceptable set of parameters from the point of view
93 // of the verifier
94 acceptable_options.validate::<HashFn>(&proof)?;
95
96 // build a seed for the public coin; the initial seed is a hash of the proof context and the
97 // public inputs, but as the protocol progresses, the coin will be reseeded with the info
98 // received from the prover
99 let mut public_coin_seed = proof.context.to_elements();
100 public_coin_seed.append(&mut pub_inputs.to_elements());
101
102 // create AIR instance for the computation specified in the proof
103 let air = AIR::new(proof.trace_info().clone(), pub_inputs, proof.options().clone());
104
105 // figure out which version of the generic proof verification procedure to run. this is a sort
106 // of static dispatch for selecting two generic parameter: extension field and hash function.
107 match air.options().field_extension() {
108 FieldExtension::None => {
109 let public_coin = RandCoin::new(&public_coin_seed);
110 let channel = VerifierChannel::new(&air, proof)?;
111 perform_verification::<AIR, AIR::BaseField, HashFn, RandCoin, VC>(
112 air,
113 channel,
114 public_coin,
115 )
116 },
117 FieldExtension::Quadratic => {
118 if !<QuadExtension<AIR::BaseField>>::is_supported() {
119 return Err(VerifierError::UnsupportedFieldExtension(2));
120 }
121 let public_coin = RandCoin::new(&public_coin_seed);
122 let channel = VerifierChannel::new(&air, proof)?;
123 perform_verification::<AIR, QuadExtension<AIR::BaseField>, HashFn, RandCoin, VC>(
124 air,
125 channel,
126 public_coin,
127 )
128 },
129 FieldExtension::Cubic => {
130 if !<CubeExtension<AIR::BaseField>>::is_supported() {
131 return Err(VerifierError::UnsupportedFieldExtension(3));
132 }
133 let public_coin = RandCoin::new(&public_coin_seed);
134 let channel = VerifierChannel::new(&air, proof)?;
135 perform_verification::<AIR, CubeExtension<AIR::BaseField>, HashFn, RandCoin, VC>(
136 air,
137 channel,
138 public_coin,
139 )
140 },
141 }
142}
143
144// VERIFICATION PROCEDURE
145// ================================================================================================
146/// Performs the actual verification by reading the data from the `channel` and making sure it
147/// attests to a correct execution of the computation specified by the provided `air`.
148fn perform_verification<A, E, H, R, V>(
149 air: A,
150 mut channel: VerifierChannel<E, H, V>,
151 mut public_coin: R,
152) -> Result<(), VerifierError>
153where
154 E: FieldElement<BaseField = A::BaseField>,
155 A: Air,
156 H: ElementHasher<BaseField = A::BaseField>,
157 R: RandomCoin<BaseField = A::BaseField, Hasher = H>,
158 V: VectorCommitment<H>,
159{
160 // 1 ----- trace commitment -------------------------------------------------------------------
161 // Read the commitments to evaluations of the trace polynomials over the LDE domain sent by the
162 // prover. The commitments are used to update the public coin, and draw sets of random elements
163 // from the coin (in the interactive version of the protocol the verifier sends these random
164 // elements to the prover after each commitment is made). When there are multiple trace
165 // commitments (i.e., the trace consists of more than one segment), each previous commitment is
166 // used to draw random elements needed to construct the next trace segment. The last trace
167 // commitment is used to draw a set of random coefficients which the prover uses to compute
168 // constraint composition polynomial.
169 const MAIN_TRACE_IDX: usize = 0;
170 const AUX_TRACE_IDX: usize = 1;
171 let trace_commitments = channel.read_trace_commitments();
172
173 // reseed the coin with the commitment to the main trace segment
174 public_coin.reseed(trace_commitments[MAIN_TRACE_IDX]);
175
176 // process auxiliary trace segments (if any), to build a set of random elements for each segment
177 let aux_trace_rand_elements = if air.trace_info().is_multi_segment() {
178 let aux_rand_elements = air
179 .get_aux_rand_elements(&mut public_coin)
180 .expect("failed to generate the random elements needed to build the auxiliary trace");
181
182 public_coin.reseed(trace_commitments[AUX_TRACE_IDX]);
183
184 Some(aux_rand_elements)
185 } else {
186 None
187 };
188
189 // build random coefficients for the composition polynomial
190 let constraint_coeffs = air
191 .get_constraint_composition_coefficients(&mut public_coin)
192 .map_err(|_| VerifierError::RandomCoinError)?;
193
194 // 2 ----- constraint commitment --------------------------------------------------------------
195 // read the commitment to evaluations of the constraint composition polynomial over the LDE
196 // domain sent by the prover, use it to update the public coin, and draw an out-of-domain point
197 // z from the coin; in the interactive version of the protocol, the verifier sends this point z
198 // to the prover, and the prover evaluates trace and constraint composition polynomials at z,
199 // and sends the results back to the verifier.
200 let constraint_commitment = channel.read_constraint_commitment();
201 public_coin.reseed(constraint_commitment);
202 let z = public_coin.draw::<E>().map_err(|_| VerifierError::RandomCoinError)?;
203
204 // 3 ----- OOD consistency check --------------------------------------------------------------
205 // make sure that evaluations obtained by evaluating constraints over the out-of-domain frame
206 // are consistent with the evaluations of composition polynomial columns sent by the prover
207
208 // read the out-of-domain trace frames (the main trace frame and auxiliary trace frame, if
209 // provided) sent by the prover and evaluate constraints over them; also, reseed the public
210 // coin with the OOD frames received from the prover.
211 let ood_trace_frame = channel.read_ood_trace_frame();
212 let ood_main_trace_frame = ood_trace_frame.main_frame();
213 let ood_aux_trace_frame = ood_trace_frame.aux_frame();
214 let ood_constraint_evaluation_1 = evaluate_constraints(
215 &air,
216 constraint_coeffs,
217 &ood_main_trace_frame,
218 &ood_aux_trace_frame,
219 aux_trace_rand_elements.as_ref(),
220 z,
221 );
222 public_coin.reseed(ood_trace_frame.hash::<H>());
223
224 // read evaluations of composition polynomial columns sent by the prover, and reduce them into
225 // a single value by computing \sum_{i=0}^{m-1}(z^(i * l) * value_i), where value_i is the
226 // evaluation of the ith column polynomial H_i(X) at z, l is the trace length and m is
227 // the number of composition column polynomials. This computes H(z) (i.e.
228 // the evaluation of the composition polynomial at z) using the fact that
229 // H(X) = \sum_{i=0}^{m-1} X^{i * l} H_i(X).
230 // Also, reseed the public coin with the OOD constraint evaluations received from the prover.
231 let ood_constraint_evaluations = channel.read_ood_constraint_frame();
232 let ood_constraint_evaluation_2 = ood_constraint_evaluations
233 .current_row()
234 .iter()
235 .enumerate()
236 .fold(E::ZERO, |result, (i, &value)| {
237 result + z.exp_vartime(((i * (air.trace_length())) as u32).into()) * value
238 });
239
240 let ood_constraint_hash = ood_constraint_evaluations.hash::<H>();
241 public_coin.reseed(ood_constraint_hash);
242
243 // finally, make sure the values are the same
244 if ood_constraint_evaluation_1 != ood_constraint_evaluation_2 {
245 return Err(VerifierError::InconsistentOodConstraintEvaluations);
246 }
247
248 // 4 ----- FRI commitments --------------------------------------------------------------------
249 // draw coefficients for computing DEEP composition polynomial from the public coin; in the
250 // interactive version of the protocol, the verifier sends these coefficients to the prover
251 // and the prover uses them to compute the DEEP composition polynomial. the prover, then
252 // applies FRI protocol to the evaluations of the DEEP composition polynomial.
253 let deep_coefficients = air
254 .get_deep_composition_coefficients::<E, R>(&mut public_coin)
255 .map_err(|_| VerifierError::RandomCoinError)?;
256
257 // instantiates a FRI verifier with the FRI layer commitments read from the channel. From the
258 // verifier's perspective, this is equivalent to executing the commit phase of the FRI protocol.
259 // The verifier uses these commitments to update the public coin and draw random points alpha
260 // from them; in the interactive version of the protocol, the verifier sends these alphas to
261 // the prover, and the prover uses them to compute and commit to the subsequent FRI layers.
262 let fri_verifier = FriVerifier::new(
263 &mut channel,
264 &mut public_coin,
265 air.options().to_fri_options(),
266 air.trace_poly_degree(),
267 )
268 .map_err(VerifierError::FriVerificationFailed)?;
269 // TODO: make sure air.lde_domain_size() == fri_verifier.domain_size()
270
271 // 5 ----- trace and constraint queries -------------------------------------------------------
272 // read proof-of-work nonce sent by the prover
273 let pow_nonce = channel.read_pow_nonce();
274
275 // make sure the proof-of-work specified by the grinding factor is satisfied
276 if public_coin.check_leading_zeros(pow_nonce) < air.options().grinding_factor() {
277 return Err(VerifierError::QuerySeedProofOfWorkVerificationFailed);
278 }
279
280 // draw pseudo-random query positions for the LDE domain from the public coin; in the
281 // interactive version of the protocol, the verifier sends these query positions to the prover,
282 // and the prover responds with decommitments against these positions for trace and constraint
283 // composition polynomial evaluations.
284 let mut query_positions = public_coin
285 .draw_integers(air.options().num_queries(), air.lde_domain_size(), pow_nonce)
286 .map_err(|_| VerifierError::RandomCoinError)?;
287
288 // remove any potential duplicates from the positions as the prover will send openings only
289 // for unique queries
290 query_positions.sort_unstable();
291 query_positions.dedup();
292
293 // read evaluations of trace and constraint composition polynomials at the queried positions;
294 // this also checks that the read values are valid against trace and constraint commitments
295 let (queried_main_trace_states, queried_aux_trace_states) =
296 channel.read_queried_trace_states(&query_positions)?;
297 let queried_constraint_evaluations = channel.read_constraint_evaluations(&query_positions)?;
298
299 // 6 ----- DEEP composition -------------------------------------------------------------------
300 // compute evaluations of the DEEP composition polynomial at the queried positions
301 let composer = DeepComposer::new(&air, &query_positions, z, deep_coefficients);
302 let deep_evaluations = composer.compose_columns(
303 queried_main_trace_states,
304 queried_aux_trace_states,
305 queried_constraint_evaluations,
306 ood_main_trace_frame,
307 ood_aux_trace_frame,
308 ood_constraint_evaluations,
309 );
310
311 // 7 ----- Verify low-degree proof -------------------------------------------------------------
312 // make sure that evaluations of the DEEP composition polynomial we computed in the previous
313 // step are in fact evaluations of a polynomial of degree equal to trace polynomial degree
314 fri_verifier
315 .verify(&mut channel, &deep_evaluations, &query_positions)
316 .map_err(VerifierError::FriVerificationFailed)
317}
318
319// ACCEPTABLE OPTIONS
320// ================================================================================================
321// Specifies either the minimal, conjectured or proven, security level or a set of
322// `ProofOptions` that are acceptable by the verification procedure.
323pub enum AcceptableOptions {
324 /// Minimal acceptable conjectured security level
325 MinConjecturedSecurity(u32),
326 /// Minimal acceptable proven security level
327 MinProvenSecurity(u32),
328 /// Set of acceptable proof parameters
329 OptionSet(Vec<ProofOptions>),
330}
331
332impl AcceptableOptions {
333 /// Checks that a proof was generated using an acceptable set of parameters.
334 pub fn validate<H: Hasher>(&self, proof: &Proof) -> Result<(), VerifierError> {
335 match self {
336 AcceptableOptions::MinConjecturedSecurity(minimal_security) => {
337 let conjectured_security = proof.conjectured_security::<H>();
338 if !conjectured_security.is_at_least(*minimal_security) {
339 return Err(VerifierError::InsufficientConjecturedSecurity(
340 *minimal_security,
341 conjectured_security.bits(),
342 ));
343 }
344 },
345 AcceptableOptions::MinProvenSecurity(minimal_security) => {
346 let proven_security = proof.proven_security::<H>();
347 if !proven_security.is_at_least(*minimal_security) {
348 return Err(VerifierError::InsufficientProvenSecurity(
349 *minimal_security,
350 cmp::max(proven_security.ldr_bits(), proven_security.udr_bits()),
351 ));
352 }
353 },
354 AcceptableOptions::OptionSet(options) => {
355 if !options.iter().any(|opt| opt == proof.options()) {
356 return Err(VerifierError::UnacceptableProofOptions);
357 }
358 },
359 }
360 Ok(())
361 }
362}