Cotton code
221 lines · 8.5 KB · RustRaw
//! A Mac's relay key kept by the serving Mac (`cotton_device_relay_keys`,//! v136, architect's ruling of 12 Oct 2026) — the fold's rules for it on every//! device: written by the judge of the row's own serving epoch only, never//! changed or deleted, one row per (device, epoch), and the key every reader//! takes is the LOWEST epoch's, so every device reads the same key whatever//! order the rows and the serving facts arrive in.//!//! Every value is synthetic.use cotton_store::actor::{Actor, JobName};use cotton_store::fold::{arrive, fold_ops, Arrival};use cotton_store::migrate::migrate_store;use cotton_store::mint::Change;use cotton_store::protocol::derived_id::relay_key_id;use cotton_store::protocol::hlc::next_hlc;use cotton_store::protocol::types::CottonOp;use cotton_store::wire::op_of_change;use cotton_store::Driver;use rusqlite::types::Value;use serde_json::{json, Map, Value as JsonValue};const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";const NOW: &str = "2026-10-12T09:00:00.000Z";/// The serving Macs of epochs 1 and 2, as authors and as device keys.const STUDY: &str = "device:01JSTUDYMAC0000000000000000";const KITCHEN: &str = "device:01JKITCHENMAC000000000000000";/// The Mac whose approval carried no relay key.const KEYLESS_MAC: &str = "a-keyless-mac-device-key";const KEY_A: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";const KEY_B: &str = "HyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4";const T0: i64 = 1_800_000_000_000;fn text(value: &str) -> Value {    Value::Text(value.to_string())}fn file() -> Driver {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[text(WORKSPACE), text("A workspace"), text("owner-1"), text(NOW)],    )    .expect("the workspace row");    db}/// The serving fact of `epoch`, naming `author`'s Mac.fn serving(db: &Driver, epoch: i64, author: &str) {    db.run(        "INSERT INTO cotton_serving_machine \           (id, workspace_id, epoch, device_credential_id, author_id, since) \         VALUES (?, ?, ?, ?, ?, ?)",        &[            text(&format!("fact-{epoch}")),            text(WORKSPACE),            Value::Integer(epoch),            text(author),            text(author),            text(NOW),        ],    )    .expect("the serving fact");}fn patch(value: JsonValue) -> Map<String, JsonValue> {    match value {        JsonValue::Object(map) => map,        other => panic!("a patch is an object, got {other}"),    }}thread_local! {    static SCHEMA: Driver = {        let db = Driver::open_in_memory().expect("opens");        migrate_store(&db).expect("migrates");        db    };}fn receipt_op(change: Change, op_id: &str, author: &str, ms: i64) -> CottonOp {    let hlc = next_hlc(author, None, ms).expect("a stamp in range");    let actor = Actor::device_job(JobName::named("devices").expect("a job name"));    SCHEMA        .with(|db| op_of_change(db, &change, &hlc, author, &actor, op_id.to_string()))        .expect("a receipt")}/// The keyless Mac's key, kept at `epoch` by `author`.fn kept(op_id: &str, epoch: i64, key: &str, author: &str, ms: i64) -> CottonOp {    let id = relay_key_id(KEYLESS_MAC, epoch);    receipt_op(        Change::create(            "cotton_device_relay_keys",            &id,            patch(json!({                "id": id,                "workspace_id": WORKSPACE,                "device_id": KEYLESS_MAC,                "epoch": epoch,                "relay_identity_key": key,                "set_at": NOW,                "set_by": "the serving Mac",                "created_at": NOW,                "updated_at": NOW,            })),        ),        op_id,        author,        ms,    )}/// The key every reader takes for the keyless Mac: the lowest epoch's.fn the_key(db: &Driver) -> Option<String> {    db.get(        "SELECT relay_identity_key FROM cotton_device_relay_keys \         WHERE device_id = ? ORDER BY epoch ASC, id ASC LIMIT 1",        &[text(KEYLESS_MAC)],    )    .expect("reads")    .and_then(|row| row.text("relay_identity_key").map(str::to_string))}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).expect("counts").and_then(|row| row.int("n")).unwrap_or(0)}/// RULE: two relay-key fills from different serving epochs, in either arrival order, yield the same key on every device — the lowest epoch's.#[test]fn two_fills_from_different_epochs_yield_the_same_key_in_either_order() {    let first = kept("op-epoch-1", 1, KEY_A, STUDY, T0);    let second = kept("op-epoch-2", 2, KEY_B, KITCHEN, T0 + 10);    for order in [[first.clone(), second.clone()], [second, first]] {        let db = file();        serving(&db, 1, STUDY);        serving(&db, 2, KITCHEN);        for write in &order {            let result = fold_ops(&db, std::slice::from_ref(write)).expect("folds");            assert!(result.parked.is_empty() && result.rejected.is_empty(), "{result:?}");        }        assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_device_relay_keys"), 2);        assert_eq!(the_key(&db).as_deref(), Some(KEY_A));    }}/// RULE: a kept relay key is taken only from a serving author of the epoch the row names; from any other author it is parked as a conflict and not applied.#[test]fn a_fill_from_an_author_that_is_not_its_epochs_judge_is_parked() {    let db = file();    serving(&db, 1, STUDY);    serving(&db, 2, KITCHEN);    // KITCHEN serves epoch 2, not epoch 1.    let result = fold_ops(&db, &[kept("op-not-judge", 1, KEY_A, KITCHEN, T0)]).expect("folds");    assert!(result.applied.is_empty(), "{result:?}");    assert_eq!(result.parked.len(), 1, "{result:?}");    assert!(result.parked[0].reason.contains("conflict"), "got {:?}", result.parked[0].reason);    assert_eq!(the_key(&db), None);    // Written here by such an author, it is refused to its writer.    let result = arrive(&db, &[kept("op-not-judge-local", 1, KEY_A, KITCHEN, T0 + 5)], Arrival::Local)        .expect("folds");    assert!(result.applied.is_empty());    assert_eq!(result.rejected.len(), 1, "{result:?}");}/// RULE: a kept relay key that arrives before the serving fact of its epoch waits, and is applied when that fact arrives.#[test]fn a_fill_waits_for_its_epochs_serving_fact() {    let db = file();    let result = cotton_store::exchange::fold_incoming(&db, &[kept("op-early", 1, KEY_A, STUDY, T0)])        .expect("folds");    assert!(result.rejected.is_empty(), "{result:?}");    assert_eq!(the_key(&db), None);    assert_eq!(        count(&db, "SELECT COUNT(*) AS n FROM _parked WHERE op_id = 'op-early' AND class = 'waiting'"),        1    );    // The fact of epoch 1 arrives, and the kept key with it.    let fact = {        let change = Change::create(            "cotton_serving_machine",            "fact-1",            patch(json!({                "id": "fact-1",                "workspace_id": WORKSPACE,                "epoch": 1,                "device_credential_id": STUDY,                "author_id": STUDY,                "since": NOW,            })),        );        receipt_op(change, "op-fact", STUDY, T0 + 100)    };    cotton_store::exchange::fold_incoming(&db, &[fact]).expect("folds");    assert_eq!(the_key(&db).as_deref(), Some(KEY_A), "the fact's arrival applied it");}/// RULE: a set relay key is never changed — not by a change, not by a delete, and not by a second, different fill of the same epoch, even from that epoch's judge.#[test]fn a_kept_key_is_never_changed_or_deleted() {    let db = file();    serving(&db, 1, STUDY);    fold_ops(&db, &[kept("op-kept", 1, KEY_A, STUDY, T0)]).expect("folds");    let id = relay_key_id(KEYLESS_MAC, 1);    let change = receipt_op(        Change::update("cotton_device_relay_keys", &id, patch(json!({ "relay_identity_key": KEY_B }))),        "op-change",        STUDY,        T0 + 10,    );    let delete = receipt_op(Change::retract("cotton_device_relay_keys", &id), "op-delete", STUDY, T0 + 20);    let swap = kept("op-swap", 1, KEY_B, STUDY, T0 + 30);    for (write, word) in [(&change, "never updated"), (&delete, "never deleted"), (&swap, "conflict")] {        let result = fold_ops(&db, std::slice::from_ref(write)).expect("folds");        assert!(result.applied.is_empty(), "{word}: {result:?}");        assert_eq!(result.parked.len(), 1, "{word}: {result:?}");        assert!(result.parked[0].reason.contains(word), "got {:?}", result.parked[0].reason);    }    assert_eq!(the_key(&db).as_deref(), Some(KEY_A));}