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.
17//!
18//! The one `vector-community/v1/*` label still in use is the edition hash
19//! (`vector-community/v1/edition`, `community::version::EDITION_LABEL`), which
20//! upstream froze verbatim.
21
22use nostr_sdk::prelude::nip44::v2::ConversationKey;
23use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
24use sha2::{Digest, Sha256};
25
26use super::super::{ChannelId, CommunityId, Epoch};
27
28/// A.6 purpose labels. Part of the wire format — append, never edit or reuse.
29const LABEL_CHANNEL: &str = "concord/channel";
30const LABEL_CONTROL: &str = "concord/control";
31const LABEL_CONTROL_SIGNER: &str = "concord/control-signer";
32const LABEL_REKEY_PSEUDONYM: &str = "concord/rekey-pseudonym";
33const LABEL_BASE_REKEY_PSEUDONYM: &str = "concord/base-rekey-pseudonym";
34const LABEL_RECIPIENT_PSEUDONYM: &str = "concord/recipient-pseudonym";
35const LABEL_GUESTBOOK: &str = "concord/guestbook";
36const LABEL_CHANNEL_ACCESS: &str = "concord/channel-access";
37const LABEL_CHANNEL_WRITER: &str = "concord/channel-writer";
38const LABEL_VOICE_SIGNER: &str = "concord/voice-signer";
39const LABEL_VOICE_MEDIA: &str = "concord/voice-media";
40const LABEL_VOICE_SENDER: &str = "concord/voice-sender";
41const LABEL_DISSOLVED: &str = "concord/dissolved";
42const LABEL_GRANT: &str = "concord/grant";
43const LABEL_BANLIST: &str = "concord/banlist";
44const LABEL_PINS: &str = "concord/pins";
45const LABEL_INVITE_LINKS: &str = "concord/invite-links";
46const LABEL_EVERYONE: &str = "concord/everyone";
47const LABEL_TENURE: &str = "concord/tenure";
48const LABEL_ACL: &str = "concord/acl";
49const LABEL_SYNC: &str = "concord/sync";
50const LABEL_WRITERS: &str = "concord/writers";
51/// A restricted Channel's writer scope prefix — plain SHA-256.
52const LABEL_WRITER_SCOPE: &[u8] = b"concord/writer-scope";
53const LABEL_CERTIFIER_SCOPE: &[u8] = b"concord/certifier-scope";
54const LABEL_EDITION_BINDING: &str = "concord/edition-binding";
55const LABEL_INVITE_KEY: &str = "concord/invite-key";
56const LABEL_WRAP_OWNER: &str = "concord/wrap-owner";
57/// A.4 community_id commitment prefix — plain SHA-256, NOT the hkdf shape.
58const LABEL_COMMUNITY: &str = "concord/community";
59/// A.5 epoch-key commitment prefix — plain SHA-256.
60const LABEL_EPOCH_COMMITMENT: &str = "concord/epoch-key-commitment";
61
62const ZERO32: [u8; 32] = [0u8; 32];
63
64/// The size of a public-invite unlock token (CORD-05 §2).
65pub const TOKEN_LEN: usize = 16;
66
67/// Build the frozen A.1 `info` byte string. `epoch` is `None` for the no-epoch
68/// labels (grant/banlist/invite-links/invite-key/dissolved/voice-sender).
69fn build_info(label: &str, id32: &[u8; 32], epoch: Option<u64>) -> Vec<u8> {
70    let mut info = Vec::with_capacity(label.len() + 1 + 32 + 8);
71    info.extend_from_slice(label.as_bytes());
72    info.push(0x00);
73    info.extend_from_slice(id32);
74    if let Some(e) = epoch {
75        info.extend_from_slice(&e.to_be_bytes());
76    }
77    info
78}
79
80/// HKDF-SHA256 to 32 bytes with a zero-length salt (RFC 5869: identical PRK to
81/// a 32-zero-byte salt under HMAC-SHA256). `ikm` length varies by caller: 32
82/// for keys/ids, 64 for the recipient-locator pair, 16 for an invite token.
83fn hkdf32(ikm: &[u8], info: &[u8]) -> [u8; 32] {
84    // L = 32 is one expand block: T(1) = HMAC(PRK, info || 0x01).
85    let mut prk = crate::crypto::sha256::hmac(&[0u8; 32], &[ikm]);
86    let okm = crate::crypto::sha256::hmac(&prk, &[info, &[1]]);
87    zeroize::Zeroize::zeroize(&mut prk);
88    okm
89}
90
91/// A.3 `scalar_normalize`: reduce an hkdf seed to a valid secp256k1 secret key.
92/// First attempt carries NO counter byte; on rejection append one incrementing
93/// counter byte to the info and retry, the counter starting at 0. The reject
94/// branch is ~2⁻¹²⁸ rare; the counter keeps it deterministic cross-impl.
95fn hkdf_to_secret_key(ikm: &[u8], base_info: &[u8]) -> SecretKey {
96    if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, base_info)) {
97        return sk;
98    }
99    for counter in 0u8..=255 {
100        let mut info = base_info.to_vec();
101        info.push(counter);
102        if let Ok(sk) = SecretKey::from_slice(&hkdf32(ikm, &info)) {
103            return sk;
104        }
105    }
106    unreachable!("secp256k1 scalar rejection 257 times running is impossible")
107}
108
109/// A.2 `group_key` — a plane's stream keypair. The x-only pubkey is the on-wire
110/// Stream address (the `authors` filter), the secret key signs the plane's
111/// wraps, and the NIP-44 self-ECDH conversation key encrypts them. Only a
112/// holder of the deriving secret can produce any of the three, so only members
113/// can even *identify* a plane's traffic.
114#[derive(Clone)]
115pub struct GroupKey {
116    keys: Keys,
117    conv_key: ConversationKey,
118}
119
120/// Entries per generation of the session's [`GroupKey`] memo. Every held plane is one entry, and
121/// the live route table alone walks all of them, so the bound sits well above a large held set.
122const GROUP_KEY_MEMO_CAP: usize = 4096;
123
124/// The memo in two generations: a full `cur` ages into `prev` rather than being wiped, and a hit
125/// in `prev` moves back, so a working set within the bound never goes cold all at once.
126#[derive(Default)]
127struct GroupKeyMemo {
128    cur: std::collections::HashMap<[u8; 32], GroupKey>,
129    prev: std::collections::HashMap<[u8; 32], GroupKey>,
130}
131
132impl GroupKeyMemo {
133    fn get(&mut self, key: &[u8; 32]) -> Option<GroupKey> {
134        if let Some(hit) = self.cur.get(key) {
135            return Some(hit.clone());
136        }
137        let hit = self.prev.remove(key)?;
138        self.insert(*key, hit.clone());
139        Some(hit)
140    }
141
142    fn insert(&mut self, key: [u8; 32], value: GroupKey) {
143        if self.cur.len() >= GROUP_KEY_MEMO_CAP {
144            // A new table, not a cleared one: a runaway's allocation goes with its generation.
145            self.prev = std::mem::take(&mut self.cur);
146        }
147        self.cur.insert(key, value);
148    }
149}
150
151impl GroupKey {
152    /// Assemble a SPLIT write group (CORD-01 Write-Restricted Streams): the
153    /// control_root-derived signer keypair paired with the community_root-derived
154    /// read conv_key. Only the Control Plane composes keys this way — every
155    /// other plane's signer and conv_key come from one derivation.
156    pub(crate) fn from_parts(keys: Keys, conv_key: ConversationKey) -> Self {
157        GroupKey { keys, conv_key }
158    }
159
160    fn derive(label: &str, secret: &[u8], id32: &[u8; 32], epoch: Option<u64>) -> Self {
161        // Memoized: the HKDF is cheap, but Keys::new + the self-ECDH are two
162        // EC point-multiplies, and the dispatch trial re-paid them for every
163        // held community on every arriving wrap — a full core on a live
164        // evening. Pure function of its inputs, so the memo is exact; keyed
165        // by a digest so no input secret sits in the map, session-scoped so
166        // an account's derived keys die with its session. The digest itself runs
167        // per channel per arriving wrap, so it takes the hardware SHA-256 path.
168        let memo_key: [u8; 32] = {
169            let mut h = crate::crypto::sha256::Sha256::new();
170            h.update(label.as_bytes());
171            h.update([0u8]);
172            h.update(secret);
173            h.update(id32);
174            h.update(epoch.unwrap_or(u64::MAX).to_be_bytes());
175            h.update([epoch.is_some() as u8]);
176            h.finalize()
177        };
178        struct MemoKey;
179        type MemoMap = std::sync::Mutex<GroupKeyMemo>;
180        let memo: std::sync::Arc<MemoMap> = crate::db::current_session().scoped::<MemoKey, MemoMap>();
181        if let Some(hit) = memo.lock().unwrap_or_else(|e| e.into_inner()).get(&memo_key) {
182            return hit;
183        }
184        let info = build_info(label, id32, epoch);
185        let sk = hkdf_to_secret_key(secret, &info);
186        let keys = Keys::new(sk);
187        let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key())
188            .expect("self-ECDH of a valid keypair cannot fail");
189        let out = GroupKey { keys, conv_key };
190        memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, out.clone());
191        out
192    }
193
194    /// A plane's group key from its own secret, as a Channel's published history carries it
195    /// (CORD-03 §2). `None` for bytes that are no secret key.
196    pub(crate) fn from_secret(secret: &[u8; 32]) -> Option<Self> {
197        let keys = Keys::new(nostr_sdk::prelude::SecretKey::from_slice(secret).ok()?);
198        let conv_key = ConversationKey::derive(keys.secret_key(), &keys.public_key()).ok()?;
199        Some(GroupKey { keys, conv_key })
200    }
201
202    /// The plane's own secret, which opens and signs this plane and no other.
203    pub(crate) fn secret(&self) -> [u8; 32] {
204        self.keys.secret_key().to_secret_bytes()
205    }
206
207    /// The Stream address (x-only pubkey) — what `authors` filters match.
208    pub fn pk(&self) -> PublicKey {
209        self.keys.public_key()
210    }
211
212    /// The Stream address as lowercase hex.
213    pub fn pk_hex(&self) -> String {
214        self.keys.public_key().to_hex()
215    }
216
217    /// The keypair that signs this plane's wraps.
218    pub fn keys(&self) -> &Keys {
219        &self.keys
220    }
221
222    /// The NIP-44 conversation key (self-ECDH) that encrypts this plane's wraps.
223    pub fn conv_key(&self) -> &ConversationKey {
224        &self.conv_key
225    }
226}
227
228impl std::fmt::Debug for GroupKey {
229    // No key material in logs — address only.
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        f.debug_struct("GroupKey").field("pk", &self.pk_hex()).finish()
232    }
233}
234
235// ── Plane keys (CORD-02 §5, CORD-03 §1, CORD-06 §2) ─────────────────────────
236
237/// A Channel's Chat Plane group key. `secret` is the `community_root` for a
238/// Public Channel (at the root epoch) or the Channel's independent key for a
239/// Private one (at its own channel epoch) — CORD-03 §1. The channel id in the
240/// derivation gives every Channel a distinct address regardless of which secret
241/// feeds it.
242pub fn channel_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
243    GroupKey::derive(LABEL_CHANNEL, secret, &channel_id.0, Some(epoch.0))
244}
245
246/// The Control Plane's community_root-keyed group key (CORD-02 §5).
247///
248/// Post-split this is the plane's READ key: its conv_key encrypts the wraps for
249/// every member. On a LEGACY (pre-split) epoch the same derivation was the whole
250/// plane — its pk the address and wrap signer too — retained for reading such
251/// epochs; the two schemes never collide (different labels, different addresses).
252pub fn control_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
253    GroupKey::derive(LABEL_CONTROL, community_root, &community_id.0, Some(epoch.0))
254}
255
256/// The Control Plane's control_root-keyed SIGNER keypair (CORD-02 §2/§5): its pk
257/// is the plane's address, its staff-only sk signs the wraps. Every member holds
258/// the derived `control_pk` (delivered, never derived — only the owner and staff
259/// hold the `control_root` input); wrap content encrypts under
260/// [`control_group_key`]'s conv_key, not this one's.
261pub fn control_signer_group_key(control_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
262    GroupKey::derive(LABEL_CONTROL_SIGNER, control_root, &community_id.0, Some(epoch.0))
263}
264
265/// The Guestbook Plane's group key (community_root-keyed, community-id-bound).
266pub fn guestbook_group_key(community_root: &[u8; 32], community_id: &CommunityId, epoch: Epoch) -> GroupKey {
267    GroupKey::derive(LABEL_GUESTBOOK, community_root, &community_id.0, Some(epoch.0))
268}
269
270/// A restricted Channel's writer keypair for a writer epoch (CORD-03 §1): its public key is the
271/// address posts land at, its secret signs their wraps. The wraps stay encrypted to the
272/// Channel's read key.
273pub fn channel_writer_group_key(writer_secret: &[u8; 32], channel_id: &ChannelId, writer_epoch: Epoch) -> GroupKey {
274    GroupKey::derive(LABEL_CHANNEL_WRITER, writer_secret, &channel_id.0, Some(writer_epoch.0))
275}
276
277/// A Channel's access plane for the root epoch, where any key holder delivers the key to
278/// an entitled member who lacks it (CORD-03 §5).
279pub fn channel_access_group_key(community_root: &[u8; 32], channel_id: &ChannelId, root_epoch: Epoch) -> GroupKey {
280    GroupKey::derive(LABEL_CHANNEL_ACCESS, community_root, &channel_id.0, Some(root_epoch.0))
281}
282
283/// A private Channel's rekey address for `new_epoch`, keyed by the
284/// community_root the receiver already holds (CORD-06 §2) — root-keyed, not
285/// channel-keyed, so any member recovers any epoch's rekey directly (no
286/// ratchet; epochs stay independently recoverable).
287pub fn channel_rekey_group_key(root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
288    GroupKey::derive(LABEL_REKEY_PSEUDONYM, root, &channel_id.0, Some(new_epoch.0))
289}
290
291/// The base-rotation rekey address for `new_epoch`, keyed by the PRIOR
292/// community_root — the base has no stable key above it, so the prior root is
293/// the one handle every retained member holds through the rotation (CORD-06 §2/§3).
294pub fn base_rekey_group_key(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
295    GroupKey::derive(LABEL_BASE_REKEY_PSEUDONYM, prior_root, &community_id.0, Some(new_epoch.0))
296}
297
298/// The dissolution tombstone's group key — derived from the community_id ALONE
299/// (no key, no epoch), so every member past or present resolves the same
300/// address and a Refounding can never strand the grave (CORD-02 §9).
301pub fn dissolved_group_key(community_id: &CommunityId) -> GroupKey {
302    GroupKey::derive(LABEL_DISSOLVED, &community_id.0, &ZERO32, None)
303}
304
305// ── Voice sub-keys (CORD-07 §1/§3 — Vector defers voice; derivations frozen
306//    now so the registry can't drift) ─────────────────────────────────────────
307
308/// A voice Channel's SFU room keypair: `pk` IS the room name, `sk` signs token
309/// grants. Same (secret, epoch) pair that addresses the Channel's Chat Plane,
310/// so the room rolls exactly when the Channel's key does.
311pub fn voice_group_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> GroupKey {
312    GroupKey::derive(LABEL_VOICE_SIGNER, secret, &channel_id.0, Some(epoch.0))
313}
314
315/// A voice Channel's raw 32-byte media-encryption root — never feeds a cipher
316/// directly, every publisher's per-sender frame key derives from it.
317pub fn voice_media_key(secret: &[u8; 32], channel_id: &ChannelId, epoch: Epoch) -> [u8; 32] {
318    hkdf32(secret, &build_info(LABEL_VOICE_MEDIA, &channel_id.0, Some(epoch.0)))
319}
320
321/// A publisher's per-sender frame key material:
322/// `hkdf(voice_media_key, "concord/voice-sender", sha256(utf8(identity)))` —
323/// epoch omitted, the media key already carries it. Distinct per-sender keys
324/// partition the AEAD nonce domains.
325pub fn voice_sender_key(media_key: &[u8; 32], identity: &str) -> [u8; 32] {
326    let id: [u8; 32] = Sha256::digest(identity.as_bytes()).into();
327    hkdf32(media_key, &build_info(LABEL_VOICE_SENDER, &id, None))
328}
329
330// ── Keyless coordinates (32-byte edition locators; community-id-bound so they
331//    survive every Refounding — CORD-04 §1) ──────────────────────────────────
332
333/// A member's Grant entity coordinate (the edition `eid`).
334pub fn grant_locator(community_id: &CommunityId, member_xonly: &[u8; 32]) -> [u8; 32] {
335    // Memoized: every roster fold asks again for each grant, several times over.
336    #[derive(Default)]
337    struct Locators {
338        cur: std::collections::HashMap<[u8; 64], [u8; 32]>,
339        prev: std::collections::HashMap<[u8; 64], [u8; 32]>,
340    }
341    const GEN: usize = 8192;
342    let mut key = [0u8; 64];
343    key[..32].copy_from_slice(&community_id.0);
344    key[32..].copy_from_slice(member_xonly);
345    let memo = crate::db::current_session().scoped::<Locators, std::sync::Mutex<Locators>>();
346    let mut held = memo.lock().unwrap_or_else(|e| e.into_inner());
347    if let Some(hit) = held.cur.get(&key) {
348        return *hit;
349    }
350    let locator = match held.prev.remove(&key) {
351        Some(hit) => hit,
352        None => hkdf32(&community_id.0, &build_info(LABEL_GRANT, member_xonly, None)),
353    };
354    if held.cur.len() >= GEN {
355        held.prev = std::mem::take(&mut held.cur);
356    }
357    held.cur.insert(key, locator);
358    locator
359}
360
361/// The community-wide Banlist coordinate.
362pub fn banlist_locator(community_id: &CommunityId) -> [u8; 32] {
363    hkdf32(&community_id.0, &build_info(LABEL_BANLIST, &ZERO32, None))
364}
365
366/// The `@everyone` Role's coordinate (CORD-04 §2); an owner edition here activates Roles v2.
367pub fn everyone_locator(community_id: &CommunityId) -> [u8; 32] {
368    hkdf32(&community_id.0, &build_info(LABEL_EVERYONE, &ZERO32, None))
369}
370
371/// What a marked edition names to bind itself to its Community (CORD-02): derived, so the
372/// rumor never carries the `community_id` itself.
373pub fn edition_binding(community_id: &CommunityId) -> [u8; 32] {
374    hkdf32(&community_id.0, &build_info(LABEL_EDITION_BINDING, &ZERO32, None))
375}
376
377/// A member's Tenure from one writer (CORD-04 §9): each writer seals in an entity of their
378/// own, so nobody re-signs a standing another writer sealed.
379pub fn tenure_locator(community_id: &CommunityId, member_xonly: &[u8; 32], sealer_xonly: &[u8; 32]) -> [u8; 32] {
380    let pair: [u8; 32] = Sha256::new().chain_update(member_xonly).chain_update(sealer_xonly).finalize().into();
381    hkdf32(&community_id.0, &build_info(LABEL_TENURE, &pair, None))
382}
383
384/// One overwrite's coordinate (CORD-04 §8): a Channel or Category `scope` and the Role,
385/// member or `@everyone` locator it applies to. One entity per pair, so editors of
386/// different overwrites never race on one document.
387pub fn acl_locator(community_id: &CommunityId, scope: &[u8; 32], target: &[u8; 32]) -> [u8; 32] {
388    let pair: [u8; 32] = Sha256::new().chain_update(scope).chain_update(target).finalize().into();
389    hkdf32(&community_id.0, &build_info(LABEL_ACL, &pair, None))
390}
391
392/// A Channel's sync coordinate (CORD-04 §8).
393pub fn sync_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
394    hkdf32(&community_id.0, &build_info(LABEL_SYNC, &channel_id.0, None))
395}
396
397/// A restricted Channel's Writers ledger coordinate (CORD-03 §1).
398pub fn writers_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
399    hkdf32(&community_id.0, &build_info(LABEL_WRITERS, &channel_id.0, None))
400}
401
402/// What a Channel's writer blobs bind to (CORD-03 §1), so one is never a read key.
403pub fn writer_scope(channel_id: &ChannelId) -> [u8; 32] {
404    Sha256::new().chain_update(LABEL_WRITER_SCOPE).chain_update(channel_id.0).finalize().into()
405}
406
407/// What a Channel's writer certifier blobs bind to (CORD-03 §1): never a read or a writer key.
408pub fn certifier_scope(channel_id: &ChannelId) -> [u8; 32] {
409    Sha256::new().chain_update(LABEL_CERTIFIER_SCOPE).chain_update(channel_id.0).finalize().into()
410}
411
412/// A Channel's Pin List coordinate (CORD-04 §7).
413pub fn pins_locator(community_id: &CommunityId, channel_id: &ChannelId) -> [u8; 32] {
414    hkdf32(&community_id.0, &build_info(LABEL_PINS, &channel_id.0, None))
415}
416
417/// A creator's invite-link Registry coordinate (CORD-05 §5) — bound to the
418/// creator so each creator owns exactly their own list.
419pub fn invite_links_locator(community_id: &CommunityId, creator_xonly: &[u8; 32]) -> [u8; 32] {
420    hkdf32(&community_id.0, &build_info(LABEL_INVITE_LINKS, creator_xonly, None))
421}
422
423/// A rekey blob's per-recipient locator (CORD-06 §2):
424/// `hkdf(rotator_xonly || recipient_xonly, "concord/recipient-pseudonym", scope_id, new_epoch)`.
425///
426/// Derived from PUBLIC inputs on purpose (full NIP-46 bunker parity, no raw-key
427/// access) — which means a locator match proves NOTHING. It is a lookup index
428/// only; authenticity rests on the rotator's seal + authority check and the
429/// blob's bound plaintext (CORD-06 D1).
430pub fn recipient_locator(
431    rotator_xonly: &[u8; 32],
432    recipient_xonly: &[u8; 32],
433    scope_id: &[u8; 32],
434    new_epoch: Epoch,
435) -> [u8; 32] {
436    let mut ikm = [0u8; 64];
437    ikm[..32].copy_from_slice(rotator_xonly);
438    ikm[32..].copy_from_slice(recipient_xonly);
439    hkdf32(&ikm, &build_info(LABEL_RECIPIENT_PSEUDONYM, scope_id, Some(new_epoch.0)))
440}
441
442/// The public-invite bundle decrypt key, derived from the link's 16-byte
443/// unlock token alone (CORD-05 §2).
444pub fn invite_bundle_key(token: &[u8; TOKEN_LEN]) -> [u8; 32] {
445    hkdf32(token, &build_info(LABEL_INVITE_KEY, &ZERO32, None))
446}
447
448// ── CORD-01 §Deletions: the owner of an author's own wrap ────────────────────
449
450/// The `p` key of an author's own wrap at `address`, whose holder may delete the wrap
451/// (CORD-01 §Deletions): `hkdf(author_secret, "concord/wrap-owner", sha256(address || rumor_id))`.
452/// Every client holding the author's key derives it again, so any of them can delete any of
453/// the author's wraps; without that key it links the wrap to nobody.
454pub fn wrap_owner_key(author_secret: &[u8; 32], address: &PublicKey, rumor_id: &[u8; 32]) -> Keys {
455    let mut h = Sha256::new();
456    h.update(address.to_bytes());
457    h.update(rumor_id);
458    let id: [u8; 32] = h.finalize().into();
459    Keys::new(hkdf_to_secret_key(author_secret, &build_info(LABEL_WRAP_OWNER, &id, None)))
460}
461
462// ── A.4: the self-certifying community_id ────────────────────────────────────
463
464/// `community_id = sha256("concord/community" || owner_xonly || owner_salt)` —
465/// a plain SHA-256 commitment, NOT the hkdf shape. Ownership is a property of
466/// the id itself: forging a different owner onto an existing id is a
467/// second-preimage on SHA-256.
468pub fn community_id_of(owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> CommunityId {
469    let mut h = Sha256::new();
470    h.update(LABEL_COMMUNITY.as_bytes());
471    h.update(owner_xonly);
472    h.update(owner_salt);
473    CommunityId(h.finalize().into())
474}
475
476/// Verify a claimed `(owner, salt)` pair reproduces `community_id`. Every
477/// bundle, pointer, and rehydrate path MUST pass this before trusting a claimed
478/// owner.
479pub fn verify_community_id(community_id: &CommunityId, owner_xonly: &[u8; 32], owner_salt: &[u8; 32]) -> bool {
480    community_id_of(owner_xonly, owner_salt) == *community_id
481}
482
483// ── A.5: the epoch-key commitment ────────────────────────────────────────────
484
485/// `sha256("concord/epoch-key-commitment" || prev_epoch_be[8] || prev_key[32])`
486/// — the `prevcommit` continuity check on every rekey (CORD-06 §2). A
487/// convergence mechanism, never a secrecy one.
488pub fn epoch_key_commitment(prev_epoch: Epoch, prev_key: &[u8; 32]) -> [u8; 32] {
489    let mut h = Sha256::new();
490    h.update(LABEL_EPOCH_COMMITMENT.as_bytes());
491    h.update(prev_epoch.0.to_be_bytes());
492    h.update(prev_key);
493    h.finalize().into()
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499
500    #[test]
501    fn coordinates_match_the_spec_vectors() {
502        use crate::community::roles::OverwriteTarget;
503        use crate::community::v2::roles::overwrite_target_bytes;
504        let h = |b: [u8; 32]| crate::simd::hex::bytes_to_hex_32(&b);
505        let (cid, ch, member, sealer, role) = (CommunityId([1; 32]), ChannelId([2; 32]), [3u8; 32], [4u8; 32], [5u8; 32]);
506        assert_eq!(h(grant_locator(&cid, &member)), "087cc31d524f398b0810e36aa18b9d135427514c3788382c39c50c0bc50381f3");
507        assert_eq!(h(banlist_locator(&cid)), "cf2767777adcceb8a2ce51d5c3d3c20de9c74bf4867bc2373e5b12eacb5c73d8");
508        assert_eq!(h(everyone_locator(&cid)), "3fbe677b7b2bbddc50d08a428d4e61c8e4c7fdba586d13f1b0f421ab906eeebd");
509        assert_eq!(h(edition_binding(&cid)), "d09129fb5961dc61a181cdfaa2c6588396465ebbdb2c45d79b3fae0b9ad71955");
510        assert_eq!(h(tenure_locator(&cid, &member, &sealer)), "e252eea5e2d7172d166c2dc9c6902df736180fb2105bfaf859f990f509be57d1");
511        assert_eq!(h(sync_locator(&cid, &ch)), "6b08541be1e17ef80f2552273d2534d5b6eac9ab244c4044d2cf150cecfab49f");
512        assert_eq!(h(writers_locator(&cid, &ch)), "f79c6f82f7076ca71112846c985a42acee711f95e2b37aaf05ed4777b0779324");
513        assert_eq!(h(pins_locator(&cid, &ch)), "6e1aa2cb6c78baed7d417d2f6432b1b651b8b605db58515d0749f400b0593a00");
514        for (target, acl) in [
515            (OverwriteTarget::Everyone, "5b337620f7f8d929a0434be597e20ce5c4440bce8c377eb41e0b3b250b6a0ffe"),
516            (OverwriteTarget::Role(h(role)), "cf60d1469c48371fe46a8a2643b4dc0e9da025ba3ac1b08c07acc63ca27d1393"),
517            (OverwriteTarget::Member(h(member)), "1ac57124b4398297a2ac7c96099cef0f21b206e3602921f740c89408c3e69ed1"),
518        ] {
519            assert_eq!(h(acl_locator(&cid, &ch.0, &overwrite_target_bytes(&cid, &target).unwrap())), acl);
520        }
521    }
522
523    #[test]
524    fn a_wrap_owner_key_is_the_authors_alone_and_one_per_wrap() {
525        let address = Keys::new(SecretKey::from_slice(&[9; 32]).unwrap()).public_key();
526        let other_address = Keys::new(SecretKey::from_slice(&[10; 32]).unwrap()).public_key();
527        let owner = wrap_owner_key(&[7; 32], &address, &[8; 32]);
528        assert_eq!(owner.public_key().to_hex(), "decf171297dc66aa114a80471fb2a4b43c54f66ccd0f089545f68fe2ec08a2fd");
529        assert_eq!(wrap_owner_key(&[7; 32], &address, &[8; 32]).public_key(), owner.public_key(), "every client of the author derives the same key");
530        assert_ne!(wrap_owner_key(&[7; 32], &address, &[11; 32]).public_key(), owner.public_key(), "each message has its own");
531        assert_ne!(wrap_owner_key(&[7; 32], &other_address, &[8; 32]).public_key(), owner.public_key(), "each plane has its own");
532        assert_ne!(wrap_owner_key(&[12; 32], &address, &[8; 32]).public_key(), owner.public_key(), "another author derives another key");
533
534        // The spec's vector: the Appendix A secret as the author, its `channel` pk as the address.
535        let secret: [u8; 32] = std::array::from_fn(|i| i as u8);
536        let id: [u8; 32] = std::array::from_fn(|i| 0xff - i as u8);
537        let channel = channel_group_key(&secret, &ChannelId(id), Epoch(0)).pk();
538        assert_eq!(wrap_owner_key(&secret, &channel, &[0x11; 32]).public_key().to_hex(), "5beb1665f03b5bdbd02dcb3e644a9c7ebca0e0c86b26767c7588470e4603f5dc");
539    }
540
541    #[test]
542    fn hkdf32_matches_the_hkdf_crate_for_every_input_shape() {
543        for ikm_len in [0usize, 16, 32, 64, 65, 200] {
544            let ikm: Vec<u8> = (0..ikm_len).map(|i| (i * 7 + 3) as u8).collect();
545            for info_len in [0usize, 1, 33, 41, 63, 64, 120] {
546                let info: Vec<u8> = (0..info_len).map(|i| (i * 13 + 5) as u8).collect();
547                let mut want = [0u8; 32];
548                hkdf::Hkdf::<Sha256>::new(None, &ikm).expand(&info, &mut want).unwrap();
549                assert_eq!(hkdf32(&ikm, &info), want, "ikm {ikm_len} info {info_len}");
550            }
551        }
552    }
553
554    #[test]
555    fn a_full_group_key_memo_ages_a_generation_and_keeps_what_is_used() {
556        let value = guestbook_group_key(&[7; 32], &CommunityId([8; 32]), Epoch(0));
557        let key = |i: u32| {
558            let mut k = [0u8; 32];
559            k[..4].copy_from_slice(&i.to_le_bytes());
560            k
561        };
562        let mut memo = GroupKeyMemo::default();
563        let cap = GROUP_KEY_MEMO_CAP as u32;
564        for i in 0..cap {
565            memo.insert(key(i), value.clone());
566        }
567        memo.insert(key(cap), value.clone());
568        assert_eq!((memo.cur.len(), memo.prev.len()), (1, GROUP_KEY_MEMO_CAP), "a full generation ages whole");
569        // A working set as large as the bound, walked again and again, never misses.
570        for round in 0..3 {
571            for i in 0..cap {
572                assert!(memo.get(&key(i)).is_some(), "round {round}: key {i} went cold");
573            }
574        }
575        // What nobody touches for two generations is gone, and the tables stay bounded.
576        for i in cap..cap * 3 {
577            memo.insert(key(i + 1), value.clone());
578        }
579        assert!(memo.get(&key(0)).is_none());
580        assert!(memo.cur.len() <= GROUP_KEY_MEMO_CAP && memo.prev.len() <= GROUP_KEY_MEMO_CAP);
581    }
582
583    // Fixed test inputs. The golden hex below was produced by an INDEPENDENT
584    // implementation (Python: hmac+hashlib RFC 5869 HKDF, and pure-integer
585    // secp256k1 point math for the x-only pubkeys), so a match proves the
586    // construction — including the secp keypair step — is correct
587    // cross-implementation, not merely self-consistent. If any of these
588    // assertions ever change, the wire format changed — that must be a
589    // conscious, versioned decision.
590    fn secret() -> [u8; 32] {
591        // 0x00,0x01,..,0x1f
592        let mut k = [0u8; 32];
593        for (i, b) in k.iter_mut().enumerate() {
594            *b = i as u8;
595        }
596        k
597    }
598
599    fn id32() -> [u8; 32] {
600        // 0xff,0xfe,..,0xe0
601        let mut id = [0u8; 32];
602        for (i, b) in id.iter_mut().enumerate() {
603            *b = (255 - i) as u8;
604        }
605        id
606    }
607
608    fn alt() -> [u8; 32] {
609        [0x11u8; 32]
610    }
611
612    fn cid() -> CommunityId {
613        CommunityId(id32())
614    }
615
616    fn chan() -> ChannelId {
617        ChannelId(id32())
618    }
619
620    /// A multibyte epoch whose big-endian bytes are order-revealing.
621    const EPOCH_MULTI: u64 = 0x0102030405060708;
622
623    const GOLDEN_CHANNEL_E0_SEED: &str = "1a99a5958bf9fcc5336e6e19db42aabf36ffbfa12f38a1d5fbde2ae383ed751b";
624    const GOLDEN_CHANNEL_E0_PK: &str = "7a5c5dff759a63f1fc2779864487432bae3d1ea72c4ffabd39f4c1fdaf62097a";
625    const GOLDEN_CHANNEL_EMULTI_PK: &str = "f20c7d192cc87615d7341e86f38f85303f4708b40232d4fea521ab8217767391";
626    const GOLDEN_CONTROL_E0_PK: &str = "c43df20bf4d6eeaea5149619662ffe9b211f31e11bb4a59f56b6e906f702d46f";
627    const GOLDEN_CONTROL_SIGNER_E0_SEED: &str = "c4a3e8354d95137132087356412b67b53e025d127d45de45cff9ecf45b0c24f6";
628    const GOLDEN_CONTROL_SIGNER_E0_PK: &str = "718aef388257f3fd9f1bfae5cf2cbd0594a2ffc31adb5c1fe22c502c046acaee";
629    const GOLDEN_CONTROL_SIGNER_EMULTI_PK: &str = "e27235cc13be2f9ad65648e01ff2b63402846469c8638b5386c625688194ec7d";
630    const GOLDEN_GUESTBOOK_E0_PK: &str = "ad09de582026fa7a052db18bb5827fa24c15e929d59aadcc91efb8508f5368ad";
631    const GOLDEN_CHANNEL_ACCESS_E0_PK: &str = "901126284c4d1dfd5e753aa866e28b498825c3382611d1f5d5e929de0bcae15e";
632    const GOLDEN_CHANNEL_WRITER_E1_PK: &str = "7a5b45238020c162ffb7237c680934cf088ddfa47e1d5e2d630450672bc32555";
633    const GOLDEN_WRITER_SCOPE: &str = "211ceda4b4148fa644628adcc2fe6fd8db10878bcdf1cefe02e59ad5d85741a5";
634    const GOLDEN_WRITERS_LOCATOR: &str = "18b69b68718ea12d42ddc77692f72660c2320e7b5fadc0b671f9dfe265099a91";
635    const GOLDEN_SYNC_LOCATOR: &str = "c5ec430fce319555a3c7c0fad4800b8a245c644fc4ab17b8db3aa4e42605e882";
636    const GOLDEN_CHANNEL_REKEY_E1_PK: &str = "7c55cdb957e9db2b4800d687b2a07d3f7066b1a35824a1e86ba871f55e87e8b5";
637    const GOLDEN_BASE_REKEY_E1_PK: &str = "fb2fa44fba66ba15595f784255a1cb569531db8784432ac0e4fe838498dd9dea";
638    const GOLDEN_DISSOLVED_PK: &str = "4d3d55d88fdf9d9c2089651e5cbb0dfa93b6b9b10cdcb2319b0dce1a1398096a";
639    const GOLDEN_GRANT_LOCATOR: &str = "fd2f88cc7f1eb8d7d862c91dc22afe700c358d1845158b3f353b769ce4898e35";
640    const GOLDEN_BANLIST_LOCATOR: &str = "88089214afae6d3c412fd817ada44d6df4d485a53565646471e74476397693c9";
641    const GOLDEN_INVITE_LINKS_LOCATOR: &str = "f4ae29994165767bac23e8dce630f81b926d2c8aa150e5cbf0bdf75865e8379a";
642    const GOLDEN_RECIPIENT_LOCATOR: &str = "342deb400e191f0f52c81f27600934552550beb85aa9bf169f02d0e7f826cf74";
643    const GOLDEN_INVITE_KEY: &str = "94bf8b0d89e579ddaeccf8d9db3f5de5c86a1259c597f2560ff0120173bc5e1f";
644    const GOLDEN_VOICE_MEDIA_E0: &str = "8ab5b935c5e17f156563860ae6263f3700bfd836c326f8b3d7082be2fbaef6a0";
645    const GOLDEN_VOICE_SIGNER_E0_PK: &str = "7591f1306c265ee1dce6a07b72c76fadb3af13bf9ccce0d284cb3af6134211a1";
646    const GOLDEN_VOICE_SENDER: &str = "9ce1c11a39ce16a84b72c2697724a39e5c41ec07f4d703dcb01241271837599e";
647    const GOLDEN_COMMUNITY_ID: &str = "2b790bd59df98bdc52092b74ebd6933a89ef8eaeecc9030861cbdeae7c814c46";
648    const GOLDEN_EPOCH_COMMITMENT: &str = "3e6d6a3c9973c16d1ca7c5602d36979927c55c21a7e2c840f883af3f047e80a4";
649
650    fn hex(bytes: &[u8]) -> String {
651        crate::simd::hex::bytes_to_hex_32(bytes.try_into().expect("32 bytes"))
652    }
653
654    #[test]
655    fn channel_group_key_golden_vector() {
656        let gk = channel_group_key(&secret(), &chan(), Epoch(0));
657        // The hkdf seed is a valid scalar (overwhelming case), so sk == seed —
658        // pinning both proves hkdf AND the secp keypair step.
659        assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CHANNEL_E0_SEED);
660        assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_E0_PK);
661    }
662
663    #[test]
664    fn channel_group_key_golden_multibyte_epoch_is_big_endian() {
665        let gk = channel_group_key(&secret(), &chan(), Epoch(EPOCH_MULTI));
666        assert_eq!(gk.pk_hex(), GOLDEN_CHANNEL_EMULTI_PK);
667    }
668
669    #[test]
670    fn control_group_key_golden_vector() {
671        assert_eq!(control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_CONTROL_E0_PK);
672    }
673
674    #[test]
675    fn control_signer_group_key_golden_vectors() {
676        // Same fixed inputs as the control read key, different label — the split's
677        // signer address must land elsewhere (CORD-02 §5: the two never collide).
678        let gk = control_signer_group_key(&secret(), &cid(), Epoch(0));
679        assert_eq!(hex(gk.keys().secret_key().as_secret_bytes()), GOLDEN_CONTROL_SIGNER_E0_SEED);
680        assert_eq!(gk.pk_hex(), GOLDEN_CONTROL_SIGNER_E0_PK);
681        assert_ne!(gk.pk_hex(), GOLDEN_CONTROL_E0_PK);
682        assert_eq!(
683            control_signer_group_key(&secret(), &cid(), Epoch(EPOCH_MULTI)).pk_hex(),
684            GOLDEN_CONTROL_SIGNER_EMULTI_PK
685        );
686    }
687
688    #[test]
689    fn guestbook_group_key_golden_vector() {
690        assert_eq!(guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(), GOLDEN_GUESTBOOK_E0_PK);
691    }
692
693    #[test]
694    fn channel_access_group_key_golden_vector() {
695        assert_eq!(channel_access_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_CHANNEL_ACCESS_E0_PK);
696    }
697
698    #[test]
699    fn writer_golden_vectors() {
700        assert_eq!(channel_writer_group_key(&secret(), &chan(), Epoch(1)).pk_hex(), GOLDEN_CHANNEL_WRITER_E1_PK);
701        assert_eq!(hex(&writer_scope(&chan())), GOLDEN_WRITER_SCOPE);
702        assert_eq!(hex(&writers_locator(&cid(), &chan())), GOLDEN_WRITERS_LOCATOR);
703        assert_eq!(hex(&sync_locator(&cid(), &chan())), GOLDEN_SYNC_LOCATOR);
704    }
705
706    #[test]
707    fn rekey_group_keys_golden_vectors() {
708        assert_eq!(
709            channel_rekey_group_key(&secret(), &chan(), Epoch(1)).pk_hex(),
710            GOLDEN_CHANNEL_REKEY_E1_PK
711        );
712        assert_eq!(
713            base_rekey_group_key(&secret(), &cid(), Epoch(1)).pk_hex(),
714            GOLDEN_BASE_REKEY_E1_PK
715        );
716    }
717
718    #[test]
719    fn dissolved_group_key_golden_and_is_epoch_free() {
720        assert_eq!(dissolved_group_key(&cid()).pk_hex(), GOLDEN_DISSOLVED_PK);
721        // Epoch omission is real omission, not epoch=0: a manual derivation WITH
722        // an epoch field of 0 must land elsewhere.
723        let with_epoch = GroupKey::derive(LABEL_DISSOLVED, &cid().0, &ZERO32, Some(0));
724        assert_ne!(with_epoch.pk_hex(), GOLDEN_DISSOLVED_PK);
725    }
726
727    #[test]
728    fn locator_golden_vectors() {
729        assert_eq!(hex(&grant_locator(&cid(), &alt())), GOLDEN_GRANT_LOCATOR);
730        assert_eq!(hex(&banlist_locator(&cid())), GOLDEN_BANLIST_LOCATOR);
731        assert_eq!(hex(&invite_links_locator(&cid(), &alt())), GOLDEN_INVITE_LINKS_LOCATOR);
732        assert_eq!(
733            hex(&recipient_locator(&secret(), &alt(), &id32(), Epoch(3))),
734            GOLDEN_RECIPIENT_LOCATOR
735        );
736        assert_eq!(hex(&invite_bundle_key(&[0x07u8; TOKEN_LEN])), GOLDEN_INVITE_KEY);
737    }
738
739    #[test]
740    fn voice_golden_vectors() {
741        let media = voice_media_key(&secret(), &chan(), Epoch(0));
742        assert_eq!(hex(&media), GOLDEN_VOICE_MEDIA_E0);
743        assert_eq!(voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(), GOLDEN_VOICE_SIGNER_E0_PK);
744        assert_eq!(
745            hex(&voice_sender_key(&media, "00112233445566778899aabbccddeeff")),
746            GOLDEN_VOICE_SENDER
747        );
748    }
749
750    #[test]
751    fn community_id_golden_and_verifies() {
752        let id = community_id_of(&secret(), &alt());
753        assert_eq!(hex(&id.0), GOLDEN_COMMUNITY_ID);
754        assert!(verify_community_id(&id, &secret(), &alt()));
755        // Wrong owner or wrong salt must fail the commitment.
756        assert!(!verify_community_id(&id, &alt(), &alt()));
757        assert!(!verify_community_id(&id, &secret(), &id32()));
758    }
759
760    #[test]
761    fn epoch_key_commitment_golden_and_binds_both_inputs() {
762        assert_eq!(hex(&epoch_key_commitment(Epoch(2), &secret())), GOLDEN_EPOCH_COMMITMENT);
763        assert_ne!(hex(&epoch_key_commitment(Epoch(3), &secret())), GOLDEN_EPOCH_COMMITMENT);
764        assert_ne!(hex(&epoch_key_commitment(Epoch(2), &alt())), GOLDEN_EPOCH_COMMITMENT);
765    }
766
767    #[test]
768    fn labels_domain_separate_every_plane() {
769        // One (secret, id, epoch) triple across every keyed label — all
770        // addresses must be pairwise distinct.
771        let pks = [
772            channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
773            control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
774            control_signer_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
775            guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
776            channel_rekey_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
777            base_rekey_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
778            voice_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
779        ];
780        let unique: std::collections::HashSet<_> = pks.iter().collect();
781        assert_eq!(unique.len(), pks.len(), "two labels collided on one address");
782    }
783
784    #[test]
785    fn epoch_rotates_every_keyed_address() {
786        assert_ne!(
787            channel_group_key(&secret(), &chan(), Epoch(0)).pk_hex(),
788            channel_group_key(&secret(), &chan(), Epoch(1)).pk_hex()
789        );
790        assert_ne!(
791            control_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
792            control_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
793        );
794        assert_ne!(
795            guestbook_group_key(&secret(), &cid(), Epoch(0)).pk_hex(),
796            guestbook_group_key(&secret(), &cid(), Epoch(1)).pk_hex()
797        );
798    }
799
800    #[test]
801    fn recipient_locator_binds_direction_scope_and_epoch() {
802        let base = recipient_locator(&secret(), &alt(), &id32(), Epoch(1));
803        // Rotator↔recipient direction matters (concatenation order).
804        assert_ne!(recipient_locator(&alt(), &secret(), &id32(), Epoch(1)), base);
805        assert_ne!(recipient_locator(&secret(), &alt(), &id32(), Epoch(2)), base);
806        assert_ne!(recipient_locator(&secret(), &alt(), &ZERO32, Epoch(1)), base);
807    }
808
809    #[test]
810    fn conv_key_is_deterministic_self_ecdh() {
811        let a = channel_group_key(&secret(), &chan(), Epoch(0));
812        let b = channel_group_key(&secret(), &chan(), Epoch(0));
813        assert_eq!(a.conv_key().as_bytes(), b.conv_key().as_bytes());
814    }
815}