binius_field/
binary_field.rs

1// Copyright 2023-2025 Irreducible Inc.
2
3use std::{
4	fmt::{Debug, Display, Formatter},
5	iter::{Product, Sum},
6	ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
7};
8
9use binius_utils::{
10	DeserializeBytes, SerializationError, SerializeBytes,
11	bytes::{Buf, BufMut},
12};
13use bytemuck::Zeroable;
14
15use super::{
16	UnderlierWithBitOps, WithUnderlier, binary_field_arithmetic::TowerFieldArithmetic,
17	extension::ExtensionField,
18};
19use crate::{Field, underlier::U1};
20
21/// A finite field with characteristic 2.
22pub trait BinaryField:
23	ExtensionField<BinaryField1b> + WithUnderlier<Underlier: UnderlierWithBitOps>
24{
25	const N_BITS: usize = Self::DEGREE;
26}
27
28/// A binary field *isomorphic* to a binary tower field.
29///
30/// The canonical binary field tower construction is specified in [DP23], section 2.3. This is a
31/// family of binary fields with extension degree $2^{\iota}$ for any tower height $\iota$. This
32/// trait can be implemented on any binary field *isomorphic* to the canonical tower field.
33///
34/// [DP23]: https://eprint.iacr.org/2023/1784
35pub trait TowerField: BinaryField {
36	/// The level $\iota$ in the tower, where this field is isomorphic to $T_{\iota}$.
37	const TOWER_LEVEL: usize = Self::N_BITS.ilog2() as usize;
38
39	/// Returns the smallest valid `TOWER_LEVEL` in the tower that can fit the same value.
40	///
41	/// Since which `TOWER_LEVEL` values are valid depends on the tower,
42	/// `F::Canonical::from(elem).min_tower_level()` can return a different result
43	/// from `elem.min_tower_level()`.
44	fn min_tower_level(self) -> usize;
45
46	/// Returns the i'th basis element of this field as an extension over the tower subfield with
47	/// level $\iota$.
48	///
49	/// # Preconditions
50	///
51	/// * `iota` must be at most `TOWER_LEVEL`.
52	/// * `i` must be less than `2^(TOWER_LEVEL - iota)`.
53	fn basis(iota: usize, i: usize) -> Self {
54		assert!(iota <= Self::TOWER_LEVEL, "iota {iota} exceeds tower level {}", Self::TOWER_LEVEL);
55		let n_basis_elts = 1 << (Self::TOWER_LEVEL - iota);
56		assert!(i < n_basis_elts, "index {i} out of range for {n_basis_elts} basis elements");
57		<Self as ExtensionField<BinaryField1b>>::basis(i << iota)
58	}
59
60	/// Multiplies a field element by the canonical primitive element of the extension $T_{\iota +
61	/// 1} / T_{iota}$.
62	///
63	/// We represent the tower field $T_{\iota + 1}$ as a vector space over $T_{\iota}$ with the
64	/// basis $\{1, \beta^{(\iota)}_1\}$. This operation multiplies the element by
65	/// $\beta^{(\iota)}_1$.
66	///
67	/// # Preconditions
68	///
69	/// * `iota` must be less than `TOWER_LEVEL`.
70	fn mul_primitive(self, iota: usize) -> Self {
71		assert!(
72			iota < Self::TOWER_LEVEL,
73			"iota {iota} must be less than tower level {}",
74			Self::TOWER_LEVEL
75		);
76		self * <Self as ExtensionField<BinaryField1b>>::basis(1 << iota)
77	}
78}
79
80/// Returns the i'th basis element of `FExt` as a field extension of `FSub`.
81///
82/// This is an alias function for [`ExtensionField::basis`].
83///
84/// ## Pre-conditions
85///
86/// * `i` must be in the range $[0, d)$, where $d$ is the field extension degree.
87#[inline]
88pub fn ext_basis<FExt, FSub>(i: usize) -> FExt
89where
90	FSub: Field,
91	FExt: ExtensionField<FSub>,
92{
93	<FExt as ExtensionField<FSub>>::basis(i)
94}
95
96pub(super) trait TowerExtensionField:
97	TowerField
98	+ ExtensionField<Self::DirectSubfield>
99	+ From<(Self::DirectSubfield, Self::DirectSubfield)>
100	+ Into<(Self::DirectSubfield, Self::DirectSubfield)>
101{
102	type DirectSubfield: TowerField;
103}
104
105/// Macro to generate an implementation of a BinaryField.
106macro_rules! binary_field {
107	($vis:vis $name:ident($typ:ty), $gen:expr) => {
108		#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Zeroable, bytemuck::TransparentWrapper)]
109		#[repr(transparent)]
110		$vis struct $name(pub(crate) $typ);
111
112		impl $name {
113			pub const fn new(value: $typ) -> Self {
114				Self(value)
115			}
116
117			pub const fn val(self) -> $typ {
118				self.0
119			}
120		}
121
122		unsafe impl $crate::underlier::WithUnderlier for $name {
123			type Underlier = $typ;
124		}
125
126		impl Neg for $name {
127			type Output = Self;
128
129			fn neg(self) -> Self::Output {
130				self
131			}
132		}
133
134		impl Add<Self> for $name {
135			type Output = Self;
136
137			#[allow(clippy::suspicious_arithmetic_impl)]
138			fn add(self, rhs: Self) -> Self::Output {
139				$name(self.0 ^ rhs.0)
140			}
141		}
142
143		impl Add<&Self> for $name {
144			type Output = Self;
145
146			#[allow(clippy::suspicious_arithmetic_impl)]
147			fn add(self, rhs: &Self) -> Self::Output {
148				$name(self.0 ^ rhs.0)
149			}
150		}
151
152		impl Sub<Self> for $name {
153			type Output = Self;
154
155			#[allow(clippy::suspicious_arithmetic_impl)]
156			fn sub(self, rhs: Self) -> Self::Output {
157				$name(self.0 ^ rhs.0)
158			}
159		}
160
161		impl Sub<&Self> for $name {
162			type Output = Self;
163
164			#[allow(clippy::suspicious_arithmetic_impl)]
165			fn sub(self, rhs: &Self) -> Self::Output {
166				$name(self.0 ^ rhs.0)
167			}
168		}
169
170		impl Mul<Self> for $name {
171			type Output = Self;
172
173			fn mul(self, rhs: Self) -> Self::Output {
174				$crate::tracing::trace_multiplication!($name);
175
176				TowerFieldArithmetic::multiply(self, rhs)
177			}
178		}
179
180		impl Mul<&Self> for $name {
181			type Output = Self;
182
183			fn mul(self, rhs: &Self) -> Self::Output {
184				self * *rhs
185			}
186		}
187
188		impl AddAssign<Self> for $name {
189			fn add_assign(&mut self, rhs: Self) {
190				*self = *self + rhs;
191			}
192		}
193
194		impl AddAssign<&Self> for $name {
195			fn add_assign(&mut self, rhs: &Self) {
196				*self = *self + *rhs;
197			}
198		}
199
200		impl SubAssign<Self> for $name {
201			fn sub_assign(&mut self, rhs: Self) {
202				*self = *self - rhs;
203			}
204		}
205
206		impl SubAssign<&Self> for $name {
207			fn sub_assign(&mut self, rhs: &Self) {
208				*self = *self - *rhs;
209			}
210		}
211
212		impl MulAssign<Self> for $name {
213			fn mul_assign(&mut self, rhs: Self) {
214				*self = *self * rhs;
215			}
216		}
217
218		impl MulAssign<&Self> for $name {
219			fn mul_assign(&mut self, rhs: &Self) {
220				*self = *self * rhs;
221			}
222		}
223
224		impl Sum<Self> for $name {
225			fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
226				iter.fold(Self::ZERO, |acc, x| acc + x)
227			}
228		}
229
230		impl<'a> Sum<&'a Self> for $name {
231			fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
232				iter.fold(Self::ZERO, |acc, x| acc + x)
233			}
234		}
235
236		impl Product<Self> for $name {
237			fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
238				iter.fold(Self::ONE, |acc, x| acc * x)
239			}
240		}
241
242		impl<'a> Product<&'a Self> for $name {
243			fn product<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
244				iter.fold(Self::ONE, |acc, x| acc * x)
245			}
246		}
247
248
249		impl crate::arithmetic_traits::Square for $name {
250			fn square(self) -> Self {
251				TowerFieldArithmetic::square(self)
252			}
253		}
254
255		impl Field for $name {
256			const ZERO: Self = $name::new(<$typ as $crate::underlier::UnderlierWithBitOps>::ZERO);
257			const ONE: Self = $name::new(<$typ as $crate::underlier::UnderlierWithBitOps>::ONE);
258			const CHARACTERISTIC: usize = 2;
259			const MULTIPLICATIVE_GENERATOR: $name = $name($gen);
260
261			fn double(&self) -> Self {
262				Self::ZERO
263			}
264		}
265
266		impl ::rand::distr::Distribution<$name> for ::rand::distr::StandardUniform {
267			fn sample<R: ::rand::Rng + ?Sized>(&self, rng: &mut R) -> $name {
268				$name(rng.random())
269			}
270		}
271
272		impl Display for $name {
273			fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
274				write!(f, "0x{repr:0>width$x}", repr=self.val(), width=Self::N_BITS.max(4) / 4)
275			}
276		}
277
278		impl Debug for $name {
279			fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
280				let structure_name = std::any::type_name::<$name>().split("::").last().expect("exist");
281
282				write!(f, "{}({})",structure_name, self)
283			}
284		}
285
286		impl BinaryField for $name {}
287
288		impl From<$typ> for $name {
289			fn from(val: $typ) -> Self {
290				return Self(val)
291			}
292		}
293
294		impl From<$name> for $typ {
295			fn from(val: $name) -> Self {
296				return val.0
297			}
298		}
299	}
300}
301
302pub(crate) use binary_field;
303
304macro_rules! mul_by_binary_field_1b {
305	($name:ident) => {
306		impl Mul<BinaryField1b> for $name {
307			type Output = Self;
308
309			#[inline]
310			#[allow(clippy::suspicious_arithmetic_impl)]
311			fn mul(self, rhs: BinaryField1b) -> Self::Output {
312				use $crate::underlier::{UnderlierWithBitOps, WithUnderlier};
313
314				$crate::tracing::trace_multiplication!(BinaryField128b, BinaryField1b);
315
316				Self(self.0 & <$name as WithUnderlier>::Underlier::fill_with_bit(u8::from(rhs.0)))
317			}
318		}
319	};
320}
321
322pub(crate) use mul_by_binary_field_1b;
323
324macro_rules! impl_field_extension {
325	($subfield_name:ident($subfield_typ:ty) < @$log_degree:expr => $name:ident($typ:ty)) => {
326		impl TryFrom<$name> for $subfield_name {
327			type Error = ();
328
329			#[inline]
330			fn try_from(elem: $name) -> Result<Self, Self::Error> {
331				use $crate::underlier::NumCast;
332
333				if elem.0 >> $subfield_name::N_BITS
334					== <$typ as $crate::underlier::UnderlierWithBitOps>::ZERO
335				{
336					Ok($subfield_name::new(<$subfield_typ>::num_cast_from(elem.val())))
337				} else {
338					Err(())
339				}
340			}
341		}
342
343		impl From<$subfield_name> for $name {
344			#[inline]
345			fn from(elem: $subfield_name) -> Self {
346				$name::new(<$typ>::from(elem.val()))
347			}
348		}
349
350		impl Add<$subfield_name> for $name {
351			type Output = Self;
352
353			#[inline]
354			fn add(self, rhs: $subfield_name) -> Self::Output {
355				self + Self::from(rhs)
356			}
357		}
358
359		impl Sub<$subfield_name> for $name {
360			type Output = Self;
361
362			#[inline]
363			fn sub(self, rhs: $subfield_name) -> Self::Output {
364				self - Self::from(rhs)
365			}
366		}
367
368		impl AddAssign<$subfield_name> for $name {
369			#[inline]
370			fn add_assign(&mut self, rhs: $subfield_name) {
371				*self = *self + rhs;
372			}
373		}
374
375		impl SubAssign<$subfield_name> for $name {
376			#[inline]
377			fn sub_assign(&mut self, rhs: $subfield_name) {
378				*self = *self - rhs;
379			}
380		}
381
382		impl MulAssign<$subfield_name> for $name {
383			#[inline]
384			fn mul_assign(&mut self, rhs: $subfield_name) {
385				*self = *self * rhs;
386			}
387		}
388
389		impl Add<$name> for $subfield_name {
390			type Output = $name;
391
392			#[inline]
393			fn add(self, rhs: $name) -> Self::Output {
394				rhs + self
395			}
396		}
397
398		impl Sub<$name> for $subfield_name {
399			type Output = $name;
400
401			#[allow(clippy::suspicious_arithmetic_impl)]
402			#[inline]
403			fn sub(self, rhs: $name) -> Self::Output {
404				rhs + self
405			}
406		}
407
408		impl Mul<$name> for $subfield_name {
409			type Output = $name;
410
411			#[inline]
412			fn mul(self, rhs: $name) -> Self::Output {
413				rhs * self
414			}
415		}
416
417		impl ExtensionField<$subfield_name> for $name {
418			const LOG_DEGREE: usize = $log_degree;
419
420			#[inline]
421			fn basis(i: usize) -> Self {
422				use $crate::underlier::UnderlierWithBitOps;
423
424				assert!(
425					i < 1 << $log_degree,
426					"index {} out of range for degree {}",
427					i,
428					1 << $log_degree
429				);
430				Self::new(<$typ>::ONE << (i * $subfield_name::N_BITS))
431			}
432
433			#[inline]
434			fn from_bases_sparse(
435				base_elems: impl IntoIterator<Item = $subfield_name>,
436				log_stride: usize,
437			) -> Self {
438				use $crate::underlier::UnderlierWithBitOps;
439
440				debug_assert!($name::N_BITS.is_power_of_two());
441				let shift_step = ($subfield_name::N_BITS << log_stride) & ($name::N_BITS - 1);
442				let mut value = <$typ>::ZERO;
443				let mut shift = 0;
444
445				for elem in base_elems.into_iter() {
446					assert!(shift < $name::N_BITS, "too many base elements for extension degree");
447					value |= <$typ>::from(elem.val()) << shift;
448					shift += shift_step;
449				}
450
451				Self::new(value)
452			}
453
454			#[inline]
455			fn iter_bases(&self) -> impl Iterator<Item = $subfield_name> {
456				use binius_utils::iter::IterExtensions;
457				use $crate::underlier::{Divisible, WithUnderlier};
458
459				Divisible::<<$subfield_name as WithUnderlier>::Underlier>::ref_iter(&self.0)
460					.map_skippable($subfield_name::from)
461			}
462
463			#[inline]
464			fn into_iter_bases(self) -> impl Iterator<Item = $subfield_name> {
465				use binius_utils::iter::IterExtensions;
466				use $crate::underlier::{Divisible, WithUnderlier};
467
468				Divisible::<<$subfield_name as WithUnderlier>::Underlier>::value_iter(self.0)
469					.map_skippable($subfield_name::from)
470			}
471
472			#[inline]
473			unsafe fn get_base_unchecked(&self, i: usize) -> $subfield_name {
474				use $crate::underlier::{UnderlierWithBitOps, WithUnderlier};
475				unsafe { $subfield_name::from_underlier(self.to_underlier().get_subvalue(i)) }
476			}
477
478			#[inline]
479			fn square_transpose(values: &mut [Self]) {
480				crate::transpose::square_transforms_extension_field::<$subfield_name, Self>(values)
481			}
482		}
483	};
484}
485
486pub(crate) use impl_field_extension;
487
488binary_field!(pub BinaryField1b(U1), U1::new(0x1));
489
490macro_rules! serialize_deserialize {
491	($bin_type:ty) => {
492		impl SerializeBytes for $bin_type {
493			fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError> {
494				self.0.serialize(write_buf)
495			}
496		}
497
498		impl DeserializeBytes for $bin_type {
499			fn deserialize(read_buf: impl Buf) -> Result<Self, SerializationError> {
500				Ok(Self(DeserializeBytes::deserialize(read_buf)?))
501			}
502		}
503	};
504}
505
506serialize_deserialize!(BinaryField1b);
507
508impl BinaryField1b {
509	/// Creates value without checking that it is within valid range (0 or 1)
510	///
511	/// # Safety
512	/// Value should not exceed 1
513	#[inline]
514	pub unsafe fn new_unchecked(val: u8) -> Self {
515		debug_assert!(val < 2, "val has to be less than 2, but it's {val}");
516
517		Self::new(U1::new_unchecked(val))
518	}
519}
520
521impl From<u8> for BinaryField1b {
522	#[inline]
523	fn from(val: u8) -> Self {
524		Self::new(U1::new(val))
525	}
526}
527
528impl From<BinaryField1b> for u8 {
529	#[inline]
530	fn from(value: BinaryField1b) -> Self {
531		value.val().into()
532	}
533}
534
535impl From<bool> for BinaryField1b {
536	#[inline]
537	fn from(value: bool) -> Self {
538		Self::from(U1::new_unchecked(value.into()))
539	}
540}
541
542#[cfg(test)]
543pub(crate) mod tests {
544	use binius_utils::{DeserializeBytes, SerializeBytes, bytes::BytesMut};
545	use proptest::prelude::*;
546
547	use super::BinaryField1b as BF1;
548	use crate::{AESTowerField8b, BinaryField, BinaryField1b, BinaryField128bGhash, Field};
549
550	#[test]
551	fn test_gf2_add() {
552		assert_eq!(BF1::from(0) + BF1::from(0), BF1::from(0));
553		assert_eq!(BF1::from(0) + BF1::from(1), BF1::from(1));
554		assert_eq!(BF1::from(1) + BF1::from(0), BF1::from(1));
555		assert_eq!(BF1::from(1) + BF1::from(1), BF1::from(0));
556	}
557
558	#[test]
559	fn test_gf2_sub() {
560		assert_eq!(BF1::from(0) - BF1::from(0), BF1::from(0));
561		assert_eq!(BF1::from(0) - BF1::from(1), BF1::from(1));
562		assert_eq!(BF1::from(1) - BF1::from(0), BF1::from(1));
563		assert_eq!(BF1::from(1) - BF1::from(1), BF1::from(0));
564	}
565
566	#[test]
567	fn test_gf2_mul() {
568		assert_eq!(BF1::from(0) * BF1::from(0), BF1::from(0));
569		assert_eq!(BF1::from(0) * BF1::from(1), BF1::from(0));
570		assert_eq!(BF1::from(1) * BF1::from(0), BF1::from(0));
571		assert_eq!(BF1::from(1) * BF1::from(1), BF1::from(1));
572	}
573
574	pub(crate) fn is_binary_field_valid_generator<F: BinaryField>() -> bool {
575		// Binary fields should contain a multiplicative subgroup of size 2^n - 1
576		let mut order = if F::N_BITS == 128 {
577			u128::MAX
578		} else {
579			(1 << F::N_BITS) - 1
580		};
581
582		// Naive factorization of group order - represented as a multiset of prime factors
583		let mut factorization = Vec::new();
584
585		let mut prime = 2;
586		while prime * prime <= order {
587			while order.is_multiple_of(prime) {
588				order /= prime;
589				factorization.push(prime);
590			}
591
592			prime += if prime > 2 { 2 } else { 1 };
593		}
594
595		if order > 1 {
596			factorization.push(order);
597		}
598
599		// Iterate over all divisors (some may be tested several times if order is non-square-free)
600		for mask in 0..(1 << factorization.len()) {
601			let mut divisor = 1;
602
603			for (bit_index, &prime) in factorization.iter().enumerate() {
604				if (1 << bit_index) & mask != 0 {
605					divisor *= prime;
606				}
607			}
608
609			// Compute pow(generator, divisor) in log time
610			divisor = divisor.reverse_bits();
611
612			let mut pow_divisor = F::ONE;
613			while divisor > 0 {
614				pow_divisor *= pow_divisor;
615
616				if divisor & 1 != 0 {
617					pow_divisor *= F::MULTIPLICATIVE_GENERATOR;
618				}
619
620				divisor >>= 1;
621			}
622
623			// Generator invariant
624			let is_root_of_unity = pow_divisor == F::ONE;
625			let is_full_group = mask + 1 == 1 << factorization.len();
626
627			if is_root_of_unity && !is_full_group || !is_root_of_unity && is_full_group {
628				return false;
629			}
630		}
631
632		true
633	}
634
635	#[test]
636	fn test_multiplicative_generators() {
637		assert!(is_binary_field_valid_generator::<BinaryField1b>());
638		assert!(is_binary_field_valid_generator::<AESTowerField8b>());
639		assert!(is_binary_field_valid_generator::<BinaryField128bGhash>());
640	}
641
642	#[test]
643	fn test_field_degrees() {
644		assert_eq!(BinaryField1b::N_BITS, 1);
645		assert_eq!(AESTowerField8b::N_BITS, 8);
646		assert_eq!(BinaryField128bGhash::N_BITS, 128);
647	}
648
649	#[test]
650	fn test_field_formatting() {
651		assert_eq!(format!("{}", BinaryField1b::from(1)), "0x1");
652		assert_eq!(format!("{}", AESTowerField8b::from(3)), "0x03");
653		assert_eq!(
654			format!("{}", BinaryField128bGhash::from(5)),
655			"0x00000000000000000000000000000005"
656		);
657	}
658
659	#[test]
660	fn test_inverse_on_zero() {
661		assert!(BinaryField1b::ZERO.invert().is_none());
662		assert!(AESTowerField8b::ZERO.invert().is_none());
663		assert!(BinaryField128bGhash::ZERO.invert().is_none());
664	}
665
666	proptest! {
667		#[test]
668		fn test_inverse_8b(val in 1u8..) {
669			let x = AESTowerField8b::new(val);
670			let x_inverse = x.invert().unwrap();
671			assert_eq!(x * x_inverse, AESTowerField8b::ONE);
672		}
673
674		#[test]
675		fn test_inverse_128b(val in 1u128..) {
676			let x = BinaryField128bGhash::new(val);
677			let x_inverse = x.invert().unwrap();
678			assert_eq!(x * x_inverse, BinaryField128bGhash::ONE);
679		}
680	}
681
682	#[test]
683	fn test_serialization() {
684		let mut buffer = BytesMut::new();
685		let b1 = BinaryField1b::from(0x1);
686		let b8 = AESTowerField8b::new(0x12);
687		let b128 = BinaryField128bGhash::new(0x147AD0369CF258BE8899AABBCCDDEEFF);
688
689		b1.serialize(&mut buffer).unwrap();
690		b8.serialize(&mut buffer).unwrap();
691		b128.serialize(&mut buffer).unwrap();
692
693		let mut read_buffer = buffer.freeze();
694
695		assert_eq!(BinaryField1b::deserialize(&mut read_buffer).unwrap(), b1);
696		assert_eq!(AESTowerField8b::deserialize(&mut read_buffer).unwrap(), b8);
697		assert_eq!(BinaryField128bGhash::deserialize(&mut read_buffer).unwrap(), b128);
698	}
699
700	#[test]
701	fn test_gf2_new_unchecked() {
702		for i in 0..2 {
703			assert_eq!(unsafe { BF1::new_unchecked(i) }, BF1::from(i));
704		}
705	}
706}