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