uftp 0.1.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
//! Cryptographic Scheme Type 1 (CS1) `[UFTP App. 4 §1]`.
//!
//! CS1 is NaCl's `crypto_sign`: Ed25519 with the 64-byte signature placed in front of the
//! message, which yields the *sealed* message. A participant publishes its public signing
//! key and public encryption key (`crypto_box`) together, as `cs1.` followed by Base64 of
//! the 64 bytes.
//!
//! Verification is strict: non-canonical signatures and small-order keys are refused.

use std::fmt;
use std::str::FromStr;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use ed25519_dalek::{Signature, Signer as _};

use crate::error::{RejectKind, Rejection};

/// A participant's private signing key.
///
/// It is never printed: `Debug` shows `SigningKey(<redacted>)`. It has no `Display` and no
/// serialisation, and its memory is zeroed on drop. The library has no random
/// source, so the caller brings the seed.
#[derive(Clone)]
pub struct SigningKey(ed25519_dalek::SigningKey);

impl SigningKey {
    /// A key from its 32-byte seed (libsodium's `crypto_sign_seed_keypair`).
    #[must_use]
    pub fn from_seed(seed: &[u8; 32]) -> Self {
        Self(ed25519_dalek::SigningKey::from_bytes(seed))
    }

    /// A key from libsodium's 64-byte secret key (seed followed by public key), as
    /// `crypto_sign_keypair` returns it.
    ///
    /// # Errors
    /// If the public half does not belong to the seed.
    pub fn from_libsodium_secret(secret: &[u8; 64]) -> Result<Self, Rejection> {
        ed25519_dalek::SigningKey::from_keypair_bytes(secret)
            .map(Self)
            .map_err(|_| {
                Rejection::new(
                    RejectKind::Signature,
                    "[UFTP App. 4 §1] crypto_sign_keypair",
                    "The public half of the secret key does not match its seed.",
                )
            })
    }

    /// The public signing key.
    #[must_use]
    pub fn verifying_key(&self) -> VerifyingKey {
        VerifyingKey(self.0.verifying_key())
    }

    /// The published key pair: this key's public signing key with the given public
    /// encryption key.
    #[must_use]
    pub fn public_keys(&self, encryption_key: [u8; 32]) -> PublicKeys {
        PublicKeys {
            signing: self.verifying_key(),
            encryption: encryption_key,
        }
    }

    /// `crypto_sign`: the signature followed by the message.
    pub(crate) fn seal(&self, message: &[u8]) -> Vec<u8> {
        let signature: Signature = self.0.sign(message);
        let mut sealed = Vec::with_capacity(64 + message.len());
        sealed.extend_from_slice(&signature.to_bytes());
        sealed.extend_from_slice(message);
        sealed
    }
}

impl fmt::Debug for SigningKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SigningKey(<redacted>)")
    }
}

/// A public signing key.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct VerifyingKey(ed25519_dalek::VerifyingKey);

impl VerifyingKey {
    /// A key from its 32 bytes.
    ///
    /// # Errors
    /// If the bytes are not a valid Ed25519 point, or the point has small order.
    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, Rejection> {
        let key = ed25519_dalek::VerifyingKey::from_bytes(bytes)
            .map_err(|_| bad_key("The signing key is not a valid Ed25519 public key."))?;
        if key.is_weak() {
            return Err(bad_key(
                "The signing key has small order and would accept forged signatures.",
            ));
        }
        Ok(Self(key))
    }

    /// The 32 bytes.
    #[must_use]
    pub fn to_bytes(&self) -> [u8; 32] {
        self.0.to_bytes()
    }

    /// `crypto_sign_open`: verifies `sealed` strictly and returns the message it carries.
    pub(crate) fn open<'a>(&self, sealed: &'a [u8]) -> Result<&'a [u8], Rejection> {
        let invalid = || {
            Rejection::new(
                RejectKind::Signature,
                "[UFTP App. 4 §4] invalid signature",
                "The body does not verify under the sender's public signing key.",
            )
        };
        if sealed.len() < 64 {
            return Err(invalid());
        }
        let (sig, message) = sealed.split_at(64);
        let signature = Signature::from_slice(sig).map_err(|_| invalid())?;
        self.0
            .verify_strict(message, &signature)
            .map_err(|_| invalid())?;
        Ok(message)
    }
}

