use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use crate::time::Timestamp;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PrincipalId(pub String);
impl PrincipalId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl<T: Into<String>> From<T> for PrincipalId {
fn from(v: T) -> Self {
Self(v.into())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MemberClass {
Agent,
Human,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attestation {
pub member: String,
pub principal: PrincipalId,
pub class: MemberClass,
#[serde(default)]
pub wot: f64,
pub at: Timestamp,
}
impl Attestation {
pub fn agent(
member: impl Into<String>,
principal: impl Into<PrincipalId>,
at: Timestamp,
) -> Self {
Self {
member: member.into(),
principal: principal.into(),
class: MemberClass::Agent,
wot: 0.0,
at,
}
}
pub fn human(member: impl Into<String>, wot: f64, at: Timestamp) -> Self {
let member = member.into();
Self {
principal: PrincipalId(member.clone()),
member,
class: MemberClass::Human,
wot,
at,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollapsedPrincipal {
pub id: PrincipalId,
pub class: MemberClass,
pub wot: f64,
pub members: usize,
pub first: Timestamp,
pub last: Timestamp,
}
pub fn collapse(attestations: &[Attestation]) -> Vec<CollapsedPrincipal> {
let mut by_principal: BTreeMap<&PrincipalId, (CollapsedPrincipal, Vec<&str>)> = BTreeMap::new();
for a in attestations {
let entry = by_principal.entry(&a.principal).or_insert_with(|| {
(
CollapsedPrincipal {
id: a.principal.clone(),
class: a.class,
wot: a.wot,
members: 0,
first: a.at,
last: a.at,
},
Vec::new(),
)
});
let (p, seen) = entry;
if a.class == MemberClass::Human {
p.class = MemberClass::Human;
}
p.wot = p.wot.max(a.wot);
p.first = p.first.min(a.at);
p.last = p.last.max(a.at);
if !seen.contains(&a.member.as_str()) {
seen.push(&a.member);
}
}
by_principal
.into_values()
.map(|(mut p, seen)| {
p.members = seen.len();
p
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ConfirmationPolicy {
pub agent_principal_weight: f64,
pub human_base_weight: f64,
pub human_max_weight: f64,
pub flag_weight: f64,
pub saturation_k: f64,
}
impl Default for ConfirmationPolicy {
fn default() -> Self {
Self {
agent_principal_weight: 1.0,
human_base_weight: 1.0,
human_max_weight: 3.0,
flag_weight: 1.0,
saturation_k: 0.462_098_12, }
}
}
impl ConfirmationPolicy {
pub fn principal_weight(&self, p: &CollapsedPrincipal) -> f64 {
match p.class {
MemberClass::Agent => self.agent_principal_weight,
MemberClass::Human => {
let wot = p.wot.clamp(0.0, 1.0);
self.human_base_weight + wot * (self.human_max_weight - self.human_base_weight)
}
}
}
pub fn weigh(&self, principals: &[CollapsedPrincipal]) -> f64 {
principals.iter().map(|p| self.principal_weight(p)).sum()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn t(n: i64) -> Timestamp {
Timestamp::from_secs(n)
}
#[test]
fn a_swarm_under_one_principal_collapses_to_one() {
let swarm: Vec<_> = (0..800)
.map(|i| Attestation::agent(format!("agent-{i}"), "did:nostr:one", t(i as i64)))
.collect();
let c = collapse(&swarm);
assert_eq!(c.len(), 1);
assert_eq!(c[0].members, 800, "the count is reported, never weighted");
assert_eq!(ConfirmationPolicy::default().weigh(&c), 1.0);
}
#[test]
fn three_principals_outrank_eight_hundred_accounts_under_two() {
let policy = ConfirmationPolicy::default();
let mut concentrated = Vec::new();
for i in 0..800 {
let p = if i % 2 == 0 {
"did:nostr:a"
} else {
"did:nostr:b"
};
concentrated.push(Attestation::agent(format!("agent-{i}"), p, t(i)));
}
let diverse: Vec<_> = ["x", "y", "z"]
.iter()
.map(|p| Attestation::agent(format!("agent-{p}"), format!("did:nostr:{p}"), t(0)))
.collect();
let (c, d) = (collapse(&concentrated), collapse(&diverse));
assert_eq!((c.len(), d.len()), (2, 3));
assert!(
policy.weigh(&d) > policy.weigh(&c),
"cq's headline trust rule must hold: {} vs {}",
policy.weigh(&d),
policy.weigh(&c)
);
}
#[test]
fn repeat_attestations_from_one_member_do_not_accrue() {
let once = vec![Attestation::agent("a", "did:nostr:p", t(0))];
let many: Vec<_> = (0..50)
.map(|i| Attestation::agent("a", "did:nostr:p", t(i)))
.collect();
let policy = ConfirmationPolicy::default();
assert_eq!(
policy.weigh(&collapse(&once)),
policy.weigh(&collapse(&many))
);
assert_eq!(collapse(&many)[0].members, 1);
}
#[test]
fn a_human_under_a_principal_upgrades_that_principals_class() {
let mixed = vec![
Attestation::agent("agent-1", "did:nostr:alice", t(0)),
Attestation::human("did:nostr:alice", 1.0, t(10)),
];
let c = collapse(&mixed);
assert_eq!(c.len(), 1);
assert_eq!(c[0].class, MemberClass::Human);
assert_eq!(c[0].members, 2);
assert_eq!(ConfirmationPolicy::default().principal_weight(&c[0]), 3.0);
}
#[test]
fn the_human_cap_is_worth_exactly_three_agent_operators() {
let policy = ConfirmationPolicy::default();
let human = collapse(&[Attestation::human("did:nostr:h", 1.0, t(0))]);
let swarm: Vec<_> = (0..40)
.map(|i| Attestation::agent(format!("a{i}"), "did:nostr:one", t(0)))
.collect();
let three: Vec<_> = ["p", "q", "r"]
.iter()
.map(|p| Attestation::agent(*p, format!("did:nostr:{p}"), t(0)))
.collect();
assert!(policy.weigh(&human) > policy.weigh(&collapse(&swarm)));
assert_eq!(
policy.weigh(&human),
policy.weigh(&collapse(&three)),
"the 3x cap, made concrete: a maximally trusted person equals three independent operators"
);
}
#[test]
fn cross_principal_agents_draw_full_weight() {
let policy = ConfirmationPolicy::default();
let a = collapse(&[Attestation::agent("a", "did:nostr:1", t(0))]);
let b = collapse(&[Attestation::agent("b", "did:nostr:2", t(0))]);
assert_eq!(policy.weigh(&a), policy.weigh(&b));
}
#[test]
fn collapse_is_order_independent() {
let mut xs = vec![
Attestation::agent("a", "did:nostr:2", t(5)),
Attestation::agent("b", "did:nostr:1", t(3)),
Attestation::human("did:nostr:1", 0.5, t(9)),
];
let first = collapse(&xs);
xs.reverse();
assert_eq!(first, collapse(&xs));
}
}