1use std::marker::PhantomData;
5
6use binius_core::{
7 constraint_system::{ConstraintSystem, InoutSegment},
8 word::Word,
9};
10use binius_field::{BinaryField, ExtensionField, FieldOps, Rijndael8b as B8};
11use binius_hash::HashSuite;
12use binius_iop::{
13 basefold::compiler::BaseFoldVerifierCompiler,
14 channel::{IOPVerifierChannel, OracleSchedule, oracle_setup::OracleSetupChannel},
15};
16use binius_ip::channel::{IPVerifierChannel, WordIPVerifierChannel};
17use binius_math::{BinarySubspace, univariate::EvaluationDomain};
18use binius_transcript::{VerifierTranscript, fiat_shamir::Challenger};
19use binius_utils::DeserializeBytes;
20use digest::Output;
21use itertools::chain;
22
23use super::error::Error;
24use crate::{
25 config::{B1, B128, LOG_WORDS_PER_ELEM, PROVER_SMALL_FIELD_ZEROCHECK_CHALLENGES},
26 fri::{FRIParams, calculate_n_test_queries},
27 merkle_tree::BinaryMerkleTreeScheme,
28 protocols::{
29 bitand::{AndCheckOutput, UnivariateSkipOutput, verify_univariate_skip},
30 rerand::{self, OperandClaims},
31 shift::{self, WiringEvalClaim, WiringInfo},
32 },
33 reduction::{ReductionOutput, reduce_constraints, verify_public_eval},
34 ring_switch,
35};
36
37pub const SECURITY_BITS: usize = 96;
38
39#[derive(Debug, Clone)]
45pub struct IOPVerifier {
46 constraint_system: ConstraintSystem,
47 log_public_words: usize,
48 wiring: WiringInfo,
50}
51
52impl IOPVerifier {
53 pub fn new(constraint_system: ConstraintSystem, log_public_words: usize) -> Self {
61 let wiring = WiringInfo::new(&constraint_system, InoutSegment::Public);
62 Self {
63 constraint_system,
64 log_public_words,
65 wiring,
66 }
67 }
68
69 pub const fn constraint_system(&self) -> &ConstraintSystem {
71 &self.constraint_system
72 }
73
74 pub fn into_constraint_system(self) -> ConstraintSystem {
76 self.constraint_system
77 }
78
79 pub const fn wiring(&self) -> &WiringInfo {
81 &self.wiring
82 }
83
84 pub const fn log_public_words(&self) -> usize {
86 self.log_public_words
87 }
88
89 pub const fn log_witness_elems(&self) -> usize {
101 let log_segment_words = self
102 .constraint_system
103 .log_segment_words(InoutSegment::Public);
104 assert!(
105 log_segment_words >= LOG_WORDS_PER_ELEM,
106 "the committed trace is a whole number of field elements, so the wider value \
107 segment spans at least that many words"
108 );
109 log_segment_words - LOG_WORDS_PER_ELEM
110 }
111
112 pub const fn n_witness_elems(&self) -> usize {
114 self.constraint_system
115 .n_hidden_words(InoutSegment::Public)
116 .div_ceil(1 << LOG_WORDS_PER_ELEM)
117 }
118
119 pub const fn log_witness_words(&self) -> usize {
121 self.log_witness_elems() + LOG_WORDS_PER_ELEM
122 }
123
124 pub fn oracle_schedule(&self, is_zk: bool) -> OracleSchedule {
138 let mut channel = OracleSetupChannel::new(is_zk);
139 let inout = vec![Word::ZERO; self.constraint_system.n_inout];
142 let _ = self.verify(&inout, &mut channel);
146 channel.into_oracle_schedule()
147 }
148
149 pub fn verify<Channel>(
163 &self,
164 inout: &[Channel::Word],
165 channel: &mut Channel,
166 ) -> Result<WiringEvalClaim<'_, Channel::Elem>, Error>
167 where
168 Channel: IOPVerifierChannel<B128> + WordIPVerifierChannel<B128>,
169 Channel::Elem: FieldOps<Scalar = B128> + From<B128>,
170 {
171 if inout.len() != self.constraint_system.n_inout {
175 return Err(Error::IncorrectPublicInputLength {
176 expected: self.constraint_system.n_inout,
177 actual: inout.len(),
178 });
179 }
180
181 let public = self
185 .constraint_system
186 .constants
187 .iter()
188 .map(|&word| Channel::Word::from(word))
189 .chain(inout.iter().cloned())
190 .collect::<Vec<_>>();
191
192 let _verify_guard =
193 tracing::info_span!("Verify", operation = "verify", perfetto_category = "operation")
194 .entered();
195
196 let trace_oracle = channel.recv_oracle(self.n_witness_elems(), true)?;
199
200 let cs = self.constraint_system();
202 let ReductionOutput {
204 r_x,
205 z_challenge,
206 operand_claims,
207 ..
208 } = reduce_constraints(cs, 0, channel)?;
209
210 let shift_output = {
212 let _guard = tracing::info_span!(
213 "[phase] Verify Shift Reduction",
214 phase = "verify_shift_reduction",
215 perfetto_category = "phase"
216 )
217 .entered();
218 shift::verify::<B128, _>(
219 cs.log_segment_words(InoutSegment::Public),
220 &operand_claims,
221 channel,
222 )?
223 };
224 let shift::VerifyOutput {
225 r_j,
226 r_y,
227 witness_eval,
228 ..
229 } = &shift_output;
230
231 let wiring = {
233 let _guard = tracing::info_span!(
234 "[phase] Verify Public Input",
235 phase = "verify_public_input",
236 perfetto_category = "phase"
237 )
238 .entered();
239 let public_eval =
240 verify_public_eval(cs, InoutSegment::Public, &public, r_j, r_y, channel)?;
241 let shift_domain = BinarySubspace::<B8>::with_dim(Word::LOG_BITS).isomorphic::<B128>();
242 shift::check_eval::<B128, _>(
243 &self.wiring,
244 public_eval,
245 &r_x,
246 &shift_domain,
247 &z_challenge,
248 &shift_output,
249 channel,
250 )?
251 };
252
253 let pcs_guard = tracing::info_span!(
255 "[phase] Verify PCS Opening",
256 phase = "verify_pcs_opening",
257 perfetto_category = "phase"
258 )
259 .entered();
260
261 let eval_point = [r_j.as_slice(), r_y].concat();
264 let ring_switch::RingSwitchVerifyOutput {
265 eq_r_double_prime,
266 sumcheck_claim,
267 } = ring_switch::verify(witness_eval.clone(), &eval_point, channel)?;
268
269 let log_packing = <B128 as ExtensionField<B1>>::LOG_DEGREE;
270 let eval_point_high = eval_point[log_packing..].to_vec();
271
272 let n_witness_elems = self.n_witness_elems();
273 let transparent = Box::new(move |point: &[Channel::Elem]| {
274 ring_switch::eval_rs_eq(
275 n_witness_elems,
276 &eval_point_high,
277 point,
278 eq_r_double_prime.as_ref(),
279 )
280 });
281
282 channel.verify_oracle_relation(trace_oracle, transparent, sumcheck_claim)?;
286
287 drop(pcs_guard);
288
289 Ok(wiring)
290 }
291
292 pub fn verify_statement<Channel>(
298 &self,
299 inout: &[Word],
300 channel: &mut Channel,
301 ) -> Result<(), Error>
302 where
303 Channel: IOPVerifierChannel<B128, Elem = B128> + WordIPVerifierChannel<B128>,
304 {
305 let inout = channel.observe_words(inout);
306 self.verify(&inout, channel)?.check_native()?;
307 Ok(())
308 }
309}
310
311#[derive(Clone)]
316pub struct Verifier<H: HashSuite> {
317 iop_verifier: IOPVerifier,
319 iop_compiler: BaseFoldVerifierCompiler<B128>,
321 _hash_marker: PhantomData<H>,
323}
324
325impl<H> Verifier<H>
326where
327 H: HashSuite,
328 Output<H::LeafHash>: DeserializeBytes,
329{
330 pub fn setup(constraint_system: ConstraintSystem, log_inv_rate: usize) -> Result<Self, Error> {
338 constraint_system.validate()?;
339
340 let log_public_words = constraint_system.log_public_words(InoutSegment::Public);
341
342 let iop_verifier = IOPVerifier::new(constraint_system, log_public_words);
343
344 let oracle_schedule = iop_verifier.oracle_schedule(false);
347
348 let merkle_scheme = BinaryMerkleTreeScheme::<B128, H>::new();
349
350 let n_test_queries = calculate_n_test_queries(SECURITY_BITS, log_inv_rate);
352
353 let iop_compiler = BaseFoldVerifierCompiler::new(
354 &merkle_scheme,
355 oracle_schedule,
356 log_inv_rate,
357 n_test_queries,
358 );
359
360 Ok(Self {
361 iop_verifier,
362 iop_compiler,
363 _hash_marker: PhantomData,
364 })
365 }
366
367 pub const fn iop_verifier(&self) -> &IOPVerifier {
369 &self.iop_verifier
370 }
371
372 pub fn into_iop_verifier(self) -> IOPVerifier {
374 self.iop_verifier
375 }
376
377 pub const fn log_witness_words(&self) -> usize {
379 self.iop_verifier.log_witness_words()
380 }
381
382 pub const fn log_witness_elems(&self) -> usize {
384 self.iop_verifier.log_witness_elems()
385 }
386
387 pub const fn constraint_system(&self) -> &ConstraintSystem {
389 self.iop_verifier.constraint_system()
390 }
391
392 pub const fn fri_params(&self) -> &FRIParams<B128> {
394 self.iop_compiler.fri_params()
395 }
396
397 pub const fn log_public_words(&self) -> usize {
399 self.iop_verifier.log_public_words()
400 }
401
402 pub const fn iop_compiler(&self) -> &BaseFoldVerifierCompiler<B128> {
404 &self.iop_compiler
405 }
406
407 pub fn verify<Challenger_: Challenger>(
408 &self,
409 inout: &[Word],
410 transcript: &mut VerifierTranscript<Challenger_>,
411 ) -> Result<(), Error> {
412 let cs = self.iop_verifier.constraint_system();
413
414 let _verify_scope = tracing::info_span!(
415 "Verify",
416 n_hidden_words = cs.n_hidden_words(InoutSegment::Public),
417 n_bitand = cs.and_constraints.len(),
418 n_intmul = cs.imul_constraints.len(),
419 )
420 .entered();
421
422 let mut channel = self
423 .iop_compiler
424 .create_channel_from_transcript::<H, Challenger_, _>(transcript);
425 self.iop_verifier.verify_statement(inout, &mut channel)?;
426 channel.finish()?;
427 Ok(())
428 }
429}
430
431pub fn verify_bitand_reduction<F, C>(
454 log_constraint_count: usize,
455 eval_domain: &BinarySubspace<F>,
456 operands: &[OperandClaims<'_, C::Elem>],
457 channel: &mut C,
458) -> Result<AndCheckOutput<C::Elem>, Error>
459where
460 F: BinaryField + From<B8>,
461 C: IPVerifierChannel<F>,
462 C::Elem: From<F>,
464{
465 let small_field_zerocheck_challenges = PROVER_SMALL_FIELD_ZEROCHECK_CHALLENGES
466 .into_iter()
467 .take(log_constraint_count)
468 .map(|b8_val| C::Elem::from(F::from(b8_val)))
469 .collect::<Vec<_>>();
470
471 let big_field_zerocheck_challenges =
472 channel.sample_many(log_constraint_count - small_field_zerocheck_challenges.len());
473
474 let zerocheck_challenges =
475 chain!(small_field_zerocheck_challenges, big_field_zerocheck_challenges)
476 .collect::<Vec<_>>();
477
478 let UnivariateSkipOutput { z_challenge, claim } = verify_univariate_skip(channel, eval_domain)?;
479 let lagrange = eval_domain
481 .reduce_dim(Word::LOG_BITS)
482 .lagrange_evals(&z_challenge);
483 let rerand = rerand::verify(&zerocheck_challenges, claim, &lagrange, operands, channel)?;
484 Ok(AndCheckOutput {
485 z_challenge,
486 rerand,
487 })
488}