Created
May 22, 2023 04:27
-
-
Save erwanor/a9d2d067f4a7f6733ef778abe36eec99 to your computer and use it in GitHub Desktop.
Deserializing a `Node`
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
use std::collections::BTreeMap; | |
use anyhow::{bail, Result}; | |
use borsh::{BorshDeserialize, BorshSerialize}; | |
use jmt::storage::{Node, NodeKey, TreeReader}; | |
use jmt::{JellyfishMerkleTree, KeyHash, OwnedValue, Sha256Jmt}; | |
use sha2::Sha256; | |
struct MockStorage { | |
values: BTreeMap<Vec<u8>, OwnedValue>, | |
tree: BTreeMap<NodeKey, Node>, | |
} | |
impl TreeReader for MockStorage { | |
fn get_node(&self, node_key: &jmt::storage::NodeKey) -> Result<Node> { | |
match self.tree.get(node_key).cloned() { | |
Some(node) => Ok(node), | |
None => bail!("no node found"), | |
} | |
} | |
fn get_node_option(&self, node_key: &jmt::storage::NodeKey) -> Result<Option<Node>> { | |
Ok(self.tree.get(node_key).cloned()) | |
} | |
fn get_value_option( | |
&self, | |
max_version: jmt::Version, | |
key_hash: jmt::KeyHash, | |
) -> Result<Option<jmt::OwnedValue>> { | |
let mut key = max_version.to_be_bytes().to_vec(); | |
let key_hash = key_hash.0.as_slice(); | |
key.extend_from_slice(key_hash); | |
let Some(value) = self.values.get(&key) else { | |
return Ok(None) | |
}; | |
Ok(Some(value.to_vec())) | |
} | |
fn get_rightmost_leaf( | |
&self, | |
) -> Result<Option<(jmt::storage::NodeKey, jmt::storage::LeafNode)>> { | |
unimplemented!() | |
} | |
} | |
impl Default for MockStorage { | |
fn default() -> Self { | |
Self { | |
values: BTreeMap::new(), | |
tree: BTreeMap::new(), | |
} | |
} | |
} | |
fn main() { | |
let db = MockStorage::default(); | |
let tree = Sha256Jmt::new(&db); | |
let keyhash = KeyHash::with::<Sha256>("goat"); | |
let value = "barn".to_string(); | |
let value = value.as_bytes().to_vec(); | |
let value_set = vec![(keyhash, Some(value))]; | |
let (root_hash, tree_update_batch) = tree.put_value_set(value_set, 0u64).unwrap(); | |
println!("root_hash: {root_hash:?}"); | |
println!("tree_update_batch: {tree_update_batch:?}"); | |
for (k, v) in tree_update_batch.node_batch.values() { | |
println!("(key, value) to persist:"); | |
println!("{k:?}, {v:?}"); | |
println!(""); | |
} | |
for (node_key, node) in tree_update_batch.node_batch.nodes() { | |
println!("node_key: {node_key:?}"); | |
println!("node: {node:?}"); | |
println!("serializing deserializing test:"); | |
let encoded_node = node.try_to_vec().unwrap(); | |
println!("encoded node: {encoded_node:?}"); | |
let decoded_node = Node::try_from_slice(&encoded_node).unwrap(); | |
println!("decoded node: {decoded_node:?}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cargo.toml for repro: