Skip to content

Commit

Permalink
feat: add merkle path wrapper
Browse files Browse the repository at this point in the history
A Merkle path is a vector of nodes, regardless of the Merkle tree
implementation.

This commit introduces an encapsulation for such vector, also to provide
functionality that is common between different algorithms such as
opening verification.

related issue: #36
  • Loading branch information
vlopes11 committed Feb 13, 2023
1 parent 66da469 commit 21a8cbc
Show file tree
Hide file tree
Showing 6 changed files with 227 additions and 132 deletions.
18 changes: 9 additions & 9 deletions src/merkle/merkle_tree.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{Felt, MerkleError, Rpo256, RpoDigest, Vec, Word};
use super::{Felt, MerkleError, MerklePath, Rpo256, RpoDigest, Vec, Word};
use crate::{utils::uninit_vector, FieldElement};
use core::slice;
use winter_math::log2;
Expand Down Expand Up @@ -88,7 +88,7 @@ impl MerkleTree {
/// Returns an error if:
/// * The specified depth is greater than the depth of the tree.
/// * The specified index not valid for the specified depth.
pub fn get_path(&self, depth: u32, index: u64) -> Result<Vec<Word>, MerkleError> {
pub fn get_path(&self, depth: u32, index: u64) -> Result<MerklePath, MerkleError> {
if depth == 0 {
return Err(MerkleError::DepthTooSmall(depth));
} else if depth > self.depth() {
Expand All @@ -106,7 +106,7 @@ impl MerkleTree {
pos >>= 1;
}

Ok(path)
Ok(path.into())
}

/// Replaces the leaf at the specified index with the provided value.
Expand Down Expand Up @@ -206,14 +206,14 @@ mod tests {
let (_, node2, node3) = compute_internal_nodes();

// check depth 2
assert_eq!(vec![LEAVES4[1], node3], tree.get_path(2, 0).unwrap());
assert_eq!(vec![LEAVES4[0], node3], tree.get_path(2, 1).unwrap());
assert_eq!(vec![LEAVES4[3], node2], tree.get_path(2, 2).unwrap());
assert_eq!(vec![LEAVES4[2], node2], tree.get_path(2, 3).unwrap());
assert_eq!(vec![LEAVES4[1], node3], *tree.get_path(2, 0).unwrap());
assert_eq!(vec![LEAVES4[0], node3], *tree.get_path(2, 1).unwrap());
assert_eq!(vec![LEAVES4[3], node2], *tree.get_path(2, 2).unwrap());
assert_eq!(vec![LEAVES4[2], node2], *tree.get_path(2, 3).unwrap());

// check depth 1
assert_eq!(vec![node3], tree.get_path(1, 0).unwrap());
assert_eq!(vec![node2], tree.get_path(1, 1).unwrap());
assert_eq!(vec![node3], *tree.get_path(1, 0).unwrap());
assert_eq!(vec![node2], *tree.get_path(1, 1).unwrap());
}

#[test]
Expand Down
11 changes: 7 additions & 4 deletions src/merkle/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use super::{
hash::rpo::{Rpo256, RpoDigest},
utils::collections::{BTreeMap, Vec},
utils::collections::{vec, BTreeMap, Vec},
Felt, Word, ZERO,
};
use core::fmt;

mod merkle_tree;
pub use merkle_tree::MerkleTree;

mod merkle_path_set;
pub use merkle_path_set::MerklePathSet;
mod path;
pub use path::MerklePath;

mod path_set;
pub use path_set::MerklePathSet;

mod simple_smt;
pub use simple_smt::SimpleSmt;
Expand All @@ -24,7 +27,7 @@ pub enum MerkleError {
NumLeavesNotPowerOfTwo(usize),
InvalidIndex(u32, u64),
InvalidDepth(u32, u32),
InvalidPath(Vec<Word>),
InvalidPath(MerklePath),
InvalidEntriesCount(usize, usize),
NodeNotInSet(u64),
}
Expand Down
89 changes: 89 additions & 0 deletions src/merkle/path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use super::{vec, Rpo256, Vec, Word};
use core::ops::{Deref, DerefMut};

// MERKLE PATH
// ================================================================================================

/// A merkle path container, composed of a sequence of nodes of a Merkle tree.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MerklePath {
nodes: Vec<Word>,
}

impl MerklePath {
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------

/// Creates a new Merkle path from a list of nodes.
pub fn new(nodes: Vec<Word>) -> Self {
Self { nodes }
}

// PROVIDERS
// --------------------------------------------------------------------------------------------

/// Computes the merkle root for this opening.
pub fn compute_root(&self, mut index: u64, node: Word) -> Word {
self.nodes.iter().copied().fold(node, |node, sibling| {
// build the input node, considering the parity of the current index.
let is_right_sibling = (index & 1) == 1;
let input = if is_right_sibling {
[sibling.into(), node.into()]
} else {
[node.into(), sibling.into()]
};
// compute the node and move to the next iteration.
index >>= 1;
Rpo256::merge(&input).into()
})
}

/// Returns the depth in which this Merkle path proof is valid.
pub fn depth(&self) -> u8 {
self.nodes.len() as u8
}

/// Verifies the Merkle opening proof towards the provided root.
///
/// Returns `true` if `node` exists at `index` in a Merkle tree with `root`.
pub fn verify(&self, index: u64, node: Word, root: &Word) -> bool {
root == &self.compute_root(index, node)
}
}

impl From<Vec<Word>> for MerklePath {
fn from(path: Vec<Word>) -> Self {
Self::new(path)
}
}

impl Deref for MerklePath {
// we use `Vec` here instead of slice so we can call vector mutation methods directly from the
// merkle path (example: `Vec::remove`).
type Target = Vec<Word>;

fn deref(&self) -> &Self::Target {
&self.nodes
}
}

impl DerefMut for MerklePath {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.nodes
}
}

impl FromIterator<Word> for MerklePath {
fn from_iter<T: IntoIterator<Item = Word>>(iter: T) -> Self {
Self::new(iter.into_iter().collect())
}
}

impl IntoIterator for MerklePath {
type Item = Word;
type IntoIter = vec::IntoIter<Word>;

fn into_iter(self) -> Self::IntoIter {
self.nodes.into_iter()
}
}
Loading

0 comments on commit 21a8cbc

Please sign in to comment.