impl fmt::Debug for VerifyingKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VerifyingKey({})", STANDARD.encode(self.0.to_bytes()))
    }
}

fn bad_key(message: &str) -> Rejection {
    Rejection::new(
        RejectKind::KeyLookup,
        "[UFTP App. 4 §1] CS1 public key",
        message,
    )
}

/// A participant's published public keys: signing key and encryption key, written as
/// `cs1.` and Base64 of the 64 bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicKeys {
    signing: VerifyingKey,
    encryption: [u8; 32],
}

impl PublicKeys {
    /// The signing half.
    #[must_use]
    pub fn signing(&self) -> &VerifyingKey {
        &self.signing
    }

    /// The encryption half (`crypto_box`). It is carried but not used by this version.
    #[must_use]
    pub fn encryption(&self) -> &[u8; 32] {
        &self.encryption
    }
}

impl FromStr for PublicKeys {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let b64 = s
            .strip_prefix("cs1.")
            .ok_or_else(|| bad_key("A CS1 public key starts with `cs1.`."))?;
        let bytes = STANDARD
            .decode(b64)
            .map_err(|_| bad_key("The CS1 public key is not valid Base64."))?;
        let bytes: [u8; 64] = bytes.try_into().map_err(|v: Vec<u8>| {
            bad_key(&format!(
                "A CS1 public key is 64 bytes (signing key and encryption key); this one is {}.",
                v.len()
            ))
        })?;
        let mut signing = [0u8; 32];
        let mut encryption = [0u8; 32];
        signing.copy_from_slice(&bytes[..32]);
        encryption.copy_from_slice(&bytes[32..]);
        Ok(Self {
            signing: VerifyingKey::from_bytes(&signing)?,
            encryption,
        })
    }
}

impl fmt::Display for PublicKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&self.signing.to_bytes());
        bytes[32..].copy_from_slice(&self.encryption);
        write!(f, "cs1.{}", STANDARD.encode(bytes))
    }
}

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

    #[test]
    fn spec_example_key_is_not_a_valid_point() {
        // The example key of UFTP 3.1.0, Appendix 4 §1. Its signing half is not an Ed25519
        // point; libsodium's crypto_core_ed25519_is_valid_point agrees (spec note SS-10).
        let s = "cs1.V4lZrkYHq8FzneXxUML+QEMXMul3tBm+gPGoVDIZBA92VoWTu8/kRu2Zx72XOm1i/qwwoSgXjqSAqSa43myCaQ==";
        let e = s.parse::<PublicKeys>().unwrap_err();
        assert!(e.message().contains("not a valid Ed25519 public key"));
    }

    #[test]
    fn public_keys_print_and_parse() {
        let keys = SigningKey::from_seed(&[9; 32]).public_keys([5; 32]);
        let s = keys.to_string();
        assert!(s.starts_with("cs1."));
        assert_eq!(s.parse::<PublicKeys>().unwrap(), keys);
    }

    #[test]
    fn wrong_prefix_and_length_refused() {
        assert!(
            "cs2.AAAA"
                .parse::<PublicKeys>()
                .unwrap_err()
                .message()
                .contains("cs1.")
        );
        let short = format!("cs1.{}", STANDARD.encode([1u8; 63]));
        assert!(
            short
                .parse::<PublicKeys>()
                .unwrap_err()
                .message()
                .contains("63")
        );
    }

    #[test]
    fn seal_then_open() {
        let k = SigningKey::from_seed(&[7; 32]);
        let sealed = k.seal(b"hello");
        assert_eq!(sealed.len(), 69);
        assert_eq!(k.verifying_key().open(&sealed).unwrap(), b"hello");
        let mut tampered = sealed.clone();
        tampered[66] ^= 1;
        assert_eq!(
            k.verifying_key().open(&tampered).unwrap_err().http_status(),
            401
        );
    }

    #[test]
    fn debug_redacts() {
        let k = SigningKey::from_seed(&[7; 32]);
        assert_eq!(format!("{k:?}"), "SigningKey(<redacted>)");
    }
}