Skip to main content

vector_core/
clock.rs

1//! The time Vector stamps and judges by: this device's clock, corrected when the account's
2//! relays agree it is off. Every HTTPS answer carries a `Date` (RFC 9110 ยง6.6.1), so any relay
3//! can tell the time, whether or not it serves NIP-11; their median moves the clock, so one wrong
4//! relay can't, and nothing of Vector's own is asked.
5
6use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, Ordering};
7
8use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
9
10/// The account setting: `"false"` keeps the device's clock, anything else follows the relays.
11pub const SETTING_KEY: &str = "clock_decentralised";
12
13/// What the UI hears when the clock in force, or what is known about it, changes.
14pub const EVENT: &str = "clock_changed";
15
16/// How far the relays' clock is ahead of this device's, in ms, as last agreed.
17static MEASURED_MS: AtomicI64 = AtomicI64::new(0);
18
19/// Whether Vector runs on the relays' clock (the default) or the device's.
20static DECENTRALISED: AtomicBool = AtomicBool::new(true);
21
22/// The last check: how many relays answered, how many agreed, and when (device unix secs).
23static ANSWERED: AtomicU8 = AtomicU8::new(0);
24static AGREEING: AtomicU8 = AtomicU8::new(0);
25static CHECKED_AT: AtomicU64 = AtomicU64::new(0);
26
27/// `Date` has one-second resolution: a smaller gap is no evidence of a wrong clock.
28const NOISE_MS: i64 = 2_000;
29
30/// How close a relay must be to the median to count as agreeing with it.
31const AGREE_MS: i64 = 5_000;
32
33/// How many relays must agree before their time is used. Never two: when two disagree, there is
34/// no telling which is wrong.
35const QUORUM: usize = 3;
36
37/// A sample whose round trip took longer than this can't place the time closely enough.
38const MAX_ROUND_TRIP_MS: u64 = 8_000;
39
40/// How often the relays are asked again.
41pub(crate) const RESYNC: std::time::Duration = std::time::Duration::from_secs(60 * 60);
42
43/// The soonest an early check may follow the last one, so a burst of clock refusals asks once.
44const MIN_RESYNC_SECS: u64 = 60;
45
46/// Now, in unix ms, on the clock in force.
47pub fn now_ms() -> u64 {
48    let offset = offset_ms();
49    #[cfg(test)]
50    let offset = offset + TEST_SHIFT_MS.with(|s| s.get());
51    device_ms().saturating_add_signed(offset)
52}
53
54#[cfg(test)]
55thread_local! {
56    static TEST_SHIFT_MS: std::cell::Cell<i64> = const { std::cell::Cell::new(0) };
57}
58
59/// Move this test thread's clock by `ms`, as a relays' correction would.
60#[cfg(test)]
61pub(crate) fn shift_for_test(ms: i64) {
62    TEST_SHIFT_MS.with(|s| s.set(ms));
63}
64
65/// Now, in unix seconds, on the clock in force.
66pub fn now_secs() -> u64 {
67    now_ms() / 1000
68}
69
70/// Now, as the `created_at` or filter bound of an event. Use this, never `Timestamp::now()`.
71pub fn timestamp() -> Timestamp {
72    Timestamp::from_secs(now_secs())
73}
74
75/// The correction in force, in ms (positive when this device runs behind). Zero on the device clock.
76pub fn offset_ms() -> i64 {
77    if DECENTRALISED.load(Ordering::Relaxed) {
78        MEASURED_MS.load(Ordering::Relaxed)
79    } else {
80        0
81    }
82}
83
84fn device_ms() -> u64 {
85    // device-clock: what every correction is measured from.
86    web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
87}
88
89/// Move an event nostr stamped with the device's clock onto the clock in force. A time the caller
90/// chose (a backdated wrap, an edition's own date) is left alone, and so is the id it fixed.
91pub fn restamp(mut unsigned: UnsignedEvent) -> UnsignedEvent {
92    if offset_ms() == 0 || unsigned.created_at.as_secs().abs_diff(device_ms() / 1000) > 1 {
93        return unsigned;
94    }
95    unsigned.created_at = timestamp();
96    if unsigned.id.take().is_some() {
97        unsigned.ensure_id();
98    }
99    unsigned
100}
101
102/// A length of time as a person says it: "40 seconds", "4 minutes", "2 hours".
103pub fn describe_span(secs: u64) -> String {
104    let (n, unit) = match secs {
105        0..=89 => (secs, "second"),
106        90..=5_399 => ((secs + 30) / 60, "minute"),
107        5_400..=172_799 => ((secs + 1_800) / 3_600, "hour"),
108        _ => ((secs + 43_200) / 86_400, "day"),
109    };
110    format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
111}
112
113/// Whether Vector runs on the relays' clock.
114pub fn is_decentralised() -> bool {
115    DECENTRALISED.load(Ordering::Relaxed)
116}
117
118/// Read the live account's choice. Called as its session starts.
119pub fn load_setting() {
120    let on = !matches!(crate::db::get_sql_setting(SETTING_KEY.to_string()), Ok(Some(v)) if v == "false" || v == "0");
121    if DECENTRALISED.swap(on, Ordering::Relaxed) != on {
122        announce();
123    }
124}
125
126/// Choose the relays' clock or the device's, for this account, from now on.
127pub fn set_decentralised(on: bool) -> Result<(), String> {
128    crate::db::set_sql_setting(SETTING_KEY.to_string(), if on { "true" } else { "false" }.to_string())?;
129    DECENTRALISED.store(on, Ordering::Relaxed);
130    announce();
131    Ok(())
132}
133
134/// What the clock is doing, for Settings.
135#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
136pub struct Status {
137    /// Running on the relays' clock.
138    pub decentralised: bool,
139    /// How far the relays' clock is ahead of this device's, in ms, whichever clock is in force.
140    pub measured_offset_ms: i64,
141    /// The correction applied now, in ms.
142    pub offset_ms: i64,
143    /// At the last check: relays that answered, and how many of them agreed.
144    pub answered: u8,
145    pub agreeing: u8,
146    /// When the last check ran, in unix secs on the clock in force; 0 before the first.
147    pub checked_at: u64,
148}
149
150pub fn status() -> Status {
151    let checked = CHECKED_AT.load(Ordering::Relaxed);
152    Status {
153        decentralised: is_decentralised(),
154        measured_offset_ms: MEASURED_MS.load(Ordering::Relaxed),
155        offset_ms: offset_ms(),
156        answered: ANSWERED.load(Ordering::Relaxed),
157        agreeing: AGREEING.load(Ordering::Relaxed),
158        checked_at: if checked == 0 { 0 } else { checked.saturating_add_signed(offset_ms() / 1000) },
159    }
160}
161
162fn announce() {
163    crate::traits::emit_event(EVENT, &status());
164}
165
166/// The offset `samples` (each a relay's clock minus this device's, in ms) agree on: their median,
167/// when at least [`QUORUM`] lie within [`AGREE_MS`] of it, with how many do.
168fn agreed(samples: &mut [i64]) -> Option<(i64, usize)> {
169    if samples.len() < QUORUM {
170        return None;
171    }
172    samples.sort_unstable();
173    let median = samples[samples.len() / 2];
174    let near = samples.iter().filter(|s| (*s - median).abs() <= AGREE_MS).count();
175    (near >= QUORUM).then_some((median, near))
176}
177
178/// Ask `relays` for the time and correct the clock by what they agree on. Leaves it alone when
179/// fewer than `QUORUM` answer alike, the device's clock is used until they do.
180pub async fn sync_with(relays: &[String]) {
181    let asked = relays.iter().take(8).map(|r| sample(r));
182    let mut samples: Vec<i64> = futures_util::future::join_all(asked).await.into_iter().flatten().collect();
183    let answered = samples.len();
184    let agreement = agreed(&mut samples);
185    ANSWERED.store(answered.min(u8::MAX as usize) as u8, Ordering::Relaxed);
186    AGREEING.store(agreement.map_or(0, |(_, n)| n.min(u8::MAX as usize) as u8), Ordering::Relaxed);
187    CHECKED_AT.store(device_ms() / 1000, Ordering::Relaxed);
188    let offset = match agreement {
189        Some((offset, _)) if offset.abs() >= NOISE_MS => offset,
190        _ => 0,
191    };
192    if MEASURED_MS.swap(offset, Ordering::Relaxed) != offset {
193        match agreement {
194            Some(_) if offset != 0 => crate::log_warn!("[clock] this device's clock is {} ms off the relays'", -offset),
195            Some(_) => {}
196            None => crate::log_warn!("[clock] fewer than {QUORUM} relays agree on the time; using this device's clock"),
197        }
198    }
199    announce();
200}
201
202static RESYNC_NOW: tokio::sync::Notify = tokio::sync::Notify::const_new();
203
204/// Ask the relays again soon, rather than at the next hourly check: a server said this clock is off.
205pub fn resync_soon() {
206    let last = CHECKED_AT.load(Ordering::Relaxed);
207    if last == 0 || device_ms() / 1000 >= last.saturating_add(MIN_RESYNC_SECS) {
208        RESYNC_NOW.notify_one();
209    }
210}
211
212/// Until the next check is due: the hourly one, or one [`resync_soon`] asked for.
213pub(crate) async fn until_next_check() {
214    let hourly = std::pin::pin!(crate::rt::time::sleep(RESYNC));
215    let early = std::pin::pin!(RESYNC_NOW.notified());
216    futures_util::future::select(hourly, early).await;
217}
218
219/// One relay's clock minus this device's, in ms, from the `Date` (and any `Age`) on its answer.
220/// In a browser, only a relay that sends `Access-Control-Expose-Headers: Date` can answer.
221async fn sample(relay: &str) -> Option<i64> {
222    let url = http_url(relay)?;
223    let client = crate::net::build_http_client(std::time::Duration::from_secs(10)).ok()?;
224    let sent = device_ms();
225    let resp = client
226        .get(url)
227        .header("Accept", "application/nostr+json")
228        .header("Cache-Control", "no-cache")
229        .send()
230        .await
231        .ok()?;
232    let back = device_ms();
233    if back.saturating_sub(sent) > MAX_ROUND_TRIP_MS {
234        return None;
235    }
236    let date = parse_http_date(resp.headers().get("date")?.to_str().ok()?)?;
237    let age = resp.headers().get("age").and_then(|a| a.to_str().ok()?.trim().parse::<u64>().ok()).unwrap_or(0);
238    // The relay stamped a whole second it was somewhere inside, met about mid-trip.
239    let relay_ms = (date + age) * 1000 + 500;
240    Some(relay_ms as i64 - (sent + back) as i64 / 2)
241}
242
243/// Where a relay answers over HTTP: its own address, path included.
244fn http_url(relay: &str) -> Option<String> {
245    let relay = relay.trim();
246    relay.strip_prefix("wss://").map(|r| format!("https://{r}")).or_else(|| relay.strip_prefix("ws://").map(|r| format!("http://{r}")))
247}
248
249/// Unix seconds of an IMF-fixdate, `Sun, 06 Nov 1994 08:49:37 GMT`: the form RFC 9110 has every
250/// server send.
251fn parse_http_date(s: &str) -> Option<u64> {
252    let parts: Vec<&str> = s.split_whitespace().collect();
253    let [_, day, month, year, time, "GMT"] = parts.as_slice() else { return None };
254    let month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].iter().position(|m| m == month)? as i64 + 1;
255    let (day, year): (i64, i64) = (day.parse().ok()?, year.parse().ok()?);
256    let hms: Vec<i64> = time.split(':').map(|p| p.parse().ok()).collect::<Option<_>>()?;
257    let [h, m, sec] = hms.as_slice() else { return None };
258    if !(1..=31).contains(&day) || *h > 23 || *m > 59 || *sec > 60 {
259        return None;
260    }
261    // Days from 1970-01-01 to the civil date (proleptic Gregorian).
262    let y = if month <= 2 { year - 1 } else { year };
263    let era = y.div_euclid(400);
264    let yoe = y - era * 400;
265    let doy = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
266    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
267    let days = era * 146_097 + doe - 719_468;
268    u64::try_from(days * 86_400 + h * 3600 + m * 60 + sec).ok()
269}
270
271/// Every place under `src_root` that reads the time off the device rather than this clock, as
272/// `path:line` relative to `crate_root`: `Timestamp::now()`, unix time from `SystemTime`, and
273/// signing with bare keys through nostr's `finalize`, which stamps the device's clock. A read
274/// that must stay on the device (a file's age, a log line, an id) says why with
275/// `// device-clock: <why>` on its line or the three above.
276pub fn device_clock_reads(crate_root: &std::path::Path, src_root: &std::path::Path) -> Vec<String> {
277    let mut found = Vec::new();
278    let mut stack = vec![src_root.to_path_buf()];
279    while let Some(dir) = stack.pop() {
280        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
281        for entry in entries.flatten() {
282            let path = entry.path();
283            if path.is_dir() {
284                stack.push(path);
285                continue;
286            }
287            let rel = path.strip_prefix(crate_root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
288            if path.extension().and_then(|e| e.to_str()) != Some("rs") || ["/tests", "fixtures", "bench"].iter().any(|t| rel.contains(t)) {
289                continue;
290            }
291            let Ok(src) = std::fs::read_to_string(&path) else { continue };
292            found.extend(device_reads_in(&src).into_iter().map(|n| format!("{rel}:{n}")));
293        }
294    }
295    found.sort();
296    found
297}
298
299/// The 1-based lines of one file's shipping code that read the device's clock unmarked.
300fn device_reads_in(src: &str) -> Vec<usize> {
301    let lines: Vec<&str> = src.lines().collect();
302    if lines.iter().map(|l| l.trim()).find(|l| !l.is_empty() && !l.starts_with("//")) == Some("#![cfg(test)]") {
303        return Vec::new();
304    }
305    let cut = lines
306        .windows(2)
307        .position(|w| {
308            w[0].trim() == "#[cfg(test)]"
309                && ["mod ", "pub mod ", "pub(crate) mod "].iter().any(|m| w[1].trim_start().starts_with(m))
310        })
311        .unwrap_or(lines.len());
312    let shipping = &lines[..cut];
313    let signs_bare = |l: &str| {
314        l.split(concat!(".final", "ize(")).skip(1).any(|rest| rest.trim_start().chars().next().is_some_and(|c| c != ')'))
315    };
316    (0..shipping.len())
317        .filter(|&i| {
318            let l = shipping[i];
319            let unix = l.contains(concat!("SystemTime::", "now()"))
320                && shipping[i..(i + 4).min(cut)].iter().any(|n| n.contains(concat!("UNIX_", "EPOCH")));
321            !l.trim_start().starts_with("//")
322                && (l.contains(concat!("Timestamp::", "now()")) || unix || signs_bare(l))
323                && !shipping[i.saturating_sub(3)..=i].iter().any(|p| p.contains("device-clock:"))
324        })
325        .map(|i| i + 1)
326        .collect()
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn an_http_date_reads_as_its_unix_time() {
335        assert_eq!(parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT"), Some(784_111_777));
336        assert_eq!(parse_http_date("Wed, 21 Oct 2026 16:59:42 GMT"), Some(1_792_601_982));
337        assert_eq!(parse_http_date("Thu, 01 Jan 1970 00:00:00 GMT"), Some(0));
338        assert_eq!(parse_http_date("Sunday, 06-Nov-94 08:49:37 GMT"), None, "only the form servers must send");
339        assert_eq!(parse_http_date("Sun, 06 Foo 1994 08:49:37 GMT"), None);
340    }
341
342    #[test]
343    fn the_clock_moves_only_on_relays_that_agree() {
344        assert_eq!(agreed(&mut []), None);
345        assert_eq!(agreed(&mut [90_000]), None, "one relay is no agreement");
346        assert_eq!(agreed(&mut [-120_000, -119_000]), None, "nor are two, even agreeing: never two compasses");
347        assert_eq!(agreed(&mut [90_000, 91_000, 89_500, -3_000_000]), Some((90_000, 3)), "a lone liar is outvoted");
348        assert_eq!(agreed(&mut [90_000, 91_000, -3_000_000]), None, "two against one is not three");
349        assert_eq!(agreed(&mut [-120_000, -119_000, -121_000]), Some((-120_000, 3)));
350    }
351
352    #[test]
353    fn nothing_in_the_core_reads_the_device_clock_unmarked() {
354        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
355        let found = device_clock_reads(root, &root.join("src"));
356        assert!(
357            found.is_empty(),
358            "these read the device's clock: use crate::clock (timestamp, now_secs, now_ms, FinalizeOnClock), \
359             or mark the site `// device-clock: <why>`:\n  {}",
360            found.join("\n  ")
361        );
362    }
363
364    #[test]
365    fn the_audit_sees_each_kind_of_device_read() {
366        let src = "fn a() { Timestamp::now(); }\nfn b() {\n    let t = SystemTime::now()\n        .duration_since(UNIX_EPOCH);\n}\nfn c() { b.finalize(&keys); h.finalize(); }\n// device-clock: ok\nfn d() { Timestamp::now(); }\n#[cfg(test)]\nmod tests { fn e() { Timestamp::now(); } }\n";
367        assert_eq!(device_reads_in(&src.replace("Timestamp::now", concat!("Timestamp::", "now"))), vec![1, 3, 6]);
368    }
369
370    #[test]
371    fn restamping_moves_only_a_device_stamp() {
372        use nostr_sdk::prelude::FinalizeUnsignedEvent;
373        let keys = nostr_sdk::prelude::Keys::generate();
374        let builder = || nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::TextNote, "hi");
375        shift_for_test(0);
376        MEASURED_MS.store(-240_000, Ordering::Relaxed);
377        DECENTRALISED.store(true, Ordering::Relaxed);
378
379        let mut defaulted = builder().finalize_unsigned(keys.public_key());
380        defaulted.ensure_id();
381        let before = defaulted.id;
382        let moved = restamp(defaulted);
383        assert_eq!(moved.created_at.as_secs(), device_ms() / 1000 - 240, "onto the relays' clock");
384        assert_ne!(moved.id, before, "and its id follows");
385
386        let chosen = builder().custom_created_at(Timestamp::from_secs(1_000)).finalize_unsigned(keys.public_key());
387        assert_eq!(restamp(chosen).created_at.as_secs(), 1_000, "a chosen time stays");
388
389        DECENTRALISED.store(false, Ordering::Relaxed);
390        let device = builder().finalize_unsigned(keys.public_key());
391        let stamp = device.created_at;
392        assert_eq!(restamp(device).created_at, stamp, "the device clock is left alone when chosen");
393        assert_eq!(offset_ms(), 0);
394        assert_eq!(status().measured_offset_ms, -240_000, "but what the relays said is still shown");
395
396        DECENTRALISED.store(true, Ordering::Relaxed);
397        MEASURED_MS.store(0, Ordering::Relaxed);
398    }
399}