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