Cotton code
999 lines · 35.8 KB · RustRaw
//! THE ONE HAND-OVER OF A SERVING ROLE: the owner moves a database from the//! device that serves it (the SOURCE) to an approved Mac of the household//! (the TARGET). A phone that founded a database hands it to the Mac that//! joins it, and a Mac hands its household to another Mac of it, by these//! same steps and no others://!//! 1. the target PREPARES a signed [`Offer`] naming the source, the epoch it//!    serves at, the host the target will serve at, and a first author the//!    target signed: on a private copy of the database it keeps//!    ([`prepare`]), or — a Mac that joined as a device and keeps no copy —//!    from its own device key and the source's [`Seed`] alone//!    ([`prepare_from_seed`]). Everything the offer reads of the file the//!    source supplies; the target's bytes are never part of it;//! 2. the source's owner act signs the common `serving_grant::ServingGrant`//!    with the file's owner key, and the source RELINQUISHES ([`relinquish`])://!    the grant, the next epoch's serving fact naming the target, and the//!    source's own new client author commit in one transaction. From that//!    commit there is one authority (the target), even while its file is on//!    the way; the source keeps its file and queues any later edit;//! 3. the source makes the WHOLE copy ([`copy_whole`]), unstripped, through an//!    independent reader, and signs a [`WholeCopy`] proof of it;//! 4. the target CLAIMS it ([`claim_whole`]): every byte checked against the//!    proof, the grant verified against the owner's retained record, and the//!    file activated under the target's prepared author;//! 5. the target signs [`Ready`] for that exact copy and origin, and the//!    source CONFIRMS it ([`Ready::confirm`]) before it lets go of its own//!    standing (a phone follows the Mac; a Mac stands down).use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use rusqlite::types::Value as SqlValue;use serde::{Deserialize, Serialize};use serde_json::json;use sha2::{Digest, Sha256};use std::io::Read;use std::path::Path;use std::sync::Arc;use crate::actor::Actor;use crate::mint::{Act, AuthorReason, Change, Clock, Held, History};use crate::outbox::IdSource;use crate::protocol::types::CottonOp;use crate::serving_grant::ServingGrant;use crate::{Driver, StoreError};#[derive(Debug, thiserror::Error)]#[error("{message}")]pub struct Refused {    code: &'static str,    message: String,}impl Refused {    pub fn code(&self) -> &'static str {        self.code    }}impl From<StoreError> for Refused {    fn from(error: StoreError) -> Self {        refusal("handover_failed", error.to_string())    }}fn refusal(code: &'static str, message: impl Into<String>) -> Refused {    Refused {        code,        message: message.into(),    }}type Result<T> = std::result::Result<T, Refused>;fn text(value: &str) -> SqlValue {    SqlValue::Text(value.into())}fn atomic<T>(db: &Driver, run: impl FnOnce() -> Result<T>) -> Result<T> {    let mut refused = None;    let result = db.transaction(|_| {        run().map_err(|error| {            let store = StoreError::refused(error.to_string());            refused = Some(error);            store        })    });    result.map_err(|error| refused.unwrap_or_else(|| error.into()))}/// The target's signed intent, bound to this database, source and epoch./// The author fact is signed by the target; the source never signs for it./// This is preparation only. It grants no serving authority: relinquish and/// activation require the same owner-signed `serving_grant::ServingGrant`/// used for every server move, retained in the file before the whole copy.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct Offer {    pub database: String,    pub source: String,    pub target: String,    pub target_host: String,    pub epoch: i64,    pub author: CottonOp,    pub signature: String,}impl Offer {    fn intent(&self) -> Vec<u8> {        serde_json::to_vec(&json!([            "cotton-serving-handover-v1",            self.database,            self.source,            self.target,            self.target_host,            self.epoch,            self.author.receipt        ]))        .expect("JSON values serialize")    }    /// Whether the offer is the target's own, whole and current in form:    /// asked before anything is written for it.    pub fn verify(&self) -> Result<()> {        let bad = || {            refusal(                "invalid_handover_offer",                "The target's hand-over offer does not verify.",            )        };        if self.epoch < 1 || self.epoch == i64::MAX {            return Err(bad());        }        // Verify the carried bytes verbatim: mint is the only author of a        // receipt's bytes, even when this envelope is only being checked.        let mut reconstructed = crate::wire::from_bytes(            self.author.op_id.clone(),            self.author.receipt.as_bytes(),        )        .map_err(|_| bad())?;        reconstructed.sig = self.author.sig.clone();        if reconstructed != self.author            || crate::signed::introduced_device(&self.author).as_deref() != Some(&self.target)            || self                .author                .patch                .as_ref()                .and_then(|p| p.get("workspace_id"))                .and_then(serde_json::Value::as_str)                != Some(&self.database)        {            return Err(bad());        }        crate::signed::verify_op(&self.author, &self.database, |_| None).map_err(|_| bad())?;        let signature = URL_SAFE_NO_PAD.decode(&self.signature).map_err(|_| bad())?;        crate::signed::verify(            &self.target,            &self.database,            &self.intent(),            Some(&signature),        )        .map_err(|_| bad())    }}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Granted {    pub epoch: i64,    pub target: String,    pub author: String,}/// Ensure a locally founded database records its first server. No schema rise:/// this is the same serving fact every Mac-founded database already records.pub fn found(db: &Driver, database: &str, clock: &Clock, ids: &mut dyn IdSource) -> Result<()> {    atomic(db, || {        if crate::serving::serving_fact(db, database)?.is_some() {            return Ok(());        }        let meta = crate::meta::read_meta(db)?            .ok_or_else(|| refusal("wrong_database", "The file has no identity."))?;        if meta.workspace_id != database {            return Err(refusal("wrong_database", "The file is another database."));        }        let device = db            .signer()            .map(|key| key.device_key())            .unwrap_or(meta.device_id);        let author = crate::mint::file_author(db)?;        let at = crate::protocol::js::to_iso_string(crate::mint::clock::stamping(clock).ms)            .ok_or_else(|| refusal("handover_clock_unavailable", "The clock is unreadable."))?;        write_fact(            db,            database,            1,            json!({"epoch":1,"device_credential_id":device,            "author_id":author,"since":at,"relay_key":null,"backup_access_key_id":null,            "confirmed_by":null,"start_positions":null}),            clock,            ids,        )?;        Ok(())    })}/// WHAT A TARGET THAT KEEPS NO COPY NEEDS OF THE SOURCE'S FILE to prepare/// its offer: the database's identity, the serving fact it offers to follow,/// the file's clock (the target's first stamp starts above it, as one minted/// on a copy would) and its schema. The source answers it; nothing in it is/// a secret and nothing in it grants anything — [`relinquish`] checks the/// offer against the source's own file again.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct Seed {    pub database: String,    pub owner: String,    pub source: String,    pub epoch: i64,    pub last_hlc: Option<String>,    pub schema_version: u32,}/// The source's [`Seed`] of `database`, read from its own file.pub fn seed(db: &Driver, database: &str) -> Result<Seed> {    let meta = crate::meta::read_meta(db)?        .ok_or_else(|| refusal("wrong_database", "The file has no identity."))?;    if meta.workspace_id != database {        return Err(refusal("wrong_database", "The file is another database."));    }    let fact = crate::serving::serving_fact(db, database)?.ok_or_else(|| {        refusal("no_serving_fact", "The source has not recorded its serving role.")    })?;    Ok(Seed {        database: database.into(),        owner: meta.owner_id,        source: fact.device_credential_id,        epoch: fact.epoch,        last_hlc: meta.last_hlc,        schema_version: crate::migrate::current_version(db)?,    })}/// The target prepares its offer FROM ITS DEVICE KEY AND THE SOURCE'S SEED,/// keeping no copy of the database: its first author is coined on a fresh,/// empty file of this build's schema at `scratch` (made here, removed here),/// whose identity and clock are the seed's. The fact is the one [`prepare`]/// mints — the author, the database, a first stamp above the file's clock —/// so [`relinquish`] folds it on the source exactly as it folds one prepared/// on a copy. Reuse the returned offer on retry.pub fn prepare_from_seed(    scratch: &Path,    seed: &Seed,    target_host: &str,    signer: Arc<dyn crate::signed::ReceiptSigner>,    clock: &Clock,    ids: &mut dyn IdSource,) -> Result<Offer> {    if seed.epoch < 1 || seed.epoch == i64::MAX {        return Err(refusal("invalid_handover_seed", "The source's seed names no serving epoch."));    }    if seed.source == signer.device_key() {        return Err(refusal("already_serving", "This device already serves the database."));    }    if seed.schema_version != crate::schema::ddl::SCHEMA_VERSION {        return Err(refusal(            "schema_differs",            "Update both devices before handing over the database.",        ));    }    let remove = || {        for suffix in ["", "-wal", "-shm", "-journal"] {            let mut path = scratch.as_os_str().to_owned();            path.push(suffix);            // not a copy: the hand-over's scratch file.            let _ = std::fs::remove_file(std::path::PathBuf::from(path));        }    };    remove();    let made = (|| -> Result<Offer> {        let db = Driver::open(scratch)?.signed_by(Arc::clone(&signer));        crate::create::create_workspace(            &db,            &crate::meta::Meta {                workspace_id: seed.database.clone(),                owner_id: seed.owner.clone(),                device_id: signer.device_key(),                last_server_seq: 0,                last_hlc: seed.last_hlc.clone(),            },        )?;        let author = crate::mint::coin_author(            &db,            &signer.device_key(),            None,            AuthorReason::First,            clock,            ids,            None,        )?;        signed_offer(&db, &seed.database, &seed.source, seed.epoch, target_host, author.fact)    })();    remove();    made}fn signed_offer(    db: &Driver,    database: &str,    source: &str,    epoch: i64,    target_host: &str,    author: CottonOp,) -> Result<Offer> {    let signer = db        .signer()        .ok_or_else(|| refusal("handover_key_required", "The target needs its device key."))?;    let mut offer = Offer {        database: database.into(),        source: source.into(),        target: signer.device_key(),        target_host: target_host.into(),        epoch,        author,        signature: String::new(),    };    offer.signature = URL_SAFE_NO_PAD.encode(        signer            .sign(&crate::signed::signed_string(database, &offer.intent()))            .map_err(|why| refusal("handover_signing_failed", why))?,    );    Ok(offer)}/// The target prepares an author on a preliminary copy. It cannot serve that/// copy: the latest fact still names the source. Reuse the returned offer on retry.pub fn prepare(    db: &Driver,    database: &str,    target_host: &str,    clock: &Clock,    ids: &mut dyn IdSource,) -> Result<Offer> {    atomic(db, || {        let signer = db.signer().ok_or_else(|| {            refusal(                "handover_key_required",                "The target needs its device key.",            )        })?;        let fact = crate::serving::serving_fact(db, database)?.ok_or_else(|| {            refusal(                "no_serving_fact",                "The source has not recorded its serving role.",            )        })?;        if fact.device_credential_id == signer.device_key() {            return Err(refusal(                "already_serving",                "This device already serves the database.",            ));        }        if db            .get(                "SELECT 1 FROM _outbox WHERE tbl <> 'cotton_authors' LIMIT 1",                &[],            )?            .is_some()        {            return Err(refusal(                "handover_target_has_writes",                "Sync this Mac's pending edits before preparing a hand-over.",            ));        }        db.run(            "UPDATE _meta SET author_id = NULL, device_id = ?",            &[text(&signer.device_key())],        )?;        let author = crate::mint::first_author(            db,            &signer.device_key(),            None,            AuthorReason::First,            clock,            ids,            Held::Replica,        )?;        signed_offer(db, database, &fact.device_credential_id, fact.epoch, target_host, author.fact)    })}fn write_fact(    db: &Driver,    database: &str,    epoch: i64,    fields: serde_json::Value,    clock: &Clock,    ids: &mut dyn IdSource,) -> Result<()> {    let id = crate::protocol::derived_id::derived_id(        "cotton_serving_machine",        &[database, &epoch.to_string()],    );    let mut fields = fields.as_object().unwrap().clone();    fields.insert("workspace_id".into(), database.into());    let minted = crate::mint::mint(        db,        &Act {            actor: Actor::takeover(),            verb: "handover_serving_role".into(),            history: History::None,            changes: vec![Change::create("cotton_serving_machine", &id, fields)],        },        clock,        ids,        Held::Served,    )?;    if minted.held {        return Err(refusal(            "handover_clock_unavailable",            "A serving role cannot be transferred under an unchecked clock.",        ));    }    Ok(())}/// Commit the grant on the CURRENT server. The source never deletes its file./// The new fact and replica author are one SQLite write transaction, so a/// competing writer sees either the old server or the new queued client.pub fn relinquish(    db: &Driver,    offer: &Offer,    grant: &ServingGrant,    clock: &Clock,    ids: &mut dyn IdSource,) -> Result<Granted> {    offer.verify()?;    atomic(db, || {        let signer = db            .signer()            .ok_or_else(|| refusal("handover_key_required", "The source needs its device key."))?;        if signer.device_key() != offer.source {            return Err(refusal(                "not_serving_here",                "Only the device that serves can grant the next epoch.",            ));        }        let fact = crate::serving::serving_fact(db, &offer.database)?            .ok_or_else(|| refusal("no_serving_fact", "The file names no server."))?;        let done = Granted {            epoch: offer.epoch + 1,            target: offer.target.clone(),            author: offer.author.row_id.clone(),        };        grant            .verify_target(db, &offer.target_host, &offer.target)            .map_err(grant_error)?;        if grant.database_id != offer.database || grant.source_epoch != offer.epoch {            return Err(refusal(                "serving_grant_invalid",                "The owner's grant does not match this join.",            ));        }        if matches_grant(db, offer)? {            if crate::serving_grant::retained(db, &offer.database)                .map_err(grant_error)?                .as_ref()                != Some(grant)            {                return Err(refusal(                    "serving_grant_epoch_conflict",                    "Another grant already chose this epoch.",                ));            }            return Ok(done);        }        if fact.epoch != offer.epoch || fact.device_credential_id != offer.source {            return Err(refusal(                "handover_epoch_changed",                "The serving role has changed; prepare a new offer.",            ));        }        require_mac(db, &offer.target)?;        let stamping = crate::mint::clock::stamping(clock);        if stamping.held {            return Err(refusal(                "handover_clock_unavailable",                "The hand-over needs a checked clock.",            ));        }        if db.get("SELECT 1 FROM _writes WHERE held = 1 UNION ALL SELECT 1 FROM _tombstones WHERE held = 1 LIMIT 1", &[])?.is_some() {            if clock.judge_ms().is_some() && clock.boot.is_some() {                crate::mint::clock::release_held(db, clock, ids, Held::Served)?;            } else {                return Err(refusal("handover_writes_held", "The source has applied edits waiting for checked time. Release them before handing over the file."));            }        }        let folded = crate::fold::fold_ops(db, std::slice::from_ref(&offer.author))?;        if !folded.rejected.is_empty() {            return Err(refusal(                "invalid_handover_offer",                "The target's author did not apply.",            ));        }        let relay_key = crate::serving_grant::relay_key_of_device(db, &offer.target)            .map_err(grant_error)?            .ok_or_else(|| grant_error(crate::serving_grant::Refused::TargetRelayKeyMissing))?;        crate::serving_grant::commit(            db,            grant,            &grant.source_host,            &offer.target,            &relay_key,            Some(&offer.author.row_id),            clock,            ids,        )        .map_err(grant_error)?;        db.run("UPDATE _meta SET author_id = NULL, device_id = ?, heard_serving_epoch = ?, handed_over_epoch = ?",            &[text(&offer.source),SqlValue::Integer(done.epoch),SqlValue::Integer(offer.epoch)])?;        // The source's file has seen every write in it: as a client it asks        // the target only for what is newer (the stand-down's same step).        let now = crate::protocol::js::to_iso_string(stamping.ms)            .ok_or_else(|| refusal("handover_clock_unavailable", "The clock is unreadable."))?;        db.run("DELETE FROM _cursors", &[])?;        for (author, hlc_seen) in crate::cursors::cursor_ceiling(db)? {            db.run(                "INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES (?, ?, ?)",                &[text(&author), text(&hlc_seen), text(&now)],            )?;        }        crate::mint::first_author(            db,            &offer.source,            None,            AuthorReason::First,            clock,            ids,            Held::Replica,        )?;        Ok(done)    })}fn require_mac(db: &Driver, target: &str) -> Result<()> {    let database = crate::meta::read_meta(db)?        .ok_or_else(|| refusal("wrong_database", "The file has no identity."))?        .workspace_id;    if crate::revocation::device_standing(db, target)? != crate::revocation::Standing::Live        || db            .get(                "SELECT 1 FROM cotton_devices WHERE device_id = ? AND platform = 'mac'",                &[text(target)],            )?            .is_none()        || !crate::storage_rules::keeps_everything(db, &database, target)?        || crate::device_scope::require_write(db, target).is_err()    {        return Err(refusal(            "handover_target_not_approved",            "The target Mac must be approved in this database.",        ));    }    Ok(())}fn grant_error(error: crate::serving_grant::Refused) -> Refused {    refusal(error.code(), error.to_string())}fn matches_grant(db: &Driver, offer: &Offer) -> Result<bool> {    let Some(fact) = crate::serving::serving_fact(db, &offer.database)? else {        return Ok(false);    };    let Some(grant) = crate::serving_grant::retained(db, &offer.database).map_err(grant_error)?    else {        return Ok(false);    };    grant        .verify_target(db, &offer.target_host, &offer.target)        .map_err(grant_error)?;    let source = db.get("SELECT device_credential_id FROM cotton_serving_machine WHERE workspace_id = ? AND epoch = ? ORDER BY id DESC LIMIT 1",        &[text(&offer.database), SqlValue::Integer(offer.epoch)])?;    Ok(fact.epoch == offer.epoch + 1        && fact.device_credential_id == offer.target        && fact.author_id == offer.author.row_id        && grant.source_epoch == offer.epoch        && grant.database_id == offer.database        && source            .as_ref()            .and_then(|row| row.text("device_credential_id"))            == Some(offer.source.as_str()))}/// An authenticated, resumable whole-file transfer. Its digest identifies/// the immutable SQLite copy, not a changing live file or a byte attachment.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct WholeCopy {    pub offer: Offer,    pub grant: ServingGrant,    pub sha256: String,    pub bytes: u64,    pub signature: String,}impl WholeCopy {    fn intent(&self) -> Vec<u8> {        serde_json::to_vec(&json!([            "cotton-serving-whole-v1",            self.offer.database,            self.offer.source,            self.offer.target,            self.offer.epoch,            self.offer.signature,            self.grant.signing_bytes(),            self.grant.owner_signature,            self.sha256,            self.bytes        ]))        .expect("JSON values serialize")    }    pub fn verify(&self) -> Result<()> {        self.offer.verify()?;        if self.grant.database_id != self.offer.database            || self.grant.source_epoch != self.offer.epoch            || self.grant.target_host != self.offer.target_host            || crate::serving_grant::fingerprint(&self.offer.target).map_err(grant_error)?                != self.grant.target_key_fingerprint        {            return Err(refusal(                "invalid_handover_copy",                "The owner grant does not match the transfer intent.",            ));        }        let bad = || {            refusal(                "invalid_handover_copy",                "The source's whole-file proof does not verify.",            )        };        let signature = URL_SAFE_NO_PAD.decode(&self.signature).map_err(|_| bad())?;        crate::signed::verify(            &self.offer.source,            &self.offer.database,            &self.intent(),            Some(&signature),        )        .map_err(|_| bad())    }}/// The chosen Mac's current acknowledgement, bound to the exact whole copy/// and its serving origin. The source lets go of its standing only on this proof.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct Ready {    pub origin: String,    pub signature: String,}impl Ready {    fn intent(&self, copy: &WholeCopy) -> Vec<u8> {        serde_json::to_vec(&json!([            "cotton-serving-ready-v1",            copy.offer.database,            copy.offer.target,            copy.offer.epoch + 1,            copy.sha256,            copy.bytes,            self.origin        ]))        .expect("JSON values serialize")    }    pub fn after_activation(db: &Driver, copy: &WholeCopy, origin: &str) -> Result<Self> {        resume_installed(db, copy)?;        if origin != copy.grant.target_host {            return Err(refusal(                "serving_grant_wrong_target_host",                "The ready origin must be the host the owner signed.",            ));        }        let signer = db.signer().ok_or_else(|| {            refusal(                "handover_key_required",                "The serving Mac needs its device key.",            )        })?;        if signer.device_key() != copy.offer.target            || !matches_grant(db, &copy.offer)?            || !crate::serving::is_serving_author(db, &crate::mint::file_author(db)?)?        {            return Err(refusal(                "handover_not_active",                "The chosen Mac has not activated this whole copy.",            ));        }        let mut ready = Self {            origin: origin.into(),            signature: String::new(),        };        ready.signature = URL_SAFE_NO_PAD.encode(            signer                .sign(&crate::signed::signed_string(                    &copy.offer.database,                    &ready.intent(copy),                ))                .map_err(|why| refusal("handover_signing_failed", why))?,        );        Ok(ready)    }    pub fn confirm(&self, db: &Driver, copy: &WholeCopy) -> Result<()> {        copy.verify()?;        let bad = || {            refusal(                "invalid_handover_ready",                "The chosen Mac's acknowledgement does not verify for this file and origin.",            )        };        let signature = URL_SAFE_NO_PAD.decode(&self.signature).map_err(|_| bad())?;        crate::signed::verify(            &copy.offer.target,            &copy.offer.database,            &self.intent(copy),            Some(&signature),        )        .map_err(|_| bad())?;        if self.origin != copy.grant.target_host {            return Err(refusal(                "serving_grant_wrong_target_host",                "The acknowledgement names a host the owner did not grant.",            ));        }        crate::serving_grant::verify_retained(db, &copy.grant, &self.origin, &copy.offer.target)            .map_err(grant_error)?;        if !matches_grant(db, &copy.offer)? {            return Err(refusal(                "handover_epoch_changed",                "The serving role has changed since this copy was sent.",            ));        }        Ok(())    }}fn digest(path: &Path) -> Result<(String, u64)> {    let mut file = std::fs::File::open(path)        .map_err(|error| refusal("handover_file_unreadable", error.to_string()))?;    let mut hash = Sha256::new();    let mut bytes = 0;    let mut buffer = [0u8; 256 * 1024];    loop {        let read = file            .read(&mut buffer)            .map_err(|error| refusal("handover_file_unreadable", error.to_string()))?;        if read == 0 {            break;        }        hash.update(&buffer[..read]);        bytes += read as u64;    }    Ok((hex::encode(hash.finalize()), bytes))}/// After relinquish, make a consistent, unfiltered SQLite copy using an/// independent WAL reader. The source's writes continue while VACUUM reads. Retry/// transfers this same immutable file by offset; never recopy over it.pub fn copy_whole(    source: &Path,    destination: &Path,    offer: &Offer,    signer: Arc<dyn crate::signed::ReceiptSigner>,) -> Result<WholeCopy> {    offer.verify()?;    if signer.device_key() != offer.source {        return Err(refusal(            "handover_wrong_source",            "Only the device that granted the role can send its whole file.",        ));    }    if destination.exists() {        let same = std::fs::canonicalize(source).ok() == std::fs::canonicalize(destination).ok();        #[cfg(unix)]        let same = {            use std::os::unix::fs::MetadataExt;            let left = std::fs::metadata(source)                .map_err(|error| refusal("handover_file_unreadable", error.to_string()))?;            let right = std::fs::metadata(destination)                .map_err(|error| refusal("handover_file_unreadable", error.to_string()))?;            same || (left.dev() == right.dev() && left.ino() == right.ino())        };        if same {            return Err(refusal(                "handover_copy_is_live_file",                "The transfer copy must be separate from the source's live database.",            ));        }    }    let reader = Driver::open_reader(source)?;    if !matches_grant(&reader, offer)? {        return Err(refusal(            "handover_not_granted",            "Commit the serving-role grant before copying the file.",        ));    }    if destination.exists() {        // A frozen VACUUM output may use a rollback journal. It has no        // writer, so read it without the live-reader WAL requirement and        // without changing its bytes (the digest must stay resumable).        let kept = Driver::from_connection(            rusqlite::Connection::open_with_flags(                destination,                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY                    | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,            )            .map_err(StoreError::from)?,            false,        )?;        if kept            .get("PRAGMA quick_check", &[])?            .and_then(|row| row.text("quick_check").map(str::to_string))            .as_deref()            != Some("ok")        {            return Err(refusal("handover_copy_incomplete", "The kept copy is incomplete; it has been kept and a new copy needs a separate path."));        }        if !matches_grant(&kept, offer)? {            return Err(refusal(                "handover_copy_in_the_way",                "The existing copy belongs to another hand-over; it has been kept.",            ));        }    } else {        crate::snapshot::copy_file(source, destination)?;    }    let (sha256, bytes) = digest(destination)?;    let grant = crate::serving_grant::retained(&reader, &offer.database)        .map_err(grant_error)?        .ok_or_else(|| {            refusal(                "serving_grant_not_retained",                "The file contains no owner's grant.",            )        })?;    let mut copy = WholeCopy {        offer: offer.clone(),        grant,        sha256,        bytes,        signature: String::new(),    };    copy.signature = URL_SAFE_NO_PAD.encode(        signer            .sign(&crate::signed::signed_string(                &offer.database,                &copy.intent(),            ))            .map_err(|why| refusal("handover_signing_failed", why))?,    );    Ok(copy)}/// Check every byte before opening or claiming an arrived copy. The source/// file is kept on the source and a refused staged copy is kept for diagnosis./// The caller supplies a new, private staging path, never an existing replica.pub fn claim_whole(    path: &Path,    copy: &WholeCopy,    signer: Arc<dyn crate::signed::ReceiptSigner>,) -> Result<Granted> {    copy.verify()?;    if signer.device_key() != copy.offer.target {        return Err(refusal(            "handover_wrong_target",            "This hand-over belongs to another Mac.",        ));    }    let (sha256, bytes) = digest(path)?;    if sha256 != copy.sha256 || bytes != copy.bytes {        return Err(refusal(            "handover_copy_incomplete",            "The whole file has not arrived intact; resume the same copy.",        ));    }    let db = Driver::open(path)?.signed_by(signer);    copy.grant        .verify_target(&db, &copy.grant.target_host, &copy.offer.target)        .map_err(grant_error)?;    if crate::serving_grant::retained(&db, &copy.offer.database)        .map_err(grant_error)?        .as_ref()        != Some(&copy.grant)    {        return Err(refusal(            "serving_grant_not_retained",            "The copy's grant differs from the owner's retained record.",        ));    }    activate(&db, &copy.offer)}/// Activate only the final WHOLE file carrying the source's grant. The shell/// installs it at the served address afterwards. No epoch is minted here.struct NoActivationIds;impl IdSource for NoActivationIds {    fn next_op_id(&mut self, _: i64) -> crate::Result<String> {        Err(StoreError::refused(            "a target must retain its prepared author",        ))    }}pub(crate) fn activate(db: &Driver, offer: &Offer) -> Result<Granted> {    offer.verify()?;    atomic(db, || {        if db.signer().map(|signer| signer.device_key()).as_deref() != Some(&offer.target) {            return Err(refusal(                "handover_wrong_target",                "This hand-over belongs to another Mac.",            ));        }        if crate::migrate::current_version(db)? != crate::schema::ddl::SCHEMA_VERSION {            return Err(refusal(                "schema_differs",                "Update both devices before handing over the database.",            ));        }        if !matches_grant(db, offer)? {            return Err(refusal(                "handover_not_granted",                "The whole file does not carry the source's grant.",            ));        }        require_mac(db, &offer.target)?;        let meta = crate::meta::read_meta(db)?            .ok_or_else(|| refusal("wrong_database", "The file has no identity."))?;        if meta.workspace_id != offer.database {            return Err(refusal("wrong_database", "The file is another database."));        }        if meta.device_id == offer.target && crate::mint::file_author(db)? == offer.author.row_id {            return Ok(Granted {                epoch: offer.epoch + 1,                target: offer.target.clone(),                author: offer.author.row_id.clone(),            });        }        if crate::signed::verify_op(&offer.author, &offer.database, |_| None).is_err() {            return Err(refusal(                "invalid_handover_offer",                "The target's author does not verify.",            ));        }        let grant = crate::serving_grant::retained(db, &offer.database)            .map_err(grant_error)?            .ok_or_else(|| {                refusal(                    "serving_grant_not_retained",                    "The file contains no owner's grant.",                )            })?;        let mut ids = NoActivationIds;        let since = crate::serving::serving_fact(db, &offer.database)?            .and_then(|fact| crate::protocol::js::parse_date_ms(&fact.since))            .ok_or_else(|| refusal("serving_grant_invalid", "The grant has no serving instant."))?;        crate::serving_grant::activate(            db,            &grant,            &offer.target_host,            &Clock::wall(since),            &mut ids,        )        .map_err(grant_error)?;        Ok(Granted {            epoch: offer.epoch + 1,            target: offer.target.clone(),            author: offer.author.row_id.clone(),        })    })}/// A retry after the verified file moved to its served address. This only/// reads an already activated database; it cannot claim a new arrival.pub fn resume_installed(db: &Driver, copy: &WholeCopy) -> Result<Granted> {    copy.verify()?;    crate::serving_grant::verify_retained(        db,        &copy.grant,        &copy.offer.target_host,        &copy.offer.target,    )    .map_err(grant_error)?;    let own = db.get("SELECT device_id, handed_over_epoch FROM _meta", &[])?;    if db.signer().map(|signer| signer.device_key()).as_deref() != Some(&copy.offer.target)        || own.as_ref().and_then(|row| row.text("device_id")) != Some(copy.offer.target.as_str())        || own.as_ref().and_then(|row| row.int("handed_over_epoch")) != Some(copy.offer.epoch + 1)        || !matches_grant(db, &copy.offer)?        || !crate::serving::is_serving_author(db, &crate::mint::file_author(db)?)?    {        return Err(refusal(            "handover_not_active",            "This database has not been activated from the verified whole copy.",        ));    }    Ok(Granted {        epoch: copy.offer.epoch + 1,        target: copy.offer.target.clone(),        author: copy.offer.author.row_id.clone(),    })}#[cfg(test)]#[path = "serving_handover_tests.rs"]mod tests;