Cotton code
171 lines · 6.9 KB · RustRaw
//! THE SAFETY NUMBER (22 Nov 2026): what two people//! compare to know their chat is sealed for each other's phones and nobody//! else's. `assets/design/chat/SEALING.md` "Safety numbers" says why it is//! over these keys; `CONTRACT.md` "Safety number" what the phones draw.//!//! **What it is over.** Cotton has no lasting key for a person: every box is//! sealed for each of a person's devices, to the key that device published//! (its `c1` chat key, and for a `c2` device the Olm identity and signing keys//! its record binds to it). So a person's half is over every device a sender//! seals for, as the keys answer tells them, under the person's stable id (their//! number, E.164). A Worker that handed out a key of its own for one device, or//! slipped in a device of its own, changes that half on one phone and not on//! the other, and the two numbers differ. The price is plain: the number also//! changes when either person sets up Comms on a new phone.//!//! **The derivation (version 1).** Each half is Signal's displayable//! fingerprint, kept as Signal does it: SHA-512 over the version, the keys and//! the id, then 5,200 times over the last hash and the keys; its first 30 bytes//! are six groups of five digits (each five bytes, big-endian, mod 100,000).//! The keys are each device's entry (`01 ‖ chat key`, or `02 ‖ chat key ‖//! identity ‖ signing`), sorted and de-duplicated, after the domain. The halves//! stand in the order of their ids, so both phones show the same twelve groups.//!//! **The code** is `cotton-safety:` and base64url of `version ‖ pair tag ‖ the//! two halves in the same order`: the same text on both phones when they//! agree. The pair tag (8 bytes of SHA-256 over the two ids) tells a code of//! another chat from a code of this one that does not match.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use sha2::{Digest, Sha256, Sha512};/// This build's derivation. A change to any step is a new version, never a change to this one.pub const VERSION: u8 = 1;/// The hash's rounds (Signal's).pub const ITERATIONS: u32 = 5_200;/// Groups of five digits the number shows: six for each person.pub const GROUPS: usize = 12;/// What every code starts with, so a camera can tell one.pub const CODE_PREFIX: &str = "cotton-safety:";const KEYS_DOMAIN: &[u8] = b"cotton-safety-keys";const PAIR_DOMAIN: &[u8] = b"cotton-safety-pair";const TAG_LEN: usize = 8;const HALF_LEN: usize = 30;const CODE_LEN: usize = 1 + TAG_LEN + 2 * HALF_LEN;/// One device a sender seals for: its chat key, and its `c2` identity and signing keys when its record verifies.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Device {    pub chat: [u8; 32],    pub c2: Option<([u8; 32], [u8; 32])>,}/// One person's half: the first 30 bytes of their iterated hash.pub type Half = [u8; HALF_LEN];/// What a scanned code says of this chat.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Scan {    /// Both halves are the ones this phone has.    Matched,    /// A code of this chat whose halves differ: one of the phones was told other keys.    NotMatched,    /// A code of another pair of people.    NotThisChat,}/// A code that is not one.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum CodeError {    Malformed,    /// A code from a build whose derivation this one does not know.    OtherVersion(u8),}fn entry(device: &Device) -> Vec<u8> {    match device.c2 {        None => [&[1u8][..], &device.chat].concat(),        Some((identity, signing)) => [&[2u8][..], &device.chat, &identity, &signing].concat(),    }}/// The keys a half is over: the domain, then each device's entry, sorted, once each.fn keys(devices: &[Device]) -> Vec<u8> {    let mut entries: Vec<Vec<u8>> = devices.iter().map(entry).collect();    entries.sort();    entries.dedup();    let mut out = KEYS_DOMAIN.to_vec();    out.extend((entries.len() as u32).to_be_bytes());    for e in entries {        out.extend(e);    }    out}/// One person's half, over every device of theirs a sender seals for, under their number.pub fn half(id: &str, devices: &[Device]) -> Half {    let keys = keys(devices);    let mut hash = Sha512::new().chain_update([0u8, VERSION]).chain_update(&keys).chain_update(id.as_bytes()).finalize();    for _ in 0..ITERATIONS {        hash = Sha512::new().chain_update(hash).chain_update(&keys).finalize();    }    let mut out = [0u8; HALF_LEN];    out.copy_from_slice(&hash[..HALF_LEN]);    out}/// A half as text, to keep beside a contact.pub fn half_text(half: &Half) -> String {    hex::encode(half)}pub fn half_from_text(text: &str) -> Option<Half> {    hex::decode(text).ok()?.try_into().ok()}fn digits(half: &Half) -> impl Iterator<Item = String> + '_ {    half.chunks(5).map(|c| format!("{:05}", c.iter().fold(0u64, |n, b| (n << 8) | u64::from(*b)) % 100_000))}/// The two halves in the order of their ids.fn ordered<'a>(a: (&'a str, &'a Half), b: (&'a str, &'a Half)) -> ((&'a str, &'a Half), (&'a str, &'a Half)) {    if a.0 <= b.0 {        (a, b)    } else {        (b, a)    }}/// The twelve groups both phones show for the chat between `a` and `b`.pub fn number(a: &str, a_half: &Half, b: &str, b_half: &Half) -> Vec<String> {    let (first, second) = ordered((a, a_half), (b, b_half));    digits(first.1).chain(digits(second.1)).collect()}fn tag(first: &str, second: &str) -> [u8; TAG_LEN] {    let hash = Sha256::new().chain_update(PAIR_DOMAIN).chain_update(first.as_bytes()).chain_update([0u8]).chain_update(second.as_bytes()).finalize();    let mut out = [0u8; TAG_LEN];    out.copy_from_slice(&hash[..TAG_LEN]);    out}/// The code a phone draws for the chat between `a` and `b`: the same text on both phones when they agree.pub fn code(a: &str, a_half: &Half, b: &str, b_half: &Half) -> String {    let (first, second) = ordered((a, a_half), (b, b_half));    let bytes = [&[VERSION][..], &tag(first.0, second.0), first.1, second.1].concat();    format!("{CODE_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes))}/// What a code scanned from the other phone says of this chat, as this phone holds it.pub fn scan(me: &str, my_half: &Half, them: &str, their_half: &Half, scanned: &str) -> Result<Scan, CodeError> {    let body = scanned.trim().strip_prefix(CODE_PREFIX).ok_or(CodeError::Malformed)?;    let bytes = URL_SAFE_NO_PAD.decode(body).map_err(|_| CodeError::Malformed)?;    if bytes.first().is_some_and(|v| *v != VERSION) {        return Err(CodeError::OtherVersion(bytes[0]));    }    if bytes.len() != CODE_LEN {        return Err(CodeError::Malformed);    }    let (first, second) = ordered((me, my_half), (them, their_half));    if bytes[1..1 + TAG_LEN] != tag(first.0, second.0) {        return Ok(Scan::NotThisChat);    }    let halves = &bytes[1 + TAG_LEN..];    Ok(if halves[..HALF_LEN] == first.1[..] && halves[HALF_LEN..] == second.1[..] { Scan::Matched } else { Scan::NotMatched })}#[cfg(test)]#[path = "safety_tests.rs"]mod tests;