use std::collections::{BTreeMap, BTreeSet};
use p2panda_core::cbor::encode_cbor;
use proofs::Digest;
use serde::{Deserialize, Serialize};
use crate::moot::tessera::Policy;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AmendmentRule {
FounderSigned,
MemberQuorum {
electorate: BTreeSet<[u8; 32]>,
threshold: u16,
},
}
impl AmendmentRule {
pub fn permits(&self, founder: [u8; 32], actor: [u8; 32]) -> bool {
match self {
Self::FounderSigned => actor == founder,
Self::MemberQuorum {
electorate,
threshold,
} => {
*threshold > 0
&& usize::from(*threshold) <= electorate.len()
&& electorate.contains(&actor)
}
}
}
pub fn threshold(&self) -> usize {
match self {
Self::FounderSigned => 1,
Self::MemberQuorum { threshold, .. } => usize::from(*threshold),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilityGrant {
pub id: [u8; 32],
pub subject: [u8; 32],
pub path_prefix: String,
pub not_before_ms: u64,
pub expires_at_ms: Option<u64>,
#[serde(default, skip_serializing_if = "is_zero_u16")]
pub delegation_depth: u16,
}
fn is_zero_u16(value: &u16) -> bool {
*value == 0
}
impl CapabilityGrant {
pub fn covers(&self, subject: [u8; 32], path: &str, at_ms: u64) -> bool {
self.subject == subject
&& !self.path_prefix.is_empty()
&& at_ms >= self.not_before_ms
&& match self.expires_at_ms {
None => true,
Some(expires) => expires >= self.not_before_ms && at_ms <= expires,
}
&& (path == self.path_prefix
|| path
.strip_prefix(&self.path_prefix)
.is_some_and(|suffix| suffix.starts_with('/')))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConstitutionRules {
pub amendment: AmendmentRule,
pub checkpoint_signers: BTreeSet<[u8; 32]>,
pub admission: Policy,
pub capability_grants: BTreeMap<[u8; 32], CapabilityGrant>,
}
impl ConstitutionRules {
pub fn founder_only(founder: [u8; 32]) -> Self {
Self {
amendment: AmendmentRule::FounderSigned,
checkpoint_signers: [founder].into_iter().collect(),
admission: Policy::OpenWithFloor(Default::default()),
capability_grants: BTreeMap::new(),
}
}
pub fn grant(&mut self, grant: CapabilityGrant) {
self.capability_grants.insert(grant.id, grant);
}
pub fn revoke_grant(&mut self, grant_id: &[u8; 32]) -> Option<CapabilityGrant> {
self.capability_grants.remove(grant_id)
}
pub fn grant_covers(&self, subject: [u8; 32], path: &str, at_ms: u64) -> bool {
self.capability_grants
.values()
.any(|grant| grant.covers(subject, path, at_ms))
}
pub fn digest(&self) -> Digest {
let bytes = encode_cbor(self).expect("constitution rules always CBOR-encode");
Digest::blake3(&bytes)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConstitutionEvent {
Genesis {
moot_id: [u8; 32],
founder: [u8; 32],
parent_constitution: Option<Digest>,
divergence_point: Option<Digest>,
rules: ConstitutionRules,
rules_hash: Digest,
at_ms: u64,
},
Amended {
previous: Digest,
rules: ConstitutionRules,
rules_hash: Digest,
at_ms: u64,
},
}
impl ConstitutionEvent {
pub fn genesis(
moot_id: [u8; 32],
founder: [u8; 32],
parent_constitution: Option<Digest>,
divergence_point: Option<Digest>,
rules: ConstitutionRules,
at_ms: u64,
) -> Self {
let rules_hash = rules.digest();
Self::Genesis {
moot_id,
founder,
parent_constitution,
divergence_point,
rules,
rules_hash,
at_ms,
}
}
pub fn amended(previous: Digest, rules: ConstitutionRules, at_ms: u64) -> Self {
let rules_hash = rules.digest();
Self::Amended {
previous,
rules,
rules_hash,
at_ms,
}
}
pub fn at_ms(&self) -> u64 {
match self {
Self::Genesis { at_ms, .. } | Self::Amended { at_ms, .. } => *at_ms,
}
}
pub fn rules_are_bound(&self) -> bool {
match self {
Self::Genesis {
rules, rules_hash, ..
}
| Self::Amended {
rules, rules_hash, ..
} => rules.digest() == *rules_hash,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Serialize)]
struct LegacyCapabilityGrant {
id: [u8; 32],
subject: [u8; 32],
path_prefix: String,
not_before_ms: u64,
expires_at_ms: Option<u64>,
}
#[test]
fn direct_grants_keep_the_legacy_canonical_encoding() {
let legacy = LegacyCapabilityGrant {
id: [1; 32],
subject: [2; 32],
path_prefix: "moot/fauna".into(),
not_before_ms: 10,
expires_at_ms: Some(20),
};
let current = CapabilityGrant {
id: legacy.id,
subject: legacy.subject,
path_prefix: legacy.path_prefix.clone(),
not_before_ms: legacy.not_before_ms,
expires_at_ms: legacy.expires_at_ms,
delegation_depth: 0,
};
assert_eq!(
encode_cbor(&legacy).unwrap(),
encode_cbor(¤t).unwrap()
);
}
}