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
use crate::bristol;
use crate::common::BitVec;
use crate::evaluate::and;
use crate::gate::base::BaseGate;
use crate::mul_triple::boolean::MulTriple;
use crate::mul_triple::boolean::MulTriples;
use crate::protocols::{Gate, Plain, Protocol, ScalarDim, SetupStorage, Share, Sharing};
use crate::utils::{rand_bitvec, BitVecExt};
use itertools::Itertools;
use rand::{CryptoRng, Rng};
use serde::{Deserialize, Serialize};
use tracing::trace;

#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)]
pub struct BooleanGmw;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Msg {
    // TODO ser/de the BitVecs or Vecs? Or maybe a single Vec? e and d have the same length
    AndLayer {
        size: usize,
        e: Vec<usize>,
        d: Vec<usize>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SimdMsg {
    packed_data: Msg,
    simd_sizes: Vec<u32>,
}

#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum BooleanGate {
    Base(BaseGate<bool>),
    And,
    Xor,
    Inv,
}

#[derive(Debug)]
pub struct XorSharing<R: CryptoRng + Rng> {
    rng: R,
}

impl Protocol for BooleanGmw {
    const SIMD_SUPPORT: bool = true;
    type Plain = bool;
    type Share = bool;
    type Msg = Msg;
    type SimdMsg = SimdMsg;
    type Gate = BooleanGate;
    type Wire = ();
    type ShareStorage = BitVec<usize>;
    type SetupStorage = MulTriples;

    fn share_constant(&self, party_id: usize, _output_share: bool, val: bool) -> Self::Share {
        if party_id == 0 {
            val
        } else {
            false
        }
    }

    fn evaluate_non_interactive(
        &self,
        party_id: usize,
        gate: &Self::Gate,
        mut inputs: impl Iterator<Item = Self::Share>,
    ) -> Self::Share {
        match gate {
            BooleanGate::Base(base) => base.default_evaluate(party_id, inputs),
            BooleanGate::And => panic!("Called evaluate_non_interactive on Gate::AND"),
            BooleanGate::Xor => {
                inputs.next().expect("Missing inputs") ^ inputs.next().expect("Missing inputs")
            }
            BooleanGate::Inv => {
                let inp = inputs.next().expect("Empty input");
                if party_id == 0 {
                    !inp
                } else {
                    inp
                }
            }
        }
    }

    fn evaluate_non_interactive_simd<'e>(
        &self,
        party_id: usize,
        gate: &Self::Gate,
        mut inputs: impl Iterator<Item = &'e <Self::Share as Share>::SimdShare>,
    ) -> <Self::Share as Share>::SimdShare {
        match gate {
            BooleanGate::Base(base) => base.default_evaluate_simd(party_id, inputs),
            BooleanGate::And => panic!("Called evaluate_non_interactive on Gate::AND"),
            BooleanGate::Xor => inputs
                .next()
                .expect("Missing inputs")
                .clone()
                .fast_bit_xor(inputs.next().expect("Missing inputs")),
            BooleanGate::Inv => {
                let inp = inputs.next().expect("Empty input").clone();
                if party_id == 0 {
                    !inp
                } else {
                    inp
                }
            }
        }
    }

    fn compute_msg(
        &self,
        _party_id: usize,
        interactive_gates: impl Iterator<Item = BooleanGate>,
        _gate_outputs: impl Iterator<Item = bool>,
        mut inputs: impl Iterator<Item = bool>,
        mul_triples: &mut MulTriples,
    ) -> Self::Msg {
        trace!("compute_msg");
        let (d, e): (BitVec<usize>, BitVec<usize>) = interactive_gates
            .zip(mul_triples.iter().rev())
            .map(|(gate, mt): (BooleanGate, MulTriple)| {
                // TODO debug_assert?
                assert!(matches!(gate, BooleanGate::And));
                let mut inputs = inputs.by_ref().take(gate.input_size());
                let (x, y) = (inputs.next().unwrap(), inputs.next().unwrap());
                debug_assert!(
                    inputs.next().is_none(),
                    "Currently only support AND gates with 2 inputs"
                );
                and::compute_shares(x, y, &mt)
            })
            .unzip();
        Msg::AndLayer {
            size: e.len(),
            e: e.into_vec(),
            d: d.into_vec(),
        }
    }

