use crate::Error;
use crate::derec_message::current_timestamp;
use crate::primitives::pairing::PairingError;
use crate::types::ChannelId;
use derec_cryptography::pairing::{
FingerprintCommitment, PairingContactMessageMaterial, contact_binding_hash,
};
use derec_proto::{ContactMessage, ContactMode, TransportProtocol};
pub(crate) trait ContactMessageExt {
fn validate(&self) -> Result<(), Error>;
fn validate_for_mode(&self, expected: ContactMode) -> Result<(), Error>;
fn requires_pre_pair(&self) -> bool;
fn inline_keys(
channel_id: ChannelId,
nonce: u64,
own: Vec<TransportProtocol>,
pk: PairingContactMessageMaterial,
fingerprint_commitment: FingerprintCommitment,
) -> ContactMessage;
fn hashed_keys(
channel_id: ChannelId,
nonce: u64,
own: Vec<TransportProtocol>,
pk: &PairingContactMessageMaterial,
) -> Result<ContactMessage, Error>;
fn no_keys(channel_id: ChannelId, nonce: u64, own: Vec<TransportProtocol>) -> ContactMessage;
}
impl ContactMessageExt for ContactMessage {
fn validate(&self) -> Result<(), Error> {
let mode = ContactMode::try_from(self.contact_mode).map_err(|_| {
#[cfg(feature = "logging")]
tracing::warn!(
contact_mode = self.contact_mode,
"unknown contact_mode value"
);
PairingError::InvalidContactMessage("unknown contact_mode value")
})?;
let mlkem_present = self
.mlkem_encapsulation_key
.as_ref()
.is_some_and(|v| !v.is_empty());
let ecies_present = self
.ecies_public_key
.as_ref()
.is_some_and(|v| !v.is_empty());
let hash_present = self
.contact_binding_hash
.as_ref()
.is_some_and(|v| !v.is_empty());
let commitment = self.fingerprint_commitment.as_deref();
match mode {
ContactMode::InlineKeys => {
check_inline_keys_fields(mlkem_present, ecies_present, hash_present)?;
check_fingerprint_commitment(commitment)?;
}
ContactMode::HashedKeys => {
check_hashed_keys_fields(
mlkem_present,
ecies_present,
self.contact_binding_hash.as_deref(),
)?;
check_no_fingerprint_commitment(commitment)?;
}
ContactMode::NoKeys => {
check_no_keys_fields(mlkem_present, ecies_present, hash_present)?;
check_no_fingerprint_commitment(commitment)?;
}
}
if self.supported_transports.is_empty() {
#[cfg(feature = "logging")]
tracing::warn!("contact advertises no usable transport endpoint");
return Err(PairingError::EmptyTransportUri.into());
}
Ok(())
}
fn validate_for_mode(&self, expected: ContactMode) -> Result<(), Error> {
if self.contact_mode != expected as i32 {
#[cfg(feature = "logging")]
tracing::warn!(
contact_mode = self.contact_mode,
expected = expected as i32,
"contact_mode mismatch"
);
return Err(PairingError::InvalidContactMessage(match expected {
ContactMode::InlineKeys => "expected INLINE_KEYS contact mode",
ContactMode::HashedKeys => "expected HASHED_KEYS contact mode",
ContactMode::NoKeys => "expected NO_KEYS contact mode",
})
.into());
}
self.validate()
}
fn requires_pre_pair(&self) -> bool {
self.contact_mode == ContactMode::HashedKeys as i32
|| self.contact_mode == ContactMode::NoKeys as i32
}
fn inline_keys(
channel_id: ChannelId,
nonce: u64,
own: Vec<TransportProtocol>,
pk: PairingContactMessageMaterial,
fingerprint_commitment: FingerprintCommitment,
) -> ContactMessage {
ContactMessage {
channel_id: channel_id.into(),
contact_mode: ContactMode::InlineKeys as i32,
mlkem_encapsulation_key: Some(pk.mlkem_encapsulation_key),
ecies_public_key: Some(pk.ecies_public_key),
contact_binding_hash: None,
nonce,
timestamp: Some(current_timestamp()),
supported_transports: own,
fingerprint_commitment: Some(fingerprint_commitment.to_vec()),
}
}
fn hashed_keys(
channel_id: ChannelId,
nonce: u64,
own: Vec<TransportProtocol>,
pk: &PairingContactMessageMaterial,
) -> Result<ContactMessage, Error> {
let binding_hash = contact_binding_hash(
&pk.mlkem_encapsulation_key,
&pk.ecies_public_key,
nonce,
channel_id.into(),
)
.map_err(|source| PairingError::ContactMessageKeygen { source })?;
Ok(ContactMessage {
channel_id: channel_id.into(),
contact_mode: ContactMode::HashedKeys as i32,
mlkem_encapsulation_key: None,
ecies_public_key: None,
contact_binding_hash: Some(binding_hash.to_vec()),
nonce,
timestamp: Some(current_timestamp()),
supported_transports: own,
fingerprint_commitment: None,
})
}
fn no_keys(channel_id: ChannelId, nonce: u64, own: Vec<TransportProtocol>) -> ContactMessage {
ContactMessage {
channel_id: channel_id.into(),
contact_mode: ContactMode::NoKeys as i32,
mlkem_encapsulation_key: None,
ecies_public_key: None,
contact_binding_hash: None,
nonce,
timestamp: Some(current_timestamp()),
supported_transports: own,
fingerprint_commitment: None,
}
}
}
fn check_inline_keys_fields(
mlkem_present: bool,
ecies_present: bool,
hash_present: bool,
) -> Result<(), Error> {
if !mlkem_present {
return Err(PairingError::InvalidContactMessage(
"inline_keys contact missing mlkem_encapsulation_key",
)
.into());
}
if !ecies_present {
return Err(PairingError::InvalidContactMessage(
"inline_keys contact missing ecies_public_key",
)
.into());
}
if hash_present {
return Err(PairingError::InvalidContactMessage(
"inline_keys contact must not carry contact_binding_hash",
)
.into());
}
Ok(())
}
fn check_hashed_keys_fields(
mlkem_present: bool,
ecies_present: bool,
contact_binding_hash: Option<&[u8]>,
) -> Result<(), Error> {
const BINDING_HASH_LEN: usize = 48;
if mlkem_present || ecies_present {
return Err(PairingError::InvalidContactMessage(
"hashed_keys contact must not carry inline keys",
)
.into());
}
let hash = contact_binding_hash.filter(|h| !h.is_empty()).ok_or(
PairingError::InvalidContactMessage("hashed_keys contact missing contact_binding_hash"),
)?;
if hash.len() != BINDING_HASH_LEN {
return Err(PairingError::InvalidContactMessage(
"hashed_keys contact_binding_hash is not a SHA-384 digest",
)
.into());
}
Ok(())
}
fn check_fingerprint_commitment(commitment: Option<&[u8]>) -> Result<(), Error> {
const COMMITMENT_LEN: usize = 32;
match commitment {
Some(c) if c.len() == COMMITMENT_LEN => Ok(()),
Some(_) => Err(PairingError::InvalidContactMessage(
"inline_keys fingerprint_commitment is not a SHA-256 digest",
)
.into()),
None => Err(PairingError::InvalidContactMessage(
"inline_keys contact missing fingerprint_commitment",
)
.into()),
}
}
fn check_no_fingerprint_commitment(commitment: Option<&[u8]>) -> Result<(), Error> {
if commitment.is_some() {
return Err(PairingError::InvalidContactMessage(
"only an inline_keys contact carries fingerprint_commitment",
)
.into());
}
Ok(())
}
fn check_no_keys_fields(
mlkem_present: bool,
ecies_present: bool,
hash_present: bool,
) -> Result<(), Error> {
if mlkem_present || ecies_present {
return Err(PairingError::InvalidContactMessage(
"no_keys contact must not carry inline keys",
)
.into());
}
if hash_present {
return Err(PairingError::InvalidContactMessage(
"no_keys contact must not carry contact_binding_hash",
)
.into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Error;
use derec_proto::Protocol;
use prost_types::Timestamp;
fn ts(seconds: i64) -> Timestamp {
Timestamp { seconds, nanos: 0 }
}
fn well_formed_inline_keys_contact() -> ContactMessage {
ContactMessage {
channel_id: 42,
contact_mode: ContactMode::InlineKeys as i32,
mlkem_encapsulation_key: Some(vec![1; 1184]),
ecies_public_key: Some(vec![2; 33]),
contact_binding_hash: None,
nonce: 0xCAFE_BABE,
timestamp: Some(ts(1_700_000_000)),
supported_transports: vec![TransportProtocol {
uri: "https://relay.example/alice".to_owned(),
protocol: Protocol::Https.into(),
}],
fingerprint_commitment: Some(vec![3; 32]),
}
}
fn well_formed_hashed_keys_contact() -> ContactMessage {
ContactMessage {
channel_id: 42,
contact_mode: ContactMode::HashedKeys as i32,
mlkem_encapsulation_key: None,
ecies_public_key: None,
contact_binding_hash: Some(vec![0xAB; 48]),
nonce: 0xDEAD_BEEF,
timestamp: Some(ts(1_700_000_000)),
supported_transports: vec![TransportProtocol {
uri: "https://relay.example/alice/ephemeral".to_owned(),
protocol: Protocol::Https.into(),
}],
fingerprint_commitment: None,
}
}
fn well_formed_no_keys_contact() -> ContactMessage {
ContactMessage {
channel_id: 1234,
contact_mode: ContactMode::NoKeys as i32,
mlkem_encapsulation_key: None,
ecies_public_key: None,
contact_binding_hash: None,
nonce: 4321,
timestamp: Some(ts(1_700_000_000)),
supported_transports: vec![TransportProtocol {
uri: "https://institution.example/pair".to_owned(),
protocol: Protocol::Https.into(),
}],
fingerprint_commitment: None,
}
}
fn assert_invalid_contact(result: Result<(), Error>, expected: &'static str) {
match result {
Err(Error::Pairing(PairingError::InvalidContactMessage(m))) => {
assert_eq!(m, expected, "wrong InvalidContactMessage payload")
}
other => panic!("expected InvalidContactMessage({expected:?}), got {other:?}"),
}
}
#[test]
fn validate_accepts_well_formed_inline_keys() {
well_formed_inline_keys_contact()
.validate()
.expect("well-formed inline_keys must pass");
}
#[test]
fn validate_accepts_well_formed_hashed_keys() {
well_formed_hashed_keys_contact()
.validate()
.expect("well-formed hashed_keys must pass");
}
#[test]
fn validate_accepts_well_formed_no_keys() {
well_formed_no_keys_contact()
.validate()
.expect("well-formed no_keys must pass");
}
#[test]
fn validate_rejects_unknown_contact_mode() {
let mut c = well_formed_inline_keys_contact();
c.contact_mode = 7;
assert_invalid_contact(c.validate(), "unknown contact_mode value");
}
#[test]
fn validate_rejects_inline_missing_mlkem_key() {
let mut c = well_formed_inline_keys_contact();
c.mlkem_encapsulation_key = None;
assert_invalid_contact(
c.validate(),
"inline_keys contact missing mlkem_encapsulation_key",
);
}
#[test]
fn validate_rejects_inline_missing_ecies_key() {
let mut c = well_formed_inline_keys_contact();
c.ecies_public_key = None;
assert_invalid_contact(c.validate(), "inline_keys contact missing ecies_public_key");
}
#[test]
fn validate_rejects_inline_with_binding_hash() {
let mut c = well_formed_inline_keys_contact();
c.contact_binding_hash = Some(vec![0xCD; 48]);
assert_invalid_contact(
c.validate(),
"inline_keys contact must not carry contact_binding_hash",
);
}
#[test]
fn validate_rejects_hashed_with_inline_keys() {
let mut c = well_formed_hashed_keys_contact();
c.mlkem_encapsulation_key = Some(vec![1; 1184]);
assert_invalid_contact(
c.validate(),
"hashed_keys contact must not carry inline keys",
);
}
#[test]
fn validate_rejects_hashed_missing_binding_hash() {
let mut c = well_formed_hashed_keys_contact();
c.contact_binding_hash = None;
assert_invalid_contact(
c.validate(),
"hashed_keys contact missing contact_binding_hash",
);
}
#[test]
fn validate_rejects_hashed_empty_binding_hash() {
let mut c = well_formed_hashed_keys_contact();
c.contact_binding_hash = Some(Vec::new());
assert_invalid_contact(
c.validate(),
"hashed_keys contact missing contact_binding_hash",
);
}
#[test]
fn validate_rejects_hashed_wrong_hash_length() {
let mut c = well_formed_hashed_keys_contact();
c.contact_binding_hash = Some(vec![0xAB; 32]);
assert_invalid_contact(
c.validate(),
"hashed_keys contact_binding_hash is not a SHA-384 digest",
);
}
#[test]
fn validate_rejects_no_keys_with_mlkem_key() {
let mut c = well_formed_no_keys_contact();
c.mlkem_encapsulation_key = Some(vec![1; 1184]);
assert_invalid_contact(c.validate(), "no_keys contact must not carry inline keys");
}
#[test]
fn validate_rejects_no_keys_with_ecies_key() {
let mut c = well_formed_no_keys_contact();
c.ecies_public_key = Some(vec![2; 33]);
assert_invalid_contact(c.validate(), "no_keys contact must not carry inline keys");
}
#[test]
fn validate_rejects_no_keys_with_binding_hash() {
let mut c = well_formed_no_keys_contact();
c.contact_binding_hash = Some(vec![0xAB; 48]);
assert_invalid_contact(
c.validate(),
"no_keys contact must not carry contact_binding_hash",
);
}
#[test]
fn validate_rejects_inline_missing_fingerprint_commitment() {
let mut c = well_formed_inline_keys_contact();
c.fingerprint_commitment = None;
assert_invalid_contact(
c.validate(),
"inline_keys contact missing fingerprint_commitment",
);
}
#[test]
fn validate_rejects_inline_short_fingerprint_commitment() {
let mut c = well_formed_inline_keys_contact();
c.fingerprint_commitment = Some(vec![3; 31]);
assert_invalid_contact(
c.validate(),
"inline_keys fingerprint_commitment is not a SHA-256 digest",
);
}
#[test]
fn validate_rejects_hashed_with_fingerprint_commitment() {
let mut c = well_formed_hashed_keys_contact();
c.fingerprint_commitment = Some(vec![3; 32]);
assert_invalid_contact(
c.validate(),
"only an inline_keys contact carries fingerprint_commitment",
);
}
#[test]
fn validate_rejects_no_keys_with_fingerprint_commitment() {
let mut c = well_formed_no_keys_contact();
c.fingerprint_commitment = Some(vec![3; 32]);
assert_invalid_contact(
c.validate(),
"only an inline_keys contact carries fingerprint_commitment",
);
}
}