arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
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>(&parameters)?;
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, _>(&parameters, 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                    &parameters,
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        while cur_height < (Self::HEIGHT - 1) as usize {
165            cur_hash = hash_inner_node::<P::H>(&parameters, &cur_hash, &empty_hash, &mut buffer)?;
166            padding_tree.push((cur_hash.clone(), empty_hash.clone()));
167            cur_height += 1;
168        }
169
170        let root_hash = hash_inner_node::<P::H>(&parameters, &cur_hash, &empty_hash, &mut buffer)?;
171
172        end_timer!(new_time);
173
174        Ok(MerkleHashTree {
175            tree,
176            padding_tree,
177            parameters,
178            root: Some(root_hash),
179        })
180    }
181
182    #[inline]
183    pub fn root(&self) -> <P::H as FixedLengthCRH>::Output {
184        self.root.clone().unwrap()
185    }
186
187    pub fn generate_proof<L: ToBytes>(
188        &self,
189        index: usize,
190        leaf: &L,
191    ) -> Result<MerkleTreePath<P>, Error> {
192        let prove_time = start_timer!(|| "MerkleTree::GenProof");
193        let mut path = Vec::new();
194
195        let mut buffer = [0u8; 128];
196        let leaf_hash = hash_leaf::<P::H, _>(&self.parameters, leaf, &mut buffer)?;
197        let tree_height = tree_height(self.tree.len());
198        let tree_index = convert_index_to_last_level(index, tree_height);
199        let empty_hash = hash_empty::<P::H>(&self.parameters)?;
200
201        // Check that the given index corresponds to the correct leaf.
202        if leaf_hash != self.tree[tree_index] {
203            return Err(MerkleTreeError::IncorrectLeafIndex(tree_index).into());
204        }
205
206        // Iterate from the leaf up to the root, storing all intermediate hash values.
207        let mut current_node = tree_index;
208        while !is_root(current_node) {
209            let sibling_node = sibling(current_node).unwrap();
210            let (curr_hash, sibling_hash) = (
211                self.tree[current_node].clone(),
212                self.tree[sibling_node].clone(),
213            );
214            if is_left_child(current_node) {
215                path.push((curr_hash, sibling_hash));
216            } else {
217                path.push((sibling_hash, curr_hash));
218            }
219            current_node = parent(current_node).unwrap();
220        }
221
222        // Store the root node. Set boolean as true for consistency with digest
223        // location.
224        assert!(path.len() < Self::HEIGHT as usize);
225        if path.len() != (Self::HEIGHT - 1) as usize {
226            path.push((self.tree[0].clone(), empty_hash));
227            for &(ref hash, ref sibling_hash) in &self.padding_tree {
228                path.push((hash.clone(), sibling_hash.clone()));
229            }
230        }
231        end_timer!(prove_time);
232        if path.len() != (Self::HEIGHT - 1) as usize {
233            return Err(MerkleTreeError::IncorrectPathLength(path.len()).into());
234        } else {
235            Ok(MerkleTreePath { path })
236        }
237    }
238}
239
240#[derive(Debug)]
241pub enum MerkleTreeError {
242    IncorrectLeafIndex(usize),
243    IncorrectPathLength(usize),
244}
245
246impl core::fmt::Display for MerkleTreeError {
247    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
248        let msg = match self {
249            MerkleTreeError::IncorrectLeafIndex(index) => {
250                format!("incorrect leaf index: {}", index)
251            }
252            MerkleTreeError::IncorrectPathLength(len) => format!("incorrect path length: {}", len),
253        };
254        write!(f, "{}", msg)
255    }
256}
257
258impl algebra_core::Error for MerkleTreeError {}
259
260/// Returns the log2 value of the given number.
261#[inline]
262fn log2(number: usize) -> usize {
263    algebra_core::log2(number) as usize
264}
265
266/// Returns the height of the tree, given the size of the tree.
267#[inline]
268fn tree_height(tree_size: usize) -> usize {
269    log2(tree_size)
270}
271
272/// Returns true iff the index represents the root.
273#[inline]
274fn is_root(index: usize) -> bool {
275    index == 0
276}
277
278/// Returns the index of the left child, given an index.
279#[inline]
280fn left_child(index: usize) -> usize {
281    2 * index + 1
282}
283
284/// Returns the index of the right child, given an index.
285#[inline]
286fn right_child(index: usize) -> usize {
287    2 * index + 2
288}
289
290/// Returns the index of the sibling, given an index.
291#[inline]
292fn sibling(index: usize) -> Option<usize> {
293    if index == 0 {
294        None
295    } else if is_left_child(index) {
296        Some(index + 1)
297    } else {
298        Some(index - 1)
299    }
300}
301
302/// Returns true iff the given index represents a left child.
303#[inline]
304fn is_left_child(index: usize) -> bool {
305    index % 2 == 1
306}
307
308/// Returns the index of the parent, given an index.
309#[inline]
310fn parent(index: usize) -> Option<usize> {
311    if index > 0 {
312        Some((index - 1) >> 1)
313    } else {
314        None
315    }
316}
317
318#[inline]
319fn convert_index_to_last_level(index: usize, tree_height: usize) -> usize {
320    index + (1 << (tree_height - 1)) - 1
321}
322
323/// Returns the output hash, given a left and right hash value.
324pub(crate) fn hash_inner_node<H: FixedLengthCRH>(
325    parameters: &H::Parameters,
326    left: &H::Output,
327    right: &H::Output,
328    buffer: &mut [u8],
329) -> Result<H::Output, Error> {
330    let mut writer = Cursor::new(&mut *buffer);
331    // Construct left input.
332    left.write(&mut writer)?;
333
334    // Construct right input.
335    right.write(&mut writer)?;
336
337    H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
338}
339
340/// Returns the hash of a leaf.
341pub(crate) fn hash_leaf<H: FixedLengthCRH, L: ToBytes>(
342    parameters: &H::Parameters,
343    leaf: &L,
344    buffer: &mut [u8],
345) -> Result<H::Output, Error> {
346    let mut writer = Cursor::new(&mut *buffer);
347    leaf.write(&mut writer)?;
348
349    H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
350}
351
352pub(crate) fn hash_empty<H: FixedLengthCRH>(
353    parameters: &H::Parameters,
354) -> Result<H::Output, Error> {
355    let empty_buffer = vec![0u8; H::INPUT_SIZE_BITS / 8];
356    H::evaluate(parameters, &empty_buffer)
357}
358
359#[cfg(test)]
360mod test {
361    use crate::{
362        crh::{pedersen::*, *},
363        merkle_tree::*,
364    };
365    use algebra::{jubjub::JubJubAffine as JubJub, Zero};
366    use rand::SeedableRng;
367    use rand_xorshift::XorShiftRng;
368
369    #[derive(Clone)]
370    pub(super) struct Window4x256;
371    impl PedersenWindow for Window4x256 {
372        const WINDOW_SIZE: usize = 4;
373        const NUM_WINDOWS: usize = 256;
374    }
375
376    type H = PedersenCRH<JubJub, Window4x256>;
377
378    struct JubJubMerkleTreeParams;
379
380    impl MerkleTreeConfig for JubJubMerkleTreeParams {
381        const HEIGHT: usize = 32;
382        type H = H;
383    }
384    type JubJubMerkleTree = MerkleHashTree<JubJubMerkleTreeParams>;
385
386    fn generate_merkle_tree<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
387        let mut rng = XorShiftRng::seed_from_u64(9174123u64);
388
389        let crh_parameters = H::setup(&mut rng).unwrap();
390        let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
391        let root = tree.root();
392        for (i, leaf) in leaves.iter().enumerate() {
393            let proof = tree.generate_proof(i, &leaf).unwrap();
394            assert!(proof.verify(&crh_parameters, &root, &leaf).unwrap());
395        }
396    }
397
398    #[test]
399    fn good_root_test() {
400        let mut leaves = Vec::new();
401        for i in 0..4u8 {
402            leaves.push([i, i, i, i, i, i, i, i]);
403        }
404        generate_merkle_tree(&leaves);
405        let mut leaves = Vec::new();
406        for i in 0..100u8 {
407            leaves.push([i, i, i, i, i, i, i, i]);
408        }
409        generate_merkle_tree(&leaves);
410    }
411
412    fn bad_merkle_tree_verify<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
413        let mut rng = XorShiftRng::seed_from_u64(13423423u64);
414
415        let crh_parameters = H::setup(&mut rng).unwrap();
416        let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
417        let root = JubJub::zero();
418        for (i, leaf) in leaves.iter().enumerate() {
419            let proof = tree.generate_proof(i, &leaf).unwrap();
420            assert!(proof.verify(&crh_parameters, &root, &leaf).unwrap());
421        }
422    }
423
424    #[should_panic]
425    #[test]
426    fn bad_root_test() {
427        let mut leaves = Vec::new();
428        for i in 0..4u8 {
429            leaves.push([i, i, i, i, i, i, i, i]);
430        }
431        generate_merkle_tree(&leaves);
432        let mut leaves = Vec::new();
433        for i in 0..100u8 {
434            leaves.push([i, i, i, i, i, i, i, i]);
435        }
436        bad_merkle_tree_verify(&leaves);
437    }
438}