ark-r1cs-std/crypto-primitives/src/merkle_tree/mod.rs
crypto-primitives/src/merkle_tree/mod.rsRaw
1use crate::{crh::FixedLengthCRH, Error, Vec};
2use algebra_core::{bytes::ToBytes, io::Cursor};
3use core::fmt;
4
5#[cfg(feature = "r1cs")]
6pub mod constraints;
7
8pub trait MerkleTreeConfig {
9 const HEIGHT: usize;
10 type H: FixedLengthCRH;
11}
12
13/// Stores the hashes of a particular path (in order) from leaf to root.
14/// Our path `is_left_child()` if the boolean in `path` is true.
15#[derive(Derivative)]
16#[derivative(
17 Clone(bound = "P: MerkleTreeConfig"),
18 Debug(bound = "P: MerkleTreeConfig, <P::H as FixedLengthCRH>::Output: fmt::Debug")
19)]
20pub struct MerkleTreePath<P: MerkleTreeConfig> {
21 pub(crate) path: Vec<(
22 <P::H as FixedLengthCRH>::Output,
23 <P::H as FixedLengthCRH>::Output,
24 )>,
25}
26
27pub type MerkleTreeParams<P> = <<P as MerkleTreeConfig>::H as FixedLengthCRH>::Parameters;
28pub type MerkleTreeDigest<P> = <<P as MerkleTreeConfig>::H as FixedLengthCRH>::Output;
29
30impl<P: MerkleTreeConfig> Default for MerkleTreePath<P> {
31 fn default() -> Self {
32 let mut path = Vec::with_capacity(P::HEIGHT as usize);
33 for _i in 1..P::HEIGHT as usize {
34 path.push((
35 <P::H as FixedLengthCRH>::Output::default(),
36 <P::H as FixedLengthCRH>::Output::default(),
37 ));
38 }
39 Self { path }
40 }
41}
42
43impl<P: MerkleTreeConfig> MerkleTreePath<P> {
44 pub fn verify<L: ToBytes>(
45 &self,
46 parameters: &<P::H as FixedLengthCRH>::Parameters,
47 root_hash: &<P::H as FixedLengthCRH>::Output,
48 leaf: &L,
49 ) -> Result<bool, Error> {
50 if self.path.len() != (P::HEIGHT - 1) as usize {
51 return Ok(false);
52 }
53 // Check that the given leaf matches the leaf in the membership proof.
54 let mut buffer = [0u8; 128];
55
56 if !self.path.is_empty() {
57 let claimed_leaf_hash = hash_leaf::<P::H, L>(parameters, leaf, &mut buffer)?;
58
59 // Check if leaf is one of the bottom-most siblings.
60 if claimed_leaf_hash != self.path[0].0 && claimed_leaf_hash != self.path[0].1 {
61 return Ok(false);
62 };
63
64 let mut prev = claimed_leaf_hash;
65 // Check levels between leaf level and root.
66 for &(ref hash, ref sibling_hash) in &self.path {
67 // Check if the previous hash matches the correct current hash.
68 if &prev != hash && &prev != sibling_hash {
69 return Ok(false);
70 };
71 prev = hash_inner_node::<P::H>(parameters, hash, sibling_hash, &mut buffer)?;
72 }
73
74 if root_hash != &prev {
75 return Ok(false);
76 }
77 Ok(true)
78 } else {
79 Ok(false)
80 }
81 }
82}
83
84pub struct MerkleHashTree<P: MerkleTreeConfig> {
85 tree: Vec<<P::H as FixedLengthCRH>::Output>,
86 padding_tree: Vec<(
87 <P::H as FixedLengthCRH>::Output,
88 <P::H as FixedLengthCRH>::Output,
89 )>,
90 parameters: <P::H as FixedLengthCRH>::Parameters,
91 root: Option<<P::H as FixedLengthCRH>::Output>,
92}
93
94impl<P: MerkleTreeConfig> MerkleHashTree<P> {
95 pub const HEIGHT: u8 = P::HEIGHT as u8;
96
97 pub fn blank(parameters: <P::H as FixedLengthCRH>::Parameters) -> Self {
98 MerkleHashTree {
99 tree: Vec::new(),
100 padding_tree: Vec::new(),
101 root: None,
102 parameters,
103 }
104 }
105
106 pub fn new<L: ToBytes>(
107 parameters: <P::H as FixedLengthCRH>::Parameters,
108 leaves: &[L],
109 ) -> Result<Self, Error> {
110 let new_time = start_timer!(|| "MerkleTree::New");
111
112 let last_level_size = leaves.len().next_power_of_two();
113 let tree_size = 2 * last_level_size - 1;
114 let tree_height = tree_height(tree_size);
115 assert!(tree_height as u8 <= Self::HEIGHT);
116
117 // Initialize the merkle tree.
118 let mut tree = Vec::with_capacity(tree_size);
119 let empty_hash = hash_empty::<P::H>(¶meters)?;
120 for _ in 0..tree_size {
121 tree.push(empty_hash.clone());
122 }
123
124 // Compute the starting indices for each level of the tree.
125 let mut index = 0;
126 let mut level_indices = Vec::with_capacity(tree_height);
127 for _ in 0..tree_height {
128 level_indices.push(index);
129 index = left_child(index);
130 }
131
132 // Compute and store the hash values for each leaf.
133 let last_level_index = level_indices.pop().unwrap_or(0);
134 let mut buffer = [0u8; 128];
135 for (i, leaf) in leaves.iter().enumerate() {
136 tree[last_level_index + i] = hash_leaf::<P::H, _>(¶meters, leaf, &mut buffer)?;
137 }
138
139 // Compute the hash values for every node in the tree.
140 let mut upper_bound = last_level_index;
141 let mut buffer = [0u8; 128];
142 level_indices.reverse();
143 for &start_index in &level_indices {
144 // Iterate over the current level.
145 for current_index in start_index..upper_bound {
146 let left_index = left_child(current_index);
147 let right_index = right_child(current_index);
148
149 // Compute Hash(left || right).
150 tree[current_index] = hash_inner_node::<P::H>(
151 ¶meters,
152 &tree[left_index],
153 &tree[right_index],
154 &mut buffer,
155 )?;
156 }
157 upper_bound = start_index;
158 }
159 // Finished computing actual tree.
160 // Now, we compute the dummy nodes until we hit our HEIGHT goal.
161 let mut cur_height = tree_height;
162 let mut padding_tree = Vec::new();
163 let mut cur_hash = tree[0].clone();
164 let root_hash = if cur_height < Self::HEIGHT as usize {
165 while cur_height < (Self::HEIGHT - 1) as usize {
166 cur_hash = hash_inner_node::<P::H>(¶meters, &cur_hash, &empty_hash, &mut buffer)?;
167 padding_tree.push((cur_hash.clone(), empty_hash.clone()));
168 cur_height += 1;
169 }
170 hash_inner_node::<P::H>(¶meters, &cur_hash, &empty_hash, &mut buffer)?
171 } else {
172 cur_hash
173 };
174 end_timer!(new_time);
175
176 Ok(MerkleHashTree {
177 tree,
178 padding_tree,
179 parameters,
180 root: Some(root_hash),
181 })
182 }
183
184 #[inline]
185 pub fn root(&self) -> <P::H as FixedLengthCRH>::Output {
186 self.root.clone().unwrap()
187 }
188
189 pub fn generate_proof<L: ToBytes>(
190 &self,
191 index: usize,
192 leaf: &L,
193 ) -> Result<MerkleTreePath<P>, Error> {
194 let prove_time = start_timer!(|| "MerkleTree::GenProof");
195 let mut path = Vec::new();
196
197 let mut buffer = [0u8; 128];
198 let leaf_hash = hash_leaf::<P::H, _>(&self.parameters, leaf, &mut buffer)?;
199 let tree_height = tree_height(self.tree.len());
200 let tree_index = convert_index_to_last_level(index, tree_height);
201 let empty_hash = hash_empty::<P::H>(&self.parameters)?;
202
203 // Check that the given index corresponds to the correct leaf.
204 if leaf_hash != self.tree[tree_index] {
205 return Err(MerkleTreeError::IncorrectLeafIndex(tree_index).into());
206 }
207
208 // Iterate from the leaf up to the root, storing all intermediate hash values.
209 let mut current_node = tree_index;
210 while !is_root(current_node) {
211 let sibling_node = sibling(current_node).unwrap();
212 let (curr_hash, sibling_hash) = (
213 self.tree[current_node].clone(),
214 self.tree[sibling_node].clone(),
215 );
216 if is_left_child(current_node) {
217 path.push((curr_hash, sibling_hash));
218 } else {
219 path.push((sibling_hash, curr_hash));
220 }
221 current_node = parent(current_node).unwrap();
222 }
223
224 // Store the root node. Set boolean as true for consistency with digest
225 // location.
226 assert!(path.len() < Self::HEIGHT as usize);
227 if path.len() != (Self::HEIGHT - 1) as usize {
228 path.push((self.tree[0].clone(), empty_hash));
229 for &(ref hash, ref sibling_hash) in &self.padding_tree {
230 path.push((hash.clone(), sibling_hash.clone()));
231 }
232 }
233 end_timer!(prove_time);
234 if path.len() != (Self::HEIGHT - 1) as usize {
235 return Err(MerkleTreeError::IncorrectPathLength(path.len()).into());
236 } else {
237 Ok(MerkleTreePath { path })
238 }
239 }
240}
241
242#[derive(Debug)]
243pub enum MerkleTreeError {
244 IncorrectLeafIndex(usize),
245 IncorrectPathLength(usize),
246}
247
248impl core::fmt::Display for MerkleTreeError {
249 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
250 let msg = match self {
251 MerkleTreeError::IncorrectLeafIndex(index) => {
252 format!("incorrect leaf index: {}", index)
253 }
254 MerkleTreeError::IncorrectPathLength(len) => format!("incorrect path length: {}", len),
255 };
256 write!(f, "{}", msg)
257 }
258}
259
260impl algebra_core::Error for MerkleTreeError {}
261
262/// Returns the log2 value of the given number.
263#[inline]
264fn log2(number: usize) -> usize {
265 algebra_core::log2(number) as usize
266}
267
268/// Returns the height of the tree, given the size of the tree.
269#[inline]
270fn tree_height(tree_size: usize) -> usize {
271 log2(tree_size)
272}
273
274/// Returns true iff the index represents the root.
275#[inline]
276fn is_root(index: usize) -> bool {
277 index == 0
278}
279
280/// Returns the index of the left child, given an index.
281#[inline]
282fn left_child(index: usize) -> usize {
283 2 * index + 1
284}
285
286/// Returns the index of the right child, given an index.
287#[inline]
288fn right_child(index: usize) -> usize {
289 2 * index + 2
290}
291
292/// Returns the index of the sibling, given an index.
293#[inline]
294fn sibling(index: usize) -> Option<usize> {
295 if index == 0 {
296 None
297 } else if is_left_child(index) {
298 Some(index + 1)
299 } else {
300 Some(index - 1)
301 }
302}
303
304/// Returns true iff the given index represents a left child.
305#[inline]
306fn is_left_child(index: usize) -> bool {
307 index % 2 == 1
308}
309
310/// Returns the index of the parent, given an index.
311#[inline]
312fn parent(index: usize) -> Option<usize> {
313 if index > 0 {
314 Some((index - 1) >> 1)
315 } else {
316 None
317 }
318}
319
320#[inline]
321fn convert_index_to_last_level(index: usize, tree_height: usize) -> usize {
322 index + (1 << (tree_height - 1)) - 1
323}
324
325/// Returns the output hash, given a left and right hash value.
326pub(crate) fn hash_inner_node<H: FixedLengthCRH>(
327 parameters: &H::Parameters,
328 left: &H::Output,
329 right: &H::Output,
330 buffer: &mut [u8],
331) -> Result<H::Output, Error> {
332 let mut writer = Cursor::new(&mut *buffer);
333 // Construct left input.
334 left.write(&mut writer)?;
335
336 // Construct right input.
337 right.write(&mut writer)?;
338
339 H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
340}
341
342/// Returns the hash of a leaf.
343pub(crate) fn hash_leaf<H: FixedLengthCRH, L: ToBytes>(
344 parameters: &H::Parameters,
345 leaf: &L,
346 buffer: &mut [u8],
347) -> Result<H::Output, Error> {
348 let mut writer = Cursor::new(&mut *buffer);
349 leaf.write(&mut writer)?;
350
351 H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
352}
353
354pub(crate) fn hash_empty<H: FixedLengthCRH>(
355 parameters: &H::Parameters,
356) -> Result<H::Output, Error> {
357 let empty_buffer = vec![0u8; H::INPUT_SIZE_BITS / 8];
358 H::evaluate(parameters, &empty_buffer)
359}
360
361#[cfg(test)]
362mod test {
363 use crate::{
364 crh::{pedersen::*, *},
365 merkle_tree::*,
366 };
367 use algebra::{jubjub::JubJubAffine as JubJub, Zero};
368 use rand::SeedableRng;
369 use rand_xorshift::XorShiftRng;
370
371 #[derive(Clone)]
372 pub(super) struct Window4x256;
373 impl PedersenWindow for Window4x256 {
374 const WINDOW_SIZE: usize = 4;
375 const NUM_WINDOWS: usize = 256;
376 }
377
378 type H = PedersenCRH<JubJub, Window4x256>;
379
380 struct JubJubMerkleTreeParams;
381
382 impl MerkleTreeConfig for JubJubMerkleTreeParams {
383 const HEIGHT: usize = 8;
384 type H = H;
385 }
386 type JubJubMerkleTree = MerkleHashTree<JubJubMerkleTreeParams>;
387
388 fn generate_merkle_tree<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
389 let mut rng = XorShiftRng::seed_from_u64(9174123u64);
390
391 let crh_parameters = H::setup(&mut rng).unwrap();
392 let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
393 let root = tree.root();
394 for (i, leaf) in leaves.iter().enumerate() {
395 let proof = tree.generate_proof(i, &leaf).unwrap();
396 assert!(proof.verify(&crh_parameters, &root, &leaf).unwrap());
397 }
398 }
399
400 #[test]
401 fn good_root_test() {
402 let mut leaves = Vec::new();
403 for i in 0..4u8 {
404 leaves.push([i, i, i, i, i, i, i, i]);
405 }
406 generate_merkle_tree(&leaves);
407 let mut leaves = Vec::new();
408 for i in 0..100u8 {
409 leaves.push([i, i, i, i, i, i, i, i]);
410 }
411 generate_merkle_tree(&leaves);
412 }
413
414 #[test]
415 fn no_dummy_nodes_test() {
416 let mut leaves = Vec::new();
417 for i in 0..(1u8 << JubJubMerkleTree::HEIGHT - 1) {
418 leaves.push([i, i, i, i, i, i, i, i]);
419 }
420 generate_merkle_tree(&leaves);
421 }
422
423 #[test]
424 fn single_leaf_test() {
425 generate_merkle_tree(&[[1u8; 8]]);
426 }
427
428 fn bad_merkle_tree_verify<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
429 let mut rng = XorShiftRng::seed_from_u64(13423423u64);
430
431 let crh_parameters = H::setup(&mut rng).unwrap();
432 let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
433 let root = JubJub::zero();
434 for (i, leaf) in leaves.iter().enumerate() {
435 let proof = tree.generate_proof(i, &leaf).unwrap();
436 assert!(proof.verify(&crh_parameters, &root, &leaf).unwrap());
437 }
438 }
439
440 #[should_panic]
441 #[test]
442 fn bad_root_test() {
443 let mut leaves = Vec::new();
444 for i in 0..4u8 {
445 leaves.push([i, i, i, i, i, i, i, i]);
446 }
447 generate_merkle_tree(&leaves);
448 let mut leaves = Vec::new();
449 for i in 0..100u8 {
450 leaves.push([i, i, i, i, i, i, i, i]);
451 }
452 bad_merkle_tree_verify(&leaves);
453 }
454}