feat: allow merging of leaves

Consider the case of a MMR with one entry, and a new entry is being
added. Both of these values are quite unique, they are at the same time
the root and only leaf of their corresponding tree. Currently this
representation is not supported by the [MerkleStore], so the leaves are
not in it. Once the two values are merged, they both become leaves of a
new tree under the new parent, and the existing validation didn't permit
that promotion from happening.

This lifts the validation, and changes the method to clarify that not
only `root` are being merged, by arbitrary nodes of a tree (leafs,
internal, or roots), with arbitrary mixing of each.
This commit is contained in:
Augusto F. Hack 2023-04-14 20:35:08 +02:00
parent 7fa03c7967
commit 3996374a8b
No known key found for this signature in database
GPG key ID: 3F3584B7FB1DFB76

View file

@ -478,26 +478,23 @@ impl MerkleStore {
Ok(RootPath { root, path })
}
/// Merges two elements and adds the resulting node into the store.
///
/// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
let root1: RpoDigest = root1.into();
let root2: RpoDigest = root2.into();
if !self.nodes.contains_key(&root1) {
Err(MerkleError::NodeNotInStore(root1.into(), NodeIndex::root()))
} else if !self.nodes.contains_key(&root1) {
Err(MerkleError::NodeNotInStore(root2.into(), NodeIndex::root()))
} else {
let parent: Word = Rpo256::merge(&[root1, root2]).into();
self.nodes.insert(
parent.into(),
Node {
left: root1,
right: root2,
},
);
let parent: Word = Rpo256::merge(&[root1, root2]).into();
self.nodes.insert(
parent.into(),
Node {
left: root1,
right: root2,
},
);
Ok(parent)
}
Ok(parent)
}
}