From d4ed8c1254796bd6b3c5c0d0876b7a24d19ae6e1 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 07:55:47 -0500 Subject: [PATCH 001/117] smt: scaffolding --- src/merkle/mod.rs | 3 ++ src/merkle/smt.rs | 79 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/merkle/smt.rs diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 9c6c3c77..07c9703f 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -27,6 +27,9 @@ pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; pub use simple_smt::SimpleSmt; +mod smt; +pub use smt::{InnerNode, LeafIndex, SparseMerkleTree}; + mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs new file mode 100644 index 00000000..8bfff791 --- /dev/null +++ b/src/merkle/smt.rs @@ -0,0 +1,79 @@ +use crate::hash::rpo::{Rpo256, RpoDigest}; + +use super::{MerklePath, NodeIndex}; + +pub type LeafIndex = u64; + +/// An abstract description of a sparse Merkle tree. +/// +/// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed +/// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's +/// value was not explicitly updated, then its value is the default value. Typically, the vast +/// majority of leaves will store the default value (hence it is "sparse"), and therefore the +/// internal representation of the tree will only keep track of the leaves that have a different +/// value from the default. +/// +/// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the +/// longer its proofs are - of exactly `log(depth)` size. +/// +/// Every key value maps to one leaf. If there are as many keys as there are leaves, then +/// [Self::Leaf] should be the same type as [Self::Value], as is the case with +/// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] +/// must accomodate all keys that map to the same leaf. +pub trait SparseMerkleTree { + /// The type for a key, which must be convertible into a `u64` infaillibly + type Key: Into; + /// The type for a value + type Value: Default; + /// The type for a leaf + type Leaf; + + // PROVIDED METHODS + // --------------------------------------------------------------------------------------------- + + /// Returns a Merkle path from the leaf node specified by the key to the root. + /// + /// The node itself is not included in the path. + fn get_merkle_path(&self, key: &Self::Key) -> MerklePath { + todo!() + } + + /// Updates value of the leaf at the specified index returning the old leaf value. + /// + /// This also recomputes all hashes between the leaf and the root, updating the root itself. + fn update_leaf_at(&mut self, key: &Self::Key, value: Self::Value) -> Self::Value { + todo!() + } + + // ABSTRACT METHODS + // --------------------------------------------------------------------------------------------- + + /// The root of the tree + fn root(&self) -> RpoDigest; + + /// The depth of the tree + fn depth(&self) -> u8; + + /// Retrieves an inner node at the given index + fn get_inner_node(&self, index: NodeIndex) -> InnerNode; + + /// Inserts a leaf node, and returns the value at the key if already exists + fn insert_leaf_node(&self, key: Self::Key, value: Self::Value) -> Option; + + /// Returns the hash of a leaf + fn hash_leaf(v: Self::Leaf) -> RpoDigest; +} + +// TODO: Reconcile somehow with `simple_smt::BranchNode` +#[derive(Debug, Default, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub struct InnerNode { + left: RpoDigest, + right: RpoDigest, +} + +impl InnerNode { + pub fn hash(&self) -> RpoDigest { + Rpo256::merge(&[self.left, self.right]) + } +} From 15544f82b7e06313efcd18f0153d32d42443ee85 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 09:54:51 -0500 Subject: [PATCH 002/117] implement `update_leaf_at` --- src/merkle/smt.rs | 57 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 8bfff791..9122abb5 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -1,6 +1,6 @@ use crate::hash::rpo::{Rpo256, RpoDigest}; -use super::{MerklePath, NodeIndex}; +use super::{MerkleError, MerklePath, NodeIndex}; pub type LeafIndex = u64; @@ -22,9 +22,9 @@ pub type LeafIndex = u64; /// must accomodate all keys that map to the same leaf. pub trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly - type Key: Into; + type Key: Into + Clone; /// The type for a value - type Value: Default; + type Value: Clone + Default + PartialEq; /// The type for a leaf type Leaf; @@ -34,15 +34,29 @@ pub trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn get_merkle_path(&self, key: &Self::Key) -> MerklePath { + fn get_merkle_path(&self, key: Self::Key) -> MerklePath { todo!() } /// Updates value of the leaf at the specified index returning the old leaf value. /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. - fn update_leaf_at(&mut self, key: &Self::Key, value: Self::Value) -> Self::Value { - todo!() + fn update_leaf_at( + &mut self, + key: Self::Key, + value: Self::Value, + ) -> Result { + let old_value = self.insert_leaf_node(key.clone(), value.clone()).unwrap_or_default(); + + // if the old value and new value are the same, there is nothing to update + if value == old_value { + return Ok(value); + } + + let idx = NodeIndex::new(self.depth(), key.into())?; + recompute_nodes_from_index_to_root(self, idx, Self::hash_value(value)); + + Ok(old_value) } // ABSTRACT METHODS @@ -51,17 +65,46 @@ pub trait SparseMerkleTree { /// The root of the tree fn root(&self) -> RpoDigest; + /// Sets the root of the tree + fn set_root(&mut self, root: RpoDigest); + /// The depth of the tree fn depth(&self) -> u8; /// Retrieves an inner node at the given index fn get_inner_node(&self, index: NodeIndex) -> InnerNode; + /// Inserts an inner node at the given index + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode); + /// Inserts a leaf node, and returns the value at the key if already exists fn insert_leaf_node(&self, key: Self::Key, value: Self::Value) -> Option; /// Returns the hash of a leaf - fn hash_leaf(v: Self::Leaf) -> RpoDigest; + fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; + + /// Returns the hash of a value + /// FIXME: I found no good interface to mean "is hashable into a RpoDigest" that I could apply to `Self::Value` + fn hash_value(value: Self::Value) -> RpoDigest; +} + +fn recompute_nodes_from_index_to_root( + smt: &mut T, + mut index: NodeIndex, + node_hash_at_index: RpoDigest, +) where + T: SparseMerkleTree + ?Sized, +{ + let mut value = node_hash_at_index; + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = smt.get_inner_node(index); + let (left, right) = if is_right { (left, value) } else { (value, right) }; + smt.insert_inner_node(index, InnerNode { left, right }); + value = Rpo256::merge(&[left, right]); + } + smt.set_root(value); } // TODO: Reconcile somehow with `simple_smt::BranchNode` From 74b4db60b5bb86bc14573146f910c13a9056ff6b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 09:58:52 -0500 Subject: [PATCH 003/117] docstring --- src/merkle/smt.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 9122abb5..aee9a637 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -20,6 +20,8 @@ pub type LeafIndex = u64; /// [Self::Leaf] should be the same type as [Self::Value], as is the case with /// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] /// must accomodate all keys that map to the same leaf. +/// +/// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. pub trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly type Key: Into + Clone; From fba526fc3b92af89c9d5cc9aca5ca337a51991cc Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 10:05:48 -0500 Subject: [PATCH 004/117] move `recompute_nodes_from_index_to_root` into trait --- src/merkle/smt.rs | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index aee9a637..ffeb05e5 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -20,7 +20,7 @@ pub type LeafIndex = u64; /// [Self::Leaf] should be the same type as [Self::Value], as is the case with /// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] /// must accomodate all keys that map to the same leaf. -/// +/// /// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. pub trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly @@ -56,11 +56,30 @@ pub trait SparseMerkleTree { } let idx = NodeIndex::new(self.depth(), key.into())?; - recompute_nodes_from_index_to_root(self, idx, Self::hash_value(value)); + self.recompute_nodes_from_index_to_root(idx, Self::hash_value(value)); Ok(old_value) } + /// Recomputes the branch nodes (including the root) from `index` all the way to the root. + /// `node_hash_at_index` is the hash of the node stored at index. + fn recompute_nodes_from_index_to_root( + &mut self, + mut index: NodeIndex, + node_hash_at_index: RpoDigest, + ) { + let mut value = node_hash_at_index; + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = self.get_inner_node(index); + let (left, right) = if is_right { (left, value) } else { (value, right) }; + self.insert_inner_node(index, InnerNode { left, right }); + value = Rpo256::merge(&[left, right]); + } + self.set_root(value); + } + // ABSTRACT METHODS // --------------------------------------------------------------------------------------------- @@ -90,26 +109,6 @@ pub trait SparseMerkleTree { fn hash_value(value: Self::Value) -> RpoDigest; } -fn recompute_nodes_from_index_to_root( - smt: &mut T, - mut index: NodeIndex, - node_hash_at_index: RpoDigest, -) where - T: SparseMerkleTree + ?Sized, -{ - let mut value = node_hash_at_index; - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = smt.get_inner_node(index); - let (left, right) = if is_right { (left, value) } else { (value, right) }; - smt.insert_inner_node(index, InnerNode { left, right }); - value = Rpo256::merge(&[left, right]); - } - smt.set_root(value); -} - -// TODO: Reconcile somehow with `simple_smt::BranchNode` #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InnerNode { From 8f485b9bb0776d28794a62c9e2bb876c07fab436 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 10:29:03 -0500 Subject: [PATCH 005/117] implement `get_merkle_path` --- src/merkle/smt.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index ffeb05e5..4caf8d02 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -36,8 +36,27 @@ pub trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn get_merkle_path(&self, key: Self::Key) -> MerklePath { - todo!() + /// + /// # Errors + /// Returns an error if the specified index is too large given the depth of this Merkle tree. + fn get_merkle_path(&self, key: Self::Key) -> Result { + let mut index = NodeIndex::new(self.depth(), key.into())?; + + if index.is_root() { + return Err(MerkleError::DepthTooSmall(index.depth())); + } else if index.depth() > self.depth() { + return Err(MerkleError::DepthTooBig(index.depth() as u64)); + } + + let mut path = Vec::with_capacity(index.depth() as usize); + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = self.get_inner_node(index); + let value = if is_right { left } else { right }; + path.push(value); + } + Ok(MerklePath::new(path)) } /// Updates value of the leaf at the specified index returning the old leaf value. From 78fe6a7141e8990c8af33343b37474e583d1e914 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 10:48:34 -0500 Subject: [PATCH 006/117] introduce `DEPTH` const generic to remove runtime errors --- src/merkle/smt.rs | 64 +++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 4caf8d02..83eec923 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -2,8 +2,6 @@ use crate::hash::rpo::{Rpo256, RpoDigest}; use super::{MerkleError, MerklePath, NodeIndex}; -pub type LeafIndex = u64; - /// An abstract description of a sparse Merkle tree. /// /// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed @@ -22,9 +20,9 @@ pub type LeafIndex = u64; /// must accomodate all keys that map to the same leaf. /// /// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. -pub trait SparseMerkleTree { +pub trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly - type Key: Into + Clone; + type Key: Into> + Clone; /// The type for a value type Value: Clone + Default + PartialEq; /// The type for a leaf @@ -39,14 +37,11 @@ pub trait SparseMerkleTree { /// /// # Errors /// Returns an error if the specified index is too large given the depth of this Merkle tree. - fn get_merkle_path(&self, key: Self::Key) -> Result { - let mut index = NodeIndex::new(self.depth(), key.into())?; - - if index.is_root() { - return Err(MerkleError::DepthTooSmall(index.depth())); - } else if index.depth() > self.depth() { - return Err(MerkleError::DepthTooBig(index.depth() as u64)); - } + fn get_merkle_path(&self, key: Self::Key) -> MerklePath { + let mut index: NodeIndex = { + let leaf_index: LeafIndex = key.into(); + leaf_index.into() + }; let mut path = Vec::with_capacity(index.depth() as usize); for _ in 0..index.depth() { @@ -56,28 +51,29 @@ pub trait SparseMerkleTree { let value = if is_right { left } else { right }; path.push(value); } - Ok(MerklePath::new(path)) + + MerklePath::new(path) } /// Updates value of the leaf at the specified index returning the old leaf value. /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. - fn update_leaf_at( - &mut self, - key: Self::Key, - value: Self::Value, - ) -> Result { + fn update_leaf_at(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { let old_value = self.insert_leaf_node(key.clone(), value.clone()).unwrap_or_default(); // if the old value and new value are the same, there is nothing to update if value == old_value { - return Ok(value); + return value; } - let idx = NodeIndex::new(self.depth(), key.into())?; - self.recompute_nodes_from_index_to_root(idx, Self::hash_value(value)); + let node_index = { + let leaf_index: LeafIndex = key.into(); + leaf_index.into() + }; - Ok(old_value) + self.recompute_nodes_from_index_to_root(node_index, Self::hash_value(value)); + + old_value } /// Recomputes the branch nodes (including the root) from `index` all the way to the root. @@ -108,9 +104,6 @@ pub trait SparseMerkleTree { /// Sets the root of the tree fn set_root(&mut self, root: RpoDigest); - /// The depth of the tree - fn depth(&self) -> u8; - /// Retrieves an inner node at the given index fn get_inner_node(&self, index: NodeIndex) -> InnerNode; @@ -128,6 +121,27 @@ pub trait SparseMerkleTree { fn hash_value(value: Self::Value) -> RpoDigest; } +/// The index of a leaf, at a depth known at compile-time. +pub struct LeafIndex { + index: NodeIndex, +} + +impl LeafIndex { + pub fn new(value: u64) -> Result { + Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? }) + } + + pub fn value(&self) -> u64 { + self.index.value() + } +} + +impl From> for NodeIndex { + fn from(value: LeafIndex) -> Self { + value.index + } +} + #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InnerNode { From d42b38bbfda7c82ef5a7552598aa3e9865906ced Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 11:04:10 -0500 Subject: [PATCH 007/117] leaf index at depth 64 --- src/merkle/smt.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 83eec923..e685f005 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -1,4 +1,7 @@ -use crate::hash::rpo::{Rpo256, RpoDigest}; +use crate::{ + hash::rpo::{Rpo256, RpoDigest}, + Word, +}; use super::{MerkleError, MerklePath, NodeIndex}; @@ -136,12 +139,26 @@ impl LeafIndex { } } +impl LeafIndex<64> { + pub fn new_max_depth(value: u64) -> Self { + LeafIndex { + index: NodeIndex::new_unchecked(64, value), + } + } +} + impl From> for NodeIndex { fn from(value: LeafIndex) -> Self { value.index } } +impl From for LeafIndex<64> { + fn from(value: Word) -> Self { + Self::new_max_depth(value[0].inner()) + } +} + #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InnerNode { From babd406370e6be030cf4f18d8fb3bd9a2b46103d Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 11:08:38 -0500 Subject: [PATCH 008/117] add `depth()` method to smt --- src/merkle/smt.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index e685f005..83ab5680 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -98,6 +98,11 @@ pub trait SparseMerkleTree { self.set_root(value); } + /// Returns the depth of the sparse Merkle tree + fn depth(&self) -> u8 { + DEPTH + } + // ABSTRACT METHODS // --------------------------------------------------------------------------------------------- From adde9438cbdb73bfe73cf2b237753fca5c828396 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 11:23:54 -0500 Subject: [PATCH 009/117] file separators --- src/merkle/smt.rs | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 83ab5680..25457a4c 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -5,6 +5,9 @@ use crate::{ use super::{MerkleError, MerklePath, NodeIndex}; +// SPARSE MERKLE TREE +// ================================================================================================ + /// An abstract description of a sparse Merkle tree. /// /// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed @@ -129,6 +132,25 @@ pub trait SparseMerkleTree { fn hash_value(value: Self::Value) -> RpoDigest; } +// INNER NODE +// ================================================================================================ + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub struct InnerNode { + left: RpoDigest, + right: RpoDigest, +} + +impl InnerNode { + pub fn hash(&self) -> RpoDigest { + Rpo256::merge(&[self.left, self.right]) + } +} + +// LEAF INDEX +// ================================================================================================ + /// The index of a leaf, at a depth known at compile-time. pub struct LeafIndex { index: NodeIndex, @@ -163,16 +185,3 @@ impl From for LeafIndex<64> { Self::new_max_depth(value[0].inner()) } } - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct InnerNode { - left: RpoDigest, - right: RpoDigest, -} - -impl InnerNode { - pub fn hash(&self) -> RpoDigest { - Rpo256::merge(&[self.left, self.right]) - } -} From 8610986fb7c9bbc115af6f7c859e2b34f809be92 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 11:31:41 -0500 Subject: [PATCH 010/117] remove hash_value --- src/merkle/smt.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 25457a4c..5b138355 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -72,12 +72,13 @@ pub trait SparseMerkleTree { return value; } + let leaf = self.get_leaf_at(&key); let node_index = { let leaf_index: LeafIndex = key.into(); leaf_index.into() }; - self.recompute_nodes_from_index_to_root(node_index, Self::hash_value(value)); + self.recompute_nodes_from_index_to_root(node_index, Self::hash_leaf(&leaf)); old_value } @@ -124,12 +125,11 @@ pub trait SparseMerkleTree { /// Inserts a leaf node, and returns the value at the key if already exists fn insert_leaf_node(&self, key: Self::Key, value: Self::Value) -> Option; + /// Returns the leaf at the specified index. + fn get_leaf_at(&self, key: &Self::Key) -> Self::Leaf; + /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; - - /// Returns the hash of a value - /// FIXME: I found no good interface to mean "is hashable into a RpoDigest" that I could apply to `Self::Value` - fn hash_value(value: Self::Value) -> RpoDigest; } // INNER NODE From 445f802852fdf3e09075353db46f41e096cecf44 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 11:32:35 -0500 Subject: [PATCH 011/117] use Vec --- src/merkle/smt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 5b138355..f4df3633 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -3,7 +3,7 @@ use crate::{ Word, }; -use super::{MerkleError, MerklePath, NodeIndex}; +use super::{MerkleError, MerklePath, NodeIndex, Vec}; // SPARSE MERKLE TREE // ================================================================================================ From 4ec228ff492eee3058aa9d74b746a9a6b4284c6c Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 13:23:20 -0500 Subject: [PATCH 012/117] use `InnerNode` in `SimpleSmt` --- src/merkle/simple_smt/mod.rs | 36 ++++++++++------------------------ src/merkle/simple_smt/tests.rs | 2 +- src/merkle/smt.rs | 4 ++-- 3 files changed, 13 insertions(+), 29 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 4ce94a41..2e9a05ac 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,6 @@ use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNodeInfo, MerkleError, MerklePath, MerkleTreeDelta, - NodeIndex, Rpo256, RpoDigest, StoreNode, TryApplyDiff, Vec, Word, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, MerkleError, MerklePath, + MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, StoreNode, TryApplyDiff, Vec, Word, }; #[cfg(test)] @@ -18,7 +18,7 @@ pub struct SimpleSmt { depth: u8, root: RpoDigest, leaves: BTreeMap, - branches: BTreeMap, + branches: BTreeMap, } impl SimpleSmt { @@ -152,7 +152,7 @@ impl SimpleSmt { }; Ok(leaf) } else { - Ok(self.get_branch_node(&index).parent()) + Ok(self.get_branch_node(&index).hash()) } } @@ -183,7 +183,7 @@ impl SimpleSmt { for _ in 0..index.depth() { let is_right = index.is_value_odd(); index.move_up(); - let BranchNode { left, right } = self.get_branch_node(&index); + let InnerNode { left, right } = self.get_branch_node(&index); let value = if is_right { left } else { right }; path.push(value); } @@ -212,7 +212,7 @@ impl SimpleSmt { /// Returns an iterator over the inner nodes of this Merkle tree. pub fn inner_nodes(&self) -> impl Iterator + '_ { self.branches.values().map(|e| InnerNodeInfo { - value: e.parent(), + value: e.hash(), left: e.left, right: e.right, }) @@ -317,7 +317,7 @@ impl SimpleSmt { for _ in 0..index.depth() { let is_right = index.is_value_odd(); index.move_up(); - let BranchNode { left, right } = self.get_branch_node(&index); + let InnerNode { left, right } = self.get_branch_node(&index); let (left, right) = if is_right { (left, value) } else { (value, right) }; self.insert_branch_node(index, left, right); value = Rpo256::merge(&[left, right]); @@ -333,35 +333,19 @@ impl SimpleSmt { self.leaves.insert(key, node) } - fn get_branch_node(&self, index: &NodeIndex) -> BranchNode { + fn get_branch_node(&self, index: &NodeIndex) -> InnerNode { self.branches.get(index).cloned().unwrap_or_else(|| { let node = EmptySubtreeRoots::entry(self.depth, index.depth() + 1); - BranchNode { left: *node, right: *node } + InnerNode { left: *node, right: *node } }) } fn insert_branch_node(&mut self, index: NodeIndex, left: RpoDigest, right: RpoDigest) { - let branch = BranchNode { left, right }; + let branch = InnerNode { left, right }; self.branches.insert(index, branch); } } -// BRANCH NODE -// ================================================================================================ - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -struct BranchNode { - left: RpoDigest, - right: RpoDigest, -} - -impl BranchNode { - fn parent(&self) -> RpoDigest { - Rpo256::merge(&[self.left, self.right]) - } -} - // TRY APPLY DIFF // ================================================================================================ impl TryApplyDiff for SimpleSmt { diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 7949646f..92f80b8a 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -396,7 +396,7 @@ fn test_simplesmt_set_subtree() { assert_eq!(tree.root(), k); assert_eq!(tree.get_leaf(4).unwrap(), c); - assert_eq!(tree.get_branch_node(&NodeIndex::new_unchecked(2, 2)).parent(), g); + assert_eq!(tree.get_branch_node(&NodeIndex::new_unchecked(2, 2)).hash(), g); } /// Ensures that an invalid input node index into `set_subtree()` incurs no mutation of the tree diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index f4df3633..8add4971 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -138,8 +138,8 @@ pub trait SparseMerkleTree { #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InnerNode { - left: RpoDigest, - right: RpoDigest, + pub left: RpoDigest, + pub right: RpoDigest, } impl InnerNode { From d5cee9fec4cf597e331f969ed5acaf42952e5472 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 14:20:42 -0500 Subject: [PATCH 013/117] SimpleSmt: make DEPTH const generic --- Cargo.toml | 14 ++++-- benches/smt.rs | 82 ++++++++++++++++------------------ benches/store.rs | 38 ++++++++-------- src/merkle/delta.rs | 2 +- src/merkle/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 71 ++++++++++++++--------------- src/merkle/simple_smt/tests.rs | 70 +++++++++++++---------------- src/merkle/store/mod.rs | 4 +- src/merkle/store/tests.rs | 28 ++++++------ 9 files changed, 154 insertions(+), 157 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 008936f9..394c7111 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,19 +35,27 @@ harness = false default = ["std"] executable = ["dep:clap", "dep:rand_utils", "std"] serde = ["dep:serde", "serde?/alloc", "winter_math/serde"] -std = ["blake3/std", "dep:cc", "dep:libc", "winter_crypto/std", "winter_math/std", "winter_utils/std"] +std = [ + "blake3/std", + "dep:cc", + "dep:libc", + "winter_crypto/std", + "winter_math/std", + "winter_utils/std", +] [dependencies] blake3 = { version = "1.5", default-features = false } clap = { version = "4.4", features = ["derive"], optional = true } -libc = { version = "0.2", default-features = false, optional = true } +libc = { version = "0.2", default-features = false, optional = true } rand_utils = { version = "0.7", package = "winter-rand-utils", optional = true } -serde = { version = "1.0", features = [ "derive" ], default-features = false, optional = true } +serde = { version = "1.0", features = ["derive"], default-features = false, optional = true } winter_crypto = { version = "0.7", package = "winter-crypto", default-features = false } winter_math = { version = "0.7", package = "winter-math", default-features = false } winter_utils = { version = "0.7", package = "winter-utils", default-features = false } [dev-dependencies] +seq-macro = { version = "0.3" } criterion = { version = "0.5", features = ["html_reports"] } proptest = "1.4" rand_utils = { version = "0.7", package = "winter-rand-utils" } diff --git a/benches/smt.rs b/benches/smt.rs index 0f9c371a..601206b8 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -2,15 +2,16 @@ use core::mem::swap; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use miden_crypto::{merkle::SimpleSmt, Felt, Word}; use rand_utils::prng_array; +use seq_macro::seq; fn smt_rpo(c: &mut Criterion) { // setup trees let mut seed = [0u8; 32]; - let mut trees = vec![]; + let leaf = generate_word(&mut seed); - for depth in 14..=20 { - let leaves = ((1 << depth) - 1) as u64; + seq!(DEPTH in 14..=20 { + let leaves = ((1 << DEPTH) - 1) as u64; for count in [1, leaves / 2, leaves] { let entries: Vec<_> = (0..count) .map(|i| { @@ -18,50 +19,45 @@ fn smt_rpo(c: &mut Criterion) { (i, word) }) .collect(); - let tree = SimpleSmt::with_leaves(depth, entries).unwrap(); - trees.push((tree, count)); - } - } - - let leaf = generate_word(&mut seed); + let mut tree = SimpleSmt::::with_leaves(entries).unwrap(); - // benchmarks + // benchmark 1 + let mut insert = c.benchmark_group("smt update_leaf".to_string()); + { + let depth = tree.depth(); + let key = count >> 2; + insert.bench_with_input( + format!("simple smt(depth:{depth},count:{count})"), + &(key, leaf), + |b, (key, leaf)| { + b.iter(|| { + tree.update_leaf(black_box(*key), black_box(*leaf)).unwrap(); + }); + }, + ); - let mut insert = c.benchmark_group("smt update_leaf".to_string()); + } + insert.finish(); - for (tree, count) in trees.iter_mut() { - let depth = tree.depth(); - let key = *count >> 2; - insert.bench_with_input( - format!("simple smt(depth:{depth},count:{count})"), - &(key, leaf), - |b, (key, leaf)| { - b.iter(|| { - tree.update_leaf(black_box(*key), black_box(*leaf)).unwrap(); - }); - }, - ); - } + // benchmark 2 + let mut path = c.benchmark_group("smt get_leaf_path".to_string()); + { + let depth = tree.depth(); + let key = count >> 2; + path.bench_with_input( + format!("simple smt(depth:{depth},count:{count})"), + &key, + |b, key| { + b.iter(|| { + tree.get_leaf_path(black_box(*key)).unwrap(); + }); + }, + ); - insert.finish(); - - let mut path = c.benchmark_group("smt get_leaf_path".to_string()); - - for (tree, count) in trees.iter_mut() { - let depth = tree.depth(); - let key = *count >> 2; - path.bench_with_input( - format!("simple smt(depth:{depth},count:{count})"), - &key, - |b, key| { - b.iter(|| { - tree.get_leaf_path(black_box(*key)).unwrap(); - }); - }, - ); - } - - path.finish(); + } + path.finish(); + } + }); } criterion_group!(smt_group, smt_rpo); diff --git a/benches/store.rs b/benches/store.rs index 0abeb980..bc761b45 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -1,5 +1,7 @@ use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; -use miden_crypto::merkle::{DefaultMerkleStore as MerkleStore, MerkleTree, NodeIndex, SimpleSmt}; +use miden_crypto::merkle::{ + DefaultMerkleStore as MerkleStore, MerkleTree, NodeIndex, SimpleSmt, SIMPLE_SMT_MAX_DEPTH, +}; use miden_crypto::Word; use miden_crypto::{hash::rpo::RpoDigest, Felt}; use rand_utils::{rand_array, rand_value}; @@ -28,26 +30,26 @@ fn random_index(range: u64, depth: u8) -> NodeIndex { fn get_empty_leaf_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_empty_leaf_simplesmt"); - let depth = SimpleSmt::MAX_DEPTH; + const DEPTH: u8 = SIMPLE_SMT_MAX_DEPTH; let size = u64::MAX; // both SMT and the store are pre-populated with empty hashes, accessing these values is what is // being benchmarked here, so no values are inserted into the backends - let smt = SimpleSmt::new(depth).unwrap(); + let smt = SimpleSmt::::new().unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); - group.bench_function(BenchmarkId::new("SimpleSmt", depth), |b| { + group.bench_function(BenchmarkId::new("SimpleSmt", DEPTH), |b| { b.iter_batched( - || random_index(size, depth), + || random_index(size, DEPTH), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) }); - group.bench_function(BenchmarkId::new("MerkleStore", depth), |b| { + group.bench_function(BenchmarkId::new("MerkleStore", DEPTH), |b| { b.iter_batched( - || random_index(size, depth), + || random_index(size, DEPTH), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) @@ -104,7 +106,7 @@ fn get_leaf_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); @@ -132,18 +134,18 @@ fn get_leaf_simplesmt(c: &mut Criterion) { fn get_node_of_empty_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_node_of_empty_simplesmt"); - let depth = SimpleSmt::MAX_DEPTH; + const DEPTH: u8 = SIMPLE_SMT_MAX_DEPTH; // both SMT and the store are pre-populated with the empty hashes, accessing the internal nodes // of these values is what is being benchmarked here, so no values are inserted into the // backends. - let smt = SimpleSmt::new(depth).unwrap(); + let smt = SimpleSmt::::new().unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); - let half_depth = depth / 2; + let half_depth = DEPTH / 2; let half_size = 2_u64.pow(half_depth as u32); - group.bench_function(BenchmarkId::new("SimpleSmt", depth), |b| { + group.bench_function(BenchmarkId::new("SimpleSmt", DEPTH), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(smt.get_node(index)), @@ -151,7 +153,7 @@ fn get_node_of_empty_simplesmt(c: &mut Criterion) { ) }); - group.bench_function(BenchmarkId::new("MerkleStore", depth), |b| { + group.bench_function(BenchmarkId::new("MerkleStore", DEPTH), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(store.get_node(root, index)), @@ -212,7 +214,7 @@ fn get_node_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let half_depth = smt.depth() / 2; @@ -286,7 +288,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); @@ -352,7 +354,7 @@ fn new(c: &mut Criterion) { .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>() }, - |l| black_box(SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, l)), + |l| black_box(SimpleSmt::::with_leaves(l)), BatchSize::SmallInput, ) }); @@ -367,7 +369,7 @@ fn new(c: &mut Criterion) { .collect::>() }, |l| { - let smt = SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, l).unwrap(); + let smt = SimpleSmt::::with_leaves(l).unwrap(); black_box(MerkleStore::from(&smt)); }, BatchSize::SmallInput, @@ -433,7 +435,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let mut smt = SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, smt_leaves.clone()).unwrap(); + let mut smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let mut store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); diff --git a/src/merkle/delta.rs b/src/merkle/delta.rs index 064cd01b..4de94750 100644 --- a/src/merkle/delta.rs +++ b/src/merkle/delta.rs @@ -126,7 +126,7 @@ fn test_compute_merkle_delta() { (20, [Felt::new(8), Felt::new(9), Felt::new(10), Felt::new(11)]), (31, [Felt::new(12), Felt::new(13), Felt::new(14), Felt::new(15)]), ]; - let simple_smt = SimpleSmt::with_leaves(30, entries.clone()).unwrap(); + let simple_smt = SimpleSmt::<30>::with_leaves(entries.clone()).unwrap(); let mut store: MerkleStore = (&simple_smt).into(); let root = simple_smt.root(); diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 07c9703f..64a11d4b 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,7 +25,7 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; -pub use simple_smt::SimpleSmt; +pub use simple_smt::{SimpleSmt, SIMPLE_SMT_MAX_DEPTH, SIMPLE_SMT_MIN_DEPTH}; mod smt; pub use smt::{InnerNode, LeafIndex, SparseMerkleTree}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 2e9a05ac..fcd4a878 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -6,6 +6,18 @@ use super::{ #[cfg(test)] mod tests; +// CONSTANTS +// ================================================================================================ + +/// Minimum supported depth. +pub const SIMPLE_SMT_MIN_DEPTH: u8 = 1; + +/// Maximum supported depth. +pub const SIMPLE_SMT_MAX_DEPTH: u8 = 64; + +/// Value of an empty leaf. +pub const EMPTY_VALUE: Word = super::EMPTY_WORD; + // SPARSE MERKLE TREE // ================================================================================================ @@ -14,26 +26,13 @@ mod tests; /// The root of the tree is recomputed on each new leaf update. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct SimpleSmt { - depth: u8, +pub struct SimpleSmt { root: RpoDigest, leaves: BTreeMap, branches: BTreeMap, } -impl SimpleSmt { - // CONSTANTS - // -------------------------------------------------------------------------------------------- - - /// Minimum supported depth. - pub const MIN_DEPTH: u8 = 1; - - /// Maximum supported depth. - pub const MAX_DEPTH: u8 = 64; - - /// Value of an empty leaf. - pub const EMPTY_VALUE: Word = super::EMPTY_WORD; - +impl SimpleSmt { // CONSTRUCTORS // -------------------------------------------------------------------------------------------- @@ -43,19 +42,18 @@ impl SimpleSmt { /// /// # Errors /// Returns an error if the depth is 0 or is greater than 64. - pub fn new(depth: u8) -> Result { + pub fn new() -> Result { // validate the range of the depth. - if depth < Self::MIN_DEPTH { - return Err(MerkleError::DepthTooSmall(depth)); - } else if Self::MAX_DEPTH < depth { - return Err(MerkleError::DepthTooBig(depth as u64)); + if DEPTH < SIMPLE_SMT_MIN_DEPTH { + return Err(MerkleError::DepthTooSmall(DEPTH)); + } else if SIMPLE_SMT_MAX_DEPTH < DEPTH { + return Err(MerkleError::DepthTooBig(DEPTH as u64)); } - let root = *EmptySubtreeRoots::entry(depth, 0); + let root = *EmptySubtreeRoots::entry(DEPTH, 0); Ok(Self { root, - depth, leaves: BTreeMap::new(), branches: BTreeMap::new(), }) @@ -72,15 +70,14 @@ impl SimpleSmt { /// - The number of entries exceeds the maximum tree capacity, that is 2^{depth}. /// - The provided entries contain multiple values for the same key. pub fn with_leaves( - depth: u8, entries: impl IntoIterator, ) -> Result { // create an empty tree - let mut tree = Self::new(depth)?; + let mut tree = Self::new()?; // compute the max number of entries. We use an upper bound of depth 63 because we consider // passing in a vector of size 2^64 infeasible. - let max_num_entries = 2_usize.pow(tree.depth.min(63).into()); + let max_num_entries = 2_usize.pow(tree.depth().min(63).into()); // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so // entries with the empty value need additional tracking. @@ -93,11 +90,11 @@ impl SimpleSmt { let old_value = tree.update_leaf(key, value)?; - if old_value != Self::EMPTY_VALUE || key_set_to_zero.contains(&key) { + if old_value != EMPTY_VALUE || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex(key)); } - if value == Self::EMPTY_VALUE { + if value == EMPTY_VALUE { key_set_to_zero.insert(key); }; } @@ -107,11 +104,9 @@ impl SimpleSmt { /// Wrapper around [`SimpleSmt::with_leaves`] which inserts leaves at contiguous indices /// starting at index 0. pub fn with_contiguous_leaves( - depth: u8, entries: impl IntoIterator, ) -> Result { Self::with_leaves( - depth, entries .into_iter() .enumerate() @@ -129,7 +124,7 @@ impl SimpleSmt { /// Returns the depth of this Merkle tree. pub const fn depth(&self) -> u8 { - self.depth + DEPTH } /// Returns a node at the specified index. @@ -148,7 +143,7 @@ impl SimpleSmt { let leaf_pos = index.value(); let leaf = match self.get_leaf_node(leaf_pos) { Some(word) => word.into(), - None => *EmptySubtreeRoots::entry(self.depth, index.depth()), + None => *EmptySubtreeRoots::entry(self.depth(), index.depth()), }; Ok(leaf) } else { @@ -161,7 +156,7 @@ impl SimpleSmt { /// # Errors /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}. pub fn get_leaf(&self, index: u64) -> Result { - let index = NodeIndex::new(self.depth, index)?; + let index = NodeIndex::new(self.depth(), index)?; Ok(self.get_node(index)?.into()) } @@ -231,7 +226,7 @@ impl SimpleSmt { // validate the index before modifying the structure let idx = NodeIndex::new(self.depth(), index)?; - let old_value = self.insert_leaf_node(index, value).unwrap_or(Self::EMPTY_VALUE); + let old_value = self.insert_leaf_node(index, value).unwrap_or(EMPTY_VALUE); // if the old value and new value are the same, there is nothing to update if value == old_value { @@ -247,10 +242,10 @@ impl SimpleSmt { /// computed as `self.depth() - subtree.depth()`. /// /// Returns the new root. - pub fn set_subtree( + pub fn set_subtree( &mut self, subtree_insertion_index: u64, - subtree: SimpleSmt, + subtree: SimpleSmt, ) -> Result { if subtree.depth() > self.depth() { return Err(MerkleError::InvalidSubtreeDepth { @@ -335,7 +330,7 @@ impl SimpleSmt { fn get_branch_node(&self, index: &NodeIndex) -> InnerNode { self.branches.get(index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(self.depth, index.depth() + 1); + let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); InnerNode { left: *node, right: *node } }) } @@ -348,7 +343,7 @@ impl SimpleSmt { // TRY APPLY DIFF // ================================================================================================ -impl TryApplyDiff for SimpleSmt { +impl TryApplyDiff for SimpleSmt { type Error = MerkleError; type DiffType = MerkleTreeDelta; @@ -361,7 +356,7 @@ impl TryApplyDiff for SimpleSmt { } for slot in diff.cleared_slots() { - self.update_leaf(*slot, Self::EMPTY_VALUE)?; + self.update_leaf(*slot, EMPTY_VALUE)?; } for (slot, value) in diff.updated_slots() { diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 92f80b8a..3a43cd44 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -34,14 +34,14 @@ const ZERO_VALUES8: [Word; 8] = [int_to_leaf(0); 8]; #[test] fn build_empty_tree() { // tree of depth 3 - let smt = SimpleSmt::new(3).unwrap(); + let smt = SimpleSmt::<3>::new().unwrap(); let mt = MerkleTree::new(ZERO_VALUES8).unwrap(); assert_eq!(mt.root(), smt.root()); } #[test] fn build_sparse_tree() { - let mut smt = SimpleSmt::new(3).unwrap(); + let mut smt = SimpleSmt::<3>::new().unwrap(); let mut values = ZERO_VALUES8.to_vec(); // insert single value @@ -75,11 +75,11 @@ fn build_sparse_tree() { #[test] fn build_contiguous_tree() { let tree_with_leaves = - SimpleSmt::with_leaves(2, [0, 1, 2, 3].into_iter().zip(digests_to_words(&VALUES4))) + SimpleSmt::<2>::with_leaves([0, 1, 2, 3].into_iter().zip(digests_to_words(&VALUES4))) .unwrap(); let tree_with_contiguous_leaves = - SimpleSmt::with_contiguous_leaves(2, digests_to_words(&VALUES4)).unwrap(); + SimpleSmt::<2>::with_contiguous_leaves(digests_to_words(&VALUES4)).unwrap(); assert_eq!(tree_with_leaves, tree_with_contiguous_leaves); } @@ -87,7 +87,7 @@ fn build_contiguous_tree() { #[test] fn test_depth2_tree() { let tree = - SimpleSmt::with_leaves(2, KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); + SimpleSmt::<2>::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); // check internal structure let (root, node2, node3) = compute_internal_nodes(); @@ -115,7 +115,7 @@ fn test_depth2_tree() { #[test] fn test_inner_node_iterator() -> Result<(), MerkleError> { let tree = - SimpleSmt::with_leaves(2, KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); + SimpleSmt::<2>::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); // check depth 2 assert_eq!(VALUES4[0], tree.get_node(NodeIndex::make(2, 0)).unwrap()); @@ -146,7 +146,7 @@ fn test_inner_node_iterator() -> Result<(), MerkleError> { #[test] fn update_leaf() { let mut tree = - SimpleSmt::with_leaves(3, KEYS8.into_iter().zip(digests_to_words(&VALUES8))).unwrap(); + SimpleSmt::<3>::with_leaves(KEYS8.into_iter().zip(digests_to_words(&VALUES8))).unwrap(); // update one value let key = 3; @@ -197,9 +197,8 @@ fn small_tree_opening_is_consistent() { let k = Rpo256::merge(&[i, j]); - let depth = 3; let entries = vec![(0, a), (1, b), (4, c), (7, d)]; - let tree = SimpleSmt::with_leaves(depth, entries).unwrap(); + let tree = SimpleSmt::<3>::with_leaves(entries).unwrap(); assert_eq!(tree.root(), k); @@ -241,12 +240,12 @@ fn test_simplesmt_fail_on_duplicates() { for (first, second) in values.iter() { // consecutive let entries = [(1, *first), (1, *second)]; - let smt = SimpleSmt::with_leaves(64, entries); + let smt = SimpleSmt::<64>::with_leaves(entries); assert_eq!(smt.unwrap_err(), MerkleError::DuplicateValuesForIndex(1)); // not consecutive let entries = [(1, *first), (5, int_to_leaf(5)), (1, *second)]; - let smt = SimpleSmt::with_leaves(64, entries); + let smt = SimpleSmt::<64>::with_leaves(entries); assert_eq!(smt.unwrap_err(), MerkleError::DuplicateValuesForIndex(1)); } } @@ -254,7 +253,7 @@ fn test_simplesmt_fail_on_duplicates() { #[test] fn with_no_duplicates_empty_node() { let entries = [(1_u64, int_to_leaf(0)), (5, int_to_leaf(2))]; - let smt = SimpleSmt::with_leaves(64, entries); + let smt = SimpleSmt::<64>::with_leaves(entries); assert!(smt.is_ok()); } @@ -264,19 +263,19 @@ fn test_simplesmt_update_nonexisting_leaf_with_zero() { // -------------------------------------------------------------------------------------------- // Depth 1 has 2 leaf. Position is 0-indexed, position 2 doesn't exist. - let mut smt = SimpleSmt::new(1).unwrap(); + let mut smt = SimpleSmt::<1>::new().unwrap(); let result = smt.update_leaf(2, EMPTY_WORD); assert!(!smt.leaves.contains_key(&2)); assert!(result.is_err()); // Depth 2 has 4 leaves. Position is 0-indexed, position 4 doesn't exist. - let mut smt = SimpleSmt::new(2).unwrap(); + let mut smt = SimpleSmt::<2>::new().unwrap(); let result = smt.update_leaf(4, EMPTY_WORD); assert!(!smt.leaves.contains_key(&4)); assert!(result.is_err()); // Depth 3 has 8 leaves. Position is 0-indexed, position 8 doesn't exist. - let mut smt = SimpleSmt::new(3).unwrap(); + let mut smt = SimpleSmt::<3>::new().unwrap(); let result = smt.update_leaf(8, EMPTY_WORD); assert!(!smt.leaves.contains_key(&8)); assert!(result.is_err()); @@ -286,19 +285,19 @@ fn test_simplesmt_update_nonexisting_leaf_with_zero() { let value = int_to_node(1); // Depth 1 has 2 leaves. Position is 0-indexed, position 1 doesn't exist. - let mut smt = SimpleSmt::new(1).unwrap(); + let mut smt = SimpleSmt::<1>::new().unwrap(); let result = smt.update_leaf(2, *value); assert!(!smt.leaves.contains_key(&2)); assert!(result.is_err()); // Depth 2 has 4 leaves. Position is 0-indexed, position 2 doesn't exist. - let mut smt = SimpleSmt::new(2).unwrap(); + let mut smt = SimpleSmt::<2>::new().unwrap(); let result = smt.update_leaf(4, *value); assert!(!smt.leaves.contains_key(&4)); assert!(result.is_err()); // Depth 3 has 8 leaves. Position is 0-indexed, position 4 doesn't exist. - let mut smt = SimpleSmt::new(3).unwrap(); + let mut smt = SimpleSmt::<3>::new().unwrap(); let result = smt.update_leaf(8, *value); assert!(!smt.leaves.contains_key(&8)); assert!(result.is_err()); @@ -311,17 +310,17 @@ fn test_simplesmt_with_leaves_nonexisting_leaf() { // Depth 1 has 2 leaf. Position is 0-indexed, position 2 doesn't exist. let leaves = [(2, EMPTY_WORD)]; - let result = SimpleSmt::with_leaves(1, leaves); + let result = SimpleSmt::<1>::with_leaves(leaves); assert!(result.is_err()); // Depth 2 has 4 leaves. Position is 0-indexed, position 4 doesn't exist. let leaves = [(4, EMPTY_WORD)]; - let result = SimpleSmt::with_leaves(2, leaves); + let result = SimpleSmt::<2>::with_leaves(leaves); assert!(result.is_err()); // Depth 3 has 8 leaves. Position is 0-indexed, position 8 doesn't exist. let leaves = [(8, EMPTY_WORD)]; - let result = SimpleSmt::with_leaves(3, leaves); + let result = SimpleSmt::<3>::with_leaves(leaves); assert!(result.is_err()); // TESTING WITH A VALUE @@ -330,17 +329,17 @@ fn test_simplesmt_with_leaves_nonexisting_leaf() { // Depth 1 has 2 leaves. Position is 0-indexed, position 2 doesn't exist. let leaves = [(2, *value)]; - let result = SimpleSmt::with_leaves(1, leaves); + let result = SimpleSmt::<1>::with_leaves(leaves); assert!(result.is_err()); // Depth 2 has 4 leaves. Position is 0-indexed, position 4 doesn't exist. let leaves = [(4, *value)]; - let result = SimpleSmt::with_leaves(2, leaves); + let result = SimpleSmt::<2>::with_leaves(leaves); assert!(result.is_err()); // Depth 3 has 8 leaves. Position is 0-indexed, position 8 doesn't exist. let leaves = [(8, *value)]; - let result = SimpleSmt::with_leaves(3, leaves); + let result = SimpleSmt::<3>::with_leaves(leaves); assert!(result.is_err()); } @@ -378,16 +377,14 @@ fn test_simplesmt_set_subtree() { // / \ // c 0 let subtree = { - let depth = 1; let entries = vec![(0, c)]; - SimpleSmt::with_leaves(depth, entries).unwrap() + SimpleSmt::<1>::with_leaves(entries).unwrap() }; // insert subtree let tree = { - let depth = 3; let entries = vec![(0, a), (1, b), (7, d)]; - let mut tree = SimpleSmt::with_leaves(depth, entries).unwrap(); + let mut tree = SimpleSmt::<3>::with_leaves(entries).unwrap(); tree.set_subtree(2, subtree).unwrap(); @@ -424,15 +421,13 @@ fn test_simplesmt_set_subtree_unchanged_for_wrong_index() { // / \ // c 0 let subtree = { - let depth = 1; let entries = vec![(0, c)]; - SimpleSmt::with_leaves(depth, entries).unwrap() + SimpleSmt::<1>::with_leaves(entries).unwrap() }; let mut tree = { - let depth = 3; let entries = vec![(0, a), (1, b), (7, d)]; - SimpleSmt::with_leaves(depth, entries).unwrap() + SimpleSmt::<3>::with_leaves(entries).unwrap() }; let tree_root_before_insertion = tree.root(); @@ -462,21 +457,20 @@ fn test_simplesmt_set_subtree_entire_tree() { let c = Word::from(Rpo256::merge(&[b.into(); 2])); let d = Word::from(Rpo256::merge(&[c.into(); 2])); - let depth = 3; - // subtree: E3 - let subtree = { SimpleSmt::with_leaves(depth, Vec::new()).unwrap() }; - assert_eq!(subtree.root(), *EmptySubtreeRoots::entry(depth, 0)); + const DEPTH: u8 = 3; + let subtree = { SimpleSmt::::with_leaves(Vec::new()).unwrap() }; + assert_eq!(subtree.root(), *EmptySubtreeRoots::entry(DEPTH, 0)); // insert subtree let mut tree = { let entries = vec![(0, a), (1, b), (4, c), (7, d)]; - SimpleSmt::with_leaves(depth, entries).unwrap() + SimpleSmt::<3>::with_leaves(entries).unwrap() }; tree.set_subtree(0, subtree).unwrap(); - assert_eq!(tree.root(), *EmptySubtreeRoots::entry(depth, 0)); + assert_eq!(tree.root(), *EmptySubtreeRoots::entry(DEPTH, 0)); } // HELPER FUNCTIONS diff --git a/src/merkle/store/mod.rs b/src/merkle/store/mod.rs index caba99e5..7e931904 100644 --- a/src/merkle/store/mod.rs +++ b/src/merkle/store/mod.rs @@ -490,8 +490,8 @@ impl> From<&MerkleTree> for MerkleStore { } } -impl> From<&SimpleSmt> for MerkleStore { - fn from(value: &SimpleSmt) -> Self { +impl, const DEPTH: u8> From<&SimpleSmt> for MerkleStore { + fn from(value: &SimpleSmt) -> Self { let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect(); Self { nodes } } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 2d22b3d0..3f53091f 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -3,7 +3,9 @@ use super::{ PartialMerkleTree, RecordingMerkleStore, Rpo256, RpoDigest, }; use crate::{ - merkle::{digests_to_words, int_to_leaf, int_to_node, MerkleTree, SimpleSmt}, + merkle::{ + digests_to_words, int_to_leaf, int_to_node, MerkleTree, SimpleSmt, SIMPLE_SMT_MAX_DEPTH, + }, Felt, Word, ONE, WORD_SIZE, ZERO, }; @@ -13,6 +15,8 @@ use super::{Deserializable, Serializable}; #[cfg(feature = "std")] use std::error::Error; +use seq_macro::seq; + // TEST DATA // ================================================================================================ @@ -173,10 +177,10 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { // Starts at 1 because leafs are not included in the store. // Ends at 64 because it is not possible to represent an index of a depth greater than 64, // because a u64 is used to index the leaf. - for depth in 1..64 { - let smt = SimpleSmt::new(depth)?; + seq!(DEPTH in 1_u8..64_u8 { + let smt = SimpleSmt::::new()?; - let index = NodeIndex::make(depth, 0); + let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; let smt_path = smt.get_path(index)?; assert_eq!( @@ -189,11 +193,12 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { "the returned merkle path does not match the computed values" ); assert_eq!( - store_path.path.compute_root(depth.into(), RpoDigest::default()).unwrap(), + store_path.path.compute_root(DEPTH.into(), RpoDigest::default()).unwrap(), smt.root(), "computed root from the path must match the empty tree root" ); - } + + }); Ok(()) } @@ -210,7 +215,7 @@ fn test_get_invalid_node() { fn test_add_sparse_merkle_tree_one_level() -> Result<(), MerkleError> { let keys2: [u64; 2] = [0, 1]; let leaves2: [Word; 2] = [int_to_leaf(1), int_to_leaf(2)]; - let smt = SimpleSmt::with_leaves(1, keys2.into_iter().zip(leaves2)).unwrap(); + let smt = SimpleSmt::<1>::with_leaves(keys2.into_iter().zip(leaves2)).unwrap(); let store = MerkleStore::from(&smt); let idx = NodeIndex::make(1, 0); @@ -226,8 +231,7 @@ fn test_add_sparse_merkle_tree_one_level() -> Result<(), MerkleError> { #[test] fn test_sparse_merkle_tree() -> Result<(), MerkleError> { - let smt = SimpleSmt::with_leaves( - SimpleSmt::MAX_DEPTH, + let smt = SimpleSmt::::with_leaves( KEYS4.into_iter().zip(digests_to_words(&VALUES4)), ) .unwrap(); @@ -552,9 +556,8 @@ fn test_constructors() -> Result<(), MerkleError> { assert_eq!(mtree.get_path(index)?, value_path.path); } - let depth = 32; let smt = - SimpleSmt::with_leaves(depth, KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); + SimpleSmt::<32>::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); @@ -880,8 +883,7 @@ fn test_serialization() -> Result<(), Box> { fn test_recorder() { // instantiate recorder from MerkleTree and SimpleSmt let mtree = MerkleTree::new(digests_to_words(&VALUES4)).unwrap(); - let smtree = SimpleSmt::with_leaves( - 64, + let smtree = SimpleSmt::<64>::with_leaves( KEYS8.into_iter().zip(VALUES8.into_iter().map(|x| x.into()).rev()), ) .unwrap(); From 781ea71093de1e89a182a003d3f132b57c077c9a Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 14:24:11 -0500 Subject: [PATCH 014/117] LeafIndex: derives --- src/merkle/smt.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 8add4971..cf1440db 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -152,6 +152,8 @@ impl InnerNode { // ================================================================================================ /// The index of a leaf, at a depth known at compile-time. +#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct LeafIndex { index: NodeIndex, } From 8e0cde0d14406c39304aab50cadaaa1710bb6087 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 14:32:42 -0500 Subject: [PATCH 015/117] implement SparseMerkleTree for SimpleSmt --- src/merkle/simple_smt/mod.rs | 42 ++++++++++++++++++++++++++++++++++-- src/merkle/smt.rs | 2 +- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index fcd4a878..7234954d 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,7 @@ use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, MerkleError, MerklePath, - MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, StoreNode, TryApplyDiff, Vec, Word, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, + MerklePath, MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, SparseMerkleTree, StoreNode, + TryApplyDiff, Vec, Word, }; #[cfg(test)] @@ -341,6 +342,43 @@ impl SimpleSmt { } } +impl SparseMerkleTree for SimpleSmt { + type Key = LeafIndex; + type Value = Word; + type Leaf = Word; + + fn root(&self) -> RpoDigest { + self.root() + } + + fn set_root(&mut self, root: RpoDigest) { + self.root = root; + } + + fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + self.get_branch_node(&index) + } + + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { + let InnerNode { left, right } = inner_node; + + self.insert_branch_node(index, left, right) + } + + fn insert_leaf_node(&mut self, key: LeafIndex, value: Word) -> Option { + self.leaves.insert(key.value(), value) + } + + fn get_leaf_at(&self, key: &LeafIndex) -> Word { + self.get_leaf(key.value()) + .expect("we have compile-time guarantees on the depth of the tree") + } + + fn hash_leaf(leaf: &Word) -> RpoDigest { + leaf.into() + } +} + // TRY APPLY DIFF // ================================================================================================ impl TryApplyDiff for SimpleSmt { diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index cf1440db..0a794a5d 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -123,7 +123,7 @@ pub trait SparseMerkleTree { fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode); /// Inserts a leaf node, and returns the value at the key if already exists - fn insert_leaf_node(&self, key: Self::Key, value: Self::Value) -> Option; + fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option; /// Returns the leaf at the specified index. fn get_leaf_at(&self, key: &Self::Key) -> Self::Leaf; From da9ada4d76638dac4184874b7a09ecf26f5cbe0c Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 14:34:24 -0500 Subject: [PATCH 016/117] Remove old comment --- src/merkle/smt.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 0a794a5d..a70efb14 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -40,9 +40,6 @@ pub trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - /// - /// # Errors - /// Returns an error if the specified index is too large given the depth of this Merkle tree. fn get_merkle_path(&self, key: Self::Key) -> MerklePath { let mut index: NodeIndex = { let leaf_index: LeafIndex = key.into(); From f8720d524f3b078b2c12efd3a44ae25a6a98f0c9 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 10 Jan 2024 14:38:45 -0500 Subject: [PATCH 017/117] Rename get_merkle_path --- src/merkle/smt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index a70efb14..34567ac5 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -40,7 +40,7 @@ pub trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn get_merkle_path(&self, key: Self::Key) -> MerklePath { + fn get_leaf_path(&self, key: Self::Key) -> MerklePath { let mut index: NodeIndex = { let leaf_index: LeafIndex = key.into(); leaf_index.into() From eeba1784dfb67841895651bf40c7637b159cbf24 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:23:50 -0500 Subject: [PATCH 018/117] Remove `SimpleSmt::get_path()` and `get_leaf_path()` --- benches/smt.rs | 7 ++++-- benches/store.rs | 9 ++++++-- src/merkle/simple_smt/mod.rs | 39 +------------------------------ src/merkle/simple_smt/tests.rs | 42 ++++++++++++++-------------------- src/merkle/store/tests.rs | 30 ++++++++++++------------ 5 files changed, 46 insertions(+), 81 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index 601206b8..828019b2 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -1,6 +1,9 @@ use core::mem::swap; use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use miden_crypto::{merkle::SimpleSmt, Felt, Word}; +use miden_crypto::{ + merkle::{LeafIndex, SimpleSmt, SparseMerkleTree}, + Felt, Word, +}; use rand_utils::prng_array; use seq_macro::seq; @@ -49,7 +52,7 @@ fn smt_rpo(c: &mut Criterion) { &key, |b, key| { b.iter(|| { - tree.get_leaf_path(black_box(*key)).unwrap(); + tree.get_leaf_path(black_box(LeafIndex::::new(*key).unwrap())); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index bc761b45..38e6282e 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -1,6 +1,7 @@ use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use miden_crypto::merkle::{ - DefaultMerkleStore as MerkleStore, MerkleTree, NodeIndex, SimpleSmt, SIMPLE_SMT_MAX_DEPTH, + DefaultMerkleStore as MerkleStore, LeafIndex, MerkleTree, NodeIndex, SimpleSmt, + SparseMerkleTree, SIMPLE_SMT_MAX_DEPTH, }; use miden_crypto::Word; use miden_crypto::{hash::rpo::RpoDigest, Felt}; @@ -297,7 +298,11 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( || random_index(size_u64, depth), - |index| black_box(smt.get_path(index)), + |index| { + black_box(smt.get_leaf_path( + LeafIndex::::new(index.value()).unwrap(), + )) + }, BatchSize::SmallInput, ) }); diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 7234954d..90c4a850 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,7 +1,6 @@ use super::{ BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerklePath, MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, SparseMerkleTree, StoreNode, - TryApplyDiff, Vec, Word, + MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, }; #[cfg(test)] @@ -161,42 +160,6 @@ impl SimpleSmt { Ok(self.get_node(index)?.into()) } - /// Returns a Merkle path from the node at the specified index to the root. - /// - /// The node itself is not included in the path. - /// - /// # Errors - /// Returns an error if the specified index has depth set to 0 or the depth is greater than - /// the depth of this Merkle tree. - pub fn get_path(&self, mut index: NodeIndex) -> Result { - if index.is_root() { - return Err(MerkleError::DepthTooSmall(index.depth())); - } else if index.depth() > self.depth() { - return Err(MerkleError::DepthTooBig(index.depth() as u64)); - } - - let mut path = Vec::with_capacity(index.depth() as usize); - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = self.get_branch_node(&index); - let value = if is_right { left } else { right }; - path.push(value); - } - Ok(MerklePath::new(path)) - } - - /// Return a Merkle path from the leaf at the specified index to the root. - /// - /// The leaf itself is not included in the path. - /// - /// # Errors - /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}. - pub fn get_leaf_path(&self, index: u64) -> Result { - let index = NodeIndex::new(self.depth(), index)?; - self.get_path(index) - } - // ITERATORS // -------------------------------------------------------------------------------------------- diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 3a43cd44..2c0e5745 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -1,9 +1,11 @@ use super::{ super::{InnerNodeInfo, MerkleError, MerkleTree, RpoDigest, SimpleSmt, EMPTY_WORD}, - NodeIndex, Rpo256, Vec, + NodeIndex, Rpo256, }; use crate::{ - merkle::{digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots}, + merkle::{ + digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex, SparseMerkleTree, + }, Word, }; @@ -53,7 +55,7 @@ fn build_sparse_tree() { assert_eq!(mt2.root(), smt.root()); assert_eq!( mt2.get_path(NodeIndex::make(3, 6)).unwrap(), - smt.get_path(NodeIndex::make(3, 6)).unwrap() + smt.get_leaf_path(LeafIndex::<3>::new(6).unwrap()) ); assert_eq!(old_value, EMPTY_WORD); @@ -66,7 +68,7 @@ fn build_sparse_tree() { assert_eq!(mt3.root(), smt.root()); assert_eq!( mt3.get_path(NodeIndex::make(3, 2)).unwrap(), - smt.get_path(NodeIndex::make(3, 2)).unwrap() + smt.get_leaf_path(LeafIndex::<3>::new(2).unwrap()) ); assert_eq!(old_value, EMPTY_WORD); } @@ -102,14 +104,10 @@ fn test_depth2_tree() { assert_eq!(VALUES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap()); // check get_path(): depth 2 - assert_eq!(vec![VALUES4[1], node3], *tree.get_path(NodeIndex::make(2, 0)).unwrap()); - assert_eq!(vec![VALUES4[0], node3], *tree.get_path(NodeIndex::make(2, 1)).unwrap()); - assert_eq!(vec![VALUES4[3], node2], *tree.get_path(NodeIndex::make(2, 2)).unwrap()); - assert_eq!(vec![VALUES4[2], node2], *tree.get_path(NodeIndex::make(2, 3)).unwrap()); - - // check get_path(): depth 1 - assert_eq!(vec![node3], *tree.get_path(NodeIndex::make(1, 0)).unwrap()); - assert_eq!(vec![node2], *tree.get_path(NodeIndex::make(1, 1)).unwrap()); + assert_eq!(vec![VALUES4[1], node3], *tree.get_leaf_path(LeafIndex::<2>::new(0).unwrap())); + assert_eq!(vec![VALUES4[0], node3], *tree.get_leaf_path(LeafIndex::<2>::new(1).unwrap())); + assert_eq!(vec![VALUES4[3], node2], *tree.get_leaf_path(LeafIndex::<2>::new(2).unwrap())); + assert_eq!(vec![VALUES4[2], node2], *tree.get_leaf_path(LeafIndex::<2>::new(3).unwrap())); } #[test] @@ -202,21 +200,15 @@ fn small_tree_opening_is_consistent() { assert_eq!(tree.root(), k); - let cases: Vec<(u8, u64, Vec)> = vec![ - (3, 0, vec![b.into(), f, j]), - (3, 1, vec![a.into(), f, j]), - (3, 4, vec![z.into(), h, i]), - (3, 7, vec![z.into(), g, i]), - (2, 0, vec![f, j]), - (2, 1, vec![e, j]), - (2, 2, vec![h, i]), - (2, 3, vec![g, i]), - (1, 0, vec![j]), - (1, 1, vec![i]), + let cases: Vec<(u64, Vec)> = vec![ + (0, vec![b.into(), f, j]), + (1, vec![a.into(), f, j]), + (4, vec![z.into(), h, i]), + (7, vec![z.into(), g, i]), ]; - for (depth, key, path) in cases { - let opening = tree.get_path(NodeIndex::make(depth, key)).unwrap(); + for (key, path) in cases { + let opening = tree.get_leaf_path(LeafIndex::<3>::new(key).unwrap()); assert_eq!(path, *opening); } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 3f53091f..eb4d8230 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -4,7 +4,8 @@ use super::{ }; use crate::{ merkle::{ - digests_to_words, int_to_leaf, int_to_node, MerkleTree, SimpleSmt, SIMPLE_SMT_MAX_DEPTH, + digests_to_words, int_to_leaf, int_to_node, LeafIndex, MerkleTree, SimpleSmt, + SparseMerkleTree, SIMPLE_SMT_MAX_DEPTH, }, Felt, Word, ONE, WORD_SIZE, ZERO, }; @@ -182,7 +183,7 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; - let smt_path = smt.get_path(index)?; + let smt_path = smt.get_leaf_path(LeafIndex::::new(0)?); assert_eq!( store_path.value, RpoDigest::default(), @@ -302,8 +303,8 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.get_path(NodeIndex::make(smt.depth(), 0)), - Ok(result.path), + smt.get_leaf_path(LeafIndex::::new(0).unwrap()), + result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -313,8 +314,8 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.get_path(NodeIndex::make(smt.depth(), 1)), - Ok(result.path), + smt.get_leaf_path(LeafIndex::::new(1).unwrap()), + result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -324,8 +325,8 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.get_path(NodeIndex::make(smt.depth(), 2)), - Ok(result.path), + smt.get_leaf_path(LeafIndex::::new(2).unwrap()), + result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -335,8 +336,8 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.get_path(NodeIndex::make(smt.depth(), 3)), - Ok(result.path), + smt.get_leaf_path(LeafIndex::::new(3).unwrap()), + result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -347,8 +348,8 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.get_path(NodeIndex::make(smt.depth(), 4)), - Ok(result.path), + smt.get_leaf_path(LeafIndex::::new(4).unwrap()), + result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); @@ -556,15 +557,16 @@ fn test_constructors() -> Result<(), MerkleError> { assert_eq!(mtree.get_path(index)?, value_path.path); } + const DEPTH: u8 = 32; let smt = - SimpleSmt::<32>::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); + SimpleSmt::::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); for key in KEYS4 { let index = NodeIndex::make(depth, key); let value_path = store.get_path(smt.root(), index)?; - assert_eq!(smt.get_path(index)?, value_path.path); + assert_eq!(smt.get_leaf_path(LeafIndex::::new(key).unwrap()), value_path.path); } let d = 2; From f5acf5d2bde06bc501d0247ea191a02424b747f7 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:47:09 -0500 Subject: [PATCH 019/117] add tryfrom NodeIndex for LeafIndex --- src/merkle/smt.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 34567ac5..e5cd7958 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -179,6 +179,21 @@ impl From> for NodeIndex { } } +impl TryFrom for LeafIndex { + type Error = MerkleError; + + fn try_from(node_index: NodeIndex) -> Result { + if node_index.depth() != DEPTH { + return Err(MerkleError::InvalidDepth { + expected: DEPTH, + provided: node_index.depth(), + }); + } + + Self::new(node_index.value()) + } +} + impl From for LeafIndex<64> { fn from(value: Word) -> Self { Self::new_max_depth(value[0].inner()) From f762d8a361358607e918b00287828b2e3d342a8e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:53:33 -0500 Subject: [PATCH 020/117] impl get_leaf_at on its own --- src/merkle/simple_smt/mod.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 90c4a850..f717acd5 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -333,8 +333,14 @@ impl SparseMerkleTree for SimpleSmt { } fn get_leaf_at(&self, key: &LeafIndex) -> Word { - self.get_leaf(key.value()) - .expect("we have compile-time guarantees on the depth of the tree") + // the lookup in empty_hashes could fail only if empty_hashes were not built correctly + // by the constructor as we check the depth of the lookup above. + let leaf_pos = key.value(); + + match self.get_leaf_node(leaf_pos) { + Some(word) => word, + None => Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), + } } fn hash_leaf(leaf: &Word) -> RpoDigest { From 8688661719a5ec697da0171076282cf1d4426172 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:55:35 -0500 Subject: [PATCH 021/117] impl get_node in terms of get_leaf_at --- src/merkle/simple_smt/mod.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index f717acd5..90df1137 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -138,14 +138,9 @@ impl SimpleSmt { } else if index.depth() > self.depth() { Err(MerkleError::DepthTooBig(index.depth() as u64)) } else if index.depth() == self.depth() { - // the lookup in empty_hashes could fail only if empty_hashes were not built correctly - // by the constructor as we check the depth of the lookup above. - let leaf_pos = index.value(); - let leaf = match self.get_leaf_node(leaf_pos) { - Some(word) => word.into(), - None => *EmptySubtreeRoots::entry(self.depth(), index.depth()), - }; - Ok(leaf) + let leaf = self.get_leaf_at(&LeafIndex::::try_from(index)?); + + Ok(leaf.into()) } else { Ok(self.get_branch_node(&index).hash()) } From b025d48018faa897699e5aaa739b9efeeeb1deb0 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:59:03 -0500 Subject: [PATCH 022/117] Remove `get_leaf()` --- src/merkle/simple_smt/mod.rs | 9 --------- src/merkle/simple_smt/tests.rs | 5 +++-- src/merkle/store/tests.rs | 9 +++++++-- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 90df1137..8b32d440 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -146,15 +146,6 @@ impl SimpleSmt { } } - /// Returns a value of the leaf at the specified index. - /// - /// # Errors - /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}. - pub fn get_leaf(&self, index: u64) -> Result { - let index = NodeIndex::new(self.depth(), index)?; - Ok(self.get_node(index)?.into()) - } - // ITERATORS // -------------------------------------------------------------------------------------------- diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 2c0e5745..10191a54 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -374,9 +374,10 @@ fn test_simplesmt_set_subtree() { }; // insert subtree + const TREE_DEPTH: u8 = 3; let tree = { let entries = vec![(0, a), (1, b), (7, d)]; - let mut tree = SimpleSmt::<3>::with_leaves(entries).unwrap(); + let mut tree = SimpleSmt::::with_leaves(entries).unwrap(); tree.set_subtree(2, subtree).unwrap(); @@ -384,7 +385,7 @@ fn test_simplesmt_set_subtree() { }; assert_eq!(tree.root(), k); - assert_eq!(tree.get_leaf(4).unwrap(), c); + assert_eq!(tree.get_leaf_at(&LeafIndex::::new(4).unwrap()), c); assert_eq!(tree.get_branch_node(&NodeIndex::new_unchecked(2, 2)).hash(), g); } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index eb4d8230..a195d37b 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -885,7 +885,9 @@ fn test_serialization() -> Result<(), Box> { fn test_recorder() { // instantiate recorder from MerkleTree and SimpleSmt let mtree = MerkleTree::new(digests_to_words(&VALUES4)).unwrap(); - let smtree = SimpleSmt::<64>::with_leaves( + + const TREE_DEPTH: u8 = 64; + let smtree = SimpleSmt::::with_leaves( KEYS8.into_iter().zip(VALUES8.into_iter().map(|x| x.into()).rev()), ) .unwrap(); @@ -921,7 +923,10 @@ fn test_recorder() { assert_eq!(node, smtree.get_node(index_1).unwrap()); let node = merkle_store.get_node(smtree.root(), index_2).unwrap(); - assert_eq!(node, smtree.get_leaf(index_2.value()).unwrap().into()); + assert_eq!( + node, + smtree.get_leaf_at(&LeafIndex::::try_from(index_2).unwrap()).into() + ); // assert that is doesnt contain nodes that were not recorded let not_recorded_index = NodeIndex::new(smtree.depth(), 4).unwrap(); From 981042890ded8ab2b808147b29ccc5c2f16d85b6 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 07:59:45 -0500 Subject: [PATCH 023/117] rename get_leaf_at --- src/merkle/simple_smt/mod.rs | 4 ++-- src/merkle/simple_smt/tests.rs | 2 +- src/merkle/smt.rs | 4 ++-- src/merkle/store/tests.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 8b32d440..e3669b19 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -138,7 +138,7 @@ impl SimpleSmt { } else if index.depth() > self.depth() { Err(MerkleError::DepthTooBig(index.depth() as u64)) } else if index.depth() == self.depth() { - let leaf = self.get_leaf_at(&LeafIndex::::try_from(index)?); + let leaf = self.get_leaf(&LeafIndex::::try_from(index)?); Ok(leaf.into()) } else { @@ -318,7 +318,7 @@ impl SparseMerkleTree for SimpleSmt { self.leaves.insert(key.value(), value) } - fn get_leaf_at(&self, key: &LeafIndex) -> Word { + fn get_leaf(&self, key: &LeafIndex) -> Word { // the lookup in empty_hashes could fail only if empty_hashes were not built correctly // by the constructor as we check the depth of the lookup above. let leaf_pos = key.value(); diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 10191a54..2c9169fd 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -385,7 +385,7 @@ fn test_simplesmt_set_subtree() { }; assert_eq!(tree.root(), k); - assert_eq!(tree.get_leaf_at(&LeafIndex::::new(4).unwrap()), c); + assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()), c); assert_eq!(tree.get_branch_node(&NodeIndex::new_unchecked(2, 2)).hash(), g); } diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index e5cd7958..c0e13a28 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -69,7 +69,7 @@ pub trait SparseMerkleTree { return value; } - let leaf = self.get_leaf_at(&key); + let leaf = self.get_leaf(&key); let node_index = { let leaf_index: LeafIndex = key.into(); leaf_index.into() @@ -123,7 +123,7 @@ pub trait SparseMerkleTree { fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option; /// Returns the leaf at the specified index. - fn get_leaf_at(&self, key: &Self::Key) -> Self::Leaf; + fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index a195d37b..271e6b90 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -925,7 +925,7 @@ fn test_recorder() { let node = merkle_store.get_node(smtree.root(), index_2).unwrap(); assert_eq!( node, - smtree.get_leaf_at(&LeafIndex::::try_from(index_2).unwrap()).into() + smtree.get_leaf(&LeafIndex::::try_from(index_2).unwrap()).into() ); // assert that is doesnt contain nodes that were not recorded From 0db21a4824647e97b87dbb1cc1e6eecdaa0f7a71 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:09:47 -0500 Subject: [PATCH 024/117] remove get_branch_node --- src/merkle/simple_smt/mod.rs | 17 +++++++---------- src/merkle/simple_smt/tests.rs | 2 +- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index e3669b19..280d5a33 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -142,7 +142,7 @@ impl SimpleSmt { Ok(leaf.into()) } else { - Ok(self.get_branch_node(&index).hash()) + Ok(self.get_inner_node(index).hash()) } } @@ -262,7 +262,7 @@ impl SimpleSmt { for _ in 0..index.depth() { let is_right = index.is_value_odd(); index.move_up(); - let InnerNode { left, right } = self.get_branch_node(&index); + let InnerNode { left, right } = self.get_inner_node(index); let (left, right) = if is_right { (left, value) } else { (value, right) }; self.insert_branch_node(index, left, right); value = Rpo256::merge(&[left, right]); @@ -278,13 +278,6 @@ impl SimpleSmt { self.leaves.insert(key, node) } - fn get_branch_node(&self, index: &NodeIndex) -> InnerNode { - self.branches.get(index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); - InnerNode { left: *node, right: *node } - }) - } - fn insert_branch_node(&mut self, index: NodeIndex, left: RpoDigest, right: RpoDigest) { let branch = InnerNode { left, right }; self.branches.insert(index, branch); @@ -305,7 +298,11 @@ impl SparseMerkleTree for SimpleSmt { } fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - self.get_branch_node(&index) + self.branches.get(&index).cloned().unwrap_or_else(|| { + let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); + + InnerNode { left: *node, right: *node } + }) } fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 2c9169fd..5a0c2a9b 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -386,7 +386,7 @@ fn test_simplesmt_set_subtree() { assert_eq!(tree.root(), k); assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()), c); - assert_eq!(tree.get_branch_node(&NodeIndex::new_unchecked(2, 2)).hash(), g); + assert_eq!(tree.get_inner_node(NodeIndex::new_unchecked(2, 2)).hash(), g); } /// Ensures that an invalid input node index into `set_subtree()` incurs no mutation of the tree From 9e08ccddeeff30c6be6f019eec55147820ca908b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:12:27 -0500 Subject: [PATCH 025/117] remove insert_branch_node --- src/merkle/simple_smt/mod.rs | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 280d5a33..4e98574d 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -29,7 +29,7 @@ pub const EMPTY_VALUE: Word = super::EMPTY_WORD; pub struct SimpleSmt { root: RpoDigest, leaves: BTreeMap, - branches: BTreeMap, + inner_nodes: BTreeMap, } impl SimpleSmt { @@ -55,7 +55,7 @@ impl SimpleSmt { Ok(Self { root, leaves: BTreeMap::new(), - branches: BTreeMap::new(), + inner_nodes: BTreeMap::new(), }) } @@ -156,7 +156,7 @@ impl SimpleSmt { /// Returns an iterator over the inner nodes of this Merkle tree. pub fn inner_nodes(&self) -> impl Iterator + '_ { - self.branches.values().map(|e| InnerNodeInfo { + self.inner_nodes.values().map(|e| InnerNodeInfo { value: e.hash(), left: e.left, right: e.right, @@ -229,7 +229,7 @@ impl SimpleSmt { // add subtree's branch nodes (which includes the root) // -------------- - for (branch_idx, branch_node) in subtree.branches { + for (branch_idx, branch_node) in subtree.inner_nodes { let new_branch_idx = { let new_depth = subtree_root_insertion_depth + branch_idx.depth(); let new_value = subtree_insertion_index * 2_u64.pow(branch_idx.depth().into()) @@ -238,7 +238,7 @@ impl SimpleSmt { NodeIndex::new(new_depth, new_value).expect("index guaranteed to be valid") }; - self.branches.insert(new_branch_idx, branch_node); + self.inner_nodes.insert(new_branch_idx, branch_node); } // recompute nodes starting from subtree root @@ -264,7 +264,7 @@ impl SimpleSmt { index.move_up(); let InnerNode { left, right } = self.get_inner_node(index); let (left, right) = if is_right { (left, value) } else { (value, right) }; - self.insert_branch_node(index, left, right); + self.insert_inner_node(index, InnerNode { left, right }); value = Rpo256::merge(&[left, right]); } self.root = value; @@ -277,11 +277,6 @@ impl SimpleSmt { fn insert_leaf_node(&mut self, key: u64, node: Word) -> Option { self.leaves.insert(key, node) } - - fn insert_branch_node(&mut self, index: NodeIndex, left: RpoDigest, right: RpoDigest) { - let branch = InnerNode { left, right }; - self.branches.insert(index, branch); - } } impl SparseMerkleTree for SimpleSmt { @@ -298,7 +293,7 @@ impl SparseMerkleTree for SimpleSmt { } fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - self.branches.get(&index).cloned().unwrap_or_else(|| { + self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); InnerNode { left: *node, right: *node } @@ -306,9 +301,7 @@ impl SparseMerkleTree for SimpleSmt { } fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { - let InnerNode { left, right } = inner_node; - - self.insert_branch_node(index, left, right) + self.inner_nodes.insert(index, inner_node); } fn insert_leaf_node(&mut self, key: LeafIndex, value: Word) -> Option { From 47a34f8f347cc9af2ad0c0dfea1c5a49354288ee Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:14:33 -0500 Subject: [PATCH 026/117] remove duplicate recompute_nodes_from_index_to_root --- src/merkle/simple_smt/mod.rs | 21 +-------------------- src/merkle/simple_smt/tests.rs | 3 ++- 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 4e98574d..7154360e 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,6 @@ use super::{ BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerkleTreeDelta, NodeIndex, Rpo256, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, + MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, }; #[cfg(test)] @@ -251,25 +251,6 @@ impl SimpleSmt { // HELPER METHODS // -------------------------------------------------------------------------------------------- - /// Recomputes the branch nodes (including the root) from `index` all the way to the root. - /// `node_hash_at_index` is the hash of the node stored at index. - fn recompute_nodes_from_index_to_root( - &mut self, - mut index: NodeIndex, - node_hash_at_index: RpoDigest, - ) { - let mut value = node_hash_at_index; - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = self.get_inner_node(index); - let (left, right) = if is_right { (left, value) } else { (value, right) }; - self.insert_inner_node(index, InnerNode { left, right }); - value = Rpo256::merge(&[left, right]); - } - self.root = value; - } - fn get_leaf_node(&self, key: u64) -> Option { self.leaves.get(&key).copied() } diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 5a0c2a9b..123389d7 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -1,8 +1,9 @@ use super::{ super::{InnerNodeInfo, MerkleError, MerkleTree, RpoDigest, SimpleSmt, EMPTY_WORD}, - NodeIndex, Rpo256, + NodeIndex, }; use crate::{ + hash::rpo::Rpo256, merkle::{ digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex, SparseMerkleTree, }, From dcd8e262ea0f982206fdd604ea83c042f7466cb1 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:18:01 -0500 Subject: [PATCH 027/117] remove private get_leaf_node --- src/merkle/simple_smt/mod.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 7154360e..9df721c3 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -251,10 +251,6 @@ impl SimpleSmt { // HELPER METHODS // -------------------------------------------------------------------------------------------- - fn get_leaf_node(&self, key: u64) -> Option { - self.leaves.get(&key).copied() - } - fn insert_leaf_node(&mut self, key: u64, node: Word) -> Option { self.leaves.insert(key, node) } @@ -294,8 +290,8 @@ impl SparseMerkleTree for SimpleSmt { // by the constructor as we check the depth of the lookup above. let leaf_pos = key.value(); - match self.get_leaf_node(leaf_pos) { - Some(word) => word, + match self.leaves.get(&leaf_pos) { + Some(word) => *word, None => Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), } } From 79ffcd8857a5c7d7987a3392fbaffc08471170e1 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:21:26 -0500 Subject: [PATCH 028/117] remove trivial helper --- src/merkle/simple_smt/mod.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 9df721c3..b5b58299 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -176,7 +176,7 @@ impl SimpleSmt { // validate the index before modifying the structure let idx = NodeIndex::new(self.depth(), index)?; - let old_value = self.insert_leaf_node(index, value).unwrap_or(EMPTY_VALUE); + let old_value = self.leaves.insert(index, value).unwrap_or(EMPTY_VALUE); // if the old value and new value are the same, there is nothing to update if value == old_value { @@ -224,7 +224,7 @@ impl SimpleSmt { let new_leaf_idx = leaf_index_shift + subtree_leaf_idx; debug_assert!(new_leaf_idx < 2_u64.pow(self.depth().into())); - self.insert_leaf_node(new_leaf_idx, *leaf_value); + self.leaves.insert(new_leaf_idx, *leaf_value); } // add subtree's branch nodes (which includes the root) @@ -247,13 +247,6 @@ impl SimpleSmt { Ok(self.root) } - - // HELPER METHODS - // -------------------------------------------------------------------------------------------- - - fn insert_leaf_node(&mut self, key: u64, node: Word) -> Option { - self.leaves.insert(key, node) - } } impl SparseMerkleTree for SimpleSmt { From 2c6e38d66d9bcaaafc4525cc38459951d5556c3b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:35:28 -0500 Subject: [PATCH 029/117] remove extra `root()` method --- src/merkle/delta.rs | 91 +++++++++++++++++------------------- src/merkle/simple_smt/mod.rs | 7 +-- 2 files changed, 44 insertions(+), 54 deletions(-) diff --git a/src/merkle/delta.rs b/src/merkle/delta.rs index 4de94750..1c0e4f41 100644 --- a/src/merkle/delta.rs +++ b/src/merkle/delta.rs @@ -25,7 +25,6 @@ pub struct MerkleStoreDelta(pub Vec<(RpoDigest, MerkleTreeDelta)>); /// - depth: the depth of the merkle tree. /// - cleared_slots: indexes of slots where values were set to [ZERO; 4]. /// - updated_slots: index-value pairs of slots where values were set to non [ZERO; 4] values. -#[cfg(not(test))] #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct MerkleTreeDelta { @@ -105,52 +104,48 @@ pub fn merkle_tree_delta>( }) } -// INTERNALS -// -------------------------------------------------------------------------------------------- -#[cfg(test)] -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct MerkleTreeDelta { - pub depth: u8, - pub cleared_slots: Vec, - pub updated_slots: Vec<(u64, Word)>, -} - -// MERKLE DELTA +// TESTS // ================================================================================================ -#[test] -fn test_compute_merkle_delta() { - let entries = vec![ - (10, [ZERO, ONE, Felt::new(2), Felt::new(3)]), - (15, [Felt::new(4), Felt::new(5), Felt::new(6), Felt::new(7)]), - (20, [Felt::new(8), Felt::new(9), Felt::new(10), Felt::new(11)]), - (31, [Felt::new(12), Felt::new(13), Felt::new(14), Felt::new(15)]), - ]; - let simple_smt = SimpleSmt::<30>::with_leaves(entries.clone()).unwrap(); - let mut store: MerkleStore = (&simple_smt).into(); - let root = simple_smt.root(); - - // add a new node - let new_value = [Felt::new(16), Felt::new(17), Felt::new(18), Felt::new(19)]; - let new_index = NodeIndex::new(simple_smt.depth(), 32).unwrap(); - let root = store.set_node(root, new_index, new_value.into()).unwrap().root; - - // update an existing node - let update_value = [Felt::new(20), Felt::new(21), Felt::new(22), Felt::new(23)]; - let update_idx = NodeIndex::new(simple_smt.depth(), entries[0].0).unwrap(); - let root = store.set_node(root, update_idx, update_value.into()).unwrap().root; - - // remove a node - let remove_idx = NodeIndex::new(simple_smt.depth(), entries[1].0).unwrap(); - let root = store.set_node(root, remove_idx, EMPTY_WORD.into()).unwrap().root; - - let merkle_delta = - merkle_tree_delta(simple_smt.root(), root, simple_smt.depth(), &store).unwrap(); - let expected_merkle_delta = MerkleTreeDelta { - depth: simple_smt.depth(), - cleared_slots: vec![remove_idx.value()], - updated_slots: vec![(update_idx.value(), update_value), (new_index.value(), new_value)], - }; - - assert_eq!(merkle_delta, expected_merkle_delta); + +#[cfg(test)] +mod tests { + use super::*; + use crate::merkle::SparseMerkleTree; + + #[test] + fn test_compute_merkle_delta() { + let entries = vec![ + (10, [ZERO, ONE, Felt::new(2), Felt::new(3)]), + (15, [Felt::new(4), Felt::new(5), Felt::new(6), Felt::new(7)]), + (20, [Felt::new(8), Felt::new(9), Felt::new(10), Felt::new(11)]), + (31, [Felt::new(12), Felt::new(13), Felt::new(14), Felt::new(15)]), + ]; + let simple_smt = SimpleSmt::<30>::with_leaves(entries.clone()).unwrap(); + let mut store: MerkleStore = (&simple_smt).into(); + let root = simple_smt.root(); + + // add a new node + let new_value = [Felt::new(16), Felt::new(17), Felt::new(18), Felt::new(19)]; + let new_index = NodeIndex::new(simple_smt.depth(), 32).unwrap(); + let root = store.set_node(root, new_index, new_value.into()).unwrap().root; + + // update an existing node + let update_value = [Felt::new(20), Felt::new(21), Felt::new(22), Felt::new(23)]; + let update_idx = NodeIndex::new(simple_smt.depth(), entries[0].0).unwrap(); + let root = store.set_node(root, update_idx, update_value.into()).unwrap().root; + + // remove a node + let remove_idx = NodeIndex::new(simple_smt.depth(), entries[1].0).unwrap(); + let root = store.set_node(root, remove_idx, EMPTY_WORD.into()).unwrap().root; + + let merkle_delta = + merkle_tree_delta(simple_smt.root(), root, simple_smt.depth(), &store).unwrap(); + let expected_merkle_delta = MerkleTreeDelta { + depth: simple_smt.depth(), + cleared_slots: vec![remove_idx.value()], + updated_slots: vec![(update_idx.value(), update_value), (new_index.value(), new_value)], + }; + + assert_eq!(merkle_delta, expected_merkle_delta); + } } diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index b5b58299..cad3beb7 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -117,11 +117,6 @@ impl SimpleSmt { // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- - /// Returns the root of this Merkle tree. - pub const fn root(&self) -> RpoDigest { - self.root - } - /// Returns the depth of this Merkle tree. pub const fn depth(&self) -> u8 { DEPTH @@ -255,7 +250,7 @@ impl SparseMerkleTree for SimpleSmt { type Leaf = Word; fn root(&self) -> RpoDigest { - self.root() + self.root } fn set_root(&mut self, root: RpoDigest) { From b661312d4614c1d253fe126a1c284acfd11f8e9d Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:38:38 -0500 Subject: [PATCH 030/117] add vscode gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 1f178797..d4a844e3 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ Cargo.lock # Generated by cmake cmake-build-* + +# VS Code +.vscode/ From 740a31607d93027a244e0227b5e805604547a2ca Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:49:50 -0500 Subject: [PATCH 031/117] remove old `get_leaf()` --- benches/smt.rs | 2 +- benches/store.rs | 7 +++- src/merkle/simple_smt/mod.rs | 28 ++-------------- src/merkle/simple_smt/tests.rs | 60 +++++----------------------------- 4 files changed, 18 insertions(+), 79 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index 828019b2..2a2f2b46 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -34,7 +34,7 @@ fn smt_rpo(c: &mut Criterion) { &(key, leaf), |b, (key, leaf)| { b.iter(|| { - tree.update_leaf(black_box(*key), black_box(*leaf)).unwrap(); + tree.update_leaf_at(black_box(LeafIndex::::new(*key).unwrap()), black_box(*leaf)); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index 38e6282e..9ee7e727 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -449,7 +449,12 @@ fn update_leaf_simplesmt(c: &mut Criterion) { group.bench_function(BenchmarkId::new("SimpleSMT", size), |b| { b.iter_batched( || (rand_value::() % size_u64, random_word()), - |(index, value)| black_box(smt.update_leaf(index, value)), + |(index, value)| { + black_box(smt.update_leaf_at( + LeafIndex::::new(index).unwrap(), + value, + )) + }, BatchSize::SmallInput, ) }); diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index cad3beb7..5aa0357e 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -88,7 +88,7 @@ impl SimpleSmt { return Err(MerkleError::InvalidNumEntries(max_num_entries)); } - let old_value = tree.update_leaf(key, value)?; + let old_value = tree.update_leaf_at(LeafIndex::::new(key)?, value); if old_value != EMPTY_VALUE || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex(key)); @@ -161,28 +161,6 @@ impl SimpleSmt { // STATE MUTATORS // -------------------------------------------------------------------------------------------- - /// Updates value of the leaf at the specified index returning the old leaf value. - /// - /// This also recomputes all hashes between the leaf and the root, updating the root itself. - /// - /// # Errors - /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}. - pub fn update_leaf(&mut self, index: u64, value: Word) -> Result { - // validate the index before modifying the structure - let idx = NodeIndex::new(self.depth(), index)?; - - let old_value = self.leaves.insert(index, value).unwrap_or(EMPTY_VALUE); - - // if the old value and new value are the same, there is nothing to update - if value == old_value { - return Ok(value); - } - - self.recompute_nodes_from_index_to_root(idx, RpoDigest::from(value)); - - Ok(old_value) - } - /// Inserts a subtree at the specified index. The depth at which the subtree is inserted is /// computed as `self.depth() - subtree.depth()`. /// @@ -304,11 +282,11 @@ impl TryApplyDiff for SimpleSmt { } for slot in diff.cleared_slots() { - self.update_leaf(*slot, EMPTY_VALUE)?; + self.update_leaf_at(LeafIndex::::new(*slot)?, EMPTY_VALUE); } for (slot, value) in diff.updated_slots() { - self.update_leaf(*slot, *value)?; + self.update_leaf_at(LeafIndex::::new(*slot)?, *value); } Ok(()) diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 123389d7..65c1667b 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -44,14 +44,15 @@ fn build_empty_tree() { #[test] fn build_sparse_tree() { - let mut smt = SimpleSmt::<3>::new().unwrap(); + const DEPTH: u8 = 3; + let mut smt = SimpleSmt::::new().unwrap(); let mut values = ZERO_VALUES8.to_vec(); // insert single value let key = 6; let new_node = int_to_leaf(7); values[key as usize] = new_node; - let old_value = smt.update_leaf(key, new_node).expect("Failed to update leaf"); + let old_value = smt.update_leaf_at(LeafIndex::::new(key).unwrap(), new_node); let mt2 = MerkleTree::new(values.clone()).unwrap(); assert_eq!(mt2.root(), smt.root()); assert_eq!( @@ -64,7 +65,7 @@ fn build_sparse_tree() { let key = 2; let new_node = int_to_leaf(3); values[key as usize] = new_node; - let old_value = smt.update_leaf(key, new_node).expect("Failed to update leaf"); + let old_value = smt.update_leaf_at(LeafIndex::::new(key).unwrap(), new_node); let mt3 = MerkleTree::new(values).unwrap(); assert_eq!(mt3.root(), smt.root()); assert_eq!( @@ -144,8 +145,9 @@ fn test_inner_node_iterator() -> Result<(), MerkleError> { #[test] fn update_leaf() { + const DEPTH: u8 = 3; let mut tree = - SimpleSmt::<3>::with_leaves(KEYS8.into_iter().zip(digests_to_words(&VALUES8))).unwrap(); + SimpleSmt::::with_leaves(KEYS8.into_iter().zip(digests_to_words(&VALUES8))).unwrap(); // update one value let key = 3; @@ -154,7 +156,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf(key as u64, new_node).unwrap(); + let old_leaf = tree.update_leaf_at(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); @@ -164,7 +166,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf(key as u64, new_node).unwrap(); + let old_leaf = tree.update_leaf_at(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); } @@ -250,52 +252,6 @@ fn with_no_duplicates_empty_node() { assert!(smt.is_ok()); } -#[test] -fn test_simplesmt_update_nonexisting_leaf_with_zero() { - // TESTING WITH EMPTY WORD - // -------------------------------------------------------------------------------------------- - - // Depth 1 has 2 leaf. Position is 0-indexed, position 2 doesn't exist. - let mut smt = SimpleSmt::<1>::new().unwrap(); - let result = smt.update_leaf(2, EMPTY_WORD); - assert!(!smt.leaves.contains_key(&2)); - assert!(result.is_err()); - - // Depth 2 has 4 leaves. Position is 0-indexed, position 4 doesn't exist. - let mut smt = SimpleSmt::<2>::new().unwrap(); - let result = smt.update_leaf(4, EMPTY_WORD); - assert!(!smt.leaves.contains_key(&4)); - assert!(result.is_err()); - - // Depth 3 has 8 leaves. Position is 0-indexed, position 8 doesn't exist. - let mut smt = SimpleSmt::<3>::new().unwrap(); - let result = smt.update_leaf(8, EMPTY_WORD); - assert!(!smt.leaves.contains_key(&8)); - assert!(result.is_err()); - - // TESTING WITH A VALUE - // -------------------------------------------------------------------------------------------- - let value = int_to_node(1); - - // Depth 1 has 2 leaves. Position is 0-indexed, position 1 doesn't exist. - let mut smt = SimpleSmt::<1>::new().unwrap(); - let result = smt.update_leaf(2, *value); - assert!(!smt.leaves.contains_key(&2)); - assert!(result.is_err()); - - // Depth 2 has 4 leaves. Position is 0-indexed, position 2 doesn't exist. - let mut smt = SimpleSmt::<2>::new().unwrap(); - let result = smt.update_leaf(4, *value); - assert!(!smt.leaves.contains_key(&4)); - assert!(result.is_err()); - - // Depth 3 has 8 leaves. Position is 0-indexed, position 4 doesn't exist. - let mut smt = SimpleSmt::<3>::new().unwrap(); - let result = smt.update_leaf(8, *value); - assert!(!smt.leaves.contains_key(&8)); - assert!(result.is_err()); -} - #[test] fn test_simplesmt_with_leaves_nonexisting_leaf() { // TESTING WITH EMPTY WORD From 66f7330ae4a6290442884b0515332267a69ec221 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:50:13 -0500 Subject: [PATCH 032/117] Rename `update_leaf_at` --- benches/smt.rs | 2 +- benches/store.rs | 2 +- src/merkle/simple_smt/mod.rs | 6 +++--- src/merkle/simple_smt/tests.rs | 8 ++++---- src/merkle/smt.rs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index 2a2f2b46..dec4a0e3 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -34,7 +34,7 @@ fn smt_rpo(c: &mut Criterion) { &(key, leaf), |b, (key, leaf)| { b.iter(|| { - tree.update_leaf_at(black_box(LeafIndex::::new(*key).unwrap()), black_box(*leaf)); + tree.update_leaf(black_box(LeafIndex::::new(*key).unwrap()), black_box(*leaf)); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index 9ee7e727..8856d670 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -450,7 +450,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { b.iter_batched( || (rand_value::() % size_u64, random_word()), |(index, value)| { - black_box(smt.update_leaf_at( + black_box(smt.update_leaf( LeafIndex::::new(index).unwrap(), value, )) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 5aa0357e..b85ae63c 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -88,7 +88,7 @@ impl SimpleSmt { return Err(MerkleError::InvalidNumEntries(max_num_entries)); } - let old_value = tree.update_leaf_at(LeafIndex::::new(key)?, value); + let old_value = tree.update_leaf(LeafIndex::::new(key)?, value); if old_value != EMPTY_VALUE || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex(key)); @@ -282,11 +282,11 @@ impl TryApplyDiff for SimpleSmt { } for slot in diff.cleared_slots() { - self.update_leaf_at(LeafIndex::::new(*slot)?, EMPTY_VALUE); + self.update_leaf(LeafIndex::::new(*slot)?, EMPTY_VALUE); } for (slot, value) in diff.updated_slots() { - self.update_leaf_at(LeafIndex::::new(*slot)?, *value); + self.update_leaf(LeafIndex::::new(*slot)?, *value); } Ok(()) diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 65c1667b..96de6d7d 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -52,7 +52,7 @@ fn build_sparse_tree() { let key = 6; let new_node = int_to_leaf(7); values[key as usize] = new_node; - let old_value = smt.update_leaf_at(LeafIndex::::new(key).unwrap(), new_node); + let old_value = smt.update_leaf(LeafIndex::::new(key).unwrap(), new_node); let mt2 = MerkleTree::new(values.clone()).unwrap(); assert_eq!(mt2.root(), smt.root()); assert_eq!( @@ -65,7 +65,7 @@ fn build_sparse_tree() { let key = 2; let new_node = int_to_leaf(3); values[key as usize] = new_node; - let old_value = smt.update_leaf_at(LeafIndex::::new(key).unwrap(), new_node); + let old_value = smt.update_leaf(LeafIndex::::new(key).unwrap(), new_node); let mt3 = MerkleTree::new(values).unwrap(); assert_eq!(mt3.root(), smt.root()); assert_eq!( @@ -156,7 +156,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf_at(LeafIndex::::new(key as u64).unwrap(), new_node); + let old_leaf = tree.update_leaf(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); @@ -166,7 +166,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf_at(LeafIndex::::new(key as u64).unwrap(), new_node); + let old_leaf = tree.update_leaf(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); } diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index c0e13a28..321fe122 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -61,7 +61,7 @@ pub trait SparseMerkleTree { /// Updates value of the leaf at the specified index returning the old leaf value. /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. - fn update_leaf_at(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { + fn update_leaf(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { let old_value = self.insert_leaf_node(key.clone(), value.clone()).unwrap_or_default(); // if the old value and new value are the same, there is nothing to update From 20a623a2babc064c5db6e5cd898b185804815572 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 08:51:37 -0500 Subject: [PATCH 033/117] add comment --- src/merkle/simple_smt/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index b85ae63c..a1c74783 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -263,6 +263,7 @@ impl SparseMerkleTree for SimpleSmt { } fn hash_leaf(leaf: &Word) -> RpoDigest { + // `SimpleSmt` takes the leaf value itself as the hash leaf.into() } } From fba5577f6c401da950cc1e2aa81cb99529daf9e9 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 09:25:04 -0500 Subject: [PATCH 034/117] import `Vec` for `no_std` --- src/merkle/simple_smt/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index 96de6d7d..c9ac88d1 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -7,6 +7,7 @@ use crate::{ merkle::{ digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex, SparseMerkleTree, }, + utils::collections::Vec, Word, }; From 11e44c8fb9282e2b1632300b88eb84a698e10645 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 09:26:25 -0500 Subject: [PATCH 035/117] fix docstring --- src/merkle/smt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 321fe122..226651bf 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -12,7 +12,7 @@ use super::{MerkleError, MerklePath, NodeIndex, Vec}; /// /// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed /// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's -/// value was not explicitly updated, then its value is the default value. Typically, the vast +/// value was not explicitly set, then its value is the default value. Typically, the vast /// majority of leaves will store the default value (hence it is "sparse"), and therefore the /// internal representation of the tree will only keep track of the leaves that have a different /// value from the default. From f7872c1d9a217729c8d0dc030e338789f850ed13 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 09:28:08 -0500 Subject: [PATCH 036/117] nightly fmt --- benches/store.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/benches/store.rs b/benches/store.rs index 8856d670..aca86e09 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -450,10 +450,12 @@ fn update_leaf_simplesmt(c: &mut Criterion) { b.iter_batched( || (rand_value::() % size_u64, random_word()), |(index, value)| { - black_box(smt.update_leaf( - LeafIndex::::new(index).unwrap(), - value, - )) + black_box( + smt.update_leaf( + LeafIndex::::new(index).unwrap(), + value, + ), + ) }, BatchSize::SmallInput, ) From b13ef60a47511d3f58b8fcc08b6409b4f642c5a4 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 09:38:07 -0500 Subject: [PATCH 037/117] new_smt scaffolding --- src/merkle/mod.rs | 3 ++ src/merkle/new_smt/mod.rs | 65 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 src/merkle/new_smt/mod.rs diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 64a11d4b..76fcfd1a 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -30,6 +30,9 @@ pub use simple_smt::{SimpleSmt, SIMPLE_SMT_MAX_DEPTH, SIMPLE_SMT_MIN_DEPTH}; mod smt; pub use smt::{InnerNode, LeafIndex, SparseMerkleTree}; +mod new_smt; +pub use new_smt::{NewSmt, NewSmtKey, NewSmtLeaf, NEW_SMT_DEPTH}; + mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs new file mode 100644 index 00000000..186941d2 --- /dev/null +++ b/src/merkle/new_smt/mod.rs @@ -0,0 +1,65 @@ +use super::{BTreeMap, InnerNode, LeafIndex, NodeIndex, RpoDigest, SparseMerkleTree, Word}; + +pub const NEW_SMT_DEPTH: u8 = 64; + +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub struct NewSmt { + root: RpoDigest, + leaves: BTreeMap, + inner_nodes: BTreeMap, +} + +impl SparseMerkleTree for NewSmt { + type Key = NewSmtKey; + + type Value = Word; + + type Leaf = NewSmtLeaf; + + fn root(&self) -> RpoDigest { + todo!() + } + + fn set_root(&mut self, root: RpoDigest) { + todo!() + } + + fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + todo!() + } + + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { + todo!() + } + + fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option { + todo!() + } + + fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { + todo!() + } + + fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { + todo!() + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum NewSmtLeaf { + Single((u64, Word)), + Multiple(Vec<(u64, Word)>), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NewSmtKey { + word: Word, +} + +impl From for LeafIndex { + fn from(key: NewSmtKey) -> Self { + let most_significant_felt = key.word[0]; + Self::new_max_depth(most_significant_felt.inner()) + } +} From c1902d701431ac29794cf3597b17eedb67b87aa7 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 10:00:38 -0500 Subject: [PATCH 038/117] implement `hash_leaf()` --- src/merkle/new_smt/mod.rs | 41 +++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 186941d2..ca092eab 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -1,4 +1,9 @@ -use super::{BTreeMap, InnerNode, LeafIndex, NodeIndex, RpoDigest, SparseMerkleTree, Word}; +use crate::hash::rpo::Rpo256; +use crate::Felt; + +use super::{ + BTreeMap, EmptySubtreeRoots, InnerNode, LeafIndex, NodeIndex, RpoDigest, SparseMerkleTree, Word, +}; pub const NEW_SMT_DEPTH: u8 = 64; @@ -18,19 +23,23 @@ impl SparseMerkleTree for NewSmt { type Leaf = NewSmtLeaf; fn root(&self) -> RpoDigest { - todo!() + self.root } fn set_root(&mut self, root: RpoDigest) { - todo!() + self.root = root; } fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - todo!() + self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { + let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); + + InnerNode { left: *node, right: *node } + }) } fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { - todo!() + self.inner_nodes.insert(index, inner_node); } fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option { @@ -42,7 +51,7 @@ impl SparseMerkleTree for NewSmt { } fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { - todo!() + leaf.hash() } } @@ -52,6 +61,26 @@ pub enum NewSmtLeaf { Multiple(Vec<(u64, Word)>), } +impl NewSmtLeaf { + pub fn hash(&self) -> RpoDigest { + fn tuple_to_elements((key, value): &(u64, Word)) -> impl Iterator + '_ { + let key_ele = Felt::from(*key); + let value_eles = value.iter().copied(); + + std::iter::once(key_ele).chain(value_eles) + } + + let elements: Vec = match self { + NewSmtLeaf::Single(tuple) => tuple_to_elements(tuple).collect(), + NewSmtLeaf::Multiple(tuples) => { + tuples.into_iter().flat_map(tuple_to_elements).collect() + } + }; + + Rpo256::hash_elements(&elements) + } +} + #[derive(Clone, Copy, Debug, PartialEq)] pub struct NewSmtKey { word: Word, From dfc3f77c19cda90277434611cf24f92ad725c30b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 10:09:17 -0500 Subject: [PATCH 039/117] implement `get_leaf()` --- src/merkle/new_smt/mod.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index ca092eab..a540dc54 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -11,7 +11,7 @@ pub const NEW_SMT_DEPTH: u8 = 64; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct NewSmt { root: RpoDigest, - leaves: BTreeMap, + leaves: BTreeMap, inner_nodes: BTreeMap, } @@ -47,7 +47,15 @@ impl SparseMerkleTree for NewSmt { } fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { - todo!() + let leaf_pos = LeafIndex::::from(*key).value(); + + match self.leaves.get(&leaf_pos) { + Some(leaf) => leaf.clone(), + None => NewSmtLeaf::Single(( + leaf_pos, + Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), + )), + } } fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { @@ -55,7 +63,8 @@ impl SparseMerkleTree for NewSmt { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum NewSmtLeaf { Single((u64, Word)), Multiple(Vec<(u64, Word)>), From 561271b654444ab61175320298d3acfd2a0f7644 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 11:18:53 -0500 Subject: [PATCH 040/117] use `Vec` --- src/merkle/new_smt/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index a540dc54..cdda8196 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -1,4 +1,5 @@ use crate::hash::rpo::Rpo256; +use crate::utils::collections::Vec; use crate::Felt; use super::{ From a07e42c47e727d3fe71f3e3d8e281cb025a63c86 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 11:43:59 -0500 Subject: [PATCH 041/117] insert_leaf_node scaffold --- src/merkle/new_smt/mod.rs | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index cdda8196..cbfebe3c 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -44,7 +44,18 @@ impl SparseMerkleTree for NewSmt { } fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option { - todo!() + let leaf_index: LeafIndex = key.into(); + match self.leaves.get(&leaf_index.value()) { + Some(leaf) => match leaf { + NewSmtLeaf::Single(kv_pair) => todo!(), + NewSmtLeaf::Multiple(_) => todo!(), + }, + None => { + self.leaves.insert(leaf_index.value(), NewSmtLeaf::Single((key.clone(), value))); + + Some(Self::Value::default()) + } + } } fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { @@ -53,7 +64,7 @@ impl SparseMerkleTree for NewSmt { match self.leaves.get(&leaf_pos) { Some(leaf) => leaf.clone(), None => NewSmtLeaf::Single(( - leaf_pos, + key.clone(), Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), )), } @@ -67,31 +78,30 @@ impl SparseMerkleTree for NewSmt { #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum NewSmtLeaf { - Single((u64, Word)), - Multiple(Vec<(u64, Word)>), + Single((NewSmtKey, Word)), + Multiple(Vec<(NewSmtKey, Word)>), } impl NewSmtLeaf { pub fn hash(&self) -> RpoDigest { - fn tuple_to_elements((key, value): &(u64, Word)) -> impl Iterator + '_ { - let key_ele = Felt::from(*key); - let value_eles = value.iter().copied(); + fn kv_to_elements((key, value): &(NewSmtKey, Word)) -> impl Iterator + '_ { + let key_elements = key.word.iter().copied(); + let value_elements = value.iter().copied(); - std::iter::once(key_ele).chain(value_eles) + key_elements.chain(value_elements) } let elements: Vec = match self { - NewSmtLeaf::Single(tuple) => tuple_to_elements(tuple).collect(), - NewSmtLeaf::Multiple(tuples) => { - tuples.into_iter().flat_map(tuple_to_elements).collect() - } + NewSmtLeaf::Single(kv) => kv_to_elements(kv).collect(), + NewSmtLeaf::Multiple(kvs) => kvs.into_iter().flat_map(kv_to_elements).collect(), }; Rpo256::hash_elements(&elements) } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct NewSmtKey { word: Word, } From bec00e03caaec05e89689c05b06a09a553afe4d0 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 12:03:47 -0500 Subject: [PATCH 042/117] insert on leaf with single element --- src/merkle/new_smt/mod.rs | 53 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index cbfebe3c..8cd96301 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -1,3 +1,7 @@ +use core::cmp::Ordering; + +use winter_math::StarkField; + use crate::hash::rpo::Rpo256; use crate::utils::collections::Vec; use crate::Felt; @@ -45,9 +49,25 @@ impl SparseMerkleTree for NewSmt { fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option { let leaf_index: LeafIndex = key.into(); - match self.leaves.get(&leaf_index.value()) { + match self.leaves.get_mut(&leaf_index.value()) { Some(leaf) => match leaf { - NewSmtLeaf::Single(kv_pair) => todo!(), + NewSmtLeaf::Single(kv_pair) => { + // if the key is already in this entry, update the value and return + if kv_pair.0 == key { + let old_value = kv_pair.1; + kv_pair.1 = value; + return Some(old_value); + } + + // transform the entry into a list entry, and make sure the key-value pairs + // are sorted by key + let mut pairs = vec![*kv_pair, (key, value)]; + pairs.sort_by(|pair_1, pair_2| cmp_pairs(*pair_1, *pair_2)); + + self.leaves.insert(leaf_index.value(), NewSmtLeaf::Multiple(pairs)); + + None + } NewSmtLeaf::Multiple(_) => todo!(), }, None => { @@ -112,3 +132,32 @@ impl From for LeafIndex { Self::new_max_depth(most_significant_felt.inner()) } } + +// HELPER FUNCTIONS +// ================================================================================================ + +/// Compares two (key-value) pairs, ordered first by keys, then values. +/// +/// Both keys and values are compared element-by-element using their integer representations +/// starting with the most significant element. +fn cmp_pairs((key_1, value_1): (NewSmtKey, Word), (key_2, value_2): (NewSmtKey, Word)) -> Ordering { + let key_order = cmp_words(key_1.word, key_2.word); + + if key_order != Ordering::Equal { + key_order + } else { + cmp_words(value_1, value_2) + } +} + +fn cmp_words(w1: Word, w2: Word) -> Ordering { + for (v1, v2) in w1.iter().zip(w2.iter()).rev() { + let v1 = v1.as_int(); + let v2 = v2.as_int(); + if v1 != v2 { + return v1.cmp(&v2); + } + } + + Ordering::Equal +} From fb49a699b156116ec49b8fb756221d0486563f3e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 12:10:48 -0500 Subject: [PATCH 043/117] cmp just keys --- src/merkle/new_smt/mod.rs | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 8cd96301..fe9d764c 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -62,7 +62,7 @@ impl SparseMerkleTree for NewSmt { // transform the entry into a list entry, and make sure the key-value pairs // are sorted by key let mut pairs = vec![*kv_pair, (key, value)]; - pairs.sort_by(|pair_1, pair_2| cmp_pairs(*pair_1, *pair_2)); + pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); self.leaves.insert(leaf_index.value(), NewSmtLeaf::Multiple(pairs)); @@ -136,22 +136,10 @@ impl From for LeafIndex { // HELPER FUNCTIONS // ================================================================================================ -/// Compares two (key-value) pairs, ordered first by keys, then values. -/// -/// Both keys and values are compared element-by-element using their integer representations -/// starting with the most significant element. -fn cmp_pairs((key_1, value_1): (NewSmtKey, Word), (key_2, value_2): (NewSmtKey, Word)) -> Ordering { - let key_order = cmp_words(key_1.word, key_2.word); - - if key_order != Ordering::Equal { - key_order - } else { - cmp_words(value_1, value_2) - } -} - -fn cmp_words(w1: Word, w2: Word) -> Ordering { - for (v1, v2) in w1.iter().zip(w2.iter()).rev() { +/// Compares two keys, compared element-by-element using their integer representations starting with +/// the most significant element. +fn cmp_keys(key_1: NewSmtKey, key_2: NewSmtKey) -> Ordering { + for (v1, v2) in key_1.word.iter().zip(key_2.word.iter()).rev() { let v1 = v1.as_int(); let v2 = v2.as_int(); if v1 != v2 { From c07d8143f7a5b417a79d3a855536782f45111510 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 12:14:35 -0500 Subject: [PATCH 044/117] insert leaf: multiple --- src/merkle/new_smt/mod.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index fe9d764c..36d35e61 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -68,10 +68,24 @@ impl SparseMerkleTree for NewSmt { None } - NewSmtLeaf::Multiple(_) => todo!(), + NewSmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + kv_pairs[pos].1 = value; + + Some(old_value) + } + Err(pos) => { + kv_pairs.insert(pos, (key, value)); + + None + } + } + } }, None => { - self.leaves.insert(leaf_index.value(), NewSmtLeaf::Single((key.clone(), value))); + self.leaves.insert(leaf_index.value(), NewSmtLeaf::Single((key, value))); Some(Self::Value::default()) } @@ -84,7 +98,7 @@ impl SparseMerkleTree for NewSmt { match self.leaves.get(&leaf_pos) { Some(leaf) => leaf.clone(), None => NewSmtLeaf::Single(( - key.clone(), + *key, Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), )), } @@ -113,7 +127,7 @@ impl NewSmtLeaf { let elements: Vec = match self { NewSmtLeaf::Single(kv) => kv_to_elements(kv).collect(), - NewSmtLeaf::Multiple(kvs) => kvs.into_iter().flat_map(kv_to_elements).collect(), + NewSmtLeaf::Multiple(kvs) => kvs.iter().flat_map(kv_to_elements).collect(), }; Rpo256::hash_elements(&elements) From ac96e5ee9c1e86b7b6e124fe41770b743ab29051 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 12:15:57 -0500 Subject: [PATCH 045/117] reorg file --- src/merkle/new_smt/mod.rs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 36d35e61..16eebaf6 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -109,6 +109,25 @@ impl SparseMerkleTree for NewSmt { } } +// KEY +// ================================================================================================ + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub struct NewSmtKey { + word: Word, +} + +impl From for LeafIndex { + fn from(key: NewSmtKey) -> Self { + let most_significant_felt = key.word[0]; + Self::new_max_depth(most_significant_felt.inner()) + } +} + +// LEAF +// ================================================================================================ + #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum NewSmtLeaf { @@ -134,19 +153,6 @@ impl NewSmtLeaf { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct NewSmtKey { - word: Word, -} - -impl From for LeafIndex { - fn from(key: NewSmtKey) -> Self { - let most_significant_felt = key.word[0]; - Self::new_max_depth(most_significant_felt.inner()) - } -} - // HELPER FUNCTIONS // ================================================================================================ From 9425ea08351642988ba64200c754d2e0e3a71f4c Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 12:19:53 -0500 Subject: [PATCH 046/117] no_std vec --- src/merkle/new_smt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 16eebaf6..ce7fc3be 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -3,7 +3,7 @@ use core::cmp::Ordering; use winter_math::StarkField; use crate::hash::rpo::Rpo256; -use crate::utils::collections::Vec; +use crate::utils::{collections::Vec, vec}; use crate::Felt; use super::{ From 53fe96d1ffe1c49545eb8d33c5eb4a71b4e3eaef Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 13:54:19 -0500 Subject: [PATCH 047/117] rename `SMT_MAX_DEPTH` --- benches/store.rs | 22 +++++++++++----------- src/merkle/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 4 ++-- src/merkle/store/tests.rs | 14 +++++++------- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/benches/store.rs b/benches/store.rs index aca86e09..1cca8bfc 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -1,7 +1,7 @@ use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use miden_crypto::merkle::{ DefaultMerkleStore as MerkleStore, LeafIndex, MerkleTree, NodeIndex, SimpleSmt, - SparseMerkleTree, SIMPLE_SMT_MAX_DEPTH, + SparseMerkleTree, SMT_MAX_DEPTH, }; use miden_crypto::Word; use miden_crypto::{hash::rpo::RpoDigest, Felt}; @@ -31,7 +31,7 @@ fn random_index(range: u64, depth: u8) -> NodeIndex { fn get_empty_leaf_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_empty_leaf_simplesmt"); - const DEPTH: u8 = SIMPLE_SMT_MAX_DEPTH; + const DEPTH: u8 = SMT_MAX_DEPTH; let size = u64::MAX; // both SMT and the store are pre-populated with empty hashes, accessing these values is what is @@ -107,7 +107,7 @@ fn get_leaf_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); @@ -135,7 +135,7 @@ fn get_leaf_simplesmt(c: &mut Criterion) { fn get_node_of_empty_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_node_of_empty_simplesmt"); - const DEPTH: u8 = SIMPLE_SMT_MAX_DEPTH; + const DEPTH: u8 = SMT_MAX_DEPTH; // both SMT and the store are pre-populated with the empty hashes, accessing the internal nodes // of these values is what is being benchmarked here, so no values are inserted into the @@ -215,7 +215,7 @@ fn get_node_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let half_depth = smt.depth() / 2; @@ -289,7 +289,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); + let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); @@ -300,7 +300,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { || random_index(size_u64, depth), |index| { black_box(smt.get_leaf_path( - LeafIndex::::new(index.value()).unwrap(), + LeafIndex::::new(index.value()).unwrap(), )) }, BatchSize::SmallInput, @@ -359,7 +359,7 @@ fn new(c: &mut Criterion) { .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>() }, - |l| black_box(SimpleSmt::::with_leaves(l)), + |l| black_box(SimpleSmt::::with_leaves(l)), BatchSize::SmallInput, ) }); @@ -374,7 +374,7 @@ fn new(c: &mut Criterion) { .collect::>() }, |l| { - let smt = SimpleSmt::::with_leaves(l).unwrap(); + let smt = SimpleSmt::::with_leaves(l).unwrap(); black_box(MerkleStore::from(&smt)); }, BatchSize::SmallInput, @@ -440,7 +440,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { .enumerate() .map(|(c, v)| (c.try_into().unwrap(), v.into())) .collect::>(); - let mut smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); + let mut smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let mut store = MerkleStore::from(&smt); let depth = smt.depth(); let root = smt.root(); @@ -452,7 +452,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { |(index, value)| { black_box( smt.update_leaf( - LeafIndex::::new(index).unwrap(), + LeafIndex::::new(index).unwrap(), value, ), ) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 76fcfd1a..4f63bb12 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,7 +25,7 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; -pub use simple_smt::{SimpleSmt, SIMPLE_SMT_MAX_DEPTH, SIMPLE_SMT_MIN_DEPTH}; +pub use simple_smt::{SimpleSmt, SMT_MAX_DEPTH, SIMPLE_SMT_MIN_DEPTH}; mod smt; pub use smt::{InnerNode, LeafIndex, SparseMerkleTree}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index a1c74783..f4ba7a9a 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -13,7 +13,7 @@ mod tests; pub const SIMPLE_SMT_MIN_DEPTH: u8 = 1; /// Maximum supported depth. -pub const SIMPLE_SMT_MAX_DEPTH: u8 = 64; +pub const SMT_MAX_DEPTH: u8 = 64; /// Value of an empty leaf. pub const EMPTY_VALUE: Word = super::EMPTY_WORD; @@ -46,7 +46,7 @@ impl SimpleSmt { // validate the range of the depth. if DEPTH < SIMPLE_SMT_MIN_DEPTH { return Err(MerkleError::DepthTooSmall(DEPTH)); - } else if SIMPLE_SMT_MAX_DEPTH < DEPTH { + } else if SMT_MAX_DEPTH < DEPTH { return Err(MerkleError::DepthTooBig(DEPTH as u64)); } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 271e6b90..60ff5b47 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -5,7 +5,7 @@ use super::{ use crate::{ merkle::{ digests_to_words, int_to_leaf, int_to_node, LeafIndex, MerkleTree, SimpleSmt, - SparseMerkleTree, SIMPLE_SMT_MAX_DEPTH, + SparseMerkleTree, SMT_MAX_DEPTH, }, Felt, Word, ONE, WORD_SIZE, ZERO, }; @@ -232,7 +232,7 @@ fn test_add_sparse_merkle_tree_one_level() -> Result<(), MerkleError> { #[test] fn test_sparse_merkle_tree() -> Result<(), MerkleError> { - let smt = SimpleSmt::::with_leaves( + let smt = SimpleSmt::::with_leaves( KEYS4.into_iter().zip(digests_to_words(&VALUES4)), ) .unwrap(); @@ -303,7 +303,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(0).unwrap()), + smt.get_leaf_path(LeafIndex::::new(0).unwrap()), result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -314,7 +314,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(1).unwrap()), + smt.get_leaf_path(LeafIndex::::new(1).unwrap()), result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -325,7 +325,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(2).unwrap()), + smt.get_leaf_path(LeafIndex::::new(2).unwrap()), result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -336,7 +336,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(3).unwrap()), + smt.get_leaf_path(LeafIndex::::new(3).unwrap()), result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -348,7 +348,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(4).unwrap()), + smt.get_leaf_path(LeafIndex::::new(4).unwrap()), result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); From ae04c792419582a706ce10a1fb1f4bc8e8fbb43f Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 13:56:31 -0500 Subject: [PATCH 048/117] use `SMT_MAX_DEPTH` --- src/merkle/mod.rs | 4 ++-- src/merkle/simple_smt/mod.rs | 5 +---- src/merkle/smt.rs | 12 +++++++++--- src/merkle/store/tests.rs | 7 +++---- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 4f63bb12..363ab7b1 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,10 +25,10 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; -pub use simple_smt::{SimpleSmt, SMT_MAX_DEPTH, SIMPLE_SMT_MIN_DEPTH}; +pub use simple_smt::{SimpleSmt, SIMPLE_SMT_MIN_DEPTH}; mod smt; -pub use smt::{InnerNode, LeafIndex, SparseMerkleTree}; +pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH}; mod new_smt; pub use new_smt::{NewSmt, NewSmtKey, NewSmtLeaf, NEW_SMT_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index f4ba7a9a..dbd0e011 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,6 @@ use super::{ BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, + MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, smt::SMT_MAX_DEPTH, }; #[cfg(test)] @@ -12,9 +12,6 @@ mod tests; /// Minimum supported depth. pub const SIMPLE_SMT_MIN_DEPTH: u8 = 1; -/// Maximum supported depth. -pub const SMT_MAX_DEPTH: u8 = 64; - /// Value of an empty leaf. pub const EMPTY_VALUE: Word = super::EMPTY_WORD; diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 226651bf..a24b5b90 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -5,6 +5,12 @@ use crate::{ use super::{MerkleError, MerklePath, NodeIndex, Vec}; +// CONSTANTS +// ================================================================================================ + +/// Maximum supported depth. +pub const SMT_MAX_DEPTH: u8 = 64; + // SPARSE MERKLE TREE // ================================================================================================ @@ -165,10 +171,10 @@ impl LeafIndex { } } -impl LeafIndex<64> { +impl LeafIndex { pub fn new_max_depth(value: u64) -> Self { LeafIndex { - index: NodeIndex::new_unchecked(64, value), + index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value), } } } @@ -194,7 +200,7 @@ impl TryFrom for LeafIndex { } } -impl From for LeafIndex<64> { +impl From for LeafIndex { fn from(value: Word) -> Self { Self::new_max_depth(value[0].inner()) } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 60ff5b47..5c89fc14 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -232,10 +232,9 @@ fn test_add_sparse_merkle_tree_one_level() -> Result<(), MerkleError> { #[test] fn test_sparse_merkle_tree() -> Result<(), MerkleError> { - let smt = SimpleSmt::::with_leaves( - KEYS4.into_iter().zip(digests_to_words(&VALUES4)), - ) - .unwrap(); + let smt = + SimpleSmt::::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))) + .unwrap(); let store = MerkleStore::from(&smt); From b9b9d1ea8dec01a2a435066d9e433870c9fe2bd8 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:08:08 -0500 Subject: [PATCH 049/117] `SMT_MIN_DEPTH` --- src/merkle/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 363ab7b1..ae0596fe 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,7 +25,7 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; -pub use simple_smt::{SimpleSmt, SIMPLE_SMT_MIN_DEPTH}; +pub use simple_smt::{SimpleSmt, SMT_MIN_DEPTH}; mod smt; pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index dbd0e011..75aa7fe8 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -10,7 +10,7 @@ mod tests; // ================================================================================================ /// Minimum supported depth. -pub const SIMPLE_SMT_MIN_DEPTH: u8 = 1; +pub const SMT_MIN_DEPTH: u8 = 1; /// Value of an empty leaf. pub const EMPTY_VALUE: Word = super::EMPTY_WORD; @@ -41,7 +41,7 @@ impl SimpleSmt { /// Returns an error if the depth is 0 or is greater than 64. pub fn new() -> Result { // validate the range of the depth. - if DEPTH < SIMPLE_SMT_MIN_DEPTH { + if DEPTH < SMT_MIN_DEPTH { return Err(MerkleError::DepthTooSmall(DEPTH)); } else if SMT_MAX_DEPTH < DEPTH { return Err(MerkleError::DepthTooBig(DEPTH as u64)); From 9fb9a20a272b0cc39d9bb6895457a10d6de5d964 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:11:21 -0500 Subject: [PATCH 050/117] Enforce `SMT_MIN_DEPTH` in `LeafIndex` --- src/merkle/mod.rs | 4 ++-- src/merkle/simple_smt/mod.rs | 5 +---- src/merkle/smt.rs | 18 +++++++++++++----- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index ae0596fe..11119698 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,10 +25,10 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; -pub use simple_smt::{SimpleSmt, SMT_MIN_DEPTH}; +pub use simple_smt::SimpleSmt; mod smt; -pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH}; +pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod new_smt; pub use new_smt::{NewSmt, NewSmtKey, NewSmtLeaf, NEW_SMT_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 75aa7fe8..03e1f472 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,6 @@ use super::{ BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, smt::SMT_MAX_DEPTH, + MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, smt::SMT_MAX_DEPTH, SMT_MIN_DEPTH, }; #[cfg(test)] @@ -9,9 +9,6 @@ mod tests; // CONSTANTS // ================================================================================================ -/// Minimum supported depth. -pub const SMT_MIN_DEPTH: u8 = 1; - /// Value of an empty leaf. pub const EMPTY_VALUE: Word = super::EMPTY_WORD; diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index a24b5b90..545d9369 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -8,6 +8,9 @@ use super::{MerkleError, MerklePath, NodeIndex, Vec}; // CONSTANTS // ================================================================================================ +/// Minimum supported depth. +pub const SMT_MIN_DEPTH: u8 = 1; + /// Maximum supported depth. pub const SMT_MAX_DEPTH: u8 = 64; @@ -18,13 +21,14 @@ pub const SMT_MAX_DEPTH: u8 = 64; /// /// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed /// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's -/// value was not explicitly set, then its value is the default value. Typically, the vast -/// majority of leaves will store the default value (hence it is "sparse"), and therefore the -/// internal representation of the tree will only keep track of the leaves that have a different -/// value from the default. +/// value was not explicitly set, then its value is the default value. Typically, the vast majority +/// of leaves will store the default value (hence it is "sparse"), and therefore the internal +/// representation of the tree will only keep track of the leaves that have a different value from +/// the default. /// /// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the -/// longer its proofs are - of exactly `log(depth)` size. +/// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a +/// tree is just a single value, and is probably a programming mistake. /// /// Every key value maps to one leaf. If there are as many keys as there are leaves, then /// [Self::Leaf] should be the same type as [Self::Value], as is the case with @@ -163,6 +167,10 @@ pub struct LeafIndex { impl LeafIndex { pub fn new(value: u64) -> Result { + if DEPTH < SMT_MIN_DEPTH { + return Err(MerkleError::DepthTooSmall(DEPTH)); + } + Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? }) } From 82c84bb126b3fc2d4999e522a583cada7a1d0b66 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:13:12 -0500 Subject: [PATCH 051/117] nightly fmt --- benches/store.rs | 11 ++++------- src/merkle/simple_smt/mod.rs | 5 +++-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/benches/store.rs b/benches/store.rs index 1cca8bfc..1981540e 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -299,9 +299,9 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { b.iter_batched( || random_index(size_u64, depth), |index| { - black_box(smt.get_leaf_path( - LeafIndex::::new(index.value()).unwrap(), - )) + black_box( + smt.get_leaf_path(LeafIndex::::new(index.value()).unwrap()), + ) }, BatchSize::SmallInput, ) @@ -451,10 +451,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { || (rand_value::() % size_u64, random_word()), |(index, value)| { black_box( - smt.update_leaf( - LeafIndex::::new(index).unwrap(), - value, - ), + smt.update_leaf(LeafIndex::::new(index).unwrap(), value), ) }, BatchSize::SmallInput, diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 03e1f472..e6a83443 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,6 +1,7 @@ use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, smt::SMT_MAX_DEPTH, SMT_MIN_DEPTH, + smt::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, + MerkleError, MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, + Word, SMT_MIN_DEPTH, }; #[cfg(test)] From 0d1fa1cd150f54b059ce8e4f07339cee9124b51e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:15:23 -0500 Subject: [PATCH 052/117] `as_int` instead of `inner()` --- src/merkle/new_smt/mod.rs | 2 +- src/merkle/smt.rs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index ce7fc3be..c50ce95a 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -121,7 +121,7 @@ pub struct NewSmtKey { impl From for LeafIndex { fn from(key: NewSmtKey) -> Self { let most_significant_felt = key.word[0]; - Self::new_max_depth(most_significant_felt.inner()) + Self::new_max_depth(most_significant_felt.as_int()) } } diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index 545d9369..aa349748 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -1,3 +1,5 @@ +use winter_math::StarkField; + use crate::{ hash::rpo::{Rpo256, RpoDigest}, Word, @@ -210,6 +212,6 @@ impl TryFrom for LeafIndex { impl From for LeafIndex { fn from(value: Word) -> Self { - Self::new_max_depth(value[0].inner()) + Self::new_max_depth(value[0].as_int()) } } From feabd0f0c5a546ce51c6f4f97f0c8cd6d3bac66a Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:23:36 -0500 Subject: [PATCH 053/117] rename `insert_leaf_node` --- src/merkle/new_smt/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/smt.rs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index c50ce95a..8e143956 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -47,7 +47,7 @@ impl SparseMerkleTree for NewSmt { self.inner_nodes.insert(index, inner_node); } - fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option { + fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { let leaf_index: LeafIndex = key.into(); match self.leaves.get_mut(&leaf_index.value()) { Some(leaf) => match leaf { diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index e6a83443..a09ad33d 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -242,7 +242,7 @@ impl SparseMerkleTree for SimpleSmt { self.inner_nodes.insert(index, inner_node); } - fn insert_leaf_node(&mut self, key: LeafIndex, value: Word) -> Option { + fn insert_value(&mut self, key: LeafIndex, value: Word) -> Option { self.leaves.insert(key.value(), value) } diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index aa349748..c9e67b2f 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -74,7 +74,7 @@ pub trait SparseMerkleTree { /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. fn update_leaf(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { - let old_value = self.insert_leaf_node(key.clone(), value.clone()).unwrap_or_default(); + let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or_default(); // if the old value and new value are the same, there is nothing to update if value == old_value { @@ -132,7 +132,7 @@ pub trait SparseMerkleTree { fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode); /// Inserts a leaf node, and returns the value at the key if already exists - fn insert_leaf_node(&mut self, key: Self::Key, value: Self::Value) -> Option; + fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option; /// Returns the leaf at the specified index. fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; From 8c6ae9f0bbdaaf60fe0be21e30d549520b2f53ec Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:33:06 -0500 Subject: [PATCH 054/117] add tests mod --- src/merkle/new_smt/mod.rs | 9 +++++++++ src/merkle/new_smt/tests.rs | 0 2 files changed, 9 insertions(+) create mode 100644 src/merkle/new_smt/tests.rs diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 8e143956..d7ea41ba 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -10,8 +10,17 @@ use super::{ BTreeMap, EmptySubtreeRoots, InnerNode, LeafIndex, NodeIndex, RpoDigest, SparseMerkleTree, Word, }; +#[cfg(test)] +mod tests; + +// CONSTANTS +// ================================================================================================ + pub const NEW_SMT_DEPTH: u8 = 64; +// SMT +// ================================================================================================ + #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct NewSmt { diff --git a/src/merkle/new_smt/tests.rs b/src/merkle/new_smt/tests.rs new file mode 100644 index 00000000..e69de29b From 6bf5f0794a707eb2f239ac5364dddda5a67594b2 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:40:42 -0500 Subject: [PATCH 055/117] most signifcant felt: last felt of word --- src/merkle/smt.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/merkle/smt.rs b/src/merkle/smt.rs index c9e67b2f..5b72c2ca 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/smt.rs @@ -212,6 +212,7 @@ impl TryFrom for LeafIndex { impl From for LeafIndex { fn from(value: Word) -> Self { - Self::new_max_depth(value[0].as_int()) + // We use the most significant `Felt` of a `Word` as the leaf index. + Self::new_max_depth(value[3].as_int()) } } From 0ae34647caaff9679f6baddd7bc85482b00bf71b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:47:01 -0500 Subject: [PATCH 056/117] fix comments --- src/merkle/simple_smt/mod.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index a09ad33d..9eaabd91 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -31,12 +31,12 @@ impl SimpleSmt { // CONSTRUCTORS // -------------------------------------------------------------------------------------------- - /// Returns a new [SimpleSmt] instantiated with the specified depth. + /// Returns a new [SimpleSmt]. /// /// All leaves in the returned tree are set to [ZERO; 4]. /// /// # Errors - /// Returns an error if the depth is 0 or is greater than 64. + /// Returns an error if [DEPTH] is 0 or is greater than 64. pub fn new() -> Result { // validate the range of the depth. if DEPTH < SMT_MIN_DEPTH { @@ -54,8 +54,7 @@ impl SimpleSmt { }) } - /// Returns a new [SimpleSmt] instantiated with the specified depth and with leaves - /// set as specified by the provided entries. + /// Returns a new [SimpleSmt] instantiated with leaves set as specified by the provided entries. /// /// All leaves omitted from the entries list are set to [ZERO; 4]. /// From 6c9b87d758650759a2a3d4face34f6bdc5da983b Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 14:49:27 -0500 Subject: [PATCH 057/117] `NewSmt` constructor --- src/merkle/new_smt/mod.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index d7ea41ba..2443a005 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -29,6 +29,21 @@ pub struct NewSmt { inner_nodes: BTreeMap, } +impl NewSmt { + /// Returns a new [NewSmt]. + /// + /// All leaves in the returned tree are set to [ZERO; 4]. + pub fn new() -> Self { + let root = *EmptySubtreeRoots::entry(NEW_SMT_DEPTH, 0); + + Self { + root, + leaves: BTreeMap::new(), + inner_nodes: BTreeMap::new(), + } + } +} + impl SparseMerkleTree for NewSmt { type Key = NewSmtKey; From 795ff9649f38ecfc63442f71b9709b4dbbd29759 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 11 Jan 2024 15:14:23 -0500 Subject: [PATCH 058/117] fix comment --- src/merkle/new_smt/mod.rs | 81 ++++++++++++++++++++++++++++++++++++- src/merkle/new_smt/tests.rs | 1 + 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 2443a005..fa6a1e43 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -4,10 +4,11 @@ use winter_math::StarkField; use crate::hash::rpo::Rpo256; use crate::utils::{collections::Vec, vec}; -use crate::Felt; +use crate::{Felt, EMPTY_WORD}; use super::{ - BTreeMap, EmptySubtreeRoots, InnerNode, LeafIndex, NodeIndex, RpoDigest, SparseMerkleTree, Word, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, LeafIndex, MerkleError, NodeIndex, RpoDigest, + SparseMerkleTree, Word, }; #[cfg(test)] @@ -42,6 +43,48 @@ impl NewSmt { inner_nodes: BTreeMap::new(), } } + + /// Returns a new [SimpleSmt] instantiated with leaves set as specified by the provided entries. + /// + /// All leaves omitted from the entries list are set to [ZERO; 4]. + /// + /// # Errors + /// Returns an error if: + /// - The number of entries exceeds 2^63 entries. + /// - The provided entries contain multiple values for the same key. + pub fn with_entries( + entries: impl IntoIterator, + ) -> Result { + // create an empty tree + let mut tree = Self::new(); + + // compute the max number of entries. We use an upper bound of depth 63 because we consider + // passing in a vector of size 2^64 infeasible. + let max_num_entries = 2_usize.pow(tree.depth().min(63).into()); + + // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so + // entries with the empty value need additional tracking. + let mut key_set_to_zero = BTreeSet::new(); + + for (idx, (key, value)) in entries.into_iter().enumerate() { + if idx >= max_num_entries { + return Err(MerkleError::InvalidNumEntries(max_num_entries)); + } + + let old_value = tree.update_leaf(key, value); + + if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { + return Err(MerkleError::DuplicateValuesForIndex( + LeafIndex::::from(key).value(), + )); + } + + if value == EMPTY_WORD { + key_set_to_zero.insert(key); + }; + } + Ok(tree) + } } impl SparseMerkleTree for NewSmt { @@ -133,6 +176,12 @@ impl SparseMerkleTree for NewSmt { } } +impl Default for NewSmt { + fn default() -> Self { + Self::new() + } +} + // KEY // ================================================================================================ @@ -149,6 +198,34 @@ impl From for LeafIndex { } } +impl Ord for NewSmtKey { + fn cmp(&self, other: &Self) -> Ordering { + // Note that the indices are reversed. This is because a `Word` is treated as little-endian + // (i.e. most significant Felt is at index 3). In comparing integer arrays, we want to + // compare the most significant felts first, and so on until the least signifcant felt. + let self_word: [u64; 4] = [ + self.word[3].as_int(), + self.word[2].as_int(), + self.word[1].as_int(), + self.word[0].as_int(), + ]; + let other_word: [u64; 4] = [ + other.word[3].as_int(), + other.word[2].as_int(), + other.word[1].as_int(), + other.word[0].as_int(), + ]; + + self_word.cmp(&other_word) + } +} + +impl PartialOrd for NewSmtKey { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + // LEAF // ================================================================================================ diff --git a/src/merkle/new_smt/tests.rs b/src/merkle/new_smt/tests.rs index e69de29b..8b137891 100644 --- a/src/merkle/new_smt/tests.rs +++ b/src/merkle/new_smt/tests.rs @@ -0,0 +1 @@ + From ff996390c938c513d796bd58fa9ef05e0e060d8f Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:26:23 -0500 Subject: [PATCH 059/117] Remove `max_num_entries` in `NewSmt` --- src/merkle/new_smt/mod.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index fa6a1e43..3216ea3f 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -58,19 +58,11 @@ impl NewSmt { // create an empty tree let mut tree = Self::new(); - // compute the max number of entries. We use an upper bound of depth 63 because we consider - // passing in a vector of size 2^64 infeasible. - let max_num_entries = 2_usize.pow(tree.depth().min(63).into()); - // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so // entries with the empty value need additional tracking. let mut key_set_to_zero = BTreeSet::new(); - for (idx, (key, value)) in entries.into_iter().enumerate() { - if idx >= max_num_entries { - return Err(MerkleError::InvalidNumEntries(max_num_entries)); - } - + for (key, value) in entries { let old_value = tree.update_leaf(key, value); if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { From 9514ecf26856880a5e20e85f2091a2ae8f20a089 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:33:23 -0500 Subject: [PATCH 060/117] Rename `NewSmt` to `Smt` --- src/merkle/mod.rs | 2 +- src/merkle/new_smt/mod.rs | 62 +++++++++++++++++++-------------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 11119698..51d1ca90 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -31,7 +31,7 @@ mod smt; pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod new_smt; -pub use new_smt::{NewSmt, NewSmtKey, NewSmtLeaf, NEW_SMT_DEPTH}; +pub use new_smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/new_smt/mod.rs index 3216ea3f..9f407068 100644 --- a/src/merkle/new_smt/mod.rs +++ b/src/merkle/new_smt/mod.rs @@ -17,25 +17,25 @@ mod tests; // CONSTANTS // ================================================================================================ -pub const NEW_SMT_DEPTH: u8 = 64; +pub const SMT_DEPTH: u8 = 64; // SMT // ================================================================================================ #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct NewSmt { +pub struct Smt { root: RpoDigest, - leaves: BTreeMap, + leaves: BTreeMap, inner_nodes: BTreeMap, } -impl NewSmt { +impl Smt { /// Returns a new [NewSmt]. /// /// All leaves in the returned tree are set to [ZERO; 4]. pub fn new() -> Self { - let root = *EmptySubtreeRoots::entry(NEW_SMT_DEPTH, 0); + let root = *EmptySubtreeRoots::entry(SMT_DEPTH, 0); Self { root, @@ -53,7 +53,7 @@ impl NewSmt { /// - The number of entries exceeds 2^63 entries. /// - The provided entries contain multiple values for the same key. pub fn with_entries( - entries: impl IntoIterator, + entries: impl IntoIterator, ) -> Result { // create an empty tree let mut tree = Self::new(); @@ -67,7 +67,7 @@ impl NewSmt { if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex( - LeafIndex::::from(key).value(), + LeafIndex::::from(key).value(), )); } @@ -79,12 +79,12 @@ impl NewSmt { } } -impl SparseMerkleTree for NewSmt { - type Key = NewSmtKey; +impl SparseMerkleTree for Smt { + type Key = SmtKey; type Value = Word; - type Leaf = NewSmtLeaf; + type Leaf = SmtLeaf; fn root(&self) -> RpoDigest { self.root @@ -107,10 +107,10 @@ impl SparseMerkleTree for NewSmt { } fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { - let leaf_index: LeafIndex = key.into(); + let leaf_index: LeafIndex = key.into(); match self.leaves.get_mut(&leaf_index.value()) { Some(leaf) => match leaf { - NewSmtLeaf::Single(kv_pair) => { + SmtLeaf::Single(kv_pair) => { // if the key is already in this entry, update the value and return if kv_pair.0 == key { let old_value = kv_pair.1; @@ -123,11 +123,11 @@ impl SparseMerkleTree for NewSmt { let mut pairs = vec![*kv_pair, (key, value)]; pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); - self.leaves.insert(leaf_index.value(), NewSmtLeaf::Multiple(pairs)); + self.leaves.insert(leaf_index.value(), SmtLeaf::Multiple(pairs)); None } - NewSmtLeaf::Multiple(kv_pairs) => { + SmtLeaf::Multiple(kv_pairs) => { match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { Ok(pos) => { let old_value = kv_pairs[pos].1; @@ -144,7 +144,7 @@ impl SparseMerkleTree for NewSmt { } }, None => { - self.leaves.insert(leaf_index.value(), NewSmtLeaf::Single((key, value))); + self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); Some(Self::Value::default()) } @@ -152,11 +152,11 @@ impl SparseMerkleTree for NewSmt { } fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { - let leaf_pos = LeafIndex::::from(*key).value(); + let leaf_pos = LeafIndex::::from(*key).value(); match self.leaves.get(&leaf_pos) { Some(leaf) => leaf.clone(), - None => NewSmtLeaf::Single(( + None => SmtLeaf::Single(( *key, Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), )), @@ -168,7 +168,7 @@ impl SparseMerkleTree for NewSmt { } } -impl Default for NewSmt { +impl Default for Smt { fn default() -> Self { Self::new() } @@ -179,18 +179,18 @@ impl Default for NewSmt { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct NewSmtKey { +pub struct SmtKey { word: Word, } -impl From for LeafIndex { - fn from(key: NewSmtKey) -> Self { +impl From for LeafIndex { + fn from(key: SmtKey) -> Self { let most_significant_felt = key.word[0]; Self::new_max_depth(most_significant_felt.as_int()) } } -impl Ord for NewSmtKey { +impl Ord for SmtKey { fn cmp(&self, other: &Self) -> Ordering { // Note that the indices are reversed. This is because a `Word` is treated as little-endian // (i.e. most significant Felt is at index 3). In comparing integer arrays, we want to @@ -212,7 +212,7 @@ impl Ord for NewSmtKey { } } -impl PartialOrd for NewSmtKey { +impl PartialOrd for SmtKey { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } @@ -223,14 +223,14 @@ impl PartialOrd for NewSmtKey { #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub enum NewSmtLeaf { - Single((NewSmtKey, Word)), - Multiple(Vec<(NewSmtKey, Word)>), +pub enum SmtLeaf { + Single((SmtKey, Word)), + Multiple(Vec<(SmtKey, Word)>), } -impl NewSmtLeaf { +impl SmtLeaf { pub fn hash(&self) -> RpoDigest { - fn kv_to_elements((key, value): &(NewSmtKey, Word)) -> impl Iterator + '_ { + fn kv_to_elements((key, value): &(SmtKey, Word)) -> impl Iterator + '_ { let key_elements = key.word.iter().copied(); let value_elements = value.iter().copied(); @@ -238,8 +238,8 @@ impl NewSmtLeaf { } let elements: Vec = match self { - NewSmtLeaf::Single(kv) => kv_to_elements(kv).collect(), - NewSmtLeaf::Multiple(kvs) => kvs.iter().flat_map(kv_to_elements).collect(), + SmtLeaf::Single(kv) => kv_to_elements(kv).collect(), + SmtLeaf::Multiple(kvs) => kvs.iter().flat_map(kv_to_elements).collect(), }; Rpo256::hash_elements(&elements) @@ -251,7 +251,7 @@ impl NewSmtLeaf { /// Compares two keys, compared element-by-element using their integer representations starting with /// the most significant element. -fn cmp_keys(key_1: NewSmtKey, key_2: NewSmtKey) -> Ordering { +fn cmp_keys(key_1: SmtKey, key_2: SmtKey) -> Ordering { for (v1, v2) in key_1.word.iter().zip(key_2.word.iter()).rev() { let v1 = v1.as_int(); let v2 = v2.as_int(); From e7899b32a0dacae70990021d5bc9e687e376a027 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:40:10 -0500 Subject: [PATCH 061/117] Rename `NewSmt` to `Smt`, and `smt` module to `sparse_merkle_tree` --- src/merkle/mod.rs | 8 ++++---- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/{new_smt => smt}/mod.rs | 0 src/merkle/{new_smt => smt}/tests.rs | 0 src/merkle/{smt.rs => sparse_merkle_tree.rs} | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) rename src/merkle/{new_smt => smt}/mod.rs (100%) rename src/merkle/{new_smt => smt}/tests.rs (100%) rename src/merkle/{smt.rs => sparse_merkle_tree.rs} (98%) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 51d1ca90..93a97002 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -27,11 +27,11 @@ pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; pub use simple_smt::SimpleSmt; -mod smt; -pub use smt::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; +mod sparse_merkle_tree; +pub use sparse_merkle_tree::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; -mod new_smt; -pub use new_smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; +mod smt; +pub use smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 9eaabd91..8168736c 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,5 +1,5 @@ use super::{ - smt::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, + sparse_merkle_tree::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, Word, SMT_MIN_DEPTH, }; diff --git a/src/merkle/new_smt/mod.rs b/src/merkle/smt/mod.rs similarity index 100% rename from src/merkle/new_smt/mod.rs rename to src/merkle/smt/mod.rs diff --git a/src/merkle/new_smt/tests.rs b/src/merkle/smt/tests.rs similarity index 100% rename from src/merkle/new_smt/tests.rs rename to src/merkle/smt/tests.rs diff --git a/src/merkle/smt.rs b/src/merkle/sparse_merkle_tree.rs similarity index 98% rename from src/merkle/smt.rs rename to src/merkle/sparse_merkle_tree.rs index 5b72c2ca..baa8ba94 100644 --- a/src/merkle/smt.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -32,7 +32,7 @@ pub const SMT_MAX_DEPTH: u8 = 64; /// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a /// tree is just a single value, and is probably a programming mistake. /// -/// Every key value maps to one leaf. If there are as many keys as there are leaves, then +/// Every key maps to one leaf. If there are as many keys as there are leaves, then /// [Self::Leaf] should be the same type as [Self::Value], as is the case with /// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] /// must accomodate all keys that map to the same leaf. From a7fdaf965b2a887512302722c949529f013e7fe3 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:46:56 -0500 Subject: [PATCH 062/117] Replace `Value`'s `Default` trait bound with `EMPTY_VALUE` associated constant --- src/merkle/simple_smt/mod.rs | 10 +++++++--- src/merkle/smt/mod.rs | 4 ++-- src/merkle/sparse_merkle_tree.rs | 7 +++++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 8168736c..80e75b6b 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,7 +1,9 @@ +use crate::EMPTY_WORD; + use super::{ - sparse_merkle_tree::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, - MerkleError, MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, StoreNode, TryApplyDiff, - Word, SMT_MIN_DEPTH, + sparse_merkle_tree::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, + InnerNodeInfo, LeafIndex, MerkleError, MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, + StoreNode, TryApplyDiff, Word, SMT_MIN_DEPTH, }; #[cfg(test)] @@ -221,6 +223,8 @@ impl SparseMerkleTree for SimpleSmt { type Value = Word; type Leaf = Word; + const EMPTY_VALUE: Self::Value = EMPTY_WORD; + fn root(&self) -> RpoDigest { self.root } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 9f407068..069613b2 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -81,11 +81,11 @@ impl Smt { impl SparseMerkleTree for Smt { type Key = SmtKey; - type Value = Word; - type Leaf = SmtLeaf; + const EMPTY_VALUE: Self::Value = EMPTY_WORD; + fn root(&self) -> RpoDigest { self.root } diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index baa8ba94..9cf87035 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -42,10 +42,13 @@ pub trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly type Key: Into> + Clone; /// The type for a value - type Value: Clone + Default + PartialEq; + type Value: Clone + PartialEq; /// The type for a leaf type Leaf; + /// The default value used to compute the hash of empty leaves + const EMPTY_VALUE: Self::Value; + // PROVIDED METHODS // --------------------------------------------------------------------------------------------- @@ -74,7 +77,7 @@ pub trait SparseMerkleTree { /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. fn update_leaf(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { - let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or_default(); + let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or(Self::EMPTY_VALUE); // if the old value and new value are the same, there is nothing to update if value == old_value { From d4c51b873c4af305d5eaa0d0ade331b3fddc1298 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:47:45 -0500 Subject: [PATCH 063/117] remove `SimpleSmt`'s `EMPTY_VALUE` constant --- src/merkle/mod.rs | 4 +++- src/merkle/simple_smt/mod.rs | 12 +++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 93a97002..36b5b37f 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -28,7 +28,9 @@ mod simple_smt; pub use simple_smt::SimpleSmt; mod sparse_merkle_tree; -pub use sparse_merkle_tree::{InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; +pub use sparse_merkle_tree::{ + InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH, +}; mod smt; pub use smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 80e75b6b..056e0bb1 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -9,12 +9,6 @@ use super::{ #[cfg(test)] mod tests; -// CONSTANTS -// ================================================================================================ - -/// Value of an empty leaf. -pub const EMPTY_VALUE: Word = super::EMPTY_WORD; - // SPARSE MERKLE TREE // ================================================================================================ @@ -86,11 +80,11 @@ impl SimpleSmt { let old_value = tree.update_leaf(LeafIndex::::new(key)?, value); - if old_value != EMPTY_VALUE || key_set_to_zero.contains(&key) { + if old_value != Self::EMPTY_VALUE || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex(key)); } - if value == EMPTY_VALUE { + if value == Self::EMPTY_VALUE { key_set_to_zero.insert(key); }; } @@ -281,7 +275,7 @@ impl TryApplyDiff for SimpleSmt { } for slot in diff.cleared_slots() { - self.update_leaf(LeafIndex::::new(*slot)?, EMPTY_VALUE); + self.update_leaf(LeafIndex::::new(*slot)?, Self::EMPTY_VALUE); } for (slot, value) in diff.updated_slots() { From 7f8e17841b99b4ba161095421290c83ced7ba0a6 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:48:29 -0500 Subject: [PATCH 064/117] ABSTRACT -> PROVIDED --- src/merkle/sparse_merkle_tree.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 9cf87035..41efa563 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -119,7 +119,7 @@ pub trait SparseMerkleTree { DEPTH } - // ABSTRACT METHODS + // REQUIRED METHODS // --------------------------------------------------------------------------------------------- /// The root of the tree From e93c9a272e032b1c8570f38c08357633f70462fc Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 08:58:28 -0500 Subject: [PATCH 065/117] remove `depth()` method --- src/merkle/smt/mod.rs | 9 ++++----- src/merkle/sparse_merkle_tree.rs | 5 ----- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 069613b2..5e047f36 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -96,7 +96,7 @@ impl SparseMerkleTree for Smt { fn get_inner_node(&self, index: NodeIndex) -> InnerNode { self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); + let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); InnerNode { left: *node, right: *node } }) @@ -156,10 +156,9 @@ impl SparseMerkleTree for Smt { match self.leaves.get(&leaf_pos) { Some(leaf) => leaf.clone(), - None => SmtLeaf::Single(( - *key, - Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), - )), + None => { + SmtLeaf::Single((*key, Word::from(*EmptySubtreeRoots::entry(SMT_DEPTH, SMT_DEPTH)))) + } } } diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 41efa563..237e18af 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -114,11 +114,6 @@ pub trait SparseMerkleTree { self.set_root(value); } - /// Returns the depth of the sparse Merkle tree - fn depth(&self) -> u8 { - DEPTH - } - // REQUIRED METHODS // --------------------------------------------------------------------------------------------- From fe6a9dcf66037e0e0865c5e54568c2154e81588c Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 09:08:43 -0500 Subject: [PATCH 066/117] `SmtKey`: use `RpoDigest` internally --- src/merkle/smt/mod.rs | 38 +++++++------------------------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 5e047f36..47c19b35 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -173,13 +173,17 @@ impl Default for Smt { } } -// KEY +// SMT KEY // ================================================================================================ -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Represents a key (256 bits) for the Smt. +/// +/// The most significant `u64` determines the corresponding leaf index when inserting values into +/// the Smt. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct SmtKey { - word: Word, + word: RpoDigest, } impl From for LeafIndex { @@ -189,34 +193,6 @@ impl From for LeafIndex { } } -impl Ord for SmtKey { - fn cmp(&self, other: &Self) -> Ordering { - // Note that the indices are reversed. This is because a `Word` is treated as little-endian - // (i.e. most significant Felt is at index 3). In comparing integer arrays, we want to - // compare the most significant felts first, and so on until the least signifcant felt. - let self_word: [u64; 4] = [ - self.word[3].as_int(), - self.word[2].as_int(), - self.word[1].as_int(), - self.word[0].as_int(), - ]; - let other_word: [u64; 4] = [ - other.word[3].as_int(), - other.word[2].as_int(), - other.word[1].as_int(), - other.word[0].as_int(), - ]; - - self_word.cmp(&other_word) - } -} - -impl PartialOrd for SmtKey { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - // LEAF // ================================================================================================ From 306dad1953fd3ebb315c95fd660a97314c737306 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 09:10:06 -0500 Subject: [PATCH 067/117] add constructors to `SmtKey` --- src/merkle/smt/mod.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 47c19b35..6eb86afe 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -193,6 +193,18 @@ impl From for LeafIndex { } } +impl From for SmtKey { + fn from(digest: RpoDigest) -> Self { + Self { word: digest } + } +} + +impl From for SmtKey { + fn from(word: Word) -> Self { + Self { word: word.into() } + } +} + // LEAF // ================================================================================================ From f8e474f64c6b7e6b041cd558c014113316624a69 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 09:24:37 -0500 Subject: [PATCH 068/117] optimize `SmtLeaf::hash()` --- src/merkle/smt/mod.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 6eb86afe..32764b69 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -224,12 +224,13 @@ impl SmtLeaf { key_elements.chain(value_elements) } - let elements: Vec = match self { - SmtLeaf::Single(kv) => kv_to_elements(kv).collect(), - SmtLeaf::Multiple(kvs) => kvs.iter().flat_map(kv_to_elements).collect(), - }; - - Rpo256::hash_elements(&elements) + match self { + SmtLeaf::Single((key, value)) => Rpo256::merge(&[key.word.into(), value.into()]), + SmtLeaf::Multiple(kvs) => { + let elements: Vec = kvs.iter().flat_map(kv_to_elements).collect(); + Rpo256::hash_elements(&elements) + } + } } } From 21220a4f26b83f4434f8e099df0e2f7b84cd3806 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 09:36:09 -0500 Subject: [PATCH 069/117] impl `to_elements()` and `into_elements()` for `SmtLeaf` --- src/merkle/smt/mod.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 32764b69..5eab01ae 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -216,18 +216,25 @@ pub enum SmtLeaf { } impl SmtLeaf { - pub fn hash(&self) -> RpoDigest { - fn kv_to_elements((key, value): &(SmtKey, Word)) -> impl Iterator + '_ { - let key_elements = key.word.iter().copied(); - let value_elements = value.iter().copied(); + /// Converts a leaf to a list of field elements + pub fn to_elements(&self) -> Vec { + self.clone().into_elements() + } - key_elements.chain(value_elements) + /// Converts a leaf to a list of field elements + pub fn into_elements(self) -> Vec { + match self { + SmtLeaf::Single(kv_pair) => kv_to_elements(kv_pair).collect(), + SmtLeaf::Multiple(kv_pairs) => kv_pairs.into_iter().flat_map(kv_to_elements).collect(), } + } + /// Compute the hash of the leaf + pub fn hash(&self) -> RpoDigest { match self { - SmtLeaf::Single((key, value)) => Rpo256::merge(&[key.word.into(), value.into()]), + SmtLeaf::Single((key, value)) => Rpo256::merge(&[key.word, value.into()]), SmtLeaf::Multiple(kvs) => { - let elements: Vec = kvs.iter().flat_map(kv_to_elements).collect(); + let elements: Vec = kvs.iter().copied().flat_map(kv_to_elements).collect(); Rpo256::hash_elements(&elements) } } @@ -237,6 +244,14 @@ impl SmtLeaf { // HELPER FUNCTIONS // ================================================================================================ +/// Converts a key-value tuple to an iterator of `Felt`s +fn kv_to_elements((key, value): (SmtKey, Word)) -> impl Iterator { + let key_elements = key.word.into_iter(); + let value_elements = value.into_iter(); + + key_elements.chain(value_elements) +} + /// Compares two keys, compared element-by-element using their integer representations starting with /// the most significant element. fn cmp_keys(key_1: SmtKey, key_2: SmtKey) -> Ordering { From 8ebafed78eaade99289861c4b727b225c82004fb Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 10:59:08 -0500 Subject: [PATCH 070/117] Make `SparseMerkleTree` pub(crate) --- benches/smt.rs | 2 +- benches/store.rs | 3 +-- src/merkle/delta.rs | 1 - src/merkle/mod.rs | 6 ++---- src/merkle/simple_smt/mod.rs | 36 +++++++++++++++++++++++++++++--- src/merkle/simple_smt/tests.rs | 4 +--- src/merkle/smt/mod.rs | 34 ++++++++++++++++++++++++++++-- src/merkle/sparse_merkle_tree.rs | 2 +- src/merkle/store/tests.rs | 3 +-- 9 files changed, 72 insertions(+), 19 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index dec4a0e3..60307ab0 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -1,7 +1,7 @@ use core::mem::swap; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use miden_crypto::{ - merkle::{LeafIndex, SimpleSmt, SparseMerkleTree}, + merkle::{LeafIndex, SimpleSmt}, Felt, Word, }; use rand_utils::prng_array; diff --git a/benches/store.rs b/benches/store.rs index 1981540e..15b8f61e 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -1,7 +1,6 @@ use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use miden_crypto::merkle::{ - DefaultMerkleStore as MerkleStore, LeafIndex, MerkleTree, NodeIndex, SimpleSmt, - SparseMerkleTree, SMT_MAX_DEPTH, + DefaultMerkleStore as MerkleStore, LeafIndex, MerkleTree, NodeIndex, SimpleSmt, SMT_MAX_DEPTH, }; use miden_crypto::Word; use miden_crypto::{hash::rpo::RpoDigest, Felt}; diff --git a/src/merkle/delta.rs b/src/merkle/delta.rs index 1c0e4f41..8049fa41 100644 --- a/src/merkle/delta.rs +++ b/src/merkle/delta.rs @@ -110,7 +110,6 @@ pub fn merkle_tree_delta>( #[cfg(test)] mod tests { use super::*; - use crate::merkle::SparseMerkleTree; #[test] fn test_compute_merkle_delta() { diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 36b5b37f..83e44d75 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -27,10 +27,8 @@ pub use path::{MerklePath, RootPath, ValuePath}; mod simple_smt; pub use simple_smt::SimpleSmt; -mod sparse_merkle_tree; -pub use sparse_merkle_tree::{ - InnerNode, LeafIndex, SparseMerkleTree, SMT_MAX_DEPTH, SMT_MIN_DEPTH, -}; +pub(crate) mod sparse_merkle_tree; +pub use sparse_merkle_tree::{InnerNode, LeafIndex, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod smt; pub use smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 056e0bb1..791a212e 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,9 +1,10 @@ use crate::EMPTY_WORD; use super::{ - sparse_merkle_tree::SMT_MAX_DEPTH, BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, - InnerNodeInfo, LeafIndex, MerkleError, MerkleTreeDelta, NodeIndex, RpoDigest, SparseMerkleTree, - StoreNode, TryApplyDiff, Word, SMT_MIN_DEPTH, + sparse_merkle_tree::{SparseMerkleTree, SMT_MAX_DEPTH}, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, + MerklePath, MerkleTreeDelta, NodeIndex, RpoDigest, StoreNode, TryApplyDiff, Word, + SMT_MIN_DEPTH, }; #[cfg(test)] @@ -112,6 +113,28 @@ impl SimpleSmt { DEPTH } + /// Returns the root of the tree + pub fn root(&self) -> RpoDigest { + >::root(self) + } + + /// Returns the leaf at the specified index. + pub fn get_leaf(&self, key: &LeafIndex) -> Word { + >::get_leaf(self, key) + } + + /// Inserts an inner node at the given index + pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + >::get_inner_node(self, index) + } + + /// Returns a Merkle path from the leaf node specified by the key to the root. + /// + /// The node itself is not included in the path. + pub fn get_leaf_path(&self, key: LeafIndex) -> MerklePath { + >::get_leaf_path(self, key) + } + /// Returns a node at the specified index. /// /// # Errors @@ -151,6 +174,13 @@ impl SimpleSmt { // STATE MUTATORS // -------------------------------------------------------------------------------------------- + /// Updates value of the leaf at the specified index returning the old leaf value. + /// + /// This also recomputes all hashes between the leaf and the root, updating the root itself. + pub fn update_leaf(&mut self, key: LeafIndex, value: Word) -> Word { + >::update_leaf(self, key, value) + } + /// Inserts a subtree at the specified index. The depth at which the subtree is inserted is /// computed as `self.depth() - subtree.depth()`. /// diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index c9ac88d1..dd780aee 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -4,9 +4,7 @@ use super::{ }; use crate::{ hash::rpo::Rpo256, - merkle::{ - digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex, SparseMerkleTree, - }, + merkle::{digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex}, utils::collections::Vec, Word, }; diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 5eab01ae..0caab4cc 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -6,9 +6,10 @@ use crate::hash::rpo::Rpo256; use crate::utils::{collections::Vec, vec}; use crate::{Felt, EMPTY_WORD}; +use super::sparse_merkle_tree::SparseMerkleTree; use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, LeafIndex, MerkleError, NodeIndex, RpoDigest, - SparseMerkleTree, Word, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, LeafIndex, MerkleError, MerklePath, + NodeIndex, RpoDigest, Word, }; #[cfg(test)] @@ -77,6 +78,35 @@ impl Smt { } Ok(tree) } + + /// Returns the root of the tree + pub fn root(&self) -> RpoDigest { + >::root(self) + } + + /// Returns the leaf at the specified index. + pub fn get_leaf(&self, key: &SmtKey) -> SmtLeaf { + >::get_leaf(self, key) + } + + /// Inserts an inner node at the given index + pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + >::get_inner_node(self, index) + } + + /// Returns a Merkle path from the leaf node specified by the key to the root. + /// + /// The node itself is not included in the path. + pub fn get_leaf_path(&self, key: SmtKey) -> MerklePath { + >::get_leaf_path(self, key) + } + + /// Updates value of the leaf at the specified index returning the old leaf value. + /// + /// This also recomputes all hashes between the leaf and the root, updating the root itself. + pub fn update_leaf(&mut self, key: SmtKey, value: Word) -> Word { + >::update_leaf(self, key, value) + } } impl SparseMerkleTree for Smt { diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 237e18af..3a1f90a5 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -38,7 +38,7 @@ pub const SMT_MAX_DEPTH: u8 = 64; /// must accomodate all keys that map to the same leaf. /// /// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. -pub trait SparseMerkleTree { +pub(crate) trait SparseMerkleTree { /// The type for a key, which must be convertible into a `u64` infaillibly type Key: Into> + Clone; /// The type for a value diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 5c89fc14..90e88ac8 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -4,8 +4,7 @@ use super::{ }; use crate::{ merkle::{ - digests_to_words, int_to_leaf, int_to_node, LeafIndex, MerkleTree, SimpleSmt, - SparseMerkleTree, SMT_MAX_DEPTH, + digests_to_words, int_to_leaf, int_to_node, LeafIndex, MerkleTree, SimpleSmt, SMT_MAX_DEPTH, }, Felt, Word, ONE, WORD_SIZE, ZERO, }; From b0e0bdd9a7484c0e585646adb9e2642293ec87cf Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 11:01:53 -0500 Subject: [PATCH 071/117] add sections to `Smt` --- src/merkle/smt/mod.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 0caab4cc..139235d5 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -32,6 +32,9 @@ pub struct Smt { } impl Smt { + // CONSTRUCTORS + // -------------------------------------------------------------------------------------------- + /// Returns a new [NewSmt]. /// /// All leaves in the returned tree are set to [ZERO; 4]. @@ -79,6 +82,9 @@ impl Smt { Ok(tree) } + // PUBLIC ACCESSORS + // -------------------------------------------------------------------------------------------- + /// Returns the root of the tree pub fn root(&self) -> RpoDigest { >::root(self) @@ -101,6 +107,9 @@ impl Smt { >::get_leaf_path(self, key) } + // STATE MUTATORS + // -------------------------------------------------------------------------------------------- + /// Updates value of the leaf at the specified index returning the old leaf value. /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. From 662e886cda538f348291511137eaad7d12c056af Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 11:10:49 -0500 Subject: [PATCH 072/117] remove `SimpleSmt::depth()` --- benches/smt.rs | 4 +-- benches/store.rs | 15 +++++------ src/merkle/delta.rs | 15 +++++------ src/merkle/simple_smt/mod.rs | 36 +++++++++++--------------- src/merkle/store/tests.rs | 49 ++++++++++++++++++------------------ 5 files changed, 54 insertions(+), 65 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index 60307ab0..d2800c4a 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -27,7 +27,7 @@ fn smt_rpo(c: &mut Criterion) { // benchmark 1 let mut insert = c.benchmark_group("smt update_leaf".to_string()); { - let depth = tree.depth(); + let depth = DEPTH; let key = count >> 2; insert.bench_with_input( format!("simple smt(depth:{depth},count:{count})"), @@ -45,7 +45,7 @@ fn smt_rpo(c: &mut Criterion) { // benchmark 2 let mut path = c.benchmark_group("smt get_leaf_path".to_string()); { - let depth = tree.depth(); + let depth = DEPTH; let key = count >> 2; path.bench_with_input( format!("simple smt(depth:{depth},count:{count})"), diff --git a/benches/store.rs b/benches/store.rs index 15b8f61e..ed1b159c 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -108,13 +108,12 @@ fn get_leaf_simplesmt(c: &mut Criterion) { .collect::>(); let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); - let depth = smt.depth(); let root = smt.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( - || random_index(size_u64, depth), + || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) @@ -122,7 +121,7 @@ fn get_leaf_simplesmt(c: &mut Criterion) { group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( - || random_index(size_u64, depth), + || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) @@ -217,7 +216,7 @@ fn get_node_simplesmt(c: &mut Criterion) { let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); - let half_depth = smt.depth() / 2; + let half_depth = SMT_MAX_DEPTH / 2; let half_size = 2_u64.pow(half_depth as u32); group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { @@ -290,13 +289,12 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { .collect::>(); let smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); - let depth = smt.depth(); let root = smt.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( - || random_index(size_u64, depth), + || random_index(size_u64, SMT_MAX_DEPTH), |index| { black_box( smt.get_leaf_path(LeafIndex::::new(index.value()).unwrap()), @@ -308,7 +306,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( - || random_index(size_u64, depth), + || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(store.get_path(root, index)), BatchSize::SmallInput, ) @@ -441,7 +439,6 @@ fn update_leaf_simplesmt(c: &mut Criterion) { .collect::>(); let mut smt = SimpleSmt::::with_leaves(smt_leaves.clone()).unwrap(); let mut store = MerkleStore::from(&smt); - let depth = smt.depth(); let root = smt.root(); let size_u64 = size as u64; @@ -460,7 +457,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { let mut store_root = root; group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( - || (random_index(size_u64, depth), random_word()), + || (random_index(size_u64, SMT_MAX_DEPTH), random_word()), |(index, value)| { // The MerkleTree automatically updates its internal root, the Store maintains // the old root and adds the new one. Here we update the root to have a fair diff --git a/src/merkle/delta.rs b/src/merkle/delta.rs index 8049fa41..baede807 100644 --- a/src/merkle/delta.rs +++ b/src/merkle/delta.rs @@ -113,34 +113,35 @@ mod tests { #[test] fn test_compute_merkle_delta() { + const TREE_DEPTH: u8 = 30; + let entries = vec![ (10, [ZERO, ONE, Felt::new(2), Felt::new(3)]), (15, [Felt::new(4), Felt::new(5), Felt::new(6), Felt::new(7)]), (20, [Felt::new(8), Felt::new(9), Felt::new(10), Felt::new(11)]), (31, [Felt::new(12), Felt::new(13), Felt::new(14), Felt::new(15)]), ]; - let simple_smt = SimpleSmt::<30>::with_leaves(entries.clone()).unwrap(); + let simple_smt = SimpleSmt::::with_leaves(entries.clone()).unwrap(); let mut store: MerkleStore = (&simple_smt).into(); let root = simple_smt.root(); // add a new node let new_value = [Felt::new(16), Felt::new(17), Felt::new(18), Felt::new(19)]; - let new_index = NodeIndex::new(simple_smt.depth(), 32).unwrap(); + let new_index = NodeIndex::new(TREE_DEPTH, 32).unwrap(); let root = store.set_node(root, new_index, new_value.into()).unwrap().root; // update an existing node let update_value = [Felt::new(20), Felt::new(21), Felt::new(22), Felt::new(23)]; - let update_idx = NodeIndex::new(simple_smt.depth(), entries[0].0).unwrap(); + let update_idx = NodeIndex::new(TREE_DEPTH, entries[0].0).unwrap(); let root = store.set_node(root, update_idx, update_value.into()).unwrap().root; // remove a node - let remove_idx = NodeIndex::new(simple_smt.depth(), entries[1].0).unwrap(); + let remove_idx = NodeIndex::new(TREE_DEPTH, entries[1].0).unwrap(); let root = store.set_node(root, remove_idx, EMPTY_WORD.into()).unwrap().root; - let merkle_delta = - merkle_tree_delta(simple_smt.root(), root, simple_smt.depth(), &store).unwrap(); + let merkle_delta = merkle_tree_delta(simple_smt.root(), root, TREE_DEPTH, &store).unwrap(); let expected_merkle_delta = MerkleTreeDelta { - depth: simple_smt.depth(), + depth: TREE_DEPTH, cleared_slots: vec![remove_idx.value()], updated_slots: vec![(update_idx.value(), update_value), (new_index.value(), new_value)], }; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 791a212e..e06d398d 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -68,7 +68,7 @@ impl SimpleSmt { // compute the max number of entries. We use an upper bound of depth 63 because we consider // passing in a vector of size 2^64 infeasible. - let max_num_entries = 2_usize.pow(tree.depth().min(63).into()); + let max_num_entries = 2_usize.pow(DEPTH.min(63).into()); // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so // entries with the empty value need additional tracking. @@ -108,11 +108,6 @@ impl SimpleSmt { // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- - /// Returns the depth of this Merkle tree. - pub const fn depth(&self) -> u8 { - DEPTH - } - /// Returns the root of the tree pub fn root(&self) -> RpoDigest { >::root(self) @@ -143,9 +138,9 @@ impl SimpleSmt { pub fn get_node(&self, index: NodeIndex) -> Result { if index.is_root() { Err(MerkleError::DepthTooSmall(index.depth())) - } else if index.depth() > self.depth() { + } else if index.depth() > DEPTH { Err(MerkleError::DepthTooBig(index.depth() as u64)) - } else if index.depth() == self.depth() { + } else if index.depth() == DEPTH { let leaf = self.get_leaf(&LeafIndex::::try_from(index)?); Ok(leaf.into()) @@ -182,7 +177,7 @@ impl SimpleSmt { } /// Inserts a subtree at the specified index. The depth at which the subtree is inserted is - /// computed as `self.depth() - subtree.depth()`. + /// computed as `DEPTH - SUBTREE_DEPTH`. /// /// Returns the new root. pub fn set_subtree( @@ -190,15 +185,15 @@ impl SimpleSmt { subtree_insertion_index: u64, subtree: SimpleSmt, ) -> Result { - if subtree.depth() > self.depth() { + if SUBTREE_DEPTH > DEPTH { return Err(MerkleError::InvalidSubtreeDepth { - subtree_depth: subtree.depth(), - tree_depth: self.depth(), + subtree_depth: SUBTREE_DEPTH, + tree_depth: DEPTH, }); } // Verify that `subtree_insertion_index` is valid. - let subtree_root_insertion_depth = self.depth() - subtree.depth(); + let subtree_root_insertion_depth = DEPTH - SUBTREE_DEPTH; let subtree_root_index = NodeIndex::new(subtree_root_insertion_depth, subtree_insertion_index)?; @@ -212,10 +207,10 @@ impl SimpleSmt { // you can see it as there's a full subtree sitting on its left. In general, for // `subtree_insertion_index = i`, there are `i` subtrees sitting before the subtree we want // to insert, so we need to adjust all its leaves by `i * 2^d`. - let leaf_index_shift: u64 = subtree_insertion_index * 2_u64.pow(subtree.depth().into()); + let leaf_index_shift: u64 = subtree_insertion_index * 2_u64.pow(SUBTREE_DEPTH.into()); for (subtree_leaf_idx, leaf_value) in subtree.leaves() { let new_leaf_idx = leaf_index_shift + subtree_leaf_idx; - debug_assert!(new_leaf_idx < 2_u64.pow(self.depth().into())); + debug_assert!(new_leaf_idx < 2_u64.pow(DEPTH.into())); self.leaves.insert(new_leaf_idx, *leaf_value); } @@ -259,7 +254,7 @@ impl SparseMerkleTree for SimpleSmt { fn get_inner_node(&self, index: NodeIndex) -> InnerNode { self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(self.depth(), index.depth() + 1); + let node = EmptySubtreeRoots::entry(DEPTH, index.depth() + 1); InnerNode { left: *node, right: *node } }) @@ -280,7 +275,7 @@ impl SparseMerkleTree for SimpleSmt { match self.leaves.get(&leaf_pos) { Some(word) => *word, - None => Word::from(*EmptySubtreeRoots::entry(self.depth(), self.depth())), + None => Word::from(*EmptySubtreeRoots::entry(DEPTH, DEPTH)), } } @@ -297,11 +292,8 @@ impl TryApplyDiff for SimpleSmt { type DiffType = MerkleTreeDelta; fn try_apply(&mut self, diff: MerkleTreeDelta) -> Result<(), MerkleError> { - if diff.depth() != self.depth() { - return Err(MerkleError::InvalidDepth { - expected: self.depth(), - provided: diff.depth(), - }); + if diff.depth() != DEPTH { + return Err(MerkleError::InvalidDepth { expected: DEPTH, provided: diff.depth() }); } for slot in diff.cleared_slots() { diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 90e88ac8..b3f362ca 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -240,27 +240,27 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { // STORE LEAVES ARE CORRECT ============================================================== // checks the leaves in the store corresponds to the expected values assert_eq!( - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 0)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 0)), Ok(VALUES4[0]), "node 0 must be in the tree" ); assert_eq!( - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 1)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 1)), Ok(VALUES4[1]), "node 1 must be in the tree" ); assert_eq!( - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 2)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 2)), Ok(VALUES4[2]), "node 2 must be in the tree" ); assert_eq!( - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 3)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 3)), Ok(VALUES4[3]), "node 3 must be in the tree" ); assert_eq!( - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 4)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 4)), Ok(RpoDigest::default()), "unmodified node 4 must be ZERO" ); @@ -268,34 +268,34 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { // STORE LEAVES MATCH TREE =============================================================== // sanity check the values returned by the store and the tree assert_eq!( - smt.get_node(NodeIndex::make(smt.depth(), 0)), - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 0)), + smt.get_node(NodeIndex::make(SMT_MAX_DEPTH, 0)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 0)), "node 0 must be the same for both SparseMerkleTree and MerkleStore" ); assert_eq!( - smt.get_node(NodeIndex::make(smt.depth(), 1)), - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 1)), + smt.get_node(NodeIndex::make(SMT_MAX_DEPTH, 1)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 1)), "node 1 must be the same for both SparseMerkleTree and MerkleStore" ); assert_eq!( - smt.get_node(NodeIndex::make(smt.depth(), 2)), - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 2)), + smt.get_node(NodeIndex::make(SMT_MAX_DEPTH, 2)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 2)), "node 2 must be the same for both SparseMerkleTree and MerkleStore" ); assert_eq!( - smt.get_node(NodeIndex::make(smt.depth(), 3)), - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 3)), + smt.get_node(NodeIndex::make(SMT_MAX_DEPTH, 3)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 3)), "node 3 must be the same for both SparseMerkleTree and MerkleStore" ); assert_eq!( - smt.get_node(NodeIndex::make(smt.depth(), 4)), - store.get_node(smt.root(), NodeIndex::make(smt.depth(), 4)), + smt.get_node(NodeIndex::make(SMT_MAX_DEPTH, 4)), + store.get_node(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 4)), "node 4 must be the same for both SparseMerkleTree and MerkleStore" ); // STORE MERKLE PATH MATCHES ============================================================== // assert the merkle path returned by the store is the same as the one in the tree - let result = store.get_path(smt.root(), NodeIndex::make(smt.depth(), 0)).unwrap(); + let result = store.get_path(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 0)).unwrap(); assert_eq!( VALUES4[0], result.value, "Value for merkle path at index 0 must match leaf value" @@ -306,7 +306,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); - let result = store.get_path(smt.root(), NodeIndex::make(smt.depth(), 1)).unwrap(); + let result = store.get_path(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 1)).unwrap(); assert_eq!( VALUES4[1], result.value, "Value for merkle path at index 1 must match leaf value" @@ -317,7 +317,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); - let result = store.get_path(smt.root(), NodeIndex::make(smt.depth(), 2)).unwrap(); + let result = store.get_path(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 2)).unwrap(); assert_eq!( VALUES4[2], result.value, "Value for merkle path at index 2 must match leaf value" @@ -328,7 +328,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); - let result = store.get_path(smt.root(), NodeIndex::make(smt.depth(), 3)).unwrap(); + let result = store.get_path(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 3)).unwrap(); assert_eq!( VALUES4[3], result.value, "Value for merkle path at index 3 must match leaf value" @@ -339,7 +339,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); - let result = store.get_path(smt.root(), NodeIndex::make(smt.depth(), 4)).unwrap(); + let result = store.get_path(smt.root(), NodeIndex::make(SMT_MAX_DEPTH, 4)).unwrap(); assert_eq!( RpoDigest::default(), result.value, @@ -559,10 +559,9 @@ fn test_constructors() -> Result<(), MerkleError> { let smt = SimpleSmt::::with_leaves(KEYS4.into_iter().zip(digests_to_words(&VALUES4))).unwrap(); let store = MerkleStore::from(&smt); - let depth = smt.depth(); for key in KEYS4 { - let index = NodeIndex::make(depth, key); + let index = NodeIndex::make(DEPTH, key); let value_path = store.get_path(smt.root(), index)?; assert_eq!(smt.get_leaf_path(LeafIndex::::new(key).unwrap()), value_path.path); } @@ -898,13 +897,13 @@ fn test_recorder() { let node = recorder.get_node(mtree.root(), index_0).unwrap(); assert_eq!(node, mtree.get_node(index_0).unwrap()); - let index_1 = NodeIndex::new(smtree.depth(), 1).unwrap(); + let index_1 = NodeIndex::new(TREE_DEPTH, 1).unwrap(); let node = recorder.get_node(smtree.root(), index_1).unwrap(); assert_eq!(node, smtree.get_node(index_1).unwrap()); // insert a value and assert that when we request it next time it is accurate let new_value = [ZERO, ZERO, ONE, ONE].into(); - let index_2 = NodeIndex::new(smtree.depth(), 2).unwrap(); + let index_2 = NodeIndex::new(TREE_DEPTH, 2).unwrap(); let root = recorder.set_node(smtree.root(), index_2, new_value).unwrap().root; assert_eq!(recorder.get_node(root, index_2).unwrap(), new_value); @@ -927,7 +926,7 @@ fn test_recorder() { ); // assert that is doesnt contain nodes that were not recorded - let not_recorded_index = NodeIndex::new(smtree.depth(), 4).unwrap(); + let not_recorded_index = NodeIndex::new(TREE_DEPTH, 4).unwrap(); assert!(merkle_store.get_node(smtree.root(), not_recorded_index).is_err()); assert!(smtree.get_node(not_recorded_index).is_ok()); } From 59a037a0a4573d97755968441ce2afc005daa5b2 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 11:17:18 -0500 Subject: [PATCH 073/117] fix `get_inner_node()` docstring --- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/smt/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index e06d398d..504644ba 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -118,7 +118,7 @@ impl SimpleSmt { >::get_leaf(self, key) } - /// Inserts an inner node at the given index + /// Retrieves an inner node at the given index pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { >::get_inner_node(self, index) } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 139235d5..630c96c5 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -95,7 +95,7 @@ impl Smt { >::get_leaf(self, key) } - /// Inserts an inner node at the given index + /// Retrieves an inner node at the given index pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { >::get_inner_node(self, index) } From 05e327152ab1c110be5956359f4ac8655fbe4240 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 11:20:56 -0500 Subject: [PATCH 074/117] remove `get_inner_node` from public API --- src/merkle/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 12 +++--------- src/merkle/simple_smt/tests.rs | 5 ++++- src/merkle/smt/mod.rs | 11 +++-------- src/merkle/sparse_merkle_tree.rs | 2 +- 5 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 83e44d75..5d8b5421 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -28,7 +28,7 @@ mod simple_smt; pub use simple_smt::SimpleSmt; pub(crate) mod sparse_merkle_tree; -pub use sparse_merkle_tree::{InnerNode, LeafIndex, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; +pub use sparse_merkle_tree::{LeafIndex, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod smt; pub use smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 504644ba..a81fa8d9 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -1,10 +1,9 @@ use crate::EMPTY_WORD; use super::{ - sparse_merkle_tree::{SparseMerkleTree, SMT_MAX_DEPTH}, - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, - MerklePath, MerkleTreeDelta, NodeIndex, RpoDigest, StoreNode, TryApplyDiff, Word, - SMT_MIN_DEPTH, + sparse_merkle_tree::{InnerNode, SparseMerkleTree, SMT_MAX_DEPTH}, + BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNodeInfo, LeafIndex, MerkleError, MerklePath, + MerkleTreeDelta, NodeIndex, RpoDigest, StoreNode, TryApplyDiff, Word, SMT_MIN_DEPTH, }; #[cfg(test)] @@ -118,11 +117,6 @@ impl SimpleSmt { >::get_leaf(self, key) } - /// Retrieves an inner node at the given index - pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - >::get_inner_node(self, index) - } - /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index dd780aee..c6552b1a 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -4,7 +4,10 @@ use super::{ }; use crate::{ hash::rpo::Rpo256, - merkle::{digests_to_words, int_to_leaf, int_to_node, EmptySubtreeRoots, LeafIndex}, + merkle::{ + digests_to_words, int_to_leaf, int_to_node, sparse_merkle_tree::SparseMerkleTree, + EmptySubtreeRoots, LeafIndex, + }, utils::collections::Vec, Word, }; diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 630c96c5..9ff059e4 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -6,10 +6,10 @@ use crate::hash::rpo::Rpo256; use crate::utils::{collections::Vec, vec}; use crate::{Felt, EMPTY_WORD}; -use super::sparse_merkle_tree::SparseMerkleTree; +use super::sparse_merkle_tree::{InnerNode, SparseMerkleTree}; use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNode, LeafIndex, MerkleError, MerklePath, - NodeIndex, RpoDigest, Word, + BTreeMap, BTreeSet, EmptySubtreeRoots, LeafIndex, MerkleError, MerklePath, NodeIndex, + RpoDigest, Word, }; #[cfg(test)] @@ -95,11 +95,6 @@ impl Smt { >::get_leaf(self, key) } - /// Retrieves an inner node at the given index - pub fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - >::get_inner_node(self, index) - } - /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 3a1f90a5..3bd9e05e 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -144,7 +144,7 @@ pub(crate) trait SparseMerkleTree { #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct InnerNode { +pub(crate) struct InnerNode { pub left: RpoDigest, pub right: RpoDigest, } From 19dde05e1d0c73cef78fe5765e50f30c1d519c93 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 12:05:40 -0500 Subject: [PATCH 075/117] insert_value: if no value at key, always return `None` --- src/merkle/smt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 9ff059e4..843af430 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -180,7 +180,7 @@ impl SparseMerkleTree for Smt { None => { self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); - Some(Self::Value::default()) + None } } } From 5f1777124de36d80a7e0c2f0ded7cc78d028e935 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 13:46:54 -0500 Subject: [PATCH 076/117] cover case of inserting an `EMPTY_VALUE` --- src/merkle/smt/mod.rs | 138 +++++++++++++++++++++++++++++++----------- 1 file changed, 101 insertions(+), 37 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 843af430..8c967663 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -111,55 +111,36 @@ impl Smt { pub fn update_leaf(&mut self, key: SmtKey, value: Word) -> Word { >::update_leaf(self, key, value) } -} - -impl SparseMerkleTree for Smt { - type Key = SmtKey; - type Value = Word; - type Leaf = SmtLeaf; - - const EMPTY_VALUE: Self::Value = EMPTY_WORD; - - fn root(&self) -> RpoDigest { - self.root - } - - fn set_root(&mut self, root: RpoDigest) { - self.root = root; - } - fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); - - InnerNode { left: *node, right: *node } - }) - } + // HELPERS + // -------------------------------------------------------------------------------------------- - fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { - self.inner_nodes.insert(index, inner_node); - } + /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty + /// value, such that this is indeed an insertion. + fn perform_insert(&mut self, key: SmtKey, value: Word) -> Option { + debug_assert_ne!(value, Self::EMPTY_VALUE); - fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { let leaf_index: LeafIndex = key.into(); + match self.leaves.get_mut(&leaf_index.value()) { Some(leaf) => match leaf { SmtLeaf::Single(kv_pair) => { - // if the key is already in this entry, update the value and return if kv_pair.0 == key { + // the key is already in this leaf. Update the value and return the previous + // value let old_value = kv_pair.1; kv_pair.1 = value; - return Some(old_value); - } - - // transform the entry into a list entry, and make sure the key-value pairs - // are sorted by key - let mut pairs = vec![*kv_pair, (key, value)]; - pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); + Some(old_value) + } else { + // Another entry is present in this leaf. Transform the entry into a list + // entry, and make sure the key-value pairs are sorted by key + let mut pairs = vec![*kv_pair, (key, value)]; + pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); - self.leaves.insert(leaf_index.value(), SmtLeaf::Multiple(pairs)); + self.leaves.insert(leaf_index.value(), SmtLeaf::Multiple(pairs)); - None + None + } } SmtLeaf::Multiple(kv_pairs) => { match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { @@ -185,6 +166,89 @@ impl SparseMerkleTree for Smt { } } + /// Removes `key`/`value` pair at leaf index pointed to by `key` if it exists. + fn perform_remove(&mut self, key: SmtKey) -> Option { + let leaf_index: LeafIndex = key.into(); + + if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { + match leaf { + SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { + if *key_at_leaf == key { + // our key was indeed stored in the leaf, so we remove the leaf and return + // the value that was stored in it + let old_value = *value_at_leaf; + self.leaves.remove(&leaf_index.value()); + Some(old_value) + } else { + // another key is stored at leaf; nothing to update + None + } + } + SmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + + kv_pairs.remove(pos); + debug_assert!(!kv_pairs.is_empty()); + + if kv_pairs.len() == 1 { + // convert the leaf into `Single` + *leaf = SmtLeaf::Single(kv_pairs[0]); + } + + Some(old_value) + } + Err(_) => { + // other keys are stored at leaf; nothing to update + None + } + } + } + } + } else { + // there's nothing stored at the leaf; nothing to update + None + } + } +} + +impl SparseMerkleTree for Smt { + type Key = SmtKey; + type Value = Word; + type Leaf = SmtLeaf; + + const EMPTY_VALUE: Self::Value = EMPTY_WORD; + + fn root(&self) -> RpoDigest { + self.root + } + + fn set_root(&mut self, root: RpoDigest) { + self.root = root; + } + + fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { + let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); + + InnerNode { left: *node, right: *node } + }) + } + + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { + self.inner_nodes.insert(index, inner_node); + } + + fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { + // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key` + if value != Self::EMPTY_VALUE { + self.perform_insert(key, value) + } else { + self.perform_remove(key) + } + } + fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { let leaf_pos = LeafIndex::::from(*key).value(); From 8ad9d806151322521083439912300d3f20554449 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 14:05:53 -0500 Subject: [PATCH 077/117] `NewLeaf::insert` --- src/merkle/smt/mod.rs | 79 ++++++++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 8c967663..11e2d119 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -123,41 +123,7 @@ impl Smt { let leaf_index: LeafIndex = key.into(); match self.leaves.get_mut(&leaf_index.value()) { - Some(leaf) => match leaf { - SmtLeaf::Single(kv_pair) => { - if kv_pair.0 == key { - // the key is already in this leaf. Update the value and return the previous - // value - let old_value = kv_pair.1; - kv_pair.1 = value; - Some(old_value) - } else { - // Another entry is present in this leaf. Transform the entry into a list - // entry, and make sure the key-value pairs are sorted by key - let mut pairs = vec![*kv_pair, (key, value)]; - pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); - - self.leaves.insert(leaf_index.value(), SmtLeaf::Multiple(pairs)); - - None - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - kv_pairs[pos].1 = value; - - Some(old_value) - } - Err(pos) => { - kv_pairs.insert(pos, (key, value)); - - None - } - } - } - }, + Some(leaf) => leaf.insert(key, value), None => { self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); @@ -337,6 +303,49 @@ impl SmtLeaf { } } } + + // HELPERS + // --------------------------------------------------------------------------------------------- + + /// Insert key-value pair into the leaf; return the previous value associated with `key`, if + /// any. + fn insert(&mut self, key: SmtKey, value: Word) -> Option { + match self { + SmtLeaf::Single(kv_pair) => { + if kv_pair.0 == key { + // the key is already in this leaf. Update the value and return the previous + // value + let old_value = kv_pair.1; + kv_pair.1 = value; + Some(old_value) + } else { + // Another entry is present in this leaf. Transform the entry into a list + // entry, and make sure the key-value pairs are sorted by key + let mut pairs = vec![*kv_pair, (key, value)]; + pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); + + *self = SmtLeaf::Multiple(pairs); + + None + } + } + SmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + kv_pairs[pos].1 = value; + + Some(old_value) + } + Err(pos) => { + kv_pairs.insert(pos, (key, value)); + + None + } + } + } + } + } } // HELPER FUNCTIONS From 97f06ab0d546b74e7decd8b7df6b3462fda55685 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 14:15:09 -0500 Subject: [PATCH 078/117] update comment --- src/merkle/smt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 11e2d119..ae3c79dc 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -132,7 +132,7 @@ impl Smt { } } - /// Removes `key`/`value` pair at leaf index pointed to by `key` if it exists. + /// Removes key-value pair at leaf index pointed to by `key` if it exists. fn perform_remove(&mut self, key: SmtKey) -> Option { let leaf_index: LeafIndex = key.into(); From 29768fb3d65c4030a93673eeebd9df45b2b5f88d Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:03:29 -0500 Subject: [PATCH 079/117] test_smt_insert_at_same_key --- src/merkle/smt/tests.rs | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 8b137891..05ee6802 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -1 +1,52 @@ +use crate::{merkle::MerkleStore, ONE, WORD_SIZE}; +use super::*; + +/// This test checks that inserting twice at the same key functions as expected. The test covers +/// only the case where the key is alone in its leaf +#[test] +fn test_smt_insert_at_same_key() { + let mut smt = Smt::default(); + let mut store: MerkleStore = MerkleStore::default(); + + assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); + + let key_1: SmtKey = { + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + }; + let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); + + let value_1 = [ONE; WORD_SIZE]; + let value_2 = [ONE + ONE; WORD_SIZE]; + + // Insert value 1 and ensure root is as expected + { + let leaf_node = build_single_leaf_node(key_1, value_1); + let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; + + let old_value_1 = smt.update_leaf(key_1, value_1); + assert_eq!(old_value_1, EMPTY_WORD); + + assert_eq!(smt.root(), tree_root); + } + + // Insert value 2 and ensure root is as expected + { + let leaf_node = build_single_leaf_node(key_1, value_2); + let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; + + let old_value_2 = smt.update_leaf(key_1, value_2); + assert_eq!(old_value_2, value_1); + + assert_eq!(smt.root(), tree_root); + } +} + +// HELPERS +// -------------------------------------------------------------------------------------------- + +fn build_single_leaf_node(key: SmtKey, value: Word) -> RpoDigest { + SmtLeaf::Single((key, value)).hash() +} From 52cbc2103c6f451a2f3401be2c169f65ae8254c1 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:09:32 -0500 Subject: [PATCH 080/117] test_smt_insert_at_same_key_2 --- src/merkle/smt/tests.rs | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 05ee6802..f6529630 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -44,6 +44,63 @@ fn test_smt_insert_at_same_key() { } } +/// This test checks that inserting twice at the same key functions as expected. The test covers +/// only the case where the leaf type is `SmtLeaf::Multiple` +#[test] +fn test_smt_insert_at_same_key_2() { + let key_already_present: SmtKey = { + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + RpoDigest::from([ONE + ONE, ONE + ONE, ONE + ONE, Felt::new(raw)]).into() + }; + let key_already_present_index: NodeIndex = + LeafIndex::::from(key_already_present).into(); + let value_already_present = [ONE + ONE + ONE; WORD_SIZE]; + + let mut smt = + Smt::with_entries(std::iter::once((key_already_present, value_already_present))).unwrap(); + let mut store: MerkleStore = { + let mut store = MerkleStore::default(); + + let leaf_node = build_single_leaf_node(key_already_present, value_already_present); + store + .set_node(*EmptySubtreeRoots::entry(SMT_DEPTH, 0), key_already_present_index, leaf_node) + .unwrap(); + store + }; + + let key_1: SmtKey = { + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + }; + let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); + + let value_1 = [ONE; WORD_SIZE]; + let value_2 = [ONE + ONE; WORD_SIZE]; + + // Insert value 1 and ensure root is as expected + { + let leaf_node = build_single_leaf_node(key_1, value_1); + let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; + + let old_value_1 = smt.update_leaf(key_1, value_1); + assert_eq!(old_value_1, EMPTY_WORD); + + assert_eq!(smt.root(), tree_root); + } + + // Insert value 2 and ensure root is as expected + { + let leaf_node = build_single_leaf_node(key_1, value_2); + let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; + + let old_value_2 = smt.update_leaf(key_1, value_2); + assert_eq!(old_value_2, value_1); + + assert_eq!(smt.root(), tree_root); + } +} // HELPERS // -------------------------------------------------------------------------------------------- From 132beafdcd0e64e19da5c1134ce727814b3535e8 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:16:00 -0500 Subject: [PATCH 081/117] fix most_significant_felt for `SmtKey` --- src/merkle/smt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index ae3c79dc..ad9b88c0 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -252,7 +252,7 @@ pub struct SmtKey { impl From for LeafIndex { fn from(key: SmtKey) -> Self { - let most_significant_felt = key.word[0]; + let most_significant_felt = key.word[3]; Self::new_max_depth(most_significant_felt.as_int()) } } From 31e26bfd0684879ac26ed0c87690a372aa9e4e33 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:21:17 -0500 Subject: [PATCH 082/117] fix test_smt_insert_at_same_key_2 --- src/merkle/smt/tests.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index f6529630..98db5206 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -76,12 +76,18 @@ fn test_smt_insert_at_same_key_2() { }; let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); + assert_eq!(key_1_index, key_already_present_index); + let value_1 = [ONE; WORD_SIZE]; let value_2 = [ONE + ONE; WORD_SIZE]; // Insert value 1 and ensure root is as expected { - let leaf_node = build_single_leaf_node(key_1, value_1); + // Note: key_1 comes first because it is smaller + let leaf_node = build_multiple_leaf_node(&[ + (key_1, value_1), + (key_already_present, value_already_present), + ]); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; let old_value_1 = smt.update_leaf(key_1, value_1); @@ -92,7 +98,10 @@ fn test_smt_insert_at_same_key_2() { // Insert value 2 and ensure root is as expected { - let leaf_node = build_single_leaf_node(key_1, value_2); + let leaf_node = build_multiple_leaf_node(&[ + (key_1, value_2), + (key_already_present, value_already_present), + ]); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; let old_value_2 = smt.update_leaf(key_1, value_2); @@ -101,9 +110,24 @@ fn test_smt_insert_at_same_key_2() { assert_eq!(smt.root(), tree_root); } } + // HELPERS // -------------------------------------------------------------------------------------------- fn build_single_leaf_node(key: SmtKey, value: Word) -> RpoDigest { SmtLeaf::Single((key, value)).hash() } + +fn build_multiple_leaf_node(kv_pairs: &[(SmtKey, Word)]) -> RpoDigest { + let elements: Vec = kv_pairs + .iter() + .flat_map(|(key, value)| { + let key_elements = key.word.into_iter(); + let value_elements = value.clone().into_iter(); + + key_elements.chain(value_elements) + }) + .collect(); + + Rpo256::hash_elements(&elements) +} From 8bd01b937ebc1eadcc4114e6653ad3bf21d85bab Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:35:42 -0500 Subject: [PATCH 083/117] test inserting multiple values --- src/merkle/smt/tests.rs | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 98db5206..23f3eaaf 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -111,6 +111,51 @@ fn test_smt_insert_at_same_key_2() { } } +/// This test ensures that the root of the tree is as expected when we add 3 items at 3 different +/// keys +#[test] +fn test_smt_insert_multiple_values() { + let mut smt = Smt::default(); + let mut store: MerkleStore = MerkleStore::default(); + + assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); + + let key_1: SmtKey = { + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + }; + + let key_2: SmtKey = { + let raw = 0b_11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111_u64; + + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + }; + + let key_3: SmtKey = { + let raw = 0b_00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000_u64; + + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + }; + + let value_1 = [ONE; WORD_SIZE]; + let value_2 = [ONE + ONE; WORD_SIZE]; + let value_3 = [ONE + ONE + ONE; WORD_SIZE]; + + let key_values = [(key_1, value_1), (key_2, value_2), (key_3, value_3)]; + + for (key, value) in key_values { + let key_index: NodeIndex = LeafIndex::::from(key).into(); + + let leaf_node = build_single_leaf_node(key, value); + let tree_root = store.set_node(smt.root(), key_index, leaf_node).unwrap().root; + + let old_value = smt.update_leaf(key, value); + assert_eq!(old_value, EMPTY_WORD); + + assert_eq!(smt.root(), tree_root); + } +} // HELPERS // -------------------------------------------------------------------------------------------- From bc1dca9345ba989f09bcd7d1e84db5a6421d5cba Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:51:49 -0500 Subject: [PATCH 084/117] test_smt_insert_multiple_values --- src/merkle/smt/tests.rs | 78 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 23f3eaaf..686d804c 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -156,6 +156,84 @@ fn test_smt_insert_multiple_values() { assert_eq!(smt.root(), tree_root); } } + +/// This tests that inserting the empty value does indeed remove the key-value contained at the +/// leaf. We insert & remove 3 values at the same leaf to ensure that all cases are covered (empty, +/// single, multiple). +#[test] +fn test_smt_removal() { + let mut smt = Smt::default(); + + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + let key_1: SmtKey = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into(); + let key_2: SmtKey = + RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]).into(); + let key_3: SmtKey = + RpoDigest::from([3_u64.into(), 3_u64.into(), 3_u64.into(), Felt::new(raw)]).into(); + + let value_1 = [ONE; WORD_SIZE]; + let value_2 = [2_u64.into(); WORD_SIZE]; + let value_3: [Felt; 4] = [3_u64.into(); WORD_SIZE]; + + // insert key-value 1 + { + let old_value_1 = smt.update_leaf(key_1, value_1); + assert_eq!(old_value_1, EMPTY_WORD); + + assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, value_1))); + } + + // insert key-value 2 + { + let old_value_2 = smt.update_leaf(key_2, value_2); + assert_eq!(old_value_2, EMPTY_WORD); + + assert_eq!( + smt.get_leaf(&key_2), + SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) + ); + } + + // insert key-value 3 + { + let old_value_3 = smt.update_leaf(key_3, value_3); + assert_eq!(old_value_3, EMPTY_WORD); + + assert_eq!( + smt.get_leaf(&key_3), + SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2), (key_3, value_3)]) + ); + } + + // remove key 3 + { + let old_value_3 = smt.update_leaf(key_3, EMPTY_WORD); + assert_eq!(old_value_3, value_3); + + assert_eq!( + smt.get_leaf(&key_3), + SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) + ); + } + + // remove key 2 + { + let old_value_2 = smt.update_leaf(key_2, EMPTY_WORD); + assert_eq!(old_value_2, value_2); + + assert_eq!(smt.get_leaf(&key_2), SmtLeaf::Single((key_1, value_1))); + } + + // remove key 1 + { + let old_value_1 = smt.update_leaf(key_1, EMPTY_WORD); + assert_eq!(old_value_1, value_1); + + assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, EMPTY_WORD))); + } +} + // HELPERS // -------------------------------------------------------------------------------------------- From e95af3f82da5fa67a14f2bd496050c91663d346e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:52:35 -0500 Subject: [PATCH 085/117] simplify interface --- src/merkle/smt/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index ad9b88c0..56d4888f 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -220,9 +220,7 @@ impl SparseMerkleTree for Smt { match self.leaves.get(&leaf_pos) { Some(leaf) => leaf.clone(), - None => { - SmtLeaf::Single((*key, Word::from(*EmptySubtreeRoots::entry(SMT_DEPTH, SMT_DEPTH)))) - } + None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), } } From e8566e04bcc67f6600dfd98481979d23288bbaf9 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 15:53:27 -0500 Subject: [PATCH 086/117] core::iter instead of std --- src/merkle/smt/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 686d804c..aa289950 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -58,7 +58,7 @@ fn test_smt_insert_at_same_key_2() { let value_already_present = [ONE + ONE + ONE; WORD_SIZE]; let mut smt = - Smt::with_entries(std::iter::once((key_already_present, value_already_present))).unwrap(); + Smt::with_entries(core::iter::once((key_already_present, value_already_present))).unwrap(); let mut store: MerkleStore = { let mut store = MerkleStore::default(); From 69c19592ed6c0c289aff457b6fabfa45068b4e33 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 16:00:36 -0500 Subject: [PATCH 087/117] test_smt_path_to_keys_in_same_leaf_are_equal --- src/merkle/smt/tests.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index aa289950..3fcf5c73 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -112,7 +112,7 @@ fn test_smt_insert_at_same_key_2() { } /// This test ensures that the root of the tree is as expected when we add 3 items at 3 different -/// keys +/// keys. This also tests that the merkle paths produced are as expected. #[test] fn test_smt_insert_multiple_values() { let mut smt = Smt::default(); @@ -154,6 +154,9 @@ fn test_smt_insert_multiple_values() { assert_eq!(old_value, EMPTY_WORD); assert_eq!(smt.root(), tree_root); + + let expected_path = store.get_path(tree_root, key_index).unwrap(); + assert_eq!(smt.get_leaf_path(key), expected_path.path); } } @@ -234,6 +237,23 @@ fn test_smt_removal() { } } +/// Tests that 2 key-value pairs stored in the same leaf have the same path +#[test] +fn test_smt_path_to_keys_in_same_leaf_are_equal() { + let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; + + let key_1: SmtKey = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into(); + let key_2: SmtKey = + RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]).into(); + + let value_1 = [ONE; WORD_SIZE]; + let value_2 = [2_u64.into(); WORD_SIZE]; + + let smt = Smt::with_entries([(key_1, value_1), (key_2, value_2)]).unwrap(); + + assert_eq!(smt.get_leaf_path(key_1), smt.get_leaf_path(key_2)); +} + // HELPERS // -------------------------------------------------------------------------------------------- From 986b14d499242455f1e6e806a356d872666f9b9d Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 16:09:58 -0500 Subject: [PATCH 088/117] cleanup `perform_remove()` --- src/merkle/smt/mod.rs | 79 ++++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 34 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 56d4888f..97753c4f 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -137,41 +137,11 @@ impl Smt { let leaf_index: LeafIndex = key.into(); if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { - match leaf { - SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { - if *key_at_leaf == key { - // our key was indeed stored in the leaf, so we remove the leaf and return - // the value that was stored in it - let old_value = *value_at_leaf; - self.leaves.remove(&leaf_index.value()); - Some(old_value) - } else { - // another key is stored at leaf; nothing to update - None - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - - kv_pairs.remove(pos); - debug_assert!(!kv_pairs.is_empty()); - - if kv_pairs.len() == 1 { - // convert the leaf into `Single` - *leaf = SmtLeaf::Single(kv_pairs[0]); - } - - Some(old_value) - } - Err(_) => { - // other keys are stored at leaf; nothing to update - None - } - } - } + let (old_value, is_empty) = leaf.remove(key); + if is_empty { + self.leaves.remove(&leaf_index.value()); } + old_value } else { // there's nothing stored at the leaf; nothing to update None @@ -344,6 +314,47 @@ impl SmtLeaf { } } } + + /// Remove key-value pair into the leaf stored at key; return the previous value associated with + /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf is empty, + /// and must be removed from the data structure it is contained in. + fn remove(&mut self, key: SmtKey) -> (Option, bool) { + match self { + SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { + if *key_at_leaf == key { + // our key was indeed stored in the leaf, so we return the value that was stored + // in it, and indicate that the leaf should be removed + let old_value = *value_at_leaf; + + (Some(old_value), true) + } else { + // another key is stored at leaf; nothing to update + (None, false) + } + } + SmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + + kv_pairs.remove(pos); + debug_assert!(!kv_pairs.is_empty()); + + if kv_pairs.len() == 1 { + // convert the leaf into `Single` + *self = SmtLeaf::Single(kv_pairs[0]); + } + + (Some(old_value), false) + } + Err(_) => { + // other keys are stored at leaf; nothing to update + (None, false) + } + } + } + } + } } // HELPER FUNCTIONS From 5e5c418039656b63c02b73c82e1f5182795a8bd0 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Fri, 12 Jan 2024 16:15:19 -0500 Subject: [PATCH 089/117] clippy --- src/merkle/smt/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 3fcf5c73..a0c584da 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -266,7 +266,7 @@ fn build_multiple_leaf_node(kv_pairs: &[(SmtKey, Word)]) -> RpoDigest { .iter() .flat_map(|(key, value)| { let key_elements = key.word.into_iter(); - let value_elements = value.clone().into_iter(); + let value_elements = (*value).into_iter(); key_elements.chain(value_elements) }) From 280218212cc0b36565278b27c3718c56c374e081 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:38:39 -0500 Subject: [PATCH 090/117] fix comment --- src/merkle/smt/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 97753c4f..39409737 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -316,8 +316,8 @@ impl SmtLeaf { } /// Remove key-value pair into the leaf stored at key; return the previous value associated with - /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf is empty, - /// and must be removed from the data structure it is contained in. + /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf became + /// empty, and must be removed from the data structure it is contained in. fn remove(&mut self, key: SmtKey) -> (Option, bool) { match self { SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { From cca076028b01a31e91aaa2296a27a2d0e0b0acd0 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:40:53 -0500 Subject: [PATCH 091/117] add `depth()` function --- src/merkle/smt/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 39409737..0ce29346 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -95,6 +95,11 @@ impl Smt { >::get_leaf(self, key) } + /// Returns the depth of the tree + pub const fn depth(&self) -> u8 { + SMT_DEPTH + } + /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. From 8fce44c71c2c7ba2ed01063a7434ef62cedfb6a5 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:41:29 -0500 Subject: [PATCH 092/117] add depth() fn to simple smt --- src/merkle/simple_smt/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index a81fa8d9..1d7bce4a 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -117,6 +117,11 @@ impl SimpleSmt { >::get_leaf(self, key) } + /// Returns the depth of the tree + pub const fn depth(&self) -> u8 { + DEPTH + } + /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. From 851000771343a6276f1486f104f283d48afdec7d Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:51:25 -0500 Subject: [PATCH 093/117] `SparseMerkleTtree`: rename `update_leaf` to `insert` --- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/smt/mod.rs | 2 +- src/merkle/sparse_merkle_tree.rs | 9 ++++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 1d7bce4a..70bcf00e 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -172,7 +172,7 @@ impl SimpleSmt { /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. pub fn update_leaf(&mut self, key: LeafIndex, value: Word) -> Word { - >::update_leaf(self, key, value) + >::insert(self, key, value) } /// Inserts a subtree at the specified index. The depth at which the subtree is inserted is diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 0ce29346..f71f9f73 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -114,7 +114,7 @@ impl Smt { /// /// This also recomputes all hashes between the leaf and the root, updating the root itself. pub fn update_leaf(&mut self, key: SmtKey, value: Word) -> Word { - >::update_leaf(self, key, value) + >::insert(self, key, value) } // HELPERS diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 3bd9e05e..24a135e4 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -73,10 +73,13 @@ pub(crate) trait SparseMerkleTree { MerklePath::new(path) } - /// Updates value of the leaf at the specified index returning the old leaf value. + /// Inserts a value at the specified key, returning the previous value associated with that key. + /// Recall that by definition, any key that hasn't been updated is associated with + /// [`Self::EMPTY_VALUE`]. /// - /// This also recomputes all hashes between the leaf and the root, updating the root itself. - fn update_leaf(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { + /// This also recomputes all hashes between the leaf (associated with the key) and the root, + /// updating the root itself. + fn insert(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or(Self::EMPTY_VALUE); // if the old value and new value are the same, there is nothing to update From e162242b8e9dae2d33a473187d52cdcf7e872fda Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:53:27 -0500 Subject: [PATCH 094/117] `Smt`: rename `update_leaf` --- src/merkle/smt/mod.rs | 11 +++++++---- src/merkle/smt/tests.rs | 22 +++++++++++----------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index f71f9f73..ed7a4519 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -67,7 +67,7 @@ impl Smt { let mut key_set_to_zero = BTreeSet::new(); for (key, value) in entries { - let old_value = tree.update_leaf(key, value); + let old_value = tree.insert(key, value); if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex( @@ -110,10 +110,13 @@ impl Smt { // STATE MUTATORS // -------------------------------------------------------------------------------------------- - /// Updates value of the leaf at the specified index returning the old leaf value. + /// Inserts a value at the specified key, returning the previous value associated with that key. + /// Recall that by definition, any key that hasn't been updated is associated with + /// [`Self::EMPTY_VALUE`]. /// - /// This also recomputes all hashes between the leaf and the root, updating the root itself. - pub fn update_leaf(&mut self, key: SmtKey, value: Word) -> Word { + /// This also recomputes all hashes between the leaf (associated with the key) and the root, + /// updating the root itself. + pub fn insert(&mut self, key: SmtKey, value: Word) -> Word { >::insert(self, key, value) } diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index a0c584da..e6522032 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -26,7 +26,7 @@ fn test_smt_insert_at_same_key() { let leaf_node = build_single_leaf_node(key_1, value_1); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - let old_value_1 = smt.update_leaf(key_1, value_1); + let old_value_1 = smt.insert(key_1, value_1); assert_eq!(old_value_1, EMPTY_WORD); assert_eq!(smt.root(), tree_root); @@ -37,7 +37,7 @@ fn test_smt_insert_at_same_key() { let leaf_node = build_single_leaf_node(key_1, value_2); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - let old_value_2 = smt.update_leaf(key_1, value_2); + let old_value_2 = smt.insert(key_1, value_2); assert_eq!(old_value_2, value_1); assert_eq!(smt.root(), tree_root); @@ -90,7 +90,7 @@ fn test_smt_insert_at_same_key_2() { ]); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - let old_value_1 = smt.update_leaf(key_1, value_1); + let old_value_1 = smt.insert(key_1, value_1); assert_eq!(old_value_1, EMPTY_WORD); assert_eq!(smt.root(), tree_root); @@ -104,7 +104,7 @@ fn test_smt_insert_at_same_key_2() { ]); let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - let old_value_2 = smt.update_leaf(key_1, value_2); + let old_value_2 = smt.insert(key_1, value_2); assert_eq!(old_value_2, value_1); assert_eq!(smt.root(), tree_root); @@ -150,7 +150,7 @@ fn test_smt_insert_multiple_values() { let leaf_node = build_single_leaf_node(key, value); let tree_root = store.set_node(smt.root(), key_index, leaf_node).unwrap().root; - let old_value = smt.update_leaf(key, value); + let old_value = smt.insert(key, value); assert_eq!(old_value, EMPTY_WORD); assert_eq!(smt.root(), tree_root); @@ -181,7 +181,7 @@ fn test_smt_removal() { // insert key-value 1 { - let old_value_1 = smt.update_leaf(key_1, value_1); + let old_value_1 = smt.insert(key_1, value_1); assert_eq!(old_value_1, EMPTY_WORD); assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, value_1))); @@ -189,7 +189,7 @@ fn test_smt_removal() { // insert key-value 2 { - let old_value_2 = smt.update_leaf(key_2, value_2); + let old_value_2 = smt.insert(key_2, value_2); assert_eq!(old_value_2, EMPTY_WORD); assert_eq!( @@ -200,7 +200,7 @@ fn test_smt_removal() { // insert key-value 3 { - let old_value_3 = smt.update_leaf(key_3, value_3); + let old_value_3 = smt.insert(key_3, value_3); assert_eq!(old_value_3, EMPTY_WORD); assert_eq!( @@ -211,7 +211,7 @@ fn test_smt_removal() { // remove key 3 { - let old_value_3 = smt.update_leaf(key_3, EMPTY_WORD); + let old_value_3 = smt.insert(key_3, EMPTY_WORD); assert_eq!(old_value_3, value_3); assert_eq!( @@ -222,7 +222,7 @@ fn test_smt_removal() { // remove key 2 { - let old_value_2 = smt.update_leaf(key_2, EMPTY_WORD); + let old_value_2 = smt.insert(key_2, EMPTY_WORD); assert_eq!(old_value_2, value_2); assert_eq!(smt.get_leaf(&key_2), SmtLeaf::Single((key_1, value_1))); @@ -230,7 +230,7 @@ fn test_smt_removal() { // remove key 1 { - let old_value_1 = smt.update_leaf(key_1, EMPTY_WORD); + let old_value_1 = smt.insert(key_1, EMPTY_WORD); assert_eq!(old_value_1, value_1); assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, EMPTY_WORD))); From 1265dead507093670a69a22169e0a23c9e041b06 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:55:01 -0500 Subject: [PATCH 095/117] `SimpleSmt`: rename `update_leaf` --- benches/smt.rs | 2 +- benches/store.rs | 2 +- src/merkle/simple_smt/mod.rs | 15 +++++++++------ src/merkle/simple_smt/tests.rs | 8 ++++---- src/merkle/smt/mod.rs | 2 +- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index d2800c4a..27d26e2f 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -34,7 +34,7 @@ fn smt_rpo(c: &mut Criterion) { &(key, leaf), |b, (key, leaf)| { b.iter(|| { - tree.update_leaf(black_box(LeafIndex::::new(*key).unwrap()), black_box(*leaf)); + tree.insert(black_box(LeafIndex::::new(*key).unwrap()), black_box(*leaf)); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index ed1b159c..43992db7 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -447,7 +447,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { || (rand_value::() % size_u64, random_word()), |(index, value)| { black_box( - smt.update_leaf(LeafIndex::::new(index).unwrap(), value), + smt.insert(LeafIndex::::new(index).unwrap(), value), ) }, BatchSize::SmallInput, diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 70bcf00e..1f0d814e 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -78,7 +78,7 @@ impl SimpleSmt { return Err(MerkleError::InvalidNumEntries(max_num_entries)); } - let old_value = tree.update_leaf(LeafIndex::::new(key)?, value); + let old_value = tree.insert(LeafIndex::::new(key)?, value); if old_value != Self::EMPTY_VALUE || key_set_to_zero.contains(&key) { return Err(MerkleError::DuplicateValuesForIndex(key)); @@ -168,10 +168,13 @@ impl SimpleSmt { // STATE MUTATORS // -------------------------------------------------------------------------------------------- - /// Updates value of the leaf at the specified index returning the old leaf value. + /// Inserts a value at the specified key, returning the previous value associated with that key. + /// Recall that by definition, any key that hasn't been updated is associated with + /// [`EMPTY_WORD`]. /// - /// This also recomputes all hashes between the leaf and the root, updating the root itself. - pub fn update_leaf(&mut self, key: LeafIndex, value: Word) -> Word { + /// This also recomputes all hashes between the leaf (associated with the key) and the root, + /// updating the root itself. + pub fn insert(&mut self, key: LeafIndex, value: Word) -> Word { >::insert(self, key, value) } @@ -296,11 +299,11 @@ impl TryApplyDiff for SimpleSmt { } for slot in diff.cleared_slots() { - self.update_leaf(LeafIndex::::new(*slot)?, Self::EMPTY_VALUE); + self.insert(LeafIndex::::new(*slot)?, Self::EMPTY_VALUE); } for (slot, value) in diff.updated_slots() { - self.update_leaf(LeafIndex::::new(*slot)?, *value); + self.insert(LeafIndex::::new(*slot)?, *value); } Ok(()) diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index c6552b1a..ac7c943c 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -54,7 +54,7 @@ fn build_sparse_tree() { let key = 6; let new_node = int_to_leaf(7); values[key as usize] = new_node; - let old_value = smt.update_leaf(LeafIndex::::new(key).unwrap(), new_node); + let old_value = smt.insert(LeafIndex::::new(key).unwrap(), new_node); let mt2 = MerkleTree::new(values.clone()).unwrap(); assert_eq!(mt2.root(), smt.root()); assert_eq!( @@ -67,7 +67,7 @@ fn build_sparse_tree() { let key = 2; let new_node = int_to_leaf(3); values[key as usize] = new_node; - let old_value = smt.update_leaf(LeafIndex::::new(key).unwrap(), new_node); + let old_value = smt.insert(LeafIndex::::new(key).unwrap(), new_node); let mt3 = MerkleTree::new(values).unwrap(); assert_eq!(mt3.root(), smt.root()); assert_eq!( @@ -158,7 +158,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf(LeafIndex::::new(key as u64).unwrap(), new_node); + let old_leaf = tree.insert(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); @@ -168,7 +168,7 @@ fn update_leaf() { expected_values[key] = new_node; let expected_tree = MerkleTree::new(expected_values.clone()).unwrap(); - let old_leaf = tree.update_leaf(LeafIndex::::new(key as u64).unwrap(), new_node); + let old_leaf = tree.insert(LeafIndex::::new(key as u64).unwrap(), new_node); assert_eq!(expected_tree.root(), tree.root); assert_eq!(old_leaf, *VALUES8[key]); } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index ed7a4519..5e77cc30 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -112,7 +112,7 @@ impl Smt { /// Inserts a value at the specified key, returning the previous value associated with that key. /// Recall that by definition, any key that hasn't been updated is associated with - /// [`Self::EMPTY_VALUE`]. + /// [`EMPTY_WORD`]. /// /// This also recomputes all hashes between the leaf (associated with the key) and the root, /// updating the root itself. From 7bc8eb09d69489ba440d3d31ad473d67165ddb91 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 10:57:09 -0500 Subject: [PATCH 096/117] fmt --- benches/store.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/benches/store.rs b/benches/store.rs index 43992db7..080c5cd9 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -446,9 +446,7 @@ fn update_leaf_simplesmt(c: &mut Criterion) { b.iter_batched( || (rand_value::() % size_u64, random_word()), |(index, value)| { - black_box( - smt.insert(LeafIndex::::new(index).unwrap(), value), - ) + black_box(smt.insert(LeafIndex::::new(index).unwrap(), value)) }, BatchSize::SmallInput, ) From 4b2f3c54b4fdb960cfac48f20dd7b39a64555ac8 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 15:01:21 -0500 Subject: [PATCH 097/117] get_leaf_path -> open --- benches/smt.rs | 2 +- benches/store.rs | 2 +- src/merkle/simple_smt/mod.rs | 4 ++-- src/merkle/simple_smt/tests.rs | 14 +++++++------- src/merkle/smt/mod.rs | 4 ++-- src/merkle/smt/tests.rs | 4 ++-- src/merkle/sparse_merkle_tree.rs | 2 +- src/merkle/store/tests.rs | 14 +++++++------- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index 27d26e2f..a0296d8c 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -52,7 +52,7 @@ fn smt_rpo(c: &mut Criterion) { &key, |b, key| { b.iter(|| { - tree.get_leaf_path(black_box(LeafIndex::::new(*key).unwrap())); + tree.open(black_box(LeafIndex::::new(*key).unwrap())); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index 080c5cd9..f59a917b 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -297,7 +297,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { || random_index(size_u64, SMT_MAX_DEPTH), |index| { black_box( - smt.get_leaf_path(LeafIndex::::new(index.value()).unwrap()), + smt.open(LeafIndex::::new(index.value()).unwrap()), ) }, BatchSize::SmallInput, diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 1f0d814e..83478f25 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -125,8 +125,8 @@ impl SimpleSmt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn get_leaf_path(&self, key: LeafIndex) -> MerklePath { - >::get_leaf_path(self, key) + pub fn open(&self, key: LeafIndex) -> MerklePath { + >::open(self, key) } /// Returns a node at the specified index. diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index ac7c943c..d0a31a43 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -59,7 +59,7 @@ fn build_sparse_tree() { assert_eq!(mt2.root(), smt.root()); assert_eq!( mt2.get_path(NodeIndex::make(3, 6)).unwrap(), - smt.get_leaf_path(LeafIndex::<3>::new(6).unwrap()) + smt.open(LeafIndex::<3>::new(6).unwrap()) ); assert_eq!(old_value, EMPTY_WORD); @@ -72,7 +72,7 @@ fn build_sparse_tree() { assert_eq!(mt3.root(), smt.root()); assert_eq!( mt3.get_path(NodeIndex::make(3, 2)).unwrap(), - smt.get_leaf_path(LeafIndex::<3>::new(2).unwrap()) + smt.open(LeafIndex::<3>::new(2).unwrap()) ); assert_eq!(old_value, EMPTY_WORD); } @@ -108,10 +108,10 @@ fn test_depth2_tree() { assert_eq!(VALUES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap()); // check get_path(): depth 2 - assert_eq!(vec![VALUES4[1], node3], *tree.get_leaf_path(LeafIndex::<2>::new(0).unwrap())); - assert_eq!(vec![VALUES4[0], node3], *tree.get_leaf_path(LeafIndex::<2>::new(1).unwrap())); - assert_eq!(vec![VALUES4[3], node2], *tree.get_leaf_path(LeafIndex::<2>::new(2).unwrap())); - assert_eq!(vec![VALUES4[2], node2], *tree.get_leaf_path(LeafIndex::<2>::new(3).unwrap())); + assert_eq!(vec![VALUES4[1], node3], *tree.open(LeafIndex::<2>::new(0).unwrap())); + assert_eq!(vec![VALUES4[0], node3], *tree.open(LeafIndex::<2>::new(1).unwrap())); + assert_eq!(vec![VALUES4[3], node2], *tree.open(LeafIndex::<2>::new(2).unwrap())); + assert_eq!(vec![VALUES4[2], node2], *tree.open(LeafIndex::<2>::new(3).unwrap())); } #[test] @@ -213,7 +213,7 @@ fn small_tree_opening_is_consistent() { ]; for (key, path) in cases { - let opening = tree.get_leaf_path(LeafIndex::<3>::new(key).unwrap()); + let opening = tree.open(LeafIndex::<3>::new(key).unwrap()); assert_eq!(path, *opening); } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 5e77cc30..350342b1 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -103,8 +103,8 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn get_leaf_path(&self, key: SmtKey) -> MerklePath { - >::get_leaf_path(self, key) + pub fn open(&self, key: SmtKey) -> MerklePath { + >::open(self, key) } // STATE MUTATORS diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index e6522032..7d8b03b9 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -156,7 +156,7 @@ fn test_smt_insert_multiple_values() { assert_eq!(smt.root(), tree_root); let expected_path = store.get_path(tree_root, key_index).unwrap(); - assert_eq!(smt.get_leaf_path(key), expected_path.path); + assert_eq!(smt.open(key), expected_path.path); } } @@ -251,7 +251,7 @@ fn test_smt_path_to_keys_in_same_leaf_are_equal() { let smt = Smt::with_entries([(key_1, value_1), (key_2, value_2)]).unwrap(); - assert_eq!(smt.get_leaf_path(key_1), smt.get_leaf_path(key_2)); + assert_eq!(smt.open(key_1), smt.open(key_2)); } // HELPERS diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 24a135e4..0aee6111 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -55,7 +55,7 @@ pub(crate) trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn get_leaf_path(&self, key: Self::Key) -> MerklePath { + fn open(&self, key: Self::Key) -> MerklePath { let mut index: NodeIndex = { let leaf_index: LeafIndex = key.into(); leaf_index.into() diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index b3f362ca..70347c10 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -182,7 +182,7 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; - let smt_path = smt.get_leaf_path(LeafIndex::::new(0)?); + let smt_path = smt.open(LeafIndex::::new(0)?); assert_eq!( store_path.value, RpoDigest::default(), @@ -301,7 +301,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(0).unwrap()), + smt.open(LeafIndex::::new(0).unwrap()), result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -312,7 +312,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(1).unwrap()), + smt.open(LeafIndex::::new(1).unwrap()), result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -323,7 +323,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(2).unwrap()), + smt.open(LeafIndex::::new(2).unwrap()), result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -334,7 +334,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(3).unwrap()), + smt.open(LeafIndex::::new(3).unwrap()), result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -346,7 +346,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.get_leaf_path(LeafIndex::::new(4).unwrap()), + smt.open(LeafIndex::::new(4).unwrap()), result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); @@ -563,7 +563,7 @@ fn test_constructors() -> Result<(), MerkleError> { for key in KEYS4 { let index = NodeIndex::make(DEPTH, key); let value_path = store.get_path(smt.root(), index)?; - assert_eq!(smt.get_leaf_path(LeafIndex::::new(key).unwrap()), value_path.path); + assert_eq!(smt.open(LeafIndex::::new(key).unwrap()), value_path.path); } let d = 2; From 40c3b7638e1db7ee0c3d714aeb0bc0d08eba89de Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 15:08:23 -0500 Subject: [PATCH 098/117] `SparseMerkleTree::Opening` type --- benches/store.rs | 4 +--- src/merkle/simple_smt/mod.rs | 1 + src/merkle/smt/mod.rs | 1 + src/merkle/sparse_merkle_tree.rs | 2 ++ 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/benches/store.rs b/benches/store.rs index f59a917b..ede98bed 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -296,9 +296,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| { - black_box( - smt.open(LeafIndex::::new(index.value()).unwrap()), - ) + black_box(smt.open(LeafIndex::::new(index.value()).unwrap())) }, BatchSize::SmallInput, ) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 83478f25..c337729a 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -243,6 +243,7 @@ impl SparseMerkleTree for SimpleSmt { type Key = LeafIndex; type Value = Word; type Leaf = Word; + type Opening = (MerklePath, Word); const EMPTY_VALUE: Self::Value = EMPTY_WORD; diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 350342b1..3800bfb7 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -161,6 +161,7 @@ impl SparseMerkleTree for Smt { type Key = SmtKey; type Value = Word; type Leaf = SmtLeaf; + type Opening = (MerklePath, SmtLeaf); const EMPTY_VALUE: Self::Value = EMPTY_WORD; diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 0aee6111..3e1f25a5 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -45,6 +45,8 @@ pub(crate) trait SparseMerkleTree { type Value: Clone + PartialEq; /// The type for a leaf type Leaf; + /// The type for an opening (i.e. a "proof") of a leaf + type Opening: Into<(MerklePath, Self::Leaf)>; /// The default value used to compute the hash of empty leaves const EMPTY_VALUE: Self::Value; From fd607694ee4602d0bc9100e1de752386226a2079 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 15:27:39 -0500 Subject: [PATCH 099/117] `open()` returns `Self::Opening` --- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/simple_smt/tests.rs | 14 +++++++------- src/merkle/smt/mod.rs | 2 +- src/merkle/smt/tests.rs | 2 +- src/merkle/sparse_merkle_tree.rs | 28 +++++++++++++++++----------- src/merkle/store/tests.rs | 14 +++++++------- 6 files changed, 34 insertions(+), 28 deletions(-) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index c337729a..6a05a6d1 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -125,7 +125,7 @@ impl SimpleSmt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: LeafIndex) -> MerklePath { + pub fn open(&self, key: LeafIndex) -> (MerklePath, Word) { >::open(self, key) } diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index d0a31a43..b952adfa 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -59,7 +59,7 @@ fn build_sparse_tree() { assert_eq!(mt2.root(), smt.root()); assert_eq!( mt2.get_path(NodeIndex::make(3, 6)).unwrap(), - smt.open(LeafIndex::<3>::new(6).unwrap()) + smt.open(LeafIndex::<3>::new(6).unwrap()).0 ); assert_eq!(old_value, EMPTY_WORD); @@ -72,7 +72,7 @@ fn build_sparse_tree() { assert_eq!(mt3.root(), smt.root()); assert_eq!( mt3.get_path(NodeIndex::make(3, 2)).unwrap(), - smt.open(LeafIndex::<3>::new(2).unwrap()) + smt.open(LeafIndex::<3>::new(2).unwrap()).0 ); assert_eq!(old_value, EMPTY_WORD); } @@ -108,10 +108,10 @@ fn test_depth2_tree() { assert_eq!(VALUES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap()); // check get_path(): depth 2 - assert_eq!(vec![VALUES4[1], node3], *tree.open(LeafIndex::<2>::new(0).unwrap())); - assert_eq!(vec![VALUES4[0], node3], *tree.open(LeafIndex::<2>::new(1).unwrap())); - assert_eq!(vec![VALUES4[3], node2], *tree.open(LeafIndex::<2>::new(2).unwrap())); - assert_eq!(vec![VALUES4[2], node2], *tree.open(LeafIndex::<2>::new(3).unwrap())); + assert_eq!(vec![VALUES4[1], node3], *tree.open(LeafIndex::<2>::new(0).unwrap()).0); + assert_eq!(vec![VALUES4[0], node3], *tree.open(LeafIndex::<2>::new(1).unwrap()).0); + assert_eq!(vec![VALUES4[3], node2], *tree.open(LeafIndex::<2>::new(2).unwrap()).0); + assert_eq!(vec![VALUES4[2], node2], *tree.open(LeafIndex::<2>::new(3).unwrap()).0); } #[test] @@ -213,7 +213,7 @@ fn small_tree_opening_is_consistent() { ]; for (key, path) in cases { - let opening = tree.open(LeafIndex::<3>::new(key).unwrap()); + let (opening, _) = tree.open(LeafIndex::<3>::new(key).unwrap()); assert_eq!(path, *opening); } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 3800bfb7..624da8d1 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -103,7 +103,7 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: SmtKey) -> MerklePath { + pub fn open(&self, key: SmtKey) -> (MerklePath, SmtLeaf) { >::open(self, key) } diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 7d8b03b9..02b10534 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -156,7 +156,7 @@ fn test_smt_insert_multiple_values() { assert_eq!(smt.root(), tree_root); let expected_path = store.get_path(tree_root, key_index).unwrap(); - assert_eq!(smt.open(key), expected_path.path); + assert_eq!(smt.open(key).0, expected_path.path); } } diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 3e1f25a5..1400bc00 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -46,7 +46,7 @@ pub(crate) trait SparseMerkleTree { /// The type for a leaf type Leaf; /// The type for an opening (i.e. a "proof") of a leaf - type Opening: Into<(MerklePath, Self::Leaf)>; + type Opening: From<(MerklePath, Self::Leaf)>; /// The default value used to compute the hash of empty leaves const EMPTY_VALUE: Self::Value; @@ -57,22 +57,28 @@ pub(crate) trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn open(&self, key: Self::Key) -> MerklePath { + fn open(&self, key: Self::Key) -> Self::Opening { + let leaf = self.get_leaf(&key); + let mut index: NodeIndex = { let leaf_index: LeafIndex = key.into(); leaf_index.into() }; - let mut path = Vec::with_capacity(index.depth() as usize); - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = self.get_inner_node(index); - let value = if is_right { left } else { right }; - path.push(value); - } + let merkle_path = { + let mut path = Vec::with_capacity(index.depth() as usize); + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = self.get_inner_node(index); + let value = if is_right { left } else { right }; + path.push(value); + } + + MerklePath::new(path) + }; - MerklePath::new(path) + (merkle_path, leaf).into() } /// Inserts a value at the specified key, returning the previous value associated with that key. diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 70347c10..b1dd801c 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -182,7 +182,7 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; - let smt_path = smt.open(LeafIndex::::new(0)?); + let smt_path = smt.open(LeafIndex::::new(0)?).0; assert_eq!( store_path.value, RpoDigest::default(), @@ -301,7 +301,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(0).unwrap()), + smt.open(LeafIndex::::new(0).unwrap()).0, result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -312,7 +312,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(1).unwrap()), + smt.open(LeafIndex::::new(1).unwrap()).0, result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -323,7 +323,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(2).unwrap()), + smt.open(LeafIndex::::new(2).unwrap()).0, result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -334,7 +334,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(3).unwrap()), + smt.open(LeafIndex::::new(3).unwrap()).0, result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -346,7 +346,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(4).unwrap()), + smt.open(LeafIndex::::new(4).unwrap()).0, result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); @@ -563,7 +563,7 @@ fn test_constructors() -> Result<(), MerkleError> { for key in KEYS4 { let index = NodeIndex::make(DEPTH, key); let value_path = store.get_path(smt.root(), index)?; - assert_eq!(smt.open(LeafIndex::::new(key).unwrap()), value_path.path); + assert_eq!(smt.open(LeafIndex::::new(key).unwrap()).0, value_path.path); } let d = 2; From 9d683b62a78d4691a5a07401180a20a061c65e55 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 16:03:35 -0500 Subject: [PATCH 100/117] Introduce `key_to_leaf_index` --- src/merkle/mod.rs | 2 +- src/merkle/simple_smt/mod.rs | 4 ++ src/merkle/smt/mod.rs | 75 ++++++++++---------------------- src/merkle/smt/tests.rs | 46 ++++++++++---------- src/merkle/sparse_merkle_tree.rs | 16 +++++-- 5 files changed, 64 insertions(+), 79 deletions(-) diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 5d8b5421..8bbc38ac 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -31,7 +31,7 @@ pub(crate) mod sparse_merkle_tree; pub use sparse_merkle_tree::{LeafIndex, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod smt; -pub use smt::{Smt, SmtKey, SmtLeaf, SMT_DEPTH}; +pub use smt::{Smt, SmtLeaf, SMT_DEPTH}; mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index 6a05a6d1..a486d18b 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -286,6 +286,10 @@ impl SparseMerkleTree for SimpleSmt { // `SimpleSmt` takes the leaf value itself as the hash leaf.into() } + + fn key_to_leaf_index(leaf: &LeafIndex) -> LeafIndex { + *leaf + } } // TRY APPLY DIFF diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 624da8d1..ee684893 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -57,7 +57,7 @@ impl Smt { /// - The number of entries exceeds 2^63 entries. /// - The provided entries contain multiple values for the same key. pub fn with_entries( - entries: impl IntoIterator, + entries: impl IntoIterator, ) -> Result { // create an empty tree let mut tree = Self::new(); @@ -91,7 +91,7 @@ impl Smt { } /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &SmtKey) -> SmtLeaf { + pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { >::get_leaf(self, key) } @@ -103,7 +103,7 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: SmtKey) -> (MerklePath, SmtLeaf) { + pub fn open(&self, key: RpoDigest) -> (MerklePath, SmtLeaf) { >::open(self, key) } @@ -116,7 +116,7 @@ impl Smt { /// /// This also recomputes all hashes between the leaf (associated with the key) and the root, /// updating the root itself. - pub fn insert(&mut self, key: SmtKey, value: Word) -> Word { + pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word { >::insert(self, key, value) } @@ -125,10 +125,10 @@ impl Smt { /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty /// value, such that this is indeed an insertion. - fn perform_insert(&mut self, key: SmtKey, value: Word) -> Option { + fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option { debug_assert_ne!(value, Self::EMPTY_VALUE); - let leaf_index: LeafIndex = key.into(); + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); match self.leaves.get_mut(&leaf_index.value()) { Some(leaf) => leaf.insert(key, value), @@ -141,8 +141,8 @@ impl Smt { } /// Removes key-value pair at leaf index pointed to by `key` if it exists. - fn perform_remove(&mut self, key: SmtKey) -> Option { - let leaf_index: LeafIndex = key.into(); + fn perform_remove(&mut self, key: RpoDigest) -> Option { + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { let (old_value, is_empty) = leaf.remove(key); @@ -158,7 +158,7 @@ impl Smt { } impl SparseMerkleTree for Smt { - type Key = SmtKey; + type Key = RpoDigest; type Value = Word; type Leaf = SmtLeaf; type Opening = (MerklePath, SmtLeaf); @@ -194,7 +194,7 @@ impl SparseMerkleTree for Smt { } } - fn get_leaf(&self, key: &Self::Key) -> Self::Leaf { + fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { let leaf_pos = LeafIndex::::from(*key).value(); match self.leaves.get(&leaf_pos) { @@ -206,6 +206,11 @@ impl SparseMerkleTree for Smt { fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { leaf.hash() } + + fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex { + let most_significant_felt = key[3]; + LeafIndex::new_max_depth(most_significant_felt.as_int()) + } } impl Default for Smt { @@ -214,46 +219,14 @@ impl Default for Smt { } } -// SMT KEY -// ================================================================================================ - -/// Represents a key (256 bits) for the Smt. -/// -/// The most significant `u64` determines the corresponding leaf index when inserting values into -/// the Smt. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct SmtKey { - word: RpoDigest, -} - -impl From for LeafIndex { - fn from(key: SmtKey) -> Self { - let most_significant_felt = key.word[3]; - Self::new_max_depth(most_significant_felt.as_int()) - } -} - -impl From for SmtKey { - fn from(digest: RpoDigest) -> Self { - Self { word: digest } - } -} - -impl From for SmtKey { - fn from(word: Word) -> Self { - Self { word: word.into() } - } -} - // LEAF // ================================================================================================ #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum SmtLeaf { - Single((SmtKey, Word)), - Multiple(Vec<(SmtKey, Word)>), + Single((RpoDigest, Word)), + Multiple(Vec<(RpoDigest, Word)>), } impl SmtLeaf { @@ -273,7 +246,7 @@ impl SmtLeaf { /// Compute the hash of the leaf pub fn hash(&self) -> RpoDigest { match self { - SmtLeaf::Single((key, value)) => Rpo256::merge(&[key.word, value.into()]), + SmtLeaf::Single((key, value)) => Rpo256::merge(&[*key, value.into()]), SmtLeaf::Multiple(kvs) => { let elements: Vec = kvs.iter().copied().flat_map(kv_to_elements).collect(); Rpo256::hash_elements(&elements) @@ -286,7 +259,7 @@ impl SmtLeaf { /// Insert key-value pair into the leaf; return the previous value associated with `key`, if /// any. - fn insert(&mut self, key: SmtKey, value: Word) -> Option { + fn insert(&mut self, key: RpoDigest, value: Word) -> Option { match self { SmtLeaf::Single(kv_pair) => { if kv_pair.0 == key { @@ -327,7 +300,7 @@ impl SmtLeaf { /// Remove key-value pair into the leaf stored at key; return the previous value associated with /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf became /// empty, and must be removed from the data structure it is contained in. - fn remove(&mut self, key: SmtKey) -> (Option, bool) { + fn remove(&mut self, key: RpoDigest) -> (Option, bool) { match self { SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { if *key_at_leaf == key { @@ -370,8 +343,8 @@ impl SmtLeaf { // ================================================================================================ /// Converts a key-value tuple to an iterator of `Felt`s -fn kv_to_elements((key, value): (SmtKey, Word)) -> impl Iterator { - let key_elements = key.word.into_iter(); +fn kv_to_elements((key, value): (RpoDigest, Word)) -> impl Iterator { + let key_elements = key.into_iter(); let value_elements = value.into_iter(); key_elements.chain(value_elements) @@ -379,8 +352,8 @@ fn kv_to_elements((key, value): (SmtKey, Word)) -> impl Iterator { /// Compares two keys, compared element-by-element using their integer representations starting with /// the most significant element. -fn cmp_keys(key_1: SmtKey, key_2: SmtKey) -> Ordering { - for (v1, v2) in key_1.word.iter().zip(key_2.word.iter()).rev() { +fn cmp_keys(key_1: RpoDigest, key_2: RpoDigest) -> Ordering { + for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() { let v1 = v1.as_int(); let v2 = v2.as_int(); if v1 != v2 { diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index 02b10534..d341cab3 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -11,10 +11,10 @@ fn test_smt_insert_at_same_key() { assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); - let key_1: SmtKey = { + let key_1: RpoDigest = { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) }; let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); @@ -48,10 +48,10 @@ fn test_smt_insert_at_same_key() { /// only the case where the leaf type is `SmtLeaf::Multiple` #[test] fn test_smt_insert_at_same_key_2() { - let key_already_present: SmtKey = { + let key_already_present: RpoDigest = { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - RpoDigest::from([ONE + ONE, ONE + ONE, ONE + ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE + ONE, ONE + ONE, ONE + ONE, Felt::new(raw)]) }; let key_already_present_index: NodeIndex = LeafIndex::::from(key_already_present).into(); @@ -69,10 +69,10 @@ fn test_smt_insert_at_same_key_2() { store }; - let key_1: SmtKey = { + let key_1: RpoDigest = { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) }; let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); @@ -120,22 +120,22 @@ fn test_smt_insert_multiple_values() { assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); - let key_1: SmtKey = { + let key_1: RpoDigest = { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) }; - let key_2: SmtKey = { + let key_2: RpoDigest = { let raw = 0b_11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111_u64; - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) }; - let key_3: SmtKey = { + let key_3: RpoDigest = { let raw = 0b_00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000_u64; - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into() + RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) }; let value_1 = [ONE; WORD_SIZE]; @@ -169,11 +169,11 @@ fn test_smt_removal() { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - let key_1: SmtKey = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into(); - let key_2: SmtKey = - RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]).into(); - let key_3: SmtKey = - RpoDigest::from([3_u64.into(), 3_u64.into(), 3_u64.into(), Felt::new(raw)]).into(); + let key_1: RpoDigest = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]); + let key_2: RpoDigest = + RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]); + let key_3: RpoDigest = + RpoDigest::from([3_u64.into(), 3_u64.into(), 3_u64.into(), Felt::new(raw)]); let value_1 = [ONE; WORD_SIZE]; let value_2 = [2_u64.into(); WORD_SIZE]; @@ -242,9 +242,9 @@ fn test_smt_removal() { fn test_smt_path_to_keys_in_same_leaf_are_equal() { let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - let key_1: SmtKey = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]).into(); - let key_2: SmtKey = - RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]).into(); + let key_1: RpoDigest = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]); + let key_2: RpoDigest = + RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]); let value_1 = [ONE; WORD_SIZE]; let value_2 = [2_u64.into(); WORD_SIZE]; @@ -257,15 +257,15 @@ fn test_smt_path_to_keys_in_same_leaf_are_equal() { // HELPERS // -------------------------------------------------------------------------------------------- -fn build_single_leaf_node(key: SmtKey, value: Word) -> RpoDigest { +fn build_single_leaf_node(key: RpoDigest, value: Word) -> RpoDigest { SmtLeaf::Single((key, value)).hash() } -fn build_multiple_leaf_node(kv_pairs: &[(SmtKey, Word)]) -> RpoDigest { +fn build_multiple_leaf_node(kv_pairs: &[(RpoDigest, Word)]) -> RpoDigest { let elements: Vec = kv_pairs .iter() .flat_map(|(key, value)| { - let key_elements = key.word.into_iter(); + let key_elements = key.into_iter(); let value_elements = (*value).into_iter(); key_elements.chain(value_elements) diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index 1400bc00..d01000a0 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -39,8 +39,8 @@ pub const SMT_MAX_DEPTH: u8 = 64; /// /// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. pub(crate) trait SparseMerkleTree { - /// The type for a key, which must be convertible into a `u64` infaillibly - type Key: Into> + Clone; + /// The type for a key + type Key: Clone; /// The type for a value type Value: Clone + PartialEq; /// The type for a leaf @@ -61,7 +61,7 @@ pub(crate) trait SparseMerkleTree { let leaf = self.get_leaf(&key); let mut index: NodeIndex = { - let leaf_index: LeafIndex = key.into(); + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); leaf_index.into() }; @@ -97,7 +97,7 @@ pub(crate) trait SparseMerkleTree { let leaf = self.get_leaf(&key); let node_index = { - let leaf_index: LeafIndex = key.into(); + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); leaf_index.into() }; @@ -148,6 +148,8 @@ pub(crate) trait SparseMerkleTree { /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; + + fn key_to_leaf_index(key: &Self::Key) -> LeafIndex; } // INNER NODE @@ -225,3 +227,9 @@ impl From for LeafIndex { Self::new_max_depth(value[3].as_int()) } } + +impl From for LeafIndex { + fn from(value: RpoDigest) -> Self { + Word::from(value).into() + } +} From 3ba0bb0831503363810e70eaed15f67b855474af Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 16:07:17 -0500 Subject: [PATCH 101/117] open() takes a reference to `key` --- benches/smt.rs | 2 +- benches/store.rs | 2 +- src/merkle/simple_smt/mod.rs | 2 +- src/merkle/simple_smt/tests.rs | 14 +++++++------- src/merkle/smt/mod.rs | 2 +- src/merkle/smt/tests.rs | 4 ++-- src/merkle/sparse_merkle_tree.rs | 6 +++--- src/merkle/store/tests.rs | 14 +++++++------- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/benches/smt.rs b/benches/smt.rs index a0296d8c..a8c410f9 100644 --- a/benches/smt.rs +++ b/benches/smt.rs @@ -52,7 +52,7 @@ fn smt_rpo(c: &mut Criterion) { &key, |b, key| { b.iter(|| { - tree.open(black_box(LeafIndex::::new(*key).unwrap())); + tree.open(black_box(&LeafIndex::::new(*key).unwrap())); }); }, ); diff --git a/benches/store.rs b/benches/store.rs index ede98bed..ca1bbcd1 100644 --- a/benches/store.rs +++ b/benches/store.rs @@ -296,7 +296,7 @@ fn get_leaf_path_simplesmt(c: &mut Criterion) { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| { - black_box(smt.open(LeafIndex::::new(index.value()).unwrap())) + black_box(smt.open(&LeafIndex::::new(index.value()).unwrap())) }, BatchSize::SmallInput, ) diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/simple_smt/mod.rs index a486d18b..8a167755 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/simple_smt/mod.rs @@ -125,7 +125,7 @@ impl SimpleSmt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: LeafIndex) -> (MerklePath, Word) { + pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { >::open(self, key) } diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/simple_smt/tests.rs index b952adfa..3c74cef6 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/simple_smt/tests.rs @@ -59,7 +59,7 @@ fn build_sparse_tree() { assert_eq!(mt2.root(), smt.root()); assert_eq!( mt2.get_path(NodeIndex::make(3, 6)).unwrap(), - smt.open(LeafIndex::<3>::new(6).unwrap()).0 + smt.open(&LeafIndex::<3>::new(6).unwrap()).0 ); assert_eq!(old_value, EMPTY_WORD); @@ -72,7 +72,7 @@ fn build_sparse_tree() { assert_eq!(mt3.root(), smt.root()); assert_eq!( mt3.get_path(NodeIndex::make(3, 2)).unwrap(), - smt.open(LeafIndex::<3>::new(2).unwrap()).0 + smt.open(&LeafIndex::<3>::new(2).unwrap()).0 ); assert_eq!(old_value, EMPTY_WORD); } @@ -108,10 +108,10 @@ fn test_depth2_tree() { assert_eq!(VALUES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap()); // check get_path(): depth 2 - assert_eq!(vec![VALUES4[1], node3], *tree.open(LeafIndex::<2>::new(0).unwrap()).0); - assert_eq!(vec![VALUES4[0], node3], *tree.open(LeafIndex::<2>::new(1).unwrap()).0); - assert_eq!(vec![VALUES4[3], node2], *tree.open(LeafIndex::<2>::new(2).unwrap()).0); - assert_eq!(vec![VALUES4[2], node2], *tree.open(LeafIndex::<2>::new(3).unwrap()).0); + assert_eq!(vec![VALUES4[1], node3], *tree.open(&LeafIndex::<2>::new(0).unwrap()).0); + assert_eq!(vec![VALUES4[0], node3], *tree.open(&LeafIndex::<2>::new(1).unwrap()).0); + assert_eq!(vec![VALUES4[3], node2], *tree.open(&LeafIndex::<2>::new(2).unwrap()).0); + assert_eq!(vec![VALUES4[2], node2], *tree.open(&LeafIndex::<2>::new(3).unwrap()).0); } #[test] @@ -213,7 +213,7 @@ fn small_tree_opening_is_consistent() { ]; for (key, path) in cases { - let (opening, _) = tree.open(LeafIndex::<3>::new(key).unwrap()); + let (opening, _) = tree.open(&LeafIndex::<3>::new(key).unwrap()); assert_eq!(path, *opening); } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index ee684893..b5f0624b 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -103,7 +103,7 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: RpoDigest) -> (MerklePath, SmtLeaf) { + pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { >::open(self, key) } diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/tests.rs index d341cab3..66b40ec5 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/tests.rs @@ -156,7 +156,7 @@ fn test_smt_insert_multiple_values() { assert_eq!(smt.root(), tree_root); let expected_path = store.get_path(tree_root, key_index).unwrap(); - assert_eq!(smt.open(key).0, expected_path.path); + assert_eq!(smt.open(&key).0, expected_path.path); } } @@ -251,7 +251,7 @@ fn test_smt_path_to_keys_in_same_leaf_are_equal() { let smt = Smt::with_entries([(key_1, value_1), (key_2, value_2)]).unwrap(); - assert_eq!(smt.open(key_1), smt.open(key_2)); + assert_eq!(smt.open(&key_1), smt.open(&key_2)); } // HELPERS diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs index d01000a0..5cc7a0ff 100644 --- a/src/merkle/sparse_merkle_tree.rs +++ b/src/merkle/sparse_merkle_tree.rs @@ -57,11 +57,11 @@ pub(crate) trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn open(&self, key: Self::Key) -> Self::Opening { - let leaf = self.get_leaf(&key); + fn open(&self, key: &Self::Key) -> Self::Opening { + let leaf = self.get_leaf(key); let mut index: NodeIndex = { - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); + let leaf_index: LeafIndex = Self::key_to_leaf_index(key); leaf_index.into() }; diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index b1dd801c..0ef51354 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -182,7 +182,7 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; - let smt_path = smt.open(LeafIndex::::new(0)?).0; + let smt_path = smt.open(&LeafIndex::::new(0)?).0; assert_eq!( store_path.value, RpoDigest::default(), @@ -301,7 +301,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(0).unwrap()).0, + smt.open(&LeafIndex::::new(0).unwrap()).0, result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -312,7 +312,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(1).unwrap()).0, + smt.open(&LeafIndex::::new(1).unwrap()).0, result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -323,7 +323,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(2).unwrap()).0, + smt.open(&LeafIndex::::new(2).unwrap()).0, result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -334,7 +334,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(3).unwrap()).0, + smt.open(&LeafIndex::::new(3).unwrap()).0, result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -346,7 +346,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.open(LeafIndex::::new(4).unwrap()).0, + smt.open(&LeafIndex::::new(4).unwrap()).0, result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); @@ -563,7 +563,7 @@ fn test_constructors() -> Result<(), MerkleError> { for key in KEYS4 { let index = NodeIndex::make(DEPTH, key); let value_path = store.get_path(smt.root(), index)?; - assert_eq!(smt.open(LeafIndex::::new(key).unwrap()).0, value_path.path); + assert_eq!(smt.open(&LeafIndex::::new(key).unwrap()).0, value_path.path); } let d = 2; From 4eee502f3a1b08b7de7be71d5c9e8b7a638a08f8 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 16:33:34 -0500 Subject: [PATCH 102/117] new directory structure --- src/merkle/mod.rs | 8 +- src/merkle/smt/full/mod.rs | 367 ++++++++++++++ src/merkle/smt/{ => full}/tests.rs | 6 +- src/merkle/smt/mod.rs | 472 +++++++----------- src/merkle/{simple_smt => smt/simple}/mod.rs | 12 +- .../{simple_smt => smt/simple}/tests.rs | 8 +- src/merkle/sparse_merkle_tree.rs | 235 --------- 7 files changed, 558 insertions(+), 550 deletions(-) create mode 100644 src/merkle/smt/full/mod.rs rename src/merkle/smt/{ => full}/tests.rs (99%) rename src/merkle/{simple_smt => smt/simple}/mod.rs (97%) rename src/merkle/{simple_smt => smt/simple}/tests.rs (98%) delete mode 100644 src/merkle/sparse_merkle_tree.rs diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index 8bbc38ac..edd75d40 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -24,14 +24,8 @@ pub use merkle_tree::{path_to_text, tree_to_text, MerkleTree}; mod path; pub use path::{MerklePath, RootPath, ValuePath}; -mod simple_smt; -pub use simple_smt::SimpleSmt; - -pub(crate) mod sparse_merkle_tree; -pub use sparse_merkle_tree::{LeafIndex, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; - mod smt; -pub use smt::{Smt, SmtLeaf, SMT_DEPTH}; +pub use smt::{LeafIndex, SimpleSmt, Smt, SmtLeaf, SMT_DEPTH, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs new file mode 100644 index 00000000..f8c17aca --- /dev/null +++ b/src/merkle/smt/full/mod.rs @@ -0,0 +1,367 @@ +use core::cmp::Ordering; + +use winter_math::StarkField; + +use crate::hash::rpo::Rpo256; +use crate::merkle::EmptySubtreeRoots; +use crate::utils::{ + collections::{BTreeMap, BTreeSet, Vec}, + vec, +}; +use crate::{Felt, EMPTY_WORD}; + +use super::{ + InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, +}; + +#[cfg(test)] +mod tests; + +// CONSTANTS +// ================================================================================================ + +pub const SMT_DEPTH: u8 = 64; + +// SMT +// ================================================================================================ + +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub struct Smt { + root: RpoDigest, + leaves: BTreeMap, + inner_nodes: BTreeMap, +} + +impl Smt { + // CONSTRUCTORS + // -------------------------------------------------------------------------------------------- + + /// Returns a new [NewSmt]. + /// + /// All leaves in the returned tree are set to [ZERO; 4]. + pub fn new() -> Self { + let root = *EmptySubtreeRoots::entry(SMT_DEPTH, 0); + + Self { + root, + leaves: BTreeMap::new(), + inner_nodes: BTreeMap::new(), + } + } + + /// Returns a new [SimpleSmt] instantiated with leaves set as specified by the provided entries. + /// + /// All leaves omitted from the entries list are set to [ZERO; 4]. + /// + /// # Errors + /// Returns an error if: + /// - The number of entries exceeds 2^63 entries. + /// - The provided entries contain multiple values for the same key. + pub fn with_entries( + entries: impl IntoIterator, + ) -> Result { + // create an empty tree + let mut tree = Self::new(); + + // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so + // entries with the empty value need additional tracking. + let mut key_set_to_zero = BTreeSet::new(); + + for (key, value) in entries { + let old_value = tree.insert(key, value); + + if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { + return Err(MerkleError::DuplicateValuesForIndex( + LeafIndex::::from(key).value(), + )); + } + + if value == EMPTY_WORD { + key_set_to_zero.insert(key); + }; + } + Ok(tree) + } + + // PUBLIC ACCESSORS + // -------------------------------------------------------------------------------------------- + + /// Returns the root of the tree + pub fn root(&self) -> RpoDigest { + >::root(self) + } + + /// Returns the leaf at the specified index. + pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { + >::get_leaf(self, key) + } + + /// Returns the depth of the tree + pub const fn depth(&self) -> u8 { + SMT_DEPTH + } + + /// Returns a Merkle path from the leaf node specified by the key to the root. + /// + /// The node itself is not included in the path. + pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { + >::open(self, key) + } + + // STATE MUTATORS + // -------------------------------------------------------------------------------------------- + + /// Inserts a value at the specified key, returning the previous value associated with that key. + /// Recall that by definition, any key that hasn't been updated is associated with + /// [`EMPTY_WORD`]. + /// + /// This also recomputes all hashes between the leaf (associated with the key) and the root, + /// updating the root itself. + pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word { + >::insert(self, key, value) + } + + // HELPERS + // -------------------------------------------------------------------------------------------- + + /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty + /// value, such that this is indeed an insertion. + fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option { + debug_assert_ne!(value, Self::EMPTY_VALUE); + + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); + + match self.leaves.get_mut(&leaf_index.value()) { + Some(leaf) => leaf.insert(key, value), + None => { + self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); + + None + } + } + } + + /// Removes key-value pair at leaf index pointed to by `key` if it exists. + fn perform_remove(&mut self, key: RpoDigest) -> Option { + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); + + if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { + let (old_value, is_empty) = leaf.remove(key); + if is_empty { + self.leaves.remove(&leaf_index.value()); + } + old_value + } else { + // there's nothing stored at the leaf; nothing to update + None + } + } +} + +impl SparseMerkleTree for Smt { + type Key = RpoDigest; + type Value = Word; + type Leaf = SmtLeaf; + type Opening = (MerklePath, SmtLeaf); + + const EMPTY_VALUE: Self::Value = EMPTY_WORD; + + fn root(&self) -> RpoDigest { + self.root + } + + fn set_root(&mut self, root: RpoDigest) { + self.root = root; + } + + fn get_inner_node(&self, index: NodeIndex) -> InnerNode { + self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { + let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); + + InnerNode { left: *node, right: *node } + }) + } + + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { + self.inner_nodes.insert(index, inner_node); + } + + fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { + // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key` + if value != Self::EMPTY_VALUE { + self.perform_insert(key, value) + } else { + self.perform_remove(key) + } + } + + fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { + let leaf_pos = LeafIndex::::from(*key).value(); + + match self.leaves.get(&leaf_pos) { + Some(leaf) => leaf.clone(), + None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), + } + } + + fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { + leaf.hash() + } + + fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex { + let most_significant_felt = key[3]; + LeafIndex::new_max_depth(most_significant_felt.as_int()) + } +} + +impl Default for Smt { + fn default() -> Self { + Self::new() + } +} + +// LEAF +// ================================================================================================ + +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub enum SmtLeaf { + Single((RpoDigest, Word)), + Multiple(Vec<(RpoDigest, Word)>), +} + +impl SmtLeaf { + /// Converts a leaf to a list of field elements + pub fn to_elements(&self) -> Vec { + self.clone().into_elements() + } + + /// Converts a leaf to a list of field elements + pub fn into_elements(self) -> Vec { + match self { + SmtLeaf::Single(kv_pair) => kv_to_elements(kv_pair).collect(), + SmtLeaf::Multiple(kv_pairs) => kv_pairs.into_iter().flat_map(kv_to_elements).collect(), + } + } + + /// Compute the hash of the leaf + pub fn hash(&self) -> RpoDigest { + match self { + SmtLeaf::Single((key, value)) => Rpo256::merge(&[*key, value.into()]), + SmtLeaf::Multiple(kvs) => { + let elements: Vec = kvs.iter().copied().flat_map(kv_to_elements).collect(); + Rpo256::hash_elements(&elements) + } + } + } + + // HELPERS + // --------------------------------------------------------------------------------------------- + + /// Insert key-value pair into the leaf; return the previous value associated with `key`, if + /// any. + fn insert(&mut self, key: RpoDigest, value: Word) -> Option { + match self { + SmtLeaf::Single(kv_pair) => { + if kv_pair.0 == key { + // the key is already in this leaf. Update the value and return the previous + // value + let old_value = kv_pair.1; + kv_pair.1 = value; + Some(old_value) + } else { + // Another entry is present in this leaf. Transform the entry into a list + // entry, and make sure the key-value pairs are sorted by key + let mut pairs = vec![*kv_pair, (key, value)]; + pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); + + *self = SmtLeaf::Multiple(pairs); + + None + } + } + SmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + kv_pairs[pos].1 = value; + + Some(old_value) + } + Err(pos) => { + kv_pairs.insert(pos, (key, value)); + + None + } + } + } + } + } + + /// Remove key-value pair into the leaf stored at key; return the previous value associated with + /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf became + /// empty, and must be removed from the data structure it is contained in. + fn remove(&mut self, key: RpoDigest) -> (Option, bool) { + match self { + SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { + if *key_at_leaf == key { + // our key was indeed stored in the leaf, so we return the value that was stored + // in it, and indicate that the leaf should be removed + let old_value = *value_at_leaf; + + (Some(old_value), true) + } else { + // another key is stored at leaf; nothing to update + (None, false) + } + } + SmtLeaf::Multiple(kv_pairs) => { + match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { + Ok(pos) => { + let old_value = kv_pairs[pos].1; + + kv_pairs.remove(pos); + debug_assert!(!kv_pairs.is_empty()); + + if kv_pairs.len() == 1 { + // convert the leaf into `Single` + *self = SmtLeaf::Single(kv_pairs[0]); + } + + (Some(old_value), false) + } + Err(_) => { + // other keys are stored at leaf; nothing to update + (None, false) + } + } + } + } + } +} + +// HELPER FUNCTIONS +// ================================================================================================ + +/// Converts a key-value tuple to an iterator of `Felt`s +fn kv_to_elements((key, value): (RpoDigest, Word)) -> impl Iterator { + let key_elements = key.into_iter(); + let value_elements = value.into_iter(); + + key_elements.chain(value_elements) +} + +/// Compares two keys, compared element-by-element using their integer representations starting with +/// the most significant element. +fn cmp_keys(key_1: RpoDigest, key_2: RpoDigest) -> Ordering { + for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() { + let v1 = v1.as_int(); + let v2 = v2.as_int(); + if v1 != v2 { + return v1.cmp(&v2); + } + } + + Ordering::Equal +} diff --git a/src/merkle/smt/tests.rs b/src/merkle/smt/full/tests.rs similarity index 99% rename from src/merkle/smt/tests.rs rename to src/merkle/smt/full/tests.rs index 66b40ec5..f068e22f 100644 --- a/src/merkle/smt/tests.rs +++ b/src/merkle/smt/full/tests.rs @@ -1,6 +1,8 @@ -use crate::{merkle::MerkleStore, ONE, WORD_SIZE}; - use super::*; +use crate::{ + merkle::{EmptySubtreeRoots, MerkleStore}, + ONE, WORD_SIZE, +}; /// This test checks that inserting twice at the same key functions as expected. The test covers /// only the case where the key is alone in its leaf diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index b5f0624b..4e0e153c 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -1,365 +1,241 @@ -use core::cmp::Ordering; - use winter_math::StarkField; -use crate::hash::rpo::Rpo256; -use crate::utils::{collections::Vec, vec}; -use crate::{Felt, EMPTY_WORD}; - -use super::sparse_merkle_tree::{InnerNode, SparseMerkleTree}; -use super::{ - BTreeMap, BTreeSet, EmptySubtreeRoots, LeafIndex, MerkleError, MerklePath, NodeIndex, - RpoDigest, Word, +use crate::{ + hash::rpo::{Rpo256, RpoDigest}, + Word, }; -#[cfg(test)] -mod tests; +use super::{MerkleError, MerklePath, NodeIndex, Vec}; -// CONSTANTS -// ================================================================================================ +mod full; +pub use full::{Smt, SmtLeaf, SMT_DEPTH}; -pub const SMT_DEPTH: u8 = 64; +mod simple; +pub use simple::SimpleSmt; -// SMT +// CONSTANTS // ================================================================================================ -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct Smt { - root: RpoDigest, - leaves: BTreeMap, - inner_nodes: BTreeMap, -} - -impl Smt { - // CONSTRUCTORS - // -------------------------------------------------------------------------------------------- - - /// Returns a new [NewSmt]. - /// - /// All leaves in the returned tree are set to [ZERO; 4]. - pub fn new() -> Self { - let root = *EmptySubtreeRoots::entry(SMT_DEPTH, 0); - - Self { - root, - leaves: BTreeMap::new(), - inner_nodes: BTreeMap::new(), - } - } - - /// Returns a new [SimpleSmt] instantiated with leaves set as specified by the provided entries. - /// - /// All leaves omitted from the entries list are set to [ZERO; 4]. - /// - /// # Errors - /// Returns an error if: - /// - The number of entries exceeds 2^63 entries. - /// - The provided entries contain multiple values for the same key. - pub fn with_entries( - entries: impl IntoIterator, - ) -> Result { - // create an empty tree - let mut tree = Self::new(); - - // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so - // entries with the empty value need additional tracking. - let mut key_set_to_zero = BTreeSet::new(); - - for (key, value) in entries { - let old_value = tree.insert(key, value); - - if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { - return Err(MerkleError::DuplicateValuesForIndex( - LeafIndex::::from(key).value(), - )); - } - - if value == EMPTY_WORD { - key_set_to_zero.insert(key); - }; - } - Ok(tree) - } +/// Minimum supported depth. +pub const SMT_MIN_DEPTH: u8 = 1; - // PUBLIC ACCESSORS - // -------------------------------------------------------------------------------------------- +/// Maximum supported depth. +pub const SMT_MAX_DEPTH: u8 = 64; - /// Returns the root of the tree - pub fn root(&self) -> RpoDigest { - >::root(self) - } - - /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { - >::get_leaf(self, key) - } +// SPARSE MERKLE TREE +// ================================================================================================ - /// Returns the depth of the tree - pub const fn depth(&self) -> u8 { - SMT_DEPTH - } +/// An abstract description of a sparse Merkle tree. +/// +/// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed +/// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's +/// value was not explicitly set, then its value is the default value. Typically, the vast majority +/// of leaves will store the default value (hence it is "sparse"), and therefore the internal +/// representation of the tree will only keep track of the leaves that have a different value from +/// the default. +/// +/// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the +/// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a +/// tree is just a single value, and is probably a programming mistake. +/// +/// Every key maps to one leaf. If there are as many keys as there are leaves, then +/// [Self::Leaf] should be the same type as [Self::Value], as is the case with +/// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] +/// must accomodate all keys that map to the same leaf. +/// +/// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. +pub(crate) trait SparseMerkleTree { + /// The type for a key + type Key: Clone; + /// The type for a value + type Value: Clone + PartialEq; + /// The type for a leaf + type Leaf; + /// The type for an opening (i.e. a "proof") of a leaf + type Opening: From<(MerklePath, Self::Leaf)>; + + /// The default value used to compute the hash of empty leaves + const EMPTY_VALUE: Self::Value; + + // PROVIDED METHODS + // --------------------------------------------------------------------------------------------- /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { - >::open(self, key) - } + fn open(&self, key: &Self::Key) -> Self::Opening { + let leaf = self.get_leaf(key); + + let mut index: NodeIndex = { + let leaf_index: LeafIndex = Self::key_to_leaf_index(key); + leaf_index.into() + }; + + let merkle_path = { + let mut path = Vec::with_capacity(index.depth() as usize); + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = self.get_inner_node(index); + let value = if is_right { left } else { right }; + path.push(value); + } - // STATE MUTATORS - // -------------------------------------------------------------------------------------------- + MerklePath::new(path) + }; + + (merkle_path, leaf).into() + } /// Inserts a value at the specified key, returning the previous value associated with that key. /// Recall that by definition, any key that hasn't been updated is associated with - /// [`EMPTY_WORD`]. + /// [`Self::EMPTY_VALUE`]. /// /// This also recomputes all hashes between the leaf (associated with the key) and the root, /// updating the root itself. - pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word { - >::insert(self, key, value) - } - - // HELPERS - // -------------------------------------------------------------------------------------------- - - /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty - /// value, such that this is indeed an insertion. - fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option { - debug_assert_ne!(value, Self::EMPTY_VALUE); - - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); - - match self.leaves.get_mut(&leaf_index.value()) { - Some(leaf) => leaf.insert(key, value), - None => { - self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); + fn insert(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { + let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or(Self::EMPTY_VALUE); - None - } + // if the old value and new value are the same, there is nothing to update + if value == old_value { + return value; } - } - /// Removes key-value pair at leaf index pointed to by `key` if it exists. - fn perform_remove(&mut self, key: RpoDigest) -> Option { - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); - - if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { - let (old_value, is_empty) = leaf.remove(key); - if is_empty { - self.leaves.remove(&leaf_index.value()); - } - old_value - } else { - // there's nothing stored at the leaf; nothing to update - None + let leaf = self.get_leaf(&key); + let node_index = { + let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); + leaf_index.into() + }; + + self.recompute_nodes_from_index_to_root(node_index, Self::hash_leaf(&leaf)); + + old_value + } + + /// Recomputes the branch nodes (including the root) from `index` all the way to the root. + /// `node_hash_at_index` is the hash of the node stored at index. + fn recompute_nodes_from_index_to_root( + &mut self, + mut index: NodeIndex, + node_hash_at_index: RpoDigest, + ) { + let mut value = node_hash_at_index; + for _ in 0..index.depth() { + let is_right = index.is_value_odd(); + index.move_up(); + let InnerNode { left, right } = self.get_inner_node(index); + let (left, right) = if is_right { (left, value) } else { (value, right) }; + self.insert_inner_node(index, InnerNode { left, right }); + value = Rpo256::merge(&[left, right]); } + self.set_root(value); } -} -impl SparseMerkleTree for Smt { - type Key = RpoDigest; - type Value = Word; - type Leaf = SmtLeaf; - type Opening = (MerklePath, SmtLeaf); + // REQUIRED METHODS + // --------------------------------------------------------------------------------------------- - const EMPTY_VALUE: Self::Value = EMPTY_WORD; + /// The root of the tree + fn root(&self) -> RpoDigest; - fn root(&self) -> RpoDigest { - self.root - } - - fn set_root(&mut self, root: RpoDigest) { - self.root = root; - } + /// Sets the root of the tree + fn set_root(&mut self, root: RpoDigest); - fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); + /// Retrieves an inner node at the given index + fn get_inner_node(&self, index: NodeIndex) -> InnerNode; - InnerNode { left: *node, right: *node } - }) - } + /// Inserts an inner node at the given index + fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode); - fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { - self.inner_nodes.insert(index, inner_node); - } + /// Inserts a leaf node, and returns the value at the key if already exists + fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option; - fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { - // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key` - if value != Self::EMPTY_VALUE { - self.perform_insert(key, value) - } else { - self.perform_remove(key) - } - } + /// Returns the leaf at the specified index. + fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; - fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { - let leaf_pos = LeafIndex::::from(*key).value(); + /// Returns the hash of a leaf + fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; - match self.leaves.get(&leaf_pos) { - Some(leaf) => leaf.clone(), - None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), - } - } + fn key_to_leaf_index(key: &Self::Key) -> LeafIndex; +} - fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { - leaf.hash() - } +// INNER NODE +// ================================================================================================ - fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex { - let most_significant_felt = key[3]; - LeafIndex::new_max_depth(most_significant_felt.as_int()) - } +#[derive(Debug, Default, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub(crate) struct InnerNode { + pub left: RpoDigest, + pub right: RpoDigest, } -impl Default for Smt { - fn default() -> Self { - Self::new() +impl InnerNode { + pub fn hash(&self) -> RpoDigest { + Rpo256::merge(&[self.left, self.right]) } } -// LEAF +// LEAF INDEX // ================================================================================================ -#[derive(Clone, Debug, PartialEq, Eq)] +/// The index of a leaf, at a depth known at compile-time. +#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub enum SmtLeaf { - Single((RpoDigest, Word)), - Multiple(Vec<(RpoDigest, Word)>), +pub struct LeafIndex { + index: NodeIndex, } -impl SmtLeaf { - /// Converts a leaf to a list of field elements - pub fn to_elements(&self) -> Vec { - self.clone().into_elements() - } - - /// Converts a leaf to a list of field elements - pub fn into_elements(self) -> Vec { - match self { - SmtLeaf::Single(kv_pair) => kv_to_elements(kv_pair).collect(), - SmtLeaf::Multiple(kv_pairs) => kv_pairs.into_iter().flat_map(kv_to_elements).collect(), +impl LeafIndex { + pub fn new(value: u64) -> Result { + if DEPTH < SMT_MIN_DEPTH { + return Err(MerkleError::DepthTooSmall(DEPTH)); } - } - /// Compute the hash of the leaf - pub fn hash(&self) -> RpoDigest { - match self { - SmtLeaf::Single((key, value)) => Rpo256::merge(&[*key, value.into()]), - SmtLeaf::Multiple(kvs) => { - let elements: Vec = kvs.iter().copied().flat_map(kv_to_elements).collect(); - Rpo256::hash_elements(&elements) - } - } + Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? }) } - // HELPERS - // --------------------------------------------------------------------------------------------- + pub fn value(&self) -> u64 { + self.index.value() + } +} - /// Insert key-value pair into the leaf; return the previous value associated with `key`, if - /// any. - fn insert(&mut self, key: RpoDigest, value: Word) -> Option { - match self { - SmtLeaf::Single(kv_pair) => { - if kv_pair.0 == key { - // the key is already in this leaf. Update the value and return the previous - // value - let old_value = kv_pair.1; - kv_pair.1 = value; - Some(old_value) - } else { - // Another entry is present in this leaf. Transform the entry into a list - // entry, and make sure the key-value pairs are sorted by key - let mut pairs = vec![*kv_pair, (key, value)]; - pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); - - *self = SmtLeaf::Multiple(pairs); - - None - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - kv_pairs[pos].1 = value; - - Some(old_value) - } - Err(pos) => { - kv_pairs.insert(pos, (key, value)); - - None - } - } - } +impl LeafIndex { + pub fn new_max_depth(value: u64) -> Self { + LeafIndex { + index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value), } } +} - /// Remove key-value pair into the leaf stored at key; return the previous value associated with - /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf became - /// empty, and must be removed from the data structure it is contained in. - fn remove(&mut self, key: RpoDigest) -> (Option, bool) { - match self { - SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { - if *key_at_leaf == key { - // our key was indeed stored in the leaf, so we return the value that was stored - // in it, and indicate that the leaf should be removed - let old_value = *value_at_leaf; - - (Some(old_value), true) - } else { - // another key is stored at leaf; nothing to update - (None, false) - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - - kv_pairs.remove(pos); - debug_assert!(!kv_pairs.is_empty()); - - if kv_pairs.len() == 1 { - // convert the leaf into `Single` - *self = SmtLeaf::Single(kv_pairs[0]); - } - - (Some(old_value), false) - } - Err(_) => { - // other keys are stored at leaf; nothing to update - (None, false) - } - } - } - } +impl From> for NodeIndex { + fn from(value: LeafIndex) -> Self { + value.index } } -// HELPER FUNCTIONS -// ================================================================================================ +impl TryFrom for LeafIndex { + type Error = MerkleError; -/// Converts a key-value tuple to an iterator of `Felt`s -fn kv_to_elements((key, value): (RpoDigest, Word)) -> impl Iterator { - let key_elements = key.into_iter(); - let value_elements = value.into_iter(); + fn try_from(node_index: NodeIndex) -> Result { + if node_index.depth() != DEPTH { + return Err(MerkleError::InvalidDepth { + expected: DEPTH, + provided: node_index.depth(), + }); + } - key_elements.chain(value_elements) + Self::new(node_index.value()) + } } -/// Compares two keys, compared element-by-element using their integer representations starting with -/// the most significant element. -fn cmp_keys(key_1: RpoDigest, key_2: RpoDigest) -> Ordering { - for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() { - let v1 = v1.as_int(); - let v2 = v2.as_int(); - if v1 != v2 { - return v1.cmp(&v2); - } +impl From for LeafIndex { + fn from(value: Word) -> Self { + // We use the most significant `Felt` of a `Word` as the leaf index. + Self::new_max_depth(value[3].as_int()) } +} - Ordering::Equal +impl From for LeafIndex { + fn from(value: RpoDigest) -> Self { + Word::from(value).into() + } } diff --git a/src/merkle/simple_smt/mod.rs b/src/merkle/smt/simple/mod.rs similarity index 97% rename from src/merkle/simple_smt/mod.rs rename to src/merkle/smt/simple/mod.rs index 8a167755..c097fa95 100644 --- a/src/merkle/simple_smt/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -1,10 +1,14 @@ -use crate::EMPTY_WORD; +use crate::{ + merkle::{EmptySubtreeRoots, InnerNodeInfo, MerkleTreeDelta, StoreNode}, + utils::collections::TryApplyDiff, + EMPTY_WORD, +}; use super::{ - sparse_merkle_tree::{InnerNode, SparseMerkleTree, SMT_MAX_DEPTH}, - BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNodeInfo, LeafIndex, MerkleError, MerklePath, - MerkleTreeDelta, NodeIndex, RpoDigest, StoreNode, TryApplyDiff, Word, SMT_MIN_DEPTH, + InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, + SMT_MAX_DEPTH, SMT_MIN_DEPTH, }; +use crate::utils::collections::{BTreeMap, BTreeSet}; #[cfg(test)] mod tests; diff --git a/src/merkle/simple_smt/tests.rs b/src/merkle/smt/simple/tests.rs similarity index 98% rename from src/merkle/simple_smt/tests.rs rename to src/merkle/smt/simple/tests.rs index 3c74cef6..4ef501c7 100644 --- a/src/merkle/simple_smt/tests.rs +++ b/src/merkle/smt/simple/tests.rs @@ -1,15 +1,15 @@ use super::{ - super::{InnerNodeInfo, MerkleError, MerkleTree, RpoDigest, SimpleSmt, EMPTY_WORD}, + super::{MerkleError, RpoDigest, SimpleSmt}, NodeIndex, }; use crate::{ hash::rpo::Rpo256, merkle::{ - digests_to_words, int_to_leaf, int_to_node, sparse_merkle_tree::SparseMerkleTree, - EmptySubtreeRoots, LeafIndex, + digests_to_words, int_to_leaf, int_to_node, smt::SparseMerkleTree, EmptySubtreeRoots, + InnerNodeInfo, LeafIndex, MerkleTree, }, utils::collections::Vec, - Word, + Word, EMPTY_WORD, }; // TEST DATA diff --git a/src/merkle/sparse_merkle_tree.rs b/src/merkle/sparse_merkle_tree.rs deleted file mode 100644 index 5cc7a0ff..00000000 --- a/src/merkle/sparse_merkle_tree.rs +++ /dev/null @@ -1,235 +0,0 @@ -use winter_math::StarkField; - -use crate::{ - hash::rpo::{Rpo256, RpoDigest}, - Word, -}; - -use super::{MerkleError, MerklePath, NodeIndex, Vec}; - -// CONSTANTS -// ================================================================================================ - -/// Minimum supported depth. -pub const SMT_MIN_DEPTH: u8 = 1; - -/// Maximum supported depth. -pub const SMT_MAX_DEPTH: u8 = 64; - -// SPARSE MERKLE TREE -// ================================================================================================ - -/// An abstract description of a sparse Merkle tree. -/// -/// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed -/// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's -/// value was not explicitly set, then its value is the default value. Typically, the vast majority -/// of leaves will store the default value (hence it is "sparse"), and therefore the internal -/// representation of the tree will only keep track of the leaves that have a different value from -/// the default. -/// -/// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the -/// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a -/// tree is just a single value, and is probably a programming mistake. -/// -/// Every key maps to one leaf. If there are as many keys as there are leaves, then -/// [Self::Leaf] should be the same type as [Self::Value], as is the case with -/// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`] -/// must accomodate all keys that map to the same leaf. -/// -/// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs. -pub(crate) trait SparseMerkleTree { - /// The type for a key - type Key: Clone; - /// The type for a value - type Value: Clone + PartialEq; - /// The type for a leaf - type Leaf; - /// The type for an opening (i.e. a "proof") of a leaf - type Opening: From<(MerklePath, Self::Leaf)>; - - /// The default value used to compute the hash of empty leaves - const EMPTY_VALUE: Self::Value; - - // PROVIDED METHODS - // --------------------------------------------------------------------------------------------- - - /// Returns a Merkle path from the leaf node specified by the key to the root. - /// - /// The node itself is not included in the path. - fn open(&self, key: &Self::Key) -> Self::Opening { - let leaf = self.get_leaf(key); - - let mut index: NodeIndex = { - let leaf_index: LeafIndex = Self::key_to_leaf_index(key); - leaf_index.into() - }; - - let merkle_path = { - let mut path = Vec::with_capacity(index.depth() as usize); - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = self.get_inner_node(index); - let value = if is_right { left } else { right }; - path.push(value); - } - - MerklePath::new(path) - }; - - (merkle_path, leaf).into() - } - - /// Inserts a value at the specified key, returning the previous value associated with that key. - /// Recall that by definition, any key that hasn't been updated is associated with - /// [`Self::EMPTY_VALUE`]. - /// - /// This also recomputes all hashes between the leaf (associated with the key) and the root, - /// updating the root itself. - fn insert(&mut self, key: Self::Key, value: Self::Value) -> Self::Value { - let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or(Self::EMPTY_VALUE); - - // if the old value and new value are the same, there is nothing to update - if value == old_value { - return value; - } - - let leaf = self.get_leaf(&key); - let node_index = { - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); - leaf_index.into() - }; - - self.recompute_nodes_from_index_to_root(node_index, Self::hash_leaf(&leaf)); - - old_value - } - - /// Recomputes the branch nodes (including the root) from `index` all the way to the root. - /// `node_hash_at_index` is the hash of the node stored at index. - fn recompute_nodes_from_index_to_root( - &mut self, - mut index: NodeIndex, - node_hash_at_index: RpoDigest, - ) { - let mut value = node_hash_at_index; - for _ in 0..index.depth() { - let is_right = index.is_value_odd(); - index.move_up(); - let InnerNode { left, right } = self.get_inner_node(index); - let (left, right) = if is_right { (left, value) } else { (value, right) }; - self.insert_inner_node(index, InnerNode { left, right }); - value = Rpo256::merge(&[left, right]); - } - self.set_root(value); - } - - // REQUIRED METHODS - // --------------------------------------------------------------------------------------------- - - /// The root of the tree - fn root(&self) -> RpoDigest; - - /// Sets the root of the tree - fn set_root(&mut self, root: RpoDigest); - - /// Retrieves an inner node at the given index - fn get_inner_node(&self, index: NodeIndex) -> InnerNode; - - /// Inserts an inner node at the given index - fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode); - - /// Inserts a leaf node, and returns the value at the key if already exists - fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option; - - /// Returns the leaf at the specified index. - fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; - - /// Returns the hash of a leaf - fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; - - fn key_to_leaf_index(key: &Self::Key) -> LeafIndex; -} - -// INNER NODE -// ================================================================================================ - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub(crate) struct InnerNode { - pub left: RpoDigest, - pub right: RpoDigest, -} - -impl InnerNode { - pub fn hash(&self) -> RpoDigest { - Rpo256::merge(&[self.left, self.right]) - } -} - -// LEAF INDEX -// ================================================================================================ - -/// The index of a leaf, at a depth known at compile-time. -#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct LeafIndex { - index: NodeIndex, -} - -impl LeafIndex { - pub fn new(value: u64) -> Result { - if DEPTH < SMT_MIN_DEPTH { - return Err(MerkleError::DepthTooSmall(DEPTH)); - } - - Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? }) - } - - pub fn value(&self) -> u64 { - self.index.value() - } -} - -impl LeafIndex { - pub fn new_max_depth(value: u64) -> Self { - LeafIndex { - index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value), - } - } -} - -impl From> for NodeIndex { - fn from(value: LeafIndex) -> Self { - value.index - } -} - -impl TryFrom for LeafIndex { - type Error = MerkleError; - - fn try_from(node_index: NodeIndex) -> Result { - if node_index.depth() != DEPTH { - return Err(MerkleError::InvalidDepth { - expected: DEPTH, - provided: node_index.depth(), - }); - } - - Self::new(node_index.value()) - } -} - -impl From for LeafIndex { - fn from(value: Word) -> Self { - // We use the most significant `Felt` of a `Word` as the leaf index. - Self::new_max_depth(value[3].as_int()) - } -} - -impl From for LeafIndex { - fn from(value: RpoDigest) -> Self { - Word::from(value).into() - } -} From 7532d72fb62e6fe6f808512a854a8b921dbc7079 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Tue, 16 Jan 2024 17:33:25 -0500 Subject: [PATCH 103/117] `SimpleSmtTrait`: Return possibly borrowed data --- src/merkle/smt/full/mod.rs | 18 +++++++++++------- src/merkle/smt/full/tests.rs | 12 ++++++------ src/merkle/smt/mod.rs | 11 +++++++---- src/merkle/smt/simple/mod.rs | 23 +++++++++++++++-------- src/merkle/smt/simple/tests.rs | 2 +- src/merkle/store/tests.rs | 5 ++++- src/utils/mod.rs | 4 ++-- 7 files changed, 46 insertions(+), 29 deletions(-) diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs index f8c17aca..921a432d 100644 --- a/src/merkle/smt/full/mod.rs +++ b/src/merkle/smt/full/mod.rs @@ -6,7 +6,7 @@ use crate::hash::rpo::Rpo256; use crate::merkle::EmptySubtreeRoots; use crate::utils::{ collections::{BTreeMap, BTreeSet, Vec}, - vec, + vec, Cow, }; use crate::{Felt, EMPTY_WORD}; @@ -93,7 +93,7 @@ impl Smt { } /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { + pub fn get_leaf(&self, key: &RpoDigest) -> Cow<'_, SmtLeaf> { >::get_leaf(self, key) } @@ -105,7 +105,7 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { + pub fn open(&self, key: &RpoDigest) -> (MerklePath, Cow<'_, SmtLeaf>) { >::open(self, key) } @@ -163,7 +163,7 @@ impl SparseMerkleTree for Smt { type Key = RpoDigest; type Value = Word; type Leaf = SmtLeaf; - type Opening = (MerklePath, SmtLeaf); + type Opening<'a> = (MerklePath, Cow<'a, SmtLeaf>); const EMPTY_VALUE: Self::Value = EMPTY_WORD; @@ -196,12 +196,16 @@ impl SparseMerkleTree for Smt { } } - fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { + fn get_leaf(&self, key: &RpoDigest) -> Cow<'_, Self::Leaf> { let leaf_pos = LeafIndex::::from(*key).value(); match self.leaves.get(&leaf_pos) { - Some(leaf) => leaf.clone(), - None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), + Some(leaf) => Cow::Borrowed(leaf), + None => { + let default_leaf = SmtLeaf::Single((*key, Self::EMPTY_VALUE)); + + Cow::Owned(default_leaf) + } } } diff --git a/src/merkle/smt/full/tests.rs b/src/merkle/smt/full/tests.rs index f068e22f..2a543044 100644 --- a/src/merkle/smt/full/tests.rs +++ b/src/merkle/smt/full/tests.rs @@ -186,7 +186,7 @@ fn test_smt_removal() { let old_value_1 = smt.insert(key_1, value_1); assert_eq!(old_value_1, EMPTY_WORD); - assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, value_1))); + assert_eq!(smt.get_leaf(&key_1).into_owned(), SmtLeaf::Single((key_1, value_1))); } // insert key-value 2 @@ -195,7 +195,7 @@ fn test_smt_removal() { assert_eq!(old_value_2, EMPTY_WORD); assert_eq!( - smt.get_leaf(&key_2), + smt.get_leaf(&key_2).into_owned(), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) ); } @@ -206,7 +206,7 @@ fn test_smt_removal() { assert_eq!(old_value_3, EMPTY_WORD); assert_eq!( - smt.get_leaf(&key_3), + smt.get_leaf(&key_3).into_owned(), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2), (key_3, value_3)]) ); } @@ -217,7 +217,7 @@ fn test_smt_removal() { assert_eq!(old_value_3, value_3); assert_eq!( - smt.get_leaf(&key_3), + smt.get_leaf(&key_3).into_owned(), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) ); } @@ -227,7 +227,7 @@ fn test_smt_removal() { let old_value_2 = smt.insert(key_2, EMPTY_WORD); assert_eq!(old_value_2, value_2); - assert_eq!(smt.get_leaf(&key_2), SmtLeaf::Single((key_1, value_1))); + assert_eq!(smt.get_leaf(&key_2).into_owned(), SmtLeaf::Single((key_1, value_1))); } // remove key 1 @@ -235,7 +235,7 @@ fn test_smt_removal() { let old_value_1 = smt.insert(key_1, EMPTY_WORD); assert_eq!(old_value_1, value_1); - assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, EMPTY_WORD))); + assert_eq!(smt.get_leaf(&key_1).into_owned(), SmtLeaf::Single((key_1, EMPTY_WORD))); } } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 4e0e153c..9e3f983e 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -2,6 +2,7 @@ use winter_math::StarkField; use crate::{ hash::rpo::{Rpo256, RpoDigest}, + utils::Cow, Word, }; @@ -50,9 +51,11 @@ pub(crate) trait SparseMerkleTree { /// The type for a value type Value: Clone + PartialEq; /// The type for a leaf - type Leaf; + type Leaf: Clone; /// The type for an opening (i.e. a "proof") of a leaf - type Opening: From<(MerklePath, Self::Leaf)>; + type Opening<'a>: From<(MerklePath, Cow<'a, Self::Leaf>)> + where + Self: 'a; /// The default value used to compute the hash of empty leaves const EMPTY_VALUE: Self::Value; @@ -63,7 +66,7 @@ pub(crate) trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn open(&self, key: &Self::Key) -> Self::Opening { + fn open(&self, key: &Self::Key) -> Self::Opening<'_> { let leaf = self.get_leaf(key); let mut index: NodeIndex = { @@ -150,7 +153,7 @@ pub(crate) trait SparseMerkleTree { fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option; /// Returns the leaf at the specified index. - fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; + fn get_leaf(&self, key: &Self::Key) -> Cow<'_, Self::Leaf>; /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index c097fa95..54640de4 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -8,7 +8,10 @@ use super::{ InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, SMT_MAX_DEPTH, SMT_MIN_DEPTH, }; -use crate::utils::collections::{BTreeMap, BTreeSet}; +use crate::utils::{ + collections::{BTreeMap, BTreeSet}, + Cow, +}; #[cfg(test)] mod tests; @@ -117,7 +120,7 @@ impl SimpleSmt { } /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &LeafIndex) -> Word { + pub fn get_leaf(&self, key: &LeafIndex) -> Cow<'_, Word> { >::get_leaf(self, key) } @@ -129,7 +132,7 @@ impl SimpleSmt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { + pub fn open(&self, key: &LeafIndex) -> (MerklePath, Cow<'_, Word>) { >::open(self, key) } @@ -144,7 +147,7 @@ impl SimpleSmt { } else if index.depth() > DEPTH { Err(MerkleError::DepthTooBig(index.depth() as u64)) } else if index.depth() == DEPTH { - let leaf = self.get_leaf(&LeafIndex::::try_from(index)?); + let leaf = self.get_leaf(&LeafIndex::::try_from(index)?).into_owned(); Ok(leaf.into()) } else { @@ -247,7 +250,7 @@ impl SparseMerkleTree for SimpleSmt { type Key = LeafIndex; type Value = Word; type Leaf = Word; - type Opening = (MerklePath, Word); + type Opening<'a> = (MerklePath, Cow<'a, Word>); const EMPTY_VALUE: Self::Value = EMPTY_WORD; @@ -275,14 +278,18 @@ impl SparseMerkleTree for SimpleSmt { self.leaves.insert(key.value(), value) } - fn get_leaf(&self, key: &LeafIndex) -> Word { + fn get_leaf(&self, key: &LeafIndex) -> Cow<'_, Word> { // the lookup in empty_hashes could fail only if empty_hashes were not built correctly // by the constructor as we check the depth of the lookup above. let leaf_pos = key.value(); match self.leaves.get(&leaf_pos) { - Some(word) => *word, - None => Word::from(*EmptySubtreeRoots::entry(DEPTH, DEPTH)), + Some(word) => Cow::Borrowed(word), + None => { + let empty_root = *EmptySubtreeRoots::entry(DEPTH, DEPTH); + + Cow::Owned(empty_root.into()) + } } } diff --git a/src/merkle/smt/simple/tests.rs b/src/merkle/smt/simple/tests.rs index 4ef501c7..0a2c2d2a 100644 --- a/src/merkle/smt/simple/tests.rs +++ b/src/merkle/smt/simple/tests.rs @@ -344,7 +344,7 @@ fn test_simplesmt_set_subtree() { }; assert_eq!(tree.root(), k); - assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()), c); + assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()).into_owned(), c); assert_eq!(tree.get_inner_node(NodeIndex::new_unchecked(2, 2)).hash(), g); } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 0ef51354..0bdb357b 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -922,7 +922,10 @@ fn test_recorder() { let node = merkle_store.get_node(smtree.root(), index_2).unwrap(); assert_eq!( node, - smtree.get_leaf(&LeafIndex::::try_from(index_2).unwrap()).into() + smtree + .get_leaf(&LeafIndex::::try_from(index_2).unwrap()) + .into_owned() + .into() ); // assert that is doesnt contain nodes that were not recorded diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 715eee87..45a78084 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -4,10 +4,10 @@ use super::{utils::string::String, Word}; use core::fmt::{self, Display, Write}; #[cfg(not(feature = "std"))] -pub use alloc::{format, vec}; +pub use alloc::{borrow::Cow, format, vec}; #[cfg(feature = "std")] -pub use std::{format, vec}; +pub use std::{borrow::Cow, format, vec}; mod diff; mod kv_map; From 3d583d0d3f47f66181fdf786ded8bdd73ab1e112 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:06:25 -0500 Subject: [PATCH 104/117] Revert "`SimpleSmtTrait`: Return possibly borrowed data" This reverts commit d39aee97d6be6890fbc689bdbfe4cceb7af58a97. --- src/merkle/smt/full/mod.rs | 18 +++++++----------- src/merkle/smt/full/tests.rs | 12 ++++++------ src/merkle/smt/mod.rs | 11 ++++------- src/merkle/smt/simple/mod.rs | 23 ++++++++--------------- src/merkle/smt/simple/tests.rs | 2 +- src/merkle/store/tests.rs | 5 +---- src/utils/mod.rs | 4 ++-- 7 files changed, 29 insertions(+), 46 deletions(-) diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs index 921a432d..f8c17aca 100644 --- a/src/merkle/smt/full/mod.rs +++ b/src/merkle/smt/full/mod.rs @@ -6,7 +6,7 @@ use crate::hash::rpo::Rpo256; use crate::merkle::EmptySubtreeRoots; use crate::utils::{ collections::{BTreeMap, BTreeSet, Vec}, - vec, Cow, + vec, }; use crate::{Felt, EMPTY_WORD}; @@ -93,7 +93,7 @@ impl Smt { } /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &RpoDigest) -> Cow<'_, SmtLeaf> { + pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { >::get_leaf(self, key) } @@ -105,7 +105,7 @@ impl Smt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: &RpoDigest) -> (MerklePath, Cow<'_, SmtLeaf>) { + pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { >::open(self, key) } @@ -163,7 +163,7 @@ impl SparseMerkleTree for Smt { type Key = RpoDigest; type Value = Word; type Leaf = SmtLeaf; - type Opening<'a> = (MerklePath, Cow<'a, SmtLeaf>); + type Opening = (MerklePath, SmtLeaf); const EMPTY_VALUE: Self::Value = EMPTY_WORD; @@ -196,16 +196,12 @@ impl SparseMerkleTree for Smt { } } - fn get_leaf(&self, key: &RpoDigest) -> Cow<'_, Self::Leaf> { + fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { let leaf_pos = LeafIndex::::from(*key).value(); match self.leaves.get(&leaf_pos) { - Some(leaf) => Cow::Borrowed(leaf), - None => { - let default_leaf = SmtLeaf::Single((*key, Self::EMPTY_VALUE)); - - Cow::Owned(default_leaf) - } + Some(leaf) => leaf.clone(), + None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), } } diff --git a/src/merkle/smt/full/tests.rs b/src/merkle/smt/full/tests.rs index 2a543044..f068e22f 100644 --- a/src/merkle/smt/full/tests.rs +++ b/src/merkle/smt/full/tests.rs @@ -186,7 +186,7 @@ fn test_smt_removal() { let old_value_1 = smt.insert(key_1, value_1); assert_eq!(old_value_1, EMPTY_WORD); - assert_eq!(smt.get_leaf(&key_1).into_owned(), SmtLeaf::Single((key_1, value_1))); + assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, value_1))); } // insert key-value 2 @@ -195,7 +195,7 @@ fn test_smt_removal() { assert_eq!(old_value_2, EMPTY_WORD); assert_eq!( - smt.get_leaf(&key_2).into_owned(), + smt.get_leaf(&key_2), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) ); } @@ -206,7 +206,7 @@ fn test_smt_removal() { assert_eq!(old_value_3, EMPTY_WORD); assert_eq!( - smt.get_leaf(&key_3).into_owned(), + smt.get_leaf(&key_3), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2), (key_3, value_3)]) ); } @@ -217,7 +217,7 @@ fn test_smt_removal() { assert_eq!(old_value_3, value_3); assert_eq!( - smt.get_leaf(&key_3).into_owned(), + smt.get_leaf(&key_3), SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) ); } @@ -227,7 +227,7 @@ fn test_smt_removal() { let old_value_2 = smt.insert(key_2, EMPTY_WORD); assert_eq!(old_value_2, value_2); - assert_eq!(smt.get_leaf(&key_2).into_owned(), SmtLeaf::Single((key_1, value_1))); + assert_eq!(smt.get_leaf(&key_2), SmtLeaf::Single((key_1, value_1))); } // remove key 1 @@ -235,7 +235,7 @@ fn test_smt_removal() { let old_value_1 = smt.insert(key_1, EMPTY_WORD); assert_eq!(old_value_1, value_1); - assert_eq!(smt.get_leaf(&key_1).into_owned(), SmtLeaf::Single((key_1, EMPTY_WORD))); + assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, EMPTY_WORD))); } } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 9e3f983e..4e0e153c 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -2,7 +2,6 @@ use winter_math::StarkField; use crate::{ hash::rpo::{Rpo256, RpoDigest}, - utils::Cow, Word, }; @@ -51,11 +50,9 @@ pub(crate) trait SparseMerkleTree { /// The type for a value type Value: Clone + PartialEq; /// The type for a leaf - type Leaf: Clone; + type Leaf; /// The type for an opening (i.e. a "proof") of a leaf - type Opening<'a>: From<(MerklePath, Cow<'a, Self::Leaf>)> - where - Self: 'a; + type Opening: From<(MerklePath, Self::Leaf)>; /// The default value used to compute the hash of empty leaves const EMPTY_VALUE: Self::Value; @@ -66,7 +63,7 @@ pub(crate) trait SparseMerkleTree { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - fn open(&self, key: &Self::Key) -> Self::Opening<'_> { + fn open(&self, key: &Self::Key) -> Self::Opening { let leaf = self.get_leaf(key); let mut index: NodeIndex = { @@ -153,7 +150,7 @@ pub(crate) trait SparseMerkleTree { fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option; /// Returns the leaf at the specified index. - fn get_leaf(&self, key: &Self::Key) -> Cow<'_, Self::Leaf>; + fn get_leaf(&self, key: &Self::Key) -> Self::Leaf; /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 54640de4..c097fa95 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -8,10 +8,7 @@ use super::{ InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, SMT_MAX_DEPTH, SMT_MIN_DEPTH, }; -use crate::utils::{ - collections::{BTreeMap, BTreeSet}, - Cow, -}; +use crate::utils::collections::{BTreeMap, BTreeSet}; #[cfg(test)] mod tests; @@ -120,7 +117,7 @@ impl SimpleSmt { } /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &LeafIndex) -> Cow<'_, Word> { + pub fn get_leaf(&self, key: &LeafIndex) -> Word { >::get_leaf(self, key) } @@ -132,7 +129,7 @@ impl SimpleSmt { /// Returns a Merkle path from the leaf node specified by the key to the root. /// /// The node itself is not included in the path. - pub fn open(&self, key: &LeafIndex) -> (MerklePath, Cow<'_, Word>) { + pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { >::open(self, key) } @@ -147,7 +144,7 @@ impl SimpleSmt { } else if index.depth() > DEPTH { Err(MerkleError::DepthTooBig(index.depth() as u64)) } else if index.depth() == DEPTH { - let leaf = self.get_leaf(&LeafIndex::::try_from(index)?).into_owned(); + let leaf = self.get_leaf(&LeafIndex::::try_from(index)?); Ok(leaf.into()) } else { @@ -250,7 +247,7 @@ impl SparseMerkleTree for SimpleSmt { type Key = LeafIndex; type Value = Word; type Leaf = Word; - type Opening<'a> = (MerklePath, Cow<'a, Word>); + type Opening = (MerklePath, Word); const EMPTY_VALUE: Self::Value = EMPTY_WORD; @@ -278,18 +275,14 @@ impl SparseMerkleTree for SimpleSmt { self.leaves.insert(key.value(), value) } - fn get_leaf(&self, key: &LeafIndex) -> Cow<'_, Word> { + fn get_leaf(&self, key: &LeafIndex) -> Word { // the lookup in empty_hashes could fail only if empty_hashes were not built correctly // by the constructor as we check the depth of the lookup above. let leaf_pos = key.value(); match self.leaves.get(&leaf_pos) { - Some(word) => Cow::Borrowed(word), - None => { - let empty_root = *EmptySubtreeRoots::entry(DEPTH, DEPTH); - - Cow::Owned(empty_root.into()) - } + Some(word) => *word, + None => Word::from(*EmptySubtreeRoots::entry(DEPTH, DEPTH)), } } diff --git a/src/merkle/smt/simple/tests.rs b/src/merkle/smt/simple/tests.rs index 0a2c2d2a..4ef501c7 100644 --- a/src/merkle/smt/simple/tests.rs +++ b/src/merkle/smt/simple/tests.rs @@ -344,7 +344,7 @@ fn test_simplesmt_set_subtree() { }; assert_eq!(tree.root(), k); - assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()).into_owned(), c); + assert_eq!(tree.get_leaf(&LeafIndex::::new(4).unwrap()), c); assert_eq!(tree.get_inner_node(NodeIndex::new_unchecked(2, 2)).hash(), g); } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 0bdb357b..0ef51354 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -922,10 +922,7 @@ fn test_recorder() { let node = merkle_store.get_node(smtree.root(), index_2).unwrap(); assert_eq!( node, - smtree - .get_leaf(&LeafIndex::::try_from(index_2).unwrap()) - .into_owned() - .into() + smtree.get_leaf(&LeafIndex::::try_from(index_2).unwrap()).into() ); // assert that is doesnt contain nodes that were not recorded diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 45a78084..715eee87 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -4,10 +4,10 @@ use super::{utils::string::String, Word}; use core::fmt::{self, Display, Write}; #[cfg(not(feature = "std"))] -pub use alloc::{borrow::Cow, format, vec}; +pub use alloc::{format, vec}; #[cfg(feature = "std")] -pub use std::{borrow::Cow, format, vec}; +pub use std::{format, vec}; mod diff; mod kv_map; From 5ff055f44d23bfe33892c2764049bbea3522403c Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:14:51 -0500 Subject: [PATCH 105/117] docstring --- src/merkle/smt/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 4e0e153c..92017021 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -155,6 +155,7 @@ pub(crate) trait SparseMerkleTree { /// Returns the hash of a leaf fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest; + /// Maps a key to a leaf index fn key_to_leaf_index(key: &Self::Key) -> LeafIndex; } From 9c7a8297c55f0774318df3d304edbfb3a50f7599 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:21:53 -0500 Subject: [PATCH 106/117] fix `open()` docstring --- src/merkle/smt/full/mod.rs | 5 ++--- src/merkle/smt/mod.rs | 5 ++--- src/merkle/smt/simple/mod.rs | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs index f8c17aca..c63800bf 100644 --- a/src/merkle/smt/full/mod.rs +++ b/src/merkle/smt/full/mod.rs @@ -102,9 +102,8 @@ impl Smt { SMT_DEPTH } - /// Returns a Merkle path from the leaf node specified by the key to the root. - /// - /// The node itself is not included in the path. + /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle + /// path to the leaf, as well as the leaf itself. pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { >::open(self, key) } diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 92017021..03920952 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -60,9 +60,8 @@ pub(crate) trait SparseMerkleTree { // PROVIDED METHODS // --------------------------------------------------------------------------------------------- - /// Returns a Merkle path from the leaf node specified by the key to the root. - /// - /// The node itself is not included in the path. + /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle + /// path to the leaf, as well as the leaf itself. fn open(&self, key: &Self::Key) -> Self::Opening { let leaf = self.get_leaf(key); diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index c097fa95..fc9b1096 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -126,9 +126,8 @@ impl SimpleSmt { DEPTH } - /// Returns a Merkle path from the leaf node specified by the key to the root. - /// - /// The node itself is not included in the path. + /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle + /// path to the leaf, as well as the leaf itself. pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { >::open(self, key) } From 771ce46fc5adeb3b4b1ae07fb14f433d78fb29ab Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:23:55 -0500 Subject: [PATCH 107/117] move `depth()` function up --- src/merkle/smt/full/mod.rs | 10 +++++----- src/merkle/smt/simple/mod.rs | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs index c63800bf..c0cdaa69 100644 --- a/src/merkle/smt/full/mod.rs +++ b/src/merkle/smt/full/mod.rs @@ -87,6 +87,11 @@ impl Smt { // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- + /// Returns the depth of the tree + pub const fn depth(&self) -> u8 { + SMT_DEPTH + } + /// Returns the root of the tree pub fn root(&self) -> RpoDigest { >::root(self) @@ -97,11 +102,6 @@ impl Smt { >::get_leaf(self, key) } - /// Returns the depth of the tree - pub const fn depth(&self) -> u8 { - SMT_DEPTH - } - /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle /// path to the leaf, as well as the leaf itself. pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index fc9b1096..1c5f821e 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -111,6 +111,11 @@ impl SimpleSmt { // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- + /// Returns the depth of the tree + pub const fn depth(&self) -> u8 { + DEPTH + } + /// Returns the root of the tree pub fn root(&self) -> RpoDigest { >::root(self) @@ -121,11 +126,6 @@ impl SimpleSmt { >::get_leaf(self, key) } - /// Returns the depth of the tree - pub const fn depth(&self) -> u8 { - DEPTH - } - /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle /// path to the leaf, as well as the leaf itself. pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { From a6a0ddc510fcd25ad793572ddfe9fcd83165fbcc Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:25:08 -0500 Subject: [PATCH 108/117] fix var name --- src/merkle/smt/simple/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 1c5f821e..da2306f2 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -290,8 +290,8 @@ impl SparseMerkleTree for SimpleSmt { leaf.into() } - fn key_to_leaf_index(leaf: &LeafIndex) -> LeafIndex { - *leaf + fn key_to_leaf_index(key: &LeafIndex) -> LeafIndex { + *key } } From e4d9c5ac8f62e67edd56d66d7bd27ba4e1bd5be9 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:26:00 -0500 Subject: [PATCH 109/117] move `open()` down --- src/merkle/smt/simple/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index da2306f2..33518593 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -126,12 +126,6 @@ impl SimpleSmt { >::get_leaf(self, key) } - /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle - /// path to the leaf, as well as the leaf itself. - pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { - >::open(self, key) - } - /// Returns a node at the specified index. /// /// # Errors @@ -151,6 +145,12 @@ impl SimpleSmt { } } + /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle + /// path to the leaf, as well as the leaf itself. + pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { + >::open(self, key) + } + // ITERATORS // -------------------------------------------------------------------------------------------- From eb24376b4ba1eed3ed0f00da24cc6b6100c8d69e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:26:53 -0500 Subject: [PATCH 110/117] fix comment --- src/merkle/smt/simple/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 33518593..a04e50b4 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -159,7 +159,7 @@ impl SimpleSmt { self.leaves.iter().map(|(i, w)| (*i, w)) } - /// Returns an iterator over the inner nodes of this Merkle tree. + /// Returns an iterator over the inner nodes of this [SimpleSmt]. pub fn inner_nodes(&self) -> impl Iterator + '_ { self.inner_nodes.values().map(|e| InnerNodeInfo { value: e.hash(), From 9dc022804cfeae524079059f90833c8fab5fa368 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:38:03 -0500 Subject: [PATCH 111/117] `ValuePath`: adjust constructor --- src/merkle/path.rs | 4 ++-- src/merkle/store/mod.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/merkle/path.rs b/src/merkle/path.rs index f2b12b77..a1dfdf23 100644 --- a/src/merkle/path.rs +++ b/src/merkle/path.rs @@ -174,8 +174,8 @@ pub struct ValuePath { impl ValuePath { /// Returns a new [ValuePath] instantiated from the specified value and path. - pub fn new(value: RpoDigest, path: Vec) -> Self { - Self { value, path: MerklePath::new(path) } + pub fn new(value: RpoDigest, path: MerklePath) -> Self { + Self { value, path } } } diff --git a/src/merkle/store/mod.rs b/src/merkle/store/mod.rs index 7e931904..9f9bf0d6 100644 --- a/src/merkle/store/mod.rs +++ b/src/merkle/store/mod.rs @@ -173,7 +173,7 @@ impl> MerkleStore { // the path is computed from root to leaf, so it must be reversed path.reverse(); - Ok(ValuePath::new(hash, path)) + Ok(ValuePath::new(hash, MerklePath::new(path))) } // LEAF TRAVERSAL From 0e5c64d703aa1ea09cfcf63395893b6d0047f3aa Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 09:44:02 -0500 Subject: [PATCH 112/117] Use `ValuePath` in simple smt --- src/merkle/path.rs | 8 ++++++++ src/merkle/smt/simple/mod.rs | 10 +++++----- src/merkle/smt/simple/tests.rs | 16 ++++++++-------- src/merkle/store/tests.rs | 14 +++++++------- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/merkle/path.rs b/src/merkle/path.rs index a1dfdf23..a9c86b1a 100644 --- a/src/merkle/path.rs +++ b/src/merkle/path.rs @@ -1,3 +1,5 @@ +use crate::Word; + use super::{vec, InnerNodeInfo, MerkleError, NodeIndex, Rpo256, RpoDigest, Vec}; use core::ops::{Deref, DerefMut}; use winter_utils::{ByteReader, Deserializable, DeserializationError, Serializable}; @@ -179,6 +181,12 @@ impl ValuePath { } } +impl From<(MerklePath, Word)> for ValuePath { + fn from((path, value): (MerklePath, Word)) -> Self { + ValuePath::new(value.into(), path) + } +} + /// A container for a [MerklePath] and its [Word] root. /// /// This structure does not provide any guarantees regarding the correctness of the path to the diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index a04e50b4..05c8e214 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -1,12 +1,12 @@ use crate::{ - merkle::{EmptySubtreeRoots, InnerNodeInfo, MerkleTreeDelta, StoreNode}, + merkle::{EmptySubtreeRoots, InnerNodeInfo, MerkleTreeDelta, StoreNode, ValuePath}, utils::collections::TryApplyDiff, EMPTY_WORD, }; use super::{ - InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, - SMT_MAX_DEPTH, SMT_MIN_DEPTH, + InnerNode, LeafIndex, MerkleError, NodeIndex, RpoDigest, SparseMerkleTree, Word, SMT_MAX_DEPTH, + SMT_MIN_DEPTH, }; use crate::utils::collections::{BTreeMap, BTreeSet}; @@ -147,7 +147,7 @@ impl SimpleSmt { /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle /// path to the leaf, as well as the leaf itself. - pub fn open(&self, key: &LeafIndex) -> (MerklePath, Word) { + pub fn open(&self, key: &LeafIndex) -> ValuePath { >::open(self, key) } @@ -246,7 +246,7 @@ impl SparseMerkleTree for SimpleSmt { type Key = LeafIndex; type Value = Word; type Leaf = Word; - type Opening = (MerklePath, Word); + type Opening = ValuePath; const EMPTY_VALUE: Self::Value = EMPTY_WORD; diff --git a/src/merkle/smt/simple/tests.rs b/src/merkle/smt/simple/tests.rs index 4ef501c7..87b385d7 100644 --- a/src/merkle/smt/simple/tests.rs +++ b/src/merkle/smt/simple/tests.rs @@ -59,7 +59,7 @@ fn build_sparse_tree() { assert_eq!(mt2.root(), smt.root()); assert_eq!( mt2.get_path(NodeIndex::make(3, 6)).unwrap(), - smt.open(&LeafIndex::<3>::new(6).unwrap()).0 + smt.open(&LeafIndex::<3>::new(6).unwrap()).path ); assert_eq!(old_value, EMPTY_WORD); @@ -72,7 +72,7 @@ fn build_sparse_tree() { assert_eq!(mt3.root(), smt.root()); assert_eq!( mt3.get_path(NodeIndex::make(3, 2)).unwrap(), - smt.open(&LeafIndex::<3>::new(2).unwrap()).0 + smt.open(&LeafIndex::<3>::new(2).unwrap()).path ); assert_eq!(old_value, EMPTY_WORD); } @@ -108,10 +108,10 @@ fn test_depth2_tree() { assert_eq!(VALUES4[3], tree.get_node(NodeIndex::make(2, 3)).unwrap()); // check get_path(): depth 2 - assert_eq!(vec![VALUES4[1], node3], *tree.open(&LeafIndex::<2>::new(0).unwrap()).0); - assert_eq!(vec![VALUES4[0], node3], *tree.open(&LeafIndex::<2>::new(1).unwrap()).0); - assert_eq!(vec![VALUES4[3], node2], *tree.open(&LeafIndex::<2>::new(2).unwrap()).0); - assert_eq!(vec![VALUES4[2], node2], *tree.open(&LeafIndex::<2>::new(3).unwrap()).0); + assert_eq!(vec![VALUES4[1], node3], *tree.open(&LeafIndex::<2>::new(0).unwrap()).path); + assert_eq!(vec![VALUES4[0], node3], *tree.open(&LeafIndex::<2>::new(1).unwrap()).path); + assert_eq!(vec![VALUES4[3], node2], *tree.open(&LeafIndex::<2>::new(2).unwrap()).path); + assert_eq!(vec![VALUES4[2], node2], *tree.open(&LeafIndex::<2>::new(3).unwrap()).path); } #[test] @@ -213,9 +213,9 @@ fn small_tree_opening_is_consistent() { ]; for (key, path) in cases { - let (opening, _) = tree.open(&LeafIndex::<3>::new(key).unwrap()); + let opening = tree.open(&LeafIndex::<3>::new(key).unwrap()); - assert_eq!(path, *opening); + assert_eq!(path, *opening.path); } } diff --git a/src/merkle/store/tests.rs b/src/merkle/store/tests.rs index 0ef51354..74986b47 100644 --- a/src/merkle/store/tests.rs +++ b/src/merkle/store/tests.rs @@ -182,7 +182,7 @@ fn test_leaf_paths_for_empty_trees() -> Result<(), MerkleError> { let index = NodeIndex::make(DEPTH, 0); let store_path = store.get_path(smt.root(), index)?; - let smt_path = smt.open(&LeafIndex::::new(0)?).0; + let smt_path = smt.open(&LeafIndex::::new(0)?).path; assert_eq!( store_path.value, RpoDigest::default(), @@ -301,7 +301,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 0 must match leaf value" ); assert_eq!( - smt.open(&LeafIndex::::new(0).unwrap()).0, + smt.open(&LeafIndex::::new(0).unwrap()).path, result.path, "merkle path for index 0 must be the same for the MerkleTree and MerkleStore" ); @@ -312,7 +312,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 1 must match leaf value" ); assert_eq!( - smt.open(&LeafIndex::::new(1).unwrap()).0, + smt.open(&LeafIndex::::new(1).unwrap()).path, result.path, "merkle path for index 1 must be the same for the MerkleTree and MerkleStore" ); @@ -323,7 +323,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 2 must match leaf value" ); assert_eq!( - smt.open(&LeafIndex::::new(2).unwrap()).0, + smt.open(&LeafIndex::::new(2).unwrap()).path, result.path, "merkle path for index 2 must be the same for the MerkleTree and MerkleStore" ); @@ -334,7 +334,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 3 must match leaf value" ); assert_eq!( - smt.open(&LeafIndex::::new(3).unwrap()).0, + smt.open(&LeafIndex::::new(3).unwrap()).path, result.path, "merkle path for index 3 must be the same for the MerkleTree and MerkleStore" ); @@ -346,7 +346,7 @@ fn test_sparse_merkle_tree() -> Result<(), MerkleError> { "Value for merkle path at index 4 must match leaf value" ); assert_eq!( - smt.open(&LeafIndex::::new(4).unwrap()).0, + smt.open(&LeafIndex::::new(4).unwrap()).path, result.path, "merkle path for index 4 must be the same for the MerkleTree and MerkleStore" ); @@ -563,7 +563,7 @@ fn test_constructors() -> Result<(), MerkleError> { for key in KEYS4 { let index = NodeIndex::make(DEPTH, key); let value_path = store.get_path(smt.root(), index)?; - assert_eq!(smt.open(&LeafIndex::::new(key).unwrap()).0, value_path.path); + assert_eq!(smt.open(&LeafIndex::::new(key).unwrap()).path, value_path.path); } let d = 2; From 5d7600612a854a2327b55c61eb62634c7324e154 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 10:01:34 -0500 Subject: [PATCH 113/117] remove `Smt` --- src/merkle/mod.rs | 2 +- src/merkle/smt/full/mod.rs | 366 ----------------------------------- src/merkle/smt/full/tests.rs | 278 -------------------------- src/merkle/smt/mod.rs | 3 - 4 files changed, 1 insertion(+), 648 deletions(-) delete mode 100644 src/merkle/smt/full/mod.rs delete mode 100644 src/merkle/smt/full/tests.rs diff --git a/src/merkle/mod.rs b/src/merkle/mod.rs index edd75d40..c3ad147e 100644 --- a/src/merkle/mod.rs +++ b/src/merkle/mod.rs @@ -25,7 +25,7 @@ mod path; pub use path::{MerklePath, RootPath, ValuePath}; mod smt; -pub use smt::{LeafIndex, SimpleSmt, Smt, SmtLeaf, SMT_DEPTH, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; +pub use smt::{LeafIndex, SimpleSmt, SMT_MAX_DEPTH, SMT_MIN_DEPTH}; mod tiered_smt; pub use tiered_smt::{TieredSmt, TieredSmtProof, TieredSmtProofError}; diff --git a/src/merkle/smt/full/mod.rs b/src/merkle/smt/full/mod.rs deleted file mode 100644 index c0cdaa69..00000000 --- a/src/merkle/smt/full/mod.rs +++ /dev/null @@ -1,366 +0,0 @@ -use core::cmp::Ordering; - -use winter_math::StarkField; - -use crate::hash::rpo::Rpo256; -use crate::merkle::EmptySubtreeRoots; -use crate::utils::{ - collections::{BTreeMap, BTreeSet, Vec}, - vec, -}; -use crate::{Felt, EMPTY_WORD}; - -use super::{ - InnerNode, LeafIndex, MerkleError, MerklePath, NodeIndex, RpoDigest, SparseMerkleTree, Word, -}; - -#[cfg(test)] -mod tests; - -// CONSTANTS -// ================================================================================================ - -pub const SMT_DEPTH: u8 = 64; - -// SMT -// ================================================================================================ - -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub struct Smt { - root: RpoDigest, - leaves: BTreeMap, - inner_nodes: BTreeMap, -} - -impl Smt { - // CONSTRUCTORS - // -------------------------------------------------------------------------------------------- - - /// Returns a new [NewSmt]. - /// - /// All leaves in the returned tree are set to [ZERO; 4]. - pub fn new() -> Self { - let root = *EmptySubtreeRoots::entry(SMT_DEPTH, 0); - - Self { - root, - leaves: BTreeMap::new(), - inner_nodes: BTreeMap::new(), - } - } - - /// Returns a new [SimpleSmt] instantiated with leaves set as specified by the provided entries. - /// - /// All leaves omitted from the entries list are set to [ZERO; 4]. - /// - /// # Errors - /// Returns an error if: - /// - The number of entries exceeds 2^63 entries. - /// - The provided entries contain multiple values for the same key. - pub fn with_entries( - entries: impl IntoIterator, - ) -> Result { - // create an empty tree - let mut tree = Self::new(); - - // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so - // entries with the empty value need additional tracking. - let mut key_set_to_zero = BTreeSet::new(); - - for (key, value) in entries { - let old_value = tree.insert(key, value); - - if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) { - return Err(MerkleError::DuplicateValuesForIndex( - LeafIndex::::from(key).value(), - )); - } - - if value == EMPTY_WORD { - key_set_to_zero.insert(key); - }; - } - Ok(tree) - } - - // PUBLIC ACCESSORS - // -------------------------------------------------------------------------------------------- - - /// Returns the depth of the tree - pub const fn depth(&self) -> u8 { - SMT_DEPTH - } - - /// Returns the root of the tree - pub fn root(&self) -> RpoDigest { - >::root(self) - } - - /// Returns the leaf at the specified index. - pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf { - >::get_leaf(self, key) - } - - /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle - /// path to the leaf, as well as the leaf itself. - pub fn open(&self, key: &RpoDigest) -> (MerklePath, SmtLeaf) { - >::open(self, key) - } - - // STATE MUTATORS - // -------------------------------------------------------------------------------------------- - - /// Inserts a value at the specified key, returning the previous value associated with that key. - /// Recall that by definition, any key that hasn't been updated is associated with - /// [`EMPTY_WORD`]. - /// - /// This also recomputes all hashes between the leaf (associated with the key) and the root, - /// updating the root itself. - pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word { - >::insert(self, key, value) - } - - // HELPERS - // -------------------------------------------------------------------------------------------- - - /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty - /// value, such that this is indeed an insertion. - fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option { - debug_assert_ne!(value, Self::EMPTY_VALUE); - - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); - - match self.leaves.get_mut(&leaf_index.value()) { - Some(leaf) => leaf.insert(key, value), - None => { - self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value))); - - None - } - } - } - - /// Removes key-value pair at leaf index pointed to by `key` if it exists. - fn perform_remove(&mut self, key: RpoDigest) -> Option { - let leaf_index: LeafIndex = Self::key_to_leaf_index(&key); - - if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) { - let (old_value, is_empty) = leaf.remove(key); - if is_empty { - self.leaves.remove(&leaf_index.value()); - } - old_value - } else { - // there's nothing stored at the leaf; nothing to update - None - } - } -} - -impl SparseMerkleTree for Smt { - type Key = RpoDigest; - type Value = Word; - type Leaf = SmtLeaf; - type Opening = (MerklePath, SmtLeaf); - - const EMPTY_VALUE: Self::Value = EMPTY_WORD; - - fn root(&self) -> RpoDigest { - self.root - } - - fn set_root(&mut self, root: RpoDigest) { - self.root = root; - } - - fn get_inner_node(&self, index: NodeIndex) -> InnerNode { - self.inner_nodes.get(&index).cloned().unwrap_or_else(|| { - let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1); - - InnerNode { left: *node, right: *node } - }) - } - - fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) { - self.inner_nodes.insert(index, inner_node); - } - - fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option { - // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key` - if value != Self::EMPTY_VALUE { - self.perform_insert(key, value) - } else { - self.perform_remove(key) - } - } - - fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf { - let leaf_pos = LeafIndex::::from(*key).value(); - - match self.leaves.get(&leaf_pos) { - Some(leaf) => leaf.clone(), - None => SmtLeaf::Single((*key, Self::EMPTY_VALUE)), - } - } - - fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest { - leaf.hash() - } - - fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex { - let most_significant_felt = key[3]; - LeafIndex::new_max_depth(most_significant_felt.as_int()) - } -} - -impl Default for Smt { - fn default() -> Self { - Self::new() - } -} - -// LEAF -// ================================================================================================ - -#[derive(Clone, Debug, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] -pub enum SmtLeaf { - Single((RpoDigest, Word)), - Multiple(Vec<(RpoDigest, Word)>), -} - -impl SmtLeaf { - /// Converts a leaf to a list of field elements - pub fn to_elements(&self) -> Vec { - self.clone().into_elements() - } - - /// Converts a leaf to a list of field elements - pub fn into_elements(self) -> Vec { - match self { - SmtLeaf::Single(kv_pair) => kv_to_elements(kv_pair).collect(), - SmtLeaf::Multiple(kv_pairs) => kv_pairs.into_iter().flat_map(kv_to_elements).collect(), - } - } - - /// Compute the hash of the leaf - pub fn hash(&self) -> RpoDigest { - match self { - SmtLeaf::Single((key, value)) => Rpo256::merge(&[*key, value.into()]), - SmtLeaf::Multiple(kvs) => { - let elements: Vec = kvs.iter().copied().flat_map(kv_to_elements).collect(); - Rpo256::hash_elements(&elements) - } - } - } - - // HELPERS - // --------------------------------------------------------------------------------------------- - - /// Insert key-value pair into the leaf; return the previous value associated with `key`, if - /// any. - fn insert(&mut self, key: RpoDigest, value: Word) -> Option { - match self { - SmtLeaf::Single(kv_pair) => { - if kv_pair.0 == key { - // the key is already in this leaf. Update the value and return the previous - // value - let old_value = kv_pair.1; - kv_pair.1 = value; - Some(old_value) - } else { - // Another entry is present in this leaf. Transform the entry into a list - // entry, and make sure the key-value pairs are sorted by key - let mut pairs = vec![*kv_pair, (key, value)]; - pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2)); - - *self = SmtLeaf::Multiple(pairs); - - None - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - kv_pairs[pos].1 = value; - - Some(old_value) - } - Err(pos) => { - kv_pairs.insert(pos, (key, value)); - - None - } - } - } - } - } - - /// Remove key-value pair into the leaf stored at key; return the previous value associated with - /// `key`, if any. We also return an `is_empty` flag which indicates whether the leaf became - /// empty, and must be removed from the data structure it is contained in. - fn remove(&mut self, key: RpoDigest) -> (Option, bool) { - match self { - SmtLeaf::Single((key_at_leaf, value_at_leaf)) => { - if *key_at_leaf == key { - // our key was indeed stored in the leaf, so we return the value that was stored - // in it, and indicate that the leaf should be removed - let old_value = *value_at_leaf; - - (Some(old_value), true) - } else { - // another key is stored at leaf; nothing to update - (None, false) - } - } - SmtLeaf::Multiple(kv_pairs) => { - match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) { - Ok(pos) => { - let old_value = kv_pairs[pos].1; - - kv_pairs.remove(pos); - debug_assert!(!kv_pairs.is_empty()); - - if kv_pairs.len() == 1 { - // convert the leaf into `Single` - *self = SmtLeaf::Single(kv_pairs[0]); - } - - (Some(old_value), false) - } - Err(_) => { - // other keys are stored at leaf; nothing to update - (None, false) - } - } - } - } - } -} - -// HELPER FUNCTIONS -// ================================================================================================ - -/// Converts a key-value tuple to an iterator of `Felt`s -fn kv_to_elements((key, value): (RpoDigest, Word)) -> impl Iterator { - let key_elements = key.into_iter(); - let value_elements = value.into_iter(); - - key_elements.chain(value_elements) -} - -/// Compares two keys, compared element-by-element using their integer representations starting with -/// the most significant element. -fn cmp_keys(key_1: RpoDigest, key_2: RpoDigest) -> Ordering { - for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() { - let v1 = v1.as_int(); - let v2 = v2.as_int(); - if v1 != v2 { - return v1.cmp(&v2); - } - } - - Ordering::Equal -} diff --git a/src/merkle/smt/full/tests.rs b/src/merkle/smt/full/tests.rs deleted file mode 100644 index f068e22f..00000000 --- a/src/merkle/smt/full/tests.rs +++ /dev/null @@ -1,278 +0,0 @@ -use super::*; -use crate::{ - merkle::{EmptySubtreeRoots, MerkleStore}, - ONE, WORD_SIZE, -}; - -/// This test checks that inserting twice at the same key functions as expected. The test covers -/// only the case where the key is alone in its leaf -#[test] -fn test_smt_insert_at_same_key() { - let mut smt = Smt::default(); - let mut store: MerkleStore = MerkleStore::default(); - - assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); - - let key_1: RpoDigest = { - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) - }; - let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); - - let value_1 = [ONE; WORD_SIZE]; - let value_2 = [ONE + ONE; WORD_SIZE]; - - // Insert value 1 and ensure root is as expected - { - let leaf_node = build_single_leaf_node(key_1, value_1); - let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - - let old_value_1 = smt.insert(key_1, value_1); - assert_eq!(old_value_1, EMPTY_WORD); - - assert_eq!(smt.root(), tree_root); - } - - // Insert value 2 and ensure root is as expected - { - let leaf_node = build_single_leaf_node(key_1, value_2); - let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - - let old_value_2 = smt.insert(key_1, value_2); - assert_eq!(old_value_2, value_1); - - assert_eq!(smt.root(), tree_root); - } -} - -/// This test checks that inserting twice at the same key functions as expected. The test covers -/// only the case where the leaf type is `SmtLeaf::Multiple` -#[test] -fn test_smt_insert_at_same_key_2() { - let key_already_present: RpoDigest = { - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - RpoDigest::from([ONE + ONE, ONE + ONE, ONE + ONE, Felt::new(raw)]) - }; - let key_already_present_index: NodeIndex = - LeafIndex::::from(key_already_present).into(); - let value_already_present = [ONE + ONE + ONE; WORD_SIZE]; - - let mut smt = - Smt::with_entries(core::iter::once((key_already_present, value_already_present))).unwrap(); - let mut store: MerkleStore = { - let mut store = MerkleStore::default(); - - let leaf_node = build_single_leaf_node(key_already_present, value_already_present); - store - .set_node(*EmptySubtreeRoots::entry(SMT_DEPTH, 0), key_already_present_index, leaf_node) - .unwrap(); - store - }; - - let key_1: RpoDigest = { - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) - }; - let key_1_index: NodeIndex = LeafIndex::::from(key_1).into(); - - assert_eq!(key_1_index, key_already_present_index); - - let value_1 = [ONE; WORD_SIZE]; - let value_2 = [ONE + ONE; WORD_SIZE]; - - // Insert value 1 and ensure root is as expected - { - // Note: key_1 comes first because it is smaller - let leaf_node = build_multiple_leaf_node(&[ - (key_1, value_1), - (key_already_present, value_already_present), - ]); - let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - - let old_value_1 = smt.insert(key_1, value_1); - assert_eq!(old_value_1, EMPTY_WORD); - - assert_eq!(smt.root(), tree_root); - } - - // Insert value 2 and ensure root is as expected - { - let leaf_node = build_multiple_leaf_node(&[ - (key_1, value_2), - (key_already_present, value_already_present), - ]); - let tree_root = store.set_node(smt.root(), key_1_index, leaf_node).unwrap().root; - - let old_value_2 = smt.insert(key_1, value_2); - assert_eq!(old_value_2, value_1); - - assert_eq!(smt.root(), tree_root); - } -} - -/// This test ensures that the root of the tree is as expected when we add 3 items at 3 different -/// keys. This also tests that the merkle paths produced are as expected. -#[test] -fn test_smt_insert_multiple_values() { - let mut smt = Smt::default(); - let mut store: MerkleStore = MerkleStore::default(); - - assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0)); - - let key_1: RpoDigest = { - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) - }; - - let key_2: RpoDigest = { - let raw = 0b_11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111_u64; - - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) - }; - - let key_3: RpoDigest = { - let raw = 0b_00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000_u64; - - RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]) - }; - - let value_1 = [ONE; WORD_SIZE]; - let value_2 = [ONE + ONE; WORD_SIZE]; - let value_3 = [ONE + ONE + ONE; WORD_SIZE]; - - let key_values = [(key_1, value_1), (key_2, value_2), (key_3, value_3)]; - - for (key, value) in key_values { - let key_index: NodeIndex = LeafIndex::::from(key).into(); - - let leaf_node = build_single_leaf_node(key, value); - let tree_root = store.set_node(smt.root(), key_index, leaf_node).unwrap().root; - - let old_value = smt.insert(key, value); - assert_eq!(old_value, EMPTY_WORD); - - assert_eq!(smt.root(), tree_root); - - let expected_path = store.get_path(tree_root, key_index).unwrap(); - assert_eq!(smt.open(&key).0, expected_path.path); - } -} - -/// This tests that inserting the empty value does indeed remove the key-value contained at the -/// leaf. We insert & remove 3 values at the same leaf to ensure that all cases are covered (empty, -/// single, multiple). -#[test] -fn test_smt_removal() { - let mut smt = Smt::default(); - - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - let key_1: RpoDigest = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]); - let key_2: RpoDigest = - RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]); - let key_3: RpoDigest = - RpoDigest::from([3_u64.into(), 3_u64.into(), 3_u64.into(), Felt::new(raw)]); - - let value_1 = [ONE; WORD_SIZE]; - let value_2 = [2_u64.into(); WORD_SIZE]; - let value_3: [Felt; 4] = [3_u64.into(); WORD_SIZE]; - - // insert key-value 1 - { - let old_value_1 = smt.insert(key_1, value_1); - assert_eq!(old_value_1, EMPTY_WORD); - - assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, value_1))); - } - - // insert key-value 2 - { - let old_value_2 = smt.insert(key_2, value_2); - assert_eq!(old_value_2, EMPTY_WORD); - - assert_eq!( - smt.get_leaf(&key_2), - SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) - ); - } - - // insert key-value 3 - { - let old_value_3 = smt.insert(key_3, value_3); - assert_eq!(old_value_3, EMPTY_WORD); - - assert_eq!( - smt.get_leaf(&key_3), - SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2), (key_3, value_3)]) - ); - } - - // remove key 3 - { - let old_value_3 = smt.insert(key_3, EMPTY_WORD); - assert_eq!(old_value_3, value_3); - - assert_eq!( - smt.get_leaf(&key_3), - SmtLeaf::Multiple(vec![(key_1, value_1), (key_2, value_2)]) - ); - } - - // remove key 2 - { - let old_value_2 = smt.insert(key_2, EMPTY_WORD); - assert_eq!(old_value_2, value_2); - - assert_eq!(smt.get_leaf(&key_2), SmtLeaf::Single((key_1, value_1))); - } - - // remove key 1 - { - let old_value_1 = smt.insert(key_1, EMPTY_WORD); - assert_eq!(old_value_1, value_1); - - assert_eq!(smt.get_leaf(&key_1), SmtLeaf::Single((key_1, EMPTY_WORD))); - } -} - -/// Tests that 2 key-value pairs stored in the same leaf have the same path -#[test] -fn test_smt_path_to_keys_in_same_leaf_are_equal() { - let raw = 0b_01101001_01101100_00011111_11111111_10010110_10010011_11100000_00000000_u64; - - let key_1: RpoDigest = RpoDigest::from([ONE, ONE, ONE, Felt::new(raw)]); - let key_2: RpoDigest = - RpoDigest::from([2_u64.into(), 2_u64.into(), 2_u64.into(), Felt::new(raw)]); - - let value_1 = [ONE; WORD_SIZE]; - let value_2 = [2_u64.into(); WORD_SIZE]; - - let smt = Smt::with_entries([(key_1, value_1), (key_2, value_2)]).unwrap(); - - assert_eq!(smt.open(&key_1), smt.open(&key_2)); -} - -// HELPERS -// -------------------------------------------------------------------------------------------- - -fn build_single_leaf_node(key: RpoDigest, value: Word) -> RpoDigest { - SmtLeaf::Single((key, value)).hash() -} - -fn build_multiple_leaf_node(kv_pairs: &[(RpoDigest, Word)]) -> RpoDigest { - let elements: Vec = kv_pairs - .iter() - .flat_map(|(key, value)| { - let key_elements = key.into_iter(); - let value_elements = (*value).into_iter(); - - key_elements.chain(value_elements) - }) - .collect(); - - Rpo256::hash_elements(&elements) -} diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index 03920952..e44cb57a 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -7,9 +7,6 @@ use crate::{ use super::{MerkleError, MerklePath, NodeIndex, Vec}; -mod full; -pub use full::{Smt, SmtLeaf, SMT_DEPTH}; - mod simple; pub use simple::SimpleSmt; From 1c92eebbdef7efedd238251c4bd1fb323590c6e2 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Wed, 17 Jan 2024 12:47:14 -0500 Subject: [PATCH 114/117] make `new_max_depth()` const --- src/merkle/smt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/mod.rs b/src/merkle/smt/mod.rs index e44cb57a..67bb8167 100644 --- a/src/merkle/smt/mod.rs +++ b/src/merkle/smt/mod.rs @@ -196,7 +196,7 @@ impl LeafIndex { } impl LeafIndex { - pub fn new_max_depth(value: u64) -> Self { + pub const fn new_max_depth(value: u64) -> Self { LeafIndex { index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value), } From b02cd4ad80b14a0a17935db3a383db65bc904e6e Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 18 Jan 2024 15:07:06 -0500 Subject: [PATCH 115/117] add EMPTY_VALUE --- src/merkle/smt/simple/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 05c8e214..71fd8124 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -28,6 +28,12 @@ pub struct SimpleSmt { } impl SimpleSmt { + // CONSTANTS + // -------------------------------------------------------------------------------------------- + + /// The default value used to compute the hash of empty leaves + pub const EMPTY_VALUE: Word = >::EMPTY_VALUE; + // CONSTRUCTORS // -------------------------------------------------------------------------------------------- From b009c59a3d0e7c0563c10806a45743953d65a166 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 18 Jan 2024 15:49:48 -0500 Subject: [PATCH 116/117] fix doc --- src/merkle/smt/simple/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 71fd8124..5507fb74 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -42,7 +42,7 @@ impl SimpleSmt { /// All leaves in the returned tree are set to [ZERO; 4]. /// /// # Errors - /// Returns an error if [DEPTH] is 0 or is greater than 64. + /// Returns an error if [Self::DEPTH] is 0 or is greater than 64. pub fn new() -> Result { // validate the range of the depth. if DEPTH < SMT_MIN_DEPTH { From a26a58ee335f80d35ac5395b4285618250c82492 Mon Sep 17 00:00:00 2001 From: Philippe Laferriere Date: Thu, 18 Jan 2024 15:52:11 -0500 Subject: [PATCH 117/117] fix doc --- src/merkle/smt/simple/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/merkle/smt/simple/mod.rs b/src/merkle/smt/simple/mod.rs index 5507fb74..4186cf7d 100644 --- a/src/merkle/smt/simple/mod.rs +++ b/src/merkle/smt/simple/mod.rs @@ -42,7 +42,7 @@ impl SimpleSmt { /// All leaves in the returned tree are set to [ZERO; 4]. /// /// # Errors - /// Returns an error if [Self::DEPTH] is 0 or is greater than 64. + /// Returns an error if DEPTH is 0 or is greater than 64. pub fn new() -> Result { // validate the range of the depth. if DEPTH < SMT_MIN_DEPTH {