    fn compute_msg_simd<'e>(
        &self,
        _party_id: usize,
        _interactive_gates: impl Iterator<Item = Self::Gate>,
        _gate_outputs: impl Iterator<Item = &'e BitVec<usize>>,
        inputs: impl Iterator<Item = &'e BitVec<usize>>,
        mul_triples: &mut Self::SetupStorage,
    ) -> Self::SimdMsg {
        let mut simd_sizes = vec![];
        let mut d = BitVec::new();
        let mut e = BitVec::new();
        inputs.chunks(2).into_iter().for_each(|mut chunk| {
            let x = chunk.next().unwrap();
            let y = chunk.next().unwrap();
            simd_sizes.push(x.len() as u32);
            debug_assert_eq!(x.len(), y.len(), "Unequal SIMD sizes");
            e.extend_from_bitslice(x);
            d.extend_from_bitslice(y);
        });
        let mts = mul_triples.slice(mul_triples.len() - d.len()..);

        d.fast_bit_xor_mut(&mts.a().to_bitvec());
        e.fast_bit_xor_mut(&mts.b().to_bitvec());

        SimdMsg {
            packed_data: Msg::AndLayer {
                size: 0,
                e: e.into_vec(),
                d: d.into_vec(),
            },
            simd_sizes,
        }
    }

    fn evaluate_interactive(
        &self,
        party_id: usize,
        _interactive_gates: impl Iterator<Item = Self::Gate>,
        _gate_outputs: impl Iterator<Item = bool>,
        own_msg: Self::Msg,
        other_msg: Self::Msg,
        mul_triples: &mut MulTriples,
    ) -> Self::ShareStorage {
        let Msg::AndLayer { d, e, size } = own_msg;
        let d = BitVec::from_vec(d);
        let e = BitVec::from_vec(e);
        let Msg::AndLayer {
            size: resp_size,
            d: resp_d,
            e: resp_e,
        } = other_msg;
        assert_eq!(size, resp_size, "Message have unequal size");
        // Remove the mul_triples used in compute_msg
        let mul_triples = mul_triples.split_off_last(size);
        d.into_iter()
            .zip(e)
            .zip(BitVec::from_vec(resp_d))
            .zip(BitVec::from_vec(resp_e))
            .zip(mul_triples.iter().rev())
            .map(|((((d, e), d_resp), e_resp), mt)| {
                let d = [d, d_resp];
                let e = [e, e_resp];
                and::evaluate(d, e, mt, party_id)
            })
            .collect()
    }

    fn evaluate_interactive_simd<'e>(
        &self,
        party_id: usize,
        _interactive_gates: impl Iterator<Item = Self::Gate>,
        _gate_outputs: impl Iterator<Item = &'e BitVec<usize>>,
        own_msg: Self::SimdMsg,
        other_msg: Self::SimdMsg,
        mul_triples: &mut Self::SetupStorage,
    ) -> Vec<Self::ShareStorage> {
        let SimdMsg {
            packed_data: Msg::AndLayer { d, e, size },
            simd_sizes,
        } = own_msg;
        let own_d = BitVec::from_vec(d);
        let own_e = BitVec::from_vec(e);
        let SimdMsg {
            packed_data:
                Msg::AndLayer {
                    d: resp_d,
                    e: resp_e,
                    size: resp_size,
                },
            simd_sizes: resp_simd_sizes,
        } = other_msg;
        let resp_d = BitVec::from_vec(resp_d);
        let resp_e = BitVec::from_vec(resp_e);

        assert_eq!(size, resp_size, "Message have unequal size");
        assert_eq!(
            simd_sizes, resp_simd_sizes,
            "Message have unequal simd sizes"
        );
        let total_size = simd_sizes.iter().copied().sum::<u32>() as usize;
        // Remove the mul_triples used in compute_msg
        let mts = mul_triples.split_off_last(total_size);
        let d = own_d.fast_bit_xor(&resp_d);
        let e = own_e.fast_bit_xor(&resp_e);
        let mut res = if party_id == 0 {
            d.clone().fast_bit_and(&e)
        } else {
            BitVec::repeat(false, total_size)
        };
        res.fast_bit_xor_mut(&d.fast_bit_and(mts.b()))
            .fast_bit_xor_mut(&e.fast_bit_and(mts.a()))
            .fast_bit_xor_mut(mts.c());
        // res ^= d & mts.b ^ e & mts.a ^ mts.c;
        let mut res = res.as_bitslice();
        simd_sizes
            .iter()
            .map(|size| {
                let simd_share = res[..*size as usize].to_bitvec();
                res = &res[*size as usize..];
                simd_share
            })
            .collect()
    }
}

