miden-crypto/src/merkle/mmr/peaks.rs
src/merkle/mmr/peaks.rsRaw
1use alloc::vec::Vec;
2
3use super::{super::ZERO, Felt, MmrError, MmrProof, Rpo256, RpoDigest, Word};
4
5// MMR PEAKS
6// ================================================================================================
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
10pub struct MmrPeaks {
11 /// The number of leaves is used to differentiate MMRs that have the same number of peaks. This
12 /// happens because the number of peaks goes up-and-down as the structure is used causing
13 /// existing trees to be merged and new ones to be created. As an example, every time the MMR
14 /// has a power-of-two number of leaves there is a single peak.
15 ///
16 /// Every tree in the MMR forest has a distinct power-of-two size, this means only the right-
17 /// most tree can have an odd number of elements (e.g. `1`). Additionally this means that the
18 /// bits in `num_leaves` conveniently encode the size of each individual tree.
19 ///
20 /// Examples:
21 ///
22 /// - With 5 leaves, the binary `0b101`. The number of set bits is equal the number of peaks,
23 /// in this case there are 2 peaks. The 0-indexed least-significant position of the bit
24 /// determines the number of elements of a tree, so the rightmost tree has `2**0` elements
25 /// and the left most has `2**2`.
26 /// - With 12 leaves, the binary is `0b1100`, this case also has 2 peaks, the leftmost tree has
27 /// `2**3=8` elements, and the right most has `2**2=4` elements.
28 num_leaves: usize,
29
30 /// All the peaks of every tree in the MMR forest. The peaks are always ordered by number of
31 /// leaves, starting from the peak with most children, to the one with least.
32 ///
33 /// Invariant: The length of `peaks` must be equal to the number of true bits in `num_leaves`.
34 peaks: Vec<RpoDigest>,
35}
36
37impl MmrPeaks {
38 // CONSTRUCTOR
39 // --------------------------------------------------------------------------------------------
40
41 /// Returns new [MmrPeaks] instantiated from the provided vector of peaks and the number of
42 /// leaves in the underlying MMR.
43 ///
44 /// # Errors
45 /// Returns an error if the number of leaves and the number of peaks are inconsistent.
46 pub fn new(num_leaves: usize, peaks: Vec<RpoDigest>) -> Result<Self, MmrError> {
47 if num_leaves.count_ones() as usize != peaks.len() {
48 return Err(MmrError::InvalidPeaks);
49 }
50
51 Ok(Self { num_leaves, peaks })
52 }
53
54 // ACCESSORS
55 // --------------------------------------------------------------------------------------------
56
57 /// Returns a count of leaves in the underlying MMR.
58 pub fn num_leaves(&self) -> usize {
59 self.num_leaves
60 }
61
62 /// Returns the number of peaks of the underlying MMR.
63 pub fn num_peaks(&self) -> usize {
64 self.peaks.len()
65 }
66
67 /// Returns the list of peaks of the underlying MMR.
68 pub fn peaks(&self) -> &[RpoDigest] {
69 &self.peaks
70 }
71
72 /// Converts this [MmrPeaks] into its components: number of leaves and a vector of peaks of
73 /// the underlying MMR.
74 pub fn into_parts(self) -> (usize, Vec<RpoDigest>) {
75 (self.num_leaves, self.peaks)
76 }
77
78 /// Hashes the peaks.
79 ///
80 /// The procedure will:
81 /// - Flatten and pad the peaks to a vector of Felts.
82 /// - Hash the vector of Felts.
83 pub fn hash_peaks(&self) -> RpoDigest {
84 Rpo256::hash_elements(&self.flatten_and_pad_peaks())
85 }
86
87 pub fn verify(&self, value: RpoDigest, opening: MmrProof) -> bool {
88 let root = &self.peaks[opening.peak_index()];
89 opening.merkle_path.verify(opening.relative_pos() as u64, value, root)
90 }
91
92 /// Flattens and pads the peaks to make hashing inside of the Miden VM easier.
93 ///
94 /// The procedure will:
95 /// - Flatten the vector of Words into a vector of Felts.
96 /// - Pad the peaks with ZERO to an even number of words, this removes the need to handle RPO
97 /// padding.
98 /// - Pad the peaks to a minimum length of 16 words, which reduces the constant cost of hashing.
99 pub fn flatten_and_pad_peaks(&self) -> Vec<Felt> {
100 let num_peaks = self.peaks.len();
101
102 // To achieve the padding rules above we calculate the length of the final vector.
103 // This is calculated as the number of field elements. Each peak is 4 field elements.
104 // The length is calculated as follows:
105 // - If there are less than 16 peaks, the data is padded to 16 peaks and as such requires 64
106 // field elements.
107 // - If there are more than 16 peaks and the number of peaks is odd, the data is padded to
108 // an even number of peaks and as such requires `(num_peaks + 1) * 4` field elements.
109 // - If there are more than 16 peaks and the number of peaks is even, the data is not padded
110 // and as such requires `num_peaks * 4` field elements.
111 let len = if num_peaks < 16 {
112 64
113 } else if num_peaks % 2 == 1 {
114 (num_peaks + 1) * 4
115 } else {
116 num_peaks * 4
117 };
118
119 let mut elements = Vec::with_capacity(len);
120 elements.extend_from_slice(
121 &self
122 .peaks
123 .as_slice()
124 .iter()
125 .map(|digest| digest.into())
126 .collect::<Vec<Word>>()
127 .concat(),
128 );
129 elements.resize(len, ZERO);
130 elements
131 }
132}
133
134impl From<MmrPeaks> for Vec<RpoDigest> {
135 fn from(peaks: MmrPeaks) -> Self {
136 peaks.peaks
137 }
138}