ab_merkle_tree/
balanced.rs1use crate::{hash_pair, hash_pair_block, hash_pairs};
2use ab_blake3::{BLOCK_LEN, OUT_LEN};
3#[cfg(feature = "alloc")]
4use alloc::boxed::Box;
5use core::iter::TrustedLen;
6use core::mem;
7use core::mem::MaybeUninit;
8use core::num::NonZero;
9
10const BATCH_HASH_NUM_BLOCKS: usize = 16;
12const BATCH_HASH_NUM_LEAVES: usize = BATCH_HASH_NUM_BLOCKS * BLOCK_LEN / OUT_LEN;
14
15pub const fn compute_root_only_large_stack_size(n: usize) -> usize {
18 if n < BATCH_HASH_NUM_LEAVES {
21 return 1;
22 }
23
24 (n / BATCH_HASH_NUM_LEAVES).ilog2() as usize + 1
25}
26
27pub const fn ensure_supported_n(n: usize) -> usize {
32 assert!(
33 n.is_power_of_two(),
34 "Balanced Merkle Tree must have a number of leaves that is a power of 2"
35 );
36
37 assert!(
38 n > 1,
39 "This Balanced Merkle Tree must have more than one leaf"
40 );
41
42 0
43}
44
45#[derive(Debug)]
63pub struct BalancedMerkleTree<'a, const N: usize>
64where
65 [(); N - 1]:,
66{
67 leaves: &'a [[u8; OUT_LEN]],
68 tree: [[u8; OUT_LEN]; N - 1],
70}
71
72impl<'a, const N: usize> BalancedMerkleTree<'a, N>
75where
76 [(); N - 1]:,
77 [(); ensure_supported_n(N)]:,
78{
79 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
84 pub fn new(leaves: &'a [[u8; OUT_LEN]; N]) -> Self {
85 let mut tree = [MaybeUninit::<[u8; OUT_LEN]>::uninit(); _];
86
87 Self::init_internal(leaves, &mut tree);
88
89 Self {
90 leaves,
91 tree: unsafe { tree.transpose().assume_init() },
93 }
94 }
95
96 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
98 pub fn new_in<'b>(
99 instance: &'b mut MaybeUninit<Self>,
100 leaves: &'a [[u8; OUT_LEN]; N],
101 ) -> &'b mut Self {
102 let instance_ptr = instance.as_mut_ptr();
103 unsafe {
105 (&raw mut (*instance_ptr).leaves).write(leaves);
106 }
107 let tree = {
108 let tree_ptr = unsafe { &raw mut (*instance_ptr).tree };
110 unsafe {
112 tree_ptr
113 .cast::<[MaybeUninit<[u8; OUT_LEN]>; N - 1]>()
114 .as_mut_unchecked()
115 }
116 };
117
118 Self::init_internal(leaves, tree);
119
120 unsafe { instance.assume_init_mut() }
122 }
123
124 #[cfg(feature = "alloc")]
127 pub fn new_boxed(leaves: &'a [[u8; OUT_LEN]; N]) -> Box<Self> {
128 let mut instance = Box::<Self>::new_uninit();
129
130 Self::new_in(&mut instance, leaves);
131
132 unsafe { instance.assume_init() }
134 }
135
136 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
137 fn init_internal(leaves: &[[u8; OUT_LEN]; N], tree: &mut [MaybeUninit<[u8; OUT_LEN]>; N - 1]) {
138 let mut tree_hashes = tree.as_mut_slice();
139 let mut level_hashes = leaves.as_slice();
140
141 while level_hashes.len() > 1 {
142 let num_pairs = level_hashes.len() / 2;
143 let parent_hashes;
144 (parent_hashes, tree_hashes) = unsafe { tree_hashes.split_at_mut_unchecked(num_pairs) };
147
148 if parent_hashes.len().is_multiple_of(BATCH_HASH_NUM_BLOCKS) {
149 let parent_hashes_chunks =
151 unsafe { parent_hashes.as_chunks_unchecked_mut::<BATCH_HASH_NUM_BLOCKS>() };
152 for (pairs, hashes) in level_hashes
153 .as_chunks::<BATCH_HASH_NUM_LEAVES>()
154 .0
155 .iter()
156 .zip(parent_hashes_chunks)
157 {
158 let hashes = unsafe {
162 mem::transmute::<
163 &mut [MaybeUninit<[u8; OUT_LEN]>; BATCH_HASH_NUM_BLOCKS],
164 &mut MaybeUninit<[[u8; OUT_LEN]; BATCH_HASH_NUM_BLOCKS]>,
165 >(hashes)
166 };
167
168 hashes.write(hash_pairs(pairs));
171 }
172 } else {
173 for (pair, parent_hash) in level_hashes
174 .as_chunks()
175 .0
176 .iter()
177 .zip(parent_hashes.iter_mut())
178 {
179 let pair = unsafe {
181 mem::transmute::<&[[u8; OUT_LEN]; BLOCK_LEN / OUT_LEN], &[u8; BLOCK_LEN]>(
182 pair,
183 )
184 };
185 parent_hash.write(hash_pair_block(pair));
186 }
187 }
188
189 level_hashes = unsafe { parent_hashes.assume_init_ref() };
191 }
192 }
193
194 #[inline]
200 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
201 pub fn compute_root_only(leaves: &[[u8; OUT_LEN]; N]) -> [u8; OUT_LEN]
202 where
203 [(); N.ilog2() as usize + 1]:,
204 [(); compute_root_only_large_stack_size(N)]:,
205 {
206 match N {
208 2 => {
209 let [root] = hash_pairs(leaves);
210
211 return root;
212 }
213 4 => {
214 let hashes = hash_pairs::<2, _>(leaves);
215 let [root] = hash_pairs(&hashes);
216
217 return root;
218 }
219 8 => {
220 let hashes = hash_pairs::<4, _>(leaves);
221 let hashes = hash_pairs::<2, _>(&hashes);
222 let [root] = hash_pairs(&hashes);
223
224 return root;
225 }
226 16 => {
227 let hashes = hash_pairs::<8, _>(leaves);
228 let hashes = hash_pairs::<4, _>(&hashes);
229 let hashes = hash_pairs::<2, _>(&hashes);
230 let [root] = hash_pairs(&hashes);
231
232 return root;
233 }
234 _ => {
235 assert!(N >= BATCH_HASH_NUM_LEAVES);
237 }
238 }
239
240 let mut stack =
244 [[[0u8; OUT_LEN]; BATCH_HASH_NUM_BLOCKS]; compute_root_only_large_stack_size(N)];
245
246 let mut parent_current = [[0u8; OUT_LEN]; BATCH_HASH_NUM_LEAVES];
249 for (num_chunks, chunk_leaves) in leaves
250 .as_chunks::<BATCH_HASH_NUM_LEAVES>()
251 .0
252 .iter()
253 .enumerate()
254 {
255 let current_half = &mut parent_current[BATCH_HASH_NUM_BLOCKS..];
256
257 let current = hash_pairs::<BATCH_HASH_NUM_BLOCKS, _>(chunk_leaves);
258 current_half.copy_from_slice(¤t);
259
260 let lowest_active_levels = num_chunks.trailing_ones() as usize;
262 for parent in &mut stack[..lowest_active_levels] {
263 let parent_half = &mut parent_current[..BATCH_HASH_NUM_BLOCKS];
264 parent_half.copy_from_slice(parent);
265
266 let current = hash_pairs::<BATCH_HASH_NUM_BLOCKS, _>(&parent_current);
267
268 let current_half = &mut parent_current[BATCH_HASH_NUM_BLOCKS..];
269 current_half.copy_from_slice(¤t);
270 }
271
272 let current_half = &mut parent_current[BATCH_HASH_NUM_BLOCKS..];
273
274 stack[lowest_active_levels].copy_from_slice(current_half);
276 }
277
278 let hashes = &mut stack[compute_root_only_large_stack_size(N) - 1];
279 let hashes = hash_pairs::<{ BATCH_HASH_NUM_BLOCKS / 2 }, _>(hashes);
280 let hashes = hash_pairs::<{ BATCH_HASH_NUM_BLOCKS / 4 }, _>(&hashes);
281 let hashes = hash_pairs::<{ BATCH_HASH_NUM_BLOCKS / 8 }, _>(&hashes);
282 let [root] = hash_pairs::<{ BATCH_HASH_NUM_BLOCKS / 16 }, _>(&hashes);
283
284 root
285 }
286
287 #[inline]
289 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
290 pub fn root(&self) -> [u8; OUT_LEN] {
291 *self
292 .tree
293 .last()
294 .or(self.leaves.last())
295 .expect("There is always at least one leaf hash; qed")
296 }
297
298 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
300 pub fn all_proofs(
301 &self,
302 ) -> impl ExactSizeIterator<Item = [[u8; OUT_LEN]; N.ilog2() as usize]> + TrustedLen
303 where
304 [(); N.ilog2() as usize]:,
305 {
306 let iter = self.leaves.as_chunks().0.iter().enumerate().flat_map(
307 |(pair_index, &[left_hash, right_hash])| {
308 let mut left_proof = [MaybeUninit::<[u8; OUT_LEN]>::uninit(); _];
309 left_proof[0].write(right_hash);
310
311 let left_proof = {
312 let shared_proof = &mut left_proof[1..];
313
314 let mut tree_hashes = self.tree.as_slice();
315 let mut parent_position = pair_index;
316 let mut parent_level_size = N / 2;
317
318 for hash in shared_proof {
319 let parent_other_position = parent_position ^ 1;
326
327 let other_hash =
329 unsafe { tree_hashes.get_unchecked(parent_other_position) };
330 hash.write(*other_hash);
331 tree_hashes = &tree_hashes[parent_level_size..];
332
333 parent_position /= 2;
334 parent_level_size /= 2;
335 }
336
337 unsafe { left_proof.transpose().assume_init() }
339 };
340
341 let mut right_proof = left_proof;
342 right_proof[0] = left_hash;
343
344 [left_proof, right_proof]
345 },
346 );
347
348 ProofsIterator { iter, len: N }
349 }
350
351 #[inline]
353 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
354 pub fn verify(
355 root: &[u8; OUT_LEN],
356 proof: &[[u8; OUT_LEN]; N.ilog2() as usize],
357 leaf_index: usize,
358 leaf: [u8; OUT_LEN],
359 ) -> bool
360 where
361 [(); N.ilog2() as usize]:,
362 {
363 if leaf_index >= N {
364 return false;
365 }
366
367 let mut computed_root = leaf;
368
369 let mut position = leaf_index;
370 for hash in proof {
371 computed_root = if position.is_multiple_of(2) {
372 hash_pair(&computed_root, hash)
373 } else {
374 hash_pair(hash, &computed_root)
375 };
376
377 position /= 2;
378 }
379
380 root == &computed_root
381 }
382}
383
384struct ProofsIterator<Iter> {
385 iter: Iter,
386 len: usize,
387}
388
389impl<Iter> Iterator for ProofsIterator<Iter>
390where
391 Iter: Iterator,
392{
393 type Item = Iter::Item;
394
395 #[inline(always)]
396 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
397 fn next(&mut self) -> Option<Self::Item> {
398 let item = self.iter.next();
399 self.len = self.len.saturating_sub(1);
400 item
401 }
402
403 #[inline(always)]
404 fn size_hint(&self) -> (usize, Option<usize>) {
405 (self.len, Some(self.len))
406 }
407
408 #[inline(always)]
409 fn count(self) -> usize
410 where
411 Self: Sized,
412 {
413 self.len
414 }
415
416 #[inline(always)]
417 fn last(self) -> Option<Self::Item>
418 where
419 Self: Sized,
420 {
421 self.iter.last()
422 }
423
424 #[inline(always)]
425 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
426 self.len = self.len.saturating_sub(n);
427 self.iter.advance_by(n)
428 }
429
430 #[inline(always)]
431 fn nth(&mut self, n: usize) -> Option<Self::Item> {
432 self.len = self.len.saturating_sub(n.saturating_add(1));
433 self.iter.nth(n)
434 }
435}
436
437impl<Iter> ExactSizeIterator for ProofsIterator<Iter>
438where
439 Iter: Iterator,
440{
441 #[inline(always)]
442 fn len(&self) -> usize {
443 self.len
444 }
445}
446
447unsafe impl<Iter> TrustedLen for ProofsIterator<Iter> where Iter: Iterator {}