uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! Where public keys and endpoints come from: a static [`Directory`], what a key lookup may
//! return ([`IntoKeys`]), and the DNS names of `[UFTP App. 4 §2]` in [`dns`].

use std::collections::HashMap;
use std::fmt;

use crate::cs1::PublicKeys;
use crate::error::{RejectKind, Rejection};
use crate::types::{InternetDomain, Role};

/// Why a key lookup failed. It maps to 419: the sender may retry once DNS or the
/// configuration is fixed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyLookupError(pub String);

impl fmt::Display for KeyLookupError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for KeyLookupError {}

/// What a key lookup may return: one key, or the keys of a rollover.
///
/// The lookup [`open`](crate::open) takes is a closure
/// `Fn(&InternetDomain, Role) -> Result<impl IntoKeys, KeyLookupError>`; a body that
/// verifies under any of the keys is accepted.
pub trait IntoKeys {
    /// The keys.
    fn into_keys(self) -> Vec<PublicKeys>;
}

impl IntoKeys for PublicKeys {
    fn into_keys(self) -> Vec<PublicKeys> {
        vec![self]
    }
}

impl IntoKeys for Vec<PublicKeys> {
    fn into_keys(self) -> Vec<PublicKeys> {
        self
    }
}

impl IntoKeys for &[PublicKeys] {
    fn into_keys(self) -> Vec<PublicKeys> {
        self.to_vec()
    }
}

impl<const N: usize> IntoKeys for [PublicKeys; N] {
    fn into_keys(self) -> Vec<PublicKeys> {
        self.to_vec()
    }
}

/// The most keys a participant may publish at once `[UFTP App. 4 §2]`.
pub const MAX_KEYS: usize = 2;

/// A participant you trade with: who it is, the keys it signs with, and where it
/// receives messages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Participant {
    /// Its Internet domain.
    pub domain: InternetDomain,
    /// Its role under that domain.
    pub role: Role,
    keys: Vec<PublicKeys>,
    /// The URL it receives messages at, such as
    /// `https://dso.example/shapeshifter/api/v3/message`.
    pub endpoint: Option<String>,
}

impl Participant {
    /// A participant with one key.
    #[must_use]
    pub fn new(domain: InternetDomain, role: Role, keys: PublicKeys) -> Self {
        Self {
            domain,
            role,
            keys: vec![keys],
            endpoint: None,
        }
    }

    /// Sets the endpoint URL.
    #[must_use]
    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
        self.endpoint = Some(url.into());
        self
    }

    /// Adds the next key of a rollover.
    ///
    /// # Errors
    /// If the participant already has [`MAX_KEYS`] keys.
    pub fn with_next_key(mut self, keys: PublicKeys) -> Result<Self, Rejection> {
        if self.keys.len() >= MAX_KEYS {
            return Err(too_many_keys(self.keys.len() + 1));
        }
        self.keys.push(keys);
        Ok(self)
    }

    /// Its current keys.
    #[must_use]
    pub fn keys(&self) -> &[PublicKeys] {
        &self.keys
    }
}

fn too_many_keys(n: usize) -> Rejection {
    Rejection::new(
        RejectKind::KeyLookup,
        "[UFTP App. 4 §2] up to two keys per role",
        format!("A participant publishes at most {MAX_KEYS} keys per role; this one has {n}."),
    )
}

/// A static set of participants, for configured deployments and tests. Use it as the key
/// lookup of [`open`](crate::open): `directory.lookup()`.
///
/// ```
/// use uftp::*;
///
/// let dso = SigningKey::from_seed(&[1; 32]);
/// let directory = Directory::new()
///     .with(Participant::new("dso.example".parse()?, Role::Dso, dso.public_keys([0; 32]))
///         .with_endpoint("https://dso.example/shapeshifter/api/v3/message"));
/// assert!(directory.get(&"dso.example".parse()?, Role::Dso).is_some());
/// # Ok::<(), Rejection>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Directory {
    participants: HashMap<(InternetDomain, Role), Participant>,
}

impl Directory {
    /// An empty directory.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The directory with `participant` added or replaced.
    #[must_use]
    pub fn with(mut self, participant: Participant) -> Self {
        self.insert(participant);
        self
    }

