zaun_community_protocol/signed/
delegation.rs1use 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
10const ADDRESSES_MAX: usize = 4;
12const ADDRESS_BYTES: usize = 2_048;
14
15bitflags::bitflags! {
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19 pub struct Scopes: u64 {
20 const OPERATE = 1 << 0;
22 const ADMIT_MEMBERS = 1 << 1;
24 const STORE_CONTENT = 1 << 2;
26 const ENFORCE_MODERATION = 1 << 3;
28 }
29}
30
31impl Scopes {
32 pub const V1_HOST: Self = Self::all();
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct HostDelegation {
39 pub community_id: CommunityId,
41 pub host_id: HostId,
43 pub host_public_key: PublicKey,
45 pub host_addresses: Vec<String>,
47 pub scopes: Scopes,
49 pub epoch: u64,
51 pub not_before: u64,
53 pub expires_at: Option<u64>,
55 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 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 #[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}