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
use super::*;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MerklePath<E: Environment, const DEPTH: u8> {
leaf_index: U64<E>,
siblings: Vec<Field<E>>,
}
impl<E: Environment, const DEPTH: u8> TryFrom<(U64<E>, Vec<Field<E>>)> for MerklePath<E, DEPTH> {
type Error = Error;
fn try_from((leaf_index, siblings): (U64<E>, Vec<Field<E>>)) -> Result<Self> {
ensure!(DEPTH > 0, "Merkle tree depth must be greater than 0");
ensure!(DEPTH <= 64u8, "Merkle tree depth must be less than or equal to 64");
ensure!((*leaf_index as u128) < (1u128 << DEPTH), "Found an out of bounds Merkle leaf index");
ensure!(siblings.len() == DEPTH as usize, "Found an incorrect Merkle path length");
Ok(Self { leaf_index, siblings })
}
}
impl<E: Environment, const DEPTH: u8> MerklePath<E, DEPTH> {
pub fn leaf_index(&self) -> U64<E> {
self.leaf_index
}
pub fn siblings(&self) -> &[Field<E>] {
&self.siblings
}
pub fn verify<LH: LeafHash<Hash = PH::Hash>, PH: PathHash<Hash = Field<E>>>(
&self,
leaf_hasher: &LH,
path_hasher: &PH,
root: &PH::Hash,
leaf: &LH::Leaf,
) -> bool {
if (*self.leaf_index as u128) >= (1u128 << DEPTH) {
eprintln!("Found an out of bounds Merkle leaf index");
return false;
}
else if self.siblings.len() != DEPTH as usize {
eprintln!("Found an incorrect Merkle path length");
return false;
}
let mut current_hash = match leaf_hasher.hash_leaf(leaf) {
Ok(candidate_leaf_hash) => candidate_leaf_hash,
Err(error) => {
eprintln!("Failed to hash the Merkle leaf during verification: {error}");
return false;
}
};
let indicators = (0..DEPTH).map(|i| ((*self.leaf_index >> i) & 1) == 0);
for (indicator, sibling_hash) in indicators.zip_eq(&self.siblings) {
let (left, right) = match indicator {
true => (current_hash, *sibling_hash),
false => (*sibling_hash, current_hash),
};
match path_hasher.hash_children(&left, &right) {
Ok(hash) => current_hash = hash,
Err(error) => {
eprintln!("Failed to hash the Merkle path during verification: {error}");
return false;
}
}
}
current_hash == *root
}
}
impl<E: Environment, const DEPTH: u8> FromBytes for MerklePath<E, DEPTH> {
#[inline]
fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
let leaf_index = u64::read_le(&mut reader)?;
let siblings =
(0..DEPTH).map(|_| Ok(Field::new(FromBytes::read_le(&mut reader)?))).collect::<IoResult<Vec<_>>>()?;
Self::try_from((U64::new(leaf_index), siblings)).map_err(|err| error(err.to_string()))
}
}
impl<E: Environment, const DEPTH: u8> ToBytes for MerklePath<E, DEPTH> {
#[inline]
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
self.leaf_index.write_le(&mut writer)?;
self.siblings.iter().try_for_each(|sibling| sibling.write_le(&mut writer))
}
}
impl<E: Environment, const DEPTH: u8> Serialize for MerklePath<E, DEPTH> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
ToBytesSerializer::serialize(self, serializer)
}
}
impl<'de, E: Environment, const DEPTH: u8> Deserialize<'de> for MerklePath<E, DEPTH> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let size = 8 + DEPTH as usize * (Field::<E>::size_in_bits() + 7) / 8;
FromBytesDeserializer::<Self>::deserialize(deserializer, "Merkle path", size)
}
}