Skip to main content

zaun_community_protocol/signed/validity/
pair.rs

1//! Rules 2–5 for a (descriptor, delegation) pair (specification §4.3).
2
3use super::{AcceptedState, CLOCK_SKEW_MS, ValidDescriptor, validate_descriptor};
4use crate::crypto::content_hash;
5use crate::ids::CommunityId;
6use crate::json::SignedJson;
7use crate::signed::delegation::HostDelegation;
8use crate::signed::descriptor::{CommunityDescriptor, DelegationRef};
9use crate::signed::error::ValidityError;
10use crate::signed::object::Signed;
11use crate::signed::rotation::{ChainHead, SignedRootRotation};
12
13/// A (descriptor, delegation) pair valid at the time it was checked, with the state to store.
14/// Only [`validate_pair`] creates one.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ValidPair {
17    descriptor: Signed<CommunityDescriptor>,
18    delegation: Signed<HostDelegation>,
19    chain: ChainHead,
20    state: AcceptedState,
21}
22
23impl ValidPair {
24    /// The verified descriptor.
25    #[must_use]
26    pub const fn descriptor(&self) -> &Signed<CommunityDescriptor> {
27        &self.descriptor
28    }
29
30    /// The verified delegation.
31    #[must_use]
32    pub const fn delegation(&self) -> &Signed<HostDelegation> {
33        &self.delegation
34    }
35
36    /// The verified rotation chain.
37    #[must_use]
38    pub const fn chain(&self) -> &ChainHead {
39        &self.chain
40    }
41
42    /// The anti-rollback state to store for the community after accepting this pair.
43    #[must_use]
44    pub const fn state(&self) -> &AcceptedState {
45        &self.state
46    }
47}
48
49/// Rule 4 with the subtraction and addition rearranged so nothing over- or underflows:
50/// `not_before − skew ≤ now` and (`expires_at` none or `now ≤ expires_at + skew`).
51fn check_window(delegation: &HostDelegation, now_ms: u64) -> Result<(), ValidityError> {
52    if delegation.not_before > now_ms.saturating_add(CLOCK_SKEW_MS) {
53        return Err(ValidityError::NotYetValid);
54    }
55    match delegation.expires_at {
56        Some(expires) if now_ms > expires.saturating_add(CLOCK_SKEW_MS) => {
57            Err(ValidityError::Expired)
58        }
59        _ => Ok(()),
60    }
61}
62
63fn check_epoch(
64    current: DelegationRef,
65    accepted: Option<&AcceptedState>,
66) -> Result<(), ValidityError> {
67    match accepted.and_then(|a| a.delegation) {
68        Some(prev) if current.epoch < prev.epoch => Err(ValidityError::EpochRollback),
69        Some(prev)
70            if current.epoch == prev.epoch && current.delegation_hash != prev.delegation_hash =>
71        {
72            Err(ValidityError::EpochConflict)
73        }
74        _ => Ok(()),
75    }
76}
77
78/// Whether a (descriptor, delegation) pair is valid at `now_ms` (§4.3 rules 1–5). `chain` is
79/// the full rotation chain from the genesis key; `accepted` is the verifier's stored state
80/// for the community, if any. On success the returned pair carries the state to store.
81///
82/// # Errors
83/// [`ValidityError`] naming the first rule that fails.
84pub fn validate_pair(
85    community_id: &CommunityId,
86    descriptor: &SignedJson,
87    delegation: &SignedJson,
88    chain: &[SignedRootRotation],
89    accepted: Option<&AcceptedState>,
90    now_ms: u64,
91) -> Result<ValidPair, ValidityError> {
92    let valid = validate_descriptor(community_id, descriptor, chain, accepted)?;
93    let mut state = valid.accepted_state(accepted);
94    let ValidDescriptor {
95        descriptor,
96        chain: chain_head,
97    } = valid;
98    let d = descriptor.object();
99    let reference = d.delegation.ok_or(ValidityError::NoDelegation)?;
100    if content_hash(&delegation.bytes) != reference.delegation_hash {
101        return Err(ValidityError::DelegationHash);
102    }
103    let delegation = Signed::<HostDelegation>::from_json(delegation, chain_head.key(), d.min_suite)
104        .map_err(ValidityError::Delegation)?;
105    let g = delegation.object();
106    if g.epoch != reference.epoch {
107        return Err(ValidityError::DelegationEpoch);
108    }
109    if g.community_id != d.community_id {
110        return Err(ValidityError::DelegationCommunity);
111    }
112    check_window(g, now_ms)?;
113    check_epoch(reference, accepted)?;
114    state.delegation = Some(reference);
115    Ok(ValidPair {
116        descriptor,
117        delegation,
118        chain: chain_head,
119        state,
120    })
121}