fancy_garbling/garble/
garbler.rs1use crate::{BinaryWireLabel, WireLabel, wire::mod2::tweak};
2use fancy_traits::{Fancy, FancyBinary, FancyConstant, FancyEncode, FancyOutput};
3use rand::CryptoRng;
4use swanky_channel::Channel;
5use swanky_error::Result;
6use swanky_field_binary::F2;
7use vectoreyes::U8x16;
8
9pub struct Garbler<W, RNG> {
14 zero: W,
16 delta: W,
17 current_gate: usize,
18 rng: RNG,
19}
20
21impl<W: WireLabel<F2>, RNG: CryptoRng> Garbler<W, RNG> {
22 pub fn new(mut rng: RNG) -> Self {
24 let delta = W::rand_delta(&mut rng);
25 let one = W::from_repr(U8x16::from(1u128));
28 let zero = delta + one;
29 Garbler {
30 zero,
31 delta,
32 current_gate: 0,
33 rng,
34 }
35 }
36
37 fn current_gate(&mut self) -> usize {
39 let current = self.current_gate;
40 self.current_gate += 1;
41 current
42 }
43
44 pub fn delta(&self) -> W {
46 self.delta
47 }
48
49 pub(crate) fn encode_zero(&mut self) -> W {
51 W::rand(&mut self.rng)
52 }
53}
54
55impl<W: WireLabel<F2>, RNG> Fancy for Garbler<W, RNG> {
56 type Item = W;
57}
58
59impl<W: BinaryWireLabel, RNG: CryptoRng> FancyBinary for Garbler<W, RNG> {
60 fn and(&mut self, x: &Self::Item, y: &Self::Item, channel: &mut Channel) -> Result<Self::Item> {
61 let gate_num = self.current_gate();
62 let (gate0, gate1, z) = W::garble_and_gate(gate_num, *x, *y, self.delta);
63 channel.write(&gate0)?;
64 channel.write(&gate1)?;
65 Ok(z)
66 }
67
68 fn xor(&mut self, x: &Self::Item, y: &Self::Item) -> Self::Item {
69 *x + *y
70 }
71
72 fn negate(&mut self, x: &Self::Item) -> Self::Item {
73 self.zero + *x
74 }
75}
76
77impl<W: WireLabel<F2>, RNG> FancyConstant<F2> for Garbler<W, RNG> {
78 fn constant(&mut self, x: F2) -> Self::Item {
79 if x.into() {
80 self.zero
83 } else {
84 Default::default()
86 }
87 }
88}
89
90impl<W: WireLabel<F2>, RNG: CryptoRng> FancyEncode<F2> for Garbler<W, RNG> {
91 fn encode_many(&mut self, values: &[F2], channel: &mut Channel) -> Result<Vec<Self::Item>> {
92 let mut zeros = Vec::with_capacity(values.len());
93 for x in values.iter() {
94 let zero = self.encode_zero();
95 let encoded = zero + self.delta * (*x).into();
96 channel.write(&encoded.to_repr())?;
97 zeros.push(zero);
98 }
99 Ok(zeros)
100 }
101}
102
103impl<W: WireLabel<F2>, RNG: CryptoRng> FancyOutput<F2> for Garbler<W, RNG> {
104 fn output(&mut self, x: &W, channel: &mut Channel) -> Result<Option<F2>> {
105 let i = self.current_gate() as u64;
106 let zero = (*x).hash(tweak(i, 0));
107 let one = (*x + self.delta()).hash(tweak(i, 1));
108 channel.write(&zero)?;
109 channel.write(&one)?;
110 Ok(None)
111 }
112}