arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/merkle_tree.rs
src/merkle/merkle_tree.rsRaw
  1use super::{InnerNodeInfo, MerkleError, MerklePath, NodeIndex, Rpo256, RpoDigest, Vec, Word};
  2use crate::utils::{string::String, uninit_vector, word_to_hex};
  3use core::{fmt, ops::Deref, slice};
  4use winter_math::log2;
  5
  6// MERKLE TREE
  7// ================================================================================================
  8
  9/// A fully-balanced binary Merkle tree (i.e., a tree where the number of leaves is a power of two).
 10#[derive(Debug, Clone, PartialEq, Eq)]
 11pub struct MerkleTree {
 12    nodes: Vec<RpoDigest>,
 13}
 14
 15impl MerkleTree {
 16    // CONSTRUCTOR
 17    // --------------------------------------------------------------------------------------------
 18    /// Returns a Merkle tree instantiated from the provided leaves.
 19    ///
 20    /// # Errors
 21    /// Returns an error if the number of leaves is smaller than two or is not a power of two.
 22    pub fn new(leaves: Vec<Word>) -> Result<Self, MerkleError> {
 23        let n = leaves.len();
 24        if n <= 1 {
 25            return Err(MerkleError::DepthTooSmall(n as u8));
 26        } else if !n.is_power_of_two() {
 27            return Err(MerkleError::NumLeavesNotPowerOfTwo(n));
 28        }
 29
 30        // create un-initialized vector to hold all tree nodes
 31        let mut nodes = unsafe { uninit_vector(2 * n) };
 32        nodes[0] = RpoDigest::default();
 33
 34        // copy leaves into the second part of the nodes vector
 35        nodes[n..].iter_mut().zip(leaves).for_each(|(node, leaf)| {
 36            *node = RpoDigest::from(leaf);
 37        });
 38
 39        // re-interpret nodes as an array of two nodes fused together
 40        // Safety: `nodes` will never move here as it is not bound to an external lifetime (i.e.
 41        // `self`).
 42        let ptr = nodes.as_ptr() as *const [RpoDigest; 2];
 43        let pairs = unsafe { slice::from_raw_parts(ptr, n) };
 44
 45        // calculate all internal tree nodes
 46        for i in (1..n).rev() {
 47            nodes[i] = Rpo256::merge(&pairs[i]);
 48        }
 49
 50        Ok(Self { nodes })
 51    }
 52
 53    // PUBLIC ACCESSORS
 54    // --------------------------------------------------------------------------------------------
 55
 56    /// Returns the root of this Merkle tree.
 57    pub fn root(&self) -> RpoDigest {
 58        self.nodes[1]
 59    }
 60
 61    /// Returns the depth of this Merkle tree.
 62    ///
 63    /// Merkle tree of depth 1 has two leaves, depth 2 has four leaves etc.
 64    pub fn depth(&self) -> u8 {
 65        log2(self.nodes.len() / 2) as u8
 66    }
 67
 68    /// Returns a node at the specified depth and index value.
 69    ///
 70    /// # Errors
 71    /// Returns an error if:
 72    /// * The specified depth is greater than the depth of the tree.
 73    /// * The specified index is not valid for the specified depth.
 74    pub fn get_node(&self, index: NodeIndex) -> Result<RpoDigest, MerkleError> {
 75        if index.is_root() {
 76            return Err(MerkleError::DepthTooSmall(index.depth()));
 77        } else if index.depth() > self.depth() {
 78            return Err(MerkleError::DepthTooBig(index.depth() as u64));
 79        }
 80
 81        let pos = index.to_scalar_index() as usize;
 82        Ok(self.nodes[pos])
 83    }
 84
 85    /// Returns a Merkle path to the node at the specified depth and index value. The node itself
 86    /// is not included in the path.
 87    ///
 88    /// # Errors
 89    /// Returns an error if:
 90    /// * The specified depth is greater than the depth of the tree.
 91    /// * The specified value is not valid for the specified depth.
 92    pub fn get_path(&self, mut index: NodeIndex) -> Result<MerklePath, MerkleError> {
 93        if index.is_root() {
 94            return Err(MerkleError::DepthTooSmall(index.depth()));
 95        } else if index.depth() > self.depth() {
 96            return Err(MerkleError::DepthTooBig(index.depth() as u64));
 97        }
 98
 99        // TODO should we create a helper in `NodeIndex` that will encapsulate traversal to root so
100        // we always use inlined `for` instead of `while`? the reason to use `for` is because its
101        // easier for the compiler to vectorize.
102        let mut path = Vec::with_capacity(index.depth() as usize);
103        for _ in 0..index.depth() {
104            let sibling = index.sibling().to_scalar_index() as usize;
105            path.push(self.nodes[sibling]);
106            index.move_up();
107        }
108
109        debug_assert!(index.is_root(), "the path walk must go all the way to the root");
110
111        Ok(path.into())
112    }
113
114    // ITERATORS
115    // --------------------------------------------------------------------------------------------
116
117    /// Returns an iterator over the leaves of this [MerkleTree].
118    pub fn leaves(&self) -> impl Iterator<Item = (u64, &Word)> {
119        let leaves_start = self.nodes.len() / 2;
120        self.nodes
121            .iter()
122            .skip(leaves_start)
123            .enumerate()
124            .map(|(i, v)| (i as u64, v.deref()))
125    }
126
127    /// Returns n iterator over every inner node of this [MerkleTree].
128    ///
129    /// The iterator order is unspecified.
130    pub fn inner_nodes(&self) -> InnerNodeIterator {
131        InnerNodeIterator {
132            nodes: &self.nodes,
133            index: 1, // index 0 is just padding, start at 1
134        }
135    }
136
137    // STATE MUTATORS
138    // --------------------------------------------------------------------------------------------
139
140    /// Replaces the leaf at the specified index with the provided value.
141    ///
142    /// # Errors
143    /// Returns an error if the specified index value is not a valid leaf value for this tree.
144    pub fn update_leaf<'a>(&'a mut self, index_value: u64, value: Word) -> Result<(), MerkleError> {
145        let mut index = NodeIndex::new(self.depth(), index_value)?;
146
147        // we don't need to copy the pairs into a new address as we are logically guaranteed to not
148        // overlap write instructions. however, it's important to bind the lifetime of pairs to
149        // `self.nodes` so the compiler will never move one without moving the other.
150        debug_assert_eq!(self.nodes.len() & 1, 0);
151        let n = self.nodes.len() / 2;
152
153        // Safety: the length of nodes is guaranteed to contain pairs of words; hence, pairs of
154        // digests. we explicitly bind the lifetime here so we add an extra layer of guarantee that
155        // `self.nodes` will be moved only if `pairs` is moved as well. also, the algorithm is
156        // logically guaranteed to not overlap write positions as the write index is always half
157        // the index from which we read the digest input.
158        let ptr = self.nodes.as_ptr() as *const [RpoDigest; 2];
159        let pairs: &'a [[RpoDigest; 2]] = unsafe { slice::from_raw_parts(ptr, n) };
160
161        // update the current node
162        let pos = index.to_scalar_index() as usize;
163        self.nodes[pos] = value.into();
164
165        // traverse to the root, updating each node with the merged values of its parents
166        for _ in 0..index.depth() {
167            index.move_up();
168            let pos = index.to_scalar_index() as usize;
169            let value = Rpo256::merge(&pairs[pos]);
170            self.nodes[pos] = value;
171        }
172
173        Ok(())
174    }
175}
176
177// ITERATORS
178// ================================================================================================
179
180/// An iterator over every inner node of the [MerkleTree].
181///
182/// Use this to extract the data of the tree, there is no guarantee on the order of the elements.
183pub struct InnerNodeIterator<'a> {
184    nodes: &'a Vec<RpoDigest>,
185    index: usize,
186}
187
188impl<'a> Iterator for InnerNodeIterator<'a> {
189    type Item = InnerNodeInfo;
190
191    fn next(&mut self) -> Option<Self::Item> {
192        if self.index < self.nodes.len() / 2 {
193            let value = self.index;
194            let left = self.index * 2;
195            let right = left + 1;
196
197            self.index += 1;
198
199            Some(InnerNodeInfo {
200                value: self.nodes[value],
201                left: self.nodes[left],
202                right: self.nodes[right],
203            })
204        } else {
205            None
206        }
207    }
208}
209
210// UTILITY FUNCTIONS
211// ================================================================================================
212
213/// Utility to visualize a [MerkleTree] in text.
214pub fn tree_to_text(tree: &MerkleTree) -> Result<String, fmt::Error> {
215    let indent = "  ";
216    let mut s = String::new();
217    s.push_str(&word_to_hex(&tree.root())?);
218    s.push('\n');
219    for d in 1..=tree.depth() {
220        let entries = 2u64.pow(d.into());
221        for i in 0..entries {
222            let index = NodeIndex::new(d, i).expect("The index must always be valid");
223            let node = tree.get_node(index).expect("The node must always be found");
224
225            for _ in 0..d {
226                s.push_str(indent);
227            }
228            s.push_str(&word_to_hex(&node)?);
229            s.push('\n');
230        }
231    }
232
233    Ok(s)
234}
235
236/// Utility to visualize a [MerklePath] in text.
237pub fn path_to_text(path: &MerklePath) -> Result<String, fmt::Error> {
238    let mut s = String::new();
239    s.push('[');
240
241    for el in path.iter() {
242        s.push_str(&word_to_hex(el)?);
243        s.push_str(", ");
244    }
245
246    // remove the last ", "
247    if path.len() != 0 {
248        s.pop();
249        s.pop();
250    }
251    s.push(']');
252
253    Ok(s)
254}
255
256// TESTS
257// ================================================================================================
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use crate::{
263        merkle::{digests_to_words, int_to_leaf, int_to_node, InnerNodeInfo},
264        Felt, Word, WORD_SIZE,
265    };
266    use core::mem::size_of;
267    use proptest::prelude::*;
268
269    const LEAVES4: [RpoDigest; WORD_SIZE] =
270        [int_to_node(1), int_to_node(2), int_to_node(3), int_to_node(4)];
271
272    const LEAVES8: [RpoDigest; 8] = [
273        int_to_node(1),
274        int_to_node(2),
275        int_to_node(3),
276        int_to_node(4),
277        int_to_node(5),
278        int_to_node(6),
279        int_to_node(7),
280        int_to_node(8),
281    ];
282
283    #[test]
284    fn build_merkle_tree() {
285        let tree = super::MerkleTree::new(digests_to_words(&LEAVES4)).unwrap();
286        assert_eq!(8, tree.nodes.len());
287
288        // leaves were copied correctly
289        for (a, b) in tree.nodes.iter().skip(4).zip(LEAVES4.iter()) {
290            assert_eq!(*a, RpoDigest::from(*b));
291        }
292
293        let (root, node2, node3) = compute_internal_nodes();
294
295        assert_eq!(root, tree.nodes[1]);
296        assert_eq!(node2, tree.nodes[2]);
297        assert_eq!(node3, tree.nodes[3]);
298
299        assert_eq!(root, tree.root());
300    }
301
302    #[test]
303    fn get_leaf() {
304        let tree = super::MerkleTree::new(digests_to_words(&LEAVES4)).unwrap();
305
306        // check depth 2
307        assert_eq!(LEAVES4[0], tree.get_node(NodeIndex::make(2, 0)).unwrap());
308        assert_eq!(LEAVES4[1], tree.get_node(NodeIndex::make(2, 1)).unwrap());
309        assert_eq!(LEAVES4[2], tree.get_node(NodeIndex::make(2, 2)).unwrap());
310        assert_eq!(LEAVES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap());
311
312        // check depth 1
313        let (_, node2, node3) = compute_internal_nodes();
314
315        assert_eq!(node2, tree.get_node(NodeIndex::make(1, 0)).unwrap());
316        assert_eq!(node3, tree.get_node(NodeIndex::make(1, 1)).unwrap());
317    }
318
319    #[test]
320    fn get_path() {
321        let tree = super::MerkleTree::new(digests_to_words(&LEAVES4)).unwrap();
322
323        let (_, node2, node3) = compute_internal_nodes();
324
325        // check depth 2
326        assert_eq!(vec![LEAVES4[1], node3], *tree.get_path(NodeIndex::make(2, 0)).unwrap());
327        assert_eq!(vec![LEAVES4[0], node3], *tree.get_path(NodeIndex::make(2, 1)).unwrap());
328        assert_eq!(vec![LEAVES4[3], node2], *tree.get_path(NodeIndex::make(2, 2)).unwrap());
329        assert_eq!(vec![LEAVES4[2], node2], *tree.get_path(NodeIndex::make(2, 3)).unwrap());
330
331        // check depth 1
332        assert_eq!(vec![node3], *tree.get_path(NodeIndex::make(1, 0)).unwrap());
333        assert_eq!(vec![node2], *tree.get_path(NodeIndex::make(1, 1)).unwrap());
334    }
335
336    #[test]
337    fn update_leaf() {
338        let mut tree = super::MerkleTree::new(digests_to_words(&LEAVES8)).unwrap();
339
340        // update one leaf
341        let value = 3;
342        let new_node = int_to_leaf(9);
343        let mut expected_leaves = digests_to_words(&LEAVES8);
344        expected_leaves[value as usize] = new_node.into();
345        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
346
347        tree.update_leaf(value, new_node).unwrap();
348        assert_eq!(expected_tree.nodes, tree.nodes);
349
350        // update another leaf
351        let value = 6;
352        let new_node = int_to_leaf(10);
353        expected_leaves[value as usize] = new_node;
354        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
355
356        tree.update_leaf(value, new_node).unwrap();
357        assert_eq!(expected_tree.nodes, tree.nodes);
358    }
359
360    #[test]
361    fn nodes() -> Result<(), MerkleError> {
362        let tree = super::MerkleTree::new(digests_to_words(&LEAVES4)).unwrap();
363        let root = tree.root();
364        let l1n0 = tree.get_node(NodeIndex::make(1, 0))?;
365        let l1n1 = tree.get_node(NodeIndex::make(1, 1))?;
366        let l2n0 = tree.get_node(NodeIndex::make(2, 0))?;
367        let l2n1 = tree.get_node(NodeIndex::make(2, 1))?;
368        let l2n2 = tree.get_node(NodeIndex::make(2, 2))?;
369        let l2n3 = tree.get_node(NodeIndex::make(2, 3))?;
370
371        let nodes: Vec<InnerNodeInfo> = tree.inner_nodes().collect();
372        let expected = vec![
373            InnerNodeInfo {
374                value: root,
375                left: l1n0,
376                right: l1n1,
377            },
378            InnerNodeInfo {
379                value: l1n0,
380                left: l2n0,
381                right: l2n1,
382            },
383            InnerNodeInfo {
384                value: l1n1,
385                left: l2n2,
386                right: l2n3,
387            },
388        ];
389        assert_eq!(nodes, expected);
390
391        Ok(())
392    }
393
394    proptest! {
395        #[test]
396        fn arbitrary_word_can_be_represented_as_digest(
397            a in prop::num::u64::ANY,
398            b in prop::num::u64::ANY,
399            c in prop::num::u64::ANY,
400            d in prop::num::u64::ANY,
401        ) {
402            // this test will assert the memory equivalence between word and digest.
403            // it is used to safeguard the `[MerkleTee::update_leaf]` implementation
404            // that assumes this equivalence.
405
406            // build a word and copy it to another address as digest
407            let word = [Felt::new(a), Felt::new(b), Felt::new(c), Felt::new(d)];
408            let digest = RpoDigest::from(word);
409
410            // assert the addresses are different
411            let word_ptr = (&word).as_ptr() as *const u8;
412            let digest_ptr = (&digest).as_ptr() as *const u8;
413            assert_ne!(word_ptr, digest_ptr);
414
415            // compare the bytes representation
416            let word_bytes = unsafe { slice::from_raw_parts(word_ptr, size_of::<Word>()) };
417            let digest_bytes = unsafe { slice::from_raw_parts(digest_ptr, size_of::<RpoDigest>()) };
418            assert_eq!(word_bytes, digest_bytes);
419        }
420    }
421
422    // HELPER FUNCTIONS
423    // --------------------------------------------------------------------------------------------
424
425    fn compute_internal_nodes() -> (RpoDigest, RpoDigest, RpoDigest) {
426        let node2 =
427            Rpo256::hash_elements(&[Word::from(LEAVES4[0]), Word::from(LEAVES4[1])].concat());
428        let node3 =
429            Rpo256::hash_elements(&[Word::from(LEAVES4[2]), Word::from(LEAVES4[3])].concat());
430        let root = Rpo256::merge(&[node2, node3]);
431
432        (root, node2, node3)
433    }
434}