fancy_garbling/
classic.rs1use 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#[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 pub fn new(blocks: Vec<U8x16>) -> Self {
31 GarbledCircuit {
32 blocks,
33 phantom: PhantomData,
34 }
35 }
36
37 pub fn size(&self) -> usize {
39 self.blocks.len()
40 }
41
42 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 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 let outputs = circuit.execute(&mut garbler, circuit.map(inputs.clone()), channel)?;
64 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 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#[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 fn new(inputs: Vec<W>, delta: W) -> Self {
103 Encoder { inputs, delta }
104 }
105
106 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
121struct GarbledChannel {
136 reader: Option<GarbledReader>,
137 writer: Option<GarbledWriter>,
138}
139
140impl GarbledChannel {
141 fn new_writer(ngates: Option<usize>) -> Self {
143 Self {
144 reader: None,
145 writer: Some(GarbledWriter::new(ngates)),
146 }
147 }
148
149 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#[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 return Ok(16 * (self.index - start));
217 }
218 }
219 Ok(buf.len())
220 }
221}
222
223#[derive(Debug)]
225struct GarbledWriter {
226 blocks: Vec<U8x16>,
227}
228
229impl GarbledWriter {
230 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 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}