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 FUNCTIONS
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] = [int_to_node(1), int_to_node(2), int_to_node(3), int_to_node(4)];
252
253 const LEAVES8: [Word; 8] = [
254 int_to_node(1),
255 int_to_node(2),
256 int_to_node(3),
257 int_to_node(4),
258 int_to_node(5),
259 int_to_node(6),
260 int_to_node(7),
261 int_to_node(8),
262 ];
263
264 #[test]
265 fn build_merkle_tree() {
266 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
267 assert_eq!(8, tree.nodes.len());
268
269 // leaves were copied correctly
270 for (a, b) in tree.nodes.iter().skip(4).zip(LEAVES4.iter()) {
271 assert_eq!(a, b);
272 }
273
274 let (root, node2, node3) = compute_internal_nodes();
275
276 assert_eq!(root, tree.nodes[1]);
277 assert_eq!(node2, tree.nodes[2]);
278 assert_eq!(node3, tree.nodes[3]);
279
280 assert_eq!(root, tree.root());
281 }
282
283 #[test]
284 fn get_leaf() {
285 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
286
287 // check depth 2
288 assert_eq!(LEAVES4[0], tree.get_node(NodeIndex::make(2, 0)).unwrap());
289 assert_eq!(LEAVES4[1], tree.get_node(NodeIndex::make(2, 1)).unwrap());
290 assert_eq!(LEAVES4[2], tree.get_node(NodeIndex::make(2, 2)).unwrap());
291 assert_eq!(LEAVES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap());
292
293 // check depth 1
294 let (_, node2, node3) = compute_internal_nodes();
295
296 assert_eq!(node2, tree.get_node(NodeIndex::make(1, 0)).unwrap());
297 assert_eq!(node3, tree.get_node(NodeIndex::make(1, 1)).unwrap());
298 }
299
300 #[test]
301 fn get_path() {
302 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
303
304 let (_, node2, node3) = compute_internal_nodes();
305
306 // check depth 2
307 assert_eq!(vec![LEAVES4[1], node3], *tree.get_path(NodeIndex::make(2, 0)).unwrap());
308 assert_eq!(vec![LEAVES4[0], node3], *tree.get_path(NodeIndex::make(2, 1)).unwrap());
309 assert_eq!(vec![LEAVES4[3], node2], *tree.get_path(NodeIndex::make(2, 2)).unwrap());
310 assert_eq!(vec![LEAVES4[2], node2], *tree.get_path(NodeIndex::make(2, 3)).unwrap());
311
312 // check depth 1
313 assert_eq!(vec![node3], *tree.get_path(NodeIndex::make(1, 0)).unwrap());
314 assert_eq!(vec![node2], *tree.get_path(NodeIndex::make(1, 1)).unwrap());
315 }
316
317 #[test]
318 fn update_leaf() {
319 let mut tree = super::MerkleTree::new(LEAVES8.to_vec()).unwrap();
320
321 // update one leaf
322 let value = 3;
323 let new_node = int_to_node(9);
324 let mut expected_leaves = LEAVES8.to_vec();
325 expected_leaves[value as usize] = new_node;
326 let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
327
328 tree.update_leaf(value, new_node).unwrap();
329 assert_eq!(expected_tree.nodes, tree.nodes);
330
331 // update another leaf
332 let value = 6;
333 let new_node = int_to_node(10);
334 expected_leaves[value as usize] = new_node;
335 let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
336
337 tree.update_leaf(value, new_node).unwrap();
338 assert_eq!(expected_tree.nodes, tree.nodes);
339 }
340
341 #[test]
342 fn nodes() -> Result<(), MerkleError> {
343 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
344 let root = tree.root();
345 let l1n0 = tree.get_node(NodeIndex::make(1, 0))?;
346 let l1n1 = tree.get_node(NodeIndex::make(1, 1))?;
347 let l2n0 = tree.get_node(NodeIndex::make(2, 0))?;
348 let l2n1 = tree.get_node(NodeIndex::make(2, 1))?;
349 let l2n2 = tree.get_node(NodeIndex::make(2, 2))?;
350 let l2n3 = tree.get_node(NodeIndex::make(2, 3))?;
351
352 let nodes: Vec<InnerNodeInfo> = tree.inner_nodes().collect();
353 let expected = vec![
354 InnerNodeInfo {
355 value: root,
356 left: l1n0,
357 right: l1n1,
358 },
359 InnerNodeInfo {
360 value: l1n0,
361 left: l2n0,
362 right: l2n1,
363 },
364 InnerNodeInfo {
365 value: l1n1,
366 left: l2n2,
367 right: l2n3,
368 },
369 ];
370 assert_eq!(nodes, expected);
371
372 Ok(())
373 }
374
375 proptest! {
376 #[test]
377 fn arbitrary_word_can_be_represented_as_digest(
378 a in prop::num::u64::ANY,
379 b in prop::num::u64::ANY,
380 c in prop::num::u64::ANY,
381 d in prop::num::u64::ANY,
382 ) {
383 // this test will assert the memory equivalence between word and digest.
384 // it is used to safeguard the `[MerkleTee::update_leaf]` implementation
385 // that assumes this equivalence.
386
387 // build a word and copy it to another address as digest
388 let word = [Felt::new(a), Felt::new(b), Felt::new(c), Felt::new(d)];
389 let digest = RpoDigest::from(word);
390
391 // assert the addresses are different
392 let word_ptr = (&word).as_ptr() as *const u8;
393 let digest_ptr = (&digest).as_ptr() as *const u8;
394 assert_ne!(word_ptr, digest_ptr);
395
396 // compare the bytes representation
397 let word_bytes = unsafe { slice::from_raw_parts(word_ptr, size_of::<Word>()) };
398 let digest_bytes = unsafe { slice::from_raw_parts(digest_ptr, size_of::<RpoDigest>()) };
399 assert_eq!(word_bytes, digest_bytes);
400 }
401 }
402
403 // HELPER FUNCTIONS
404 // --------------------------------------------------------------------------------------------
405
406 fn compute_internal_nodes() -> (Word, Word, Word) {
407 let node2 = Rpo256::hash_elements(&[LEAVES4[0], LEAVES4[1]].concat());
408 let node3 = Rpo256::hash_elements(&[LEAVES4[2], LEAVES4[3]].concat());
409 let root = Rpo256::merge(&[node2, node3]);
410
411 (root.into(), node2.into(), node3.into())
412 }
413}