merkle_lite/
lib.rs

1//! A binary Merkle tree and proof.
2//!
3//! [merkle tree and proof]: https://en.wikipedia.org/wiki/Merkle_tree
4//! [rust crypto]: https://github.com/RustCrypto
5//!
6//! A simple, fast, and composable binary [Merkle tree and proof] for
7//! [Rust Crypto] hash functions.
8//!
9//! # Examples
10//!
11//! [`merkletree`]: struct.MerkleTree.html
12//! [`merkleproof`]: struct.MerkleProof.html
13//!
14//! It's super simple to compose [MerkleTree] from the ordered array
15//! of hashes and verify the proof of inclusion with [MerkleProof]:
16//!
17//! ```
18//! use merkle_lite::MerkleTree;
19//! use rand_core::RngCore;
20//!
21//! // Composes MerkleTree from the 50,000 random hashes.
22//! let tree: MerkleTree<sha3::Sha3_256> = std::iter::repeat([0u8; 32])
23//!     .map(|mut leaf| {
24//!         rand_core::OsRng.fill_bytes(&mut leaf);
25//!         leaf
26//!     })
27//!     .take(50_000)
28//!     .collect();
29//!
30//! // Verifies the proof of inclusion for the arbitrary leaves.
31//! let tree_leaves = tree.get_leaves();
32//! let leaf_indices = [12, 0, 1, 1201, 13_903, 980];
33//! let leaf_hashes: Vec<_> = leaf_indices
34//!     .iter()
35//!     .map(|index| (*index, tree_leaves[*index]))
36//!     .collect();
37//! assert_eq!(
38//!     tree.proof(&leaf_indices)
39//!         .expect("proof")
40//!         .verify(&leaf_hashes)
41//!         .expect("verify")
42//!         .as_ref(),
43//!     tree.root().expect("root"),
44//! );
45//! ```
46
47#![no_std]
48#![forbid(unsafe_code, missing_docs, missing_debug_implementations)]
49
50extern crate alloc;
51
52use core::fmt::{self, Debug};
53use core::mem;
54use core::ops::{Deref, DerefMut, Div, DivAssign, Index, IndexMut};
55
56use alloc::collections::{BTreeMap, BTreeSet};
57use alloc::{vec, vec::Vec};
58
59use digest::block_buffer;
60use digest::generic_array::ArrayLength;
61use digest::{Digest, OutputSizeUser};
62
63type Buffer<B> = <<B as OutputSizeUser>::OutputSize as ArrayLength<u8>>::ArrayType;
64
65/// A Merkle tree.
66///
67/// # Examples
68///
69/// Basic usage:
70/// ```
71/// use sha3::Sha3_256;
72/// use hex_literal::hex;
73///
74/// use merkle_lite::MerkleTree;
75///
76/// // 16 identical leaves for the demonstration purpose.
77/// let leaves = [[0xab_u8; 32]; 16];
78/// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
79///
80/// assert_eq!(
81///     tree.root().unwrap(),
82///     hex!("34fac4b8781d0b811746ec45623606f43df1a8b9009f89c5564e68025a6fd604"),
83/// );
84/// ```
85#[derive(Clone)]
86pub struct MerkleTree<B>
87where
88    B: Digest,
89    Buffer<B>: Copy,
90{
91    /// Provides the range of leaf node index.
92    leaf_range: NodeIndexRange,
93
94    /// Points to the contiguous memory of array of `data`, e.g. hash value.
95    data: Vec<NodeData<B>>,
96}
97
98impl<B> Debug for MerkleTree<B>
99where
100    B: Digest,
101    Buffer<B>: Copy,
102{
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.debug_struct("MerkleTree")
105            .field("leaf_range", &self.leaf_range)
106            .field("tree_depth", &self.depth())
107            .field("data_len", &self.data.len())
108            .finish()
109    }
110}
111
112impl<A, B> FromIterator<A> for MerkleTree<B>
113where
114    A: AsRef<[u8]>,
115    B: Digest,
116    Buffer<B>: Copy,
117{
118    /// Conversion from an `Iterator`.
119    ///
120    /// # Panics
121    ///
122    /// May panic in case the length of iterator item is not the valid
123    /// hash length.
124    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
125        let iter = iter.into_iter();
126        let (leaf_len, _) = iter.size_hint();
127
128        // prep the leaf nodes.
129        let mut tree = Self::with_leaf_len(leaf_len);
130        iter.for_each(|data| {
131            assert!(
132                data.as_ref().len() == <B as Digest>::output_size(),
133                "invalid hash length"
134            );
135            tree.push(NodeData::try_from(data.as_ref()).unwrap());
136        });
137
138        // nothing to do in case of the zero or single leaf tree.
139        if tree.leaf_range.len() <= 1 {
140            return tree;
141        }
142
143        // calculate the Merkle root.
144        for _ in tree.merkle_root_iter(tree.leaf_range.clone()) {}
145
146        tree
147    }
148}
149
150impl<B> MerkleTree<B>
151where
152    B: Digest,
153    Buffer<B>: Copy,
154{
155    /// Returns the number of node in the tree.
156    ///
157    /// # Examples
158    ///
159    /// Basic usage:
160    /// ```
161    /// use merkle_lite::MerkleTree;
162    /// use sha3::Sha3_256;
163    ///
164    /// let leaves = [[0u8; 32]; 2];
165    /// let tree: MerkleTree<Sha3_256> = leaves.into_iter().collect();
166    ///
167    /// assert_eq!(tree.len(), 3);
168    /// ```
169    pub fn len(&self) -> usize {
170        self.data.len()
171    }
172
173    /// Returns `true` if the tree is empty.
174    ///
175    /// # Examples
176    ///
177    /// Basic usage:
178    /// ```
179    /// use merkle_lite::MerkleTree;
180    /// use sha3::Sha3_256;
181    ///
182    /// // zero length leaf.
183    /// let leaves = [[0u8; 32]; 0];
184    /// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
185    ///
186    /// assert!(tree.is_empty());
187    /// ```
188    pub fn is_empty(&self) -> bool {
189        self.data.len() == 0
190    }
191
192    /// Returns the total number of tree node without reallocating.
193    pub fn capacity(&self) -> usize {
194        self.data.capacity()
195    }
196
197    /// Returns the length of the Merkle tree leaves.
198    ///
199    /// # Examples
200    ///
201    /// Basic usage:
202    /// ```
203    /// use merkle_lite::MerkleTree;
204    /// use sha3::Sha3_256;
205    ///
206    /// let leaves = [[0u8; 32]; 127];
207    /// let tree: MerkleTree<Sha3_256> = leaves.into_iter().collect();
208    ///
209    /// assert_eq!(tree.leaf_len(), 127);
210    /// ```
211    pub const fn leaf_len(&self) -> usize {
212        self.leaf_range.len()
213    }
214
215    /// Returns the Merkle tree depth.
216    ///
217    /// # Examples
218    ///
219    /// Basic usage:
220    /// ```
221    /// use digest::generic_array::GenericArray;
222    /// use digest::typenum::U32;
223    ///
224    /// use sha3::Sha3_256;
225    ///
226    /// use merkle_lite::MerkleTree;
227    ///
228    /// let leaves = [GenericArray::<u8, U32>::default(); 14];
229    /// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
230    ///
231    /// assert_eq!(tree.depth(), 5);
232    /// ```
233    pub fn depth(&self) -> usize {
234        (usize::BITS - self.data.len().leading_zeros()) as usize
235    }
236
237    /// Returns the Merkle root.
238    ///
239    /// # Examples
240    ///
241    /// Basic usage:
242    /// ```
243    /// use sha3::Sha3_256;
244    /// use hex_literal::hex;
245    ///
246    /// use merkle_lite::MerkleTree;
247    ///
248    /// // identical leaves for the demonstration purpose.
249    /// let leaves = [[0xab_u8; 32]; 14];
250    /// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
251    ///
252    /// assert_eq!(
253    ///     tree.root().unwrap(),
254    ///     hex!("34fac4b8781d0b811746ec45623606f43df1a8b9009f89c5564e68025a6fd604"),
255    /// );
256    /// ```
257    pub fn root(&self) -> Option<&[u8]> {
258        self.data.last().map(|node| node.as_ref())
259    }
260
261    /// Returns the leaves iterator of the Merkle tree.
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// use std::iter;
267    /// use sha3::Sha3_256;
268    ///
269    /// use merkle_lite::MerkleTree;
270    ///
271    /// // create a sequencial leaf for the demonstration purpose.
272    /// let leaves = iter::repeat(0x1_u8)
273    ///     .enumerate()
274    ///     .map(|(i, byte)| [byte * i as u8; 32])
275    ///     .take(18);
276    ///
277    /// // create a Merkle tree.
278    /// let tree: MerkleTree<Sha3_256> = leaves.clone().collect();
279    ///
280    /// // test leaves.
281    /// assert_eq!(tree.leaf_len(), 18);
282    /// assert_eq!(tree.leaves().count(), 18);
283    /// for (got, want) in tree.leaves().zip(leaves) {
284    ///     assert_eq!(got, want);
285    /// }
286    /// ```
287    pub fn leaves(&self) -> impl Iterator<Item = &[u8]> {
288        self.data[self.leaf_range.as_range_usize()]
289            .iter()
290            .map(|node| node.as_ref())
291    }
292
293    /// Gets the Merkle tree leaves.
294    ///
295    /// # Example
296    ///
297    /// ```
298    /// use sha3::Sha3_256;
299    /// use hex_literal::hex;
300    ///
301    /// use merkle_lite::MerkleTree;
302    ///
303    /// // Composes a tree from sequential leaves.
304    /// let leaves: Vec<_> = [[1u8; 32]; 14]
305    ///     .iter()
306    ///     .enumerate()
307    ///     .map(|(i, mut leaf)| leaf.map(|mut leaf| {
308    ///         leaf *= i as u8;
309    ///         leaf
310    ///     }))
311    ///     .collect();
312    /// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
313    ///
314    /// // Gets the `MerkleLeaves` and checks each element.
315    /// let tree_leaves = tree.get_leaves();
316    /// for (i, leaf) in leaves.iter().enumerate() {
317    ///     assert_eq!(tree_leaves[i].as_slice(), leaf);
318    /// }
319    /// ```
320    pub fn get_leaves(&self) -> MerkleLeaves<B> {
321        MerkleLeaves {
322            leaves: &self.data[self.leaf_range.as_range_usize()],
323        }
324    }
325
326    /// Gets the mutable Merkle tree leaves.
327    ///
328    /// Please note that updating the Merkle tree through this
329    /// `MerkleLeavesMut` is inefficient because it re-calculate
330    /// the Merkle root once `MerkleLeavesMut` drops.
331    ///
332    /// # Example
333    ///
334    /// Updating the Merkle root with the new hash values.
335    ///
336    /// ```
337    /// use sha3::Sha3_256;
338    /// use hex_literal::hex;
339    ///
340    /// use merkle_lite::MerkleTree;
341    ///
342    /// // create tree with the dummy leaves first.
343    /// let leaves = [[0u8; 32]; 14];
344    /// let mut tree: MerkleTree<Sha3_256> = leaves.iter().collect();
345    /// {
346    ///     let mut tree_leaves = tree.get_leaves_mut();
347    ///
348    ///     // sets the leaves with the new hash and update
349    ///     // the Merkle root when it drops.
350    ///     (0..leaves.len()).for_each(|i| {
351    ///         tree_leaves[i] = [0xab_u8; 32].into();
352    ///     });
353    /// }
354    /// assert_eq!(
355    ///     tree.root().unwrap(),
356    ///     hex!("34fac4b8781d0b811746ec45623606f43df1a8b9009f89c5564e68025a6fd604"),
357    /// );
358    /// ```
359    pub fn get_leaves_mut(&mut self) -> MerkleLeavesMut<B> {
360        MerkleLeavesMut {
361            changed_set: LeftNodeIndexSet::default(),
362            tree: self,
363        }
364    }
365
366    /// Returns a [`MerkleProof`] for the specified leaf indices.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use rand_core::RngCore;
372    /// use sha3::Sha3_256;
373    ///
374    /// use merkle_lite::MerkleTree;
375    ///
376    /// // Composes MerkleTree for the 10 random leaves.
377    /// let tree: MerkleTree<Sha3_256> = std::iter::repeat([0u8; 32])
378    ///     .map(|mut leaf| {
379    ///         rand_core::OsRng.fill_bytes(&mut leaf);
380    ///         leaf
381    ///     })
382    ///     .take(10)
383    ///     .collect();
384    ///
385    /// // Verifies the proof of inclusion for the particular leaves.
386    /// let leaves = tree.get_leaves();
387    /// assert_eq!(
388    ///     tree.proof(&[0, 1, 9])
389    ///         .unwrap()
390    ///         .verify(&[
391    ///             (1, leaves[1]),
392    ///             (9, leaves[9]),
393    ///             (0, leaves[0]),
394    ///         ])
395    ///         .unwrap()
396    ///         .as_ref(),
397    ///     tree.root().unwrap(),
398    /// );
399    /// ```
400    pub fn proof<'a, I>(&self, leaf_indices: I) -> Option<MerkleProof<B>>
401    where
402        I: IntoIterator<Item = &'a usize>,
403    {
404        // Ignore the out of range indices.
405        let leaf_indices: BTreeSet<_> = leaf_indices
406            .into_iter()
407            .map(|index| NodeIndex(*index))
408            .filter(|index| self.leaf_range.0.contains(index))
409            .collect();
410
411        // no valid leaf indices.
412        if leaf_indices.is_empty() {
413            return None;
414        }
415
416        // get the lemmas for each level all the way to the root.
417        let mut proof = MerkleProof {
418            leaf_range: self.leaf_range.clone(),
419            leaf_indices: leaf_indices.clone(),
420            lemmas: Vec::new(),
421        };
422        for lemmas in self.merkle_lemmas_iter(leaf_indices) {
423            proof.lemmas.push(lemmas);
424        }
425
426        Some(proof)
427    }
428
429    fn with_leaf_len(leaf_len: usize) -> Self {
430        let total_len = match leaf_len {
431            0 => 0,
432            leaf_len if leaf_len.is_power_of_two() => {
433                // The following equasion will give us the entire
434                // tree size, as `leaf_len - 1` represents the
435                // size of the base tree.
436                2 * leaf_len - 1
437            }
438            _ => {
439                // Counts each level length for depth's times.
440                //
441                // In case of the odd number of length, add one
442                // for the next level.
443                let mut total = 1;
444                let mut level_len = leaf_len;
445                while level_len > 1 {
446                    total += level_len;
447                    level_len = level_len / 2 + level_len % 2;
448                }
449                total
450            }
451        };
452        Self {
453            data: vec![NodeData::default(); total_len],
454            leaf_range: NodeIndexRange::default(),
455        }
456    }
457
458    fn push(&mut self, data: NodeData<B>) {
459        if *self.leaf_range.end < self.data.len() {
460            self.data[*self.leaf_range.end] = data;
461        } else {
462            self.data.push(data);
463        }
464        *self.leaf_range.end += 1;
465    }
466
467    fn merkle_root_iter(&mut self, changed_range: NodeIndexRange) -> MerkleRootIter<B> {
468        MerkleRootIter {
469            changed_range,
470            level_range: self.leaf_range.clone(),
471            data: &mut self.data[..],
472        }
473    }
474
475    fn merkle_root_set_iter(&mut self, changed_set: LeftNodeIndexSet) -> MerkleRootSetIter<B> {
476        MerkleRootSetIter {
477            changed_set,
478            level_range: self.leaf_range.clone(),
479            data: &mut self.data[..],
480        }
481    }
482
483    fn merkle_lemmas_iter(&self, leaf_indices: BTreeSet<NodeIndex>) -> MerkleLemmasIter<B> {
484        MerkleLemmasIter {
485            level_indices: leaf_indices,
486            level_range: self.leaf_range.clone(),
487            data: &self.data[..],
488        }
489    }
490}
491
492/// A shared reference to the Merkle leaves.
493///
494/// Please refer to [`MerkleRoot::get_leaves()`] for the example.
495///
496/// [`merkleroot::get_leaves()`]: struct.MerkleTree.html#method.get_leaves
497pub struct MerkleLeaves<'a, B>
498where
499    B: OutputSizeUser,
500    Buffer<B>: Copy,
501{
502    leaves: &'a [NodeData<B>],
503}
504
505impl<'a, B> Debug for MerkleLeaves<'a, B>
506where
507    B: OutputSizeUser,
508    Buffer<B>: Copy,
509{
510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511        f.debug_struct("MerkleLeaves")
512            .field("leaf_len", &self.leaves.len())
513            .finish()
514    }
515}
516
517impl<'a, B> Index<usize> for MerkleLeaves<'a, B>
518where
519    B: OutputSizeUser,
520    Buffer<B>: Copy,
521{
522    type Output = digest::Output<B>;
523
524    fn index(&self, index: usize) -> &Self::Output {
525        self.leaves[index].0.as_ref().unwrap()
526    }
527}
528
529/// A mutable reference to the Merkle leaves.
530///
531/// It accumulates the changes and triggers the Merkle root calculation
532/// when it drops.
533///
534/// Please refer to [`MerkleRoot::get_leaves_mut()`] for the example.
535///
536/// [`merkleroot::get_leaves_mut()`]: struct.MerkleTree.html#method.get_leaves_mut
537pub struct MerkleLeavesMut<'a, B>
538where
539    B: Digest,
540    Buffer<B>: Copy,
541{
542    /// A changed set of the leaf indices.
543    ///
544    /// It only keeps track of the left side of the index
545    /// to make the parent hash calculation simpler.
546    changed_set: LeftNodeIndexSet,
547
548    /// mutable reference to the tree for the merkle root calculation.
549    tree: &'a mut MerkleTree<B>,
550}
551
552impl<'a, B> Debug for MerkleLeavesMut<'a, B>
553where
554    B: Digest,
555    Buffer<B>: Copy,
556{
557    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558        f.debug_struct("MerkleLeavesMut")
559            .field("leaf_len", &self.tree.leaf_len())
560            .field("changed_set_len", &self.changed_set.len())
561            .finish()
562    }
563}
564
565impl<'a, B> Drop for MerkleLeavesMut<'a, B>
566where
567    B: Digest,
568    Buffer<B>: Copy,
569{
570    /// Calculates the Merkle root in case there is a change in the leaves.
571    fn drop(&mut self) {
572        // There is no change.
573        if self.changed_set.is_empty() {
574            return;
575        }
576        for _ in self.tree.merkle_root_set_iter(self.changed_set.clone()) {}
577    }
578}
579
580impl<'a, B> Index<usize> for MerkleLeavesMut<'a, B>
581where
582    B: Digest,
583    Buffer<B>: Copy,
584{
585    type Output = digest::Output<B>;
586
587    fn index(&self, index: usize) -> &Self::Output {
588        self.tree.data[index].0.as_ref().unwrap()
589    }
590}
591
592impl<'a, B> IndexMut<usize> for MerkleLeavesMut<'a, B>
593where
594    B: Digest,
595    Buffer<B>: Copy,
596{
597    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
598        self.changed_set
599            .insert(NodeIndex(index), &self.tree.leaf_range);
600        self.tree.data[index].0.as_mut().unwrap()
601    }
602}
603
604/// A Merkle proof.
605///
606/// A Merkle proof of the inclusion.
607///
608/// Please refer to [`MerkleRoot::proof()`] for more detail.
609///
610/// [`merkleroot::proof()`]: struct.MerkleTree.html#method.proof
611#[derive(Clone)]
612pub struct MerkleProof<B>
613where
614    B: OutputSizeUser,
615    Buffer<B>: Copy,
616{
617    /// the range of the Merkle tree leaves.
618    leaf_range: NodeIndexRange,
619
620    /// the indices of the Merkle proof verification.
621    leaf_indices: BTreeSet<NodeIndex>,
622
623    /// Merkle proof lemmas.
624    ///
625    /// It's indexed starting from the leaf level to the top.
626    /// The last entry of the vector, e.g. lemmans[lemmas.len() - 1],
627    /// will be used as a Merkle root cache for the Merkle proof
628    /// verification.
629    lemmas: Vec<BTreeMap<NodeIndex, NodeData<B>>>,
630}
631
632impl<B> Debug for MerkleProof<B>
633where
634    B: Digest,
635    Buffer<B>: Copy,
636{
637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638        f.debug_struct("MerkleProof")
639            .field("leaf_range", &self.leaf_range)
640            .field("leaf_indices_len", &self.leaf_indices.len())
641            .field("leaf_lemmas_depth", &self.lemmas.len())
642            .finish()
643    }
644}
645
646impl<B> MerkleProof<B>
647where
648    B: Digest,
649    Buffer<B>: Copy,
650{
651    /// Returns the Merkle root as the proof of inclusion.
652    ///
653    /// # Examples
654    ///
655    /// ```
656    /// use rand_core::RngCore;
657    /// use sha3::Sha3_256;
658    ///
659    /// use merkle_lite::MerkleTree;
660    ///
661    /// // A tree with 100 random leaves.
662    /// let leaves: Vec<_> = std::iter::repeat([0u8; 32])
663    ///     .map(|mut leaf| {
664    ///         rand_core::OsRng.fill_bytes(&mut leaf);
665    ///         leaf
666    ///     })
667    ///     .take(100)
668    ///     .collect();
669    ///
670    /// // A Merkle tree composed from the leaves.
671    /// let tree: MerkleTree<Sha3_256> = leaves.iter().collect();
672    ///
673    /// // A proof of inclusion for an arbitrary number of leaves
674    /// // specified by the 0-indexed ordered indices.
675    /// let proof = tree.proof(&[99, 98]).unwrap();
676    ///
677    /// // verify the merkle proof of inclusion by comparing the
678    /// // result to the Merkle root.
679    /// let inclusion = vec![(98, &leaves[98]), (99, &leaves[99])];
680    /// assert_eq!(
681    ///     proof.verify(&inclusion).unwrap().as_ref(),
682    ///     tree.root().unwrap(),
683    /// );
684    /// ```
685    pub fn verify<'a, T, I>(mut self, leaves: I) -> Option<impl AsRef<[u8]>>
686    where
687        T: AsRef<[u8]> + 'a,
688        I: IntoIterator<Item = &'a (usize, T)>,
689    {
690        let leaves: BTreeMap<_, _> = leaves
691            .into_iter()
692            .map(|(k, v)| {
693                assert!(
694                    v.as_ref().len() == <B as Digest>::output_size(),
695                    "invalid hash length"
696                );
697                let data = NodeData::<B>::try_from(v.as_ref()).unwrap();
698                (NodeIndex(*k), data)
699            })
700            .collect();
701
702        // Checks if `leaf_indices` covers all the required indices.
703        let leaf_indices: BTreeSet<_> = leaves.keys().cloned().collect();
704        if leaf_indices != self.leaf_indices {
705            return None;
706        }
707
708        // Calculates the Merkle proof root.
709        for _ in self.merkle_proof_iter(leaves) {}
710
711        // last entry of lemmas holds the merkle root.
712        self.lemmas
713            .last()
714            .and_then(|lemmas| lemmas.get(&NodeIndex(0)))
715            .and_then(|node| node.0)
716    }
717
718    fn merkle_proof_iter(
719        &mut self,
720        leaf_hashes: BTreeMap<NodeIndex, NodeData<B>>,
721    ) -> MerkleProofIter<B> {
722        MerkleProofIter {
723            level_hashes: leaf_hashes,
724            level_range: self.leaf_range.clone(),
725            lemmas: &mut self.lemmas[..],
726        }
727    }
728}
729
730/// A Merkle proof iterator.
731///
732/// Calculate the Merkle root as for the proof of inclusion.
733struct MerkleProofIter<'a, B>
734where
735    B: Digest,
736    Buffer<B>: Copy,
737{
738    /// A current level hashes to calculate the parent hashes.
739    level_hashes: BTreeMap<NodeIndex, NodeData<B>>,
740
741    /// A current level range.
742    level_range: NodeIndexRange,
743
744    /// Lemmas for the Merkle proof calculation.
745    lemmas: &'a mut [BTreeMap<NodeIndex, NodeData<B>>],
746}
747
748impl<'a, B> Iterator for MerkleProofIter<'a, B>
749where
750    B: Digest,
751    Buffer<B>: Copy,
752{
753    type Item = ();
754
755    fn next(&mut self) -> Option<Self::Item> {
756        // Gets the next level lemmas.
757        let lemmas = match mem::take(&mut self.lemmas).split_first_mut() {
758            None => return None,
759            Some((first, remains)) if remains.is_empty() => {
760                // There is a special case, not practical, that the Merkle
761                // proof had been called against the single node tree.
762                //
763                // We just copy Merkle root, which was passed by the caller.
764                if first.is_empty() {
765                    *first = self.level_hashes.clone();
766                }
767                return None;
768            }
769            Some((first, remains)) => {
770                self.lemmas = remains;
771                first
772            }
773        };
774
775        // Calculates the next level hashes.
776        let mut level_hashes = BTreeMap::new();
777        for (index, data) in &self.level_hashes {
778            let sibling_index = index.sibling(&self.level_range).unwrap();
779            let sibling = match self.level_hashes.get(&sibling_index) {
780                Some(data) => data,
781                None => match lemmas.get(&sibling_index) {
782                    None => return None,
783                    Some(data) => data,
784                },
785            };
786            let mut hasher = B::new();
787            if index.is_right(&self.level_range) {
788                hasher.update(sibling);
789                hasher.update(data);
790            } else {
791                hasher.update(data);
792                hasher.update(sibling);
793            }
794            let parent_data = NodeData::<B>::from(hasher.finalize());
795            let parent_index = *index / 2;
796            level_hashes.insert(parent_index, parent_data);
797        }
798
799        // Keeps the Markle root in case it's in the root level.
800        if self.lemmas.len() == 1 {
801            if let Some(lemma) = self.lemmas.first_mut() {
802                *lemma = level_hashes;
803            }
804        } else {
805            self.level_hashes = level_hashes;
806            self.level_range /= 2;
807        }
808
809        Some(())
810    }
811}
812
813/// A Merkle proof lemmas iterator.
814///
815/// Get the Merkle tree lemmas for the Merkle proof.
816struct MerkleLemmasIter<'a, B>
817where
818    B: OutputSizeUser,
819    Buffer<B>: Copy,
820{
821    /// A current level indices needs lemma, e.g. sibling.
822    level_indices: BTreeSet<NodeIndex>,
823
824    /// A current level index range.
825    level_range: NodeIndexRange,
826
827    /// A remaining node of tree.
828    data: &'a [NodeData<B>],
829}
830
831impl<'a, B> Iterator for MerkleLemmasIter<'a, B>
832where
833    B: OutputSizeUser,
834    Buffer<B>: Copy,
835{
836    type Item = BTreeMap<NodeIndex, NodeData<B>>;
837
838    fn next(&mut self) -> Option<Self::Item> {
839        // Checks for the completion.
840        if self.data.is_empty() {
841            return None;
842        }
843
844        // Prepares the current level node.
845        let split = *self.level_range.end;
846        let (children, parents) = mem::take(&mut self.data).split_at(split);
847        if parents.is_empty() {
848            // Set's the data to zero and returns the empty `BTreeMap`
849            // as a placeholder of the Merkle root calculated by
850            // `MerkleProofIter`.
851            self.data = parents;
852            return Some(BTreeMap::new());
853        }
854
855        // Prepares the next level index and the level lemmas.
856        let mut next_indices = BTreeSet::new();
857        let mut lemmas = BTreeMap::new();
858        for index in &self.level_indices {
859            // Remembers the parent indices for the next iteration.
860            next_indices.insert(*index / 2);
861
862            // Gets the sibling index.
863            let sibling = index.sibling(&self.level_range).unwrap();
864
865            // We don't need to store the lemma in case of
866            // the sibling pair is IN the `level_indices`.
867            if self.level_indices.contains(&sibling) {
868                continue;
869            }
870
871            // Stores the lemma.
872            //
873            // If in case the sibling is out of range, stores itself.
874            if sibling == self.level_range.end {
875                lemmas.insert(sibling, children[index.0].clone());
876            } else {
877                lemmas.insert(sibling, children[sibling.0].clone());
878            }
879        }
880
881        // Update the next level indices.
882        self.level_indices = next_indices;
883        self.level_range /= 2;
884        self.data = parents;
885
886        Some(lemmas)
887    }
888}
889
890/// A Merkle root calculation iterator based on [`NodeIndexRange`].
891///
892/// It iteratively calculates parent hashes for the range of
893/// child hashes toward the Merkle root.
894///
895/// [`nodeindexrange`]: struct.NodeIndexRange.html
896struct MerkleRootIter<'a, B>
897where
898    B: Digest,
899    Buffer<B>: Copy,
900{
901    /// A changed range of the indices.
902    changed_range: NodeIndexRange,
903
904    /// A current level index range.
905    level_range: NodeIndexRange,
906
907    /// A remaining tree of node.
908    data: &'a mut [NodeData<B>],
909}
910
911impl<'a, B> Iterator for MerkleRootIter<'a, B>
912where
913    B: Digest,
914    Buffer<B>: Copy,
915{
916    type Item = NodeIndexRange;
917
918    fn next(&mut self) -> Option<Self::Item> {
919        if self.data.len() <= 1 {
920            return None;
921        }
922
923        // Adjust the child and the parent ranges.
924        let mut child_range = self.changed_range.clone();
925        if child_range.start.is_right(&self.level_range) {
926            // The updated index range always starts even.
927            *child_range.start -= 1;
928        }
929        if child_range.is_empty() {
930            // It's at least one node remains to update the
931            // parent hash.
932            *child_range.end += 1;
933        }
934        let mut parent_range = self.changed_range.clone() / 2;
935        if parent_range.is_empty() {
936            *parent_range.end += 1;
937        }
938
939        // Calculates the parent hash.
940        let split = *self.level_range.end;
941        let (children, parents) = mem::take(&mut self.data).split_at_mut(split);
942        let siblings = children[child_range.as_range_usize()].chunks_exact(2);
943        let mut parent_index = 0;
944        for pair in siblings.clone() {
945            let mut hasher = B::new();
946            for child in pair {
947                hasher.update(child);
948            }
949            parents[parent_index] = NodeData::from(hasher.finalize());
950            parent_index += 1;
951        }
952        // Duplicates the last odd child, if there is.
953        if let Some(child) = siblings.remainder().first() {
954            let mut hasher = B::new();
955            hasher.update(child);
956            hasher.update(child);
957            parents[parent_index] = NodeData::from(hasher.finalize());
958        }
959
960        // Prepare the iterator for the next round.
961        self.changed_range = parent_range.clone();
962        self.level_range /= 2;
963        self.data = parents;
964
965        Some(parent_range)
966    }
967}
968
969/// A Merkle root calculation iterator based on [`LeftNodeIndexSet`].
970///
971/// It iteratively calculates parent hashes for the set of
972/// child hashes toward the Merkle root.
973///
974/// [`leftnodeindexset`]: struct.LeftNodeIndexSet.html
975struct MerkleRootSetIter<'a, B>
976where
977    B: Digest,
978    Buffer<B>: Copy,
979{
980    /// A changed range of the indices.
981    ///
982    /// It only keeps track of the left side of the indices
983    /// to make the parent hash calculation simpler.
984    changed_set: LeftNodeIndexSet,
985
986    /// A current level index range.
987    level_range: NodeIndexRange,
988
989    /// A remaining tree of node.
990    data: &'a mut [NodeData<B>],
991}
992
993impl<'a, B> Iterator for MerkleRootSetIter<'a, B>
994where
995    B: Digest,
996    Buffer<B>: Copy,
997{
998    type Item = usize;
999
1000    fn next(&mut self) -> Option<Self::Item> {
1001        if self.data.len() <= 1 {
1002            return None;
1003        }
1004
1005        // `LeftNodeIndexSet` for the parent changed set.
1006        let mut next_set = LeftNodeIndexSet::default();
1007
1008        // Splits the tree to get the current level node.
1009        let split = *self.level_range.end;
1010        let (current, next) = mem::take(&mut self.data).split_at_mut(split);
1011
1012        // Calculates the parent hash.
1013        for index in self.changed_set.iter() {
1014            let sibling = index.sibling(&self.level_range).unwrap();
1015            let mut hasher = B::new();
1016            hasher.update(&current[**index]);
1017            hasher.update(&current[*sibling]);
1018            let parent = index.parent(&self.level_range).unwrap();
1019            next[*parent] = NodeData::from(hasher.finalize());
1020            next_set.insert(parent, &self.level_range);
1021        }
1022
1023        // Update the changed sets and data for the next iteration.
1024        let changed_count = next_set.len();
1025        self.changed_set = next_set;
1026        self.level_range /= 2;
1027        self.data = next;
1028
1029        Some(changed_count)
1030    }
1031}
1032
1033/// A left node index set.
1034///
1035/// [`MerkleRootSetIter`] uses it to keep track
1036/// of the current changed set to calculate
1037/// the parent hashes.
1038///
1039/// It keeps track of the left side of the indices
1040/// to make the parent hash calculation simpler.
1041///
1042/// [`merklerootsetiter`]: struct.MerkleRootSetIter.html
1043#[derive(Clone, Debug, Default)]
1044struct LeftNodeIndexSet(BTreeSet<NodeIndex>);
1045
1046impl Deref for LeftNodeIndexSet {
1047    type Target = BTreeSet<NodeIndex>;
1048
1049    fn deref(&self) -> &BTreeSet<NodeIndex> {
1050        &self.0
1051    }
1052}
1053
1054impl From<&NodeIndexRange> for LeftNodeIndexSet {
1055    fn from(range: &NodeIndexRange) -> Self {
1056        // The following code will be replaced by `BTreeSet::from_iter()`
1057        // with [`Range`] one liner once [`Step`] is in stable.
1058        //
1059        // [`range`]: https://doc.rust-lang.org/core/ops/struct.Range.html#impl-Iterator-forRange%3CA%3E
1060        // [`step`]: https://doc.rust-lang.org/core/iter/trait.Step.html
1061        let mut this = Self::default();
1062        for index in range.as_range_usize() {
1063            this.insert(NodeIndex(index), range);
1064        }
1065        this
1066    }
1067}
1068
1069impl LeftNodeIndexSet {
1070    /// Gets an iterator that visits the `NodeIndex`es
1071    /// in `LeftNodeIndexSet`.
1072    fn iter(&self) -> impl Iterator<Item = &NodeIndex> {
1073        self.0.iter()
1074    }
1075
1076    /// Adds a left side of the index to the set.
1077    fn insert(&mut self, index: NodeIndex, range: &NodeIndexRange) -> bool {
1078        assert!(range.contains(&index));
1079        if index.is_right(range) {
1080            match index.sibling(range) {
1081                Some(index) => self.0.insert(index),
1082                None => false,
1083            }
1084        } else {
1085            self.0.insert(index)
1086        }
1087    }
1088}
1089
1090/// A node index range.
1091#[derive(Clone, Default)]
1092struct NodeIndexRange(core::ops::Range<NodeIndex>);
1093
1094impl Debug for NodeIndexRange {
1095    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096        f.write_fmt(format_args!("{}..{}", *self.start, *self.end))
1097    }
1098}
1099
1100impl Deref for NodeIndexRange {
1101    type Target = core::ops::Range<NodeIndex>;
1102
1103    fn deref(&self) -> &Self::Target {
1104        &self.0
1105    }
1106}
1107
1108impl DerefMut for NodeIndexRange {
1109    fn deref_mut(&mut self) -> &mut Self::Target {
1110        &mut self.0
1111    }
1112}
1113
1114impl From<core::ops::Range<usize>> for NodeIndexRange {
1115    fn from(range: core::ops::Range<usize>) -> Self {
1116        Self(core::ops::Range {
1117            start: NodeIndex(range.start),
1118            end: NodeIndex(range.end),
1119        })
1120    }
1121}
1122
1123impl From<core::ops::RangeTo<usize>> for NodeIndexRange {
1124    fn from(range: core::ops::RangeTo<usize>) -> Self {
1125        Self(core::ops::Range {
1126            start: NodeIndex(0),
1127            end: NodeIndex(range.end),
1128        })
1129    }
1130}
1131
1132impl From<NodeIndexRange> for core::ops::Range<usize> {
1133    fn from(range: NodeIndexRange) -> Self {
1134        core::ops::Range {
1135            start: *range.0.start,
1136            end: *range.0.end,
1137        }
1138    }
1139}
1140
1141impl Div<usize> for NodeIndexRange {
1142    type Output = Self;
1143
1144    fn div(mut self, rhs: usize) -> Self {
1145        self /= rhs;
1146        self
1147    }
1148}
1149
1150impl DivAssign<usize> for NodeIndexRange {
1151    fn div_assign(&mut self, rhs: usize) {
1152        *self.0.start /= rhs;
1153        *self.0.end = (*self.0.end + (rhs - 1)) / rhs;
1154    }
1155}
1156
1157impl NodeIndexRange {
1158    /// Returns the `NodeIndexRange` as `Range<usize>`.
1159    #[inline]
1160    const fn as_range_usize(&self) -> core::ops::Range<usize> {
1161        self.0.start.0..self.0.end.0
1162    }
1163
1164    /// Returns the length of the range.
1165    #[inline]
1166    const fn len(&self) -> usize {
1167        self.0.end.0 - self.0.start.0
1168    }
1169}
1170
1171/// A node index.
1172#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)]
1173struct NodeIndex(usize);
1174
1175impl Deref for NodeIndex {
1176    type Target = usize;
1177
1178    fn deref(&self) -> &usize {
1179        &self.0
1180    }
1181}
1182
1183impl DerefMut for NodeIndex {
1184    fn deref_mut(&mut self) -> &mut usize {
1185        &mut self.0
1186    }
1187}
1188
1189impl From<NodeIndex> for usize {
1190    fn from(index: NodeIndex) -> usize {
1191        index.0
1192    }
1193}
1194
1195impl Div<usize> for NodeIndex {
1196    type Output = Self;
1197
1198    fn div(self, rhs: usize) -> Self {
1199        Self(self.0 / rhs)
1200    }
1201}
1202
1203impl NodeIndex {
1204    /// Returns `true` if the index is the right side of the node.
1205    #[inline]
1206    const fn is_right(&self, range: &NodeIndexRange) -> bool {
1207        (self.0 - range.0.start.0) % 2 == 1
1208    }
1209
1210    /// Returns the parent index of `Self`, or `None`, in
1211    /// case of the `Self` is the root index.
1212    #[inline]
1213    const fn parent(&self, range: &NodeIndexRange) -> Option<Self> {
1214        if range.len() == 1 {
1215            None
1216        } else {
1217            Some(Self(self.0 / 2))
1218        }
1219    }
1220
1221    /// Returns the sibling index of `Self`, or:
1222    ///
1223    /// 1) `None` in case of `Self` is the root index.
1224    /// 2) `Self` in case of the sibling is out of range.
1225    #[inline]
1226    fn sibling(&self, range: &NodeIndexRange) -> Option<Self> {
1227        if range.len() == 1 {
1228            None
1229        } else if self.is_right(range) {
1230            Some(Self(self.0 - 1))
1231        } else {
1232            let sibling = Self(self.0 + 1);
1233            if range.0.contains(&sibling) {
1234                Some(sibling)
1235            } else {
1236                Some(*self)
1237            }
1238        }
1239    }
1240}
1241
1242/// A node data.
1243///
1244/// It abstructs the [`digest::Output`] value.
1245///
1246/// [`digest::Output`]: https://docs.rs/digest/latest/digest/type.Output.html
1247#[derive(Copy, Debug)]
1248struct NodeData<B>(Option<digest::Output<B>>)
1249where
1250    B: OutputSizeUser,
1251    Buffer<B>: Copy;
1252
1253impl<B> Clone for NodeData<B>
1254where
1255    B: OutputSizeUser,
1256    Buffer<B>: Copy,
1257{
1258    fn clone(&self) -> Self {
1259        Self(self.0)
1260    }
1261}
1262
1263impl<B> Default for NodeData<B>
1264where
1265    B: OutputSizeUser,
1266    Buffer<B>: Copy,
1267{
1268    fn default() -> Self {
1269        Self(None)
1270    }
1271}
1272
1273impl<B> AsRef<[u8]> for NodeData<B>
1274where
1275    B: OutputSizeUser,
1276    Buffer<B>: Copy,
1277{
1278    fn as_ref(&self) -> &[u8] {
1279        debug_assert!(self.0.is_some(), "uninitialized node");
1280        self.0.as_ref().unwrap()
1281    }
1282}
1283
1284impl<B> From<digest::Output<B>> for NodeData<B>
1285where
1286    B: OutputSizeUser,
1287    Buffer<B>: Copy,
1288{
1289    fn from(inner: digest::Output<B>) -> Self {
1290        Self(Some(inner))
1291    }
1292}
1293
1294impl<B> TryFrom<&[u8]> for NodeData<B>
1295where
1296    B: OutputSizeUser,
1297    Buffer<B>: Copy,
1298{
1299    type Error = block_buffer::Error;
1300
1301    fn try_from(from: &[u8]) -> Result<Self, Self::Error> {
1302        if from.len() != B::output_size() {
1303            return Err(block_buffer::Error);
1304        }
1305        Ok(Self(Some(digest::Output::<B>::clone_from_slice(from))))
1306    }
1307}