Skip to main content

binius_spartan_prover/wrapper/
zk_wrapped_prover_channel.rs

1// Copyright 2026 The Binius Developers
2
3//! ZK-wrapped prover channel that runs an inner proof and then proves the outer
4//! wrapper constraint system.
5//!
6//! [`ZKWrappedProverChannel`] wraps a [`BaseFoldProverChannel`] and records all channel values.
7//! On `send_*`/`sample`/`observe_*`, it delegates to the inner BaseFold channel and records
8//! each value. After the inner proof is run, [`finish`] replays the recorded interaction through
9//! a caller-provided closure to fill the outer witness, then runs the outer IOP prover.
10//!
11//! [`BaseFoldProverChannel`]: binius_iop_prover::basefold::channel::BaseFoldProverChannel
12//! [`finish`]: ZKWrappedProverChannel::finish
13
14use std::{
15	iter::{self, repeat_with},
16	sync::Arc,
17};
18
19use binius_alloc::Allocator;
20use binius_field::{BinaryField, PackedField};
21use binius_iop::channel::OracleSpec;
22use binius_iop_prover::{
23	basefold::channel::{BaseFoldOracle, BaseFoldProverChannel},
24	channel::IOPProverChannel,
25	merkle_channel::MerkleIPProverChannel,
26};
27use binius_ip_prover::channel::{IPProverChannel, WordIPProverChannel};
28use binius_math::{FieldBuffer, FieldSlice, FieldVec, ntt::AdditiveNTT};
29use binius_spartan_frontend::constraint_system::WitnessLayout;
30use binius_spartan_verifier::IOPVerifier;
31use rand::CryptoRng;
32
33use crate::{Error, IOPProver, pack_and_blind_witness, wrapper::ReplayChannel};
34
35/// A prover channel that wraps a [`BaseFoldProverChannel`] and an outer Spartan IOP prover.
36///
37/// This channel records all channel values. On
38/// `send_*`/`sample`/`observe_*`, it delegates to the inner BaseFold channel and records each
39/// value. After the inner proof is run through this channel, call
40/// [`finish`](Self::finish) to replay the interaction, fill the outer witness, and generate the
41/// outer proof.
42///
43/// The `ReplayFn` closure is called during [`finish`](Self::finish) with a [`ReplayChannel`] to
44/// replay the inner verification and fill the outer witness. This allows the channel to be generic
45/// over different inner verification protocols.
46pub struct ZKWrappedProverChannel<'a, P, NTT, Channel, ReplayFn, A>
47where
48	P: PackedField<Scalar: BinaryField>,
49	NTT: AdditiveNTT<Field = P::Scalar> + Sync,
50	Channel: MerkleIPProverChannel<P::Scalar>,
51	A: Allocator,
52{
53	inner_channel: BaseFoldProverChannel<'a, P::Scalar, P, NTT, Channel, A>,
54	outer_prover: &'a IOPProver<P::Scalar>,
55	/// Allocator for the outer proof's working buffers, borrowed from the owning prover so it
56	/// outlives this per-proof channel. Used in [`Self::finish`].
57	alloc: &'a A,
58	outer_layout: Arc<WitnessLayout<P::Scalar>>,
59	replay_fn: ReplayFn,
60	keys: Vec<P::Scalar>,
61	next_key_idx: usize,
62	interaction: Vec<P::Scalar>,
63	/// Handle to the outer precommit oracle committed at construction time. Its buffer is purely
64	/// random — it is the one-time-pad encryption key for the outer encrypted transcript (to be
65	/// wired up in a follow-up; for now the outer circuit has no precommit wires that reference
66	/// it).
67	precommit_oracle: BaseFoldOracle,
68	/// The packed outer precommit buffer committed as [`Self::precommit_oracle`], which the outer
69	/// proof reads in [`Self::finish`].
70	precommit_packed: FieldVec<P, A>,
71	/// Number of outer oracles still to be committed on `inner_channel` during `finish` (the
72	/// outer prover's non-precommit oracles — private and mask).
73	n_outer_suffix_oracles: usize,
74}
75
76impl<'a, F, P, NTT, Channel, ReplayFn, A> ZKWrappedProverChannel<'a, P, NTT, Channel, ReplayFn, A>
77where
78	F: BinaryField,
79	P: PackedField<Scalar = F>,
80	NTT: AdditiveNTT<Field = F> + Sync,
81	Channel: MerkleIPProverChannel<F>,
82	A: Allocator,
83{
84	/// Creates a new ZK-wrapped prover channel.
85	///
86	/// Commits the outer prover's precommit oracle on the inner channel as part of construction:
87	/// a random [`FieldBuffer<P>`](binius_math::FieldBuffer) the size of the outer precommit oracle
88	/// segment is sent to the channel, which the outer proof takes it back from in
89	/// [`Self::finish`]. This random buffer is
90	/// the one-time-pad encryption key for the (future) outer encrypted transcript.
91	///
92	/// The inner channel's oracle specs are expected to be laid out as
93	/// `[outer_precommit, inner..., outer_private, outer_mask]`.
94	///
95	/// # Arguments
96	///
97	/// * `inner_channel` - The BaseFold ZK channel with oracle specs for both inner and outer
98	///   proofs
99	/// * `outer_prover` - The IOP prover for the outer (wrapper) constraint system
100	/// * `outer_layout` - The witness layout for the outer constraint system
101	/// * `alloc` - Allocator for the outer proof's working buffers, borrowed from the owning prover
102	/// * `rng` - RNG used to generate the random precommit buffer (the future OTP key)
103	/// * `replay_fn` - Closure called during [`finish`](Self::finish) with a [`ReplayChannel`] to
104	///   replay the inner verification and fill the outer witness
105	pub fn new(
106		mut inner_channel: BaseFoldProverChannel<'a, F, P, NTT, Channel, A>,
107		outer_prover: &'a IOPProver<F>,
108		outer_layout: Arc<WitnessLayout<F>>,
109		alloc: &'a A,
110		rng: impl CryptoRng,
111		replay_fn: ReplayFn,
112	) -> Self {
113		let outer_schedule =
114			IOPVerifier::new(outer_prover.constraint_system().clone()).oracle_schedule();
115		let outer_oracle_specs = outer_schedule.specs();
116		let all_specs = inner_channel.remaining_oracle_specs();
117		let n_outer = outer_oracle_specs.len();
118		assert!(
119			n_outer >= 1 && all_specs.len() >= n_outer,
120			"outer oracle specs ({n_outer}) exceed channel oracle specs ({}) or are empty",
121			all_specs.len(),
122		);
123		assert_eq!(
124			all_specs[0], outer_oracle_specs[0],
125			"outer precommit oracle spec must be the first spec on the channel",
126		);
127		let suffix_len = n_outer - 1;
128		assert_eq!(
129			&all_specs[all_specs.len() - suffix_len..],
130			&outer_oracle_specs[1..],
131			"outer private/mask oracle specs must be the final suffix of channel specs",
132		);
133
134		let (keys, precommit_oracle, precommit_packed) = {
135			let _scope = tracing::debug_span!("Commit Transcript Mask").entered();
136			Self::commit_transcript_mask(&mut inner_channel, outer_prover, alloc, rng)
137		};
138
139		Self {
140			inner_channel,
141			outer_prover,
142			alloc,
143			outer_layout,
144			replay_fn,
145			keys,
146			next_key_idx: 0,
147			interaction: Vec::new(),
148			precommit_oracle,
149			precommit_packed,
150			n_outer_suffix_oracles: suffix_len,
151		}
152	}
153
154	/// Commits random OTP keys as the outer precommit oracle. Each key encrypts one element sent by
155	/// the inner prover through this wrapped channel; the outer CS (built symbolically from the
156	/// inner verifier) contains a matching precommit wire per key that the outer proof uses to
157	/// decrypt.
158	fn commit_transcript_mask(
159		inner_channel: &mut BaseFoldProverChannel<'a, F, P, NTT, Channel, A>,
160		outer_prover: &IOPProver<F>,
161		alloc: &A,
162		mut rng: impl CryptoRng,
163	) -> (Vec<F>, BaseFoldOracle, FieldVec<P, A>) {
164		let cs = outer_prover.constraint_system();
165		let keys = repeat_with(|| F::random(&mut rng))
166			.take(cs.n_precommit() as usize)
167			.collect::<Vec<F>>();
168		let precommit_blinding = *cs.blinding_info();
169		let precommit_packed = pack_and_blind_witness::<_, _, P>(
170			alloc,
171			cs.log_precommit() as usize,
172			&keys,
173			cs.n_precommit() as usize,
174			&precommit_blinding,
175			&mut rng,
176		);
177		let precommit_oracle = inner_channel.send_oracle(precommit_packed.as_view());
178		(keys, precommit_oracle, precommit_packed)
179	}
180
181	fn next_key(&mut self) -> F {
182		let key = self.keys[self.next_key_idx];
183		self.next_key_idx += 1;
184		key
185	}
186
187	/// Consumes the channel and runs the outer proof.
188	///
189	/// This should be called after the inner proof has been run through this channel.
190	/// It:
191	/// 1. Creates a [`ReplayChannel`] from the recorded interaction
192	/// 2. Calls the `replay_fn` closure to replay the inner verification and fill the outer witness
193	/// 3. Validates and generates the outer IOP proof
194	pub fn finish(self, rng: impl CryptoRng) -> Result<(), Error>
195	where
196		ReplayFn: FnOnce(&mut ReplayChannel<F>),
197	{
198		let Self {
199			mut inner_channel,
200			outer_prover,
201			alloc,
202			outer_layout,
203			replay_fn,
204			keys,
205			interaction,
206			precommit_oracle,
207			precommit_packed,
208			..
209		} = self;
210
211		// Replay the inner verification through the outer witness generator.
212		let witness = {
213			let _scope = tracing::debug_span!("Generating ZK wrapper witness").entered();
214			let mut replay_channel = ReplayChannel::new(outer_layout, keys, interaction);
215			replay_fn(&mut replay_channel);
216			replay_channel
217				.finish()
218				.expect("outer witness generation should not fail")
219		};
220
221		// Validate and generate the outer proof.
222		outer_prover.prove::<P, _, _>(
223			&witness,
224			precommit_oracle,
225			precommit_packed.as_view(),
226			rng,
227			&mut inner_channel,
228			alloc,
229		)?;
230		// Both the inner and outer proofs queued their oracle relations onto `inner_channel`; run
231		// the single combined opening over all committed oracles now.
232		inner_channel.finish();
233		Ok(())
234	}
235}
236
237impl<F, P, NTT, Channel, ReplayFn, A> IPProverChannel<F>
238	for ZKWrappedProverChannel<'_, P, NTT, Channel, ReplayFn, A>
239where
240	F: BinaryField,
241	P: PackedField<Scalar = F>,
242	NTT: AdditiveNTT<Field = F> + Sync,
243	Channel: MerkleIPProverChannel<F>,
244	A: Allocator,
245{
246	fn send_one(&mut self, elem: F) {
247		let key = self.next_key();
248		// Encrypt the element with the OTP key before sending. Record the encrypted value in
249		// `interaction` — that's what the outer witness's inout wires hold (and what the replay
250		// side adds the key back to in order to recover the plaintext for the inner verifier).
251		let encrypted = elem + key;
252		self.inner_channel.send_one(encrypted);
253		self.interaction.push(encrypted);
254	}
255
256	fn send_public_claim(&mut self, elem: F) {
257		// A claim is a function of public values, so it is sent in the clear and consumes no OTP
258		// key. `interaction` records the plaintext, which is what the outer witness's inout wire
259		// holds and what the replay hands the inner verifier.
260		self.inner_channel.send_one(elem);
261		self.interaction.push(elem);
262	}
263
264	fn observe_one(&mut self, val: F) {
265		self.inner_channel.observe_one(val);
266		self.interaction.push(val);
267	}
268
269	fn sample(&mut self) -> F {
270		let val = self.inner_channel.sample();
271		self.interaction.push(val);
272		val
273	}
274}
275
276impl<F, P, NTT, Channel, ReplayFn, A> WordIPProverChannel<F>
277	for ZKWrappedProverChannel<'_, P, NTT, Channel, ReplayFn, A>
278where
279	F: BinaryField,
280	P: PackedField<Scalar = F>,
281	NTT: AdditiveNTT<Field = F> + Sync,
282	Channel: MerkleIPProverChannel<F>,
283	A: Allocator,
284{
285	type Word = Channel::Word;
286
287	fn observe_words(&mut self, words: &[Self::Word]) {
288		// Only the inner Fiat-Shamir state takes the words. Nothing is recorded for replay, since
289		// the replay channel observes nothing either.
290		self.inner_channel.observe_words(words);
291	}
292
293	fn sample_bits(&mut self, bits: usize) -> Self::Word {
294		self.inner_channel.sample_bits(bits)
295	}
296}
297
298impl<F, P, NTT, Channel, ReplayFn, A> IOPProverChannel<P, A>
299	for ZKWrappedProverChannel<'_, P, NTT, Channel, ReplayFn, A>
300where
301	F: BinaryField,
302	P: PackedField<Scalar = F>,
303	NTT: AdditiveNTT<Field = F> + Sync,
304	Channel: MerkleIPProverChannel<F>,
305	A: Allocator,
306{
307	type Oracle = BaseFoldOracle;
308
309	fn remaining_oracle_specs(&self) -> &[OracleSpec] {
310		let remaining = self.inner_channel.remaining_oracle_specs();
311		let n_inner_remaining = remaining.len() - self.n_outer_suffix_oracles;
312		&remaining[..n_inner_remaining]
313	}
314
315	fn send_oracle(&mut self, buffer: FieldSlice<'_, P>) -> Self::Oracle {
316		assert!(
317			!self.remaining_oracle_specs().is_empty(),
318			"send_oracle called but no inner oracle specs remaining"
319		);
320		self.inner_channel.send_oracle(buffer)
321	}
322
323	fn prove_multi_oracle_relation(
324		&mut self,
325		operands: impl IntoIterator<Item = (Self::Oracle, FieldBuffer<P, A::Vec<P>>)>,
326		claim: P::Scalar,
327	) {
328		// The target is a linear image of the witness, so it is sent as the ciphertext `c = s + k`
329		// under a fresh key `k`. The outer circuit decrypts it, and the compiler is handed the
330		// relation `<π, t> + <z_pre, e_k> = c`, which reads `k` from the precommit oracle at the
331		// key's index.
332		let key_index = self.next_key_idx;
333		self.send_one(claim);
334		let ciphertext = claim + self.keys[key_index];
335
336		let mut key_indicator = FieldBuffer::zeros_in(self.alloc, self.precommit_packed.log_len());
337		key_indicator.set(key_index, P::Scalar::ONE);
338		self.inner_channel.prove_multi_oracle_relation(
339			operands
340				.into_iter()
341				.chain(iter::once((self.precommit_oracle, key_indicator))),
342			ciphertext,
343		);
344	}
345}