//! The Circle over a scripted object and this copy's contacts: rows are contacts, not numbers; an act on a person//! reaches each of their numbers; an ask from someone he does not have becomes a contact when he accepts it. Every//! number and name is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};usesuper::{list, over};usecrate::handle::CottonHandle;usecrate::phone::passwords::tests::phone;usecrate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const ASHA: &str = "+15550100011";const ASHA_WORK: &str = "+15550100012";const RAVI: &str = "+15550100013";const KABIR: &str = "+15550100014";const LATA: &str = "+15550100015";const DEV: &str = "+15550100016";fn with_door(handle: &CottonHandle, replies: implIntoIterator<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 sql(handle: &CottonHandle, statement: &str, params: &[SqlValue]) { handle.client().with_writer(|replica| replica.driver.run(statement, params).map(|_| ()).map_err(|e| e.to_string())).expect(statement);}fn t(s: &str) -> SqlValue {SqlValue::Text(s.to_string())}fn workspace(handle: &CottonHandle) -> String {crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap().as_str().unwrap().to_string()}/// A contact with its numbers, as the address book or a hand would make it.fn contact(handle: &CottonHandle, id: &str, name: &str, numbers: &[&str]) {let ws = workspace(handle); sql(handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, '2026-11-01', '2026-11-01')", &[t(id), t(&ws), t(name)]);for (i, n) in numbers.iter().enumerate() { sql( handle,"INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, position, created_at, updated_at) VALUES (?, ?, ?, 'phone', ?, ?, 'manual', ?, '2026-11-01', '2026-11-01')", &[t(&format!("{id}-h{i}")), t(&ws), t(id), t(n), t(n), SqlValue::Integer(i as i64)], ); }}fn people(asking: Value, people: Value, blocked: Value) -> Reply {Reply::ok(&json!({ "people": people, "asking": asking, "blocked": blocked }).to_string())}fn body(seen: &Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body")}fn ids(list: &Value, key: &str) -> Vec<String> { list[key].as_array().unwrap().iter().map(|s| s["id"].as_str().unwrap().to_string()).collect()}// RULE: the Circle's rows are contacts: a number is named by the one contact holding it, a stranger's ask by the name// they gave ("Calls themselves … · not in your contacts"); sections asking, in, waiting, blocked in that order, empty// ones left out; an ask carries Accept (primary), Not now and Block (red, with a sentence to confirm).#[test]fn the_circle_names_every_number_by_his_contact_and_a_stranger_by_what_they_gave() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA, ASHA_WORK]); contact(&handle, "p-ravi", "Ravi Shah", &[RAVI]); contact(&handle, "p-lata", "Lata Kumar", &[LATA]);let exchange = with_door( &handle, [people( json!([{ "number": RAVI, "name": "Ravi", "at": "2026-11-28T08:00:00.000Z" }, { "number": KABIR, "name": "Kabir P.", "at": "2026-11-28T08:00:00.000Z" }]), json!([{ "number": ASHA, "name": null, "waiting": false }, { "number": LATA, "name": null, "waiting": true }]), json!([]), )], );let drawn = list(&handle.client()); assert_eq!(exchange.seen()[0].path, "/v1/chat/people"); assert_eq!(drawn["title"], "Your Circle"); assert_eq!(drawn["intro"], "People you both accepted on Cotton. Being here shares nothing by itself."); assert_eq!(ids(&drawn, "sections"), ["asking", "in", "waiting"]);let asking = &drawn["sections"][0]["rows"]; assert_eq!((asking[0]["words"].as_str(), asking[0]["person"].as_str()), (Some("Ravi Shah"), Some("p-ravi"))); assert_eq!(asking[0]["detail"], "In your contacts · asks to join your Circle"); assert_eq!(asking[1]["words"], "Kabir P."); assert_eq!(asking[1]["person"], Value::Null); assert_eq!(asking[1]["detail"], "Calls themselves Kabir P. · not in your contacts");let acts: Vec<&str> = asking[0]["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect(); assert_eq!(acts, ["accept", "later", "block"]); assert_eq!(asking[0]["acts"][0]["call"], json!({ "method": "circle.answer", "request": { "ask": RAVI, "answer": "accept" } })); assert_eq!(asking[0]["acts"][2]["red"], true); assert!(asking[0]["acts"][2]["confirm"].as_str().unwrap().starts_with("Block Ravi Shah?"));let asha = &drawn["sections"][1]["rows"][0]; assert_eq!((asha["id"].as_str(), asha["words"].as_str(), asha["state"].as_str()), (Some("p-asha"), Some("Asha Menon"), Some("in"))); assert_eq!(asha["call"], json!({ "method": "contacts.person", "request": { "id": "p-asha" } })); assert_eq!(asha["acts"][0]["call"], json!({ "method": "circle.remove.plan", "request": { "person": "p-asha" } }));let lata = &drawn["sections"][2]["rows"][0]; assert_eq!((lata["words"].as_str(), lata["state"].as_str(), lata["detail"].as_str()), (Some("Lata Kumar"), Some("asked"), Some("You asked · waiting for them"))); assert_eq!(lata["acts"][0]["call"], json!({ "method": "circle.ask.stop", "request": { "person": "p-lata" } }));}// RULE: accepting someone he does not have makes a contact for them, named with what they gave and holding their// number; Not now is the object's refuse; Block is the object's block and the chat on this phone says blocked.#[test]fn accepting_a_stranger_makes_a_contact_with_their_number() {let (_dir, handle) = phone();let asking = || people(json!([{ "number": KABIR, "name": "Kabir P.", "at": "2026-11-28T08:00:00.000Z" }]), json!([]), json!([]));let after = || people(json!([]), json!([{ "number": KABIR, "name": "Kabir P.", "waiting": false }]), json!([]));let exchange = with_door(&handle, [asking(), Reply::ok(r#"{"ok":true}"#), after()]);let answered = over(&handle.client(), "circle.answer", &json!({ "ask": KABIR, "answer": "accept" })).unwrap(); assert_eq!(answered["said"], "Kabir P. is in your Circle.");let paths: Vec<String> = exchange.seen().iter().map(|s| s.path.clone()).collect();// The list after it also reads the pins for its Circle rows (no reply scripted: none checked). assert_eq!(paths[..3], ["/v1/chat/people", "/v1/chat/accept", "/v1/chat/people"]); assert_eq!(body(&exchange.seen()[1]), json!({ "number": KABIR }));let row = &answered["list"]["sections"][0]["rows"][0]; assert_eq!(row["words"], "Kabir P.");let person = row["person"].as_str().expect("a contact was made for them"); assert_eq!(row["call"], json!({ "method": "contacts.person", "request": { "id": person } }));let (_dir, handle) = phone();let exchange = with_door(&handle, [asking(), Reply::ok(r#"{"ok":true}"#), people(json!([]), json!([]), json!([]))]); assert_eq!(over(&handle.client(), "circle.answer", &json!({ "ask": KABIR, "answer": "later" })).unwrap()["said"], "Left Kabir P.'s ask."); assert_eq!(exchange.seen()[1].path, "/v1/chat/refuse");}// RULE: a block covers every number of the person (PEOPLE-DESIGN c), and unblock reaches only the numbers the object holds as blocked.#[test]fn a_block_covers_every_number_of_the_person() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA, ASHA_WORK]);let blocked = || people(json!([]), json!([]), json!([{ "number": ASHA, "name": null }, { "number": ASHA_WORK, "name": null }]));let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#), blocked()]);let said = over(&handle.client(), "circle.block", &json!({ "person": "p-asha" })).unwrap(); assert_eq!(said["said"], "Asha Menon is blocked.");let seen = exchange.seen(); assert_eq!((seen[0].path.as_str(), seen[1].path.as_str()), ("/v1/chat/block", "/v1/chat/block")); assert_eq!((body(&seen[0]), body(&seen[1])), (json!({ "number": ASHA }), json!({ "number": ASHA_WORK }))); assert_eq!(said["list"]["sections"][0]["id"], "blocked"); assert_eq!(said["list"]["sections"][0]["rows"].as_array().unwrap().len(), 2);let exchange = with_door(&handle, [people(json!([]), json!([]), json!([{ "number": ASHA_WORK, "name": null }])), Reply::ok(r#"{"ok":true}"#), people(json!([]), json!([]), json!([]))]); assert_eq!(over(&handle.client(), "circle.unblock", &json!({ "person": "p-asha" })).unwrap()["said"], "Asha Menon is unblocked.");let paths: Vec<String> = exchange.seen().iter().map(|s| s.path.clone()).collect(); assert_eq!(paths, ["/v1/chat/people", "/v1/chat/unblock", "/v1/chat/people"]); assert_eq!(body(&exchange.seen()[1]), json!({ "number": ASHA_WORK }));}// RULE: Add someone offers Ask on every number of every contact not yet in the object's lists, one row per number,// filtered by a name or digits; it never says who is on Cotton (no row says so, C1). Asking a typed number no contact// holds makes a contact for it.#[test]fn add_someone_offers_ask_on_every_contact_number_and_never_says_who_is_on_cotton() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA, ASHA_WORK]); contact(&handle, "p-dev", "Dev Nair", &[DEV]); contact(&handle, "p-ravi", "Ravi Shah", &[RAVI]);let none = || people(json!([]), json!([{ "number": RAVI, "name": null, "waiting": false }]), json!([])); with_door(&handle, [none(), none()]);let page = over(&handle.client(), "circle.add.page", &json!({})).unwrap();let rows: Vec<(String, String)> = page["rows"].as_array().unwrap().iter().map(|r| (r["words"].as_str().unwrap().to_string(), r["detail"].as_str().unwrap().to_string())).collect(); assert_eq!(rows, [("Asha Menon".to_string(), ASHA.to_string()), ("Asha Menon".to_string(), ASHA_WORK.to_string()), ("Dev Nair".to_string(), DEV.to_string())]); assert_eq!(page["rows"][2]["acts"], json!([ { "id": "ask", "words": "Ask", "call": { "method": "circle.ask", "request": { "person": "p-dev", "handle": "p-dev-h0" } } }, { "id": "invite", "words": "Invite", "call": { "method": "circle.invite", "request": { "person": "p-dev" } } }, ])); assert_eq!(page["foot"], "Asking sends your name to that number only. Cotton never looks through your contacts to find who is on it.");let found = over(&handle.client(), "circle.add.page", &json!({ "query": "dev" })).unwrap(); assert_eq!(found["rows"].as_array().unwrap().len(), 1);let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#), people(json!([]), json!([{ "number": KABIR, "name": null, "waiting": true }]), json!([]))]);let asked = over(&handle.client(), "circle.ask", &json!({ "number": "+1 555 010 0014" })).unwrap(); assert_eq!(body(&exchange.seen()[0]), json!({ "number": KABIR })); assert_eq!(asked["said"], format!("Asked {KABIR}. They join your Circle once they accept.")); assert!(asked["list"]["sections"][0]["rows"][0]["person"].as_str().is_some(), "the typed number is a contact now");}// RULE: signed out, every circle method answers signedOut and nothing else, asking no object.#[test]fn signed_out_the_circle_says_so() {let (_dir, handle) = phone();let answer = over(&handle.client(), "circle.list", &json!({})).unwrap(); assert_eq!(answer["signedOut"]["title"], "Sign in to have a Circle"); assert!(answer.get("sections").is_none());}// RULE: Remove's plan says what ends and what stays, and offers Remove <name> and Block instead; Block's plan offers Block.#[test]fn the_remove_plan_says_what_ends_and_what_stays() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA]); with_door(&handle, []);let plan = over(&handle.client(), "circle.remove.plan", &json!({ "person": "p-asha" })).unwrap(); assert_eq!(plan["title"], "Remove Asha Menon from your Circle?"); assert_eq!(plan["stays"], json!(["What they already saw or saved.", "Your chat, as history.", "Your contact for them."])); assert_eq!(plan["acts"][0], json!({ "id": "remove", "words": "Remove Asha Menon", "red": true, "call": { "method": "circle.remove", "request": { "person": "p-asha" } } })); assert_eq!(plan["acts"][1]["call"]["method"], "circle.remove.plan");let block = over(&handle.client(), "circle.remove.plan", &json!({ "person": "p-asha", "block": true })).unwrap(); assert_eq!(block["title"], "Block Asha Menon?"); assert_eq!(block["acts"][0]["call"], json!({ "method": "circle.block", "request": { "person": "p-asha" } }));}// RULE: a Circle member's safety number is Albums' safety_code over both people's sharing and signing keys, the same// on both phones; first sight pins their keys as seen (a sealed note on his object) with "They match" offered;// confirming marks them checked and pins the sharing key for Secrets too; a scanned code that is not theirs checks// nothing. Someone not in the Circle has no safety number.#[test]fn the_safety_number_is_seen_then_checked_and_a_wrong_scan_checks_nothing() {let (_dir, handle) = phone();let client = handle.client(); client.data_keys().hold(&client.current_database().unwrap(), &cotton_core::seal::DataKey::from_bytes([7u8; 32])); contact(&handle, "p-asha", "Asha Menon", &[ASHA]);let (share, sign) = ("A".repeat(43), "B".repeat(43));let in_circle = || people(json!([]), json!([{ "number": ASHA, "name": null, "waiting": false }]), json!([]));let keys = || Reply::ok(&json!({ "key": share, "sign": sign, "me": "+15550100099" }).to_string());let ok = || Reply::ok(r#"{"ok":true,"notes":[]}"#);let exchange = with_door(&handle, [in_circle(), keys(), ok(), ok(), ok(), ok()]);let seen = over(&handle.client(), "circle.check", &json!({ "person": "p-asha" })).unwrap(); assert!(seen.get("error").is_none(), "{seen}");let mine = (crate::phone::send_seal::sharing(&handle.client()).unwrap().1, crate::phone::send_seal::sign_public(&handle.client()).unwrap()); assert_eq!(seen["words"], cotton_core::seal::shared_album::safety_code((&mine.0, &mine.1), (&share, &sign))); assert_eq!(seen["state"], "seen"); assert_eq!(seen["acts"][0]["call"], json!({ "method": "circle.check.confirm", "request": { "person": "p-asha", "number": null } })); assert_eq!(seen["qr"], format!("cotton-circle:1:+15550100099:{}:{}", mine.0, mine.1));let puts: Vec<String> = exchange.seen().iter().filter(|s| s.method == "PUT").map(|s| body(s)["key"].as_str().unwrap().to_string()).collect(); assert_eq!(puts.len(), 1, "first sight pins their keys once"); assert!(puts[0].starts_with("circle:"));let exchange = with_door(&handle, [in_circle(), keys(), ok(), ok(), ok(), ok()]);let checked = over(&handle.client(), "circle.check.confirm", &json!({ "person": "p-asha" })).unwrap(); assert_eq!((checked["state"].as_str(), checked["said"].as_str()), (Some("checked"), Some("Asha Menon is checked.")));let puts: Vec<String> = exchange.seen().iter().filter(|s| s.method == "PUT").map(|s| body(s)["key"].as_str().unwrap().to_string()).collect(); assert_eq!(puts.len(), 2, "the Circle's pin and Secrets' pin"); assert!(puts.iter().any(|k| k.starts_with("pin:")) && puts.iter().any(|k| k.starts_with("circle:"))); with_door(&handle, [in_circle(), keys(), ok(), ok(), ok()]);let wrong = over(&handle.client(), "circle.check.scan", &json!({ "person": "p-asha", "scanned": "cotton-circle:1:+15550100011:x:y" })).unwrap(); assert_eq!(wrong["error"], "That code isn't Asha Menon's. Nothing was checked."); with_door(&handle, [people(json!([]), json!([]), json!([]))]);let outside = over(&handle.client(), "circle.check", &json!({ "person": "p-asha" })).unwrap(); assert_eq!(outside["error"], "Asha Menon isn't in your Circle yet, so there is no safety number to compare.");}// RULE: an invitation link is <origin>/c/<code>#<secret>: only the secret's SHA-256 reaches the object; the invited// person's phone opens the link by redeeming code and secret from their own object, and the inviter becomes a contact// named with what they gave; anything that is not such a link is refused in words.#[test]fn an_invitation_link_carries_its_secret_only_in_the_fragment_and_opens_on_their_phone() {use sha2::Digestas _;let (_dir, handle) = phone(); contact(&handle, "p-meera", "Meera Iyer", &[]);let exchange = with_door(&handle, [Reply::ok(r#"{"id":"inv-1","code":"abcdefghijkm","ends_at":"2026-12-28T00:00:00.000Z"}"#)]);let made = over(&handle.client(), "circle.invite", &json!({ "person": "p-meera" })).unwrap(); assert_eq!(made["title"], "Invite Meera");let link = made["link"].as_str().unwrap();let (front, secret) = link.split_once('#').unwrap(); assert_eq!(front, "https://cottondb.example.test/c/abcdefghijkm");let sent = body(&exchange.seen()[0]);use base64::Engineas _; assert_eq!(sent["secret_hash"], base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(secret.as_bytes()))); assert!(!String::from_utf8_lossy(&exchange.seen()[0].body).contains(secret), "the secret never reaches the object"); assert_eq!(made["stop"]["call"], json!({ "method": "circle.invite.stop", "request": { "invite": "inv-1" } })); assert!(made["share"].as_str().unwrap().contains(link));let (_dir, theirs) = phone();let exchange = with_door(&theirs, [Reply::ok(&json!({ "number": ASHA, "name": "Asha" }).to_string()), people(json!([]), json!([{ "number": ASHA, "name": "Asha", "waiting": false }]), json!([]))]);// AUDIT E (owner approved, 28 Nov): a link alone only asks; nothing reaches the object until the person says Join.let asked = over(&theirs.client(), "circle.invite.open", &json!({ "link": link })).unwrap(); assert!(exchange.seen().is_empty(), "a link opened by a web page or another app joins no one"); assert_eq!(asked["ask"]["title"], "Join this Circle?"); assert_eq!(asked["ask"]["join"]["call"], json!({ "method": "circle.invite.open", "request": { "link": link, "join": true } })); assert!(asked["ask"]["cancel"].as_str().is_some() && asked["ask"]["line"].as_str().is_some()); assert!(asked.get("said").is_none());let opened = over(&theirs.client(), "circle.invite.open", &json!({ "link": link, "join": true })).unwrap(); assert_eq!(opened["said"], "You and Asha are in each other's Circle."); assert_eq!(body(&exchange.seen()[0]), json!({ "code": "abcdefghijkm", "secret": secret })); assert!(opened["list"]["sections"][0]["rows"][0]["person"].as_str().is_some(), "the inviter is a contact now"); assert_eq!(over(&theirs.client(), "circle.invite.open", &json!({ "link": "https://example.test/nothing" })).unwrap()["error"], "This isn't a Cotton invitation link.");}// RULE: the person page's Circle block says where the contact stands and offers the acts for it: in (with the safety// number and Remove, Block), waiting (Stop asking), none (Ask and Invite); nothing for a contact that is not a person.#[test]fn the_person_page_says_where_the_contact_stands_in_the_circle() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA]); contact(&handle, "p-lata", "Lata Kumar", &[LATA]); contact(&handle, "p-dev", "Dev Nair", &[DEV]);let lists = || people(json!([]), json!([{ "number": ASHA, "name": null, "waiting": false }, { "number": LATA, "name": null, "waiting": true }]), json!([])); with_door(&handle, [lists(), lists(), lists()]);let asha = super::person_part(&handle.client(), "p-asha").unwrap(); assert_eq!((asha["state"].as_str(), asha["check"].as_str()), (Some("in"), Some("seen"))); assert_eq!(asha["safety"]["call"], json!({ "method": "circle.check", "request": { "person": "p-asha" } }));let lata = super::person_part(&handle.client(), "p-lata").unwrap(); assert_eq!(lata["state"], "asked"); assert_eq!(lata["acts"][0]["call"]["method"], "circle.ask.stop");let dev = super::person_part(&handle.client(), "p-dev").unwrap(); assert_eq!(dev["state"], "none"); assert_eq!(dev["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect::<Vec<_>>(), ["ask", "invite"]);}// RULE: someone whose account was erased shows "Left Cotton", and a number that now leads to another account "This// number belongs to someone else on Cotton now", both under No longer on Cotton, never in the Circle; Take off the// list removes them.#[test]fn someone_gone_or_a_number_that_changed_hands_is_no_longer_in_the_circle() {let (_dir, handle) = phone(); contact(&handle, "p-asha", "Asha Menon", &[ASHA]); contact(&handle, "p-ravi", "Ravi Shah", &[RAVI]); with_door(&handle, [people(json!([]), json!([{ "number": ASHA, "name": null, "waiting": false, "left": true }, { "number": RAVI, "name": null, "waiting": false, "changed": true }]), json!([]))]);let drawn = list(&handle.client()); assert_eq!(ids(&drawn, "sections"), ["gone"]); assert_eq!(drawn["sections"][0]["title"], "No longer on Cotton");let rows = &drawn["sections"][0]["rows"]; assert_eq!((rows[0]["words"].as_str(), rows[0]["state"].as_str(), rows[0]["detail"].as_str()), (Some("Asha Menon"), Some("left"), Some("Left Cotton"))); assert_eq!((rows[1]["state"].as_str(), rows[1]["detail"].as_str()), (Some("changed"), Some("This number belongs to someone else on Cotton now"))); assert_eq!(rows[1]["acts"][0]["call"], json!({ "method": "circle.remove", "request": { "person": "p-ravi" } }));}// RULE: Remove's plan says what ends in each app, plainly: secrets they hold taken back (and change the ones they// opened), secrets they shared gone from his phones, his albums they leave, their albums he leaves.#[test]fn the_remove_plan_names_what_ends_in_each_app() {let shares = super::Shares { secrets_out: vec![(ASHA.into(), true), (ASHA.into(), false), (ASHA.into(), true)], secrets_in: vec!["share-1".into()], albums_mine: vec![("sp-1".into(), "m-1".into(), "Mum's 70th".into())], albums_theirs: vec![("sp-2".into(), "Goa trip".into())], unread: false, };let details: Vec<String> = shares.lines().iter().map(|l| format!("{}: {}", l["words"].as_str().unwrap(), l["detail"].as_str().unwrap())).collect(); assert_eq!(details, ["Secrets: 3 they hold are taken back. They opened 2, so change them.","Secrets: 1 they shared with you go from your phones.","Albums: They leave \u{201c}Mum's 70th\u{201d}, which you made.","Albums: You leave \u{201c}Goa trip\u{201d}, which they made.", ]); assert!(super::Shares::default().lines().is_empty());}/// A Circle row's sealed copy as the object writes it (chat.ts `reseal`): `{number, name}` sealed to the arrival key.fn sealed_copy(client: &crate::shell::client::ClientController, number: &str, name: Option<&str>) -> String {use cotton_core::seal::arrival::{arrival_public, seal_arrival_with, VALUE_PREFIX, VALUE_TABLE};use cotton_core::definitions::seal::SealSpec;use cotton_core::seal::{DataKey, Dek};let database = client.current_database().unwrap();let public = arrival_public(&DataKey::from_bytes([7u8; 32]), &database).unwrap();let payload = json!({ "number": number, "name": name }).to_string();let data = json!({ "payload": payload }).as_object().unwrap().clone();let row = seal_arrival_with(&Dek::from_bytes([1; 32]), &[2; 12], &[3; 32], &[4; 12], &public, &database, VALUE_TABLE, super::CIRCLE_BOX, &SealSpec::default(), &data).unwrap(); format!("{VALUE_PREFIX}{}|{}", row["sealed_enc"].as_str().unwrap(), row["dek_enc"].as_str().unwrap())}// RULE (PEOPLE-DESIGN b.4): a row's sealed copy, opened with the DK, is what the row says; the clear fields stand in// only for a row with no sealed copy (written before the object held the arrival key) or one that does not open.#[test]fn the_circle_reads_a_rows_sealed_copy_before_its_clear_fields() {let (_dir, handle) = phone();let client = handle.client(); client.data_keys().hold(&client.current_database().unwrap(), &cotton_core::seal::DataKey::from_bytes([7u8; 32])); contact(&handle, "p-asha", "Asha Menon", &[ASHA]); contact(&handle, "p-ravi", "Ravi Shah", &[RAVI]);let asha = sealed_copy(&client, ASHA, None);let kabir = sealed_copy(&client, KABIR, Some("Kabir from the walking group"));// A row whose clear number the object dropped (step B): only the sealed copy says who.let meera = sealed_copy(&client, "+15550100019", Some("Meera Invented")); with_door( &handle, [people(// A stranger's ask: their name only in the sealed copy. json!([{ "number": KABIR, "name": null, "at": "2026-11-20", "sealed": kabir }]),// Asha's clear number is stale; her sealed copy is the truth. Ravi's row is old: clear only. json!([{ "number": DEV, "name": null, "waiting": false, "sealed": asha }, { "number": RAVI, "name": null, "waiting": false }, { "number": LATA, "name": null, "waiting": false, "sealed": "a2:broken|box" }, { "number": null, "name": null, "waiting": false, "sealed": meera }, { "number": null, "name": null, "waiting": false, "sealed": "a2:broken|box" }]), json!([]), )], );let drawn = list(&client); assert_eq!(ids(&drawn, "sections"), ["asking", "in"]); assert!(drawn["sections"][0]["rows"][0]["words"].as_str().unwrap().contains("Kabir from the walking group"), "{}", drawn["sections"][0]);let words: Vec<&str> = drawn["sections"][1]["rows"].as_array().unwrap().iter().map(|r| r["words"].as_str().unwrap()).collect(); assert!(words.contains(&"Asha Menon") && words.contains(&"Ravi Shah"), "{words:?}"); assert!(words.iter().any(|w| w.contains("Meera Invented")), "{words:?}");// A copy that does not open falls back to the clear number; with no clear number either, the row is left out. assert_eq!(words.len(), 4, "{words:?}");}