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
use crate::gate::base::BaseGate;
use crate::mul_triple::arithmetic::MulTriple;
use crate::mul_triple::arithmetic::MulTriples;
use crate::protocols::{Gate, Protocol, Ring, ScalarDim, SetupStorage, Sharing};
use itertools::izip;
use rand::distributions::{Distribution, Standard};
use rand::{CryptoRng, Rng};
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;

#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)]
pub struct ArithmeticGmw<R>(PhantomData<R>);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Msg<R> {
    MulLayer { e: Vec<R>, d: Vec<R> },
}

#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum ArithmeticGate<R> {
    Base(BaseGate<R>),
    Mul,
    Add,
    Sub,
}

#[derive(Debug)]
pub struct AdditiveSharing<RING, RNG: CryptoRng + Rng> {
    rng: RNG,
    phantom: PhantomData<RING>,
}

impl<R: Ring> Protocol for ArithmeticGmw<R> {
    type Plain = R;
    type Share = R;
    type Msg = Msg<R>;
    type SimdMsg = ();
    type Gate = ArithmeticGate<R>;
    type Wire = ();
    type ShareStorage = Vec<R>;
    type SetupStorage = MulTriples<R>;

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

    fn evaluate_non_interactive(
        &self,
        party_id: usize,
        gate: &Self::Gate,
        inputs: impl Iterator<Item = Self::Share>,
    ) -> Self::Share {
        let mut inputs = inputs.into_iter();
        match gate {
            ArithmeticGate::Base(base) => base.default_evaluate(party_id, inputs.by_ref()),
            ArithmeticGate::Mul => panic!("Called evaluate_non_interactive on Gate::AND"),
            ArithmeticGate::Add => {
                let x = inputs.next().expect("Empty input");
                let y = inputs.next().expect("Empty input");
                x.wrapping_add(&y)
            }
            ArithmeticGate::Sub => {
                // TODO is this the correct order?
                let x = inputs.next().expect("Empty input");
                let y = inputs.next().expect("Empty input");
                x.wrapping_sub(&y)
            }
        }
    }

    fn compute_msg(
        &self,
        _party_id: usize,
        interactive_gates: impl Iterator<Item = Self::Gate>,
        _gate_outputs: impl Iterator<Item = R>,
        mut inputs: impl Iterator<Item = R>,
        mul_triples: &mut MulTriples<R>,
    ) -> Self::Msg {
        let (d, e) = interactive_gates
            .zip(mul_triples.iter())
            .map(|(gate, mt): (ArithmeticGate<R>, MulTriple<R>)| {
                // TODO debug_assert?
                assert!(matches!(gate, ArithmeticGate::Mul));
                let mut inputs = inputs.by_ref().take(gate.input_size());
                let (x, y): (R, R) = (inputs.next().unwrap(), inputs.next().unwrap());
                debug_assert!(
                    inputs.next().is_none(),
                    "Currently only support AND gates with 2 inputs"
                );
                (x.wrapping_sub(mt.a()), y.wrapping_sub(mt.c()))
            })
            .unzip();
        Msg::MulLayer { e, d }
    }

    fn evaluate_interactive(
        &self,
        party_id: usize,
        _interactive_gates: impl Iterator<Item = Self::Gate>,
        _gate_outputs: impl Iterator<Item = R>,
        own_msg: Self::Msg,
        other_msg: Self::Msg,
        mul_triples: &mut MulTriples<R>,
    ) -> Self::ShareStorage {
        let Msg::MulLayer { e, d } = own_msg;
        let Msg::MulLayer {
            e: resp_e,
            d: resp_d,
        } = other_msg;

        let mts = mul_triples.remove_first(e.len());

        izip!(d, e, resp_d, resp_e, mts.iter())
            .map(|(own_d, own_e, resp_d, resp_e, mt)| {
                let d = own_d.wrapping_add(&resp_d);
                let e = own_e.wrapping_add(&resp_e);
                let da = d.wrapping_mul(mt.a());
                let eb = e.wrapping_mul(mt.b());
                let da_eb_c = da.wrapping_add(&eb).wrapping_add(mt.c());
                if party_id == 0 {
                    let de = d.wrapping_mul(&e);
                    da_eb_c.wrapping_add(&de)
                } else {
                    da_eb_c
                }
            })
            .collect()
    }
}

impl<R: Ring> Gate<R> for ArithmeticGate<R> {
    type DimTy = ScalarDim;

    fn is_interactive(&self) -> bool {
        matches!(self, ArithmeticGate::Mul)
    }

    fn input_size(&self) -> usize {
        match self {
            ArithmeticGate::Base(base_gate) => base_gate.input_size(),
            ArithmeticGate::Mul | ArithmeticGate::Add | ArithmeticGate::Sub => 2,
        }
    }

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

    fn wrap_base_gate(base_gate: BaseGate<R>) -> Self {
        Self::Base(base_gate)
    }
}

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

impl<RING, RNG: CryptoRng + Rng> AdditiveSharing<RING, RNG> {
    pub fn new(rng: RNG) -> Self {
        Self {
            rng,
            phantom: PhantomData,
        }
    }
}

impl<RING, RNG> Sharing for AdditiveSharing<RING, RNG>
where
    RING: Ring,
    RNG: CryptoRng + Rng,
    Standard: Distribution<RING>,
{
    type Plain = RING;
    type Shared = Vec<RING>;

    fn share(&mut self, input: Self::Shared) -> [Self::Shared; 2] {
        let rand: Vec<_> = (&mut self.rng)
            .sample_iter(Standard)
            .take(input.len())
            .collect();
        let masked_input = rand
            .iter()
            .zip(input)
            .map(|(rand, inp)| inp.wrapping_sub(rand))
            .collect();
        [rand, masked_input]
    }

    fn reconstruct(shares: [Self::Shared; 2]) -> Self::Shared {
        let [a, b] = shares;
        a.into_iter()
            .zip(b)
            .map(|(a, b)| a.wrapping_add(&b))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use crate::circuit::{BaseCircuit, DefaultIdx, ExecutableCircuit};
    use crate::gate::base::BaseGate;
    use crate::private_test_utils::{execute_circuit, TestChannel};
    use crate::protocols::arithmetic_gmw::{AdditiveSharing, ArithmeticGate, ArithmeticGmw};
    use crate::protocols::ScalarDim;

    #[tokio::test]
    async fn simple_circ() -> anyhow::Result<()> {
        let mut bc = BaseCircuit::<u32, _, DefaultIdx>::new();
        let inp1 = bc.add_gate(ArithmeticGate::Base(BaseGate::Input(ScalarDim)));
        let inp2 = bc.add_gate(ArithmeticGate::Base(BaseGate::Input(ScalarDim)));
        let inp3 = bc.add_gate(ArithmeticGate::Base(BaseGate::Input(ScalarDim)));
        let add = bc.add_wired_gate(ArithmeticGate::Add, &[inp1, inp2]);
        let mul = bc.add_wired_gate(ArithmeticGate::Mul, &[inp3, add]);
        bc.add_wired_gate(ArithmeticGate::Base(BaseGate::Output(ScalarDim)), &[mul]);

        let circ = ExecutableCircuit::DynLayers(bc.into());

        let out = execute_circuit::<ArithmeticGmw<u32>, _, AdditiveSharing<u32, _>>(
            &circ,
            (5, 5, 10),
            TestChannel::InMemory,
        )
        .await?;

        assert_eq!(100, out[0]);

        Ok(())
    }
}