impl Plain for bool {}

impl Share for bool {
    type Plain = bool;
    type SimdShare = BitVec<usize>;
}

impl Gate<bool> for BooleanGate {
    type DimTy = ScalarDim;

    fn is_interactive(&self) -> bool {
        matches!(self, BooleanGate::And)
    }

    fn input_size(&self) -> usize {
        match self {
            BooleanGate::Base(base_gate) => base_gate.input_size(),
            BooleanGate::Inv => 1,
            BooleanGate::And | BooleanGate::Xor => 2,
        }
    }

    fn as_base_gate(&self) -> Option<&BaseGate<bool>> {
        match self {
            BooleanGate::Base(base_gate) => Some(base_gate),
            _ => None,
        }
    }

    fn wrap_base_gate(base_gate: BaseGate<bool, Self::DimTy>) -> Self {
        Self::Base(base_gate)
    }
}

impl From<&bristol::Gate> for BooleanGate {
    fn from(gate: &bristol::Gate) -> Self {
        match gate {
            bristol::Gate::And(_) => BooleanGate::And,
            bristol::Gate::Xor(_) => BooleanGate::Xor,
            bristol::Gate::Inv(_) => BooleanGate::Inv,
        }
    }
}

impl From<BaseGate<bool>> for BooleanGate {
    fn from(base_gate: BaseGate<bool>) -> Self {
        BooleanGate::Base(base_gate)
    }
}

impl<R: CryptoRng + Rng> XorSharing<R> {
    pub fn new(rng: R) -> Self {
        Self { rng }
    }
}

impl<R: CryptoRng + Rng> Sharing for XorSharing<R> {
    type Plain = bool;
    type Shared = BitVec<usize>;

    fn share(&mut self, input: Self::Shared) -> [Self::Shared; 2] {
        let rand = rand_bitvec(input.len(), &mut self.rng);
        let masked_input = input ^ &rand;
        [rand, masked_input]
    }

    fn reconstruct(shares: [Self::Shared; 2]) -> Self::Shared {
        let [a, b] = shares;
        a ^ b
    }
}

impl Default for Msg {
    fn default() -> Self {
        Self::AndLayer {
            size: 0,
            e: vec![],
            d: vec![],
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::circuit::ExecutableCircuit;
    use crate::common::BitVec;
    use crate::private_test_utils::{execute_circuit, TestChannel};
    use crate::protocols::boolean_gmw::BooleanGmw;
    use crate::secret::Secret;
    use crate::{BooleanGate, CircuitBuilder};

    #[tokio::test]
    async fn simple_logic() -> anyhow::Result<()> {
        let a = Secret::<_, u32>::input(0);
        (a & false).output();

        let circ = CircuitBuilder::<bool, BooleanGate, u32>::global_into_circuit();
        let out = execute_circuit::<BooleanGmw, _, _>(
            &ExecutableCircuit::DynLayers(circ),
            true,
            TestChannel::InMemory,
        )
        .await?;
        assert_eq!(out, BitVec::<u8>::repeat(false, 1));
        Ok(())
    }
}