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 pub(crate) 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 is 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 is 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 debug_assert!(index.is_root(), "the path must include the root");
112
113 Ok(path.into())
114 }
115
116 /// Replaces the leaf at the specified index with the provided value.
117 ///
118 /// # Errors
119 /// Returns an error if the specified index value is not a valid leaf value for this tree.
120 pub fn update_leaf<'a>(&'a mut self, index_value: u64, value: Word) -> Result<(), MerkleError> {
121 let depth = self.depth();
122 let mut index = NodeIndex::new(depth, index_value);
123 if !index.is_valid() {
124 return Err(MerkleError::InvalidIndex(index));
125 }
126
127 // we don't need to copy the pairs into a new address as we are logically guaranteed to not
128 // overlap write instructions. however, it's important to bind the lifetime of pairs to
129 // `self.nodes` so the compiler will never move one without moving the other.
130 debug_assert_eq!(self.nodes.len() & 1, 0);
131 let n = self.nodes.len() / 2;
132
133 // Safety: the length of nodes is guaranteed to contain pairs of words; hence, pairs of
134 // digests. we explicitly bind the lifetime here so we add an extra layer of guarantee that
135 // `self.nodes` will be moved only if `pairs` is moved as well. also, the algorithm is
136 // logically guaranteed to not overlap write positions as the write index is always half
137 // the index from which we read the digest input.
138 let ptr = self.nodes.as_ptr() as *const [RpoDigest; 2];
139 let pairs: &'a [[RpoDigest; 2]] = unsafe { slice::from_raw_parts(ptr, n) };
140
141 // update the current node
142 let pos = index.to_scalar_index() as usize;
143 self.nodes[pos] = value;
144
145 // traverse to the root, updating each node with the merged values of its parents
146 for _ in 0..index.depth() {
147 index.move_up();
148 let pos = index.to_scalar_index() as usize;
149 let value = Rpo256::merge(&pairs[pos]).into();
150 self.nodes[pos] = value;
151 }
152
153 Ok(())
154 }
155}
156
157// TESTS
158// ================================================================================================
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163 use crate::merkle::int_to_node;
164 use core::mem::size_of;
165 use proptest::prelude::*;
166
167 const LEAVES4: [Word; 4] = [
168 int_to_node(1),
169 int_to_node(2),
170 int_to_node(3),
171 int_to_node(4),
172 ];
173
174 const LEAVES8: [Word; 8] = [
175 int_to_node(1),
176 int_to_node(2),
177 int_to_node(3),
178 int_to_node(4),
179 int_to_node(5),
180 int_to_node(6),
181 int_to_node(7),
182 int_to_node(8),
183 ];
184
185 #[test]
186 fn build_merkle_tree() {
187 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
188 assert_eq!(8, tree.nodes.len());
189
190 // leaves were copied correctly
191 for (a, b) in tree.nodes.iter().skip(4).zip(LEAVES4.iter()) {
192 assert_eq!(a, b);
193 }
194
195 let (root, node2, node3) = compute_internal_nodes();
196
197 assert_eq!(root, tree.nodes[1]);
198 assert_eq!(node2, tree.nodes[2]);
199 assert_eq!(node3, tree.nodes[3]);
200
201 assert_eq!(root, tree.root());
202 }
203
204 #[test]
205 fn get_leaf() {
206 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
207
208 // check depth 2
209 assert_eq!(LEAVES4[0], tree.get_node(NodeIndex::new(2, 0)).unwrap());
210 assert_eq!(LEAVES4[1], tree.get_node(NodeIndex::new(2, 1)).unwrap());
211 assert_eq!(LEAVES4[2], tree.get_node(NodeIndex::new(2, 2)).unwrap());
212 assert_eq!(LEAVES4[3], tree.get_node(NodeIndex::new(2, 3)).unwrap());
213
214 // check depth 1
215 let (_, node2, node3) = compute_internal_nodes();
216
217 assert_eq!(node2, tree.get_node(NodeIndex::new(1, 0)).unwrap());
218 assert_eq!(node3, tree.get_node(NodeIndex::new(1, 1)).unwrap());
219 }
220
221 #[test]
222 fn get_path() {
223 let tree = super::MerkleTree::new(LEAVES4.to_vec()).unwrap();
224
225 let (_, node2, node3) = compute_internal_nodes();
226
227 // check depth 2
228 assert_eq!(
229 vec![LEAVES4[1], node3],
230 *tree.get_path(NodeIndex::new(2, 0)).unwrap()
231 );
232 assert_eq!(
233 vec![LEAVES4[0], node3],
234 *tree.get_path(NodeIndex::new(2, 1)).unwrap()
235 );
236 assert_eq!(
237 vec![LEAVES4[3], node2],
238 *tree.get_path(NodeIndex::new(2, 2)).unwrap()
239 );
240 assert_eq!(
241 vec![LEAVES4[2], node2],
242 *tree.get_path(NodeIndex::new(2, 3)).unwrap()
243 );
244
245 // check depth 1
246 assert_eq!(vec![node3], *tree.get_path(NodeIndex::new(1, 0)).unwrap());
247 assert_eq!(vec![node2], *tree.get_path(NodeIndex::new(1, 1)).unwrap());
248 }
249
250 #[test]
251 fn update_leaf() {
252 let mut tree = super::MerkleTree::new(LEAVES8.to_vec()).unwrap();
253
254 // update one leaf
255 let value = 3;
256 let new_node = int_to_node(9);
257 let mut expected_leaves = LEAVES8.to_vec();
258 expected_leaves[value as usize] = new_node;
259 let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
260
261 tree.update_leaf(value, new_node).unwrap();
262 assert_eq!(expected_tree.nodes, tree.nodes);
263
264 // update another leaf
265 let value = 6;
266 let new_node = int_to_node(10);
267 expected_leaves[value as usize] = new_node;
268 let expected_tree = super::MerkleTree::new(expected_leaves.clone()).unwrap();
269
270 tree.update_leaf(value, new_node).unwrap();
271 assert_eq!(expected_tree.nodes, tree.nodes);
272 }
273
274 proptest! {
275 #[test]
276 fn arbitrary_word_can_be_represented_as_digest(
277 a in prop::num::u64::ANY,
278 b in prop::num::u64::ANY,
279 c in prop::num::u64::ANY,
280 d in prop::num::u64::ANY,
281 ) {
282 // this test will assert the memory equivalence between word and digest.
283 // it is used to safeguard the `[MerkleTee::update_leaf]` implementation
284 // that assumes this equivalence.
285
286 // build a word and copy it to another address as digest
287 let word = [Felt::new(a), Felt::new(b), Felt::new(c), Felt::new(d)];
288 let digest = RpoDigest::from(word);
289
290 // assert the addresses are different
291 let word_ptr = (&word).as_ptr() as *const u8;
292 let digest_ptr = (&digest).as_ptr() as *const u8;
293 assert_ne!(word_ptr, digest_ptr);
294
295 // compare the bytes representation
296 let word_bytes = unsafe { slice::from_raw_parts(word_ptr, size_of::<Word>()) };
297 let digest_bytes = unsafe { slice::from_raw_parts(digest_ptr, size_of::<RpoDigest>()) };
298 assert_eq!(word_bytes, digest_bytes);
299 }
300 }
301
302 // HELPER FUNCTIONS
303 // --------------------------------------------------------------------------------------------
304
305 fn compute_internal_nodes() -> (Word, Word, Word) {
306 let node2 = Rpo256::hash_elements(&[LEAVES4[0], LEAVES4[1]].concat());
307 let node3 = Rpo256::hash_elements(&[LEAVES4[2], LEAVES4[3]].concat());
308 let root = Rpo256::merge(&[node2, node3]);
309
310 (root.into(), node2.into(), node3.into())
311 }
312}