arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
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    /// Returns the peak by the provided index.
 73    ///
 74    /// # Errors
 75    /// Returns an error if the provided peak index is greater or equal to the current number of
 76    /// peaks in the Mmr.
 77    pub fn get_peak(&self, peak_idx: usize) -> Result<&RpoDigest, MmrError> {
 78        self.peaks
 79            .get(peak_idx)
 80            .ok_or(MmrError::PeakOutOfBounds(peak_idx, self.peaks.len()))
 81    }
 82
 83    /// Converts this [MmrPeaks] into its components: number of leaves and a vector of peaks of
 84    /// the underlying MMR.
 85    pub fn into_parts(self) -> (usize, Vec<RpoDigest>) {
 86        (self.num_leaves, self.peaks)
 87    }
 88
 89    /// Hashes the peaks.
 90    ///
 91    /// The procedure will:
 92    /// - Flatten and pad the peaks to a vector of Felts.
 93    /// - Hash the vector of Felts.
 94    pub fn hash_peaks(&self) -> RpoDigest {
 95        Rpo256::hash_elements(&self.flatten_and_pad_peaks())
 96    }
 97
 98    /// Verifies the Merkle opening proof.
 99    ///
100    /// # Errors
101    /// Returns an error if:
102    /// - provided opening proof is invalid.
103    /// - Mmr root value computed using the provided leaf value differs from the actual one.
104    pub fn verify(&self, value: RpoDigest, opening: MmrProof) -> Result<(), MmrError> {
105        let root = self.get_peak(opening.peak_index())?;
106        opening
107            .merkle_path
108            .verify(opening.relative_pos() as u64, value, root)
109            .map_err(MmrError::MerkleError)
110    }
111
112    /// Flattens and pads the peaks to make hashing inside of the Miden VM easier.
113    ///
114    /// The procedure will:
115    /// - Flatten the vector of Words into a vector of Felts.
116    /// - Pad the peaks with ZERO to an even number of words, this removes the need to handle RPO
117    ///   padding.
118    /// - Pad the peaks to a minimum length of 16 words, which reduces the constant cost of hashing.
119    pub fn flatten_and_pad_peaks(&self) -> Vec<Felt> {
120        let num_peaks = self.peaks.len();
121
122        // To achieve the padding rules above we calculate the length of the final vector.
123        // This is calculated as the number of field elements. Each peak is 4 field elements.
124        // The length is calculated as follows:
125        // - If there are less than 16 peaks, the data is padded to 16 peaks and as such requires 64
126        //   field elements.
127        // - If there are more than 16 peaks and the number of peaks is odd, the data is padded to
128        //   an even number of peaks and as such requires `(num_peaks + 1) * 4` field elements.
129        // - If there are more than 16 peaks and the number of peaks is even, the data is not padded
130        //   and as such requires `num_peaks * 4` field elements.
131        let len = if num_peaks < 16 {
132            64
133        } else if num_peaks % 2 == 1 {
134            (num_peaks + 1) * 4
135        } else {
136            num_peaks * 4
137        };
138
139        let mut elements = Vec::with_capacity(len);
140        elements.extend_from_slice(
141            &self
142                .peaks
143                .as_slice()
144                .iter()
145                .map(|digest| digest.into())
146                .collect::<Vec<Word>>()
147                .concat(),
148        );
149        elements.resize(len, ZERO);
150        elements
151    }
152}
153
154impl From<MmrPeaks> for Vec<RpoDigest> {
155    fn from(peaks: MmrPeaks) -> Self {
156        peaks.peaks
157    }
158}