ct_merkle/
lib.rs

1// The doc_cfg feature is only available in nightly. It lets us mark items in documentation as
2// dependent on specific features.
3#![cfg_attr(docsrs, feature(doc_cfg))]
4#![no_std]
5#![doc = include_str!("../README.md")]
6extern crate alloc;
7
8#[cfg(feature = "std")]
9extern crate std;
10
11pub use digest;
12
13mod consistency;
14mod error;
15mod inclusion;
16pub mod mem_backed_tree;
17mod tree_util;
18
19#[cfg(test)]
20mod test_util;
21
22pub use consistency::*;
23pub use error::*;
24pub use inclusion::*;
25pub use tree_util::*;
26
27use digest::Digest;
28use subtle::ConstantTimeEq;
29
30/// The root hash of a Merkle tree. This uniquely represents the tree.
31#[derive(Clone, Debug)]
32pub struct RootHash<H: Digest> {
33    /// The root hash of the Merkle tree that this root represents
34    root_hash: digest::Output<H>,
35
36    /// The number of leaves in the Merkle tree that this root represents.
37    num_leaves: u64,
38}
39
40impl<H: Digest> PartialEq for RootHash<H> {
41    /// Compares this `RootHash` to another in constant time.
42    fn eq(&self, other: &RootHash<H>) -> bool {
43        self.num_leaves == other.num_leaves() && self.root_hash.ct_eq(&other.root_hash).into()
44    }
45}
46
47impl<H: Digest> Eq for RootHash<H> {}
48
49impl<H: Digest> RootHash<H> {
50    /// Constructs a `RootHash` from the given hash digest and the number of leaves in the tree
51    /// that created it.
52    pub fn new(digest: digest::Output<H>, num_leaves: u64) -> RootHash<H> {
53        RootHash {
54            root_hash: digest,
55            num_leaves,
56        }
57    }
58
59    /// Returns the Merkle Tree Hash of the tree that created this `RootHash`.
60    ///
61    /// This is precisely the Merkle Tree Hash (MTH) of the tree that created it, as defined in [RFC
62    /// 6962 ยง2.1](https://www.rfc-editor.org/rfc/rfc6962.html#section-2.1).
63    pub fn as_bytes(&self) -> &digest::Output<H> {
64        &self.root_hash
65    }
66
67    /// Returns the number of leaves in the tree that created this `RootHash`.
68    pub fn num_leaves(&self) -> u64 {
69        self.num_leaves
70    }
71}