fancy_garbling/garble/
evaluator.rs1use crate::{BinaryWireLabel, util::output_tweak, wire::WireLabel};
2use fancy_traits::{Fancy, FancyBinary, FancyConstant, FancyOutput, FancyReceive};
3use swanky_channel::Channel;
4use swanky_error::ErrorKind;
5use swanky_field_binary::F2;
6use vectoreyes::U8x16;
7
8pub struct Evaluator<Wire> {
13 one: Wire,
14 current_gate: usize,
15 current_output: usize,
16}
17
18impl<Wire: WireLabel<F2>> Evaluator<Wire> {
19 pub fn new() -> Self {
21 let one = Wire::from_repr(U8x16::from(1u128));
23 Evaluator {
24 one,
25 current_gate: 0,
26 current_output: 0,
27 }
28 }
29
30 fn current_gate(&mut self) -> usize {
32 let current = self.current_gate;
33 self.current_gate += 1;
34 current
35 }
36
37 fn current_output(&mut self) -> usize {
39 let current = self.current_output;
40 self.current_output += 1;
41 current
42 }
43}
44
45impl<Wire: WireLabel<F2>> Default for Evaluator<Wire> {
46 fn default() -> Self {
47 Self::new()
48 }
49}
50
51impl<W: BinaryWireLabel> FancyBinary for Evaluator<W> {
52 fn negate(&mut self, x: &Self::Item) -> Self::Item {
53 *x + self.one
54 }
55
56 fn xor(&mut self, x: &Self::Item, y: &Self::Item) -> Self::Item {
57 *x + *y
58 }
59
60 fn and(
61 &mut self,
62 A: &Self::Item,
63 B: &Self::Item,
64 channel: &mut Channel,
65 ) -> swanky_error::Result<Self::Item> {
66 let gate_num = self.current_gate();
67 let gate0 = channel.read()?;
68 let gate1 = channel.read()?;
69 Ok(W::evaluate_and_gate(gate_num, A, B, &gate0, &gate1))
70 }
71}
72
73impl<Wire: WireLabel<F2>> Fancy for Evaluator<Wire> {
74 type Item = Wire;
75}
76
77impl<Wire: WireLabel<F2>> FancyConstant<F2> for Evaluator<Wire> {
78 fn constant(&mut self, x: F2) -> Self::Item {
79 if x.into() {
80 self.one
81 } else {
82 Default::default()
84 }
85 }
86}
87
88impl<Wire: WireLabel<F2>> FancyReceive<F2> for Evaluator<Wire> {
89 fn receive_many(
90 &mut self,
91 n: usize,
92 channel: &mut Channel,
93 ) -> swanky_error::Result<Vec<Self::Item>> {
94 (0..n)
95 .map(|_| {
96 let block = channel.read()?;
97 Ok(Wire::from_repr(block))
98 })
99 .collect()
100 }
101}
102
103impl<Wire: WireLabel<F2>> FancyOutput<F2> for Evaluator<Wire> {
104 fn output(&mut self, x: &Wire, channel: &mut Channel) -> swanky_error::Result<Option<F2>> {
105 let i = self.current_output();
106
107 let mut ct = Vec::with_capacity(2);
109 for _ in 0..2 {
110 let block = channel.read()?;
111 ct.push(block);
112 }
113
114 let mut decoded = None;
116 for k in 0..2 {
117 let hashed_wire = x.hash(output_tweak(i, k));
118 if hashed_wire == ct[k as usize] {
119 decoded = Some(k);
120 break;
121 }
122 }
123
124 if let Some(output) = decoded {
125 Ok(Some(F2::from(output != 0)))
126 } else {
127 swanky_error::bail!(ErrorKind::OtherError, "Decoding failed");
128 }
129 }
130}