1use std::ops::Mul;
2
3use aes::{cipher::KeyInit, Aes128Enc};
4use ff::Field;
5
6use crate::{
7 algebra::field::{binary::Gf2_128, FieldExtension},
8 hashing::{hash_cr, hash_into},
9 izip_eq,
10 random::prg::Aes128Prng,
11 types::{HeapArray, HeapMatrix, Positive, SessionId},
12};
13
14#[derive(Debug, Clone)]
15pub struct FullTrees<
16 F: FieldExtension,
17 TreeDepth: Positive,
18 TreeLeafCnt: Positive,
19 BatchSize: Positive,
20> {
21 pub leaves: HeapMatrix<F, TreeLeafCnt, BatchSize>,
22 pub keys: HeapMatrix<[Gf2_128; 2], TreeDepth, BatchSize>,
23}
24
25#[derive(Debug, Clone)]
26pub struct PuncturedTrees<F: FieldExtension, TreeLeafCnt: Positive, BatchSize: Positive> {
27 pub leaves: HeapMatrix<F, TreeLeafCnt, BatchSize>,
28}
29
30#[derive(Debug, Clone)]
31pub struct GGM {
32 ciphers: (Aes128Enc, Aes128Enc),
33}
34
35impl GGM {
36 pub fn new(session_id: SessionId) -> Self {
37 Self {
38 ciphers: Self::new_ciphers(session_id),
39 }
40 }
41
42 fn new_ciphers(session_id: SessionId) -> (Aes128Enc, Aes128Enc) {
43 let (mut seed0, mut seed1) = ([0; 16], [0; 16]);
44
45 hash_into([b"0".as_slice(), session_id.as_ref()], &mut seed0);
46 hash_into([b"1".as_slice(), session_id.as_ref()], &mut seed1);
47
48 (
49 Aes128Enc::new_from_slice(&seed0).unwrap(),
50 Aes128Enc::new_from_slice(&seed1).unwrap(),
51 )
52 }
53
54 pub fn expand_full_tree<F, TreeDepth, TreeLeafCnt, BatchSize>(
55 &mut self,
56 root_batches: &HeapArray<Gf2_128, BatchSize>,
57 ) -> FullTrees<F, TreeDepth, TreeLeafCnt, BatchSize>
58 where
59 F: FieldExtension,
60 TreeDepth: Positive,
61 TreeLeafCnt: Positive + Mul<BatchSize, Output: Positive>,
62 BatchSize: Positive,
63 {
64 let (seeds, keys) = compute_full_tree(root_batches, &self.ciphers.0, &self.ciphers.1);
65 let leaves =
66 generate_from_seeds::<F, _, BatchSize>(&self.ciphers.0, &self.ciphers.1, seeds);
67
68 FullTrees { leaves, keys }
69 }
70
71 pub fn expand_punctured_tree<F, TreeDepth, TreeLeafCnt, BatchSize>(
72 &mut self,
73 alpha_batches: &HeapArray<usize, BatchSize>,
74 keys_batches: &HeapMatrix<Gf2_128, TreeDepth, BatchSize>, ) -> PuncturedTrees<F, TreeLeafCnt, BatchSize>
79 where
80 F: FieldExtension,
81 TreeDepth: Positive,
82 TreeLeafCnt: Positive + Mul<BatchSize, Output: Positive>,
83 BatchSize: Positive,
84 {
85 let seeds = compute_punctured_tree(
86 alpha_batches,
87 keys_batches,
88 &self.ciphers.0,
89 &self.ciphers.1,
90 );
91
92 let leaves = generate_from_seeds::<F, _, _>(&self.ciphers.0, &self.ciphers.1, seeds);
93
94 PuncturedTrees { leaves }
95 }
96}
97
98fn generate_from_seeds<F, TreeLeafCnt, BatchSize>(
99 enc_left: &Aes128Enc,
100 enc_right: &Aes128Enc,
101 seeds: HeapMatrix<Gf2_128, TreeLeafCnt, BatchSize>,
102) -> HeapMatrix<F, TreeLeafCnt, BatchSize>
103where
104 F: FieldExtension,
105 TreeLeafCnt: Positive + Mul<BatchSize, Output: Positive>,
106 BatchSize: Positive,
107{
108 let ciphers = [enc_left, enc_right];
109
110 let tmp = seeds
111 .into_flat_iter()
112 .enumerate()
113 .map(|(i, s)| F::random(Aes128Prng::new(ciphers[i % 2], s)));
114
115 HeapMatrix::<_, TreeLeafCnt, BatchSize>::from_flat_iter(tmp)
116}
117
118#[allow(clippy::type_complexity)]
119fn compute_full_tree<TreeDepth: Positive, TreeLeafCnt: Positive, BatchSize: Positive>(
120 root_batches: &HeapArray<Gf2_128, BatchSize>,
121 cipher0: &Aes128Enc,
122 cipher1: &Aes128Enc,
123) -> (
124 HeapMatrix<Gf2_128, TreeLeafCnt, BatchSize>, HeapMatrix<[Gf2_128; 2], TreeDepth, BatchSize>, ) {
127 assert_eq!(1u64 << TreeDepth::USIZE, TreeLeafCnt::U64);
128 assert!(BatchSize::USIZE > 0);
129
130 let mut leaves_batches: HeapMatrix<Gf2_128, TreeLeafCnt, BatchSize> = Default::default();
131 let mut keys_batches: HeapMatrix<[Gf2_128; 2], TreeDepth, BatchSize> = Default::default();
132
133 izip_eq!(
134 root_batches,
135 leaves_batches.col_iter_mut(),
136 keys_batches.col_iter_mut()
137 )
138 .for_each(|(root, leaves, keys)| {
139 leaves[0] = *root;
140
141 keys.iter_mut().enumerate().for_each(|(level, keys)| {
142 *keys = ggm_level_expand(leaves, level, cipher0, cipher1);
143 });
144 });
145
146 (leaves_batches, keys_batches)
147}
148
149fn compute_punctured_tree<TreeDepth: Positive, TreeLeafCnt: Positive, BatchSize: Positive>(
150 alpha_batches: &HeapArray<usize, BatchSize>,
151 keys_tilde_batches: &HeapMatrix<Gf2_128, TreeDepth, BatchSize>, cipher0: &Aes128Enc,
158 cipher1: &Aes128Enc,
159) -> HeapMatrix<Gf2_128, TreeLeafCnt, BatchSize> {
160 assert_eq!(1u64 << TreeDepth::USIZE, TreeLeafCnt::U64);
161 assert!(BatchSize::USIZE > 0);
162
163 let mut leaves_batches: HeapMatrix<Gf2_128, TreeLeafCnt, BatchSize> = Default::default();
164
165 izip_eq!(
166 leaves_batches.col_iter_mut(),
167 alpha_batches,
168 keys_tilde_batches.col_iter()
169 )
170 .for_each(|(leaves, alpha, keys_tilde)| {
171 let alpha = alpha & ((1 << TreeDepth::USIZE) - 1);
173
174 let k: usize = TreeDepth::USIZE - 1;
177 let idx = (1 ^ (alpha >> k)) << k;
178 leaves[idx] = keys_tilde[0];
179
180 (1..TreeDepth::USIZE - 1).for_each(|level| {
188 let lvl_keys_tilde = ggm_level_expand(leaves, level, cipher0, cipher1);
189 let k: usize = TreeDepth::USIZE - level - 1;
192 let idx = 1 ^ (alpha >> k);
193 let alpha_k_neg = idx & 1;
194 let idx = idx << k;
195 leaves[idx] += keys_tilde[level] - lvl_keys_tilde[alpha_k_neg];
196 });
197
198 let level = TreeDepth::USIZE - 1;
200 let lvl_keys_tilde = ggm_level_expand(leaves, level, cipher0, cipher1);
201 leaves[alpha ^ 1] += keys_tilde[level] - lvl_keys_tilde[(alpha ^ 1) & 1];
202 });
203
204 leaves_batches
205}
206
207#[inline]
208fn ggm_level_expand(
209 nodes: &mut [Gf2_128],
210 level: usize,
211 cipher0: &Aes128Enc,
212 cipher1: &Aes128Enc,
213) -> [Gf2_128; 2] {
214 assert!(nodes.len() >= (1 << (level + 1)));
215 let mut k0 = Gf2_128::ZERO;
216 let mut k1 = Gf2_128::ZERO;
217
218 let n = nodes.len();
219 let step = n >> (level + 1);
220 for j in (0..n).step_by(step << 1) {
221 let s0 = hash_cr(cipher0, &nodes[j]);
222 let s1 = hash_cr(cipher1, &nodes[j]);
223
224 k0 += &s0;
225 k1 += &s1;
226
227 nodes[j] = s0;
228 nodes[j + step] = s1;
229 }
230
231 [k0, k1]
232}
233
234#[cfg(test)]
235mod tests {
236 use std::fmt::Debug;
237
238 use rand::Rng;
239 use typenum::U;
240
241 use super::*;
242 use crate::{
243 algebra::{
244 elliptic_curve::{Curve25519Ristretto, ScalarField},
245 field::binary::Gf2_128,
246 },
247 izip_eq,
248 izip_eq_lazy,
249 random::Random,
250 };
251
252 fn ggm_tree<TreeDepth, TreeLeafCnt, BatchSize>()
253 where
254 TreeDepth: Debug + Positive + Mul<BatchSize, Output: Positive>,
255 TreeLeafCnt: Debug + Positive,
256 BatchSize: Debug + Positive,
257 {
258 let mut rng = crate::random::test_rng();
259 let session_id = SessionId::random(&mut rng);
260
261 let alpha_batches = HeapArray::from_fn(|_| rng.gen::<usize>() % TreeLeafCnt::USIZE);
263
264 let root_batches = Gf2_128::random_elements(&mut rng);
265
266 let (cipher0, cipher1) = {
267 let (mut seed0, mut seed1) = ([0; 16], [0; 16]);
268
269 hash_into([b"0".as_slice(), session_id.as_ref()], &mut seed0);
270 hash_into([b"1".as_slice(), session_id.as_ref()], &mut seed1);
271
272 (
273 Aes128Enc::new_from_slice(&seed0).unwrap(),
274 Aes128Enc::new_from_slice(&seed1).unwrap(),
275 )
276 };
277
278 let (full_leaves_batches, full_keys_batches) = compute_full_tree::<
279 TreeDepth,
280 TreeLeafCnt,
281 BatchSize,
282 >(&root_batches, &cipher0, &cipher1);
283
284 let tmp = izip_eq!(&alpha_batches, full_keys_batches.col_iter())
286 .map(|(alpha, full_keys)| {
287 HeapArray::from_fn(|k| {
288 let alpha_k = (alpha >> (TreeDepth::USIZE - k - 1)) & 1;
289 full_keys[k][1 ^ alpha_k]
290 })
291 })
292 .collect();
293
294 let keys_batches: HeapMatrix<Gf2_128, TreeDepth, BatchSize> =
295 HeapMatrix::from_cols_array(tmp);
296
297 let punctured_leaves_batches = compute_punctured_tree::<TreeDepth, TreeLeafCnt, BatchSize>(
298 &alpha_batches,
299 &keys_batches,
300 &cipher0,
301 &cipher1,
302 );
303
304 izip_eq!(
305 alpha_batches,
306 full_leaves_batches.col_iter(),
307 punctured_leaves_batches.col_iter()
308 )
309 .for_each(|(alpha, full_leaves, puncured_leaves)| {
310 izip_eq_lazy!(full_leaves, puncured_leaves)
311 .enumerate()
312 .for_each(|(k, (r, s))| {
313 if k != alpha {
314 assert_eq!(r, s);
315 } else {
316 assert_ne!(r, s);
317 }
318 });
319 })
320 }
321
322 #[test]
323 fn test_ggm_tree() {
324 ggm_tree::<U<2>, U<4>, U<17>>();
325 ggm_tree::<U<7>, U<128>, U<4>>();
326 ggm_tree::<U<12>, U<4096>, U<1>>();
327 }
328
329 fn ggm_classic<F, TreeDepth, TreeLeafCnt, BatchSize>()
330 where
331 F: FieldExtension,
332 TreeDepth: Positive + Mul<BatchSize, Output: Positive>,
333 TreeLeafCnt: Positive + Mul<BatchSize, Output: Positive>,
334 BatchSize: Positive,
335 {
336 let mut rng = crate::random::test_rng();
337
338 let alpha_batches = HeapArray::from_fn(|_| rng.gen::<usize>() % TreeLeafCnt::USIZE);
340
341 let root_batches = Gf2_128::random_elements(&mut rng);
342
343 let mut ggm = GGM::new(SessionId::random(&mut rng));
344 let FullTrees {
345 leaves: full_leaves_batches,
346 keys: full_keys_batches,
347 } = ggm.expand_full_tree::<F, TreeDepth, TreeLeafCnt, BatchSize>(&root_batches);
348
349 let tmp = izip_eq!(&alpha_batches, full_keys_batches.col_iter())
351 .map(|(alpha, full_keys)| {
352 HeapArray::from_fn(|k| {
353 let alpha_k = (alpha >> (TreeDepth::USIZE - k - 1)) & 1;
354 full_keys[k][1 ^ alpha_k]
355 })
356 })
357 .collect();
358
359 let keys_batches: HeapMatrix<Gf2_128, TreeDepth, BatchSize> =
360 HeapMatrix::from_cols_array(tmp);
361
362 let PuncturedTrees {
363 leaves: punctured_leaves_batches,
364 } = ggm.expand_punctured_tree::<F, TreeDepth, TreeLeafCnt, BatchSize>(
365 &alpha_batches,
366 &keys_batches,
367 );
368
369 izip_eq!(
370 alpha_batches,
371 full_leaves_batches.col_iter(),
372 punctured_leaves_batches.col_iter()
373 )
374 .for_each(|(alpha, full_leaves, puncured_leaves)| {
375 izip_eq_lazy!(full_leaves, puncured_leaves)
376 .enumerate()
377 .for_each(|(k, (r, s))| {
378 if k != alpha {
379 assert_eq!(r, s);
380 } else {
381 assert_ne!(r, s);
382 }
383 });
384 })
385 }
386
387 #[test]
388 fn test_ggm_classic() {
389 ggm_classic::<Gf2_128, U<4>, U<16>, U<17>>();
390 ggm_classic::<Gf2_128, U<7>, U<128>, U<4>>();
391 ggm_classic::<Gf2_128, U<12>, U<4096>, U<1>>();
392
393 type Fq = ScalarField<Curve25519Ristretto>;
394 ggm_classic::<Fq, U<4>, U<16>, U<17>>();
395 ggm_classic::<Fq, U<7>, U<128>, U<4>>();
396 ggm_classic::<Fq, U<12>, U<4096>, U<1>>();
397 }
398}