primitives/random/prf/
ggm.rs

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>, /* K^i_{~alpha_i}, where
75                                                                   * alpha_i is the i-th MSB
76                                                                   * of
77                                                                   * alpha. */
78    ) -> 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>,    // leaves
125    HeapMatrix<[Gf2_128; 2], TreeDepth, BatchSize>, // level keys
126) {
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>, /* K^ij_{~alpha_ij}, where
152                                                                     * alpha_ij
153                                                                     * is the i-th
154                                                                     * MSB
155                                                                     * of
156                                                                     * alpha_j. */
157    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        // Sanitize input, zero unused bits
172        let alpha = alpha & ((1 << TreeDepth::USIZE) - 1);
173
174        // Start tree at first level with node at position `(~alpha_0) << (depth - 2)` set from
175        // OT result
176        let k: usize = TreeDepth::USIZE - 1;
177        let idx = (1 ^ (alpha >> k)) << k;
178        leaves[idx] = keys_tilde[0];
179
180        // For each level `lvl=1..depth-1` expand GGM tree as usual and let `k = depth - lvl`.
181        // The node at index `(alpha >> k) << (k - 1)` is unknown (gibberish in our
182        // implementation). This node is expanded into 2 siblings with wrong values
183        // also:
184        //    * node at index `(alpha >> (k - 1)) << (k - 2)` is the unknown node,
185        //    * its sibling at index `((alpha >> (k - 1)) ^ 1) << (k - 2)` is the node whose value
186        //      should be corrected using input `keys[lvl]`.
187        (1..TreeDepth::USIZE - 1).for_each(|level| {
188            let lvl_keys_tilde = ggm_level_expand(leaves, level, cipher0, cipher1);
189            // lvl_keys_tilde contains one (the) unknown node and its sibling to be corrected
190            // correct node
191            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        // Last level is specific
199        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        // Random set of depth bytes
262        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        // Emulate OT between full_tree.keys and negated alpha bits
285        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        // Random set of depth bytes
339        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        // Emulate OT between full_tree.keys and negated alpha bits
350        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}