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        return out;
126    }
127
128    fn d(&self) -> usize {
129        self.d
130    }
131}
132
133fn round_value<T: PrimInt>(value: T, ignore_bits: usize) -> T {
134    if ignore_bits == 0 {
135        return value;
136    }
137
138    let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
139    (value >> ignore_bits) + ignored_msb
140}
141
142#[cfg(test)]
143mod tests {
144    use rand::{thread_rng, Rng};
145
146    use crate::{
147        backend::{ModInit, ModularOpsU64},
148        decomposer::round_value,
149        utils::generate_prime,
150    };
151
152    use super::{Decomposer, DefaultDecomposer};
153
154    #[test]
155    fn decomposition_works() {
156        let logq = 15;
157        let logb = 3;
158        let d = 5;
159
160        let mut rng = thread_rng();
161
162        // q is prime of bits logq and i is true, other q = 1<<logq
163        // FIXME: Test fails when q is prime, albeit the difference is minute
164        for i in [true] {
165            let q = if i {
166                generate_prime(logq, 1 << 4, 1u64 << logq).unwrap()
167            } else {
168                1u64 << logq
169            };
170            let decomposer = DefaultDecomposer::new(q, logb, d);
171            let modq_op = ModularOpsU64::new(q);
172            for _ in 0..100 {
173                let value = rng.gen_range(0..q);
174                let limbs = decomposer.decompose(&value);
175                let value_back = decomposer.recompose(&limbs, &modq_op);
176                let rounded_value =
177                    round_value(value, decomposer.ignore_bits) << decomposer.ignore_bits;
178                dbg!(rounded_value, value, value_back);
179                assert_eq!(
180                    rounded_value, value_back,
181                    "Expected {rounded_value} got {value_back} for q={q}"
182                );
183            }
184        }
185    }
186}