poulpy-core 0.5.0

A backend agnostic crate implementing RLWE-based encryption & arithmetic.
Documentation
use poulpy_hal::{
    layouts::{
        Backend, Data, DataMut, DataRef, FillUniform, MatZnx, MatZnxToMut, MatZnxToRef, Module, ReaderFrom, WriterTo, ZnxInfos,
    },
    source::Source,
};

use crate::layouts::{
    Base2K, Degree, Dnum, Dsize, GGSW, GGSWInfos, GGSWToMut, GLWEInfos, LWEInfos, Rank, TorusPrecision,
    compressed::{GLWECompressed, GLWEDecompress},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;

/// Seed-compressed GGSW (gadget GSW) ciphertext layout.
///
/// Stores only the body components of a [`GGSW`] ciphertext; the mask
/// polynomials are regenerated deterministically from 32-byte PRNG
/// seeds during decompression.
#[derive(PartialEq, Eq, Clone)]
pub struct GGSWCompressed<D: Data> {
    pub(crate) data: MatZnx<D>,
    pub(crate) k: TorusPrecision,
    pub(crate) base2k: Base2K,
    pub(crate) dsize: Dsize,
    pub(crate) rank: Rank,
    pub(crate) seed: Vec<[u8; 32]>,
}

/// Provides mutable access to the PRNG seeds of a compressed GGSW.
pub trait GGSWCompressedSeedMut {
    /// Returns a mutable reference to the vector of 32-byte PRNG seeds.
    fn seed_mut(&mut self) -> &mut Vec<[u8; 32]>;
}

impl<D: DataMut> GGSWCompressedSeedMut for GGSWCompressed<D> {
    fn seed_mut(&mut self) -> &mut Vec<[u8; 32]> {
        &mut self.seed
    }
}

/// Provides read access to the PRNG seeds of a compressed GGSW.
pub trait GGSWCompressedSeed {
    /// Returns a reference to the vector of 32-byte PRNG seeds.
    fn seed(&self) -> &Vec<[u8; 32]>;
}

impl<D: DataRef> GGSWCompressedSeed for GGSWCompressed<D> {
    fn seed(&self) -> &Vec<[u8; 32]> {
        &self.seed
    }
}

impl<D: Data> LWEInfos for GGSWCompressed<D> {
    fn n(&self) -> Degree {
        Degree(self.data.n() as u32)
    }

    fn base2k(&self) -> Base2K {
        self.base2k
    }

    fn k(&self) -> TorusPrecision {
        self.k
    }
    fn size(&self) -> usize {
        self.data.size()
    }
}
impl<D: Data> GLWEInfos for GGSWCompressed<D> {
    fn rank(&self) -> Rank {
        self.rank
    }
}

impl<D: Data> GGSWInfos for GGSWCompressed<D> {
    fn dsize(&self) -> Dsize {
        self.dsize
    }

    fn dnum(&self) -> Dnum {
        Dnum(self.data.rows() as u32)
    }
}

impl<D: DataRef> fmt::Debug for GGSWCompressed<D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

impl<D: DataRef> fmt::Display for GGSWCompressed<D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "(GGSWCompressed: base2k={} k={} dsize={}) {}",
            self.base2k, self.k, self.dsize, self.data
        )
    }
}

impl<D: DataMut> FillUniform for GGSWCompressed<D> {
    fn fill_uniform(&mut self, log_bound: usize, source: &mut Source) {
        self.data.fill_uniform(log_bound, source);
    }
}

impl GGSWCompressed<Vec<u8>> {
    /// Allocates a new compressed GGSW by copying parameters from an existing info provider.
    pub fn alloc_from_infos<A>(infos: &A) -> Self
    where
        A: GGSWInfos,
    {
        Self::alloc(
            infos.n(),
            infos.base2k(),
            infos.k(),
            infos.rank(),
            infos.dnum(),
            infos.dsize(),
        )
    }

