Skip to main content

offline_protocol/protocol/
mod.rs

1//! Main protocol engine.
2
3mod blocking;
4mod config_accessors;
5mod custodian;
6pub(crate) mod custody;
7#[cfg(feature = "data")]
8pub(crate) mod data;
9#[cfg(feature = "data")]
10mod data_sync;
11mod decryption_queue;
12pub(crate) mod mesh_relay;
13mod message_dispatch;
14mod nostr_discovery;
15mod nostr_publication;
16mod observability;
17mod pending_queue;
18mod prefixes;
19pub(crate) mod reachability;
20mod receive;
21mod security;
22mod send;
23mod session;
24pub(crate) mod state_crypto;
25mod storage;
26mod types;
27
28pub use custody::{CustodyRefusal, CustodyStats};
29pub(crate) use decryption_queue::PendingDecryptionQueue;
30pub use decryption_queue::PendingQueueMetrics;
31pub(crate) use prefixes::*;
32#[cfg(feature = "file-store")]
33pub(crate) use storage::{sealed_state_key_types, stored_state_record_key, StoredRecordKey};
34pub(crate) use storage::{PruneAllowance, RestorableRecord};
35pub(crate) use types::*;
36pub use types::{GatewayCarrier, MediaSendOptions, ProtocolState, SendMessageOptions};
37
38use crate::file_transfer::{FileTransferManager, OutboundTransferState};
39use crate::group_mesh::{MAX_RELAY_CAPABILITIES, MAX_RELAY_CAPABILITY_TOKEN_BYTES};
40use crate::mls_observability::{MlsEventEmitter, MlsEventRateLimiter, NoopMlsEventEmitter};
41use crate::telemetry::aggregator::{
42    build_metrics_frame, device_battery_from_available, diff_device_capability,
43    diff_transport_state, DeviceSnap,
44};
45#[cfg(feature = "telemetry-pipe")]
46use crate::telemetry::pipe::{
47    store::Backend, AppState, PipeParts, TelemetryHost, TelemetryPipe, TelemetryStats,
48    FINAL_FLUSH_BUDGET,
49};
50use crate::telemetry::{
51    dispatch_record, Scrubber, TelemetryConfig, TelemetryContext, TelemetryRecord, TelemetrySink,
52};
53use crate::{
54    Error, EstablishmentState, Event, ProtocolConfig, ProtocolStateStorage, Result,
55    TransportManager,
56};
57use chrono::{DateTime, Utc};
58use mesh_relay::{MeshRelayGovernor, RelayActivity};
59use offline_protocol_core::{LamportClock, Message, MessageId, MutexExt, Username};
60use offline_protocol_mls::{EncryptedMessage, MlsManager, MlsStorage, WelcomeMessage};
61use offline_protocol_reliability::{AckManager, Deduplicator, RetryQueue};
62use offline_protocol_router::{RelayPriority, RelayRole, TransportSelector};
63use offline_protocol_services::MeshServices;
64use offline_protocol_transport::{BleTransport, TransportStatus, TransportType};
65use std::collections::HashMap;
66use std::collections::HashSet;
67use std::collections::VecDeque;
68use std::sync::{Arc, Mutex, RwLock};
69use std::time::Instant;
70use tracing::{debug, error, info, warn};
71use zeroize::Zeroizing;
72
73/// Returns whether `timestamp` is at least `lifetime_ms` old without relying
74/// on Chrono's panicking `DateTime - Duration` operator.
75///
76/// A lifetime too large to represent, or whose cutoff predates Chrono's
77/// calendar range, cannot expire a representable timestamp.
78fn lifetime_expired(now: DateTime<Utc>, timestamp: DateTime<Utc>, lifetime_ms: u64) -> bool {
79    let Ok(lifetime_ms) = i64::try_from(lifetime_ms) else {
80        return false;
81    };
82    now.checked_sub_signed(chrono::Duration::milliseconds(lifetime_ms))
83        .is_some_and(|cutoff| timestamp <= cutoff)
84}
85
86/// Whether a relay-pushed outbox entry has outlived its fixed redelivery
87/// window ([`offline_protocol_reliability::constants::REDELIVERY_WINDOW_MS`]
88/// from `first_sent_at`). Neither the sliding window nor the restore refresh
89/// moves this: every re-send past it would earn a second visible push, and
90/// the recipient no longer recognises the id as a duplicate.
91fn relay_push_window_closed(now: DateTime<Utc>, entry: &OutboxEntry) -> bool {
92    entry.relay_pushed
93        && lifetime_expired(
94            now,
95            entry.first_sent_at,
96            offline_protocol_reliability::constants::REDELIVERY_WINDOW_MS,
97        )
98}
99
100/// Main entry point for the Offline Protocol SDK.
101///
102/// This struct combines all protocol components and provides a unified API
103/// for sending/receiving messages with automatic transport selection and
104/// reliable delivery.
105pub struct OfflineProtocol {
106    /// Configuration.
107    pub(crate) config: ProtocolConfig,
108
109    /// This device's identity on the wire: the address derived from the
110    /// identity key in this profile's storage.
111    ///
112    /// Every outbound frame is stamped with it, every self-filter compares
113    /// against it, and it is one half of every 1:1 session slot. It is set
114    /// once, by `initialize_mls`, from the key that storage holds — the
115    /// protocol cannot know it before then, because storage is what carries
116    /// the key and storage does not arrive until that call.
117    ///
118    /// Until then it holds [`ProtocolConfig::profile`], which is *not* an
119    /// address and is never a peer's real identity. That fallback keeps the
120    /// pre-MLS surface (transport wiring, local bookkeeping) working on an
121    /// instance that has not been initialized.
122    ///
123    /// One configuration can put the fallback on the wire: the explicit
124    /// `require_encryption = false` opt-out lets a send go out in plaintext
125    /// with MLS never initialized, and such a frame is stamped with the
126    /// profile. It is the same fall-through that already emits
127    /// [`crate::events::SecurityWarningCode::PlaintextSend`], so the condition
128    /// is reported rather than silent. The default config forbids it —
129    /// `require_encryption` is `true`, which fails the send closed.
130    pub(crate) local_id: String,
131
132    /// Whether [`Self::local_id`] is the derived address rather than the
133    /// profile fallback.
134    pub(crate) identity_established: bool,
135
136    /// Transport manager (manages all transports with DORS).
137    pub(crate) transport_manager: TransportManager,
138
139    /// ACK manager for tracking acknowledgments.
140    ack_manager: AckManager,
141
142    /// Retry queue for failed messages.
143    retry_queue: RetryQueue,
144
145    /// Deduplicator for preventing duplicates.
146    pub(crate) deduplicator: Deduplicator,
147
148    /// Decides which frames this device carries for other people, when they
149    /// go out, and how fast. Kept separate from [`Self::deduplicator`], whose
150    /// entries track messages addressed to us and are removed again when
151    /// delivery has to be retried.
152    pub(crate) mesh_relay: MeshRelayGovernor,
153
154    /// Frames held in custody for a neighbour, with the quotas and the
155    /// counters (`docs/spec/custody.md`). Disjoint from
156    /// [`Self::mesh_relay`]'s suppression cache by construction: accepting a
157    /// frame never records its id there, and redelivering one never consults
158    /// it, so a custodian never blanks the route it is holding.
159    pub(crate) custody: custody::CustodyStore,
160
161    /// Receipts this device holds as a *depositor*: for each outbox entry,
162    /// the custodians holding it and until when a further deposit request
163    /// toward each is suppressed, in Unix milliseconds from the receipt's own
164    /// timestamp. In memory only, bounded by the outbox and
165    /// by [`custody::MAX_CUSTODY_RECEIPTS_PER_MESSAGE`]; losing it at a
166    /// restart costs one duplicate deposit, which the custodian absorbs.
167    pub(crate) custody_receipts: HashMap<MessageId, HashMap<String, i64>>,
168
169    /// When the custody store was last swept for expired records.
170    custody_last_sweep: Instant,
171
172    /// Shared mutable state.
173    shared_state: Arc<Mutex<SharedState>>,
174
175    /// Messages awaiting delivery/acknowledgment (store-and-forward outbox).
176    outbox: HashMap<MessageId, OutboxEntry>,
177
178    /// Transient staging for outbox re-seal provenance, keyed by message id.
179    /// Populated at send time (where the plaintext is in scope) and consumed
180    /// when the outbox entry is first created (which happens deep in the send/
181    /// retry machinery, from the already-sealed `Message`). Once consumed it
182    /// lives on the `OutboxEntry` itself. See [`OutboxReseal`].
183    pending_reseal: HashMap<MessageId, OutboxReseal>,
184
185    /// Dedicated outbox for file chunk messages, separate from the main outbox
186    /// to prevent large file transfers from evicting regular messages.
187    media_outbox: HashMap<MessageId, OutboxEntry>,
188
189    /// Consecutive unreachable-park counter per recipient for plain DMs,
190    /// driving the escalating reachability-probe interval on every carrier
191    /// (see `handle_recipient_unreachable_for_message` —
192    /// mirrors `WelcomeLifecycleRecord::unreachable_parks`). Reset on every
193    /// reachability edge (`flush_outbox_for_peer_via` / `flush_outbox_all`) and
194    /// on delivery; pruned alongside `cleanup_outbox` so only peers that
195    /// still hold outbox entries can retain a counter. While live, ACK
196    /// exhaustion for the recipient's plain DMs re-parks instead of
197    /// settling terminally (`try_repark_exhausted_dm`). In-memory only: a
198    /// restart re-drives the outbox anyway, which is itself a fresh probe.
199    dm_unreachable_parks: HashMap<String, u32>,
200
201    /// Delivery acknowledgements no carrier could take when they were owed,
202    /// with the transport the acknowledged frame arrived on and when they
203    /// were held. Re-routed on the next carrier-level edge
204    /// (`flush_unrouted_acks` from `flush_outbox_all`); bounded by
205    /// `MAX_UNROUTED_ACKS` and `UNROUTED_ACK_TTL`. In-memory only.
206    unrouted_acks: VecDeque<(Message, TransportType, Instant)>,
207
208    /// Per-recipient reachability claims, keyed by recipient and carrier.
209    ///
210    /// The generalisation of the counter above: that one records *how often*
211    /// a recipient has been parked, this one records *what a carrier said*
212    /// about reaching them, so a decision can be made before the send rather
213    /// than only after it failed. Written by the same producers (a gateway
214    /// verdict, a gateway presence answer), read at the send and carrying
215    /// seams. In-memory only, and absent facts mean today's behaviour.
216    pub(crate) reachability: reachability::ReachabilityFacts,
217
218    /// Capability tokens the attached gateway daemon advertised.
219    ///
220    /// Delivered at attach, before the bridge reports the carrier available,
221    /// and cleared when the carrier drops: a stale advertisement outlives the
222    /// gateway that made it, and a reconnect may land on a different one.
223    ///
224    /// Stored and never read on a decision. The backbone behind the daemon
225    /// is the gateway's own property and reaches this device only as a
226    /// `backbone_<kind>_v1` token in this set; the set is for an application
227    /// to show, and the first production reader would turn a string set by
228    /// whoever holds the socket into a routing input (ADR 0026).
229    ///
230    /// Kept apart from `group_mesh.relay_capabilities` deliberately, though
231    /// both are capability sets from a gateway. That one gates the relay
232    /// group-broadcast path, and a token advertised by whatever box is
233    /// plugged into the venue Wi-Fi must not be able to open it.
234    gateway_capabilities: HashSet<String>,
235
236    /// MLS manager for end-to-end encryption.
237    mls_manager: Option<Arc<RwLock<MlsManager>>>,
238
239    /// Pending messages waiting for session establishment (recipient -> messages).
240    pending_encrypted_messages: HashMap<String, Vec<PendingMessage>>,
241
242    /// Terminal message settlements produced while restoring, held until the
243    /// event pipeline is live.
244    ///
245    /// Restore runs inside `initialize_mls`, which apps routinely call before
246    /// installing an event callback — so a `message_failed` emitted there would
247    /// be dropped, and the app would keep an id that never resolves. `start()`
248    /// drains this, mirroring how restored media descriptors already wait to be
249    /// announced.
250    ///
251    /// Explicitly capped at [`MAX_DEFERRED_RESTORE_SETTLEMENTS`] rather than
252    /// left to the restore caps that feed it. Those caps do bound it, but they
253    /// bound it as a *sum* across every category, and nothing drains this until
254    /// `start()` — which an app that only ever calls `initialize_mls`, or that
255    /// retries it against a failing store, may never reach.
256    deferred_restore_settlements: Vec<Event>,
257
258    /// Number of settlements suppressed by the cap above, so the count is
259    /// reported even though the individual events are not.
260    suppressed_restore_settlements: usize,
261
262    /// Earliest wall-clock expiry in `pending_encrypted_messages`.
263    ///
264    /// `process()` consults this before scanning the bounded queue, avoiding an
265    /// O(N) walk on every 100 ms tick while preserving exact configured expiry.
266    /// A stale early deadline is harmless: it causes one extra scan, which then
267    /// recomputes the real minimum.
268    next_pending_message_expiry: Option<DateTime<Utc>>,
269
270    /// Key packages received but not yet used (sender_id -> package).
271    pub(crate) pending_key_packages: HashMap<String, ReceivedKeyPackage>,
272
273    /// Peers we have pushed our key package to, with when we last did and how
274    /// many times the push has been re-armed since.
275    ///
276    /// The instant is what lets a push that produced no session be re-armed
277    /// (`Self::rearm_key_package_for_peer`) instead of standing in for a
278    /// delivery it never proved; the count is that re-arm's backoff.
279    pub(crate) key_package_sent_to: HashMap<String, (Instant, u32)>,
280
281    /// All discovered/connected peers, tracked independently of encryption.
282    /// Used by service discovery to know who to broadcast queries to.
283    /// Values are last-seen instants: refreshed on every discovery signal,
284    /// swept by [`Self::prune_stale_known_peers`] after `KNOWN_PEER_TTL_SECS`,
285    /// and used to pick the least-recently-seen victim when an insert hits
286    /// `MAX_KNOWN_PEERS`.
287    known_peers: HashMap<String, Instant>,
288
289    /// Sessions confirmed established (received Welcome or successful decrypt).
290    /// Only encrypt messages when the session is confirmed to avoid race conditions.
291    confirmed_sessions: std::collections::HashSet<String>,
292
293    /// Peers that have demonstrated they run MLS, used by
294    /// [`Self::accept_plaintext_content`] to reject cleartext claiming to come
295    /// from an encryption-capable peer.
296    ///
297    /// # Why this is not `confirmed_sessions`, and not a storage read
298    ///
299    /// The gate used to ask `is_session_confirmed`, which reads the
300    /// `session_states` protocol-state record. That record lives in the
301    /// install-scoped app container, where an attacker with write access can
302    /// simply **delete** it: restore then treats absence as `Pending` (it must
303    /// — see `bootstrap_missing_session_state`), the peer drops out of
304    /// `confirmed_sessions`, and the gate opens for unauthenticated cleartext
305    /// carrying an attacker-chosen `sender`. Sealing the record does not help;
306    /// a seal authenticates bytes that are present, and this attack removes
307    /// them. So the signal has to come from somewhere the app container cannot
308    /// reach.
309    ///
310    /// Both sources here are credential-store-resident: the MLS session list
311    /// and the durable capability records
312    /// ([`storage_keys::ENCRYPTION_CAPABLE_PEERS`]). Neither is sufficient
313    /// alone. A session can exist for a peer that has never signed a control
314    /// frame we verified (it is established from key packages, and the Welcome
315    /// path marks capability without a signature), and a record can outlive the
316    /// session it was learned alongside. The union is what actually tracks
317    /// "this peer speaks MLS".
318    ///
319    /// # Monotone within a run — deliberately, and this is load-bearing
320    ///
321    /// Entries are added and **never removed on session teardown**. That looks
322    /// like a leak and is in fact the whole security property. Teardown is
323    /// reachable from an *unauthenticated* frame: an injected `__MLS_ENC__`
324    /// classifies as `SessionDesync`, `schedule_session_rekey` tears down our
325    /// session and advertises a `session_reset` key package, and the peer's
326    /// `handle_key_package_message` then deletes its own. A set that shrank on
327    /// teardown would therefore let one injected frame re-open the very gate
328    /// this field exists to hold shut — moving the attack from "needs
329    /// app-container write access" to "needs one forged packet", which is
330    /// strictly worse than the bug it fixes.
331    ///
332    /// Keeping a peer after teardown costs nothing real: a peer that spoke MLS
333    /// a moment ago is still encryption-capable, so its cleartext is still a
334    /// downgrade. The invariant to preserve is one-directional — this set may
335    /// **over**-approximate (which fails closed) but must never
336    /// **under**-approximate (which fails open). Anything that populates it may
337    /// be lossy; nothing may prune it.
338    ///
339    /// There is no longer any way out at all, and that is now *correct* rather
340    /// than merely safe. The old escape hatch (`reset_tofu_for_peer`) meant
341    /// "this identity has re-keyed, treat it as new" — a thing that could
342    /// happen when an identity was a name. Under self-certifying addressing an
343    /// address is the hash of its key, so a peer that re-keys becomes a
344    /// *different address*: nothing about the old one ever stops being true,
345    /// and forgetting it could only ever be wrong.
346    ///
347    /// Bounded by [`MAX_ENCRYPTION_CAPABLE_PEERS`], enforced as a refusal rather
348    /// than an eviction so the monotonicity above survives the cap — see
349    /// [`Self::mark_encryption_capable`].
350    encryption_capable_peers: std::collections::HashSet<String>,
351
352    /// Peers whose key package advertised the compact MLS envelope
353    /// ([`MLS_ENVELOPE_COMPACT_V1`] in `env_versions`), so
354    /// `seal_encrypted_content` may emit it instead of the legacy JSON form.
355    /// Learned from key-package exchange, persisted per peer as
356    /// [`PeerCapabilities`], and repopulated by `restore_peer_capabilities`
357    /// on `initialize_mls` — unlike the transport manager's binary-wire
358    /// registry, which stays in-memory because direct connections re-exchange
359    /// key packages anyway. Bounded like `key_package_sent_to` (it is keyed
360    /// by the wire-claimed sender).
361    peer_compact_envelope: std::collections::HashSet<String>,
362
363    /// Peers whose key package advertised that they verify the
364    /// freshness-bound control payload ([`CTRL_SIGN_V2`] in `ctrl_versions`),
365    /// so control frames addressed to them are signed under
366    /// `offline-ctrl-v2`. Same lifecycle as `peer_compact_envelope` above:
367    /// learned from key-package exchange, persisted as [`PeerCapabilities`],
368    /// restored on `initialize_mls`, bounded like `key_package_sent_to`.
369    ///
370    /// This is the **send** half, and it is a hint: forgetting a peer costs
371    /// them the older payload, which they still verify. The **accept** half is
372    /// [`Self::control_freshness_peers`], which is a ratchet and is not
373    /// allowed to forget.
374    ///
375    /// [`CTRL_SIGN_V2`]: offline_protocol_sealed::CTRL_SIGN_V2
376    peer_ctrl_freshness: std::collections::HashSet<String>,
377
378    /// Peers that have presented a control-frame signature over the
379    /// freshness-bound payload, so their frames under the older one are
380    /// refused.
381    ///
382    /// A **ratchet**, and the difference from every capability set above is
383    /// the whole point: those record what a peer said and may be forgotten
384    /// harmlessly, this records what a peer *proved* and forgetting it
385    /// re-opens the replay it exists to close. It is durable (in the peer's
386    /// [`EncryptionCapableEntry`], not in [`PeerCapabilities`], which is
387    /// overwritten wholesale by every key package) and has no removal path
388    /// short of forgetting the peer entirely.
389    ///
390    /// A strict subset of [`Self::encryption_capable_peers`] by construction,
391    /// so `MAX_ENCRYPTION_CAPABLE_PEERS` bounds it too. See
392    /// `record_control_freshness_proved` for why the ordering that makes that
393    /// true is load-bearing.
394    pub(crate) control_freshness_peers: std::collections::HashSet<String>,
395
396    /// Per-peer high-water mark: the signed timestamp of the most recent
397    /// session reset acted on from that peer.
398    ///
399    /// A reset is honoured only when its signed timestamp is strictly newer
400    /// than this, which is what stops one captured reset frame from being
401    /// spent again and again inside the freshness window. Chosen over a set of
402    /// spent frame ids because it is one integer per peer instead of a list
403    /// that grows with traffic, and because it is strictly stronger: it
404    /// refuses *every* older reset, including ones this node has no memory of.
405    ///
406    /// Durable in the peer's [`EncryptionCapableEntry`], and bounded by
407    /// construction like [`Self::control_freshness_peers`]: entries are only
408    /// written for peers the capped encryption-capable set accepted.
409    pub(crate) control_reset_watermark: std::collections::HashMap<String, i64>,
410
411    /// Peers whose key package advertised the sealed rich payload
412    /// ([`RICH_PAYLOAD_V1`] in `rich_versions`), so the send path may seal
413    /// rich extras (reply context, rich media metadata, forward attribution)
414    /// inside the `__RICH_V1__` body. Same lifecycle as
415    /// `peer_compact_envelope` above: learned from key-package exchange,
416    /// persisted, restored on `initialize_mls`, bounded like
417    /// `key_package_sent_to`. Forgetting a peer only costs silently dropped
418    /// rich extras — never a cleartext fallback.
419    peer_rich_payload: std::collections::HashSet<String>,
420
421    /// Peers whose key package advertised replicated-document sync
422    /// ([`DATA_SYNC_V1`] in `data_versions`), so the send path may push
423    /// `__DATA_V1__` frames to them. Same lifecycle as the two capability
424    /// sets above: learned from key-package exchange, persisted, restored on
425    /// `initialize_mls`, bounded like `key_package_sent_to`.
426    ///
427    /// Forgetting a peer costs replication with them until the next live
428    /// exchange, which is worse than it sounds: documents stay editable on
429    /// both sides and diverge quietly, so the symptom is not an error but
430    /// two people looking at different text. It is why this set is restored
431    /// rather than relearned.
432    ///
433    /// [`DATA_SYNC_V1`]: crate::protocol::types::DATA_SYNC_V1
434    peer_data_sync: std::collections::HashSet<String>,
435
436    /// Peers whose sealed-rich-payload support we learned *indirectly*: a
437    /// group inviter attested it on the Add commit (to existing members) or
438    /// the Welcome (to the joining member), because the members of a group
439    /// never directly exchange key packages with everyone else. Kept
440    /// separate from `peer_rich_payload` (direct self-advertisement) so
441    /// direct knowledge can stay authoritative: any directly received key
442    /// package from a peer evicts its attested entry. Consulted only by
443    /// `group_rich_seal_active` — never DM sealing (which always has direct
444    /// knowledge: session establishment exchanges key packages) and never
445    /// envelope selection (a stale attestation there could corrupt
446    /// decoding; here the worst case is one member rendering a literal
447    /// `__RICH_V1__` body). Persisted inside `PeerCapabilities`, restored
448    /// on `initialize_mls`, bounded like `key_package_sent_to`.
449    peer_rich_attested: std::collections::HashSet<String>,
450
451    /// Peers whose key package advertised *group* document replication
452    /// ([`DATA_GROUP_V1`] in `data_versions`), so a group they share with
453    /// this device may carry `__DATA_V1__` frames.
454    ///
455    /// Separate from `peer_data_sync` because the two entries mean
456    /// different things and a peer can advertise the first without the
457    /// second: an install predating group spaces replicates 1:1 perfectly
458    /// well and would render a group sync frame as chat text. Same
459    /// lifecycle as every capability set: learned from key-package
460    /// exchange, persisted, restored on `initialize_mls`, bounded like
461    /// `key_package_sent_to`.
462    ///
463    /// [`DATA_GROUP_V1`]: crate::protocol::types::DATA_GROUP_V1
464    peer_data_group: std::collections::HashSet<String>,
465
466    /// Peers whose *group* replication support we learned indirectly, from
467    /// an inviter's attestation on the Add commit or Welcome.
468    ///
469    /// The group analogue of `peer_rich_attested`, and load-bearing for the
470    /// same structural reason: members of a group never exchange key
471    /// packages with each other, so without attestation a group would
472    /// replicate only among whichever members happened to have met
473    /// directly. Direct knowledge stays authoritative — a key package from
474    /// the peer evicts its attested entry. Consulted only by
475    /// `group_data_sync_active`, never by 1:1 sync.
476    peer_data_group_attested: std::collections::HashSet<String>,
477
478    /// Peers whose key package advertised attachment and snapshot carriage
479    /// over the media path ([`DATA_MEDIA_V1`] in `data_versions`), so this
480    /// device may ask them for a blob and may hand them a document too large
481    /// to travel inside a sync frame.
482    ///
483    /// A third set rather than a flag on the first, for the same reason
484    /// `peer_data_group` is separate: a peer can advertise 1:1 replication
485    /// without this, and toward such a peer a data-purposed media transfer
486    /// arrives as an ordinary received file. Same lifecycle as every
487    /// capability set: learned from key-package exchange, persisted inside
488    /// `PeerCapabilities`, restored on `initialize_mls`, bounded like
489    /// `key_package_sent_to`.
490    ///
491    /// [`DATA_MEDIA_V1`]: crate::protocol::types::DATA_MEDIA_V1
492    peer_data_media: std::collections::HashSet<String>,
493
494    /// Peers whose key package advertised document removals
495    /// ([`DATA_TOMBSTONE_V1`] in `data_versions`), so a version offer toward
496    /// them carries the `gone` field.
497    ///
498    /// A fourth set for the same reason as the third, with one difference
499    /// worth keeping in mind: this one gates traffic, not safety. A peer
500    /// missing from it ignores the field rather than mishandling it, and
501    /// this device still refuses that peer's offers of removed content
502    /// against its own floor.
503    ///
504    /// [`DATA_TOMBSTONE_V1`]: crate::protocol::types::DATA_TOMBSTONE_V1
505    peer_data_tombstones: std::collections::HashSet<String>,
506
507    /// Peers whose key package advertised interest-scoped replication
508    /// ([`DATA_INTEREST_V1`] in `data_versions`), so a version offer toward
509    /// them carries the `want` field.
510    ///
511    /// A fifth set, and a traffic gate like the fourth: a peer missing from
512    /// it answers with everything it holds, and this device refuses what it
513    /// did not ask for on arrival.
514    ///
515    /// [`DATA_INTEREST_V1`]: crate::protocol::types::DATA_INTEREST_V1
516    peer_data_interest: std::collections::HashSet<String>,
517
518    /// Peers whose key package advertised attachment bytes inside a group
519    /// ([`DATA_GROUP_BLOB_V1`] in `data_versions`).
520    ///
521    /// Direct knowledge only. Members of a group do not exchange key
522    /// packages with each other, so absence from this set is "we have not
523    /// heard" far more often than "they cannot", which is why the attested
524    /// sibling below exists and why the refusal reads both.
525    ///
526    /// [`DATA_GROUP_BLOB_V1`]: crate::protocol::types::DATA_GROUP_BLOB_V1
527    peer_data_group_blob: std::collections::HashSet<String>,
528
529    /// Peers an inviter attested carry attachment bytes inside a group.
530    ///
531    /// The sibling of `peer_data_group_attested`, and it exists for the same
532    /// reason: this is the only way to learn anything about a member whose
533    /// key package this device has never seen. Evicted by any directly
534    /// received key package, in either direction.
535    peer_data_group_blob_attested: std::collections::HashSet<String>,
536
537    /// Peers whose key package advertised the custody receipt
538    /// ([`DATA_CUSTODY_V1`] in `data_versions`), so this device may answer
539    /// their deposits with one. Gates the receipt and nothing else: a deposit
540    /// is judged by the quotas. Persisted inside `PeerCapabilities`, restored
541    /// on `initialize_mls`, bounded like `key_package_sent_to`.
542    ///
543    /// [`DATA_CUSTODY_V1`]: crate::protocol::types::DATA_CUSTODY_V1
544    peer_data_custody: std::collections::HashSet<String>,
545
546    /// Peers already flagged with a `PlaintextSend` security warning, so the
547    /// explicit-opt-out plaintext path warns once per peer instead of once
548    /// per message.
549    pub(crate) plaintext_send_warned: std::collections::HashSet<String>,
550
551    /// Peers already flagged with a `PlaintextReceiveRejected` security
552    /// warning, so a chatty legacy or malicious peer warns once per peer
553    /// instead of once per rejected message. Keys are wire-claimed
554    /// (attacker-controllable) sender ids, so the set is bounded: it resets
555    /// at `MAX_PLAINTEXT_RECEIVE_WARNED_PEERS` instead of growing without
556    /// limit.
557    pub(crate) plaintext_receive_warned: std::collections::HashSet<String>,
558
559    /// Peers whose durable `encryption_capable_peers` record is known to be on
560    /// disk — either restored from it at boot or written successfully this run.
561    ///
562    /// Purely a write-elision cache for
563    /// [`OfflineProtocol::record_encryption_capable`]: a verified control frame
564    /// arrives on chatty prefixes (`__TYPING__`, `__PRESENCE__`), and the record
565    /// it would rewrite carries no field any decision reads. Tracking *landed
566    /// writes* rather than set membership is what keeps a best-effort storage
567    /// failure retryable on the peer's next frame instead of stranded for the
568    /// process.
569    ///
570    /// A subset of [`Self::encryption_capable_peers`] by construction, so
571    /// `MAX_ENCRYPTION_CAPABLE_PEERS` bounds it too.
572    pub(crate) encryption_capable_persisted: HashSet<String>,
573
574    /// Which control-gate rejection codes have already been reported per peer,
575    /// as a bitmask (see `OfflineProtocol::control_gate_warning_bit`), so a
576    /// peer whose control traffic keeps being refused warns once per code
577    /// instead of once per frame.
578    ///
579    /// Keys are wire-claimed (attacker-controllable) sender ids, so the map is
580    /// bounded: it resets at `MAX_CONTROL_GATE_WARNED_PEERS` instead of growing
581    /// without limit.
582    pub(crate) control_gate_warned: HashMap<String, u8>,
583
584    /// Bounded pending decryption queue for encrypted messages received before
585    /// the MLS session is ready.
586    pub(crate) pending_queue: PendingDecryptionQueue,
587
588    /// Secure storage for MLS/key material and SDK-owned secrets.
589    secure_storage: Option<Arc<dyn MlsStorage>>,
590
591    /// Install-scoped storage for restartable message-plane and protocol state.
592    protocol_state_storage: Option<Arc<dyn ProtocolStateStorage>>,
593
594    /// Seals sensitive protocol-state records before they reach the
595    /// install-scoped store, with a per-install key held in `secure_storage`.
596    ///
597    /// `None` until that key is available (and if it never becomes available,
598    /// for the whole session). Sealed categories then fail *closed*: they are
599    /// not persisted at all rather than written in the clear, since losing
600    /// crash recovery is recoverable and losing at-rest confidentiality is not.
601    /// See `state_crypto` and `restore_or_init_state_record_key`.
602    ///
603    /// Always belongs to the currently attached `secure_storage` — it is
604    /// re-derived, never carried across a storage swap.
605    state_record_cipher: Option<state_crypto::StateRecordCipher>,
606
607    /// Open replicated documents and their per-space indexes.
608    #[cfg(feature = "data")]
609    pub(crate) data: data::DataLayer,
610
611    /// When each peer was last offered our document versions.
612    ///
613    /// Neighbour rediscovery is not a rare event: a peer walking in and out
614    /// of Bluetooth range fires it repeatedly, and an offer per discovery
615    /// would put a frame on the mesh every time. The offer is not urgent
616    /// (anything committed locally is pushed as it happens) and it is not
617    /// load-bearing (the next trigger repeats it), so it is exactly the kind
618    /// of traffic that should be rate limited rather than merely small.
619    #[cfg(feature = "data")]
620    pub(crate) last_data_sync_offer: HashMap<String, Instant>,
621
622    /// Settle offers waiting for local commits to a space to go quiet, keyed
623    /// by space: when the offer is due, and the documents committed since
624    /// the last one. Pushed out by every local commit and removed when it
625    /// fires. See [`DATA_SYNC_SETTLE_DELAY`].
626    ///
627    /// [`DATA_SYNC_SETTLE_DELAY`]: crate::protocol::data_sync::DATA_SYNC_SETTLE_DELAY
628    #[cfg(feature = "data")]
629    pub(crate) data_sync_settle: HashMap<String, (Instant, std::collections::BTreeSet<String>)>,
630
631    /// Attachment fetches asked for and not yet answered, keyed by space and
632    /// blob hash, valued by the last sign that an answer is coming: the
633    /// moment the question went out, or the arrival of a chunk of its
634    /// answer.
635    ///
636    /// The refresh is what keeps this record's two jobs consistent. It bounds
637    /// how long a question is remembered, and it is also what admits the
638    /// bytes when they finally land, so a record that expired while its own
639    /// answer was arriving would discard a blob that fully crossed.
640    ///
641    /// Load-bearing for more than bookkeeping: arriving blob bytes are
642    /// admitted only against an entry here, checked when the transfer's
643    /// chunk 0 identifies it and again before the bytes reach the
644    /// application. Without it a peer could push blobs this device never
645    /// asked for and the application would be handed files nobody wanted.
646    ///
647    /// The bound it gives is on delivery and on the bulk of the buffering,
648    /// not on every byte: chunks need not arrive in order, so any that land
649    /// before chunk 0 are buffered before there is anything to judge, and
650    /// are released when it arrives. What remains is bounded by the media
651    /// layer's own resource caps, the same ones every unsolicited file
652    /// transfer has always been subject to.
653    ///
654    /// Gated on the data feature, which the record's own type now is: what
655    /// a fetch is waiting on, and what it has assembled so far, are facts
656    /// about the data layer and have no meaning without it.
657    #[cfg(feature = "data")]
658    pub(crate) pending_attachment_fetches:
659        HashMap<String, crate::protocol::data_sync::PendingFetch>,
660
661    /// Blob requests recently acted on, keyed by asking peer and blob hash.
662    ///
663    /// Its own map rather than a corner of `last_data_sync_offer`, because
664    /// this is the only rate-limit key a peer chooses freely: every other one
665    /// is a peer or a peer-and-group, bounded by a roster. Bounded here by
666    /// [`MAX_BLOB_REQUESTS_PER_WINDOW`] per peer and
667    /// [`MAX_BLOB_REQUEST_WINDOWS`] overall, and swept on every read.
668    ///
669    /// [`MAX_BLOB_REQUESTS_PER_WINDOW`]: crate::protocol::data_sync::MAX_BLOB_REQUESTS_PER_WINDOW
670    /// [`MAX_BLOB_REQUEST_WINDOWS`]: crate::protocol::data_sync::MAX_BLOB_REQUEST_WINDOWS
671    pub(crate) blob_request_windows: HashMap<String, Instant>,
672
673    /// Whether the MLS group list has been read into `group_mesh.members`
674    /// once this session, so the shared-group rediscovery sweep can see the
675    /// groups this device is in.
676    ///
677    /// That cache is filled on demand by group traffic and is empty after a
678    /// restart, so a sweep that only read it would find nothing on exactly
679    /// the launch where two members have drifted apart and neither is
680    /// editing. Enumerating is one key listing plus, per group not already
681    /// cached, the group-state read the next group send would have paid
682    /// anyway.
683    ///
684    /// One shot rather than per sweep because the cache stays complete once
685    /// filled: creating a group inserts, a Welcome inserts, and leaving
686    /// removes. Deliberately not a cold-start sweep, which was rejected for
687    /// putting an offer per member per group on the mesh at every launch;
688    /// this is per peer, only when that peer is actually in front of us, and
689    /// still behind the offer window.
690    #[cfg(feature = "data")]
691    pub(crate) group_spaces_enumerated: bool,
692
693    /// Lamport logical clock for causal message ordering.
694    /// Ticked on send, merged on receive.
695    lamport_clock: LamportClock,
696
697    /// Retry schedule for peers whose confirmation persistence failed.
698    confirmation_retry_due_at: HashMap<String, DateTime<Utc>>,
699
700    /// Probe schedule for pending sessions to guarantee post-restart convergence.
701    confirmation_probe_due_at: HashMap<String, DateTime<Utc>>,
702
703    /// Consecutive relay "recipient unreachable" verdicts per peer for the
704    /// session-confirmation probe. Drives an escalating backoff of
705    /// `confirmation_probe_due_at` (15s -> 600s cap, the same ladder the welcome
706    /// lifecycle uses) so a peer that established a session then vanished is not
707    /// probed every `CONFIRMATION_PROBE_INTERVAL_SECS` forever; a fleet of such
708    /// peers would otherwise exceed the relay's per-connection rate limit and
709    /// flap the connection. Reset on a reachability edge (`on_peer_presence`).
710    confirmation_probe_unreachable_parks: HashMap<String, u32>,
711
712    /// The confirmation probe each pending peer last sent. At most one probe
713    /// per peer lives in the outbox: a new one supersedes the last. Stacking a
714    /// fresh probe (new id, full retry ladder) every
715    /// `CONFIRMATION_PROBE_INTERVAL_SECS` on top of the unanswered ones filled
716    /// the outbox whenever no relay verdict (`unreachable` or
717    /// `relay_pushed`) arrived to back the schedule off, as on a mesh-only
718    /// carrier. Capacity eviction then failed real messages.
719    confirmation_probe_outstanding: HashMap<String, MessageId>,
720
721    /// The probe each pending peer's current one superseded. A relay verdict
722    /// finds its peer through the outbox entry, which the supersede removed,
723    /// so a verdict slower than `CONFIRMATION_PROBE_INTERVAL_SECS` would
724    /// otherwise be dropped and never back the schedule off, leaving the
725    /// peer probed every 5s against a relay that has said it is not there.
726    /// One id per peer, so this covers a verdict up to two intervals late;
727    /// one later than that is dropped, and the next probe's verdict backs
728    /// the schedule off instead.
729    confirmation_probe_superseded: HashMap<String, MessageId>,
730
731    /// Token bucket that caps how fast the RETRY/PROBE path
732    /// (`process_retry_queue`) re-sends, so a large backlog of resends to
733    /// unreachable peers cannot burst past the relay's per-connection rate limit
734    /// and trigger the disconnect->reconnect->reflood loop ("flapping"). Only
735    /// consulted when `RetryConfig::edge_driven_unreachable_dm` is opted in. It
736    /// bounds ONLY resends — first-attempt sends, ACKs, control frames and
737    /// handshakes take other paths and are never throttled, so live traffic
738    /// keeps full throughput/latency. `retry_drain_last` is None until first use.
739    retry_drain_tokens: f64,
740    retry_drain_last: Option<Instant>,
741
742    /// Rate-limit schedule for 1:1 session re-keys triggered by an epoch-desync
743    /// decrypt failure. Bounds the re-key to at most one per peer per
744    /// `REKEY_INTERVAL_SECS` so a peer replaying stale-epoch ciphertext (or an
745    /// injected wrong-epoch frame) cannot drive a re-key storm. The floor is
746    /// **never reset early** — not even by a successful decrypt on the healed
747    /// session — because a genuine re-fork and a replay are indistinguishable
748    /// here; it lapses only by the interval elapsing (see
749    /// `schedule_session_rekey`). In-memory only: a re-key is a live-connectivity
750    /// action, and a fresh desync after restart simply re-arms it.
751    rekey_due_at: HashMap<String, DateTime<Utc>>,
752
753    /// Outbound welcome lifecycle records keyed by peer id.
754    welcome_lifecycles: HashMap<String, WelcomeLifecycleRecord>,
755
756    /// Outbound connection requests still awaiting a transport outcome,
757    /// keyed by message id → recipient. Lets `on_transport_send_failed`
758    /// turn the relay's authoritative "recipient offline" DeliveryError
759    /// into a typed `ConnectionRequestUndeliverable` event instead of
760    /// silently discarding it (the welcome-only path never matches a
761    /// connection request's message id). Entries are dropped on emission
762    /// and on proof of delivery (the request's delivery ack, or an inbound
763    /// accept/reject from the recipient), and TTL-pruned on insert and at
764    /// read; bounded, so an app spamming requests cannot grow it
765    /// unboundedly.
766    pending_connection_requests: HashMap<String, PendingConnectionRequest>,
767
768    /// Backoff state for presence-driven welcome rescue, keyed by peer id.
769    /// Bounds how often an online-but-never-confirming peer triggers a
770    /// welcome re-arm/re-send (see `on_peer_presence`). Entries are dropped
771    /// lazily once the peer has no unconfirmed welcome left.
772    welcome_presence_rescue: HashMap<String, PresenceRescueThrottle>,
773
774    /// Peers for which we are the both-create "owner" (kept our own session
775    /// group on the lexicographic tiebreak) and are still awaiting a
776    /// *group-aware* proof that the peer adopted our group. While a peer is in
777    /// this set, only `decrypt_success` may confirm the session — a plaintext
778    /// confirmation probe/ack is NOT group-aware (it only proves the peer holds
779    /// *some* session, possibly its own pre-adoption group) and must not be
780    /// allowed to stop our Welcome retransmission, or the peer could be left
781    /// stranded on a divergent group. Persisted (see
782    /// `restore_both_create_awaiting_decrypt`) so an owner restart mid-convergence
783    /// keeps the gate, rather than letting a stale plaintext probe/ack confirm
784    /// prematurely. Mutate only via `mark_both_create_awaiting_decrypt` /
785    /// `clear_both_create_awaiting_decrypt` to keep memory and storage in sync.
786    both_create_awaiting_decrypt: std::collections::HashSet<String>,
787
788    /// Sink for MLS lifecycle telemetry.
789    mls_event_emitter: Arc<dyn MlsEventEmitter>,
790
791    /// Rate limiting policy for MLS failure event floods.
792    mls_event_rate_limiter: MlsEventRateLimiter,
793
794    /// Pre-install scrubber used by MLS emit sites before a sink is
795    /// installed (`enable_telemetry`, or `install_sink` beneath it). Once one
796    /// is installed, emit sites read `self.telemetry.scrubber` instead via
797    /// `current_scrubber()`.
798    /// Both scrubbers share `telemetry_fallback_secret` so opaque identifiers
799    /// observed by the legacy `MlsEventEmitter` stay consistent across the
800    /// install boundary.
801    telemetry_scrubber: Scrubber,
802
803    /// Per-instance fallback secret for identifier scrubbing. Random at
804    /// construction. Reused by both the pre-install `telemetry_scrubber`
805    /// and by any scrubber built inside `install_sink` (unless the
806    /// installed `TelemetryConfig` carries its own `scrub_secret`). Keeping
807    /// the fallback stable across installs means the legacy
808    /// `MlsEventEmitter` path observes consistent opaque IDs before and
809    /// after a sink is installed on the same protocol instance.
810    telemetry_fallback_secret: [u8; 16],
811
812    /// Whether the persistent per-install scrub secret has been loaded from
813    /// (or initialized into) secure storage yet. Starts `false`; set `true`
814    /// the first time `restore_or_init_scrub_secret` succeeds so the load is
815    /// idempotent across the two storage-entry paths
816    /// (`initialize_mls` also enables persistence, which would otherwise
817    /// re-load and rebuild the scrubber a second time).
818    telemetry_secret_persisted: bool,
819
820    /// Whether the persistent per-install Nostr signing secret has been
821    /// loaded from (or initialized into) secure storage and installed into
822    /// the Nostr transport yet. Same idempotency role across the two
823    /// storage-entry paths as `telemetry_secret_persisted`; see
824    /// `restore_or_init_nostr_signing_secret`.
825    nostr_secret_persisted: bool,
826
827    /// A Nostr signing secret that was installed into the transport but
828    /// could not be persisted (storage `store` failed). Kept so the next
829    /// `restore_or_init_nostr_signing_secret` attempt retries persisting
830    /// this same secret instead of rotating the install's relay-visible
831    /// identity again mid-session.
832    nostr_unpersisted_secret: Option<Zeroizing<[u8; 32]>>,
833
834    /// Installed telemetry context (sink + config + scrubber). `None` until
835    /// `enable_telemetry` installs one; thereafter shared with
836    /// `SharedState` via `Arc` clone so both emit paths dispatch through the
837    /// same configuration.
838    ///
839    /// The duplication with [`SharedState::telemetry`] is deliberate: MLS
840    /// lifecycle emission is driven from `&self` on `OfflineProtocol` and
841    /// does not hold the shared-state lock, while protocol-event emission
842    /// happens inside `SharedState::emit_event` under the lock. Each path
843    /// reads the context from whichever side it already has in hand, and
844    /// `install_sink` is the single writer that keeps both copies in sync
845    /// (guaranteed atomic from the caller's perspective because `&mut self`
846    /// excludes concurrent calls), and `detach_telemetry_pipe` the single
847    /// clearer.
848    pub(crate) telemetry: Option<Arc<TelemetryContext>>,
849
850    /// The running telemetry pipe, when `enable_telemetry` built one. Its
851    /// sink is what `telemetry` dispatches into; the pipe itself is kept so
852    /// the tick can wake it and `initialize_mls` can hand it storage.
853    #[cfg(feature = "telemetry-pipe")]
854    telemetry_pipe: Option<Arc<TelemetryPipe>>,
855
856    /// File transfer manager for chunking outbound and reassembling inbound media.
857    file_transfer_manager: FileTransferManager,
858
859    /// Stashed (content_type, media_metadata) from chunk-0 of incoming file transfers,
860    /// used to populate the FileReceived event once all chunks arrive.
861    pending_media_metadata: HashMap<String, PendingMediaMetadataEntry>,
862    /// Tracks outbound media transfer delivery progress keyed by file_id.
863    outbound_media_transfers: HashMap<String, OutboundMediaTransfer>,
864    /// Maps each outbound media chunk message ID to (file_id, chunk_index).
865    outbound_media_chunks: HashMap<MessageId, (String, u32)>,
866    /// Sliding-window state for outbound file transfers, keyed by file_id.
867    /// Chunks are only sent when the window has capacity (previous chunks ACKed).
868    outbound_media_windows: HashMap<String, OutboundTransferState>,
869    /// Descriptors of transfers that were in flight when the previous process
870    /// died, restored from storage. `start()` emits one `MediaResendRequired`
871    /// event each but deliberately does NOT drain them: entries stay parked
872    /// (and persisted) until a same-`file_id` resend consumes them — after
873    /// `send_media_with` checksum-validates the re-supplied bytes against
874    /// the descriptor — or the restore TTL prunes them, so an app that
875    /// misses the signal gets it again next restart.
876    restored_media_descriptors: HashMap<String, MediaTransferDescriptor>,
877
878    /// Mesh service registry and handler (extracted crate).
879    mesh_services: MeshServices,
880
881    /// Bundled state for mesh group messaging (member cache, dedup, pending commits).
882    pub(crate) group_mesh: crate::group_mesh::GroupMeshState,
883
884    /// Set of blocked user IDs. Messages from blocked users are silently
885    /// dropped (no ACK, no event). Persisted via `ProtocolStateStorage`.
886    blocked_users: HashSet<String>,
887
888    /// Timestamp of the last `kick_pending_session_reconciliation` execution.
889    /// Used to throttle reconciliation to avoid expensive storage I/O
890    /// (list_sessions → Keychain/Keystore) on every process tick / receive poll.
891    last_reconciliation_at: Option<Instant>,
892
893    /// Instant of the last periodic `MetricsFrame` emission, used to rate
894    /// the telemetry aggregator to `TelemetryConfig::metrics_cadence`.
895    last_metrics_emit_at: Option<Instant>,
896
897    /// Last observed per-transport status map, used by the telemetry
898    /// aggregator to diff against the current map and emit one
899    /// `TransportStateEvent` per transition.
900    transport_status_snapshot: HashMap<TransportType, TransportStatus>,
901
902    /// Last observed (battery, charging, relay_role) snapshot, used by the
903    /// telemetry aggregator to fire `DeviceCapabilitySnapshot` on change.
904    device_capability_snapshot: Option<DeviceSnap>,
905
906    /// The Lamport clock value at the time of the last storage write.
907    /// Used to debounce `persist_lamport_clock()` — only write when the
908    /// in-memory value has advanced past this by `LAMPORT_PERSIST_INTERVAL`
909    /// ticks. On crash, at most `LAMPORT_PERSIST_INTERVAL` ticks are lost,
910    /// which is harmless for a logical clock (the gap is absorbed by the
911    /// next merge with any peer).
912    last_persisted_lamport: u64,
913
914    /// Receive-side changes to the deduplicator's seen set since it was last
915    /// written. Drives the batched write in `persist_dedup_seen_if_due`;
916    /// see `DedupSeenRecord` for why the set is persisted at all.
917    dedup_dirty: u32,
918
919    /// When the seen set was last written (or restored), for the time half of
920    /// the batching rule. Starts at construction so the first write waits for
921    /// either the interval or the dirty threshold like every later one.
922    dedup_last_persist: Instant,
923
924    /// The Nostr receive watermark last written to storage, or `None` if this
925    /// session has neither written nor restored one. Debounces
926    /// `persist_nostr_watermark()` the same way `last_persisted_lamport`
927    /// debounces the clock.
928    ///
929    /// Deliberately *not* captured for `initialize_mls` rollback, matching
930    /// where the restore itself runs: the mark lives in the transport, which
931    /// the rollback cannot reach, and re-installing a durable value that only
932    /// ever moves forward is not something a failed MLS restore needs undone.
933    last_persisted_nostr_watermark: Option<i64>,
934
935    /// Which MLS key package stands in each published Nostr slot.
936    ///
937    /// Persisted, because the alternative to remembering it is republishing
938    /// under fresh slot ids on every launch — leaving the old records standing
939    /// with packages we would no longer track for consumption.
940    nostr_publication_slots: Vec<nostr_publication::NostrPublicationSlot>,
941
942    /// Slot ids published during *this* process.
943    ///
944    /// Deliberately not persisted: an addressable record lives on the relays,
945    /// so a launch cannot know which of them still hold it. Publishing each
946    /// slot once per process is the cheap way to be sure — it replaces rather
947    /// than accumulates, so the cost of being wrong is one redundant event.
948    nostr_published_slots: HashSet<String>,
949
950    /// When the publication slots were last re-scanned, throttling the MLS
951    /// storage reads that scan costs. See `nostr_slot_refresh_due`.
952    last_nostr_slot_refresh: Option<Instant>,
953
954    /// Per-slot republish backoff after publications that never reached a
955    /// relay. Memory-only, and pruned to the live slot ids each refresh.
956    nostr_publication_backoff: HashMap<String, nostr_publication::PublicationBackoff>,
957
958    /// When the slot-exhaustion security warning was last emitted, suppressing
959    /// repeats for a cause that by nature persists.
960    last_nostr_slot_warning: Option<Instant>,
961
962    /// The username this install has published a discovery claim for, as last
963    /// persisted. `None` means no claim stands.
964    ///
965    /// Persisted, because it is the only thing that knows *which* name to
966    /// retract when the profile changes or the feature is turned off. See
967    /// `storage_keys::NOSTR_DISCOVERY_CLAIM`.
968    nostr_discovery_claim: Option<Username>,
969
970    /// Names whose tombstone has not yet reached a relay, oldest first.
971    ///
972    /// Persisted beside the claim, and for a stronger reason than the claim
973    /// is: the claim can be rebuilt from `config.profile`, while a retracted
974    /// name has no other record anywhere once the profile has moved on.
975    /// Dropping it before the tombstone lands strands a human-readable name in
976    /// a public directory pointing at an address whose key packages are still
977    /// being published, so nothing downstream expires it.
978    nostr_discovery_retracting: Vec<Username>,
979
980    /// Whether the standing claim has been published during *this* process.
981    ///
982    /// Not persisted, for the same reason `nostr_published_slots` is not: an
983    /// addressable record lives on the relays and a launch cannot know which
984    /// of them still hold it. Republishing once per process replaces rather
985    /// than accumulates.
986    nostr_discovery_published: bool,
987
988    /// Republish backoff for the discovery claim, keyed by its tag.
989    ///
990    /// Memory-only and structurally identical to
991    /// `nostr_publication_backoff`: a relay that rejects kind 30777 outright
992    /// would otherwise be retried once per refresh forever.
993    nostr_discovery_backoff: HashMap<String, nostr_publication::PublicationBackoff>,
994
995    /// When the discovery claim was last re-examined, throttling the tick.
996    last_nostr_discovery_refresh: Option<Instant>,
997
998    /// In-flight username resolutions, keyed by query id.
999    ///
1000    /// A resolution accumulates every verified claim for its username and
1001    /// emits **one** event carrying the whole set. See
1002    /// `nostr_discovery::PendingResolution` for why the set is the only thing
1003    /// that is ever emitted.
1004    nostr_resolutions: HashMap<String, nostr_discovery::PendingResolution>,
1005
1006    /// Username lookups requested but not yet minted into a relay query, with
1007    /// the time each was asked for.
1008    ///
1009    /// The transport holds the queue; this holds the *deadline*. They are
1010    /// separate because minting is what may never happen: the platform pumps
1011    /// queries only while the relay socket is up, so a lookup requested offline
1012    /// would otherwise have no clock running behind it and no event to arrive.
1013    /// Bounded by the transport's own resolve-queue ceiling, since an entry is
1014    /// recorded only when the transport accepts the lookup.
1015    nostr_resolution_requests: HashMap<Username, Instant>,
1016
1017    /// When the push key-package pool-exhaustion warning was last emitted.
1018    ///
1019    /// Suppressed for the same reason the slot warning is: the condition is a
1020    /// pool at its ceiling, which persists until packages are consumed or
1021    /// expire, and every push while it holds would otherwise emit.
1022    last_push_key_package_warning: Option<Instant>,
1023
1024    /// When the last `GatewayAddressDeclarationRefused` and
1025    /// `GatewayAddressBindingMismatch` warnings were emitted, for the same
1026    /// suppression the push-key-package warning uses.
1027    last_gateway_refusal_warning: Option<Instant>,
1028    last_gateway_binding_mismatch_warning: Option<Instant>,
1029}
1030
1031impl Drop for OfflineProtocol {
1032    fn drop(&mut self) {
1033        // Flush debounced Lamport clock so no ticks are lost when the
1034        // protocol is dropped without an explicit stop() call.
1035        self.flush_lamport_clock();
1036        self.flush_nostr_watermark();
1037        // And the deduplicator's seen set, whose write is batched the same
1038        // way: a copy of a message received in the last few seconds before
1039        // the drop would otherwise be re-processed by the next launch.
1040        self.flush_dedup_seen();
1041        // Same reason: edits batch before they reach a record, so without a
1042        // flush here the debounce window between an edit and its delta is a
1043        // window in which work is lost.
1044        #[cfg(feature = "data")]
1045        let _ = self.data_flush_all();
1046    }
1047}
1048
1049#[cfg(test)]
1050struct TestProtocolStateStorage {
1051    storage: Arc<dyn MlsStorage>,
1052}
1053
1054/// Maps the fixture's MLS-storage failures onto the protocol-state contract,
1055/// mirroring what the UniFFI adapter does for real providers.
1056#[cfg(test)]
1057pub(crate) fn map_test_storage_error(
1058    error: offline_protocol_mls::StorageError,
1059) -> crate::ProtocolStateError {
1060    use crate::ProtocolStateError as P;
1061    use offline_protocol_mls::StorageError as S;
1062    match error {
1063        S::KeyNotFound(detail) => P::NotFound(detail),
1064        S::CorruptedData(detail) => P::Corrupted(detail),
1065        S::StoreFailed(detail) => P::StoreFailed(detail),
1066        S::LoadFailed(detail) => P::LoadFailed(detail),
1067        S::DeleteFailed(detail) => P::DeleteFailed(detail),
1068        S::Unavailable(detail) => P::LoadFailed(detail),
1069        // Required by `#[non_exhaustive]` on StorageError. This fixture mirrors
1070        // the UniFFI adapter, whose own fallback also degrades to `LoadFailed`.
1071        ref other => P::LoadFailed(other.to_string()),
1072    }
1073}
1074
1075#[cfg(test)]
1076impl ProtocolStateStorage for TestProtocolStateStorage {
1077    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> crate::ProtocolStateResult<()> {
1078        self.storage
1079            .store(key_type, key_id, data)
1080            .map_err(map_test_storage_error)
1081    }
1082
1083    fn load(&self, key_type: &str, key_id: &str) -> crate::ProtocolStateResult<Option<Vec<u8>>> {
1084        self.storage
1085            .load(key_type, key_id)
1086            .map_err(map_test_storage_error)
1087    }
1088
1089    fn delete(&self, key_type: &str, key_id: &str) -> crate::ProtocolStateResult<()> {
1090        self.storage
1091            .delete(key_type, key_id)
1092            .map_err(map_test_storage_error)
1093    }
1094
1095    fn list_keys(&self, key_type: &str) -> crate::ProtocolStateResult<Vec<String>> {
1096        self.storage
1097            .list_keys(key_type)
1098            .map_err(map_test_storage_error)
1099    }
1100}
1101
1102impl OfflineProtocol {
1103    /// Creates a new protocol instance.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// * `config` - Protocol configuration
1108    ///
1109    /// # Returns
1110    ///
1111    /// Returns `Ok(OfflineProtocol)` if successful, `Err` if configuration is invalid.
1112    pub fn new(config: ProtocolConfig) -> Result<Self> {
1113        // Validate configuration
1114        config.validate()?;
1115
1116        // Create transport selector for DORS
1117        let transport_selector = TransportSelector::with_config(config.dors.clone());
1118
1119        // Create transport manager
1120        let transport_manager = TransportManager::new(transport_selector);
1121
1122        // Per-instance fallback secret for identifier scrubbing. Stable for
1123        // the life of this protocol instance so opaque IDs stay consistent
1124        // across any later `install_telemetry_sink` call that does not
1125        // supply its own `scrub_secret`.
1126        let telemetry_fallback_secret = *uuid::Uuid::new_v4().as_bytes();
1127
1128        Ok(Self {
1129            transport_manager,
1130            ack_manager: AckManager::with_config(config.reliability.ack.clone()),
1131            retry_queue: RetryQueue::with_config(config.reliability.retry.clone()),
1132            deduplicator: Deduplicator::with_config(config.reliability.dedup.clone()),
1133            mesh_relay: MeshRelayGovernor::with_config(
1134                config.profile.clone(),
1135                config.mesh_relay.clone(),
1136            ),
1137            custody: custody::CustodyStore::new(config.custody.clone()),
1138            custody_receipts: HashMap::new(),
1139            custody_last_sweep: Instant::now(),
1140            local_id: config.profile.clone(),
1141            identity_established: false,
1142            shared_state: Arc::new(Mutex::new(SharedState::new())),
1143            outbox: HashMap::new(),
1144            pending_reseal: HashMap::new(),
1145            media_outbox: HashMap::new(),
1146            dm_unreachable_parks: HashMap::new(),
1147            unrouted_acks: VecDeque::new(),
1148            reachability: reachability::ReachabilityFacts::default(),
1149            gateway_capabilities: HashSet::new(),
1150            mls_manager: None,
1151            pending_encrypted_messages: HashMap::new(),
1152            deferred_restore_settlements: Vec::new(),
1153            suppressed_restore_settlements: 0,
1154            next_pending_message_expiry: None,
1155            pending_key_packages: HashMap::new(),
1156            key_package_sent_to: HashMap::new(),
1157            known_peers: HashMap::new(),
1158            confirmed_sessions: std::collections::HashSet::new(),
1159            encryption_capable_peers: std::collections::HashSet::new(),
1160            peer_compact_envelope: std::collections::HashSet::new(),
1161            peer_ctrl_freshness: std::collections::HashSet::new(),
1162            control_freshness_peers: std::collections::HashSet::new(),
1163            control_reset_watermark: std::collections::HashMap::new(),
1164            peer_rich_payload: std::collections::HashSet::new(),
1165            peer_data_sync: std::collections::HashSet::new(),
1166            peer_data_group: std::collections::HashSet::new(),
1167            peer_data_group_attested: std::collections::HashSet::new(),
1168            peer_data_media: std::collections::HashSet::new(),
1169            peer_data_tombstones: std::collections::HashSet::new(),
1170            peer_data_interest: std::collections::HashSet::new(),
1171            peer_data_group_blob: std::collections::HashSet::new(),
1172            peer_data_group_blob_attested: std::collections::HashSet::new(),
1173            peer_data_custody: std::collections::HashSet::new(),
1174            peer_rich_attested: std::collections::HashSet::new(),
1175            plaintext_send_warned: std::collections::HashSet::new(),
1176            plaintext_receive_warned: std::collections::HashSet::new(),
1177            encryption_capable_persisted: HashSet::new(),
1178            control_gate_warned: HashMap::new(),
1179            pending_queue: PendingDecryptionQueue::default(),
1180            secure_storage: None,
1181            protocol_state_storage: None,
1182            state_record_cipher: None,
1183            #[cfg(feature = "data")]
1184            data: data::DataLayer::default(),
1185            #[cfg(feature = "data")]
1186            last_data_sync_offer: HashMap::new(),
1187            #[cfg(feature = "data")]
1188            data_sync_settle: HashMap::new(),
1189            #[cfg(feature = "data")]
1190            pending_attachment_fetches: HashMap::new(),
1191            blob_request_windows: HashMap::new(),
1192            #[cfg(feature = "data")]
1193            group_spaces_enumerated: false,
1194            lamport_clock: LamportClock::new(),
1195            confirmation_retry_due_at: HashMap::new(),
1196            confirmation_probe_due_at: HashMap::new(),
1197            confirmation_probe_unreachable_parks: HashMap::new(),
1198            confirmation_probe_outstanding: HashMap::new(),
1199            confirmation_probe_superseded: HashMap::new(),
1200            retry_drain_tokens: 0.0,
1201            retry_drain_last: None,
1202            rekey_due_at: HashMap::new(),
1203            welcome_lifecycles: HashMap::new(),
1204            pending_connection_requests: HashMap::new(),
1205            welcome_presence_rescue: HashMap::new(),
1206            both_create_awaiting_decrypt: std::collections::HashSet::new(),
1207            mls_event_emitter: Arc::new(NoopMlsEventEmitter),
1208            mls_event_rate_limiter: MlsEventRateLimiter::default(),
1209            // The pre-install scrubber uses `TelemetryConfig::default()` —
1210            // `scrub_ids=true`, no explicit `scrub_secret`. Identifier hashing
1211            // is therefore on from the moment the protocol is constructed,
1212            // matching today's always-scrub MLS observability semantics. When
1213            // `install_telemetry_sink` later supplies a config with
1214            // `scrub_ids(false)`, a new scrubber is derived from that config
1215            // but reuses `telemetry_fallback_secret` so opaque IDs remain
1216            // stable across the install boundary.
1217            telemetry_scrubber: Scrubber::from_config(
1218                &TelemetryConfig::default(),
1219                telemetry_fallback_secret,
1220            ),
1221            telemetry_fallback_secret,
1222            telemetry_secret_persisted: false,
1223            nostr_secret_persisted: false,
1224            nostr_unpersisted_secret: None,
1225            telemetry: None,
1226            #[cfg(feature = "telemetry-pipe")]
1227            telemetry_pipe: None,
1228            file_transfer_manager: FileTransferManager::new(),
1229            pending_media_metadata: HashMap::new(),
1230            outbound_media_transfers: HashMap::new(),
1231            outbound_media_chunks: HashMap::new(),
1232            outbound_media_windows: HashMap::new(),
1233            restored_media_descriptors: HashMap::new(),
1234            mesh_services: MeshServices::new(),
1235            group_mesh: crate::group_mesh::GroupMeshState::default(),
1236            blocked_users: HashSet::new(),
1237            last_reconciliation_at: None,
1238            last_metrics_emit_at: None,
1239            transport_status_snapshot: HashMap::new(),
1240            device_capability_snapshot: None,
1241            last_persisted_lamport: 0,
1242            dedup_dirty: 0,
1243            dedup_last_persist: Instant::now(),
1244            last_persisted_nostr_watermark: None,
1245            nostr_publication_slots: Vec::new(),
1246            nostr_published_slots: HashSet::new(),
1247            last_nostr_slot_refresh: None,
1248            nostr_publication_backoff: HashMap::new(),
1249            last_nostr_slot_warning: None,
1250            nostr_discovery_claim: None,
1251            nostr_discovery_retracting: Vec::new(),
1252            nostr_discovery_published: false,
1253            nostr_discovery_backoff: HashMap::new(),
1254            last_nostr_discovery_refresh: None,
1255            nostr_resolutions: HashMap::new(),
1256            nostr_resolution_requests: HashMap::new(),
1257            last_push_key_package_warning: None,
1258            last_gateway_refusal_warning: None,
1259            last_gateway_binding_mismatch_warning: None,
1260            config,
1261        })
1262    }
1263
1264    /// Initializes MLS encryption and protocol persistence.
1265    ///
1266    /// This must be called before encryption can be used. The storage
1267    /// `secure_storage` must be a platform-native credential store.
1268    /// `protocol_state_storage` must be scoped to the app container and is
1269    /// removed when that container is deleted.
1270    ///
1271    /// Ownership model:
1272    /// - `OfflineProtocol` is the single authoritative owner of `MlsManager`
1273    /// - initialization is idempotent per protocol instance
1274    /// - subsequent calls return without replacing the existing manager
1275    /// - manager publication is transactional: restore must succeed before
1276    ///   `mls_manager` becomes visible to callers
1277    ///
1278    /// The two storage domains are intentionally different trait objects. This
1279    /// prevents message-plane state from inheriting the lifecycle of Keychain
1280    /// or another credential store.
1281    pub fn initialize_mls(
1282        &mut self,
1283        secure_storage: Arc<dyn MlsStorage>,
1284        protocol_state_storage: Arc<dyn ProtocolStateStorage>,
1285    ) -> Result<()> {
1286        self.initialize_mls_inner(secure_storage, protocol_state_storage, true)
1287    }
1288
1289    /// Returns this device's address, once it has one.
1290    ///
1291    /// `None` before `initialize_mls`: the address is the hash of an identity
1292    /// key that lives in this profile's storage, and storage does not arrive
1293    /// until then. It never changes afterwards, and it is stable across
1294    /// restarts of the same profile because the key is.
1295    pub fn local_address(&self) -> Option<&str> {
1296        self.identity_established.then_some(self.local_id.as_str())
1297    }
1298
1299    /// `adopt_legacy_state` exists only so test fixtures can point both handles
1300    /// at one backend. Adoption moves records *between* the two stores, which
1301    /// on a shared backend would mean deleting a record through the same store
1302    /// it was just read from.
1303    ///
1304    /// There is one identity path and every caller takes it — a fixture that
1305    /// wants a particular identity seeds the key into `secure_storage` first
1306    /// (see [`crate::test_identity`]) rather than naming an id here, because an
1307    /// id nothing holds a key for is exactly what `MlsManager::new` refuses.
1308    fn initialize_mls_inner(
1309        &mut self,
1310        secure_storage: Arc<dyn MlsStorage>,
1311        protocol_state_storage: Arc<dyn ProtocolStateStorage>,
1312        adopt_legacy_state: bool,
1313    ) -> Result<()> {
1314        if self.mls_manager.is_some() {
1315            return Ok(());
1316        }
1317
1318        // The bootstrap inversion: load (or mint) the identity key first, and
1319        // take this device's wire identity from it. Before this point the
1320        // protocol has no address — `local_id` is still the profile — which is
1321        // exactly why the key has to be resolved here, ahead of the manager
1322        // that embeds the id in its credential and in every session slot.
1323        let (_, address) = MlsManager::load_or_create_identity(&secure_storage)?;
1324        let local_id = address.to_string();
1325
1326        let mut manager = MlsManager::new(&local_id, secure_storage.clone())?;
1327        // Installed before the manager becomes shared: the enforcement flag is
1328        // read on every group decrypt, and this is the one point where the
1329        // manager is still uniquely owned.
1330        manager.set_enforce_admin_commits(self.config.group.enforce_admin_commits);
1331        let manager = Arc::new(RwLock::new(manager));
1332
1333        // Keep initialization transactional so a restore failure cannot leave
1334        // partially-initialized MLS state visible and then permanently block retries.
1335        let previous_secure_storage = self.secure_storage.clone();
1336        let previous_protocol_state_storage = self.protocol_state_storage.clone();
1337        // The record cipher belongs to the secure store it was loaded from, so
1338        // it is part of the same transaction as the storage handles: taken here
1339        // so a failed init cannot leave the new store's key installed next to
1340        // the rolled-back handles, and restored below alongside them.
1341        let previous_state_record_cipher = self.state_record_cipher.take();
1342        let previous_pending_messages = self.pending_encrypted_messages.clone();
1343        let previous_pending_message_expiry = self.next_pending_message_expiry;
1344        // The inbound half of the same transaction: the restore re-admits
1345        // parked frames from the store being attached, so a rollback has to put
1346        // back what the queue held before, not an empty queue.
1347        let previous_pending_queue = self.pending_queue.clone();
1348        // Populated by restore steps that run before other fallible ones, so
1349        // they belong in the transaction like everything else: a failed init
1350        // must not leave a key-package cache, parked media descriptors, or an
1351        // owner gate sourced from a store the rollback has just detached.
1352        let previous_pending_key_packages = self.pending_key_packages.clone();
1353        let previous_restored_media_descriptors = self.restored_media_descriptors.clone();
1354        let previous_both_create_awaiting_decrypt = self.both_create_awaiting_decrypt.clone();
1355        let previous_confirmed_sessions = self.confirmed_sessions.clone();
1356        let previous_encryption_capable_peers = self.encryption_capable_peers.clone();
1357        let previous_welcome_lifecycles = self.welcome_lifecycles.clone();
1358        let previous_lamport_clock = self.lamport_clock.value();
1359        // The debounce watermark travels with the clock: `restore_lamport_clock`
1360        // sets both, so rolling back only the clock leaves a watermark ahead of
1361        // it and `persist_lamport_clock`'s `wrapping_sub` reads that as an
1362        // enormous delta — writing on every tick instead of every interval.
1363        let previous_last_persisted_lamport = self.last_persisted_lamport;
1364        let previous_blocked_users = self.blocked_users.clone();
1365        let previous_outbox = self.outbox.clone();
1366        let previous_peer_compact_envelope = self.peer_compact_envelope.clone();
1367        let previous_peer_ctrl_freshness = self.peer_ctrl_freshness.clone();
1368        // Snapshotted with its siblings so a failed re-initialize restores it
1369        // too. It is a ratchet, so the direction that matters is that a
1370        // rollback must not *lose* it: a peer we hold to the newer payload has
1371        // to still be held to it if the re-initialize is abandoned.
1372        let previous_control_freshness_peers = self.control_freshness_peers.clone();
1373        let previous_control_reset_watermark = self.control_reset_watermark.clone();
1374        let previous_peer_rich_payload = self.peer_rich_payload.clone();
1375        let previous_peer_data_sync = self.peer_data_sync.clone();
1376        let previous_peer_rich_attested = self.peer_rich_attested.clone();
1377        let previous_peer_data_group = self.peer_data_group.clone();
1378        let previous_peer_data_group_attested = self.peer_data_group_attested.clone();
1379        let previous_peer_data_media = self.peer_data_media.clone();
1380        let previous_peer_data_tombstones = self.peer_data_tombstones.clone();
1381        let previous_peer_data_interest = self.peer_data_interest.clone();
1382        let previous_peer_data_group_blob = self.peer_data_group_blob.clone();
1383        let previous_peer_data_group_blob_attested = self.peer_data_group_blob_attested.clone();
1384
1385        let previous_local_id = std::mem::replace(&mut self.local_id, local_id.clone());
1386        let previous_identity_established = self.identity_established;
1387        self.identity_established = true;
1388        // The governor took the profile at construction because no address
1389        // existed yet; it keys relay fan-out and jitter off the local id, so it
1390        // has to move to the real one here.
1391        self.mesh_relay.set_local_id(local_id);
1392
1393        self.secure_storage = Some(secure_storage);
1394        self.protocol_state_storage = Some(protocol_state_storage);
1395
1396        // Must precede every restore below: sealed protocol-state records
1397        // (pending messages, outbox, media descriptors) are unreadable without
1398        // this key, so restoring first would silently start from empty and then
1399        // overwrite durable state with that empty view.
1400        self.restore_or_init_state_record_key();
1401
1402        // Then adopt anything the pre-split build left in secure storage, so
1403        // the restores below see one complete view. Must follow the record key
1404        // (adoption seals what it moves) and precede every restore (a restore
1405        // that ran first would find nothing and then overwrite the legacy state
1406        // with that empty view). Best-effort and resumable: a failure here
1407        // leaves the legacy records in place for the next launch.
1408        if adopt_legacy_state {
1409            self.adopt_legacy_protocol_state();
1410        }
1411
1412        // The settlement queue is deliberately NOT captured for rollback, and
1413        // that is the whole point rather than an omission.
1414        //
1415        // The rollback below restores *in-memory* state. It restores no storage
1416        // state, because restore has none to give back: by the time a later
1417        // step fails, an earlier one has already deleted an unaddressable
1418        // pending queue, dropped a record its store reported corrupt, and
1419        // rewritten a peer's snapshot without the entries it evicted for
1420        // capacity. Those records are gone. So the invariant adoption is
1421        // documented with — nothing can re-derive a settlement for a record
1422        // that no longer exists — is not special to adoption; it holds for
1423        // every settlement produced under this transaction, and rolling any of
1424        // them back means the application keeps an id that resolves to nothing,
1425        // on this launch and on every launch after it.
1426        //
1427        // The cost of not rolling back is that a retry which re-examines a
1428        // still-present record can settle the same id twice. `message_failed`
1429        // is terminal and idempotent for any reasonable consumer, and a
1430        // duplicate terminal event is a far smaller lie than silence.
1431        //
1432        // Load the persistent scrub secret outside the transactional restore
1433        // below: it is independent of MLS state, and a later MLS-restore
1434        // rollback must not undo it (the secret is idempotent and reused on
1435        // the next attempt).
1436        self.restore_or_init_scrub_secret();
1437
1438        // Same reasoning for the Nostr signing secret: independent of MLS
1439        // state, idempotent, and must survive an MLS-restore rollback.
1440        self.restore_or_init_nostr_signing_secret();
1441
1442        // And for the Nostr receive watermark, which sits outside the
1443        // transaction below for a third reason on top of those two: it does
1444        // not live in `self` at all. The mark is transport state, so the
1445        // rollback — which restores in-memory fields of `OfflineProtocol` —
1446        // could not put it back even if it wanted to. Installing it under a
1447        // later failure is harmless: it only ever moves forward, and the worst
1448        // a stale-but-installed mark does is narrow one replay window.
1449        self.restore_nostr_watermark();
1450        self.restore_nostr_publication_slots();
1451        self.restore_nostr_discovery_claim();
1452
1453        // The launch's whole durable-delete allowance, in one place because the
1454        // bound is on the launch. A device-barrier storm kills *this call*, not
1455        // any single walk in it, so no walk may hand itself a pool — see
1456        // `PruneAllowance::pool`. Four of them, and the ceiling is their sum:
1457        //
1458        // - `advisory_prunes` is shared by the `ADVISORY_PRUNE_WALKS` walks
1459        //   whose prunes are caches or advisory signals. They draw in the order
1460        //   written below, and that order is part of the contract: each leaves
1461        //   the ones after it a `MIN_ADVISORY_PRUNE_DELETES` floor and may take
1462        //   the rest, so an earlier walk gets first call on whatever the later
1463        //   ones do not reserve. Reordering them, or adding a sixth without
1464        //   bumping `ADVISORY_PRUNE_WALKS`, changes who gets pruned under load.
1465        // - `pending_prunes` and `outbox_prunes` are private to the two
1466        //   settlement-paired walks, because being starved there defers a
1467        //   diagnostic or a *delivery* rather than a cache eviction, and
1468        //   neither may be held hostage to a key-package flood in a category it
1469        //   has nothing to do with.
1470        // - `inbound_prunes` is private to the two receive-side walks for the
1471        //   same reason: the pending-decryption walk holds ciphertext the app
1472        //   is told about when it is lost. It draws first, and the seen-set
1473        //   restore takes whatever is left for its one possible delete.
1474        //
1475        // See `storage::MAX_RESTORE_PRUNE_DELETES`.
1476        let mut advisory_prunes = PruneAllowance::pool();
1477        let mut pending_prunes = PruneAllowance::pool();
1478        let mut outbox_prunes = PruneAllowance::pool();
1479        let mut inbound_prunes = PruneAllowance::pool();
1480
1481        // Restore state from previous session
1482        let restore_result = (|| {
1483            self.restore_pending_messages(&mut pending_prunes)?;
1484            self.restore_pending_decrypt_entries(&mut inbound_prunes);
1485            self.restore_custody(&mut inbound_prunes);
1486            self.restore_lamport_clock();
1487            self.restore_dedup_seen(&mut inbound_prunes);
1488            self.restore_encryption_capable_peers();
1489            self.restore_blocked_users()?;
1490            self.restore_session_states_from_manager(manager.clone(), &mut advisory_prunes)?;
1491            self.restore_peer_key_packages(&manager, &mut advisory_prunes)?;
1492            // Must precede start(): flush_restored_confirmed_pending_messages
1493            // re-makes the rich seal decision against these sets, and an
1494            // empty set there silently drops queued rich extras.
1495            self.restore_peer_capabilities(&manager, &mut advisory_prunes);
1496            self.restore_welcome_lifecycles(&mut advisory_prunes)?;
1497            self.restore_outbox(&mut outbox_prunes)?;
1498            self.restore_media_descriptors(&mut advisory_prunes)?;
1499            self.restore_both_create_awaiting_decrypt();
1500            Ok(())
1501        })();
1502
1503        if let Err(err) = restore_result {
1504            self.mesh_relay.set_local_id(previous_local_id.clone());
1505            self.local_id = previous_local_id;
1506            self.identity_established = previous_identity_established;
1507            self.secure_storage = previous_secure_storage;
1508            self.protocol_state_storage = previous_protocol_state_storage;
1509            self.state_record_cipher = previous_state_record_cipher;
1510            self.pending_encrypted_messages = previous_pending_messages;
1511            self.next_pending_message_expiry = previous_pending_message_expiry;
1512            // Back to what the queue held before this call. Emptying it lost
1513            // frames that were never persisted (no store was attached, or the
1514            // best-effort write failed). Keeping what the restore added would
1515            // leave entries sourced from the store the rollback just detached:
1516            // draining one deletes nothing on disk, so the next launch restores
1517            // it and drains it again into a spent ratchet generation.
1518            self.pending_queue = previous_pending_queue;
1519            // `deferred_restore_settlements` is deliberately left alone — see
1520            // the comment where the other baselines are captured.
1521            self.pending_key_packages = previous_pending_key_packages;
1522            self.restored_media_descriptors = previous_restored_media_descriptors;
1523            self.both_create_awaiting_decrypt = previous_both_create_awaiting_decrypt;
1524            self.confirmed_sessions = previous_confirmed_sessions;
1525            // Restored for consistency with the rest of the transaction, not
1526            // for safety: this set only ever grows, so keeping the wider view
1527            // would also have been sound. Rolling it back keeps "a failed
1528            // initialize_mls leaves no trace" true without exception.
1529            self.encryption_capable_peers = previous_encryption_capable_peers;
1530            self.welcome_lifecycles = previous_welcome_lifecycles;
1531            self.lamport_clock = LamportClock::from_value(previous_lamport_clock);
1532            self.last_persisted_lamport = previous_last_persisted_lamport;
1533            self.blocked_users = previous_blocked_users;
1534            self.outbox = previous_outbox;
1535            self.peer_compact_envelope = previous_peer_compact_envelope;
1536            self.peer_ctrl_freshness = previous_peer_ctrl_freshness;
1537            self.control_freshness_peers = previous_control_freshness_peers;
1538            self.control_reset_watermark = previous_control_reset_watermark;
1539            self.peer_rich_payload = previous_peer_rich_payload;
1540            self.peer_data_sync = previous_peer_data_sync;
1541            self.peer_rich_attested = previous_peer_rich_attested;
1542            self.peer_data_group = previous_peer_data_group;
1543            self.peer_data_group_attested = previous_peer_data_group_attested;
1544            self.peer_data_media = previous_peer_data_media;
1545            self.peer_data_tombstones = previous_peer_data_tombstones;
1546            self.peer_data_interest = previous_peer_data_interest;
1547            self.peer_data_group_blob = previous_peer_data_group_blob;
1548            self.peer_data_group_blob_attested = previous_peer_data_group_blob_attested;
1549            return Err(err);
1550        }
1551
1552        self.mls_manager = Some(manager);
1553        #[cfg(feature = "telemetry-pipe")]
1554        self.attach_telemetry_storage();
1555        // A re-init can swap the identity, and with it which groups exist, so
1556        // the one-shot group enumeration has to run again. Past the last
1557        // `return Err` above, so a failed init leaves the flag alone.
1558        #[cfg(feature = "data")]
1559        {
1560            self.group_spaces_enumerated = false;
1561        }
1562        self.emit_mls_initialized();
1563
1564        // Announced only here, past the last `return Err` — a restore failure
1565        // rolls the address back, and announcing an identity the instance then
1566        // abandoned would leave the app addressing a device that is not this
1567        // one.
1568        self.emit_event(Event::identity_ready(self.local_id.clone()));
1569
1570        info!(profile = %self.config.profile, "MLS encryption initialized with split secure and protocol-state storage");
1571        Ok(())
1572    }
1573
1574    /// Test-only adapter for fixtures that intentionally use one
1575    /// in-memory/fault-injection backend to observe both storage domains.
1576    #[cfg(test)]
1577    pub(crate) fn initialize_mls_for_test(&mut self, storage: Arc<dyn MlsStorage>) -> Result<()> {
1578        let protocol_state_storage = Arc::new(TestProtocolStateStorage {
1579            storage: storage.clone(),
1580        });
1581        // Give the storage the identity this fixture's profile label stands
1582        // for, then take the production path over it. The instance comes up as
1583        // a genuine derived address, and it is the *same* address every time a
1584        // fixture says `"alice"` — which is what lets tests keep readable
1585        // labels while still exercising derived identity.
1586        crate::test_identity::seed_identity(&storage, &self.config.profile);
1587        self.initialize_mls_inner(storage, protocol_state_storage, false)
1588    }
1589
1590    /// Test-only init that takes the **production** identity path: the address
1591    /// is derived from the identity key in `storage` rather than forced.
1592    #[cfg(test)]
1593    pub(crate) fn initialize_mls_for_test_derived(
1594        &mut self,
1595        storage: Arc<dyn MlsStorage>,
1596    ) -> Result<()> {
1597        let protocol_state_storage = Arc::new(TestProtocolStateStorage {
1598            storage: storage.clone(),
1599        });
1600        self.initialize_mls_inner(storage, protocol_state_storage, false)
1601    }
1602
1603    /// Test-only storage initialization for persistence-focused fixtures that
1604    /// do not need an MLS manager.
1605    #[cfg(test)]
1606    pub(crate) fn enable_message_persistence_for_test(
1607        &mut self,
1608        storage: Arc<dyn MlsStorage>,
1609    ) -> Result<()> {
1610        self.secure_storage = Some(storage.clone());
1611        self.protocol_state_storage = Some(Arc::new(TestProtocolStateStorage { storage }));
1612        self.restore_or_init_state_record_key();
1613        self.restore_or_init_scrub_secret();
1614        self.restore_or_init_nostr_signing_secret();
1615        self.restore_nostr_watermark();
1616        self.restore_nostr_publication_slots();
1617        self.restore_nostr_discovery_claim();
1618        // Same four pools as `initialize_mls_inner`, for the same reason.
1619        let mut advisory_prunes = PruneAllowance::pool();
1620        let mut pending_prunes = PruneAllowance::pool();
1621        let mut outbox_prunes = PruneAllowance::pool();
1622        let mut inbound_prunes = PruneAllowance::pool();
1623        self.restore_pending_messages(&mut pending_prunes)?;
1624        self.restore_pending_decrypt_entries(&mut inbound_prunes);
1625        self.restore_custody(&mut inbound_prunes);
1626        self.restore_lamport_clock();
1627        self.restore_dedup_seen(&mut inbound_prunes);
1628        self.restore_encryption_capable_peers();
1629        self.restore_blocked_users()?;
1630        self.restore_outbox(&mut outbox_prunes)?;
1631        self.restore_media_descriptors(&mut advisory_prunes)?;
1632        Ok(())
1633    }
1634
1635    /// Checks if MLS encryption is initialized.
1636    pub fn is_mls_initialized(&self) -> bool {
1637        self.mls_manager.is_some()
1638    }
1639
1640    /// Records that `peer_id` has demonstrated it runs MLS.
1641    ///
1642    /// The only way into [`Self::encryption_capable_peers`]. Call it from
1643    /// anywhere a peer proves encryption capability — creating or joining a 1:1
1644    /// session with them, or pinning their signing key. Calling it redundantly
1645    /// is free and calling it too often is safe; the failure that matters is
1646    /// *not* calling it, which leaves the plaintext gate open for that peer.
1647    ///
1648    /// # Bounded by refusal, never by eviction
1649    ///
1650    /// The keys are wire-claimed ids and need their own cap, like every other
1651    /// map keyed that way — but not for the reason this comment used to give.
1652    /// It cited an unsigned `__MLS_WELCOME__` reaching the marking path; the
1653    /// control gate now rejects unsigned control frames before dispatch, and
1654    /// `__MLS_WELCOME__` is in neither exemption list, so `handle_welcome_message`
1655    /// only ever runs on a verified frame.
1656    ///
1657    /// The cap survives that because a signature was never the bound. A
1658    /// signature proves the signer holds the key its address derives from; it
1659    /// does not prove the address belongs to anyone real, and minting a fresh
1660    /// one costs a keygen. So an attacker willing to spend keygens can still
1661    /// present an unbounded supply of distinct, perfectly well-signed peers —
1662    /// which is precisely what a cap on a wire-keyed map is for.
1663    ///
1664    /// It has to be a refusal. Evicting would un-mark a peer that really is
1665    /// encryption-capable — the fail-open direction this field exists to
1666    /// prevent — and would hand an attacker a way to unprotect a *chosen*
1667    /// victim by flooding. Refusing only declines to add knowledge: that peer
1668    /// falls through to the `is_session_confirmed` check in
1669    /// [`Self::accept_plaintext_content`], which is exactly what shipped before
1670    /// this set existed. So a flood costs later peers the improvement and never
1671    /// costs anyone the protection they already had.
1672    ///
1673    /// Legitimate peers are also first in line by construction: restore seeds
1674    /// the set from the session list and the durable capability records during
1675    /// `initialize_mls`, before `start()` admits any traffic.
1676    ///
1677    /// # Return value
1678    ///
1679    /// `true` when `peer_id` is in the set on return — whether this call added
1680    /// it or a previous one did. This is what bounds the *durable* record:
1681    /// [`Self::record_encryption_capable`](crate::OfflineProtocol) persists only
1682    /// when this returns `true`, so the storage category can never hold more
1683    /// peers than the cap below. Without that coupling a Sybil flood — cheap,
1684    /// since each identity is one Ed25519 keygen that signs honestly as itself
1685    /// — would write unbounded records, and the restore walk (bounded by
1686    /// `MAX_RESTORE_KEYS_PER_CATEGORY`) could then miss a legitimate peer's
1687    /// record and re-open the plaintext gate for them on the next launch.
1688    pub(crate) fn mark_encryption_capable(&mut self, peer_id: &str) -> bool {
1689        if peer_id.is_empty() || peer_id == self.local_id {
1690            return false;
1691        }
1692        if self.encryption_capable_peers.contains(peer_id) {
1693            return true;
1694        }
1695        if self.encryption_capable_peers.len() >= MAX_ENCRYPTION_CAPABLE_PEERS {
1696            debug!(
1697                peer_id = %peer_id,
1698                cap = MAX_ENCRYPTION_CAPABLE_PEERS,
1699                "Encryption-capability set at capacity; peer falls back to the session-state check"
1700            );
1701            return false;
1702        }
1703        self.encryption_capable_peers.insert(peer_id.to_string());
1704        debug!(peer_id = %peer_id, "Peer marked encryption-capable");
1705        if self.encryption_capable_peers.len() == MAX_ENCRYPTION_CAPABLE_PEERS {
1706            // Emitted on the transition into full, so it cannot become a
1707            // per-frame flood: the set only grows and has no removal path, so
1708            // this line is reachable exactly once per process.
1709            warn!(
1710                cap = MAX_ENCRYPTION_CAPABLE_PEERS,
1711                "Encryption-capability set reached capacity; further peers fall back to the \
1712                 session-state check. Expected only under a forged-sender flood."
1713            );
1714        }
1715        true
1716    }
1717
1718    /// Whether `peer_id` is known to run MLS. See
1719    /// [`Self::encryption_capable_peers`] for why this is not a storage read.
1720    pub(crate) fn is_encryption_capable(&self, peer_id: &str) -> bool {
1721        self.encryption_capable_peers.contains(peer_id)
1722    }
1723
1724    /// Drops `peer_id` from the in-memory capability set **only**, leaving its
1725    /// durable record and write-elision cache entry in place.
1726    ///
1727    /// Test-only, and deliberately not a general "forget" — the set has no
1728    /// removal path by design (see [`Self::encryption_capable_peers`]). It
1729    /// reproduces one specific state that production does reach: the rollback in
1730    /// `initialize_mls` restores the pre-restore snapshot of the set while
1731    /// [`Self::encryption_capable_persisted`] keeps what the restore walk read,
1732    /// so the two disagree until the peer's next verified frame re-marks them.
1733    #[cfg(test)]
1734    pub(crate) fn forget_encryption_capable_for_test(&mut self, peer_id: &str) {
1735        self.encryption_capable_peers.remove(peer_id);
1736    }
1737
1738    /// Returns whether auto-encryption should be applied.
1739    fn should_auto_encrypt(&self) -> bool {
1740        self.config.encryption.enabled && self.mls_manager.is_some()
1741    }
1742
1743    /// Configures the MLS lifecycle event emitter.
1744    pub fn set_mls_event_emitter(&mut self, emitter: Arc<dyn MlsEventEmitter>) {
1745        self.mls_event_emitter = emitter;
1746    }
1747
1748    /// Installs the unified telemetry sink for this protocol instance.
1749    ///
1750    /// Every subsequent protocol [`Event`] and MLS lifecycle event is
1751    /// additionally forwarded to `sink` as a
1752    /// [`crate::telemetry::TelemetryRecord`], gated by the verbosity tier
1753    /// and identifier-scrubbing preferences in `config`. Protocol events
1754    /// flow through as [`TelemetryRecord::Protocol`], MLS lifecycle events
1755    /// as [`TelemetryRecord::Mls`].
1756    ///
1757    /// This does not replace the legacy [`crate::EventCallback`] and
1758    /// [`MlsEventEmitter`] paths — they continue to fire independently for
1759    /// backward compatibility.
1760    ///
1761    /// Events emitted before this call (for example
1762    /// [`crate::mls_observability::MlsLifecycleEvent::Initialized`] fired
1763    /// during `initialize_mls`) are not replayed to a sink installed later.
1764    ///
1765    /// # Re-install semantics
1766    ///
1767    /// Calling this method a second time *replaces* the previously installed
1768    /// sink and config — the old sink stops receiving records as soon as
1769    /// this call returns. The per-instance fallback secret is preserved so
1770    /// opaque identifiers stay stable across the swap when the new config
1771    /// does not carry its own `scrub_secret`.
1772    ///
1773    /// The per-tick diff snapshots (transport status, device capability,
1774    /// metrics cadence) are **rearmed** on every install: the next
1775    /// `process()` tick observes the current state as its baseline and emits
1776    /// no synthetic transitions for transports that were already available
1777    /// at install time. Apps that need the current transport statuses at
1778    /// install time should pull them explicitly via
1779    /// [`TransportManager::get_all_transport_statuses`].
1780    ///
1781    /// The escalation-trigger dedupe window (`ESCALATION_TRIGGER_DEDUPE_SECS`
1782    /// inside [`TransportManager`]) is **not** rearmed. A sink installed
1783    /// within that window after an escalation event fired to a previous
1784    /// sink may miss the next occurrence of the same reason until the
1785    /// window elapses. This is intentional: the dedupe is a property of
1786    /// the routing engine, not of the observer.
1787    ///
1788    /// # Lifecycle
1789    ///
1790    /// Installing a sink wires the structured routing-decision callback
1791    /// on the underlying [`TransportManager`]. The callback lives for the
1792    /// life of the protocol instance or until another
1793    /// `install_telemetry_sink` call replaces it — `start()` and `stop()`
1794    /// do not toggle it. This means apps can install a sink before
1795    /// `start()` and see routing records from the very first `send()`,
1796    /// and a `stop() → start()` cycle preserves the wiring so no
1797    /// re-install is needed. Conversely, apps that never install a sink
1798    /// pay no per-`send()` routing-emission overhead.
1799    ///
1800    /// # Errors
1801    ///
1802    /// Returns `Err` if the shared-state mutex is poisoned (indicating an
1803    /// earlier panic in another thread while holding the lock). On error no
1804    /// sink is installed, and the legacy emission paths are unaffected.
1805    ///
1806    /// [`TelemetryRecord::Protocol`]: crate::telemetry::TelemetryRecord::Protocol
1807    /// [`TelemetryRecord::Mls`]: crate::telemetry::TelemetryRecord::Mls
1808    // Crate-private since 0.26: the pipe is the one production sink, and the
1809    // engine's own tests are the remaining callers.
1810    #[cfg_attr(not(test), allow(dead_code))]
1811    pub(crate) fn install_telemetry_sink(
1812        &mut self,
1813        sink: Arc<dyn TelemetrySink>,
1814        config: TelemetryConfig,
1815    ) -> Result<()> {
1816        self.install_sink(
1817            sink,
1818            config,
1819            Arc::new(std::sync::atomic::AtomicBool::new(true)),
1820        )
1821    }
1822
1823    /// Installs `sink` behind `gate`, the flag every emit site reads first.
1824    fn install_sink(
1825        &mut self,
1826        sink: Arc<dyn TelemetrySink>,
1827        config: TelemetryConfig,
1828        gate: Arc<std::sync::atomic::AtomicBool>,
1829    ) -> Result<()> {
1830        // Forward the routing-diagnostic preference to the TransportManager
1831        // before wiring any callbacks so the very first routing decision
1832        // post-install already reflects the requested tier.
1833        self.transport_manager
1834            .set_routing_diagnostic(config.routing_diagnostic());
1835
1836        let ctx = TelemetryContext::with_gate(sink, config, self.telemetry_fallback_secret, gate);
1837        let mut state = lock_shared_state(&self.shared_state).map_err(|err| {
1838            error!(
1839                error = %err,
1840                "install_telemetry_sink: shared-state mutex poisoned; sink NOT installed",
1841            );
1842            err
1843        })?;
1844        state.telemetry = Some(ctx.clone());
1845        drop(state);
1846        self.telemetry = Some(ctx);
1847
1848        // Wire the structured routing-decision callback here so the
1849        // `TransportManager` pays the per-`send()` emission cost only when
1850        // a sink is actually installed, and so the wiring persists across
1851        // `stop() → start()` cycles (the callback reads `s.telemetry` on
1852        // every invocation and that field stays set). A subsequent
1853        // `install_telemetry_sink` replaces the closure with one capturing
1854        // the fresh `shared_routing` clone; both closures read the same
1855        // `SharedState::telemetry` slot, so even a concurrent in-flight
1856        // emission from the pre-replace closure would still resolve to
1857        // the currently-installed sink.
1858        let shared_routing = self.shared_state.clone();
1859        self.transport_manager
1860            .set_routing_decision_callback(Some(Arc::new(move |decision| {
1861                let s = shared_routing.lock_or_recover();
1862                if let Some(ctx) = s.telemetry.as_ref().filter(|ctx| ctx.enabled()) {
1863                    let record = TelemetryRecord::Routing(Box::new(decision));
1864                    // Dispatch is panic-isolated so a sink that panics
1865                    // here cannot unwind through the live `MutexGuard`
1866                    // and poison `SharedState`.
1867                    dispatch_record(&ctx.sink, &record);
1868                }
1869            })));
1870
1871        // Rearm the per-tick diff snapshots so the first tick after install
1872        // reports honest transitions only. Without this, a sink installed
1873        // after start() would observe a synthetic `Unavailable → Available`
1874        // transition for every already-running transport on the next tick.
1875        let (statuses, available) = self.transport_manager.snapshot_status_and_available();
1876        self.transport_status_snapshot = statuses;
1877        let (battery_level, is_charging) =
1878            device_battery_from_available(self.transport_manager.current_transport(), &available);
1879        let relay_role = self.relay_role();
1880        self.device_capability_snapshot = Some(DeviceSnap::from_parts(
1881            battery_level,
1882            is_charging,
1883            relay_role,
1884        ));
1885        // Leave `last_metrics_emit_at` at None so the first tick after
1886        // install fires a fresh metrics snapshot — that is the bootstrap
1887        // payload a new sink actually wants (full counter state in one
1888        // record).
1889        self.last_metrics_emit_at = None;
1890
1891        Ok(())
1892    }
1893
1894    /// Enables telemetry: the SDK collects, batches and uploads accepted
1895    /// events to the ingest itself.
1896    ///
1897    /// `config` must carry the `api_key` and `app_id` the developer portal
1898    /// issued; [`TelemetryConfig::validate`] names any field that is refused,
1899    /// and the refusal is [`Error::TelemetryConfigInvalid`]. `host` names the
1900    /// platform stamped on every batch and the application state right now.
1901    ///
1902    /// Nothing waits on I/O here: the pipe's storage load and first upload
1903    /// run on its own thread. Batches are durable across a restart once a
1904    /// protocol-state store is attached, which on the mobile bindings
1905    /// happens inside `initialize_mls`; before that they are held in memory.
1906    /// Calling this again replaces the running pipe after its final flush.
1907    ///
1908    /// What leaves the device, when, and how to switch it off are in
1909    /// `docs/telemetry.md`.
1910    #[cfg(feature = "telemetry-pipe")]
1911    pub fn enable_telemetry(&mut self, config: TelemetryConfig, host: TelemetryHost) -> Result<()> {
1912        if let Err(field) = config.validate() {
1913            return Err(Error::TelemetryConfigInvalid(field.to_string()));
1914        }
1915        if let Some(previous) = self.detach_telemetry_pipe() {
1916            previous.stop(FINAL_FLUSH_BUDGET);
1917        }
1918        // Always started in memory, even when a store is already attached.
1919        // Adopting a backend loads the durable queue: an index read, up to
1920        // `MAX_PENDING_BATCHES` sealed record reads with a decrypt and a parse
1921        // each, a `list_keys` and the orphan sweep. Doing that here would run
1922        // it on the caller, holding `&mut self`, which on the mobile bindings
1923        // is the common order: `initialize_mls` has already attached storage
1924        // by the time an app enables telemetry. `attach_telemetry_storage`
1925        // hands the backend over instead, and the pipe's own thread adopts it.
1926        let device_id = self.telemetry_install_id();
1927        let pipe = TelemetryPipe::start(
1928            &config,
1929            PipeParts::production(host, Backend::Memory, device_id),
1930        )?;
1931        self.install_sink(pipe.sink(), config, pipe.enabled_flag())?;
1932        self.telemetry_pipe = Some(pipe);
1933        self.attach_telemetry_storage();
1934        Ok(())
1935    }
1936
1937    /// Disables telemetry: one final flush within [`FINAL_FLUSH_BUDGET`], then
1938    /// the uploader thread stops and every emit site goes back to its
1939    /// telemetry-off cost. Callers holding an outer lock should prefer
1940    /// [`Self::detach_telemetry_pipe`] and stop the pipe outside it.
1941    #[cfg(feature = "telemetry-pipe")]
1942    pub fn disable_telemetry(&mut self) {
1943        if let Some(pipe) = self.detach_telemetry_pipe() {
1944            pipe.stop(FINAL_FLUSH_BUDGET);
1945        }
1946    }
1947
1948    /// Detaches the running pipe without stopping it: the sink is
1949    /// uninstalled, the routing callback cleared, and the pipe handed back
1950    /// for the caller to stop once it holds no engine lock. Its final flush
1951    /// may block for up to [`FINAL_FLUSH_BUDGET`], which is why the two steps
1952    /// are separable.
1953    #[cfg(feature = "telemetry-pipe")]
1954    pub fn detach_telemetry_pipe(&mut self) -> Option<Arc<TelemetryPipe>> {
1955        let pipe = self.telemetry_pipe.take()?;
1956        self.telemetry = None;
1957        self.shared_state.lock_or_recover().telemetry = None;
1958        self.transport_manager.set_routing_decision_callback(None);
1959        self.transport_manager.set_routing_diagnostic(false);
1960        Some(pipe)
1961    }
1962
1963    /// The running telemetry pipe, if any.
1964    #[cfg(feature = "telemetry-pipe")]
1965    pub fn telemetry_pipe(&self) -> Option<Arc<TelemetryPipe>> {
1966        self.telemetry_pipe.clone()
1967    }
1968
1969    /// Stops or resumes collection without tearing the pipe down. Off, every
1970    /// emit site costs one atomic load; what is already queued still drains.
1971    #[cfg(feature = "telemetry-pipe")]
1972    pub fn set_telemetry_enabled(&self, enabled: bool) {
1973        if let Some(pipe) = &self.telemetry_pipe {
1974            pipe.set_enabled(enabled);
1975        }
1976    }
1977
1978    /// Asks the uploader to flush now. Returns immediately.
1979    #[cfg(feature = "telemetry-pipe")]
1980    pub fn flush_telemetry(&self) {
1981        if let Some(pipe) = &self.telemetry_pipe {
1982            pipe.flush();
1983        }
1984    }
1985
1986    /// Flushes and waits up to `budget` for the uploader to finish.
1987    #[cfg(feature = "telemetry-pipe")]
1988    pub fn flush_telemetry_blocking(&self, budget: std::time::Duration) -> bool {
1989        self.telemetry_pipe
1990            .as_ref()
1991            .is_some_and(|pipe| pipe.flush_blocking(budget))
1992    }
1993
1994    /// The pipe's counters, or `None` while telemetry is not enabled.
1995    #[cfg(feature = "telemetry-pipe")]
1996    pub fn telemetry_stats(&self) -> Option<TelemetryStats> {
1997        self.telemetry_pipe.as_ref().map(|pipe| pipe.stats())
1998    }
1999
2000    /// Closes the current telemetry session: summary, a blocking flush,
2001    /// then a fresh session id.
2002    #[cfg(feature = "telemetry-pipe")]
2003    pub fn end_telemetry_session(&self) {
2004        if let Some(pipe) = &self.telemetry_pipe {
2005            pipe.end_session();
2006        }
2007    }
2008
2009    /// Reports an application lifecycle transition to the pipe.
2010    #[cfg(feature = "telemetry-pipe")]
2011    pub fn notify_app_state(&self, state: AppState) {
2012        if let Some(pipe) = &self.telemetry_pipe {
2013            pipe.notify_app_state(state);
2014        }
2015    }
2016
2017    /// Hands the pipe the protocol-state store and the per-install id once
2018    /// `initialize_mls` has them. Adoption happens on the pipe's own thread.
2019    #[cfg(feature = "telemetry-pipe")]
2020    fn attach_telemetry_storage(&self) {
2021        let Some(pipe) = &self.telemetry_pipe else {
2022            return;
2023        };
2024        if let (Some(storage), Some(cipher)) =
2025            (&self.protocol_state_storage, &self.state_record_cipher)
2026        {
2027            pipe.attach_storage(storage.clone(), cipher.clone());
2028        }
2029        pipe.set_device_id(self.telemetry_install_id());
2030    }
2031
2032    /// Starts the protocol.
2033    ///
2034    /// # Returns
2035    ///
2036    /// Returns `Ok(())` if started successfully, `Err` if already started.
2037    pub fn start(&mut self) -> Result<()> {
2038        let state = lock_shared_state(&self.shared_state)?;
2039
2040        if state.state != ProtocolState::Stopped {
2041            return Err(Error::AlreadyStarted);
2042        }
2043
2044        // Start all transports
2045        drop(state);
2046        self.transport_manager.start()?;
2047
2048        // Apply the Nostr sealing kill switch here rather than at transport
2049        // construction: the transport is built by the bindings layer, so this
2050        // is the one place every caller — FFI, RN, and a pure-Rust embedder
2051        // that installed its own `NostrTransport` — passes through with the
2052        // config in hand. A no-op when Nostr is not installed.
2053        self.transport_manager
2054            .set_nostr_sealing_enabled(self.config.transport.nostr_sealing_enabled);
2055        self.transport_manager
2056            .set_nostr_cold_contact_enabled(self.config.transport.nostr_cold_contact_enabled);
2057        self.transport_manager.set_nostr_username_discovery_enabled(
2058            self.config.transport.nostr_username_discovery_enabled,
2059        );
2060
2061        // Wire DORS event callback so app receives dors_score_updated, dors_transport_selected,
2062        let shared = self.shared_state.clone();
2063        self.transport_manager
2064            .set_dors_event_callback(Some(Arc::new(move |event| {
2065                shared.lock_or_recover().emit_event(event);
2066            })));
2067
2068        // NOTE: the structured routing-decision callback is wired by
2069        // `install_telemetry_sink`, not here. Its lifetime is tied to sink
2070        // presence rather than protocol start/stop — see the docstring on
2071        // `install_telemetry_sink` for the rationale.
2072
2073        // Wire BLE fragment eviction callback so app receives FragmentAssemblyEvicted.
2074        if let Some(ble_arc) = self.transport_manager.get_transport(TransportType::BLE) {
2075            let shared = self.shared_state.clone();
2076            if let Some(ble) = ble_arc.as_any().downcast_ref::<BleTransport>() {
2077                ble.set_fragment_eviction_callback(Some(Arc::new(move |info| {
2078                    shared
2079                        .lock_or_recover()
2080                        .emit_event(Event::fragment_assembly_evicted(
2081                            info.message_id,
2082                            info.completion_percent,
2083                            "capacity".to_string(),
2084                        ));
2085                })));
2086            }
2087        }
2088
2089        let mut state = lock_shared_state(&self.shared_state)?;
2090
2091        state.state = ProtocolState::Running;
2092        drop(state);
2093
2094        // Settle what restore could not recover, now that the event pipeline is
2095        // live. These ids were handed to the app by `send_message*` before the
2096        // process died; without this they would never resolve to anything.
2097        // Drained before the flush below so an app sees the failures first and
2098        // cannot mistake a restored send for the settlement of a lost one.
2099        self.drain_deferred_restore_settlements();
2100
2101        self.flush_restored_confirmed_pending_messages();
2102
2103        // Cold start: sessions restored from storage are already confirmed,
2104        // so no confirmation transition will fire for them and nothing else
2105        // would offer versions until the peer happened to be rediscovered.
2106        // Frames toward an unreachable peer queue in the outbox, which is the
2107        // ladder doing its job rather than a reason not to try.
2108        #[cfg(feature = "data")]
2109        {
2110            // The space list is derived from the records themselves rather
2111            // than from the space index, because the index is a cache: a
2112            // document written without ever being explicitly created leaves
2113            // records but no index entry, and those are precisely the
2114            // documents no peer has seen yet.
2115            // Group spaces appear in this list and are deliberately not
2116            // swept: `kick_data_sync` answers only for a space named after
2117            // a peer, so a group space falls through it. A cold-start sweep
2118            // for groups would mean an offer per member per group at every
2119            // launch, and what it would recover is narrow — a local commit
2120            // is already pushed to the roster when it happens, and the
2121            // per-member outbox carries it across a restart. Rediscovery
2122            // and joins reconcile the rest.
2123            for space in self.data_list_spaces().unwrap_or_default() {
2124                self.kick_data_sync(&space, "start");
2125            }
2126        }
2127
2128        self.kick_pending_session_reconciliation("start");
2129        self.process_welcome_retry_queue()?;
2130
2131        // Re-drive delivery of any outbox entries restored from a previous
2132        // session. They land here in the "stranded" state (not in the retry
2133        // queue, not awaiting an ACK), which flush_outbox_all already recovers:
2134        // it sends immediately where a transport is available and re-enqueues
2135        // the rest with backoff. Runs at start() rather than at restore time
2136        // because transports aren't up yet during initialize_mls.
2137        self.flush_outbox_all();
2138
2139        // Media transfers that died with the previous process cannot be
2140        // re-driven — only their descriptors survive (never chunk bytes).
2141        // Tell the app which transfers to re-initiate, now that the event
2142        // pipeline is live. The descriptors stay parked (and persisted)
2143        // until the resend consumes them or the restore TTL prunes them,
2144        // so an app that misses this signal gets it again next restart.
2145        //
2146        // Except the layer's own. An application cannot answer one of those:
2147        // the only surface that takes a caller-supplied `file_id` is
2148        // `send_media_with`, which forces the purpose to `None`, so a
2149        // well-behaved app re-supplying the bytes would deliver a document
2150        // snapshot to the peer's user as a downloaded file. They are dropped
2151        // instead, and nothing is stranded: the requester's fetch expires and
2152        // can be asked again, and a snapshot is re-offered by the next
2153        // anti-entropy exchange.
2154        let (recoverable, internal): (Vec<_>, Vec<_>) = self
2155            .restored_media_descriptors
2156            .values()
2157            .cloned()
2158            .partition(|descriptor| descriptor.data_purpose.is_none());
2159        for descriptor in &internal {
2160            debug!(
2161                file_id = %descriptor.file_id,
2162                "Dropping an interrupted document-layer transfer; the asking side will retry"
2163            );
2164            self.restored_media_descriptors.remove(&descriptor.file_id);
2165            self.remove_media_descriptor(&descriptor.file_id);
2166        }
2167        for descriptor in recoverable {
2168            self.emit_event(Event::media_resend_required(
2169                descriptor.file_id.clone(),
2170                descriptor.recipient.clone(),
2171                descriptor.file_name.clone(),
2172                descriptor.file_size,
2173                descriptor.app_id.clone(),
2174            ));
2175        }
2176
2177        Ok(())
2178    }
2179
2180    /// Stops the protocol gracefully.
2181    ///
2182    /// # Returns
2183    ///
2184    /// Returns `Ok(())` if stopped successfully, `Err` if not started.
2185    pub fn stop(&mut self) -> Result<()> {
2186        let state = lock_shared_state(&self.shared_state)?;
2187
2188        if state.state == ProtocolState::Stopped {
2189            return Ok(()); // Already stopped
2190        }
2191
2192        // Flush debounced Lamport clock before stopping so no ticks are lost.
2193        drop(state);
2194        self.flush_lamport_clock();
2195        // Same for the Nostr receive watermark: an un-flushed tail costs the
2196        // next launch a wider replay window.
2197        self.flush_nostr_watermark();
2198        // And the deduplicator's seen set: an un-flushed tail is a message
2199        // whose second copy the next launch fails to recognise.
2200        self.flush_dedup_seen();
2201        // Answer any lookup still in flight while the transport is still up to
2202        // take the cancellations. Nothing pumps relays or sweeps deadlines once
2203        // stopped, so a resolution left here is an event that never comes.
2204        self.flush_username_resolutions_for_stop();
2205
2206        // Clear event callbacks to release shared_state references.
2207        // NOTE: the routing-decision callback is deliberately NOT cleared
2208        // here. Its lifetime is sink-scoped (installed by
2209        // `install_telemetry_sink`, replaced by a subsequent install),
2210        // not protocol-running-scoped — so a `stop() → start()` cycle
2211        // preserves the wiring without requiring the app to re-install.
2212        self.transport_manager.set_dors_event_callback(None);
2213        if let Some(ble_arc) = self.transport_manager.get_transport(TransportType::BLE) {
2214            if let Some(ble) = ble_arc.as_any().downcast_ref::<BleTransport>() {
2215                ble.set_fragment_eviction_callback(None);
2216            }
2217        }
2218
2219        self.transport_manager.stop()?;
2220        let mut state = lock_shared_state(&self.shared_state)?;
2221
2222        state.state = ProtocolState::Stopped;
2223
2224        Ok(())
2225    }
2226
2227    /// Pauses the protocol (for background mode).
2228    pub fn pause(&mut self) -> Result<()> {
2229        self.flush_lamport_clock();
2230        self.flush_nostr_watermark();
2231        let mut state = lock_shared_state(&self.shared_state)?;
2232
2233        if state.state != ProtocolState::Running {
2234            return Err(Error::NotStarted);
2235        }
2236
2237        state.state = ProtocolState::Paused;
2238        Ok(())
2239    }
2240
2241    /// Resumes the protocol from pause.
2242    pub fn resume(&mut self) -> Result<()> {
2243        {
2244            let mut state = lock_shared_state(&self.shared_state)?;
2245
2246            if state.state != ProtocolState::Paused {
2247                return Err(Error::InvalidConfiguration(
2248                    "Protocol is not paused".to_string(),
2249                ));
2250            }
2251
2252            state.state = ProtocolState::Running;
2253        }
2254
2255        // A pause is the other edge back into a live event pipeline, so it owes
2256        // the same drain `start()` does. `settle_restored_message_failure` parks
2257        // anything it produces while the protocol is not `Running`, and
2258        // `update_retry_config` reaches it at runtime: shortening
2259        // `pending_message_max_lifetime_ms` in the background expires queued
2260        // messages and parks their terminal `message_failed`. Without this the
2261        // app would hold those ids until a `start()` that may never come again.
2262        self.drain_deferred_restore_settlements();
2263        Ok(())
2264    }
2265
2266    /// Emits every terminal settlement parked while the event pipeline was not
2267    /// live, and reports the count of any the cap dropped.
2268    ///
2269    /// Called from both edges into `Running` ([`Self::start`] and
2270    /// [`Self::resume`]) so a parked settlement has no state to be stranded in.
2271    /// Idempotent: draining an empty queue emits nothing.
2272    fn drain_deferred_restore_settlements(&mut self) {
2273        for event in std::mem::take(&mut self.deferred_restore_settlements) {
2274            self.emit_event(event);
2275        }
2276        let suppressed = std::mem::take(&mut self.suppressed_restore_settlements);
2277        if suppressed > 0 {
2278            warn!(
2279                suppressed,
2280                cap = MAX_DEFERRED_RESTORE_SETTLEMENTS,
2281                "Restore produced more terminal settlements than any legitimate run can produce; \
2282                 the ids past the cap were not reported individually"
2283            );
2284        }
2285    }
2286
2287    /// Forget that a peer replicates documents.
2288    ///
2289    /// The capability and the offer window are two halves of one fact, and
2290    /// they have to be dropped together: a window left behind outlives the
2291    /// capability and then suppresses the first offer to the same peer once
2292    /// it is relearned, which is a document that silently does not sync.
2293    pub(crate) fn forget_data_sync_peer(&mut self, peer: &str) {
2294        self.peer_data_sync.remove(peer);
2295        self.peer_data_group.remove(peer);
2296        self.peer_data_group_attested.remove(peer);
2297        self.peer_data_media.remove(peer);
2298        self.peer_data_tombstones.remove(peer);
2299        self.peer_data_interest.remove(peer);
2300        self.peer_data_group_blob.remove(peer);
2301        self.peer_data_group_blob_attested.remove(peer);
2302        self.peer_data_custody.remove(peer);
2303        // A peer we have stopped replicating with cannot answer anything we
2304        // asked them for, so the questions go too. Left behind they would
2305        // hold slots against the fetch bound until they timed out.
2306        #[cfg(feature = "data")]
2307        self.forget_attachment_state(peer);
2308        #[cfg(feature = "data")]
2309        self.forget_data_sync_offer_windows(peer);
2310    }
2311
2312    /// [`Self::forget_data_sync_peer`] for every peer at once.
2313    pub(crate) fn forget_every_data_sync_peer(&mut self) {
2314        self.peer_data_sync.clear();
2315        self.peer_data_group.clear();
2316        self.peer_data_group_attested.clear();
2317        self.peer_data_media.clear();
2318        self.peer_data_tombstones.clear();
2319        self.peer_data_interest.clear();
2320        self.peer_data_group_blob.clear();
2321        self.peer_data_group_blob_attested.clear();
2322        // Reported, not merely dropped, exactly as the single-peer road
2323        // reports. Nothing the application did reaches this one: the bound
2324        // on remembered peers is hit, a stranger's key package forgets every
2325        // capability at once, and a fetch outstanding at that moment ends
2326        // for a reason its asker has no way to see. Dropping the record
2327        // silently also forecloses the expiry that would have reported it
2328        // later, so the spinner this event exists to end never ends at all.
2329        #[cfg(feature = "data")]
2330        self.end_every_pending_fetch();
2331        self.blob_request_windows.clear();
2332        #[cfg(feature = "data")]
2333        self.last_data_sync_offer.clear();
2334    }
2335
2336    /// Called when a new neighbor is discovered.
2337    ///
2338    /// When auto key exchange is enabled, this method sends our key package
2339    /// to the newly discovered peer to enable encrypted communication.
2340    ///
2341    /// # Arguments
2342    ///
2343    /// * `peer_id` - The ID of the discovered peer
2344    pub fn on_neighbor_discovered(&mut self, peer_id: &str) {
2345        self.on_neighbor_discovered_via(peer_id, None);
2346    }
2347
2348    /// [`Self::on_neighbor_discovered`] with an optional transport override
2349    /// for the outbox flush (see [`Self::flush_outbox_for_peer_via`]).
2350    /// `unpark_via` is `Some(Internet)` when the relay presence-online edge
2351    /// re-enters discovery through its rescue branch: a message whose
2352    /// forced-internet re-drive just failed sits in the retry queue with no
2353    /// pending ACK, so this inner flush would pick it up again — and
2354    /// without the override DORS could route it into the mesh void with the
2355    /// park counter already cleared, past re-park's reach.
2356    fn on_neighbor_discovered_via(&mut self, peer_id: &str, unpark_via: Option<TransportType>) {
2357        // Don't track ourselves
2358        if peer_id == self.local_id {
2359            return;
2360        }
2361
2362        // Don't track or auto-exchange keys with blocked users
2363        if self.is_user_blocked(peer_id) {
2364            debug!(peer_id = %peer_id, "Ignoring neighbor discovery for blocked user");
2365            return;
2366        }
2367
2368        // Track discovered peers for service discovery and routing. Existing
2369        // peers get their last-seen refreshed; a new peer at capacity evicts
2370        // the least-recently-seen entry so a genuinely present neighbor is
2371        // never locked out by stale message-path senders (issue #140).
2372        if let Some(last_seen) = self.known_peers.get_mut(peer_id) {
2373            *last_seen = Instant::now();
2374        } else {
2375            if self.known_peers.len() >= MAX_KNOWN_PEERS {
2376                if let Some(victim) = self
2377                    .known_peers
2378                    .iter()
2379                    .min_by_key(|(_, seen)| **seen)
2380                    .map(|(id, _)| id.clone())
2381                {
2382                    debug!(peer_id = %peer_id, evicted = %victim, cap = MAX_KNOWN_PEERS, "Known peers at capacity, evicting least-recently-seen");
2383                    self.evict_known_peer(&victim);
2384                }
2385            }
2386            self.known_peers.insert(peer_id.to_string(), Instant::now());
2387        }
2388
2389        // Flush any pending outbox messages destined for this peer
2390        self.flush_outbox_for_peer_via(peer_id, unpark_via);
2391
2392        // Held frames for this neighbour, or to try through it
2393        // (`docs/spec/custody.md`, "Redelivery").
2394        self.redeliver_custody_to(peer_id);
2395
2396        // A Welcome that stalled or expired while this peer was unreachable now
2397        // has a fresh delivery opportunity over the carrier that surfaced this
2398        // peer — re-arm it. No-op when there is no pending Welcome for the peer.
2399        self.rearm_welcome_for_peer(peer_id, "peer_rediscovered");
2400
2401        // Offer document versions while the peer is in front of us. This has
2402        // to sit above the key-package guard below, which returns early for
2403        // any peer we have already exchanged with — that is to say, for
2404        // exactly the established peers whose documents drifted apart during
2405        // the partition this discovery just ended.
2406        #[cfg(feature = "data")]
2407        self.kick_data_sync(peer_id, "peer_rediscovered");
2408
2409        // The same reconciliation for every group space shared with this
2410        // peer. A group space cannot ride the 1:1 trigger above: two
2411        // members of a group need not have a session with each other at
2412        // all, so for them this discovery is the only moment anything knows
2413        // they are both reachable.
2414        #[cfg(feature = "data")]
2415        self.kick_shared_group_data_sync(peer_id, "peer_rediscovered");
2416
2417        // Only send key package if encryption is enabled and auto key exchange is on
2418        if !self.config.encryption.enabled || !self.config.encryption.auto_key_exchange {
2419            return;
2420        }
2421
2422        // The first push is discovery's. A later discovery re-arms it only
2423        // when that push produced no session, at most once per interval.
2424        if self.key_package_sent_to.contains_key(peer_id) {
2425            self.rearm_key_package_for_peer(peer_id);
2426            return;
2427        }
2428
2429        // Only if MLS is initialized
2430        if self.mls_manager.is_none() {
2431            return;
2432        }
2433
2434        if let Err(e) = self.send_key_package_to(peer_id, false) {
2435            warn!(error = %e, peer_id = %peer_id, "Failed to send key package on discovery");
2436        }
2437    }
2438
2439    /// Immediately attempts to send all pending outbox messages destined
2440    /// for a specific peer, bypassing backoff timers. Called on per-peer
2441    /// reachability edges (discovery, relay presence-online) to flush
2442    /// messages that were queued while the peer was unreachable.
2443    ///
2444    /// `unpark_via` is an optional transport override for the re-driven
2445    /// sends: `Some(Internet)` on the relay presence-online edge
2446    /// (`on_peer_presence`, including its rescue branch's re-entry through
2447    /// `on_neighbor_discovered_via`): the reachability
2448    /// proof is relay-scoped, so the re-drive must go out over the internet
2449    /// transport — DORS could otherwise route it back into the mesh, where
2450    /// the send locally succeeds against a peer that is not there,
2451    /// re-registering an unanswerable ACK that re-strands the message (and,
2452    /// with the platform bridge unwatching the peer on the online answer,
2453    /// no further presence edge would arrive to save it). Pinned media
2454    /// transports still win over the override.
2455    fn flush_outbox_for_peer_via(&mut self, peer_id: &str, unpark_via: Option<TransportType>) {
2456        // Probe ACKs first: with a live park counter, the peer's DMs may be
2457        // mid-probe — awaiting a probe ACK that may never arrive (never, over
2458        // a mesh carrier) — and the awaiting-ACK filter below would skip
2459        // exactly the messages this edge exists to re-drive.
2460        self.cancel_probe_state_for_parked_peer(peer_id);
2461        // A per-peer reachability edge: the escalating unreachable-probe
2462        // interval starts over (mirrors rearm_welcome_for_peer resetting
2463        // unreachable_parks). Snapshotted, not dropped: an edge whose
2464        // re-drives all fail didn't actually take, and restores it below.
2465        let prior_parks = self.dm_unreachable_parks.remove(peer_id);
2466
2467        // Collect matching messages from outbox + media_outbox
2468        let mut to_send: Vec<(Message, u32)> = Vec::new();
2469
2470        for entry in self.outbox.values() {
2471            if entry.message.recipient.as_str() == peer_id
2472                && !self.ack_manager.is_waiting_for_ack(&entry.message.id)
2473            {
2474                to_send.push((entry.message.clone(), entry.attempt_count));
2475            }
2476        }
2477        for entry in self.media_outbox.values() {
2478            if entry.message.recipient.as_str() == peer_id
2479                && !self.ack_manager.is_waiting_for_ack(&entry.message.id)
2480            {
2481                to_send.push((entry.message.clone(), entry.attempt_count));
2482            }
2483        }
2484
2485        if to_send.is_empty() {
2486            return;
2487        }
2488
2489        let count = to_send.len().min(crate::constants::FLUSH_BATCH_LIMIT);
2490        debug!(peer_id = %peer_id, count = count, "Flushing outbox for discovered peer");
2491
2492        let mut iter = to_send.into_iter();
2493        let mut parked_dm_seen = false;
2494        let mut parked_dm_redriven = false;
2495
2496        // Only process up to FLUSH_BATCH_LIMIT messages per edge.
2497        for (message, attempt_count) in iter.by_ref().take(crate::constants::FLUSH_BATCH_LIMIT) {
2498            let parkable = self.is_parkable_plain_dm(&message.id);
2499            // Remove from retry queue since we're sending immediately
2500            self.retry_queue.remove(&message.id.as_str());
2501            let sent = self.try_flush_send_via(message, attempt_count, unpark_via);
2502            if parkable {
2503                parked_dm_seen = true;
2504                parked_dm_redriven |= sent.is_some();
2505            }
2506        }
2507
2508        // Re-enqueue the overflow (mirrors flush_outbox_all): the probe
2509        // cancel above may have stripped a parked message's retry entry, so
2510        // "still holds its backoff timer" cannot be assumed past the batch
2511        // limit. Enqueue dedupes by id — entries still scheduled keep their
2512        // existing timer, canceled ones get a fresh backoff slot instead of
2513        // stranding edge-only with the park counter cleared.
2514        for (message, attempt_count) in iter {
2515            parked_dm_seen = parked_dm_seen || self.is_parkable_plain_dm(&message.id);
2516            let _ = self.retry_queue.enqueue(message, attempt_count);
2517        }
2518
2519        // An edge that re-drove no parkable DM at all didn't actually take:
2520        // the DMs now sit in the retry queue, whose later sends are
2521        // DORS-routed (no transport override there), and a send that succeeds
2522        // locally without reaching the peer would re-register an ACK nothing
2523        // will answer. Restore the counter so exhaustion stays within
2524        // `try_repark_exhausted_dm`'s reach instead of settling terminally
2525        // with the counter cleared.
2526        //
2527        // Restore granularity is per-peer, matching the counter: one
2528        // successful re-drive clears it even when a sibling's send failed on
2529        // the same edge, leaving that sibling on DORS-routed backoff exposed
2530        // to terminal exhaustion. Accepted gap — it requires one transport
2531        // to both succeed and fail within a single flush loop.
2532        if let Some(parks) = prior_parks {
2533            if parked_dm_seen && !parked_dm_redriven {
2534                self.dm_unreachable_parks.insert(peer_id.to_string(), parks);
2535            }
2536        }
2537    }
2538
2539    /// Immediately attempts to send all pending outbox messages across all peers.
2540    ///
2541    /// Called when a transport becomes available (e.g. internet reconnects) to
2542    /// flush all queued messages, bypassing backoff timers.
2543    pub fn flush_outbox_all(&mut self) {
2544        // Acknowledgements we owe first: they are what stop peers re-sending
2545        // to us, and they have no outbox entry for the walk below to find.
2546        self.flush_unrouted_acks();
2547        // Probe ACKs first (see `flush_outbox_for_peer_via`): mid-probe DMs
2548        // are awaiting unanswerable mesh ACKs, and the awaiting-ACK guard
2549        // below would strand them past this edge with their counters
2550        // cleared. Canceled entries surface through the stranded-outbox
2551        // collection.
2552        let parked_peers: Vec<String> = self.dm_unreachable_parks.keys().cloned().collect();
2553        for peer_id in parked_peers {
2554            self.cancel_probe_state_for_parked_peer(&peer_id);
2555        }
2556        // A carrier-level reachability edge (reconnect / start): every
2557        // escalating unreachable-probe interval starts over. Snapshotted,
2558        // not dropped: a peer whose re-drives all fail gets its counter
2559        // restored below (see `flush_outbox_for_peer_via`).
2560        let prior_parks = std::mem::take(&mut self.dm_unreachable_parks);
2561
2562        // Drain all entries from the retry queue (ignores timing)
2563        let retry_entries = self.retry_queue.drain_all();
2564
2565        // Also collect outbox entries NOT in the retry queue (stranded after
2566        // previous max_retries rejection)
2567        let mut all_messages: Vec<(Message, u32)> = retry_entries
2568            .into_iter()
2569            .map(|e| (e.message, e.retry_count))
2570            .collect();
2571
2572        // Add outbox entries that weren't in the retry queue (stranded) AND
2573        // aren't already waiting for an ACK (successfully sent, just awaiting
2574        // confirmation). Without the ACK check, a prior flush that succeeded
2575        // would cause these messages to be re-sent unnecessarily.
2576        let retry_ids: std::collections::HashSet<String> =
2577            all_messages.iter().map(|(m, _)| m.id.as_str()).collect();
2578
2579        for entry in self.outbox.values() {
2580            if !retry_ids.contains(&entry.message.id.as_str())
2581                && !self.ack_manager.is_waiting_for_ack(&entry.message.id)
2582            {
2583                all_messages.push((entry.message.clone(), entry.attempt_count));
2584            }
2585        }
2586        for entry in self.media_outbox.values() {
2587            if !retry_ids.contains(&entry.message.id.as_str())
2588                && !self.ack_manager.is_waiting_for_ack(&entry.message.id)
2589            {
2590                all_messages.push((entry.message.clone(), entry.attempt_count));
2591            }
2592        }
2593
2594        // Opt-in (`edge_driven_unreachable_dm`): on the start/reconnect re-drive,
2595        // leave durably-failing messages (first sent longer ago than
2596        // OUTBOX_DURABLE_UNREACHABLE_AGE_SECS, still undelivered) edge-driven
2597        // rather than re-driving them, so a restart does not re-ramp a large
2598        // dead-peer backlog. They rest in the outbox and flush the instant their
2599        // peer next proves reachable. Default-off preserves the documented
2600        // "reconnect re-drives, ignoring timing" behaviour for every existing
2601        // app. drain_all() already removed these from the retry queue and the
2602        // outbox entry is untouched, so "not collected" == "resting edge-driven".
2603        if self.config.reliability.retry.edge_driven_unreachable_dm {
2604            let now = Utc::now();
2605            let durable_age = chrono::Duration::seconds(
2606                crate::protocol::types::OUTBOX_DURABLE_UNREACHABLE_AGE_SECS,
2607            );
2608            all_messages.retain(|(m, _)| {
2609                match self
2610                    .outbox
2611                    .get(&m.id)
2612                    .or_else(|| self.media_outbox.get(&m.id))
2613                    .map(|e| e.first_sent_at)
2614                {
2615                    Some(first_sent) => now.signed_duration_since(first_sent) < durable_age,
2616                    None => true,
2617                }
2618            });
2619        }
2620
2621        if all_messages.is_empty() {
2622            return;
2623        }
2624
2625        let count = all_messages.len().min(crate::constants::FLUSH_BATCH_LIMIT);
2626        debug!(
2627            count = count,
2628            total = all_messages.len(),
2629            "Flushing all outbox messages"
2630        );
2631
2632        let mut iter = all_messages.into_iter();
2633        let mut parked_dm_seen: std::collections::HashSet<String> =
2634            std::collections::HashSet::new();
2635        let mut parked_dm_redriven: std::collections::HashSet<String> =
2636            std::collections::HashSet::new();
2637
2638        for (message, attempt_count) in iter.by_ref().take(crate::constants::FLUSH_BATCH_LIMIT) {
2639            let recipient = message.recipient.as_str().to_string();
2640            let parkable =
2641                prior_parks.contains_key(&recipient) && self.is_parkable_plain_dm(&message.id);
2642            let sent_via = self.try_flush_send(message, attempt_count);
2643            if parkable {
2644                // Unlike the per-peer edges (discovery carries mesh-scoped
2645                // proof, presence-online forces the answering carrier), this
2646                // carrier-level edge re-drives via DORS with no per-peer
2647                // reachability proof: a mesh-routed send "locally succeeds"
2648                // into the mesh whether or not the peer is there, so only a
2649                // send over a carrier that answers verdicts counts as
2650                // re-driven for counter-clearing — that is the send whose
2651                // failure would say something. A mesh-routed success keeps
2652                // the counter restore-eligible; if its ACK genuinely
2653                // arrives, delivery prunes the counter.
2654                if sent_via.and_then(GatewayCarrier::from_transport).is_some() {
2655                    parked_dm_redriven.insert(recipient);
2656                } else {
2657                    parked_dm_seen.insert(recipient);
2658                }
2659            }
2660        }
2661
2662        // Re-enqueue any messages beyond the batch limit so they aren't lost
2663        for (message, attempt_count) in iter {
2664            let recipient = message.recipient.as_str();
2665            if prior_parks.contains_key(recipient) && self.is_parkable_plain_dm(&message.id) {
2666                parked_dm_seen.insert(recipient.to_string());
2667            }
2668            let _ = self.retry_queue.enqueue(message, attempt_count);
2669        }
2670
2671        // Restore the counter of every parked peer none of whose DMs were
2672        // re-driven on this edge (see `flush_outbox_for_peer_via`): their
2673        // retry-queue sends are DORS-routed, and a send that succeeds locally
2674        // without reaching the peer must leave exhaustion re-parkable rather
2675        // than terminal.
2676        for (peer_id, parks) in prior_parks {
2677            if parked_dm_seen.contains(&peer_id) && !parked_dm_redriven.contains(&peer_id) {
2678                self.dm_unreachable_parks.insert(peer_id, parks);
2679            }
2680        }
2681    }
2682
2683    /// Records what the attached gateway daemon says it can do.
2684    ///
2685    /// Wholesale replace, like the relay's: each attach describes the gateway
2686    /// actually connected now. The bridge calls this **before** it reports the
2687    /// carrier available, which is the contract's own ordering — a device must
2688    /// not drain into a gateway whose features it has not been told — and it
2689    /// clears the set when the carrier drops.
2690    ///
2691    /// The list is wire-supplied, so it is bounded exactly as the relay's is,
2692    /// which is what the contract points at rather than inventing a second
2693    /// pair of numbers: at most 64 tokens of at most 128 bytes each, the same
2694    /// `MAX_RELAY_CAPABILITIES` and `MAX_RELAY_CAPABILITY_TOKEN_BYTES` the
2695    /// relay's advertisement is bounded by. Oversized tokens are
2696    /// dropped *before* the count is applied, so padding cannot evict real
2697    /// ones.
2698    ///
2699    /// Nothing here gates a security decision. Tokens gate features, and an
2700    /// attacker who can set them is already the gateway.
2701    pub fn set_gateway_capabilities(&mut self, capabilities: Vec<String>) {
2702        let caps: HashSet<String> = capabilities
2703            .into_iter()
2704            .filter(|c| !c.is_empty() && c.len() <= MAX_RELAY_CAPABILITY_TOKEN_BYTES)
2705            .take(MAX_RELAY_CAPABILITIES)
2706            .collect();
2707        debug!(count = caps.len(), "Gateway capabilities updated");
2708        self.gateway_capabilities = caps;
2709    }
2710
2711    /// Forgets the attached gateway's advertisement, on carrier drop.
2712    pub fn clear_gateway_capabilities(&mut self) {
2713        if !self.gateway_capabilities.is_empty() {
2714            debug!("Gateway capabilities cleared on carrier drop");
2715            self.gateway_capabilities.clear();
2716        }
2717    }
2718
2719    /// The attached gateway's advertised capability tokens, sorted so the
2720    /// order a caller sees does not depend on hashing.
2721    pub fn gateway_capabilities(&self) -> Vec<String> {
2722        let mut tokens: Vec<String> = self.gateway_capabilities.iter().cloned().collect();
2723        tokens.sort();
2724        tokens
2725    }
2726
2727    /// Peers the platform layer should watch via a gateway `CheckPresence`
2728    /// query: every peer with an undelivered or session-unproven MLS welcome
2729    /// ([`Self::welcome_pending_peers`]) plus every recipient of an outbox
2730    /// message not currently awaiting an ACK — which includes DMs parked on a
2731    /// `recipient_unreachable` verdict. A gateway's presence-online answer
2732    /// lands in [`Self::on_peer_presence_via`], whose
2733    /// `flush_outbox_for_peer_via` is what re-drives (un-parks) those
2734    /// messages, so the SDK — not the app — owns the "watch my DeliveryError
2735    /// recipients" duty. Bounded by the outbox cap (500 entries).
2736    ///
2737    /// Carrier-agnostic on purpose: the set is "who this device is waiting to
2738    /// hear about", which does not depend on who is asked. Every attached
2739    /// gateway watches the same peers.
2740    pub fn presence_watch_peers(&self) -> Vec<String> {
2741        let mut peers = self.welcome_pending_peers();
2742        let mut seen: std::collections::HashSet<String> = peers.iter().cloned().collect();
2743        for entry in self.outbox.values() {
2744            if self.ack_manager.is_waiting_for_ack(&entry.message.id) {
2745                continue;
2746            }
2747            let recipient = entry.message.recipient.as_str();
2748            if seen.insert(recipient.to_string()) {
2749                peers.push(recipient.to_string());
2750            }
2751        }
2752        peers
2753    }
2754
2755    /// Attempts to send a single message as part of a flush operation.
2756    ///
2757    /// Ensures the outbox entry exists before sending. A message reaching here
2758    /// normally has one: every path that gives a message up retires its retry
2759    /// entry with it (`retire_undeliverable_message`), so an eviction no longer
2760    /// leaves one behind to resurrect here, and re-creating a settled message
2761    /// would evict a live one at capacity. On success,
2762    /// registers ACK tracking and updates the outbox entry. On failure,
2763    /// re-enqueues the message to the retry queue with its current attempt count
2764    /// so backoff resumes. Returns the transport the send went out over, or
2765    /// `None` when it failed (or, defensively, when the transport could not
2766    /// be attributed — the park restore logic treats both as not-redriven,
2767    /// the safe direction; in practice a successful send always has one).
2768    fn try_flush_send(&mut self, message: Message, attempt_count: u32) -> Option<TransportType> {
2769        self.try_flush_send_via(message, attempt_count, None)
2770    }
2771
2772    /// [`Self::try_flush_send`] with an optional transport override (see
2773    /// [`Self::flush_outbox_for_peer_via`]). A pinned media transport takes
2774    /// precedence over the override; without either, DORS picks.
2775    fn try_flush_send_via(
2776        &mut self,
2777        mut message: Message,
2778        attempt_count: u32,
2779        transport_override: Option<TransportType>,
2780    ) -> Option<TransportType> {
2781        self.ensure_outbox_entry(&message);
2782        // Tier 2: re-seal against the peer's current session before flushing, so
2783        // a post-re-key epoch change no longer leaves the bytes undecryptable.
2784        // No-op for media/plaintext/unconfirmed sessions.
2785        self.reseal_for_resend_in_place(&mut message);
2786        let forced_transport = self
2787            .pinned_media_transport_for_message(&message.id)
2788            .or(transport_override);
2789        let send_result = if let Some(transport) = forced_transport {
2790            self.transport_manager
2791                .send_via_transport(&message, transport)
2792        } else {
2793            self.transport_manager.send(&message)
2794        };
2795        let current_transport =
2796            forced_transport.or_else(|| self.transport_manager.current_transport());
2797
2798        match send_result {
2799            Ok(()) => {
2800                if let Err(e) = self.ensure_ack_registration(&message) {
2801                    warn!(message_id = %message.id, error = %e, "ACK registration failed during flush");
2802                }
2803                self.mark_message_sent(
2804                    &message,
2805                    current_transport,
2806                    Some(attempt_count.saturating_add(1)),
2807                );
2808                debug!(message_id = %message.id, "Flush send succeeded");
2809                current_transport
2810            }
2811            Err(e) => {
2812                let _ = self.retry_queue.enqueue(message.clone(), attempt_count);
2813                debug!(message_id = %message.id, error = %e, "Flush send failed, re-enqueued");
2814                None
2815            }
2816        }
2817    }
2818
2819    /// Called when a neighbor is lost.
2820    ///
2821    /// Cleans up tracking state for the lost peer.
2822    ///
2823    /// # Arguments
2824    ///
2825    /// * `peer_id` - The ID of the lost peer
2826    pub fn on_neighbor_lost(&mut self, peer_id: &str) {
2827        self.evict_known_peer(peer_id);
2828    }
2829
2830    /// Drops a peer from discovery tracking. Shared by explicit neighbor
2831    /// loss, the TTL sweep, and least-recently-seen eviction at capacity —
2832    /// all three mean "treat this peer as gone until re-seen", so all three
2833    /// also clear the key-package marker, letting a re-appearing peer
2834    /// receive a fresh key package exactly as on a BLE reconnect.
2835    fn evict_known_peer(&mut self, peer_id: &str) {
2836        self.key_package_sent_to.remove(peer_id);
2837        self.known_peers.remove(peer_id);
2838        // Release the forwarding allowance held for this link. A peer that
2839        // reconnects starts with a full allowance, which is correct: the limit
2840        // exists to pace a live link, not to punish one that came back.
2841        self.mesh_relay.forget_peer(peer_id);
2842    }
2843
2844    /// Tears down the 1:1 session with `peer_id` and rebuilds it, advancing
2845    /// post-compromise security.
2846    ///
2847    /// # Why an application has to ask
2848    ///
2849    /// Post-compromise security arrives when a commit rotates a member's leaf
2850    /// in the ratchet tree. This engine originates one on a re-key, and until
2851    /// now the only thing that drove a re-key was an **epoch desync**: a
2852    /// healthy pair that never forked never rotated, so the window an attacker
2853    /// holding old key material keeps open was bounded by nothing.
2854    ///
2855    /// That is felt hardest against a leaf node, which never commits at all, so
2856    /// every rotation in such a pair is the phone's to originate. It is not
2857    /// exclusive to one: two phones that simply never desync are in the same
2858    /// position.
2859    ///
2860    /// The cadence is the application's because this engine cannot pick one.
2861    /// A rotation costs a teardown, a key-package exchange and a re-establish,
2862    /// and what that is worth depends on the deployment: a door lock on mains
2863    /// power and a phone on a metered link do not want the same interval, and
2864    /// nothing on the wire says which one is on the other end.
2865    ///
2866    /// # What the peer sees
2867    ///
2868    /// Exactly what a desync-driven re-key sends, because it is the same code:
2869    /// a `__MLS_KEY_PKG__` frame carrying `session_reset`. A peer running this
2870    /// engine discards its stale session and converges in one round trip; a
2871    /// leaf node discards its session, mints a fresh key package and re-pairs.
2872    /// Queued plaintext survives, because it is sealed at flush time against
2873    /// whatever session is current then.
2874    ///
2875    /// # Rate limit
2876    ///
2877    /// Shared with the desync path, one re-key per peer per window. A caller
2878    /// looping on this cannot do to a pair what that bound exists to stop an
2879    /// attacker doing.
2880    ///
2881    /// # Returns
2882    ///
2883    /// * `Ok(true)` - the reset was advertised and the session torn down.
2884    /// * `Ok(false)` - the rate-limit window has not lapsed; nothing was done,
2885    ///   and a later call succeeds. Not an error: a caller on a fixed schedule
2886    ///   that briefly runs faster than the floor is behaving correctly.
2887    ///
2888    /// # A rotation that fails changes nothing
2889    ///
2890    /// The reset is advertised **before** the local session is torn down, so
2891    /// an `Err` leaves the pair exactly as it was: the session is still there,
2892    /// still usable, and the rate-limit window is not spent. Rotate while the
2893    /// peer is reachable, and treat a failure as "try again later" rather than
2894    /// as a session to rebuild.
2895    ///
2896    /// The order matters most against a leaf node, which speaks only when
2897    /// spoken to. Tearing down first and failing to send would leave this side
2898    /// with no session, the device holding one it will never be told to drop,
2899    /// and nothing on either side that re-opens the exchange.
2900    ///
2901    /// # Errors
2902    ///
2903    /// * [`Error::MlsNotInitialized`] - encryption is not set up.
2904    /// * [`Error::UserBlocked`] - the peer is blocked.
2905    /// * [`Error::Mls`] with `SessionNotFound` - there is no session to rebuild.
2906    ///   Establishing a first session is [`Self::establish_secure_session`];
2907    ///   this heals one that exists.
2908    /// * [`Error::Transport`] - no transport accepted the reset frame. The
2909    ///   session is untouched, as above.
2910    pub fn rekey_session(&mut self, peer_id: &str) -> Result<bool> {
2911        if self.is_user_blocked(peer_id) {
2912            return Err(Error::UserBlocked(peer_id.to_string()));
2913        }
2914        if self.mls_manager.is_none() {
2915            return Err(Error::MlsNotInitialized);
2916        }
2917        // A session has to exist for there to be one to heal. Checked before
2918        // the slot is claimed, so a refused call does not spend the window and
2919        // leave a real re-key waiting on it.
2920        if !self.has_mls_session(peer_id)? {
2921            return Err(Error::Mls(offline_protocol_mls::MlsError::SessionNotFound(
2922                peer_id.to_string(),
2923            )));
2924        }
2925        if !self.claim_rekey_slot(peer_id) {
2926            debug!(
2927                peer_id = %peer_id,
2928                "rekey_session: the rate-limit window has not lapsed"
2929            );
2930            return Ok(false);
2931        }
2932        if let Err(err) = self.drive_session_rekey(peer_id, "requested by the application") {
2933            // Nothing was sent and nothing was torn down, so nothing was
2934            // spent: a caller back in range a second from now is asking for a
2935            // rotation this pair has not had.
2936            self.release_rekey_slot(peer_id);
2937            return Err(err);
2938        }
2939        Ok(true)
2940    }
2941
2942    /// Establishes a secure MLS session with a peer.
2943    ///
2944    /// This high-level method handles the complete session establishment flow:
2945    /// 1. Checks if a session already exists (returns Ok(None) if so)
2946    /// 2. Checks for a pending key package from the peer
2947    /// 3. If found, imports the key package, creates the session, and sends the Welcome message
2948    /// 4. If no key package is available, returns an error
2949    ///
2950    /// This method is designed for use by application code that needs explicit control
2951    /// over session establishment, as opposed to the automatic encryption flow.
2952    ///
2953    /// # Arguments
2954    ///
2955    /// * `peer_id` - The ID of the peer to establish a session with
2956    ///
2957    /// # Returns
2958    ///
2959    /// * `Ok(Some(WelcomeMessage))` - Session created, Welcome message returned (and sent to peer)
2960    /// * `Ok(None)` - Session already exists
2961    /// * `Err(SessionNotReady(state))` - Establishment in progress; caller can retry or show "Establishing…"
2962    pub fn establish_secure_session(&mut self, peer_id: &str) -> Result<Option<WelcomeMessage>> {
2963        if self.is_user_blocked(peer_id) {
2964            return Err(Error::UserBlocked(peer_id.to_string()));
2965        }
2966
2967        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
2968
2969        // Check if session already exists
2970        let has_session = {
2971            let manager = mls
2972                .read()
2973                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
2974            manager.has_session(peer_id)?
2975        };
2976
2977        if has_session {
2978            debug!(peer_id = %peer_id, "Session already exists");
2979            return Ok(None);
2980        }
2981
2982        // Try loading key package from storage (e.g. after restart) before giving up
2983        self.try_load_key_package_from_storage_into_memory(peer_id);
2984
2985        // Check for pending key package (memory, possibly just restored from storage)
2986        // Clone first, only remove after all operations succeed to avoid losing the key package on failure
2987        if let Some(received_pkg) = self.pending_key_packages.get(peer_id).cloned() {
2988            // Check if key package has expired (using local clock)
2989            let now_ms = Utc::now().timestamp_millis() as u64;
2990            if now_ms >= received_pkg.local_expires_at_ms {
2991                warn!(peer_id = %peer_id, "Received key package has expired, discarding");
2992                self.pending_key_packages.remove(peer_id);
2993                self.delete_peer_key_package_from_storage(peer_id);
2994            } else {
2995                self.import_pending_key_package(&mls, peer_id, &received_pkg.key_package_data)?;
2996
2997                // Create session and get welcome message
2998                let welcome = {
2999                    let manager = mls
3000                        .read()
3001                        .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3002                    manager.create_session(peer_id)?
3003                };
3004                // The handshake starts here. This is the auto-establish path
3005                // taken the moment a peer's key package arrives, which is how
3006                // an ordinary session begins and which raises no
3007                // `session_missing` at all; see `emit_mls_session_establishing`.
3008                self.emit_mls_session_establishing(
3009                    peer_id,
3010                    welcome.group_id.as_str(),
3011                    crate::mls_observability::MlsOperationContext::Welcome,
3012                );
3013                // We only ever build a session from a key package the peer
3014                // published, so reaching here proves they run MLS.
3015                self.mark_encryption_capable(peer_id);
3016
3017                // Send welcome message to peer
3018                let welcome_sent = self.send_welcome_message(peer_id, &welcome)?;
3019
3020                // All operations succeeded, now safe to remove the key package
3021                self.pending_key_packages.remove(peer_id);
3022                self.delete_peer_key_package_from_storage(peer_id);
3023
3024                let group_id = welcome.group_id.as_str().to_string();
3025                let is_session = group_id.starts_with("session:");
3026                if let Err(err) = self.ensure_session_state_entry(peer_id, "session_created_local")
3027                {
3028                    warn!(
3029                        peer_id = %peer_id,
3030                        error = %err,
3031                        "Failed to persist pending session state"
3032                    );
3033                }
3034
3035                info!(peer_id = %peer_id, group_id = %group_id, "Established secure session");
3036
3037                // Send a fresh key package so the peer has one available for
3038                // group invites (the original was consumed to create this session).
3039                if self.config.encryption.enabled {
3040                    let _ = self.send_key_package_to(peer_id, false);
3041                }
3042
3043                if welcome_sent {
3044                    debug!(peer_id = %peer_id, group_id = %group_id, is_session, "Welcome synchronously sent");
3045                }
3046
3047                return Ok(Some(welcome));
3048            }
3049        }
3050
3051        // No key package available (memory nor storage) — return non-terminal state so caller can retry
3052        Err(Error::SessionNotReady(self.establishment_state(peer_id)?))
3053    }
3054
3055    /// Imports `peer_id`'s pending key package into MLS, reporting a refusal
3056    /// by this device's clock.
3057    ///
3058    /// The one place the engine admits a pending package, so that the refusal
3059    /// is reported whichever route reached it: `establish_secure_session`,
3060    /// taken when a package arrives, and the send path's
3061    /// `ensure_session_establishment`, taken on the first send after a
3062    /// restart or with `auto_key_exchange` off. Reported on only the first,
3063    /// the restart case left a message queued "anyway" with nothing to say why,
3064    /// which is the failure the code exists for. The throttle makes a second
3065    /// route free: one event per peer either way.
3066    ///
3067    /// A window that has not started keeps the package, since it becomes valid
3068    /// once the clocks agree. A window that has closed discards it, exactly as
3069    /// an expired cached package is discarded, because it may be a package a
3070    /// relay held for days rather than a clock, and kept it would fail every
3071    /// attempt until its cached expiry. The next package the peer sends
3072    /// replaces it.
3073    pub(super) fn import_pending_key_package(
3074        &mut self,
3075        mls: &Arc<RwLock<MlsManager>>,
3076        peer_id: &str,
3077        key_package_data: &[u8],
3078    ) -> Result<()> {
3079        let imported = {
3080            let manager = mls
3081                .read()
3082                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3083            manager.import_key_package(peer_id, key_package_data)
3084        };
3085        if let Err(offline_protocol_mls::MlsError::KeyPackageOutsideValidityWindow { expired }) =
3086            &imported
3087        {
3088            let reason = if *expired {
3089                warn!(
3090                    peer_id = %peer_id,
3091                    "Peer key package's validity window has closed by this device's \
3092                     clock; discarding it until the peer sends a fresh one"
3093                );
3094                self.pending_key_packages.remove(peer_id);
3095                self.delete_peer_key_package_from_storage(peer_id);
3096                "The peer's key package has expired by this device's clock. Either \
3097                 this device's date is ahead, or the package is older than its 30-day \
3098                 window; it is discarded and the next one the peer sends replaces it."
3099            } else {
3100                warn!(
3101                    peer_id = %peer_id,
3102                    "Peer key package's validity window has not started by this \
3103                     device's clock; this device cannot start a session with the peer \
3104                     until the clocks agree"
3105                );
3106                "The peer's key package is not valid yet at this device's time. \
3107                 Check this device's date and time, then the peer's."
3108            };
3109            self.warn_control_gate_rejection(
3110                peer_id,
3111                crate::events::SecurityWarningCode::KeyPackageOutsideValidityWindow,
3112                reason,
3113            );
3114        }
3115        Ok(imported?)
3116    }
3117
3118    /// Checks if a pending key package is available for a peer.
3119    ///
3120    /// This can be used to check if session establishment is possible
3121    /// before calling `establish_secure_session`.
3122    ///
3123    /// # Arguments
3124    ///
3125    /// * `peer_id` - The ID of the peer to check
3126    ///
3127    /// # Returns
3128    ///
3129    /// `true` if a key package is available, `false` otherwise
3130    pub fn has_pending_key_package(&self, peer_id: &str) -> bool {
3131        self.pending_key_packages.contains_key(peer_id)
3132    }
3133
3134    /// Returns the current establishment state for a peer.
3135    ///
3136    /// Use this to show "Establishing…" or drive retries without calling send/establish.
3137    pub fn get_establishment_state(&self, peer_id: &str) -> Result<EstablishmentState> {
3138        self.establishment_state(peer_id)
3139    }
3140
3141    /// Whether rich extras (reply context, rich media metadata, forward
3142    /// attribution) on a send toward `peer_id` would travel in the sealed
3143    /// rich body — i.e. the peer's last key package advertised the
3144    /// capability (surviving restarts) and our own `rich_payload_enabled`
3145    /// kill switch is on. When `false` the extras are silently dropped and
3146    /// the message degrades to plain text, so apps can use this to render
3147    /// honest degraded-reply UX instead of discovering the drop after the
3148    /// fact.
3149    pub fn peer_supports_rich_payload(&self, peer_id: &str) -> bool {
3150        self.rich_seal_active(peer_id)
3151    }
3152
3153    /// Creates a session using manually imported key material.
3154    ///
3155    /// This entrypoint is for bindings that expose low-level MLS APIs. It must
3156    /// still keep protocol-level session lifecycle state in sync with MLS state.
3157    pub fn manual_mls_create_session(&mut self, peer_id: &str) -> Result<WelcomeMessage> {
3158        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3159        let welcome = {
3160            let manager = mls
3161                .read()
3162                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3163            manager.create_session(peer_id)?
3164        };
3165        self.mark_encryption_capable(peer_id);
3166        if let Err(err) = self.ensure_session_state_entry(peer_id, "manual_session_created") {
3167            warn!(
3168                peer_id = %peer_id,
3169                error = %err,
3170                "Failed to persist pending session state after manual session create"
3171            );
3172        }
3173        Ok(welcome)
3174    }
3175
3176    /// Imports a contact's key package and records them encryption-capable.
3177    ///
3178    /// The entry point for bindings that expose low-level MLS APIs. It exists
3179    /// because the FFI wrapper used to reach straight for the `MlsManager` and
3180    /// pass the since-deleted `KeyPackageTrust::FirstUse` — so an app could
3181    /// import a key package
3182    /// under any peer id with no correlation to that peer, bypassing the check
3183    /// `establish_secure_session` performs. The identity claim no longer needs
3184    /// the detour: `import_key_package` re-derives the address from the leaf
3185    /// signature key and refuses a mismatch on its own. The routing stays
3186    /// because the capability record lives here, not on the manager.
3187    pub fn manual_mls_import_key_package(
3188        &mut self,
3189        peer_id: &str,
3190        key_package_data: &[u8],
3191    ) -> Result<()> {
3192        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3193        {
3194            let manager = mls
3195                .read()
3196                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3197            manager.import_key_package(peer_id, key_package_data)?;
3198        }
3199        // A key package we accepted for this peer is proof they run MLS.
3200        self.mark_encryption_capable(peer_id);
3201        Ok(())
3202    }
3203
3204    /// Deletes a 1:1 session and clears protocol-level lifecycle state.
3205    pub fn manual_mls_delete_session(&mut self, peer_id: &str) -> Result<()> {
3206        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3207        let manager = mls
3208            .read()
3209            .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3210        manager.delete_session(peer_id)?;
3211
3212        // Apply protocol-state cleanup only after MLS deletion succeeds.
3213        self.confirmed_sessions.remove(peer_id);
3214        self.clear_confirmation_recovery_tracking(peer_id);
3215        self.welcome_lifecycles.remove(peer_id);
3216        // Drop the both-create owner gate too (memory + storage). A leaked gate
3217        // entry would make `can_confirm_from_source` reject every non-decrypt
3218        // confirmation source — including `welcome_received` — on the NEXT
3219        // session with this peer, re-stranding it in Pending (and surviving
3220        // restart via `restore_both_create_awaiting_decrypt`).
3221        self.clear_both_create_awaiting_decrypt(peer_id);
3222        self.clear_session_state_entry(peer_id)?;
3223        self.clear_welcome_lifecycle_entry(peer_id)?;
3224        Ok(())
3225    }
3226
3227    /// Joins a session from a Welcome message and synchronizes confirmation state.
3228    pub fn manual_mls_join_session(
3229        &mut self,
3230        welcome: &WelcomeMessage,
3231    ) -> Result<offline_protocol_mls::GroupInfo> {
3232        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3233        let group_info = {
3234            let manager = mls
3235                .read()
3236                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3237            manager.join_session(welcome)?
3238        };
3239        self.handle_manual_welcome_confirmation(&welcome.inviter_id);
3240        Ok(group_info)
3241    }
3242
3243    /// Processes an MLS Welcome message and synchronizes confirmation state.
3244    pub fn manual_mls_process_welcome(
3245        &mut self,
3246        welcome: &WelcomeMessage,
3247    ) -> Result<offline_protocol_mls::GroupInfo> {
3248        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3249        let group_info = {
3250            let manager = mls
3251                .read()
3252                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3253            manager.process_welcome(welcome)?
3254        };
3255        self.handle_manual_welcome_confirmation(&welcome.inviter_id);
3256        Ok(group_info)
3257    }
3258
3259    /// Decrypts a user-scoped MLS message and synchronizes confirmation state.
3260    pub fn manual_mls_decrypt_from_user(
3261        &mut self,
3262        encrypted: &EncryptedMessage,
3263    ) -> Result<Option<Vec<u8>>> {
3264        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3265        let plaintext = {
3266            let manager = mls
3267                .read()
3268                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3269            manager.decrypt_from_user(encrypted, &encrypted.sender_id)?
3270        };
3271        if plaintext.is_some() {
3272            self.handle_manual_decrypt_confirmation(&encrypted.sender_id);
3273        }
3274        Ok(plaintext)
3275    }
3276
3277    /// Decrypts any MLS message and synchronizes confirmation state for 1:1 flows.
3278    pub fn manual_mls_decrypt(&mut self, encrypted: &EncryptedMessage) -> Result<Option<Vec<u8>>> {
3279        let mls = self.mls_manager.clone().ok_or(Error::MlsNotInitialized)?;
3280        let plaintext = {
3281            let manager = mls
3282                .read()
3283                .map_err(|_| Error::Other("MLS lock poisoned".to_string()))?;
3284            manager.decrypt(encrypted, &encrypted.sender_id)?
3285        };
3286        if plaintext.is_some() && Self::is_session_group_id(encrypted.group_id.as_str()) {
3287            self.handle_manual_decrypt_confirmation(&encrypted.sender_id);
3288        }
3289        Ok(plaintext)
3290    }
3291
3292    pub(crate) fn is_session_group_id(group_id: &str) -> bool {
3293        group_id.starts_with("session:")
3294    }
3295
3296    fn handle_manual_welcome_confirmation(&mut self, peer_id: &str) {
3297        // Shared by `manual_mls_join_session` and `manual_mls_process_welcome`:
3298        // in both cases we just joined a session this peer built for us.
3299        self.mark_encryption_capable(peer_id);
3300        match self.confirm_session_state(peer_id, "welcome_received") {
3301            Ok(true) => {
3302                let _ = self.flush_pending_messages(peer_id);
3303                self.process_pending_decryption(peer_id);
3304            }
3305            Ok(false) => {}
3306            Err(err) => {
3307                warn!(
3308                    peer_id = %peer_id,
3309                    error = %err,
3310                    "Failed to persist session confirmation after manual welcome processing"
3311                );
3312            }
3313        }
3314    }
3315
3316    fn handle_manual_decrypt_confirmation(&mut self, peer_id: &str) {
3317        if !self.can_confirm_from_source(peer_id, "decrypt_success") {
3318            return;
3319        }
3320        match self.confirm_session_state(peer_id, "decrypt_success") {
3321            Ok(true) => {
3322                let _ = self.flush_pending_messages(peer_id);
3323            }
3324            Ok(false) => {}
3325            Err(err) => {
3326                warn!(
3327                    peer_id = %peer_id,
3328                    error = %err,
3329                    "Failed to persist session confirmation after manual decrypt"
3330                );
3331            }
3332        }
3333    }
3334
3335    /// Processes internal MLS protocol messages.
3336    ///
3337    /// Returns `Some(InternalMessageResult::Consumed)` if the message was an internal
3338    /// protocol message that should not be surfaced to the application.
3339    /// Returns `Some(InternalMessageResult::Decrypted(plaintext))` if the message was
3340    /// encrypted and successfully decrypted.
3341    /// Returns `None` if the message is not an internal message.
3342    pub(crate) fn process_internal_message(
3343        &mut self,
3344        message: &Message,
3345    ) -> Option<InternalMessageResult> {
3346        self.process_internal_message_via(message, None)
3347    }
3348
3349    /// [`Self::process_internal_message`] with the transport the frame
3350    /// arrived on, when the caller knows it. Handlers that trust relay-server
3351    /// answers (`__GROUP_CREATED__` setting `relay_synced`) require the
3352    /// Internet transport; with `None` they treat the frame as untrusted.
3353    pub(crate) fn process_internal_message_via(
3354        &mut self,
3355        message: &Message,
3356        arrival_transport: Option<TransportType>,
3357    ) -> Option<InternalMessageResult> {
3358        let content = &message.content;
3359
3360        // Run the security gate for control messages (transport identity +
3361        // signature verification + freshness). `Rejected` drops the message;
3362        // `Proceed` carries whether the frame was actually signed, for the one
3363        // handler that consumes a payload field as authenticated data, and
3364        // whether its age was established, for the one that acts on a
3365        // directive worth replaying.
3366        let (signed, freshness_bound) =
3367            match self.security_gate_control_message(message, arrival_transport) {
3368                ControlGateOutcome::Rejected(result) => return Some(result),
3369                ControlGateOutcome::Proceed {
3370                    signed,
3371                    freshness_bound,
3372                } => (signed, freshness_bound),
3373            };
3374
3375        let sender = message.sender.as_str();
3376
3377        // Handle key package messages
3378        if let Some(data) = content.strip_prefix(internal_prefixes::KEY_PACKAGE) {
3379            // The stamp travels only when it was signed *and* checked, so a
3380            // handler cannot reach for it in the case where it means nothing.
3381            let freshness = freshness_bound.then(|| message.timestamp.as_millis());
3382            self.handle_key_package_message(sender, data, signed, freshness);
3383            return Some(InternalMessageResult::Consumed);
3384        }
3385
3386        if content.starts_with(internal_prefixes::SESSION_CONFIRM_PROBE) {
3387            self.handle_session_confirm_probe(sender, content);
3388            return Some(InternalMessageResult::Consumed);
3389        }
3390
3391        if content.starts_with(internal_prefixes::SESSION_CONFIRM_ACK) {
3392            self.handle_session_confirm_ack(sender, content);
3393            return Some(InternalMessageResult::Consumed);
3394        }
3395
3396        // Handle welcome messages (session invitation)
3397        if let Some(data) = content.strip_prefix(internal_prefixes::WELCOME) {
3398            self.handle_welcome_message(sender, data);
3399            return Some(InternalMessageResult::Consumed);
3400        }
3401
3402        // Handle encrypted messages
3403        if let Some(data) = content.strip_prefix(internal_prefixes::ENCRYPTED) {
3404            if let Some(result) =
3405                self.handle_encrypted_message(sender, data, message, arrival_transport)
3406            {
3407                return Some(result);
3408            }
3409            return Some(InternalMessageResult::Consumed);
3410        }
3411
3412        // Handle connection request messages
3413        if let Some(data) = content.strip_prefix(internal_prefixes::CONN_REQUEST) {
3414            self.handle_connection_request(sender, data);
3415            return Some(InternalMessageResult::Consumed);
3416        }
3417
3418        // Handle connection accepted messages
3419        if let Some(data) = content.strip_prefix(internal_prefixes::CONN_ACCEPT) {
3420            self.handle_connection_accepted(sender, data);
3421            return Some(InternalMessageResult::Consumed);
3422        }
3423
3424        // Handle connection rejected messages
3425        if content
3426            .strip_prefix(internal_prefixes::CONN_REJECT)
3427            .is_some()
3428        {
3429            self.handle_connection_rejected(sender);
3430            return Some(InternalMessageResult::Consumed);
3431        }
3432
3433        // Handle connection cancelled messages
3434        if content
3435            .strip_prefix(internal_prefixes::CONN_CANCEL)
3436            .is_some()
3437        {
3438            self.handle_connection_cancelled(sender);
3439            return Some(InternalMessageResult::Consumed);
3440        }
3441
3442        // --- Presence, typing, and read receipt messages ---
3443
3444        if let Some(data) = content.strip_prefix(internal_prefixes::PRESENCE) {
3445            self.handle_presence_message(sender, data);
3446            return Some(InternalMessageResult::Consumed);
3447        }
3448
3449        if let Some(data) = content.strip_prefix(internal_prefixes::TYPING_INDICATOR) {
3450            self.handle_typing_indicator(sender, data);
3451            return Some(InternalMessageResult::Consumed);
3452        }
3453
3454        if let Some(data) = content.strip_prefix(internal_prefixes::READ_RECEIPT) {
3455            self.handle_read_receipt(sender, data);
3456            return Some(InternalMessageResult::Consumed);
3457        }
3458
3459        // A custody receipt from a neighbour holding one of our frames. Past
3460        // the control gate like every signed frame; it suppresses re-deposit
3461        // toward that custodian and settles nothing (`docs/spec/custody.md`).
3462        // Consumed whatever the body says: a malformed one is refused
3463        // silently, and a receipt never requests an acknowledgement.
3464        if let Some(data) = content.strip_prefix(internal_prefixes::CUSTODY_RECEIPT) {
3465            self.handle_custody_receipt(sender, data, message.timestamp.as_millis());
3466            return Some(InternalMessageResult::Consumed);
3467        }
3468
3469        // --- Group (mesh/MLS) messages ---
3470
3471        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_MLS_MSG) {
3472            return Some(self.handle_group_mls_msg_via(message, sender, data, arrival_transport));
3473        }
3474
3475        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_MLS_WELCOME) {
3476            let mid = message.id.as_str();
3477            self.handle_group_mls_welcome(&mid, sender, data);
3478            return Some(InternalMessageResult::Consumed);
3479        }
3480
3481        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_MLS_COMMIT) {
3482            let mid = message.id.as_str();
3483            self.handle_group_mls_commit(&mid, sender, data);
3484            return Some(InternalMessageResult::Consumed);
3485        }
3486
3487        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_MLS_LEAVE) {
3488            let mid = message.id.as_str();
3489            self.handle_group_mls_leave(&mid, sender, data);
3490            return Some(InternalMessageResult::Consumed);
3491        }
3492
3493        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_ROLE_CHANGE) {
3494            let mid = message.id.as_str();
3495            self.handle_group_role_change(&mid, sender, data);
3496            return Some(InternalMessageResult::Consumed);
3497        }
3498
3499        if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_RENAME) {
3500            let mid = message.id.as_str();
3501            self.handle_group_rename(&mid, sender, data);
3502            return Some(InternalMessageResult::Consumed);
3503        }
3504
3505        // --- Group (relay) and service messages ---
3506
3507        if content.starts_with(internal_prefixes::GROUP_CREATED)
3508            || content.starts_with(internal_prefixes::GROUP_MSG)
3509            || content.starts_with(internal_prefixes::GROUP_MEMBER_ADDED)
3510            || content.starts_with(internal_prefixes::GROUP_MEMBER_REMOVED)
3511            || content.starts_with(internal_prefixes::GROUP_INFO)
3512            || content.starts_with(internal_prefixes::USER_GROUPS)
3513            || content.starts_with(internal_prefixes::GROUP_ERROR)
3514        {
3515            self.handle_group_relay_message(sender, content, arrival_transport);
3516            return Some(InternalMessageResult::Consumed);
3517        }
3518
3519        // --- Service discovery & request/response ---
3520        if content.starts_with(offline_protocol_services::SVC_MESSAGE_PREFIX) {
3521            self.handle_service_message(sender, content, message);
3522            return Some(InternalMessageResult::Consumed);
3523        }
3524
3525        None // Not an internal message
3526    }
3527
3528    /// Registers an event handler.
3529    ///
3530    /// # Arguments
3531    ///
3532    /// * `handler` - Callback function that will be called for each event
3533    pub fn on_event<F>(&mut self, handler: F)
3534    where
3535        F: Fn(Event) + Send + Sync + 'static,
3536    {
3537        let Ok(mut state) = lock_shared_state(&self.shared_state) else {
3538            error!("Failed to lock shared state in on_event");
3539            return;
3540        };
3541        state.event_handlers.push(Arc::new(handler));
3542    }
3543
3544    /// Processes pending operations (retries, timeouts, etc.).
3545    ///
3546    /// This should be called periodically to handle background tasks.
3547    pub fn process(&mut self) -> Result<()> {
3548        {
3549            let state = lock_shared_state(&self.shared_state)?;
3550            if state.state != ProtocolState::Running {
3551                return Ok(()); // Don't process if not running
3552            }
3553        }
3554
3555        // Transmit forwards whose hold has elapsed. Runs early and before the
3556        // retry ladders: other people's traffic is time-sensitive in a way our
3557        // own retries are not — a frame held too long is dropped rather than
3558        // sent late.
3559        self.flush_mesh_relays();
3560        // Held frames past their hold, and receipt suppressions past their
3561        // end. Throttled inside; hours-long holds need no per-tick walk.
3562        self.sweep_custody();
3563
3564        self.process_retry_queue()?;
3565        self.process_welcome_retry_queue()?;
3566        self.process_relay_register_retries();
3567        self.process_relay_broadcast_report_timeouts();
3568        self.process_timed_out_acks()?;
3569
3570        // Throttle session reconciliation to avoid expensive storage I/O
3571        // (list_sessions → Keychain/Keystore) on every tick. Only run when
3572        // there's pending work AND enough time has elapsed since the last run.
3573        self.run_throttled_reconciliation("process_tick");
3574
3575        let _ = self.prune_expired_pending_global_front(Instant::now(), 256);
3576        // Batched like the Lamport clock: the seen set reaches disk on a
3577        // change threshold or a time cadence, never per message.
3578        self.persist_dedup_seen_if_due();
3579        self.pump_media_transfers();
3580        #[cfg(feature = "data")]
3581        self.send_due_data_settle_offers(Instant::now());
3582        self.refresh_nostr_key_package_slots();
3583        self.refresh_nostr_discovery_claim();
3584        // A relay is free never to send end-of-stored-events, and that is the
3585        // only natural completion signal a resolution has. Without this sweep
3586        // a quiet relay turns a lookup into a hang rather than an empty answer.
3587        self.sweep_username_resolutions();
3588        self.cleanup_expired_entries();
3589        self.evaluate_relay_role();
3590        self.tick_telemetry_categories();
3591
3592        Ok(())
3593    }
3594
3595    /// Reports this device's condition to the forwarding governor and announces
3596    /// any change in whether it is acting as a relay (`RelayPromoted`,
3597    /// `RelayDemoted`, `RelayDemotedBattery`).
3598    ///
3599    /// Runs every tick independently of telemetry: these are app-facing events
3600    /// delivered through the `EventCallback` channel, which is live whether or
3601    /// not a telemetry sink is installed. It also keeps the
3602    /// `DeviceCapabilitySnapshot.relay_role` signal honest, since
3603    /// `tick_telemetry_categories` reads the standing immediately after.
3604    ///
3605    /// **The relay standing is observed, not predicted.** It says this device
3606    /// has been carrying other people's traffic, not that its battery and
3607    /// neighbor count suggest it could — those only bias *how much* it carries
3608    /// (`set_conditions`), continuously and with no threshold to cross. So the
3609    /// promotion here is a report about the mesh, and an app can trust
3610    /// `is_relay()` to mean the device is doing the work.
3611    ///
3612    /// Two things still transition on policy rather than on observation, and
3613    /// both are gates rather than predictions: relaying switched off in
3614    /// configuration, and the battery falling through the forwarding floor.
3615    /// Each stops forwarding outright, so the standing is surrendered at once
3616    /// instead of decaying over the activity windows — the window measures
3617    /// quiet, and this is refusal.
3618    ///
3619    /// Unlike the threshold policy this replaces, a device with no battery
3620    /// reading still participates: forwarding is what is being observed, and
3621    /// it happens whether or not the host has reported a level.
3622    fn evaluate_relay_role(&mut self) {
3623        let (_statuses, available) = self.transport_manager.snapshot_status_and_available();
3624        let (battery_level, is_charging) =
3625            device_battery_from_available(self.transport_manager.current_transport(), &available);
3626
3627        let eager = matches!(self.config.relay.relay_priority, RelayPriority::Always);
3628        // The bias ramp is measured from the level at which forwarding actually
3629        // stops, which is the configured minimum raised to the hard critical
3630        // floor — not the raw configured value, which may be set below it.
3631        // Passing the unclamped one would start the ramp under the gate and
3632        // scale a device that is about to stop forwarding altogether.
3633        let forwarding_floor = self.relay_battery_floor(is_charging);
3634        self.mesh_relay
3635            .set_conditions(battery_level, is_charging, eager, forwarding_floor);
3636        let relay = &self.config.relay;
3637
3638        // Relaying switched off in configuration.
3639        if !relay.allow_relay || matches!(relay.relay_priority, RelayPriority::Never) {
3640            if self.mesh_relay.force_inactive() {
3641                self.emit_event(Event::relay_demoted("relaying disabled by configuration"));
3642            }
3643            return;
3644        }
3645
3646        // Battery through the forwarding floor. Same gate `try_relay_message`
3647        // applies to each frame, evaluated from the reading already in hand.
3648        if !self.battery_allows_relaying_with(battery_level, is_charging) {
3649            if self.mesh_relay.force_inactive() {
3650                self.emit_event(Event::relay_demoted_battery(
3651                    battery_level.unwrap_or(0),
3652                    self.relay_battery_floor(is_charging),
3653                ));
3654            }
3655            return;
3656        }
3657
3658        match self.mesh_relay.observe_activity(Instant::now()) {
3659            Some(RelayActivity::Began { .. }) => {
3660                let connection_count = self.known_peers.len();
3661                self.emit_event(Event::relay_promoted(connection_count, battery_level));
3662            }
3663            Some(RelayActivity::Ceased) => {
3664                self.emit_event(Event::relay_demoted(
3665                    "no traffic carried for other devices recently",
3666                ));
3667            }
3668            None => {}
3669        }
3670    }
3671
3672    /// The relay standing this device currently holds, for telemetry.
3673    fn relay_role(&self) -> RelayRole {
3674        if self.mesh_relay.is_active_relay() {
3675            RelayRole::Relay
3676        } else {
3677            RelayRole::Regular
3678        }
3679    }
3680
3681    /// Per-tick telemetry work: diff transport statuses, diff device
3682    /// capability, and emit a `MetricsFrame` when `metrics_cadence` has
3683    /// elapsed. No-ops unless a sink has been installed.
3684    ///
3685    /// Runs at the end of `process()` so reliability/queue state observed
3686    /// here is the same state the rest of the tick has already advanced.
3687    /// Snapshots `get_available_transports()` exactly once per tick and
3688    /// reuses the map across every downstream helper that needs it.
3689    ///
3690    /// If an earlier step in `process()` returns `Err(...)`, this method is
3691    /// skipped and telemetry emission for that interval is deferred to the
3692    /// next successful tick — the cadence guarantee relaxes under sustained
3693    /// partial failure.
3694    ///
3695    /// # Sink-panic semantics
3696    ///
3697    /// Each per-tick cursor is advanced *before* the emit call that
3698    /// observes it, so a panicking sink does not cause re-delivery of the
3699    /// record it panicked on. The transport-status path advances
3700    /// **per-transport**: when multiple transitions fall in a single tick,
3701    /// a panic on transition K commits K's entry (at-most-once for K) but
3702    /// leaves entries L..N in `transport_status_snapshot` at their previous
3703    /// values, so the next tick re-diffs and emits them fresh. This avoids
3704    /// silent data loss for transitions that never reached the sink.
3705    ///
3706    /// The device-capability and metrics-frame paths emit at most one
3707    /// record per tick each, so a simpler "advance then emit" discipline
3708    /// suffices there: a panic advances the cursor and the same record is
3709    /// not re-emitted on the next tick.
3710    fn tick_telemetry_categories(&mut self) {
3711        let Some(ctx) = self.telemetry.clone().filter(|ctx| ctx.enabled()) else {
3712            return;
3713        };
3714        let now_ms = Utc::now().timestamp_millis();
3715        let now = Instant::now();
3716
3717        // One lock-per-transport pass: get statuses (for the transition
3718        // diff) and the available-only metrics map (for the metrics frame
3719        // and the device-capability diff). Reused across every helper
3720        // below.
3721        let (current_statuses, available) = self.transport_manager.snapshot_status_and_available();
3722
3723        // Transport-status diff: one record per changed transport. Commit
3724        // each transport's new snapshot entry *before* emitting its event
3725        // so a panic on event K is at-most-once for K; untouched entries
3726        // L..N stay at their previous values and get re-diffed next tick.
3727        let transitions =
3728            diff_transport_state(now_ms, &self.transport_status_snapshot, &current_statuses);
3729        for event in transitions {
3730            let transport = event.transport;
3731            match current_statuses.get(&transport) {
3732                Some(status) => {
3733                    self.transport_status_snapshot.insert(transport, *status);
3734                }
3735                None => {
3736                    self.transport_status_snapshot.remove(&transport);
3737                }
3738            }
3739            dispatch_record(&ctx.sink, &TelemetryRecord::TransportState(event));
3740            // An internet-capable transport coming up is the pipe's cue to
3741            // send what an offline stretch queued; the pipe decides which
3742            // transports count.
3743            #[cfg(feature = "telemetry-pipe")]
3744            if let Some(pipe) = &self.telemetry_pipe {
3745                pipe.notify_transport(event.transport, event.current);
3746            }
3747        }
3748
3749        // Device capability diff. At-most-one emission per tick, so the
3750        // simple advance-before-emit pattern preserves at-most-once.
3751        let (battery_level, is_charging) =
3752            device_battery_from_available(self.transport_manager.current_transport(), &available);
3753        let relay_role = self.relay_role();
3754        let device_now = DeviceSnap::from_parts(battery_level, is_charging, relay_role);
3755        let device_change =
3756            diff_device_capability(now_ms, self.device_capability_snapshot, device_now);
3757        self.device_capability_snapshot = Some(device_now);
3758        if let Some(snapshot) = device_change {
3759            dispatch_record(&ctx.sink, &TelemetryRecord::Device(snapshot));
3760        }
3761
3762        // Periodic metrics snapshot. Rearm cadence before emit so a
3763        // panicking sink doesn't cause an immediate retry next tick.
3764        if let Some(cadence) = ctx.config.metrics_cadence() {
3765            let due = match self.last_metrics_emit_at {
3766                None => true,
3767                Some(prev) => now.saturating_duration_since(prev) >= cadence,
3768            };
3769            if due {
3770                let is_local_relay = matches!(relay_role, RelayRole::Relay);
3771                let frame = build_metrics_frame(
3772                    now_ms,
3773                    self.transport_manager.current_transport(),
3774                    &available,
3775                    &self.retry_queue,
3776                    &self.deduplicator,
3777                    &self.ack_manager,
3778                    self.known_peers.len(),
3779                    is_local_relay,
3780                );
3781                self.last_metrics_emit_at = Some(now);
3782                dispatch_record(
3783                    &ctx.sink,
3784                    &TelemetryRecord::MetricsSnapshot(Box::new(frame)),
3785                );
3786            }
3787        }
3788    }
3789
3790    /// Processes messages ready for retry from the retry queue.
3791    ///
3792    /// EDGE CASE HANDLING:
3793    /// - Checks transport availability before each retry attempt
3794    /// - Handles transport switch mid-retry
3795    /// - Properly tracks retry counts and transport failures
3796    fn process_retry_queue(&mut self) -> Result<()> {
3797        // Limit batch size to prevent blocking on large queues
3798        let mut max_batch_size = crate::constants::FLUSH_BATCH_LIMIT;
3799
3800        // Opt-in resend rate cap: bound how fast the RETRY/PROBE path re-sends,
3801        // so a backlog of resends to unreachable peers cannot burst past the
3802        // relay's per-connection rate limit and flap the connection. Refills a
3803        // token bucket by elapsed wall-time and caps this call's batch to the
3804        // whole tokens available. Only resends are bounded; first-attempt sends,
3805        // ACKs, control frames and handshakes take other paths and are never
3806        // throttled, so live traffic keeps full throughput and latency. Fully
3807        // off by default (unchanged retry behaviour for every existing app).
3808        if self.config.reliability.retry.edge_driven_unreachable_dm {
3809            let now = Instant::now();
3810            match self.retry_drain_last {
3811                Some(last) => {
3812                    let elapsed = now.duration_since(last).as_secs_f64();
3813                    self.retry_drain_tokens = (self.retry_drain_tokens
3814                        + elapsed * crate::protocol::types::RETRY_DRAIN_RATE_PER_SEC)
3815                        .min(crate::protocol::types::RETRY_DRAIN_BURST);
3816                }
3817                None => {
3818                    // First drain: start with a full burst budget.
3819                    self.retry_drain_tokens = crate::protocol::types::RETRY_DRAIN_BURST;
3820                }
3821            }
3822            self.retry_drain_last = Some(now);
3823            let budget = self.retry_drain_tokens.floor() as usize;
3824            max_batch_size = max_batch_size.min(budget);
3825        }
3826
3827        let mut processed = 0;
3828
3829        while processed < max_batch_size {
3830            let mut entry = match self.retry_queue.dequeue_ready() {
3831                Some(e) => e,
3832                None => break,
3833            };
3834
3835            processed += 1;
3836            let previous_transport = self.transport_manager.current_transport();
3837            // Normally finds the entry already there: a retry entry outlives
3838            // its outbox entry only if a give-up path skipped
3839            // `retire_undeliverable_message`, and at capacity this call would
3840            // then evict a live message to bring a settled one back.
3841            self.ensure_outbox_entry(&entry.message);
3842
3843            // Tier 2: re-seal against the peer's current session before this
3844            // resend, so a post-re-key epoch change no longer leaves the bytes
3845            // undecryptable. No-op for media/plaintext/unconfirmed sessions.
3846            self.reseal_for_resend_in_place(&mut entry.message);
3847
3848            let forced_transport = self.pinned_media_transport_for_message(&entry.message.id);
3849            let send_result = if let Some(transport) = forced_transport {
3850                self.transport_manager
3851                    .send_via_transport(&entry.message, transport)
3852            } else {
3853                self.transport_manager.send(&entry.message)
3854            };
3855            let current_transport =
3856                forced_transport.or_else(|| self.transport_manager.current_transport());
3857
3858            match send_result {
3859                Ok(()) => {
3860                    let ack_registered_now = self.ensure_ack_registration(&entry.message)?;
3861
3862                    if ack_registered_now {
3863                        // The resend registered a brand-new ACK (the prior one
3864                        // was cleared, e.g. by an ACK timeout that re-queued
3865                        // this message). A fresh ACK starts at retry_count 0, so
3866                        // carry the count the retry-queue entry already holds —
3867                        // advanced by this attempt — onto it. Without this the
3868                        // backoff ladder resets to 0 on every relay-accepted
3869                        // resend and `delay_for_retry` is pinned at its 1s floor
3870                        // forever for a peer that never ACKs (an offline
3871                        // recipient), flooding the relay ~once per second.
3872                        self.ack_manager.set_retry_count(
3873                            &entry.message.id,
3874                            entry.retry_count.saturating_add(1),
3875                        );
3876                    } else {
3877                        self.ack_manager.increment_retry_count(&entry.message.id);
3878                    }
3879                    self.mark_message_sent(
3880                        &entry.message,
3881                        current_transport,
3882                        Some(entry.retry_count.saturating_add(1)),
3883                    );
3884
3885                    if let Some(transport) = current_transport {
3886                        self.transport_manager.reset_retry_count(transport);
3887                    }
3888
3889                    debug!(
3890                        message_id = %entry.message.id,
3891                        retry_count = entry.retry_count,
3892                        transport = ?current_transport,
3893                        "Retry send succeeded"
3894                    );
3895                }
3896                Err(e) => {
3897                    // Re-enqueue with incremented retry count for backoff
3898                    let next_retry_at = self
3899                        .retry_queue
3900                        .enqueue(entry.message.clone(), entry.retry_count + 1);
3901
3902                    if let Some(transport) = forced_transport.or(previous_transport) {
3903                        self.transport_manager.record_retry_failure(transport);
3904                    }
3905
3906                    // Surface the schedule so apps can show retry state
3907                    // instead of inferring it from silence. None = the id
3908                    // was already queued; the earlier emission stands.
3909                    if let Some(retry_at) = next_retry_at {
3910                        self.emit_event(Event::message_retrying(
3911                            entry.message.id.clone(),
3912                            entry.message.recipient.as_str().to_string(),
3913                            entry.retry_count + 1,
3914                            retry_at.timestamp_millis(),
3915                        ));
3916                    }
3917
3918                    debug!(
3919                        message_id = %entry.message.id,
3920                        retry_count = entry.retry_count,
3921                        transport = ?current_transport,
3922                        error = %e,
3923                        "Retry send failed, will retry later"
3924                    );
3925                }
3926            }
3927        }
3928
3929        if processed > 0 {
3930            debug!(processed = processed, "Processed retry queue entries");
3931            // Spend the resend-rate tokens actually used (opt-in cap only).
3932            if self.config.reliability.retry.edge_driven_unreachable_dm {
3933                self.retry_drain_tokens = (self.retry_drain_tokens - processed as f64).max(0.0);
3934            }
3935        }
3936
3937        Ok(())
3938    }
3939
3940    /// Processes timed out ACKs and handles retry or failure.
3941    fn process_timed_out_acks(&mut self) -> Result<()> {
3942        let timed_out = self.ack_manager.drain_timed_out();
3943        for pending in timed_out {
3944            let message_id = pending.message_id.clone();
3945
3946            if pending.retry_count >= self.config.reliability.retry.max_retries {
3947                self.handle_max_retries_exceeded(&message_id, pending.retry_count)?;
3948                continue;
3949            }
3950
3951            self.handle_ack_timeout_retry(&message_id, pending.retry_count)?;
3952        }
3953        Ok(())
3954    }
3955
3956    /// Handles a message that has exceeded maximum retries.
3957    fn handle_max_retries_exceeded(
3958        &mut self,
3959        message_id: &MessageId,
3960        retry_count: u32,
3961    ) -> Result<()> {
3962        // A plain DM whose recipient still holds a live unreachable-park
3963        // counter re-parks instead of settling: the exhausted budget was burnt
3964        // by reachability probes — sends that succeed locally without proving
3965        // the peer is back — not by a peer believed reachable (see
3966        // try_repark_exhausted_dm).
3967        if self.try_repark_exhausted_dm(message_id) {
3968            return Ok(());
3969        }
3970
3971        // Retry exhaustion is terminal for a connection request: settle the
3972        // pending entry and surface the typed undeliverable signal alongside
3973        // the generic message_failed, so apps keep connection-request
3974        // context without parsing reason strings.
3975        let undeliverable_recipient = self.take_undeliverable_connection_request(message_id);
3976
3977        let state = lock_shared_state(&self.shared_state).map_err(|e| {
3978            error!(
3979                "Failed to lock shared state for message failed event: {}",
3980                e
3981            );
3982            e
3983        })?;
3984        state.emit_event(Event::message_failed(
3985            message_id.clone(),
3986            "Max retries exceeded",
3987            retry_count,
3988        ));
3989        if let Some(recipient) = undeliverable_recipient {
3990            warn!(
3991                recipient = %recipient,
3992                message_id = %message_id,
3993                "Connection request undeliverable: max retries exceeded"
3994            );
3995            state.emit_event(Event::connection_request_undeliverable(
3996                recipient,
3997                message_id.as_str(),
3998                "max_retries_exceeded",
3999            ));
4000        }
4001        drop(state);
4002
4003        self.retire_undeliverable_message(message_id, "max retries exceeded");
4004        Ok(())
4005    }
4006
4007    /// Handles retry logic for a timed out ACK.
4008    fn handle_ack_timeout_retry(&mut self, message_id: &MessageId, retry_count: u32) -> Result<()> {
4009        if let Some(entry) = self
4010            .outbox
4011            .get(message_id)
4012            .or_else(|| self.media_outbox.get(message_id))
4013        {
4014            let message_clone = entry.message.clone();
4015            let recipient = entry.message.recipient.as_str().to_string();
4016            let last_transport = entry.last_transport;
4017
4018            // enqueue is infallible (retry queue has no attempt limit)
4019            let next_retry_at = self.retry_queue.enqueue(message_clone, retry_count);
4020            if let Some(transport) = last_transport {
4021                self.transport_manager.record_retry_failure(transport);
4022            }
4023            if let Some(retry_at) = next_retry_at {
4024                self.emit_event(Event::message_retrying(
4025                    message_id.clone(),
4026                    recipient,
4027                    retry_count,
4028                    retry_at.timestamp_millis(),
4029                ));
4030            }
4031        } else {
4032            self.handle_missing_outbox_entry(message_id, retry_count)?;
4033        }
4034        Ok(())
4035    }
4036
4037    /// Emits a protocol event to all registered handlers.
4038    ///
4039    /// Silently no-ops if the shared state lock is poisoned.
4040    pub(crate) fn emit_event(&self, event: Event) {
4041        if let Ok(state) = lock_shared_state(&self.shared_state) {
4042            state.emit_event(event);
4043        }
4044    }
4045
4046    /// Emits a terminal settlement, or parks it until `start()` if the event
4047    /// pipeline is not live yet.
4048    ///
4049    /// Restore paths settle messages the app is still holding ids for. They run
4050    /// from `initialize_mls`, before `start()` and often before the app has
4051    /// installed its event callback, so emitting directly there would silently
4052    /// discard exactly the signals that exist to stop an id from hanging
4053    /// forever. Once running, this is a plain emit — the same call is used from
4054    /// `process()`-driven expiry, where no deferral is wanted.
4055    pub(crate) fn settle_restored_message_failure(&mut self, event: Event) {
4056        let running = self.protocol_is_running();
4057        self.settle_one_restored_message_failure(event, running);
4058    }
4059
4060    /// Settles a batch, taking the shared-state lock once rather than once per
4061    /// event. Restore emits these in loops that a tampered or pre-split store
4062    /// can drive into the thousands.
4063    pub(crate) fn settle_restored_message_failures(
4064        &mut self,
4065        events: impl IntoIterator<Item = Event>,
4066    ) {
4067        let running = self.protocol_is_running();
4068        for event in events {
4069            self.settle_one_restored_message_failure(event, running);
4070        }
4071    }
4072
4073    /// Whether [`Self::start`] has run and nothing has stopped it since.
4074    ///
4075    /// Two callers want different things from the same fact. The restore
4076    /// paths above want to know whether an emit reaches an application at
4077    /// all. The document layer wants to know whether a frame it is about to
4078    /// build can leave the device, because a send attempted before the
4079    /// transports are up stamps a rate-limit window against an offer that
4080    /// was never carried.
4081    pub(crate) fn protocol_is_running(&self) -> bool {
4082        lock_shared_state(&self.shared_state)
4083            .map(|state| state.state == ProtocolState::Running)
4084            .unwrap_or(false)
4085    }
4086
4087    fn settle_one_restored_message_failure(&mut self, event: Event, running: bool) {
4088        if running {
4089            self.emit_event(event);
4090            return;
4091        }
4092        // Every other accumulation on the restore path has an explicit ceiling
4093        // and logs what it dropped; this one is retained until `start()`, which
4094        // may never come, so it gets the same treatment. Keeping the *oldest*
4095        // is deliberate: the settlements a restore produces first are the ones
4096        // for records it examined first, and dropping those in favour of later
4097        // ones would bias the survivors by backend listing order.
4098        if self.deferred_restore_settlements.len() >= MAX_DEFERRED_RESTORE_SETTLEMENTS {
4099            self.suppressed_restore_settlements += 1;
4100            return;
4101        }
4102        self.deferred_restore_settlements.push(event);
4103    }
4104
4105    /// Returns an iterator over outbox messages (test-only).
4106    #[cfg(test)]
4107    pub(crate) fn outbox_messages(&self) -> impl Iterator<Item = &Message> {
4108        self.outbox.values().map(|e| &e.message)
4109    }
4110
4111    /// Returns the total number of entries across outbox and media_outbox (test-only).
4112    #[cfg(test)]
4113    pub(crate) fn outbox_entry_count(&self) -> usize {
4114        self.outbox.len() + self.media_outbox.len()
4115    }
4116
4117    /// Clears all outbox entries (test-only).
4118    #[cfg(test)]
4119    pub(crate) fn clear_outbox(&mut self) {
4120        self.outbox.clear();
4121    }
4122
4123    /// Returns `true` when `message_id` is anywhere in the reliability
4124    /// machinery — awaiting an ACK, held in the outbox, or queued for retry
4125    /// (test-only).
4126    ///
4127    /// Exists for the fire-and-forget frames (relay hints, delivery ACKs),
4128    /// whose correctness is defined by leaving *no* trace here: an un-ACKable
4129    /// frame that registers a pending ACK is retransmitted until the retry cap
4130    /// and then reported failed.
4131    #[cfg(test)]
4132    pub(crate) fn is_tracked_for_delivery(&self, message_id: &MessageId) -> bool {
4133        self.ack_manager.is_waiting_for_ack(message_id)
4134            || self.outbox.contains_key(message_id)
4135            || self.media_outbox.contains_key(message_id)
4136            || self.retry_queue.contains(&message_id.as_str())
4137    }
4138
4139    /// Returns a reference to the MLS manager Arc (test-only).
4140    #[cfg(test)]
4141    pub(crate) fn mls_manager_for_testing(&self) -> &Arc<RwLock<offline_protocol_mls::MlsManager>> {
4142        self.mls_manager
4143            .as_ref()
4144            .expect("MLS not initialized in test")
4145    }
4146
4147    /// Acquires a read guard on the MLS manager.
4148    ///
4149    /// Returns an error if MLS is not initialized or the lock is poisoned.
4150    pub(crate) fn read_mls_guard(
4151        &self,
4152    ) -> Result<std::sync::RwLockReadGuard<'_, offline_protocol_mls::MlsManager>> {
4153        let mls = self
4154            .mls_manager
4155            .as_ref()
4156            .ok_or_else(|| Error::Other("MLS not initialized".to_string()))?;
4157        mls.read()
4158            .map_err(|_| Error::Other("MLS lock poisoned".to_string()))
4159    }
4160}
4161
4162#[cfg(test)]
4163pub(crate) mod tests;