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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
#![allow(clippy::suspicious_arithmetic_impl)]
#![cfg_attr(target_arch = "aarch64", feature(stdsimd))]
#[cfg(all(feature = "pairing", feature = "blst"))]
compile_error!("pairing and blst features are mutually exclusive. Running with --no-default-features might help.");
#[cfg(test)]
#[macro_use]
extern crate hex_literal;
pub mod bls;
pub mod domain;
pub mod gadgets;
pub mod gpu;
#[cfg(feature = "groth16")]
pub mod groth16;
pub mod multicore;
pub mod multiexp;
pub mod util_cs;
use ff::{Field, ScalarEngine};
use rustc_hash::FxHashMap as HashMap;
use std::io;
use std::marker::PhantomData;
use std::ops::{Add, Sub};
const BELLMAN_VERSION: &str = env!("CARGO_PKG_VERSION");
pub trait Circuit<E: ScalarEngine> {
fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError>;
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Variable(Index);
impl Variable {
pub fn new_unchecked(idx: Index) -> Variable {
Variable(idx)
}
pub fn get_unchecked(&self) -> Index {
self.0
}
}
#[derive(Copy, Clone, PartialEq, Debug, Eq, Hash)]
pub enum Index {
Input(usize),
Aux(usize),
}
#[derive(Clone)]
pub struct LinearCombination<E: ScalarEngine>(HashMap<Variable, E::Fr>);
impl<E: ScalarEngine> Default for LinearCombination<E> {
fn default() -> Self {
Self::zero()
}
}
impl<E: ScalarEngine> LinearCombination<E> {
pub fn zero() -> LinearCombination<E> {
LinearCombination(HashMap::default())
}
pub fn iter(&self) -> impl Iterator<Item = (&Variable, &E::Fr)> + '_ {
self.0.iter()
}
pub fn add_unsimplified(mut self, (coeff, var): (E::Fr, Variable)) -> LinearCombination<E> {
self.0
.entry(var)
.or_insert_with(E::Fr::zero)
.add_assign(&coeff);
self
}
}
impl<E: ScalarEngine> Add<(E::Fr, Variable)> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn add(mut self, (coeff, var): (E::Fr, Variable)) -> LinearCombination<E> {
self.0
.entry(var)
.or_insert_with(E::Fr::zero)
.add_assign(&coeff);
self
}
}
impl<E: ScalarEngine> Sub<(E::Fr, Variable)> for LinearCombination<E> {
type Output = LinearCombination<E>;
#[allow(clippy::suspicious_arithmetic_impl)]
fn sub(self, (mut coeff, var): (E::Fr, Variable)) -> LinearCombination<E> {
coeff.negate();
self + (coeff, var)
}
}
impl<E: ScalarEngine> Add<Variable> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn add(self, other: Variable) -> LinearCombination<E> {
self + (E::Fr::one(), other)
}
}
impl<E: ScalarEngine> Sub<Variable> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn sub(self, other: Variable) -> LinearCombination<E> {
self - (E::Fr::one(), other)
}
}
impl<'a, E: ScalarEngine> Add<&'a LinearCombination<E>> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn add(mut self, other: &'a LinearCombination<E>) -> LinearCombination<E> {
for (var, val) in &other.0 {
self.0
.entry(*var)
.or_insert_with(E::Fr::zero)
.add_assign(val);
}
self
}
}
impl<'a, E: ScalarEngine> Sub<&'a LinearCombination<E>> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn sub(mut self, other: &'a LinearCombination<E>) -> LinearCombination<E> {
for (var, val) in &other.0 {
self = self - (*val, *var);
}
self
}
}
impl<'a, E: ScalarEngine> Add<(E::Fr, &'a LinearCombination<E>)> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn add(mut self, (coeff, other): (E::Fr, &'a LinearCombination<E>)) -> LinearCombination<E> {
for s in &other.0 {
let mut tmp = *s.1;
tmp.mul_assign(&coeff);
self = self + (tmp, *s.0);
}
self
}
}
impl<'a, E: ScalarEngine> Sub<(E::Fr, &'a LinearCombination<E>)> for LinearCombination<E> {
type Output = LinearCombination<E>;
fn sub(mut self, (coeff, other): (E::Fr, &'a LinearCombination<E>)) -> LinearCombination<E> {
for s in &other.0 {
let mut tmp = *s.1;
tmp.mul_assign(&coeff);
self = self - (tmp, *s.0);
}
self
}
}
#[allow(clippy::upper_case_acronyms)]
#[derive(thiserror::Error, Debug)]
pub enum SynthesisError {
#[error("an assignment for a variable could not be computed")]
AssignmentMissing,
#[error("division by zero")]
DivisionByZero,
#[error("unsatisfiable constraint system")]
Unsatisfiable,
#[error("polynomial degree is too large")]
PolynomialDegreeTooLarge,
#[error("encountered an identity element in the CRS")]
UnexpectedIdentity,
#[error("encountered an I/O error: {0}")]
IoError(#[from] io::Error),
#[error("malformed verifying key")]
MalformedVerifyingKey,
#[error("auxiliary variable was unconstrained")]
UnconstrainedVariable,
#[error("encountered a GPU error: {0}")]
GPUError(#[from] gpu::GPUError),
#[error("attempted to aggregate malformed proofs: {0}")]
MalformedProofs(String),
#[error("malformed SRS")]
MalformedSrs,
#[error("non power of two proofs given for aggregation")]
NonPowerOfTwo,
#[error("incompatible vector length: {0}")]
IncompatibleLengthVector(String),
#[error("invalid pairing")]
InvalidPairing,
}
pub trait ConstraintSystem<E: ScalarEngine>: Sized + Send {
type Root: ConstraintSystem<E>;
fn new() -> Self {
unimplemented!(
"ConstraintSystem::new must be implemented for extensible types implementing ConstraintSystem"
);
}
fn one() -> Variable {
Variable::new_unchecked(Index::Input(0))
}
fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>;
fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>;
fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC)
where
A: FnOnce() -> AR,
AR: Into<String>,
LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>;
fn push_namespace<NR, N>(&mut self, name_fn: N)
where
NR: Into<String>,
N: FnOnce() -> NR;
fn pop_namespace(&mut self);
fn get_root(&mut self) -> &mut Self::Root;
fn namespace<NR, N>(&mut self, name_fn: N) -> Namespace<'_, E, Self::Root>
where
NR: Into<String>,
N: FnOnce() -> NR,
{
self.get_root().push_namespace(name_fn);
Namespace(self.get_root(), Default::default())
}
fn is_extensible() -> bool {
false
}
fn extend(&mut self, _other: Self) {
unimplemented!(
"ConstraintSystem::extend must be implemented for types implementing ConstraintSystem"
);
}
}
pub struct Namespace<'a, E: ScalarEngine, CS: ConstraintSystem<E>>(&'a mut CS, SendMarker<E>);
struct SendMarker<E: ScalarEngine>(PhantomData<E>);
impl<E: ScalarEngine> Default for SendMarker<E> {
fn default() -> Self {
Self(PhantomData)
}
}
unsafe impl<E: ScalarEngine> Send for SendMarker<E> {}
impl<'cs, E: ScalarEngine, CS: ConstraintSystem<E>> ConstraintSystem<E> for Namespace<'cs, E, CS> {
type Root = CS::Root;
fn one() -> Variable {
CS::one()
}
fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
self.0.alloc(annotation, f)
}
fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
self.0.alloc_input(annotation, f)
}
fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC)
where
A: FnOnce() -> AR,
AR: Into<String>,
LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
{
self.0.enforce(annotation, a, b, c)
}
fn push_namespace<NR, N>(&mut self, _: N)
where
NR: Into<String>,
N: FnOnce() -> NR,
{
panic!("only the root's push_namespace should be called");
}
fn pop_namespace(&mut self) {
panic!("only the root's pop_namespace should be called");
}
fn get_root(&mut self) -> &mut Self::Root {
self.0.get_root()
}
}
impl<'a, E: ScalarEngine, CS: ConstraintSystem<E>> Drop for Namespace<'a, E, CS> {
fn drop(&mut self) {
self.get_root().pop_namespace()
}
}
impl<'cs, E: ScalarEngine, CS: ConstraintSystem<E>> ConstraintSystem<E> for &'cs mut CS {
type Root = CS::Root;
fn one() -> Variable {
CS::one()
}
fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
(**self).alloc(annotation, f)
}
fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<E::Fr, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
(**self).alloc_input(annotation, f)
}
fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC)
where
A: FnOnce() -> AR,
AR: Into<String>,
LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
{
(**self).enforce(annotation, a, b, c)
}
fn push_namespace<NR, N>(&mut self, name_fn: N)
where
NR: Into<String>,
N: FnOnce() -> NR,
{
(**self).push_namespace(name_fn)
}
fn pop_namespace(&mut self) {
(**self).pop_namespace()
}
fn get_root(&mut self) -> &mut Self::Root {
(**self).get_root()
}
}
#[cfg(all(test, feature = "groth16"))]
mod tests {
use super::*;
#[test]
fn test_add_simplify() {
use crate::bls::Bls12;
let n = 5;
let mut lc = LinearCombination::<Bls12>::zero();
let mut expected_sums = vec![<Bls12 as ScalarEngine>::Fr::zero(); n];
let mut total_additions = 0;
for (i, expected_sum) in expected_sums.iter_mut().enumerate() {
for _ in 0..i + 1 {
let coeff = <Bls12 as ScalarEngine>::Fr::one();
lc = lc + (coeff, Variable::new_unchecked(Index::Aux(i)));
expected_sum.add_assign(&coeff);
total_additions += 1;
}
}
assert_eq!(n, lc.0.len());
assert!(lc.0.len() != total_additions);
lc.0.iter().for_each(|(var, coeff)| match var.0 {
Index::Aux(i) => assert_eq!(expected_sums[i], *coeff),
_ => panic!("unexpected variable type"),
});
}
}