moreinlaw-kernel 0.3.1

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
Documentation
//! How instances refer to each other: an organization's address on the network, the public
//! set of organizations an instance knows, and the private list of those its Host verified. A
//! list that fails a check here is ignored, so its verifications are not counted.
//!
//! This runs on every federation sync and whenever a peer instance asks for the verified list.

use std::collections::BTreeSet;

use nostr::prelude::*;

use crate::params::MAX_LIST_COORDS;
use crate::params::{DISCOVERY_TAG, REGISTRATION_KIND};
pub use crate::params::{LIST_KIND, ORGS_SET_D, VERIFIED_SET_D};
use crate::registration::valid_slug;

pub fn coord(operator_hex: &str, slug: &str) -> String {
    format!("{REGISTRATION_KIND}:{operator_hex}:{slug}")
}

/// `30779:<64 lowercase hex>:<slug>` split into (operator hex, slug); anything else is None.
pub fn parse_coord(raw: &str) -> Option<(String, String)> {
    let mut parts = raw.splitn(3, ':');
    let (kind, key, slug) = (parts.next()?, parts.next()?, parts.next()?);
    let hex_ok = key.len() == 64 && key.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
    if kind != REGISTRATION_KIND.to_string() || !hex_ok || !valid_slug(slug) {
        return None;
    }
    Some((key.to_string(), slug.to_string()))
}

fn build_list(
    keys: &Keys,
    d: &str,
    title: &str,
    coords: &[String],
    created_at: Timestamp,
) -> Result<Event, String> {
    let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
    let sorted: BTreeSet<&String> = coords
        .iter()
        .filter(|c| parse_coord(c).is_some())
        .take(MAX_LIST_COORDS)
        .collect();
    let mut tags = vec![Tag::identifier(d), tag(&["title", title])?];
    for c in sorted {
        tags.push(tag(&["a", c])?);
    }
    tags.push(tag(&["t", DISCOVERY_TAG])?);
    EventBuilder::new(Kind::from(LIST_KIND as u16), "", tags)
        .custom_created_at(created_at)
        .to_event(keys)
        .map_err(|e| format!("could not sign the list: {e}"))
}

/// The public set of every organization this instance knows. Published to relays.
pub fn build_org_set(keys: &Keys, coords: &[String]) -> Result<Event, String> {
    build_org_set_at(keys, coords, Timestamp::now())
}

/// Same as `build_org_set` with an explicit time, so a caller with its own clock (and the
/// frozen test vectors) need not read the system one.
pub fn build_org_set_at(
    keys: &Keys,
    coords: &[String],
    created_at: Timestamp,
) -> Result<Event, String> {
    build_list(
        keys,
        ORGS_SET_D,
        "MoreInLaw organizations",
        coords,
        created_at,
    )
}

/// The private list of organizations this Host verified. Never published to a relay.
pub fn build_verified_list(
    keys: &Keys,
    coords: &[String],
    host_name: &str,
) -> Result<Event, String> {
    build_list(
        keys,
        VERIFIED_SET_D,
        &format!("Organizations verified by {host_name}"),
        coords,
        Timestamp::now(),
    )
}

