reverie-zk 0.3.2

An efficient implementation of the NIZKPoK outlined in KKW 2018
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::convert::{AsMut, AsRef};
use std::fmt::Debug;
use std::io;
use std::ops::{Add, Mul, Sub};

use mcircuit::WireValue;
use num_traits::identities::Zero;
use rand::RngCore;

use crate::crypto::hash;
use crate::crypto::prg::{Key, PRG};
use crate::generator::ShareGen;
use crate::{BATCH_SIZE, PACKED, PLAYERS};

#[allow(clippy::suspicious_arithmetic_impl)] // Clippy thinks GF2 arithmetic is suspicious
pub mod gf2;
pub mod z64;

pub trait Serialize {
    fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()>;
}

pub trait Deserialize {
    fn deserialize<R: io::Read>(&mut self, reader: &mut R) -> io::Result<()>;
}

impl<T: AsRef<[u8]>> Serialize for T {
    fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
        writer.write_all(self.as_ref())
    }
}

impl<T: AsMut<[u8]>> Deserialize for T {
    fn deserialize<R: io::Read>(&mut self, reader: &mut R) -> io::Result<()> {
        reader.read_exact(self.as_mut())
    }
}

pub trait Hashable {
    fn hash(&self, hashers: &mut hash::PackedHasher);
}

pub trait Recon:
    Sized
    + Pack
    + Zero
    + Add<Output = Self>
    + Mul<Output = Self>
    + Sub<Output = Self>
    + Copy
    + Debug
    + Clone
    + Hashable
    + Default
    + PartialEq
    + Eq
    + EqIndex
{
}

pub trait Batch: Sized + Add + Zero + Default {
    fn random(&mut self, prg: &mut PRG);
}

pub trait Pack: Sized {
    fn pack(
        dst: &mut [Vec<u8>; PACKED], // serialized elements for each repetition
        src: &[Self],                // slice of packed elements
        selected: &[bool; PACKED],   // should the repetition be extracted?
    );

    #[allow(clippy::ptr_arg)]
    fn unpack(
        dst: &mut Vec<Self>,   // packed elements
        src: &[&[u8]; PACKED], // slice of bytes for each repetition
    );
}

pub trait PackSelected: Sized {
    /// Extract and save (to dst) the shares of the selected players from the sharings.
    /// E.g. given a 2 packed sharing between 4 players: `abcd|1234`
    /// Between players:
    ///
    /// - P_a
    /// - P_b
    /// - P_c
    /// - P_d
    ///
    /// - P_1
    /// - P_2
    /// - P_3
    /// - P_4
    ///
    /// And `selected = [1, 3]`, the destination vector will contain:
    ///
    /// - `dst[0] = [b, ...]`
    /// - `dst[1] = [1, ...]`
    ///
    /// # Arguments
    ///
    /// - `dst`: Individually serialized share for each player (one vector of results per instance).
    /// - `src`: The input sharings.
    /// - `selected`: The players whose shares should be extracted.
    ///               If `selected[i] >= PLAYERS` no share are extracted.
    ///
    fn pack_selected(dst: &mut [Vec<u8>; PACKED], src: &[Self], selected: [usize; PACKED]);

    #[allow(clippy::ptr_arg)]
    fn unpack_selected(dst: &mut Vec<Self>, src: &[&[u8]; PACKED], selected: [usize; PACKED]);
}

pub trait Share:
    Sized
    + PackSelected
    + Debug
    + Zero
    + Add<Output = Self>
    + Sub<Output = Self>
    + Default
    + Copy
    + Clone
    + Hashable
    + EqIndex
{
}

// Used in unit tests to compare individual coordinates.
pub trait EqIndex {
    fn compare_index(
        _rep1: usize,
        _p1: usize,
        _v1: &Self, // first index
        _rep2: usize,
        _p2: usize,
        _v2: &Self, // second index
    ) -> bool {
        true
    }
}

pub trait Domain: Copy + Clone + Debug {
    // per-player batch
    type Batch: Batch;

    // packed reconstruction
    type Recon: Recon;

    // packed shares of players
    type Share: Share
        + Mul<Self::Recon, Output = Self::Share>
        + Add<Self::Recon, Output = Self::Share>;

    //
    fn reconstruct(share: &Self::Share) -> Self::Recon;

    // one share per player
    fn batches_to_shares(
        to: &mut [Self::Share; BATCH_SIZE],
        from: &[[Self::Batch; PLAYERS]; PACKED],
    );

    /// Used in tests only
    ///
    /// Generates random shares
    fn random_shares<R: RngCore>(rng: &mut R, num: usize) -> Vec<Self::Share> {
        // create share generator with randomness from rng
        let mut keys: [[Key; PLAYERS]; PACKED] = [[Default::default(); PLAYERS]; PACKED];
        for packed_keys in keys.iter_mut().take(PACKED) {
            for player_key in packed_keys.iter_mut().take(PLAYERS) {
                rng.fill_bytes(player_key);
            }
        }
        let mut share_gen: ShareGen<Self> = ShareGen::new(&keys, [PLAYERS; PACKED]);

        // generate requested shares one-by-one
        let mut shares: Vec<Self::Share> = Vec::with_capacity(num);
        for _ in 0..num {
            shares.push(share_gen.next());
        }
        shares
    }

    /// Used in tests only
    ///
    /// Generates random reconstructions
    fn random_recon<R: RngCore>(rng: &mut R, num: usize) -> Vec<Self::Recon> {
        let shares = Self::random_shares(rng, num);
        shares.iter().map(|s| Self::reconstruct(s)).collect()
    }

