ic_certified_map/
hashtree.rs

1#[cfg(test)]
2mod test;
3
4use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor};
5use serde::{Serialize, Serializer, ser::SerializeSeq};
6use serde_bytes::Bytes;
7use sha2::{Digest, Sha256};
8use std::borrow::Cow;
9use std::fmt;
10
11/// SHA-256 hash bytes.
12pub type Hash = [u8; 32];
13
14/// `HashTree` as defined in the [interfaces spec](https://internetcomputer.org/docs/current/references/ic-interface-spec#certificate).
15#[derive(Debug, Clone, Default)]
16pub enum HashTree<'a> {
17    /// No child nodes; a proof of absence.
18    #[default]
19    Empty,
20    /// Left and right child branches.
21    Fork(Box<(HashTree<'a>, HashTree<'a>)>),
22    /// A labeled child node.
23    Labeled(&'a [u8], Box<HashTree<'a>>),
24    /// A leaf node containing a value or hash.
25    Leaf(Cow<'a, [u8]>),
26    /// A branch that has been removed from this view of the tree, but is not necessarily absent.
27    Pruned(Hash),
28}
29
30/// Shorthand for [`HashTree::Fork`].
31pub fn fork<'a>(l: HashTree<'a>, r: HashTree<'a>) -> HashTree<'a> {
32    HashTree::Fork(Box::new((l, r)))
33}
34
35/// Shorthand for [`HashTree::Labeled`].
36pub fn labeled<'a>(l: &'a [u8], t: HashTree<'a>) -> HashTree<'a> {
37    HashTree::Labeled(l, Box::new(t))
38}
39
40/// Identifiably hashes a fork in the branch. Used for hashing [`HashTree::Fork`].
41pub fn fork_hash(l: &Hash, r: &Hash) -> Hash {
42    let mut h = domain_sep("ic-hashtree-fork");
43    h.update(&l[..]);
44    h.update(&r[..]);
45    h.finalize().into()
46}
47
48/// Identifiably hashes a leaf node's data. Used for hashing [`HashTree::Leaf`].
49pub fn leaf_hash(data: &[u8]) -> Hash {
50    let mut h = domain_sep("ic-hashtree-leaf");
51    h.update(data);
52    h.finalize().into()
53}
54
55/// Identifiably hashes a label for this branch. Used for hashing [`HashTree::Labeled`].
56pub fn labeled_hash(label: &[u8], content_hash: &Hash) -> Hash {
57    let mut h = domain_sep("ic-hashtree-labeled");
58    h.update(label);
59    h.update(&content_hash[..]);
60    h.finalize().into()
61}
62
63impl HashTree<'_> {
64    /// Produces the root hash of the tree.
65    pub fn reconstruct(&self) -> Hash {
66        match self {
67            Self::Empty => domain_sep("ic-hashtree-empty").finalize().into(),
68            Self::Fork(f) => fork_hash(&f.0.reconstruct(), &f.1.reconstruct()),
69            Self::Labeled(l, t) => {
70                let thash = t.reconstruct();
71                labeled_hash(l, &thash)
72            }
73            Self::Leaf(data) => leaf_hash(data),
74            Self::Pruned(h) => *h,
75        }
76    }
77}
78
79impl Serialize for HashTree<'_> {
80    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
81    where
82        S: Serializer,
83    {
84        match self {
85            HashTree::Empty => {
86                let mut seq = serializer.serialize_seq(Some(1))?;
87                seq.serialize_element(&0u8)?;
88                seq.end()
89            }
90            HashTree::Fork(p) => {
91                let mut seq = serializer.serialize_seq(Some(3))?;
92                seq.serialize_element(&1u8)?;
93                seq.serialize_element(&p.0)?;
94                seq.serialize_element(&p.1)?;
95                seq.end()
96            }
97            HashTree::Labeled(label, tree) => {
98                let mut seq = serializer.serialize_seq(Some(3))?;
99                seq.serialize_element(&2u8)?;
100                seq.serialize_element(Bytes::new(label))?;
101                seq.serialize_element(&tree)?;
102                seq.end()
103            }
104            HashTree::Leaf(leaf_bytes) => {
105                let mut seq = serializer.serialize_seq(Some(2))?;
106                seq.serialize_element(&3u8)?;
107                seq.serialize_element(Bytes::new(leaf_bytes.as_ref()))?;
108                seq.end()
109            }
110            HashTree::Pruned(digest) => {
111                let mut seq = serializer.serialize_seq(Some(2))?;
112                seq.serialize_element(&4u8)?;
113                seq.serialize_element(Bytes::new(&digest[..]))?;
114                seq.end()
115            }
116        }
117    }
118}
119
120impl<'de> Deserialize<'de> for HashTree<'de> {
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        struct HashTreeVisitor;
126
127        impl<'de> Visitor<'de> for HashTreeVisitor {
128            type Value = HashTree<'de>;
129
130            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131                formatter.write_str("a valid sequence representing a HashTree")
132            }
133
134            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
135            where
136                A: SeqAccess<'de>,
137            {
138                let variant: u8 = seq
139                    .next_element()?
140                    .ok_or_else(|| de::Error::invalid_length(0, &"variant for the HashTree"))?;
141
142                match variant {
143                    0 => Ok(HashTree::Empty),
144                    1 => {
145                        let left: HashTree<'de> = seq.next_element()?.ok_or_else(|| {
146                            de::Error::invalid_length(1, &"left child for the Fork")
147                        })?;
148                        let right: HashTree<'de> = seq.next_element()?.ok_or_else(|| {
149                            de::Error::invalid_length(2, &"right child for the Fork")
150                        })?;
151                        Ok(HashTree::Fork(Box::new((left, right))))
152                    }
153                    2 => {
154                        let label: &'de [u8] = seq.next_element()?.ok_or_else(|| {
155                            de::Error::invalid_length(1, &"label for the Labeled")
156                        })?;
157                        let tree: HashTree<'de> = seq
158                            .next_element()?
159                            .ok_or_else(|| de::Error::invalid_length(2, &"tree for the Labeled"))?;
160                        Ok(HashTree::Labeled(label, Box::new(tree)))
161                    }
162                    3 => {
163                        let bytes: &'de [u8] = seq
164                            .next_element()?
165                            .ok_or_else(|| de::Error::invalid_length(1, &"bytes for the Leaf"))?;
166                        Ok(HashTree::Leaf(Cow::Borrowed(bytes)))
167                    }
168                    4 => {
169                        let digest: &'de [u8] = seq.next_element()?.ok_or_else(|| {
170                            de::Error::invalid_length(1, &"digest for the Pruned")
171                        })?;
172                        let hash: Hash = digest.try_into().map_err(|_| {
173                            de::Error::invalid_length(digest.len(), &"32 bytes for the Hash")
174                        })?;
175                        Ok(HashTree::Pruned(hash))
176                    }
177                    _ => Err(de::Error::unknown_variant(
178                        &variant.to_string(),
179                        &["0", "1", "2", "3", "4"],
180                    )),
181                }
182            }
183        }
184
185        deserializer.deserialize_seq(HashTreeVisitor)
186    }
187}
188
189fn domain_sep(s: &str) -> sha2::Sha256 {
190    let buf: [u8; 1] = [s.len() as u8];
191    let mut h = Sha256::new();
192    h.update(&buf[..]);
193    h.update(s.as_bytes());
194    h
195}