forked from filecoin-project/bellperson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc.rs
452 lines (377 loc) · 13.1 KB
/
lc.rs
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use std::ops::{Add, Sub};
use ff::PrimeField;
use crate::multiexp::DensityTracker;
/// Represents a variable in our constraint system.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Variable(pub Index);
impl Variable {
/// This constructs a variable with an arbitrary index.
/// Circuit implementations are not recommended to use this.
pub fn new_unchecked(idx: Index) -> Variable {
Variable(idx)
}
/// This returns the index underlying the variable.
/// Circuit implementations are not recommended to use this.
pub fn get_unchecked(&self) -> Index {
self.0
}
}
/// Represents the index of either an input variable or
/// auxiliary variable.
#[derive(Copy, Clone, PartialEq, Debug, Eq, Hash)]
pub enum Index {
Input(usize),
Aux(usize),
}
/// This represents a linear combination of some variables, with coefficients
/// in the scalar field of a pairing-friendly elliptic curve group.
#[derive(Clone, Debug, PartialEq)]
pub struct LinearCombination<Scalar: PrimeField> {
inputs: Indexer<Scalar>,
aux: Indexer<Scalar>,
}
#[derive(Clone, Debug, PartialEq)]
struct Indexer<T> {
/// Stores a list of `T` indexed by the number in the first slot of the tuple.
values: Vec<(usize, T)>,
/// `(index, key)` of the last insertion operation. Used to optimize consecutive operations
last_inserted: Option<(usize, usize)>,
}
impl<T> Default for Indexer<T> {
fn default() -> Self {
Indexer {
values: Vec::new(),
last_inserted: None,
}
}
}
impl<T> Indexer<T> {
pub fn from_value(index: usize, value: T) -> Self {
Indexer {
values: vec![(index, value)],
last_inserted: Some((0, index)),
}
}
pub fn iter(&self) -> impl Iterator<Item = (&usize, &T)> + '_ {
self.values.iter().map(|(key, value)| (key, value))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&mut usize, &mut T)> + '_ {
self.values.iter_mut().map(|(key, value)| (key, value))
}
pub fn insert_or_update<F, G>(&mut self, key: usize, insert: F, update: G)
where
F: FnOnce() -> T,
G: FnOnce(&mut T),
{
if let Some((last_index, last_key)) = self.last_inserted {
// Optimization to avoid doing binary search on inserts & updates that are linear, meaning
// they are adding a consecutive values.
if last_key == key {
// update the same key again
update(&mut self.values[last_index].1);
return;
} else if last_key + 1 == key {
// optimization for follow on updates
let i = last_index + 1;
if i >= self.values.len() {
// insert at the end
self.values.push((key, insert()));
self.last_inserted = Some((i, key));
} else if self.values[i].0 == key {
// update
update(&mut self.values[i].1);
} else {
// insert
self.values.insert(i, (key, insert()));
self.last_inserted = Some((i, key));
}
return;
}
}
match self.values.binary_search_by_key(&key, |(k, _)| *k) {
Ok(i) => {
update(&mut self.values[i].1);
}
Err(i) => {
self.values.insert(i, (key, insert()));
self.last_inserted = Some((i, key));
}
}
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
}
impl<Scalar: PrimeField> Default for LinearCombination<Scalar> {
fn default() -> Self {
Self::zero()
}
}
impl<Scalar: PrimeField> LinearCombination<Scalar> {
pub fn zero() -> LinearCombination<Scalar> {
LinearCombination {
inputs: Default::default(),
aux: Default::default(),
}
}
pub fn from_coeff(var: Variable, coeff: Scalar) -> Self {
match var {
Variable(Index::Input(i)) => Self {
inputs: Indexer::from_value(i, coeff),
aux: Default::default(),
},
Variable(Index::Aux(i)) => Self {
inputs: Default::default(),
aux: Indexer::from_value(i, coeff),
},
}
}
pub fn from_variable(var: Variable) -> Self {
Self::from_coeff(var, Scalar::one())
}
pub fn iter(&self) -> impl Iterator<Item = (Variable, &Scalar)> + '_ {
self.inputs
.iter()
.map(|(k, v)| (Variable(Index::Input(*k)), v))
.chain(self.aux.iter().map(|(k, v)| (Variable(Index::Aux(*k)), v)))
}
#[inline]
pub fn iter_inputs(&self) -> impl Iterator<Item = (&usize, &Scalar)> + '_ {
self.inputs.iter()
}
#[inline]
pub fn iter_aux(&self) -> impl Iterator<Item = (&usize, &Scalar)> + '_ {
self.aux.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (Variable, &mut Scalar)> + '_ {
self.inputs
.iter_mut()
.map(|(k, v)| (Variable(Index::Input(*k)), v))
.chain(
self.aux
.iter_mut()
.map(|(k, v)| (Variable(Index::Aux(*k)), v)),
)
}
#[inline]
fn add_assign_unsimplified_input(&mut self, new_var: usize, coeff: Scalar) {
self.inputs
.insert_or_update(new_var, || coeff, |val| *val += coeff);
}
#[inline]
fn add_assign_unsimplified_aux(&mut self, new_var: usize, coeff: Scalar) {
self.aux
.insert_or_update(new_var, || coeff, |val| *val += coeff);
}
pub fn add_unsimplified(
mut self,
(coeff, var): (Scalar, Variable),
) -> LinearCombination<Scalar> {
match var.0 {
Index::Input(new_var) => {
self.add_assign_unsimplified_input(new_var, coeff);
}
Index::Aux(new_var) => {
self.add_assign_unsimplified_aux(new_var, coeff);
}
}
self
}
#[inline]
fn sub_assign_unsimplified_input(&mut self, new_var: usize, coeff: Scalar) {
self.add_assign_unsimplified_input(new_var, -coeff);
}
#[inline]
fn sub_assign_unsimplified_aux(&mut self, new_var: usize, coeff: Scalar) {
self.add_assign_unsimplified_aux(new_var, -coeff);
}
pub fn sub_unsimplified(
mut self,
(coeff, var): (Scalar, Variable),
) -> LinearCombination<Scalar> {
match var.0 {
Index::Input(new_var) => {
self.sub_assign_unsimplified_input(new_var, coeff);
}
Index::Aux(new_var) => {
self.sub_assign_unsimplified_aux(new_var, coeff);
}
}
self
}
pub fn len(&self) -> usize {
self.inputs.len() + self.aux.len()
}
pub fn is_empty(&self) -> bool {
self.inputs.is_empty() && self.aux.is_empty()
}
pub fn eval(
&self,
mut input_density: Option<&mut DensityTracker>,
mut aux_density: Option<&mut DensityTracker>,
input_assignment: &[Scalar],
aux_assignment: &[Scalar],
) -> Scalar {
let mut acc = Scalar::zero();
let one = Scalar::one();
for (index, coeff) in self.iter_inputs() {
let mut tmp = input_assignment[*index];
if coeff == &one {
acc += tmp;
} else {
tmp *= coeff;
acc += tmp;
}
if let Some(ref mut v) = input_density {
v.inc(*index);
}
}
for (index, coeff) in self.iter_aux() {
let mut tmp = aux_assignment[*index];
if coeff == &one {
acc += tmp;
} else {
tmp *= coeff;
acc += tmp;
}
if let Some(ref mut v) = aux_density {
v.inc(*index);
}
}
acc
}
}
impl<Scalar: PrimeField> Add<(Scalar, Variable)> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
fn add(self, (coeff, var): (Scalar, Variable)) -> LinearCombination<Scalar> {
self.add_unsimplified((coeff, var))
}
}
impl<Scalar: PrimeField> Sub<(Scalar, Variable)> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
#[allow(clippy::suspicious_arithmetic_impl)]
fn sub(self, (coeff, var): (Scalar, Variable)) -> LinearCombination<Scalar> {
self.sub_unsimplified((coeff, var))
}
}
impl<Scalar: PrimeField> Add<Variable> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
fn add(self, other: Variable) -> LinearCombination<Scalar> {
self + (Scalar::one(), other)
}
}
impl<Scalar: PrimeField> Sub<Variable> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
fn sub(self, other: Variable) -> LinearCombination<Scalar> {
self - (Scalar::one(), other)
}
}
impl<'a, Scalar: PrimeField> Add<&'a LinearCombination<Scalar>> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
fn add(mut self, other: &'a LinearCombination<Scalar>) -> LinearCombination<Scalar> {
for (var, val) in other.inputs.iter() {
self.add_assign_unsimplified_input(*var, *val);
}
for (var, val) in other.aux.iter() {
self.add_assign_unsimplified_aux(*var, *val);
}
self
}
}
impl<'a, Scalar: PrimeField> Sub<&'a LinearCombination<Scalar>> for LinearCombination<Scalar> {
type Output = LinearCombination<Scalar>;
fn sub(mut self, other: &'a LinearCombination<Scalar>) -> LinearCombination<Scalar> {
for (var, val) in other.inputs.iter() {
self.sub_assign_unsimplified_input(*var, *val);
}
for (var, val) in other.aux.iter() {
self.sub_assign_unsimplified_aux(*var, *val);
}
self
}
}
impl<'a, Scalar: PrimeField> Add<(Scalar, &'a LinearCombination<Scalar>)>
for LinearCombination<Scalar>
{
type Output = LinearCombination<Scalar>;
fn add(
mut self,
(coeff, other): (Scalar, &'a LinearCombination<Scalar>),
) -> LinearCombination<Scalar> {
for (var, val) in other.inputs.iter() {
self.add_assign_unsimplified_input(*var, *val * coeff);
}
for (var, val) in other.aux.iter() {
self.add_assign_unsimplified_aux(*var, *val * coeff);
}
self
}
}
impl<'a, Scalar: PrimeField> Sub<(Scalar, &'a LinearCombination<Scalar>)>
for LinearCombination<Scalar>
{
type Output = LinearCombination<Scalar>;
fn sub(
mut self,
(coeff, other): (Scalar, &'a LinearCombination<Scalar>),
) -> LinearCombination<Scalar> {
for (var, val) in other.inputs.iter() {
self.sub_assign_unsimplified_input(*var, *val * coeff);
}
for (var, val) in other.aux.iter() {
self.sub_assign_unsimplified_aux(*var, *val * coeff);
}
self
}
}
#[cfg(all(test, feature = "groth16"))]
mod tests {
use super::*;
use blstrs::Scalar;
use ff::Field;
#[test]
fn test_add_simplify() {
let n = 5;
let mut lc = LinearCombination::<Scalar>::zero();
let mut expected_sums = vec![Scalar::zero(); n];
let mut total_additions = 0;
for (i, expected_sum) in expected_sums.iter_mut().enumerate() {
for _ in 0..i + 1 {
let coeff = Scalar::one();
lc = lc + (coeff, Variable::new_unchecked(Index::Aux(i)));
*expected_sum += coeff;
total_additions += 1;
}
}
// There are only as many terms as distinct variable Indexes — not one per addition operation.
assert_eq!(n, lc.len());
assert!(lc.len() != total_additions);
// Each variable has the expected coefficient, the sume of those added by its Index.
lc.iter().for_each(|(var, coeff)| match var.0 {
Index::Aux(i) => assert_eq!(expected_sums[i], *coeff),
_ => panic!("unexpected variable type"),
});
}
#[test]
fn test_insert_or_update() {
let mut indexer = Indexer::default();
let one = Scalar::one();
let mut two = one;
two += one;
indexer.insert_or_update(2, || one, |v| *v += one);
assert_eq!(&indexer.values, &[(2, one)]);
assert_eq!(&indexer.last_inserted, &Some((0, 2)));
indexer.insert_or_update(3, || one, |v| *v += one);
assert_eq!(&indexer.values, &[(2, one), (3, one)]);
assert_eq!(&indexer.last_inserted, &Some((1, 3)));
indexer.insert_or_update(1, || one, |v| *v += one);
assert_eq!(&indexer.values, &[(1, one), (2, one), (3, one)]);
assert_eq!(&indexer.last_inserted, &Some((0, 1)));
indexer.insert_or_update(2, || one, |v| *v += one);
assert_eq!(&indexer.values, &[(1, one), (2, two), (3, one)]);
assert_eq!(&indexer.last_inserted, &Some((0, 1)));
}
}