Cotton code
438 lines · 22.1 KB · RustRaw
//! A SHARED ALBUM'S ROSTER, signed (SHARED 4, 27 Nov 2026;//! the coordinator's review: the server is the adversary). Who is in a space,//! with what keys, who owns it and which wraps hand out its keys is a chain of//! statements, each signed on a phone and naming the hash of the one before.//! The server keeps the chain in order and reads nothing else of it//! (apps/business src/space/space.ts `takeStatement`); a phone accepts a//! member, opens a wrap or shows an owner ONLY from a chain that verifies back//! to the founding statement it first saw.//!//! ```text//! statement   = "t1:" b64url(body JSON) "." b64url(Ed25519(signer, "cotton-space-roster-v1\n" body JSON))//! hash        = hex(SHA-256(statement text))                 the next statement's `prev`//! body        = {v: 1, space, seq, prev, kind, by, epoch, members: [{member, share, sign, role, serial, name}],//!                wraps: {member: w1 at epoch}, links: [{link, public, album}], link_wraps: {link: w1 at epoch}, at}//! ```//!//! What each kind may do (the previous state P, the new body B; `by` signs)://!//! | kind    | by                  | members                                   | epoch   | wraps                    |//! |---------|---------------------|-------------------------------------------|---------|--------------------------|//! | `found` | the owner in B      | B (seq 0, prev "")                        | 1       | every member             |//! | `add`   | P's owner           | P plus newcomers (role member)            | P's     | exactly the newcomers    |//! | `epoch` | P's owner           | a subset of P (the owner stays)           | P's + 1 | exactly B's members      |//! | `leave` | a member of P       | P less `by`; if `by` owned, the lowest serial owns | P's | none          |//! | `link`  | P's owner           | P                                         | P's     | `link_wraps`: the new link |//! | `claim` | a member of P       | P less P's owner, `by` owning             | P's     | none                     |//! | `handover` | P's owner        | P, the lowest other serial owning, `by` a member | P's | none                   |//! | `void`  | the owner a claim right before it took the place of | the roster as it was before that claim | P's | none |//!//! - **Every entry names who the member IS** (`who`, [`member_who`]: a slow hash of their number salted by the space,//!   inside the signed bytes). A phone recognises a member only by matching `who` against numbers it already knows//!   (its own pins), never by a number or name the server gives. An entry with no `who` is refused.//! - No statement changes a member's keys or serial: a person with a new key//!   is a new member (and their phone pins say so, `cotton-ffi` albums_shared).//! - A `claim` (the owner's account was erased with no hand-over) is NOT//!   signed by the old owner, so a phone applies it only once its person has//!   confirmed it ([`Applied::NeedsConfirm`]); until then nothing after it is//!   applied, so nothing is wrapped to anyone a claimed owner adds.//! - Links shrink freely at an epoch move or a leave; they grow only by `link`.use std::collections::{BTreeMap, BTreeSet};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use super::SealError;const DOMAIN: &str = "cotton-space-roster-v1";pub const PREFIX: &str = "t1:";#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Entry {    pub member: String,    /// The member's sharing key (X25519), base64url.    pub share: String,    /// The member's signing key (Ed25519), base64url.    pub sign: String,    pub role: String,    pub serial: u64,    #[serde(default)]    pub name: Option<String>,    /// [`member_who`] of the member's number: who this member IS, signed.    #[serde(default)]    pub who: String,}/// The cost of [`member_who`]: 2^14 rounds of scrypt (16 MB, about 50 ms on a phone), so a member who holds the roster/// cannot cheaply run every phone number through it to learn the numbers of people they do not have.pub const WHO_LOG_N: u8 = 14;/// Who a member is, as the roster names them: scrypt(number, salt = "cotton-member-v1\n" space), base64url. The same/// number in another album is another value, so albums cannot be joined by it.pub fn member_who(space: &str, number: &str) -> String {    member_who_at(space, number, WHO_LOG_N)}/// [`member_who`] at another cost (tests).pub fn member_who_at(space: &str, number: &str, log_n: u8) -> String {    let params = scrypt::Params::new(log_n, 8, 1, 32).expect("scrypt parameters");    let mut out = [0u8; 32];    scrypt::scrypt(number.as_bytes(), format!("cotton-member-v1\n{space}").as_bytes(), &params, &mut out).expect("scrypt output length");    b64(&out)}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct LinkEntry {    pub link: String,    pub public: String,    pub album: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Body {    pub v: u32,    pub space: String,    pub seq: u64,    pub prev: String,    pub kind: String,    pub by: String,    pub epoch: u32,    pub members: Vec<Entry>,    #[serde(default)]    pub wraps: BTreeMap<String, String>,    #[serde(default)]    pub links: Vec<LinkEntry>,    #[serde(default)]    pub link_wraps: BTreeMap<String, String>,    #[serde(default)]    pub at: i64,}fn b64(bytes: &[u8]) -> String {    URL_SAFE_NO_PAD.encode(bytes)}fn unb64(text: &str) -> Result<Vec<u8>, SealError> {    URL_SAFE_NO_PAD.decode(text).map_err(|_| SealError::DoesNotOpen)}fn broken(why: impl Into<String>) -> SealError {    SealError::BadInput(format!("the roster does not hold: {}", why.into()))}/// A statement signed: what a phone posts with the act it records.pub fn sign(signer: &SigningKey, body: &Body) -> String {    let json = serde_json::to_string(body).expect("a statement serialises");    let sig = signer.sign(format!("{DOMAIN}\n{json}").as_bytes());    format!("{PREFIX}{}.{}", b64(json.as_bytes()), b64(&sig.to_bytes()))}/// The hash the next statement names.pub fn hash(text: &str) -> String {    Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()}/// A statement read (not yet verified): its body, the exact JSON signed, and the signature.fn read(text: &str) -> Result<(Body, String, [u8; 64]), SealError> {    let rest = text.strip_prefix(PREFIX).ok_or_else(|| broken("not a statement"))?;    let (body, sig) = rest.split_once('.').ok_or_else(|| broken("not a statement"))?;    let json = String::from_utf8(unb64(body)?).map_err(|_| broken("not text"))?;    let parsed: Body = serde_json::from_str(&json).map_err(|_| broken("not a statement body"))?;    let sig: [u8; 64] = unb64(sig)?.try_into().map_err(|_| broken("a signature is 64 bytes"))?;    Ok((parsed, json, sig))}fn verify(sign_key: &str, json: &str, sig: &[u8; 64]) -> Result<(), SealError> {    let public: [u8; 32] = unb64(sign_key)?.try_into().map_err(|_| broken("a signing key is 32 bytes"))?;    let key = VerifyingKey::from_bytes(&public).map_err(|_| broken("not a signing key"))?;    key.verify(format!("{DOMAIN}\n{json}").as_bytes(), &Signature::from_bytes(sig)).map_err(|_| broken("a signature does not verify"))}/// The roster as a chain of statements says it is now.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Roster {    pub space: String,    pub seq: u64,    /// The hash of the last statement applied.    pub head: String,    /// The hash of the founding statement: a phone pins it the first time it sees the space.    pub founding: String,    pub epoch: u32,    pub members: Vec<Entry>,    pub links: Vec<LinkEntry>,    /// Every epoch's wraps from the statements: epoch → holder (a member id, or `link:<id>`) → `w1:`.    pub wraps: BTreeMap<u32, BTreeMap<String, String>>,    /// Everyone who was ever a member, with the keys the chain gave them: an old record's signer is checked here.    pub ever: BTreeMap<String, Entry>,    /// The statement at which each departed member left (a leave, a removal, a claim over them).    pub left_at: BTreeMap<String, u64>,    /// The hash of every statement applied, by seq: a record naming a head is checked against it.    pub heads: Vec<String>,    /// A statement after the last good one did not verify: the album is read as of here and nothing new is sealed.    pub stuck: Option<String>,    /// The statement at which each member (ever) came in.    pub joined_at: BTreeMap<String, u64>,    /// The epoch in force after each statement, by seq.    pub epochs: Vec<u32>,    /// The last statement was a claim: who it took the place of, and the roster before it (a `void` by them restores it).    pub claimed: Option<(String, Box<Roster>)>,}/// What applying one statement did.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Applied {    Done,    /// A claim of ownership no old owner signed: applied only once the person confirms its hash.    NeedsConfirm { from: String, to: String, hash: String },}impl Roster {    /// The founding statement, verified against the key it names for its own signer (trust on first sight: the    /// phone pins its hash, and safety numbers check the people in it).    pub fn found(text: &str) -> Result<Roster, SealError> {        let (b, json, sig) = read(text)?;        if b.v != 1 || b.kind != "found" || b.seq != 0 || !b.prev.is_empty() || b.epoch != 1 {            return Err(broken("the first statement founds the space at epoch 1"));        }        check_members(&b.members)?;        let owner = b.members.iter().find(|m| m.member == b.by && m.role == "owner").ok_or_else(|| broken("the founder is its owner"))?;        verify(&owner.sign, &json, &sig)?;        exactly(&b.wraps, b.members.iter().map(|m| m.member.as_str()), "a founding wrap for every member")?;        let mut wraps = BTreeMap::new();        wraps.insert(1, b.wraps.clone());        Ok(Roster {            space: b.space.clone(),            seq: 0,            head: hash(text),            founding: hash(text),            epoch: 1,            ever: b.members.iter().map(|m| (m.member.clone(), m.clone())).collect(),            joined_at: b.members.iter().map(|m| (m.member.clone(), 0)).collect(),            members: b.members,            links: Vec::new(),            wraps,            left_at: BTreeMap::new(),            heads: vec![hash(text)],            stuck: None,            epochs: vec![1],            claimed: None,        })    }    /// A whole chain, founding first. Stops (without error) at a claim not yet confirmed, and at a statement that does    /// not verify (`stuck`: the album reads as of the last good one; nothing after it is applied).    pub fn fold(texts: &[String], confirmed: &BTreeSet<String>) -> Result<(Roster, Option<Applied>), SealError> {        let first = texts.first().ok_or_else(|| broken("no founding statement"))?;        let mut roster = Roster::found(first)?;        let mut i = 1;        while i < texts.len() {            let text = &texts[i];            i += 1;            match roster.apply(text, confirmed) {                Ok(pending @ Applied::NeedsConfirm { .. }) => {                    // A claim the old owner voided right after: both skipped, nobody needs to confirm anything.                    let mut tried = roster.clone();                    let mut with: BTreeSet<String> = confirmed.clone();                    with.insert(hash(text));                    if let (Some(void), Ok(_)) = (texts.get(i), tried.apply(text, &with)) {                        if tried.apply(void, confirmed).is_ok() {                            roster = tried;                            i += 1;                            continue;                        }                    }                    return Ok((roster, Some(pending)));                }                Ok(Applied::Done) => {}                Err(why) => {                    roster.stuck = Some(why.to_string());                    return Ok((roster, None));                }            }        }        Ok((roster, None))    }    /// Whether `member` was in the album right after statement `seq`.    pub fn member_at(&self, member: &str, seq: u64) -> bool {        self.joined_at.get(member).is_some_and(|j| *j <= seq) && self.left_at.get(member).is_none_or(|l| *l > seq)    }    /// Whether `member` held the key of `epoch` (a wrap the chain handed them).    pub fn held(&self, member: &str, epoch: u32) -> bool {        self.wraps.get(&epoch).is_some_and(|w| w.contains_key(member))    }    pub fn owner(&self) -> Option<&Entry> {        self.members.iter().find(|m| m.role == "owner")    }    pub fn member(&self, id: &str) -> Option<&Entry> {        self.members.iter().find(|m| m.member == id)    }    /// The next statement, checked against every rule above, then applied.    pub fn apply(&mut self, text: &str, confirmed: &BTreeSet<String>) -> Result<Applied, SealError> {        let (b, json, sig) = read(text)?;        if b.v != 1 || b.space != self.space || b.seq != self.seq + 1 || b.prev != self.head {            return Err(broken(format!("statement {} does not follow statement {}", b.seq, self.seq)));        }        if b.kind == "void" {            let (from, before) = self.claimed.clone().ok_or_else(|| broken("a void follows a claim"))?;            need(b.by == from, "only the owner a claim displaced voids it")?;            let by = before.member(&from).cloned().ok_or_else(|| broken("the voiding owner was a member"))?;            verify(&by.sign, &json, &sig)?;            need(b.members == before.members && b.epoch == before.epoch && b.links == before.links && b.wraps.is_empty() && b.link_wraps.is_empty(), "a void puts back the roster as it was before the claim")?;            let mut heads = self.heads.clone();            heads.push(hash(text));            let mut epochs = self.epochs.clone();            epochs.push(before.epoch);            *self = Roster { seq: b.seq, head: hash(text), heads, epochs, claimed: None, ..*before };            // The claimant's place was never taken from them: nobody left at the claim.            return Ok(Applied::Done);        }        let by = self.member(&b.by).cloned().ok_or_else(|| broken("signed by someone not a member"))?;        verify(&by.sign, &json, &sig)?;        check_members(&b.members)?;        // Nobody's keys, serial or name change under the same member id.        for m in &b.members {            if let Some(was) = self.ever.get(&m.member) {                if (was.share.as_str(), was.sign.as_str(), was.serial, was.who.as_str()) != (m.share.as_str(), m.sign.as_str(), m.serial, m.who.as_str()) {                    return Err(broken(format!("{}'s keys changed under the same member", m.member)));                }            }        }        let owner = self.owner().map(|o| o.member.clone()).unwrap_or_default();        let same_roles = |a: &[Entry], b: &[Entry]| a.iter().all(|m| b.iter().find(|n| n.member == m.member).is_none_or(|n| n.role == m.role));        let ids = |v: &[Entry]| v.iter().map(|m| m.member.clone()).collect::<BTreeSet<_>>();        let (was, now) = (ids(&self.members), ids(&b.members));        match b.kind.as_str() {            "add" => {                need(by.member == owner, "only the owner adds")?;                need(was.is_subset(&now) && same_roles(&self.members, &b.members) && b.epoch == self.epoch, "an add keeps everyone and the epoch")?;                let top = self.ever.values().map(|m| m.serial).max().unwrap_or(0);                let fresh: Vec<&Entry> = b.members.iter().filter(|m| !was.contains(&m.member)).collect();                need(!fresh.is_empty() && fresh.iter().all(|m| m.role == "member" && m.serial > top && !self.ever.contains_key(&m.member)), "newcomers are new members")?;                exactly(&b.wraps, fresh.iter().map(|m| m.member.as_str()), "a wrap for exactly the newcomers")?;                need(b.links == self.links && b.link_wraps.is_empty(), "an add changes no link")?;            }            "epoch" => {                need(by.member == owner, "only the owner moves the key")?;                need(now.is_subset(&was) && now.contains(&owner) && same_roles(&b.members, &self.members), "an epoch move only removes, and the owner stays")?;                need(b.epoch == self.epoch + 1, "an epoch move goes up by one")?;                exactly(&b.wraps, b.members.iter().map(|m| m.member.as_str()), "a wrap for exactly the members who stay")?;                need(b.links.iter().all(|l| self.links.contains(l)), "an epoch move adds no link")?;                exactly(&b.link_wraps, b.links.iter().map(|l| l.link.as_str()), "a wrap for exactly the links kept")?;            }            "leave" => {                let mut expect: Vec<Entry> = self.members.iter().filter(|m| m.member != by.member).cloned().collect();                if by.member == owner {                    if let Some(next) = expect.iter_mut().min_by_key(|m| m.serial) {                        next.role = "owner".into();                    }                }                need(b.members == expect && b.epoch == self.epoch && b.wraps.is_empty() && b.link_wraps.is_empty(), "a leave takes out its signer alone (the longest member owning after an owner)")?;                need(b.links.iter().all(|l| self.links.contains(l)), "a leave adds no link")?;            }            "link" => {                need(by.member == owner, "only the owner makes a link")?;                need(b.members == self.members && b.epoch == self.epoch && b.wraps.is_empty(), "a link changes no member")?;                let fresh: Vec<&LinkEntry> = b.links.iter().filter(|l| !self.links.contains(l)).collect();                need(fresh.len() == 1 && self.links.iter().all(|l| b.links.contains(l)), "a link statement adds one link")?;                exactly(&b.link_wraps, fresh.iter().map(|l| l.link.as_str()), "a wrap for the new link")?;            }            "handover" => {                need(by.member == owner, "only the owner hands over")?;                let next = self.members.iter().filter(|m| m.member != owner).min_by_key(|m| m.serial).map(|m| m.member.clone()).ok_or_else(|| broken("nobody to hand over to"))?;                let expect: Vec<Entry> = self.members.iter().map(|m| Entry { role: if m.member == next { "owner".into() } else { "member".into() }, ..m.clone() }).collect();                need(b.members == expect && b.epoch == self.epoch && b.wraps.is_empty() && b.link_wraps.is_empty() && b.links == self.links, "a hand-over moves the owner's place to the longest member and nothing else")?;            }            "claim" => {                need(by.member != owner, "an owner does not claim")?;                let expect: Vec<Entry> = self                    .members                    .iter()                    .filter(|m| m.member != owner)                    .map(|m| Entry { role: if m.member == by.member { "owner".into() } else { "member".into() }, ..m.clone() })                    .collect();                need(b.members == expect && b.epoch == self.epoch && b.wraps.is_empty() && b.link_wraps.is_empty(), "a claim takes the owner's place and nothing else")?;                if !confirmed.contains(&hash(text)) {                    return Ok(Applied::NeedsConfirm { from: owner, to: by.member.clone(), hash: hash(text) });                }            }            other => return Err(broken(format!("no statement kind {other:?}"))),        }        self.claimed = if b.kind == "claim" { Some((owner.clone(), Box::new(Roster { claimed: None, ..self.clone() }))) } else { None };        for m in &b.members {            self.ever.entry(m.member.clone()).or_insert_with(|| m.clone());            self.joined_at.entry(m.member.clone()).or_insert(b.seq);        }        for m in &self.members {            if !b.members.iter().any(|n| n.member == m.member) {                self.left_at.insert(m.member.clone(), b.seq);            }        }        self.heads.push(hash(text));        self.epochs.push(b.epoch);        let at = self.wraps.entry(b.epoch).or_default();        at.extend(b.wraps.clone());        at.extend(b.link_wraps.iter().map(|(k, v)| (format!("link:{k}"), v.clone())));        self.seq = b.seq;        self.head = hash(text);        self.epoch = b.epoch;        self.members = b.members;        self.links = b.links;        Ok(Applied::Done)    }    /// The next statement's body, ready to fill: this roster's state, the next seq, naming its head.    pub fn next(&self, kind: &str, by: &str, at: i64) -> Body {        Body {            v: 1,            space: self.space.clone(),            seq: self.seq + 1,            prev: self.head.clone(),            kind: kind.into(),            by: by.into(),            epoch: self.epoch,            members: self.members.clone(),            wraps: BTreeMap::new(),            links: self.links.clone(),            link_wraps: BTreeMap::new(),            at,        }    }}fn need(ok: bool, why: &str) -> Result<(), SealError> {    if ok {        Ok(())    } else {        Err(broken(why))    }}fn exactly<'a>(map: &BTreeMap<String, String>, want: impl Iterator<Item = &'a str>, why: &str) -> Result<(), SealError> {    let want: BTreeSet<&str> = want.collect();    need(map.keys().map(String::as_str).collect::<BTreeSet<_>>() == want && map.values().all(|w| w.starts_with("w1:")), why)}fn check_members(members: &[Entry]) -> Result<(), SealError> {    let ids: BTreeSet<&str> = members.iter().map(|m| m.member.as_str()).collect();    need(ids.len() == members.len() && !members.is_empty(), "each member once")?;    need(members.iter().filter(|m| m.role == "owner").count() == 1, "one owner")?;    need(members.iter().all(|m| m.role == "owner" || m.role == "member"), "a member is an owner or a member")?;    need(members.iter().all(|m| unb64(&m.who).map(|b| b.len() == 32).unwrap_or(false)), "every member names who they are")?;    for m in members {        need(unb64(&m.share).map(|b| b.len() == 32).unwrap_or(false) && unb64(&m.sign).map(|b| b.len() == 32).unwrap_or(false), "a member's keys are 32 bytes each")?;    }    Ok(())}#[cfg(test)]#[path = "shared_roster_tests.rs"]mod tests;