miden-crypto/src/merkle/path.rs
src/merkle/path.rsRaw
1use super::{vec, InnerNodeInfo, MerkleError, NodeIndex, Rpo256, Vec, Word};
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<Word>,
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<Word>) -> 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: Word) -> Result<Word, 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.into(), sibling.into());
36 index.move_up();
37 Rpo256::merge(&input).into()
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: Word, root: &Word) -> 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(&self, index: u64, node: Word) -> Result<InnerNodeIterator, MerkleError> {
59 Ok(InnerNodeIterator {
60 nodes: &self.nodes,
61 index: NodeIndex::new(self.depth(), index)?,
62 value: node,
63 })
64 }
65}
66
67impl From<Vec<Word>> for MerklePath {
68 fn from(path: Vec<Word>) -> Self {
69 Self::new(path)
70 }
71}
72
73impl Deref for MerklePath {
74 // we use `Vec` here instead of slice so we can call vector mutation methods directly from the
75 // merkle path (example: `Vec::remove`).
76 type Target = Vec<Word>;
77
78 fn deref(&self) -> &Self::Target {
79 &self.nodes
80 }
81}
82
83impl DerefMut for MerklePath {
84 fn deref_mut(&mut self) -> &mut Self::Target {
85 &mut self.nodes
86 }
87}
88
89// ITERATORS
90// ================================================================================================
91
92impl FromIterator<Word> for MerklePath {
93 fn from_iter<T: IntoIterator<Item = Word>>(iter: T) -> Self {
94 Self::new(iter.into_iter().collect())
95 }
96}
97
98impl IntoIterator for MerklePath {
99 type Item = Word;
100 type IntoIter = vec::IntoIter<Word>;
101
102 fn into_iter(self) -> Self::IntoIter {
103 self.nodes.into_iter()
104 }
105}
106
107/// An iterator over internal nodes of a [MerklePath].
108pub struct InnerNodeIterator<'a> {
109 nodes: &'a Vec<Word>,
110 index: NodeIndex,
111 value: Word,
112}
113
114impl<'a> Iterator for InnerNodeIterator<'a> {
115 type Item = InnerNodeInfo;
116
117 fn next(&mut self) -> Option<Self::Item> {
118 if !self.index.is_root() {
119 let sibling_pos = self.nodes.len() - self.index.depth() as usize;
120 let (left, right) = if self.index.is_value_odd() {
121 (self.nodes[sibling_pos], self.value)
122 } else {
123 (self.value, self.nodes[sibling_pos])
124 };
125
126 self.value = Rpo256::merge(&[left.into(), right.into()]).into();
127 self.index.move_up();
128
129 Some(InnerNodeInfo {
130 value: self.value,
131 left,
132 right,
133 })
134 } else {
135 None
136 }
137 }
138}
139
140// MERKLE PATH CONTAINERS
141// ================================================================================================
142
143/// A container for a [Word] value and its [MerklePath] opening.
144#[derive(Clone, Debug, Default, PartialEq, Eq)]
145pub struct ValuePath {
146 /// The node value opening for `path`.
147 pub value: Word,
148 /// The path from `value` to `root` (exclusive).
149 pub path: MerklePath,
150}
151
152/// A container for a [MerklePath] and its [Word] root.
153///
154/// This structure does not provide any guarantees regarding the correctness of the path to the
155/// root. For more information, check [MerklePath::verify].
156#[derive(Clone, Debug, Default, PartialEq, Eq)]
157pub struct RootPath {
158 /// The node value opening for `path`.
159 pub root: Word,
160 /// The path from `value` to `root` (exclusive).
161 pub path: MerklePath,
162}
163
164// TESTS
165// ================================================================================================
166
167#[cfg(test)]
168mod tests {
169 use crate::merkle::{int_to_node, MerklePath};
170
171 #[test]
172 fn test_inner_nodes() {
173 let nodes = vec![int_to_node(1), int_to_node(2), int_to_node(3), int_to_node(4)];
174 let merkle_path = MerklePath::new(nodes);
175
176 let index = 6;
177 let node = int_to_node(5);
178 let root = merkle_path.compute_root(index, node).unwrap();
179
180 let inner_root = merkle_path.inner_nodes(index, node).unwrap().last().unwrap().value;
181
182 assert_eq!(root, inner_root);
183 }
184}