moreinlaw-kernel 0.3.3

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
Documentation
//! How many organizations vouch for another. Every instance shows this number next to an
//! organization, so two instances that count differently show different trust for the same one.
//!
//! This runs whenever an instance builds its public summary or its admin list.

use std::collections::HashSet;

/// One peer's verified list, as far as counting needs it. `proved` means its address proof
/// passed; `active` means this instance's operator approved it as a peer.
#[derive(Debug, Clone, PartialEq)]
pub struct PeerList {
    pub org_id: i64,
    pub proved: bool,
    pub active: bool,
    pub coords: Vec<String>,
}

/// How many distinct organizations verified `org_coord`: each proved, active peer (other than
/// the organization itself) whose list contains it, plus this instance when it verified the
/// organization and is not that organization.
pub fn verified_by_count(
    org_id: i64,
    org_coord: &str,
    is_self: bool,
    verified_by_us: bool,
    peers: &[PeerList],
) -> i64 {
    let by_peers: HashSet<i64> = peers
        .iter()
        .filter(|p| {
            p.org_id != org_id && p.proved && p.active && p.coords.iter().any(|c| c == org_coord)
        })
        .map(|p| p.org_id)
        .collect();
    by_peers.len() as i64 + i64::from(verified_by_us && !is_self)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lists::coord;

    fn peer(org_id: i64, proved: bool, active: bool, coords: &[&str]) -> PeerList {
        PeerList {
            org_id,
            proved,
            active,
            coords: coords.iter().map(|c| c.to_string()).collect(),
        }
    }

    #[test]
    fn counting_follows_the_rule() {
        let target = coord(&"a".repeat(64), "alpha-law");
        let t = target.as_str();
        let peers = vec![
            peer(2, true, true, &[t]),
            peer(3, true, true, &[t]),
            peer(4, false, true, &[t]),
            peer(5, true, false, &[t]),
            peer(7, true, true, &["30779:other"]),
            // the org's own list never counts for itself
            peer(1, true, true, &[t]),
        ];
        assert_eq!(verified_by_count(1, t, false, false, &peers), 2);
        assert_eq!(verified_by_count(1, t, false, true, &peers), 3);
        assert_eq!(
            verified_by_count(1, t, true, true, &peers),
            2,
            "self never verifies itself"
        );
        assert_eq!(verified_by_count(9, t, false, false, &[]), 0);
        // a peer listed twice still counts once
        let dup = vec![peer(2, true, true, &[t]), peer(2, true, true, &[t])];
        assert_eq!(verified_by_count(1, t, false, false, &dup), 1);
    }
}