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_evaluations();
232    let ood_constraint_evaluation_2 =
233        ood_constraint_evaluations
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    public_coin.reseed(H::hash_elements(&ood_constraint_evaluations));
240
241    // finally, make sure the values are the same
242    if ood_constraint_evaluation_1 != ood_constraint_evaluation_2 {
243        return Err(VerifierError::InconsistentOodConstraintEvaluations);
244    }
245
246    // 4 ----- FRI commitments --------------------------------------------------------------------
247    // draw coefficients for computing DEEP composition polynomial from the public coin; in the
248    // interactive version of the protocol, the verifier sends these coefficients to the prover
249    // and the prover uses them to compute the DEEP composition polynomial. the prover, then
250    // applies FRI protocol to the evaluations of the DEEP composition polynomial.
251    let deep_coefficients = air
252        .get_deep_composition_coefficients::<E, R>(&mut public_coin)
253        .map_err(|_| VerifierError::RandomCoinError)?;
254
255    // instantiates a FRI verifier with the FRI layer commitments read from the channel. From the
256    // verifier's perspective, this is equivalent to executing the commit phase of the FRI protocol.
257    // The verifier uses these commitments to update the public coin and draw random points alpha
258    // from them; in the interactive version of the protocol, the verifier sends these alphas to
259    // the prover, and the prover uses them to compute and commit to the subsequent FRI layers.
260    let fri_verifier = FriVerifier::new(
261        &mut channel,
262        &mut public_coin,
263        air.options().to_fri_options(),
264        air.trace_poly_degree(),
265    )
266    .map_err(VerifierError::FriVerificationFailed)?;
267    // TODO: make sure air.lde_domain_size() == fri_verifier.domain_size()
268
269    // 5 ----- trace and constraint queries -------------------------------------------------------
270    // read proof-of-work nonce sent by the prover
271    let pow_nonce = channel.read_pow_nonce();
272
273    // make sure the proof-of-work specified by the grinding factor is satisfied
274    if public_coin.check_leading_zeros(pow_nonce) < air.options().grinding_factor() {
275        return Err(VerifierError::QuerySeedProofOfWorkVerificationFailed);
276    }
277
278    // draw pseudo-random query positions for the LDE domain from the public coin; in the
279    // interactive version of the protocol, the verifier sends these query positions to the prover,
280    // and the prover responds with decommitments against these positions for trace and constraint
281    // composition polynomial evaluations.
282    let mut query_positions = public_coin
283        .draw_integers(air.options().num_queries(), air.lde_domain_size(), pow_nonce)
284        .map_err(|_| VerifierError::RandomCoinError)?;
285
286    // remove any potential duplicates from the positions as the prover will send openings only
287    // for unique queries
288    query_positions.sort_unstable();
289    query_positions.dedup();
290
291    // read evaluations of trace and constraint composition polynomials at the queried positions;
292    // this also checks that the read values are valid against trace and constraint commitments
293    let (queried_main_trace_states, queried_aux_trace_states) =
294        channel.read_queried_trace_states(&query_positions)?;
295    let queried_constraint_evaluations = channel.read_constraint_evaluations(&query_positions)?;
296
297    // 6 ----- DEEP composition -------------------------------------------------------------------
298    // compute evaluations of the DEEP composition polynomial at the queried positions
299    let composer = DeepComposer::new(&air, &query_positions, z, deep_coefficients);
300    let t_composition = composer.compose_trace_columns(
301        queried_main_trace_states,
302        queried_aux_trace_states,
303        ood_main_trace_frame,
304        ood_aux_trace_frame,
305    );
306    let c_composition = composer
307        .compose_constraint_evaluations(queried_constraint_evaluations, ood_constraint_evaluations);
308    let deep_evaluations = composer.combine_compositions(t_composition, c_composition);
309
310    // 7 ----- Verify low-degree proof -------------------------------------------------------------
311    // make sure that evaluations of the DEEP composition polynomial we computed in the previous
312    // step are in fact evaluations of a polynomial of degree equal to trace polynomial degree
313    fri_verifier
314        .verify(&mut channel, &deep_evaluations, &query_positions)
315        .map_err(VerifierError::FriVerificationFailed)
316}
317
318// ACCEPTABLE OPTIONS
319// ================================================================================================
320// Specifies either the minimal, conjectured or proven, security level or a set of
321// `ProofOptions` that are acceptable by the verification procedure.
322pub enum AcceptableOptions {
323    /// Minimal acceptable conjectured security level
324    MinConjecturedSecurity(u32),
325    /// Minimal acceptable proven security level
326    MinProvenSecurity(u32),
327    /// Set of acceptable proof parameters
328    OptionSet(Vec<ProofOptions>),
329}
330
331impl AcceptableOptions {
332    /// Checks that a proof was generated using an acceptable set of parameters.
333    pub fn validate<H: Hasher>(&self, proof: &Proof) -> Result<(), VerifierError> {
334        match self {
335            AcceptableOptions::MinConjecturedSecurity(minimal_security) => {
336                let conjectured_security = proof.conjectured_security::<H>();
337                if !conjectured_security.is_at_least(*minimal_security) {
338                    return Err(VerifierError::InsufficientConjecturedSecurity(
339                        *minimal_security,
340                        conjectured_security.bits(),
341                    ));
342                }
343            },
344            AcceptableOptions::MinProvenSecurity(minimal_security) => {
345                let proven_security = proof.proven_security::<H>();
346                if !proven_security.is_at_least(*minimal_security) {
347                    return Err(VerifierError::InsufficientProvenSecurity(
348                        *minimal_security,
349                        cmp::max(proven_security.ldr_bits(), proven_security.udr_bits()),
350                    ));
351                }
352            },
353            AcceptableOptions::OptionSet(options) => {
354                if !options.iter().any(|opt| opt == proof.options()) {
355                    return Err(VerifierError::UnacceptableProofOptions);
356                }
357            },
358        }
359        Ok(())
360    }
361}