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