Skip to main content

derec_library/protocol/types/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 DeRec Alliance. All rights reserved.
3
4//! Protocol-layer types.
5//!
6//! Everything in this module is "post-pairing" — the channel and store
7//! shapes the orchestrator manages once a pair handshake completes. The
8//! primitives layer never touches these (it operates on raw wire bytes
9//! and the cross-layer [`crate::types::ChannelId`] / [`crate::types::SharedKey`]
10//! aliases).
11//!
12//! Re-exported at [`crate::protocol`] for ergonomic access, so callers
13//! can write `use derec_library::protocol::Channel;` rather than
14//! `use derec_library::protocol::types::Channel;`.
15
16use crate::Error;
17use crate::types::SharedKey;
18use crate::types::{ChannelId, ReplicaId};
19use derec_cryptography::pairing::PairingSecretKeyMaterial;
20use derec_proto::ContactMessage;
21use derec_proto::GetShareResponseMessage;
22use derec_proto::SenderKind;
23use derec_proto::TransportProtocol;
24use derec_proto::VerifyShareRequestMessage;
25#[cfg(any(feature = "serde", target_arch = "wasm32"))]
26use serde::{Deserialize, Serialize};
27use std::collections::HashMap;
28use std::collections::HashSet;
29use std::time::Duration;
30use zeroize::Zeroizing;
31
32pub mod secret;
33#[cfg(any(feature = "serde", target_arch = "wasm32"))]
34pub mod state_record;
35
36pub use secret::{HelperInfo, ReplicaInfo, Replicas, Secret, UserSecret};
37#[cfg(any(feature = "serde", target_arch = "wasm32"))]
38pub use state_record::{ReplicaDiscoveryReport, StateItemRecord, StateKeyRecord};
39
40/// Selects which channels a flow targets.
41#[derive(Debug, Clone)]
42pub enum Target {
43    /// Send to all paired channels (most common case).
44    All,
45    /// Send to a single channel.
46    Single(ChannelId),
47    /// Send to a specific set of channels.
48    Many(Vec<ChannelId>),
49}
50
51impl Target {
52    /// Narrow this target to the channels in `known`.
53    ///
54    /// A caller may name a channel this device never paired on, or one that
55    /// has since been unpaired. Those ids are **dropped, not refused**: a
56    /// target asks to reach whoever is reachable, and one stale id should
57    /// not fail a fan-out to everyone else. A caller that needs to know an
58    /// id went nowhere compares the returned length against what it asked
59    /// for.
60    ///
61    /// Ordering differs by variant, deliberately:
62    ///
63    /// - [`Target::All`] and [`Target::Single`] follow `known`, which is the
64    ///   order the channel store returned.
65    /// - [`Target::Many`] follows the order the **caller** listed, so an
66    ///   application that ranks its helpers keeps that ranking.
67    pub fn filter(self, known: &[ChannelId]) -> Vec<ChannelId> {
68        match self {
69            Target::All => known.to_vec(),
70            Target::Single(id) => known.iter().copied().filter(|k| *k == id).collect(),
71            Target::Many(ids) => ids.into_iter().filter(|id| known.contains(id)).collect(),
72        }
73    }
74
75    /// The ids this target names, for [`ChannelFilter::ids`]. Empty for
76    /// [`Target::All`], which names none and so restricts nothing.
77    ///
78    /// Narrowing the listing by these does not replace [`Self::filter`]: the
79    /// store decides which of them exist, `filter` decides the order they come
80    /// back in.
81    pub fn ids(&self) -> Vec<ChannelId> {
82        match self {
83            Target::All => Vec::new(),
84            Target::Single(id) => vec![*id],
85            Target::Many(ids) => ids.clone(),
86        }
87    }
88}
89
90/// Status of a channel in the protocol lifecycle.
91///
92/// A channel starts as `Pending` after pairing completes and transitions to
93/// `Paired` once fingerprint verification succeeds. Two cases take that path:
94///
95/// - **Replica channels**, always. Admitting a second device to the group is
96///   a human decision.
97/// - **[`derec_proto::ContactMode::NoKeys`] channels**, whatever the kind.
98///   That mode inlines neither the keys nor a commitment to them, so nothing
99///   binds what the scanner received over the plaintext `PrePair` leg to the
100///   contact delivered out of band. The fingerprint, derived from the
101///   established shared key, is the only check that detects a substituted
102///   key — it is to `NoKeys` what `contact_binding_hash` is to
103///   [`derec_proto::ContactMode::HashedKeys`].
104///
105/// Helper/Owner channels paired over
106/// [`derec_proto::ContactMode::InlineKeys`] or
107/// [`derec_proto::ContactMode::HashedKeys`] are `Paired` immediately: the
108/// contact carried the keys, or a commitment already verified against them.
109#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
110#[cfg_attr(
111    any(feature = "serde", target_arch = "wasm32"),
112    derive(Serialize, Deserialize)
113)]
114pub enum ChannelStatus {
115    /// Channel is awaiting out-of-band fingerprint confirmation: every
116    /// replica pairing, and every
117    /// [`derec_proto::ContactMode::NoKeys`] pairing. Not a publish target,
118    /// not a recovery source, and inbound messages on it are ignored.
119    Pending,
120    /// Channel is fully paired and ready for protocol messages.
121    #[default]
122    Paired,
123    /// Being torn down. A helper channel is `Unpairing` from the moment an
124    /// unpair under [`UnpairAck::Required`](crate::protocol::UnpairAck::Required)
125    /// is sent until the helper answers or the acknowledgement window
126    /// elapses; a rejection returns it to `Paired`, except for a recovery
127    /// channel `restore` tears down, which is dropped. A replica member is
128    /// `Unpairing` once told to leave, until the version that completes its
129    /// removal. Not a publish target, not a recovery source, and not a
130    /// target of any new request, but inbound messages on it are still
131    /// processed, so the answer to the unpair is.
132    Unpairing,
133}
134
135/// Policy governing automatic removal of expired `Pending` channels.
136///
137/// [`crate::protocol::DeRecProtocol::process`] consults this on every
138/// call. It does not affect
139/// [`crate::protocol::DeRecProtocol::remove_expired_channels`], which
140/// always sweeps at the threshold it is given — that is what makes
141/// [`Self::Disabled`] mean "the application drives cleanup itself"
142/// rather than "cleanup never happens".
143///
144/// Configured via
145/// [`crate::protocol::types::Timeouts::expired_channels`].
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147#[cfg_attr(
148    any(feature = "serde", target_arch = "wasm32"),
149    derive(Serialize, Deserialize)
150)]
151pub enum ExpiredChannelCleanup {
152    /// No automatic sweep during `process()`. The application drives
153    /// cleanup itself via
154    /// [`crate::protocol::DeRecProtocol::remove_expired_channels`].
155    Disabled,
156    /// `process()` removes `Pending` channels older than this.
157    Enabled { timeout_in_secs: u64 },
158}
159
160impl Default for ExpiredChannelCleanup {
161    fn default() -> Self {
162        Self::Enabled {
163            timeout_in_secs: 300,
164        }
165    }
166}
167
168/// How long the protocol waits on each thing it can be kept waiting by.
169///
170/// These were one knob until it became clear they answer different questions.
171/// [`inbound_message`](Self::inbound_message) is a **security** boundary — it
172/// bounds how stale a message may be and still be accepted, so it has to
173/// tolerate transport latency and clock skew. The other three are **liveness**
174/// budgets: how long to keep hoping a peer will answer before giving up on it.
175/// A value that suits one is wrong for the others, and collapsing them meant
176/// tightening the replay window every time someone wanted rounds to settle
177/// faster.
178///
179/// Unspecified fields keep their default:
180///
181/// ```
182/// use derec_library::protocol::types::Timeouts;
183/// use std::time::Duration;
184///
185/// let timeouts = Timeouts {
186///     sharing_round: Duration::from_secs(30),
187///     ..Default::default()
188/// };
189/// assert_eq!(timeouts.sharing_round, Duration::from_secs(30));
190/// assert_eq!(timeouts.inbound_message, Duration::from_secs(300));
191/// ```
192///
193/// # Granularity
194///
195/// **One second is the smallest effective unit.** Wire timestamps
196/// (protobuf `Timestamp.seconds`) carry whole seconds only, so ages can be
197/// measured no finer. Sub-second precision is truncated and any value below
198/// one second is clamped to one, so an accidental [`Duration::ZERO`] cannot
199/// silently disable a timeout.
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub struct Timeouts {
202    /// Staleness boundary for **inbound envelopes**: any message whose
203    /// timestamp is older than this is discarded on receipt, whatever the
204    /// flow. This is the replay-defence window.
205    ///
206    /// Lower is not safer in any simple sense. The protocol is
207    /// transport-agnostic — a store-and-forward transport, a phone that was
208    /// offline, or a peer whose clock is a minute out all produce legitimately
209    /// old messages, and this value is what decides whether they are refused.
210    ///
211    /// Default: **300 seconds**.
212    pub inbound_message: Duration,
213    /// How long a publishing round waits for a peer that has not answered.
214    /// On expiry the silent helpers are failed, the silent members are
215    /// reported behind, and the round closes.
216    ///
217    /// This is what bounds how long
218    /// [`DeRecEvent::SharingComplete`](crate::protocol::events::DeRecEvent::SharingComplete)
219    /// can be delayed by one unreachable peer, so it is the one to shorten if
220    /// a stalled round should surface quickly.
221    ///
222    /// Default: **60 seconds**.
223    pub sharing_round: Duration,
224    /// How long to wait for a peer to acknowledge an unpair before dropping
225    /// the local channel state anyway. Expiry only discards local state; the
226    /// unpair itself was already sent.
227    ///
228    /// Default: **60 seconds**.
229    pub unpair_ack: Duration,
230    /// How long a recovery waits for a Helper to answer its `GetShareRequest`.
231    ///
232    /// A recovery decides only once every Helper it asked has answered or
233    /// this has elapsed since the requests went out, so a secret is never
234    /// chosen while an answer that could contradict it is still due. On
235    /// expiry the silent Helpers are reported failed and the recovery settles
236    /// on the shares it holds. The budget is a **human** one when Helpers
237    /// approve share requests by hand.
238    ///
239    /// The same budget bounds a replica version check
240    /// ([`DeRecFlow::ReplicaDiscovery`](crate::protocol::DeRecFlow::ReplicaDiscovery)):
241    /// once it elapses, the check concludes on the versions already reported.
242    ///
243    /// Default: **300 seconds**.
244    pub get_share_response: Duration,
245    /// How long a pairing stays possible: how old a contact may be when it is
246    /// scanned or answered, and how old a pairing request may be when it is
247    /// accepted.
248    ///
249    /// Both sides enforce it. The scanner refuses to start with a contact
250    /// older than this. The creator ignores a request on such a contact, and
251    /// neither prompts for nor accepts a request older than this, so a
252    /// request accepted after its scanner gave up cannot leave a channel only
253    /// one side holds. Nothing is sent on expiry: pairing involves both
254    /// parties, and the remedy is to scan or share a fresh contact.
255    ///
256    /// A scanner keeps its side of a pairing in flight for
257    /// [`expired_channels`](Self::expired_channels), which should therefore
258    /// be at least this plus the time a response takes to arrive.
259    ///
260    /// The request's age is measured against the creator's clock and the
261    /// contact's age against the scanner's, so two devices whose clocks
262    /// differ by more than this cannot pair. The budget is also a **human**
263    /// one: the contact must be scanned, and a manual accept given, within
264    /// it.
265    ///
266    /// Default: **30 seconds**.
267    pub pairing: Duration,
268    /// When to remove a channel still awaiting out-of-band fingerprint
269    /// confirmation — every replica pairing, and every
270    /// [`derec_proto::ContactMode::NoKeys`] pairing.
271    ///
272    /// Unlike the others this can be [`ExpiredChannelCleanup::Disabled`],
273    /// leaving the sweep to the application. The budget is a **human** one:
274    /// someone comparing a fingerprint out of band, possibly over the phone.
275    /// Shortening it below a minute or so will strand real pairings.
276    ///
277    /// Default: `Enabled { timeout_in_secs: 300 }`.
278    pub expired_channels: ExpiredChannelCleanup,
279}
280
281impl Default for Timeouts {
282    fn default() -> Self {
283        Self {
284            inbound_message: Duration::from_secs(300),
285            sharing_round: Duration::from_secs(60),
286            unpair_ack: Duration::from_secs(60),
287            get_share_response: Duration::from_secs(300),
288            pairing: Duration::from_secs(30),
289            expired_channels: ExpiredChannelCleanup::default(),
290        }
291    }
292}
293
294impl ExpiredChannelCleanup {
295    /// Enable automatic cleanup with the given timeout.
296    ///
297    /// Performs no validation. A zero is clamped to one second by
298    /// [`crate::protocol::types::Timeouts::expired_channels`],
299    /// the single normalization point.
300    pub fn from_secs(secs: u64) -> Self {
301        Self::Enabled {
302            timeout_in_secs: secs,
303        }
304    }
305
306    /// Build a policy from the flat `(enabled, timeout_in_secs)` pair the
307    /// FFI and WASM layers carry. When `enabled` is `false` the timeout is
308    /// ignored and the result is [`Self::Disabled`].
309    ///
310    /// This is the marshalling seam for the SDKs: they forward both values
311    /// verbatim and this function decides what they mean, so the rule is
312    /// written and tested once rather than in every binding.
313    pub fn new(enabled: bool, timeout_in_secs: u64) -> Self {
314        if enabled {
315            Self::Enabled { timeout_in_secs }
316        } else {
317            Self::Disabled
318        }
319    }
320}
321
322/// Which side of a replica pairing a member holds for one secret.
323///
324/// Exactly one member of a group is the [`Source`](Self::Source). This is a
325/// property of *membership*, not of a channel: all members share one channel,
326/// so the channel cannot carry it.
327///
328/// The value is **absolute**: every member records the same role for a given
329/// peer, regardless of who is reading. One exception is bounded and
330/// self-correcting — between pairing and the first sync, a joiner holds the
331/// role its admitter presented (a device admitting a new member pairs as
332/// `ReplicaSource` whether or not it is the group's source). The first roster
333/// it hydrates overwrites that provisional value, after which the group again
334/// names exactly one source. Nothing acts on the roles in that window: the
335/// joiner cannot publish before it has a snapshot.
336///
337/// Serialization is unconditional rather than feature-gated: the role rides
338/// inside the recoverable secret (see [`crate::protocol::types::secret`]),
339/// which every build must encode.
340#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
341pub enum ReplicaRole {
342    /// Originated the secret. Exactly one member per group.
343    Source,
344    /// Holds a mirrored copy.
345    Destination,
346}
347
348impl ReplicaRole {
349    /// The role the peer holds, given this one.
350    pub fn counterparty(self) -> Self {
351        match self {
352            ReplicaRole::Source => ReplicaRole::Destination,
353            ReplicaRole::Destination => ReplicaRole::Source,
354        }
355    }
356
357    /// Map from the discriminant carried by [`ReplicaInfo::role`], or `None`
358    /// if it names no known role.
359    ///
360    /// [`ReplicaInfo::role`]: crate::protocol::types::ReplicaInfo::role
361    pub fn from_i32(value: i32) -> Option<Self> {
362        match value {
363            v if v == ReplicaRole::Source as i32 => Some(ReplicaRole::Source),
364            v if v == ReplicaRole::Destination as i32 => Some(ReplicaRole::Destination),
365            _ => None,
366        }
367    }
368
369    /// Map from the wire `SenderKind`, or `None` for non-replica kinds.
370    pub fn from_sender_kind(kind: SenderKind) -> Option<Self> {
371        match kind {
372            SenderKind::ReplicaSource => Some(ReplicaRole::Source),
373            SenderKind::ReplicaDestination => Some(ReplicaRole::Destination),
374            _ => None,
375        }
376    }
377
378    /// Map to the wire `SenderKind`.
379    pub fn to_sender_kind(self) -> SenderKind {
380        match self {
381            ReplicaRole::Source => SenderKind::ReplicaSource,
382            ReplicaRole::Destination => SenderKind::ReplicaDestination,
383        }
384    }
385}
386
387/// A channel to a single helper, or to the owner from a helper's side.
388///
389/// Keyed by `(secret_id, channel_id)`. Also the record written while an
390/// owner-helper pairing is still in flight — that flow is unchanged.
391#[derive(Clone, Debug)]
392#[cfg_attr(
393    any(feature = "serde", target_arch = "wasm32"),
394    derive(Serialize, Deserialize),
395    serde(
396        into = "channel_wire::HelperChannelWire",
397        try_from = "channel_wire::HelperChannelWire"
398    )
399)]
400pub struct HelperChannel {
401    pub channel_id: ChannelId,
402    /// Every endpoint this peer advertised, in the order it offered them.
403    ///
404    /// The library never ranks these — it filters them through
405    /// [`TransportPolicy`](crate::transport::TransportPolicy) and hands the
406    /// survivors to [`DeRecTransport::send`](crate::protocol::DeRecTransport),
407    /// which is the application's to choose among and fail over between.
408    ///
409    /// # Reading a pre-0.0.3 stored record
410    ///
411    /// This replaced a single `transport` field. A record written by an older
412    /// build still loads: the deserializer accepts either spelling and lifts
413    /// a lone `transport` object into a one-element list, so no application
414    /// has to migrate a schema the library defines. See
415    /// [`CHANNEL_RECORD_SCHEMA_VERSION`].
416    ///
417    /// What is *not* accepted is a record naming no endpoint at all — absent
418    /// under both spellings, or present and empty. Defaulting those to an
419    /// empty list would yield a channel that looks paired and is unreachable,
420    /// which is worse than one that refuses to load, so they stay a loud
421    /// deserialization error.
422    pub transports: Vec<TransportProtocol>,
423    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
424    pub communication_info: HashMap<String, String>,
425    /// The **peer's** role: `Owner` when this node is the helper, `Helper`
426    /// when this node is the owner.
427    pub peer_role: SenderKind,
428    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
429    pub status: ChannelStatus,
430    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
431    pub created_at: u64,
432    /// The number of Shamir subshares this Helper receives: the weight the
433    /// last [`DeRecFlow::ProtectSecret`](crate::protocol::DeRecFlow::ProtectSecret)
434    /// resolved for it, reused by every publish the library starts on its own.
435    ///
436    /// Each `ProtectSecret` round writes the weight it gave every paired
437    /// Helper, before anything is sent: its `weights` entry, or `1` when the
438    /// map does not name it. A new pairing starts at `1`. The value travels in
439    /// the roster as [`HelperInfo::weight`](crate::protocol::types::HelperInfo::weight),
440    /// so restore and replica hydration write it back. A record stored before
441    /// this field existed reads as `1`, and so does a stored `0`: `0` is never
442    /// a valid weight, so it can only come from a writer that predates the
443    /// field. On the helper side of a channel
444    /// (`peer_role == Owner`) it is unused and stays `1`.
445    #[cfg_attr(
446        any(feature = "serde", target_arch = "wasm32"),
447        serde(default = "channel_wire::default_weight")
448    )]
449    pub weight: u32,
450}
451
452/// One member of a replica group, including this device itself.
453///
454/// Keyed by `(secret_id, replica_id)`. Every member shares one `channel_id`,
455/// so the channel cannot be the key. Storing this device's own row is what
456/// makes the roster reconstructible from stores alone.
457///
458/// An initiating device writes its **own** row when it starts a replica
459/// pairing — it knows its identity and role then, and the peer's role is the
460/// counterpart. The peer's row follows once the response announces its id.
461#[derive(Clone, Debug)]
462#[cfg_attr(
463    any(feature = "serde", target_arch = "wasm32"),
464    derive(Serialize, Deserialize),
465    serde(
466        into = "channel_wire::ReplicaMemberWire",
467        try_from = "channel_wire::ReplicaMemberWire"
468    )
469)]
470pub struct ReplicaMember {
471    /// The group channel. Identical for every member.
472    pub channel_id: ChannelId,
473    /// This member's identity — the primary key within the group.
474    pub replica_id: ReplicaId,
475    /// Every endpoint this member advertised. See
476    /// [`HelperChannel::transports`] for the ordering and compatibility
477    /// contract.
478    pub transports: Vec<TransportProtocol>,
479    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
480    pub communication_info: HashMap<String, String>,
481    pub role: ReplicaRole,
482    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
483    pub status: ChannelStatus,
484    #[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
485    pub created_at: u64,
486    /// The channel this member handed the group over to this device on, while
487    /// that channel is still in use.
488    ///
489    /// Set on the device that joined the group through this member: the
490    /// handover arrives on the pairing channel, and the member keeps sending
491    /// there, under the pairing key, until it learns this device holds the
492    /// group key. The pairing key is kept at this channel so those copies stay
493    /// readable, and a message from this member on that channel is read as
494    /// coming from it. The first message from the member on the group channel
495    /// proves it has moved on: the key at this channel is removed and the
496    /// field cleared. `None` on every other row.
497    pub handover_channel: Option<ChannelId>,
498}
499
500/// Schema version stamped onto every channel record this build writes.
501///
502/// Applications persist [`HelperChannel`] and [`ReplicaMember`] as opaque
503/// blobs whose shape the *library* owns, so a field change here is a
504/// migration the application cannot write without knowing a schema it does
505/// not define. The marker is what lets the library do that migration itself:
506/// a reader can tell a record apart by the shape it was written in rather
507/// than by guessing from which fields happen to be present.
508///
509/// A record written before the marker existed deserializes as version 0 and
510/// is upgraded on read. A record claiming a version *newer* than this build
511/// understands is refused, because the alternative is silently dropping
512/// fields this build cannot see and writing the truncated result back.
513///
514/// The value tracks the release that last changed the shape, not the release
515/// that is current: it moved to 3 when `transport` became `transports`, to 4
516/// when [`ReplicaMember::handover_channel`] was added, and stays there until
517/// the next shape change.
518///
519/// Declared unconditionally, unlike the serde impls that stamp it: the SDK
520/// bridges mirror this number in their own encoders, and a constant they must
521/// agree with should not appear and disappear with a feature flag.
522pub const CHANNEL_RECORD_SCHEMA_VERSION: u8 = 4;
523
524/// Stored-format compatibility for the two channel records.
525///
526/// [`HelperChannel`] and [`ReplicaMember`] route both serde directions
527/// through the shadow structs here, which is what lets one stored shape be
528/// read and a different one written. Two properties make it worth the
529/// indirection:
530///
531/// - The conversion is a plain `TryFrom`, so an error message can say what is
532///   wrong with a record rather than surfacing serde's field-level default.
533/// - The two spellings are distinct *fields* rather than one field with an
534///   `untagged` shape, so nothing here needs `deserialize_any`. Applications
535///   own this persistence and the library does not dictate their format; an
536///   `untagged` enum would have silently ruled out every non-self-describing
537///   one.
538#[cfg(any(feature = "serde", target_arch = "wasm32"))]
539mod channel_wire {
540    use super::{
541        CHANNEL_RECORD_SCHEMA_VERSION, ChannelId, ChannelStatus, HelperChannel, ReplicaId,
542        ReplicaMember, ReplicaRole,
543    };
544    use derec_proto::SenderKind;
545    use derec_proto::TransportProtocol;
546    use serde::{Deserialize, Serialize};
547    use std::collections::HashMap;
548
549    /// Resolve the two endpoint spellings into the one this build uses.
550    ///
551    /// `transports` wins when both are present. A migration script that adds
552    /// the list without deleting the superseded object is doing the sane
553    /// thing, and refusing it would punish the more careful migration.
554    fn endpoints(
555        transport: Option<TransportProtocol>,
556        transports: Option<Vec<TransportProtocol>>,
557        record: &'static str,
558    ) -> Result<Vec<TransportProtocol>, String> {
559        let resolved = match (transports, transport) {
560            (Some(list), _) => list,
561            (None, Some(one)) => vec![one],
562            (None, None) => {
563                return Err(format!(
564                    "{record} names no transport endpoint: neither `transports` nor the \
565                     pre-0.0.3 `transport` is present. A channel record with no endpoint \
566                     describes a peer that looks paired and cannot be reached"
567                ));
568            }
569        };
570        if resolved.is_empty() {
571            return Err(format!(
572                "{record} has an empty `transports` list. A recorded channel always has at \
573                 least one endpoint — the library refuses to record a peer whose endpoints \
574                 were all filtered away"
575            ));
576        }
577        Ok(resolved)
578    }
579
580    /// The weight of a record stored before `weight` existed.
581    pub(super) fn default_weight() -> u32 {
582        1
583    }
584
585    /// Refuse a record written by a build that knew a shape this one does not.
586    fn check_version(schema_version: u8, record: &'static str) -> Result<(), String> {
587        if schema_version > CHANNEL_RECORD_SCHEMA_VERSION {
588            return Err(format!(
589                "{record} was written with schema version {schema_version}, but this build \
590                 understands at most {CHANNEL_RECORD_SCHEMA_VERSION}. Reading it would drop \
591                 the fields this build cannot see, and writing the record back would make \
592                 that loss permanent"
593            ));
594        }
595        Ok(())
596    }
597
598    #[derive(Serialize, Deserialize)]
599    pub struct HelperChannelWire {
600        #[serde(default)]
601        schema_version: u8,
602        channel_id: ChannelId,
603        /// Pre-0.0.3 spelling. Read, never written.
604        #[serde(default, skip_serializing_if = "Option::is_none")]
605        transport: Option<TransportProtocol>,
606        #[serde(default, skip_serializing_if = "Option::is_none")]
607        transports: Option<Vec<TransportProtocol>>,
608        #[serde(default)]
609        communication_info: HashMap<String, String>,
610        peer_role: SenderKind,
611        #[serde(default)]
612        status: ChannelStatus,
613        #[serde(default)]
614        created_at: u64,
615        #[serde(default = "default_weight")]
616        weight: u32,
617    }
618
619    impl From<HelperChannel> for HelperChannelWire {
620        fn from(value: HelperChannel) -> Self {
621            Self {
622                schema_version: CHANNEL_RECORD_SCHEMA_VERSION,
623                channel_id: value.channel_id,
624                transport: None,
625                transports: Some(value.transports),
626                communication_info: value.communication_info,
627                peer_role: value.peer_role,
628                status: value.status,
629                created_at: value.created_at,
630                weight: value.weight,
631            }
632        }
633    }
634
635    impl TryFrom<HelperChannelWire> for HelperChannel {
636        type Error = String;
637
638        fn try_from(wire: HelperChannelWire) -> Result<Self, Self::Error> {
639            check_version(wire.schema_version, "HelperChannel")?;
640            Ok(Self {
641                channel_id: wire.channel_id,
642                transports: endpoints(wire.transport, wire.transports, "HelperChannel")?,
643                communication_info: wire.communication_info,
644                peer_role: wire.peer_role,
645                status: wire.status,
646                created_at: wire.created_at,
647                weight: wire.weight.max(1),
648            })
649        }
650    }
651
652    #[derive(Serialize, Deserialize)]
653    pub struct ReplicaMemberWire {
654        #[serde(default)]
655        schema_version: u8,
656        channel_id: ChannelId,
657        replica_id: ReplicaId,
658        /// Pre-0.0.3 spelling. Read, never written.
659        #[serde(default, skip_serializing_if = "Option::is_none")]
660        transport: Option<TransportProtocol>,
661        #[serde(default, skip_serializing_if = "Option::is_none")]
662        transports: Option<Vec<TransportProtocol>>,
663        #[serde(default)]
664        communication_info: HashMap<String, String>,
665        role: ReplicaRole,
666        #[serde(default)]
667        status: ChannelStatus,
668        #[serde(default)]
669        created_at: u64,
670        #[serde(default, skip_serializing_if = "Option::is_none")]
671        handover_channel: Option<ChannelId>,
672    }
673
674    impl From<ReplicaMember> for ReplicaMemberWire {
675        fn from(value: ReplicaMember) -> Self {
676            Self {
677                schema_version: CHANNEL_RECORD_SCHEMA_VERSION,
678                channel_id: value.channel_id,
679                replica_id: value.replica_id,
680                transport: None,
681                transports: Some(value.transports),
682                communication_info: value.communication_info,
683                role: value.role,
684                status: value.status,
685                created_at: value.created_at,
686                handover_channel: value.handover_channel,
687            }
688        }
689    }
690
691    impl TryFrom<ReplicaMemberWire> for ReplicaMember {
692        type Error = String;
693
694        fn try_from(wire: ReplicaMemberWire) -> Result<Self, Self::Error> {
695            check_version(wire.schema_version, "ReplicaMember")?;
696            Ok(Self {
697                channel_id: wire.channel_id,
698                replica_id: wire.replica_id,
699                transports: endpoints(wire.transport, wire.transports, "ReplicaMember")?,
700                communication_info: wire.communication_info,
701                role: wire.role,
702                status: wire.status,
703                created_at: wire.created_at,
704                handover_channel: wire.handover_channel,
705            })
706        }
707    }
708}
709
710/// Addresses a single record in [`crate::protocol::DeRecChannelStore`].
711#[derive(Clone, Copy, Debug, PartialEq, Eq)]
712pub enum ChannelQuery {
713    Helper {
714        channel_id: ChannelId,
715    },
716    Replica {
717        channel_id: ChannelId,
718        replica_id: ReplicaId,
719    },
720}
721
722impl ChannelQuery {
723    pub fn channel_id(&self) -> ChannelId {
724        match self {
725            ChannelQuery::Helper { channel_id } => *channel_id,
726            ChannelQuery::Replica { channel_id, .. } => *channel_id,
727        }
728    }
729}
730
731/// Narrows a listing from [`crate::protocol::DeRecChannelStore`].
732///
733/// Every field is a *restriction*, and every field's empty value means "do not
734/// restrict on this" — so [`Default`] selects everything and is equivalent to
735/// an unfiltered listing. Restrictions combine with AND, and `exclude` is
736/// applied last, overriding `ids`.
737///
738/// # Returning everything is correct
739///
740/// **Ignoring the filter entirely and returning every record under the
741/// `secret_id` is a correct implementation**, and the one to write unless
742/// there is a measured reason not to. The protocol re-applies the filter to
743/// whatever a listing returns and drops anything it excludes, so a superset is
744/// trimmed to exactly the right set before anything acts on it.
745///
746/// # Pushing it into the query is an optimization you opt into
747///
748/// A store *may* translate the filter into a `WHERE` clause or a key-condition
749/// expression and return only the matching rows. That saves transferring rows
750/// the caller would discard, which costs bandwidth everywhere and real money
751/// on a metered backing such as DynamoDB, which bills by bytes read.
752///
753/// It also moves this type's semantics into a query language by hand, and the
754/// error that matters is asymmetric. The library's re-check is a **one-way**
755/// guarantee: dropping rows can enforce an upper bound, so returning too
756/// *many* costs only the transfer. It cannot recover a row that was never
757/// returned. A pushdown that selects too *few* is wrong in a way nothing here
758/// can detect — no exception, no event, no log line. The protocol simply fails
759/// to act, and what that looks like is a share that was never published.
760///
761/// So treat pushdown as a performance claim about your own query, and verify
762/// it: `fixtures/channel_filter.json` is a table of
763/// `(records, filter, expected)` cases covering the clauses that are easy to
764/// get subtly wrong — empty-means-unrestricted per field, `role` as an
765/// optional, and `exclude` applied *after* `ids`. Every binding's test suite
766/// drives it, and a store that pushes down should be driven through it too.
767///
768/// [`ChannelFilter::matches`] is the same predicate the library re-checks
769/// with, exported so a store that cannot express the filter as a query can
770/// apply it in memory without re-deriving the rules.
771///
772/// The listing methods state which record field each of `status`, `role` and
773/// the id fields refers to.
774#[derive(Clone, Debug, PartialEq, Eq)]
775#[cfg_attr(
776    any(feature = "serde", target_arch = "wasm32"),
777    derive(Serialize, Deserialize),
778    serde(
779        default,
780        bound = "Role: Serialize + serde::de::DeserializeOwned, Id: Serialize + serde::de::DeserializeOwned"
781    )
782)]
783pub struct ChannelFilter<Role, Id> {
784    /// Restrict to these ids. Empty selects every record.
785    pub ids: Vec<Id>,
786    /// Restrict to these statuses. Empty selects any status.
787    pub status: Vec<ChannelStatus>,
788    /// Restrict to this role. `None` selects any role.
789    pub role: Option<Role>,
790    /// Omit these ids, applied after `ids`. Empty omits nothing.
791    pub exclude: Vec<Id>,
792}
793
794impl<Role, Id> Default for ChannelFilter<Role, Id> {
795    fn default() -> Self {
796        Self {
797            ids: Vec::new(),
798            status: Vec::new(),
799            role: None,
800            exclude: Vec::new(),
801        }
802    }
803}
804
805impl<Role: PartialEq, Id: PartialEq> ChannelFilter<Role, Id> {
806    /// Whether a record with these attributes survives the filter.
807    ///
808    /// A store whose backing cannot express the restrictions as a query can
809    /// list and call this, which is correct but transfers the rows the filter
810    /// was meant to leave behind.
811    pub fn matches(&self, id: &Id, status: ChannelStatus, role: &Role) -> bool {
812        (self.ids.is_empty() || self.ids.contains(id))
813            && (self.status.is_empty() || self.status.contains(&status))
814            && self.role.as_ref().is_none_or(|wanted| wanted == role)
815            && !self.exclude.contains(id)
816    }
817}
818
819/// Narrows [`crate::protocol::DeRecChannelStore::replicas`].
820///
821/// Ids are [`ReplicaMember::replica_id`] and the role is
822/// [`ReplicaMember::role`].
823pub type ReplicaFilter = ChannelFilter<ReplicaRole, ReplicaId>;
824
825/// Narrows [`crate::protocol::DeRecChannelStore::helpers`].
826///
827/// Ids are [`HelperChannel::channel_id`] and the role is the **peer's**
828/// [`HelperChannel::peer_role`].
829pub type HelperFilter = ChannelFilter<SenderKind, ChannelId>;
830
831/// A record returned by [`crate::protocol::DeRecChannelStore::load`].
832#[derive(Clone, Debug)]
833#[cfg_attr(
834    any(feature = "serde", target_arch = "wasm32"),
835    derive(Serialize, Deserialize)
836)]
837pub enum ChannelRecord {
838    Helper(HelperChannel),
839    Replica(ReplicaMember),
840}
841
842impl ChannelRecord {
843    pub fn channel_id(&self) -> ChannelId {
844        match self {
845            ChannelRecord::Helper(h) => h.channel_id,
846            ChannelRecord::Replica(r) => r.channel_id,
847        }
848    }
849    pub fn status(&self) -> ChannelStatus {
850        match self {
851            ChannelRecord::Helper(h) => h.status,
852            ChannelRecord::Replica(r) => r.status,
853        }
854    }
855    /// Every endpoint the peer advertised, in the order it offered them.
856    ///
857    /// Never empty for a recorded channel: the library refuses to record a
858    /// peer whose endpoints were all filtered away.
859    pub fn transports(&self) -> &[TransportProtocol] {
860        match self {
861            ChannelRecord::Helper(h) => &h.transports,
862            ChannelRecord::Replica(r) => &r.transports,
863        }
864    }
865    pub fn communication_info(&self) -> &HashMap<String, String> {
866        match self {
867            ChannelRecord::Helper(h) => &h.communication_info,
868            ChannelRecord::Replica(r) => &r.communication_info,
869        }
870    }
871    pub fn as_helper(&self) -> Option<&HelperChannel> {
872        match self {
873            ChannelRecord::Helper(h) => Some(h),
874            _ => None,
875        }
876    }
877    pub fn as_replica(&self) -> Option<&ReplicaMember> {
878        match self {
879            ChannelRecord::Replica(r) => Some(r),
880            _ => None,
881        }
882    }
883}
884
885/// Snapshot of the user-facing secret contents persisted by
886/// [`crate::protocol::DeRecUserSecretStore`] for one `secret_id`.
887///
888/// Written every time the application calls
889/// `start(FlowKind::ProtectSecret)`; read by the pair-completion
890/// auto-publish hook so a freshly-paired Helper or Replica receives the
891/// current state without an explicit re-publish from the app.
892#[derive(Clone, Debug, PartialEq)]
893pub struct UserSecrets {
894    /// Secret version this snapshot represents. Monotonically increasing
895    /// per `secret_id` — the protocol bumps it on every publish.
896    pub version: u32,
897    /// User-facing secret entries. Same wire shape as
898    /// [`Secret::secrets`].
899    pub secrets: Vec<UserSecret>,
900    /// Optional human-readable label for this version, forwarded to
901    /// helpers in `StoreShareRequest.description`.
902    pub description: Option<String>,
903    /// The replica-group member that published this version.
904    ///
905    /// Set on every publish, whatever changed — the secrets or only the
906    /// roster — and carried to every other member with the version, so each
907    /// one knows who wrote what it holds. A replica compares it with the
908    /// author of an incoming copy at the same version: the same author is a
909    /// re-send, a different one is a conflict.
910    ///
911    /// `None` when the version was not published by a group member: an owner
912    /// with no replica identity, or a snapshot rebuilt by recovery.
913    pub author_replica_id: Option<u64>,
914    /// The threshold `t` the next publish splits at, unless
915    /// [`DeRecFlow::ProtectSecret`](crate::protocol::DeRecFlow::ProtectSecret)
916    /// passes its own `threshold`.
917    ///
918    /// Every publish writes the `t` it used. [`restore`](crate::protocol::DeRecProtocol::restore)
919    /// and replica hydration write the roster's
920    /// [`Secret::threshold`](crate::protocol::types::Secret::threshold), so a
921    /// recovered or receiving device keeps splitting at the `t` the secret
922    /// was shared under.
923    ///
924    /// `None` on a snapshot written before the threshold was recorded, or
925    /// restored from a roster that carries none. The builder's
926    /// [`with_threshold`](crate::protocol::DeRecProtocolBuilder::with_threshold)
927    /// then applies.
928    pub threshold: Option<u32>,
929}
930
931/// A single helper's share of the current secret — wire-pairs a
932/// `channel_id` with the serialized `CommittedDeRecShare` bytes that
933/// were sent to that helper. Part of [`ReplicaSecretPayload`].
934#[derive(Clone, PartialEq, ::prost::Message)]
935pub struct ChannelShare {
936    /// Channel id of the helper that holds this share.
937    #[prost(uint64, tag = "1")]
938    pub channel_id: u64,
939    /// Serialized `CommittedDeRecShare` bytes — the same payload the
940    /// helper received in their `StoreShareRequest`.
941    #[prost(bytes = "vec", tag = "2")]
942    pub committed_share: ::prost::alloc::vec::Vec<u8>,
943}
944
945/// The composite payload sent to each Replica Destination on a
946/// `ProtectSecret` round. Carries the full [`Secret`] plus the map of
947/// `(channel_id → committed_share)` for the same round, so the
948/// Destination can recover via either path — read the secret directly,
949/// or contact each helper using `secret.helpers[i].shared_key` and
950/// request their stored share.
951///
952/// # Group-key handover
953///
954/// All replica channels for a given `secret_id` converge on a single
955/// symmetric "group" key. The `shared_key` field carries that group key
956/// inside the encrypted payload **only** when the sender knows the
957/// receiver doesn't have it yet — i.e. on the first round to a newly
958/// paired Destination. That round travels on the ephemeral pairing
959/// channel under the pairing key, and both sides leave that channel for
960/// the group channel only once the other side is known to be there:
961///
962/// - **Sender**: keeps the joiner on the pairing channel, and the pairing
963///   key, until the joiner answers on the group channel, so a copy sent
964///   before the joiner confirmed, or whose acknowledgement was lost, can
965///   be sent again.
966/// - **Receiver**: hydrates onto the group channel, acknowledges there
967///   under the group key, and records the pairing channel as its member
968///   row's `handover_channel`, so copies still arriving there are read. It
969///   drops the pairing key once the sender reaches it on the group channel.
970///
971/// On the first-ever replica pair, the group key is implicitly the
972/// pair-handshake key — `shared_key` is left empty, no swap happens,
973/// and the channel-key entry both sides already saved is the group key.
974#[derive(Clone, PartialEq, ::prost::Message)]
975pub struct ReplicaSecretPayload {
976    /// The full secret the sender is committing to this version.
977    #[prost(message, optional, tag = "1")]
978    pub secret: ::core::option::Option<Secret>,
979    /// One entry per helper that received a VSS share on this round.
980    #[prost(message, repeated, tag = "2")]
981    pub shares: ::prost::alloc::vec::Vec<ChannelShare>,
982    /// 32-byte replica-group key. Present only on the first-sync round
983    /// to a newly-paired Destination; empty on every subsequent round
984    /// (since the receiving channel already holds the group key) and
985    /// empty when the receiving Destination is the very first pair for
986    /// this `secret_id` (the pair-handshake key is implicitly the group
987    /// key). See type-level docs for the swap protocol.
988    #[prost(bytes = "vec", tag = "3")]
989    pub shared_key: ::prost::alloc::vec::Vec<u8>,
990    /// The version `secret` and `shares` belong to.
991    ///
992    /// The payload is self-describing because its two carriers disagree
993    /// about what the enclosing `version` field means. On a push it is
994    /// the round being published and matches
995    /// `StoreShareRequestMessage.version`. On a catch-up the enclosing
996    /// `GetShareResponseMessage.version` echoes the version the *asker*
997    /// requested, while the payload is whatever snapshot the *answerer*
998    /// happens to hold — so filing the share map under the enclosing
999    /// value would key it to a version these bytes were never part of.
1000    ///
1001    /// `0` means the writer predates this field. A receiver falls back
1002    /// to the enclosing message's version, which is what that writer
1003    /// intended.
1004    #[prost(uint32, tag = "4")]
1005    pub version: u32,
1006    /// The member that published `version`.
1007    ///
1008    /// Like `version`, carried in the payload because the enclosing message
1009    /// cannot say it: a push's `replicaId` is the publisher, but a catch-up
1010    /// answer's `replicaId` is whichever member answered, which need not be
1011    /// the one that wrote the version it serves. Absent when the serving
1012    /// member's snapshot records no author.
1013    #[prost(uint64, optional, tag = "5")]
1014    pub author_replica_id: ::core::option::Option<u64>,
1015}
1016
1017/// Kind of secret material stored by [`crate::protocol::DeRecSecretStore`].
1018///
1019/// Each variant has its own lifecycle (see per-variant docs). Used as the
1020/// `kind` argument to [`crate::protocol::DeRecSecretStore::load`] and
1021/// [`crate::protocol::DeRecSecretStore::remove`]; on
1022/// [`crate::protocol::DeRecSecretStore::save`] the kind is inferred from
1023/// the [`SecretValue`] variant and need not be passed.
1024///
1025/// # Discriminant stability
1026///
1027/// **The numeric values below are stable and safe to persist.** They will
1028/// not be renumbered, and new variants are appended rather than inserted.
1029///
1030/// This is a guarantee, not an implementation detail, because store
1031/// implementations legitimately need a compact tag for the secret they are
1032/// writing and `kind as u8` is the obvious one to reach for. A deployed
1033/// store's rows outlive any single version of this crate, so renumbering
1034/// would silently reinterpret data already at rest — and two of the three
1035/// variants carry variable-length payloads, so a swapped tag decodes into a
1036/// plausible wrong value rather than failing.
1037///
1038/// Note that [`SecretValue`]'s serde representation carries no such
1039/// guarantee (see its docs). Persisting the discriminant plus your own
1040/// payload encoding is the supported way to store secret material durably.
1041#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1042pub enum SecretKind {
1043    /// The post-pairing symmetric channel key (see [`SecretValue::SharedKey`]).
1044    SharedKey = 0,
1045    /// The ephemeral ECIES / ML-KEM key material used during pairing.
1046    PairingSecret = 1,
1047    /// The [`ContactMessage`] a pairing runs against, stored transiently
1048    /// until pairing completes: by the party that scans a contact when it
1049    /// starts pairing, and by the contact creator for a `NoKeys` contact,
1050    /// which has no key material to store instead. Removed once the shared
1051    /// key is derived.
1052    PairingContact = 2,
1053}
1054
1055/// How [`crate::protocol::DeRecSecretStore::load_many`] handles channels
1056/// with no stored secret of the requested [`SecretKind`].
1057#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1058pub enum MissingPolicy {
1059    /// Silently drop missing channels from the returned vector.
1060    ///
1061    /// Use when missing entries are an expected outcome — e.g. a `Target::Many`
1062    /// list that mixes paired and unpaired channels.
1063    Skip,
1064    /// Return [`crate::protocol::SecretStoreError::MissingEntries`] carrying
1065    /// the channel ids that had no entry.
1066    ///
1067    /// Use when every input id is expected to have an entry — e.g. after
1068    /// filtering to channels already known to
1069    /// [`crate::protocol::DeRecChannelStore`]. A miss signals a cross-store
1070    /// invariant violation.
1071    Fail,
1072}
1073
1074/// Opaque, serialized pairing key material as held by
1075/// [`crate::protocol::DeRecSecretStore`] under [`SecretValue::PairingSecret`].
1076///
1077/// This is the store-boundary form of the ephemeral key pair the pairing
1078/// handshake produces. The protocol deliberately exposes it as an opaque
1079/// byte blob rather than a cryptographic type, so a store implementation can
1080/// persist and reload it without depending on `derec-cryptography` or any
1081/// serialization framework: call [`as_bytes`](Self::as_bytes) to obtain the
1082/// bytes to persist on `save`, and hand the same bytes back to
1083/// [`from_bytes`](Self::from_bytes) on `load`.
1084///
1085/// The byte layout is a library-internal detail, is not part of the public
1086/// API, and may change between versions; treat the blob as opaque and never
1087/// interpret it.
1088///
1089/// The bytes are held in [`zeroize::Zeroizing`] so the plaintext key material
1090/// is wiped from memory on drop.
1091#[derive(Clone)]
1092pub struct PairingKeyMaterial(Zeroizing<Vec<u8>>);
1093
1094impl PairingKeyMaterial {
1095    /// Wrap raw bytes previously obtained from [`as_bytes`](Self::as_bytes)
1096    /// and persisted by a store.
1097    pub fn from_bytes(bytes: Vec<u8>) -> Self {
1098        Self(Zeroizing::new(bytes))
1099    }
1100
1101    /// The opaque bytes to persist. Round-trips through
1102    /// [`from_bytes`](Self::from_bytes).
1103    pub fn as_bytes(&self) -> &[u8] {
1104        self.0.as_slice()
1105    }
1106
1107    /// Serialize live pairing secret key material into the store-boundary
1108    /// form.
1109    ///
1110    /// Library-internal: the pairing handlers call this before handing the
1111    /// value to the secret store, keeping the `ark-serialize` encoding an
1112    /// implementation detail that never crosses the public API.
1113    pub(crate) fn from_secret(material: &PairingSecretKeyMaterial) -> Self {
1114        use ark_serialize::CanonicalSerialize as _;
1115        let mut buf = Vec::with_capacity(material.compressed_size());
1116        material
1117            .serialize_compressed(&mut buf)
1118            .expect("ark serialization of PairingSecretKeyMaterial is infallible");
1119        Self(Zeroizing::new(buf))
1120    }
1121
1122    /// Reconstruct live pairing secret key material from the store-boundary
1123    /// form.
1124    ///
1125    /// Library-internal: the pairing handlers call this after loading the
1126    /// value from the secret store. A decode failure means the persisted
1127    /// bytes were corrupted or truncated, which is an internal invariant
1128    /// violation rather than valid caller input.
1129    pub(crate) fn to_secret(&self) -> crate::Result<PairingSecretKeyMaterial> {
1130        use ark_serialize::CanonicalDeserialize as _;
1131        PairingSecretKeyMaterial::deserialize_compressed(self.0.as_slice())
1132            .map_err(|_| Error::Invariant("stored PairingSecret bytes failed to decode"))
1133    }
1134}
1135
1136#[cfg(feature = "serde")]
1137impl Serialize for PairingKeyMaterial {
1138    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1139    where
1140        S: serde::Serializer,
1141    {
1142        self.0.as_slice().serialize(serializer)
1143    }
1144}
1145
1146#[cfg(feature = "serde")]
1147impl<'de> Deserialize<'de> for PairingKeyMaterial {
1148    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1149    where
1150        D: serde::Deserializer<'de>,
1151    {
1152        let bytes = Vec::<u8>::deserialize(deserializer)?;
1153        Ok(Self(Zeroizing::new(bytes)))
1154    }
1155}
1156
1157/// Serde adapter for the prost [`ContactMessage`] carried by
1158/// [`SecretValue::PairingContact`]. prost messages have no native serde
1159/// support, so the value is (de)serialized through its canonical protobuf
1160/// byte encoding.
1161#[cfg(feature = "serde")]
1162mod contact_serde {
1163    use super::ContactMessage;
1164    use prost::Message as _;
1165    use serde::de;
1166    use serde::{Deserialize as _, Deserializer, Serialize as _, Serializer};
1167
1168    pub(super) fn serialize<S>(contact: &ContactMessage, serializer: S) -> Result<S::Ok, S::Error>
1169    where
1170        S: Serializer,
1171    {
1172        contact.encode_to_vec().serialize(serializer)
1173    }
1174
1175    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<ContactMessage, D::Error>
1176    where
1177        D: Deserializer<'de>,
1178    {
1179        let bytes = Vec::<u8>::deserialize(deserializer)?;
1180        ContactMessage::decode(bytes.as_slice()).map_err(de::Error::custom)
1181    }
1182}
1183
1184/// The payload returned by [`crate::protocol::DeRecSecretStore::load`] and
1185/// passed to [`crate::protocol::DeRecSecretStore::save`].
1186///
1187/// Variants are 1:1 with [`SecretKind`].
1188///
1189/// With the `serde` feature enabled, `Serialize` / `Deserialize` are
1190/// derived so a store implementation can persist an entry with any serde
1191/// format instead of hand-rolling a codec. This is an alternative to the
1192/// byte-level accessors on the individual payloads (e.g.
1193/// [`PairingKeyMaterial::as_bytes`] / [`PairingKeyMaterial::from_bytes`]);
1194/// implementors pick whichever fits their backend, and consumers that do
1195/// not use serde pay no dependency for it. The serde wire format is not
1196/// part of the public API and may change independently.
1197#[derive(Clone)]
1198#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1199pub enum SecretValue {
1200    /// The post-pairing symmetric channel key. Established by pairing and used
1201    /// to authenticate and encrypt every subsequent message on the channel.
1202    SharedKey(SharedKey),
1203    /// The ephemeral ECIES / ML-KEM key material created by `start` and
1204    /// consumed when the pairing response arrives. Removed once the shared
1205    /// key is derived. Held as an opaque [`PairingKeyMaterial`] blob so
1206    /// store implementors never touch a cryptography primitive.
1207    PairingSecret(PairingKeyMaterial),
1208    /// The initiator's [`ContactMessage`], needed by
1209    /// [`crate::primitives::pairing::response::process`] to derive the shared
1210    /// key. Ephemeral — removed after pairing completes.
1211    PairingContact(#[cfg_attr(feature = "serde", serde(with = "contact_serde"))] ContactMessage),
1212}
1213
1214/// Tag identifying which kind of in-flight orchestrator state an entry in
1215/// [`crate::protocol::DeRecStateStore`] holds. Used by
1216/// [`crate::protocol::DeRecStateStore::load_all`] to filter by category.
1217///
1218/// # Discriminant stability
1219///
1220/// The same guarantee as [`SecretKind`]: these values are stable, safe to
1221/// persist, and new variants are appended rather than inserted. A durable
1222/// state store needs a column to filter `load_all` by, and this is it.
1223///
1224/// The values are written out explicitly for that reason. Left implicit they
1225/// would still *have* numbers — ones every reader would have to count out by
1226/// hand, and that a reordering would change without touching a single digit
1227/// in this file.
1228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1229pub enum StateKind {
1230    /// Outstanding [`derec_proto::VerifyShareRequestMessage`], one per
1231    /// channel. Load-bearing for the replay-defence binding gate.
1232    PendingVerification = 0,
1233    /// Recovery accumulator, one per `(recovered secret_id, version)`
1234    /// within a partition. Holds every
1235    /// [`derec_proto::GetShareResponseMessage`] received so far for that
1236    /// reconstruction target. See [`StateKey::PendingRecovery`] on why
1237    /// the recovered id is distinct from the partitioning one.
1238    PendingRecovery = 1,
1239    /// Outstanding unpair acknowledgement, one per channel. Carries the
1240    /// `started_at` unix-seconds timestamp so the orchestrator can time
1241    /// out unresponsive peers.
1242    PendingUnpair = 2,
1243    /// Active sharing round, one row per in-flight version. Several can be
1244    /// open at once: publishes are started by the pair-completion hook and by
1245    /// the promotion inside `verify_fingerprint`, not only by
1246    /// `start(ProtectSecret)`. Holds the per-channel tallies (`pending` /
1247    /// `confirmed` / `failed`), the per-member tallies, and the `started_at`
1248    /// timestamp used to time out unresponsive peers.
1249    SharingRound = 3,
1250    /// Active replica catch-up. At most one entry exists per `secret_id`
1251    /// (a new `start(ReplicaDiscovery)` overwrites any prior one). Holds the
1252    /// versions members have reported so far, so the asker can pick the
1253    /// member holding the newest state once every peer has answered.
1254    PendingReplicaDiscovery = 4,
1255}
1256
1257/// Secondary-key selector identifying a single row within a given
1258/// [`StateKind`] under a `secret_id`. Passed to
1259/// [`crate::protocol::DeRecStateStore::load`] and
1260/// [`crate::protocol::DeRecStateStore::remove`].
1261#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1262pub enum StateKey {
1263    /// Row is scoped to one channel.
1264    PendingVerification { channel_id: ChannelId },
1265    /// Row is scoped to one reconstruction target.
1266    ///
1267    /// `secret_id` is the secret *being recovered*, which is not
1268    /// necessarily the `secret_id` naming the partition this row lives
1269    /// in: a recovering device runs an ephemeral instance whose own id
1270    /// owns the partition, while the target belongs to the wire. Keying
1271    /// on it lets one instance recover several secrets concurrently at
1272    /// the same version without their accumulators colliding.
1273    PendingRecovery { secret_id: u64, version: u32 },
1274    /// Row is scoped to one channel.
1275    PendingUnpair { channel_id: ChannelId },
1276    /// At most one row per `secret_id`. No secondary key.
1277    PendingReplicaDiscovery,
1278    /// Row is scoped to one publishing round, identified by the version it
1279    /// distributes.
1280    ///
1281    /// Keying on the version is load-bearing rather than cosmetic. Rounds are
1282    /// not started only by `start(ProtectSecret)`: the pair-completion hook
1283    /// and the promotion inside `verify_fingerprint` both publish, and both
1284    /// run while handling an *inbound* message. A single unkeyed row meant a
1285    /// round started that way silently replaced one already in flight, after
1286    /// which neither completed — responses for the replaced round arrived
1287    /// against state that no longer existed, and no `SharingComplete` was
1288    /// emitted for either. An application could not prevent this, because it
1289    /// cannot see the library's round state. Distinct versions now accumulate
1290    /// independently.
1291    SharingRound { version: u32 },
1292}
1293
1294impl StateKey {
1295    /// The [`StateKind`] this key selects. Used by store implementations
1296    /// that persist rows in a `(secret_id, kind, secondary_key)` schema.
1297    pub fn kind(&self) -> StateKind {
1298        match self {
1299            StateKey::PendingVerification { .. } => StateKind::PendingVerification,
1300            StateKey::PendingRecovery { .. } => StateKind::PendingRecovery,
1301            StateKey::PendingUnpair { .. } => StateKind::PendingUnpair,
1302            StateKey::PendingReplicaDiscovery => StateKind::PendingReplicaDiscovery,
1303            StateKey::SharingRound { .. } => StateKind::SharingRound,
1304        }
1305    }
1306}
1307
1308/// The payload of one row in the [`crate::protocol::DeRecStateStore`].
1309///
1310/// # Write pattern
1311///
1312/// The library treats [`crate::protocol::DeRecStateStore::save`] as
1313/// **full-replacement upsert** — there is no per-item merge or append
1314/// semantic at the store level. Accumulator-style state
1315/// ([`StateItem::PendingRecovery`] and [`StateItem::SharingRound`]) grows
1316/// via load-modify-save cycles from the library. Backends do not need to
1317/// implement any append primitive; a naive replace-on-save is correct.
1318#[derive(Debug, Clone)]
1319pub enum StateItem {
1320    /// The full outstanding [`derec_proto::VerifyShareRequestMessage`] the
1321    /// orchestrator sent for this channel. Retained so the corresponding
1322    /// inbound [`derec_proto::VerifyShareResponseMessage`] can be validated
1323    /// against the exact `(nonce, secret_id, version)` triple that was
1324    /// minted at request time.
1325    ///
1326    /// Overwritten in place by a subsequent `save` for the same
1327    /// `(secret_id, channel_id)`; the most recent challenge wins.
1328    PendingVerification {
1329        channel_id: ChannelId,
1330        request: VerifyShareRequestMessage,
1331    },
1332
1333    /// Accumulator for one in-progress recovery target.
1334    ///
1335    /// The library writes this variant one share at a time as each inbound
1336    /// [`derec_proto::GetShareResponseMessage`] arrives. The write sequence
1337    /// under a single `(recovered secret_id, version)` is:
1338    ///
1339    /// 1. First response arrives. Library calls `save` with a `shares`
1340    ///    vector containing exactly one element.
1341    /// 2. Second response arrives. Library `load`s the accumulator,
1342    ///    appends the new share to the returned Vec, and `save`s the
1343    ///    grown Vec back.
1344    /// 3. …repeat until threshold. On threshold met, library `remove`s
1345    ///    the accumulator.
1346    ///
1347    /// Each entry names the channel its share arrived on, and a channel
1348    /// holds at most one entry: a later share from the same channel
1349    /// replaces the earlier one. A share that fails its own checks is never
1350    /// written here (see [`crate::protocol::DeRecEvent::RecoveryShareCorrupted`]).
1351    ///
1352    /// Implementations MUST accept `shares` vectors of any length,
1353    /// including one. Every `save` replaces the stored value in place
1354    /// with the caller-supplied Vec; no append primitive is required.
1355    ///
1356    /// # Concurrency
1357    ///
1358    /// See [`crate::protocol::DeRecStateStore`] for the multi-instance
1359    /// concurrency contract. Concurrent inbound shares racing on the same
1360    /// accumulator will clobber each other via a naive load-modify-save;
1361    /// the application layer is responsible for serializing concurrent
1362    /// `process()` calls that touch the same `(recovered secret_id,
1363    /// version)` if this matters. Recoveries of *different* secrets do
1364    /// not contend: they occupy separate rows even at the same version.
1365    PendingRecovery {
1366        /// The secret being recovered. See
1367        /// [`StateKey::PendingRecovery`] — this is a wire-level id and
1368        /// may differ from the `secret_id` partitioning the row.
1369        secret_id: u64,
1370        version: u32,
1371        shares: Vec<CollectedShare>,
1372        /// The Helpers asked for a share that have not answered yet. The
1373        /// recovery decides once this is empty, or once `started_at` is
1374        /// older than [`Timeouts::get_share_response`].
1375        pending: HashSet<ChannelId>,
1376        /// Unix seconds at which the share requests went out.
1377        started_at: u64,
1378    },
1379
1380    /// Outstanding unpair acknowledgement window. `started_at` is the
1381    /// unix-seconds timestamp stamped when the request was sent; the
1382    /// orchestrator sweeps expired entries via
1383    /// [`crate::protocol::DeRecStateStore::load_all`].
1384    PendingUnpair {
1385        channel_id: ChannelId,
1386        started_at: u64,
1387        /// The channel is dropped whatever the Helper answers: a refusal is
1388        /// reported and the channel still goes, instead of returning to
1389        /// `Paired`. Set for the recovery channels a restore tears down.
1390        drop_on_rejection: bool,
1391    },
1392
1393    /// Active sharing round, keyed by the version it distributes. Created by
1394    /// a publish — `start(ProtectSecret)`, the pair-completion hook, or the
1395    /// promotion inside `verify_fingerprint` — and cleared by the orchestrator
1396    /// once every targeted peer has responded (confirmed, rejected, or timed
1397    /// out). Rounds at different versions are independent and settle
1398    /// separately; one never displaces another.
1399    ///
1400    /// `pending` / `confirmed` / `failed` partition the round's target
1401    /// channels; the union is invariant across the round's lifetime.
1402    /// `started_at` is the unix-seconds timestamp used to time out
1403    /// unresponsive helpers.
1404    /// An in-flight replica catch-up: the versions members have reported so
1405    /// far, plus the asker's own, so the winner can be chosen once every peer
1406    /// has answered or timed out.
1407    PendingReplicaDiscovery {
1408        /// The version the asker held when the check started.
1409        local_version: u32,
1410        /// Members asked that have not yet answered.
1411        pending: HashSet<ReplicaId>,
1412        /// Versions reported so far, by member.
1413        reported: HashMap<ReplicaId, u32>,
1414        started_at: u64,
1415    },
1416    /// An in-flight publishing round. Boxed because it is by far the largest
1417    /// variant, and every other `StateItem` would otherwise be padded to its
1418    /// size.
1419    SharingRound(Box<SharingRoundState>),
1420}
1421
1422/// The accounting for one in-flight publishing round.
1423///
1424/// The two populations are tracked separately and by different keys — helpers
1425/// by [`ChannelId`], members by [`ReplicaId`]. A single set keyed on
1426/// `ChannelId` cannot express the replica leg at all: every member shares the
1427/// group channel, so they would collapse into one entry and the first answer
1428/// would settle the round for the whole group.
1429#[derive(Clone, Debug, PartialEq, Eq)]
1430pub struct SharingRoundState {
1431    pub version: u32,
1432    /// Helpers written to that have not yet answered.
1433    pub pending: HashSet<ChannelId>,
1434    /// Helpers that confirmed storage.
1435    pub confirmed: HashSet<ChannelId>,
1436    /// Helpers that rejected or timed out.
1437    pub failed: HashSet<ChannelId>,
1438    /// Members written to that have not yet answered.
1439    pub pending_replicas: HashSet<ReplicaId>,
1440    /// Members that acknowledged.
1441    pub synced_replicas: HashSet<ReplicaId>,
1442    /// Members that refused, timed out, or could not be reached.
1443    pub behind_replicas: HashSet<ReplicaId>,
1444    pub started_at: u64,
1445    /// The `keepVersion` every Helper received in this round. A Helper that
1446    /// confirms the round has removed every version it held on that channel
1447    /// other than the confirmed one and this one, so the owner removes its
1448    /// proofs of those versions too. `None` when the round sent no share, or
1449    /// on a row written before the field existed; the owner then removes no
1450    /// proof.
1451    pub keep_version: Option<u32>,
1452    /// The threshold `t` this round split at, which `SharingComplete.threshold_met`
1453    /// is judged against. `None` on a round written before the threshold was
1454    /// recorded; the builder's threshold then applies.
1455    pub threshold: Option<u32>,
1456}
1457
1458impl StateItem {
1459    /// The [`StateKind`] this item is an instance of.
1460    pub fn kind(&self) -> StateKind {
1461        match self {
1462            StateItem::PendingVerification { .. } => StateKind::PendingVerification,
1463            StateItem::PendingRecovery { .. } => StateKind::PendingRecovery,
1464            StateItem::PendingUnpair { .. } => StateKind::PendingUnpair,
1465            StateItem::PendingReplicaDiscovery { .. } => StateKind::PendingReplicaDiscovery,
1466            StateItem::SharingRound(_) => StateKind::SharingRound,
1467        }
1468    }
1469
1470    /// The [`StateKey`] identifying this item within its `(secret_id, kind)`
1471    /// partition. Convenience so callers don't have to hand-construct a
1472    /// key that matches the payload.
1473    pub fn key(&self) -> StateKey {
1474        match self {
1475            StateItem::PendingVerification { channel_id, .. } => StateKey::PendingVerification {
1476                channel_id: *channel_id,
1477            },
1478            StateItem::PendingRecovery {
1479                secret_id, version, ..
1480            } => StateKey::PendingRecovery {
1481                secret_id: *secret_id,
1482                version: *version,
1483            },
1484            StateItem::PendingUnpair { channel_id, .. } => StateKey::PendingUnpair {
1485                channel_id: *channel_id,
1486            },
1487            StateItem::PendingReplicaDiscovery { .. } => StateKey::PendingReplicaDiscovery,
1488            StateItem::SharingRound(round) => StateKey::SharingRound {
1489                version: round.version,
1490            },
1491        }
1492    }
1493}
1494
1495/// One share collected towards a recovery, with the channel it arrived on.
1496///
1497/// The channel is what lets a share that turns out to disagree with the
1498/// rest be attributed to the helper that sent it.
1499#[derive(Debug, Clone)]
1500pub struct CollectedShare {
1501    /// The helper channel the response arrived on.
1502    pub channel_id: ChannelId,
1503    /// The helper's response, carrying its committed share.
1504    pub response: GetShareResponseMessage,
1505}
1506
1507/// A single stored share entry, fully self-describing.
1508#[derive(Debug, Clone)]
1509pub struct Share {
1510    /// Numeric identifier of the secret this share belongs to.
1511    pub secret_id: u64,
1512    /// Version number of the secret.
1513    pub version: u32,
1514    /// Opaque protobuf bytes — see [`crate::protocol::DeRecShareStore`] for
1515    /// the per-side format.
1516    pub bytes: Vec<u8>,
1517    /// How many Shamir subshares this share carries. **Owner side only.**
1518    ///
1519    /// The library fills it on every share the owner side saves: the copy it
1520    /// keeps of what it sent each Helper, and the copies a replica
1521    /// Destination mirrors from its Source. It is the Helper's weight in the
1522    /// round that published this version, which a later round may change, so
1523    /// it is the only record of how many subshares a Helper holds for an
1524    /// older version.
1525    ///
1526    /// - Always `None` on a Helper's stored share: a Helper has no notion of
1527    ///   how many subshares it was given.
1528    /// - `None` on an owner row written before this field existed, meaning
1529    ///   the count was not recorded. The library never backfills it;
1530    ///   recomputing it from `bytes` is the application's concern.
1531    ///
1532    /// Stores persist it as given and return it unchanged.
1533    pub subshares: Option<u32>,
1534    /// The threshold `t` this version was split with. **Owner side only.**
1535    ///
1536    /// Written on the same shares as [`Share::subshares`]: the copy the owner
1537    /// keeps of what it sent each Helper carries the round's `t`, and a
1538    /// replica Destination's mirrored copies carry the roster's `t`. A later
1539    /// round may change `t`, so this is the only record of the `t` an older
1540    /// version needs to be recoverable.
1541    ///
1542    /// - Always `None` on a Helper's stored share.
1543    /// - `None` on an owner row written before this field existed. The library
1544    ///   never backfills it.
1545    ///
1546    /// Stores persist it as given and return it unchanged.
1547    pub threshold: Option<u32>,
1548}
1549
1550/// The stored shape of a channel record, which applications persist and the
1551/// library owns.
1552///
1553/// These assert against **JSON text**, not against a round trip. A round trip
1554/// only proves this build agrees with itself; it says nothing about the record
1555/// an older build wrote, which is the compatibility that actually matters here
1556/// and the one that had no coverage when `transport` became `transports`.
1557#[cfg(all(test, feature = "serde"))]
1558mod channel_record_format_tests {
1559    use super::*;
1560    use derec_proto::Protocol;
1561
1562    fn endpoint(uri: &str) -> TransportProtocol {
1563        TransportProtocol {
1564            uri: uri.to_owned(),
1565            protocol: Protocol::Https as i32,
1566        }
1567    }
1568
1569    /// Exactly what a pre-0.0.3 build wrote: a singular `transport` object and
1570    /// no schema marker.
1571    const LEGACY_HELPER: &str = r#"{
1572        "channel_id": 42,
1573        "transport": { "uri": "https://helper.example/derec", "protocol": 0 },
1574        "peer_role": "Helper",
1575        "status": "Paired",
1576        "created_at": 1700000000
1577    }"#;
1578
1579    #[test]
1580    fn a_pre_0_0_3_helper_record_still_loads() {
1581        let decoded: HelperChannel =
1582            serde_json::from_str(LEGACY_HELPER).expect("a record written before the list shape");
1583
1584        assert_eq!(
1585            decoded.transports.len(),
1586            1,
1587            "the singular `transport` is lifted into a one-element list"
1588        );
1589        assert_eq!(decoded.transports[0].uri, "https://helper.example/derec");
1590        assert_eq!(decoded.channel_id, ChannelId(42));
1591        assert_eq!(decoded.status, ChannelStatus::Paired);
1592    }
1593
1594    #[test]
1595    fn a_pre_0_0_3_replica_record_still_loads() {
1596        let legacy = r#"{
1597            "channel_id": 9,
1598            "replica_id": 3,
1599            "transport": { "uri": "https://member.example/derec", "protocol": 0 },
1600            "role": "Source"
1601        }"#;
1602
1603        let decoded: ReplicaMember = serde_json::from_str(legacy).expect("legacy replica row");
1604
1605        assert_eq!(decoded.transports.len(), 1);
1606        assert_eq!(decoded.transports[0].uri, "https://member.example/derec");
1607        assert_eq!(decoded.replica_id, ReplicaId(3));
1608    }
1609
1610    /// A member row written before `handover_channel` existed has none.
1611    #[test]
1612    fn a_v3_replica_record_reads_with_no_handover_channel() {
1613        let v3 = r#"{"schema_version":3,"channel_id":9,"replica_id":3,"transports":[{"uri":"https://member.example/derec","protocol":0}],"communication_info":{},"role":"Source","status":"Paired","created_at":0}"#;
1614
1615        let decoded: ReplicaMember = serde_json::from_str(v3).expect("a v3 replica row");
1616
1617        assert_eq!(decoded.handover_channel, None);
1618    }
1619
1620    /// The field is written only when set, so a member row without one keeps
1621    /// the exact text the Go and .NET bridges rebuild.
1622    #[test]
1623    fn a_handover_channel_is_written_only_when_set() {
1624        let mut member = ReplicaMember {
1625            channel_id: ChannelId(9),
1626            replica_id: ReplicaId(3),
1627            transports: vec![endpoint("https://member.example/derec")],
1628            communication_info: HashMap::new(),
1629            role: ReplicaRole::Source,
1630            status: ChannelStatus::Paired,
1631            created_at: 0,
1632            handover_channel: None,
1633        };
1634        assert_eq!(
1635            serde_json::to_string(&member).expect("serializes"),
1636            r#"{"schema_version":4,"channel_id":9,"replica_id":3,"transports":[{"uri":"https://member.example/derec","protocol":0}],"communication_info":{},"role":"Source","status":"Paired","created_at":0}"#
1637        );
1638
1639        member.handover_channel = Some(ChannelId(7));
1640        let json = serde_json::to_string(&member).expect("serializes");
1641        assert_eq!(
1642            json,
1643            r#"{"schema_version":4,"channel_id":9,"replica_id":3,"transports":[{"uri":"https://member.example/derec","protocol":0}],"communication_info":{},"role":"Source","status":"Paired","created_at":0,"handover_channel":7}"#
1644        );
1645        let reloaded: ReplicaMember = serde_json::from_str(&json).expect("reloads");
1646        assert_eq!(reloaded.handover_channel, Some(ChannelId(7)));
1647    }
1648
1649    /// The loud-failure property the `transport` -> `transports` change was
1650    /// made to keep. Defaulting these to an empty list would produce a channel
1651    /// that looks paired and can never be reached.
1652    #[test]
1653    fn a_record_naming_no_endpoint_is_refused() {
1654        let no_endpoint = r#"{ "channel_id": 42, "peer_role": "Helper" }"#;
1655        let err = serde_json::from_str::<HelperChannel>(no_endpoint)
1656            .expect_err("a record with neither spelling must not default to no endpoints");
1657        assert!(
1658            err.to_string().contains("names no transport endpoint"),
1659            "the error has to say what is wrong with the record: {err}"
1660        );
1661
1662        let empty_list = r#"{ "channel_id": 42, "transports": [], "peer_role": "Helper" }"#;
1663        let err = serde_json::from_str::<HelperChannel>(empty_list)
1664            .expect_err("an explicitly empty list is as unreachable as an absent one");
1665        assert!(
1666            err.to_string().contains("empty `transports`"),
1667            "the error has to distinguish empty from absent: {err}"
1668        );
1669    }
1670
1671    /// A record written before `weight` existed is a Helper on one subshare,
1672    /// which is what every publish gave it then. The schema version does not
1673    /// move for an additive field.
1674    #[test]
1675    fn a_record_without_a_weight_reads_as_one() {
1676        let current = r#"{
1677            "schema_version": 3,
1678            "channel_id": 42,
1679            "transports": [{ "uri": "https://helper.example/derec", "protocol": 0 }],
1680            "peer_role": "Helper"
1681        }"#;
1682        let decoded: HelperChannel = serde_json::from_str(current).expect("a v3 record");
1683        assert_eq!(decoded.weight, 1);
1684
1685        let legacy: HelperChannel =
1686            serde_json::from_str(LEGACY_HELPER).expect("a pre-0.0.3 record");
1687        assert_eq!(legacy.weight, 1);
1688    }
1689
1690    /// `0` is never a valid weight, so a stored `0` comes from a writer that
1691    /// predates the field and reads as `1`, the same rule the protobuf roster
1692    /// applies.
1693    #[test]
1694    fn a_stored_weight_of_zero_reads_as_one() {
1695        let zero = r#"{
1696            "schema_version": 3,
1697            "channel_id": 42,
1698            "transports": [{ "uri": "https://helper.example/derec", "protocol": 0 }],
1699            "peer_role": "Helper",
1700            "weight": 0
1701        }"#;
1702        let decoded: HelperChannel = serde_json::from_str(zero).expect("a v3 record");
1703        assert_eq!(decoded.weight, 1);
1704    }
1705
1706    #[test]
1707    fn a_stored_weight_round_trips() {
1708        let record = HelperChannel {
1709            channel_id: ChannelId(42),
1710            transports: vec![endpoint("https://helper.example/derec")],
1711            communication_info: HashMap::new(),
1712            peer_role: SenderKind::Helper,
1713            status: ChannelStatus::Paired,
1714            created_at: 1_700_000_000,
1715            weight: 3,
1716        };
1717        let json = serde_json::to_string(&record).expect("serializes");
1718        let reloaded: HelperChannel = serde_json::from_str(&json).expect("reloads");
1719        assert_eq!(reloaded.weight, 3);
1720        assert_eq!(
1721            serde_json::from_str::<serde_json::Value>(&json).unwrap()["schema_version"],
1722            serde_json::json!(4)
1723        );
1724    }
1725
1726    /// A record from a build that knew a shape this one does not must not be
1727    /// read and written back with the unknown fields silently dropped.
1728    #[test]
1729    fn a_newer_schema_version_is_refused() {
1730        let from_the_future = format!(
1731            r#"{{
1732                "schema_version": {},
1733                "channel_id": 42,
1734                "transports": [{{ "uri": "https://helper.example/derec", "protocol": 0 }}],
1735                "peer_role": "Helper"
1736            }}"#,
1737            CHANNEL_RECORD_SCHEMA_VERSION + 1
1738        );
1739
1740        let err = serde_json::from_str::<HelperChannel>(&from_the_future)
1741            .expect_err("a future schema version must be refused, not truncated");
1742        assert!(
1743            err.to_string().contains("understands at most"),
1744            "the error has to name the version gap: {err}"
1745        );
1746    }
1747
1748    /// Both spellings present is what a careful migration leaves behind — it
1749    /// added the list without deleting what it replaced.
1750    #[test]
1751    fn the_list_wins_when_both_spellings_are_present() {
1752        let both = r#"{
1753            "channel_id": 42,
1754            "transport": { "uri": "https://stale.example/derec", "protocol": 0 },
1755            "transports": [
1756                { "uri": "https://current.example/derec", "protocol": 0 },
1757                { "uri": "grpcs://current.example:443", "protocol": 1 }
1758            ],
1759            "peer_role": "Helper"
1760        }"#;
1761
1762        let decoded: HelperChannel = serde_json::from_str(both).expect("both spellings present");
1763
1764        assert_eq!(decoded.transports.len(), 2, "the list is authoritative");
1765        assert_eq!(decoded.transports[0].uri, "https://current.example/derec");
1766    }
1767
1768    /// What this build writes, asserted against the serialized text: the
1769    /// marker is stamped, the list is the only endpoint spelling emitted, and
1770    /// the superseded one is never written back.
1771    #[test]
1772    fn a_written_record_carries_the_marker_and_only_the_list() {
1773        let record = HelperChannel {
1774            channel_id: ChannelId(42),
1775            transports: vec![endpoint("https://helper.example/derec")],
1776            communication_info: HashMap::new(),
1777            peer_role: SenderKind::Helper,
1778            status: ChannelStatus::Paired,
1779            created_at: 1_700_000_000,
1780            weight: 1,
1781        };
1782
1783        let json: serde_json::Value =
1784            serde_json::to_value(&record).expect("a channel record serializes");
1785
1786        assert_eq!(
1787            json["schema_version"],
1788            serde_json::json!(CHANNEL_RECORD_SCHEMA_VERSION),
1789            "every record this build writes is stamped"
1790        );
1791        assert!(json["transports"].is_array());
1792        assert!(
1793            json.get("transport").is_none(),
1794            "the pre-0.0.3 spelling is read, never written: {json}"
1795        );
1796
1797        // The exact text, not just the fields: the Go and .NET bridges
1798        // rebuild this JSON from their own structs rather than passing the
1799        // bytes through, and their encoders are ordered hand-written mirrors
1800        // of this one. Asserting the string is what makes a field added here
1801        // — or reordered — fail on the Rust side too, instead of only in a
1802        // hand-written SDK expectation that nothing cross-checks.
1803        assert_eq!(
1804            serde_json::to_string(&record).expect("serializes"),
1805            r#"{"schema_version":4,"channel_id":42,"transports":[{"uri":"https://helper.example/derec","protocol":0}],"communication_info":{},"peer_role":"Helper","status":"Paired","created_at":1700000000,"weight":1}"#
1806        );
1807    }
1808
1809    /// A record written by this build reads back identically, and a record
1810    /// upgraded from the legacy shape is indistinguishable from one written
1811    /// natively once it has been through a save.
1812    #[test]
1813    fn an_upgraded_record_is_stable_once_rewritten() {
1814        let upgraded: HelperChannel =
1815            serde_json::from_str(LEGACY_HELPER).expect("legacy record loads");
1816
1817        let rewritten = serde_json::to_string(&upgraded).expect("serializes");
1818        let reloaded: HelperChannel =
1819            serde_json::from_str(&rewritten).expect("its own output reloads");
1820
1821        assert_eq!(reloaded.transports.len(), upgraded.transports.len());
1822        assert_eq!(reloaded.transports[0].uri, upgraded.transports[0].uri);
1823        assert_eq!(reloaded.channel_id, upgraded.channel_id);
1824        assert_eq!(reloaded.created_at, upgraded.created_at);
1825        assert!(
1826            serde_json::from_str::<serde_json::Value>(&rewritten).unwrap()["schema_version"]
1827                == serde_json::json!(CHANNEL_RECORD_SCHEMA_VERSION),
1828            "the upgrade is persisted, so the next read needs no lifting"
1829        );
1830    }
1831
1832    /// The records travel inside `ChannelRecord`, so the compatibility has to
1833    /// survive the enum's tagging rather than only working on the inner type.
1834    #[test]
1835    fn the_compatibility_survives_the_channel_record_wrapper() {
1836        let legacy = format!(r#"{{ "Helper": {LEGACY_HELPER} }}"#);
1837
1838        let decoded: ChannelRecord =
1839            serde_json::from_str(&legacy).expect("a legacy record inside its wrapper");
1840
1841        match decoded {
1842            ChannelRecord::Helper(h) => assert_eq!(h.transports.len(), 1),
1843            other => panic!("expected a helper record, got {other:?}"),
1844        }
1845    }
1846}
1847
1848#[cfg(all(test, feature = "serde"))]
1849mod tests {
1850    use super::*;
1851
1852    /// Every `SecretValue` variant round-trips through serde — the path a
1853    /// store implementation takes when it opts for serde over the
1854    /// byte-level accessors. Exercises the custom `PairingKeyMaterial`
1855    /// impls and the prost `ContactMessage` adapter.
1856    #[test]
1857    fn secret_value_serde_round_trips_all_variants() {
1858        let cases = [
1859            SecretValue::SharedKey([7u8; 32]),
1860            SecretValue::PairingSecret(PairingKeyMaterial::from_bytes(vec![1, 2, 3, 4, 5])),
1861            SecretValue::PairingContact(ContactMessage {
1862                nonce: 42,
1863                ..Default::default()
1864            }),
1865        ];
1866
1867        for value in cases {
1868            let json = serde_json::to_vec(&value).expect("serialize");
1869            let decoded: SecretValue = serde_json::from_slice(&json).expect("deserialize");
1870            match (&value, &decoded) {
1871                (SecretValue::SharedKey(a), SecretValue::SharedKey(b)) => assert_eq!(a, b),
1872                (SecretValue::PairingSecret(a), SecretValue::PairingSecret(b)) => {
1873                    assert_eq!(a.as_bytes(), b.as_bytes())
1874                }
1875                (SecretValue::PairingContact(a), SecretValue::PairingContact(b)) => {
1876                    assert_eq!(a, b)
1877                }
1878                _ => panic!("variant changed across serde round-trip"),
1879            }
1880        }
1881    }
1882
1883    /// The serde form and the `from_bytes`/`as_bytes` form describe the
1884    /// same opaque blob, so a value serialized one way decodes the other.
1885    #[test]
1886    fn pairing_key_material_serde_matches_byte_accessors() {
1887        let material = PairingKeyMaterial::from_bytes(vec![9, 8, 7, 6]);
1888        let json = serde_json::to_vec(&material).expect("serialize");
1889        let decoded: PairingKeyMaterial = serde_json::from_slice(&json).expect("deserialize");
1890        assert_eq!(material.as_bytes(), decoded.as_bytes());
1891    }
1892}
1893
1894#[cfg(test)]
1895mod persisted_discriminant_tests {
1896    //! Pins the discriminants callers are told they may store.
1897    //!
1898    //! `library/tests/enum_fixture.rs` also checks these, but it checks them
1899    //! against `enums.json` — a file that gets updated as part of responding
1900    //! to the failure. Reorder an enum, run the suite, update the fixture the
1901    //! message points you at, and it goes green with every deployed database
1902    //! now misreading its own rows.
1903    //!
1904    //! These assertions name the numbers directly, so there is nothing to
1905    //! update but the assertion itself. Changing one is then a deliberate act
1906    //! with this comment attached to it, which is the whole point: renumbering
1907    //! is not forbidden, it is just never something to do by accident.
1908    //!
1909    //! If you are here because one of these failed: appending a variant is
1910    //! fine and needs a new line below. Renumbering an existing one breaks
1911    //! data at rest in every deployment that has stored it, and no migration
1912    //! runs on our side to fix it.
1913
1914    use super::{SecretKind, StateKind};
1915
1916    #[test]
1917    fn secret_kind_discriminants_are_unchanged() {
1918        assert_eq!(SecretKind::SharedKey as u8, 0);
1919        assert_eq!(SecretKind::PairingSecret as u8, 1);
1920        assert_eq!(SecretKind::PairingContact as u8, 2);
1921    }
1922
1923    #[test]
1924    fn state_kind_discriminants_are_unchanged() {
1925        assert_eq!(StateKind::PendingVerification as u8, 0);
1926        assert_eq!(StateKind::PendingRecovery as u8, 1);
1927        assert_eq!(StateKind::PendingUnpair as u8, 2);
1928        assert_eq!(StateKind::SharingRound as u8, 3);
1929        assert_eq!(StateKind::PendingReplicaDiscovery as u8, 4);
1930    }
1931}
1932
1933#[cfg(test)]
1934mod expired_channel_cleanup_tests {
1935    use super::ExpiredChannelCleanup;
1936
1937    /// Constructors do not validate — normalization is the builder's job,
1938    /// so a zero survives construction intact.
1939    #[test]
1940    fn from_secs_does_not_clamp() {
1941        assert_eq!(
1942            ExpiredChannelCleanup::from_secs(0),
1943            ExpiredChannelCleanup::Enabled { timeout_in_secs: 0 }
1944        );
1945    }
1946
1947    #[test]
1948    fn from_secs_preserves_value() {
1949        assert_eq!(
1950            ExpiredChannelCleanup::from_secs(900),
1951            ExpiredChannelCleanup::Enabled {
1952                timeout_in_secs: 900
1953            }
1954        );
1955    }
1956
1957    /// The marshalling seam: a disabled policy discards its timeout here,
1958    /// in Rust, so no SDK has to make that decision.
1959    #[test]
1960    fn new_disabled_discards_timeout() {
1961        assert_eq!(
1962            ExpiredChannelCleanup::new(false, 900),
1963            ExpiredChannelCleanup::Disabled
1964        );
1965    }
1966
1967    #[test]
1968    fn new_enabled_keeps_timeout() {
1969        assert_eq!(
1970            ExpiredChannelCleanup::new(true, 900),
1971            ExpiredChannelCleanup::Enabled {
1972                timeout_in_secs: 900
1973            }
1974        );
1975    }
1976
1977    #[test]
1978    fn default_matches_historical_behaviour() {
1979        assert_eq!(
1980            ExpiredChannelCleanup::default(),
1981            ExpiredChannelCleanup::Enabled {
1982                timeout_in_secs: 300
1983            }
1984        );
1985    }
1986}
1987
1988#[cfg(test)]
1989mod target_filter_tests {
1990    use super::*;
1991
1992    fn ids(raw: &[u64]) -> Vec<ChannelId> {
1993        raw.iter().copied().map(ChannelId).collect()
1994    }
1995
1996    /// `All` is every paired channel, in the order the store returned them.
1997    ///
1998    /// Order is asserted rather than membership: it decides the order a
1999    /// fan-out dispatches in, and therefore the order of the events an
2000    /// application sees back.
2001    #[test]
2002    fn all_keeps_every_known_channel_in_store_order() {
2003        let known = ids(&[30, 10, 20]);
2004        assert_eq!(Target::All.filter(&known), known);
2005    }
2006
2007    #[test]
2008    fn single_yields_the_channel_when_it_is_known() {
2009        let known = ids(&[30, 10, 20]);
2010        assert_eq!(Target::Single(ChannelId(10)).filter(&known), ids(&[10]));
2011    }
2012
2013    /// A caller may name a channel this device never paired on, or one that
2014    /// has since been unpaired. It is dropped rather than refused.
2015    #[test]
2016    fn single_yields_nothing_when_the_channel_is_unknown() {
2017        let known = ids(&[30, 10, 20]);
2018        assert!(Target::Single(ChannelId(99)).filter(&known).is_empty());
2019    }
2020
2021    /// `Many` follows the **caller's** order, not the store's, so an
2022    /// application that ranks its helpers keeps that ranking.
2023    #[test]
2024    fn many_keeps_the_callers_order() {
2025        let known = ids(&[30, 10, 20]);
2026        assert_eq!(
2027            Target::Many(ids(&[20, 30])).filter(&known),
2028            ids(&[20, 30]),
2029            "the requested order must survive, not be re-sorted into store order"
2030        );
2031    }
2032
2033    /// One stale id must not fail the fan-out to everyone else.
2034    #[test]
2035    fn many_drops_unknown_ids_and_keeps_the_rest() {
2036        let known = ids(&[30, 10, 20]);
2037        assert_eq!(
2038            Target::Many(ids(&[10, 99, 20])).filter(&known),
2039            ids(&[10, 20])
2040        );
2041    }
2042
2043    #[test]
2044    fn a_target_naming_only_unknown_channels_yields_nothing() {
2045        let known = ids(&[30, 10, 20]);
2046        assert!(Target::Many(ids(&[98, 99])).filter(&known).is_empty());
2047    }
2048
2049    /// A device with no paired channels reaches nobody, whatever it asked for.
2050    #[test]
2051    fn nothing_is_reachable_when_no_channel_is_known() {
2052        assert!(Target::All.filter(&[]).is_empty());
2053        assert!(Target::Single(ChannelId(10)).filter(&[]).is_empty());
2054        assert!(Target::Many(ids(&[10, 20])).filter(&[]).is_empty());
2055    }
2056
2057    /// A duplicate in the request is not de-duplicated: the caller asked for
2058    /// it twice and the fan-out honours that literally.
2059    #[test]
2060    fn many_does_not_deduplicate_the_request() {
2061        let known = ids(&[10, 20]);
2062        assert_eq!(Target::Many(ids(&[10, 10])).filter(&known), ids(&[10, 10]));
2063    }
2064}
2065
2066#[cfg(test)]
2067mod channel_filter_tests {
2068    use super::*;
2069    use crate::types::ReplicaId;
2070
2071    fn member(
2072        id: u64,
2073        status: ChannelStatus,
2074        role: ReplicaRole,
2075    ) -> (ReplicaId, ChannelStatus, ReplicaRole) {
2076        (ReplicaId(id), status, role)
2077    }
2078
2079    /// The contract every field rests on: empty means "do not restrict".
2080    /// A store that reads `ids: []` as "no rows" instead of "all rows"
2081    /// silently returns nothing, and the flow above it does nothing at all.
2082    #[test]
2083    fn a_default_filter_admits_everything() {
2084        let filter = ReplicaFilter::default();
2085        let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
2086        assert!(filter.matches(&id, status, &role));
2087    }
2088
2089    #[test]
2090    fn ids_restrict_to_the_listed_members() {
2091        let filter = ReplicaFilter {
2092            ids: vec![ReplicaId(1), ReplicaId(2)],
2093            ..Default::default()
2094        };
2095        for id in [1, 2] {
2096            let (id, status, role) = member(id, ChannelStatus::Paired, ReplicaRole::Source);
2097            assert!(filter.matches(&id, status, &role));
2098        }
2099        let (id, status, role) = member(3, ChannelStatus::Paired, ReplicaRole::Source);
2100        assert!(!filter.matches(&id, status, &role));
2101    }
2102
2103    /// The status list is an allow-list, not a single value: the sharing
2104    /// flow needs `Paired` *and* `Unpairing` on one listing, because a
2105    /// departing member learns its removal completed by receiving the
2106    /// version that omits it.
2107    #[test]
2108    fn status_is_an_allow_list() {
2109        let filter = ReplicaFilter {
2110            status: vec![ChannelStatus::Paired, ChannelStatus::Unpairing],
2111            ..Default::default()
2112        };
2113        for status in [ChannelStatus::Paired, ChannelStatus::Unpairing] {
2114            let (id, status, role) = member(1, status, ReplicaRole::Destination);
2115            assert!(filter.matches(&id, status, &role));
2116        }
2117        let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
2118        assert!(!filter.matches(&id, status, &role));
2119    }
2120
2121    #[test]
2122    fn role_restricts_when_set_and_admits_when_none() {
2123        let filter = ReplicaFilter {
2124            role: Some(ReplicaRole::Destination),
2125            ..Default::default()
2126        };
2127        let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Destination);
2128        assert!(filter.matches(&id, status, &role));
2129        let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
2130        assert!(!filter.matches(&id, status, &role));
2131
2132        let any = ReplicaFilter::default();
2133        assert!(any.matches(&id, status, &role));
2134    }
2135
2136    /// Six flows exclude this device's own row, which `replicas()` returns
2137    /// deliberately so the group stays reconstructible from the stores.
2138    #[test]
2139    fn exclude_omits_the_named_members() {
2140        let filter = ReplicaFilter {
2141            exclude: vec![ReplicaId(7)],
2142            ..Default::default()
2143        };
2144        let (id, status, role) = member(7, ChannelStatus::Paired, ReplicaRole::Source);
2145        assert!(!filter.matches(&id, status, &role));
2146        let (id, status, role) = member(8, ChannelStatus::Paired, ReplicaRole::Source);
2147        assert!(filter.matches(&id, status, &role));
2148    }
2149
2150    /// `exclude` is applied after `ids`, so naming the same member in both
2151    /// omits it rather than admitting it. Stated because the successor pick
2152    /// and the fan-out filters compose these two fields on one call.
2153    #[test]
2154    fn exclude_overrides_ids() {
2155        let filter = ReplicaFilter {
2156            ids: vec![ReplicaId(1), ReplicaId(2)],
2157            exclude: vec![ReplicaId(2)],
2158            ..Default::default()
2159        };
2160        let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
2161        assert!(filter.matches(&id, status, &role));
2162        let (id, status, role) = member(2, ChannelStatus::Paired, ReplicaRole::Source);
2163        assert!(!filter.matches(&id, status, &role));
2164    }
2165
2166    #[test]
2167    fn restrictions_combine_with_and() {
2168        let filter = ReplicaFilter {
2169            status: vec![ChannelStatus::Paired],
2170            role: Some(ReplicaRole::Destination),
2171            exclude: vec![ReplicaId(9)],
2172            ..Default::default()
2173        };
2174        let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Destination);
2175        assert!(filter.matches(&id, status, &role));
2176
2177        // Each of the three, violated on its own.
2178        let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
2179        assert!(!filter.matches(&id, status, &role));
2180        let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
2181        assert!(!filter.matches(&id, status, &role));
2182        let (id, status, role) = member(9, ChannelStatus::Paired, ReplicaRole::Destination);
2183        assert!(!filter.matches(&id, status, &role));
2184    }
2185
2186    /// The helper alias carries the peer's `SenderKind`, not a `ReplicaRole`
2187    /// — the two listings differ in that one type, which is why the filter
2188    /// is generic over it.
2189    #[test]
2190    fn the_helper_alias_filters_on_sender_kind() {
2191        let filter = HelperFilter {
2192            role: Some(SenderKind::Helper),
2193            ..Default::default()
2194        };
2195        assert!(filter.matches(&ChannelId(1), ChannelStatus::Paired, &SenderKind::Helper));
2196        assert!(!filter.matches(&ChannelId(1), ChannelStatus::Paired, &SenderKind::Owner));
2197    }
2198}