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        for i in 0..self.d {
 75            value = modq_op.add(
 76                &value,
 77                &(modq_op.mul(
 78                    &limbs[i],
 79                    &(T::one() << (self.logb * (i + self.ignore_limbs))),
 80                )),
 81            )
 82        }
 83        value
 84    }
 85}
 86
 87impl<T: PrimInt + WrappingSub + Debug> Decomposer for DefaultDecomposer<T> {
 88    type Element = T;
 89    fn decompose(&self, value: &T) -> Vec<T> {
 90        let mut value = round_value(*value, self.ignore_bits);
 91
 92        let q = self.q;
 93        // if value >= (q >> 1) {
 94        //     value = value.wrapping_sub(&q);
 95        // }
 96
 97        let logb = self.logb;
 98        let b = T::one() << logb; // base
 99        let b_by2 = T::one() << (logb - 1);
100        // let neg_b_by2_modq = q - b_by2;
101        let full_mask = (T::one() << logb) - T::one();
102        // let half_mask = b_by2 - T::one();
103        let mut carry = T::zero();
104        let mut out = Vec::<T>::with_capacity(self.d);
105        for i in 0..self.d {
106            let mut limb = ((value >> (logb * i)) & full_mask) + carry;
107            carry = T::zero();
108            if limb >= b_by2 {
109                limb = (q + limb) - b;
110                carry = T::one();
111            }
112
113            // carry = ((q + g - limb) % q) >> logb;
114
115            // carry = limb & b_by2;
116            // limb = (q + limb) - (carry << 1);
117            // if limb > q {
118            //     limb = limb - q;
119            // }
120            out.push(limb);
121
122            // carry = carry >> (logb - 1);
123        }
124
125        out[self.d - 1] = out[self.d - 1] + (carry << logb);
126        if out[self.d - 1] > q {
127            out[self.d - 1] = out[self.d - 1] - q;
128        }
129
130        return out;
131    }
132
133    fn d(&self) -> usize {
134        self.d
135    }
136}
137
138fn round_value<T: PrimInt>(value: T, ignore_bits: usize) -> T {
139    if ignore_bits == 0 {
140        return value;
141    }
142
143    let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
144    (value >> ignore_bits) + ignored_msb
145}
146
147#[cfg(test)]
148mod tests {
149    use rand::{thread_rng, Rng};
150
151    use crate::{
152        backend::{ModInit, ModularOpsU64},
153        decomposer::round_value,
154        utils::generate_prime,
155    };
156
157    use super::{Decomposer, DefaultDecomposer};
158
159    #[test]
160    fn decomposition_works() {
161        let logq = 60;
162        let logb = 5;
163        let d = 12;
164
165        let mut rng = thread_rng();
166
167        // q is prime of bits logq and i is true, other q = 1<<logq
168        // FIXME: Test fails when q is prime, albeit the difference is minute
169        for i in [true, false] {
170            let q = if i {
171                generate_prime(logq, 1 << 4, 1u64 << logq).unwrap()
172            } else {
173                1u64 << logq
174            };
175            let decomposer = DefaultDecomposer::new(q, logb, d);
176            let modq_op = ModularOpsU64::new(q);
177            for _ in 0..100 {
178                let value = rng.gen_range(0..q);
179                let limbs = decomposer.decompose(&value);
180                let value_back = decomposer.recompose(&limbs, &modq_op);
181                let rounded_value =
182                    round_value(value, decomposer.ignore_bits) << decomposer.ignore_bits;
183                // dbg!(&limbs, q);
184                assert_eq!(
185                    rounded_value, value_back,
186                    "Expected {rounded_value} got {value_back} for q={q}"
187                );
188            }
189        }
190    }
191}