Skip to main content

vector_core/community/v2/
derive.rs

1//! Concord v2 key derivations — CORD-02 Appendix A. **FROZEN.**
2//!
3//! Everything v2 addresses on the wire derives from a Community secret through
4//! one of the shapes below; changing any labeled byte re-addresses every prior
5//! event ("a breaking change re-labels and becomes a different universe").
6//! The layout is locked by the golden vectors in the test module — minted by an
7//! independent implementation — treat those as the spec.
8//!
9//! Construction (A.1): `HKDF-SHA256(ikm=secret, salt=∅, info, L=32)` where
10//! `info = utf8(label) || 0x00 || id[32] || epoch_be[8]?`
11//!   - `id` is ALWAYS present: 32 raw bytes, all-zeroes where a label has no
12//!     meaningful id.
13//!   - the epoch (u64 big-endian) is the ONLY omittable field: labels marked
14//!     no-epoch omit the 8 bytes entirely.
15//!   - the `scalar_normalize` retry counter (A.3) appends AFTER whatever fields
16//!     are present, starting at byte value 0. (v1's equivalent starts its retry
17//!     byte at 1 — the two conventions differ only in a ~2⁻¹²⁸ branch, but v2
18//!     follows the spec exactly.)
19//!
20//! These are DISTINCT from v1's `vector-community/v1/*` labels — the two
21//! protocols are different address universes by construction. The one label the
22//! specs share is the edition hash (`vector-community/v1/edition`,
23//! `community::version::EDITION_LABEL`), which upstream froze verbatim.
24
25use hkdf::Hkdf;
26use nostr_sdk::prelude::nip44::v2::ConversationKey;
27use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
28use sha2::{Digest, Sha256};
29
30use super::super::{ChannelId, CommunityId, Epoch};
31
32/// A.6 purpose labels. Part of the wire format — append, never edit or reuse.
33const LABEL_CHANNEL: &str = "concord/channel";
34const LABEL_CONTROL: &str = "concord/control";
35const LABEL_CONTROL_SIGNER: &str = "concord/control-signer";
36const LABEL_REKEY_PSEUDONYM: &str = "concord/rekey-pseudonym";
37const LABEL_BASE_REKEY_PSEUDONYM: &str = "concord/base-rekey-pseudonym";
38const LABEL_RECIPIENT_PSEUDONYM: &str = "concord/recipient-pseudonym";
39const LABEL_GUESTBOOK: &str = "concord/guestbook";
40const LABEL_VOICE_SIGNER: &str = "concord/voice-signer";
41const LABEL_VOICE_MEDIA: &str = "concord/voice-media";
42const LABEL_VOICE_SENDER: &str = "concord/voice-sender";
43const LABEL_DISSOLVED: &str = "concord/dissolved";
44const LABEL_GRANT: &str = "concord/grant";
45const LABEL_BANLIST: &str = "concord/banlist";
46const LABEL_PINS: &str = "concord/pins";
47const LABEL_INVITE_LINKS: &str = "concord/invite-links";
48const LABEL_INVITE_KEY: &str = "concord/invite-key";
49/// A.4 community_id commitment prefix — plain SHA-256, NOT the hkdf shape.
50const LABEL_COMMUNITY: &str = "concord/community";
51/// A.5 epoch-key commitment prefix — plain SHA-256.
52const LABEL_EPOCH_COMMITMENT: &str = "concord/epoch-key-commitment";
53
54const ZERO32: [u8; 32] = [0u8; 32];
55
56/// The size of a public-invite unlock token (CORD-05 §2) — 16 bytes in v2
57/// (v1 tokens were 32).
58pub const TOKEN_LEN: usize = 16;
59
60/// Build the frozen A.1 `info` byte string. `epoch` is `None` for the no-epoch
61/// labels (grant/banlist/invite-links/invite-key/dissolved/voice-sender).
62fn build_info(label: &str, id32: &[u8; 32], epoch: Option<u64>) -> Vec<u8> {
63    let mut info = Vec::with_capacity(label.len() + 1 + 32 + 8);
64    info.extend_from_slice(label.as_bytes());
65    info.push(0x00);
66    info.extend_from_slice(id32);
67    if let Some(e) = epoch {
68        info.extend_from_slice(&e.to_be_bytes());
69    }
70    info
71}
72
73/// HKDF-SHA256 to 32 bytes with a zero-length salt (RFC 5869: identical PRK to
74/// a 32-zero-byte salt under HMAC-SHA256). `ikm` length varies by caller: 32
75/// for keys/ids, 64 for the recipient-locator pair, 16 for an invite token.
76fn hkdf32(ikm: &[u8], info: &[u8]) -> [u8; 32] {
77    let hk = Hkdf::<Sha256>::new(None, ikm);
78    let mut okm = [0u8; 32];
79    hk.expand(info, &mut okm)
80        .expect("HKDF expand of 32 bytes is infallible");
81    okm
82}
83
84/// A.3 `scalar_normalize`: reduce an hkdf seed to a valid secp256k1 secret key.
85/// First attempt carries NO counter byte; on rejection append one incrementing
86/// counter byte to the info and retry, the counter starting at 0. The reject
87/// branch is ~2⁻¹²⁸ rare; the counter keeps it deterministic cross-impl.
88fn hkdf_to_secret_key(ikm: &[u8], base_info: &[u8]) -> SecretKey {
89    if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, base_info)) {
90        return sk;
91    }
92    for counter in 0u8..=255 {
93        let mut info = base_info.to_vec();
94        info.push(counter);
95        if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, &info)) {
96            return sk;
97        }
98    }
99    unreachable!("secp256k1 scalar rejection 257 times running is impossible")
100}
101
102/// A.2 `group_key` — a plane's stream keypair. The x-only pubkey is the on-wire
103/// Stream address (the `authors` filter), the secret key signs the plane's
104/// wraps, and the NIP-44 self-ECDH conversation key encrypts them. Only a
105/// holder of the deriving secret can produce any of the three, so only members
106/// can even *identify* a plane's traffic.
107#[derive(Clone)]
108pub struct GroupKey {
109    keys: Keys,
110    conv_key: ConversationKey,
111}
112
113impl GroupKey {
114    /// Assemble a SPLIT write group (CORD-01 Write-Restricted Streams): the
115    /// control_root-derived signer keypair paired with the community_root-derived
116    /// read conv_key. Only the Control Plane composes keys this way — every
117    /// other plane's signer and conv_key come from one derivation.
118    pub(crate) fn from_parts(keys: Keys, conv_key: ConversationKey) -> Self {
119        GroupKey { keys, conv_key }
120    }
121
122    fn derive(label: &str, secret: &[u8], id32: &[u8; 32], epoch: Option<u64>) -> Self {
123        let info = build_info(label, id32, epoch);
124        let sk = hkdf_to_secret_key(secret, &info);
125        let keys = Keys::new(sk);
126        let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key())
127            .expect("self-ECDH of a valid keypair cannot fail");
128        GroupKey { keys, conv_key }
129    }
130
131    /// The Stream address (x-only pubkey) — what `authors` filters match.
132    pub fn pk(&self) -> PublicKey {
133        self.keys.public_key()
134    }
135
136    /// The Stream address as lowercase hex.
137    pub fn pk_hex(&self) -> String {
138        self.keys.public_key().to_hex()
139    }
140
141    /// The keypair that signs this plane's wraps.
142    pub fn keys(&self) -> &Keys {
143        &self.keys
144    }
145
146    /// The NIP-44 conversation key (self-ECDH) that encrypts this plane's wraps.
147    pub fn conv_key(&self) -> &ConversationKey {
148        &self.conv_key
149    }
150}
151
152impl std::fmt::Debug for GroupKey {
153    // No key material in logs — address only.
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.debug_struct("GroupKey").field("pk", &self.pk_hex()).finish()
156    }
157}
158
159// ── Plane keys (CORD-02 §5, CORD-03 §1, CORD-06 §2) ─────────────────────────
160
161/// A Channel's Chat Plane group key. `secret` is the `community_root` for a
162/// Public Channel (at the root epoch) or the Channel's independent key for a
163/// Private one (at its own channel epoch) — CORD-03 §1. The channel id in the
164/// derivation gives every Channel a distinct address regardless of which secret
165/// feeds it.
166pub fn channel_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
167    GroupKey::derive(LABEL_CHANNEL, secret, &channel_id.0, Some(epoch.0))
168}
169
170/// The Control Plane's community_root-keyed group key (CORD-02 §5).
171///
172/// Post-split this is the plane's READ key: its conv_key encrypts the wraps for
173/// every member. On a LEGACY (pre-split) epoch the same derivation was the whole
174/// plane — its pk the address and wrap signer too — retained for reading such
175/// epochs; the two schemes never collide (different labels, different addresses).
176pub fn control_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
177    GroupKey::derive(LABEL_CONTROL, community_root, &community_id.0, Some(epoch.0))
178}
179
180/// The Control Plane's control_root-keyed SIGNER keypair (CORD-02 §2/§5): its pk
181/// is the plane's address, its staff-only sk signs the wraps. Every member holds
182/// the derived `control_pk` (delivered, never derived — only the owner and staff
183/// hold the `control_root` input); wrap content encrypts under
184/// [`control_group_key`]'s conv_key, not this one's.
185pub fn control_signer_group_key(control_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
186    GroupKey::derive(LABEL_CONTROL_SIGNER, control_root, &community_id.0, Some(epoch.0))
187}
188
189/// The Guestbook Plane's group key (community_root-keyed, community-id-bound).
190pub fn guestbook_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
191    GroupKey::derive(LABEL_GUESTBOOK, community_root, &community_id.0, Some(epoch.0))
192}
193
194/// A private Channel's rekey address for `new_epoch`, keyed by the
195/// community_root the receiver already holds (CORD-06 §2) — root-keyed, not
196/// channel-keyed, so any member recovers any epoch's rekey directly (no
197/// ratchet; epochs stay independently recoverable).
198pub fn channel_rekey_group_key(root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
199    GroupKey::derive(LABEL_REKEY_PSEUDONYM, root, &channel_id.0, Some(new_epoch.0))
200}
201
202/// The base-rotation rekey address for `new_epoch`, keyed by the PRIOR
203/// community_root — the base has no stable key above it, so the prior root is
204/// the one handle every retained member holds through the rotation (CORD-06 §2/§3).
205pub fn base_rekey_group_key(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
206    GroupKey::derive(LABEL_BASE_REKEY_PSEUDONYM, prior_root, &community_id.0, Some(new_epoch.0))
207}
208
209/// The dissolution tombstone's group key — derived from the community_id ALONE
210/// (no key, no epoch), so every member past or present resolves the same
211/// address and a Refounding can never strand the grave (CORD-02 §9).
212pub fn dissolved_group_key(community_id: &CommunityId) -> GroupKey {
213    GroupKey::derive(LABEL_DISSOLVED, &community_id.0, &ZERO32, None)
214}
215
216// ── Voice sub-keys (CORD-07 §1/§3 — Vector defers voice; derivations frozen
217//    now so the registry can't drift) ─────────────────────────────────────────
218
219/// A voice Channel's SFU room keypair: `pk` IS the room name, `sk` signs token
220/// grants. Same (secret, epoch) pair that addresses the Channel's Chat Plane,
221/// so the room rolls exactly when the Channel's key does.
222pub fn voice_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
223    GroupKey::derive(LABEL_VOICE_SIGNER, secret, &channel_id.0, Some(epoch.0))
224}
225
226/// A voice Channel's raw 32-byte media-encryption root — never feeds a cipher
227/// directly, every publisher's per-sender frame key derives from it.
228pub fn voice_media_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> [u8; 32] {
229    hkdf32(secret, &build_info(LABEL_VOICE_MEDIA, &channel_id.0, Some(epoch.0)))
230}
231
232/// A publisher's per-sender frame key material:
233/// `hkdf(voice_media_key, "concord/voice-sender", sha256(utf8(identity)))` —
234/// epoch omitted, the media key already carries it. Distinct per-sender keys
235/// partition the AEAD nonce domains.
236pub fn voice_sender_key(media_key: &[u8; 32], identity: &str) -> [u8; 32] {
237    let id: [u8; 32] = Sha256::digest(identity.as_bytes()).into();
238    hkdf32(media_key, &build_info(LABEL_VOICE_SENDER, &id, None))
239}
240
241// ── Keyless coordinates (32-byte edition locators; community-id-bound so they
242//    survive every Refounding — CORD-04 §1) ──────────────────────────────────
243
244/// A member's Grant entity coordinate (the edition `eid`).
245pub fn grant_locator(community_id: &CommunityId, member_xonly: &[u8; 32]) -> [u8; 32] {
246    hkdf32(&community_id.0, &build_info(LABEL_GRANT, member_xonly, None))
247}
248
249/// The community-wide Banlist coordinate.
250pub fn banlist_locator(community_id: &CommunityId) -> [u8; 32] {
251    hkdf32(&community_id.0, &build_info(LABEL_BANLIST, &ZERO32, None))
252}
253
254/// A Channel's Pin List coordinate (CORD-04 §7).
255pub fn pins_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
256    hkdf32(&community_id.0, &build_info(LABEL_PINS, &channel_id.0, None))
257}
258
259/// A creator's invite-link Registry coordinate (CORD-05 §5) — bound to the
260/// creator so each creator owns exactly their own list.
261pub fn invite_links_locator(community_id: &CommunityId, creator_xonly: &[u8; 32]) -> [u8; 32] {
262    hkdf32(&community_id.0, &build_info(LABEL_INVITE_LINKS, creator_xonly, None))
263}
264
265/// A rekey blob's per-recipient locator (CORD-06 §2):
266/// `hkdf(rotator_xonly || recipient_xonly, "concord/recipient-pseudonym", scope_id, new_epoch)`.
267///
268/// Derived from PUBLIC inputs on purpose (full NIP-46 bunker parity, no raw-key
269/// access) — which means a locator match proves NOTHING. It is a lookup index
270/// only; authenticity rests on the rotator's seal + authority check and the
271/// blob's bound plaintext (D1 security relocation — never port v1's
272/// locator-match-⇒-authentic assumption).
273pub fn recipient_locator(
274    rotator_xonly: &[u8; 32],
275    recipient_xonly: &[u8; 32],
276    scope_id: &[u8; 32],
277    new_epoch: Epoch,
278) -> [u8; 32] {
279    let mut ikm = [0u8; 64];
280    ikm[..32].copy_from_slice(rotator_xonly);
281    ikm[32..].copy_from_slice(recipient_xonly);
282    hkdf32(&ikm, &build_info(LABEL_RECIPIENT_PSEUDONYM, scope_id, Some(new_epoch.0)))
283}
284
285/// The public-invite bundle decrypt key, derived from the link's 16-byte
286/// unlock token alone (CORD-05 §2).
287pub fn invite_bundle_key(token: &[u8; TOKEN_LEN]) -> [u8; 32] {
288    hkdf32(token, &build_info(LABEL_INVITE_KEY, &ZERO32, None))
289}
290
291// ── A.4: the self-certifying community_id ────────────────────────────────────
292
293/// `community_id = sha256("concord/community" || owner_xonly || owner_salt)` —
294/// a plain SHA-256 commitment, NOT the hkdf shape. Ownership is a property of
295/// the id itself: forging a different owner onto an existing id is a
296/// second-preimage on SHA-256. (This is the root fix for the v1 forgeable
297/// owner-attestation anchor.)
298pub fn community_id_of(owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> CommunityId {
299    let mut h = Sha256::new();
300    h.update(LABEL_COMMUNITY.as_bytes());
301    h.update(owner_xonly);
302    h.update(owner_salt);
303    CommunityId(h.finalize().into())
304}
305
306/// Verify a claimed `(owner, salt)` pair reproduces `community_id`. Every
307/// bundle, pointer, and rehydrate path MUST pass this before trusting a claimed
308/// owner.
309pub fn verify_community_id(community_id: &CommunityId, owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> bool {
310    community_id_of(owner_xonly, owner_salt) == *community_id
311}
312
313// ── A.5: the epoch-key commitment ────────────────────────────────────────────
314
315/// `sha256("concord/epoch-key-commitment" || prev_epoch_be[8] || prev_key[32])`
316/// — the `prevcommit` continuity check on every rekey (CORD-06 §2). A
317/// convergence mechanism, never a secrecy one.
318pub fn epoch_key_commitment(prev_epoch: Epoch, prev_key: &[u8; 32]) -> [u8; 32] {
319    let mut h = Sha256::new();
320    h.update(LABEL_EPOCH_COMMITMENT.as_bytes());
321    h.update(prev_epoch.0.to_be_bytes());
322    h.update(prev_key);
323    h.finalize().into()
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    // Fixed test inputs. The golden hex below was produced by an INDEPENDENT
331    // implementation (Python: hmac+hashlib RFC 5869 HKDF, and pure-integer
332    // secp256k1 point math for the x-only pubkeys), so a match proves the
333    // construction — including the secp keypair step — is correct
334    // cross-implementation, not merely self-consistent. If any of these
335    // assertions ever change, the wire format changed — that must be a
336    // conscious, versioned decision.
337    fn secret() -> [u8; 32] {
338        // 0x00,0x01,..,0x1f
339        let mut k = [0u8; 32];
340        for (i, b) in k.iter_mut().enumerate() {
341            *b = i as u8;
342        }
343        k
344    }
345
346    fn id32() -> [u8; 32] {
347        // 0xff,0xfe,..,0xe0
348        let mut id = [0u8; 32];
349        for (i, b) in id.iter_mut().enumerate() {
350            *b = (255 - i) as u8;
351        }
352        id
353    }
354
355    fn alt() -> [u8; 32] {
356        [0x11u8; 32]
357    }
358
359    fn cid() -> CommunityId {
360        CommunityId(id32())
361    }
362
363    fn chan() -> ChannelId {
364        ChannelId(id32())
365    }
366
367    /// A multibyte epoch whose big-endian bytes are order-revealing.
368    const EPOCH_MULTI: u64 = 0x0102030405060708;
369
370    const GOLDEN_CHANNEL_E0_SEED: &str = "1a99a5958bf9fcc5336e6e19db42aabf36ffbfa12f38a1d5fbde2ae383ed751b";
371    const GOLDEN_CHANNEL_E0_PK: &str = "7a5c5dff759a63f1fc2779864487432bae3d1ea72c4ffabd39f4c1fdaf62097a";
372    const GOLDEN_CHANNEL_EMULTI_PK: &str = "f20c7d192cc87615d7341e86f38f85303f4708b40232d4fea521ab8217767391";
373    const GOLDEN_CONTROL_E0_PK: &str = "c43df20bf4d6eeaea5149619662ffe9b211f31e11bb4a59f56b6e906f702d46f";
374    const GOLDEN_CONTROL_SIGNER_E0_SEED: &str = "c4a3e8354d95137132087356412b67b53e025d127d45de45cff9ecf45b0c24f6";
375    const GOLDEN_CONTROL_SIGNER_E0_PK: &str = "718aef388257f3fd9f1bfae5cf2cbd0594a2ffc31adb5c1fe22c502c046acaee";
376    const GOLDEN_CONTROL_SIGNER_EMULTI_PK: &str = "e27235cc13be2f9ad65648e01ff2b63402846469c8638b5386c625688194ec7d";
377    const GOLDEN_GUESTBOOK_E0_PK: &str = "ad09de582026fa7a052db18bb5827fa24c15e929d59aadcc91efb8508f5368ad";
378    const GOLDEN_CHANNEL_REKEY_E1_PK: &str = "7c55cdb957e9db2b4800d687b2a07d3f7066b1a35824a1e86ba871f55e87e8b5";
379    const GOLDEN_BASE_REKEY_E1_PK: &str = "fb2fa44fba66ba15595f784255a1cb569531db8784432ac0e4fe838498dd9dea";
380    const GOLDEN_DISSOLVED_PK: &str = "4d3d55d88fdf9d9c2089651e5cbb0dfa93b6b9b10cdcb2319b0dce1a1398096a";
381    const GOLDEN_GRANT_LOCATOR: &str = "fd2f88cc7f1eb8d7d862c91dc22afe700c358d1845158b3f353b769ce4898e35";
382    const GOLDEN_BANLIST_LOCATOR: &str = "88089214afae6d3c412fd817ada44d6df4d485a53565646471e74476397693c9";
383    const GOLDEN_INVITE_LINKS_LOCATOR: &str = "f4ae29994165767bac23e8dce630f81b926d2c8aa150e5cbf0bdf75865e8379a";
384    const GOLDEN_RECIPIENT_LOCATOR: &str = "342deb400e191f0f52c81f27600934552550beb85aa9bf169f02d0e7f826cf74";
385    const GOLDEN_INVITE_KEY: &str = "94bf8b0d89e579ddaeccf8d9db3f5de5c86a1259c597f2560ff0120173bc5e1f";
386    const GOLDEN_VOICE_MEDIA_E0: &str = "8ab5b935c5e17f156563860ae6263f3700bfd836c326f8b3d7082be2fbaef6a0";
387    const GOLDEN_VOICE_SIGNER_E0_PK: &str = "7591f1306c265ee1dce6a07b72c76fadb3af13bf9ccce0d284cb3af6134211a1";
388    const GOLDEN_VOICE_SENDER: &str = "9ce1c11a39ce16a84b72c2697724a39e5c41ec07f4d703dcb01241271837599e";
389    const GOLDEN_COMMUNITY_ID: &str = "2b790bd59df98bdc52092b74ebd6933a89ef8eaeecc9030861cbdeae7c814c46";
390    const GOLDEN_EPOCH_COMMITMENT: &str = "3e6d6a3c9973c16d1ca7c5602d36979927c55c21a7e2c840f883af3f047e80a4";
391
392    fn hex(bytes: &[u8]) -> String {
393        crate::simd::hex::bytes_to_hex_32(bytes.try_into().expect("32 bytes"))
394    }
395
396    #[test]
397    fn channel_group_key_golden_vector() {
398        let gk = channel_group_key(&secret(), &chan(), Epoch(0));
399        // The hkdf seed is a valid scalar (overwhelming case), so sk == seed —
400        // pinning both proves hkdf AND the secp keypair step.
401        assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CHANNEL_E0_SEED);
402        assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_E0_PK);
403    }
404
405    #[test]
406    fn channel_group_key_golden_multibyte_epoch_is_big_endian() {
407        let gk = channel_group_key(&secret(), &chan(), Epoch(EPOCH_MULTI));
408        assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_EMULTI_PK);
409    }
410
411    #[test]
412    fn control_group_key_golden_vector() {
413        assert_eq!(control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_CONTROL_E0_PK);
414    }
415
416    #[test]
417    fn control_signer_group_key_golden_vectors() {
418        // Same fixed inputs as the control read key, different label — the split's
419        // signer address must land elsewhere (CORD-02 §5: the two never collide).
420        let gk = control_signer_group_key(&secret(), &cid(), Epoch(0));
421        assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CONTROL_SIGNER_E0_SEED);
422        assert_eq!(gk.pk_hex(), GOLDEN_CONTROL_SIGNER_E0_PK);
423        assert_ne!(gk.pk_hex(), GOLDEN_CONTROL_E0_PK);
424        assert_eq!(
425            control_signer_group_key(&secret(), &cid(), Epoch(EPOCH_MULTI)).pk_hex(),
426            GOLDEN_CONTROL_SIGNER_EMULTI_PK
427        );
428    }
429
430    #[test]
431    fn guestbook_group_key_golden_vector() {
432        assert_eq!(guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_GUESTBOOK_E0_PK);
433    }
434
435    #[test]
436    fn rekey_group_keys_golden_vectors() {
437        assert_eq!(
438            channel_rekey_group_key(&secret(), &chan(), Epoch(1)).pk_hex(),
439            GOLDEN_CHANNEL_REKEY_E1_PK
440        );
441        assert_eq!(
442            base_rekey_group_key(&secret(), &cid(), Epoch(1)).pk_hex(),
443            GOLDEN_BASE_REKEY_E1_PK
444        );
445    }
446
447    #[test]
448    fn dissolved_group_key_golden_and_is_epoch_free() {
449        assert_eq!(dissolved_group_key(&cid()).pk_hex(), GOLDEN_DISSOLVED_PK);
450        // Epoch omission is real omission, not epoch=0: a manual derivation WITH
451        // an epoch field of 0 must land elsewhere.
452        let with_epoch = GroupKey::derive(LABEL_DISSOLVED, &cid().0, &ZERO32, Some(0));
453        assert_ne!(with_epoch.pk_hex(), GOLDEN_DISSOLVED_PK);
454    }
455
456    #[test]
457    fn locator_golden_vectors() {
458        assert_eq!(hex(&grant_locator(&cid(), &alt())), GOLDEN_GRANT_LOCATOR);
459        assert_eq!(hex(&banlist_locator(&cid())), GOLDEN_BANLIST_LOCATOR);
460        assert_eq!(hex(&invite_links_locator(&cid(), &alt())), GOLDEN_INVITE_LINKS_LOCATOR);
461        assert_eq!(
462            hex(&recipient_locator(&secret(), &alt(), &id32(), Epoch(3))),
463            GOLDEN_RECIPIENT_LOCATOR
464        );
465        assert_eq!(hex(&invite_bundle_key(&[0x07u8; TOKEN_LEN])), GOLDEN_INVITE_KEY);
466    }
467
468    #[test]
469    fn voice_golden_vectors() {
470        let media = voice_media_key(&secret(), &chan(), Epoch(0));
471        assert_eq!(hex(&media), GOLDEN_VOICE_MEDIA_E0);
472        assert_eq!(voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_VOICE_SIGNER_E0_PK);
473        assert_eq!(
474            hex(&voice_sender_key(&media, "00112233445566778899aabbccddeeff")),
475            GOLDEN_VOICE_SENDER
476        );
477    }
478
479    #[test]
480    fn community_id_golden_and_verifies() {
481        let id = community_id_of(&secret(), &alt());
482        assert_eq!(hex(&id.0), GOLDEN_COMMUNITY_ID);
483        assert!(verify_community_id(&id, &secret(), &alt()));
484        // Wrong owner or wrong salt must fail the commitment.
485        assert!(!verify_community_id(&id, &alt(), &alt()));
486        assert!(!verify_community_id(&id, &secret(), &id32()));
487    }
488
489    #[test]
490    fn epoch_key_commitment_golden_and_binds_both_inputs() {
491        assert_eq!(hex(&epoch_key_commitment(Epoch(2), &secret())), GOLDEN_EPOCH_COMMITMENT);
492        assert_ne!(hex(&epoch_key_commitment(Epoch(3), &secret())), GOLDEN_EPOCH_COMMITMENT);
493        assert_ne!(hex(&epoch_key_commitment(Epoch(2), &alt())), GOLDEN_EPOCH_COMMITMENT);
494    }
495
496    #[test]
497    fn labels_domain_separate_every_plane() {
498        // One (secret, id, epoch) triple across every keyed label — all
499        // addresses must be pairwise distinct.
500        let pks = [
501            channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
502            control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
503            control_signer_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
504            guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
505            channel_rekey_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
506            base_rekey_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
507            voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
508        ];
509        let unique: std::collections::HashSet<_> = pks.iter().collect();
510        assert_eq!(unique.len(), pks.len(), "two labels collided on one address");
511    }
512
513    #[test]
514    fn epoch_rotates_every_keyed_address() {
515        assert_ne!(
516            channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
517            channel_group_key(&secret(), &chan(), Epoch(1)).pk_hex()
518        );
519        assert_ne!(
520            control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
521            control_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
522        );
523        assert_ne!(
524            guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
525            guestbook_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
526        );
527    }
528
529    #[test]
530    fn recipient_locator_binds_direction_scope_and_epoch() {
531        let base = recipient_locator(&secret(), &alt(), &id32(), Epoch(1));
532        // Rotator↔recipient direction matters (concatenation order).
533        assert_ne!(recipient_locator(&alt(), &secret(), &id32(), Epoch(1)), base);
534        assert_ne!(recipient_locator(&secret(), &alt(), &id32(), Epoch(2)), base);
535        assert_ne!(recipient_locator(&secret(), &alt(), &ZERO32, Epoch(1)), base);
536    }
537
538    #[test]
539    fn conv_key_is_deterministic_self_ecdh() {
540        let a = channel_group_key(&secret(), &chan(), Epoch(0));
541        let b = channel_group_key(&secret(), &chan(), Epoch(0));
542        assert_eq!(a.conv_key().as_bytes(), b.conv_key().as_bytes());
543    }
544}