Skip to main content

zaun_community_protocol/signed/rotation/
head.rs

1//! The result of a verified rotation chain.
2
3use crate::keys::PublicKey;
4
5/// Every root key of a verified chain, `K₀` (genesis) to `Kₙ` (current). Only
6/// [`super::verify_chain`] creates one.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct ChainHead {
9    keys: Vec<PublicKey>,
10    suite: u8,
11}
12
13impl ChainHead {
14    /// A chain of only the genesis key.
15    pub(super) fn genesis_only(genesis: PublicKey) -> Self {
16        let suite = genesis.suite().byte();
17        Self {
18            keys: vec![genesis],
19            suite,
20        }
21    }
22
23    /// Appends `Kᵢ` after rotation `i` has been verified.
24    pub(super) fn push(&mut self, key: PublicKey, suite: u8) {
25        self.keys.push(key);
26        self.suite = suite;
27    }
28
29    /// `K₀`, from which the community id derives.
30    #[must_use]
31    pub fn genesis(&self) -> &PublicKey {
32        &self.keys[0]
33    }
34
35    /// The current root key `Kₙ`.
36    #[must_use]
37    pub fn key(&self) -> &PublicKey {
38        &self.keys[self.keys.len() - 1]
39    }
40
41    /// The root key after rotation `rotation_seq` (`K₀` for 0), if the chain is that long.
42    #[must_use]
43    pub fn key_at(&self, rotation_seq: u64) -> Option<&PublicKey> {
44        usize::try_from(rotation_seq)
45            .ok()
46            .and_then(|i| self.keys.get(i))
47    }
48
49    /// `n`: the last `rotation_seq`, 0 when never rotated.
50    #[must_use]
51    pub fn rotation_seq(&self) -> u64 {
52        // A chain cannot outgrow memory, let alone u64.
53        (self.keys.len() - 1) as u64
54    }
55
56    /// The suite of the current key (the last `new_suite`).
57    #[must_use]
58    pub const fn suite(&self) -> u8 {
59        self.suite
60    }
61}