Skip to main content

commonware_storage/merkle/
read.rs

1//! Shared read-only trait for merkleized data structures.
2
3use crate::merkle::{Family, Location, Position};
4use alloc::sync::Arc;
5use commonware_cryptography::Digest;
6use core::ops::Range;
7
8/// Read-only interface for a merkleized data structure.
9///
10/// This trait covers structural reads (size, leaves, retained nodes, pruning boundary). Proof
11/// construction stays on concrete types because it depends on caller-selected bagging.
12pub trait Readable: Send + Sync {
13    /// The Merkle family implemented by this structure.
14    type Family: Family;
15
16    /// The digest type used by this structure.
17    type Digest: Digest;
18
19    /// The error type returned by structural reads.
20    type Error;
21
22    /// Total number of nodes (retained + pruned).
23    fn size(&self) -> Position<Self::Family>;
24
25    /// Digest of the node at `pos`, or `None` if pruned / out of bounds.
26    fn get_node(&self, pos: Position<Self::Family>) -> Option<Self::Digest>;
27
28    /// Leaf location up to which pruning has been performed, or 0 if never pruned.
29    fn pruning_boundary(&self) -> Location<Self::Family>;
30
31    /// Total number of leaves.
32    fn leaves(&self) -> Location<Self::Family> {
33        Location::try_from(self.size()).expect("invalid merkle size")
34    }
35
36    /// `[start, end)` range of retained leaf locations.
37    fn bounds(&self) -> Range<Location<Self::Family>> {
38        self.pruning_boundary()..self.leaves()
39    }
40}
41
42impl<T: Readable> Readable for Arc<T> {
43    type Family = T::Family;
44    type Digest = T::Digest;
45    type Error = T::Error;
46
47    fn size(&self) -> Position<Self::Family> {
48        (**self).size()
49    }
50
51    fn get_node(&self, pos: Position<Self::Family>) -> Option<Self::Digest> {
52        (**self).get_node(pos)
53    }
54
55    fn pruning_boundary(&self) -> Location<Self::Family> {
56        (**self).pruning_boundary()
57    }
58}