    /// Adds or replaces a participant.
    pub fn insert(&mut self, participant: Participant) {
        self.participants
            .insert((participant.domain.clone(), participant.role), participant);
    }

    /// Removes a participant, returning it.
    pub fn remove(&mut self, domain: &InternetDomain, role: Role) -> Option<Participant> {
        self.participants.remove(&(domain.clone(), role))
    }

    /// The participant with this domain and role.
    #[must_use]
    pub fn get(&self, domain: &InternetDomain, role: Role) -> Option<&Participant> {
        self.participants.get(&(domain.clone(), role))
    }

    /// All participants, in no particular order.
    pub fn iter(&self) -> impl Iterator<Item = &Participant> {
        self.participants.values()
    }

    /// The keys of the participant with this domain and role, as the key lookup of
    /// [`open`](crate::open) needs them.
    ///
    /// # Errors
    /// If the participant is not in the directory (419).
    pub fn keys(
        &self,
        domain: &InternetDomain,
        role: Role,
    ) -> Result<&[PublicKeys], KeyLookupError> {
        self.get(domain, role)
            .map(|p| p.keys.as_slice())
            .ok_or_else(|| KeyLookupError(format!("{domain} is not a known {role}")))
    }

    /// [`keys`](Self::keys) as the key lookup of [`open`](crate::open):
    /// `open(document, &options, directory.lookup())`.
    pub fn lookup<'a>(
        &'a self,
    ) -> impl Fn(&InternetDomain, Role) -> Result<&'a [PublicKeys], KeyLookupError> + Copy + 'a
    {
        move |domain, role| self.keys(domain, role)
    }
}

/// The DNS names of `[UFTP App. 4 §2]` and the parsing of their values. The library
/// resolves nothing: query these names with a DNSSEC-validating resolver and pass the
/// answers here.
pub mod dns {
    use super::{MAX_KEYS, too_many_keys};
    use crate::cs1::PublicKeys;
    use crate::error::{RejectKind, Rejection};
    use crate::types::{InternetDomain, Role};

    fn label(role: Role) -> &'static str {
        match role {
            Role::Agr => "agr",
            Role::Cro => "cro",
            Role::Dso => "dso",
        }
    }

    /// `_usef.<domain>`: the TXT record with the specification version implemented.
    #[must_use]
    pub fn version_record(domain: &InternetDomain) -> String {
        format!("_usef.{domain}")
    }

    /// `_<role>._usef.<domain>`: the TXT record with the role's public keys.
    #[must_use]
    pub fn keys_record(domain: &InternetDomain, role: Role) -> String {
        format!("_{}._usef.{domain}", label(role))
    }

    /// `_http._<role>._usef.<domain>`: the CNAME of the role's HTTPS endpoint.
    #[must_use]
    pub fn endpoint_record(domain: &InternetDomain, role: Role) -> String {
        format!("_http._{}._usef.{domain}", label(role))
    }

    /// `_usef.<domain>.<suffix>`: the name a regulator's zone answers for an authorised
    /// participant, such as `_usef.example.com.energy.authority.test`.
    #[must_use]
    pub fn authorization_record(domain: &InternetDomain, suffix: &str) -> String {
        format!("_usef.{domain}.{}", suffix.trim_matches('.'))
    }

    /// Parses the value of a `_<role>._usef` TXT record: one or two `cs1.` keys separated
    /// by whitespace.
    ///
    /// # Errors
    /// If there is no key, more than two, or any is not a valid CS1 key.
    pub fn parse_keys_txt(txt: &str) -> Result<Vec<PublicKeys>, Rejection> {
        let keys = txt
            .split_ascii_whitespace()
            .map(str::parse)
            .collect::<Result<Vec<PublicKeys>, _>>()?;
        match keys.len() {
            0 => Err(Rejection::new(
                RejectKind::KeyLookup,
                "[UFTP App. 4 §2] _role._usef TXT record",
                "The TXT record lists no key.",
            )),
            n if n > MAX_KEYS => Err(too_many_keys(n)),
            _ => Ok(keys),
        }
    }
}