Cotton code
361 lines · 19.9 KB · RustRaw
//! COTTON DATA, PROVEN ON DEV (assets/design/data/CONTRACT.md row 12; `pnpm exec tsx scripts/data-proof.ts`).//!//! A Cotton Data phone (the shared core through its C ABI, opened as the `data` flavour, as the Android app opens it)//! against the dev Worker, on an invented number://!//! 1. It signs in. On a fresh number Data founds the account's key itself (DECISIONS "The data key for an account that//!    has only Data"); on a number made before, it opens the key with that account's recovery code (COTTON_DATA_CODE,//!    or COTTON_DATA_CODE_FILE).//! 2. Every screen's call is asked and timed: welcome, tables (until the measure has counted every table), room, a//!    table's rows (the biggest), one row, about, columns, how it links, search (a word of its rows), a table's own//!    search, lately, assistants, leftovers, keep, you. Each answer is checked for its shape and for words only (no//!    server English), and nothing is left waiting to go up: Data only reads.//! 3. Keep everything: chosen, then connected on Wi-Fi (`unmetered`), the whole object is pulled; the seconds, the//!    rows and the bytes say the fill's real rate against DECISIONS' 1.25 MB a second.//!//! Each step prints one `DATA PROOF` line; the last is `DATA PROOF PASSED` or the run panics. SKIPPED unless//! COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_CODE (the dev sign-in code's words) or COTTON_WALK_CODE_FILE, and//! COTTON_DATA_NUMBER (an invented number) are set. Never point it at the live server.use std::ffi::{c_char, CStr, CString};use std::path::{Path, PathBuf};use std::time::Instant;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "headless-data-proof";fn var(name: &str) -> Option<String> {    std::env::var(name).ok().filter(|v| !v.trim().is_empty())}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}struct Phone {    handle: *mut CottonHandle,    container: tempfile::TempDir,    private_key: String,}impl Phone {    fn open(server: &str, number: &str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton data proof {number} {:?}", std::time::SystemTime::now());        let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/data/flavour.json");        let path = if path.is_file() { path } else { cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/data/flavour.json") };        let mut manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("Data's manifest")).expect("JSON");        manifest["business"]["server"] = json!(server);        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest,        });        let text = CString::new(config.to_string()).expect("no NUL");        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        assert!(!handle.is_null(), "cotton_open refused data: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, container, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, (String, String)> {        let method_c = CString::new(method).expect("no NUL");        let request_c = CString::new(request.to_string()).expect("no NUL");        // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.        let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });        let answer: Value = serde_json::from_str(&answer).unwrap_or_else(|e| panic!("{method}: the answer is not JSON ({e})"));        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err((error["code"].as_str().unwrap_or("?").to_string(), error["message"].as_str().unwrap_or("?").to_string()))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|(code, message)| panic!("{method}: {code} {message}"))    }    /// The SignIn form's calls, then `personal.connect`, as the Android shell's Session asks them. Answers the    /// connect request, to connect again later (Keep everything).    fn sign_in(&self, server: &str, number: &str, code: &str) -> Value {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": server, "phone": number }));        let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();        let credential = answer["credential"].as_str().expect("a credential").to_string();        let connect = json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "data proof", "appVersion": APP_VERSION, "unmetered": false });        self.must("personal.connect", connect.clone());        connect    }    /// The account's key held: founded here on a fresh account, else opened with its recovery code. Answers whether    /// this phone founded it.    fn hold_key(&self, code: Option<&str>) -> bool {        let mut founded = false;        let mut opened = false;        for _ in 0..30 {            let status = self.must("seal.status", json!({}));            let yes = |k: &str| status[k] == json!(true) || status[k] == json!("true");            if yes("keyHeld") {                return founded;            }            if yes("needsKey") && yes("founds") {                let said = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "data proof" }));                founded |= said.is_ok();            } else if let (true, Some(code)) = (yes("needsKey"), code) {                let again = if opened { self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "data proof" })).ok() } else { None };                if again.is_none() {                    opened |= self.call("recovery.open", json!({ "code": code, "privateKey": self.private_key, "name": "data proof" })).is_ok();                }            }            let _ = self.call("sync.now", json!({}));            std::thread::sleep(std::time::Duration::from_secs(2));        }        panic!("Data never held the account's key");    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}/// The bytes of every SQLite file under the container: the phone's copy.fn copy_bytes(container: &Path) -> u64 {    let mut total = 0;    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);            } else if std::fs::read(&path).is_ok_and(|b| b.starts_with(b"SQLite format 3")) || path.to_string_lossy().ends_with("-wal") {                total += entry.metadata().map(|m| m.len()).unwrap_or(0);            }        }    }    total}/// An answer must be words: no server English (a route, a status, a stack) reaches a screen.fn words_only(method: &str, v: &Value) {    let text = v.to_string();    for raw in ["nothing answers", "GET /v1", "no date column", "panicked", "Traceback", "internal error"] {        assert!(!text.contains(raw), "{method} carries raw text \"{raw}\": {}", &text[..text.len().min(400)]);    }}/// One timed call, printed; a refusal is printed as the person would read it and answered as `None`.fn timed(phone: &Phone, method: &str, request: Value) -> Option<Value> {    let started = Instant::now();    let said = phone.call(method, request);    let ms = started.elapsed().as_millis();    match said {        Ok(v) => {            words_only(method, &v);            println!("DATA PROOF {method} {ms} ms");            Some(v)        }        Err((code, message)) => {            words_only(method, &json!(message));            println!("DATA PROOF {method} {ms} ms refused {code}: {message}");            None        }    }}#[test]fn cotton_data_is_proven_on_the_dev_server() {    let (Some(server), Some(number)) = (var("COTTON_WALK_SERVER"), var("COTTON_DATA_NUMBER")) else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER and COTTON_DATA_NUMBER");        return;    };    assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "Data is proven on the dev server only, not {server}");    let otp = var("COTTON_WALK_CODE").or_else(|| var("COTTON_WALK_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the dev code file").trim().to_string())).expect("the dev sign-in code");    let code = var("COTTON_DATA_CODE").or_else(|| var("COTTON_DATA_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the recovery code file").trim().to_string()));    let began = Instant::now();    let phone = Phone::open(&server, &number);    let mut connect = phone.sign_in(&server, &number, &otp);    println!("DATA PROOF account {number}, database {}", connect["databaseId"].as_str().unwrap_or("?"));    let founded = phone.hold_key(code.as_deref());    println!("DATA PROOF key held ({}) in {:.1}s", if founded { "founded by Data" } else { "opened with the account's recovery code" }, began.elapsed().as_secs_f64());    // A founded account's recovery code, kept in COTTON_DATA_CODE_OUT for a later run to open it with (never printed).    if let (true, Some(out)) = (founded, var("COTTON_DATA_CODE_OUT")) {        let made = phone.must("recovery.make", json!({ "privateKey": phone.private_key }));        std::fs::write(home(&out), made["code"].as_str().expect("a recovery code")).expect("the code file");        println!("DATA PROOF recovery code kept in {out}");    }    // The copy's first passes: Data's own small kit.    for _ in 0..10 {        let said = phone.call("sync.now", json!({})).unwrap_or_default();        if said["behind"] != json!(true) {            break;        }    }    timed(&phone, "data.welcome", json!({})).expect("welcome answers");    // You on a fresh copy, before any fill (owner, build 1: only the card stood): Data's own rows, the shared list    // from this phone alone, and its whole answer.    timed(&phone, "data.you", json!({}));    timed(&phone, "shell.settings.now", json!({ "notifications": false }));    timed(&phone, "shell.settings", json!({ "notifications": false }));    // Tables, asked until the measure has counted every table (or two minutes).    let mut tables = Value::Null;    let waited = Instant::now();    for _ in 0..24 {        tables = timed(&phone, "data.tables", json!({})).expect("tables answers");        if !tables.to_string().contains("Counting") {            break;        }        std::thread::sleep(std::time::Duration::from_secs(5));    }    let counted = !tables.to_string().contains("Counting");    println!("DATA PROOF tables counted: {counted} after {:.0}s; {}", waited.elapsed().as_secs_f64(), tables["count"]);    timed(&phone, "data.room", json!({}));    // The biggest table with rows, from the Tables answer.    let mut biggest: Option<(String, u64)> = None;    for group in tables["groups"].as_array().into_iter().flatten() {        for t in group["tables"].as_array().into_iter().flatten() {            let rows: u64 = t["rows_line"].as_str().unwrap_or("").chars().take_while(|c| c.is_ascii_digit() || *c == ',').filter(char::is_ascii_digit).collect::<String>().parse().unwrap_or(0);            let id = t["table"].as_str().unwrap_or_default().to_string();            if rows > biggest.as_ref().map_or(0, |b| b.1) && !["secret", "passkey", "code_credential"].contains(&id.as_str()) {                biggest = Some((id, rows));            }        }    }    let mut searched = String::new();    if let Some((table, rows)) = &biggest {        println!("DATA PROOF biggest table {table}: {rows} rows");        let listed = timed(&phone, "data.rows", json!({ "table": table })).unwrap_or_default();        let first = listed["groups"][0]["rows"][0].clone();        if listed["sealed_view"] == json!(true) {            println!("DATA PROOF {table} answered the locked view: this phone holds no key for it");        }        if let Some(id) = first["id"].as_str() {            timed(&phone, "data.row", json!({ "table": table, "id": id }));            timed(&phone, "data.stored", json!({ "table": table, "id": id }));            // A word of the first row's title, searched across everything and within the table.            let word = first["title"].as_str().unwrap_or("").split(|c: char| !c.is_alphanumeric()).filter(|w| w.chars().count() >= 4).last().unwrap_or("").to_lowercase();            searched = word.clone();            if !word.is_empty() {                let found = timed(&phone, "data.search", json!({ "q": word })).unwrap_or_default();                println!("DATA PROOF search \"{word}\": {} {}", found["found_line"], found["searched_line"]);                let inside = timed(&phone, "data.rows", json!({ "table": table, "q": word })).unwrap_or_default();                println!("DATA PROOF {table} search \"{word}\": {} rows", inside["groups"][0]["count"]);            }        }        timed(&phone, "data.about", json!({ "table": table }));        timed(&phone, "data.columns", json!({ "table": table }));        timed(&phone, "data.links", json!({ "table": table }));    }    let lately = timed(&phone, "data.lately", json!({})).unwrap_or_default();    println!("DATA PROOF lately: {} days", lately["days"].as_array().map_or(0, Vec::len));    timed(&phone, "data.assistants", json!({}));    let left = timed(&phone, "data.leftovers", json!({})).unwrap_or_default();    println!("DATA PROOF leftovers: {}", left["lead"]);    let keep = timed(&phone, "data.keep", json!({ "free": 50_000_000_000u64 })).unwrap_or_default();    println!("DATA PROOF keep: {} {}", keep["state"], keep["cost"]);    timed(&phone, "data.you", json!({}));    // Read only: nothing Data did waits to go up.    let status = phone.must("sync.status", json!({}));    println!("DATA PROOF read only: {} writes waiting to go up", status["pending"]);    assert_eq!(status["pending"].as_u64().unwrap_or(0), 0, "Data only reads: {status}");    // Keep everything: chosen, then connected on Wi-Fi; the whole object comes down.    if var("COTTON_DATA_FILL").is_none_or(|v| v != "0") {        phone.must("data.keep.set", json!({ "on": true, "free": 50_000_000_000u64 }));        connect["unmetered"] = json!(true);        phone.must("personal.connect", connect);        let before = copy_bytes(phone.container.path());        let started = Instant::now();        let mut passes = 0;        // The connect starts the copy's own sync loop, which does the filling; a pass asked here may find nothing        // left to do while that loop still pulls. Done once Keep everything says it is kept (the copy holds the rows'        // room) and the copy has stopped growing.        let mut last = before;        let mut still = 0;        // At the owner's size the fill runs most of an hour: COTTON_DATA_FILL_MINUTES bounds it (two hours unless said).        let limit = std::time::Duration::from_secs(60 * var("COTTON_DATA_FILL_MINUTES").and_then(|m| m.parse().ok()).unwrap_or(120u64));        while started.elapsed() < limit {            passes += 1;            let _ = phone.call("sync.now", json!({}));            std::thread::sleep(std::time::Duration::from_secs(3));            let now = copy_bytes(phone.container.path());            let state = phone.call("data.keep", json!({ "free": 50_000_000_000u64 })).map(|k| k["state"].as_str().unwrap_or("").to_string()).unwrap_or_default();            if passes % 10 == 0 {                // Tables stays usable while it fills: asked, timed, and the strip's words as they stand.                let asked = Instant::now();                let tables_ok = phone.call("data.tables", json!({})).is_ok();                let tables_ms = asked.elapsed().as_millis();                let k = phone.call("data.keep", json!({ "free": 50_000_000_000u64 })).unwrap_or_default();                println!(                    "DATA PROOF fill {:.0}s: copy {} MB, {state}, {} {}; data.tables {} in {tables_ms} ms",                    started.elapsed().as_secs_f64(),                    now / 1_000_000,                    k["state_line"].as_str().unwrap_or(""),                    k["progress"]["left_line"].as_str().unwrap_or(""),                    if tables_ok { "answered" } else { "REFUSED" }                );            }            still = if now == last { still + 1 } else { 0 };            last = now;            if state == "keeping" && still >= 2 {                break;            }        }        let secs = started.elapsed().as_secs_f64();        let bytes = copy_bytes(phone.container.path()).saturating_sub(before);        let keep = phone.must("data.keep", json!({ "free": 50_000_000_000u64 }));        println!(            "DATA PROOF fill: {:.1} MB in {secs:.0}s over {passes} passes, {:.2} MB/s (DECISIONS assumes 1.25); keep {} \"{}\"",            bytes as f64 / 1e6,            bytes as f64 / 1e6 / secs.max(0.001),            keep["state"],            keep["state_line"].as_str().unwrap_or("")        );        let tables = timed(&phone, "data.tables", json!({})).unwrap_or_default();        println!("DATA PROOF tables with everything kept: {}", tables["count"]);        if !searched.is_empty() {            let raw = phone.call("records.search", json!({ "query": searched, "limit": 5 }));            println!("DATA PROOF the phone's own search of \"{searched}\": {}", match &raw { Ok(v) => format!("{} hits {}", v["records"].as_array().map_or(0, Vec::len), v["records"].as_array().into_iter().flatten().take(3).map(|h| format!("{}/{}", h["table"], h["kind"])).collect::<Vec<_>>().join(" ")), Err((c, m)) => format!("refused {c}: {m}") });            if raw.is_err() {                for line in phone.call("log.lines", json!({})).unwrap_or_default().as_array().into_iter().flatten().rev().take(400).filter(|l| { let t = l.to_string(); t.contains("search") || t.contains("unreadable") || t.contains("no such") }).take(6) {                    println!("DATA PROOF raw: {}", line.to_string().chars().take(600).collect::<String>());                }            }            let found = timed(&phone, "data.search", json!({ "q": searched })).unwrap_or_default();            println!("DATA PROOF search \"{searched}\" with everything kept: {} {}", found["found_line"], found["searched_line"]);        }    }    println!("DATA PROOF PASSED in {:.0}s", began.elapsed().as_secs_f64());}