Skip to main content

zaun_community_protocol/crypto/voice/
package.rs

1//! `VoiceKeyPackage` (ADR-0018, ctx `zaun/v1/voice-key-package`): a participant's X-Wing
2//! public key for one voice session, signed by its member key.
3//!
4//! | # | Field | Encoding |
5//! |---|---|---|
6//! | 1 | format | `u8` = `0x01` |
7//! | 2 | suite | `u8` = [`SUITE_V1`] |
8//! | 3 | `community_id` | `bytes[32]` |
9//! | 4 | `channel_id` | `bytes[16]` |
10//! | 5 | `member_id` | `bytes[16]` |
11//! | 6 | `voice_session` | `bytes[16]` |
12//! | 7 | `kem_public` | `bytes[1216]` (X-Wing) |
13//! | 8 | `created_at` | `u64`, ms since the epoch |
14//!
15//! On the wire: the canonical bytes ([`KEY_PACKAGE_BYTES_LEN`]) followed by the composite
16//! signature (`SIGNATURE_LEN`), [`KEY_PACKAGE_WIRE_LEN`] bytes in all.
17
18use super::identity::{VoiceIdentity, VoicePublicKey};
19use super::session::VoiceSessionId;
20use super::{KEM_PUBLIC_LEN, KEY_PACKAGE_BYTES_LEN, KEY_PACKAGE_WIRE_LEN, SUITE_V1, VoiceError};
21use crate::crypto::{Context, SecretKey};
22use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
23use crate::ids::{ChannelId, CommunityId, MemberId};
24use crate::keys::{PublicKey, Signature};
25use crate::signed::{FORMAT_V1, Signed, SignedObject};
26
27/// A participant's voice key for one session in one voice channel.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct KeyPackage {
30    /// 2: the voice suite.
31    pub suite: u8,
32    /// 3: the community.
33    pub community_id: CommunityId,
34    /// 4: the voice channel.
35    pub channel_id: ChannelId,
36    /// 5: the participant; its member key signs.
37    pub member_id: MemberId,
38    /// 6: this participation.
39    pub voice_session: VoiceSessionId,
40    /// 7: the X-Wing public key sender keys are wrapped to.
41    pub kem_public: VoicePublicKey,
42    /// 8: ms since the epoch.
43    pub created_at: u64,
44}
45
46impl Encode for KeyPackage {
47    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
48        w.u8(FORMAT_V1);
49        w.u8(self.suite);
50        w.put(&self.community_id)?;
51        w.fixed(self.channel_id.as_bytes());
52        w.fixed(self.member_id.as_bytes());
53        w.fixed(self.voice_session.as_bytes());
54        w.fixed(self.kem_public.as_bytes());
55        w.u64(self.created_at);
56        Ok(())
57    }
58}
59
60impl Decode for KeyPackage {
61    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
62        if r.u8()? != FORMAT_V1 {
63            return Err(DecodeError::Invalid("format"));
64        }
65        let suite = r.u8()?;
66        if suite != SUITE_V1 {
67            return Err(DecodeError::Invalid("suite"));
68        }
69        let community_id = r.get()?;
70        let channel_id = ChannelId::from_bytes(r.array()?);
71        let member_id = MemberId::from_bytes(r.array()?);
72        let voice_session = VoiceSessionId::from_bytes(r.array()?);
73        let kem: [u8; KEM_PUBLIC_LEN] = r.array()?;
74        let kem_public =
75            VoicePublicKey::from_bytes(&kem).map_err(|_| DecodeError::Invalid("kem_public"))?;
76        Ok(Self {
77            suite,
78            community_id,
79            channel_id,
80            member_id,
81            voice_session,
82            kem_public,
83            created_at: r.u64()?,
84        })
85    }
86}
87
88impl SignedObject for KeyPackage {
89    const CONTEXT: Context = Context::VoiceKeyPackage;
90}
91
92/// What a receiver expects of a peer's key package.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct PackageExpectation {
95    /// The community of the voice channel.
96    pub community_id: CommunityId,
97    /// The voice channel.
98    pub channel_id: ChannelId,
99    /// The member the roster says this package belongs to.
100    pub member_id: MemberId,
101    /// The community's minimum signature suite (`0x01` today).
102    pub min_suite: u8,
103}
104
105/// A key package whose signature was made here or verified.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct SignedKeyPackage(Signed<KeyPackage>);
108
109impl KeyPackage {
110    /// Makes and signs this participant's key package.
111    ///
112    /// # Errors
113    /// [`VoiceError::Signed`] when signing fails.
114    pub fn create(
115        member_key: &SecretKey,
116        identity: &VoiceIdentity,
117        community_id: CommunityId,
118        channel_id: ChannelId,
119        member_id: MemberId,
120        voice_session: VoiceSessionId,
121        created_at: u64,
122    ) -> Result<SignedKeyPackage, VoiceError> {
123        let package = Self {
124            suite: SUITE_V1,
125            community_id,
126            channel_id,
127            member_id,
128            voice_session,
129            kem_public: identity.public_key().clone(),
130            created_at,
131        };
132        Ok(SignedKeyPackage(package.sign(member_key)?))
133    }
134
135    /// Verifies a peer's key package from the wire under `member_key` (the roster's key for
136    /// `expected.member_id`), then checks the community, channel and member.
137    ///
138    /// # Errors
139    /// [`VoiceError::Length`], [`VoiceError::Signed`] (checked before decoding) or
140    /// [`VoiceError::Mismatch`].
141    pub fn verify(
142        wire: &[u8],
143        member_key: &PublicKey,
144        expected: &PackageExpectation,
145    ) -> Result<SignedKeyPackage, VoiceError> {
146        if wire.len() != KEY_PACKAGE_WIRE_LEN {
147            return Err(VoiceError::Length("key package"));
148        }
149        let (bytes, sig) = wire.split_at(KEY_PACKAGE_BYTES_LEN);
150        let sig = Signature::from_bytes(sig).map_err(|e| VoiceError::Signed(e.into()))?;
151        let signed =
152            Signed::<Self>::verify_and_decode(bytes, &sig, member_key, expected.min_suite)?;
153        let p = signed.object();
154        if p.community_id != expected.community_id {
155            return Err(VoiceError::Mismatch("community_id"));
156        }
157        if p.channel_id != expected.channel_id {
158            return Err(VoiceError::Mismatch("channel_id"));
159        }
160        if p.member_id != expected.member_id {
161            return Err(VoiceError::Mismatch("member_id"));
162        }
163        Ok(SignedKeyPackage(signed))
164    }
165}
166
167impl SignedKeyPackage {
168    /// The package.
169    #[must_use]
170    pub const fn package(&self) -> &KeyPackage {
171        self.0.object()
172    }
173
174    /// `SHA3-256` of the canonical bytes: bound into every key wrapped to this package.
175    #[must_use]
176    pub fn hash(&self) -> [u8; 32] {
177        self.0.hash()
178    }
179
180    /// The wire form: canonical bytes ‖ signature.
181    #[must_use]
182    pub fn to_wire(&self) -> Vec<u8> {
183        let mut out = Vec::with_capacity(KEY_PACKAGE_WIRE_LEN);
184        out.extend_from_slice(self.0.bytes());
185        out.extend_from_slice(self.0.signature().as_bytes());
186        out
187    }
188}