use crate::types::{ChannelId, ReplicaId};
use derec_cryptography::pairing::PairingSecretKeyMaterial;
use derec_proto::ContactMessage;
#[cfg(any(feature = "serde", target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};
use std::time::Duration;
use zeroize::Zeroizing;
pub mod secret;
#[cfg(any(feature = "serde", target_arch = "wasm32"))]
pub mod state_record;
pub use secret::{HelperInfo, ReplicaInfo, Replicas, Secret, UserSecret};
#[cfg(any(feature = "serde", target_arch = "wasm32"))]
pub use state_record::{ReplicaDiscoveryReport, StateItemRecord, StateKeyRecord};
#[derive(Debug, Clone)]
pub enum Target {
All,
Single(ChannelId),
Many(Vec<ChannelId>),
}
impl Target {
pub fn filter(self, known: &[ChannelId]) -> Vec<ChannelId> {
match self {
Target::All => known.to_vec(),
Target::Single(id) => known.iter().copied().filter(|k| *k == id).collect(),
Target::Many(ids) => ids.into_iter().filter(|id| known.contains(id)).collect(),
}
}
pub fn ids(&self) -> Vec<ChannelId> {
match self {
Target::All => Vec::new(),
Target::Single(id) => vec![*id],
Target::Many(ids) => ids.clone(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize)
)]
pub enum ChannelStatus {
Pending,
#[default]
Paired,
Unpairing,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize)
)]
pub enum ExpiredChannelCleanup {
Disabled,
Enabled { timeout_in_secs: u64 },
}
impl Default for ExpiredChannelCleanup {
fn default() -> Self {
Self::Enabled {
timeout_in_secs: 300,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Timeouts {
pub inbound_message: Duration,
pub sharing_round: Duration,
pub unpair_ack: Duration,
pub expired_channels: ExpiredChannelCleanup,
}
impl Default for Timeouts {
fn default() -> Self {
Self {
inbound_message: Duration::from_secs(300),
sharing_round: Duration::from_secs(60),
unpair_ack: Duration::from_secs(60),
expired_channels: ExpiredChannelCleanup::default(),
}
}
}
impl ExpiredChannelCleanup {
pub fn from_secs(secs: u64) -> Self {
Self::Enabled {
timeout_in_secs: secs,
}
}
pub fn new(enabled: bool, timeout_in_secs: u64) -> Self {
if enabled {
Self::Enabled { timeout_in_secs }
} else {
Self::Disabled
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ReplicaRole {
Source,
Destination,
}
impl ReplicaRole {
pub fn counterparty(self) -> Self {
match self {
ReplicaRole::Source => ReplicaRole::Destination,
ReplicaRole::Destination => ReplicaRole::Source,
}
}
pub fn from_i32(value: i32) -> Option<Self> {
match value {
v if v == ReplicaRole::Source as i32 => Some(ReplicaRole::Source),
v if v == ReplicaRole::Destination as i32 => Some(ReplicaRole::Destination),
_ => None,
}
}
pub fn from_sender_kind(kind: derec_proto::SenderKind) -> Option<Self> {
match kind {
derec_proto::SenderKind::ReplicaSource => Some(ReplicaRole::Source),
derec_proto::SenderKind::ReplicaDestination => Some(ReplicaRole::Destination),
_ => None,
}
}
pub fn to_sender_kind(self) -> derec_proto::SenderKind {
match self {
ReplicaRole::Source => derec_proto::SenderKind::ReplicaSource,
ReplicaRole::Destination => derec_proto::SenderKind::ReplicaDestination,
}
}
}
#[derive(Clone, Debug)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize),
serde(
into = "channel_wire::HelperChannelWire",
try_from = "channel_wire::HelperChannelWire"
)
)]
pub struct HelperChannel {
pub channel_id: ChannelId,
pub transports: Vec<derec_proto::TransportProtocol>,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub communication_info: std::collections::HashMap<String, String>,
pub peer_role: derec_proto::SenderKind,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub status: ChannelStatus,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub created_at: u64,
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
serde(default = "channel_wire::default_weight")
)]
pub weight: u32,
}
#[derive(Clone, Debug)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize),
serde(
into = "channel_wire::ReplicaMemberWire",
try_from = "channel_wire::ReplicaMemberWire"
)
)]
pub struct ReplicaMember {
pub channel_id: ChannelId,
pub replica_id: ReplicaId,
pub transports: Vec<derec_proto::TransportProtocol>,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub communication_info: std::collections::HashMap<String, String>,
pub role: ReplicaRole,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub status: ChannelStatus,
#[cfg_attr(any(feature = "serde", target_arch = "wasm32"), serde(default))]
pub created_at: u64,
}
pub const CHANNEL_RECORD_SCHEMA_VERSION: u8 = 3;
#[cfg(any(feature = "serde", target_arch = "wasm32"))]
mod channel_wire {
use super::{
CHANNEL_RECORD_SCHEMA_VERSION, ChannelId, ChannelStatus, HelperChannel, ReplicaId,
ReplicaMember, ReplicaRole,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
fn endpoints(
transport: Option<derec_proto::TransportProtocol>,
transports: Option<Vec<derec_proto::TransportProtocol>>,
record: &'static str,
) -> Result<Vec<derec_proto::TransportProtocol>, String> {
let resolved = match (transports, transport) {
(Some(list), _) => list,
(None, Some(one)) => vec![one],
(None, None) => {
return Err(format!(
"{record} names no transport endpoint: neither `transports` nor the \
pre-0.0.3 `transport` is present. A channel record with no endpoint \
describes a peer that looks paired and cannot be reached"
));
}
};
if resolved.is_empty() {
return Err(format!(
"{record} has an empty `transports` list. A recorded channel always has at \
least one endpoint — the library refuses to record a peer whose endpoints \
were all filtered away"
));
}
Ok(resolved)
}
pub(super) fn default_weight() -> u32 {
1
}
fn check_version(schema_version: u8, record: &'static str) -> Result<(), String> {
if schema_version > CHANNEL_RECORD_SCHEMA_VERSION {
return Err(format!(
"{record} was written with schema version {schema_version}, but this build \
understands at most {CHANNEL_RECORD_SCHEMA_VERSION}. Reading it would drop \
the fields this build cannot see, and writing the record back would make \
that loss permanent"
));
}
Ok(())
}
#[derive(Serialize, Deserialize)]
pub struct HelperChannelWire {
#[serde(default)]
schema_version: u8,
channel_id: ChannelId,
#[serde(default, skip_serializing_if = "Option::is_none")]
transport: Option<derec_proto::TransportProtocol>,
#[serde(default, skip_serializing_if = "Option::is_none")]
transports: Option<Vec<derec_proto::TransportProtocol>>,
#[serde(default)]
communication_info: HashMap<String, String>,
peer_role: derec_proto::SenderKind,
#[serde(default)]
status: ChannelStatus,
#[serde(default)]
created_at: u64,
#[serde(default = "default_weight")]
weight: u32,
}
impl From<HelperChannel> for HelperChannelWire {
fn from(value: HelperChannel) -> Self {
Self {
schema_version: CHANNEL_RECORD_SCHEMA_VERSION,
channel_id: value.channel_id,
transport: None,
transports: Some(value.transports),
communication_info: value.communication_info,
peer_role: value.peer_role,
status: value.status,
created_at: value.created_at,
weight: value.weight,
}
}
}
impl TryFrom<HelperChannelWire> for HelperChannel {
type Error = String;
fn try_from(wire: HelperChannelWire) -> Result<Self, Self::Error> {
check_version(wire.schema_version, "HelperChannel")?;
Ok(Self {
channel_id: wire.channel_id,
transports: endpoints(wire.transport, wire.transports, "HelperChannel")?,
communication_info: wire.communication_info,
peer_role: wire.peer_role,
status: wire.status,
created_at: wire.created_at,
weight: wire.weight.max(1),
})
}
}
#[derive(Serialize, Deserialize)]
pub struct ReplicaMemberWire {
#[serde(default)]
schema_version: u8,
channel_id: ChannelId,
replica_id: ReplicaId,
#[serde(default, skip_serializing_if = "Option::is_none")]
transport: Option<derec_proto::TransportProtocol>,
#[serde(default, skip_serializing_if = "Option::is_none")]
transports: Option<Vec<derec_proto::TransportProtocol>>,
#[serde(default)]
communication_info: HashMap<String, String>,
role: ReplicaRole,
#[serde(default)]
status: ChannelStatus,
#[serde(default)]
created_at: u64,
}
impl From<ReplicaMember> for ReplicaMemberWire {
fn from(value: ReplicaMember) -> Self {
Self {
schema_version: CHANNEL_RECORD_SCHEMA_VERSION,
channel_id: value.channel_id,
replica_id: value.replica_id,
transport: None,
transports: Some(value.transports),
communication_info: value.communication_info,
role: value.role,
status: value.status,
created_at: value.created_at,
}
}
}
impl TryFrom<ReplicaMemberWire> for ReplicaMember {
type Error = String;
fn try_from(wire: ReplicaMemberWire) -> Result<Self, Self::Error> {
check_version(wire.schema_version, "ReplicaMember")?;
Ok(Self {
channel_id: wire.channel_id,
replica_id: wire.replica_id,
transports: endpoints(wire.transport, wire.transports, "ReplicaMember")?,
communication_info: wire.communication_info,
role: wire.role,
status: wire.status,
created_at: wire.created_at,
})
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChannelQuery {
Helper {
channel_id: ChannelId,
},
Replica {
channel_id: ChannelId,
replica_id: ReplicaId,
},
}
impl ChannelQuery {
pub fn channel_id(&self) -> ChannelId {
match self {
ChannelQuery::Helper { channel_id } => *channel_id,
ChannelQuery::Replica { channel_id, .. } => *channel_id,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize),
serde(
default,
bound = "Role: Serialize + serde::de::DeserializeOwned, Id: Serialize + serde::de::DeserializeOwned"
)
)]
pub struct ChannelFilter<Role, Id> {
pub ids: Vec<Id>,
pub status: Vec<ChannelStatus>,
pub role: Option<Role>,
pub exclude: Vec<Id>,
}
impl<Role, Id> Default for ChannelFilter<Role, Id> {
fn default() -> Self {
Self {
ids: Vec::new(),
status: Vec::new(),
role: None,
exclude: Vec::new(),
}
}
}
impl<Role: PartialEq, Id: PartialEq> ChannelFilter<Role, Id> {
pub fn matches(&self, id: &Id, status: ChannelStatus, role: &Role) -> bool {
(self.ids.is_empty() || self.ids.contains(id))
&& (self.status.is_empty() || self.status.contains(&status))
&& self.role.as_ref().is_none_or(|wanted| wanted == role)
&& !self.exclude.contains(id)
}
}
pub type ReplicaFilter = ChannelFilter<ReplicaRole, ReplicaId>;
pub type HelperFilter = ChannelFilter<derec_proto::SenderKind, ChannelId>;
#[derive(Clone, Debug)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize)
)]
pub enum ChannelRecord {
Helper(HelperChannel),
Replica(ReplicaMember),
}
impl ChannelRecord {
pub fn channel_id(&self) -> ChannelId {
match self {
ChannelRecord::Helper(h) => h.channel_id,
ChannelRecord::Replica(r) => r.channel_id,
}
}
pub fn status(&self) -> ChannelStatus {
match self {
ChannelRecord::Helper(h) => h.status,
ChannelRecord::Replica(r) => r.status,
}
}
pub fn transports(&self) -> &[derec_proto::TransportProtocol] {
match self {
ChannelRecord::Helper(h) => &h.transports,
ChannelRecord::Replica(r) => &r.transports,
}
}
pub fn communication_info(&self) -> &std::collections::HashMap<String, String> {
match self {
ChannelRecord::Helper(h) => &h.communication_info,
ChannelRecord::Replica(r) => &r.communication_info,
}
}
pub fn as_helper(&self) -> Option<&HelperChannel> {
match self {
ChannelRecord::Helper(h) => Some(h),
_ => None,
}
}
pub fn as_replica(&self) -> Option<&ReplicaMember> {
match self {
ChannelRecord::Replica(r) => Some(r),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct UserSecrets {
pub version: u32,
pub secrets: Vec<UserSecret>,
pub description: Option<String>,
pub author_replica_id: Option<u64>,
pub threshold: Option<u32>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ChannelShare {
#[prost(uint64, tag = "1")]
pub channel_id: u64,
#[prost(bytes = "vec", tag = "2")]
pub committed_share: ::prost::alloc::vec::Vec<u8>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ReplicaSecretPayload {
#[prost(message, optional, tag = "1")]
pub secret: ::core::option::Option<Secret>,
#[prost(message, repeated, tag = "2")]
pub shares: ::prost::alloc::vec::Vec<ChannelShare>,
#[prost(bytes = "vec", tag = "3")]
pub shared_key: ::prost::alloc::vec::Vec<u8>,
#[prost(uint32, tag = "4")]
pub version: u32,
#[prost(uint64, optional, tag = "5")]
pub author_replica_id: ::core::option::Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretKind {
SharedKey = 0,
PairingSecret = 1,
PairingContact = 2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingPolicy {
Skip,
Fail,
}
#[derive(Clone)]
pub struct PairingKeyMaterial(Zeroizing<Vec<u8>>);
impl PairingKeyMaterial {
pub fn from_bytes(bytes: Vec<u8>) -> Self {
Self(Zeroizing::new(bytes))
}
pub fn as_bytes(&self) -> &[u8] {
self.0.as_slice()
}
pub(crate) fn from_secret(material: &PairingSecretKeyMaterial) -> Self {
use ark_serialize::CanonicalSerialize as _;
let mut buf = Vec::with_capacity(material.compressed_size());
material
.serialize_compressed(&mut buf)
.expect("ark serialization of PairingSecretKeyMaterial is infallible");
Self(Zeroizing::new(buf))
}
pub(crate) fn to_secret(&self) -> crate::Result<PairingSecretKeyMaterial> {
use ark_serialize::CanonicalDeserialize as _;
PairingSecretKeyMaterial::deserialize_compressed(self.0.as_slice())
.map_err(|_| crate::Error::Invariant("stored PairingSecret bytes failed to decode"))
}
}
#[cfg(feature = "serde")]
impl Serialize for PairingKeyMaterial {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.as_slice().serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for PairingKeyMaterial {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = Vec::<u8>::deserialize(deserializer)?;
Ok(Self(Zeroizing::new(bytes)))
}
}
#[cfg(feature = "serde")]
mod contact_serde {
use super::ContactMessage;
use prost::Message as _;
use serde::{Deserialize as _, Deserializer, Serialize as _, Serializer};
pub(super) fn serialize<S>(contact: &ContactMessage, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
contact.encode_to_vec().serialize(serializer)
}
pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<ContactMessage, D::Error>
where
D: Deserializer<'de>,
{
let bytes = Vec::<u8>::deserialize(deserializer)?;
ContactMessage::decode(bytes.as_slice()).map_err(serde::de::Error::custom)
}
}
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SecretValue {
SharedKey(crate::types::SharedKey),
PairingSecret(PairingKeyMaterial),
PairingContact(#[cfg_attr(feature = "serde", serde(with = "contact_serde"))] ContactMessage),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StateKind {
PendingVerification = 0,
PendingRecovery = 1,
PendingUnpair = 2,
SharingRound = 3,
PendingReplicaDiscovery = 4,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateKey {
PendingVerification { channel_id: ChannelId },
PendingRecovery { secret_id: u64, version: u32 },
PendingUnpair { channel_id: ChannelId },
PendingReplicaDiscovery,
SharingRound { version: u32 },
}
impl StateKey {
pub fn kind(&self) -> StateKind {
match self {
StateKey::PendingVerification { .. } => StateKind::PendingVerification,
StateKey::PendingRecovery { .. } => StateKind::PendingRecovery,
StateKey::PendingUnpair { .. } => StateKind::PendingUnpair,
StateKey::PendingReplicaDiscovery => StateKind::PendingReplicaDiscovery,
StateKey::SharingRound { .. } => StateKind::SharingRound,
}
}
}
#[derive(Debug, Clone)]
pub enum StateItem {
PendingVerification {
channel_id: ChannelId,
request: derec_proto::VerifyShareRequestMessage,
},
PendingRecovery {
secret_id: u64,
version: u32,
shares: Vec<CollectedShare>,
},
PendingUnpair {
channel_id: ChannelId,
started_at: u64,
},
PendingReplicaDiscovery {
local_version: u32,
pending: std::collections::HashSet<ReplicaId>,
reported: std::collections::HashMap<ReplicaId, u32>,
started_at: u64,
},
SharingRound(Box<SharingRoundState>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SharingRoundState {
pub version: u32,
pub pending: std::collections::HashSet<ChannelId>,
pub confirmed: std::collections::HashSet<ChannelId>,
pub failed: std::collections::HashSet<ChannelId>,
pub pending_replicas: std::collections::HashSet<ReplicaId>,
pub synced_replicas: std::collections::HashSet<ReplicaId>,
pub behind_replicas: std::collections::HashSet<ReplicaId>,
pub started_at: u64,
pub keep_list: Vec<u32>,
pub threshold: Option<u32>,
}
impl StateItem {
pub fn kind(&self) -> StateKind {
match self {
StateItem::PendingVerification { .. } => StateKind::PendingVerification,
StateItem::PendingRecovery { .. } => StateKind::PendingRecovery,
StateItem::PendingUnpair { .. } => StateKind::PendingUnpair,
StateItem::PendingReplicaDiscovery { .. } => StateKind::PendingReplicaDiscovery,
StateItem::SharingRound(_) => StateKind::SharingRound,
}
}
pub fn key(&self) -> StateKey {
match self {
StateItem::PendingVerification { channel_id, .. } => StateKey::PendingVerification {
channel_id: *channel_id,
},
StateItem::PendingRecovery {
secret_id, version, ..
} => StateKey::PendingRecovery {
secret_id: *secret_id,
version: *version,
},
StateItem::PendingUnpair { channel_id, .. } => StateKey::PendingUnpair {
channel_id: *channel_id,
},
StateItem::PendingReplicaDiscovery { .. } => StateKey::PendingReplicaDiscovery,
StateItem::SharingRound(round) => StateKey::SharingRound {
version: round.version,
},
}
}
}
#[derive(Debug, Clone)]
pub struct CollectedShare {
pub channel_id: ChannelId,
pub response: derec_proto::GetShareResponseMessage,
}
#[derive(Debug, Clone)]
pub struct Share {
pub secret_id: u64,
pub version: u32,
pub bytes: Vec<u8>,
pub subshares: Option<u32>,
pub threshold: Option<u32>,
}
#[cfg(all(test, feature = "serde"))]
mod channel_record_format_tests {
use super::*;
fn endpoint(uri: &str) -> derec_proto::TransportProtocol {
derec_proto::TransportProtocol {
uri: uri.to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}
}
const LEGACY_HELPER: &str = r#"{
"channel_id": 42,
"transport": { "uri": "https://helper.example/derec", "protocol": 0 },
"peer_role": "Helper",
"status": "Paired",
"created_at": 1700000000
}"#;
#[test]
fn a_pre_0_0_3_helper_record_still_loads() {
let decoded: HelperChannel =
serde_json::from_str(LEGACY_HELPER).expect("a record written before the list shape");
assert_eq!(
decoded.transports.len(),
1,
"the singular `transport` is lifted into a one-element list"
);
assert_eq!(decoded.transports[0].uri, "https://helper.example/derec");
assert_eq!(decoded.channel_id, ChannelId(42));
assert_eq!(decoded.status, ChannelStatus::Paired);
}
#[test]
fn a_pre_0_0_3_replica_record_still_loads() {
let legacy = r#"{
"channel_id": 9,
"replica_id": 3,
"transport": { "uri": "https://member.example/derec", "protocol": 0 },
"role": "Source"
}"#;
let decoded: ReplicaMember = serde_json::from_str(legacy).expect("legacy replica row");
assert_eq!(decoded.transports.len(), 1);
assert_eq!(decoded.transports[0].uri, "https://member.example/derec");
assert_eq!(decoded.replica_id, ReplicaId(3));
}
#[test]
fn a_record_naming_no_endpoint_is_refused() {
let no_endpoint = r#"{ "channel_id": 42, "peer_role": "Helper" }"#;
let err = serde_json::from_str::<HelperChannel>(no_endpoint)
.expect_err("a record with neither spelling must not default to no endpoints");
assert!(
err.to_string().contains("names no transport endpoint"),
"the error has to say what is wrong with the record: {err}"
);
let empty_list = r#"{ "channel_id": 42, "transports": [], "peer_role": "Helper" }"#;
let err = serde_json::from_str::<HelperChannel>(empty_list)
.expect_err("an explicitly empty list is as unreachable as an absent one");
assert!(
err.to_string().contains("empty `transports`"),
"the error has to distinguish empty from absent: {err}"
);
}
#[test]
fn a_record_without_a_weight_reads_as_one() {
let current = r#"{
"schema_version": 3,
"channel_id": 42,
"transports": [{ "uri": "https://helper.example/derec", "protocol": 0 }],
"peer_role": "Helper"
}"#;
let decoded: HelperChannel = serde_json::from_str(current).expect("a v3 record");
assert_eq!(decoded.weight, 1);
let legacy: HelperChannel =
serde_json::from_str(LEGACY_HELPER).expect("a pre-0.0.3 record");
assert_eq!(legacy.weight, 1);
}
#[test]
fn a_stored_weight_of_zero_reads_as_one() {
let zero = r#"{
"schema_version": 3,
"channel_id": 42,
"transports": [{ "uri": "https://helper.example/derec", "protocol": 0 }],
"peer_role": "Helper",
"weight": 0
}"#;
let decoded: HelperChannel = serde_json::from_str(zero).expect("a v3 record");
assert_eq!(decoded.weight, 1);
}
#[test]
fn a_stored_weight_round_trips() {
let record = HelperChannel {
channel_id: ChannelId(42),
transports: vec![endpoint("https://helper.example/derec")],
communication_info: std::collections::HashMap::new(),
peer_role: derec_proto::SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 1_700_000_000,
weight: 3,
};
let json = serde_json::to_string(&record).expect("serializes");
let reloaded: HelperChannel = serde_json::from_str(&json).expect("reloads");
assert_eq!(reloaded.weight, 3);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&json).unwrap()["schema_version"],
serde_json::json!(3)
);
}
#[test]
fn a_newer_schema_version_is_refused() {
let from_the_future = format!(
r#"{{
"schema_version": {},
"channel_id": 42,
"transports": [{{ "uri": "https://helper.example/derec", "protocol": 0 }}],
"peer_role": "Helper"
}}"#,
CHANNEL_RECORD_SCHEMA_VERSION + 1
);
let err = serde_json::from_str::<HelperChannel>(&from_the_future)
.expect_err("a future schema version must be refused, not truncated");
assert!(
err.to_string().contains("understands at most"),
"the error has to name the version gap: {err}"
);
}
#[test]
fn the_list_wins_when_both_spellings_are_present() {
let both = r#"{
"channel_id": 42,
"transport": { "uri": "https://stale.example/derec", "protocol": 0 },
"transports": [
{ "uri": "https://current.example/derec", "protocol": 0 },
{ "uri": "grpcs://current.example:443", "protocol": 1 }
],
"peer_role": "Helper"
}"#;
let decoded: HelperChannel = serde_json::from_str(both).expect("both spellings present");
assert_eq!(decoded.transports.len(), 2, "the list is authoritative");
assert_eq!(decoded.transports[0].uri, "https://current.example/derec");
}
#[test]
fn a_written_record_carries_the_marker_and_only_the_list() {
let record = HelperChannel {
channel_id: ChannelId(42),
transports: vec![endpoint("https://helper.example/derec")],
communication_info: std::collections::HashMap::new(),
peer_role: derec_proto::SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 1_700_000_000,
weight: 1,
};
let json: serde_json::Value =
serde_json::to_value(&record).expect("a channel record serializes");
assert_eq!(
json["schema_version"],
serde_json::json!(CHANNEL_RECORD_SCHEMA_VERSION),
"every record this build writes is stamped"
);
assert!(json["transports"].is_array());
assert!(
json.get("transport").is_none(),
"the pre-0.0.3 spelling is read, never written: {json}"
);
assert_eq!(
serde_json::to_string(&record).expect("serializes"),
r#"{"schema_version":3,"channel_id":42,"transports":[{"uri":"https://helper.example/derec","protocol":0}],"communication_info":{},"peer_role":"Helper","status":"Paired","created_at":1700000000,"weight":1}"#
);
}
#[test]
fn an_upgraded_record_is_stable_once_rewritten() {
let upgraded: HelperChannel =
serde_json::from_str(LEGACY_HELPER).expect("legacy record loads");
let rewritten = serde_json::to_string(&upgraded).expect("serializes");
let reloaded: HelperChannel =
serde_json::from_str(&rewritten).expect("its own output reloads");
assert_eq!(reloaded.transports.len(), upgraded.transports.len());
assert_eq!(reloaded.transports[0].uri, upgraded.transports[0].uri);
assert_eq!(reloaded.channel_id, upgraded.channel_id);
assert_eq!(reloaded.created_at, upgraded.created_at);
assert!(
serde_json::from_str::<serde_json::Value>(&rewritten).unwrap()["schema_version"]
== serde_json::json!(CHANNEL_RECORD_SCHEMA_VERSION),
"the upgrade is persisted, so the next read needs no lifting"
);
}
#[test]
fn the_compatibility_survives_the_channel_record_wrapper() {
let legacy = format!(r#"{{ "Helper": {LEGACY_HELPER} }}"#);
let decoded: ChannelRecord =
serde_json::from_str(&legacy).expect("a legacy record inside its wrapper");
match decoded {
ChannelRecord::Helper(h) => assert_eq!(h.transports.len(), 1),
other => panic!("expected a helper record, got {other:?}"),
}
}
}
#[cfg(all(test, feature = "serde"))]
mod tests {
use super::*;
#[test]
fn secret_value_serde_round_trips_all_variants() {
let cases = [
SecretValue::SharedKey([7u8; 32]),
SecretValue::PairingSecret(PairingKeyMaterial::from_bytes(vec![1, 2, 3, 4, 5])),
SecretValue::PairingContact(ContactMessage {
nonce: 42,
..Default::default()
}),
];
for value in cases {
let json = serde_json::to_vec(&value).expect("serialize");
let decoded: SecretValue = serde_json::from_slice(&json).expect("deserialize");
match (&value, &decoded) {
(SecretValue::SharedKey(a), SecretValue::SharedKey(b)) => assert_eq!(a, b),
(SecretValue::PairingSecret(a), SecretValue::PairingSecret(b)) => {
assert_eq!(a.as_bytes(), b.as_bytes())
}
(SecretValue::PairingContact(a), SecretValue::PairingContact(b)) => {
assert_eq!(a, b)
}
_ => panic!("variant changed across serde round-trip"),
}
}
}
#[test]
fn pairing_key_material_serde_matches_byte_accessors() {
let material = PairingKeyMaterial::from_bytes(vec![9, 8, 7, 6]);
let json = serde_json::to_vec(&material).expect("serialize");
let decoded: PairingKeyMaterial = serde_json::from_slice(&json).expect("deserialize");
assert_eq!(material.as_bytes(), decoded.as_bytes());
}
}
#[cfg(test)]
mod persisted_discriminant_tests {
use super::{SecretKind, StateKind};
#[test]
fn secret_kind_discriminants_are_unchanged() {
assert_eq!(SecretKind::SharedKey as u8, 0);
assert_eq!(SecretKind::PairingSecret as u8, 1);
assert_eq!(SecretKind::PairingContact as u8, 2);
}
#[test]
fn state_kind_discriminants_are_unchanged() {
assert_eq!(StateKind::PendingVerification as u8, 0);
assert_eq!(StateKind::PendingRecovery as u8, 1);
assert_eq!(StateKind::PendingUnpair as u8, 2);
assert_eq!(StateKind::SharingRound as u8, 3);
assert_eq!(StateKind::PendingReplicaDiscovery as u8, 4);
}
}
#[cfg(test)]
mod expired_channel_cleanup_tests {
use super::ExpiredChannelCleanup;
#[test]
fn from_secs_does_not_clamp() {
assert_eq!(
ExpiredChannelCleanup::from_secs(0),
ExpiredChannelCleanup::Enabled { timeout_in_secs: 0 }
);
}
#[test]
fn from_secs_preserves_value() {
assert_eq!(
ExpiredChannelCleanup::from_secs(900),
ExpiredChannelCleanup::Enabled {
timeout_in_secs: 900
}
);
}
#[test]
fn new_disabled_discards_timeout() {
assert_eq!(
ExpiredChannelCleanup::new(false, 900),
ExpiredChannelCleanup::Disabled
);
}
#[test]
fn new_enabled_keeps_timeout() {
assert_eq!(
ExpiredChannelCleanup::new(true, 900),
ExpiredChannelCleanup::Enabled {
timeout_in_secs: 900
}
);
}
#[test]
fn default_matches_historical_behaviour() {
assert_eq!(
ExpiredChannelCleanup::default(),
ExpiredChannelCleanup::Enabled {
timeout_in_secs: 300
}
);
}
}
#[cfg(test)]
mod target_filter_tests {
use super::*;
fn ids(raw: &[u64]) -> Vec<ChannelId> {
raw.iter().copied().map(ChannelId).collect()
}
#[test]
fn all_keeps_every_known_channel_in_store_order() {
let known = ids(&[30, 10, 20]);
assert_eq!(Target::All.filter(&known), known);
}
#[test]
fn single_yields_the_channel_when_it_is_known() {
let known = ids(&[30, 10, 20]);
assert_eq!(Target::Single(ChannelId(10)).filter(&known), ids(&[10]));
}
#[test]
fn single_yields_nothing_when_the_channel_is_unknown() {
let known = ids(&[30, 10, 20]);
assert!(Target::Single(ChannelId(99)).filter(&known).is_empty());
}
#[test]
fn many_keeps_the_callers_order() {
let known = ids(&[30, 10, 20]);
assert_eq!(
Target::Many(ids(&[20, 30])).filter(&known),
ids(&[20, 30]),
"the requested order must survive, not be re-sorted into store order"
);
}
#[test]
fn many_drops_unknown_ids_and_keeps_the_rest() {
let known = ids(&[30, 10, 20]);
assert_eq!(
Target::Many(ids(&[10, 99, 20])).filter(&known),
ids(&[10, 20])
);
}
#[test]
fn a_target_naming_only_unknown_channels_yields_nothing() {
let known = ids(&[30, 10, 20]);
assert!(Target::Many(ids(&[98, 99])).filter(&known).is_empty());
}
#[test]
fn nothing_is_reachable_when_no_channel_is_known() {
assert!(Target::All.filter(&[]).is_empty());
assert!(Target::Single(ChannelId(10)).filter(&[]).is_empty());
assert!(Target::Many(ids(&[10, 20])).filter(&[]).is_empty());
}
#[test]
fn many_does_not_deduplicate_the_request() {
let known = ids(&[10, 20]);
assert_eq!(Target::Many(ids(&[10, 10])).filter(&known), ids(&[10, 10]));
}
}
#[cfg(test)]
mod channel_filter_tests {
use super::*;
use crate::types::ReplicaId;
fn member(
id: u64,
status: ChannelStatus,
role: ReplicaRole,
) -> (ReplicaId, ChannelStatus, ReplicaRole) {
(ReplicaId(id), status, role)
}
#[test]
fn a_default_filter_admits_everything() {
let filter = ReplicaFilter::default();
let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
assert!(filter.matches(&id, status, &role));
}
#[test]
fn ids_restrict_to_the_listed_members() {
let filter = ReplicaFilter {
ids: vec![ReplicaId(1), ReplicaId(2)],
..Default::default()
};
for id in [1, 2] {
let (id, status, role) = member(id, ChannelStatus::Paired, ReplicaRole::Source);
assert!(filter.matches(&id, status, &role));
}
let (id, status, role) = member(3, ChannelStatus::Paired, ReplicaRole::Source);
assert!(!filter.matches(&id, status, &role));
}
#[test]
fn status_is_an_allow_list() {
let filter = ReplicaFilter {
status: vec![ChannelStatus::Paired, ChannelStatus::Unpairing],
..Default::default()
};
for status in [ChannelStatus::Paired, ChannelStatus::Unpairing] {
let (id, status, role) = member(1, status, ReplicaRole::Destination);
assert!(filter.matches(&id, status, &role));
}
let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
assert!(!filter.matches(&id, status, &role));
}
#[test]
fn role_restricts_when_set_and_admits_when_none() {
let filter = ReplicaFilter {
role: Some(ReplicaRole::Destination),
..Default::default()
};
let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Destination);
assert!(filter.matches(&id, status, &role));
let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
assert!(!filter.matches(&id, status, &role));
let any = ReplicaFilter::default();
assert!(any.matches(&id, status, &role));
}
#[test]
fn exclude_omits_the_named_members() {
let filter = ReplicaFilter {
exclude: vec![ReplicaId(7)],
..Default::default()
};
let (id, status, role) = member(7, ChannelStatus::Paired, ReplicaRole::Source);
assert!(!filter.matches(&id, status, &role));
let (id, status, role) = member(8, ChannelStatus::Paired, ReplicaRole::Source);
assert!(filter.matches(&id, status, &role));
}
#[test]
fn exclude_overrides_ids() {
let filter = ReplicaFilter {
ids: vec![ReplicaId(1), ReplicaId(2)],
exclude: vec![ReplicaId(2)],
..Default::default()
};
let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
assert!(filter.matches(&id, status, &role));
let (id, status, role) = member(2, ChannelStatus::Paired, ReplicaRole::Source);
assert!(!filter.matches(&id, status, &role));
}
#[test]
fn restrictions_combine_with_and() {
let filter = ReplicaFilter {
status: vec![ChannelStatus::Paired],
role: Some(ReplicaRole::Destination),
exclude: vec![ReplicaId(9)],
..Default::default()
};
let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Destination);
assert!(filter.matches(&id, status, &role));
let (id, status, role) = member(1, ChannelStatus::Pending, ReplicaRole::Destination);
assert!(!filter.matches(&id, status, &role));
let (id, status, role) = member(1, ChannelStatus::Paired, ReplicaRole::Source);
assert!(!filter.matches(&id, status, &role));
let (id, status, role) = member(9, ChannelStatus::Paired, ReplicaRole::Destination);
assert!(!filter.matches(&id, status, &role));
}
#[test]
fn the_helper_alias_filters_on_sender_kind() {
let filter = HelperFilter {
role: Some(derec_proto::SenderKind::Helper),
..Default::default()
};
assert!(filter.matches(
&ChannelId(1),
ChannelStatus::Paired,
&derec_proto::SenderKind::Helper
));
assert!(!filter.matches(
&ChannelId(1),
ChannelStatus::Paired,
&derec_proto::SenderKind::Owner
));
}
}