//! Client persistence for Meow v2, designed to resist device seizure. //! //! One SQLite file per identity, used only as a **bag of uniform blocks** (`blocks.rs`): //! fixed-size rows under random ids. Without a password nothing relates blocks to one //! another: no contact list, no per-conversation count, size or date. //! //! * **Spaces.** A password opens a *space*: Argon2id(password, store salt) gives a key //! whose HMAC is the id of the space's *root* block. The root holds the space key and //! the location of the space *index*; the index lists the space's objects (profile, //! contacts, conversation segments, files) and its free blocks. The main password //! opens [`SpaceId::MAIN`]; other passwords open hidden spaces holding one or several //! contacts. Unlocking costs one Argon2id and one lookup, found or not. //! * **Deniability.** At creation a random number of random filler blocks is added and //! *not recorded anywhere*; saves sometimes add more. Hidden spaces' blocks are //! indistinguishable from them, so "blocks I cannot open" exist in every store. //! * **Unlinkability.** A rewritten object moves to other blocks (picked at random among //! the space's free ones); the old blocks are wiped. Saves also rewrite random free //! blocks. Only roots keep a fixed id. //! * **Segments.** A conversation is a list of pages of about [`PAGE_BYTES`]: appending //! rewrites only the last page, and history is read page by page. //! * **Durability.** WAL with `synchronous=FULL`, checkpointed after each save (no //! history of recent writes left in the WAL). Once [`Store::save`] returns, the data //! survives a crash: the client's "persist, then send/ack" rule relies on it. //! * **Exclusivity.** An OS lock on `.lock` is held for the store's lifetime. //! //! Known limit: an attacker holding several copies of the file taken at different //! times sees which blocks changed between them (not which object they belong to). //! See ARCHITECTURE.md §6. #![forbid(unsafe_code)] #![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] pub mod blocks; pub mod model; pub mod schema; use std::collections::HashMap; use std::path::{Path, PathBuf}; use blocks::{BlockId, ObjectRef, Writer, CAPACITY}; use meow_core::contact::{Contact, ContactId}; use meow_crypto::aead::Key; use meow_crypto::password::KdfParams; use rusqlite::{Connection, OptionalExtension}; use serde::{Deserialize, Serialize}; pub use model::{ Batch, Content, HistoryEntry, HistoryPage, OutboxItem, PendingAck, RetiredMailbox, Settings, SpaceId, State, Status, }; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("wrong password")] BadPassword, #[error("corrupted store: {0}")] Corrupted(String), #[error("{0} is in use by another process")] Locked(String), #[error("{0} already exists")] Exists(String), #[error("store written by a newer version (schema {0})")] NewerSchema(u32), #[error("this password cannot be used")] PasswordUnavailable, #[error("unknown space")] UnknownSpace, #[error("{0}")] Invalid(String), #[error("i/o: {0}")] Io(#[from] std::io::Error), #[error("sqlite: {0}")] Sqlite(#[from] rusqlite::Error), #[error("crypto: {0}")] Crypto(#[from] meow_crypto::CryptoError), } pub type Result = std::result::Result; /// Target size of a conversation segment. pub const PAGE_BYTES: usize = 4 * CAPACITY; /// Random filler blocks added at creation: between MIN and MIN + SPAN. const FILLER_MIN: usize = 128; const FILLER_SPAN: usize = 896; // ───────────────────────────── on-disk objects ───────────────────────────── #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] enum SpaceKind { Main, Hidden, } /// Single block at `HMAC(password key, label)`. #[derive(Serialize, Deserialize)] struct Root { kind: SpaceKind, space_key: [u8; 32], index: ObjectRef, } #[derive(Default, Serialize, Deserialize)] struct Index { meta: Option, contacts: Vec, outbox: Vec<(Vec, ObjectRef)>, free: Vec, } fn outbox_key(id: &[u8]) -> String { let hex: String = id.iter().map(|b| format!("{b:02x}")).collect(); format!("outbox/{hex}") } #[derive(Clone, Serialize, Deserialize)] struct ContactEntry { id: ContactId, state: ObjectRef, dir: ObjectRef, } /// Per-conversation directory: segments (oldest first) and received files. #[derive(Default, Serialize, Deserialize)] struct Dir { pages: Vec, files: Vec<(Vec, ObjectRef)>, } /// Space-wide data other than contacts. #[derive(Default, Serialize, Deserialize)] struct Meta { nickname: String, servers: Vec, pending_acks: Vec, retired_mailboxes: Vec, settings: Settings, } // ───────────────────────────── keys ───────────────────────────── struct PasswordKeys { root_id: BlockId, root_key: Key, } fn password_keys(password: &str, salt: &[u8; 16], kdf: KdfParams) -> Result { let k = meow_crypto::password::derive_key(password.as_bytes(), salt, kdf)?; Ok(PasswordKeys { root_id: meow_crypto::kdf::hmac(&k.0, b"meow/v2/store/root-id"), root_key: Key(meow_crypto::kdf::derive(&k.0, salt, "meow/v2/store/root-key")?), }) } fn space_block_key(space_key: &[u8; 32]) -> Result { Ok(Key(meow_crypto::kdf::derive(space_key, &[], "meow/v2/store/blocks")?)) } fn encode_kdf(p: KdfParams) -> Vec { [ p.m_cost_kib.to_be_bytes(), p.t_cost.to_be_bytes(), p.p_cost.to_be_bytes(), ] .concat() } fn decode_kdf(b: &[u8]) -> Result { let word = |i: usize| -> Result { b.get(i..i + 4) .and_then(|s| s.try_into().ok()) .map(u32::from_be_bytes) .ok_or_else(|| Error::Corrupted("bad kdf parameters".into())) }; let p = KdfParams { m_cost_kib: word(0)?, t_cost: word(4)?, p_cost: word(8)?, }; // Refuse absurd parameters from a tampered file (DoS). if p.m_cost_kib > 4 * 1024 * 1024 || p.t_cost > 64 || p.p_cost > 16 { return Err(Error::Corrupted("bad kdf parameters".into())); } Ok(p) } // ───────────────────────────── files ───────────────────────────── fn lock_file(path: &Path) -> Result { let f = std::fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .open(sidecar(path, ".lock"))?; match f.try_lock() { Ok(()) => Ok(f), Err(std::fs::TryLockError::WouldBlock) => Err(Error::Locked(path.display().to_string())), Err(std::fs::TryLockError::Error(e)) => Err(Error::Io(e)), } } fn sidecar(path: &Path, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_owned(); p.push(suffix); PathBuf::from(p) } /// Create the file with owner-only permissions before SQLite opens it. fn create_private(path: &Path) -> Result<()> { let mut o = std::fs::OpenOptions::new(); o.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; o.mode(0o600); } o.open(path)?; Ok(()) } fn connect(path: &Path) -> Result { let conn = Connection::open(path)?; // Fails here (SQLITE_NOTADB) when the file is not a SQLite database. conn.execute_batch( "PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA secure_delete = ON;", ) .map_err(|e| Error::Corrupted(format!("not a meow store ({e})")))?; Ok(conn) } fn checkpoint(conn: &Connection) -> Result<()> { conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?; Ok(()) } fn encode(v: &T) -> Result> { postcard::to_allocvec(v).map_err(|e| Error::Invalid(e.to_string())) } // ───────────────────────────── store ───────────────────────────── struct Space { root_id: BlockId, root_key: Key, kind: SpaceKind, space_key: [u8; 32], key: Key, index: Index, index_ref: ObjectRef, /// Plaintext hash of each object as last written, to skip unchanged ones. written: HashMap, } /// An open identity store with its unlocked spaces. pub struct Store { conn: Connection, path: PathBuf, salt: [u8; 16], kdf: KdfParams, spaces: Vec, _lock: std::fs::File, } impl std::fmt::Debug for Store { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Store") .field("path", &self.path) .field("spaces", &self.spaces.len()) .finish_non_exhaustive() } } impl Store { /// Create a new store whose main space is opened by `password`. Fails if `path` /// exists, unless `overwrite`. pub fn create(path: &Path, nickname: &str, password: &str, kdf: KdfParams, overwrite: bool) -> Result { let lock = lock_file(path)?; if path.exists() { if !overwrite { return Err(Error::Exists(path.display().to_string())); } for p in [path.to_path_buf(), sidecar(path, "-wal"), sidecar(path, "-shm")] { if p.exists() { std::fs::remove_file(p)?; } } } create_private(path)?; let mut conn = connect(path)?; schema::migrate(&mut conn)?; let salt: [u8; 16] = meow_crypto::random_bytes(); { let tx = conn.transaction()?; tx.execute("INSERT INTO meta (name, value) VALUES ('salt', ?1)", [salt.as_slice()])?; tx.execute("INSERT INTO meta (name, value) VALUES ('kdf', ?1)", [encode_kdf(kdf)])?; blocks::add_filler(&tx, FILLER_MIN + blocks::rand_below(FILLER_SPAN))?; tx.commit()?; } let mut store = Self { conn, path: path.to_path_buf(), salt, kdf, spaces: Vec::new(), _lock: lock, }; store.new_space(password, SpaceKind::Main)?; store.save( SpaceId::MAIN, &State { nickname: nickname.to_string(), ..State::default() }, Batch::default(), )?; Ok(store) } /// Open a store with its main password, migrating its schema if needed. pub fn open(path: &Path, password: &str) -> Result { if !path.exists() { return Err(Error::Io(std::io::Error::new( std::io::ErrorKind::NotFound, format!("{} does not exist", path.display()), ))); } let lock = lock_file(path)?; let mut conn = connect(path)?; let meta = |name: &str| -> Result> { conn.query_row("SELECT value FROM meta WHERE name = ?1", [name], |r| r.get(0)) .optional() .map_err(|e| Error::Corrupted(format!("not a meow store ({e})")))? .ok_or_else(|| Error::Corrupted(format!("missing {name}"))) }; let salt: [u8; 16] = meta("salt")? .try_into() .map_err(|_| Error::Corrupted("bad salt".into()))?; let kdf = decode_kdf(&meta("kdf")?)?; // Never modify a store we cannot open: unlock first, then migrate. let keys = password_keys(password, &salt, kdf)?; let space = load_space(&conn, keys)?.ok_or(Error::BadPassword)?; if space.kind != SpaceKind::Main { return Err(Error::BadPassword); } schema::migrate(&mut conn)?; Ok(Self { conn, path: path.to_path_buf(), salt, kdf, spaces: vec![space], _lock: lock, }) } pub fn path(&self) -> &Path { &self.path } /// Unlocked spaces, main first. pub fn spaces(&self) -> Vec { (0..self.spaces.len()).map(SpaceId).collect() } /// Try `password` as a hidden-space password. Same cost whether or not a space /// exists. Returns the space (already unlocked ones included), or `None`. pub fn unlock(&mut self, password: &str) -> Result> { let keys = password_keys(password, &self.salt, self.kdf)?; if let Some(i) = self.spaces.iter().position(|s| s.root_id == keys.root_id) { return Ok(Some(SpaceId(i))); } match load_space(&self.conn, keys)? { Some(space) => { self.spaces.push(space); Ok(Some(SpaceId(self.spaces.len() - 1))) } None => Ok(None), } } /// Create a hidden space opened by `password` (which must not open anything yet). pub fn create_space(&mut self, password: &str) -> Result { self.new_space(password, SpaceKind::Hidden) } fn new_space(&mut self, password: &str, kind: SpaceKind) -> Result { let keys = password_keys(password, &self.salt, self.kdf)?; if blocks::read_block(&self.conn, &keys.root_id)?.is_some() { return Err(Error::PasswordUnavailable); } let space_key: [u8; 32] = meow_crypto::random_bytes(); self.spaces.push(Space { root_id: keys.root_id, root_key: keys.root_key, kind, key: space_block_key(&space_key)?, space_key, index: Index::default(), index_ref: ObjectRef::default(), written: HashMap::new(), }); let id = SpaceId(self.spaces.len() - 1); if let Err(e) = self.save(id, &State::default(), Batch::default()) { self.spaces.pop(); return Err(e); } Ok(id) } fn space(&self, id: SpaceId) -> Result<&Space> { self.spaces.get(id.0).ok_or(Error::UnknownSpace) } /// Change the password of a space. Its data is untouched: only the root moves. pub fn change_password(&mut self, space: SpaceId, new_password: &str) -> Result<()> { let keys = password_keys(new_password, &self.salt, self.kdf)?; if blocks::read_block(&self.conn, &keys.root_id)?.is_some() { return Err(Error::PasswordUnavailable); } let sp = self.spaces.get_mut(space.0).ok_or(Error::UnknownSpace)?; let tx = self.conn.transaction()?; let root = encode(&Root { kind: sp.kind, space_key: sp.space_key, index: sp.index_ref.clone(), })?; blocks::write_block( &tx, &keys.root_id, &blocks::seal_block(&keys.root_key, &keys.root_id, &root), )?; // The old root becomes indistinguishable filler. blocks::write_block(&tx, &sp.root_id, &blocks::random_block())?; tx.commit()?; checkpoint(&self.conn)?; sp.root_id = keys.root_id; sp.root_key = keys.root_key; Ok(()) } /// Load a space's state (everything but history and files). pub fn load(&mut self, space: SpaceId) -> Result { let sp = self.spaces.get_mut(space.0).ok_or(Error::UnknownSpace)?; let mut state = State::default(); if let Some(r) = &sp.index.meta { let bytes = blocks::get(&self.conn, &sp.key, r)?; sp.written.insert("meta".into(), meow_crypto::sha256(&[&bytes])); let m: Meta = postcard::from_bytes(&bytes).map_err(|e| Error::Corrupted(format!("meta: {e}")))?; state.nickname = m.nickname; state.servers = m.servers; state.pending_acks = m.pending_acks; state.retired_mailboxes = m.retired_mailboxes; state.settings = m.settings; } for e in &sp.index.contacts { let bytes = blocks::get(&self.conn, &sp.key, &e.state)?; sp.written .insert(format!("contact/{}", e.id.0), meow_crypto::sha256(&[&bytes])); let c: Contact = postcard::from_bytes(&bytes).map_err(|e| Error::Corrupted(format!("contact: {e}")))?; if c.id != e.id { return Err(Error::Corrupted("contact id mismatch".into())); } state.contacts.push(c); } for (id, r) in &sp.index.outbox { let bytes = blocks::get(&self.conn, &sp.key, r)?; sp.written.insert(outbox_key(id), meow_crypto::sha256(&[&bytes])); let item: model::OutboxItem = postcard::from_bytes(&bytes).map_err(|e| Error::Corrupted(format!("outbox: {e}")))?; state.outbox.push(item); } Ok(state) } /// Persist a space's `state` and append `batch`, atomically and durably. Unchanged /// objects are not rewritten; contacts absent from `state` are deleted with their /// history and files. pub fn save(&mut self, space: SpaceId, state: &State, batch: Batch) -> Result<()> { let sp = self.spaces.get_mut(space.0).ok_or(Error::UnknownSpace)?; let tx = self.conn.transaction()?; let mut written = Vec::new(); let new_index_ref; let new_free; let new_contacts; let new_outbox; let new_meta; { let mut w = Writer::new(&tx, &sp.key, sp.index.free.clone()); let mut meta_ref = sp.index.meta.clone(); let mut contacts_idx = sp.index.contacts.clone(); // Space metadata. let meta = encode(&Meta { nickname: state.nickname.clone(), servers: state.servers.clone(), pending_acks: state.pending_acks.clone(), retired_mailboxes: state.retired_mailboxes.clone(), settings: state.settings, })?; let h = meow_crypto::sha256(&[&meta]); if sp.written.get("meta") != Some(&h) || meta_ref.is_none() { meta_ref = Some(w.put(&meta, meta_ref.as_ref())?); written.push(("meta".to_string(), h)); } // Removed contacts: release everything they own. let mut kept = Vec::with_capacity(contacts_idx.len()); for e in contacts_idx { if state.contacts.iter().any(|c| c.id == e.id) { kept.push(e); continue; } let dir: Dir = blocks::get_value(&tx, &sp.key, &e.dir)?; dir.pages.iter().for_each(|p| w.release(p)); dir.files.iter().for_each(|(_, f)| w.release(f)); w.release(&e.dir); w.release(&e.state); } contacts_idx = kept; // Contacts, in the state's order. let mut entries = Vec::with_capacity(state.contacts.len()); for c in &state.contacts { let bytes = encode(c)?; let h = meow_crypto::sha256(&[&bytes]); let key = format!("contact/{}", c.id.0); let entry = match contacts_idx.iter().find(|e| e.id == c.id).cloned() { Some(mut e) => { if sp.written.get(&key) != Some(&h) { e.state = w.put(&bytes, Some(&e.state))?; written.push((key, h)); } e } None => { written.push((key, h)); ContactEntry { id: c.id.clone(), state: w.put(&bytes, None)?, dir: w.put_value(&Dir::default(), None)?, } } }; entries.push(entry); } contacts_idx = entries; // Send queue: one object per item, rewritten only when it changed. let mut outbox_idx = Vec::with_capacity(state.outbox.len()); for (id, r) in &sp.index.outbox { if !state.outbox.iter().any(|o| o.id == *id) { w.release(r); } } for item in &state.outbox { let bytes = encode(item)?; let h = meow_crypto::sha256(&[&bytes]); let key = outbox_key(&item.id); let old = sp.index.outbox.iter().find(|(id, _)| *id == item.id).map(|(_, r)| r); let r = match old { Some(r) if sp.written.get(&key) == Some(&h) => r.clone(), old => { written.push((key, h)); w.put(&bytes, old)? } }; outbox_idx.push((item.id.clone(), r)); } // History and files, per conversation. #[derive(Default)] struct Pending { history: Vec, files: Vec<(Vec, Vec)>, status: Vec<(Vec, Status)>, } fn slot<'a>(v: &'a mut Vec<(ContactId, Pending)>, c: &ContactId) -> &'a mut Pending { let i = match v.iter().position(|(x, _)| x == c) { Some(i) => i, None => { v.push((c.clone(), Pending::default())); v.len() - 1 } }; &mut v[i].1 } let mut by_contact: Vec<(ContactId, Pending)> = Vec::new(); for h in batch.history { let c = h.contact.clone(); slot(&mut by_contact, &c).history.push(h); } for (c, mid, data) in batch.files { slot(&mut by_contact, &c).files.push((mid, data)); } for (c, mid, st) in batch.status { slot(&mut by_contact, &c).status.push((mid, st)); } for (cid, Pending { history, files, status }) in by_contact { let entry = contacts_idx .iter_mut() .find(|e| e.id == cid) .ok_or_else(|| Error::Invalid(format!("history for a contact not in this space: {cid}")))?; let mut dir: Dir = blocks::get_value(&tx, &sp.key, &entry.dir)?; append_history(&tx, &sp.key, &mut w, &mut dir, history)?; for (mid, data) in files { if !dir.files.iter().any(|(m, _)| *m == mid) { let r = w.put(&data, None)?; dir.files.push((mid, r)); } } update_status(&tx, &sp.key, &mut w, &mut dir, status)?; entry.dir = w.put_value(&dir, Some(&entry.dir))?; } w.finish_releases()?; // The index lists the free blocks, so its own blocks are taken first. let old_index = Some(&sp.index_ref).filter(|r| !r.blocks.is_empty()); let r = w.put_self_referencing(old_index, |free| { encode(&Index { meta: meta_ref.clone(), contacts: contacts_idx.clone(), outbox: outbox_idx.clone(), free: free.to_vec(), }) })?; let root = encode(&Root { kind: sp.kind, space_key: sp.space_key, index: r.clone(), })?; if root.len() > CAPACITY { return Err(Error::Invalid("space index too large".into())); } blocks::write_block(&tx, &sp.root_id, &blocks::seal_block(&sp.root_key, &sp.root_id, &root))?; new_index_ref = r; new_free = w.free; new_contacts = contacts_idx; new_outbox = outbox_idx; new_meta = meta_ref; } tx.commit()?; checkpoint(&self.conn)?; // Only now (committed) does the in-memory view change. sp.index_ref = new_index_ref; sp.index = Index { meta: new_meta, contacts: new_contacts, outbox: new_outbox, free: new_free, }; sp.written.retain(|k, _| { k == "meta" || state.contacts.iter().any(|c| *k == format!("contact/{}", c.id.0)) || state.outbox.iter().any(|o| *k == outbox_key(&o.id)) }); sp.written.extend(written); Ok(()) } /// One segment of a conversation (`None`: the latest one), oldest message first. pub fn history(&self, space: SpaceId, contact: &ContactId, page: Option) -> Result { let sp = self.space(space)?; let dir = self.dir(sp, contact)?; let Some(last) = dir.pages.len().checked_sub(1) else { return Ok(HistoryPage { entries: vec![], page: 0, prev: None, }); }; let page = page.unwrap_or(last).min(last); let entries: Vec = blocks::get_value(&self.conn, &sp.key, &dir.pages[page])?; Ok(HistoryPage { entries, page, prev: page.checked_sub(1), }) } /// Whole conversation, oldest first. pub fn full_history(&self, space: SpaceId, contact: &ContactId) -> Result> { let sp = self.space(space)?; let dir = self.dir(sp, contact)?; let mut out = Vec::new(); for p in &dir.pages { let mut page: Vec = blocks::get_value(&self.conn, &sp.key, p)?; out.append(&mut page); } Ok(out) } /// Content of a received file, if stored. pub fn file(&self, space: SpaceId, contact: &ContactId, message_id: &[u8]) -> Result>> { let sp = self.space(space)?; let dir = self.dir(sp, contact)?; dir.files .iter() .find(|(m, _)| m == message_id) .map(|(_, r)| blocks::get(&self.conn, &sp.key, r)) .transpose() } fn dir(&self, sp: &Space, contact: &ContactId) -> Result { let e = sp .index .contacts .iter() .find(|e| e.id == *contact) .ok_or_else(|| Error::Invalid(format!("unknown contact {contact}")))?; blocks::get_value(&self.conn, &sp.key, &e.dir) } } /// Load a space from its root, if the password opens one. fn load_space(conn: &Connection, keys: PasswordKeys) -> Result> { let Some(data) = blocks::read_block(conn, &keys.root_id)? else { return Ok(None); }; // Filler at that id (practically impossible) or a wrong key: not a root. let Ok(plain) = blocks::open_block(&keys.root_key, &keys.root_id, &data) else { return Ok(None); }; let root: Root = postcard::from_bytes(&plain).map_err(|e| Error::Corrupted(format!("root: {e}")))?; let key = space_block_key(&root.space_key)?; let index: Index = blocks::get_value(conn, &key, &root.index)?; Ok(Some(Space { root_id: keys.root_id, root_key: keys.root_key, kind: root.kind, space_key: root.space_key, key, index, index_ref: root.index, written: HashMap::new(), })) } /// Append entries to the last segment (rewritten), opening new segments past /// [`PAGE_BYTES`]. A message id already present in the last segment is ignored. fn append_history( conn: &Connection, key: &Key, w: &mut Writer, dir: &mut Dir, history: Vec, ) -> Result<()> { if history.is_empty() { return Ok(()); } let mut current: Vec = match dir.pages.last() { Some(r) => blocks::get_value(conn, key, r)?, None => Vec::new(), }; let mut current_ref = dir.pages.pop(); let mut size: usize = 0; for e in ¤t { size += encode(e)?.len(); } for h in history { if current.iter().any(|e| e.id == h.id) { continue; } let n = encode(&h)?.len(); if !current.is_empty() && size + n > PAGE_BYTES { let r = w.put_value(¤t, current_ref.as_ref())?; dir.pages.push(r); current = Vec::new(); current_ref = None; size = 0; } size += n; current.push(h); } let r = w.put_value(¤t, current_ref.as_ref())?; dir.pages.push(r); Ok(()) } /// Apply status changes, searching segments from the latest one (where nearly all /// updates land). Only rewritten segments change blocks. fn update_status( conn: &Connection, key: &Key, w: &mut Writer, dir: &mut Dir, mut updates: Vec<(Vec, Status)>, ) -> Result<()> { for i in (0..dir.pages.len()).rev() { if updates.is_empty() { break; } let mut page: Vec = blocks::get_value(conn, key, &dir.pages[i])?; let mut changed = false; updates.retain(|(mid, st)| match page.iter_mut().find(|e| e.id == *mid) { Some(e) => { if *st > e.status { e.status = *st; changed = true; } false } None => true, }); if changed { dir.pages[i] = w.put_value(&page, Some(&dir.pages[i]))?; } } Ok(()) }