Cotton code
158 lines · 9.1 KB · RustRaw
//! Invitations between two people on Cotton (CONTRACT.md section 17), two//! invented phones over scripted objects: the box each sends is the box the//! other takes. Nobody here is real.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use serde_json::{json, Value};use tempfile::TempDir;use crate::handle::CottonHandle;use crate::phone::days::tests::{ask, lines, phone, span, zone, TODAY, ZONE};use crate::phone::days_people::Heard;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const PRIYA: &str = "+447700900111";const ROSE: &str = "+447700900222";fn with_door(handle: &CottonHandle, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn hold_key(handle: &CottonHandle) -> String {    let mut bytes = [0u8; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    let client = handle.client();    let database = client.current_database().expect("a database");    client.data_keys().hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));    crate::phone::send_seal::sharing(&client).expect("a sharing key").1}fn body(seen: &Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn ok() -> Reply {    Reply::ok(r#"{"ok":true}"#)}fn key(public: &str) -> Reply {    Reply::ok(&json!({ "key": public }).to_string())}fn inbox(from: &str, sent: &Value) -> Reply {    Reply::ok(&json!({ "held": [{ "seq": 1, "from": from, "kind": sent["kind"], "id": sent["id"], "box": sent["box"], "at": 0 }] }).to_string())}/// RULE (CONTRACT §15, §17): a connected person goes by Cotton: the invitation reaches their Days sealed, they answer, the answer comes back; deleting the event calls it off in their Days. Nothing leaves Cotton.#[test]fn an_invitation_goes_from_days_to_days_and_the_answer_comes_back() {    let (a_dir, b_dir) = (TempDir::new().unwrap(), TempDir::new().unwrap());    let (priya, rose) = (phone(&a_dir), phone(&b_dir));    zone(&priya);    zone(&rose);    let (priya_key, rose_key) = (hold_key(&priya), hold_key(&rose));    Heard::connected(&priya.client(), vec![(ROSE.to_string(), Some("Rose".to_string()))]);    Heard::connected(&rose.client(), vec![(PRIYA.to_string(), Some("Priya".to_string()))]);    // Priya invites Rose.    let id = ask(&priya, "days.add", json!({ "words": "Dinner Saturday 7pm", "timezone": ZONE, "today": TODAY, "where": "days" }))["id"].as_str().unwrap().to_string();    let people = json!([{ "number": ROSE, "name": "Rose" }]);    assert_eq!(ask(&priya, "days.tell", json!({ "table": "event", "id": id, "people": people }))["lines"], json!(["Rose gets it in Days."]));    assert_eq!(ask(&priya, "days.change", json!({ "table": "event", "id": id, "people": people, "timezone": ZONE }))["google"], json!("waiting"));    let row = &ask(&priya, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }))["people"]["rows"][0];    assert_eq!((row["via"].clone(), row["detail"].clone(), row["answer"].clone()), (json!("cotton"), json!("On Cotton"), Value::Null));    let out = with_door(&priya, [ok(), key(&rose_key), ok(), Reply::ok(r#"{"held":[]}"#)]);    assert_eq!(ask(&priya, "days.invitations", json!({}))["sent"], json!(1));    let seen = out.seen();    let paths: Vec<&str> = seen.iter().map(|s| s.path.as_str()).collect();    assert_eq!(paths, ["/v1/send/key", "/v1/send/key?number=%2B447700900222", "/v1/invite/send", "/v1/invite/inbox"]);    let invite = body(&seen[2]);    assert_eq!((invite["to"].clone(), invite["kind"].clone(), invite["id"].clone()), (json!(ROSE), json!("invite"), json!(id)));    assert!(invite["box"].as_str().unwrap().starts_with("p1:"), "sealed");    assert!(!invite.to_string().contains("Dinner"), "the object never sees the words");    let told = &ask(&priya, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }))["people"]["rows"][0];    assert_eq!(told["answerWords"], json!("No answer"));    // Rose's Days takes it.    let taken = with_door(&rose, [ok(), inbox(PRIYA, &invite), key(&priya_key), ok()]);    let pass = ask(&rose, "days.invitations", json!({}));    assert_eq!(pass["said"], json!(["Priya invited you to “Dinner” on Sat 21 Nov."]));    assert_eq!(body(&taken.seen()[3]), json!({ "seqs": [1] }));    assert_eq!(lines(&span(&rose, "2026-11-21", "2026-11-21")), ["2026-11-21: 19:00 · Dinner to 20:00"]);    let landed = landed(&rose);    let sheet = ask(&rose, "days.item", json!({ "table": "event", "id": landed, "timezone": ZONE, "today": TODAY }));    assert_eq!(sheet["says"], json!("Priya invited you"));    let organizer = sheet["people"]["rows"].clone();    assert_eq!(ask(&rose, "days.tell", json!({ "table": "event", "id": landed, "people": organizer }))["lines"], json!([]), "an invitation received tells nobody");    assert_eq!(sheet["canChange"]["title"], json!(false));    let labels: Vec<&str> = sheet["invitation"]["choices"].as_array().unwrap().iter().map(|c| c["label"].as_str().unwrap()).collect();    assert_eq!(labels, ["Coming", "Maybe", "Not coming"]);    // Rose answers; the answer goes back sealed.    ask(&rose, "days.answer", json!({ "id": landed, "answer": "accepted" }));    let back = with_door(&rose, [key(&priya_key), ok(), Reply::ok(r#"{"held":[]}"#)]);    assert_eq!(ask(&rose, "days.invitations", json!({}))["sent"], json!(1));    let answer = body(&back.seen()[1]);    assert_eq!((answer["to"].clone(), answer["kind"].clone()), (json!(PRIYA), json!("answer")));    with_door(&priya, [inbox(ROSE, &answer), key(&rose_key), ok()]);    assert_eq!(ask(&priya, "days.invitations", json!({}))["said"], json!(["Rose is coming to “Dinner”."]));    let row = &ask(&priya, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }))["people"]["rows"][0];    assert_eq!(row["answerWords"], json!("Coming"));    // A new time reaches Rose as a change; deleting it calls it off.    ask(&priya, "days.change", json!({ "table": "event", "id": id, "time": "20:00", "timezone": ZONE }));    let changed = with_door(&priya, [key(&rose_key), ok(), Reply::ok(r#"{"held":[]}"#)]);    ask(&priya, "days.invitations", json!({}));    let update = body(&changed.seen()[1]);    with_door(&rose, [inbox(PRIYA, &update), key(&priya_key), ok()]);    assert_eq!(ask(&rose, "days.invitations", json!({}))["said"], json!(["Priya changed “Dinner”."]));    assert_eq!(lines(&span(&rose, "2026-11-21", "2026-11-21")), ["2026-11-21: 20:00 · Dinner to 21:00"]);    ask(&priya, "days.delete", json!({ "table": "event", "id": id }));    let off = with_door(&priya, [key(&rose_key), ok(), Reply::ok(r#"{"held":[]}"#)]);    ask(&priya, "days.invitations", json!({}));    let cancel = body(&off.seen()[1]);    assert_eq!(cancel["kind"], json!("cancel"));    with_door(&rose, [inbox(PRIYA, &cancel), key(&priya_key), ok()]);    assert_eq!(ask(&rose, "days.invitations", json!({}))["said"], json!(["Priya called off “Dinner”."]));    assert_eq!(lines(&span(&rose, "2026-11-21", "2026-11-21")), Vec::<String>::new());}/// RULE (CONTRACT §17): a box that does not open under its own invitation, or is not from the key the object holds for that number, lands nothing.#[test]fn a_box_from_someone_else_lands_nothing() {    let (a_dir, b_dir) = (TempDir::new().unwrap(), TempDir::new().unwrap());    let (priya, rose) = (phone(&a_dir), phone(&b_dir));    zone(&priya);    zone(&rose);    let (_priya_key, rose_key) = (hold_key(&priya), hold_key(&rose));    Heard::connected(&priya.client(), vec![(ROSE.to_string(), Some("Rose".to_string()))]);    let id = ask(&priya, "days.add", json!({ "words": "Dinner Saturday 7pm", "timezone": ZONE, "today": TODAY, "where": "days" }))["id"].as_str().unwrap().to_string();    ask(&priya, "days.change", json!({ "table": "event", "id": id, "people": [{ "number": ROSE, "name": "Rose" }], "timezone": ZONE }));    let out = with_door(&priya, [ok(), key(&rose_key), ok(), Reply::ok(r#"{"held":[]}"#)]);    ask(&priya, "days.invitations", json!({}));    let invite = body(&out.seen()[2]);    // The object claims it came from another number, whose key is not the sender's.    let stranger = "x".repeat(43);    with_door(&rose, [ok(), inbox("+447700900333", &invite), key(&stranger), ok()]);    assert_eq!(ask(&rose, "days.invitations", json!({}))["said"], json!([]));    assert_eq!(lines(&span(&rose, "2026-11-21", "2026-11-21")), Vec::<String>::new());}pub(super) fn landed(handle: &CottonHandle) -> String {    let mut out = String::new();    handle        .client()        .with_writer(|replica| {            out = replica.driver.get("SELECT id FROM cotton_events WHERE ical_uid LIKE 'cotton:%'", &[]).map_err(|e| e.to_string())?.and_then(|r| r.text("id").map(str::to_string)).unwrap_or_default();            Ok(())        })        .expect("read");    out}