binius_core/constraint_system/
channel.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2024-2025 Irreducible Inc.

//! A channel allows communication between tables.
//!
//! Note that the channel is unordered - meaning that rows are not
//! constrained to be in the same order when being pushed and pulled.
//!
//! The number of columns per channel must be fixed, but can be any
//! positive integer. Column order is guaranteed, and column values within
//! the same row must always stay together.
//!
//! A channel only ensures that the inputs and outputs match, using a
//! multiset check. If you want any kind of ordering, you have to
//! use polynomial constraints to additionally constraint this.
//!
//! The example below shows a channel with width=2, with multiple inputs
//! and outputs.
//! ```txt
//!                                       +-+-+
//!                                       |C|D|
//! +-+-+                           +---> +-+-+
//! |A|B|                           |     |M|N|
//! +-+-+                           |     +-+-+
//! |C|D|                           |
//! +-+-+  --+                      |     +-+-+
//! |E|F|    |                      |     |I|J|
//! +-+-+    |                      |     +-+-+
//! |G|H|    |                      |     |W|X|
//! +-+-+    |                      | +-> +-+-+
//!          |                      | |   |A|B|
//! +-+-+    +-> /¯\¯¯¯¯¯¯¯¯¯¯¯\  --+ |   +-+-+
//! |I|J|       :   :           : ----+   |K|L|
//! +-+-+  PUSH |   |  channel  |  PULL   +-+-+
//! |K|L|       :   :           : ----+
//! +-+-+    +-> \_/___________/  --+ |   +-+-+
//! |M|N|    |                      | |   |U|V|
//! +-+-+    |                      | |   +-+-+
//! |O|P|    |                      | |   |G|H|
//! +-+-+  --+                      | +-> +-+-+
//! |Q|R|                           |     |E|F|
//! +-+-+                           |     +-+-+
//! |S|T|                           |     |Q|R|
//! +-+-+                           |     +-+-+
//! |U|V|                           |
//! +-+-+                           |     +-+-+
//! |W|X|                           |     |O|P|
//! +-+-+                           +---> +-+-+
//!                                       |S|T|
//!                                       +-+-+
//! ```

use std::collections::HashMap;

use binius_field::{as_packed_field::PackScalar, underlier::UnderlierType, TowerField};
use bytes::BufMut;

use super::error::{Error, VerificationError};
use crate::{oracle::OracleId, transcript::TranscriptWriter, witness::MultilinearExtensionIndex};

pub type ChannelId = usize;

#[derive(Debug, Clone)]
pub struct Flush {
	pub oracles: Vec<OracleId>,
	pub channel_id: ChannelId,
	pub direction: FlushDirection,
	pub selector: OracleId,
	pub multiplicity: u64,
}

#[derive(Debug, Clone)]
pub struct Boundary<F: TowerField> {
	pub values: Vec<F>,
	pub channel_id: ChannelId,
	pub direction: FlushDirection,
	pub multiplicity: u64,
}

#[derive(Debug, Clone, Copy)]
pub enum FlushDirection {
	Push,
	Pull,
}

pub fn validate_witness<U, F>(
	witness: &MultilinearExtensionIndex<U, F>,
	flushes: &[Flush],
	boundaries: &[Boundary<F>],
	max_channel_id: ChannelId,
) -> Result<(), Error>
where
	U: UnderlierType + PackScalar<F>,
	F: TowerField,
{
	let mut channels = vec![Channel::<F>::new(); max_channel_id + 1];

	for boundary in boundaries.iter().cloned() {
		let Boundary {
			channel_id,
			values,
			direction,
			multiplicity,
		} = boundary;
		if channel_id > max_channel_id {
			return Err(Error::ChannelIdOutOfRange {
				max: max_channel_id,
				got: channel_id,
			});
		}
		channels[channel_id].flush(direction, multiplicity, values.clone())?;
	}

	for flush in flushes {
		let &Flush {
			ref oracles,
			channel_id,
			direction,
			selector,
			multiplicity,
		} = flush;

		if channel_id > max_channel_id {
			return Err(Error::ChannelIdOutOfRange {
				max: max_channel_id,
				got: channel_id,
			});
		}

		let channel = &mut channels[channel_id];

		let polys = oracles
			.iter()
			.map(|&id| witness.get_multilin_poly(id))
			.collect::<Result<Vec<_>, _>>()?;

		// Ensure that all the polys in a single flush have the same n_vars
		if let Some(first_poly) = polys.first() {
			let n_vars = first_poly.n_vars();
			for poly in &polys {
				if poly.n_vars() != n_vars {
					return Err(Error::ChannelFlushNvarsMismatch {
						expected: n_vars,
						got: poly.n_vars(),
					});
				}
			}

			let selector_poly = witness.get_multilin_poly(selector)?;
			// Check selector polynomial is compatible
			if selector_poly.n_vars() != n_vars {
				let id = oracles.first().copied().expect("polys is not empty");
				return Err(Error::IncompatibleFlushSelector { id, selector });
			}

			for i in 0..1 << selector_poly.n_vars() {
				if selector_poly.evaluate_on_hypercube(i)?.is_zero() {
					continue;
				}
				let values = polys
					.iter()
					.map(|poly| poly.evaluate_on_hypercube(i))
					.collect::<Result<Vec<_>, _>>()?;
				channel.flush(direction, multiplicity, values)?;
			}
		}
	}

	for (id, channel) in channels.iter().enumerate() {
		if !channel.is_balanced() {
			return Err(VerificationError::ChannelUnbalanced { id }.into());
		}
	}

	Ok(())
}

