arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/merkle_tree.rs
src/merkle/merkle_tree.rsRaw
  1use super::{Felt, MerkleError, MerklePath, NodeIndex, Rpo256, RpoDigest, Vec, Word};
  2use crate::{utils::uninit_vector, FieldElement};
  3use core::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<Word>,
 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] = [Felt::ZERO; 4];
 33
 34        // copy leaves into the second part of the nodes vector
 35        nodes[n..].copy_from_slice(&leaves);
 36
 37        // re-interpret nodes as an array of two nodes fused together
 38        // Safety: `nodes` will never move here as it is not bound to an external lifetime (i.e.
 39        // `self`).
 40        let ptr = nodes.as_ptr() as *const [RpoDigest; 2];
 41        let pairs = unsafe { slice::from_raw_parts(ptr, n) };
 42
 43        // calculate all internal tree nodes
 44        for i in (1..n).rev() {
 45            nodes[i] = Rpo256::merge(&pairs[i]).into();
 46        }
 47
 48        Ok(Self { nodes })
 49    }
 50
 51    // PUBLIC ACCESSORS
 52    // --------------------------------------------------------------------------------------------
 53
 54    /// Returns the root of this Merkle tree.
 55    pub fn root(&self) -> Word {
 56        self.nodes[1]
 57    }
 58
 59    /// Returns the depth of this Merkle tree.
 60    ///
 61    /// Merkle tree of depth 1 has two leaves, depth 2 has four leaves etc.
 62    pub fn depth(&self) -> u8 {
 63        log2(self.nodes.len() / 2) as u8
 64    }
 65
 66    /// Returns a node at the specified depth and index value.
 67    ///
 68    /// # Errors
 69    /// Returns an error if:
 70    /// * The specified depth is greater than the depth of the tree.
 71    /// * The specified index not valid for the specified depth.
 72    pub fn get_node(&self, index: NodeIndex) -> Result<Word, MerkleError> {
 73        if index.is_root() {
 74            return Err(MerkleError::DepthTooSmall(index.depth()));
 75        } else if index.depth() > self.depth() {
 76            return Err(MerkleError::DepthTooBig(index.depth() as u64));
 77        } else if !index.is_valid() {
 78            return Err(MerkleError::InvalidIndex(index));
 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 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        } else if !index.is_valid() {
 98            return Err(MerkleError::InvalidIndex(index));
 99        }
100
101        // TODO should we create a helper in `NodeIndex` that will encapsulate traversal to root so
102        // we always use inlined `for` instead of `while`? the reason to use `for` is because its
103        // easier for the compiler to vectorize.
104        let mut path = Vec::with_capacity(index.depth() as usize);
105        for _ in 0..index.depth() {
106            let sibling = index.sibling().to_scalar_index() as usize;
107            path.push(self.nodes[sibling]);
108            index.move_up();
109        }
110
111        Ok(path.into())
112    }
113
114    /// Replaces the leaf at the specified index with the provided value.
115    ///
116    /// # Errors
117    /// Returns an error if the specified index value is not a valid leaf value for this tree.
118    pub fn update_leaf<'a>(&'a mut self, index_value: u64, value: Word) -> Result<(), MerkleError> {
119        let depth = self.depth();
120        let mut index = NodeIndex::new(depth, index_value);
121        if !index.is_valid() {
122            return Err(MerkleError::InvalidIndex(index));
123        }
124
125        // we don't need to copy the pairs into a new address as we are logically guaranteed to not
126        // overlap write instructions. however, it's important to bind the lifetime of pairs to
127        // `self.nodes` so the compiler will never move one without moving the other.
128        debug_assert_eq!(self.nodes.len() & 1, 0);
129        let n = self.nodes.len() / 2;
130
131        // Safety: the length of nodes is guaranteed to contain pairs of words; hence, pairs of
132        // digests. we explicitly bind the lifetime here so we add an extra layer of guarantee that
133        // `self.nodes` will be moved only if `pairs` is moved as well. also, the algorithm is
134        // logically guaranteed to not overlap write positions as the write index is always half
135        // the index from which we read the digest input.
136        let ptr = self.nodes.as_ptr() as *const [RpoDigest; 2];
137        let pairs: &'a [[RpoDigest; 2]] = unsafe { slice::from_raw_parts(ptr, n) };
138
139        // update the current node
140        let pos = index.to_scalar_index() as usize;
141        self.nodes[pos] = value;
142
143        // traverse to the root, updating each node with the merged values of its parents
144        for _ in 0..index.depth() {
145            index.move_up();
146            let pos = index.to_scalar_index() as usize;
147            let value = Rpo256::merge(&pairs[pos]).into();
148            self.nodes[pos] = value;
149        }
150
151        Ok(())
152    }
153}
154
155// TESTS
156// ================================================================================================
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::merkle::int_to_node;
162    use core::mem::size_of;
163    use proptest::prelude::*;
164
165    const LEAVES4: [Word; 4] = [
166        int_to_node(1),
167        int_to_node(2),
168        int_to_node(3),
169        int_to_node(4),
170    ];
171
172    const LEAVES8: [Word; 8] = [
173        int_to_node(1),
174        int_to_node(2),
175        int_to_node(3),
176        int_to_node(4),
177        int_to_node(5),
178        int_to_node(6),
179        int_to_node(7),
180        int_to_node(8),
181    ];
182
183    #[test]
184    fn build_merkle_tree() {
185        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
186        assert_eq!(8, tree.nodes.len());
187
188        // leaves were copied correctly
189        for (a, b) in tree.nodes.iter().skip(4).zip(LEAVES4.iter()) {
190            assert_eq!(a, b);
191        }
192
193        let (root, node2, node3) = compute_internal_nodes();
194
195        assert_eq!(root, tree.nodes[1]);
196        assert_eq!(node2, tree.nodes[2]);
197        assert_eq!(node3, tree.nodes[3]);
198
199        assert_eq!(root, tree.root());
200    }
201
202    #[test]
203    fn get_leaf() {
204        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
205
206        // check depth 2
207        assert_eq!(LEAVES4[0], tree.get_node(NodeIndex::new(2, 0)).unwrap());
208        assert_eq!(LEAVES4[1], tree.get_node(NodeIndex::new(2, 1)).unwrap());
209        assert_eq!(LEAVES4[2], tree.get_node(NodeIndex::new(2, 2)).unwrap());
210        assert_eq!(LEAVES4[3], tree.get_node(NodeIndex::new(2, 3)).unwrap());
211
212        // check depth 1
213        let (_, node2, node3) = compute_internal_nodes();
214
215        assert_eq!(node2, tree.get_node(NodeIndex::new(1, 0)).unwrap());
216        assert_eq!(node3, tree.get_node(NodeIndex::new(1, 1)).unwrap());
217    }
218
219    #[test]
220    fn get_path() {
221        let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
222
223        let (_, node2, node3) = compute_internal_nodes();
224
225        // check depth 2
226        assert_eq!(
227            vec![LEAVES4[1], node3],
228            *tree.get_path(NodeIndex::new(2, 0)).unwrap()
229        );
230        assert_eq!(
231            vec![LEAVES4[0], node3],
232            *tree.get_path(NodeIndex::new(2, 1)).unwrap()
233        );
234        assert_eq!(
235            vec![LEAVES4[3], node2],
236            *tree.get_path(NodeIndex::new(2, 2)).unwrap()
237        );
238        assert_eq!(
239            vec![LEAVES4[2], node2],
240            *tree.get_path(NodeIndex::new(2, 3)).unwrap()
241        );
242
243        // check depth 1
244        assert_eq!(vec![node3], *tree.get_path(NodeIndex::new(1, 0)).unwrap());
245        assert_eq!(vec![node2], *tree.get_path(NodeIndex::new(1, 1)).unwrap());
246    }
247
248    #[test]
249    fn update_leaf() {
250        let mut tree = super::MerkleTree::new(LEAVES8.to_vec()).unwrap();
251
252        // update one leaf
253        let value = 3;
254        let new_node = int_to_node(9);
255        let mut expected_leaves = LEAVES8.to_vec();
256        expected_leaves[value as usize] = new_node;
257        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
258
259        tree.update_leaf(value, new_node).unwrap();
260        assert_eq!(expected_tree.nodes, tree.nodes);
261
262        // update another leaf
263        let value = 6;
264        let new_node = int_to_node(10);
265        expected_leaves[value as usize] = new_node;
266        let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
267
268        tree.update_leaf(value, new_node).unwrap();
269        assert_eq!(expected_tree.nodes, tree.nodes);
270    }
271
272    proptest! {
273        #[test]
274        fn arbitrary_word_can_be_represented_as_digest(
275            a in prop::num::u64::ANY,
276            b in prop::num::u64::ANY,
277            c in prop::num::u64::ANY,
278            d in prop::num::u64::ANY,
279        ) {
280            // this test will assert the memory equivalence between word and digest.
281            // it is used to safeguard the `[MerkleTee::update_leaf]` implementation
282            // that assumes this equivalence.
283
284            // build a word and copy it to another address as digest
285            let word = [Felt::new(a), Felt::new(b), Felt::new(c), Felt::new(d)];
286            let digest = RpoDigest::from(word);
287
288            // assert the addresses are different
289            let word_ptr = (&word).as_ptr() as *const u8;
290            let digest_ptr = (&digest).as_ptr() as *const u8;
291            assert_ne!(word_ptr, digest_ptr);
292
293            // compare the bytes representation
294            let word_bytes = unsafe { slice::from_raw_parts(word_ptr, size_of::<Word>()) };
295            let digest_bytes = unsafe { slice::from_raw_parts(digest_ptr, size_of::<RpoDigest>()) };
296            assert_eq!(word_bytes, digest_bytes);
297        }
298    }
299
300    // HELPER FUNCTIONS
301    // --------------------------------------------------------------------------------------------
302
303    fn compute_internal_nodes() -> (Word, Word, Word) {
304        let node2 = Rpo256::hash_elements(&[LEAVES4[0], LEAVES4[1]].concat());
305        let node3 = Rpo256::hash_elements(&[LEAVES4[2], LEAVES4[3]].concat());
306        let root = Rpo256::merge(&[node2, node3]);
307
308        (root.into(), node2.into(), node3.into())
309    }
310}