Skip to main content

log_fft/
field.rs

1//! Exact arithmetic in the Goldilocks prime field `F_p`, `p = 2^64 - 2^32 + 1`.
2//!
3//! The identities in the paper hold over `Z[1/2]`. Reducing modulo an odd
4//! prime is a ring homomorphism, so an identity that holds over `Z[1/2]`
5//! also holds in `F_p`. Every check in this crate is therefore exact, with
6//! no floating-point rounding.
7
8use alloc::vec::Vec;
9use core::fmt;
10use core::iter::{Product, Sum};
11use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
12
13/// The Goldilocks prime `2^64 - 2^32 + 1`.
14pub const P: u64 = 0xFFFF_FFFF_0000_0001;
15
16/// A multiplicative generator of `F_p^*`.
17pub const GENERATOR: u64 = 7;
18
19/// An element of `F_p`, always stored reduced in `[0, p)`.
20#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
21#[repr(transparent)]
22pub struct Fp(u64);
23
24impl Fp {
25    pub const ZERO: Fp = Fp(0);
26    pub const ONE: Fp = Fp(1);
27
28    pub fn new(v: u64) -> Self {
29        Fp(v % P)
30    }
31
32    pub fn from_i64(v: i64) -> Self {
33        if v >= 0 {
34            Fp::new(v as u64)
35        } else {
36            -Fp::new(v.unsigned_abs())
37        }
38    }
39
40    /// The canonical representative in `[0, p)`.
41    pub fn value(self) -> u64 {
42        self.0
43    }
44
45    /// `Some(x)` if `v < p`, otherwise `None` (no silent reduction).
46    pub fn from_canonical(v: u64) -> Option<Self> {
47        (v < P).then_some(Fp(v))
48    }
49
50    /// View field elements as their canonical `u64` values (zero-copy).
51    pub fn as_u64_slice(xs: &[Fp]) -> &[u64] {
52        // SAFETY: `Fp` is `repr(transparent)` over `u64`.
53        unsafe { core::slice::from_raw_parts(xs.as_ptr().cast(), xs.len()) }
54    }
55
56    /// View `u64`s as field elements without copying, if every value is `< p`.
57    pub fn from_canonical_slice(xs: &[u64]) -> Option<&[Fp]> {
58        if xs.iter().all(|&v| v < P) {
59            // SAFETY: `repr(transparent)`, and every value is canonical.
60            Some(unsafe { core::slice::from_raw_parts(xs.as_ptr().cast(), xs.len()) })
61        } else {
62            None
63        }
64    }
65
66    /// Mutable zero-copy view of `u64`s as field elements, if every value is `< p`.
67    pub fn from_canonical_slice_mut(xs: &mut [u64]) -> Option<&mut [Fp]> {
68        if xs.iter().all(|&v| v < P) {
69            // SAFETY: `repr(transparent)`, and every value is canonical. Writes
70            // through `&mut [Fp]` only store canonical values.
71            Some(unsafe { core::slice::from_raw_parts_mut(xs.as_mut_ptr().cast(), xs.len()) })
72        } else {
73            None
74        }
75    }
76
77    pub fn pow(self, mut e: u64) -> Self {
78        let mut base = self;
79        let mut acc = Fp::ONE;
80        while e > 0 {
81            if e & 1 == 1 {
82                acc *= base;
83            }
84            base *= base;
85            e >>= 1;
86        }
87        acc
88    }
89
90    /// Multiplicative inverse. Panics on zero.
91    pub fn inv(self) -> Self {
92        assert!(self.0 != 0, "inverse of zero");
93        self.pow(P - 2)
94    }
95
96    /// `(-1)^e` for any integer `e`.
97    pub fn sign(e: i64) -> Self {
98        if e.rem_euclid(2) == 0 {
99            Fp::ONE
100        } else {
101            -Fp::ONE
102        }
103    }
104
105    /// A primitive `n`-th root of unity. `n` must divide `p - 1`.
106    pub fn root_of_unity(n: u64) -> Self {
107        assert!(n > 0 && (P - 1) % n == 0, "no primitive {n}-th root in F_p");
108        Fp(GENERATOR).pow((P - 1) / n)
109    }
110}
111
112impl fmt::Debug for Fp {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        // Show small negatives as negatives for readability.
115        if self.0 > P / 2 {
116            write!(f, "-{}", P - self.0)
117        } else {
118            write!(f, "{}", self.0)
119        }
120    }
121}
122
123impl fmt::Display for Fp {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        fmt::Display::fmt(&self.0, f)
126    }
127}
128
129impl From<u64> for Fp {
130    /// Reduces modulo `p`.
131    fn from(v: u64) -> Self {
132        Fp::new(v)
133    }
134}
135impl From<u32> for Fp {
136    fn from(v: u32) -> Self {
137        Fp(v as u64)
138    }
139}
140impl From<i64> for Fp {
141    fn from(v: i64) -> Self {
142        Fp::from_i64(v)
143    }
144}
145impl From<bool> for Fp {
146    fn from(v: bool) -> Self {
147        Fp(v as u64)
148    }
149}
150impl From<Fp> for u64 {
151    fn from(v: Fp) -> u64 {
152        v.0
153    }
154}
155
156impl Div for Fp {
157    type Output = Fp;
158    /// Panics on division by zero.
159    #[allow(clippy::suspicious_arithmetic_impl)]
160    fn div(self, rhs: Fp) -> Fp {
161        self * rhs.inv()
162    }
163}
164impl DivAssign for Fp {
165    fn div_assign(&mut self, rhs: Fp) {
166        *self = *self / rhs;
167    }
168}
169impl Sum for Fp {
170    fn sum<I: Iterator<Item = Fp>>(iter: I) -> Fp {
171        iter.fold(Fp::ZERO, |a, b| a + b)
172    }
173}
174impl<'a> Sum<&'a Fp> for Fp {
175    fn sum<I: Iterator<Item = &'a Fp>>(iter: I) -> Fp {
176        iter.fold(Fp::ZERO, |a, b| a + *b)
177    }
178}
179impl Product for Fp {
180    fn product<I: Iterator<Item = Fp>>(iter: I) -> Fp {
181        iter.fold(Fp::ONE, |a, b| a * b)
182    }
183}
184impl<'a> Product<&'a Fp> for Fp {
185    fn product<I: Iterator<Item = &'a Fp>>(iter: I) -> Fp {
186        iter.fold(Fp::ONE, |a, b| a * *b)
187    }
188}
189
190impl Add for Fp {
191    type Output = Fp;
192    fn add(self, rhs: Fp) -> Fp {
193        let (s, carry) = self.0.overflowing_add(rhs.0);
194        if carry || s >= P {
195            Fp(s.wrapping_sub(P))
196        } else {
197            Fp(s)
198        }
199    }
200}
201
202impl Sub for Fp {
203    type Output = Fp;
204    fn sub(self, rhs: Fp) -> Fp {
205        if self.0 >= rhs.0 {
206            Fp(self.0 - rhs.0)
207        } else {
208            Fp(self.0.wrapping_sub(rhs.0).wrapping_add(P))
209        }
210    }
211}
212
213impl Neg for Fp {
214    type Output = Fp;
215    fn neg(self) -> Fp {
216        Fp::ZERO - self
217    }
218}
219
220/// `2^64 mod p = 2^32 − 1`.
221const EPSILON: u64 = 0xFFFF_FFFF;
222
223// Compile-time facts used by `reduce128` (and its Kani proof).
224const _: () = assert!((1u128 << 64) % (P as u128) == EPSILON as u128);
225const _: () = assert!((1u128 << 96) % (P as u128) == P as u128 - 1);
226
227/// Reduce a 128-bit value modulo `p`, using `2^64 ≡ 2^32 − 1` and `2^96 ≡ −1`.
228#[inline(always)]
229pub(crate) fn reduce128(x: u128) -> u64 {
230    let lo = x as u64;
231    let hi = (x >> 64) as u64;
232    let hi_hi = hi >> 32;
233    let hi_lo = hi & EPSILON;
234    // lo − hi_hi·2^96 ≡ lo − hi_hi
235    let (mut t0, borrow) = lo.overflowing_sub(hi_hi);
236    if borrow {
237        t0 = t0.wrapping_sub(EPSILON); // add 2^64 ≡ subtract (2^64 mod p) back
238    }
239    // + hi_lo·2^64 ≡ hi_lo·(2^32 − 1)
240    let t1 = hi_lo * EPSILON;
241    let (mut r, carry) = t0.overflowing_add(t1);
242    if carry {
243        r = r.wrapping_add(EPSILON);
244    }
245    if r >= P { r - P } else { r }
246}
247
248impl Mul for Fp {
249    type Output = Fp;
250    #[inline(always)]
251    fn mul(self, rhs: Fp) -> Fp {
252        Fp(reduce128(self.0 as u128 * rhs.0 as u128))
253    }
254}
255
256impl AddAssign for Fp {
257    fn add_assign(&mut self, rhs: Fp) {
258        *self = *self + rhs;
259    }
260}
261impl SubAssign for Fp {
262    fn sub_assign(&mut self, rhs: Fp) {
263        *self = *self - rhs;
264    }
265}
266impl MulAssign for Fp {
267    fn mul_assign(&mut self, rhs: Fp) {
268        *self = *self * rhs;
269    }
270}
271
272/// Generalised binomial coefficient `binom(top, k)` for any integer `top`.
273pub fn binom(top: i64, k: usize) -> Fp {
274    let mut num = Fp::ONE;
275    let mut den = Fp::ONE;
276    for t in 0..k as i64 {
277        num *= Fp::from_i64(top - t);
278        den *= Fp::from_i64(t + 1);
279    }
280    num * den.inv()
281}
282
283/// Solve the square system `a · x = rhs` by Gaussian elimination.
284/// Panics if `a` is singular.
285pub fn solve(mut a: Vec<Vec<Fp>>, mut rhs: Vec<Fp>) -> Vec<Fp> {
286    let n = rhs.len();
287    for col in 0..n {
288        let piv = (col..n)
289            .find(|&r| a[r][col] != Fp::ZERO)
290            .expect("singular system");
291        a.swap(col, piv);
292        rhs.swap(col, piv);
293        let inv = a[col][col].inv();
294        for c in col..n {
295            a[col][c] *= inv;
296        }
297        rhs[col] *= inv;
298        for r in 0..n {
299            if r != col && a[r][col] != Fp::ZERO {
300                let f = a[r][col];
301                for c in col..n {
302                    let t = a[col][c];
303                    a[r][c] -= f * t;
304                }
305                let t = rhs[col];
306                rhs[r] -= f * t;
307            }
308        }
309    }
310    rhs
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn arithmetic() {
319        let a = Fp::new(P - 1);
320        assert_eq!(a + Fp::ONE, Fp::ZERO);
321        assert_eq!(Fp::from_i64(-3) * Fp::from_i64(-5), Fp::new(15));
322        let x = Fp::new(123_456_789);
323        assert_eq!(x * x.inv(), Fp::ONE);
324        let w = Fp::root_of_unity(1 << 20);
325        assert_eq!(w.pow(1 << 20), Fp::ONE);
326        assert_ne!(w.pow(1 << 19), Fp::ONE);
327    }
328
329    #[test]
330    fn fast_reduction_matches_modulo() {
331        let edges = [0u64, 1, 2, EPSILON, EPSILON + 1, 1 << 32, P - 1, P - 2, P / 2, (1 << 63) + 12345];
332        for &a in &edges {
333            for &b in &edges {
334                let a = a % P;
335                let b = b % P;
336                let x = a as u128 * b as u128;
337                assert_eq!(reduce128(x), (x % P as u128) as u64, "{a} * {b}");
338            }
339        }
340        // Arbitrary 128-bit inputs, not only products.
341        let mut s = 0x9E37_79B9_7F4A_7C15u128;
342        for _ in 0..2_000_000 {
343            s = s.wrapping_mul(0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645).wrapping_add(1);
344            assert_eq!(reduce128(s), (s % P as u128) as u64, "x = {s}");
345        }
346        for x in [u128::MAX, u128::MAX - 1, (P as u128) << 64, ((P as u128) << 64) - 1, 1u128 << 127] {
347            assert_eq!(reduce128(x), (x % P as u128) as u64, "x = {x}");
348        }
349    }
350
351    #[test]
352    fn generalised_binomial() {
353        assert_eq!(binom(5, 2), Fp::new(10));
354        assert_eq!(binom(-3, 2), Fp::new(6)); // (-3)(-4)/2
355        assert_eq!(binom(2, 5), Fp::ZERO);
356    }
357}