use std::collections::HashMap;
use crate::moot::tessera::event::{BASIS_POINTS, ChainRoot, CommitmentId, TesseraEvent};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TesseraConfig {
pub fulfil_reward: i64,
pub lapse_penalty: i64,
pub governance_reward: i64,
pub depreciation_bp: u16,
pub vouch_loopback_bp: u16,
}
impl Default for TesseraConfig {
fn default() -> Self {
Self {
fulfil_reward: 10,
lapse_penalty: 20,
governance_reward: 1,
depreciation_bp: 5_000,
vouch_loopback_bp: 5_000,
}
}
}
#[derive(Clone, Debug)]
struct Commitment {
owner: ChainRoot,
cadence_ms: u64,
last_alive_ms: u64,
closed: bool,
}
impl Commitment {
fn is_lapsed(&self, now_ms: u64) -> bool {
!self.closed && now_ms.saturating_sub(self.last_alive_ms) > self.cadence_ms
}
}
#[derive(Clone, Debug)]
pub struct Ledger {
config: TesseraConfig,
commitments: HashMap<CommitmentId, Commitment>,
accruals: HashMap<ChainRoot, i64>,
vouchers_of: HashMap<ChainRoot, Vec<ChainRoot>>,
}
impl Ledger {
pub fn new(config: TesseraConfig) -> Self {
Self {
config,
commitments: HashMap::new(),
accruals: HashMap::new(),
vouchers_of: HashMap::new(),
}
}
pub fn config(&self) -> &TesseraConfig {
&self.config
}
pub fn from_events(config: TesseraConfig, events: &[TesseraEvent]) -> Self {
let mut ledger = Self::new(config);
for event in events {
ledger.apply(event);
}
ledger
}
fn open_owned_by(
&mut self,
commitment: &CommitmentId,
who: &ChainRoot,
) -> Option<&mut Commitment> {
self.commitments
.get_mut(commitment)
.filter(|c| !c.closed && c.owner == *who)
}
pub fn apply(&mut self, event: &TesseraEvent) {
match event {
TesseraEvent::CommitmentMade {
by,
commitment,
cadence_ms,
at_ms,
..
} => {
self.commitments.entry(*commitment).or_insert(Commitment {
owner: *by,
cadence_ms: *cadence_ms,
last_alive_ms: *at_ms,
closed: false,
});
}
TesseraEvent::Heartbeat {
by,
commitment,
at_ms,
} => {
if let Some(c) = self.open_owned_by(commitment, by) {
if *at_ms > c.last_alive_ms {
c.last_alive_ms = *at_ms;
}
}
}
TesseraEvent::CommitmentFulfilled { by, commitment, .. } => {
let fulfilled = match self.open_owned_by(commitment, by) {
Some(c) => {
c.closed = true;
true
}
None => false,
};
if fulfilled {
*self.accruals.entry(*by).or_default() += self.config.fulfil_reward;
}
}
TesseraEvent::CleanHandoff {
from,
to,
commitment,
at_ms,
} => {
if let Some(c) = self.open_owned_by(commitment, from) {
c.owner = *to;
c.last_alive_ms = *at_ms;
}
}
TesseraEvent::Vouch {
voucher,
newcomer,
fraction_bp,
..
} => {
let vouchers = self.vouchers_of.entry(*newcomer).or_default();
if !vouchers.contains(voucher) {
vouchers.push(*voucher);
}
let lent = self.accruals.get(voucher).copied().unwrap_or(0).max(0)
* (*fraction_bp as i64)
/ (BASIS_POINTS as i64);
if lent != 0 {
*self.accruals.entry(*newcomer).or_default() += lent;
}
}
TesseraEvent::GovernanceParticipation { by, .. } => {
*self.accruals.entry(*by).or_default() += self.config.governance_reward;
}
TesseraEvent::Pardon {
by, target, weight, ..
} => {
if by != target {
*self.accruals.entry(*target).or_default() += *weight as i64;
}
}
TesseraEvent::Censure {
by, target, weight, ..
} => {
if by != target {
*self.accruals.entry(*target).or_default() -= *weight as i64;
let loopback = *weight as i64 * (self.config.vouch_loopback_bp as i64)
/ (BASIS_POINTS as i64);
if loopback != 0 {
let vouchers = self.vouchers_of.get(target).cloned().unwrap_or_default();
for voucher in vouchers {
*self.accruals.entry(voucher).or_default() -= loopback;
}
}
}
}
}
}
pub fn lapsed(&self, now_ms: u64) -> Vec<(CommitmentId, ChainRoot)> {
self.commitments
.iter()
.filter(|(_, c)| c.is_lapsed(now_ms))
.map(|(id, c)| (*id, c.owner))
.collect()
}
pub fn scores(&self, now_ms: u64) -> HashMap<ChainRoot, i64> {
let mut scores = self.accruals.clone();
for (_, owner) in self.lapsed(now_ms) {
*scores.entry(owner).or_default() -= self.config.lapse_penalty;
}
scores
}
pub fn score(&self, chain_root: &ChainRoot, now_ms: u64) -> i64 {
let accrued = self.accruals.get(chain_root).copied().unwrap_or(0);
let lapses = self
.commitments
.values()
.filter(|c| c.owner == *chain_root && c.is_lapsed(now_ms))
.count() as i64;
accrued - lapses * self.config.lapse_penalty
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::moot::tessera::event::Scope;
fn root(n: u8) -> ChainRoot {
ChainRoot([n; 32])
}
fn cid(n: u8) -> CommitmentId {
CommitmentId([n; 32])
}
fn made(by: ChainRoot, commitment: CommitmentId, cadence_ms: u64, at_ms: u64) -> TesseraEvent {
TesseraEvent::CommitmentMade {
by,
commitment,
scope: Scope("session".into()),
cadence_ms,
duration_ms: None,
at_ms,
}
}
#[test]
fn fulfilment_raises_score() {
let a = root(1);
let c = cid(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c, 100, 0),
TesseraEvent::CommitmentFulfilled {
by: a,
commitment: c,
at_ms: 50,
},
],
);
assert_eq!(ledger.score(&a, 10_000), 10);
assert!(
ledger.lapsed(10_000).is_empty(),
"a fulfilled commitment can't lapse"
);
}
#[test]
fn silent_commitment_lapses_after_cadence() {
let a = root(1);
let c = cid(1);
let ledger = Ledger::from_events(TesseraConfig::default(), &[made(a, c, 100, 0)]);
assert_eq!(ledger.score(&a, 100), 0);
assert_eq!(ledger.score(&a, 101), -20);
assert_eq!(ledger.lapsed(101), vec![(c, a)]);
}
#[test]
fn heartbeats_keep_it_alive_then_lapse_and_revive() {
let a = root(1);
let c = cid(1);
let mut ledger = Ledger::new(TesseraConfig::default());
ledger.apply(&made(a, c, 100, 0));
ledger.apply(&TesseraEvent::Heartbeat {
by: a,
commitment: c,
at_ms: 80,
});
ledger.apply(&TesseraEvent::Heartbeat {
by: a,
commitment: c,
at_ms: 160,
});
assert_eq!(ledger.score(&a, 200), 0);
assert_eq!(ledger.score(&a, 400), -20);
ledger.apply(&TesseraEvent::Heartbeat {
by: a,
commitment: c,
at_ms: 410,
});
assert_eq!(
ledger.score(&a, 450),
0,
"lapse-and-revive: resuming clears the lapse"
);
}
#[test]
fn clean_handoff_moves_the_liability_not_a_penalty() {
let a = root(1);
let b = root(2);
let c = cid(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c, 100, 0),
TesseraEvent::CleanHandoff {
from: a,
to: b,
commitment: c,
at_ms: 50,
},
],
);
assert_eq!(ledger.score(&a, 1_000), 0, "A walked away clean");
assert_eq!(ledger.score(&b, 1_000), -20, "B owns the commitment now");
assert_eq!(ledger.lapsed(1_000), vec![(c, b)]);
}
#[test]
fn fulfilment_after_handoff_rewards_the_successor() {
let a = root(1);
let b = root(2);
let c = cid(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c, 100, 0),
TesseraEvent::CleanHandoff {
from: a,
to: b,
commitment: c,
at_ms: 50,
},
TesseraEvent::CommitmentFulfilled {
by: b,
commitment: c,
at_ms: 80,
},
],
);
assert_eq!(ledger.score(&a, 10_000), 0);
assert_eq!(
ledger.score(&b, 10_000),
10,
"the successor who finished it earns the reward"
);
}
#[test]
fn only_the_owner_can_heartbeat_or_fulfil() {
let a = root(1);
let stranger = root(9);
let c = cid(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c, 100, 0),
TesseraEvent::Heartbeat {
by: stranger,
commitment: c,
at_ms: 90,
},
TesseraEvent::CommitmentFulfilled {
by: stranger,
commitment: c,
at_ms: 95,
},
],
);
assert_eq!(ledger.score(&a, 1_000), -20);
assert_eq!(ledger.score(&stranger, 1_000), 0);
}
#[test]
fn governance_participation_rewards() {
let a = root(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
TesseraEvent::GovernanceParticipation { by: a, at_ms: 1 },
TesseraEvent::GovernanceParticipation { by: a, at_ms: 2 },
],
);
assert_eq!(ledger.score(&a, 10), 2);
}
#[test]
fn vouch_lends_a_fraction_of_the_vouchers_standing() {
let a = root(1);
let b = root(2);
let c = cid(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c, 100, 0),
TesseraEvent::CommitmentFulfilled {
by: a,
commitment: c,
at_ms: 10,
},
TesseraEvent::Vouch {
voucher: a,
newcomer: b,
fraction_bp: 5_000,
at_ms: 20,
},
],
);
assert_eq!(
ledger.score(&a, 1_000),
10,
"vouching lends, it does not spend the voucher's own score"
);
assert_eq!(
ledger.score(&b, 1_000),
5,
"the newcomer gets half of A's standing as a boost"
);
}
#[test]
fn a_mixed_sequence_yields_the_expected_scores() {
let a = root(1);
let b = root(2);
let (c1, c2) = (cid(1), cid(2));
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, c1, 100, 0),
TesseraEvent::CommitmentFulfilled {
by: a,
commitment: c1,
at_ms: 40,
},
made(a, c2, 100, 0), TesseraEvent::GovernanceParticipation { by: b, at_ms: 5 },
],
);
assert_eq!(ledger.score(&a, 1_000), -10);
assert_eq!(ledger.score(&b, 1_000), 1);
}
#[test]
fn censure_lowers_and_pardon_restores() {
let a = root(1);
let gov = root(50); let censured = Ledger::from_events(
TesseraConfig::default(),
&[TesseraEvent::Censure {
by: gov,
target: a,
weight: 30,
at_ms: 1,
}],
);
assert_eq!(censured.score(&a, 10), -30);
let pardoned = Ledger::from_events(
TesseraConfig::default(),
&[
TesseraEvent::Censure {
by: gov,
target: a,
weight: 30,
at_ms: 1,
},
TesseraEvent::Pardon {
by: gov,
target: a,
weight: 30,
at_ms: 2,
},
],
);
assert_eq!(pardoned.score(&a, 10), 0);
}
#[test]
fn a_pardon_can_forgive_a_lapse() {
let a = root(1);
let gov = root(50);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, cid(1), 100, 0), TesseraEvent::Pardon {
by: gov,
target: a,
weight: 20,
at_ms: 1,
},
],
);
assert_eq!(ledger.score(&a, 1_000), 0);
}
#[test]
fn you_cannot_judge_yourself() {
let a = root(1);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
TesseraEvent::Pardon {
by: a,
target: a,
weight: 100,
at_ms: 1,
},
TesseraEvent::Censure {
by: a,
target: a,
weight: 100,
at_ms: 2,
},
],
);
assert_eq!(ledger.score(&a, 10), 0);
}
#[test]
fn censure_of_a_vouchee_loops_back_to_the_voucher() {
let a = root(1); let b = root(2); let gov = root(50);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[
made(a, cid(1), 100, 0),
TesseraEvent::CommitmentFulfilled {
by: a,
commitment: cid(1),
at_ms: 10,
},
TesseraEvent::Vouch {
voucher: a,
newcomer: b,
fraction_bp: 5_000,
at_ms: 20,
},
TesseraEvent::Censure {
by: gov,
target: b,
weight: 30,
at_ms: 30,
},
],
);
assert_eq!(ledger.score(&b, 1_000), -25);
assert_eq!(ledger.score(&a, 1_000), -5);
}
#[test]
fn an_unvouched_censure_does_not_loop_back() {
let b = root(2);
let gov = root(50);
let ledger = Ledger::from_events(
TesseraConfig::default(),
&[TesseraEvent::Censure {
by: gov,
target: b,
weight: 30,
at_ms: 1,
}],
);
assert_eq!(ledger.score(&b, 10), -30);
assert_eq!(
ledger.score(&root(1), 10),
0,
"no voucher exists, nobody else is touched"
);
}
}