/// Checks a kind-30003 list and returns its valid coordinates (sorted, deduped, capped).
pub fn parse_list(
    event: &Event,
    expected_d: &str,
    expected_pubkey: &PublicKey,
) -> Result<Vec<String>, String> {
    if event.kind.as_u64() != LIST_KIND {
        return Err("not a list event".to_string());
    }
    event
        .verify()
        .map_err(|_| "the list's signature does not verify".to_string())?;
    if &event.pubkey != expected_pubkey {
        return Err("the list was signed by a different key".to_string());
    }
    let mut d = None;
    let mut coords = BTreeSet::new();
    for tag in event.tags() {
        let parts = tag.as_vec();
        match (
            parts.first().map(String::as_str),
            parts.get(1).map(String::as_str),
        ) {
            (Some("d"), Some(v)) if d.is_none() => d = Some(v.to_string()),
            (Some("a"), Some(v)) if parse_coord(v).is_some() => {
                coords.insert(v.to_string());
            }
            _ => {}
        }
    }
    if d.as_deref() != Some(expected_d) {
        return Err("the list has an unexpected 'd' tag".to_string());
    }
    Ok(coords.into_iter().take(MAX_LIST_COORDS).collect())
}

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

    fn hex(c: char) -> String {
        c.to_string().repeat(64)
    }

    fn coords() -> Vec<String> {
        vec![
            coord(&hex('b'), "beta-law"),
            coord(&hex('a'), "alpha-law"),
            coord(&hex('a'), "alpha-law"),
            "garbage".to_string(),
            format!("30779:{}:Bad_Slug", hex('c')),
        ]
    }

    fn d_of(ev: &Event) -> Option<String> {
        ev.tags().iter().find_map(|t| {
            let v = t.as_vec();
            (v[0] == "d").then(|| v[1].clone())
        })
    }

    #[test]
    fn org_set_is_sorted_deduped_tagged_and_roundtrips() {
        let keys = Keys::generate();
        let ev = build_org_set(&keys, &coords()).unwrap();
        assert_eq!(ev.kind.as_u64(), 30003);
        assert_eq!(d_of(&ev).as_deref(), Some(ORGS_SET_D));
        let a_tags: Vec<String> = ev
            .tags()
            .iter()
            .filter(|t| t.as_vec()[0] == "a")
            .map(|t| t.as_vec()[1].clone())
            .collect();
        assert_eq!(
            a_tags,
            vec![coord(&hex('a'), "alpha-law"), coord(&hex('b'), "beta-law")]
        );
        assert!(ev
            .tags()
            .iter()
            .any(|t| t.as_vec() == vec!["t".to_string(), "moreinlaw".to_string()]));
        assert!(ev.tags().iter().any(
            |t| t.as_vec() == vec!["title".to_string(), "MoreInLaw organizations".to_string()]
        ));
        assert_eq!(
            parse_list(&ev, ORGS_SET_D, &keys.public_key()).unwrap(),
            a_tags
        );
    }

    #[test]
    fn verified_list_uses_its_own_d_and_title() {
        let keys = Keys::generate();
        let ev = build_verified_list(&keys, &coords(), "main-dev Law").unwrap();
        assert_eq!(d_of(&ev).as_deref(), Some(VERIFIED_SET_D));
        assert!(ev.tags().iter().any(|t| t.as_vec()
            == vec![
                "title".to_string(),
                "Organizations verified by main-dev Law".to_string()
            ]));
        assert!(parse_list(&ev, ORGS_SET_D, &keys.public_key()).is_err());
    }

    #[test]
    fn parse_list_rejects_wrong_author_kind_and_tampering() {
        let keys = Keys::generate();
        let ev = build_org_set(&keys, &coords()).unwrap();
        assert!(parse_list(&ev, ORGS_SET_D, &Keys::generate().public_key()).is_err());

        let other_kind =
            EventBuilder::new(Kind::Custom(30004), "", vec![Tag::identifier(ORGS_SET_D)])
                .to_event(&keys)
                .unwrap();
        assert!(parse_list(&other_kind, ORGS_SET_D, &keys.public_key()).is_err());

        let json = ev.as_json().replace("alpha-law", "alpha-lax");
        if let Ok(t) = Event::from_json(&json) {
            assert!(parse_list(&t, ORGS_SET_D, &keys.public_key()).is_err());
        }
    }

    #[test]
    fn parse_list_caps_the_number_of_coordinates() {
        let keys = Keys::generate();
        let tags: Vec<Tag> = std::iter::once(Tag::identifier(ORGS_SET_D))
            .chain((0..2100).map(|n| {
                Tag::parse(&["a".to_string(), coord(&hex('a'), &format!("org-{n:04}"))]).unwrap()
            }))
            .collect();
        let ev = EventBuilder::new(Kind::from(LIST_KIND as u16), "", tags)
            .to_event(&keys)
            .unwrap();
        assert_eq!(
            parse_list(&ev, ORGS_SET_D, &keys.public_key())
                .unwrap()
                .len(),
            MAX_LIST_COORDS
        );
    }

    #[test]
    fn coords_parse_only_in_the_exact_shape() {
        assert_eq!(
            parse_coord(&coord(&hex('a'), "alpha-law")),
            Some((hex('a'), "alpha-law".to_string()))
        );
        for bad in [
            "30778:".to_string() + &hex('a') + ":alpha-law",
            coord(&hex('A'), "alpha-law"),
            coord("abc", "alpha-law"),
            coord(&hex('a'), "x"),
            coord(&hex('a'), "has space"),
        ] {
            assert!(parse_coord(&bad).is_none(), "{bad}");
        }
    }
}