zeitgeist_protocol/
consensus.rs1use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
9pub struct ConsensusState {
10 pub holonomy: f64,
12 pub peer_agreement: f64,
14 pub crdt_version: BTreeMap<u64, u64>,
16}
17
18impl ConsensusState {
19 pub fn new(holonomy: f64, peer_agreement: f64, crdt_version: BTreeMap<u64, u64>) -> Self {
20 Self { holonomy, peer_agreement, crdt_version }
21 }
22
23 pub fn default() -> Self {
24 Self {
25 holonomy: 0.0,
26 peer_agreement: 1.0,
27 crdt_version: BTreeMap::new(),
28 }
29 }
30
31 pub fn check_alignment(&self) -> Vec<String> {
33 let mut violations = Vec::new();
34 if !(0.0..=1.0).contains(&self.peer_agreement) {
35 violations.push("consensus.peer_agreement must be 0-1".into());
36 }
37 violations
38 }
39
40 pub fn merge(&self, other: &Self) -> Self {
43 let holonomy = self.holonomy.min(other.holonomy);
44 let peer_agreement = self.peer_agreement.max(other.peer_agreement);
45
46 let mut crdt_version = self.crdt_version.clone();
48 for (k, v) in &other.crdt_version {
49 crdt_version
50 .entry(*k)
51 .and_modify(|existing| *existing = (*existing).max(*v))
52 .or_insert(*v);
53 }
54
55 Self { holonomy, peer_agreement, crdt_version }
56 }
57}