Skip to main content

rings_node/mail/
recipient.rs

1//! The recipient's side: its reads of its mail topic, and what it remembers. It builds for native and browser nodes alike: its records and its inbox are any
2//! key-value store (a file store natively, IndexedDB in a browser) and any [`MailInbox`].
3//!
4//! ```text
5//!   poll(t):  E = fetch(mail_topic(d))                      the elements live at t
6//!             R = records ∖ { r | outlived(r, t) }           retention
7//!             for o ∈ open(E, d, k, fresh = ¬opened_R(k)):  k = the node's delegatee key
8//!               Incomplete             ─▶ nothing           tried again on the next poll
9//!               Unreadable             ─▶ opened(k, id)
10//!               Opened(m) ∧ filed_R(h) ─▶ opened(k, id)      h = H(Message-ID), or id without one
11//!               Opened(m)              ─▶ inbox.file(m); filed(h); opened(k, id)
12//! ```
13//!
14//! Laws:
15//! - **Schedule.** The recipient polls when it starts and every `I ≤ H / 2` while it runs
16//!   ([`MAX_MAIL_POLL_INTERVAL`]): a mail written just after one poll lives `H` and the next
17//!   poll comes within `H / 2`, which leaves the other half for clock skew and propagation.
18//! - **No removal.** It never writes its mail topic: every element retires at its horizon, and
19//!   a data carrier's remove budget (`DATA_TOMBSTONE_MAX_LEN`) is never spent on mail.
20//! - **At least once.** A mail is filed before it is remembered, so a crash between the two
21//!   files it again after a restart: a crash never loses a mail, at worst it is filed twice.
22//! - **Deduplication.** Encryption is randomized, so a resent mail is a new ciphertext: mail
23//!   with a `Message-ID` already filed is not filed again, even under another delegatee key.
24//!   Polls of one recipient are serialized, so their record snapshots cannot race each other.
25//! - **Key isolation.** An opened or unreadable verdict belongs to the delegatee public key
26//!   that produced it. Recipients sharing records under different keys cannot hide mail from
27//!   each other. Filed records stay shared because filing does not depend on the opening key.
28//!   Separate recipients do not share a poll lock: concurrent polls can both file before
29//!   either observes the other's filing record, preserving at-least-once delivery.
30//! - **Retention.** An opened id is kept `H + σ` ([`OPENED_RETENTION_MS`]), after which no copy
31//!   of its mail is served; a `Message-ID` is kept [`MESSAGE_ID_RETENTION_MS`].
32//! - **One key.** Mail opens only under the node's current delegatee key. Mail sealed to a key
33//!   the node no longer holds is lost, as mail not fetched within its lifetime is: a browser
34//!   node takes a new key at every load, so mail a gateway accepted under the old one, within the
35//!   descriptor's freshness window around a reload, never opens.
36
37use std::collections::BTreeMap;
38use std::sync::Arc;
39use std::time::Duration;
40
41use async_trait::async_trait;
42use futures::lock::Mutex;
43use rings_core::consts::MAX_TTL_MS;
44use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
45use rings_core::dht::entry::Entry;
46use rings_core::ecc::PublicKey;
47use rings_core::lifecycle::StopToken;
48use rings_core::storage::KvStorageInterface;
49use rings_core::utils::SharedClock;
50use rings_core::utils::SystemClock;
51use rings_runtime::MaybeSendSync;
52use serde::Deserialize;
53use serde::Serialize;
54use thiserror::Error;
55
56use super::envelope::MailDigest;
57use super::mail_topic;
58use super::open::open_mail_with_keys;
59use super::open::OpenedMail;
60use super::open::Opening;
61use super::write_lowercase_hex;
62use crate::processor::sleep_unless_stopped;
63use crate::processor::Processor;
64
65/// The default interval between two polls of the mail topic.
66pub const DEFAULT_MAIL_POLL_INTERVAL: Duration = Duration::from_secs(60);
67/// Default upper bound on a single recipient poll before a stalled fetch or store is aborted.
68pub const DEFAULT_MAIL_POLL_TIMEOUT: Duration = Duration::from_secs(30);
69/// The longest interval between two polls, `H / 2` (the schedule law).
70pub const MAX_MAIL_POLL_INTERVAL: Duration = Duration::from_millis(MAX_TTL_MS / 2);
71/// How long an opened mail id is kept: `H + σ`, after which no owner on a
72/// clock within the skew tolerance serves an element of a mail written before.
73pub const OPENED_RETENTION_MS: u128 = MAX_TTL_MS as u128 + TS_OFFSET_TOLERANCE_MS;
74/// How long a filed `Message-ID` is kept: five days, the longest a sender retries a message
75/// (RFC 5321 §4.5.4.1), so a resend never files a mail twice.
76pub const MESSAGE_ID_RETENTION_MS: u128 = 5 * 24 * 3600 * 1000;
77
78/// Where the recipient files the mail it opens: the mailbox store natively, IndexedDB in a
79/// browser ([`KvInbox`]).
80#[cfg_attr(rings_browser, async_trait(?Send))]
81#[cfg_attr(rings_native, async_trait)]
82pub trait MailInbox: MaybeSendSync {
83    /// Why a mail could not be filed.
84    type Error: std::error::Error + MaybeSendSync;
85
86    /// File `mail`; `Ok` once it is kept.
87    async fn file(&self, mail: &OpenedMail) -> Result<(), Self::Error>;
88}
89
90/// A mail as a [`KvInbox`] keeps it.
91#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
92pub struct StoredMail {
93    /// The message.
94    pub message: Vec<u8>,
95    /// When it was filed, in milliseconds since Unix epoch.
96    pub filed_at_ms: u128,
97}
98
99/// An inbox over a key-value store: each mail under `mail-<mail id>`.
100pub struct KvInbox<K> {
101    store: K,
102    clock: SharedClock,
103}
104
105impl<K> KvInbox<K> {
106    /// The inbox keeping its mail in `store` stamped with the system clock.
107    pub fn new(store: K) -> Self {
108        Self::new_with_clock(store, Arc::new(SystemClock))
109    }
110
111    /// The inbox keeping its mail in `store` stamped with `clock`.
112    pub fn new_with_clock(store: K, clock: SharedClock) -> Self {
113        Self { store, clock }
114    }
115
116    /// The store the mail is kept in.
117    pub fn store(&self) -> &K {
118        &self.store
119    }
120}
121
122#[cfg_attr(rings_browser, async_trait(?Send))]
123#[cfg_attr(rings_native, async_trait)]
124impl<K> MailInbox for KvInbox<K>
125where K: KvStorageInterface<StoredMail> + MaybeSendSync
126{
127    type Error = rings_core::error::Error;
128
129    async fn file(&self, mail: &OpenedMail) -> Result<(), Self::Error> {
130        let stored = StoredMail {
131            message: mail.message.clone(),
132            filed_at_ms: self.clock.now_ms(),
133        };
134        self.store
135            .put(&format!("mail-{}", mail.mail_id), &stored)
136            .await
137    }
138}
139
140/// A record the recipient keeps.
141#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
142pub enum RecipientRecord {
143    /// A mail id opened, or found unreadable, at `at_ms`: it is not opened again under the
144    /// delegatee public key in its record name (the key-isolation law).
145    Opened {
146        /// When.
147        at_ms: u128,
148    },
149    /// A mail with this deduplication key filed at `at_ms`.
150    Filed {
151        /// When.
152        at_ms: u128,
153    },
154}
155
156impl RecipientRecord {
157    /// Whether this record has outlived its retention at `now_ms` (the retention law).
158    pub fn outlived_at(&self, now_ms: u128) -> bool {
159        let (since, retention) = match self {
160            Self::Opened { at_ms } => (*at_ms, OPENED_RETENTION_MS),
161            Self::Filed { at_ms } => (*at_ms, MESSAGE_ID_RETENTION_MS),
162        };
163        now_ms >= since.saturating_add(retention)
164    }
165}
166
167/// Format the key-isolated [`RecipientRecord::Opened`] storage key
168/// `opened-<public key hex>-<mail id hex>`.
169///
170/// Law: opening names bind both the delegatee public key and the mail digest, so distinct
171/// delegatee public keys never share an opening verdict.
172fn opened_record_name(delegatee_public_key: PublicKey<33>, mail_id: MailDigest) -> String {
173    let mut name = String::with_capacity(7 + 66 + 1 + 64);
174    name.push_str("opened-");
175    let _ = write_lowercase_hex(&mut name, &delegatee_public_key.0);
176    name.push('-');
177    let _ = std::fmt::Write::write_fmt(&mut name, format_args!("{mail_id}"));
178    name
179}
180
181/// Format the shared [`RecipientRecord::Filed`] storage key `filed-<deduplication key hex>`.
182fn filed_record_name(key: MailDigest) -> String {
183    format!("filed-{key}")
184}
185
186/// The key a mail is deduplicated by: `H(Message-ID)`, or its own id without one.
187fn dedup_key(mail: &OpenedMail) -> MailDigest {
188    mail.message_id().map_or(mail.mail_id, |message_id| {
189        MailDigest::of(message_id.as_bytes())
190    })
191}
192
193/// What one poll did.
194#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
195pub struct PollReport {
196    /// Mail filed in the inbox.
197    pub filed: usize,
198    /// Mail opened whose `Message-ID` was filed before.
199    pub duplicates: usize,
200    /// Mail the node's key does not open.
201    pub unreadable: usize,
202    /// Mail a manifest lists a missing chunk of.
203    pub incomplete: usize,
204}
205
206/// Why the recipient could not start or poll.
207#[derive(Debug, Error)]
208pub enum RecipientError<E> {
209    /// The poll interval exceeds [`MAX_MAIL_POLL_INTERVAL`].
210    #[error(
211        "mail poll interval {interval:?} exceeds {MAX_MAIL_POLL_INTERVAL:?}, half the horizon"
212    )]
213    PollInterval {
214        /// The interval asked for.
215        interval: Duration,
216    },
217    /// The DHT key of the mail topic cannot be derived.
218    #[error("no DHT key for the mail topic: {0}")]
219    Key(#[source] rings_core::error::Error),
220    /// The fetch of the mail topic failed.
221    #[error("cannot fetch the mail topic: {0}")]
222    Fetch(#[source] crate::error::Error),
223    /// The records could not be read or written.
224    #[error("mail records: {0}")]
225    Records(#[source] rings_core::error::Error),
226    /// The inbox did not file a mail.
227    #[error("cannot file a mail: {0}")]
228    Inbox(#[source] E),
229    /// A cooperative stop ended the poll before completion.
230    #[error("mail recipient stopped")]
231    Stopped,
232    /// A single poll exceeded its time budget (e.g. stalled storage or network fetch).
233    #[error("mail poll timed out after {timeout:?}")]
234    PollTimeout {
235        /// The configured per-poll timeout that elapsed.
236        timeout: Duration,
237    },
238    /// The runtime could not arm the poll timeout timer.
239    #[error("mail poll timer failed: {0}")]
240    Timer(#[source] rings_runtime::TimerError),
241}
242
243/// Pure decision ADT classifying one `(Opening, Option<PublicKey<33>>)` against the current
244/// `records` snapshot before any inbox or storage side effect runs.
245enum OpeningAction {
246    /// Manifest lists a missing chunk; retry on the next poll without recording `opened`.
247    Incomplete,
248    /// Already processed under a retained previous key; record `opened` under the active key (and
249    /// the retained key when `opened_by` is present) without incrementing `PollReport`.
250    AlreadyHandledByRetained {
251        retained_opened_record: Option<String>,
252        active_opened_record: String,
253    },
254    /// Unreadable by all held keys and not previously handled; increment `unreadable` and record
255    /// `opened` under the active key.
256    Unreadable { active_opened_record: String },
257    /// Decrypted, but `Message-ID` was already filed; increment `duplicates` and record `opened`.
258    Duplicate {
259        retained_opened_record: Option<String>,
260        active_opened_record: String,
261    },
262    /// Decrypted and fresh; file into `inbox`, record `filed`, and record `opened`.
263    FileNew {
264        mail: OpenedMail,
265        filed_record: String,
266        retained_opened_record: Option<String>,
267        active_opened_record: String,
268    },
269}
270
271/// Pure decision function mapping an `(Opening, Option<PublicKey<33>>)` and the current
272/// `records` snapshot into an [`OpeningAction`].
273///
274/// Enforces the **Key-isolation law** and **Cross-key retention law** (#1153): if a retained
275/// previous key already recorded `opened-<retained_pk>-<mail_id>`, re-observing the same mail
276/// after key rotation records `opened-<active_pk>-<mail_id>` without double-counting `unreadable`
277/// or `duplicates` in [`PollReport`].
278fn classify_opening(
279    opening: Opening,
280    opened_by: Option<PublicKey<33>>,
281    delegatee_public_key: PublicKey<33>,
282    decryption_keys: &[rings_core::delegation::DelegateeKey],
283    records: &BTreeMap<String, RecipientRecord>,
284) -> OpeningAction {
285    let mail_id = opening.mail_id();
286    let active_opened_record = opened_record_name(delegatee_public_key, mail_id);
287    let retained_opened_record = opened_by
288        .filter(|&pk| pk != delegatee_public_key)
289        .map(|pk| opened_record_name(pk, mail_id));
290    let already_handled_by_retained_key = match &retained_opened_record {
291        Some(record_name) => records.contains_key(record_name),
292        None if opened_by.is_none() => decryption_keys.iter().skip(1).any(|key| {
293            records.contains_key(&opened_record_name(key.delegatee_public_key(), mail_id))
294        }),
295        None => false,
296    };
297
298    match opening {
299        Opening::Incomplete { .. } => OpeningAction::Incomplete,
300        Opening::Unreadable { .. } if already_handled_by_retained_key => {
301            OpeningAction::AlreadyHandledByRetained {
302                retained_opened_record,
303                active_opened_record,
304            }
305        }
306        Opening::Unreadable { .. } => OpeningAction::Unreadable {
307            active_opened_record,
308        },
309        Opening::Opened(_) if already_handled_by_retained_key => {
310            OpeningAction::AlreadyHandledByRetained {
311                retained_opened_record,
312                active_opened_record,
313            }
314        }
315        Opening::Opened(mail) => {
316            let filed_record = filed_record_name(dedup_key(&mail));
317            if records.contains_key(&filed_record) {
318                OpeningAction::Duplicate {
319                    retained_opened_record,
320                    active_opened_record,
321                }
322            } else {
323                OpeningAction::FileNew {
324                    mail,
325                    filed_record,
326                    retained_opened_record,
327                    active_opened_record,
328                }
329            }
330        }
331    }
332}
333
334/// A recipient: a node reading its own mail topic into `inbox`, keeping its records in
335/// `records`.
336pub struct Recipient<I, K> {
337    processor: Arc<Processor>,
338    inbox: I,
339    records: K,
340    interval: Duration,
341    poll_timeout: Duration,
342    /// Serializes this recipient's polls so each observes the previous poll's filing records.
343    poll_lock: Mutex<()>,
344}
345
346impl<I, K> Recipient<I, K>
347where
348    I: MailInbox,
349    K: KvStorageInterface<RecipientRecord> + MaybeSendSync,
350{
351    /// The recipient of `processor`'s DID, filing into `inbox`, remembering in `records`, and
352    /// polling every `interval`, which the schedule law bounds.
353    pub fn start(
354        processor: Arc<Processor>,
355        inbox: I,
356        records: K,
357        interval: Duration,
358    ) -> Result<Self, RecipientError<I::Error>> {
359        if interval > MAX_MAIL_POLL_INTERVAL {
360            return Err(RecipientError::PollInterval { interval });
361        }
362        Ok(Self {
363            processor,
364            inbox,
365            records,
366            interval,
367            poll_timeout: DEFAULT_MAIL_POLL_TIMEOUT,
368            poll_lock: Mutex::new(()),
369        })
370    }
371
372    /// Override the per-poll timeout bounding a stalled fetch or store operation.
373    pub fn with_poll_timeout(mut self, poll_timeout: Duration) -> Self {
374        self.poll_timeout = poll_timeout;
375        self
376    }
377
378    /// The inbox mail is filed in.
379    pub fn inbox(&self) -> &I {
380        &self.inbox
381    }
382
383    /// Read the mail topic once, file what opens, and remember it (the poll of this module),
384    /// bounded by this recipient's poll timeout and the node's cooperative stop token.
385    pub async fn poll(&self) -> Result<PollReport, RecipientError<I::Error>> {
386        let stop = self.processor.tasks().stop_token();
387        self.poll_with_stop(&stop).await
388    }
389
390    /// Read the mail topic once, aborting promptly when `stop` or the node's stop fires, or when
391    /// this recipient's poll timeout elapses.
392    pub async fn poll_with_stop(
393        &self,
394        stop: &StopToken,
395    ) -> Result<PollReport, RecipientError<I::Error>> {
396        let node_stop = self.processor.tasks().stop_token();
397        if stop.should_stop() || node_stop.should_stop() {
398            return Err(RecipientError::Stopped);
399        }
400        let work = self.poll_inner(stop);
401        let caller_stopped = stop.stopped();
402        let node_stopped = node_stop.stopped();
403        let deadline = rings_runtime::sleep(self.poll_timeout);
404        futures::pin_mut!(work, caller_stopped, node_stopped, deadline);
405        let any_stop = futures::future::select(caller_stopped, node_stopped);
406        match futures::future::select(work, futures::future::select(any_stop, deadline)).await {
407            futures::future::Either::Left((result, _)) => result,
408            futures::future::Either::Right((futures::future::Either::Left(_), _)) => {
409                Err(RecipientError::Stopped)
410            }
411            futures::future::Either::Right((
412                futures::future::Either::Right((timer_result, _)),
413                _,
414            )) => match timer_result {
415                Ok(()) => {
416                    tracing::warn!(
417                        timeout = ?self.poll_timeout,
418                        "mail: recipient poll timed out on stalled fetch or storage"
419                    );
420                    Err(RecipientError::PollTimeout {
421                        timeout: self.poll_timeout,
422                    })
423                }
424                Err(error) => Err(RecipientError::Timer(error)),
425            },
426        }
427    }
428
429    async fn poll_inner(&self, stop: &StopToken) -> Result<PollReport, RecipientError<I::Error>> {
430        let _poll_guard = rings_core::utils::SlowLockGuard::acquire(
431            "Recipient::poll_lock",
432            self.poll_lock.lock(),
433        )
434        .await;
435        let did = self.processor.did();
436        let key = Entry::gen_did(&mail_topic(did)).map_err(RecipientError::Key)?;
437        let entry = match self
438            .processor
439            .fetch_storage_entry_with_stop(key, stop)
440            .await
441        {
442            Ok(entry) => entry,
443            Err(crate::error::Error::RegistrationStopped) => {
444                return Err(RecipientError::Stopped);
445            }
446            Err(error) => return Err(RecipientError::Fetch(error)),
447        };
448        let now_ms = self.processor.clock().now_ms();
449        let mut records = self.retained_records(now_ms).await?;
450        let Some(entry) = entry else {
451            return Ok(PollReport::default());
452        };
453        let delegatee_key = self.processor.delegatee_key();
454        let delegatee_public_key = delegatee_key.delegatee_public_key();
455        let decryption_keys = self.processor.decryption_keys_at(now_ms);
456        let fresh = |mail_id: &MailDigest| {
457            !records.contains_key(&opened_record_name(delegatee_public_key, *mail_id))
458        };
459        let openings = open_mail_with_keys(&entry.data, did, &decryption_keys, fresh);
460        let mut report = PollReport::default();
461        for (opening, opened_by) in openings {
462            match classify_opening(
463                opening,
464                opened_by,
465                delegatee_public_key,
466                &decryption_keys,
467                &records,
468            ) {
469                OpeningAction::Incomplete => {
470                    report.incomplete = report.incomplete.saturating_add(1);
471                }
472                OpeningAction::AlreadyHandledByRetained {
473                    retained_opened_record,
474                    active_opened_record,
475                } => {
476                    self.remember_opened_pair(
477                        &mut records,
478                        retained_opened_record,
479                        active_opened_record,
480                        now_ms,
481                    )
482                    .await?;
483                }
484                OpeningAction::Unreadable {
485                    active_opened_record,
486                } => {
487                    report.unreadable = report.unreadable.saturating_add(1);
488                    self.remember_opened_pair(&mut records, None, active_opened_record, now_ms)
489                        .await?;
490                }
491                OpeningAction::Duplicate {
492                    retained_opened_record,
493                    active_opened_record,
494                } => {
495                    report.duplicates = report.duplicates.saturating_add(1);
496                    self.remember_opened_pair(
497                        &mut records,
498                        retained_opened_record,
499                        active_opened_record,
500                        now_ms,
501                    )
502                    .await?;
503                }
504                OpeningAction::FileNew {
505                    mail,
506                    filed_record,
507                    retained_opened_record,
508                    active_opened_record,
509                } => {
510                    self.inbox
511                        .file(&mail)
512                        .await
513                        .map_err(RecipientError::Inbox)?;
514                    self.remember(&mut records, filed_record, RecipientRecord::Filed {
515                        at_ms: now_ms,
516                    })
517                    .await?;
518                    report.filed = report.filed.saturating_add(1);
519                    self.remember_opened_pair(
520                        &mut records,
521                        retained_opened_record,
522                        active_opened_record,
523                        now_ms,
524                    )
525                    .await?;
526                }
527            }
528        }
529        Ok(report)
530    }
531
532    /// Record [`RecipientRecord::Opened`] for the retained key (if any) and the active key.
533    async fn remember_opened_pair(
534        &self,
535        records: &mut BTreeMap<String, RecipientRecord>,
536        retained_opened_record: Option<String>,
537        active_opened_record: String,
538        now_ms: u128,
539    ) -> Result<(), RecipientError<I::Error>> {
540        if let Some(retained_name) = retained_opened_record {
541            self.remember(records, retained_name, RecipientRecord::Opened {
542                at_ms: now_ms,
543            })
544            .await?;
545        }
546        self.remember(records, active_opened_record, RecipientRecord::Opened {
547            at_ms: now_ms,
548        })
549        .await
550    }
551
552    /// Poll now and then every interval until `stop`, logging a failed poll and polling again.
553    pub async fn run(&self, stop: StopToken) {
554        let node_stop = self.processor.tasks().stop_token();
555        loop {
556            match self.poll_with_stop(&stop).await {
557                Ok(report) if report.filed > 0 => {
558                    tracing::info!(filed = report.filed, "mail: filed new mail");
559                }
560                Ok(_) => {}
561                Err(RecipientError::Stopped) => return,
562                Err(_) if stop.should_stop() || node_stop.should_stop() => return,
563                Err(error) => tracing::warn!("mail: poll failed: {error}"),
564            }
565            match sleep_unless_stopped(self.interval, &stop, &node_stop).await {
566                Ok(true) => {}
567                Ok(false) => return,
568                Err(error) => {
569                    tracing::warn!("mail: stopping after a timer error: {error:?}");
570                    return;
571                }
572            }
573        }
574    }
575
576    /// The records retained at `now_ms`, after removing those that outlived their retention.
577    async fn retained_records(
578        &self,
579        now_ms: u128,
580    ) -> Result<BTreeMap<String, RecipientRecord>, RecipientError<I::Error>> {
581        let (expired, retained): (Vec<_>, Vec<_>) = self
582            .records
583            .get_all()
584            .await
585            .map_err(RecipientError::Records)?
586            .into_iter()
587            .partition(|(_, record)| record.outlived_at(now_ms));
588        for (name, _) in expired {
589            self.records
590                .remove(&name)
591                .await
592                .map_err(RecipientError::Records)?;
593        }
594        Ok(retained.into_iter().collect())
595    }
596
597    /// Keep `record` under `name`, in the store and in `records`, this poll's view of it: two
598    /// copies of one mail opened by one poll are filed once.
599    async fn remember(
600        &self,
601        records: &mut BTreeMap<String, RecipientRecord>,
602        name: String,
603        record: RecipientRecord,
604    ) -> Result<(), RecipientError<I::Error>> {
605        self.records
606            .put(&name, &record)
607            .await
608            .map_err(RecipientError::Records)?;
609        records.insert(name, record);
610        Ok(())
611    }
612}
613
614/// Native witnesses of key-isolated opening records and shared filing records.
615#[cfg(all(test, rings_native))]
616mod tests;