#[derive(Default, Debug, Clone)]
struct Channel<F: TowerField> {
	width: Option<usize>,
	multiplicities: HashMap<Vec<F>, i64>,
}

impl<F: TowerField> Channel<F> {
	fn new() -> Self {
		Self::default()
	}

	fn _print_unbalanced_values(&self) {
		for (key, val) in &self.multiplicities {
			if *val != 0 {
				println!("{key:?}: {val}");
			}
		}
	}

	fn flush(
		&mut self,
		direction: FlushDirection,
		multiplicity: u64,
		values: Vec<F>,
	) -> Result<(), Error> {
		if self.width.is_none() {
			self.width = Some(values.len());
		} else if self.width.expect("checked for None above") != values.len() {
			return Err(Error::ChannelFlushWidthMismatch {
				expected: self.width.unwrap(),
				got: values.len(),
			});
		}
		*self.multiplicities.entry(values).or_default() += (multiplicity as i64)
			* (match direction {
				FlushDirection::Pull => -1i64,
				FlushDirection::Push => 1i64,
			});
		Ok(())
	}

	fn is_balanced(&self) -> bool {
		self.multiplicities.iter().all(|(_, m)| *m == 0)
	}
}

impl<F: TowerField> Boundary<F> {
	pub fn write_to(&self, writer: &mut TranscriptWriter<impl BufMut>) {
		writer.buffer().put_u64(self.values.len() as u64);
		writer.write_slice(
			&self
				.values
				.iter()
				.copied()
				.map(F::Canonical::from)
				.collect::<Vec<_>>(),
		);
		writer.buffer().put_u64(self.channel_id as u64);
		writer.buffer().put_u64(self.multiplicity);
		writer.buffer().put_u64(match self.direction {
			FlushDirection::Pull => 0,
			FlushDirection::Push => 1,
		});
	}
}

#[cfg(test)]
mod tests {
	use binius_field::BinaryField64b;

	use super::*;

	#[test]
	fn test_flush_push_single_row() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Push a single row of data
		let values = vec![BinaryField64b::from(1), BinaryField64b::from(2)];
		let result = channel.flush(FlushDirection::Push, 1, values.clone());

		assert!(result.is_ok());
		assert!(!channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap(), &1);
	}

	#[test]
	fn test_flush_pull_single_row() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Pull a single row of data
		let values = vec![BinaryField64b::from(1), BinaryField64b::from(2)];
		let result = channel.flush(FlushDirection::Pull, 1, values.clone());

		assert!(result.is_ok());
		assert!(!channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap(), &-1);
	}

	#[test]
	fn test_flush_push_pull_single_row() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Push and then pull the same row
		let values = vec![BinaryField64b::from(1), BinaryField64b::from(2)];
		channel
			.flush(FlushDirection::Push, 1, values.clone())
			.unwrap();
		let result = channel.flush(FlushDirection::Pull, 1, values.clone());

		assert!(result.is_ok());
		assert!(channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap_or(&0), &0);
	}

	#[test]
	fn test_flush_multiplicity() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Push multiple rows with a multiplicity of 2
		let values = vec![BinaryField64b::from(3), BinaryField64b::from(4)];
		channel
			.flush(FlushDirection::Push, 2, values.clone())
			.unwrap();

		// Pull the same row with a multiplicity of 1
		channel
			.flush(FlushDirection::Pull, 1, values.clone())
			.unwrap();

		// The channel should not be balanced yet
		assert!(!channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap(), &1);

		// Pull the same row again with a multiplicity of 1
		channel
			.flush(FlushDirection::Pull, 1, values.clone())
			.unwrap();

		// Now the channel should be balanced
		assert!(channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap_or(&0), &0);
	}

	#[test]
	fn test_flush_width_mismatch() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Push a row with width 2
		let values1 = vec![BinaryField64b::from(1), BinaryField64b::from(2)];
		channel.flush(FlushDirection::Push, 1, values1).unwrap();

		// Attempt to push a row with width 3
		let values2 = vec![
			BinaryField64b::from(3),
			BinaryField64b::from(4),
			BinaryField64b::from(5),
		];
		let result = channel.flush(FlushDirection::Push, 1, values2);

		assert!(result.is_err());
		if let Err(Error::ChannelFlushWidthMismatch { expected, got }) = result {
			assert_eq!(expected, 2);
			assert_eq!(got, 3);
		} else {
			panic!("Expected ChannelFlushWidthMismatch error");
		}
	}

	#[test]
	fn test_flush_direction_effects() {
		let mut channel = Channel::<BinaryField64b>::new();

		// Push a row
		let values = vec![BinaryField64b::from(7), BinaryField64b::from(8)];
		channel
			.flush(FlushDirection::Push, 1, values.clone())
			.unwrap();

		// Pull a different row
		let values2 = vec![BinaryField64b::from(9), BinaryField64b::from(10)];
		channel
			.flush(FlushDirection::Pull, 1, values2.clone())
			.unwrap();

		// The channel should not be balanced because different rows were pushed and pulled
		assert!(!channel.is_balanced());
		assert_eq!(channel.multiplicities.get(&values).unwrap(), &1);
		assert_eq!(channel.multiplicities.get(&values2).unwrap(), &-1);
	}
}