-
Notifications
You must be signed in to change notification settings - Fork 80
store API proto AccountProof: optimize merkle node compression
#1178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
drahnr
wants to merge
9
commits into
bernhard-617-batch-proof
Choose a base branch
from
bernhard-617-optimize-merkle-node-compression
base: bernhard-617-batch-proof
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9c24483
use a partial SMT proof
drahnr 75743a3
changelog and a .
drahnr 30a2f95
add lookup for storage index per leaf
drahnr d58bc5e
fix
drahnr a8c8f2d
better representation in proto
drahnr 9423fa0
clippy
drahnr d9ea339
add comment to protobuf
drahnr 2a666a0
protobuf comment
drahnr af22a32
represent the internal merkle tree structure in protobuf
drahnr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,14 @@ | ||
| use std::collections::{HashMap, HashSet}; | ||
|
|
||
| use miden_objects::Word; | ||
| use miden_objects::crypto::merkle::{ | ||
| Forest, | ||
| InnerNode, | ||
| LeafIndex, | ||
| MerklePath, | ||
| MmrDelta, | ||
| NodeIndex, | ||
| PartialSmt, | ||
| SmtLeaf, | ||
| SmtProof, | ||
| SparseMerklePath, | ||
|
|
@@ -206,3 +211,226 @@ impl From<SmtProof> for proto::primitives::SmtOpening { | |
| } | ||
| } | ||
| } | ||
|
|
||
| // NODE INDEX | ||
| // ------------------------------------------------------------------------------------------------ | ||
| impl From<NodeIndex> for proto::primitives::NodeIndex { | ||
| fn from(value: NodeIndex) -> Self { | ||
| proto::primitives::NodeIndex { | ||
| depth: value.depth() as u32, | ||
| value: value.value(), | ||
| } | ||
| } | ||
| } | ||
| impl TryFrom<proto::primitives::NodeIndex> for NodeIndex { | ||
| type Error = ConversionError; | ||
| fn try_from(index: proto::primitives::NodeIndex) -> Result<Self, Self::Error> { | ||
| let depth = u8::try_from(index.depth)?; | ||
| let value = index.value; | ||
| Ok(NodeIndex::new(depth, value)?) | ||
| } | ||
| } | ||
|
Comment on lines
+217
to
+232
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Probably nothing, but we encode the depth as u32 and then cast it to u8. Should a comment be added about why is it always valid? |
||
|
|
||
| // PARTIAL SMT | ||
| // ------------------------------------------------------------------------------------------------ | ||
|
|
||
| impl TryFrom<proto::primitives::PartialSmt> for PartialSmt { | ||
| type Error = ConversionError; | ||
| fn try_from(value: proto::primitives::PartialSmt) -> Result<Self, Self::Error> { | ||
| let proto::primitives::PartialSmt { root, leaves, nodes } = value; | ||
| let root = root | ||
| .as_ref() | ||
| .ok_or(proto::primitives::PartialSmt::missing_field(stringify!(root)))? | ||
| .try_into()?; | ||
| // TODO ensure `!leaves.is_empty()` | ||
|
|
||
| // Convert other proto primitives to crypto types | ||
| let leaves = Result::<Vec<SmtLeaf>, _>::from_iter(try_convert(leaves))?; | ||
| let mut inner = | ||
| Result::<HashMap<NodeIndex, Word>, _>::from_iter(nodes.into_iter().map(|inner| { | ||
| let node_index = NodeIndex::try_from( | ||
| inner | ||
| .index | ||
| .ok_or(proto::primitives::NodeIndex::missing_field(stringify!(index)))?, | ||
| )?; | ||
| let digest = Word::try_from( | ||
| inner | ||
| .digest | ||
| .ok_or(proto::primitives::Digest::missing_field(stringify!(digest)))?, | ||
| )?; | ||
| Ok::<_, Self::Error>((node_index, digest)) | ||
| }))?; | ||
|
|
||
| let leaf_indices = | ||
| HashSet::<NodeIndex>::from_iter(leaves.iter().map(|leaf| leaf.index().into())); | ||
|
|
||
| // Must contain the leaves too | ||
| inner.extend(leaves.iter().map(|leaf| (leaf.index().into(), leaf.hash()))); | ||
|
|
||
| // Start constructing the partial SMT | ||
| // | ||
| // Construct a `MerklePath` per leaf by transcending from leaf digest down to depth 0. | ||
| // Then verify the merkle proof holds consistency and completeness checks and all | ||
| // required sibling nodes are present to deeduct required intermediate nodes. | ||
| let mut partial = PartialSmt::new(); | ||
| for leaf in leaves { | ||
| // Construct the merkle path: | ||
| let leaf_node_index: NodeIndex = leaf.index().into(); | ||
| let mut current = leaf_node_index.clone(); | ||
| let mut siblings = Vec::new(); | ||
|
|
||
| // If we ever try to trancend beyond this depth level, something is wrong and | ||
| // we must stop decoding. | ||
| let max_depth = leaf_node_index.depth(); | ||
| // root: 00 | ||
| // / \ | ||
| // 10 11 | ||
| // / \ / \ | ||
| // 20 21 22 23 | ||
| // / \ / \ / \ / \ | ||
| // leaves ... x y | ||
| // Iterate from the leaf up to the root (exclusive) | ||
| // We start by picking the sibling of `x`, `y`, our starting point and | ||
| // then moving towards the root `0`. By definition siblings have the same parent. | ||
| loop { | ||
| let sibling_idx = current.sibling(); | ||
| // TODO FIXME for a leaf we get another leaf, we need to ensure those are part of | ||
| // the inner set or contained in the inner HashMap | ||
| let sibling_digest = if let Some(sibling_digest) = inner.get(&sibling_idx) { | ||
| // Previous round already calculated the entry or it was given explicitly | ||
| *sibling_digest | ||
| } else { | ||
| // The entry does not exist, so we need to lazily follow the missing nodes and | ||
| // calculate recursively. | ||
|
|
||
| // DFS, build the subtree recursively, starting from the current sibling | ||
| let mut stack = Vec::<NodeIndex>::new(); | ||
| stack.push(sibling_idx.clone()); | ||
| loop { | ||
| let Some(idx) = stack.pop() else { | ||
| unreachable!( | ||
| "Must be an error, we must have nodes to resolve all questions, otherwise construction is borked" | ||
| ) | ||
| }; | ||
| if let Some(node_digest) = inner.get(&idx) { | ||
| if stack.is_empty() && idx == sibling_idx { | ||
| // we emptied the stack which means the current one is our desired | ||
| // starting point | ||
| break *node_digest; | ||
| } | ||
| // if the digest exists, we don't need to recurse | ||
| continue; | ||
| } | ||
| debug_assert!( | ||
| !leaf_indices.contains(&idx), | ||
| "For every relevant leaf, we must have the relevant value" | ||
| ); | ||
| let left = idx.left_child(); | ||
| let right = idx.right_child(); | ||
| if max_depth < left.depth() || max_depth < right.depth() { | ||
| // TODO might happen in case of a missing node, so we must handle this | ||
| // gracefully | ||
| unreachable!("graceful!") | ||
| } | ||
| // proceed if the inner nodes are unknown | ||
| if !inner.contains_key(&left) { | ||
| stack.push(left); | ||
| } | ||
| if !inner.contains_key(&right) { | ||
| stack.push(right); | ||
| } | ||
| // left and right exist, we can derive the digest for `idx` | ||
| if let Some(&left) = inner.get(&left) | ||
| && let Some(&right) = inner.get(&right) | ||
| { | ||
| let node = InnerNode { left, right }; | ||
| let node_digest = node.hash(); | ||
|
|
||
| if stack.is_empty() && idx == sibling_idx { | ||
| // we emptied the stack which means the current one is our desired | ||
| // starting point | ||
| break node_digest; | ||
| } | ||
| inner.insert(idx, node_digest); | ||
| } | ||
| } | ||
| }; | ||
| siblings.push(sibling_digest); | ||
|
|
||
| // Move up to the parent level, and repeat | ||
| current = current.parent(); | ||
| if current.depth() == 0 { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| let path = MerklePath::new(siblings); | ||
| path.verify(leaf_node_index.value(), leaf.hash(), &root).expect("It's fine"); | ||
| partial.add_path(leaf, path); | ||
| } | ||
| assert_eq!(partial.root(), root); // FIXME make error | ||
| Ok(partial) | ||
| } | ||
| } | ||
|
|
||
| impl From<PartialSmt> for proto::primitives::PartialSmt { | ||
| fn from(partial: PartialSmt) -> Self { | ||
| // Find all leaf digests, we need to include those, they are POIs | ||
| let mut leaves = Vec::new(); | ||
| for (key, value) in partial.entries() { | ||
| let leaf = partial.get_leaf(key).unwrap(); | ||
| leaves.push(crate::generated::primitives::SmtLeaf::from(leaf)); | ||
| } | ||
|
|
||
| // Now collect the minimal set of internal nodes to be able to recalc the intermediate nodes | ||
| // forming a partial smt | ||
| let mut retained = HashMap::<NodeIndex, Word>::new(); | ||
| for (idx, node) in partial.inner_node_indices() { | ||
| // if neither of the child keys are tracked, we cannot re-calc the inner node digest | ||
| // on-the-fly and hence need to add the node to the set to be transferred | ||
| if partial.get_value(node.left).is_err() || partial.get_value(node.left).is_err() { | ||
| retained.insert(idx, node.hash()); | ||
| continue; | ||
| } | ||
| } | ||
| let nodes = Vec::from_iter(retained.into_iter().map(|(index, digest)| { | ||
| crate::generated::primitives::InnerNode { | ||
| index: Some(crate::generated::primitives::NodeIndex::from(index)), | ||
| digest: Some(crate::generated::primitives::Digest::from(digest)), | ||
| } | ||
| })); | ||
| let root = Some(partial.root().into()); | ||
| // Remember: nodes and leaves as mutually exclusive | ||
| Self { root, nodes, leaves } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use miden_objects::crypto::merkle::{PartialSmt, Smt}; | ||
| use pretty_assertions::assert_eq; | ||
|
|
||
| use super::*; | ||
| #[test] | ||
| fn partial_smt_roundtrip() { | ||
| let mut x = Smt::new(); | ||
|
|
||
| x.insert(Word::from([1_u32, 2, 3, 4]), Word::from([5_u32, 6, 7, 8])); | ||
| x.insert(Word::from([10_u32, 11, 12, 13]), Word::from([14_u32, 15, 16, 17])); | ||
| x.insert(Word::from([0x00_u32, 0xFF, 0xFF, 0xFF]), Word::from([0x00_u32; 4])); | ||
| x.insert(Word::from([0xAA_u32, 0xFF, 0xFF, 0xFF]), Word::from([0xAA_u32; 4])); | ||
| x.insert(Word::from([0xBB_u32, 0xFF, 0xFF, 0xFF]), Word::from([0xBB_u32; 4])); | ||
| x.insert(Word::from([0xCC_u32, 0xFF, 0xFF, 0xFF]), Word::from([0xCC_u32; 4])); | ||
|
|
||
| let proof = x.open(&Word::from([10_u32, 11, 12, 13])); | ||
|
|
||
| let mut orig = PartialSmt::new(); | ||
| orig.add_proof(proof); | ||
| let orig = orig; | ||
|
|
||
| let proto = proto::primitives::PartialSmt::from(orig.clone()); | ||
| let recovered = PartialSmt::try_from(proto).unwrap(); | ||
|
|
||
| assert_eq!(orig, recovered); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking at the complexity of the code, I wonder if this should actually live in
miden-base. The main reason is that the client would need to deserialize this data but the client doesn't get anything from the node except for protobuf files.In
miden-base, we could attach the logic to thePartialStorageMapstruct. Basically, we need two things there:PartialStorageMapwe need to getSmtLeafs andInnerNodes from it. Not sure what the name of the function would be - but getting this data shouldn't be too difficult.SmtLeafs andInnerNodes, we need a constructor that would build the underlyingPartialSmtfrom this.Then, here in
miden-nodewe'll just need to convert these to/from protobuf structs - so, the logic will be pretty straight-forward.