Skip to main content

zaun_community_protocol/crypto/
hash.rs

1//! Identifier derivations and content hashes (specification §2, §3.2).
2
3use sha3::{Digest, Sha3_256};
4
5use crate::ids::{CommunityId, HostId, PublisherId};
6use crate::keys::PublicKey;
7
8const COMMUNITY_DOMAIN: &[u8] = b"zaun/community-id/v1";
9const HOST_DOMAIN: &[u8] = b"zaun/host-id/v1";
10const PUBLISHER_DOMAIN: &[u8] = b"zaun/publisher-id/v1";
11
12fn domain_hash(domain: &[u8], key: &PublicKey) -> [u8; 32] {
13    let mut hasher = Sha3_256::new();
14    hasher.update(domain);
15    hasher.update([0x00]);
16    hasher.update(key.as_bytes());
17    hasher.finalize().into()
18}
19
20/// `CommunityId = SHA3-256("zaun/community-id/v1" ‖ 0x00 ‖ genesis root key)`, over the
21/// 1 985-byte encoding including the suite byte. Always the **genesis** key (§4.6).
22#[must_use]
23pub fn community_id(genesis_root: &PublicKey) -> CommunityId {
24    CommunityId::from_bytes(domain_hash(COMMUNITY_DOMAIN, genesis_root))
25}
26
27/// `HostId = SHA3-256("zaun/host-id/v1" ‖ 0x00 ‖ host public key)`.
28#[must_use]
29pub fn host_id(host_public_key: &PublicKey) -> HostId {
30    HostId::from_bytes(domain_hash(HOST_DOMAIN, host_public_key))
31}
32
33/// `PublisherId = SHA3-256("zaun/publisher-id/v1" ‖ 0x00 ‖ publisher key)` (§4.9).
34#[must_use]
35pub fn publisher_id(publisher_key: &PublicKey) -> PublisherId {
36    PublisherId::from_bytes(domain_hash(PUBLISHER_DOMAIN, publisher_key))
37}
38
39/// `SHA3-256(bytes)`: how signed objects are identified, deduplicated and chained (never by
40/// signature bytes, §3.2), for example a `delegation_hash`.
41#[must_use]
42pub fn content_hash(bytes: &[u8]) -> [u8; 32] {
43    Sha3_256::digest(bytes).into()
44}
45
46/// An incremental [`content_hash`], for attachment files read in pieces (§8.5).
47#[derive(Clone, Default)]
48pub struct Sha3Hasher(Sha3_256);
49
50impl std::fmt::Debug for Sha3Hasher {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.write_str("Sha3Hasher")
53    }
54}
55
56impl Sha3Hasher {
57    /// An empty hash.
58    #[must_use]
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// Feeds `bytes`.
64    pub fn update(&mut self, bytes: &[u8]) {
65        self.0.update(bytes);
66    }
67
68    /// The digest.
69    #[must_use]
70    pub fn finalize(self) -> [u8; 32] {
71        self.0.finalize().into()
72    }
73}