Skip to main content

binius_iop/channel/
oracle_setup.rs

1// Copyright 2026 The Binius Developers
2
3//! An [`IOPVerifierChannel`] dry run that records the [`OracleSpec`] sequence an IOP uses.
4
5use std::{
6	iter::{Product, Sum},
7	marker::PhantomData,
8	ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
9};
10
11use binius_core::word::Word;
12use binius_field::{
13	BinaryField, ExtensionField, Field, FieldOps,
14	arithmetic_traits::{InvertOrZero, Square},
15};
16use binius_ip::channel::{IPVerifierChannel, WordIPVerifierChannel};
17
18use crate::channel::{Error, IOPVerifierChannel, OracleSchedule, OracleSpec, TransparentEvalFn};
19
20/// A dummy field element for [`OracleSetupChannel`], generic over the field `F` it stands in for.
21///
22/// The setup channel performs no real verification, so the field values flowing through it are
23/// never inspected. `DummyElem<F>` is a zero-sized stand-in whose arithmetic is all no-ops; the
24/// `PhantomData<F>` lets it satisfy `FieldOps<Scalar = F>` without doing (pointless) real field
25/// arithmetic during the structural dry run.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub struct DummyElem<F>(PhantomData<F>);
28
29macro_rules! dummy_binop {
30	($trait:ident, $method:ident) => {
31		impl<F> $trait for DummyElem<F> {
32			type Output = Self;
33			fn $method(self, _rhs: Self) -> Self {
34				self
35			}
36		}
37		impl<F> $trait<&DummyElem<F>> for DummyElem<F> {
38			type Output = Self;
39			fn $method(self, _rhs: &Self) -> Self {
40				self
41			}
42		}
43	};
44}
45dummy_binop!(Add, add);
46dummy_binop!(Sub, sub);
47dummy_binop!(Mul, mul);
48
49macro_rules! dummy_assign {
50	($trait:ident, $method:ident) => {
51		impl<F> $trait for DummyElem<F> {
52			fn $method(&mut self, _rhs: Self) {}
53		}
54		impl<F> $trait<&DummyElem<F>> for DummyElem<F> {
55			fn $method(&mut self, _rhs: &Self) {}
56		}
57	};
58}
59dummy_assign!(AddAssign, add_assign);
60dummy_assign!(SubAssign, sub_assign);
61dummy_assign!(MulAssign, mul_assign);
62
63impl<F> Neg for DummyElem<F> {
64	type Output = Self;
65	fn neg(self) -> Self {
66		self
67	}
68}
69
70impl<F> Sum for DummyElem<F> {
71	fn sum<I: Iterator<Item = Self>>(_iter: I) -> Self {
72		Self(PhantomData)
73	}
74}
75impl<'a, F> Sum<&'a DummyElem<F>> for DummyElem<F> {
76	fn sum<I: Iterator<Item = &'a Self>>(_iter: I) -> Self {
77		Self(PhantomData)
78	}
79}
80impl<F> Product for DummyElem<F> {
81	fn product<I: Iterator<Item = Self>>(_iter: I) -> Self {
82		Self(PhantomData)
83	}
84}
85impl<'a, F> Product<&'a DummyElem<F>> for DummyElem<F> {
86	fn product<I: Iterator<Item = &'a Self>>(_iter: I) -> Self {
87		Self(PhantomData)
88	}
89}
90
91impl<F> Square for DummyElem<F> {
92	fn square(self) -> Self {
93		self
94	}
95}
96impl<F> InvertOrZero for DummyElem<F> {
97	fn invert_or_zero(self) -> Self {
98		self
99	}
100}
101
102impl<F> From<F> for DummyElem<F> {
103	fn from(_value: F) -> Self {
104		Self(PhantomData)
105	}
106}
107
108impl<F: Field> FieldOps for DummyElem<F> {
109	type Scalar = F;
110
111	fn zero() -> Self {
112		Self(PhantomData)
113	}
114
115	fn one() -> Self {
116		Self(PhantomData)
117	}
118
119	fn square_transpose<FSub: Field>(_elems: &mut [Self])
120	where
121		F: ExtensionField<FSub>,
122	{
123	}
124}
125
126/// An [`IOPVerifierChannel`] that records the [`OracleSpec`] of each received oracle.
127///
128/// This performs no verification.
129///
130/// Every receive returns a dummy value, and sampling, observing, and asserting are no-ops.
131///
132/// Drive an IOP verifier with it, then read back what it recorded.
133///
134/// The channel carries one protocol-level zero-knowledge flag.
135///
136/// An oracle is zero-knowledge only if that flag is set and the oracle is witness-dependent.
137///
138/// # What is recorded
139///
140/// Two views of the same dry run, differing only in whether round boundaries survive.
141///
142/// - The flat sequence of oracles, in arrival order.
143/// - That same sequence, grouped into the rounds the oracles are committed in.
144///
145/// A round closes wherever a challenge could be drawn.
146///
147/// That is where BaseFold, committing each round as one oracle, stops taking members.
148#[derive(Debug, Default, Clone)]
149pub struct OracleSetupChannel {
150	is_zk: bool,
151	schedule: OracleSchedule,
152}
153
154impl OracleSetupChannel {
155	/// Creates a new setup channel with the given protocol-level zero-knowledge flag.
156	pub const fn new(is_zk: bool) -> Self {
157		Self {
158			is_zk,
159			schedule: OracleSchedule::new(),
160		}
161	}
162
163	/// Returns the oracle specs recorded so far.
164	pub fn oracle_specs(&self) -> &[OracleSpec] {
165		self.schedule.specs()
166	}
167
168	/// Consumes the channel and returns the recorded oracle specs, in the order received.
169	pub fn into_oracle_specs(self) -> Vec<OracleSpec> {
170		self.schedule.into_specs()
171	}
172
173	/// Consumes the channel and returns the recorded oracles, grouped by commit round.
174	///
175	/// The round left open at the end of the dry run is closed here.
176	///
177	/// So every recorded oracle belongs to some round.
178	pub fn into_oracle_schedule(mut self) -> OracleSchedule {
179		self.schedule.end_round();
180		self.schedule
181	}
182}
183
184impl<F: Field> IPVerifierChannel<F> for OracleSetupChannel {
185	type Elem = DummyElem<F>;
186
187	fn recv_one(&mut self) -> Result<DummyElem<F>, binius_ip::channel::Error> {
188		Ok(DummyElem(PhantomData))
189	}
190
191	fn recv_many(&mut self, n: usize) -> Result<Vec<DummyElem<F>>, binius_ip::channel::Error> {
192		Ok(vec![DummyElem(PhantomData); n])
193	}
194
195	fn recv_array<const N: usize>(
196		&mut self,
197	) -> Result<[DummyElem<F>; N], binius_ip::channel::Error> {
198		Ok([DummyElem(PhantomData); N])
199	}
200
201	fn sample(&mut self) -> DummyElem<F> {
202		// A challenge follows the commitments it is derived from, so it ends their round.
203		self.schedule.end_round();
204		DummyElem(PhantomData)
205	}
206
207	fn observe_one(&mut self, _val: F) -> DummyElem<F> {
208		DummyElem(PhantomData)
209	}
210
211	fn observe_many(&mut self, vals: &[F]) -> Vec<DummyElem<F>> {
212		vec![DummyElem(PhantomData); vals.len()]
213	}
214
215	fn assert_zero(&mut self, _val: DummyElem<F>) -> Result<(), binius_ip::channel::Error> {
216		Ok(())
217	}
218}
219
220impl<F: BinaryField> WordIPVerifierChannel<F> for OracleSetupChannel {
221	type Word = Word;
222
223	// The dry run records oracle shapes only, so nothing reaches a Fiat-Shamir state.
224	fn observe_words(&mut self, words: &[Word]) -> Vec<Word> {
225		words.to_vec()
226	}
227
228	fn subset_sum(&mut self, _elems: &[DummyElem<F>], _word: &Word) -> DummyElem<F> {
229		DummyElem(PhantomData)
230	}
231
232	fn select(&mut self, _elems: &[DummyElem<F>], _word: &Word) -> DummyElem<F> {
233		DummyElem(PhantomData)
234	}
235
236	// The recorded oracle shapes do not depend on which leaves a protocol would query.
237	fn sample_bits(&mut self, _bits: usize) -> Word {
238		// A sampled word is a challenge like any other, so it ends the open round too.
239		self.schedule.end_round();
240		Word::ZERO
241	}
242
243	// Only the element count matters here, and it follows from the word count alone.
244	fn pack_words(&mut self, words: &[Word]) -> Vec<DummyElem<F>> {
245		let words_per_elem = F::N_BITS / Word::BITS;
246		vec![DummyElem(PhantomData); words.len().div_ceil(words_per_elem)]
247	}
248}
249
250impl<F: Field> IOPVerifierChannel<F> for OracleSetupChannel {
251	type Oracle = ();
252
253	fn remaining_oracle_specs(&self) -> &[OracleSpec] {
254		// A setup channel has no pre-supplied specs; it records them as they are received.
255		&[]
256	}
257
258	fn recv_oracle(
259		&mut self,
260		len: usize,
261		is_witness_dependent: bool,
262	) -> Result<Self::Oracle, Error> {
263		// A non-witness-dependent oracle is never masked, whatever the protocol-level flag says.
264		self.schedule.push(OracleSpec {
265			len,
266			is_zk: self.is_zk && is_witness_dependent,
267		});
268		Ok(())
269	}
270
271	fn verify_multi_oracle_relation(
272		&mut self,
273		_operands: impl IntoIterator<Item = (Self::Oracle, TransparentEvalFn<Self::Elem>)>,
274		_claim: Self::Elem,
275	) -> Result<(), Error> {
276		// Opening an oracle needs every commitment in place, so nothing may still be queued.
277		self.schedule.end_round();
278		Ok(())
279	}
280}
281
282#[cfg(test)]
283mod tests {
284	use binius_field::Ghash128b;
285
286	use super::*;
287
288	type F = Ghash128b;
289
290	/// Draws a challenge, which is what closes a round.
291	fn sample(channel: &mut OracleSetupChannel) {
292		IPVerifierChannel::<F>::sample(channel);
293	}
294
295	/// Receives one witness-carrying oracle of the given length.
296	fn recv(channel: &mut OracleSetupChannel, log_msg_len: usize) {
297		IOPVerifierChannel::<F>::recv_oracle(channel, 1 << log_msg_len, true)
298			.expect("the setup channel never fails");
299	}
300
301	#[test]
302	fn a_challenge_ends_the_open_round() {
303		let mut channel = OracleSetupChannel::new(false);
304
305		// Two oracles, a challenge, then one more.
306		//
307		//     recv 3, recv 3, sample, recv 4, sample
308		//     \____________/          \____/
309		//        round 0              round 1
310		recv(&mut channel, 3);
311		recv(&mut channel, 3);
312		sample(&mut channel);
313		recv(&mut channel, 4);
314		sample(&mut channel);
315
316		let schedule = channel.into_oracle_schedule();
317		assert_eq!(schedule.n_rounds(), 2);
318		assert_eq!(
319			schedule.rounds().collect::<Vec<_>>(),
320			vec![
321				[OracleSpec::new(1 << 3), OracleSpec::new(1 << 3)].as_slice(),
322				[OracleSpec::new(1 << 4)].as_slice(),
323			]
324		);
325	}
326
327	#[test]
328	fn the_final_round_closes_without_a_challenge() {
329		let mut channel = OracleSetupChannel::new(false);
330
331		// The run ends with an oracle, not a challenge.
332		// That trailing oracle is still a round of its own.
333		recv(&mut channel, 2);
334		sample(&mut channel);
335		recv(&mut channel, 5);
336
337		let schedule = channel.into_oracle_schedule();
338		assert_eq!(schedule.n_rounds(), 2);
339		assert_eq!(schedule.rounds().last(), Some([OracleSpec::new(1 << 5)].as_slice()));
340	}
341
342	#[test]
343	fn a_sampled_word_ends_the_open_round_too() {
344		let mut channel = OracleSetupChannel::new(false);
345
346		// Query indices are drawn as words rather than as field elements.
347		// That is still a challenge, so it still closes the round before it.
348		recv(&mut channel, 3);
349		WordIPVerifierChannel::<F>::sample_bits(&mut channel, 4);
350		recv(&mut channel, 2);
351
352		assert_eq!(channel.into_oracle_schedule().n_rounds(), 2);
353	}
354
355	#[test]
356	fn back_to_back_challenges_make_no_empty_round() {
357		let mut channel = OracleSetupChannel::new(false);
358
359		// A protocol may draw several challenges in a row with nothing committed between them.
360		// Only the first of those closes anything.
361		recv(&mut channel, 3);
362		sample(&mut channel);
363		sample(&mut channel);
364		sample(&mut channel);
365
366		assert_eq!(channel.into_oracle_schedule().n_rounds(), 1);
367	}
368
369	#[test]
370	fn a_run_with_no_oracles_has_no_rounds() {
371		let mut channel = OracleSetupChannel::new(false);
372
373		// A challenge alone commits nothing, so it closes nothing.
374		sample(&mut channel);
375
376		let schedule = channel.into_oracle_schedule();
377		assert_eq!(schedule.n_rounds(), 0);
378		assert!(schedule.specs().is_empty());
379	}
380
381	#[test]
382	fn dropping_the_boundaries_leaves_the_flat_sequence() {
383		let mut channel = OracleSetupChannel::new(false);
384
385		// Grouping is the only thing the schedule adds.
386		// The oracles themselves, and their order, must survive it untouched.
387		recv(&mut channel, 3);
388		sample(&mut channel);
389		recv(&mut channel, 1);
390		recv(&mut channel, 4);
391
392		let flat = channel.clone().into_oracle_specs();
393		assert_eq!(channel.into_oracle_schedule().into_specs(), flat);
394	}
395}