Skip to main content

zaun_community_protocol/signed/
delegation.rs

1//! `HostDelegation` (specification §4.2, ctx `zaun/v1/delegation`).
2
3use super::fields::{Rule, decode_checked, encode_checked, ensure, get_strings, put_strings};
4use super::object::{FORMAT_V1, SignedObject, read_format};
5use crate::crypto::{self, Context};
6use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
7use crate::ids::{CommunityId, HostId};
8use crate::keys::PublicKey;
9
10/// At most this many host addresses.
11const ADDRESSES_MAX: usize = 4;
12/// Bytes per host address.
13const ADDRESS_BYTES: usize = 2_048;
14
15bitflags::bitflags! {
16    /// Delegation scopes (field 6). Unknown bits are kept for re-encoding, are ignored and
17    /// grant nothing.
18    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19    pub struct Scopes: u64 {
20        /// Bit 0: serve the descriptor, run sessions, order events.
21        const OPERATE = 1 << 0;
22        /// Bit 1: redeem invitations and bind connections.
23        const ADMIT_MEMBERS = 1 << 1;
24        /// Bit 2: store and serve messages and history.
25        const STORE_CONTENT = 1 << 2;
26        /// Bit 3: apply bans, kicks, timeouts decided by authorised members.
27        const ENFORCE_MODERATION = 1 << 3;
28    }
29}
30
31impl Scopes {
32    /// Bits 0–3: a version-1 host refuses a delegation lacking any of them (§4.2).
33    pub const V1_HOST: Self = Self::all();
34}
35
36/// The root key's authorisation of one host to operate the community.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct HostDelegation {
39    /// 2: the community.
40    pub community_id: CommunityId,
41    /// 3: MUST equal the derivation from `host_public_key`.
42    pub host_id: HostId,
43    /// 4: the host key.
44    pub host_public_key: PublicKey,
45    /// 5: 1–4 SimpleX contact addresses of the host, each ≤ 2 048 bytes.
46    pub host_addresses: Vec<String>,
47    /// 6: scopes.
48    pub scopes: Scopes,
49    /// 7: ≥ 1.
50    pub epoch: u64,
51    /// 8: ms.
52    pub not_before: u64,
53    /// 9: ms; none = until replaced or revoked.
54    pub expires_at: Option<u64>,
55    /// 10: ms.
56    pub issued_at: u64,
57}
58
59impl HostDelegation {
60    fn rules(&self) -> Rule {
61        ensure(
62            self.host_id == crypto::host_id(&self.host_public_key),
63            "host_id",
64        )?;
65        ensure(
66            (1..=ADDRESSES_MAX).contains(&self.host_addresses.len()),
67            "host_addresses",
68        )?;
69        // SPEC: §4.2 bounds each address at 2 048 bytes but gives no minimum; an empty
70        // contact address is meaningless, so we require at least one byte.
71        let sizes = self
72            .host_addresses
73            .iter()
74            .all(|a| (1..=ADDRESS_BYTES).contains(&a.len()));
75        ensure(sizes, "host_addresses")?;
76        ensure(self.epoch >= 1, "epoch")
77    }
78
79    /// Whether the delegation grants every scope in `required` (unknown bits never count).
80    #[must_use]
81    pub fn grants(&self, required: Scopes) -> bool {
82        self.scopes.contains(required)
83    }
84}
85
86impl Encode for HostDelegation {
87    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
88        encode_checked(self.rules())?;
89        w.u8(FORMAT_V1);
90        w.put(&self.community_id)?;
91        w.put(&self.host_id)?;
92        w.put(&self.host_public_key)?;
93        put_strings(w, &self.host_addresses, ADDRESSES_MAX, ADDRESS_BYTES)?;
94        w.u64(self.scopes.bits());
95        w.u64(self.epoch);
96        w.u64(self.not_before);
97        w.option(self.expires_at.as_ref(), Writer::put)?;
98        w.u64(self.issued_at);
99        Ok(())
100    }
101}
102
103impl Decode for HostDelegation {
104    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
105        read_format(r)?;
106        let value = Self {
107            community_id: r.get()?,
108            host_id: r.get()?,
109            host_public_key: r.get()?,
110            host_addresses: get_strings(r, ADDRESSES_MAX, ADDRESS_BYTES)?,
111            scopes: Scopes::from_bits_retain(r.u64()?),
112            epoch: r.u64()?,
113            not_before: r.u64()?,
114            expires_at: r.option(Reader::get)?,
115            issued_at: r.u64()?,
116        };
117        decode_checked(value, Self::rules)
118    }
119}
120
121impl SignedObject for HostDelegation {
122    const CONTEXT: Context = Context::Delegation;
123}