Skip to main content

moreinlaw_kernel/
count.rs

1//! How many organizations vouch for another. Every instance shows this number next to an
2//! organization, so two instances that count differently show different trust for the same one.
3//!
4//! This runs whenever an instance builds its public summary or its admin list.
5
6use std::collections::HashSet;
7
8/// One peer's verified list, as far as counting needs it. `proved` means its address proof
9/// passed; `active` means this instance's operator approved it as a peer.
10#[derive(Debug, Clone, PartialEq)]
11pub struct PeerList {
12    pub org_id: i64,
13    pub proved: bool,
14    pub active: bool,
15    pub coords: Vec<String>,
16}
17
18/// How many distinct organizations verified `org_coord`: each proved, active peer (other than
19/// the organization itself) whose list contains it, plus this instance when it verified the
20/// organization and is not that organization.
21pub fn verified_by_count(
22    org_id: i64,
23    org_coord: &str,
24    is_self: bool,
25    verified_by_us: bool,
26    peers: &[PeerList],
27) -> i64 {
28    let by_peers: HashSet<i64> = peers
29        .iter()
30        .filter(|p| {
31            p.org_id != org_id && p.proved && p.active && p.coords.iter().any(|c| c == org_coord)
32        })
33        .map(|p| p.org_id)
34        .collect();
35    by_peers.len() as i64 + i64::from(verified_by_us && !is_self)
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use crate::lists::coord;
42
43    fn peer(org_id: i64, proved: bool, active: bool, coords: &[&str]) -> PeerList {
44        PeerList {
45            org_id,
46            proved,
47            active,
48            coords: coords.iter().map(|c| c.to_string()).collect(),
49        }
50    }
51
52    #[test]
53    fn counting_follows_the_rule() {
54        let target = coord(&"a".repeat(64), "alpha-law");
55        let t = target.as_str();
56        let peers = vec![
57            peer(2, true, true, &[t]),
58            peer(3, true, true, &[t]),
59            peer(4, false, true, &[t]),
60            peer(5, true, false, &[t]),
61            peer(7, true, true, &["30779:other"]),
62            // the org's own list never counts for itself
63            peer(1, true, true, &[t]),
64        ];
65        assert_eq!(verified_by_count(1, t, false, false, &peers), 2);
66        assert_eq!(verified_by_count(1, t, false, true, &peers), 3);
67        assert_eq!(
68            verified_by_count(1, t, true, true, &peers),
69            2,
70            "self never verifies itself"
71        );
72        assert_eq!(verified_by_count(9, t, false, false, &[]), 0);
73        // a peer listed twice still counts once
74        let dup = vec![peer(2, true, true, &[t]), peer(2, true, true, &[t])];
75        assert_eq!(verified_by_count(1, t, false, false, &dup), 1);
76    }
77}