//! `developer.inventKeptPictures` and `developer.checkKeptPictures` — COTTON//! DEV ONLY: an invented account as large as a real one, whose kept chat//! pictures sit plain on the object as every app before 22 Nov 2026 left//! them, and the check that every one of them is still there and whole after//! the reseal pass (phone::seal_kept). The coordinator's proof of 22 Nov//! 2026: "an invented account as large as the owner (about 143,000 messages;//! several thousand kept pictures, some large, some from the Mac import//! shape), nothing lost, sha checked, interrupted midway and resumed". The//! real Cotton refuses both by name.//!//! ```text//! developer.inventKeptPictures { from?, count?, every?, bigEvery?, macEvery? } → { messages, pictures, bytes, big, mac }//! developer.checkKeptPictures { after?, limit? } → { checked, sealed, plain, bytes, bad, next }//! ```//!//! Invent writes `count` (default 2,000, at most 5,000) messages numbered from//! `from` through the phone's own write path, so they go up sealed as any//! message does, over thirty invented conversations. Every `every`th (default//! 30) carries one picture: its bytes invented (a real PNG, then filler that//! makes each one its own), put on the object PLAIN under//! `<database>/messages/<thread>/<sha256>.png`, as an app from before kept it.//! Every `bigEvery`th picture (default 60) is 6 to 14 MB, the rest 60 KB to//! 700 KB. Every `macEvery`th (default 3) is in the Mac import's shape (an//! imported WhatsApp message whose `media` names the key); the others in//! Comms' own (`meta.cotton.pictures[0].kept`, `media` cottonKept).//!//! Check walks this copy's messages that keep a picture under `messages/`,//! `limit` (default 200) a call after the message id `after`: fetches each as//! the object keeps it, opens a sealed one with this phone's key, and checks//! that the bytes are the ones its name says. `bad` names every key that is//! missing, does not open, or is not its sha.use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};usesuper::cotton_chat::{ensure_thread, namespace, put_typed, rows, touch_thread, write, ws, MESSAGES};usecrate::handle::CottonHandle;usecrate::methods::MethodError;use cotton_tools::mcp::handlers::common::insert_row;const THREADS: usize = 30;/// A real 32×24 PNG: each invented picture starts as one, so a picture drawn at a size has an image to read.const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC";fn dev_only(handle: &CottonHandle, method: &str) -> Result<(), MethodError> {if handle.flavor() != cotton_core::flavor::Flavor::Dev {returnErr(MethodError::new("not_dev", format!("developer.{method} answers only in Cotton Dev"))); }Ok(())}/// Picture `n`'s invented bytes: the PNG, then filler from `n` to `size`.fn picture(n: u64, size: usize) -> Vec<u8> {use base64::Engineas _;letmut bytes = base64::engine::general_purpose::STANDARD.decode(PNG).unwrap_or_default();letmut state = n.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;if size > bytes.len() { bytes.reserve(size - bytes.len());while bytes.len() < size { state ^= state << 13; state ^= state >> 7; state ^= state << 17; bytes.extend_from_slice(&state.to_le_bytes()); } bytes.truncate(size); } bytes}fn size_of(n: u64, big: bool) -> usize {let spread = (n.wrapping_mul(2_654_435_761) % 1000) as usize;if big {6 * 1024 * 1024 + spread * 8 * 1024 * 1024 / 1000 } else {60 * 1024 + spread * 640 * 1024 / 1000 }}pubfn invent(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> { dev_only(handle, "inventKeptPictures")?;let client = handle.client();let database = client.current_database().map_err(|why| MethodError::new("no_database", why))?;if client.object_door().is_none() {returnErr(MethodError::new("sign_in_first", "kept pictures are a signed-in phone's")); }let from = request["from"].as_u64().unwrap_or(0);let count = request["count"].as_u64().unwrap_or(2_000).min(5_000);let every = request["every"].as_u64().unwrap_or(30).max(1);let big_every = request["bigEvery"].as_u64().unwrap_or(60).max(1);let mac_every = request["macEvery"].as_u64().unwrap_or(3).max(1);let ns = namespace(&client)?;let failed = |why: String| MethodError::new("invent_failed", why);// The pictures first, each put plain as an app from before kept it; then the messages naming them, in one write.letmut pictures: Vec<(u64, String, usize, bool, bool)> = Vec::new();let (mut bytes, mut big, mut mac) = (0u64, 0usize, 0usize);let threads: Vec<String> = (0..THREADS).map(|t| format!("+1555019{:04}", 1000 + t)).collect();// Thread ids are the core's, made once by number.let thread_ids: Vec<String> = {let ns = ns.clone();let threads = threads.clone();let made = write(&client, "developer.inventKeptPictures", move |ctx| {letmut ids = Vec::new();for (t, number) in threads.iter().enumerate() { ids.push(json!(ensure_thread(ctx, &ns, number, Some(&format!("Invented kept {t}")), None, None, true)?)); }Ok(json!(ids)) })?; made.as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect() };if thread_ids.len() != THREADS {returnErr(failed(format!("made {} conversations of {THREADS}", thread_ids.len()))); }for i in from..from + count {if i % every != 0 {continue; }let n = i / every;let is_big = n % big_every == big_every - 1;let is_mac = n % mac_every == 0;// The first few are the PNG alone, so a whole one is a picture any reader draws.let size = if n < 5 { 0 } else { size_of(n, is_big) };let plain = picture(n, size);let sha = hex::encode(Sha256::digest(&plain));let thread = &thread_ids[(i as usize) % THREADS];let media_path = format!("{database}/messages/{thread}/{sha}.png"); put_typed(&client, &format!("/v1/media/{media_path}"), &plain, "image/png").map_err(|refusal| failed(format!("{media_path}: {}", refusal.message)))?; bytes += plain.len() as u64; big += usize::from(is_big); mac += usize::from(is_mac); pictures.push((i, media_path, plain.len(), is_mac, is_big)); }let at_of = |i: u64| cotton_chat_iso(1_760_000_000_000 + i as i64 * 60_000);let ids = thread_ids.clone();let shaped: Vec<(u64, String, usize, bool)> = pictures.iter().map(|(i, k, s, m, _)| (*i, k.clone(), *s, *m)).collect(); write(&client, "developer.inventKeptPictures", move |ctx| {letmut with = shaped.iter().peekable();for i in from..from + count {let thread = &ids[(i as usize) % THREADS];let at = at_of(i);letmut columns = Map::new(); columns.insert("thread_id".into(), json!(thread)); columns.insert("sent_at".into(), json!(at)); columns.insert("body".into(), json!(format!("Invented message {i}: see you at seven")));let picture = with.next_if(|(n, ..)| *n == i);match picture {Some((_, key, size, true)) => {// The Mac's WhatsApp import: an imported message, its file named in media. columns.insert("channel".into(), json!("whatsapp")); columns.insert("origin".into(), json!("imported")); columns.insert("direction".into(), json!("in")); columns.insert("external_id".into(), json!(format!("dev-kept-wa-{i:09}"))); columns.insert("media".into(), json!([{ "key": key, "contentType": "image/png", "kind": "photo", "name": format!("IMG-{i}.png"), "sizeBytes": size }])); }Some((_, key, size, false)) => {// Comms' own: the sender's kept copy, as chat_files::keep leaves it.let sha = key.rsplit('/').next().unwrap_or_default().trim_end_matches(".png").to_string(); columns.insert("channel".into(), json!(cotton_core::chat::CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("direction".into(), json!("out")); columns.insert("send_state".into(), json!("delivered")); columns.insert("external_id".into(), json!(format!("dev-kept-{i:09}"))); columns.insert("media".into(), json!([{ "key": key, "cottonKept": true, "contentType": "image/png", "kind": "photo", "name": format!("IMG_{i}.png"), "sizeBytes": size, "width": 32, "height": 24 }])); columns.insert("meta".into(), json!({ "cotton": { "pictures": [{ "kept": key, "sha256": sha, "mime": "image/png", "kind": "photo", "name": format!("IMG_{i}.png"), "bytes": size, "width": 32, "height": 24, "file": "", "key": "" }] } })); }None => { columns.insert("channel".into(), json!("whatsapp")); columns.insert("origin".into(), json!("imported")); columns.insert("direction".into(), json!(if i % 2 == 0 { "in" } else { "out" })); columns.insert("external_id".into(), json!(format!("dev-kept-wa-{i:09}"))); } } insert_row(ctx, MESSAGES, &format!("dev-kept-{i:09}"), columns).map_err(|f| f.to_string())?; }for thread in &ids { touch_thread(ctx, thread, &at_of(from + count), Some("Invented message"), false)?; }Ok(Value::Null) })?;Ok(json!({ "messages": count, "pictures": pictures.len(), "bytes": bytes, "big": big, "mac": mac }))}fn cotton_chat_iso(ms: i64) -> String {super::cotton_chat::iso(ms)}pubfn check(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {use cotton_client::transport::object::bearer; dev_only(handle, "checkKeptPictures")?;let client = handle.client();let database = client.current_database().map_err(|why| MethodError::new("no_database", why))?;let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "kept pictures are a signed-in phone's"))?;let after = request["after"].as_str().unwrap_or("").to_string();let limit = request["limit"].as_u64().unwrap_or(200).min(2_000) as i64;let prefix = format!("%{database}/messages/%");let found = super::cotton_chat::read(&client, "developer.checkKeptPictures", move |ctx| {let ws = ws(ctx);let found = rows( ctx, &format!("SELECT id, media FROM {MESSAGES} WHERE workspace_id = ? AND id > ? AND media LIKE ? AND trashed_at IS NULL ORDER BY id LIMIT ?"), &[ws, rusqlite::types::Value::Text(after.clone()), rusqlite::types::Value::Text(prefix.clone()), rusqlite::types::Value::Integer(limit)], )?;Ok(json!(found)) })?;let files = super::personal_object::person_files_of(&client, &database);let (mut checked, mut sealed, mut plain, mut bytes) = (0usize, 0usize, 0usize, 0u64);letmut bad: Vec<Value> = Vec::new();letmut next = None;for row in found.as_array().into_iter().flatten() { next = row["id"].as_str().map(str::to_string);let media = match &row["media"] {Value::String(t) => serde_json::from_str::<Value>(t).unwrap_or(Value::Null), other => other.clone(), };for entry in media.as_array().into_iter().flatten() {letSome(media_path) = entry["key"].as_str().filter(|k| k.starts_with(&format!("{database}/messages/"))) else { continue }; checked += 1;let said = |why: &str| json!({ "key": media_path, "why": why });let (status, raw) = match door.address.send_bytes(door.exchange.as_ref(), "GET", &format!("/v1/media/{media_path}"), bearer(&door.credential), None) {Ok(answer) => answer,Err(refusal) => { bad.push(said(&format!("offline: {}", refusal.message)));continue; } };if status != 200 { bad.push(said(&format!("the object answered {status}")));continue; }let opened = if raw.starts_with(cotton_core::seal::file::MAGIC) { sealed += 1;letOk(fk) = files.file_key(media_path) else { bad.push(said("no key on this phone"));continue; };letmut out = Vec::with_capacity(raw.len());if cotton_core::seal::file::open_file(&fk, media_path, &mut raw.as_slice(), &mut out).is_err() { bad.push(said("sealed, and does not open"));continue; } out } else { plain += 1; raw };let named = media_path.rsplit('/').next().unwrap_or_default().split('.').next().unwrap_or_default();if hex::encode(Sha256::digest(&opened)) != named { bad.push(said("not the bytes its name says"));continue; } bytes += opened.len() as u64; } }let full = found.as_array().map_or(0, Vec::len) as i64 >= limit;Ok(json!({ "checked": checked, "sealed": sealed, "plain": plain, "bytes": bytes, "bad": bad, "next": if full { next } else { None } }))}/// `developer.resealKept { unmetered? }` — one run of the reseal pass whatever `seal_kept::RESEAL` says, for its proof on dev.pubfn reseal(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> { dev_only(handle, "resealKept")?;let ran = super::seal_kept::carry_now(&handle.client(), request["unmetered"] != json!(false)).map_err(|why| MethodError::new("reseal_failed", why))?;Ok(json!({ "files": ran.sealed, "bytes": ran.bytes, "left": ran.left, "done": ran.done, "waiting": ran.waiting }))}