    /// Allocates a new compressed GGSW with the given parameters.
    pub fn alloc(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> Self {
        let size: usize = k.0.div_ceil(base2k.0) as usize;
        assert!(
            size as u32 > dsize.0,
            "invalid ggsw: ceil(k/base2k): {size} <= dsize: {}",
            dsize.0
        );

        assert!(
            dnum.0 * dsize.0 <= size as u32,
            "invalid ggsw: dnum: {} * dsize:{} > ceil(k/base2k): {size}",
            dnum.0,
            dsize.0,
        );

        GGSWCompressed {
            data: MatZnx::alloc(n.into(), dnum.into(), (rank + 1).into(), 1, k.0.div_ceil(base2k.0) as usize),
            k,
            base2k,
            dsize,
            rank,
            seed: vec![[0u8; 32]; dnum.as_usize() * (rank.as_usize() + 1)],
        }
    }

    /// Returns the serialized byte size by copying parameters from an existing info provider.
    pub fn bytes_of_from_infos<A>(infos: &A) -> usize
    where
        A: GGSWInfos,
    {
        Self::bytes_of(
            infos.n(),
            infos.base2k(),
            infos.k(),
            infos.rank(),
            infos.dnum(),
            infos.dsize(),
        )
    }

    /// Returns the serialized byte size for a compressed GGSW with the given parameters.
    pub fn bytes_of(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> usize {
        let size: usize = k.0.div_ceil(base2k.0) as usize;
        assert!(
            size as u32 > dsize.0,
            "invalid ggsw: ceil(k/base2k): {size} <= dsize: {}",
            dsize.0
        );

        assert!(
            dnum.0 * dsize.0 <= size as u32,
            "invalid ggsw: dnum: {} * dsize:{} > ceil(k/base2k): {size}",
            dnum.0,
            dsize.0,
        );

        MatZnx::bytes_of(n.into(), dnum.into(), (rank + 1).into(), 1, k.0.div_ceil(base2k.0) as usize)
    }
}

impl<D: DataRef> GGSWCompressed<D> {
    /// Returns an immutably-borrowed compressed GLWE at the given row and column.
    pub fn at(&self, row: usize, col: usize) -> GLWECompressed<&[u8]> {
        let rank: usize = self.rank().into();
        GLWECompressed {
            data: self.data.at(row, col),
            k: self.k,
            base2k: self.base2k,
            rank: self.rank,
            seed: self.seed[row * (rank + 1) + col],
        }
    }
}

impl<D: DataMut> GGSWCompressed<D> {
    /// Returns a mutably-borrowed compressed GLWE at the given row and column.
    pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECompressed<&mut [u8]> {
        let rank: usize = self.rank().into();
        GLWECompressed {
            data: self.data.at_mut(row, col),
            k: self.k,
            base2k: self.base2k,
            rank: self.rank,
            seed: self.seed[row * (rank + 1) + col],
        }
    }
}

impl<D: DataMut> ReaderFrom for GGSWCompressed<D> {
    fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
        self.k = TorusPrecision(reader.read_u32::<LittleEndian>()?);
        self.base2k = Base2K(reader.read_u32::<LittleEndian>()?);
        self.dsize = Dsize(reader.read_u32::<LittleEndian>()?);
        self.rank = Rank(reader.read_u32::<LittleEndian>()?);
        let seed_len: usize = reader.read_u32::<LittleEndian>()? as usize;
        self.seed = vec![[0u8; 32]; seed_len];
        for s in &mut self.seed {
            reader.read_exact(s)?;
        }
        self.data.read_from(reader)
    }
}

impl<D: DataRef> WriterTo for GGSWCompressed<D> {
    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        writer.write_u32::<LittleEndian>(self.k.into())?;
        writer.write_u32::<LittleEndian>(self.base2k.into())?;
        writer.write_u32::<LittleEndian>(self.dsize.into())?;
        writer.write_u32::<LittleEndian>(self.rank.into())?;
        writer.write_u32::<LittleEndian>(self.seed.len() as u32)?;
        for s in &self.seed {
            writer.write_all(s)?;
        }
        self.data.write_to(writer)
    }
}

/// Trait for decompressing a [`GGSWCompressed`] into a standard [`GGSW`].
///
/// Iterates over every (row, column) entry, decompressing each
/// compressed GLWE individually via [`GLWEDecompress`].
pub trait GGSWDecompress
where
    Self: GLWEDecompress,
{
    /// Decompresses `other` into `res`.
    fn decompress_ggsw<R, O>(&self, res: &mut R, other: &O)
    where
        R: GGSWToMut,
        O: GGSWCompressedToRef,
    {
        let res: &mut GGSW<&mut [u8]> = &mut res.to_mut();
        let other: &GGSWCompressed<&[u8]> = &other.to_ref();

        assert_eq!(res.rank(), other.rank());
        let dnum: usize = res.dnum().into();
        let rank: usize = res.rank().into();

        for row_i in 0..dnum {
            for col_j in 0..rank + 1 {
                self.decompress_glwe(&mut res.at_mut(row_i, col_j), &other.at(row_i, col_j));
            }
        }
    }
}

impl<B: Backend> GGSWDecompress for Module<B> where Self: GLWEDecompress {}

impl<D: DataMut> GGSW<D> {
    /// Decompresses a [`GGSWCompressed`] into this standard GGSW.
    pub fn decompress<O, M>(&mut self, module: &M, other: &O)
    where
        O: GGSWCompressedToRef,
        M: GGSWDecompress,
    {
        module.decompress_ggsw(self, other);
    }
}

/// Converts a compressed GGSW to a mutably-borrowed variant.
pub trait GGSWCompressedToMut {
    /// Returns a mutably-borrowed view of this compressed GGSW.
    fn to_mut(&mut self) -> GGSWCompressed<&mut [u8]>;
}

impl<D: DataMut> GGSWCompressedToMut for GGSWCompressed<D> {
    fn to_mut(&mut self) -> GGSWCompressed<&mut [u8]> {
        GGSWCompressed {
            k: self.k(),
            base2k: self.base2k(),
            dsize: self.dsize(),
            rank: self.rank(),
            seed: self.seed.clone(),
            data: self.data.to_mut(),
        }
    }
}

/// Converts a compressed GGSW to an immutably-borrowed variant.
pub trait GGSWCompressedToRef {
    /// Returns an immutably-borrowed view of this compressed GGSW.
    fn to_ref(&self) -> GGSWCompressed<&[u8]>;
}

impl<D: DataRef> GGSWCompressedToRef for GGSWCompressed<D> {
    fn to_ref(&self) -> GGSWCompressed<&[u8]> {
        GGSWCompressed {
            k: self.k(),
            base2k: self.base2k(),
            dsize: self.dsize(),
            rank: self.rank(),
            seed: self.seed.clone(),
            data: self.data.to_ref(),
        }
    }
}