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
use crate::{Poseidon, PoseidonLeaf, Scalar, MERKLE_ARITY, MERKLE_HEIGHT};
use std::ops;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Proof<T: PoseidonLeaf> {
pos: usize,
data: [(usize, [Option<T>; MERKLE_ARITY]); MERKLE_HEIGHT],
}
impl<T: PoseidonLeaf> Default for Proof<T> {
fn default() -> Self {
Proof {
pos: 0,
data: [(0, [None; MERKLE_ARITY]); MERKLE_HEIGHT],
}
}
}
impl<T: PoseidonLeaf> Proof<T> {
pub(crate) fn push(&mut self, idx: usize, leaves: &[Option<T>]) {
let (i, proof) = &mut self.data[self.pos];
proof.copy_from_slice(leaves);
*i = idx;
self.pos += 1;
}
pub fn data(&self) -> &[(usize, [Option<T>; MERKLE_ARITY]); MERKLE_HEIGHT] {
&self.data
}
pub fn verify(&self, leaf: &T, root: &T) -> bool
where
Scalar: ops::Mul<T, Output = T>,
{
let mut leaf = *leaf;
let mut h = Poseidon::default();
for i in 0..self.data.len() {
let (idx, data) = self.data[i];
h.replace(&data[0..MERKLE_ARITY]);
h.insert_unchecked(idx, leaf);
leaf = h.hash();
}
&leaf == root
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn proof_verify() {
let mut t = MerkleTree::<Scalar>::default();
for i in 0..MERKLE_WIDTH {
t.insert_unchecked(i, Scalar::from(i as u64));
}
let root = t.root();
let i = MERKLE_WIDTH / 3;
let proof = t.proof_index(i);
assert!(proof.verify(&Scalar::from(i as u64), &root));
}
#[test]
fn proof_verify_failure() {
let mut t = MerkleTree::<Scalar>::default();
for i in 0..MERKLE_WIDTH {
t.insert_unchecked(i, Scalar::from(i as u64));
}
let root = t.root();
let i = MERKLE_WIDTH / 3;
let proof = t.proof_index(i + 1);
assert!(!proof.verify(&Scalar::from(i as u64), &root));
}
}