Cotton code
215 lines · 8.9 KB · RustRaw
//! Judge time — the relay's word on what time it is, carried forward by the//! continuous clock (slice 1, groundwork 5.2).//!//! At each relay greeting the shell takes a READING: the relay's time `R`, the//! continuous clock `c` when it arrived, and the boot session `c` counts in.//! Judge time is then `R + (continuous now − c)` — never the wall clock, which//! an NTP step or a person in Settings moves, and only inside the boot the//! reading was taken in, because the continuous clock starts again at boot.//!//! Pure, like the rest of this crate: the shell reads the clocks (cotton-client//! `judge`) and hands them in. Which readings are taken is decided//! here, so the rules are tested without a relay or a clock./// A reading this far from the running judge time is not taken on its own/// word: one odd answer must not move every stamp the file makes.pub const FAR_FROM_JUDGE_MS: i64 = 2 * 60_000;/// Two consecutive far readings agree when the relay moved by what the/// continuous clock moved, to within this: `|(R2 − R1) − (c2 − c1)|`.pub const AGREE_WITHIN_MS: i64 = 2_000;/// The first reading of a process this far from the wall clock is taken only/// when a live device's signed `ts` confirms it.pub const FAR_FROM_WALL_MS: i64 = 60 * 60_000;/// How close a device's signed `ts` must be to the unconfirmed reading.pub const CONFIRM_WITHIN_MS: i64 = 2 * 60_000;/// A reading this old is measured again: the line re-dials at a moment with/// no open stream.pub const READING_LIFE_MS: i64 = 24 * 60 * 60_000;/// The wall clock within this of judge time is Checked; further is Corrected.pub const CHECKED_WITHIN_MS: i64 = 2 * 60_000;/// One relay reading. In memory only — it never reaches the file.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Reading {    /// The relay's time, ms since the epoch (`HELLO.server_time`).    pub relay_ms: i64,    /// The continuous clock when the reading arrived, ms.    pub cont_ms: i64,    /// The boot session `cont_ms` counts in.    pub boot: String,}impl Reading {    /// Judge time at continuous time `cont_ms` in boot `boot`. `None` in any    /// other boot: the continuous clock started again, so the reading says    /// nothing about now.    pub fn judge_at(&self, cont_ms: i64, boot: &str) -> Option<i64> {        (self.boot == boot).then(|| self.relay_ms + (cont_ms - self.cont_ms))    }    /// The reading is 24 hours old at `cont_ms` and should be measured again.    pub fn is_stale(&self, cont_ms: i64) -> bool {        cont_ms - self.cont_ms >= READING_LIFE_MS    }}/// Two readings agree: same boot, and the relay moved between them by what/// the continuous clock moved, within [`AGREE_WITHIN_MS`].pub fn readings_agree(first: &Reading, second: &Reading) -> bool {    first.boot == second.boot        && ((second.relay_ms - first.relay_ms) - (second.cont_ms - first.cont_ms)).abs()            <= AGREE_WITHIN_MS}/// What became of a reading offered to [`Judge::offer`].#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Offered {    /// It is judge time now.    Taken,    /// More than 2 minutes from the running judge time: kept aside until the    /// next reading agrees with it.    Waiting,    /// The first reading, more than an hour from the wall clock: taken only    /// when a live device's signed `ts` agrees ([`Judge::confirm`]). Until    /// then the Mac is Unchecked and shows both clocks.    NeedsConfirmation,}/// The running judge time of one process.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Judge {    taken: Option<Reading>,    waiting: Option<Reading>,    unconfirmed: Option<Reading>,}impl Judge {    pub fn new() -> Judge {        Judge::default()    }    /// Offer a reading taken at a greeting; `wall_ms` is this device's wall    /// clock at the same moment, read only for the 1-hour rule.    pub fn offer(&mut self, reading: Reading, wall_ms: i64) -> Offered {        let running = self            .taken            .as_ref()            .and_then(|taken| taken.judge_at(reading.cont_ms, &reading.boot));        let Some(running) = running else {            // No judge time in this boot yet: this is the first reading.            self.taken = None;            self.waiting = None;            if (reading.relay_ms - wall_ms).abs() <= FAR_FROM_WALL_MS {                self.unconfirmed = None;                self.taken = Some(reading);                return Offered::Taken;            }            self.unconfirmed = Some(reading);            return Offered::NeedsConfirmation;        };        if (reading.relay_ms - running).abs() <= FAR_FROM_JUDGE_MS            || self                .waiting                .as_ref()                .is_some_and(|waiting| readings_agree(waiting, &reading))        {            self.waiting = None;            self.taken = Some(reading);            return Offered::Taken;        }        // Consecutive means consecutive: an in-between near reading cleared        // `waiting` above, so only the reading just before can agree.        self.waiting = Some(reading);        Offered::Waiting    }    /// A live device's signed `ts` (ms) arrived at continuous time `cont_ms`    /// in boot `boot`. Takes the unconfirmed first reading when they agree    /// within [`CONFIRM_WITHIN_MS`]; says whether it did.    pub fn confirm(&mut self, device_ts_ms: i64, cont_ms: i64, boot: &str) -> bool {        let agrees = self            .unconfirmed            .as_ref()            .and_then(|reading| reading.judge_at(cont_ms, boot))            .is_some_and(|judge| (device_ts_ms - judge).abs() <= CONFIRM_WITHIN_MS);        if agrees {            self.taken = self.unconfirmed.take();        }        agrees    }    /// Judge time now, or `None` when there is none in this boot.    pub fn now(&self, cont_ms: i64, boot: &str) -> Option<i64> {        self.taken.as_ref()?.judge_at(cont_ms, boot)    }    /// The reading judge time runs from.    pub fn reading(&self) -> Option<&Reading> {        self.taken.as_ref()    }    /// The first reading waiting for a device to confirm it — what the line    /// naming both clocks shows.    pub fn unconfirmed(&self) -> Option<&Reading> {        self.unconfirmed.as_ref()    }    /// The taken reading is 24 hours old: re-dial when no stream is open.    pub fn needs_redial(&self, cont_ms: i64) -> bool {        self.taken            .as_ref()            .is_some_and(|reading| reading.is_stale(cont_ms))    }}/// JUDGE TIME AS A SHELL HOLDS IT — the process's one running [`Judge`] and/// the clocks it is read against. This crate reads no clock, so it names what/// it needs and the shell answers: `cotton_client::judge::JudgeClock`, fed by/// the relay's greeting, is the one implementation, and the serving Mac hands/// it to its file store ([`crate::driver::Driver::judged_by`]), its exchange/// and snapshot routes and its auth chokepoint; a replica's process hands the/// same clock to the replica it holds/// ([`crate::driver::Driver::replica_judged_by`]), fed by its server's answers.pub trait JudgeSource: Send + Sync {    /// Judge time now, ms; `None` when there is none in this boot (Unchecked).    fn now(&self) -> Option<i64>;    /// The four readings a mint takes at wall clock `wall_ms`. An unreadable    /// continuous clock or boot session is an error, never a guess.    fn mint_clock(&self, wall_ms: i64) -> Result<crate::mint::Clock, String>;    /// A live device's signed `ts` (ms): confirms an unconfirmed first    /// reading when they agree ([`Judge::confirm`]); says whether it did.    fn confirm(&self, device_ts_ms: i64) -> Result<bool, String>;    /// A judge's time as an answer carries it (ISO-8601, the form of the    /// relay's `HELLO.server_time`), offered as a reading under the same rules    /// ([`Judge::offer`]); `wall_ms` is this device's wall clock, read for the    /// 1-hour rule only. A replica offers every exchange answer's, snapshot's    /// and `future` refusal's.    fn offer(&self, server_time: &str, wall_ms: i64) -> Result<Offered, String>;}/// How a mint's wall clock stands against judge time.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ClockState {    /// Within 2 minutes: stamp by the wall clock.    Checked,    /// More than 2 minutes off: stamp by judge time and say by how much    /// (`wall − judge`, positive when this clock is ahead).    Corrected { off_by_ms: i64 },    /// No judge time yet: stamp by the wall clock and hold the receipt.    Unchecked,}/// The state of a mint given judge time (if any) and the wall clock.pub fn clock_state(judge_ms: Option<i64>, wall_ms: i64) -> ClockState {    match judge_ms {        None => ClockState::Unchecked,        Some(judge) if (wall_ms - judge).abs() <= CHECKED_WITHIN_MS => ClockState::Checked,        Some(judge) => ClockState::Corrected {            off_by_ms: wall_ms - judge,        },    }}#[cfg(test)]#[path = "judge_tests.rs"]mod tests;