1use hkdf::Hkdf;
26use nostr_sdk::nips::nip44::v2::ConversationKey;
27use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
28use sha2::{Digest, Sha256};
29
30use super::super::{ChannelId, CommunityId, Epoch};
31
32const LABEL_CHANNEL: &str = "concord/channel";
34const LABEL_CONTROL: &str = "concord/control";
35const LABEL_REKEY_PSEUDONYM: &str = "concord/rekey-pseudonym";
36const LABEL_BASE_REKEY_PSEUDONYM: &str = "concord/base-rekey-pseudonym";
37const LABEL_RECIPIENT_PSEUDONYM: &str = "concord/recipient-pseudonym";
38const LABEL_GUESTBOOK: &str = "concord/guestbook";
39const LABEL_VOICE_SIGNER: &str = "concord/voice-signer";
40const LABEL_VOICE_MEDIA: &str = "concord/voice-media";
41const LABEL_VOICE_SENDER: &str = "concord/voice-sender";
42const LABEL_DISSOLVED: &str = "concord/dissolved";
43const LABEL_GRANT: &str = "concord/grant";
44const LABEL_BANLIST: &str = "concord/banlist";
45const LABEL_INVITE_LINKS: &str = "concord/invite-links";
46const LABEL_INVITE_KEY: &str = "concord/invite-key";
47const LABEL_COMMUNITY: &str = "concord/community";
49const LABEL_EPOCH_COMMITMENT: &str = "concord/epoch-key-commitment";
51
52const ZERO32: [u8; 32] = [0u8; 32];
53
54pub const TOKEN_LEN: usize = 16;
57
58fn build_info(label: &str, id32: &[u8; 32], epoch: Option<u64>) -> Vec<u8> {
61 let mut info = Vec::with_capacity(label.len() + 1 + 32 + 8);
62 info.extend_from_slice(label.as_bytes());
63 info.push(0x00);
64 info.extend_from_slice(id32);
65 if let Some(e) = epoch {
66 info.extend_from_slice(&e.to_be_bytes());
67 }
68 info
69}
70
71fn hkdf32(ikm: &[u8], info: &[u8]) -> [u8; 32] {
75 let hk = Hkdf::<Sha256>::new(None, ikm);
76 let mut okm = [0u8; 32];
77 hk.expand(info, &mut okm)
78 .expect("HKDF expand of 32 bytes is infallible");
79 okm
80}
81
82fn hkdf_to_secret_key(ikm: &[u8], base_info: &[u8]) -> SecretKey {
87 if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, base_info)) {
88 return sk;
89 }
90 for counter in 0u8..=255 {
91 let mut info = base_info.to_vec();
92 info.push(counter);
93 if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, &info)) {
94 return sk;
95 }
96 }
97 unreachable!("secp256k1 scalar rejection 257 times running is impossible")
98}
99
100#[derive(Clone)]
106pub struct GroupKey {
107 keys: Keys,
108 conv_key: ConversationKey,
109}
110
111impl GroupKey {
112 fn derive(label: &str, secret: &[u8], id32: &[u8; 32], epoch: Option<u64>) -> Self {
113 let info = build_info(label, id32, epoch);
114 let sk = hkdf_to_secret_key(secret, &info);
115 let keys = Keys::new(sk);
116 let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key())
117 .expect("self-ECDH of a valid keypair cannot fail");
118 GroupKey { keys, conv_key }
119 }
120
121 pub fn pk(&self) -> PublicKey {
123 self.keys.public_key()
124 }
125
126 pub fn pk_hex(&self) -> String {
128 self.keys.public_key().to_hex()
129 }
130
131 pub fn keys(&self) -> &Keys {
133 &self.keys
134 }
135
136 pub fn conv_key(&self) -> &ConversationKey {
138 &self.conv_key
139 }
140}
141
142impl std::fmt::Debug for GroupKey {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 f.debug_struct("GroupKey").field("pk", &self.pk_hex()).finish()
146 }
147}
148
149pub fn channel_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
157 GroupKey::derive(LABEL_CHANNEL, secret, &channel_id.0, Some(epoch.0))
158}
159
160pub fn control_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
162 GroupKey::derive(LABEL_CONTROL, community_root, &community_id.0, Some(epoch.0))
163}
164
165pub fn guestbook_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
167 GroupKey::derive(LABEL_GUESTBOOK, community_root, &community_id.0, Some(epoch.0))
168}
169
170pub fn channel_rekey_group_key(root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
175 GroupKey::derive(LABEL_REKEY_PSEUDONYM, root, &channel_id.0, Some(new_epoch.0))
176}
177
178pub fn base_rekey_group_key(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
182 GroupKey::derive(LABEL_BASE_REKEY_PSEUDONYM, prior_root, &community_id.0, Some(new_epoch.0))
183}
184
185pub fn dissolved_group_key(community_id: &CommunityId) -> GroupKey {
189 GroupKey::derive(LABEL_DISSOLVED, &community_id.0, &ZERO32, None)
190}
191
192pub fn voice_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
199 GroupKey::derive(LABEL_VOICE_SIGNER, secret, &channel_id.0, Some(epoch.0))
200}
201
202pub fn voice_media_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> [u8; 32] {
205 hkdf32(secret, &build_info(LABEL_VOICE_MEDIA, &channel_id.0, Some(epoch.0)))
206}
207
208pub fn voice_sender_key(media_key: &[u8; 32], identity: &str) -> [u8; 32] {
213 let id: [u8; 32] = Sha256::digest(identity.as_bytes()).into();
214 hkdf32(media_key, &build_info(LABEL_VOICE_SENDER, &id, None))
215}
216
217pub fn grant_locator(community_id: &CommunityId, member_xonly: &[u8; 32]) -> [u8; 32] {
222 hkdf32(&community_id.0, &build_info(LABEL_GRANT, member_xonly, None))
223}
224
225pub fn banlist_locator(community_id: &CommunityId) -> [u8; 32] {
227 hkdf32(&community_id.0, &build_info(LABEL_BANLIST, &ZERO32, None))
228}
229
230pub fn invite_links_locator(community_id: &CommunityId, creator_xonly: &[u8; 32]) -> [u8; 32] {
233 hkdf32(&community_id.0, &build_info(LABEL_INVITE_LINKS, creator_xonly, None))
234}
235
236pub fn recipient_locator(
245 rotator_xonly: &[u8; 32],
246 recipient_xonly: &[u8; 32],
247 scope_id: &[u8; 32],
248 new_epoch: Epoch,
249) -> [u8; 32] {
250 let mut ikm = [0u8; 64];
251 ikm[..32].copy_from_slice(rotator_xonly);
252 ikm[32..].copy_from_slice(recipient_xonly);
253 hkdf32(&ikm, &build_info(LABEL_RECIPIENT_PSEUDONYM, scope_id, Some(new_epoch.0)))
254}
255
256pub fn invite_bundle_key(token: &[u8; TOKEN_LEN]) -> [u8; 32] {
259 hkdf32(token, &build_info(LABEL_INVITE_KEY, &ZERO32, None))
260}
261
262pub fn community_id_of(owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> CommunityId {
270 let mut h = Sha256::new();
271 h.update(LABEL_COMMUNITY.as_bytes());
272 h.update(owner_xonly);
273 h.update(owner_salt);
274 CommunityId(h.finalize().into())
275}
276
277pub fn verify_community_id(community_id: &CommunityId, owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> bool {
281 community_id_of(owner_xonly, owner_salt) == *community_id
282}
283
284pub fn epoch_key_commitment(prev_epoch: Epoch, prev_key: &[u8; 32]) -> [u8; 32] {
290 let mut h = Sha256::new();
291 h.update(LABEL_EPOCH_COMMITMENT.as_bytes());
292 h.update(prev_epoch.0.to_be_bytes());
293 h.update(prev_key);
294 h.finalize().into()
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 fn secret() -> [u8; 32] {
309 let mut k = [0u8; 32];
311 for (i, b) in k.iter_mut().enumerate() {
312 *b = i as u8;
313 }
314 k
315 }
316
317 fn id32() -> [u8; 32] {
318 let mut id = [0u8; 32];
320 for (i, b) in id.iter_mut().enumerate() {
321 *b = (255 - i) as u8;
322 }
323 id
324 }
325
326 fn alt() -> [u8; 32] {
327 [0x11u8; 32]
328 }
329
330 fn cid() -> CommunityId {
331 CommunityId(id32())
332 }
333
334 fn chan() -> ChannelId {
335 ChannelId(id32())
336 }
337
338 const EPOCH_MULTI: u64 = 0x0102030405060708;
340
341 const GOLDEN_CHANNEL_E0_SEED: &str = "1a99a5958bf9fcc5336e6e19db42aabf36ffbfa12f38a1d5fbde2ae383ed751b";
342 const GOLDEN_CHANNEL_E0_PK: &str = "7a5c5dff759a63f1fc2779864487432bae3d1ea72c4ffabd39f4c1fdaf62097a";
343 const GOLDEN_CHANNEL_EMULTI_PK: &str = "f20c7d192cc87615d7341e86f38f85303f4708b40232d4fea521ab8217767391";
344 const GOLDEN_CONTROL_E0_PK: &str = "c43df20bf4d6eeaea5149619662ffe9b211f31e11bb4a59f56b6e906f702d46f";
345 const GOLDEN_GUESTBOOK_E0_PK: &str = "ad09de582026fa7a052db18bb5827fa24c15e929d59aadcc91efb8508f5368ad";
346 const GOLDEN_CHANNEL_REKEY_E1_PK: &str = "7c55cdb957e9db2b4800d687b2a07d3f7066b1a35824a1e86ba871f55e87e8b5";
347 const GOLDEN_BASE_REKEY_E1_PK: &str = "fb2fa44fba66ba15595f784255a1cb569531db8784432ac0e4fe838498dd9dea";
348 const GOLDEN_DISSOLVED_PK: &str = "4d3d55d88fdf9d9c2089651e5cbb0dfa93b6b9b10cdcb2319b0dce1a1398096a";
349 const GOLDEN_GRANT_LOCATOR: &str = "fd2f88cc7f1eb8d7d862c91dc22afe700c358d1845158b3f353b769ce4898e35";
350 const GOLDEN_BANLIST_LOCATOR: &str = "88089214afae6d3c412fd817ada44d6df4d485a53565646471e74476397693c9";
351 const GOLDEN_INVITE_LINKS_LOCATOR: &str = "f4ae29994165767bac23e8dce630f81b926d2c8aa150e5cbf0bdf75865e8379a";
352 const GOLDEN_RECIPIENT_LOCATOR: &str = "342deb400e191f0f52c81f27600934552550beb85aa9bf169f02d0e7f826cf74";
353 const GOLDEN_INVITE_KEY: &str = "94bf8b0d89e579ddaeccf8d9db3f5de5c86a1259c597f2560ff0120173bc5e1f";
354 const GOLDEN_VOICE_MEDIA_E0: &str = "8ab5b935c5e17f156563860ae6263f3700bfd836c326f8b3d7082be2fbaef6a0";
355 const GOLDEN_VOICE_SIGNER_E0_PK: &str = "7591f1306c265ee1dce6a07b72c76fadb3af13bf9ccce0d284cb3af6134211a1";
356 const GOLDEN_VOICE_SENDER: &str = "9ce1c11a39ce16a84b72c2697724a39e5c41ec07f4d703dcb01241271837599e";
357 const GOLDEN_COMMUNITY_ID: &str = "2b790bd59df98bdc52092b74ebd6933a89ef8eaeecc9030861cbdeae7c814c46";
358 const GOLDEN_EPOCH_COMMITMENT: &str = "3e6d6a3c9973c16d1ca7c5602d36979927c55c21a7e2c840f883af3f047e80a4";
359
360 fn hex(bytes: &[u8]) -> String {
361 crate::simd::hex::bytes_to_hex_32(bytes.try_into().expect("32 bytes"))
362 }
363
364 #[test]
365 fn channel_group_key_golden_vector() {
366 let gk = channel_group_key(&secret(), &chan(), Epoch(0));
367 assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CHANNEL_E0_SEED);
370 assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_E0_PK);
371 }
372
373 #[test]
374 fn channel_group_key_golden_multibyte_epoch_is_big_endian() {
375 let gk = channel_group_key(&secret(), &chan(), Epoch(EPOCH_MULTI));
376 assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_EMULTI_PK);
377 }
378
379 #[test]
380 fn control_group_key_golden_vector() {
381 assert_eq!(control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_CONTROL_E0_PK);
382 }
383
384 #[test]
385 fn guestbook_group_key_golden_vector() {
386 assert_eq!(guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_GUESTBOOK_E0_PK);
387 }
388
389 #[test]
390 fn rekey_group_keys_golden_vectors() {
391 assert_eq!(
392 channel_rekey_group_key(&secret(), &chan(), Epoch(1)).pk_hex(),
393 GOLDEN_CHANNEL_REKEY_E1_PK
394 );
395 assert_eq!(
396 base_rekey_group_key(&secret(), &cid(), Epoch(1)).pk_hex(),
397 GOLDEN_BASE_REKEY_E1_PK
398 );
399 }
400
401 #[test]
402 fn dissolved_group_key_golden_and_is_epoch_free() {
403 assert_eq!(dissolved_group_key(&cid()).pk_hex(), GOLDEN_DISSOLVED_PK);
404 let with_epoch = GroupKey::derive(LABEL_DISSOLVED, &cid().0, &ZERO32, Some(0));
407 assert_ne!(with_epoch.pk_hex(), GOLDEN_DISSOLVED_PK);
408 }
409
410 #[test]
411 fn locator_golden_vectors() {
412 assert_eq!(hex(&grant_locator(&cid(), &alt())), GOLDEN_GRANT_LOCATOR);
413 assert_eq!(hex(&banlist_locator(&cid())), GOLDEN_BANLIST_LOCATOR);
414 assert_eq!(hex(&invite_links_locator(&cid(), &alt())), GOLDEN_INVITE_LINKS_LOCATOR);
415 assert_eq!(
416 hex(&recipient_locator(&secret(), &alt(), &id32(), Epoch(3))),
417 GOLDEN_RECIPIENT_LOCATOR
418 );
419 assert_eq!(hex(&invite_bundle_key(&[0x07u8; TOKEN_LEN])), GOLDEN_INVITE_KEY);
420 }
421
422 #[test]
423 fn voice_golden_vectors() {
424 let media = voice_media_key(&secret(), &chan(), Epoch(0));
425 assert_eq!(hex(&media), GOLDEN_VOICE_MEDIA_E0);
426 assert_eq!(voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_VOICE_SIGNER_E0_PK);
427 assert_eq!(
428 hex(&voice_sender_key(&media, "00112233445566778899aabbccddeeff")),
429 GOLDEN_VOICE_SENDER
430 );
431 }
432
433 #[test]
434 fn community_id_golden_and_verifies() {
435 let id = community_id_of(&secret(), &alt());
436 assert_eq!(hex(&id.0), GOLDEN_COMMUNITY_ID);
437 assert!(verify_community_id(&id, &secret(), &alt()));
438 assert!(!verify_community_id(&id, &alt(), &alt()));
440 assert!(!verify_community_id(&id, &secret(), &id32()));
441 }
442
443 #[test]
444 fn epoch_key_commitment_golden_and_binds_both_inputs() {
445 assert_eq!(hex(&epoch_key_commitment(Epoch(2), &secret())), GOLDEN_EPOCH_COMMITMENT);
446 assert_ne!(hex(&epoch_key_commitment(Epoch(3), &secret())), GOLDEN_EPOCH_COMMITMENT);
447 assert_ne!(hex(&epoch_key_commitment(Epoch(2), &alt())), GOLDEN_EPOCH_COMMITMENT);
448 }
449
450 #[test]
451 fn labels_domain_separate_every_plane() {
452 let pks = [
455 channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
456 control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
457 guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
458 channel_rekey_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
459 base_rekey_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
460 voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
461 ];
462 let unique: std::collections::HashSet<_> = pks.iter().collect();
463 assert_eq!(unique.len(), pks.len(), "two labels collided on one address");
464 }
465
466 #[test]
467 fn epoch_rotates_every_keyed_address() {
468 assert_ne!(
469 channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
470 channel_group_key(&secret(), &chan(), Epoch(1)).pk_hex()
471 );
472 assert_ne!(
473 control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
474 control_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
475 );
476 assert_ne!(
477 guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
478 guestbook_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
479 );
480 }
481
482 #[test]
483 fn recipient_locator_binds_direction_scope_and_epoch() {
484 let base = recipient_locator(&secret(), &alt(), &id32(), Epoch(1));
485 assert_ne!(recipient_locator(&alt(), &secret(), &id32(), Epoch(1)), base);
487 assert_ne!(recipient_locator(&secret(), &alt(), &id32(), Epoch(2)), base);
488 assert_ne!(recipient_locator(&secret(), &alt(), &ZERO32, Epoch(1)), base);
489 }
490
491 #[test]
492 fn conv_key_is_deterministic_self_ecdh() {
493 let a = channel_group_key(&secret(), &chan(), Epoch(0));
494 let b = channel_group_key(&secret(), &chan(), Epoch(0));
495 assert_eq!(a.conv_key().as_bytes(), b.conv_key().as_bytes());
496 }
497}