arnaucube
arnaucube/fhe-studyPublic Self-hosted repository
fhe-study/arithmetic/src/ringq.rs
arithmetic/src/ringq.rsRaw
  1//! Polynomial ring Z_q[X]/(X^N+1)
  2//!
  3
  4use rand::{distributions::Distribution, Rng};
  5use std::array;
  6use std::fmt;
  7use std::ops;
  8
  9use crate::ntt::NTT;
 10use crate::zq::{modulus_u64, Zq};
 11use anyhow::{anyhow, Result};
 12
 13/// PolynomialRing element, where the PolynomialRing is R = Z_q[X]/(X^n +1)
 14/// The implementation assumes that q is prime.
 15#[derive(Clone, Copy)]
 16pub struct Rq<const Q: u64, const N: usize> {
 17    pub(crate) coeffs: [Zq<Q>; N],
 18
 19    // evals are set when doig a PRxPR multiplication, so it can be reused in future
 20    // multiplications avoiding recomputing it
 21    pub(crate) evals: Option<[Zq<Q>; N]>,
 22}
 23
 24// TODO define a trait "PolynomialRingTrait" or similar, so that when other structs use it can just
 25// use the trait and not need to add '<Q, N>' to their params
 26
 27impl<const Q: u64, const N: usize> From<crate::ring::R<N>> for Rq<Q, N> {
 28    fn from(r: crate::ring::R<N>) -> Self {
 29        Self::from_vec(
 30            r.coeffs()
 31                .iter()
 32                .map(|e| Zq::<Q>::from_f64(*e as f64))
 33                .collect(),
 34        )
 35    }
 36}
 37
 38// apply mod (X^N+1)
 39pub fn modulus<const Q: u64, const N: usize>(p: &mut Vec<Zq<Q>>) {
 40    if p.len() < N {
 41        return;
 42    }
 43    for i in N..p.len() {
 44        p[i - N] = p[i - N].clone() - p[i].clone();
 45        p[i] = Zq(0);
 46    }
 47    p.truncate(N);
 48}
 49
 50// PR stands for PolynomialRing
 51impl<const Q: u64, const N: usize> Rq<Q, N> {
 52    pub fn coeffs(&self) -> [Zq<Q>; N] {
 53        self.coeffs
 54    }
 55    pub fn to_r(self) -> crate::R<N> {
 56        crate::R::<N>::from(self)
 57    }
 58
 59    pub fn from_vec(coeffs: Vec<Zq<Q>>) -> Self {
 60        let mut p = coeffs;
 61        modulus::<Q, N>(&mut p);
 62        let coeffs = array::from_fn(|i| p[i]);
 63        Self {
 64            coeffs,
 65            evals: None,
 66        }
 67    }
 68    // this method is mostly for tests
 69    pub fn from_vec_u64(coeffs: Vec<u64>) -> Self {
 70        let coeffs_mod_q = coeffs.iter().map(|c| Zq::from_u64(*c)).collect();
 71        Self::from_vec(coeffs_mod_q)
 72    }
 73    pub fn from_vec_f64(coeffs: Vec<f64>) -> Self {
 74        let coeffs_mod_q = coeffs.iter().map(|c| Zq::from_f64(*c)).collect();
 75        Self::from_vec(coeffs_mod_q)
 76    }
 77    pub fn from_vec_i64(coeffs: Vec<i64>) -> Self {
 78        let coeffs_mod_q = coeffs.iter().map(|c| Zq::from_f64(*c as f64)).collect();
 79        Self::from_vec(coeffs_mod_q)
 80    }
 81    pub fn new(coeffs: [Zq<Q>; N], evals: Option<[Zq<Q>; N]>) -> Self {
 82        Self { coeffs, evals }
 83    }
 84
 85    pub fn rand_abs(mut rng: impl Rng, dist: impl Distribution<f64>) -> Result<Self> {
 86        let coeffs: [Zq<Q>; N] = array::from_fn(|_| Zq::from_f64(dist.sample(&mut rng).abs()));
 87        Ok(Self {
 88            coeffs,
 89            evals: None,
 90        })
 91    }
 92    pub fn rand_f64_abs(mut rng: impl Rng, dist: impl Distribution<f64>) -> Result<Self> {
 93        let coeffs: [Zq<Q>; N] = array::from_fn(|_| Zq::from_f64(dist.sample(&mut rng).abs()));
 94        Ok(Self {
 95            coeffs,
 96            evals: None,
 97        })
 98    }
 99    pub fn rand_f64(mut rng: impl Rng, dist: impl Distribution<f64>) -> Result<Self> {
100        let coeffs: [Zq<Q>; N] = array::from_fn(|_| Zq::from_f64(dist.sample(&mut rng)));
101        Ok(Self {
102            coeffs,
103            evals: None,
104        })
105    }
106    pub fn rand_u64(mut rng: impl Rng, dist: impl Distribution<u64>) -> Result<Self> {
107        let coeffs: [Zq<Q>; N] = array::from_fn(|_| Zq::from_u64(dist.sample(&mut rng)));
108        Ok(Self {
109            coeffs,
110            evals: None,
111        })
112    }
113    // WIP. returns random v \in {0,1}. // TODO {-1, 0, 1}
114    pub fn rand_bin(mut rng: impl Rng, dist: impl Distribution<bool>) -> Result<Self> {
115        let coeffs: [Zq<Q>; N] = array::from_fn(|_| Zq::from_bool(dist.sample(&mut rng)));
116        Ok(Rq {
117            coeffs,
118            evals: None,
119        })
120    }
121    // Warning: this method will behave differently depending on the values P and Q:
122    // if Q<P, it just 'renames' the modulus parameter to P
123    // if Q>=P, it crops to mod P
124    pub fn remodule<const P: u64>(&self) -> Rq<P, N> {
125        Rq::<P, N>::from_vec_u64(self.coeffs().iter().map(|m_i| m_i.0).collect())
126    }
127    // applies mod(T) to all coefficients of self
128    pub fn coeffs_mod<const T: u64>(&self) -> Self {
129        Rq::<Q, N>::from_vec_u64(
130            self.coeffs()
131                .iter()
132                .map(|m_i| modulus_u64::<T>(m_i.0))
133                .collect(),
134        )
135    }
136
137    // TODO review if needed, or if with this interface
138    pub fn mul_by_matrix(&self, m: &Vec<Vec<Zq<Q>>>) -> Result<Vec<Zq<Q>>> {
139        matrix_vec_product(m, &self.coeffs.to_vec())
140    }
141    pub fn mul_by_zq(&self, s: &Zq<Q>) -> Self {
142        Self {
143            coeffs: array::from_fn(|i| self.coeffs[i] * *s),
144            evals: None,
145        }
146    }
147    pub fn mul_by_u64(&self, s: u64) -> Self {
148        let s = Zq::from_u64(s);
149        Self {
150            coeffs: array::from_fn(|i| self.coeffs[i] * s),
151            // coeffs: self.coeffs.iter().map(|&e| e * s).collect(),
152            evals: None,
153        }
154    }
155    pub fn mul_by_f64(&self, s: f64) -> Self {
156        Self {
157            coeffs: array::from_fn(|i| Zq::from_f64(self.coeffs[i].0 as f64 * s)),
158            evals: None,
159        }
160    }
161
162    pub fn mul(&mut self, rhs: &mut Self) -> Self {
163        mul_mut(self, rhs)
164    }
165    // divides by the given scalar 's' and rounds, returning a Rq<Q,N>
166    // TODO rm
167    pub fn div_round(&self, s: u64) -> Self {
168        let r: Vec<f64> = self
169            .coeffs()
170            .iter()
171            .map(|e| (e.0 as f64 / s as f64).round())
172            .collect();
173        Rq::<Q, N>::from_vec_f64(r)
174    }
175    // returns [ [(num/den) * self].round() ] mod q
176    // ie. performs the multiplication and division over f64, and then it rounds the
177    // result, only applying the mod Q at the end
178    pub fn mul_div_round(&self, num: u64, den: u64) -> Self {
179        let r: Vec<f64> = self
180            .coeffs()
181            .iter()
182            .map(|e| ((num as f64 * e.0 as f64) / den as f64).round())
183            .collect();
184        Rq::<Q, N>::from_vec_f64(r)
185    }
186
187    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188        // TODO simplify
189        let mut str = "";
190        let mut zero = true;
191        for (i, coeff) in self.coeffs.iter().enumerate().rev() {
192            if coeff.0 == 0 {
193                continue;
194            }
195            zero = false;
196            f.write_str(str)?;
197            if coeff.0 != 1 {
198                f.write_str(coeff.0.to_string().as_str())?;
199                if i > 0 {
200                    f.write_str("*")?;
201                }
202            }
203            if coeff.0 == 1 && i == 0 {
204                f.write_str(coeff.0.to_string().as_str())?;
205            }
206            if i == 1 {
207                f.write_str("x")?;
208            } else if i > 1 {
209                f.write_str("x^")?;
210                f.write_str(i.to_string().as_str())?;
211            }
212            str = " + ";
213        }
214        if zero {
215            f.write_str("0")?;
216        }
217
218        f.write_str(" mod Z_")?;
219        f.write_str(Q.to_string().as_str())?;
220        f.write_str("/(X^")?;
221        f.write_str(N.to_string().as_str())?;
222        f.write_str("+1)")?;
223        Ok(())
224    }
225
226    pub fn infinity_norm(&self) -> u64 {
227        self.coeffs().iter().map(|x| x.0).fold(0, |a, b| a.max(b))
228    }
229}
230pub fn matrix_vec_product<const Q: u64>(m: &Vec<Vec<Zq<Q>>>, v: &Vec<Zq<Q>>) -> Result<Vec<Zq<Q>>> {
231    // assert_eq!(m.len(), m[0].len()); // TODO change to returning err
232    // assert_eq!(m.len(), v.len());
233    if m.len() != m[0].len() {
234        return Err(anyhow!("expected 'm' to be a square matrix"));
235    }
236    if m.len() != v.len() {
237        return Err(anyhow!(
238            "m.len: {} should be equal to v.len(): {}",
239            m.len(),
240            v.len(),
241        ));
242    }
243
244    Ok(m.iter()
245        .map(|row| {
246            row.iter()
247                .zip(v.iter())
248                .map(|(&row_i, &v_i)| row_i * v_i)
249                .sum()
250        })
251        .collect::<Vec<Zq<Q>>>())
252}
253pub fn transpose<const Q: u64>(m: &[Vec<Zq<Q>>]) -> Vec<Vec<Zq<Q>>> {
254    // TODO case when m[0].len()=0
255    // TODO non square matrix
256    let mut r: Vec<Vec<Zq<Q>>> = vec![vec![Zq(0); m[0].len()]; m.len()];
257    for (i, m_row) in m.iter().enumerate() {
258        for (j, m_ij) in m_row.iter().enumerate() {
259            r[j][i] = *m_ij;
260        }
261    }
262    r
263}
264
265impl<const Q: u64, const N: usize> PartialEq for Rq<Q, N> {
266    fn eq(&self, other: &Self) -> bool {
267        self.coeffs == other.coeffs
268    }
269}
270impl<const Q: u64, const N: usize> ops::Add<Rq<Q, N>> for Rq<Q, N> {
271    type Output = Self;
272
273    fn add(self, rhs: Self) -> Self {
274        Self {
275            coeffs: array::from_fn(|i| self.coeffs[i] + rhs.coeffs[i]),
276            evals: None,
277        }
278        // Self {
279        //     coeffs: self
280        //         .coeffs
281        //         .iter()
282        //         .zip(rhs.coeffs)
283        //         .map(|(a, b)| *a + b)
284        //         .collect(),
285        //     evals: None,
286        // }
287        // Self(r.iter_mut().map(|e| e.r#mod()).collect()) // TODO mod should happen auto in +
288    }
289}
290impl<const Q: u64, const N: usize> ops::Add<&Rq<Q, N>> for &Rq<Q, N> {
291    type Output = Rq<Q, N>;
292
293    fn add(self, rhs: &Rq<Q, N>) -> Self::Output {
294        Rq {
295            coeffs: array::from_fn(|i| self.coeffs[i] + rhs.coeffs[i]),
296            evals: None,
297        }
298    }
299}
300impl<const Q: u64, const N: usize> ops::Sub<Rq<Q, N>> for Rq<Q, N> {
301    type Output = Self;
302
303    fn sub(self, rhs: Self) -> Self {
304        Self {
305            coeffs: array::from_fn(|i| self.coeffs[i] - rhs.coeffs[i]),
306            evals: None,
307        }
308    }
309}
310impl<const Q: u64, const N: usize> ops::Sub<&Rq<Q, N>> for &Rq<Q, N> {
311    type Output = Rq<Q, N>;
312
313    fn sub(self, rhs: &Rq<Q, N>) -> Self::Output {
314        Rq {
315            coeffs: array::from_fn(|i| self.coeffs[i] - rhs.coeffs[i]),
316            evals: None,
317        }
318    }
319}
320impl<const Q: u64, const N: usize> ops::Mul<Rq<Q, N>> for Rq<Q, N> {
321    type Output = Self;
322
323    fn mul(self, rhs: Self) -> Self {
324        mul(&self, &rhs)
325    }
326}
327impl<const Q: u64, const N: usize> ops::Mul<&Rq<Q, N>> for &Rq<Q, N> {
328    type Output = Rq<Q, N>;
329
330    fn mul(self, rhs: &Rq<Q, N>) -> Self::Output {
331        mul(self, rhs)
332    }
333}
334
335// mul by Zq element
336impl<const Q: u64, const N: usize> ops::Mul<Zq<Q>> for Rq<Q, N> {
337    type Output = Self;
338
339    fn mul(self, s: Zq<Q>) -> Self {
340        self.mul_by_zq(&s)
341    }
342}
343impl<const Q: u64, const N: usize> ops::Mul<&Zq<Q>> for &Rq<Q, N> {
344    type Output = Rq<Q, N>;
345
346    fn mul(self, s: &Zq<Q>) -> Self::Output {
347        self.mul_by_zq(s)
348    }
349}
350// mul by u64
351impl<const Q: u64, const N: usize> ops::Mul<u64> for Rq<Q, N> {
352    type Output = Self;
353
354    fn mul(self, s: u64) -> Self {
355        self.mul_by_u64(s)
356    }
357}
358impl<const Q: u64, const N: usize> ops::Mul<&u64> for &Rq<Q, N> {
359    type Output = Rq<Q, N>;
360
361    fn mul(self, s: &u64) -> Self::Output {
362        self.mul_by_u64(*s)
363    }
364}
365
366impl<const Q: u64, const N: usize> ops::Neg for Rq<Q, N> {
367    type Output = Self;
368
369    fn neg(self) -> Self::Output {
370        Self {
371            coeffs: array::from_fn(|i| -self.coeffs[i]),
372            evals: None,
373        }
374    }
375}
376
377fn mul_mut<const Q: u64, const N: usize>(lhs: &mut Rq<Q, N>, rhs: &mut Rq<Q, N>) -> Rq<Q, N> {
378    // reuse evaluations if already computed
379    if !lhs.evals.is_some() {
380        lhs.evals = Some(NTT::<Q, N>::ntt(lhs.coeffs));
381    };
382    if !rhs.evals.is_some() {
383        rhs.evals = Some(NTT::<Q, N>::ntt(rhs.coeffs));
384    };
385    let lhs_evals = lhs.evals.unwrap();
386    let rhs_evals = rhs.evals.unwrap();
387
388    let c_ntt: [Zq<Q>; N] = array::from_fn(|i| lhs_evals[i] * rhs_evals[i]);
389    let c = NTT::<Q, { N }>::intt(c_ntt);
390    Rq::new(c, Some(c_ntt))
391}
392fn mul<const Q: u64, const N: usize>(lhs: &Rq<Q, N>, rhs: &Rq<Q, N>) -> Rq<Q, N> {
393    // reuse evaluations if already computed
394    let lhs_evals = if lhs.evals.is_some() {
395        lhs.evals.unwrap()
396    } else {
397        NTT::<Q, N>::ntt(lhs.coeffs)
398    };
399    let rhs_evals = if rhs.evals.is_some() {
400        rhs.evals.unwrap()
401    } else {
402        NTT::<Q, N>::ntt(rhs.coeffs)
403    };
404
405    let c_ntt: [Zq<Q>; N] = array::from_fn(|i| lhs_evals[i] * rhs_evals[i]);
406    let c = NTT::<Q, { N }>::intt(c_ntt);
407    Rq::new(c, Some(c_ntt))
408}
409
410impl<const Q: u64, const N: usize> fmt::Display for Rq<Q, N> {
411    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
412        self.fmt(f)?;
413        Ok(())
414    }
415}
416impl<const Q: u64, const N: usize> fmt::Debug for Rq<Q, N> {
417    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418        self.fmt(f)?;
419        Ok(())
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn poly_ring() {
429        // the test values used are generated with SageMath
430        const Q: u64 = 7;
431        const N: usize = 3;
432
433        // p = 1x + 2x^2 + 3x^3 + 4 x^4 + 5 x^5 in R=Z_q[X]/(X^n +1)
434        let p = Rq::<Q, N>::from_vec_u64(vec![0u64, 1, 2, 3, 4, 5]);
435        assert_eq!(p.to_string(), "4*x^2 + 4*x + 4 mod Z_7/(X^3+1)");
436
437        // try with coefficients bigger than Q
438        let p = Rq::<Q, N>::from_vec_u64(vec![0u64, 1, Q + 2, 3, 4, 5]);
439        assert_eq!(p.to_string(), "4*x^2 + 4*x + 4 mod Z_7/(X^3+1)");
440
441        // try with other ring
442        let p = Rq::<7, 4>::from_vec_u64(vec![0u64, 1, 2, 3, 4, 5]);
443        assert_eq!(p.to_string(), "3*x^3 + 2*x^2 + 3*x + 3 mod Z_7/(X^4+1)");
444
445        let p = Rq::<Q, N>::from_vec_u64(vec![0u64, 0, 0, 0, 4, 5]);
446        assert_eq!(p.to_string(), "2*x^2 + 3*x mod Z_7/(X^3+1)");
447
448        let p = Rq::<Q, N>::from_vec_u64(vec![5u64, 4, 5, 2, 1, 0]);
449        assert_eq!(p.to_string(), "5*x^2 + 3*x + 3 mod Z_7/(X^3+1)");
450
451        let a = Rq::<Q, N>::from_vec_u64(vec![0u64, 1, 2, 3, 4, 5]);
452        assert_eq!(a.to_string(), "4*x^2 + 4*x + 4 mod Z_7/(X^3+1)");
453
454        let b = Rq::<Q, N>::from_vec_u64(vec![5u64, 4, 3, 2, 1, 0]);
455        assert_eq!(b.to_string(), "3*x^2 + 3*x + 3 mod Z_7/(X^3+1)");
456
457        // add
458        assert_eq!((a.clone() + b.clone()).to_string(), "0 mod Z_7/(X^3+1)");
459        assert_eq!((&a + &b).to_string(), "0 mod Z_7/(X^3+1)");
460        // assert_eq!((a.0.clone() + b.0.clone()).to_string(), "[0, 0, 0]"); // TODO
461
462        // sub
463        assert_eq!(
464            (a.clone() - b.clone()).to_string(),
465            "x^2 + x + 1 mod Z_7/(X^3+1)"
466        );
467    }
468
469    fn test_mul_opt<const Q: u64, const N: usize>(
470        a: [u64; N],
471        b: [u64; N],
472        expected_c: [u64; N],
473    ) -> Result<()> {
474        let a: [Zq<Q>; N] = array::from_fn(|i| Zq::from_u64(a[i]));
475        let mut a = Rq::new(a, None);
476        let b: [Zq<Q>; N] = array::from_fn(|i| Zq::from_u64(b[i]));
477        let mut b = Rq::new(b, None);
478        let expected_c: [Zq<Q>; N] = array::from_fn(|i| Zq::from_u64(expected_c[i]));
479        let expected_c = Rq::new(expected_c, None);
480
481        let c = mul_mut(&mut a, &mut b);
482        assert_eq!(c, expected_c);
483        Ok(())
484    }
485    #[test]
486    fn test_mul() -> Result<()> {
487        const Q: u64 = 2u64.pow(16) + 1;
488        const N: usize = 4;
489
490        let a: [u64; N] = [1u64, 2, 3, 4];
491        let b: [u64; N] = [1u64, 2, 3, 4];
492        let c: [u64; N] = [65513, 65517, 65531, 20];
493        test_mul_opt::<Q, N>(a, b, c)?;
494
495        let a: [u64; N] = [0u64, 0, 0, 2];
496        let b: [u64; N] = [0u64, 0, 0, 2];
497        let c: [u64; N] = [0u64, 0, 65533, 0];
498        test_mul_opt::<Q, N>(a, b, c)?;
499
500        // TODO more testvectors
501
502        Ok(())
503    }
504}