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