Skip to main content

cbcl_core/
certification.rs

1//! SPEC-026: declaration defaults. Resolving a committee grants no certification.
2#![forbid(unsafe_code)]
3use crate::sexpr::{Atom, SExpr};
4use alloc::{
5    string::{String, ToString},
6    vec::Vec,
7};
8
9#[derive(Debug, Clone, PartialEq, Eq, Default)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub enum Certification {
12    #[default]
13    HostGate,
14    QuorumBudget {
15        validators: Option<Vec<String>>,
16        faults: Option<u32>,
17    },
18}
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct Committee {
22    pub validators: Vec<String>,
23    pub faults: u32,
24    pub quorum: usize,
25}
26fn roster(keys: &[String]) -> Result<Vec<String>, String> {
27    if keys.is_empty() {
28        return Err("validator roster must not be empty".into());
29    }
30    let mut result = keys.to_vec();
31    if result.iter().any(|k| {
32        !k.starts_with('@')
33            || k.len() < 2
34            || !k
35                .chars()
36                .all(|c| c.is_ascii_alphanumeric() || "_-./!?+*<>=@".contains(c))
37    }) {
38        return Err("validators must be whole @key symbols".into());
39    }
40    result.sort();
41    if result.windows(2).any(|w| w[0] == w[1]) {
42        return Err("duplicate validator".into());
43    }
44    Ok(result)
45}
46impl Committee {
47    pub fn new(validators: &[String], faults: Option<u32>) -> Result<Self, String> {
48        let validators = roster(validators)?;
49        let n = validators.len();
50        let f = match faults {
51            Some(f) => f,
52            None => u32::try_from((n - 1) / 3).map_err(|_| "committee too large")?,
53        };
54        let f_usize = usize::try_from(f).map_err(|_| "fault bound too large")?;
55        if f_usize.checked_mul(3).and_then(|x| x.checked_add(1)) != Some(n) {
56            return Err("quorum-budget requires exactly 3f+1 validators".into());
57        }
58        Ok(Self {
59            validators,
60            faults: f,
61            quorum: 2 * f_usize + 1,
62        })
63    }
64    pub fn contains(&self, key: &str) -> bool {
65        self.validators
66            .binary_search_by(|k| k.as_str().cmp(key))
67            .is_ok()
68    }
69}
70impl Certification {
71    pub fn quorum_budget(
72        validators: Option<Vec<String>>,
73        faults: Option<u32>,
74    ) -> Result<Self, String> {
75        if let Some(keys) = validators {
76            let c = Committee::new(&keys, faults)?;
77            Ok(Self::QuorumBudget {
78                validators: Some(c.validators),
79                faults: Some(c.faults),
80            })
81        } else {
82            Ok(Self::QuorumBudget {
83                validators: None,
84                faults,
85            })
86        }
87    }
88    pub fn validate(&self) -> Result<(), String> {
89        if let Self::QuorumBudget {
90            validators: Some(keys),
91            faults,
92        } = self
93        {
94            Committee::new(keys, *faults)?;
95        }
96        Ok(())
97    }
98    /// `instance` is trusted, authenticated deployment configuration, not a request field.
99    pub fn resolve(&self, instance: Option<&[String]>) -> Result<Committee, String> {
100        let Self::QuorumBudget { validators, faults } = self else {
101            return Err("counter uses host-gate certification".into());
102        };
103        let keys = validators
104            .as_deref()
105            .or(instance)
106            .ok_or("quorum-budget requires a pinned instance validator roster")?;
107        let c = Committee::new(keys, *faults)?;
108        if validators.is_some() {
109            if let Some(bound) = instance {
110                if roster(bound)? != c.validators {
111                    return Err("instance validator roster differs from dialect".into());
112                }
113            }
114        }
115        Ok(c)
116    }
117    pub fn is_quorum(&self) -> bool {
118        matches!(self, Self::QuorumBudget { .. })
119    }
120    /// Omitted/explicit legacy mode retain identical pre-extension canonical bytes.
121    pub fn canonical_option(&self) -> Option<SExpr> {
122        let Self::QuorumBudget { validators, faults } = self else {
123            return None;
124        };
125        let symbol = |s: &str| SExpr::Atom(Atom::Symbol(s.to_string()));
126        let mut parts = alloc::vec![symbol("certification"), symbol("quorum-budget")];
127        if let Some(keys) = validators {
128            let mut ordered = keys.clone();
129            ordered.sort();
130            let mut xs = alloc::vec![symbol("validators")];
131            xs.extend(ordered.iter().map(|key| symbol(key)));
132            parts.push(SExpr::List(xs));
133        }
134        let bound = if let Some(keys) = validators {
135            Committee::new(keys, *faults).ok().map(|c| c.faults)
136        } else {
137            *faults
138        };
139        if let Some(f) = bound {
140            parts.push(SExpr::List(alloc::vec![
141                symbol("faults"),
142                SExpr::Atom(Atom::Num(i64::from(f)))
143            ]));
144        }
145        Some(SExpr::List(parts))
146    }
147}