Files
meow/crates/meow-core/src/contact.rs
T
2026-11-20 21:47:33 +01:00

198 lines
6.5 KiB
Rust

//! Contacts: per-relationship keys, peer public material and state.
use meow_crypto::{ratchet::Session, DhKeyPair, DhPublic, SignPublic, SigningKeyPair};
use meow_proto::{v2, PROTOCOL_VERSION};
use serde::{Deserialize, Serialize};
use crate::server::ServerInfo;
use crate::{proto_err, Error, Result};
/// Random contact identifier (16 bytes, hex encoded).
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ContactId(pub String);
impl ContactId {
pub fn random() -> Self {
Self(crate::hex(&meow_crypto::random_bytes::<16>()))
}
}
impl std::fmt::Display for ContactId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// My own key material for one relationship. Never shared between contacts.
#[derive(Clone, Serialize, Deserialize)]
pub struct OwnKeys {
pub identity: SigningKeyPair,
pub dh: DhKeyPair,
pub mailbox: SigningKeyPair,
pub ratchet: DhKeyPair,
}
impl OwnKeys {
pub fn generate() -> Self {
Self {
identity: SigningKeyPair::generate(),
dh: DhKeyPair::generate(),
mailbox: SigningKeyPair::generate(),
ratchet: DhKeyPair::generate(),
}
}
/// The card I give to this contact.
pub fn card(&self, my_name: &str, pull_servers: &[ServerInfo]) -> v2::ContactCard {
v2::ContactCard {
version: PROTOCOL_VERSION,
name: my_name.to_string(),
identity_key: self.identity.public().to_vec(),
dh_key: self.dh.public().to_vec(),
mailbox: self.mailbox.public().to_vec(),
ratchet_key: self.ratchet.public().to_vec(),
pull_servers: pull_servers.iter().map(ServerInfo::to_card).collect(),
}
}
}
/// Public material received from a contact.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerCard {
pub name: String,
pub identity: SignPublic,
pub dh: DhPublic,
pub mailbox: SignPublic,
pub ratchet: DhPublic,
pub pull_servers: Vec<ServerInfo>,
}
impl PeerCard {
pub fn from_proto(c: &v2::ContactCard) -> Result<Self> {
if c.version != PROTOCOL_VERSION {
return Err(proto_err("unsupported contact card version"));
}
let pull_servers = c
.pull_servers
.iter()
.map(ServerInfo::from_card)
.collect::<Result<Vec<_>>>()?;
if pull_servers.is_empty() {
return Err(proto_err("contact card has no pull server"));
}
Ok(Self {
name: c.name.clone(),
identity: SignPublic::from_slice(&c.identity_key)?,
dh: DhPublic::from_slice(&c.dh_key)?,
mailbox: SignPublic::from_slice(&c.mailbox)?,
ratchet: DhPublic::from_slice(&c.ratchet_key)?,
pull_servers,
})
}
}
/// Secrets kept by the initiator between steps 1 and 3.
#[derive(Clone, Serialize, Deserialize)]
pub struct OfferSecrets {
pub offer_dh: DhKeyPair,
pub answer_mailbox: SigningKeyPair,
/// Exact encoded offer, hashed into the transcript.
pub offer_bytes: Vec<u8>,
pub expires_at: u64,
}
/// Lifecycle of a contact.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContactState {
/// Initiator, step 1 done: waiting for the invitee's answer.
OfferSent,
/// Invitee, step 2 done: waiting for the initiator's confirmation.
AnswerSent,
/// Initiator, step 3 done: can send; waiting for the invitee's ack.
ConfirmSent,
/// Handshake complete on this side.
Active,
}
/// A contact (one relationship).
#[derive(Clone, Serialize, Deserialize)]
pub struct Contact {
pub id: ContactId,
/// Local name for this contact.
pub name: String,
/// Name I present to this contact.
pub my_name: String,
pub state: ContactState,
pub invitation_id: [u8; 16],
pub invitation_message: String,
/// Initiator only, until step 3.
pub offer: Option<OfferSecrets>,
/// My keys (created at step 2 for the invitee, step 3 for the initiator).
pub keys: Option<OwnKeys>,
/// Servers where I poll my mailbox for this contact.
pub my_pull_servers: Vec<ServerInfo>,
pub peer: Option<PeerCard>,
/// Serialised Double Ratchet session.
pub session: Option<Vec<u8>>,
/// Invitee only, between steps 2 and 4: hash of the received offer.
pub offer_hash: Option<[u8; 32]>,
/// Invitee only, between steps 2 and 4: the exact card sent in the answer.
pub sent_card: Option<Vec<u8>>,
/// Final handshake transcript hash, usable as a safety number.
pub transcript: Option<[u8; 32]>,
pub created_at: u64,
}
impl Contact {
pub fn can_send(&self) -> bool {
matches!(self.state, ContactState::ConfirmSent | ContactState::Active) && self.session.is_some()
}
pub(crate) fn load_session(&self) -> Result<Session> {
let bytes = self.session.as_ref().ok_or(Error::State("no ratchet session"))?;
Ok(Session::from_bytes(bytes)?)
}
pub(crate) fn keys(&self) -> Result<&OwnKeys> {
self.keys.as_ref().ok_or(Error::State("contact keys not created yet"))
}
pub(crate) fn peer(&self) -> Result<&PeerCard> {
self.peer.as_ref().ok_or(Error::State("peer card unknown"))
}
/// The mailbox I currently poll for this contact, with the key that proves ownership.
pub fn my_mailbox(&self) -> Option<&SigningKeyPair> {
match (&self.keys, &self.offer) {
(Some(k), _) => Some(&k.mailbox),
(None, Some(o)) => Some(&o.answer_mailbox),
_ => None,
}
}
/// Mailboxes to poll, with the servers to poll them on.
///
/// While an offer is pending, the initiator also keeps polling the answer mailbox.
pub fn mailboxes(&self) -> Vec<(&SigningKeyPair, &[ServerInfo])> {
let mut v = Vec::new();
if let Some(k) = &self.keys {
v.push((&k.mailbox, self.my_pull_servers.as_slice()));
}
if let Some(o) = &self.offer {
v.push((&o.answer_mailbox, self.my_pull_servers.as_slice()));
}
v
}
/// Short human-comparable safety number derived from the handshake transcript.
pub fn safety_number(&self) -> Option<String> {
self.transcript.map(|t| {
t[..10]
.chunks(2)
.map(|c| format!("{:05}", u16::from_be_bytes([c[0], c[1]])))
.collect::<Vec<_>>()
.join(" ")
})
}
}