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