-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmerkle_tree.rs
803 lines (697 loc) · 21.7 KB
/
merkle_tree.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
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
// This file is part of Webb and was adapted from Arkworks.
//
// Copyright (C) 2021 Webb Technologies Inc.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A Plonk gadget implementation of the Sparse Merkle Tree data structure.
//! For more info on the Sparse Merkle Tree data structure, see the
//! documentation for our native implementation.
//!
//! ## Usage
//!
//! In this example we build a plonk circuit with a Sparse Merkle Tree.
//!
//! ```rust
//! use ark_bn254::{Bn254, Fr as Bn254Fr};
//! use ark_ec::TEModelParameters;
//! use ark_ed_on_bn254::{EdwardsParameters as JubjubParameters, Fq};
//! use ark_ff::PrimeField;
//! use ark_std::{test_rng, UniformRand};
//! use arkworks_native_gadgets::{
//! merkle_tree::SparseMerkleTree,
//! poseidon::{sbox::PoseidonSbox, Poseidon, PoseidonParameters},
//! };
//! use arkworks_plonk_gadgets::{
//! merkle_tree::PathGadget,
//! poseidon::{FieldHasherGadget, PoseidonGadget},
//! };
//! use arkworks_utils::{
//! bytes_matrix_to_f, bytes_vec_to_f, poseidon_params::setup_poseidon_params, Curve,
//! };
//! use plonk_core::prelude::*;
//!
//! type PoseidonBn254 = Poseidon<Fq>;
//!
//! pub fn setup_params<F: PrimeField>(curve: Curve, exp: i8, width: u8) -> PoseidonParameters<F> {
//! let pos_data = setup_poseidon_params(curve, exp, width).unwrap();
//!
//! let mds_f = bytes_matrix_to_f(&pos_data.mds);
//! let rounds_f = bytes_vec_to_f(&pos_data.rounds);
//!
//! let pos = PoseidonParameters {
//! mds_matrix: mds_f,
//! round_keys: rounds_f,
//! full_rounds: pos_data.full_rounds,
//! partial_rounds: pos_data.partial_rounds,
//! sbox: PoseidonSbox(pos_data.exp),
//! width: pos_data.width,
//! };
//!
//! pos
//! }
//!
//! struct TestCircuit<
//! 'a,
//! F: PrimeField,
//! P: TEModelParameters<BaseField = F>,
//! HG: FieldHasherGadget<F, P>,
//! const N: usize,
//! > {
//! leaves: &'a [F],
//! empty_leaf: &'a [u8],
//! hasher: &'a HG::Native,
//! }
//!
//! impl<
//! F: PrimeField,
//! P: TEModelParameters<BaseField = F>,
//! HG: FieldHasherGadget<F, P>,
//! const N: usize,
//! > Circuit<F, P> for TestCircuit<'_, F, P, HG, N>
//! {
//! const CIRCUIT_ID: [u8; 32] = [0xfe; 32];
//!
//! fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
//! let hasher_gadget = HG::from_native(composer, self.hasher.clone());
//!
//! let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
//! self.leaves,
//! &self.hasher,
//! self.empty_leaf,
//! )
//! .unwrap();
//! let path = smt.generate_membership_proof(0);
//! let root = path.calculate_root(&self.leaves[0], &self.hasher).unwrap();
//!
//! let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
//! let root_var = composer.add_input(root);
//! let leaf_var = composer.add_input(self.leaves[0]);
//!
//! let res =
//! path_gadget.check_membership(composer, &root_var, &leaf_var, &hasher_gadget)?;
//! let one = composer.add_input(F::one());
//! composer.assert_equal(res, one);
//!
//! Ok(())
//! }
//!
//! fn padded_circuit_size(&self) -> usize {
//! 1 << 13
//! }
//! }
//!
//! // Create the test circuit
//!
//! let rng = &mut test_rng();
//! let curve = Curve::Bn254;
//! let params = setup_params(curve, 5, 3);
//! let poseidon = PoseidonBn254 { params };
//! let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
//! let empty_leaf = [0u8; 32];
//! let mut test_circuit = TestCircuit::<Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
//! leaves: &leaves,
//! empty_leaf: &empty_leaf,
//! hasher: &poseidon,
//! };
//! ```
use crate::poseidon::FieldHasherGadget;
use ark_ec::models::TEModelParameters;
use ark_ff::PrimeField;
use ark_std::marker::PhantomData;
use arkworks_native_gadgets::merkle_tree::Path;
use plonk_core::{constraint_system::StandardComposer, error::Error, prelude::Variable};
#[derive(Clone)]
pub struct PathGadget<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
path: [(Variable, Variable); N],
_field: PhantomData<F>,
_te: PhantomData<P>,
_hg: PhantomData<HG>,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> PathGadget<F, P, HG, N>
{
pub fn from_native(
composer: &mut StandardComposer<F, P>,
native: Path<F, HG::Native, N>,
) -> Self {
// Initialize the array
let mut path_vars = [(composer.zero_var(), composer.zero_var()); N];
for i in 0..N {
path_vars[i] = (
composer.add_input(native.path[i].0),
composer.add_input(native.path[i].1),
);
}
PathGadget {
path: path_vars,
_field: PhantomData,
_te: PhantomData,
_hg: PhantomData,
}
}
pub fn check_membership(
&self,
composer: &mut StandardComposer<F, P>,
root_hash: &Variable,
leaf: &Variable,
hasher: &HG,
) -> Result<Variable, Error> {
let computed_root = self.calculate_root(composer, leaf, hasher)?;
Ok(composer.is_eq_with_output(computed_root, *root_hash))
}
pub fn calculate_root(
&self,
composer: &mut StandardComposer<F, P>,
leaf: &Variable,
hash_gadget: &HG,
) -> Result<Variable, Error> {
// Check levels between leaf level and root
let mut previous_hash = *leaf;
for (left_hash, right_hash) in self.path.iter() {
// Check if previous_hash matches the correct current hash
let previous_is_left = composer.is_eq_with_output(previous_hash, *left_hash);
let left_or_right =
composer.conditional_select(previous_is_left, *left_hash, *right_hash);
composer.assert_equal(previous_hash, left_or_right);
// Update previous_hash
previous_hash = hash_gadget.hash_two(composer, left_hash, right_hash)?;
}
Ok(previous_hash)
}
pub fn get_index(
&self,
composer: &mut StandardComposer<F, P>,
root_hash: &Variable,
leaf: &Variable,
hasher: &HG,
) -> Result<Variable, Error> {
// First check that leaf is on path
// let is_on_path = self.check_membership(composer, root_hash, leaf, hasher)?;
let one = composer.add_input(F::one());
// composer.assert_equal(is_on_path, one);
let mut index = composer.add_input(F::zero());
let mut two_power = composer.add_input(F::one());
let mut right_value: Variable;
// Check the levels between leaf level and root
let mut previous_hash = *leaf;
for (left_hash, right_hash) in self.path.iter() {
// Check if previous hash is a left node
let previous_is_left = composer.is_eq_with_output(previous_hash, *left_hash);
right_value = composer.arithmetic_gate(|gate| {
gate.witness(index, two_power, None).add(F::one(), F::one())
});
// Assign index based on whether prev hash is left or right
index = composer.conditional_select(previous_is_left, index, right_value);
two_power = composer
.arithmetic_gate(|gate| gate.witness(two_power, one, None).mul(F::one().double()));
previous_hash = hasher.hash_two(composer, left_hash, right_hash)?;
}
//This line confirms that the path is consistent with the given merkle root
composer.assert_equal(previous_hash, *root_hash);
Ok(index)
}
}
#[cfg(test)]
mod test {
use super::PathGadget;
use crate::poseidon::{FieldHasherGadget, PoseidonGadget};
use ark_bn254::{Bn254, Fr as Bn254Fr};
use ark_ec::TEModelParameters;
use ark_ed_on_bn254::{EdwardsParameters as JubjubParameters, Fq};
use ark_ff::PrimeField;
use ark_poly::polynomial::univariate::DensePolynomial;
use ark_poly_commit::{kzg10::UniversalParams, sonic_pc::SonicKZG10, PolynomialCommitment};
use ark_std::{test_rng, UniformRand};
use arkworks_native_gadgets::{
merkle_tree::SparseMerkleTree,
poseidon::{sbox::PoseidonSbox, Poseidon, PoseidonParameters},
};
use arkworks_utils::{
bytes_matrix_to_f, bytes_vec_to_f, poseidon_params::setup_poseidon_params, Curve,
};
use plonk_core::prelude::*;
type PoseidonBn254 = Poseidon<Fq>;
pub fn setup_params<F: PrimeField>(curve: Curve, exp: i8, width: u8) -> PoseidonParameters<F> {
let pos_data = setup_poseidon_params(curve, exp, width).unwrap();
let mds_f = bytes_matrix_to_f(&pos_data.mds);
let rounds_f = bytes_vec_to_f(&pos_data.rounds);
let pos = PoseidonParameters {
mds_matrix: mds_f,
round_keys: rounds_f,
full_rounds: pos_data.full_rounds,
partial_rounds: pos_data.partial_rounds,
sbox: PoseidonSbox(pos_data.exp),
width: pos_data.width,
};
pos
}
struct TestCircuit<
'a,
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
leaves: &'a [F],
empty_leaf: &'a [u8],
hasher: &'a HG::Native,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> Circuit<F, P> for TestCircuit<'_, F, P, HG, N>
{
const CIRCUIT_ID: [u8; 32] = [0xfe; 32];
fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let path = smt.generate_membership_proof(0);
let root = path.calculate_root(&self.leaves[0], &self.hasher).unwrap();
let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
let root_var = composer.add_input(root);
let leaf_var = composer.add_input(self.leaves[0]);
let res =
path_gadget.check_membership(composer, &root_var, &leaf_var, &hasher_gadget)?;
let one = composer.add_input(F::one());
composer.assert_equal(res, one);
Ok(())
}
fn padded_circuit_size(&self) -> usize {
1 << 13
}
}
#[test]
fn should_verify_path() {
let rng = &mut test_rng();
let curve = Curve::Bn254;
let params = setup_params(curve, 5, 3);
let poseidon = PoseidonBn254 { params };
let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
let empty_leaf = [0u8; 32];
// Create the test circuit
let mut test_circuit = TestCircuit::<Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
leaves: &leaves,
empty_leaf: &empty_leaf,
hasher: &poseidon,
};
// Usual prover/verifier flow:
let u_params: UniversalParams<Bn254> =
SonicKZG10::<Bn254, DensePolynomial<Bn254Fr>>::setup(1 << 14, None, rng).unwrap();
let (pk, vd) = test_circuit
.compile::<SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>(&u_params)
.unwrap();
// PROVER
let (proof, pi) = test_circuit.gen_proof(&u_params, pk, b"SMT Test").unwrap();
// VERIFIER
let (vk, ..): (
VerifierKey<Bn254Fr, SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>,
Vec<usize>,
) = vd;
let verifier_data = VerifierData::new(vk, pi);
circuit::verify_proof::<_, JubjubParameters, _>(
&u_params,
verifier_data.key,
&proof,
&verifier_data.pi,
b"SMT Test",
)
.unwrap();
}
struct IndexTestCircuit<
'a,
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
index: u64,
leaves: &'a [F],
empty_leaf: &'a [u8],
hasher: &'a HG::Native,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> Circuit<F, P> for IndexTestCircuit<'_, F, P, HG, N>
{
const CIRCUIT_ID: [u8; 32] = [0xfd; 32];
fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let root = smt.root();
let path = smt.generate_membership_proof(self.index);
let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
let root_var = composer.add_input(root);
let leaf_var = composer.add_input(self.leaves[self.index as usize]);
let res = path_gadget.get_index(composer, &root_var, &leaf_var, &hasher_gadget)?;
let index_var = composer.add_input(F::from(self.index));
composer.assert_equal(res, index_var);
Ok(())
}
fn padded_circuit_size(&self) -> usize {
1 << 14
}
}
#[test]
fn should_verify_index() {
let rng = &mut test_rng();
let curve = Curve::Bn254;
let params = setup_params(curve, 5, 3);
let poseidon = PoseidonBn254 { params };
let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
let empty_leaf = [0u8; 32];
let index = 2u64;
let mut test_circuit =
IndexTestCircuit::<'_, Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
index,
leaves: &leaves,
empty_leaf: &empty_leaf,
hasher: &poseidon,
};
// Usual prover/verifier flow:
let u_params: UniversalParams<Bn254> =
SonicKZG10::<Bn254, DensePolynomial<Bn254Fr>>::setup(1 << 15, None, rng).unwrap();
let (pk, vd) = test_circuit
.compile::<SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>(&u_params)
.unwrap();
// PROVER
let (proof, pi) = test_circuit
.gen_proof(&u_params, pk, b"SMTIndex Test")
.unwrap();
// VERIFIER
let (vk, ..): (
VerifierKey<Bn254Fr, SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>,
Vec<usize>,
) = vd;
let verifier_data = VerifierData::new(vk, pi);
circuit::verify_proof::<_, JubjubParameters, _>(
&u_params,
verifier_data.key,
&proof,
&verifier_data.pi,
b"SMTIndex Test",
)
.unwrap();
}
// Something puzzling is that this BadIndexTestCircuit needs to be
// 4 times larger than the valid IndexTestCircuit above. Why would
// the invalidity of a circuit lead to higher degree polynomials?
struct BadIndexTestCircuit<
'a,
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
index: u64,
leaves: &'a [F],
empty_leaf: &'a [u8],
hasher: &'a HG::Native,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> Circuit<F, P> for BadIndexTestCircuit<'_, F, P, HG, N>
{
const CIRCUIT_ID: [u8; 32] = [0xfd; 32];
fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let path = smt.generate_membership_proof(self.index);
let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
// Now create an invalid root to show that get_index detects this:
let bad_leaves = &self.leaves[0..1];
let bad_smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
bad_leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let bad_root = bad_smt.root();
let bad_root_var = composer.add_input(bad_root);
let leaf_var = composer.add_input(self.leaves[self.index as usize]);
let res = path_gadget.get_index(composer, &bad_root_var, &leaf_var, &hasher_gadget)?;
let index_var = composer.add_input(F::from(self.index));
composer.assert_equal(res, index_var);
Ok(())
}
fn padded_circuit_size(&self) -> usize {
1 << 16
}
}
#[test]
fn get_index_should_fail() {
let rng = &mut test_rng();
let curve = Curve::Bn254;
let params = setup_params(curve, 5, 3);
let poseidon = PoseidonBn254 { params };
let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
let empty_leaf = [0u8; 32];
let index = 2u64;
let mut test_circuit =
BadIndexTestCircuit::<'_, Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
index,
leaves: &leaves,
empty_leaf: &empty_leaf,
hasher: &poseidon,
};
// Usual prover/verifier flow:
let u_params: UniversalParams<Bn254> =
SonicKZG10::<Bn254, DensePolynomial<Bn254Fr>>::setup(1 << 17, None, rng).unwrap();
let (pk, vd) = test_circuit
.compile::<SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>(&u_params)
.unwrap();
// PROVER
let (proof, pi) = test_circuit
.gen_proof(&u_params, pk, b"SMTIndex Test")
.unwrap();
// VERIFIER
let (vk, ..): (
VerifierKey<Bn254Fr, SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>,
Vec<usize>,
) = vd;
let verifier_data = VerifierData::new(vk, pi);
let res = circuit::verify_proof::<_, JubjubParameters, _>(
&u_params,
verifier_data.key,
&proof,
&verifier_data.pi,
b"SMTIndex Test",
)
.unwrap_err();
match res {
Error::ProofVerificationError => (),
err => panic!("Unexpected error: {:?}", err),
};
}
// Membership proof should fail due to invalid leaf input
struct BadLeafTestCircuit<
'a,
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
leaves: &'a [F],
empty_leaf: &'a [u8],
hasher: &'a HG::Native,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> Circuit<F, P> for BadLeafTestCircuit<'_, F, P, HG, N>
{
const CIRCUIT_ID: [u8; 32] = [0xfe; 32];
fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let path = smt.generate_membership_proof(0);
let root = path.calculate_root(&self.leaves[0], &self.hasher).unwrap();
let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
let root_var = composer.add_input(root);
let leaf_var = composer.zero_var();
let res =
path_gadget.check_membership(composer, &root_var, &leaf_var, &hasher_gadget)?;
let one = composer.add_input(F::one());
composer.assert_equal(res, one);
Ok(())
}
fn padded_circuit_size(&self) -> usize {
1 << 16
}
}
#[test]
fn bad_leaf_membership() {
let rng = &mut test_rng();
let curve = Curve::Bn254;
let params = setup_params(curve, 5, 3);
let poseidon = PoseidonBn254 { params };
let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
let empty_leaf = [0u8; 32];
// Create the test circuit
let mut test_circuit =
BadLeafTestCircuit::<Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
leaves: &leaves,
empty_leaf: &empty_leaf,
hasher: &poseidon,
};
// Usual prover/verifier flow:
let u_params: UniversalParams<Bn254> =
SonicKZG10::<Bn254, DensePolynomial<Bn254Fr>>::setup(1 << 17, None, rng).unwrap();
let (pk, vd) = test_circuit
.compile::<SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>(&u_params)
.unwrap();
// PROVER
let (proof, pi) = test_circuit.gen_proof(&u_params, pk, b"SMT Test").unwrap();
// VERIFIER
let (vk, ..): (
VerifierKey<Bn254Fr, SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>,
Vec<usize>,
) = vd;
let verifier_data = VerifierData::new(vk, pi);
let res = circuit::verify_proof::<_, JubjubParameters, _>(
&u_params,
verifier_data.key,
&proof,
&verifier_data.pi,
b"SMTIndex Test",
)
.unwrap_err();
match res {
Error::ProofVerificationError => (),
err => panic!("Unexpected error: {:?}", err),
};
}
// Membership proof should fail due to invalid leaf input
struct BadRootTestCircuit<
'a,
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> {
leaves: &'a [F],
empty_leaf: &'a [u8],
hasher: &'a HG::Native,
}
impl<
F: PrimeField,
P: TEModelParameters<BaseField = F>,
HG: FieldHasherGadget<F, P>,
const N: usize,
> Circuit<F, P> for BadRootTestCircuit<'_, F, P, HG, N>
{
const CIRCUIT_ID: [u8; 32] = [0xfe; 32];
fn gadget(&mut self, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let path = smt.generate_membership_proof(0);
let path_gadget = PathGadget::<F, P, HG, N>::from_native(composer, path);
let root_var = composer.zero_var();
let leaf_var = composer.add_input(self.leaves[0]);
let res =
path_gadget.check_membership(composer, &root_var, &leaf_var, &hasher_gadget)?;
let one = composer.add_input(F::one());
composer.assert_equal(res, one);
Ok(())
}
fn padded_circuit_size(&self) -> usize {
1 << 16
}
}
#[test]
fn bad_root_membership() {
let rng = &mut test_rng();
let curve = Curve::Bn254;
let params = setup_params(curve, 5, 3);
let poseidon = PoseidonBn254 { params };
let leaves = [Fq::rand(rng), Fq::rand(rng), Fq::rand(rng)];
let empty_leaf = [0u8; 32];
// Create the test circuit
let mut test_circuit =
BadRootTestCircuit::<Bn254Fr, JubjubParameters, PoseidonGadget, 3usize> {
leaves: &leaves,
empty_leaf: &empty_leaf,
hasher: &poseidon,
};
// Usual prover/verifier flow:
let u_params: UniversalParams<Bn254> =
SonicKZG10::<Bn254, DensePolynomial<Bn254Fr>>::setup(1 << 17, None, rng).unwrap();
let (pk, vd) = test_circuit
.compile::<SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>(&u_params)
.unwrap();
// PROVER
let (proof, pi) = test_circuit.gen_proof(&u_params, pk, b"SMT Test").unwrap();
// VERIFIER
let (vk, ..): (
VerifierKey<Bn254Fr, SonicKZG10<Bn254, DensePolynomial<Bn254Fr>>>,
Vec<usize>,
) = vd;
let verifier_data = VerifierData::new(vk, pi);
let res = circuit::verify_proof::<_, JubjubParameters, _>(
&u_params,
verifier_data.key,
&proof,
&verifier_data.pi,
b"SMTIndex Test",
)
.unwrap_err();
match res {
Error::ProofVerificationError => (),
err => panic!("Unexpected error: {:?}", err),
};
}
}