Skip to main content

binius_spartan_verifier/wrapper/
zk_wrapped_channel.rs

1// Copyright 2026 The Binius Developers
2
3//! ZK-wrapped verifier channel that delegates to a BaseFold ZK channel and an outer IOP verifier.
4//!
5//! [`ZKWrappedVerifierChannel`] wraps a [`BaseFoldVerifierChannel`] and an [`IOPVerifier`].
6//! Inner-channel values flow through the wrapper as `CircuitElem`s backed by an
7//! [`InstanceGenerator`], which reconstructs the outer constraint system's public-input vector
8//! `[constants | inout | derived]` exactly as the prover's witness generator does — public-derived
9//! intermediate values are recomputed natively rather than tracked by the wrapper. [`finish()`]
10//! hands that public vector to the outer verifier and runs it against the inner channel.
11//!
12//! [`finish()`]: ZKWrappedVerifierChannel::finish
13
14use std::{cell::RefCell, iter, rc::Rc, sync::Arc};
15
16use binius_core::word::Word;
17use binius_field::BinaryField;
18use binius_iop::{
19	basefold::channel::{BaseFoldOracle, BaseFoldVerifierChannel},
20	channel::{IOPVerifierChannel, OracleSpec, TransparentEvalFn},
21	merkle_channel::MerkleIPVerifierChannel,
22};
23use binius_ip::channel::{
24	IPVerifierChannel, WordIPVerifierChannel, pack_words_concrete, select_word, subset_sum_word,
25};
26use binius_math::multilinear::eval_one_hot;
27use binius_spartan_frontend::{
28	circuit_builder::{InstanceGenerator, WireAllocator},
29	constraint_system::{WireKind, WitnessLayout},
30};
31
32use crate::{Error, IOPVerifier, wrapper::circuit_elem::CircuitElem};
33
34/// A verifier channel that wraps a [`BaseFoldVerifierChannel`] and an [`IOPVerifier`].
35///
36/// `Self::Elem = CircuitElem<F, InstanceGenerator>`. F values received or sampled from the inner
37/// channel are written into the [`InstanceGenerator`]'s public segment as inout wires (in the same
38/// order the symbolic
39/// [`IronSpartanBuilderChannel`](super::builder_channel::IronSpartanBuilderChannel) allocates
40/// them); arithmetic over public values produces derived public values, and mixing with a precommit
41/// key (as `recv_one` arranges via `inout - key`) yields a value-less private result.
42///
43/// `transparent` closures supplied to [`IOPVerifierChannel::verify_oracle_relation`] must depend
44/// only on public inputs (constants and sampled challenges), never on private ones — that method
45/// panics otherwise.
46pub struct ZKWrappedVerifierChannel<'a, F, Channel>
47where
48	F: BinaryField,
49	Channel: MerkleIPVerifierChannel<F, Elem = F>,
50{
51	inner_channel: BaseFoldVerifierChannel<'a, F, Channel>,
52	outer_verifier: &'a IOPVerifier<F>,
53	precommit_oracle: BaseFoldOracle,
54	/// Reconstructs the outer public-input vector as the channel replays the inner verifier;
55	/// `build()` yields the `[constants | inout | derived]` segment for the outer verify.
56	instance_gen: Rc<RefCell<InstanceGenerator<F>>>,
57	/// Allocators for the InOut and Precommit segments. They live here, not on the
58	/// [`InstanceGenerator`], because allocating wires in interaction order is the channel's job;
59	/// the generator just writes a value to a given wire. Allocation order must match the symbolic
60	/// [`IronSpartanBuilderChannel`](super::builder_channel::IronSpartanBuilderChannel) so the
61	/// wire ids align with the outer layout.
62	inout_alloc: WireAllocator,
63	precommit_alloc: WireAllocator,
64	/// Number of outer oracles still to be received on `inner_channel` after inner verification
65	/// completes (i.e. the outer verifier's non-precommit oracles — private and mask).
66	n_outer_suffix_oracles: usize,
67}
68
69impl<'a, F, Channel> ZKWrappedVerifierChannel<'a, F, Channel>
70where
71	F: BinaryField,
72	Channel: MerkleIPVerifierChannel<F, Elem = F>,
73{
74	/// Creates a new ZK-wrapped verifier channel.
75	///
76	/// The outer verifier's oracle specs are expected to straddle the inner channel specs:
77	/// the outer precommit spec is at position 0 (committed before any inner interaction), and
78	/// the remaining outer specs (private, mask) form a suffix that will be received after the
79	/// inner verification completes. `new` receives the outer precommit oracle from the inner
80	/// channel and stores the handle for use in [`Self::finish`].
81	///
82	/// `outer_layout` is the witness layout of the outer constraint system (the same layout the
83	/// prover used); it backs the [`InstanceGenerator`] that reconstructs the public-input vector.
84	/// It is a shared `Arc`, not a borrow, so the generator is `'static`.
85	/// Its `CircuitElem`s live in the transparent closures queued onto `inner_channel`.
86	/// The `Arc` shares the layout the config owns rather than cloning it.
87	///
88	/// # Panics
89	///
90	/// Panics if the channel's oracle specs do not match the expected layout
91	/// `[outer_precommit, inner..., outer_private, outer_mask]`.
92	pub fn new(
93		mut inner_channel: BaseFoldVerifierChannel<'a, F, Channel>,
94		outer_verifier: &'a IOPVerifier<F>,
95		outer_layout: Arc<WitnessLayout<F>>,
96	) -> Result<Self, Error> {
97		let outer_schedule = outer_verifier.oracle_schedule();
98		let outer_oracle_specs = outer_schedule.specs();
99		let channel_oracle_specs = inner_channel.remaining_oracle_specs();
100
101		let n_outer = outer_oracle_specs.len();
102		let n_total = channel_oracle_specs.len();
103		assert!(
104			n_outer >= 1 && n_outer <= n_total,
105			"outer oracle specs ({n_outer}) exceed channel oracle specs ({n_total}) or are empty"
106		);
107		assert_eq!(
108			channel_oracle_specs[0], outer_oracle_specs[0],
109			"outer precommit oracle spec must be the first spec on the channel"
110		);
111		let suffix_len = n_outer - 1;
112		assert_eq!(
113			&channel_oracle_specs[n_total - suffix_len..],
114			&outer_oracle_specs[1..],
115			"outer private/mask oracle specs must be the final suffix of channel specs"
116		);
117
118		let precommit_oracle = inner_channel.recv_oracle(outer_oracle_specs[0].len, true)?;
119
120		Ok(Self {
121			inner_channel,
122			outer_verifier,
123			precommit_oracle,
124			instance_gen: Rc::new(RefCell::new(InstanceGenerator::new(outer_layout))),
125			inout_alloc: WireAllocator::new(WireKind::InOut),
126			precommit_alloc: WireAllocator::new(WireKind::Precommit),
127			n_outer_suffix_oracles: suffix_len,
128		})
129	}
130
131	/// Allocates the next inout wire, writing `value` into the public segment, and wraps it as an
132	/// element. Allocation order must match the symbolic
133	/// [`IronSpartanBuilderChannel`](super::builder_channel::IronSpartanBuilderChannel).
134	fn alloc_inout_elem(&mut self, value: F) -> CircuitElem<F, InstanceGenerator<F>> {
135		let wire = self.inout_alloc.alloc();
136		let public_wire = self.instance_gen.borrow_mut().write_inout(wire, value);
137		CircuitElem::wire(&self.instance_gen, public_wire)
138	}
139
140	/// The value of an element, when the verifier holds it.
141	///
142	/// A constant, an inout wire, or anything derived from those alone has a value here; an element
143	/// that reads a precommit wire has none. This is what lets a check over public values run
144	/// outside the wrapper circuit — the verifier evaluates it directly instead of constraining it.
145	pub const fn public_value(&self, elem: &CircuitElem<F, InstanceGenerator<F>>) -> Option<F> {
146		match elem {
147			CircuitElem::Constant(val) => Some(*val),
148			CircuitElem::Wire { wire, .. } => wire.value(),
149		}
150	}
151
152	/// Allocates the next precommit wire (value-less to the verifier) as an element, with its index
153	/// in the precommit segment.
154	fn alloc_precommit_elem(&mut self) -> (CircuitElem<F, InstanceGenerator<F>>, usize) {
155		let wire = self.precommit_alloc.alloc();
156		let public_wire = self.instance_gen.borrow_mut().placeholder_precommit(wire);
157		(CircuitElem::wire(&self.instance_gen, public_wire), wire.id() as usize)
158	}
159
160	/// Consumes the channel and runs the outer verifier.
161	///
162	/// Reads the outer public-input vector `[constants | inout | derived]` from the
163	/// [`InstanceGenerator`] and runs [`IOPVerifier::verify`] against the inner channel.
164	pub fn finish(self) -> Result<(), Error> {
165		// The instance generator produced every public value (inout + alive-derived) as the inner
166		// verifier ran, so the public segment is already final here — read it by borrow. We must
167		// NOT consume the generator: the oracle relations queued onto `inner_channel` carry
168		// transparent closures that still hold (`Weak`) references to it, and opening them in
169		// `inner_channel.finish()` evaluates those closures. They only allocate dead derived wires
170		// (ids past the layout's count, so `layout.get` returns `None` and nothing is written), so
171		// the public vector read here stays correct.
172		let public = self.instance_gen.borrow().public().to_vec();
173
174		let mut inner_channel = self.inner_channel;
175		self.outer_verifier
176			.verify(self.precommit_oracle, &public, &mut inner_channel)?;
177		// Both the inner and outer proofs queued their oracle relations onto `inner_channel`; run
178		// the single combined opening over all committed oracles now. `instance_gen` stays alive in
179		// `self` for the duration, so the transparent closures' `Weak` upgrades succeed.
180		inner_channel.finish()?;
181		Ok(())
182	}
183}
184
185impl<'a, F, Channel> IPVerifierChannel<F> for ZKWrappedVerifierChannel<'a, F, Channel>
186where
187	F: BinaryField,
188	Channel: MerkleIPVerifierChannel<F, Elem = F>,
189{
190	type Elem = CircuitElem<F, InstanceGenerator<F>>;
191
192	fn recv_one(&mut self) -> Result<Self::Elem, binius_ip::channel::Error> {
193		// Mirror `IronSpartanBuilderChannel::recv_one`'s shape: `inout - key`. The inout carries
194		// the encrypted F received from the inner channel (written into the public segment); the
195		// key is a precommit wire whose value the verifier does not know (`PublicWire(None)`).
196		// The subtraction yields a private result, matching the symbolic phase's private result
197		// wire.
198		let val = self.inner_channel.recv_one()?;
199		let inout = self.alloc_inout_elem(val);
200		let (key, _) = self.alloc_precommit_elem();
201		Ok(inout - key)
202	}
203
204	fn recv_public_claim(&mut self) -> Result<Self::Elem, binius_ip::channel::Error> {
205		// Mirror `IronSpartanBuilderChannel::recv_public_claim`: the value arrives unencrypted, so
206		// it enters as one inout wire carrying it, with no precommit key to subtract.
207		let val = self.inner_channel.recv_one()?;
208		Ok(self.alloc_inout_elem(val))
209	}
210
211	fn sample(&mut self) -> Self::Elem {
212		let val = self.inner_channel.sample();
213		self.alloc_inout_elem(val)
214	}
215
216	fn observe_one(&mut self, val: F) -> Self::Elem {
217		let elem = self.inner_channel.observe_one(val);
218		self.alloc_inout_elem(elem)
219	}
220
221	fn assert_zero(&mut self, val: Self::Elem) -> Result<(), binius_ip::channel::Error> {
222		match val {
223			// A compile-time constant is checked here; a non-zero one is an unsatisfiable
224			// assertion.
225			CircuitElem::Constant(c) => {
226				if c == F::ZERO {
227					Ok(())
228				} else {
229					Err(binius_ip::channel::Error::InvalidAssert)
230				}
231			}
232			// No-op for wires: the corresponding constraint was recorded symbolically and is
233			// checked by the outer verifier over the reconstructed public segment.
234			CircuitElem::Wire { .. } => Ok(()),
235		}
236	}
237}
238
239impl<F, Channel> WordIPVerifierChannel<F> for ZKWrappedVerifierChannel<'_, F, Channel>
240where
241	F: BinaryField,
242	Channel: MerkleIPVerifierChannel<F, Elem = F, Word = Word>,
243{
244	type Word = Word;
245
246	fn observe_words(&mut self, words: &[Word]) -> Vec<Word> {
247		// The inner channel holds the Fiat-Shamir state the inner prover mirrors, so the words go
248		// there. The outer verifier recomputes what depends on them from the public segment.
249		self.inner_channel.observe_words(words)
250	}
251
252	fn subset_sum(&mut self, elems: &[Self::Elem], word: &Word) -> Self::Elem {
253		subset_sum_word(elems, *word)
254	}
255
256	fn select(&mut self, elems: &[Self::Elem], word: &Word) -> Self::Elem {
257		select_word(elems, *word)
258	}
259
260	fn sample_bits(&mut self, bits: usize) -> Word {
261		self.inner_channel.sample_bits(bits)
262	}
263
264	fn pack_words(&mut self, words: &[Word]) -> Vec<Self::Elem> {
265		// The symbolic phase allocated an inout wire per packed element, since the statement is not
266		// the circuit's to fix. Fill them here: the words are concrete, so the verifier packs them
267		// itself and writes the result into the public segment.
268		pack_words_concrete::<F, F>(words)
269			.into_iter()
270			.map(|value| self.alloc_inout_elem(value))
271			.collect()
272	}
273}
274
275impl<'a, F, Channel> IOPVerifierChannel<F> for ZKWrappedVerifierChannel<'a, F, Channel>
276where
277	F: BinaryField,
278	Channel: MerkleIPVerifierChannel<F, Elem = F>,
279{
280	type Oracle = BaseFoldOracle;
281
282	fn remaining_oracle_specs(&self) -> &[OracleSpec] {
283		let all = self.inner_channel.remaining_oracle_specs();
284		let n_remaining_inner = all.len() - self.n_outer_suffix_oracles;
285		&all[..n_remaining_inner]
286	}
287
288	fn recv_oracle(
289		&mut self,
290		len: usize,
291		is_witness_dependent: bool,
292	) -> Result<Self::Oracle, binius_iop::channel::Error> {
293		assert!(
294			!self.remaining_oracle_specs().is_empty(),
295			"recv_oracle called but no remaining inner oracle specs"
296		);
297		self.inner_channel.recv_oracle(len, is_witness_dependent)
298	}
299
300	fn verify_multi_oracle_relation(
301		&mut self,
302		operands: impl IntoIterator<Item = (Self::Oracle, TransparentEvalFn<Self::Elem>)>,
303		claim: Self::Elem,
304	) -> Result<(), binius_iop::channel::Error> {
305		// The prover sends the target as the ciphertext `c = s + k` under a fresh key, exactly as
306		// `recv_one` reads any value, and the symbolic `IronSpartanBuilderChannel` attests
307		// `claim == c - k`. The assertion is a no-op on values here, but evaluating it keeps the
308		// instance generator's wire allocation aligned with the symbolic constraint system. The
309		// relation is passed on to the inner channel against `c`, with the key's operand
310		// `<z_pre, e_k>` added, so that it holds iff the decrypted target does.
311		let ciphertext = self.inner_channel.recv_one()?;
312		let ciphertext_elem = self.alloc_inout_elem(ciphertext);
313		let (key, key_index) = self.alloc_precommit_elem();
314		self.assert_zero(claim - (ciphertext_elem - key))?;
315		// `e_k`: the one-hot vector at the key's index, over the precommit oracle's variables.
316		let key_indicator =
317			Box::new(move |point: &[F]| eval_one_hot(key_index, point)) as TransparentEvalFn<F>;
318
319		// Wrap the sumcheck challenge coordinates for the transparent closure (which expects
320		// `CircuitElem`s). The closure can do further arithmetic; results are required to be
321		// value-known (public), never private.
322		//
323		// HACK: the coordinates are sampled challenges, so they are wrapped as `Constant`s
324		// rather than builder-backed wires. This frees the closure from holding a reference to
325		// the instance generator, and is sound only because the symbolic outer circuit
326		// (`IronSpartanBuilderChannel`) never invokes the transparent closure — it attests only
327		// `claim == decrypted_claim`, with the transparent evaluation performed out of circuit.
328		// This F->CircuitElem->F bridge should eventually be replaced by an F-level transparent
329		// evaluator.
330		let operands = operands.into_iter().map(|(oracle, transparent)| {
331			let eval_fn = move |vals: &[F]| {
332				let wrapped_vals = vals
333					.iter()
334					.map(|val| CircuitElem::Constant(*val))
335					.collect::<Vec<_>>();
336
337				match transparent(&wrapped_vals) {
338					CircuitElem::Constant(val) => val,
339					CircuitElem::Wire { wire, .. } => wire.value().expect(
340						"precondition: the transparent polynomial evaluation must depend only on known values (constants or sampled challenges)",
341					),
342				}
343			};
344			(oracle, Box::new(eval_fn) as TransparentEvalFn<F>)
345		});
346		self.inner_channel.verify_multi_oracle_relation(
347			operands.chain(iter::once((self.precommit_oracle, key_indicator))),
348			ciphertext,
349		)
350	}
351}