Skip to main content

zaun_community_protocol/signed/
validity.rs

1//! Descriptor and delegation validity (specification §4.3). Pure: the verifier's stored
2//! state and `now_ms` are parameters, and the updated state is returned.
3
4mod pair;
5
6pub use pair::{ValidPair, validate_pair};
7
8use super::descriptor::{CommunityDescriptor, DelegationRef};
9use super::error::{SignedError, ValidityError};
10use super::object::Signed;
11use super::rotation::{ChainHead, SignedRootRotation, claimed_genesis, verify_chain};
12use crate::crypto::content_hash;
13use crate::ids::CommunityId;
14use crate::json::SignedJson;
15
16/// Clock-skew allowance on delegation validity windows (rule 4), in milliseconds.
17pub const CLOCK_SKEW_MS: u64 = 300_000;
18
19/// What a verifier stores per community for anti-rollback (rule 5).
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct AcceptedState {
22    /// Highest accepted descriptor revision.
23    pub revision: u64,
24    /// `SHA3-256` of that descriptor's bytes (an equal revision must have equal bytes).
25    pub descriptor_hash: [u8; 32],
26    /// Highest accepted delegation epoch and its hash; none before the first delegation.
27    pub delegation: Option<DelegationRef>,
28    /// Highest accepted `rotation_seq` (0 when never rotated).
29    pub rotation_seq: u64,
30    /// `SHA3-256` of the root key accepted at `rotation_seq`; every later chain must pass
31    /// through that key, so a retired key cannot fork the chain.
32    pub root_key_hash: [u8; 32],
33    /// Highest accepted `min_suite`.
34    pub min_suite: u8,
35}
36
37/// A descriptor that passed rule 1 and the descriptor parts of rule 5.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct ValidDescriptor {
40    descriptor: Signed<CommunityDescriptor>,
41    chain: ChainHead,
42}
43
44impl ValidDescriptor {
45    /// The verified descriptor.
46    #[must_use]
47    pub const fn descriptor(&self) -> &Signed<CommunityDescriptor> {
48        &self.descriptor
49    }
50
51    /// The verified rotation chain.
52    #[must_use]
53    pub const fn chain(&self) -> &ChainHead {
54        &self.chain
55    }
56
57    /// The state to store after accepting this descriptor alone (for example a suspension):
58    /// the delegation part is carried over from `previous`.
59    #[must_use]
60    pub fn accepted_state(&self, previous: Option<&AcceptedState>) -> AcceptedState {
61        let d = self.descriptor.object();
62        AcceptedState {
63            revision: d.revision,
64            descriptor_hash: self.descriptor.hash(),
65            delegation: previous.and_then(|p| p.delegation),
66            rotation_seq: self.chain.rotation_seq(),
67            root_key_hash: content_hash(self.chain.key().as_bytes()),
68            min_suite: d.min_suite,
69        }
70    }
71}
72
73/// Rule 1 and the descriptor parts of rule 5: `chain` is the full rotation chain from the
74/// genesis key (`community.rotations`), `accepted` the verifier's stored state, if any.
75///
76/// # Errors
77/// [`ValidityError`] naming the first rule that fails.
78pub fn validate_descriptor(
79    community_id: &CommunityId,
80    descriptor: &SignedJson,
81    chain: &[SignedRootRotation],
82    accepted: Option<&AcceptedState>,
83) -> Result<ValidDescriptor, ValidityError> {
84    let genesis = claimed_genesis(&descriptor.bytes, chain)
85        .map_err(|e| ValidityError::Descriptor(SignedError::Decode(e)))?;
86    let chain_head = verify_chain(community_id, &genesis, chain)?;
87    let floor = accepted.map_or(1, |a| a.min_suite);
88    let signed = Signed::<CommunityDescriptor>::from_json(descriptor, chain_head.key(), floor)
89        .map_err(ValidityError::Descriptor)?;
90    let d = signed.object();
91    if d.community_id != *community_id {
92        return Err(ValidityError::Community);
93    }
94    if d.root_public_key != *chain_head.key() {
95        return Err(ValidityError::RootKey);
96    }
97    // SPEC: the descriptor carries only the latest rotation and the full chain comes from
98    // `community.rotations`; we require the embedded one to have the same canonical bytes as
99    // the chain's last element (not the same signature bytes, §3.2), and to be absent
100    // exactly when the chain is empty.
101    if d.rotations.last().map(|r| &r.bytes) != chain.last().map(|r| &r.bytes) {
102        return Err(ValidityError::EmbeddedRotation);
103    }
104    if chain_head.suite() < d.min_suite {
105        return Err(ValidityError::SuiteBelowMinimum);
106    }
107    if let Some(a) = accepted {
108        if d.revision < a.revision {
109            return Err(ValidityError::RevisionRollback);
110        }
111        if d.revision == a.revision && signed.hash() != a.descriptor_hash {
112            return Err(ValidityError::RevisionConflict);
113        }
114        // SPEC: rule 5 only rejects a shorter chain; we also require the chain to pass
115        // through the root key accepted at that length, or a retired key could fork it.
116        let then = chain_head
117            .key_at(a.rotation_seq)
118            .ok_or(ValidityError::ChainRollback)?;
119        if content_hash(then.as_bytes()) != a.root_key_hash {
120            return Err(ValidityError::RootKeyFork);
121        }
122        if d.min_suite < a.min_suite {
123            return Err(ValidityError::MinSuiteRollback);
124        }
125    }
126    Ok(ValidDescriptor {
127        descriptor: signed,
128        chain: chain_head,
129    })
130}