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!(index.is_root(), "the path walk must go all the way to the root");
113
114        Ok(path.into())
115    }
116
117    /// Replaces the leaf at the specified index with the provided value.
118    ///
119    /// # Errors
120    /// Returns an error if the specified index value is not a valid leaf value for this tree.
121    pub fn update_leaf<'a>(&'a mut self, index_value: u64, value: Word) -> Result<(), MerkleError> {
122        let mut index = NodeIndex::new(self.depth(), index_value)?;
123
124        // we don't need to copy the pairs into a new address as we are logically guaranteed to not
125        // overlap write instructions. however, it's important to bind the lifetime of pairs to
126        // `self.nodes` so the compiler will never move one without moving the other.
127        debug_assert_eq!(self.nodes.len() & 1, 0);
128        let n = self.nodes.len() / 2;
129
130        // Safety: the length of nodes is guaranteed to contain pairs of words; hence, pairs of
131        // digests. we explicitly bind the lifetime here so we add an extra layer of guarantee that
132        // `self.nodes` will be moved only if `pairs` is moved as well. also, the algorithm is
133        // logically guaranteed to not overlap write positions as the write index is always half
134        // the index from which we read the digest input.
135        let ptr = self.nodes.as_ptr() as *const [RpoDigest; 2];
136        let pairs: &'a [[RpoDigest; 2]] = unsafe { slice::from_raw_parts(ptr, n) };
137
138        // update the current node
139        let pos = index.to_scalar_index() as usize;
140        self.nodes[pos] = value;
141
142        // traverse to the root, updating each node with the merged values of its parents
143        for _ in 0..index.depth() {
144            index.move_up();
145            let pos = index.to_scalar_index() as usize;
146            let value = Rpo256::merge(&pairs[pos]).into();
147            self.nodes[pos] = value;
148        }
149
150        Ok(())
151    }
152
153    /// Returns n iterator over every inner node of this [MerkleTree].
154    ///
155    /// The iterator order is unspecified.
156    pub fn inner_nodes(&self) -> InnerNodeIterator<'_> {
157        InnerNodeIterator {
158            nodes: &self.nodes,
159            index: 1, // index 0 is just padding, start at 1
160        }
161    }
162}
163
164// ITERATORS
165// ================================================================================================
166
167/// An iterator over every inner node of the [MerkleTree].
168///
169/// Use this to extract the data of the tree, there is no guarantee on the order of the elements.
170pub struct InnerNodeIterator<'a> {
171    nodes: &'a Vec<Word>,
172    index: usize,
173}
174
175impl<'a> Iterator for InnerNodeIterator<'a> {
176    type Item = InnerNodeInfo;
177
178    fn next(&mut self) -> Option<Self::Item> {
179        if self.index < self.nodes.len() / 2 {
180            let value = self.index;
181            let left = self.index * 2;
182            let right = left + 1;
183
184            self.index += 1;
185
186            Some(InnerNodeInfo {
187                value: self.nodes[value],
188                left: self.nodes[left],
189                right: self.nodes[right],
190            })
191        } else {
192            None
193        }
194    }
195}
196
197// UTILITY FUNCTIONS
198// ================================================================================================
199
200/// Utility to visualize a [MerkleTree] in text.
201pub fn tree_to_text(tree: &MerkleTree) -> Result<String, fmt::Error> {
202    let indent = "  ";
203    let mut s = String::new();
204    s.push_str(&word_to_hex(&tree.root())?);
205    s.push('\n');
206    for d in 1..=tree.depth() {
207        let entries = 2u64.pow(d.into());
208        for i in 0..entries {
209            let index = NodeIndex::new(d, i).expect("The index must always be valid");
210            let node = tree.get_node(index).expect("The node must always be found");
211
212            for _ in 0..d {
213                s.push_str(indent);
214            }
215            s.push_str(&word_to_hex(&node)?);
216            s.push('\n');
217        }
218    }
219
220    Ok(s)
221}
222
223/// Utility to visualize a [MerklePath] in text.
224pub fn path_to_text(path: &MerklePath) -> Result<String, fmt::Error> {
225    let mut s = String::new();
226    s.push('[');
227
228    for el in path.iter() {
229        s.push_str(&word_to_hex(el)?);
230        s.push_str(", ");
231    }
232
233    // remove the last ", "
234    if path.len() != 0 {
235        s.pop();
236        s.pop();
237    }
238    s.push(']');
239
240    Ok(s)
241}
242
243// TESTS
244// ================================================================================================
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::merkle::{int_to_node, InnerNodeInfo};
250    use core::mem::size_of;
251    use proptest::prelude::*;
252
253    const LEAVES4: [Word; 4] = [int_to_node(1), int_to_node(2), int_to_node(3), int_to_node(4)];
254
255    const LEAVES8: [Word; 8] = [
256        int_to_node(1),
257        int_to_node(2),
258        int_to_node(3),
259        int_to_node(4),
260        int_to_node(5),
261        int_to_node(6),
262        int_to_node(7),
263        int_to_node(8),
264    ];
265
266    #[test]
267    fn build_merkle_tree() {
268        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
269        assert_eq!(8, tree.nodes.len());
270
271        // leaves were copied correctly
272        for (a, b) in tree.nodes.iter().skip(4).zip(LEAVES4.iter()) {
273            assert_eq!(a, b);
274        }
275
276        let (root, node2, node3) = compute_internal_nodes();
277
278        assert_eq!(root, tree.nodes[1]);
279        assert_eq!(node2, tree.nodes[2]);
280        assert_eq!(node3, tree.nodes[3]);
281
282        assert_eq!(root, tree.root());
283    }
284
285    #[test]
286    fn get_leaf() {
287        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
288
289        // check depth 2
290        assert_eq!(LEAVES4[0], tree.get_node(NodeIndex::make(2, 0)).unwrap());
291        assert_eq!(LEAVES4[1], tree.get_node(NodeIndex::make(2, 1)).unwrap());
292        assert_eq!(LEAVES4[2], tree.get_node(NodeIndex::make(2, 2)).unwrap());
293        assert_eq!(LEAVES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap());
294
295        // check depth 1
296        let (_, node2, node3) = compute_internal_nodes();
297
298        assert_eq!(node2, tree.get_node(NodeIndex::make(1, 0)).unwrap());
299        assert_eq!(node3, tree.get_node(NodeIndex::make(1, 1)).unwrap());
300    }
301
302    #[test]
303    fn get_path() {
304        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
305
306        let (_, node2, node3) = compute_internal_nodes();
307
308        // check depth 2
309        assert_eq!(vec![LEAVES4[1], node3], *tree.get_path(NodeIndex::make(2, 0)).unwrap());
310        assert_eq!(vec![LEAVES4[0], node3], *tree.get_path(NodeIndex::make(2, 1)).unwrap());
311        assert_eq!(vec![LEAVES4[3], node2], *tree.get_path(NodeIndex::make(2, 2)).unwrap());
312        assert_eq!(vec![LEAVES4[2], node2], *tree.get_path(NodeIndex::make(2, 3)).unwrap());
313
314        // check depth 1
315        assert_eq!(vec![node3], *tree.get_path(NodeIndex::make(1, 0)).unwrap());
316        assert_eq!(vec![node2], *tree.get_path(NodeIndex::make(1, 1)).unwrap());
317    }
318
319    #[test]
320    fn update_leaf() {
321        let mut tree = super::MerkleTree::new(LEAVES8.to_vec()).unwrap();
322
323        // update one leaf
324        let value = 3;
325        let new_node = int_to_node(9);
326        let mut expected_leaves = LEAVES8.to_vec();
327        expected_leaves[value as usize] = new_node;
328        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
329
330        tree.update_leaf(value, new_node).unwrap();
331        assert_eq!(expected_tree.nodes, tree.nodes);
332
333        // update another leaf
334        let value = 6;
335        let new_node = int_to_node(10);
336        expected_leaves[value as usize] = new_node;
337        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
338
339        tree.update_leaf(value, new_node).unwrap();
340        assert_eq!(expected_tree.nodes, tree.nodes);
341    }
342
343    #[test]
344    fn nodes() -> Result<(), MerkleError> {
345        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
346        let root = tree.root();
347        let l1n0 = tree.get_node(NodeIndex::make(1, 0))?;
348        let l1n1 = tree.get_node(NodeIndex::make(1, 1))?;
349        let l2n0 = tree.get_node(NodeIndex::make(2, 0))?;
350        let l2n1 = tree.get_node(NodeIndex::make(2, 1))?;
351        let l2n2 = tree.get_node(NodeIndex::make(2, 2))?;
352        let l2n3 = tree.get_node(NodeIndex::make(2, 3))?;
353
354        let nodes: Vec<InnerNodeInfo> = tree.inner_nodes().collect();
355        let expected = vec![
356            InnerNodeInfo {
357                value: root,
358                left: l1n0,
359                right: l1n1,
360            },
361            InnerNodeInfo {
362                value: l1n0,
363                left: l2n0,
364                right: l2n1,
365            },
366            InnerNodeInfo {
367                value: l1n1,
368                left: l2n2,
369                right: l2n3,
370            },
371        ];
372        assert_eq!(nodes, expected);
373
374        Ok(())
375    }
376
377    proptest! {
378        #[test]
379        fn arbitrary_word_can_be_represented_as_digest(
380            a in prop::num::u64::ANY,
381            b in prop::num::u64::ANY,
382            c in prop::num::u64::ANY,
383            d in prop::num::u64::ANY,
384        ) {
385            // this test will assert the memory equivalence between word and digest.
386            // it is used to safeguard the `[MerkleTee::update_leaf]` implementation
387            // that assumes this equivalence.
388
389            // build a word and copy it to another address as digest
390            let word = [Felt::new(a), Felt::new(b), Felt::new(c), Felt::new(d)];
391            let digest = RpoDigest::from(word);
392
393            // assert the addresses are different
394            let word_ptr = (&word).as_ptr() as *const u8;
395            let digest_ptr = (&digest).as_ptr() as *const u8;
396            assert_ne!(word_ptr, digest_ptr);
397
398            // compare the bytes representation
399            let word_bytes = unsafe { slice::from_raw_parts(word_ptr, size_of::<Word>()) };
400            let digest_bytes = unsafe { slice::from_raw_parts(digest_ptr, size_of::<RpoDigest>()) };
401            assert_eq!(word_bytes, digest_bytes);
402        }
403    }
404
405    // HELPER FUNCTIONS
406    // --------------------------------------------------------------------------------------------
407
408    fn compute_internal_nodes() -> (Word, Word, Word) {
409        let node2 = Rpo256::hash_elements(&[LEAVES4[0], LEAVES4[1]].concat());
410        let node3 = Rpo256::hash_elements(&[LEAVES4[2], LEAVES4[3]].concat());
411        let root = Rpo256::merge(&[node2, node3]);
412
413        (root.into(), node2.into(), node3.into())
414    }
415}