phantom-zone/src/decomposer.rs
src/decomposer.rsRaw
1use itertools::Itertools;
2use num_traits::{AsPrimitive, FromPrimitive, Num, One, PrimInt, ToPrimitive, WrappingSub, Zero};
3use std::{fmt::Debug, marker::PhantomData, ops::Rem};
4
5use crate::backend::{ArithmeticOps, ModularOpsU64};
6
7fn 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 RlweDecomposer {
17 type Element;
18 type D: Decomposer<Element = Self::Element>;
19
20 /// Decomposer for RLWE Part A
21 fn a(&self) -> &Self::D;
22 /// Decomposer for RLWE Part B
23 fn b(&self) -> &Self::D;
24}
25
26impl<D> RlweDecomposer for (D, D)
27where
28 D: Decomposer,
29{
30 type D = D;
31 type Element = D::Element;
32 fn a(&self) -> &Self::D {
33 &self.0
34 }
35 fn b(&self) -> &Self::D {
36 &self.1
37 }
38}
39
40pub trait Decomposer {
41 type Element;
42 fn new(q: Self::Element, logb: usize, d: usize) -> Self;
43 //FIXME(Jay): there's no reason why it returns a vec instead of an iterator
44 fn decompose(&self, v: &Self::Element) -> Vec<Self::Element>;
45 fn decomposition_count(&self) -> usize;
46}
47
48// TODO(Jay): Shouldn't Decompose also return corresponding gadget vector ?
49pub struct DefaultDecomposer<T> {
50 q: T,
51 logq: usize,
52 logb: usize,
53 d: usize,
54 ignore_bits: usize,
55 ignore_limbs: usize,
56}
57
58pub trait NumInfo {
59 const BITS: u32;
60}
61
62impl NumInfo for u64 {
63 const BITS: u32 = u64::BITS;
64}
65impl NumInfo for u32 {
66 const BITS: u32 = u32::BITS;
67}
68impl NumInfo for u128 {
69 const BITS: u32 = u128::BITS;
70}
71
72impl<T: PrimInt + NumInfo + Debug> DefaultDecomposer<T> {
73 fn recompose<Op>(&self, limbs: &[T], modq_op: &Op) -> T
74 where
75 Op: ArithmeticOps<Element = T>,
76 {
77 let mut value = T::zero();
78 for i in 0..self.d {
79 value = modq_op.add(
80 &value,
81 &(modq_op.mul(
82 &limbs[i],
83 &(T::one() << (self.logb * (i + self.ignore_limbs))),
84 )),
85 )
86 }
87 value
88 }
89
90 pub(crate) fn gadget_vector(&self) -> Vec<T> {
91 return gadget_vector(self.logq, self.logb, self.d);
92 }
93}
94
95impl<T: PrimInt + ToPrimitive + FromPrimitive + WrappingSub + Debug + NumInfo> Decomposer
96 for DefaultDecomposer<T>
97{
98 type Element = T;
99
100 fn new(q: T, logb: usize, d: usize) -> DefaultDecomposer<T> {
101 // if q is power of 2, then `BITS - leading_zeros` outputs logq + 1.
102 let logq = if q & (q - T::one()) == T::zero() {
103 (T::BITS - q.leading_zeros() - 1) as usize
104 } else {
105 (T::BITS - q.leading_zeros()) as usize
106 };
107
108 let d_ideal = (logq as f64 / logb as f64).ceil().to_usize().unwrap();
109 let ignore_limbs = (d_ideal - d);
110 let ignore_bits = (d_ideal - d) * logb;
111
112 DefaultDecomposer {
113 q,
114 logq,
115 logb,
116 d,
117 ignore_bits,
118 ignore_limbs,
119 }
120 }
121
122 /// Signed BNAF decomposition. Only returns most significant `d`
123 /// decomposition limbs
124 ///
125 /// Implements algorithm 3 of https://eprint.iacr.org/2021/1161.pdf
126 fn decompose(&self, value: &T) -> Vec<T> {
127 let mut value = round_value(*value, self.ignore_bits);
128
129 let q = self.q;
130 let logb = self.logb;
131 let b = T::one() << logb;
132 let full_mask = b - T::one();
133 let bby2 = b >> 1;
134
135 if value > (q >> 1) {
136 value = !(q - value) + T::one()
137 }
138
139 let mut out = Vec::with_capacity(self.d);
140 for _ in 0..self.d {
141 let k_i = value & full_mask;
142 value = (value - k_i) >> logb;
143
144 if k_i > bby2 || (k_i == bby2 && ((value & full_mask) >= bby2)) {
145 out.push(q - (b - k_i));
146 value = value + T::one();
147 } else {
148 out.push(k_i)
149 }
150 }
151
152 return out;
153 }
154
155 fn decomposition_count(&self) -> usize {
156 self.d
157 }
158}
159
160// impl<T> Decomposer for dyn AsRef<DefaultDecomposer<T>>
161// where
162// DefaultDecomposer<T>: Decomposer<Element = T>,
163// {
164// type Element = T;
165
166// fn new(q: Self::Element, logb: usize, d: usize) -> Self {
167// DefaultDecomposer::<T>::new(q, logb, d)
168// }
169
170// fn decompose(&self, v: &Self::Element) -> Vec<Self::Element> {
171// todo!()
172// }
173
174// fn decomposition_count(&self) -> usize {
175// todo!()
176// }
177// }
178
179// impl<U: AsRef<DefaultDecomposer<T>>> Decomposer for U
180// where
181// DefaultDecomposer<T>: Decomposer,
182// {
183// type Element = T;
184
185// fn new(q: Self::Element, logb: usize, d: usize) -> Self {
186// todo!()
187// }
188
189// fn decompose(&self, v: &Self::Element) -> Vec<Self::Element> {
190// todo!()
191// }
192
193// fn decomposition_count(&self) -> usize {
194// todo!()
195// }
196// }
197
198fn round_value<T: PrimInt>(value: T, ignore_bits: usize) -> T {
199 if ignore_bits == 0 {
200 return value;
201 }
202
203 let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
204 (value >> ignore_bits) + ignored_msb
205}
206
207#[cfg(test)]
208mod tests {
209 use num_traits::Float;
210 use rand::{thread_rng, Rng};
211
212 use crate::{
213 backend::{ModInit, ModularOpsU64},
214 decomposer::round_value,
215 utils::{generate_prime, Stats, TryConvertFrom1},
216 };
217
218 use super::{Decomposer, DefaultDecomposer};
219
220 #[test]
221 fn decomposition_works() {
222 let logq = 50;
223 let logb = 5;
224 let d = 10;
225
226 let mut rng = thread_rng();
227 let mut stats = Stats { samples: vec![] };
228
229 // q is prime of bits logq and i is true, other q = 1<<logq
230 // FIXME: Test fails when q is prime, albeit the difference is minute
231 for i in [false] {
232 let q = if i {
233 generate_prime(logq, 1 << 4, 1u64 << logq).unwrap()
234 } else {
235 1u64 << logq
236 };
237 let decomposer = DefaultDecomposer::new(q, logb, d);
238 let modq_op = ModularOpsU64::new(q);
239 for _ in 0..1000 {
240 let value = rng.gen_range(0..q);
241 let limbs = decomposer.decompose(&value);
242 let value_back = decomposer.recompose(&limbs, &modq_op);
243 let rounded_value =
244 round_value(value, decomposer.ignore_bits) << decomposer.ignore_bits;
245 stats.add_more(&Vec::<i64>::try_convert_from(&limbs, &q));
246 assert_eq!(
247 rounded_value, value_back,
248 "Expected {rounded_value} got {value_back} for q={q}"
249 );
250 }
251 }
252 println!("Mean: {}", stats.mean());
253 println!("Std: {}", stats.std_dev());
254 }
255}