jmt/
reader.rs

1use alloc::vec::Vec;
2use anyhow::{format_err, Result};
3
4use crate::node_type::{LeafNode, Node, NodeKey};
5use crate::{KeyHash, OwnedValue, Version};
6
7/// Defines the interface between a
8/// [`JellyfishMerkleTree`](crate::JellyfishMerkleTree)
9/// and underlying storage holding nodes.
10pub trait TreeReader {
11    /// Gets node given a node key. Returns error if the node does not exist.
12    fn get_node(&self, node_key: &NodeKey) -> Result<Node> {
13        self.get_node_option(node_key)?
14            .ok_or_else(|| format_err!("Missing node at {:?}.", node_key))
15    }
16
17    /// Gets node given a node key. Returns `None` if the node does not exist.
18    fn get_node_option(&self, node_key: &NodeKey) -> Result<Option<Node>>;
19
20    /// Gets a value by identifier, returning the newest value whose version is *less than or
21    /// equal to* the specified version. Returns an error if the value does not exist.
22    fn get_value(&self, max_version: Version, key_hash: KeyHash) -> Result<OwnedValue> {
23        self.get_value_option(max_version, key_hash)?
24            .ok_or_else(|| {
25                format_err!(
26                    "Missing value with max_version {max_version:} and key hash {key_hash:?}."
27                )
28            })
29    }
30
31    /// Gets a value by identifier, returning the newest value whose version is *less than or
32    /// equal to* the specified version.  Returns None if the value does not exist.
33    fn get_value_option(
34        &self,
35        max_version: Version,
36        key_hash: KeyHash,
37    ) -> Result<Option<OwnedValue>>;
38
39    /// Gets the rightmost leaf. Note that this assumes we are in the process of restoring the tree
40    /// and all nodes are at the same version.
41    fn get_rightmost_leaf(&self) -> Result<Option<(NodeKey, LeafNode)>>;
42}
43
44/// Defines the ability for a tree to look up the preimage of its key hashes.
45pub trait HasPreimage {
46    /// Gets the preimage of a key hash, if it is present in the tree.
47    fn preimage(&self, key_hash: KeyHash) -> Result<Option<Vec<u8>>>;
48}