arnaucube
arnaucube/phantom-zonePublic Self-hosted repository
phantom-zone/src/decomposer.rs
src/decomposer.rsRaw
  1use itertools::Itertools;
  2use num_traits::{AsPrimitive, One, PrimInt, ToPrimitive, WrappingSub, Zero};
  3use std::{fmt::Debug, marker::PhantomData, ops::Rem};
  4
  5use crate::backend::{ArithmeticOps, ModularOpsU64};
  6
  7pub fn gadget_vector<T: PrimInt>(logq: usize, logb: usize, d: usize) -> Vec<T> {
  8    let d_ideal = (logq as f64 / logb as f64).ceil().to_usize().unwrap();
  9    let ignored_limbs = d_ideal - d;
 10    (ignored_limbs..ignored_limbs + d)
 11        .into_iter()
 12        .map(|i| T::one() << (logb * i))
 13        .collect_vec()
 14}
 15
 16pub trait Decomposer {
 17    type Element;
 18    //FIXME(Jay): there's no reason why it returns a vec instead of an iterator
 19    fn decompose(&self, v: &Self::Element) -> Vec<Self::Element>;
 20    fn d(&self) -> usize;
 21}
 22
 23pub struct DefaultDecomposer<T> {
 24    q: T,
 25    logq: usize,
 26    logb: usize,
 27    d: usize,
 28    ignore_bits: usize,
 29    ignore_limbs: usize,
 30}
 31
 32pub trait NumInfo {
 33    const BITS: u32;
 34}
 35
 36impl NumInfo for u64 {
 37    const BITS: u32 = u64::BITS;
 38}
 39impl NumInfo for u32 {
 40    const BITS: u32 = u32::BITS;
 41}
 42impl NumInfo for u128 {
 43    const BITS: u32 = u128::BITS;
 44}
 45
 46impl<T: PrimInt + NumInfo + Debug> DefaultDecomposer<T> {
 47    pub fn new(q: T, logb: usize, d: usize) -> DefaultDecomposer<T> {
 48        // if q is power of 2, then BITS - leading zeros outputs logq + 1.
 49        let logq = if q & (q - T::one()) == T::zero() {
 50            (T::BITS - q.leading_zeros() - 1) as usize
 51        } else {
 52            (T::BITS - q.leading_zeros()) as usize
 53        };
 54
 55        let d_ideal = (logq as f64 / logb as f64).ceil().to_usize().unwrap();
 56        let ignore_limbs = (d_ideal - d);
 57        let ignore_bits = (d_ideal - d) * logb;
 58
 59        DefaultDecomposer {
 60            q,
 61            logq,
 62            logb,
 63            d,
 64            ignore_bits,
 65            ignore_limbs,
 66        }
 67    }
 68
 69    fn recompose<Op>(&self, limbs: &[T], modq_op: &Op) -> T
 70    where
 71        Op: ArithmeticOps<Element = T>,
 72    {
 73        let mut value = T::zero();
 74        dbg!(self.ignore_limbs);
 75        for i in 0..self.d {
 76            value = modq_op.add(
 77                &value,
 78                &(modq_op.mul(
 79                    &limbs[i],
 80                    &(T::one() << (self.logb * (i + self.ignore_limbs))),
 81                )),
 82            )
 83        }
 84        value
 85    }
 86}
 87
 88impl<T: PrimInt + WrappingSub + Debug> Decomposer for DefaultDecomposer<T> {
 89    type Element = T;
 90    fn decompose(&self, value: &T) -> Vec<T> {
 91        let value = round_value(*value, self.ignore_bits);
 92        let q = self.q;
 93        let logb = self.logb;
 94        // let b = T::one() << logb; // base
 95        let b_by2 = T::one() << (logb - 1);
 96        // let neg_b_by2_modq = q - b_by2;
 97        let full_mask = (T::one() << logb) - T::one();
 98        // let half_mask = b_by2 - T::one();
 99        let mut carry = T::zero();
100        let mut out = Vec::<T>::with_capacity(self.d);
101        for i in 0..self.d {
102            let mut limb = ((value >> (logb * i)) & full_mask) + carry;
103
104            carry = limb & b_by2;
105            limb = (q + limb) - (carry << 1);
106            if limb > q {
107                limb = limb - q;
108            }
109            out.push(limb);
110
111            carry = carry >> (logb - 1);
112        }
113
114        return out;
115    }
116
117    fn d(&self) -> usize {
118        self.d
119    }
120}
121
122fn round_value<T: PrimInt>(value: T, ignore_bits: usize) -> T {
123    if ignore_bits == 0 {
124        return value;
125    }
126
127    let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
128    (value >> ignore_bits) + ignored_msb
129}
130
131#[cfg(test)]
132mod tests {
133    use rand::{thread_rng, Rng};
134
135    use crate::{backend::ModularOpsU64, decomposer::round_value, utils::generate_prime};
136
137    use super::{Decomposer, DefaultDecomposer};
138
139    #[test]
140    fn decomposition_works() {
141        let logq = 15;
142        let logb = 3;
143        let d = 5;
144
145        let mut rng = thread_rng();
146
147        // q is prime of bits logq and i is true, other q = 1<<logq
148        // FIXME: Test fails when q is prime, albeit the difference is minute
149        for i in [true] {
150            let q = if i {
151                generate_prime(logq, 1 << 4, 1u64 << logq).unwrap()
152            } else {
153                1u64 << logq
154            };
155            let decomposer = DefaultDecomposer::new(q, logb, d);
156            let modq_op = ModularOpsU64::new(q);
157            for _ in 0..1 {
158                let value = rng.gen_range(0..q);
159                let limbs = decomposer.decompose(&value);
160                let value_back = decomposer.recompose(&limbs, &modq_op);
161                let rounded_value =
162                    round_value(value, decomposer.ignore_bits) << decomposer.ignore_bits;
163                dbg!(value, rounded_value, value_back, &limbs);
164                assert_eq!(
165                    rounded_value, value_back,
166                    "Expected {rounded_value} got {value_back} for q={q}"
167                );
168            }
169        }
170    }
171}