@ -1,433 +1,33 @@ |
|||||
//! Polynomial ring Z[X]/(X^N+1)
|
|
||||
//!
|
|
||||
|
|
||||
use anyhow::Result;
|
|
||||
use rand::{distributions::Distribution, Rng};
|
use rand::{distributions::Distribution, Rng};
|
||||
use std::array;
|
|
||||
use std::fmt;
|
|
||||
|
use std::fmt::Debug;
|
||||
use std::iter::Sum;
|
use std::iter::Sum;
|
||||
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
|
|
||||
|
|
||||
use crate::Ring;
|
|
||||
|
|
||||
// TODO rename to not have name conflicts with the Ring trait (R: Ring)
|
|
||||
// PolynomialRing element, where the PolynomialRing is R = Z[X]/(X^n +1)
|
|
||||
#[derive(Clone, Copy)]
|
|
||||
pub struct R<const N: usize>(pub [i64; N]);
|
|
||||
|
|
||||
impl<const N: usize> Ring for R<N> {
|
|
||||
type C = i64;
|
|
||||
fn coeffs(&self) -> Vec<Self::C> {
|
|
||||
self.0.to_vec()
|
|
||||
}
|
|
||||
fn zero() -> Self {
|
|
||||
let coeffs: [i64; N] = array::from_fn(|_| 0i64);
|
|
||||
Self(coeffs)
|
|
||||
}
|
|
||||
fn rand(mut rng: impl Rng, dist: impl Distribution<f64>) -> Self {
|
|
||||
// let coeffs: [i64; N] = array::from_fn(|_| Self::C::rand(&mut rng, &dist));
|
|
||||
let coeffs: [i64; N] = array::from_fn(|_| dist.sample(&mut rng).round() as i64);
|
|
||||
Self(coeffs)
|
|
||||
// let coeffs: [C; N] = array::from_fn(|_| Zq::from_u64(dist.sample(&mut rng)));
|
|
||||
// Self(coeffs)
|
|
||||
}
|
|
||||
|
|
||||
// returns the decomposition of each polynomial coefficient
|
|
||||
fn decompose(&self, beta: u32, l: u32) -> Vec<Self> {
|
|
||||
unimplemented!();
|
|
||||
// array::from_fn(|i| self.coeffs[i].decompose(beta, l))
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const Q: u64, const N: usize> From<crate::ringq::Rq<Q, N>> for R<N> {
|
|
||||
fn from(rq: crate::ringq::Rq<Q, N>) -> Self {
|
|
||||
Self::from_vec_u64(rq.coeffs().to_vec().iter().map(|e| e.0).collect())
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> R<N> {
|
|
||||
pub fn coeffs(&self) -> [i64; N] {
|
|
||||
self.0
|
|
||||
}
|
|
||||
pub fn to_rq<const Q: u64>(self) -> crate::Rq<Q, N> {
|
|
||||
crate::Rq::<Q, N>::from(self)
|
|
||||
}
|
|
||||
|
|
||||
pub fn from_vec(coeffs: Vec<i64>) -> Self {
|
|
||||
let mut p = coeffs;
|
|
||||
modulus::<N>(&mut p);
|
|
||||
Self(array::from_fn(|i| p[i]))
|
|
||||
}
|
|
||||
// this method is mostly for tests
|
|
||||
pub fn from_vec_u64(coeffs: Vec<u64>) -> Self {
|
|
||||
let coeffs_i64 = coeffs.iter().map(|c| *c as i64).collect();
|
|
||||
Self::from_vec(coeffs_i64)
|
|
||||
}
|
|
||||
pub fn from_vec_f64(coeffs: Vec<f64>) -> Self {
|
|
||||
let coeffs_i64 = coeffs.iter().map(|c| c.round() as i64).collect();
|
|
||||
Self::from_vec(coeffs_i64)
|
|
||||
}
|
|
||||
pub fn new(coeffs: [i64; N]) -> Self {
|
|
||||
Self(coeffs)
|
|
||||
}
|
|
||||
pub fn mul_by_i64(&self, s: i64) -> Self {
|
|
||||
Self(array::from_fn(|i| self.0[i] * s))
|
|
||||
}
|
|
||||
// performs the multiplication and division over f64, and then it rounds the
|
|
||||
// result, only applying the mod Q at the end
|
|
||||
pub fn mul_div_round<const Q: u64>(&self, num: u64, den: u64) -> crate::Rq<Q, N> {
|
|
||||
let r: Vec<f64> = self
|
|
||||
.coeffs()
|
|
||||
.iter()
|
|
||||
.map(|e| ((num as f64 * *e as f64) / den as f64).round())
|
|
||||
.collect();
|
|
||||
crate::Rq::<Q, N>::from_vec_f64(r)
|
|
||||
}
|
|
||||
|
|
||||
pub fn infinity_norm(&self) -> u64 {
|
|
||||
self.coeffs()
|
|
||||
.iter()
|
|
||||
// .map(|x| if x.0 > (Q / 2) { Q - x.0 } else { x.0 })
|
|
||||
.map(|x| x.abs() as u64)
|
|
||||
.fold(0, |a, b| a.max(b))
|
|
||||
}
|
|
||||
pub fn mod_centered_q<const Q: u64>(&self) -> R<N> {
|
|
||||
let q = Q as i64;
|
|
||||
let r = self
|
|
||||
.0
|
|
||||
.iter()
|
|
||||
.map(|v| {
|
|
||||
let mut res = v % q;
|
|
||||
if res > q / 2 {
|
|
||||
res = res - q;
|
|
||||
}
|
|
||||
res
|
|
||||
})
|
|
||||
.collect::<Vec<i64>>();
|
|
||||
R::<N>::from_vec(r)
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
pub fn mul_div_round<const Q: u64, const N: usize>(
|
|
||||
v: Vec<i64>,
|
|
||||
num: u64,
|
|
||||
den: u64,
|
|
||||
) -> crate::Rq<Q, N> {
|
|
||||
// dbg!(&v);
|
|
||||
let r: Vec<f64> = v
|
|
||||
.iter()
|
|
||||
.map(|e| ((num as f64 * *e as f64) / den as f64).round())
|
|
||||
.collect();
|
|
||||
// dbg!(&r);
|
|
||||
crate::Rq::<Q, N>::from_vec_f64(r)
|
|
||||
}
|
|
||||
|
|
||||
// TODO rename to make it clear that is not mod q, but mod X^N+1
|
|
||||
// apply mod (X^N+1)
|
|
||||
pub fn modulus<const N: usize>(p: &mut Vec<i64>) {
|
|
||||
if p.len() < N {
|
|
||||
return;
|
|
||||
}
|
|
||||
for i in N..p.len() {
|
|
||||
p[i - N] = p[i - N].clone() - p[i].clone();
|
|
||||
p[i] = 0;
|
|
||||
}
|
|
||||
p.truncate(N);
|
|
||||
}
|
|
||||
pub fn modulus_i128<const N: usize>(p: &mut Vec<i128>) {
|
|
||||
if p.len() < N {
|
|
||||
return;
|
|
||||
}
|
|
||||
for i in N..p.len() {
|
|
||||
p[i - N] = p[i - N].clone() - p[i].clone();
|
|
||||
p[i] = 0;
|
|
||||
}
|
|
||||
p.truncate(N);
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> PartialEq for R<N> {
|
|
||||
fn eq(&self, other: &Self) -> bool {
|
|
||||
self.0 == other.0
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> Add<R<N>> for R<N> {
|
|
||||
type Output = Self;
|
|
||||
|
|
||||
fn add(self, rhs: Self) -> Self {
|
|
||||
Self(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> Add<&R<N>> for &R<N> {
|
|
||||
type Output = R<N>;
|
|
||||
|
|
||||
fn add(self, rhs: &R<N>) -> Self::Output {
|
|
||||
R(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> AddAssign for R<N> {
|
|
||||
fn add_assign(&mut self, rhs: Self) {
|
|
||||
for i in 0..N {
|
|
||||
self.0[i] += rhs.0[i];
|
|
||||
}
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> Sum<R<N>> for R<N> {
|
|
||||
fn sum<I>(iter: I) -> Self
|
|
||||
where
|
|
||||
I: Iterator<Item = Self>,
|
|
||||
{
|
|
||||
let mut acc = R::<N>::zero();
|
|
||||
for e in iter {
|
|
||||
acc += e;
|
|
||||
}
|
|
||||
acc
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> Sub<R<N>> for R<N> {
|
|
||||
type Output = Self;
|
|
||||
|
|
||||
fn sub(self, rhs: Self) -> Self {
|
|
||||
Self(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> Sub<&R<N>> for &R<N> {
|
|
||||
type Output = R<N>;
|
|
||||
|
|
||||
fn sub(self, rhs: &R<N>) -> Self::Output {
|
|
||||
R(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> SubAssign for R<N> {
|
|
||||
fn sub_assign(&mut self, rhs: Self) {
|
|
||||
for i in 0..N {
|
|
||||
self.0[i] -= rhs.0[i];
|
|
||||
}
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> Mul<R<N>> for R<N> {
|
|
||||
type Output = Self;
|
|
||||
|
|
||||
fn mul(self, rhs: Self) -> Self {
|
|
||||
naive_poly_mul(&self, &rhs)
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> Mul<&R<N>> for &R<N> {
|
|
||||
type Output = R<N>;
|
|
||||
|
|
||||
fn mul(self, rhs: &R<N>) -> Self::Output {
|
|
||||
naive_poly_mul(self, rhs)
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
// TODO WIP
|
|
||||
pub fn naive_poly_mul<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> R<N> {
|
|
||||
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
|
||||
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
|
||||
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
|
||||
for i in 0..N {
|
|
||||
for j in 0..N {
|
|
||||
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
// apply mod (X^N + 1))
|
|
||||
// R::<N>::from_vec(result.iter().map(|c| *c as i64).collect())
|
|
||||
modulus_i128::<N>(&mut result);
|
|
||||
// dbg!(&result);
|
|
||||
// dbg!(R::<N>(array::from_fn(|i| result[i] as i64)).coeffs());
|
|
||||
|
|
||||
// sanity check: check that there are no coeffs > i64_max
|
|
||||
assert_eq!(
|
|
||||
result,
|
|
||||
R::<N>(array::from_fn(|i| result[i] as i64))
|
|
||||
.coeffs()
|
|
||||
.iter()
|
|
||||
.map(|c| *c as i128)
|
|
||||
.collect::<Vec<_>>()
|
|
||||
);
|
|
||||
R(array::from_fn(|i| result[i] as i64))
|
|
||||
}
|
|
||||
pub fn naive_mul_2<const N: usize>(poly1: &Vec<i128>, poly2: &Vec<i128>) -> Vec<i128> {
|
|
||||
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
|
||||
for i in 0..N {
|
|
||||
for j in 0..N {
|
|
||||
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
// apply mod (X^N + 1))
|
|
||||
// R::<N>::from_vec(result.iter().map(|c| *c as i64).collect())
|
|
||||
modulus_i128::<N>(&mut result);
|
|
||||
result
|
|
||||
}
|
|
||||
|
|
||||
pub fn naive_mul<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> Vec<i64> {
|
|
||||
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
|
||||
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
|
||||
let mut result = vec![0; (N * 2) - 1];
|
|
||||
for i in 0..N {
|
|
||||
for j in 0..N {
|
|
||||
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
|
||||
}
|
|
||||
}
|
|
||||
result.iter().map(|c| *c as i64).collect()
|
|
||||
}
|
|
||||
pub fn naive_mul_TMP<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> Vec<i64> {
|
|
||||
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
|
||||
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
|
||||
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
|
||||
for i in 0..N {
|
|
||||
for j in 0..N {
|
|
||||
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
// dbg!(&result);
|
|
||||
modulus_i128::<N>(&mut result);
|
|
||||
// for c_i in result.iter() {
|
|
||||
// println!("---");
|
|
||||
// println!("{:?}", &c_i);
|
|
||||
// println!("{:?}", *c_i as i64);
|
|
||||
// println!("{:?}", (*c_i as i64) as i128);
|
|
||||
// assert_eq!(*c_i, (*c_i as i64) as i128, "{:?}", c_i);
|
|
||||
// }
|
|
||||
result.iter().map(|c| *c as i64).collect()
|
|
||||
}
|
|
||||
|
|
||||
// wip
|
|
||||
pub fn mod_centered_q<const Q: u64, const N: usize>(p: Vec<i128>) -> R<N> {
|
|
||||
let q: i128 = Q as i128;
|
|
||||
let r = p
|
|
||||
.iter()
|
|
||||
.map(|v| {
|
|
||||
let mut res = v % q;
|
|
||||
if res > q / 2 {
|
|
||||
res = res - q;
|
|
||||
}
|
|
||||
res
|
|
||||
})
|
|
||||
.collect::<Vec<i128>>();
|
|
||||
R::<N>::from_vec(r.iter().map(|v| *v as i64).collect::<Vec<i64>>())
|
|
||||
}
|
|
||||
|
|
||||
// mul by u64
|
|
||||
impl<const N: usize> Mul<u64> for R<N> {
|
|
||||
type Output = Self;
|
|
||||
|
|
||||
fn mul(self, s: u64) -> Self {
|
|
||||
self.mul_by_i64(s as i64)
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> Mul<&u64> for &R<N> {
|
|
||||
type Output = R<N>;
|
|
||||
|
|
||||
fn mul(self, s: &u64) -> Self::Output {
|
|
||||
self.mul_by_i64(*s as i64)
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> Neg for R<N> {
|
|
||||
type Output = Self;
|
|
||||
|
|
||||
fn neg(self) -> Self::Output {
|
|
||||
Self(array::from_fn(|i| -self.0[i]))
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
impl<const N: usize> R<N> {
|
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||
let mut str = "";
|
|
||||
let mut zero = true;
|
|
||||
for (i, coeff) in self.0.iter().enumerate().rev() {
|
|
||||
if *coeff == 0 {
|
|
||||
continue;
|
|
||||
}
|
|
||||
zero = false;
|
|
||||
f.write_str(str)?;
|
|
||||
if *coeff != 1 {
|
|
||||
f.write_str(coeff.to_string().as_str())?;
|
|
||||
if i > 0 {
|
|
||||
f.write_str("*")?;
|
|
||||
}
|
|
||||
}
|
|
||||
if *coeff == 1 && i == 0 {
|
|
||||
f.write_str(coeff.to_string().as_str())?;
|
|
||||
}
|
|
||||
if i == 1 {
|
|
||||
f.write_str("x")?;
|
|
||||
} else if i > 1 {
|
|
||||
f.write_str("x^")?;
|
|
||||
f.write_str(i.to_string().as_str())?;
|
|
||||
}
|
|
||||
str = " + ";
|
|
||||
}
|
|
||||
if zero {
|
|
||||
f.write_str("0")?;
|
|
||||
}
|
|
||||
|
|
||||
f.write_str(" mod Z")?;
|
|
||||
f.write_str("/(X^")?;
|
|
||||
f.write_str(N.to_string().as_str())?;
|
|
||||
f.write_str("+1)")?;
|
|
||||
Ok(())
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> fmt::Display for R<N> {
|
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||
self.fmt(f)?;
|
|
||||
Ok(())
|
|
||||
}
|
|
||||
}
|
|
||||
impl<const N: usize> fmt::Debug for R<N> {
|
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||
self.fmt(f)?;
|
|
||||
Ok(())
|
|
||||
}
|
|
||||
}
|
|
||||
|
|
||||
#[cfg(test)]
|
|
||||
mod tests {
|
|
||||
use super::*;
|
|
||||
use anyhow::Result;
|
|
||||
|
|
||||
#[test]
|
|
||||
fn test_mul() -> Result<()> {
|
|
||||
const Q: u64 = 2u64.pow(16) + 1;
|
|
||||
const N: usize = 2;
|
|
||||
let q: i64 = Q as i64;
|
|
||||
|
|
||||
// test vectors generated with SageMath
|
|
||||
let a: [i64; N] = [q - 1, q - 1];
|
|
||||
let b: [i64; N] = [q - 1, q - 1];
|
|
||||
let c: [i64; N] = [0, 8589934592];
|
|
||||
test_mul_opt::<Q, N>(a, b, c)?;
|
|
||||
|
|
||||
let a: [i64; N] = [1, q - 1];
|
|
||||
let b: [i64; N] = [1, q - 1];
|
|
||||
let c: [i64; N] = [-4294967295, 131072];
|
|
||||
test_mul_opt::<Q, N>(a, b, c)?;
|
|
||||
|
|
||||
Ok(())
|
|
||||
}
|
|
||||
fn test_mul_opt<const Q: u64, const N: usize>(
|
|
||||
a: [i64; N],
|
|
||||
b: [i64; N],
|
|
||||
expected_c: [i64; N],
|
|
||||
) -> Result<()> {
|
|
||||
let mut a = R::new(a);
|
|
||||
let mut b = R::new(b);
|
|
||||
dbg!(&a);
|
|
||||
dbg!(&b);
|
|
||||
let expected_c = R::new(expected_c);
|
|
||||
|
|
||||
let mut c = naive_mul(&mut a, &mut b);
|
|
||||
modulus::<N>(&mut c);
|
|
||||
dbg!(R::<N>::from_vec(c.clone()));
|
|
||||
assert_eq!(c, expected_c.0.to_vec());
|
|
||||
Ok(())
|
|
||||
}
|
|
||||
|
use std::ops::{Add, AddAssign, Mul, Sub, SubAssign};
|
||||
|
|
||||
|
/// Represents a ring element. Currently implemented by ring_n.rs#R and ring_nq.rs#Rq.
|
||||
|
pub trait Ring: |
||||
|
Sized
|
||||
|
+ Add<Output = Self>
|
||||
|
+ AddAssign
|
||||
|
+ Sum
|
||||
|
+ Sub<Output = Self>
|
||||
|
+ SubAssign
|
||||
|
+ Mul<Output = Self>
|
||||
|
+ Mul<u64, Output = Self> // scalar mul
|
||||
|
+ PartialEq
|
||||
|
+ Debug
|
||||
|
+ Clone
|
||||
|
+ Sum<<Self as Add>::Output>
|
||||
|
+ Sum<<Self as Mul>::Output>
|
||||
|
{
|
||||
|
/// C defines the coefficient type
|
||||
|
type C: Debug + Clone;
|
||||
|
|
||||
|
fn coeffs(&self) -> Vec<Self::C>;
|
||||
|
fn zero() -> Self;
|
||||
|
// note/wip/warning: dist (0,q) with f64, will output more '0=q' elements than other values
|
||||
|
fn rand(rng: impl Rng, dist: impl Distribution<f64>) -> Self;
|
||||
|
|
||||
|
fn from_vec(coeffs: Vec<Self::C>) -> Self;
|
||||
|
|
||||
|
fn decompose(&self, beta: u32, l: u32) -> Vec<Self>;
|
||||
}
|
}
|
@ -0,0 +1,434 @@ |
|||||
|
//! Polynomial ring Z[X]/(X^N+1)
|
||||
|
//!
|
||||
|
|
||||
|
use anyhow::Result;
|
||||
|
use rand::{distributions::Distribution, Rng};
|
||||
|
use std::array;
|
||||
|
use std::fmt;
|
||||
|
use std::iter::Sum;
|
||||
|
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
|
||||
|
|
||||
|
use crate::Ring;
|
||||
|
|
||||
|
// TODO rename to not have name conflicts with the Ring trait (R: Ring)
|
||||
|
// PolynomialRing element, where the PolynomialRing is R = Z[X]/(X^n +1)
|
||||
|
#[derive(Clone, Copy)]
|
||||
|
pub struct R<const N: usize>(pub [i64; N]);
|
||||
|
|
||||
|
impl<const N: usize> Ring for R<N> {
|
||||
|
type C = i64;
|
||||
|
fn coeffs(&self) -> Vec<Self::C> {
|
||||
|
self.0.to_vec()
|
||||
|
}
|
||||
|
fn zero() -> Self {
|
||||
|
let coeffs: [i64; N] = array::from_fn(|_| 0i64);
|
||||
|
Self(coeffs)
|
||||
|
}
|
||||
|
fn rand(mut rng: impl Rng, dist: impl Distribution<f64>) -> Self {
|
||||
|
// let coeffs: [i64; N] = array::from_fn(|_| Self::C::rand(&mut rng, &dist));
|
||||
|
let coeffs: [i64; N] = array::from_fn(|_| dist.sample(&mut rng).round() as i64);
|
||||
|
Self(coeffs)
|
||||
|
// let coeffs: [C; N] = array::from_fn(|_| Zq::from_u64(dist.sample(&mut rng)));
|
||||
|
// Self(coeffs)
|
||||
|
}
|
||||
|
|
||||
|
fn from_vec(coeffs: Vec<Self::C>) -> Self {
|
||||
|
let mut p = coeffs;
|
||||
|
modulus::<N>(&mut p);
|
||||
|
Self(array::from_fn(|i| p[i]))
|
||||
|
}
|
||||
|
|
||||
|
// returns the decomposition of each polynomial coefficient
|
||||
|
fn decompose(&self, beta: u32, l: u32) -> Vec<Self> {
|
||||
|
unimplemented!();
|
||||
|
// array::from_fn(|i| self.coeffs[i].decompose(beta, l))
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const Q: u64, const N: usize> From<crate::ring_nq::Rq<Q, N>> for R<N> {
|
||||
|
fn from(rq: crate::ring_nq::Rq<Q, N>) -> Self {
|
||||
|
Self::from_vec_u64(rq.coeffs().to_vec().iter().map(|e| e.0).collect())
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> R<N> {
|
||||
|
pub fn coeffs(&self) -> [i64; N] {
|
||||
|
self.0
|
||||
|
}
|
||||
|
pub fn to_rq<const Q: u64>(self) -> crate::Rq<Q, N> {
|
||||
|
crate::Rq::<Q, N>::from(self)
|
||||
|
}
|
||||
|
|
||||
|
// this method is mostly for tests
|
||||
|
pub fn from_vec_u64(coeffs: Vec<u64>) -> Self {
|
||||
|
let coeffs_i64 = coeffs.iter().map(|c| *c as i64).collect();
|
||||
|
Self::from_vec(coeffs_i64)
|
||||
|
}
|
||||
|
pub fn from_vec_f64(coeffs: Vec<f64>) -> Self {
|
||||
|
let coeffs_i64 = coeffs.iter().map(|c| c.round() as i64).collect();
|
||||
|
Self::from_vec(coeffs_i64)
|
||||
|
}
|
||||
|
pub fn new(coeffs: [i64; N]) -> Self {
|
||||
|
Self(coeffs)
|
||||
|
}
|
||||
|
pub fn mul_by_i64(&self, s: i64) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] * s))
|
||||
|
}
|
||||
|
// performs the multiplication and division over f64, and then it rounds the
|
||||
|
// result, only applying the mod Q at the end
|
||||
|
pub fn mul_div_round<const Q: u64>(&self, num: u64, den: u64) -> crate::Rq<Q, N> {
|
||||
|
let r: Vec<f64> = self
|
||||
|
.coeffs()
|
||||
|
.iter()
|
||||
|
.map(|e| ((num as f64 * *e as f64) / den as f64).round())
|
||||
|
.collect();
|
||||
|
crate::Rq::<Q, N>::from_vec_f64(r)
|
||||
|
}
|
||||
|
|
||||
|
pub fn infinity_norm(&self) -> u64 {
|
||||
|
self.coeffs()
|
||||
|
.iter()
|
||||
|
// .map(|x| if x.0 > (Q / 2) { Q - x.0 } else { x.0 })
|
||||
|
.map(|x| x.abs() as u64)
|
||||
|
.fold(0, |a, b| a.max(b))
|
||||
|
}
|
||||
|
pub fn mod_centered_q<const Q: u64>(&self) -> R<N> {
|
||||
|
let q = Q as i64;
|
||||
|
let r = self
|
||||
|
.0
|
||||
|
.iter()
|
||||
|
.map(|v| {
|
||||
|
let mut res = v % q;
|
||||
|
if res > q / 2 {
|
||||
|
res = res - q;
|
||||
|
}
|
||||
|
res
|
||||
|
})
|
||||
|
.collect::<Vec<i64>>();
|
||||
|
R::<N>::from_vec(r)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
pub fn mul_div_round<const Q: u64, const N: usize>(
|
||||
|
v: Vec<i64>,
|
||||
|
num: u64,
|
||||
|
den: u64,
|
||||
|
) -> crate::Rq<Q, N> {
|
||||
|
// dbg!(&v);
|
||||
|
let r: Vec<f64> = v
|
||||
|
.iter()
|
||||
|
.map(|e| ((num as f64 * *e as f64) / den as f64).round())
|
||||
|
.collect();
|
||||
|
// dbg!(&r);
|
||||
|
crate::Rq::<Q, N>::from_vec_f64(r)
|
||||
|
}
|
||||
|
|
||||
|
// TODO rename to make it clear that is not mod q, but mod X^N+1
|
||||
|
// apply mod (X^N+1)
|
||||
|
pub fn modulus<const N: usize>(p: &mut Vec<i64>) {
|
||||
|
if p.len() < N {
|
||||
|
return;
|
||||
|
}
|
||||
|
for i in N..p.len() {
|
||||
|
p[i - N] = p[i - N].clone() - p[i].clone();
|
||||
|
p[i] = 0;
|
||||
|
}
|
||||
|
p.truncate(N);
|
||||
|
}
|
||||
|
pub fn modulus_i128<const N: usize>(p: &mut Vec<i128>) {
|
||||
|
if p.len() < N {
|
||||
|
return;
|
||||
|
}
|
||||
|
for i in N..p.len() {
|
||||
|
p[i - N] = p[i - N].clone() - p[i].clone();
|
||||
|
p[i] = 0;
|
||||
|
}
|
||||
|
p.truncate(N);
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> PartialEq for R<N> {
|
||||
|
fn eq(&self, other: &Self) -> bool {
|
||||
|
self.0 == other.0
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Add<R<N>> for R<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn add(self, rhs: Self) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Add<&R<N>> for &R<N> {
|
||||
|
type Output = R<N>;
|
||||
|
|
||||
|
fn add(self, rhs: &R<N>) -> Self::Output {
|
||||
|
R(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> AddAssign for R<N> {
|
||||
|
fn add_assign(&mut self, rhs: Self) {
|
||||
|
for i in 0..N {
|
||||
|
self.0[i] += rhs.0[i];
|
||||
|
}
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Sum<R<N>> for R<N> {
|
||||
|
fn sum<I>(iter: I) -> Self
|
||||
|
where
|
||||
|
I: Iterator<Item = Self>,
|
||||
|
{
|
||||
|
let mut acc = R::<N>::zero();
|
||||
|
for e in iter {
|
||||
|
acc += e;
|
||||
|
}
|
||||
|
acc
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Sub<R<N>> for R<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn sub(self, rhs: Self) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Sub<&R<N>> for &R<N> {
|
||||
|
type Output = R<N>;
|
||||
|
|
||||
|
fn sub(self, rhs: &R<N>) -> Self::Output {
|
||||
|
R(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> SubAssign for R<N> {
|
||||
|
fn sub_assign(&mut self, rhs: Self) {
|
||||
|
for i in 0..N {
|
||||
|
self.0[i] -= rhs.0[i];
|
||||
|
}
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Mul<R<N>> for R<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn mul(self, rhs: Self) -> Self {
|
||||
|
naive_poly_mul(&self, &rhs)
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Mul<&R<N>> for &R<N> {
|
||||
|
type Output = R<N>;
|
||||
|
|
||||
|
fn mul(self, rhs: &R<N>) -> Self::Output {
|
||||
|
naive_poly_mul(self, rhs)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// TODO WIP
|
||||
|
pub fn naive_poly_mul<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> R<N> {
|
||||
|
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
||||
|
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
||||
|
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
||||
|
for i in 0..N {
|
||||
|
for j in 0..N {
|
||||
|
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// apply mod (X^N + 1))
|
||||
|
// R::<N>::from_vec(result.iter().map(|c| *c as i64).collect())
|
||||
|
modulus_i128::<N>(&mut result);
|
||||
|
// dbg!(&result);
|
||||
|
// dbg!(R::<N>(array::from_fn(|i| result[i] as i64)).coeffs());
|
||||
|
|
||||
|
// sanity check: check that there are no coeffs > i64_max
|
||||
|
assert_eq!(
|
||||
|
result,
|
||||
|
R::<N>(array::from_fn(|i| result[i] as i64))
|
||||
|
.coeffs()
|
||||
|
.iter()
|
||||
|
.map(|c| *c as i128)
|
||||
|
.collect::<Vec<_>>()
|
||||
|
);
|
||||
|
R(array::from_fn(|i| result[i] as i64))
|
||||
|
}
|
||||
|
pub fn naive_mul_2<const N: usize>(poly1: &Vec<i128>, poly2: &Vec<i128>) -> Vec<i128> {
|
||||
|
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
||||
|
for i in 0..N {
|
||||
|
for j in 0..N {
|
||||
|
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// apply mod (X^N + 1))
|
||||
|
// R::<N>::from_vec(result.iter().map(|c| *c as i64).collect())
|
||||
|
modulus_i128::<N>(&mut result);
|
||||
|
result
|
||||
|
}
|
||||
|
|
||||
|
pub fn naive_mul<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> Vec<i64> {
|
||||
|
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
||||
|
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
||||
|
let mut result = vec![0; (N * 2) - 1];
|
||||
|
for i in 0..N {
|
||||
|
for j in 0..N {
|
||||
|
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
||||
|
}
|
||||
|
}
|
||||
|
result.iter().map(|c| *c as i64).collect()
|
||||
|
}
|
||||
|
pub fn naive_mul_TMP<const N: usize>(poly1: &R<N>, poly2: &R<N>) -> Vec<i64> {
|
||||
|
let poly1: Vec<i128> = poly1.0.iter().map(|c| *c as i128).collect();
|
||||
|
let poly2: Vec<i128> = poly2.0.iter().map(|c| *c as i128).collect();
|
||||
|
let mut result: Vec<i128> = vec![0; (N * 2) - 1];
|
||||
|
for i in 0..N {
|
||||
|
for j in 0..N {
|
||||
|
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// dbg!(&result);
|
||||
|
modulus_i128::<N>(&mut result);
|
||||
|
// for c_i in result.iter() {
|
||||
|
// println!("---");
|
||||
|
// println!("{:?}", &c_i);
|
||||
|
// println!("{:?}", *c_i as i64);
|
||||
|
// println!("{:?}", (*c_i as i64) as i128);
|
||||
|
// assert_eq!(*c_i, (*c_i as i64) as i128, "{:?}", c_i);
|
||||
|
// }
|
||||
|
result.iter().map(|c| *c as i64).collect()
|
||||
|
}
|
||||
|
|
||||
|
// wip
|
||||
|
pub fn mod_centered_q<const Q: u64, const N: usize>(p: Vec<i128>) -> R<N> {
|
||||
|
let q: i128 = Q as i128;
|
||||
|
let r = p
|
||||
|
.iter()
|
||||
|
.map(|v| {
|
||||
|
let mut res = v % q;
|
||||
|
if res > q / 2 {
|
||||
|
res = res - q;
|
||||
|
}
|
||||
|
res
|
||||
|
})
|
||||
|
.collect::<Vec<i128>>();
|
||||
|
R::<N>::from_vec(r.iter().map(|v| *v as i64).collect::<Vec<i64>>())
|
||||
|
}
|
||||
|
|
||||
|
// mul by u64
|
||||
|
impl<const N: usize> Mul<u64> for R<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn mul(self, s: u64) -> Self {
|
||||
|
self.mul_by_i64(s as i64)
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Mul<&u64> for &R<N> {
|
||||
|
type Output = R<N>;
|
||||
|
|
||||
|
fn mul(self, s: &u64) -> Self::Output {
|
||||
|
self.mul_by_i64(*s as i64)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Neg for R<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn neg(self) -> Self::Output {
|
||||
|
Self(array::from_fn(|i| -self.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> R<N> {
|
||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
|
let mut str = "";
|
||||
|
let mut zero = true;
|
||||
|
for (i, coeff) in self.0.iter().enumerate().rev() {
|
||||
|
if *coeff == 0 {
|
||||
|
continue;
|
||||
|
}
|
||||
|
zero = false;
|
||||
|
f.write_str(str)?;
|
||||
|
if *coeff != 1 {
|
||||
|
f.write_str(coeff.to_string().as_str())?;
|
||||
|
if i > 0 {
|
||||
|
f.write_str("*")?;
|
||||
|
}
|
||||
|
}
|
||||
|
if *coeff == 1 && i == 0 {
|
||||
|
f.write_str(coeff.to_string().as_str())?;
|
||||
|
}
|
||||
|
if i == 1 {
|
||||
|
f.write_str("x")?;
|
||||
|
} else if i > 1 {
|
||||
|
f.write_str("x^")?;
|
||||
|
f.write_str(i.to_string().as_str())?;
|
||||
|
}
|
||||
|
str = " + ";
|
||||
|
}
|
||||
|
if zero {
|
||||
|
f.write_str("0")?;
|
||||
|
}
|
||||
|
|
||||
|
f.write_str(" mod Z")?;
|
||||
|
f.write_str("/(X^")?;
|
||||
|
f.write_str(N.to_string().as_str())?;
|
||||
|
f.write_str("+1)")?;
|
||||
|
Ok(())
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> fmt::Display for R<N> {
|
||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
|
self.fmt(f)?;
|
||||
|
Ok(())
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> fmt::Debug for R<N> {
|
||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
|
self.fmt(f)?;
|
||||
|
Ok(())
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
#[cfg(test)]
|
||||
|
mod tests {
|
||||
|
use super::*;
|
||||
|
use anyhow::Result;
|
||||
|
|
||||
|
#[test]
|
||||
|
fn test_mul() -> Result<()> {
|
||||
|
const Q: u64 = 2u64.pow(16) + 1;
|
||||
|
const N: usize = 2;
|
||||
|
let q: i64 = Q as i64;
|
||||
|
|
||||
|
// test vectors generated with SageMath
|
||||
|
let a: [i64; N] = [q - 1, q - 1];
|
||||
|
let b: [i64; N] = [q - 1, q - 1];
|
||||
|
let c: [i64; N] = [0, 8589934592];
|
||||
|
test_mul_opt::<Q, N>(a, b, c)?;
|
||||
|
|
||||
|
let a: [i64; N] = [1, q - 1];
|
||||
|
let b: [i64; N] = [1, q - 1];
|
||||
|
let c: [i64; N] = [-4294967295, 131072];
|
||||
|
test_mul_opt::<Q, N>(a, b, c)?;
|
||||
|
|
||||
|
Ok(())
|
||||
|
}
|
||||
|
fn test_mul_opt<const Q: u64, const N: usize>(
|
||||
|
a: [i64; N],
|
||||
|
b: [i64; N],
|
||||
|
expected_c: [i64; N],
|
||||
|
) -> Result<()> {
|
||||
|
let mut a = R::new(a);
|
||||
|
let mut b = R::new(b);
|
||||
|
dbg!(&a);
|
||||
|
dbg!(&b);
|
||||
|
let expected_c = R::new(expected_c);
|
||||
|
|
||||
|
let mut c = naive_mul(&mut a, &mut b);
|
||||
|
modulus::<N>(&mut c);
|
||||
|
dbg!(R::<N>::from_vec(c.clone()));
|
||||
|
assert_eq!(c, expected_c.0.to_vec());
|
||||
|
Ok(())
|
||||
|
}
|
||||
|
}
|
@ -0,0 +1,192 @@ |
|||||
|
//! 𝕋_<N,q>[X] = ℝ_<N,q>[X] / ℤ_<N,q>[X], polynomials modulo X^N+1 with
|
||||
|
//! coefficients in 𝕋_Q.
|
||||
|
//!
|
||||
|
//! Note: this is not an algebraic ring, since internal-product is not well
|
||||
|
//! defined. But since we work over the discrete torus 𝕋_q, which we identify as
|
||||
|
//! 𝕋q = ℤ/qℤ ≈ ℤq, whith q=64. Since we allow product between 𝕋q elements and
|
||||
|
//! u64, we fit it into the `Ring` trait (from ring.rs) so that we can compose
|
||||
|
//! the 𝕋_<N,q> implementation with the other objects from the code.
|
||||
|
|
||||
|
use rand::{distributions::Distribution, Rng};
|
||||
|
use std::array;
|
||||
|
use std::iter::Sum;
|
||||
|
use std::ops::{Add, AddAssign, Mul, Sub, SubAssign};
|
||||
|
|
||||
|
use crate::{ring::Ring, torus::T64};
|
||||
|
|
||||
|
/// 𝕋_<N,Q>[X] = 𝕋<Q>[X]/(X^N +1), polynomials modulo X^N+1 with coefficients in
|
||||
|
/// 𝕋, where Q=2^64.
|
||||
|
#[derive(Clone, Copy, Debug)]
|
||||
|
pub struct Tn<const N: usize>(pub [T64; N]);
|
||||
|
|
||||
|
impl<const N: usize> Ring for Tn<N> {
|
||||
|
type C = T64;
|
||||
|
|
||||
|
fn coeffs(&self) -> Vec<T64> {
|
||||
|
self.0.to_vec()
|
||||
|
}
|
||||
|
|
||||
|
fn zero() -> Self {
|
||||
|
Self(array::from_fn(|_| T64::zero()))
|
||||
|
}
|
||||
|
|
||||
|
fn rand(mut rng: impl Rng, dist: impl Distribution<f64>) -> Self {
|
||||
|
Self(array::from_fn(|_| T64::rand_f64(&mut rng, &dist)))
|
||||
|
}
|
||||
|
|
||||
|
fn from_vec(coeffs: Vec<Self::C>) -> Self {
|
||||
|
let mut p = coeffs;
|
||||
|
modulus::<N>(&mut p);
|
||||
|
Self(array::from_fn(|i| p[i]))
|
||||
|
}
|
||||
|
|
||||
|
fn decompose(&self, beta: u32, l: u32) -> Vec<Self> {
|
||||
|
let elems: Vec<Vec<T64>> = self.0.iter().map(|r| r.decompose(beta, l)).collect();
|
||||
|
// transpose it
|
||||
|
let r: Vec<Vec<T64>> = (0..elems[0].len())
|
||||
|
.map(|i| (0..elems.len()).map(|j| elems[j][i]).collect())
|
||||
|
.collect();
|
||||
|
// convert it to Tn<N>
|
||||
|
r.iter().map(|a_i| Self::from_vec(a_i.clone())).collect()
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// apply mod (X^N+1)
|
||||
|
pub fn modulus<const N: usize>(p: &mut Vec<T64>) {
|
||||
|
if p.len() < N {
|
||||
|
return;
|
||||
|
}
|
||||
|
for i in N..p.len() {
|
||||
|
p[i - N] = p[i - N].clone() - p[i].clone();
|
||||
|
p[i] = T64::zero();
|
||||
|
}
|
||||
|
p.truncate(N);
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Add<Tn<N>> for Tn<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn add(self, rhs: Self) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Add<&Tn<N>> for &Tn<N> {
|
||||
|
type Output = Tn<N>;
|
||||
|
|
||||
|
fn add(self, rhs: &Tn<N>) -> Self::Output {
|
||||
|
Tn(array::from_fn(|i| self.0[i] + rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> AddAssign for Tn<N> {
|
||||
|
fn add_assign(&mut self, rhs: Self) {
|
||||
|
for i in 0..N {
|
||||
|
self.0[i] += rhs.0[i];
|
||||
|
}
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Sum<Tn<N>> for Tn<N> {
|
||||
|
fn sum<I>(iter: I) -> Self
|
||||
|
where
|
||||
|
I: Iterator<Item = Self>,
|
||||
|
{
|
||||
|
let mut acc = Tn::<N>::zero();
|
||||
|
for e in iter {
|
||||
|
acc += e;
|
||||
|
}
|
||||
|
acc
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Sub<Tn<N>> for Tn<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn sub(self, rhs: Self) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Sub<&Tn<N>> for &Tn<N> {
|
||||
|
type Output = Tn<N>;
|
||||
|
|
||||
|
fn sub(self, rhs: &Tn<N>) -> Self::Output {
|
||||
|
Tn(array::from_fn(|i| self.0[i] - rhs.0[i]))
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> SubAssign for Tn<N> {
|
||||
|
fn sub_assign(&mut self, rhs: Self) {
|
||||
|
for i in 0..N {
|
||||
|
self.0[i] -= rhs.0[i];
|
||||
|
}
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> PartialEq for Tn<N> {
|
||||
|
fn eq(&self, other: &Self) -> bool {
|
||||
|
self.0 == other.0
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl<const N: usize> Mul<Tn<N>> for Tn<N> {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn mul(self, rhs: Self) -> Self {
|
||||
|
naive_poly_mul(&self, &rhs)
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Mul<&Tn<N>> for &Tn<N> {
|
||||
|
type Output = Tn<N>;
|
||||
|
|
||||
|
fn mul(self, rhs: &Tn<N>) -> Self::Output {
|
||||
|
naive_poly_mul(self, rhs)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
fn naive_poly_mul<const N: usize>(poly1: &Tn<N>, poly2: &Tn<N>) -> Tn<N> {
|
||||
|
let poly1: Vec<u128> = poly1.0.iter().map(|c| c.0 as u128).collect();
|
||||
|
let poly2: Vec<u128> = poly2.0.iter().map(|c| c.0 as u128).collect();
|
||||
|
let mut result: Vec<u128> = vec![0; (N * 2) - 1];
|
||||
|
for i in 0..N {
|
||||
|
for j in 0..N {
|
||||
|
result[i + j] = result[i + j] + poly1[i] * poly2[j];
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// apply mod (X^N + 1))
|
||||
|
modulus_u128::<N>(&mut result);
|
||||
|
|
||||
|
// sanity check: check that there are no coeffs > i64_max
|
||||
|
assert_eq!(
|
||||
|
result,
|
||||
|
Tn::<N>(array::from_fn(|i| T64(result[i] as u64)))
|
||||
|
.coeffs()
|
||||
|
.iter()
|
||||
|
.map(|c| c.0 as u128)
|
||||
|
.collect::<Vec<_>>()
|
||||
|
);
|
||||
|
Tn(array::from_fn(|i| T64(result[i] as u64)))
|
||||
|
}
|
||||
|
fn modulus_u128<const N: usize>(p: &mut Vec<u128>) {
|
||||
|
if p.len() < N {
|
||||
|
return;
|
||||
|
}
|
||||
|
for i in N..p.len() {
|
||||
|
p[i - N] = p[i - N].clone() - p[i].clone();
|
||||
|
p[i] = 0;
|
||||
|
}
|
||||
|
p.truncate(N);
|
||||
|
}
|
||||
|
|
||||
|
// mul by u64
|
||||
|
impl<const N: usize> Mul<u64> for Tn<N> {
|
||||
|
type Output = Self;
|
||||
|
fn mul(self, s: u64) -> Self {
|
||||
|
Self(array::from_fn(|i| self.0[i] * s))
|
||||
|
}
|
||||
|
}
|
||||
|
impl<const N: usize> Mul<&u64> for &Tn<N> {
|
||||
|
type Output = Tn<N>;
|
||||
|
fn mul(self, s: &u64) -> Self::Output {
|
||||
|
Tn::<N>(array::from_fn(|i| self.0[i] * *s))
|
||||
|
}
|
||||
|
}
|
@ -0,0 +1,142 @@ |
|||||
|
use rand::{distributions::Distribution, Rng};
|
||||
|
use std::{
|
||||
|
iter::Sum,
|
||||
|
ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
|
||||
|
};
|
||||
|
|
||||
|
/// Let 𝕋 = ℝ/ℤ, where 𝕋 is a ℤ-module, with homogeneous external product.
|
||||
|
/// Let 𝕋q
|
||||
|
/// T64 is 𝕋q with q=2^Ω, with Ω=64. We identify 𝕋q=(1/q)ℤ/ℤ ≈ ℤq.
|
||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
|
pub struct T64(pub u64);
|
||||
|
|
||||
|
impl T64 {
|
||||
|
pub fn zero() -> Self {
|
||||
|
Self(0u64)
|
||||
|
}
|
||||
|
pub fn rand(mut rng: impl Rng, dist: impl Distribution<u64>) -> Self {
|
||||
|
let r: u64 = dist.sample(&mut rng);
|
||||
|
Self(r)
|
||||
|
}
|
||||
|
pub fn rand_f64(mut rng: impl Rng, dist: impl Distribution<f64>) -> Self {
|
||||
|
let r: f64 = dist.sample(&mut rng);
|
||||
|
Self(r.round() as u64)
|
||||
|
}
|
||||
|
|
||||
|
/// Note: only beta=2 and l=64 is supported.
|
||||
|
pub fn decompose(&self, beta: u32, l: u32) -> Vec<Self> {
|
||||
|
assert_eq!(beta, 2u32); // only beta=2 supported
|
||||
|
assert_eq!(l, 64u32); // only l=64 supported
|
||||
|
|
||||
|
(0..64)
|
||||
|
.rev()
|
||||
|
.map(|i| T64(((self.0 >> i) & 1) as u64))
|
||||
|
.collect()
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl Add<T64> for T64 {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn add(self, rhs: Self) -> Self::Output {
|
||||
|
Self(self.0.wrapping_add(rhs.0))
|
||||
|
}
|
||||
|
}
|
||||
|
impl AddAssign for T64 {
|
||||
|
fn add_assign(&mut self, rhs: Self) {
|
||||
|
self.0 += rhs.0;
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl Sub<T64> for T64 {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn sub(self, rhs: Self) -> Self::Output {
|
||||
|
Self(self.0.wrapping_sub(rhs.0))
|
||||
|
}
|
||||
|
}
|
||||
|
impl SubAssign for T64 {
|
||||
|
fn sub_assign(&mut self, rhs: Self) {
|
||||
|
self.0 -= rhs.0;
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl Neg for T64 {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn neg(self) -> Self::Output {
|
||||
|
Self(self.0.wrapping_neg())
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl Sum for T64 {
|
||||
|
fn sum<I>(iter: I) -> Self
|
||||
|
where
|
||||
|
I: Iterator<Item = Self>,
|
||||
|
{
|
||||
|
iter.fold(Self(0), |acc, x| acc + x)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
impl Mul<T64> for T64 {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn mul(self, rhs: Self) -> Self::Output {
|
||||
|
Self(self.0.wrapping_mul(rhs.0))
|
||||
|
}
|
||||
|
}
|
||||
|
impl MulAssign for T64 {
|
||||
|
fn mul_assign(&mut self, rhs: Self) {
|
||||
|
self.0 *= rhs.0;
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
// mul by u64
|
||||
|
impl Mul<u64> for T64 {
|
||||
|
type Output = Self;
|
||||
|
|
||||
|
fn mul(self, s: u64) -> Self {
|
||||
|
Self(self.0 * s)
|
||||
|
}
|
||||
|
}
|
||||
|
impl Mul<&u64> for &T64 {
|
||||
|
type Output = T64;
|
||||
|
|
||||
|
fn mul(self, s: &u64) -> Self::Output {
|
||||
|
T64(self.0 * s)
|
||||
|
}
|
||||
|
}
|
||||
|
|
||||
|
#[cfg(test)]
|
||||
|
mod tests {
|
||||
|
use super::*;
|
||||
|
use rand::distributions::Standard;
|
||||
|
|
||||
|
fn recompose(d: Vec<T64>) -> T64 {
|
||||
|
T64(d.iter().fold(0u64, |acc, &b| (acc << 1) | b.0))
|
||||
|
}
|
||||
|
#[test]
|
||||
|
fn test_decompose() {
|
||||
|
let beta: u32 = 2;
|
||||
|
let l: u32 = 64;
|
||||
|
|
||||
|
let x = T64(12345);
|
||||
|
let d = x.decompose(beta, l);
|
||||
|
assert_eq!(recompose(d), T64(12345));
|
||||
|
|
||||
|
let x = T64(0);
|
||||
|
let d = x.decompose(beta, l);
|
||||
|
assert_eq!(recompose(d), T64(0));
|
||||
|
|
||||
|
let x = T64(u64::MAX - 1);
|
||||
|
let d = x.decompose(beta, l);
|
||||
|
assert_eq!(recompose(d), T64(u64::MAX - 1));
|
||||
|
|
||||
|
let mut rng = rand::thread_rng();
|
||||
|
for _ in 0..1000 {
|
||||
|
let x = T64::rand(&mut rng, Standard);
|
||||
|
let d = x.decompose(beta, l);
|
||||
|
assert_eq!(recompose(d), x);
|
||||
|
}
|
||||
|
}
|
||||
|
}
|
@ -1,32 +0,0 @@ |
|||||
use anyhow::Result;
|
|
||||
use rand::{distributions::Distribution, Rng};
|
|
||||
use std::fmt::Debug;
|
|
||||
use std::iter::Sum;
|
|
||||
use std::ops::{Add, AddAssign, Mul, Sub, SubAssign};
|
|
||||
|
|
||||
/// Represents a ring element. Currently implemented by ring.rs#R and ringq.rs#Rq.
|
|
||||
pub trait Ring: |
|
||||
Sized
|
|
||||
+ Add<Output = Self>
|
|
||||
+ AddAssign
|
|
||||
+ Sum
|
|
||||
+ Sub<Output = Self>
|
|
||||
+ SubAssign
|
|
||||
+ Mul<Output = Self>
|
|
||||
+ Mul<u64, Output = Self> // scalar mul
|
|
||||
+ PartialEq
|
|
||||
+ Debug
|
|
||||
+ Clone
|
|
||||
+ Sum<<Self as Add>::Output>
|
|
||||
+ Sum<<Self as Mul>::Output>
|
|
||||
{
|
|
||||
/// C defines the coefficient type
|
|
||||
type C: Debug + Clone;
|
|
||||
|
|
||||
fn coeffs(&self) -> Vec<Self::C>;
|
|
||||
fn zero() -> Self;
|
|
||||
// note/wip/warning: dist (0,q) with f64, will output more '0=q' elements than other values
|
|
||||
fn rand(rng: impl Rng, dist: impl Distribution<f64>) -> Self;
|
|
||||
|
|
||||
fn decompose(&self, beta: u32, l: u32) -> Vec<Self>;
|
|
||||
}
|
|