arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/path.rs
src/merkle/path.rsRaw
  1use super::{vec, InnerNodeInfo, MerkleError, NodeIndex, Rpo256, RpoDigest, Vec};
  2use core::ops::{Deref, DerefMut};
  3
  4// MERKLE PATH
  5// ================================================================================================
  6
  7/// A merkle path container, composed of a sequence of nodes of a Merkle tree.
  8#[derive(Clone, Debug, Default, PartialEq, Eq)]
  9pub struct MerklePath {
 10    nodes: Vec<RpoDigest>,
 11}
 12
 13impl MerklePath {
 14    // CONSTRUCTORS
 15    // --------------------------------------------------------------------------------------------
 16
 17    /// Creates a new Merkle path from a list of nodes.
 18    pub fn new(nodes: Vec<RpoDigest>) -> Self {
 19        Self { nodes }
 20    }
 21
 22    // PROVIDERS
 23    // --------------------------------------------------------------------------------------------
 24
 25    /// Returns the depth in which this Merkle path proof is valid.
 26    pub fn depth(&self) -> u8 {
 27        self.nodes.len() as u8
 28    }
 29
 30    /// Computes the merkle root for this opening.
 31    pub fn compute_root(&self, index: u64, node: RpoDigest) -> Result<RpoDigest, MerkleError> {
 32        let mut index = NodeIndex::new(self.depth(), index)?;
 33        let root = self.nodes.iter().copied().fold(node, |node, sibling| {
 34            // compute the node and move to the next iteration.
 35            let input = index.build_node(node, sibling);
 36            index.move_up();
 37            Rpo256::merge(&input)
 38        });
 39        Ok(root)
 40    }
 41
 42    /// Verifies the Merkle opening proof towards the provided root.
 43    ///
 44    /// Returns `true` if `node` exists at `index` in a Merkle tree with `root`.
 45    pub fn verify(&self, index: u64, node: RpoDigest, root: &RpoDigest) -> bool {
 46        match self.compute_root(index, node) {
 47            Ok(computed_root) => root == &computed_root,
 48            Err(_) => false,
 49        }
 50    }
 51
 52    /// Returns an iterator over every inner node of this [MerklePath].
 53    ///
 54    /// The iteration order is unspecified.
 55    ///
 56    /// # Errors
 57    /// Returns an error if the specified index is not valid for this path.
 58    pub fn inner_nodes(
 59        &self,
 60        index: u64,
 61        node: RpoDigest,
 62    ) -> Result<InnerNodeIterator, MerkleError> {
 63        Ok(InnerNodeIterator {
 64            nodes: &self.nodes,
 65            index: NodeIndex::new(self.depth(), index)?,
 66            value: node,
 67        })
 68    }
 69}
 70
 71impl From<Vec<RpoDigest>> for MerklePath {
 72    fn from(path: Vec<RpoDigest>) -> Self {
 73        Self::new(path)
 74    }
 75}
 76
 77impl Deref for MerklePath {
 78    // we use `Vec` here instead of slice so we can call vector mutation methods directly from the
 79    // merkle path (example: `Vec::remove`).
 80    type Target = Vec<RpoDigest>;
 81
 82    fn deref(&self) -> &Self::Target {
 83        &self.nodes
 84    }
 85}
 86
 87impl DerefMut for MerklePath {
 88    fn deref_mut(&mut self) -> &mut Self::Target {
 89        &mut self.nodes
 90    }
 91}
 92
 93// ITERATORS
 94// ================================================================================================
 95
 96impl FromIterator<RpoDigest> for MerklePath {
 97    fn from_iter<T: IntoIterator<Item = RpoDigest>>(iter: T) -> Self {
 98        Self::new(iter.into_iter().collect())
 99    }
100}
101
102impl IntoIterator for MerklePath {
103    type Item = RpoDigest;
104    type IntoIter = vec::IntoIter<RpoDigest>;
105
106    fn into_iter(self) -> Self::IntoIter {
107        self.nodes.into_iter()
108    }
109}
110
111/// An iterator over internal nodes of a [MerklePath].
112pub struct InnerNodeIterator<'a> {
113    nodes: &'a Vec<RpoDigest>,
114    index: NodeIndex,
115    value: RpoDigest,
116}
117
118impl<'a> Iterator for InnerNodeIterator<'a> {
119    type Item = InnerNodeInfo;
120
121    fn next(&mut self) -> Option<Self::Item> {
122        if !self.index.is_root() {
123            let sibling_pos = self.nodes.len() - self.index.depth() as usize;
124            let (left, right) = if self.index.is_value_odd() {
125                (self.nodes[sibling_pos], self.value)
126            } else {
127                (self.value, self.nodes[sibling_pos])
128            };
129
130            self.value = Rpo256::merge(&[left, right]);
131            self.index.move_up();
132
133            Some(InnerNodeInfo {
134                value: self.value,
135                left,
136                right,
137            })
138        } else {
139            None
140        }
141    }
142}
143
144// MERKLE PATH CONTAINERS
145// ================================================================================================
146
147/// A container for a [Word] value and its [MerklePath] opening.
148#[derive(Clone, Debug, Default, PartialEq, Eq)]
149pub struct ValuePath {
150    /// The node value opening for `path`.
151    pub value: RpoDigest,
152    /// The path from `value` to `root` (exclusive).
153    pub path: MerklePath,
154}
155
156/// A container for a [MerklePath] and its [Word] root.
157///
158/// This structure does not provide any guarantees regarding the correctness of the path to the
159/// root. For more information, check [MerklePath::verify].
160#[derive(Clone, Debug, Default, PartialEq, Eq)]
161pub struct RootPath {
162    /// The node value opening for `path`.
163    pub root: RpoDigest,
164    /// The path from `value` to `root` (exclusive).
165    pub path: MerklePath,
166}
167
168// TESTS
169// ================================================================================================
170
171#[cfg(test)]
172mod tests {
173    use crate::merkle::{int_to_node, MerklePath};
174
175    #[test]
176    fn test_inner_nodes() {
177        let nodes = vec![int_to_node(1), int_to_node(2), int_to_node(3), int_to_node(4)];
178        let merkle_path = MerklePath::new(nodes);
179
180        let index = 6;
181        let node = int_to_node(5);
182        let root = merkle_path.compute_root(index, node).unwrap();
183
184        let inner_root = merkle_path.inner_nodes(index, node).unwrap().last().unwrap().value;
185
186        assert_eq!(root, inner_root);
187    }
188}