Skip to main content

fancy_garbling/wire/
mod2.rs

1use crate::{BinaryWireLabel, WireLabel};
2use rand::{CryptoRng, RngExt};
3use subtle::ConditionallySelectable;
4use swanky_cr_hash::TweakableCircularCorrelationRobustHash;
5use swanky_field_binary::F2;
6use vectoreyes::{
7    SimdBase, U8x16,
8    array_utils::{ArrayUnrolledExt, ArrayUnrolledOps, UnrollableArraySize},
9};
10
11/// Representation of a `mod-2` wire.
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13#[derive(Debug, Clone, Copy, PartialEq, Default)]
14pub struct WireMod2(U8x16);
15
16impl core::ops::Add for WireMod2 {
17    type Output = Self;
18
19    #[allow(clippy::suspicious_arithmetic_impl)]
20    fn add(self, rhs: Self) -> Self::Output {
21        Self(self.0 ^ rhs.0)
22    }
23}
24
25impl core::ops::AddAssign for WireMod2 {
26    #[allow(clippy::suspicious_op_assign_impl)]
27    fn add_assign(&mut self, rhs: Self) {
28        self.0 ^= rhs.0;
29    }
30}
31
32impl core::ops::Sub for WireMod2 {
33    type Output = Self;
34
35    fn sub(self, rhs: Self) -> Self::Output {
36        self + -rhs
37    }
38}
39
40impl core::ops::SubAssign for WireMod2 {
41    fn sub_assign(&mut self, rhs: Self) {
42        *self = *self - rhs;
43    }
44}
45
46impl core::ops::Neg for WireMod2 {
47    type Output = Self;
48
49    fn neg(self) -> Self::Output {
50        // Do nothing. Additive inverse is a no-op for mod 2.
51        self
52    }
53}
54
55impl core::ops::Mul<u16> for WireMod2 {
56    type Output = Self;
57
58    fn mul(self, rhs: u16) -> Self::Output {
59        if rhs == 0 {
60            Self(Default::default())
61        } else {
62            self
63        }
64    }
65}
66
67impl core::ops::MulAssign<u16> for WireMod2 {
68    fn mul_assign(&mut self, rhs: u16) {
69        if rhs == 0 {
70            self.0 = Default::default();
71        }
72    }
73}
74
75impl ConditionallySelectable for WireMod2 {
76    fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
77        WireMod2::from_repr(U8x16::conditional_select(
78            &a.to_repr(),
79            &b.to_repr(),
80            choice,
81        ))
82    }
83}
84
85impl WireLabel<F2> for WireMod2 {
86    fn rand_delta<R: CryptoRng>(rng: &mut R) -> Self {
87        let mut w = Self::rand(rng);
88        w.0 |= U8x16::set_lo(1);
89        w
90    }
91
92    fn to_repr(&self) -> U8x16 {
93        self.0
94    }
95
96    fn color(&self) -> u16 {
97        (self.0.extract::<0>() & 1) as u16
98    }
99
100    fn from_repr(repr: U8x16) -> Self {
101        Self(repr)
102    }
103
104    fn rand<R: CryptoRng>(rng: &mut R) -> Self {
105        Self(rng.random())
106    }
107
108    fn constant<RNG: CryptoRng>(x: F2, delta: Self, rng: &mut RNG) -> (Self, Self) {
109        let zero = Self::rand(rng);
110        let wire = zero + delta * x.into();
111        (zero, wire)
112    }
113}
114
115impl BinaryWireLabel for WireMod2 {
116    fn garble_and_gate(gate_num: usize, a: Self, b: Self, delta: Self) -> (U8x16, U8x16, Self) {
117        let a_color = (a.color() as u8).into();
118        let b_color = (b.color() as u8).into();
119        let j = tweak(gate_num as u64, 0);
120
121        let [a_hash, b_hash, a_plus_one_hash, b_plus_one_hash] =
122            hash_wires([&a, &b, &(a + delta), &(b + delta)], j);
123
124        let gate0 = U8x16::conditional_select(
125            &(a_hash ^ a_plus_one_hash),
126            &(a_hash ^ a_plus_one_hash ^ delta.to_repr()),
127            b_color,
128        );
129        let gate1 = b_hash ^ b_plus_one_hash ^ a.to_repr();
130
131        let zero = U8x16::conditional_select(&a_hash, &(a_hash ^ gate0), a_color)
132            ^ U8x16::conditional_select(&b_hash, &(b_hash ^ gate1 ^ a.to_repr()), b_color);
133
134        (gate0, gate1, Self::from_repr(zero))
135    }
136
137    fn evaluate_and_gate(gate_num: usize, a: Self, b: Self, gate0: U8x16, gate1: U8x16) -> Self {
138        let a_color = (a.color() as u8).into();
139        let b_color = (b.color() as u8).into();
140        let j = tweak(gate_num as u64, 0);
141
142        let [a_hash, b_hash] = hash_wires([&a, &b], j);
143
144        let left = U8x16::conditional_select(&a_hash, &(a_hash ^ gate0), a_color);
145        let right = U8x16::conditional_select(&b_hash, &(b_hash ^ gate1 ^ a.to_repr()), b_color);
146        Self::from_repr(left ^ right)
147    }
148}
149
150/// Compute a hash tweak from two counters.
151///
152/// We use `u64` for the counters here (instead of `u128`) to make it clear that
153/// we only support up to $`2^{64}`$ values for each counter.
154pub(crate) fn tweak(i: u64, j: u64) -> u128 {
155    (j as u128) << 64 | (i as u128)
156}
157
158/// Hash a batch of wires, using the same tweak for each wire.
159fn hash_wires<W: WireLabel<F2>, const N: usize>(wires: [&W; N], tweak: u128) -> [U8x16; N]
160where
161    ArrayUnrolledOps: UnrollableArraySize<N>,
162{
163    let batch = wires.array_map(|x| x.to_repr());
164    TweakableCircularCorrelationRobustHash::fixed_key().hash_many(batch, tweak)
165}
166
167#[cfg(test)]
168mod tests {
169    #[cfg(feature = "serde")]
170    #[test]
171    fn test_serialize_mod2() {
172        use crate::{WireLabel, WireMod2};
173        use rand::rng;
174
175        let mut rng = rng();
176        let w = WireMod2::rand(&mut rng);
177        let serialized = serde_json::to_string(&w).unwrap();
178
179        let deserialized: WireMod2 = serde_json::from_str(&serialized).unwrap();
180
181        assert_eq!(w, deserialized);
182    }
183}