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::{StateItemRecord, StateKeyRecord, SyncCheckReport};
#[derive(Debug, Clone)]
pub enum Target {
All,
Single(ChannelId),
Many(Vec<ChannelId>),
}
#[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)
)]
pub struct HelperChannel {
pub channel_id: ChannelId,
pub transport: 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,
}
#[derive(Clone, Debug)]
#[cfg_attr(
any(feature = "serde", target_arch = "wasm32"),
derive(Serialize, Deserialize)
)]
pub struct ReplicaMember {
pub channel_id: ChannelId,
pub replica_id: ReplicaId,
pub transport: 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,
}
#[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)]
#[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 transport(&self) -> &derec_proto::TransportProtocol {
match self {
ChannelRecord::Helper(h) => &h.transport,
ChannelRecord::Replica(r) => &r.transport,
}
}
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 replicas: Option<Replicas>,
}
#[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>,
}
#[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,
PendingRecovery,
PendingUnpair,
SharingRound,
PendingSyncCheck,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateKey {
PendingVerification { channel_id: ChannelId },
PendingRecovery { secret_id: u64, version: u32 },
PendingUnpair { channel_id: ChannelId },
PendingSyncCheck,
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::PendingSyncCheck => StateKind::PendingSyncCheck,
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<derec_proto::GetShareResponseMessage>,
},
PendingUnpair {
channel_id: ChannelId,
started_at: u64,
},
PendingSyncCheck {
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,
}
impl StateItem {
pub fn kind(&self) -> StateKind {
match self {
StateItem::PendingVerification { .. } => StateKind::PendingVerification,
StateItem::PendingRecovery { .. } => StateKind::PendingRecovery,
StateItem::PendingUnpair { .. } => StateKind::PendingUnpair,
StateItem::PendingSyncCheck { .. } => StateKind::PendingSyncCheck,
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::PendingSyncCheck { .. } => StateKey::PendingSyncCheck,
StateItem::SharingRound(round) => StateKey::SharingRound {
version: round.version,
},
}
}
}
#[derive(Debug, Clone)]
pub struct Share {
pub secret_id: u64,
pub version: u32,
pub bytes: Vec<u8>,
}
#[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 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
}
);
}
}