1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use crate::{
core::{
actually_used_field::ActuallyUsedField,
circuits::boolean::{
boolean_value::BooleanValue,
utils::{addition_circuit, subtraction_circuit, CircuitType},
},
compile_passes::compilation_pass::LocalCompilationPass,
expressions::{
conversion_expr::{
ConversionExpr::{self, BitFromEdaBit, EdaBit, ScalarFromEdaBit},
EdaBitId,
},
expr::Expr,
},
global_value::{
global_expr_store::{with_global_expr_store_as_local, with_local_expr_store_as_global},
value::FieldValue,
},
ir::IntermediateRepresentation,
ir_builder::{ExprStore, IRBuilder},
},
traits::{GetBit, Reveal, Select},
utils::number::Number,
STATISTICAL_SECURITY_FACTOR,
};
use num_bigint::BigInt;
use rustc_hash::FxHashMap;
use std::marker::PhantomData;
/// Generate a new eda bit of specific size.
/// Returns the scalar component and the (reduced) boolean component of the eda bit.
/// If size == F::NUM_BITS and reduced == true we also return
/// - the bits of eda - F::modulus() as a signed (F::NUM_BITS + 1)-bit integer
/// - the bits of eda + (F::modulus()-1)/2 as a unsigned (F::NUM_BITS + 1)-bit integer
/// - the bits of eda - (F::modulus()+1)/2 as a signed (F::NUM_BITS + 1)-bit integer.
///
/// Note:
/// - If size < F::NUM_BITS then the binary expansion of the eda bit is reduced.
/// - If size == F::NUM_BITS then one can choose whether to reduce or not.
/// - If size > F::NUM_BITS we only support unreduced expansion.
#[allow(clippy::type_complexity)]
pub fn new_eda_bit<F: ActuallyUsedField>(
size: usize,
reduced: bool,
) -> (
FieldValue<F>,
Vec<BooleanValue>,
Vec<BooleanValue>,
Vec<BooleanValue>,
Vec<BooleanValue>,
) {
assert!(
size <= F::NUM_BITS as usize || !reduced,
"Reduced eda bit for size {size} not supported."
);
let (eda_bit_scalar_id, eda_bit_bit_ids) = with_global_expr_store_as_local(|expr_store| {
let eda_bit_expr_id =
expr_store.push_conversion(EdaBit(EdaBitId::new(), size, PhantomData::<F>));
let eda_bit_scalar_id =
expr_store.push_conversion(ScalarFromEdaBit::<F, usize>(eda_bit_expr_id));
let eda_bit_bit_ids = (0..size)
.map(|i| expr_store.push_conversion(BitFromEdaBit::<F, usize>(eda_bit_expr_id, i)))
.collect::<Vec<usize>>();
(eda_bit_scalar_id, eda_bit_bit_ids)
});
let eda_bit_scalar = FieldValue::<F>::from_id(eda_bit_scalar_id);
let mut eda_bit_bits = eda_bit_bit_ids
.into_iter()
.map(BooleanValue::new)
.collect::<Vec<BooleanValue>>();
// eda - p
let mut eda_bit_minus_modulus_bits = vec![BooleanValue::from(false); eda_bit_bits.len() + 1];
// eda + (p-1)/2
let mut eda_bit_plus_offset_bits = vec![BooleanValue::from(false); eda_bit_bits.len() + 1];
// eda - p + (p-1)/2 = eda - (p+1)/2
let mut eda_bit_minus_modulus_plus_offset_bits =
vec![BooleanValue::from(false); eda_bit_bits.len() + 1];
if size == F::NUM_BITS as usize && reduced {
// Make sure eda_bit_bits represents a number strictly less than the modulus.
eda_bit_bits.push(BooleanValue::from(false));
let modulus = BigInt::from(F::modulus());
let modulus_bits = (0..eda_bit_bits.len())
.map(|i| {
BooleanValue::from((modulus.clone() >> i) & BigInt::from(1) == BigInt::from(1))
})
.collect::<Vec<BooleanValue>>();
let mut two_modulus_bits = modulus_bits.clone();
two_modulus_bits.rotate_right(1);
let eda_bit_minus_modulus =
subtraction_circuit(eda_bit_bits.clone(), modulus_bits, CircuitType::default());
// eda - 2p might not be correctly represented if eda is already reduced
let eda_bit_minus_two_modulus = subtraction_circuit(
eda_bit_bits.clone(),
two_modulus_bits,
CircuitType::default(),
);
let is_already_reduced = *eda_bit_minus_modulus.last().unwrap();
eda_bit_bits = is_already_reduced.select(eda_bit_bits, eda_bit_minus_modulus.clone());
eda_bit_minus_modulus_bits =
is_already_reduced.select(eda_bit_minus_modulus, eda_bit_minus_two_modulus);
// now compute eda + (p-1)/2 and eda - (p+1)/2
let offset = FieldValue::from(F::TWO_INV - F::ONE);
let offset_bits = (0..eda_bit_bits.len())
.map(|i| offset.get_bit(i, false))
.collect::<Vec<BooleanValue>>();
eda_bit_plus_offset_bits = addition_circuit(
eda_bit_bits.clone(),
offset_bits.clone(),
BooleanValue::from(false),
CircuitType::default(),
);
eda_bit_minus_modulus_plus_offset_bits = addition_circuit(
eda_bit_minus_modulus_bits.clone(),
offset_bits,
BooleanValue::from(false),
CircuitType::default(),
);
let _ = eda_bit_bits.pop();
}
(
eda_bit_scalar,
eda_bit_bits,
eda_bit_minus_modulus_bits,
eda_bit_plus_offset_bits,
eda_bit_minus_modulus_plus_offset_bits,
)
}
#[derive(Default)]
struct ConversionInfo {
bit_num_to_bit_to_expr_id: FxHashMap<(usize, usize, bool), usize>,
security_factor: usize, // constant
}
/// Introduces EdaBits (extended doubly authenticated bits),
/// in order to do the conversions from arithmetic to bool and inversely.
#[derive(Default)]
pub struct EdaBitIntroducer {
expr_store: IRBuilder,
conversion_info: ConversionInfo,
}
impl EdaBitIntroducer {
fn conversion_eda_bits<F: ActuallyUsedField>(
&mut self,
expr: ConversionExpr<F, usize>,
is_plaintext: bool,
) -> Expr<usize> {
use ConversionExpr::*;
match expr {
BitNumToBit(e, i, signed) if !self.expr_store.get_is_plaintext(e) => {
match self
.conversion_info
.bit_num_to_bit_to_expr_id
.get(&(e, i, signed))
{
Some(n) => self.expr_store.get_expr(*n).clone(),
None => {
// To convert a scalar x to binary, we:
// 1. Have an edaBit r, a random number whose unsigned decomposition can be
// accessed.
// 2. We compute and reveal s = x + r.
// 3. We compute a binary decomposition of s.
// 4. We compute s - r in binary.
with_local_expr_store_as_global(
|| {
let e_id = e;
let e = FieldValue::<F>::from_id(e_id);
let bounds = e.bounds();
let num_size = bounds.bin_size(signed);
if num_size > 0 {
// Maybe we already computed this.
if let Some(n) = self
.conversion_info
.bit_num_to_bit_to_expr_id
.get(&(e_id, num_size - 1, signed))
{
return if signed {
BooleanValue::new(*n).expr()
} else {
BooleanValue::from(false).expr()
};
}
}
let eda_bit_size = (num_size
+ self.conversion_info.security_factor)
.min(F::NUM_BITS as usize);
// could_underflow would work here as a name too.
// If there is overflow when we add eda_bit,
// then there will be underflow when we subtract it.
let could_overflow = Number::power_of_two(eda_bit_size)
+ Number::power_of_two(num_size)
>= F::modulus();
let (
eda_bit_scalar,
mut eda_bit_bits,
eda_bit_minus_modulus_bits,
eda_bit_plus_offset_bits,
eda_bit_minus_modulus_plus_offset_bits,
) = new_eda_bit::<F>(eda_bit_size, could_overflow);
let sum = e + eda_bit_scalar;
let mut revealed_sum = sum.reveal();
if could_overflow && signed {
// If it could overflow and it is signed,
// then we do an unsigned decomposition of x + (p-1)/2,
// from which we can extract a signed decomposition of x.
let offset = FieldValue::from(F::TWO_INV - F::ONE);
revealed_sum += offset;
}
let used_num_size = if could_overflow {
F::NUM_BITS as usize
} else {
num_size
};
eda_bit_bits = eda_bit_bits
.into_iter()
.take(used_num_size)
.collect::<Vec<BooleanValue>>();
let mut revealed_sum_bits = (0..used_num_size)
.map(|i| {
revealed_sum.get_bit(
i,
// With signed decomposition, it is hard to handle
// underflow.
// So we only do signed decomposition when no
// underflow.
(!could_overflow) && signed,
)
})
.collect::<Vec<BooleanValue>>();
let sub_bits = if could_overflow {
revealed_sum_bits.push(BooleanValue::from(false));
eda_bit_bits.push(BooleanValue::from(false));
debug_assert!(
eda_bit_bits.len() == eda_bit_minus_modulus_bits.len()
);
// sum - eda
// if sub_bits1 is non-negative it is the expansion of
// x + (p-1)/2 mod p if signed
// x otherwise
let mut sub_bits1 = subtraction_circuit(
revealed_sum_bits.clone(),
eda_bit_bits,
CircuitType::default(),
);
let has_sum_overflowed = sub_bits1.pop().unwrap();
if signed {
// sum - (eda + (p-1)/2)
let mut sub_bits2 = subtraction_circuit(
revealed_sum_bits.clone(),
eda_bit_plus_offset_bits,
CircuitType::default(),
);
let _ = sub_bits2.pop();
// sum - (eda - (p+1)/2)
let mut sub_bits3 = subtraction_circuit(
revealed_sum_bits,
eda_bit_minus_modulus_plus_offset_bits,
CircuitType::default(),
);
let _ = sub_bits3.pop();
// The correct signed decomposition of x is either
// sub_bits2 or sub_bits3 depending on whether sum has
// overflowed or not.
has_sum_overflowed.select(sub_bits3, sub_bits2)
} else {
// sum - (eda - p)
let mut sub_bits2 = subtraction_circuit(
revealed_sum_bits,
eda_bit_minus_modulus_bits,
CircuitType::default(),
);
let _ = sub_bits2.pop();
// The correct unsigned decomposition of x is either
// sub_bits1 or sub_bits2 depending on whether sum has
// overflowed or not.
has_sum_overflowed.select(sub_bits2, sub_bits1)
}
} else {
subtraction_circuit(
revealed_sum_bits,
eda_bit_bits,
CircuitType::default(),
)
};
sub_bits[0..num_size]
.iter()
.enumerate()
.for_each(|(i, bit)| {
self.conversion_info
.bit_num_to_bit_to_expr_id
.insert((e_id, i, signed), bit.get_id());
});
if signed {
sub_bits[i.min(num_size - 1)].expr()
} else if i >= num_size {
BooleanValue::from(false).expr()
} else {
sub_bits[i].expr()
}
},
&mut self.expr_store,
)
}
}
}
BitToBitNum(v, signed) => {
let n = v.len();
let are_bits_revealed = is_plaintext && n < F::NUM_BITS as usize;
with_local_expr_store_as_global(
|| {
let mut res = FieldValue::<F>::from(0);
v.into_iter()
.map(BooleanValue::new)
.enumerate()
.for_each(|(i, bit)| {
let c = if signed && i + 1 == n {
FieldValue::from(F::negative_power_of_two(i))
} else {
FieldValue::from(F::power_of_two(i))
};
if bit.is_plaintext() {
res += c * FieldValue::<F>::from(bit)
} else if are_bits_revealed {
res += c * FieldValue::<F>::from(bit.reveal())
} else {
let (eda_bit_scalar, eda_bit_bits, _, _, _) =
new_eda_bit::<F>(1, false);
let eda_bit_bit = eda_bit_bits[0];
let xor = bit ^ eda_bit_bit;
let revealed = xor.reveal();
let revealed_scalar = FieldValue::<F>::from(revealed);
let prod = revealed_scalar * eda_bit_scalar;
let scalar_xor = eda_bit_scalar + revealed_scalar
- FieldValue::<F>::from(2) * prod;
res += c * scalar_xor
}
});
res.expr()
},
&mut self.expr_store,
)
}
_ => F::conversion_expr_to_expr(expr),
}
}
}
impl LocalCompilationPass for EdaBitIntroducer {
fn expr_store(&mut self) -> &mut IRBuilder {
&mut self.expr_store
}
fn setup(&mut self, _old_ir: &IntermediateRepresentation) {
self.conversion_info.security_factor = STATISTICAL_SECURITY_FACTOR;
}
fn transform(&mut self, expr: Expr<usize>, is_plaintext: bool) -> Expr<usize> {
match expr {
Expr::ScalarConversion(e) => self.conversion_eda_bits(e, is_plaintext),
Expr::BaseConversion(e) => self.conversion_eda_bits(e, is_plaintext),
_ => expr,
}
}
}