    // Type of constant parameter to ADDC/MULC gates
    type ConstType: Into<Self::Recon> + Copy + Debug + PartialEq + WireValue;

    // multiplicative identity
    const ONE: Self::ConstType;

    // additive identity
    const ZERO: Self::ConstType;
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use rand::rngs::OsRng;
    use rand::Rng;

    use super::*;

    fn test_recon_pack<D: Domain>() {
        let tests = vec![
            // (reps, selected, recons)
            (2, 1),
        ];

        for (num_reps, num_recons) in tests.into_iter() {
            // select random indexes to extract
            let mut selected = vec![false; PACKED * num_reps];
            let mut rem = PACKED;
            while rem > 0 {
                let i = OsRng.gen::<usize>() % selected.len();
                if !selected[i] {
                    rem -= 1;
                    selected[i] = true;
                }
            }

            // generate random reconstructions
            let recon: Vec<Vec<D::Recon>> = (0..num_reps)
                .map(|_| D::random_recon(&mut OsRng, num_recons))
                .collect();

            // pack the reconstructions into individual coordinates
            let mut packed: Vec<Vec<u8>> = (0..PACKED * num_reps).map(|_| vec![]).collect();
            for i in 0..num_reps {
                let range = i * PACKED..(i + 1) * PACKED;
                D::Recon::pack(
                    <&mut [Vec<u8>; PACKED]>::try_from(&mut packed[range.clone()]).unwrap(),
                    &recon[i][..],
                    <&[bool; PACKED]>::try_from(&selected[range]).unwrap(),
                );
            }

            // collect back into a packed reconstructions
            let mut recovered: Vec<D::Recon> = vec![];
            let mut streams: Vec<&[u8]> = vec![];

            for (i, sel) in selected.iter().copied().enumerate() {
                if sel {
                    streams.push(&packed[i][..]);
                }
            }

            assert_eq!(streams.len(), PACKED);
            D::Recon::unpack(
                &mut recovered,
                <&[&[u8]; PACKED]>::try_from(&streams[..]).unwrap(),
            );

            assert!(recovered.len() >= num_recons);

            // check that the recovered reconstructions are the same as the original in the packed indexes
            for i in 0..num_recons {
                let mut nxt = 0;
                for (j, sel) in selected.iter().copied().enumerate() {
                    if sel {
                        let v1 = &recovered[i];
                        let v2 = &recon[j / PACKED][i];
                        let rep1 = nxt;
                        let rep2 = j % PACKED;
                        assert!(
                            D::Recon::compare_index(
                                nxt,
                                0,
                                &recovered[i], //
                                j % PACKED,
                                0,
                                &recon[j / PACKED][i],
                            ),
                            "recovered[_] = {:?}, recon[_] = {:?}, rep1 = {}, rep2 = {}",
                            v1,
                            v2,
                            rep1,
                            rep2
                        );
                        nxt += 1;
                    }
                }
            }

            /*
            let mut recon_unpacked: Vec<D::Recon> = vec![];
            D::Recon::unpack(
                &mut recon_unpacked,
                &[
                    &dst[0], &dst[1], &dst[2], &dst[3], &dst[4], &dst[5], &dst[6], &dst[7],
                ],
            );
            */
        }

        let selected: [bool; PACKED] = [true; PACKED];

        for num in vec![1, 2, 3, 6, 18, 32, 64, 63, 65, 128, 127] {
            let shares = D::random_shares(&mut OsRng, num);
            let recon: Vec<D::Recon> = shares.iter().map(|s| D::reconstruct(s)).collect();
            let mut dst = [
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
            ];
            D::Recon::pack(&mut dst, &recon[..], &selected);
            let mut recon_unpacked: Vec<D::Recon> = vec![];
            D::Recon::unpack(
                &mut recon_unpacked,
                &[
                    &dst[0], &dst[1], &dst[2], &dst[3], &dst[4], &dst[5], &dst[6], &dst[7],
                ],
            );

            for i in 0..recon.len() {
                assert_eq!(recon_unpacked[i], recon[i]);
            }
        }
    }

    fn test_share_partial_pack<D: Domain>() {
        for num in vec![1, 2, 3, 6, 18, 32, 64, 63, 65, 128, 127] {
            let shares = D::random_shares(&mut OsRng, num);

            let selected: [usize; PACKED] = [
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
                OsRng.gen::<usize>() % PLAYERS,
            ];

            let mut shares_packed = [
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
                vec![],
            ];

            D::Share::pack_selected(&mut shares_packed, &shares[..], selected);

            let mut shares_partial: Vec<D::Share> = vec![];

            D::Share::unpack_selected(
                &mut shares_partial,
                &[
                    &shares_packed[0],
                    &shares_packed[1],
                    &shares_packed[2],
                    &shares_packed[3],
                    &shares_packed[4],
                    &shares_packed[5],
                    &shares_packed[6],
                    &shares_packed[7],
                ],
                selected,
            );

            assert!(shares_partial.len() >= shares.len());

            println!("{:?}", shares_packed);

            for j in 0..shares.len() {
                for rep in 0..PACKED {
                    let p = selected[rep];
                    assert!(
                        D::Share::compare_index(rep, p, &shares_partial[j], rep, p, &shares[j]),
                        "{:?}",
                        selected
                    );
                }
            }
        }

        // test packing
    }

    fn test_domain<D: Domain>() {
        test_recon_pack::<D>();
        test_share_partial_pack::<D>();
    }

    #[test]
    fn test_gf2() {
        test_domain::<gf2::Domain>();
    }

    #[test]
    fn test_z64() {
        test_domain::<z64::Domain>();
    }
}