Skip to content

Commit

Permalink
jmt: simplify append api
Browse files Browse the repository at this point in the history
  • Loading branch information
erwanor committed Mar 17, 2024
1 parent 5b8dca5 commit 5d551cf
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,33 +446,36 @@ where
}

#[cfg(feature = "migration")]
/// Append value sets to the latest version of the tree.
pub fn append_value_sets(
/// Append value sets to the latest version of the tree, without incrementing its version.
pub fn append_value_set(
&self,
value_sets: impl IntoIterator<Item = impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>>,
value_set: impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>,
latest_version: Version,
) -> Result<(Vec<RootHash>, TreeUpdateBatch)> {
) -> Result<(RootHash, TreeUpdateBatch)> {
let mut tree_cache = TreeCache::new_overwrite(self.reader, latest_version)?;
for (idx, value_set) in value_sets.into_iter().enumerate() {
let version = latest_version + idx as u64;
for (i, (key, value)) in value_set.into_iter().enumerate() {
let action = if value.is_some() { "insert" } else { "delete" };
let value_hash = value.as_ref().map(|v| ValueHash::with::<H>(v));
tree_cache.put_value(version, key, value);
self.put(key, value_hash, version, &mut tree_cache, false)
.with_context(|| {
format!(
"failed to {} key {} for version {}, key = {:?}",
action, i, version, key
)
})?;
}

// Freezes the current cache to make all contents in the current cache immutable.
tree_cache.freeze::<H>()?;
for (i, (key, value)) in value_set.into_iter().enumerate() {
let action = if value.is_some() { "insert" } else { "delete" };
let value_hash = value.as_ref().map(|v| ValueHash::with::<H>(v));
tree_cache.put_value(latest_version, key, value);
self.put(key, value_hash, latest_version, &mut tree_cache, false)
.with_context(|| {
format!(
"failed to {} key {} for version {}, key = {:?}",
action, i, latest_version, key
)
})?;
}

Ok(tree_cache.into())
// Freezes the current cache to make all contents in the current cache immutable.
tree_cache.freeze::<H>()?;
let (root_hash_vec, tree_batch) = tree_cache.into();
if root_hash_vec.len() != 1 {
bail!(
"appending a value set failed, we expected a single root hash, but got {}",
root_hash_vec.len()
);
}
Ok((root_hash_vec[0], tree_batch))
}

/// Same as [`put_value_sets`], this method returns a Merkle proof for every update of the Merkle tree.
Expand Down

0 comments on commit 5d551cf

Please sign in to comment.