1use crate::batching::{BATCH_NUM_LEAVES, PARALLEL_PAIRS, hash_pairs, perfect_subtree_root};
2use crate::{MerkleHasher, NewMerkleHasherForTreeSize};
3#[cfg(feature = "alloc")]
4use alloc::boxed::Box;
5use core::iter::TrustedLen;
6use core::mem::MaybeUninit;
7use core::num::NonZero;
8
9const TREE_SIZE_WITHOUT_LEAVES<const N: usize>: usize = {
10 assert!(
12 N.is_power_of_two(),
13 "Balanced Merkle Tree must have a number of leaves that is a power of 2"
14 );
15
16 assert!(
17 N > 1,
18 "This Balanced Merkle Tree must have more than one leaf"
19 );
20
21 N - 1
22};
23pub const PROOF_ELEMENTS<const N: usize>: usize = N.ilog2() as usize;
25const ROOT_ONLY_LARGE_STACK_SIZE<const N: usize, H: MerkleHasher>: usize = {
26 if N < BATCH_NUM_LEAVES::<H> {
29 1
30 } else {
31 (N / BATCH_NUM_LEAVES::<H>).ilog2() as usize + 1
32 }
33};
34
35#[derive(Debug)]
55pub struct BalancedMerkleTree<'a, const N: usize, H>
56where
57 H: MerkleHasher,
58{
59 leaves: &'a [[u8; H::OUT_LEN]; N],
60 tree: [[u8; H::OUT_LEN]; TREE_SIZE_WITHOUT_LEAVES::<N>],
62}
63
64impl<'a, const N: usize, H> BalancedMerkleTree<'a, N, H>
65where
66 [(); TREE_SIZE_WITHOUT_LEAVES::<N>]:,
67 H: MerkleHasher + const NewMerkleHasherForTreeSize,
68{
69 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
74 pub fn new(leaves: &'a [[u8; H::OUT_LEN]; N]) -> Self {
75 const { TREE_SIZE_WITHOUT_LEAVES::<N> };
78
79 let mut tree = [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); _];
80
81 Self::init_internal(leaves, &mut tree);
82
83 Self {
84 leaves,
85 tree: unsafe { tree.transpose().assume_init() },
87 }
88 }
89
90 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
92 pub fn new_in<'b>(
93 instance: &'b mut MaybeUninit<Self>,
94 leaves: &'a [[u8; H::OUT_LEN]; N],
95 ) -> &'b mut Self {
96 const { TREE_SIZE_WITHOUT_LEAVES::<N> };
99
100 let instance_ptr = instance.as_mut_ptr();
101 unsafe {
103 (&raw mut (*instance_ptr).leaves).write(leaves);
104 }
105 let tree = {
106 let tree_ptr = unsafe { &raw mut (*instance_ptr).tree };
108 unsafe {
110 tree_ptr
111 .cast::<[MaybeUninit<[u8; H::OUT_LEN]>; TREE_SIZE_WITHOUT_LEAVES::<N>]>()
112 .as_mut_unchecked()
113 }
114 };
115
116 Self::init_internal(leaves, tree);
117
118 unsafe { instance.assume_init_mut() }
120 }
121
122 #[cfg(feature = "alloc")]
125 pub fn new_boxed(leaves: &'a [[u8; H::OUT_LEN]; N]) -> Box<Self> {
126 let mut instance = Box::<Self>::new_uninit();
127
128 Self::new_in(&mut instance, leaves);
129
130 unsafe { instance.assume_init() }
132 }
133
134 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
135 fn init_internal(
136 leaves: &[[u8; H::OUT_LEN]; N],
137 tree: &mut [MaybeUninit<[u8; H::OUT_LEN]>; TREE_SIZE_WITHOUT_LEAVES::<N>],
138 ) {
139 let hasher = const { H::new_for_tree_size(N as u64) };
140 let mut tree_hashes = tree.as_mut_slice();
141 let mut level_hashes = leaves.as_slice();
142
143 while level_hashes.len() > 1 {
144 let num_pairs = level_hashes.len() / 2;
145 let parent_hashes;
146 (parent_hashes, tree_hashes) = unsafe { tree_hashes.split_at_mut_unchecked(num_pairs) };
149
150 let (parent_hashes_chunks, parent_hashes_remainder) =
151 parent_hashes.as_chunks_mut::<{ PARALLEL_PAIRS::<H> }>();
152 if parent_hashes_remainder.is_empty() {
153 for (pairs, hashes) in level_hashes
154 .as_chunks::<{ BATCH_NUM_LEAVES::<H> }>()
155 .0
156 .iter()
157 .zip(parent_hashes_chunks)
158 {
159 *hashes = MaybeUninit::new(hash_pairs(&hasher, pairs)).into();
162 }
163 } else {
164 for (pair, parent_hash) in level_hashes
165 .as_chunks::<2>()
166 .0
167 .iter()
168 .zip(parent_hashes.iter_mut())
169 {
170 parent_hash.write(hasher.hash_pair(pair));
171 }
172 }
173
174 level_hashes = unsafe { parent_hashes.assume_init_ref() };
176 }
177 }
178
179 #[inline]
185 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
186 pub fn compute_root_only(leaves: &[[u8; H::OUT_LEN]; N]) -> [u8; H::OUT_LEN] {
187 const { TREE_SIZE_WITHOUT_LEAVES::<N> };
190
191 let hasher = const { H::new_for_tree_size(N as u64) };
192
193 if N < BATCH_NUM_LEAVES::<H> {
195 let mut nodes = *leaves;
196 return unsafe { perfect_subtree_root(&hasher, &mut nodes) };
198 }
199
200 let mut stack =
203 [[[0u8; H::OUT_LEN]; PARALLEL_PAIRS::<H>]; ROOT_ONLY_LARGE_STACK_SIZE::<N, H>];
204
205 let mut parent_current = [[0u8; H::OUT_LEN]; BATCH_NUM_LEAVES::<H>];
208 for (num_chunks, chunk_leaves) in leaves
209 .as_chunks::<{ BATCH_NUM_LEAVES::<H> }>()
210 .0
211 .iter()
212 .enumerate()
213 {
214 let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
215
216 let current = hash_pairs::<{ PARALLEL_PAIRS::<H> }, _, _>(&hasher, chunk_leaves);
217 current_half.copy_from_slice(¤t);
218
219 let lowest_active_levels = num_chunks.trailing_ones() as usize;
221 for parent in &mut stack[..lowest_active_levels] {
222 let parent_half = &mut parent_current[..PARALLEL_PAIRS::<H>];
223 parent_half.copy_from_slice(parent);
224
225 let current = hash_pairs::<{ PARALLEL_PAIRS::<H> }, _, _>(&hasher, &parent_current);
226
227 let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
228 current_half.copy_from_slice(¤t);
229 }
230
231 let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
232
233 stack[lowest_active_levels].copy_from_slice(current_half);
235 }
236
237 unsafe { perfect_subtree_root(&hasher, &mut stack[ROOT_ONLY_LARGE_STACK_SIZE::<N, H> - 1]) }
240 }
241
242 #[inline]
244 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
245 pub fn root(&self) -> [u8; H::OUT_LEN] {
246 *self
247 .tree
248 .last()
249 .or(self.leaves.last())
250 .expect("There is always at least one leaf hash; qed")
251 }
252
253 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
255 pub fn all_proofs(&self) -> ProofsIterator<'_, N, H> {
256 ProofsIterator {
257 leaves: self.leaves,
258 tree: &self.tree,
259 leaf_index: 0,
260 }
261 }
262
263 #[inline]
265 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
266 pub fn verify(
267 root: &[u8; H::OUT_LEN],
268 proof: &[[u8; H::OUT_LEN]; PROOF_ELEMENTS::<N>],
269 leaf_index: usize,
270 leaf: [u8; H::OUT_LEN],
271 ) -> bool {
272 const { TREE_SIZE_WITHOUT_LEAVES::<N> };
275
276 if leaf_index >= N {
277 return false;
278 }
279
280 let hasher = const { H::new_for_tree_size(N as u64) };
281 let mut computed_root = leaf;
282
283 let mut position = leaf_index;
284 for hash in proof {
285 computed_root = if position.is_multiple_of(2) {
286 hasher.hash_pair(&[computed_root, *hash])
287 } else {
288 hasher.hash_pair(&[*hash, computed_root])
289 };
290
291 position /= 2;
292 }
293
294 root == &computed_root
295 }
296}
297
298#[derive(Debug)]
300pub struct ProofsIterator<'a, const N: usize, H>
301where
302 H: MerkleHasher,
303{
304 leaves: &'a [[u8; H::OUT_LEN]; N],
305 tree: &'a [[u8; H::OUT_LEN]; TREE_SIZE_WITHOUT_LEAVES::<N>],
306 leaf_index: usize,
308}
309
310impl<const N: usize, H> ProofsIterator<'_, N, H>
311where
312 H: MerkleHasher,
313{
314 #[inline(always)]
315 fn remaining(&self) -> usize {
316 N - self.leaf_index
317 }
318}
319
320impl<const N: usize, H> Iterator for ProofsIterator<'_, N, H>
321where
322 H: MerkleHasher,
323{
324 type Item = [[u8; H::OUT_LEN]; PROOF_ELEMENTS::<N>];
325
326 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
327 fn next(&mut self) -> Option<Self::Item> {
328 let index = self.leaf_index;
329
330 let sibling_index = index ^ 1;
337 let sibling_hash = *self.leaves.get(sibling_index)?;
340 self.leaf_index += 1;
341
342 let mut proof = [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); _];
343 proof[0].write(sibling_hash);
344
345 let shared_proof = &mut proof[1..];
347
348 let mut tree_hashes = self.tree.as_slice();
349 let mut parent_position = index / 2;
350 let mut parent_level_size = N / 2;
351
352 for hash in shared_proof {
353 let parent_other_position = parent_position ^ 1;
354
355 let other_hash = tree_hashes.get(parent_other_position).expect(
356 "`parent_position` is within the current level of the tree, whose size is an \
357 even number; qed",
358 );
359 hash.write(*other_hash);
360 tree_hashes = &tree_hashes[parent_level_size..];
361
362 parent_position /= 2;
363 parent_level_size /= 2;
364 }
365
366 Some(unsafe { proof.transpose().assume_init() })
368 }
369
370 #[inline(always)]
371 fn size_hint(&self) -> (usize, Option<usize>) {
372 let remaining = self.remaining();
373 (remaining, Some(remaining))
374 }
375
376 #[inline(always)]
377 fn count(self) -> usize {
378 self.remaining()
379 }
380
381 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
382 fn last(mut self) -> Option<Self::Item> {
383 if self.leaf_index >= N {
384 return None;
385 }
386 self.leaf_index = N - 1;
387 self.next()
388 }
389
390 #[inline(always)]
391 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
392 let advance = n.min(self.remaining());
393 self.leaf_index += advance;
394 NonZero::new(n - advance).map_or(Ok(()), Err)
395 }
396
397 #[inline(always)]
398 fn nth(&mut self, n: usize) -> Option<Self::Item> {
399 match self.advance_by(n) {
400 Ok(()) => self.next(),
401 Err(_) => None,
402 }
403 }
404}
405
406impl<const N: usize, H> ExactSizeIterator for ProofsIterator<'_, N, H>
407where
408 H: MerkleHasher,
409{
410 #[inline(always)]
411 fn len(&self) -> usize {
412 self.remaining()
413 }
414}
415
416unsafe impl<const N: usize, H> TrustedLen for ProofsIterator<'_, N, H> where H: MerkleHasher {}