Skip to main content

binius_verifier/
zk_config.rs

1// Copyright 2026 The Binius Developers
2
3//! Zero-knowledge verification configuration for Binius64 constraint systems.
4//!
5//! This module provides [`ZKVerifier`], which wraps the Binius64 IOP verifier with a
6//! Spartan-based zero-knowledge wrapper. The wrapper transforms the non-ZK Binius64
7//! verification into a ZK proof by:
8//!
9//! 1. Symbolically executing the inner verifier to build an outer Spartan constraint system
10//! 2. Combining inner and outer oracles into a single BaseFold ZK compiler, which commits each
11//!    round's oracles as one
12//! 3. At verification time, running the inner verifier through a [`ZKWrappedVerifierChannel`] that
13//!    records all values as outer public inputs, then finishing with outer Spartan verification
14//!
15//! [`ZKWrappedVerifierChannel`]: binius_spartan_verifier::wrapper::ZKWrappedVerifierChannel
16
17use std::{marker::PhantomData, sync::Arc};
18
19use binius_core::{
20	constraint_system::{ConstraintSystem, InoutSegment},
21	word::Word,
22};
23use binius_field::Ghash128b as B128;
24use binius_hash::HashSuite;
25use binius_iop::{
26	basefold::compiler::BaseFoldVerifierCompiler,
27	channel::{
28		IOPVerifierChannel,
29		oracle_setup::{DummyElem, OracleSetupChannel},
30	},
31	fri,
32	merkle_tree::BinaryMerkleTreeScheme,
33};
34use binius_ip::channel::WordIPVerifierChannel;
35use binius_spartan_frontend::{
36	compiler::compile,
37	constraint_system::{BlindingInfo, WitnessLayout},
38};
39use binius_spartan_verifier::{
40	IOPVerifier as IronSpartanIOPVerifier,
41	constraint_system::ConstraintSystemPadded,
42	wrapper::{IronSpartanBuilderChannel, ZKWrappedVerifierChannel},
43};
44use binius_transcript::{VerifierTranscript, fiat_shamir::Challenger};
45use binius_utils::{DeserializeBytes, SerializeBytes, serialization::SerializationError};
46use bytes::{Buf, BufMut};
47use digest::Output;
48
49use crate::{
50	protocols::shift::WiringEvalClaim,
51	verify::{IOPVerifier, SECURITY_BITS},
52};
53
54/// Zero-knowledge verifier for Binius64 constraint systems.
55///
56/// Wraps the Binius64 IOP verifier with a Spartan-based ZK wrapper. Call [`Self::setup`] with
57/// a constraint system, then [`Self::verify`] with public inputs and a proof transcript.
58#[derive(Clone)]
59pub struct ZKVerifier<H: HashSuite> {
60	inner_iop_verifier: IOPVerifier,
61	outer_iop_verifier: IronSpartanIOPVerifier<B128>,
62	outer_layout: Arc<WitnessLayout<B128>>,
63	basefold_compiler: BaseFoldVerifierCompiler<B128>,
64	/// The verifier creates its Merkle transcript channels with the hash suite `H`.
65	_hash_marker: PhantomData<H>,
66}
67
68impl<H> ZKVerifier<H>
69where
70	H: HashSuite,
71	Output<H::LeafHash>: DeserializeBytes,
72{
73	/// Constructs a ZK verifier for a constraint system.
74	pub fn setup(constraint_system: ConstraintSystem, log_inv_rate: usize) -> Result<Self, Error> {
75		let _setup_guard = tracing::debug_span!("Setup ZK verifier").entered();
76
77		constraint_system.validate()?;
78
79		let log_public_words = constraint_system.log_public_words(InoutSegment::Public);
80
81		let inner_iop_verifier = IOPVerifier::new(constraint_system, log_public_words);
82
83		// Symbolically execute the inner verifier to build the outer constraint system.
84		let dummy_inout_words =
85			vec![Word::from_u64(0); inner_iop_verifier.constraint_system().n_inout];
86
87		let outer_builder = {
88			let _guard = tracing::debug_span!("Build ZK wrapper circuit").entered();
89			let mut builder_channel = IronSpartanBuilderChannel::new();
90			// The wiring claim is dropped rather than discharged: [`Self::verify`] checks it over
91			// the public segment instead, so the circuit built here carries none of it.
92			let _ = inner_iop_verifier
93				.verify(&dummy_inout_words, &mut builder_channel)
94				.expect("symbolic verify should not fail");
95			builder_channel.finish()
96		};
97		let (outer_cs, outer_layout) = {
98			let _guard = tracing::debug_span!("Compile ZK wrapper circuit").entered();
99			compile(outer_builder)
100		};
101
102		tracing::debug!(
103			n_public = outer_cs.n_public(),
104			n_precommit = outer_cs.n_precommit(),
105			n_private = outer_cs.n_private(),
106			n_mul_constraints = outer_cs.mul_constraints().len(),
107			"ZK wrapper circuit stats"
108		);
109
110		// Pad the outer constraint system for zero-knowledge.
111		let n_test_queries = fri::calculate_n_test_queries(SECURITY_BITS, log_inv_rate);
112		let blinding_info = BlindingInfo::default();
113		let outer_cs = ConstraintSystemPadded::new(outer_cs, blinding_info);
114		let outer_layout = Arc::new(outer_layout.with_blinding(*outer_cs.blinding_info()));
115		let outer_iop_verifier = IronSpartanIOPVerifier::new(outer_cs);
116
117		// Transcript layout: outer precommit oracle first (committed at wrapper construction),
118		// then all inner oracles, then the remaining outer oracles (private, mask). Replaying that
119		// sequence against one setup channel also records where each round ends, which no
120		// concatenation of the two proofs' own schedules can say.
121		let oracle_schedule = {
122			let mut channel = OracleSetupChannel::new(true);
123			<OracleSetupChannel as IOPVerifierChannel<B128>>::recv_oracle(
124				&mut channel,
125				outer_iop_verifier.constraint_system().precommit_len(),
126				true,
127			)
128			.expect("OracleSetupChannel::recv_oracle is infallible");
129			// Discarded: the setup channel performs no real verification.
130			let _ = inner_iop_verifier.verify(&dummy_inout_words, &mut channel);
131			let public = vec![
132				DummyElem::<B128>::default();
133				1 << outer_iop_verifier.constraint_system().log_public()
134			];
135			let _ = outer_iop_verifier.verify((), &public, &mut channel);
136			channel.into_oracle_schedule()
137		};
138
139		let merkle_scheme = BinaryMerkleTreeScheme::<B128, H>::new();
140		let basefold_compiler = BaseFoldVerifierCompiler::new(
141			&merkle_scheme,
142			oracle_schedule,
143			log_inv_rate,
144			n_test_queries,
145		);
146
147		Ok(Self {
148			inner_iop_verifier,
149			outer_iop_verifier,
150			outer_layout,
151			basefold_compiler,
152			_hash_marker: PhantomData,
153		})
154	}
155
156	/// Returns a reference to the inner IOP verifier.
157	pub const fn inner_iop_verifier(&self) -> &IOPVerifier {
158		&self.inner_iop_verifier
159	}
160
161	/// Returns a reference to the outer spartan IOP verifier.
162	pub const fn outer_iop_verifier(&self) -> &IronSpartanIOPVerifier<B128> {
163		&self.outer_iop_verifier
164	}
165
166	/// Returns the witness layout of the outer Spartan constraint system.
167	///
168	/// The layout maps each logical wire to its position in the witness vector.
169	pub fn outer_layout(&self) -> &WitnessLayout<B128> {
170		&self.outer_layout
171	}
172
173	/// Returns the shared handle to the outer witness layout.
174	///
175	/// The prover clones this `Arc` to share the layout instead of deep-cloning it.
176	pub fn outer_layout_arc(&self) -> Arc<WitnessLayout<B128>> {
177		Arc::clone(&self.outer_layout)
178	}
179
180	/// Returns the BaseFold ZK verifier compiler.
181	pub const fn basefold_compiler(&self) -> &BaseFoldVerifierCompiler<B128> {
182		&self.basefold_compiler
183	}
184
185	/// Returns the constraint system.
186	pub const fn constraint_system(&self) -> &ConstraintSystem {
187		self.inner_iop_verifier.constraint_system()
188	}
189
190	/// Returns log2 of the number of public words.
191	pub const fn log_public_words(&self) -> usize {
192		self.inner_iop_verifier.log_public_words()
193	}
194
195	/// Returns the log of the inverse Reed–Solomon rate this verifier was set up with.
196	pub fn log_inv_rate(&self) -> usize {
197		self.basefold_compiler.fri_params().rs_code().log_inv_rate()
198	}
199
200	/// Verifies a ZK proof against the constraint system.
201	pub fn verify<Challenger_: Challenger>(
202		&self,
203		inout: &[Word],
204		transcript: &mut VerifierTranscript<Challenger_>,
205	) -> Result<(), Error> {
206		// Create BaseFold channel and wrap with outer verifier.
207		let channel = self
208			.basefold_compiler
209			.create_channel_from_transcript::<H, Challenger_, _>(transcript);
210		let mut wrapped_channel = ZKWrappedVerifierChannel::new(
211			channel,
212			&self.outer_iop_verifier,
213			Arc::clone(&self.outer_layout),
214		)?;
215
216		// Run the inner IOP verification through the wrapped channel.
217		{
218			let inner_cs = self.inner_iop_verifier.constraint_system();
219			let _scope = tracing::debug_span!(
220				"Binius64",
221				n_hidden_words = inner_cs.n_hidden_words(InoutSegment::Public),
222				n_bitand = inner_cs.and_constraints.len(),
223				n_intmul = inner_cs.imul_constraints.len(),
224			)
225			.entered();
226
227			// The statement is observed here, and what comes back is what the IOP verifies
228			// against — the same split the transparent verifier makes.
229			let inout = wrapped_channel.observe_words(inout);
230			let claim = self
231				.inner_iop_verifier
232				.verify(&inout, &mut wrapped_channel)?;
233
234			// The wiring claim and every input it reads are public wires of the wrapper circuit, so
235			// tying the claim to the constraint system is an equation between values this verifier
236			// holds. Checking it here keeps the evaluation out of the circuit entirely, and the
237			// wrapper's other two runs — the symbolic build and the prover's replay — emit nothing
238			// for it either.
239			let public_value = |elem| {
240				wrapped_channel
241					.public_value(elem)
242					.expect("a public claim and its inputs are public wires")
243			};
244			WiringEvalClaim {
245				inputs: claim.inputs.iter().map(public_value).collect(),
246				claimed: public_value(&claim.claimed),
247				eval_fn: claim.eval_fn,
248			}
249			.check_native()
250			.map_err(crate::error::Error::from)?;
251		};
252
253		// Finish runs the outer spartan verification.
254		{
255			let outer_cs = self.outer_iop_verifier.constraint_system();
256			let _scope = tracing::debug_span!(
257				"ZK Wrapper",
258				n_witness = outer_cs.n_private(),
259				n_constraints = outer_cs.mul_constraints().len(),
260			)
261			.entered();
262
263			wrapped_channel.finish()?;
264		}
265
266		Ok(())
267	}
268
269	/// Verifies a ZK signature of knowledge over `message`.
270	///
271	/// Binds `message` into the transcript before any other data, then runs the ordinary
272	/// [`Self::verify`] checks. See [`crate::signature`] for details.
273	pub fn verify_sig<Challenger_: Challenger>(
274		&self,
275		inout: &[Word],
276		message: &[u8],
277		transcript: &mut VerifierTranscript<Challenger_>,
278	) -> Result<(), Error> {
279		crate::signature::observe_message::<H, _>(&mut transcript.observe(), message);
280		self.verify(inout, transcript)
281	}
282}
283
284/// Serializes the seed a [`ZKVerifier`] is built from — its constraint system and
285/// `log_inv_rate`. The derived state (outer constraint system, oracle specs, BaseFold compiler)
286/// is recomputed on [`DeserializeBytes::deserialize`], which is cheap relative to proving.
287impl<H> SerializeBytes for ZKVerifier<H>
288where
289	H: HashSuite,
290	Output<H::LeafHash>: DeserializeBytes,
291{
292	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
293		const VERSION: u32 = 1;
294		VERSION.serialize(&mut write_buf)?;
295		self.constraint_system().serialize(&mut write_buf)?;
296		self.log_inv_rate().serialize(write_buf)
297	}
298}
299
300impl<H> DeserializeBytes for ZKVerifier<H>
301where
302	H: HashSuite,
303	Output<H::LeafHash>: DeserializeBytes,
304{
305	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError> {
306		const VERSION: u32 = 1;
307		let version = u32::deserialize(&mut read_buf)?;
308		if version != VERSION {
309			return Err(SerializationError::InvalidConstruction {
310				name: "ZKVerifier::version",
311			});
312		}
313		let constraint_system = ConstraintSystem::deserialize(&mut read_buf)?;
314		let log_inv_rate = usize::deserialize(&mut read_buf)?;
315		Self::setup(constraint_system, log_inv_rate)
316			.map_err(|_| SerializationError::InvalidConstruction { name: "ZKVerifier" })
317	}
318}
319
320/// Error type for ZK verification.
321#[derive(Debug, thiserror::Error)]
322pub enum Error {
323	#[error("inner verification error: {0}")]
324	InnerVerification(#[from] crate::error::Error),
325	#[error("outer verification error: {0}")]
326	OuterVerification(#[from] binius_spartan_verifier::Error),
327	#[error("constraint system error: {0}")]
328	ConstraintSystem(#[from] binius_core::ConstraintSystemError),
329}