qualia_core_db/bundle/stream/proof/
hash.rs1use super::{ProofError, TreeSpec};
2use crate::net::qdnf::types::StrongDigest;
3use sha2::{Digest, Sha384};
4
5fn bind(h: &mut Sha384, spec: &TreeSpec) {
6 h.update(spec.context.as_bytes());
7 h.update(spec.entry.to_be_bytes());
8 h.update(spec.generation.to_be_bytes());
9 h.update([spec.representation as u8]);
10 h.update(spec.epoch.to_be_bytes());
11 h.update(spec.length.to_be_bytes());
12}
13fn finish(h: Sha384) -> StrongDigest {
14 StrongDigest(h.finalize().into())
15}
16
17pub fn leaf_hash(spec: &TreeSpec, index: u64, bytes: &[u8]) -> Result<StrongDigest, ProofError> {
18 let logical = spec.logical_leaf_length(index)?;
19 if bytes.len() != spec.encoded_leaf_length(index)? {
20 return Err(ProofError::Length);
21 }
22 let mut h = Sha384::new();
23 h.update(b"\x00qbdl-stream-pq-1/leaf/v1\0");
24 bind(&mut h, spec);
25 h.update(index.to_be_bytes());
26 h.update((logical as u32).to_be_bytes());
27 h.update((bytes.len() as u32).to_be_bytes());
28 h.update(bytes);
29 Ok(finish(h))
30}
31
32pub fn empty_root(spec: &TreeSpec) -> Result<StrongDigest, ProofError> {
33 if spec.leaf_count() != 0 {
34 return Err(ProofError::InvalidSpec);
35 }
36 let mut h = Sha384::new();
37 h.update(b"\x02qbdl-stream-pq-1/empty/v1\0");
38 bind(&mut h, spec);
39 Ok(finish(h))
40}
41
42pub(super) fn parent(left: StrongDigest, right: StrongDigest) -> StrongDigest {
43 let mut h = Sha384::new();
44 h.update(b"\x01qbdl-stream-pq-1/node/v1\0");
45 h.update(left.as_bytes());
46 h.update(right.as_bytes());
47 finish(h)
48}