Skip to main content

fancy_garbling/
classic.rs

1//! Provides objects and functions for statically garbling and evaluating a
2//! circuit without streaming.
3
4use crate::{
5    WireLabel,
6    garble::{Evaluator, Garbler},
7};
8use core::marker::PhantomData;
9use fancy_traits::{CircuitInputMapper, CircuitOutputMapper, FancyOutput};
10use rand::{CryptoRng, SeedableRng};
11use swanky_channel::Channel;
12use swanky_error::Result;
13use swanky_field_binary::F2;
14use vectoreyes::U8x16;
15
16/// A garbled circuit.
17///
18/// A garbled circuit at its core is just a vector of garbled rows and constant
19/// wirelabels.
20#[derive(Debug)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct GarbledCircuit<W> {
23    blocks: Vec<U8x16>,
24    phantom: PhantomData<W>,
25}
26
27impl<W: WireLabel<F2>> GarbledCircuit<W> {
28    /// Create a [`GarbledCircuit`] from a vector of garbled rows and constant
29    /// wirelabels.
30    pub fn new(blocks: Vec<U8x16>) -> Self {
31        GarbledCircuit {
32            blocks,
33            phantom: PhantomData,
34        }
35    }
36
37    /// The number of garbled rows and constant wires in the garbled circuit.
38    pub fn size(&self) -> usize {
39        self.blocks.len()
40    }
41
42    /// Garble a circuit.
43    ///
44    /// This outputs an [`Encoder`] for encoding inputs into their associated
45    /// wirelabels, and the garbled circuit itself.
46    pub fn garble<
47        C: CircuitInputMapper<Garbler<W, RNG>> + CircuitOutputMapper<Garbler<W, RNG>>,
48        RNG: CryptoRng + SeedableRng,
49    >(
50        circuit: &C,
51        rng: &mut RNG,
52    ) -> Result<(Encoder<W>, Self)> {
53        let mut garbler = Garbler::new(rng.fork());
54
55        // Produce zero wirelabels for the inputs.
56        let inputs = (0..circuit.ninputs())
57            .map(|_| garbler.encode_zero())
58            .collect::<Vec<_>>();
59
60        let mut channel = GarbledChannel::new_writer(None);
61        Channel::with(&mut channel, |channel| {
62            // First, garble the circuit.
63            let outputs = circuit.execute(&mut garbler, circuit.map(inputs.clone()), channel)?;
64            // Next, output the circuit outputs.
65            garbler.outputs(&C::flatten(outputs), channel)?;
66            Ok(())
67        })?;
68        let en = Encoder::new(inputs, garbler.delta());
69        let gc = GarbledCircuit::new(channel.finish_writing());
70        Ok((en, gc))
71    }
72
73    /// Evaluate the garbled circuit on the provided inputs, mapping the output
74    /// wirelabels to their associated values.
75    pub fn eval<C: CircuitOutputMapper<Evaluator<W>>>(
76        &self,
77        circuit: &C,
78        inputs: C::Input,
79    ) -> Result<Vec<F2>> {
80        let mut evaluator = Evaluator::new();
81        Channel::with(GarbledChannel::from(self.blocks.as_slice()), |channel| {
82            let outputs = circuit.execute(&mut evaluator, inputs, channel)?;
83            evaluator
84                .outputs(&C::flatten(outputs), channel)
85                .transpose()
86                .expect("`Evaluator` should never output `None`")
87        })
88    }
89}
90
91/// Encoder for input wirelabels.
92#[derive(Debug)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94pub struct Encoder<W> {
95    inputs: Vec<W>,
96    delta: W,
97}
98
99impl<W: WireLabel<F2>> Encoder<W> {
100    /// Make a new [`Encoder`] from a vector of zero wirelabels and the `Δ`
101    /// wirelabel.
102    fn new(inputs: Vec<W>, delta: W) -> Self {
103        Encoder { inputs, delta }
104    }
105
106    /// Encode input values into their associated wirelabels.
107    ///
108    /// # Panics
109    /// This panics if `inputs.len()` does not equal the expected number of
110    /// garbler inputs.
111    pub fn encode_inputs(&self, inputs: &[F2]) -> Vec<W> {
112        assert_eq!(inputs.len(), self.inputs.len());
113        self.inputs
114            .iter()
115            .zip(inputs)
116            .map(|(zero, x)| *zero + self.delta * (*x).into())
117            .collect()
118    }
119}
120
121/// Type for writing and reading a garbled circuit from memory.
122///
123/// A [`GarbledChannel`] provides a way to use the [`Channel`] interface to
124/// write a garbled circuit to memory, alongside the ability to read it from
125/// memory for evaluation.
126///
127/// A [`GarbledChannel`] can be instantiated in one of two ways: either by
128/// calling [`GarbledChannel::new_writer`] to store the garbled circuit in
129/// memory, or [`GarbledChannel::from`] on an existing [`GarbledCircuit`] to
130/// evaluate the garbled circuit.
131///
132/// Note that a [`GarbledChannel`] cannot be both a writer and a reader. For
133/// example, calling [`GarbledChannel::finish_writing`] on a [`GarbledChannel`]
134/// reader results in a panic.
135struct GarbledChannel {
136    reader: Option<GarbledReader>,
137    writer: Option<GarbledWriter>,
138}
139
140impl GarbledChannel {
141    /// Construct a new [`GarbledChannel`] for writing a garbled circuit.
142    fn new_writer(ngates: Option<usize>) -> Self {
143        Self {
144            reader: None,
145            writer: Some(GarbledWriter::new(ngates)),
146        }
147    }
148
149    /// Consume the [`GarbledChannel`], outputting the resulting garbled circuit.
150    ///
151    /// # Panics
152    /// Panics if there is no valid writer for the [`GarbledChannel`].
153    fn finish_writing(self) -> Vec<U8x16> {
154        self.writer.unwrap().finish()
155    }
156}
157
158impl std::io::Read for GarbledChannel {
159    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
160        let reader = self.reader.as_mut().unwrap();
161        reader.read(buf)
162    }
163}
164
165impl std::io::Write for GarbledChannel {
166    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
167        let writer = self.writer.as_mut().unwrap();
168        writer.write(buf)
169    }
170
171    fn flush(&mut self) -> std::io::Result<()> {
172        let writer = self.writer.as_mut().unwrap();
173        writer.flush()
174    }
175}
176
177impl From<&[U8x16]> for GarbledChannel {
178    fn from(value: &[U8x16]) -> Self {
179        Self {
180            reader: Some(GarbledReader::new(value)),
181            writer: None,
182        }
183    }
184}
185
186/// Implementation of the `Read` trait for use by the `Evaluator`.
187#[derive(Debug)]
188struct GarbledReader {
189    blocks: Vec<U8x16>,
190    index: usize,
191}
192
193impl GarbledReader {
194    fn new(blocks: &[U8x16]) -> Self {
195        Self {
196            blocks: blocks.to_vec(),
197            index: 0,
198        }
199    }
200}
201
202impl std::io::Read for GarbledReader {
203    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
204        assert_eq!(buf.len() % 16, 0);
205        let start = self.index;
206        for data in buf.chunks_mut(16) {
207            let block: [u8; 16] = self.blocks[self.index].into();
208            for (a, b) in data.iter_mut().zip(block.iter()) {
209                *a = *b;
210            }
211            self.index += 1;
212            if self.index == self.blocks.len() {
213                // We've read all that we can from the vector of `Block`s, so
214                // return the length of bytes that we've read to satisfy the
215                // `read` API.
216                return Ok(16 * (self.index - start));
217            }
218        }
219        Ok(buf.len())
220    }
221}
222
223/// Implementation of the `Write` trait for use by `Garbler`.
224#[derive(Debug)]
225struct GarbledWriter {
226    blocks: Vec<U8x16>,
227}
228
229impl GarbledWriter {
230    /// Make a new [`GarbledWriter`].
231    fn new(ngates: Option<usize>) -> Self {
232        let blocks = if let Some(n) = ngates {
233            Vec::with_capacity(2 * n)
234        } else {
235            Vec::new()
236        };
237        Self { blocks }
238    }
239
240    /// Consume the [`GarbledWriter`], outputting the resulting garbled circuit.
241    fn finish(self) -> Vec<U8x16> {
242        self.blocks
243    }
244}
245
246impl std::io::Write for GarbledWriter {
247    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
248        for item in buf.chunks(16) {
249            let bytes: [u8; 16] = match item.try_into() {
250                Ok(bytes) => bytes,
251                Err(_) => {
252                    return Err(std::io::Error::new(
253                        std::io::ErrorKind::InvalidData,
254                        "unable to map bytes to block",
255                    ));
256                }
257            };
258            self.blocks.push(bytes.into());
259        }
260        Ok(buf.len())
261    }
262    fn flush(&mut self) -> std::io::Result<()> {
263        Ok(())
264    }
265}