use crate::interop::protocol_names;
use crate::protocol::RecoveryHelper;
use crate::protocol::events::PendingActionKind;
use crate::protocol::types::ReplicaRole;
use crate::protocol::utils::{pending_action_wire, reserved_keys::encode_replica_id};
use crate::protocol::{CorruptionReason, IgnoreReason, NotRestoredReason, VerifyFailureReason};
use crate::protocol::{
DeRecEvent, PendingAction,
types::{ChannelShare, Secret},
};
use derec_proto::TransportProtocol;
use serde::Serialize;
use std::collections::HashMap;
#[derive(Serialize)]
#[serde(tag = "type")]
pub(crate) enum Event {
PairingCompleted {
channel_id: String,
pairing_channel_id: String,
kind: i32,
#[serde(skip_serializing_if = "HashMap::is_empty")]
peer_communication_info: HashMap<String, String>,
},
ReplicaPaired {
channel_id: String,
peer_replica_id: String,
},
ReplicaSecretReceived {
channel_id: String,
from_replica_id: String,
author_replica_id: Option<String>,
secret_id: String,
version: u32,
secret: SecretWire,
shares: Vec<Share>,
},
ReplicaSecretInstalled {
channel_id: String,
from_replica_id: String,
author_replica_id: Option<String>,
secret_id: String,
version: u32,
secret: SecretWire,
shares: Vec<Share>,
},
ReplicaVersionConflict {
channel_id: String,
from_replica_id: String,
secret_id: String,
version: u32,
held_author_replica_id: Option<String>,
incoming_author_replica_id: Option<String>,
secret: SecretWire,
},
ReplicaSecretRefused {
channel_id: String,
from_replica_id: String,
secret_id: String,
version: u32,
status: i32,
memo: String,
},
ReplicaSecretAcked {
channel_id: String,
from_replica_id: String,
secret_id: String,
version: u32,
status: i32,
memo: String,
},
ReplicaSyncRejected {
replica_id: String,
secret_id: String,
version: u32,
status: i32,
memo: String,
},
ReplicaSyncFailed {
replica_id: String,
version: u32,
reason: String,
},
ReplicaRemoved {
replica_id: String,
},
ReplicaSourceChanged {
replica_id: String,
},
SelfRemovedFromGroup {
version: u32,
},
ReplicaDiscoveryComplete {
local_version: u32,
group_version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
fetched_from: Option<String>,
},
ReplicaSyncComplete {
version: u32,
synced: Vec<String>,
behind: Vec<String>,
},
ShareStored {
channel_id: String,
version: u32,
},
ShareRefused {
channel_id: String,
version: u32,
status: i32,
memo: String,
},
ShareConfirmed {
channel_id: String,
version: u32,
},
ShareRejected {
channel_id: String,
version: u32,
status: i32,
memo: String,
},
SharingComplete {
version: u32,
confirmed_count: u32,
failed_count: u32,
threshold_met: bool,
},
ShareVerified {
channel_id: String,
version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
subshares: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
threshold: Option<u32>,
},
ShareVerifyInvalid {
channel_id: String,
version: u32,
},
ShareVerifyRejected {
channel_id: String,
version: u32,
status: i32,
memo: String,
},
SecretsDiscovered {
channel_id: String,
secrets: Vec<DiscoveredSecret>,
},
RecoveryShareReceived {
channel_id: String,
shares_received: u32,
},
RecoveryShareRefused {
channel_id: String,
version: u32,
status: i32,
memo: String,
},
RecoveryShareCorrupted {
channel_id: String,
version: u32,
reason: String,
},
SecretRecovered {
secret: SecretWire,
},
RecoveryConflict {
version: u32,
candidates: Vec<RecoveryCandidateWire>,
disputed_by: Vec<RecoveryHelperWire>,
},
RecoveryDisputed {
version: u32,
secret: SecretWire,
supported_by: Vec<RecoveryHelperWire>,
disputed_by: Vec<RecoveryHelperWire>,
},
RecoveryIncomplete {
secret_id: String,
version: u32,
shares_received: u32,
},
Unpaired {
channel_id: String,
},
UnpairRejected {
channel_id: String,
status: i32,
memo: String,
},
PrePairRejected {
channel_id: String,
status: i32,
memo: String,
},
ChannelInfoUpdated {
channel_id: String,
},
ChannelInfoUpdateRejected {
channel_id: String,
status: i32,
memo: String,
},
ActionRequired {
channel_id: String,
#[serde(with = "serde_bytes")]
action: Vec<u8>,
action_kind: String,
#[serde(skip_serializing_if = "HashMap::is_empty")]
peer_communication_info: HashMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
sender_kind: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
version: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
share_description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
share_secret_id: Option<String>,
trace_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
share_size: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
unpair_memo: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
updated_communication_info: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Vec::is_empty")]
updated_transports: Vec<Endpoint>,
},
AutoAccepted {
channel_id: String,
action_kind: String,
},
RequestFailed {
channel_id: String,
action_kind: String,
responded: bool,
status: i32,
memo: String,
error_code: String,
message: String,
#[serde(skip_serializing_if = "Option::is_none", with = "serde_bytes")]
action: Option<Vec<u8>>,
},
ErrorResponseReceived {
channel_id: String,
status: i32,
memo: String,
},
PairingRefused {
channel_id: String,
status: i32,
memo: String,
error_code: String,
message: String,
},
NoOp,
MessageIgnored {
channel_id: String,
reason: String,
trace_id: String,
},
PeerNotRestored {
channel_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
replica_id: Option<String>,
reason: String,
},
PairingStarted {
channel_id: String,
kind: i32,
trace_id: String,
},
DiscoveryStarted {
channel_id: String,
trace_id: String,
},
DiscoveryFailed {
channel_id: String,
error: String,
},
ProtectSecretStarted {
channel_id: String,
version: u32,
trace_id: String,
weight: u32,
},
ProtectSecretFailed {
channel_id: String,
version: u32,
error: String,
weight: u32,
},
VerifySharesStarted {
channel_id: String,
version: u32,
trace_id: String,
},
VerifySharesFailed {
channel_id: String,
version: u32,
reason: String,
error: String,
},
RecoverSecretStarted {
channel_id: String,
version: u32,
trace_id: String,
},
RecoverSecretFailed {
channel_id: String,
version: u32,
error: String,
},
UnpairFailed {
channel_id: String,
error: String,
},
UnpairStarted {
channel_id: String,
trace_id: String,
},
UpdateChannelInfoStarted {
channel_id: String,
trace_id: String,
},
UpdateChannelInfoFailed {
channel_id: String,
error: String,
},
}
#[derive(Serialize)]
pub struct DiscoveredSecret {
pub secret_id: String,
pub versions: Vec<DiscoveredVersion>,
}
#[derive(Serialize)]
pub struct DiscoveredVersion {
pub version: u32,
pub description: String,
}
#[derive(Serialize)]
pub struct RecoveryCandidateWire {
pub secret: SecretWire,
pub supported_by: Vec<RecoveryHelperWire>,
}
#[derive(Serialize)]
pub struct RecoveryHelperWire {
pub channel_id: String,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub communication_info: HashMap<String, String>,
}
impl From<RecoveryHelper> for RecoveryHelperWire {
fn from(h: RecoveryHelper) -> Self {
Self {
channel_id: h.channel_id.0.to_string(),
communication_info: h.communication_info,
}
}
}
fn helpers_wire(helpers: Vec<RecoveryHelper>) -> Vec<RecoveryHelperWire> {
helpers.into_iter().map(Into::into).collect()
}
#[derive(Serialize)]
pub struct SecretWire {
pub helpers: Vec<Helper>,
pub secrets: Vec<UserSecret>,
#[serde(skip_serializing_if = "Option::is_none")]
pub replicas: Option<ReplicasWire>,
#[serde(skip_serializing_if = "Option::is_none")]
pub threshold: Option<u32>,
}
#[derive(Serialize)]
pub struct ReplicasWire {
pub channel_id: String,
pub members: Vec<Replica>,
#[serde(with = "serde_bytes")]
pub shared_key: Vec<u8>,
}
#[derive(Serialize)]
pub struct Endpoint {
pub uri: String,
pub protocol: &'static str,
}
impl From<TransportProtocol> for Endpoint {
fn from(t: TransportProtocol) -> Self {
Endpoint {
uri: t.uri,
protocol: protocol_names::protocol_discriminant_to_name(t.protocol)
.unwrap_or("unknown"),
}
}
}
#[derive(Serialize)]
pub struct Helper {
pub channel_id: String,
pub transports: Vec<Endpoint>,
#[serde(with = "serde_bytes")]
pub shared_key: Vec<u8>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub communication_info: HashMap<String, String>,
pub weight: u32,
}
#[derive(Serialize)]
pub struct Replica {
pub replica_id: String,
pub transports: Vec<Endpoint>,
pub role: String,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub communication_info: HashMap<String, String>,
}
#[derive(Serialize)]
pub struct UserSecret {
#[serde(with = "serde_bytes")]
pub id: Vec<u8>,
pub name: String,
#[serde(with = "serde_bytes")]
pub data: Vec<u8>,
}
#[derive(Serialize)]
pub struct Share {
pub channel_id: String,
#[serde(with = "serde_bytes")]
pub committed_share: Vec<u8>,
}
impl From<Secret> for SecretWire {
fn from(v: Secret) -> Self {
Self {
helpers: v
.helpers
.into_iter()
.map(|h| Helper {
weight: h.effective_weight(),
channel_id: h.channel_id.to_string(),
transports: h.transports.into_iter().map(Into::into).collect(),
shared_key: h.shared_key,
communication_info: h.communication_info,
})
.collect(),
secrets: v
.secrets
.into_iter()
.map(|s| UserSecret {
id: s.id,
name: s.name,
data: s.data,
})
.collect(),
replicas: v.replicas.map(|g| ReplicasWire {
channel_id: g.channel_id.to_string(),
members: g
.members
.into_iter()
.map(|r| Replica {
replica_id: encode_replica_id(r.replica_id),
transports: r.transports.into_iter().map(Into::into).collect(),
role: ReplicaRole::from_i32(r.role)
.map(|role| format!("{role:?}"))
.unwrap_or_default(),
communication_info: r.communication_info,
})
.collect(),
shared_key: g.shared_key,
}),
threshold: v.threshold,
}
}
}
impl From<ChannelShare> for Share {
fn from(v: ChannelShare) -> Self {
Self {
channel_id: v.channel_id.to_string(),
committed_share: v.committed_share,
}
}
}
impl Event {
pub fn from_event(event: DeRecEvent) -> Result<Self, String> {
Ok(match event {
DeRecEvent::PairingCompleted {
channel_id,
pairing_channel_id,
kind,
peer_communication_info,
} => Self::PairingCompleted {
channel_id: channel_id.0.to_string(),
pairing_channel_id: pairing_channel_id.0.to_string(),
kind: kind as i32,
peer_communication_info,
},
DeRecEvent::ReplicaPaired {
channel_id,
peer_replica_id,
} => Self::ReplicaPaired {
channel_id: channel_id.0.to_string(),
peer_replica_id: encode_replica_id(peer_replica_id),
},
DeRecEvent::ReplicaSecretReceived {
channel_id,
from_replica_id,
author_replica_id,
secret_id,
version,
secret,
shares,
} => Self::ReplicaSecretReceived {
channel_id: channel_id.0.to_string(),
from_replica_id: encode_replica_id(from_replica_id),
author_replica_id: author_replica_id.map(encode_replica_id),
secret_id: secret_id.to_string(),
version,
secret: secret.into(),
shares: shares.into_iter().map(Into::into).collect(),
},
DeRecEvent::ReplicaSecretInstalled {
channel_id,
from_replica_id,
author_replica_id,
secret_id,
version,
secret,
shares,
} => Self::ReplicaSecretInstalled {
channel_id: channel_id.0.to_string(),
from_replica_id: encode_replica_id(from_replica_id),
author_replica_id: author_replica_id.map(encode_replica_id),
secret_id: secret_id.to_string(),
version,
secret: secret.into(),
shares: shares.into_iter().map(Into::into).collect(),
},
DeRecEvent::ReplicaVersionConflict {
channel_id,
from_replica_id,
secret_id,
version,
held_author_replica_id,
incoming_author_replica_id,
secret,
} => Self::ReplicaVersionConflict {
channel_id: channel_id.0.to_string(),
from_replica_id: encode_replica_id(from_replica_id),
secret_id: secret_id.to_string(),
version,
held_author_replica_id: held_author_replica_id.map(encode_replica_id),
incoming_author_replica_id: incoming_author_replica_id.map(encode_replica_id),
secret: secret.into(),
},
DeRecEvent::ReplicaSecretRefused {
channel_id,
from_replica_id,
secret_id,
version,
status,
memo,
} => Self::ReplicaSecretRefused {
channel_id: channel_id.0.to_string(),
from_replica_id: encode_replica_id(from_replica_id),
secret_id: secret_id.to_string(),
version,
status,
memo,
},
DeRecEvent::ReplicaSyncRejected {
replica_id,
secret_id,
version,
status,
memo,
} => Self::ReplicaSyncRejected {
replica_id: encode_replica_id(replica_id),
secret_id: secret_id.to_string(),
version,
status,
memo,
},
DeRecEvent::ReplicaSyncFailed {
replica_id,
version,
reason,
} => Self::ReplicaSyncFailed {
replica_id: encode_replica_id(replica_id),
version,
reason,
},
DeRecEvent::ReplicaRemoved { replica_id } => Self::ReplicaRemoved {
replica_id: encode_replica_id(replica_id),
},
DeRecEvent::ReplicaSourceChanged { replica_id } => Self::ReplicaSourceChanged {
replica_id: encode_replica_id(replica_id),
},
DeRecEvent::SelfRemovedFromGroup { version } => Self::SelfRemovedFromGroup { version },
DeRecEvent::ReplicaDiscoveryComplete {
local_version,
group_version,
fetched_from,
} => Self::ReplicaDiscoveryComplete {
local_version,
group_version,
fetched_from: fetched_from.map(encode_replica_id),
},
DeRecEvent::ReplicaSyncComplete {
version,
synced,
behind,
} => Self::ReplicaSyncComplete {
version,
synced: synced.into_iter().map(encode_replica_id).collect(),
behind: behind.into_iter().map(encode_replica_id).collect(),
},
DeRecEvent::ReplicaSecretAcked {
channel_id,
from_replica_id,
secret_id,
version,
status,
memo,
} => Self::ReplicaSecretAcked {
channel_id: channel_id.0.to_string(),
from_replica_id: encode_replica_id(from_replica_id),
secret_id: secret_id.to_string(),
version,
status,
memo,
},
DeRecEvent::ShareStored {
channel_id,
version,
} => Self::ShareStored {
channel_id: channel_id.0.to_string(),
version,
},
DeRecEvent::ShareRefused {
channel_id,
version,
status,
memo,
} => Self::ShareRefused {
channel_id: channel_id.0.to_string(),
version,
status,
memo,
},
DeRecEvent::ShareConfirmed {
channel_id,
version,
} => Self::ShareConfirmed {
channel_id: channel_id.0.to_string(),
version,
},
DeRecEvent::ShareRejected {
channel_id,
version,
status,
memo,
} => Self::ShareRejected {
channel_id: channel_id.0.to_string(),
version,
status,
memo,
},
DeRecEvent::SharingComplete {
version,
confirmed_count,
failed_count,
threshold_met,
} => Self::SharingComplete {
version,
confirmed_count: confirmed_count as u32,
failed_count: failed_count as u32,
threshold_met,
},
DeRecEvent::ShareVerified {
channel_id,
version,
subshares,
threshold,
} => Self::ShareVerified {
channel_id: channel_id.0.to_string(),
version,
subshares,
threshold,
},
DeRecEvent::ShareVerifyInvalid {
channel_id,
version,
} => Self::ShareVerifyInvalid {
channel_id: channel_id.0.to_string(),
version,
},
DeRecEvent::ShareVerifyRejected {
channel_id,
version,
status,
memo,
} => Self::ShareVerifyRejected {
channel_id: channel_id.0.to_string(),
version,
status,
memo,
},
DeRecEvent::SecretsDiscovered {
channel_id,
secrets,
} => Self::SecretsDiscovered {
channel_id: channel_id.0.to_string(),
secrets: secrets
.into_iter()
.map(|s| DiscoveredSecret {
secret_id: s.secret_id.to_string(),
versions: s
.versions
.into_iter()
.map(|v| DiscoveredVersion {
version: v.version,
description: v.description,
})
.collect(),
})
.collect(),
},
DeRecEvent::RecoveryShareReceived {
channel_id,
shares_received,
} => Self::RecoveryShareReceived {
channel_id: channel_id.0.to_string(),
shares_received: shares_received as u32,
},
DeRecEvent::RecoveryShareRefused {
channel_id,
version,
status,
memo,
} => Self::RecoveryShareRefused {
channel_id: channel_id.0.to_string(),
version,
status,
memo,
},
DeRecEvent::RecoveryShareCorrupted {
channel_id,
version,
reason,
} => Self::RecoveryShareCorrupted {
channel_id: channel_id.0.to_string(),
version,
reason: corruption_reason_label(reason).to_owned(),
},
DeRecEvent::SecretRecovered { secret } => Self::SecretRecovered {
secret: secret.into(),
},
DeRecEvent::RecoveryConflict {
version,
candidates,
disputed_by,
} => Self::RecoveryConflict {
version,
candidates: candidates
.into_iter()
.map(|c| RecoveryCandidateWire {
secret: c.secret.into(),
supported_by: helpers_wire(c.supported_by),
})
.collect(),
disputed_by: helpers_wire(disputed_by),
},
DeRecEvent::RecoveryDisputed {
version,
secret,
supported_by,
disputed_by,
} => Self::RecoveryDisputed {
version,
secret: secret.into(),
supported_by: helpers_wire(supported_by),
disputed_by: helpers_wire(disputed_by),
},
DeRecEvent::RecoveryIncomplete {
secret_id,
version,
shares_received,
} => Self::RecoveryIncomplete {
secret_id: secret_id.to_string(),
version,
shares_received: shares_received as u32,
},
DeRecEvent::Unpaired { channel_id } => Self::Unpaired {
channel_id: channel_id.0.to_string(),
},
DeRecEvent::UnpairRejected {
channel_id,
status,
memo,
} => Self::UnpairRejected {
channel_id: channel_id.0.to_string(),
status,
memo,
},
DeRecEvent::PrePairRejected {
channel_id,
status,
memo,
} => Self::PrePairRejected {
channel_id: channel_id.0.to_string(),
status,
memo,
},
DeRecEvent::ChannelInfoUpdated { channel_id } => Self::ChannelInfoUpdated {
channel_id: channel_id.0.to_string(),
},
DeRecEvent::ChannelInfoUpdateRejected {
channel_id,
status,
memo,
} => Self::ChannelInfoUpdateRejected {
channel_id: channel_id.0.to_string(),
status,
memo,
},
DeRecEvent::AutoAccepted {
channel_id,
action_kind,
} => Self::AutoAccepted {
channel_id: channel_id.0.to_string(),
action_kind: pending_action_kind_label(action_kind).to_owned(),
},
DeRecEvent::ActionRequired { channel_id, action } => {
let action_kind = action_kind_label(&action).to_owned();
let peer_communication_info = extract_peer_communication_info(&action);
let sender_kind = extract_pairing_sender_kind(&action);
let (version, share_description, share_secret_id) = extract_share_metadata(&action);
let trace_id = action.trace_id().to_string();
let share_size = match &action {
PendingAction::StoreShare { request, .. } => Some(request.share.len() as u64),
_ => None,
};
let unpair_memo = match &action {
PendingAction::Unpair { request, .. } => Some(request.memo.clone()),
_ => None,
};
let (updated_communication_info, updated_transports) = match &action {
PendingAction::UpdateChannelInfo { request, .. } => (
request.communication_info.as_ref().map(|info| {
use crate::extensions::communication_info::CommunicationInfoExt as _;
info.to_map()
}),
request
.supported_transports
.iter()
.cloned()
.map(Into::into)
.collect(),
),
_ => (None, Vec::new()),
};
let action_bytes = pending_action_wire::serialize(action)?;
Self::ActionRequired {
channel_id: channel_id.0.to_string(),
action: action_bytes,
action_kind,
peer_communication_info,
sender_kind,
version,
share_description,
share_secret_id,
trace_id,
share_size,
unpair_memo,
updated_communication_info,
updated_transports,
}
}
DeRecEvent::RequestFailed {
channel_id,
action_kind,
responded,
status,
memo,
error_code,
message,
action,
} => Self::RequestFailed {
channel_id: channel_id.0.to_string(),
action_kind: pending_action_kind_label(action_kind).to_owned(),
responded,
status,
memo,
error_code,
message,
action: action.map(pending_action_wire::serialize).transpose()?,
},
DeRecEvent::ErrorResponseReceived {
channel_id,
status,
memo,
} => Self::ErrorResponseReceived {
channel_id: channel_id.0.to_string(),
status,
memo,
},
DeRecEvent::PairingRefused {
channel_id,
status,
memo,
error_code,
message,
} => Self::PairingRefused {
channel_id: channel_id.0.to_string(),
status,
memo,
error_code,
message,
},
DeRecEvent::NoOp => Self::NoOp,
DeRecEvent::MessageIgnored {
channel_id,
reason,
trace_id,
} => Self::MessageIgnored {
channel_id: channel_id.0.to_string(),
reason: ignore_reason_label(reason).to_owned(),
trace_id: trace_id.to_string(),
},
DeRecEvent::PeerNotRestored {
channel_id,
replica_id,
reason,
} => Self::PeerNotRestored {
channel_id: channel_id.0.to_string(),
replica_id: replica_id.map(encode_replica_id),
reason: not_restored_reason_label(reason).to_owned(),
},
DeRecEvent::PairingStarted {
channel_id,
kind,
trace_id,
} => Self::PairingStarted {
channel_id: channel_id.0.to_string(),
kind: kind as i32,
trace_id: trace_id.to_string(),
},
DeRecEvent::DiscoveryStarted {
channel_id,
trace_id,
} => Self::DiscoveryStarted {
channel_id: channel_id.0.to_string(),
trace_id: trace_id.to_string(),
},
DeRecEvent::DiscoveryFailed { channel_id, error } => Self::DiscoveryFailed {
channel_id: channel_id.0.to_string(),
error,
},
DeRecEvent::ProtectSecretStarted {
channel_id,
version,
trace_id,
weight,
} => Self::ProtectSecretStarted {
channel_id: channel_id.0.to_string(),
version,
trace_id: trace_id.to_string(),
weight,
},
DeRecEvent::ProtectSecretFailed {
channel_id,
version,
error,
weight,
} => Self::ProtectSecretFailed {
channel_id: channel_id.0.to_string(),
version,
error,
weight,
},
DeRecEvent::VerifySharesStarted {
channel_id,
version,
trace_id,
} => Self::VerifySharesStarted {
channel_id: channel_id.0.to_string(),
version,
trace_id: trace_id.to_string(),
},
DeRecEvent::VerifySharesFailed {
channel_id,
version,
reason,
error,
} => Self::VerifySharesFailed {
channel_id: channel_id.0.to_string(),
version,
reason: verify_failure_reason_label(reason).to_owned(),
error,
},
DeRecEvent::RecoverSecretStarted {
channel_id,
version,
trace_id,
} => Self::RecoverSecretStarted {
channel_id: channel_id.0.to_string(),
version,
trace_id: trace_id.to_string(),
},
DeRecEvent::RecoverSecretFailed {
channel_id,
version,
error,
} => Self::RecoverSecretFailed {
channel_id: channel_id.0.to_string(),
version,
error,
},
DeRecEvent::UnpairStarted {
channel_id,
trace_id,
} => Self::UnpairStarted {
channel_id: channel_id.0.to_string(),
trace_id: trace_id.to_string(),
},
DeRecEvent::UnpairFailed { channel_id, error } => Self::UnpairFailed {
channel_id: channel_id.0.to_string(),
error,
},
DeRecEvent::UpdateChannelInfoStarted {
channel_id,
trace_id,
} => Self::UpdateChannelInfoStarted {
channel_id: channel_id.0.to_string(),
trace_id: trace_id.to_string(),
},
DeRecEvent::UpdateChannelInfoFailed { channel_id, error } => {
Self::UpdateChannelInfoFailed {
channel_id: channel_id.0.to_string(),
error,
}
}
#[allow(unreachable_patterns)]
_ => Self::NoOp,
})
}
}
pub(crate) fn ignore_reason_label(reason: IgnoreReason) -> &'static str {
match reason {
IgnoreReason::PendingVerification => "PendingVerification",
IgnoreReason::Expired => "Expired",
IgnoreReason::TimestampMismatch => "TimestampMismatch",
IgnoreReason::StaleResponse => "StaleResponse",
IgnoreReason::Superseded => "Superseded",
IgnoreReason::ProtocolVersionTooOld => "ProtocolVersionTooOld",
IgnoreReason::ProtocolVersionMismatch => "ProtocolVersionMismatch",
}
}
pub(crate) fn verify_failure_reason_label(reason: VerifyFailureReason) -> &'static str {
match reason {
VerifyFailureReason::NoSharedKey => "NoSharedKey",
VerifyFailureReason::NoProof => "NoProof",
VerifyFailureReason::DispatchFailed => "DispatchFailed",
}
}
pub(crate) fn not_restored_reason_label(reason: NotRestoredReason) -> &'static str {
match reason {
NotRestoredReason::NoTransports => "NoTransports",
}
}
pub(crate) fn corruption_reason_label(reason: CorruptionReason) -> &'static str {
match reason {
CorruptionReason::Malformed => "Malformed",
CorruptionReason::InvalidProof => "InvalidProof",
CorruptionReason::Forged => "Forged",
}
}
pub(crate) fn pending_action_kind_label(kind: PendingActionKind) -> &'static str {
use crate::protocol::events::PendingActionKind as K;
match kind {
K::Pairing => "Pairing",
K::PrePair => "PrePair",
K::StoreShare => "StoreShare",
K::VerifyShare => "VerifyShare",
K::Discovery => "Discovery",
K::GetShare => "GetShare",
K::Unpair => "Unpair",
K::UpdateChannelInfo => "UpdateChannelInfo",
K::Failed => "Failed",
}
}
fn action_kind_label(action: &PendingAction) -> &'static str {
pending_action_kind_label(action.kind())
}
fn extract_peer_communication_info(action: &PendingAction) -> HashMap<String, String> {
match action {
PendingAction::Pairing {
peer_communication_info,
..
} => peer_communication_info.clone(),
_ => HashMap::new(),
}
}
fn extract_pairing_sender_kind(action: &PendingAction) -> Option<i32> {
match action {
PendingAction::Pairing { request, .. } => Some(request.sender_kind),
_ => None,
}
}
fn extract_share_metadata(action: &PendingAction) -> (Option<u32>, Option<String>, Option<String>) {
match action {
PendingAction::StoreShare { request, .. } => {
let desc = if request.version_description.is_empty() {
None
} else {
Some(request.version_description.clone())
};
(
Some(request.version),
desc,
Some(request.secret_id.to_string()),
)
}
PendingAction::VerifyShare { request, .. } => (
Some(request.version),
None,
Some(request.secret_id.to_string()),
),
PendingAction::GetShare { request, .. } => (
Some(request.version),
None,
Some(request.secret_id.to_string()),
),
_ => (None, None, None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::FailedRequest;
use crate::protocol::ReplyTarget;
use crate::protocol::types::HelperInfo;
use crate::types::ChannelId;
use derec_proto::CommunicationInfo;
use derec_proto::GetShareRequestMessage;
use derec_proto::Protocol;
use derec_proto::StatusEnum;
use derec_proto::StoreShareRequestMessage;
use derec_proto::UnpairRequestMessage;
use derec_proto::UpdateChannelInfoRequestMessage;
fn action_required(action: PendingAction) -> serde_json::Value {
let mapped = Event::from_event(DeRecEvent::ActionRequired {
channel_id: ChannelId(7),
action,
})
.expect("ActionRequired maps");
serde_json::to_value(&mapped).expect("serializes")
}
#[test]
fn a_store_share_action_reports_its_size_and_trace_id() {
let json = action_required(PendingAction::StoreShare {
channel_id: ChannelId(7),
request: StoreShareRequestMessage {
share: vec![0xAB; 1234],
version: 3,
secret_id: 42,
..Default::default()
},
shared_key: [0; 32],
trace_id: u64::MAX,
});
assert_eq!(json["share_size"], 1234);
assert_eq!(json["version"], 3);
assert_eq!(json["share_secret_id"], "42");
assert_eq!(json["trace_id"], u64::MAX.to_string());
}
#[test]
fn a_get_share_action_names_the_share_asked_for() {
let json = action_required(PendingAction::GetShare {
channel_id: ChannelId(7),
request: GetShareRequestMessage {
secret_id: 42,
version: 5,
..Default::default()
},
shared_key: [0; 32],
trace_id: 9,
});
assert_eq!(json["share_secret_id"], "42");
assert_eq!(json["version"], 5);
assert!(json.get("share_size").is_none());
}
#[test]
fn a_recovered_helper_carries_its_weight() {
let helper = |channel_id, weight| HelperInfo {
channel_id,
transports: Vec::new(),
shared_key: vec![0; 32],
communication_info: HashMap::new(),
weight,
};
let wire = SecretWire::from(Secret {
helpers: vec![helper(1, 3), helper(2, 0)],
secrets: Vec::new(),
replicas: None,
threshold: None,
});
let json = serde_json::to_value(&wire).expect("serializes");
assert_eq!(json["helpers"][0]["weight"], 3);
assert_eq!(json["helpers"][1]["weight"], 1);
}
#[test]
fn share_verified_carries_its_subshares() {
let verified = |subshares| {
serde_json::to_string(
&Event::from_event(DeRecEvent::ShareVerified {
channel_id: ChannelId(11),
version: 2,
subshares,
threshold: None,
})
.expect("converts"),
)
.expect("serializes")
};
assert_eq!(
verified(Some(3)),
r#"{"type":"ShareVerified","channel_id":"11","version":2,"subshares":3}"#
);
assert_eq!(
verified(None),
r#"{"type":"ShareVerified","channel_id":"11","version":2}"#
);
}
#[test]
fn share_verified_carries_its_threshold() {
let verified = |threshold| {
serde_json::to_string(
&Event::from_event(DeRecEvent::ShareVerified {
channel_id: ChannelId(11),
version: 2,
subshares: Some(1),
threshold,
})
.expect("converts"),
)
.expect("serializes")
};
assert_eq!(
verified(Some(3)),
r#"{"type":"ShareVerified","channel_id":"11","version":2,"subshares":1,"threshold":3}"#
);
assert_eq!(
verified(None),
r#"{"type":"ShareVerified","channel_id":"11","version":2,"subshares":1}"#
);
}
#[test]
fn a_recovered_secret_carries_its_threshold() {
let wire = |threshold| {
serde_json::to_value(SecretWire::from(Secret {
helpers: Vec::new(),
secrets: Vec::new(),
replicas: None,
threshold,
}))
.expect("serializes")
};
assert_eq!(wire(Some(3))["threshold"], 3);
assert!(wire(None).get("threshold").is_none());
}
#[test]
fn an_unpair_action_carries_the_peer_memo() {
let json = action_required(PendingAction::Unpair {
channel_id: ChannelId(7),
request: UnpairRequestMessage {
memo: "moving devices".to_owned(),
..Default::default()
},
shared_key: [0; 32],
trace_id: 9,
});
assert_eq!(json["unpair_memo"], "moving devices");
}
#[test]
fn an_update_channel_info_action_shows_what_would_change() {
use crate::extensions::communication_info::CommunicationInfoExt as _;
let json = action_required(PendingAction::UpdateChannelInfo {
channel_id: ChannelId(7),
request: UpdateChannelInfoRequestMessage {
communication_info: Some(CommunicationInfo::from_map(&HashMap::from([(
"name".to_owned(),
"Alice".to_owned(),
)]))),
supported_transports: vec![TransportProtocol {
uri: "grpcs://alice.example:443".to_owned(),
protocol: Protocol::Grpc as i32,
}],
..Default::default()
},
shared_key: [0; 32],
trace_id: 9,
});
assert_eq!(json["updated_communication_info"]["name"], "Alice");
assert_eq!(
json["updated_transports"][0]["uri"],
"grpcs://alice.example:443"
);
assert_eq!(json["updated_transports"][0]["protocol"], "grpc");
let json = action_required(PendingAction::UpdateChannelInfo {
channel_id: ChannelId(7),
request: UpdateChannelInfoRequestMessage {
supported_transports: vec![TransportProtocol {
uri: "https://alice.example".to_owned(),
protocol: Protocol::Https as i32,
}],
..Default::default()
},
shared_key: [0; 32],
trace_id: 9,
});
assert!(json.get("updated_communication_info").is_none());
}
#[test]
fn unpair_failed_maps_to_the_wire_instead_of_degrading_to_noop() {
let mapped = Event::from_event(DeRecEvent::UnpairFailed {
channel_id: ChannelId(99),
error: "transport unreachable".to_owned(),
})
.expect("UnpairFailed must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "UnpairFailed");
assert_eq!(json["channel_id"], "99");
assert_eq!(json["error"], "transport unreachable");
}
#[test]
fn share_verify_rejected_maps_status_and_memo() {
let mapped = Event::from_event(DeRecEvent::ShareVerifyRejected {
channel_id: ChannelId(u64::MAX),
version: 3,
status: StatusEnum::UnknownShareVersion as i32,
memo: "no stored share".to_owned(),
})
.expect("ShareVerifyRejected must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "ShareVerifyRejected");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 3);
assert_eq!(json["status"], StatusEnum::UnknownShareVersion as i32);
assert_eq!(json["memo"], "no stored share");
}
#[test]
fn share_verify_invalid_maps_channel_and_version() {
let mapped = Event::from_event(DeRecEvent::ShareVerifyInvalid {
channel_id: ChannelId(u64::MAX),
version: 3,
})
.expect("ShareVerifyInvalid must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "ShareVerifyInvalid");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 3);
}
#[test]
fn verify_shares_failed_maps_reason_and_error() {
for (reason, label) in [
(VerifyFailureReason::NoSharedKey, "NoSharedKey"),
(VerifyFailureReason::NoProof, "NoProof"),
(VerifyFailureReason::DispatchFailed, "DispatchFailed"),
] {
let mapped = Event::from_event(DeRecEvent::VerifySharesFailed {
channel_id: ChannelId(u64::MAX),
version: 5,
reason,
error: "cause".to_owned(),
})
.expect("VerifySharesFailed must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "VerifySharesFailed");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 5);
assert_eq!(json["reason"], label);
assert_eq!(json["error"], "cause");
}
}
#[test]
fn message_ignored_maps_stale_response() {
let mapped = Event::from_event(DeRecEvent::MessageIgnored {
channel_id: ChannelId(7),
reason: IgnoreReason::StaleResponse,
trace_id: 1,
})
.expect("MessageIgnored must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["reason"], "StaleResponse");
}
#[test]
fn share_refused_maps_status_and_memo() {
let mapped = Event::from_event(DeRecEvent::ShareRefused {
channel_id: ChannelId(u64::MAX),
version: 6,
status: StatusEnum::VerificationFailed as i32,
memo: "bad merkle path".to_owned(),
})
.expect("ShareRefused must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "ShareRefused");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 6);
assert_eq!(json["status"], StatusEnum::VerificationFailed as i32);
assert_eq!(json["memo"], "bad merkle path");
}
#[test]
fn replica_secret_refused_maps_status_and_memo() {
let mapped = Event::from_event(DeRecEvent::ReplicaSecretRefused {
channel_id: ChannelId(u64::MAX),
from_replica_id: 7,
secret_id: u64::MAX,
version: 3,
status: StatusEnum::VerificationFailed as i32,
memo: "bad merkle path".to_owned(),
})
.expect("ReplicaSecretRefused must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "ReplicaSecretRefused");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["from_replica_id"], "7");
assert_eq!(json["secret_id"], u64::MAX.to_string());
assert_eq!(json["version"], 3);
assert_eq!(json["status"], StatusEnum::VerificationFailed as i32);
assert_eq!(json["memo"], "bad merkle path");
}
#[test]
fn recovery_share_refused_maps_status_and_memo() {
let mapped = Event::from_event(DeRecEvent::RecoveryShareRefused {
channel_id: ChannelId(u64::MAX),
version: 4,
status: StatusEnum::UnknownShareVersion as i32,
memo: "no stored share".to_owned(),
})
.expect("RecoveryShareRefused must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "RecoveryShareRefused");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 4);
assert_eq!(json["status"], StatusEnum::UnknownShareVersion as i32);
assert_eq!(json["memo"], "no stored share");
}
#[test]
fn recovery_share_corrupted_maps_channel_version_and_reason() {
for (reason, label) in [
(CorruptionReason::Malformed, "Malformed"),
(CorruptionReason::InvalidProof, "InvalidProof"),
(CorruptionReason::Forged, "Forged"),
] {
let mapped = Event::from_event(DeRecEvent::RecoveryShareCorrupted {
channel_id: ChannelId(u64::MAX),
version: 4,
reason,
})
.expect("RecoveryShareCorrupted must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "RecoveryShareCorrupted");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["version"], 4);
assert_eq!(json["reason"], label);
}
}
#[test]
fn message_ignored_maps_with_channel_reason_and_trace() {
let mapped = Event::from_event(DeRecEvent::MessageIgnored {
channel_id: ChannelId(u64::MAX),
reason: IgnoreReason::PendingVerification,
trace_id: 42,
})
.expect("MessageIgnored must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "MessageIgnored");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["reason"], "PendingVerification");
assert_eq!(json["trace_id"], "42");
}
#[test]
fn peer_not_restored_maps_helper_and_member_entries() {
let helper = serde_json::to_value(
Event::from_event(DeRecEvent::PeerNotRestored {
channel_id: ChannelId(u64::MAX),
replica_id: None,
reason: NotRestoredReason::NoTransports,
})
.expect("PeerNotRestored must map"),
)
.expect("serializes");
assert_eq!(helper["type"], "PeerNotRestored");
assert_eq!(helper["channel_id"], u64::MAX.to_string());
assert!(!helper.as_object().unwrap().contains_key("replica_id"));
assert_eq!(helper["reason"], "NoTransports");
let member = serde_json::to_value(
Event::from_event(DeRecEvent::PeerNotRestored {
channel_id: ChannelId(21),
replica_id: Some(u64::MAX),
reason: NotRestoredReason::NoTransports,
})
.expect("PeerNotRestored must map"),
)
.expect("serializes");
assert_eq!(member["channel_id"], "21");
assert_eq!(member["replica_id"], u64::MAX.to_string());
assert_eq!(member["reason"], "NoTransports");
}
#[test]
fn request_failed_carries_its_token_when_unanswered() {
let action = PendingAction::RespondToFailure {
channel_id: ChannelId(u64::MAX),
trace_id: 9,
reply: ReplyTarget {
channel_id: ChannelId(u64::MAX),
endpoints: Vec::new(),
},
request: FailedRequest::Undecodable,
};
let expected_bytes = pending_action_wire::serialize(action.clone()).expect("serializes");
let mapped = Event::from_event(DeRecEvent::RequestFailed {
channel_id: ChannelId(u64::MAX),
action_kind: PendingActionKind::StoreShare,
responded: false,
status: StatusEnum::Fail as i32,
memo: "request could not be processed".to_owned(),
error_code: "store".to_owned(),
message: "backend unavailable".to_owned(),
action: Some(action),
})
.expect("RequestFailed must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "RequestFailed");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["action_kind"], "StoreShare");
assert_eq!(json["responded"], false);
assert_eq!(json["status"], StatusEnum::Fail as i32);
assert_eq!(json["memo"], "request could not be processed");
assert_eq!(json["error_code"], "store");
assert_eq!(json["message"], "backend unavailable");
assert_eq!(json["action"], serde_json::json!(expected_bytes));
}
#[test]
fn request_failed_omits_the_token_and_keeps_the_status_when_answered() {
let mapped = Event::from_event(DeRecEvent::RequestFailed {
channel_id: ChannelId(4),
action_kind: PendingActionKind::Failed,
responded: true,
status: StatusEnum::FormatError as i32,
memo: "message body could not be decoded".to_owned(),
error_code: "internal".to_owned(),
message: "cause".to_owned(),
action: None,
})
.expect("RequestFailed must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["action_kind"], "Failed");
assert_eq!(json["responded"], true);
let object = json.as_object().expect("object");
assert!(!object.contains_key("action"));
assert_eq!(json["status"], StatusEnum::FormatError as i32);
assert_eq!(json["memo"], "message body could not be decoded");
}
#[test]
fn error_response_received_maps_status_and_memo() {
let mapped = Event::from_event(DeRecEvent::ErrorResponseReceived {
channel_id: ChannelId(u64::MAX),
status: StatusEnum::FormatError as i32,
memo: "message body could not be decoded".to_owned(),
})
.expect("ErrorResponseReceived must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "ErrorResponseReceived");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["status"], StatusEnum::FormatError as i32);
assert_eq!(json["memo"], "message body could not be decoded");
}
#[test]
fn pairing_refused_maps_status_memo_and_error() {
let mapped = Event::from_event(DeRecEvent::PairingRefused {
channel_id: ChannelId(u64::MAX),
status: StatusEnum::ReplicaIdConflict as i32,
memo: "replica id in use".to_owned(),
error_code: "replica_id_conflict".to_owned(),
message: "replica id 7 is already in use by another member of the group".to_owned(),
})
.expect("PairingRefused must map");
let json = serde_json::to_value(&mapped).expect("serializes");
assert_eq!(json["type"], "PairingRefused");
assert_eq!(json["channel_id"], u64::MAX.to_string());
assert_eq!(json["status"], StatusEnum::ReplicaIdConflict as i32);
assert_eq!(json["memo"], "replica id in use");
assert_eq!(json["error_code"], "replica_id_conflict");
assert_eq!(
json["message"],
"replica id 7 is already in use by another member of the group"
);
}
}