Skip to main content

vector_core/community/v2/
rekey.rs

1//! Concord v2 rekeys (CORD-06) — the per-recipient key-delivery atom + the 3303
2//! event that carries a rotation.
3//!
4//! A rotation mints a fresh-random key for the next epoch and delivers it only
5//! to the members who STAY, one **per-recipient blob** each. Two choices are
6//! security-load-bearing:
7//!
8//! **D1 — the locator is PUBLIC and authenticates nothing.** A blob is located by
9//! `HKDF(rotator_xonly || recipient_xonly, …)` — public inputs (full NIP-46 bunker
10//! parity: a bunker computes it without a raw key). A public locator proves
11//! NOTHING; it is a lookup index only. Authenticity rests entirely on (a) the crate's **rotator seal + roster authority** —
12//! verified by the caller before any blob is trusted — and (b) the blob's
13//! **bound plaintext** (scope+epoch checked after decrypt). So [`open_blob`]
14//! does NOT gate on the locator: the decrypt itself (only the addressed recipient's key
15//! opens a blob wrapped to them) plus the bound-plaintext check are the gate.
16//!
17//! **D5 — the blob wrap carries base64.** NIP-44/NIP-46 encrypt surfaces are
18//! string-typed, and the 72 raw bytes aren't valid UTF-8, so the wrapped
19//! plaintext is `base64(scope_id ‖ epoch_be ‖ new_key)` — a string a bunker can
20//! `nip44_encrypt`/`nip44_decrypt` to the recipient's identity key with no raw
21//! secret. The `wrapped` field is then the standard NIP-44 payload string, so a
22//! local-keys wrap and a bunker wrap produce identical wire output.
23//!
24//! The 3303 event itself is a v2 stream event (kind-1059 wrap, ENCRYPTED seal
25//! signed by the rotator's real identity) at the rekey address — reusing
26//! [`super::stream`]. Its seal is what tells the recipient WHO rotated, which is
27//! both the ECDH counterparty and the authority actor.
28//!
29//! What lives here: the blob atom, the 3303 build/parse, chunk-set assembly, and
30//! the continuity/fork comparators — all PURE. The stateful orchestration
31//! (recipient-set computation, the base+channels lockstep read-cut, DB epoch
32//! archival, and the D2 BAN-vs-MANAGE_CHANNELS authority gate, which is an
33//! apply-path concern keyed on prior-vs-current-root addressing) sits in the
34//! service layer.
35
36use nostr_sdk::prelude::nip44::v2::ConversationKey;
37use nostr_sdk::prelude::{Event, Keys, PublicKey, SecretKey, Tag, Timestamp, UnsignedEvent};
38use serde::{Deserialize, Serialize};
39use zeroize::Zeroizing;
40
41use super::super::{ChannelId, CommunityId, Epoch};
42use super::derive::{
43    base_rekey_group_key, channel_rekey_group_key, control_signer_group_key, epoch_key_commitment,
44    recipient_locator, GroupKey,
45};
46use super::stream::{self, OpenedStream, SealForm, StreamError};
47
48/// Max recipients (blobs) in ONE 3303 event when sending (CORD-06 §1): the CORD-01
49/// double wrap expands the blob array twice, and 80 blobs measure ~55 KB, under a 64 KB
50/// relay event (size-guarded by test). A larger recipient set splits across chunk events.
51pub const MAX_REKEY_BLOBS_PER_EVENT: usize = 80;
52
53/// [`MAX_REKEY_BLOBS_PER_EVENT`] for the 104- and 136-byte forms (base rotations, history): 80 of
54/// them push the rumor past a NIP-44 padding step that carries through the seal (~77 KB); 60 ~55 KB.
55pub const MAX_WIDE_BLOBS_PER_EVENT: usize = 60;
56
57/// How many blobs one event of a rotation at `scope` may carry: a base rotation's are the wide forms.
58pub fn blobs_per_event(scope: RekeyScope) -> usize {
59    if matches!(scope, RekeyScope::Root) { MAX_WIDE_BLOBS_PER_EVENT } else { MAX_REKEY_BLOBS_PER_EVENT }
60}
61
62/// Max blobs Vector will ACCEPT in one received 3303 chunk (a DoS bound checked
63/// after decrypt). Kept at the spec's stated 120 — higher than the send cap — so
64/// a chunk minted by another client at the spec limit (and delivered by a relay
65/// with a larger `maxEventSize`) still parses. An array over this is rejected.
66pub const MAX_REKEY_BLOBS_RECEIVED: usize = 120;
67
68/// [`MAX_REKEY_BLOBS_PER_EVENT`] for a writer delivery, whose recipients' certificates ride the
69/// same event (size-guarded by test).
70pub const MAX_CERTIFIED_BLOBS_PER_EVENT: usize = 48;
71
72const TAG_SCOPE: &str = "scope";
73const TAG_NEW_EPOCH: &str = "newepoch";
74const TAG_PREV_EPOCH: &str = "prevepoch";
75const TAG_PREV_COMMIT: &str = "prevcommit";
76const TAG_CHUNK: &str = "chunk";
77/// Root-scope containment marker (CORD-06 Severing Refounding): an adopter
78/// revokes its own public invite links instead of refreshing them into the new
79/// epoch. Grants no authority of its own — it rides a rotation the adopt gate
80/// has already verified.
81const TAG_SEVER: &str = "sever";
82/// Names how a 3303 delivers (CORD-03 §5); an access delivery is never a rotation.
83const TAG_DELIVERY: &str = "delivery";
84const DELIVERY_ACCESS: &str = "access";
85const DELIVERY_HISTORY: &str = "history";
86
87/// What a rekey rotates (CORD-06 §1). The 32-byte scope id is stamped into every
88/// blob's plaintext so a blob can't be spliced onto another coordinate.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum RekeyScope {
91    /// A specific private channel being rekeyed.
92    Channel(ChannelId),
93    /// The community_root (a base rotation / Refounding) — the all-zero sentinel
94    /// (a random channel id never collides with it).
95    Root,
96}
97
98impl RekeyScope {
99    /// The 32-byte scope id: the channel id, or the all-zero root sentinel.
100    pub fn id32(&self) -> [u8; 32] {
101        match self {
102            RekeyScope::Channel(c) => c.0,
103            RekeyScope::Root => [0u8; 32],
104        }
105    }
106
107    fn to_hex(self) -> String {
108        crate::simd::hex::bytes_to_hex_32(&self.id32())
109    }
110
111    fn from_hex(hex: &str) -> Option<RekeyScope> {
112        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
113            return None;
114        }
115        let bytes = crate::simd::hex::hex_to_bytes_32(hex);
116        Some(if bytes == [0u8; 32] {
117            RekeyScope::Root
118        } else {
119            RekeyScope::Channel(ChannelId(bytes))
120        })
121    }
122}
123
124/// One located, wrapped rekey blob — the unit a 3303 event carries N of.
125///
126/// `locator` is the public [`recipient_locator`] hex (a lookup index — proves
127/// nothing, D1); `wrapped` is the NIP-44 payload string whose plaintext is
128/// `base64(scope_id ‖ epoch_be ‖ new_key)` (D5).
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct RekeyBlob {
131    pub locator: String,
132    pub wrapped: String,
133}
134
135/// Errors from the rekey layer.
136#[derive(Debug)]
137pub enum RekeyError {
138    Stream(StreamError),
139    Crypto(String),
140    /// The wrapped plaintext isn't the expected 72-byte layout.
141    BadBlobLength(usize),
142    /// A base blob's plaintext isn't one of the three fixed widths (CORD-06 §1):
143    /// 72 (legacy pre-split), 104 (member), 136 (staff).
144    BadBaseBlobWidth(usize),
145    /// A 136-byte base blob's `new_control_root` doesn't derive to its
146    /// `new_control_pk` — refused whole rather than adopting a plane split from
147    /// its readers (CORD-06 §1).
148    ControlPairMismatch,
149    /// A Grant's `control_wrap` plaintext isn't the fixed 40 bytes (CORD-04 §3).
150    BadControlWrapLength(usize),
151    /// The blob's bound scope ≠ the coordinate it's being opened under (splice).
152    ScopeSplice,
153    /// The blob's bound epoch ≠ the coordinate it's being opened under (splice).
154    EpochSplice,
155    /// The rumor isn't a kind-3303 rekey.
156    NotARekey(u16),
157    /// A required tag is absent, duplicated, or malformed.
158    BadTag(&'static str),
159    /// `new_epoch <= prev_epoch` — a rotation must advance the chain.
160    NonMonotonicEpoch,
161    /// A chunk index is out of range (`i < 1`, `i > n`, or `n < 1`).
162    BadChunkIndex,
163    /// The blob array exceeds the cap.
164    TooManyBlobs(usize),
165}
166
167impl std::fmt::Display for RekeyError {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        match self {
170            RekeyError::Stream(e) => write!(f, "stream: {e}"),
171            RekeyError::Crypto(e) => write!(f, "crypto: {e}"),
172            RekeyError::BadBlobLength(n) => write!(f, "rekey blob plaintext is {n} bytes, expected 72"),
173            RekeyError::BadBaseBlobWidth(n) => write!(f, "base rekey blob plaintext is {n} bytes, expected 72, 104 or 136"),
174            RekeyError::ControlPairMismatch => write!(f, "base rekey blob control_root does not derive to its control_pk"),
175            RekeyError::BadControlWrapLength(n) => write!(f, "control_wrap plaintext is {n} bytes, expected 40"),
176            RekeyError::ScopeSplice => write!(f, "rekey blob scope binding mismatch (splice)"),
177            RekeyError::EpochSplice => write!(f, "rekey blob epoch binding mismatch (splice)"),
178            RekeyError::NotARekey(k) => write!(f, "rumor kind {k} is not a rekey"),
179            RekeyError::BadTag(t) => write!(f, "missing/duplicate/malformed rekey tag: {t}"),
180            RekeyError::NonMonotonicEpoch => write!(f, "rekey new_epoch must exceed prev_epoch"),
181            RekeyError::BadChunkIndex => write!(f, "rekey chunk index out of range"),
182            RekeyError::TooManyBlobs(n) => write!(f, "rekey carries {n} blobs, over the cap"),
183        }
184    }
185}
186
187impl std::error::Error for RekeyError {}
188
189impl From<StreamError> for RekeyError {
190    fn from(e: StreamError) -> Self {
191        RekeyError::Stream(e)
192    }
193}
194
195// ── The blob atom ────────────────────────────────────────────────────────────
196
197/// The 72-byte bound plaintext: `scope_id[32] ‖ epoch_be[8] ‖ new_key[32]`.
198/// Fixed-width, so no separators are needed to parse it unambiguously.
199fn bound_plaintext(scope: RekeyScope, epoch: Epoch, new_key: &[u8; 32]) -> [u8; 72] {
200    let mut pt = [0u8; 72];
201    pt[..32].copy_from_slice(&scope.id32());
202    pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
203    pt[40..].copy_from_slice(new_key);
204    pt
205}
206
207/// The base64 string a blob's NIP-44 layer actually encrypts (D5). Exposed so
208/// the service-layer bunker path can `signer.nip44_encrypt(recipient, this)`.
209pub fn bound_plaintext_b64(scope: RekeyScope, epoch: Epoch, new_key: &[u8; 32]) -> String {
210    crate::simd::base64::STANDARD.encode_to_string(bound_plaintext(scope, epoch, new_key))
211}
212
213/// Parse + verify a decrypted bound plaintext (the base64 already stripped),
214/// checking scope+epoch strict-equal the coordinate it was opened under before
215/// yielding `new_key`. Exposed for the bunker open path.
216pub fn parse_bound_plaintext(pt: &[u8], scope: RekeyScope, epoch: Epoch) -> Result<[u8; 32], RekeyError> {
217    if pt.len() != 72 {
218        return Err(RekeyError::BadBlobLength(pt.len()));
219    }
220    if pt[..32] != scope.id32() {
221        return Err(RekeyError::ScopeSplice);
222    }
223    let mut epoch_be = [0u8; 8];
224    epoch_be.copy_from_slice(&pt[32..40]);
225    if u64::from_be_bytes(epoch_be) != epoch.0 {
226        return Err(RekeyError::EpochSplice);
227    }
228    let mut new_key = [0u8; 32];
229    new_key.copy_from_slice(&pt[40..72]);
230    Ok(new_key)
231}
232
233// ── The base-rotation blob forms (CORD-06 §1) ────────────────────────────────
234//
235// A base rotation's blob widens past the 72-byte channel layout to carry the
236// next epoch's Control Plane keys (CORD-02 §2): every member's blob appends
237// `new_control_pk[32]` (104 bytes), a staff recipient's additionally
238// `new_control_root[32]` (136). The width declares the form; a 72-byte BASE
239// blob is the legacy pre-split rotation — honored when reading old epochs,
240// never minted by a compliant Rotator. Any other width is malformed.
241
242/// What a base blob delivered (CORD-06 §1); the width declared the form.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct BaseKeyDelivery {
245    pub new_root: [u8; 32],
246    /// The next epoch's Control Plane address — absent on a legacy 72-byte
247    /// blob, whose acceptor folds that epoch's Control at the legacy
248    /// member-derivable address instead (CORD-06 §3).
249    pub control_pk: Option<[u8; 32]>,
250    /// The staff write secret (136-byte form only), already verified to derive
251    /// to `control_pk`.
252    pub control_root: Option<[u8; 32]>,
253}
254
255fn bound_base_plaintext(epoch: Epoch, new_root: &[u8; 32], control_pk: &[u8; 32], control_root: Option<&[u8; 32]>) -> Vec<u8> {
256    let mut pt = Vec::with_capacity(if control_root.is_some() { 136 } else { 104 });
257    pt.extend_from_slice(&bound_plaintext(RekeyScope::Root, epoch, new_root));
258    pt.extend_from_slice(control_pk);
259    if let Some(cr) = control_root {
260        pt.extend_from_slice(cr);
261    }
262    pt
263}
264
265/// The base64 string a BASE blob's NIP-44 layer encrypts (D5) — the 104-byte
266/// member form, or the 136-byte staff form when `control_root` rides.
267pub fn bound_base_plaintext_b64(epoch: Epoch, new_root: &[u8; 32], control_pk: &[u8; 32], control_root: Option<&[u8; 32]>) -> String {
268    crate::simd::base64::STANDARD.encode_to_string(bound_base_plaintext(epoch, new_root, control_pk, control_root))
269}
270
271/// Parse + verify a decrypted BASE blob plaintext (CORD-06 §1): 72 (legacy
272/// pre-split), 104 (member), 136 (staff). The scope must be the all-zero base
273/// sentinel and the epoch must match the coordinate (unspliceable), and a
274/// 136-byte blob's `new_control_root` must derive to exactly its
275/// `new_control_pk` (CORD-02 §5) — a mismatched pair refuses the WHOLE blob
276/// rather than adopting a plane split from its readers.
277///
278/// A width ABOVE 136 is a future form this build predates. Refusing it would
279/// re-create the pre-split brick (a member forks off at the rotation until
280/// they update), so it degrades per CORD-06 §3's lenient grade instead: the
281/// frozen 72-byte prefix yields the root (membership and every Chat plane
282/// survive), the family's appended offsets yield the control pair when they
283/// still verify (the derive check fails closed on a reordered layout), and
284/// whatever the extra bytes govern freezes — a safe prompt to update, never a
285/// fork. Widths between the defined forms fit no append-only extension and
286/// stay malformed.
287pub fn parse_bound_base_plaintext(pt: &[u8], community_id: &CommunityId, epoch: Epoch) -> Result<BaseKeyDelivery, RekeyError> {
288    if !matches!(pt.len(), 72 | 104 | 136) && pt.len() < 137 {
289        return Err(RekeyError::BadBaseBlobWidth(pt.len()));
290    }
291    let new_root = parse_bound_plaintext(&pt[..72], RekeyScope::Root, epoch)?;
292    if pt.len() == 72 {
293        return Ok(BaseKeyDelivery { new_root, control_pk: None, control_root: None });
294    }
295    let mut control_pk = [0u8; 32];
296    control_pk.copy_from_slice(&pt[72..104]);
297    if pt.len() == 104 {
298        return Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: None });
299    }
300    let mut control_root = [0u8; 32];
301    control_root.copy_from_slice(&pt[104..136]);
302    if control_signer_group_key(&control_root, community_id, epoch).pk().to_bytes() != control_pk {
303        if pt.len() == 136 {
304            return Err(RekeyError::ControlPairMismatch);
305        }
306        // Future form whose 104..136 bytes are no longer the secret: keep the
307        // verified prefix fields, drop the unverifiable ones.
308        return Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: None });
309    }
310    Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: Some(control_root) })
311}
312
313/// Build one BASE blob via a [`VectorSigner`](crate::signer::VectorSigner) — the 104-byte member form, or
314/// 136 with `control_root` for a staff recipient (CORD-04 §3). Mirrors
315/// [`build_blob`]; the locator is the same public Root-scope locator.
316pub async fn build_base_blob<S: crate::signer::VectorSigner + ?Sized>(
317    signer: &S,
318    rotator_xonly: &[u8; 32],
319    recipient_pk: &PublicKey,
320    epoch: Epoch,
321    new_root: &[u8; 32],
322    control_pk: &[u8; 32],
323    control_root: Option<&[u8; 32]>,
324) -> Result<RekeyBlob, RekeyError> {
325    let inner_b64 = Zeroizing::new(bound_base_plaintext_b64(epoch, new_root, control_pk, control_root));
326    let wrapped = signer
327        .nip44_encrypt_async(recipient_pk, inner_b64.as_str())
328        .await
329        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
330    Ok(RekeyBlob {
331        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), RekeyScope::Root, epoch),
332        wrapped,
333    })
334}
335
336/// Open a BASE blob addressed to me via a [`VectorSigner`](crate::signer::VectorSigner). Mirror of
337/// [`open_blob`], but width-tolerant per CORD-06 §1 — the returned delivery
338/// says which form arrived.
339pub async fn open_base_blob<S: crate::signer::VectorSigner + ?Sized>(
340    signer: &S,
341    rotator_pk: &PublicKey,
342    community_id: &CommunityId,
343    epoch: Epoch,
344    blob: &RekeyBlob,
345) -> Result<BaseKeyDelivery, RekeyError> {
346    let inner_b64 = Zeroizing::new(
347        signer
348            .nip44_decrypt_async(rotator_pk, &blob.wrapped)
349            .await
350            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
351    );
352    let pt = Zeroizing::new(
353        crate::simd::base64::STANDARD
354            .decode_to_vec(inner_b64.as_bytes())
355            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
356    );
357    parse_bound_base_plaintext(&pt, community_id, epoch)
358}
359
360// ── The Grant's control_wrap plaintext (CORD-04 §3) ──────────────────────────
361
362/// `epoch_be[8] ‖ control_root[32]` — the staff write key as delivered inside a
363/// staff-making Grant, NIP-44-encrypted under the granter↔member pairwise key
364/// (the rekey-blob discipline: fixed width, the epoch INSIDE the ciphertext).
365pub fn encode_control_wrap(epoch: Epoch, control_root: &[u8; 32]) -> [u8; 40] {
366    let mut pt = [0u8; 40];
367    pt[..8].copy_from_slice(&epoch.0.to_be_bytes());
368    pt[8..].copy_from_slice(control_root);
369    pt
370}
371
372/// The base64 string a control_wrap's NIP-44 layer encrypts (string-typed
373/// signer surfaces, the D5 transport discipline).
374pub fn control_wrap_b64(epoch: Epoch, control_root: &[u8; 32]) -> String {
375    crate::simd::base64::STANDARD.encode_to_string(encode_control_wrap(epoch, control_root))
376}
377
378/// Parse a decrypted 40-byte control_wrap plaintext. The caller verifies the
379/// secret derives to the `control_pk` it holds for the named epoch — any
380/// mismatch is dropped, never adopted (CORD-04 §3).
381pub fn parse_control_wrap(pt: &[u8]) -> Result<(Epoch, [u8; 32]), RekeyError> {
382    if pt.len() != 40 {
383        return Err(RekeyError::BadControlWrapLength(pt.len()));
384    }
385    let mut epoch_be = [0u8; 8];
386    epoch_be.copy_from_slice(&pt[..8]);
387    let mut control_root = [0u8; 32];
388    control_root.copy_from_slice(&pt[8..]);
389    Ok((Epoch(u64::from_be_bytes(epoch_be)), control_root))
390}
391
392/// The public per-recipient locator (D1). Both parties compute it from public
393/// keys alone; it addresses the blob and nothing more.
394pub fn blob_locator(rotator_xonly: &[u8; 32], recipient_xonly: &[u8; 32], scope: RekeyScope, epoch: Epoch) -> String {
395    crate::simd::hex::bytes_to_hex_32(&recipient_locator(rotator_xonly, recipient_xonly, &scope.id32(), epoch))
396}
397
398/// Build one blob with LOCAL keys (the bunker path drives the same wire via the
399/// `_b64` helpers + a NIP-46 `nip44_encrypt`). The wrap is the pairwise
400/// conversation key `ConversationKey::derive(rotator_sk, recipient_pk)`, so only
401/// the recipient's identity key opens it.
402pub fn build_blob_local(
403    rotator_sk: &SecretKey,
404    rotator_xonly: &[u8; 32],
405    recipient_pk: &PublicKey,
406    scope: RekeyScope,
407    epoch: Epoch,
408    new_key: &[u8; 32],
409) -> Result<RekeyBlob, RekeyError> {
410    let inner_b64 = Zeroizing::new(bound_plaintext_b64(scope, epoch, new_key));
411    let ck = ConversationKey::derive(rotator_sk, recipient_pk).map_err(|e| RekeyError::Crypto(e.to_string()))?;
412    let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner_b64.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
413    Ok(RekeyBlob {
414        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), scope, epoch),
415        wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
416    })
417}
418
419/// Open a blob addressed to me with LOCAL keys. Per D1 this does NOT check the
420/// locator: the decrypt (only my identity key opens a blob wrapped to me by the
421/// rotator) plus the bound scope/epoch ARE the authenticity boundary. A blob
422/// relocated to a foreign locator still won't decrypt for a non-recipient, and
423/// a spliced one fails the bound check.
424pub fn open_blob_local(
425    my_sk: &SecretKey,
426    rotator_pk: &PublicKey,
427    scope: RekeyScope,
428    epoch: Epoch,
429    blob: &RekeyBlob,
430) -> Result<[u8; 32], RekeyError> {
431    let ck = ConversationKey::derive(my_sk, rotator_pk).map_err(|e| RekeyError::Crypto(e.to_string()))?;
432    let payload = crate::simd::base64::STANDARD
433        .decode_to_vec(blob.wrapped.as_bytes())
434        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
435    let inner_b64 = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
436    let pt = Zeroizing::new(
437        crate::simd::base64::STANDARD
438            .decode_to_vec(inner_b64.as_slice())
439            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
440    );
441    parse_bound_plaintext(&pt, scope, epoch)
442}
443
444/// Build one blob via a [`VectorSigner`](crate::signer::VectorSigner) (the bunker / NIP-55 path). Wire-identical
445/// to [`build_blob_local`]: `signer.nip44_encrypt(recipient, bound_plaintext_b64)`
446/// whose conversation key is ECDH(signer_identity, recipient) — the same key the
447/// local path derives from the raw rotator secret. The `wrapped` field is the
448/// standard NIP-44 payload string (D5), so both paths emit identical wire.
449pub async fn build_blob<S: crate::signer::VectorSigner + ?Sized>(
450    signer: &S,
451    rotator_xonly: &[u8; 32],
452    recipient_pk: &PublicKey,
453    scope: RekeyScope,
454    epoch: Epoch,
455    new_key: &[u8; 32],
456) -> Result<RekeyBlob, RekeyError> {
457    let inner_b64 = Zeroizing::new(bound_plaintext_b64(scope, epoch, new_key));
458    let wrapped = signer
459        .nip44_encrypt_async(recipient_pk, inner_b64.as_str())
460        .await
461        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
462    Ok(RekeyBlob {
463        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), scope, epoch),
464        wrapped,
465    })
466}
467
468/// Open a blob addressed to me via a [`VectorSigner`](crate::signer::VectorSigner). Mirror of [`open_blob_local`]:
469/// `signer.nip44_decrypt(rotator, blob.wrapped)` yields the base64 bound plaintext,
470/// then the scope/epoch bound check gates it. Per D1 the locator is NOT gated.
471pub async fn open_blob<S: crate::signer::VectorSigner + ?Sized>(
472    signer: &S,
473    rotator_pk: &PublicKey,
474    scope: RekeyScope,
475    epoch: Epoch,
476    blob: &RekeyBlob,
477) -> Result<[u8; 32], RekeyError> {
478    let inner_b64 = Zeroizing::new(
479        signer
480            .nip44_decrypt_async(rotator_pk, &blob.wrapped)
481            .await
482            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
483    );
484    let pt = Zeroizing::new(
485        crate::simd::base64::STANDARD
486            .decode_to_vec(inner_b64.as_bytes())
487            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
488    );
489    parse_bound_plaintext(&pt, scope, epoch)
490}
491
492/// Find my blob in a chunk's array by my public locator (the lookup step, D1).
493/// `None` means this chunk doesn't carry my key — never a removal on its own
494/// (only "removed" once ALL chunks are held and none has it).
495pub fn find_my_blob<'a>(
496    blobs: &'a [RekeyBlob],
497    rotator_xonly: &[u8; 32],
498    my_xonly: &[u8; 32],
499    scope: RekeyScope,
500    epoch: Epoch,
501) -> Option<&'a RekeyBlob> {
502    find_my_blobs(blobs, rotator_xonly, my_xonly, scope, epoch).next()
503}
504
505/// EVERY blob at my locator, in order. A locator is a public lookup index that
506/// proves nothing, so anyone can publish a blob at mine; with the union in
507/// [`collect_rotations`] more than one can survive to the open. Taking only the
508/// first would let a junk blob shadow the real key and park an adopter that in
509/// fact holds it — so the caller tries each and adopts on the first that opens.
510pub fn find_my_blobs<'a>(
511    blobs: &'a [RekeyBlob],
512    rotator_xonly: &[u8; 32],
513    my_xonly: &[u8; 32],
514    scope: RekeyScope,
515    epoch: Epoch,
516) -> impl Iterator<Item = &'a RekeyBlob> {
517    let want = blob_locator(rotator_xonly, my_xonly, scope, epoch);
518    blobs.iter().filter(move |b| b.locator == want)
519}
520
521// ── The 3303 event (a v2 stream event) ───────────────────────────────────────
522
523/// A parsed, seal-verified 3303 chunk. The `rotator` is the seal's real signer
524/// (the ECDH counterparty AND the authority actor the caller gates on).
525#[derive(Debug, Clone)]
526pub struct RekeyChunk {
527    pub rotator: PublicKey,
528    pub scope: RekeyScope,
529    pub new_epoch: Epoch,
530    pub prev_epoch: Epoch,
531    pub prev_commit: [u8; 32],
532    /// This chunk's `(i, n)` — 1-based, `i <= n`.
533    pub chunk: (u32, u32),
534    pub blobs: Vec<RekeyBlob>,
535    /// The rotator's `vac` (CORD-06 §Authority: "a rotation cites the Grant it
536    /// acts under like any authority action"). `None` when the owner rotates.
537    pub citation: Option<crate::community::edition::AuthorityCitation>,
538    /// Severing containment marker (`TAG_SEVER`, root scope only).
539    pub severed: bool,
540    /// When the rotator sent it, in ms.
541    pub at_ms: u64,
542}
543
544/// The key that groups chunks of ONE rotation: `(rotator, scope_id, new_epoch,
545/// prev_commit)`. Two rotators racing the same epoch, or one rotator over two
546/// channels, never alias.
547pub type RotationKey = ([u8; 32], [u8; 32], u64, [u8; 32]);
548
549impl RekeyChunk {
550    /// This chunk's [`RotationKey`].
551    pub fn correlation(&self) -> RotationKey {
552        (self.rotator.to_bytes(), self.scope.id32(), self.new_epoch.0, self.prev_commit)
553    }
554}
555
556/// Build the unsigned 3303 rumor (rotator is the pubkey; the seal will carry the
557/// signature). Enforces the monotonic-epoch and chunk-range invariants at mint.
558#[allow(clippy::too_many_arguments)]
559pub fn build_rekey_rumor(
560    rotator: PublicKey,
561    scope: RekeyScope,
562    new_epoch: Epoch,
563    prev_epoch: Epoch,
564    prev_commit: &[u8; 32],
565    blobs: &[RekeyBlob],
566    chunk_i: u32,
567    chunk_n: u32,
568    at_secs: u64,
569    citation: Option<&crate::community::edition::AuthorityCitation>,
570    severed: bool,
571) -> Result<UnsignedEvent, RekeyError> {
572    if new_epoch.0 <= prev_epoch.0 {
573        return Err(RekeyError::NonMonotonicEpoch);
574    }
575    if chunk_n < 1 || chunk_i < 1 || chunk_i > chunk_n {
576        return Err(RekeyError::BadChunkIndex);
577    }
578    if blobs.len() > blobs_per_event(scope) {
579        return Err(RekeyError::TooManyBlobs(blobs.len()));
580    }
581    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
582    let mut tags = vec![
583        Tag::custom(TAG_SCOPE, [scope.to_hex()]),
584        Tag::custom(TAG_NEW_EPOCH, [new_epoch.0.to_string()]),
585        Tag::custom(TAG_PREV_EPOCH, [prev_epoch.0.to_string()]),
586        Tag::custom(TAG_PREV_COMMIT, [crate::simd::hex::bytes_to_hex_32(prev_commit)]),
587        Tag::custom(TAG_CHUNK, [chunk_i.to_string(), chunk_n.to_string()]),
588    ];
589    // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
590    // authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
591    // never honored by a lagging client." The owner cites nothing.
592    if let Some(c) = citation {
593        tags.push(c.to_tag());
594    }
595    if severed {
596        tags.push(Tag::custom(TAG_SEVER, ["1"]));
597    }
598    // Rekeys fold by their tags, not time; still stamp created_at for the wire.
599    Ok(stream::build_rumor_secs(super::kind::REKEY, rotator, &content, tags, at_secs))
600}
601
602/// The rekey group key for a CHANNEL rekey addressed under `addressing_root`.
603/// The caller chooses the root: a STANDALONE channel rekey rides the CURRENT
604/// root (`MANAGE_CHANNELS`); a channel rekey forced by a removal rides the PRIOR
605/// root alongside the base rekey (D2 — inherits the removal's `BAN` authority,
606/// and the prior-root address is exactly what distinguishes the two classes on
607/// the wire so a base-fork loser can still open it).
608pub fn channel_rekey_group(addressing_root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
609    channel_rekey_group_key(addressing_root, channel_id, new_epoch)
610}
611
612/// The rekey group key for a BASE rotation — always under the PRIOR root (the
613/// one handle every retained member still holds through the rotation).
614pub fn base_rekey_group(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
615    base_rekey_group_key(prior_root, community_id, new_epoch)
616}
617
618/// Seal + wrap a 3303 rumor into its stream event at the rekey address. The seal
619/// is ENCRYPTED (20013 — the rekey plane MUST NOT be plaintext-sealed) and
620/// signed by the rotator; the wrap by the rekey group key.
621pub fn seal_rekey_chunk(
622    rumor: &UnsignedEvent,
623    rekey_group: &GroupKey,
624    rotator_keys: &Keys,
625    wrap_at: Timestamp,
626) -> Result<(Event, Keys), RekeyError> {
627    let seal = stream::build_seal(rumor, SealForm::Encrypted, rekey_group, rotator_keys)?;
628    Ok(stream::wrap_seal(&seal, rekey_group, stream::KIND_WRAP, wrap_at)?)
629}
630
631/// Split a full recipient blob set into 3303 chunk events ([`blobs_per_event`] each),
632/// all sharing the rotation's `(scope, new_epoch, prev_commit)` so a receiver
633/// correlates them. Local-keys convenience.
634#[allow(clippy::too_many_arguments)]
635pub fn build_rekey_chunks_local(
636    rotator_keys: &Keys,
637    rekey_group: &GroupKey,
638    scope: RekeyScope,
639    new_epoch: Epoch,
640    prev_epoch: Epoch,
641    prev_commit: &[u8; 32],
642    blobs: &[RekeyBlob],
643    at_secs: u64,
644    citation: Option<&crate::community::edition::AuthorityCitation>,
645    severed: bool,
646) -> Result<Vec<Event>, RekeyError> {
647    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
648        vec![&[]]
649    } else {
650        blobs.chunks(blobs_per_event(scope)).collect()
651    };
652    let n = groups.len() as u32;
653    let mut out = Vec::with_capacity(groups.len());
654    for (idx, group_blobs) in groups.iter().enumerate() {
655        let rumor = build_rekey_rumor(
656            rotator_keys.public_key(),
657            scope,
658            new_epoch,
659            prev_epoch,
660            prev_commit,
661            group_blobs,
662            idx as u32 + 1,
663            n,
664            at_secs,
665            citation,
666            severed,
667        )?;
668        let (wrap, _) = seal_rekey_chunk(&rumor, rekey_group, rotator_keys, Timestamp::from_secs(at_secs))?;
669        out.push(wrap);
670    }
671    Ok(out)
672}
673
674/// Signer-driven twin of [`build_rekey_chunks_local`] for bunker / NIP-55 accounts:
675/// each chunk's encrypted seal signs through a [`VectorSigner`](crate::signer::VectorSigner). `rotator_pk` must
676/// equal `my_public_key()`. Wire-identical to the local path.
677#[allow(clippy::too_many_arguments)]
678pub async fn build_rekey_chunks<S: crate::signer::VectorSigner + ?Sized>(
679    signer: &S,
680    rotator_pk: PublicKey,
681    rekey_group: &GroupKey,
682    scope: RekeyScope,
683    new_epoch: Epoch,
684    prev_epoch: Epoch,
685    prev_commit: &[u8; 32],
686    blobs: &[RekeyBlob],
687    at_secs: u64,
688    citation: Option<&crate::community::edition::AuthorityCitation>,
689    severed: bool,
690) -> Result<Vec<Event>, RekeyError> {
691    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
692        vec![&[]]
693    } else {
694        blobs.chunks(blobs_per_event(scope)).collect()
695    };
696    let n = groups.len() as u32;
697    let mut out = Vec::with_capacity(groups.len());
698    for (idx, group_blobs) in groups.iter().enumerate() {
699        let rumor = build_rekey_rumor(rotator_pk, scope, new_epoch, prev_epoch, prev_commit, group_blobs, idx as u32 + 1, n, at_secs, citation, severed)?;
700        let (wrap, _) = stream::seal_and_wrap_signed(signer, rotator_pk, &rumor, SealForm::Encrypted, rekey_group, stream::KIND_WRAP, Timestamp::from_secs(at_secs), &[]).await?;
701        out.push(wrap);
702    }
703    Ok(out)
704}
705
706/// Extend an already-published rotation's chunk set with additional blobs — the
707/// catch-up path for members a rotation forgot.
708///
709/// Indices start at `start_after + 1` and the declared total covers them, so no
710/// reader ever sees two chunks claiming the same slot. That constraint is load-
711/// bearing on DEPLOYED clients: [`collect_rotations`] keeps the first chunk seen
712/// per index, so a colliding slot silently drops the loser's blobs — and for an
713/// original recipient that reads as their own removal. Disjoint indices merge as
714/// a pure union under every fetch order, and [`Rotation::is_complete`] only
715/// requires `1..=declared_first_seen`, which extras never break.
716#[allow(clippy::too_many_arguments)]
717pub async fn build_rekey_chunk_extension<S: crate::signer::VectorSigner + ?Sized>(
718    signer: &S,
719    rotator_pk: PublicKey,
720    rekey_group: &GroupKey,
721    scope: RekeyScope,
722    new_epoch: Epoch,
723    prev_epoch: Epoch,
724    prev_commit: &[u8; 32],
725    blobs: &[RekeyBlob],
726    at_secs: u64,
727    citation: Option<&crate::community::edition::AuthorityCitation>,
728    severed: bool,
729    start_after: u32,
730) -> Result<Vec<Event>, RekeyError> {
731    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
732        vec![&[]]
733    } else {
734        blobs.chunks(blobs_per_event(scope)).collect()
735    };
736    let n = start_after + groups.len() as u32;
737    let mut out = Vec::with_capacity(groups.len());
738    for (idx, group_blobs) in groups.iter().enumerate() {
739        let i = start_after + idx as u32 + 1;
740        let rumor = build_rekey_rumor(rotator_pk, scope, new_epoch, prev_epoch, prev_commit, group_blobs, i, n, at_secs, citation, severed)?;
741        let (wrap, _) = stream::seal_and_wrap_signed(signer, rotator_pk, &rumor, SealForm::Encrypted, rekey_group, stream::KIND_WRAP, Timestamp::from_secs(at_secs), &[]).await?;
742        out.push(wrap);
743    }
744    Ok(out)
745}
746
747/// Parse a 3303 chunk from a seal-verified stream open. Rejects a non-3303
748/// rumor, a plaintext seal (the rekey plane is encrypted-only), malformed or
749/// duplicate machinery tags, a bad chunk range, and an over-cap blob array.
750pub fn parse_rekey_chunk(opened: &OpenedStream) -> Result<RekeyChunk, RekeyError> {
751    if opened.seal_form != SealForm::Encrypted {
752        // A plaintext-sealed rekey would be a liftable public artifact — reject.
753        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
754    }
755    let rumor = &opened.rumor;
756    if rumor.kind.as_u16() != super::kind::REKEY {
757        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
758    }
759    let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
760        .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
761    let new_epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
762    let prev_epoch = Epoch(parse_u64(rumor, TAG_PREV_EPOCH)?);
763    if new_epoch.0 <= prev_epoch.0 {
764        return Err(RekeyError::NonMonotonicEpoch);
765    }
766    let prev_hex = unique_tag(rumor, TAG_PREV_COMMIT)?.ok_or(RekeyError::BadTag(TAG_PREV_COMMIT))?;
767    if prev_hex.len() != 64 || !prev_hex.bytes().all(|b| b.is_ascii_hexdigit()) {
768        return Err(RekeyError::BadTag(TAG_PREV_COMMIT));
769    }
770    let prev_commit = crate::simd::hex::hex_to_bytes_32(&prev_hex);
771
772    let (chunk_i, chunk_n) = parse_chunk(rumor)?;
773
774    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
775    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
776        return Err(RekeyError::TooManyBlobs(blobs.len()));
777    }
778
779    // Spec-shaped: present means exactly "1" (CORD-01 §5 strictness), absent means false.
780    let severed = match unique_tag(rumor, TAG_SEVER)?.as_deref() {
781        None => false,
782        Some("1") => true,
783        Some(_) => return Err(RekeyError::BadTag(TAG_SEVER)),
784    };
785
786    Ok(RekeyChunk {
787        rotator: opened.author,
788        scope,
789        new_epoch,
790        prev_epoch,
791        prev_commit,
792        chunk: (chunk_i, chunk_n),
793        blobs,
794        citation: crate::community::edition::AuthorityCitation::from_tags(&rumor.tags),
795        severed,
796        at_ms: opened.at_ms,
797    })
798}
799
800/// A key delivery on a Channel's access plane (CORD-03 §5): blobs carrying the key of the
801/// Channel's current epoch. It carries no removal verdict, whatever it omits.
802#[derive(Debug, Clone)]
803pub struct AccessDelivery {
804    pub deliverer: PublicKey,
805    pub scope: RekeyScope,
806    pub epoch: Epoch,
807    pub blobs: Vec<RekeyBlob>,
808    /// The writer address a writer-scope delivery's key claims to derive to (CORD-03 §1).
809    pub writer: Option<[u8; 32]>,
810    /// Writer certificates it hands its recipients, by recipient (CORD-03 §1).
811    pub certs: Vec<([u8; 32], [u8; 64])>,
812    /// For one part of a writer epoch's minting delivery, which part of how many.
813    pub mint: Option<(u32, u32)>,
814}
815
816/// Marks one event of a writer epoch's minting delivery: `["mint", <part>, <parts>]`, from 1.
817const TAG_MINT: &str = "mint";
818
819/// `rumor` as part `part` of `parts` of a minting delivery, its id recomputed.
820pub fn as_mint_part(rumor: UnsignedEvent, part: usize, parts: usize) -> UnsignedEvent {
821    use crate::event_ext::FinalizeUnsignedWithId as _;
822    let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
823    tags.push(Tag::custom(TAG_MINT, [part.to_string(), parts.to_string()]));
824    let mut out = nostr_sdk::prelude::EventBuilder::new(rumor.kind, rumor.content).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
825    out.ensure_id();
826    out
827}
828
829/// A writer-scope delivery's claimed address.
830const TAG_WRITER: &str = "writer";
831
832/// A writer certificate for one recipient: `["cert", <recipient hex>, <signature hex>]`.
833const TAG_CERT: &str = "cert";
834
835/// The unsigned access-plane 3303 rumor.
836pub fn build_access_rumor(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
837    build_access_rumor_for(deliverer, scope, epoch, None, blobs, at_secs)
838}
839
840/// [`build_access_rumor`] naming, for a writer key, the address it derives to.
841pub fn build_access_rumor_for(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
842    build_access_rumor_certified(deliverer, scope, epoch, writer, blobs, &[], at_secs)
843}
844
845/// [`build_access_rumor_for`], handing writer certificates to its recipients.
846pub fn build_access_rumor_certified(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], certs: &[([u8; 32], [u8; 64])], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
847    let cap = if certs.is_empty() { MAX_REKEY_BLOBS_PER_EVENT } else { MAX_CERTIFIED_BLOBS_PER_EVENT };
848    if blobs.len() > cap || certs.len() > MAX_CERTIFIED_BLOBS_PER_EVENT {
849        return Err(RekeyError::TooManyBlobs(blobs.len().max(certs.len())));
850    }
851    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
852    let mut tags = vec![
853        Tag::custom(TAG_SCOPE, [scope.to_hex()]),
854        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
855        Tag::custom(TAG_DELIVERY, [DELIVERY_ACCESS]),
856    ];
857    if let Some(pk) = writer {
858        tags.push(Tag::custom(TAG_WRITER, [crate::simd::hex::bytes_to_hex_32(&pk)]));
859    }
860    for (who, cert) in certs {
861        tags.push(Tag::custom(TAG_CERT, [crate::simd::hex::bytes_to_hex_32(who), crate::simd::hex::bytes_to_hex_string(cert)]));
862    }
863    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
864}
865
866/// Parse an opened access-plane event. Anything not tagged as an access delivery is refused.
867pub fn parse_access_delivery(opened: &OpenedStream) -> Result<AccessDelivery, RekeyError> {
868    if opened.seal_form != SealForm::Encrypted {
869        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
870    }
871    let rumor = &opened.rumor;
872    if rumor.kind.as_u16() != super::kind::REKEY {
873        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
874    }
875    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_ACCESS) {
876        return Err(RekeyError::BadTag(TAG_DELIVERY));
877    }
878    let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
879        .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
880    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
881    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
882    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
883        return Err(RekeyError::TooManyBlobs(blobs.len()));
884    }
885    let writer = match unique_tag(rumor, TAG_WRITER)? {
886        None => None,
887        Some(hex) => Some(crate::simd::hex::hex_to_bytes_32_checked(&hex).ok_or(RekeyError::BadTag(TAG_WRITER))?),
888    };
889    // A malformed certificate is no certificate; it never refuses the delivery it rides.
890    let certs = rumor
891        .tags
892        .iter()
893        .filter_map(|t| {
894            let s = t.as_slice();
895            (s.first().map(String::as_str) == Some(TAG_CERT) && s.len() == 3).then_some(())?;
896            let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
897            let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
898            Some((who, cert))
899        })
900        .take(MAX_REKEY_BLOBS_RECEIVED)
901        .collect();
902    let mint = rumor
903        .tags
904        .iter()
905        .map(|t| t.as_slice())
906        .find(|t| t.first().map(String::as_str) == Some(TAG_MINT))
907        .and_then(|t| Some((t.get(1)?.parse::<u32>().ok()?, t.get(2)?.parse::<u32>().ok()?)))
908        .filter(|(part, parts)| *part >= 1 && part <= parts);
909    Ok(AccessDelivery { deliverer: opened.author, scope, epoch, blobs, writer, certs, mint })
910}
911
912/// A Channel's history scope (CORD-03 §5): what history blobs bind to, so one can never be
913/// spliced in as a current key.
914pub fn history_scope(channel: &ChannelId) -> [u8; 32] {
915    use sha2::{Digest, Sha256};
916    let mut h = Sha256::new();
917    h.update(b"concord/history-scope");
918    h.update(channel.0);
919    h.finalize().into()
920}
921
922/// A past epoch's read view of a Channel (CORD-03 §5): where its messages are and the key that
923/// opens them, never the secret that signs into it.
924#[derive(Clone, PartialEq, Eq)]
925pub struct HistoryView {
926    pub address: [u8; 32],
927    pub conv_key: [u8; 32],
928}
929
930impl std::fmt::Debug for HistoryView {
931    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932        f.debug_struct("HistoryView").field("address", &crate::simd::hex::bytes_to_hex_32(&self.address)).finish_non_exhaustive()
933    }
934}
935
936impl HistoryView {
937    pub fn of(group: &GroupKey) -> Self {
938        let mut conv_key = [0u8; 32];
939        conv_key.copy_from_slice(group.conv_key().as_bytes());
940        HistoryView { address: group.pk().to_bytes(), conv_key }
941    }
942}
943
944/// `history_scope[32] ‖ epoch_be[8] ‖ address[32] ‖ conv_key[32]`.
945fn history_plaintext_b64(channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Zeroizing<String> {
946    let mut pt = Zeroizing::new([0u8; 104]);
947    pt[..32].copy_from_slice(&history_scope(channel));
948    pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
949    pt[40..72].copy_from_slice(&view.address);
950    pt[72..].copy_from_slice(&view.conv_key);
951    Zeroizing::new(crate::simd::base64::STANDARD.encode_to_string(&pt[..]))
952}
953
954fn parse_history_plaintext(pt: &[u8], channel: &ChannelId, epoch: Epoch) -> Result<HistoryView, RekeyError> {
955    if pt.len() != 104 {
956        return Err(RekeyError::BadBlobLength(pt.len()));
957    }
958    if pt[..32] != history_scope(channel) {
959        return Err(RekeyError::ScopeSplice);
960    }
961    if pt[32..40] != epoch.0.to_be_bytes() {
962        return Err(RekeyError::EpochSplice);
963    }
964    let (mut address, mut conv_key) = ([0u8; 32], [0u8; 32]);
965    address.copy_from_slice(&pt[40..72]);
966    conv_key.copy_from_slice(&pt[72..]);
967    Ok(HistoryView { address, conv_key })
968}
969
970/// The public locator of `recipient`'s history blob for `epoch` from `deliverer`.
971pub fn history_locator(deliverer_xonly: &[u8; 32], recipient_xonly: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> String {
972    crate::simd::hex::bytes_to_hex_32(&recipient_locator(deliverer_xonly, recipient_xonly, &history_scope(channel), epoch))
973}
974
975pub async fn build_history_blob<S: crate::signer::VectorSigner + ?Sized>(
976    signer: &S,
977    deliverer_xonly: &[u8; 32],
978    recipient: &PublicKey,
979    channel: &ChannelId,
980    epoch: Epoch,
981    view: &HistoryView,
982) -> Result<RekeyBlob, RekeyError> {
983    let inner = history_plaintext_b64(channel, epoch, view);
984    let wrapped = signer.nip44_encrypt_async(recipient, inner.as_str()).await.map_err(|e| RekeyError::Crypto(e.to_string()))?;
985    Ok(RekeyBlob { locator: history_locator(deliverer_xonly, &recipient.to_bytes(), channel, epoch), wrapped })
986}
987
988pub async fn open_history_blob<S: crate::signer::VectorSigner + ?Sized>(
989    signer: &S,
990    deliverer: &PublicKey,
991    channel: &ChannelId,
992    epoch: Epoch,
993    blob: &RekeyBlob,
994) -> Result<HistoryView, RekeyError> {
995    let inner = Zeroizing::new(signer.nip44_decrypt_async(deliverer, &blob.wrapped).await.map_err(|e| RekeyError::Crypto(e.to_string()))?);
996    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
997    parse_history_plaintext(&pt, channel, epoch)
998}
999
1000/// [`build_history_blob`] with local keys.
1001pub fn build_history_blob_local(deliverer: &Keys, recipient: &PublicKey, channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Result<RekeyBlob, RekeyError> {
1002    let inner = history_plaintext_b64(channel, epoch, view);
1003    let ck = ConversationKey::derive(deliverer.secret_key(), recipient).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1004    let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1005    Ok(RekeyBlob {
1006        locator: history_locator(&deliverer.public_key().to_bytes(), &recipient.to_bytes(), channel, epoch),
1007        wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
1008    })
1009}
1010
1011/// [`open_history_blob`] with local keys.
1012pub fn open_history_blob_local(me: &SecretKey, deliverer: &PublicKey, channel: &ChannelId, epoch: Epoch, blob: &RekeyBlob) -> Result<HistoryView, RekeyError> {
1013    let ck = ConversationKey::derive(me, deliverer).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1014    let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1015    let inner = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1016    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_slice()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1017    parse_history_plaintext(&pt, channel, epoch)
1018}
1019
1020/// One epoch's history blobs on a Channel's access plane.
1021#[derive(Debug, Clone)]
1022pub struct HistoryDelivery {
1023    pub deliverer: PublicKey,
1024    pub epoch: Epoch,
1025    pub blobs: Vec<RekeyBlob>,
1026}
1027
1028pub fn build_history_rumor(deliverer: PublicKey, channel: &ChannelId, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
1029    if blobs.len() > MAX_WIDE_BLOBS_PER_EVENT {
1030        return Err(RekeyError::TooManyBlobs(blobs.len()));
1031    }
1032    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1033    let tags = vec![
1034        Tag::custom(TAG_SCOPE, [crate::simd::hex::bytes_to_hex_32(&history_scope(channel))]),
1035        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
1036        Tag::custom(TAG_DELIVERY, [DELIVERY_HISTORY]),
1037    ];
1038    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
1039}
1040
1041/// Parse an opened access-plane event as `channel`'s history, refusing anything else.
1042pub fn parse_history_delivery(opened: &OpenedStream, channel: &ChannelId) -> Result<HistoryDelivery, RekeyError> {
1043    if opened.seal_form != SealForm::Encrypted {
1044        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
1045    }
1046    let rumor = &opened.rumor;
1047    if rumor.kind.as_u16() != super::kind::REKEY {
1048        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
1049    }
1050    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_HISTORY) {
1051        return Err(RekeyError::BadTag(TAG_DELIVERY));
1052    }
1053    if unique_tag(rumor, TAG_SCOPE)?.as_deref() != Some(crate::simd::hex::bytes_to_hex_32(&history_scope(channel)).as_str()) {
1054        return Err(RekeyError::BadTag(TAG_SCOPE));
1055    }
1056    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
1057    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
1058    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
1059        return Err(RekeyError::TooManyBlobs(blobs.len()));
1060    }
1061    Ok(HistoryDelivery { deliverer: opened.author, epoch, blobs })
1062}
1063
1064// ── Continuity + removal + fork resolution (CORD-06 §2/§3) ───────────────────
1065
1066/// The verdict of the prevcommit continuity check (CORD-06 §2).
1067#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1068pub enum Continuity {
1069    /// The commitment matches the key I hold at `prev_epoch` — this rotation
1070    /// extends my chain; adopt it.
1071    Extends,
1072    /// `prev_epoch` is higher than the key I hold — I missed a rotation; fetch
1073    /// the gap first, don't adopt yet.
1074    Gap,
1075    /// The commitment doesn't match at the same epoch — a fork or garbage.
1076    Fork,
1077}
1078
1079/// Check a rotation's `prev_commit` against the `(epoch, key)` I currently hold
1080/// for its scope. A match proves the rotation extends the very key I hold; a
1081/// higher `prev_epoch` means I'm behind; anything else is a fork/garbage.
1082pub fn check_continuity(chunk: &RekeyChunk, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1083    if chunk.prev_epoch.0 == held_epoch.0 {
1084        if epoch_key_commitment(held_epoch, held_key) == chunk.prev_commit {
1085            Continuity::Extends
1086        } else {
1087            Continuity::Fork
1088        }
1089    } else if chunk.prev_epoch.0 > held_epoch.0 {
1090        Continuity::Gap
1091    } else {
1092        // prev_epoch < held: this rotation is older than where I am — a stale
1093        // fork; a settled epoch only ever heals DOWN to a sibling, never back.
1094        Continuity::Fork
1095    }
1096}
1097
1098/// A collected rotation: all chunks sharing one correlation key, and whether the
1099/// set is complete (all `n` chunks present).
1100#[derive(Debug, Clone)]
1101pub struct Rotation {
1102    pub rotator: PublicKey,
1103    pub scope: RekeyScope,
1104    pub new_epoch: Epoch,
1105    pub prev_epoch: Epoch,
1106    pub prev_commit: [u8; 32],
1107    /// The union of every chunk's blobs.
1108    pub blobs: Vec<RekeyBlob>,
1109    /// Total chunk count `n` declared by the chunks.
1110    pub declared_chunks: u32,
1111    /// Distinct chunk indices actually held.
1112    pub held_chunks: std::collections::BTreeSet<u32>,
1113    /// The rotator's `vac`, taken from the first chunk seen (every chunk of one
1114    /// rotation carries the same citation — they share a signer and an action).
1115    pub citation: Option<crate::community::edition::AuthorityCitation>,
1116    /// OR across chunks: any severed chunk marks the whole rotation severed, so
1117    /// an extension (rescue) can never launder the flag away.
1118    pub severed: bool,
1119    /// When it was sent: its earliest chunk's time, in ms.
1120    pub at_ms: u64,
1121}
1122
1123impl Rotation {
1124    /// True once every declared chunk index `1..=n` is held — the precondition
1125    /// for concluding removal (a missing chunk is "keep recovering", never a
1126    /// removal).
1127    pub fn is_complete(&self) -> bool {
1128        self.declared_chunks >= 1 && (1..=self.declared_chunks).all(|i| self.held_chunks.contains(&i))
1129    }
1130
1131    /// This rotation's continuity against the `(epoch, key)` I hold for its scope
1132    /// — the [`check_continuity`] verdict at the aggregated-rotation level (same
1133    /// prevcommit test), so a follower can gate adoption without a raw chunk.
1134    pub fn continuity(&self, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1135        if self.prev_epoch.0 == held_epoch.0 {
1136            if epoch_key_commitment(held_epoch, held_key) == self.prev_commit {
1137                Continuity::Extends
1138            } else {
1139                Continuity::Fork
1140            }
1141        } else if self.prev_epoch.0 > held_epoch.0 {
1142            Continuity::Gap
1143        } else {
1144            Continuity::Fork
1145        }
1146    }
1147}
1148
1149/// Group a batch of parsed chunks into rotations by correlation key. Chunks whose
1150/// `n` disagrees with their siblings, or that repeat an index, are the caller's
1151/// concern to police; here the largest `n` any chunk declares sets the total, and a
1152/// second chunk at a held index unions its blobs.
1153pub fn collect_rotations(chunks: &[RekeyChunk]) -> Vec<Rotation> {
1154    use std::collections::BTreeMap;
1155    let mut by_key: BTreeMap<RotationKey, Rotation> = BTreeMap::new();
1156    for c in chunks {
1157        let entry = by_key.entry(c.correlation()).or_insert_with(|| Rotation {
1158            rotator: c.rotator,
1159            scope: c.scope,
1160            new_epoch: c.new_epoch,
1161            prev_epoch: c.prev_epoch,
1162            prev_commit: c.prev_commit,
1163            blobs: Vec::new(),
1164            declared_chunks: c.chunk.1,
1165            held_chunks: std::collections::BTreeSet::new(),
1166            citation: c.citation.clone(),
1167            severed: c.severed,
1168            at_ms: c.at_ms,
1169        });
1170        entry.severed |= c.severed;
1171        entry.at_ms = entry.at_ms.min(c.at_ms);
1172        // An extension declares the larger total: complete only once every index up to it is held.
1173        entry.declared_chunks = entry.declared_chunks.max(c.chunk.1);
1174        // UNION the blobs, even when the index is already held. Treating a second
1175        // chunk at a known index as pure idempotent re-delivery is safe only while
1176        // re-delivery is byte-identical; when two chunks genuinely differ (a
1177        // catch-up extension that re-claimed a slot), dropping the loser silently
1178        // deletes its recipients from the union — and a recipient with no blob reads
1179        // as REMOVED, which tears their community down. Union can only ever ADD
1180        // blobs, so it can turn a false removal into an adoption but never the
1181        // reverse. Exact duplicates are dropped so ordinary re-delivery stays free.
1182        entry.held_chunks.insert(c.chunk.0);
1183        for b in &c.blobs {
1184            if !entry.blobs.iter().any(|held| held.locator == b.locator && held.wrapped == b.wrapped) {
1185                entry.blobs.push(b.clone());
1186            }
1187        }
1188    }
1189    by_key.into_values().collect()
1190}
1191
1192/// Have I been removed by this rotation? Only answerable on a COMPLETE rotation
1193/// (all `n` chunks held): I'm removed iff none of the union's blobs carries my
1194/// locator. On an incomplete rotation the answer is `None` — keep recovering.
1195pub fn am_i_removed(rotation: &Rotation, my_xonly: &[u8; 32]) -> Option<bool> {
1196    if !rotation.is_complete() {
1197        return None;
1198    }
1199    let mine = find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), my_xonly, rotation.scope, rotation.new_epoch);
1200    Some(mine.is_none())
1201}
1202
1203/// Deterministic same-epoch fork winner (CORD-06 §3): among candidate rotations
1204/// at one continuity point, the one whose decrypted `new_key` is lexicographically
1205/// lowest wins. Every retained member decrypts its own blob from each fork and
1206/// computes the identical winner. Returns the index into `candidates` of the
1207/// winner, or `None` if the caller decrypted no candidate.
1208pub fn lowest_key_winner(candidate_keys: &[[u8; 32]]) -> Option<usize> {
1209    candidate_keys
1210        .iter()
1211        .enumerate()
1212        .min_by(|(_, a), (_, b)| a.cmp(b))
1213        .map(|(i, _)| i)
1214}
1215
1216// ── helpers ──────────────────────────────────────────────────────────────────
1217
1218fn unique_tag(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, RekeyError> {
1219    let mut found: Option<String> = None;
1220    for t in rumor.tags.iter() {
1221        let s = t.as_slice();
1222        if s.len() >= 2 && s[0] == name {
1223            if found.is_some() {
1224                return Err(RekeyError::BadTag(name));
1225            }
1226            found = Some(s[1].clone());
1227        }
1228    }
1229    Ok(found)
1230}
1231
1232fn parse_u64(rumor: &UnsignedEvent, name: &'static str) -> Result<u64, RekeyError> {
1233    let raw = unique_tag(rumor, name)?.ok_or(RekeyError::BadTag(name))?;
1234    // Spec-shaped decimal, not a bare `parse` — that takes "+2" and "02" as
1235    // epochs a stricter peer refuses (CORD-01 §5).
1236    if !crate::community::edition::is_tag_decimal(&raw) {
1237        return Err(RekeyError::BadTag(name));
1238    }
1239    raw.parse::<u64>().map_err(|_| RekeyError::BadTag(name))
1240}
1241
1242fn parse_chunk(rumor: &UnsignedEvent) -> Result<(u32, u32), RekeyError> {
1243    let mut found: Option<(u32, u32)> = None;
1244    for t in rumor.tags.iter() {
1245        let s = t.as_slice();
1246        if s.len() >= 3 && s[0] == TAG_CHUNK {
1247            if found.is_some() {
1248                return Err(RekeyError::BadTag(TAG_CHUNK));
1249            }
1250            if !crate::community::edition::is_tag_decimal(&s[1]) || !crate::community::edition::is_tag_decimal(&s[2]) {
1251                return Err(RekeyError::BadTag(TAG_CHUNK));
1252            }
1253            let i: u32 = s[1].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1254            let n: u32 = s[2].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1255            found = Some((i, n));
1256        }
1257    }
1258    let (i, n) = found.ok_or(RekeyError::BadTag(TAG_CHUNK))?;
1259    if n < 1 || i < 1 || i > n {
1260        return Err(RekeyError::BadChunkIndex);
1261    }
1262    Ok((i, n))
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267
1268    /// Wrap raw `Keys` as the polymorphic signer. `VectorSigner` pins its error to
1269    /// `SignerError`, which bare `Keys` doesn't satisfy, so tests go through the
1270    /// same enum the app uses.
1271    fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
1272        crate::signer::ActiveSigner::Keys(k.clone())
1273    }
1274    use super::*;
1275
1276    fn keys(byte: u8) -> Keys {
1277        Keys::new(SecretKey::from_slice(&[byte; 32]).unwrap())
1278    }
1279
1280    fn xonly(k: &Keys) -> [u8; 32] {
1281        k.public_key().to_bytes()
1282    }
1283
1284    const CHAN: ChannelId = ChannelId([0x42u8; 32]);
1285
1286    // ── blob atom ────────────────────────────────────────────────────────────
1287
1288    #[test]
1289    fn bound_plaintext_layout_is_frozen() {
1290        let pt = bound_plaintext(RekeyScope::Root, Epoch(1), &[0xABu8; 32]);
1291        let expected = format!("{}{}{}", "00".repeat(32), "0000000000000001", "ab".repeat(32));
1292        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
1293        let pt2 = bound_plaintext(RekeyScope::Channel(ChannelId([0x11u8; 32])), Epoch(0x0102), &[0xCDu8; 32]);
1294        let expected2 = format!("{}{}{}", "11".repeat(32), "0000000000000102", "cd".repeat(32));
1295        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt2), expected2);
1296    }
1297
1298    #[test]
1299    fn blob_round_trips_both_scopes() {
1300        let rotator = keys(7);
1301        let recipient = keys(8);
1302        for (scope, epoch, key) in [
1303            (RekeyScope::Root, Epoch(1), [0xABu8; 32]),
1304            (RekeyScope::Channel(CHAN), Epoch(5), [0xCDu8; 32]),
1305        ] {
1306            let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1307            let got = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob).unwrap();
1308            assert_eq!(got, key, "the recipient recovers the fresh key");
1309        }
1310    }
1311
1312    #[tokio::test]
1313    async fn signer_blob_is_wire_compatible_with_local_both_directions() {
1314        // A remote signer (here a plain Keys, which impls VectorSigner) must build
1315        // AND open blobs interchangeably with the raw-key path — the CORD-06 D5
1316        // "identical wire" guarantee the bunker/NIP-55 integration rests on.
1317        let rotator = keys(7);
1318        let recipient = keys(8);
1319        let scope = RekeyScope::Root;
1320        let epoch = Epoch(3);
1321        let key = [0x5Au8; 32];
1322
1323        // local build -> signer open
1324        let blob_l = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1325        let got_s = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_l).await.unwrap();
1326        assert_eq!(got_s, key, "signer opens a local-built blob");
1327
1328        // signer build -> local open (+ identical public locator)
1329        let blob_s = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).await.unwrap();
1330        assert_eq!(blob_s.locator, blob_l.locator, "same public locator regardless of build path");
1331        let got_l = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob_s).unwrap();
1332        assert_eq!(got_l, key, "local opens a signer-built blob");
1333
1334        // signer build -> signer open
1335        let got_ss = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_s).await.unwrap();
1336        assert_eq!(got_ss, key, "signer round-trips its own blob");
1337    }
1338
1339    #[tokio::test]
1340    async fn signer_blob_bound_check_still_gates_scope_epoch_splice() {
1341        let rotator = keys(7);
1342        let recipient = keys(8);
1343        let blob = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[9u8; 32]).await.unwrap();
1344        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob).await.is_err(), "epoch splice rejected");
1345        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob).await.is_err(), "scope splice rejected");
1346    }
1347
1348    #[test]
1349    fn locator_is_public_and_computable_from_pubkeys_alone() {
1350        // D1: the locator derives from PUBLIC inputs, so the rotator computing a
1351        // recipient's slot and the recipient computing their own must agree — no
1352        // secret needed either side (bunker parity).
1353        let rotator = keys(7);
1354        let recipient = keys(8);
1355        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(2), &[1u8; 32]).unwrap();
1356        let recomputed = blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(2));
1357        assert_eq!(blob.locator, recomputed, "both sides compute the same public locator");
1358    }
1359
1360    #[test]
1361    fn a_non_recipient_cannot_open_even_holding_the_public_locator() {
1362        // The D1 security relocation: the locator authenticates NOTHING (anyone
1363        // holding both npubs computes it), yet an outsider still can't open —
1364        // the pairwise decrypt is the gate, not the locator.
1365        let rotator = keys(7);
1366        let recipient = keys(8);
1367        let outsider = keys(9);
1368        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[2u8; 32]).unwrap();
1369        // The outsider can trivially recompute the (public) locator...
1370        assert_eq!(blob.locator, blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)));
1371        // ...but pairing (outsider_sk, rotator_pk) yields a different conversation
1372        // key, so the decrypt fails.
1373        assert!(open_blob_local(outsider.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).is_err());
1374    }
1375
1376    #[test]
1377    fn a_relocated_blob_still_opens_by_decrypt_not_locator() {
1378        // Because open ignores the locator (D1), corrupting the locator does NOT
1379        // break a legitimate recipient's open — the decrypt + bound check govern.
1380        // The FIND step uses the locator; OPEN does not.
1381        let rotator = keys(7);
1382        let recipient = keys(8);
1383        let mut blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[3u8; 32]).unwrap();
1384        blob.locator = "ff".repeat(32);
1385        // Handed the blob directly (locator bypassed), the recipient still opens it.
1386        assert_eq!(
1387            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).unwrap(),
1388            [3u8; 32]
1389        );
1390        // But find_my_blob won't LOCATE it under the corrupted locator.
1391        assert!(find_my_blob(std::slice::from_ref(&blob), &xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)).is_none());
1392    }
1393
1394    #[test]
1395    fn scope_and_epoch_splices_are_rejected_on_open() {
1396        let rotator = keys(7);
1397        let recipient = keys(8);
1398        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[4u8; 32]).unwrap();
1399        // Opened under a different scope → bound scope mismatch.
1400        assert!(matches!(
1401            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob),
1402            Err(RekeyError::ScopeSplice)
1403        ));
1404        // Opened under a different epoch → bound epoch mismatch.
1405        assert!(matches!(
1406            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob),
1407            Err(RekeyError::EpochSplice)
1408        ));
1409    }
1410
1411    #[test]
1412    fn wrapped_carries_base64_of_the_72_bytes_for_bunker_parity() {
1413        // D5: the NIP-44 layer's plaintext is base64(72 bytes) — a UTF-8 string a
1414        // NIP-46 signer can nip44_encrypt/decrypt. Prove the decrypted inner is
1415        // exactly that base64 string, matching the `_b64` helper the bunker uses.
1416        let rotator = keys(7);
1417        let recipient = keys(8);
1418        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[5u8; 32]).unwrap();
1419        let ck = ConversationKey::derive(recipient.secret_key(), &rotator.public_key()).unwrap();
1420        let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).unwrap();
1421        let inner = nostr_sdk::prelude::nip44::v2::decrypt_to_bytes(&ck, &payload).unwrap();
1422        assert_eq!(String::from_utf8(inner).unwrap(), bound_plaintext_b64(RekeyScope::Root, Epoch(1), &[5u8; 32]));
1423    }
1424
1425    #[test]
1426    fn distinct_recipients_and_scopes_get_distinct_locators() {
1427        let rotator = keys(7);
1428        let r1 = keys(8);
1429        let r2 = keys(9);
1430        assert_ne!(
1431            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1432            blob_locator(&xonly(&rotator), &xonly(&r2), RekeyScope::Root, Epoch(1))
1433        );
1434        // Same pair, a base blob and a channel blob at one epoch don't collide.
1435        assert_ne!(
1436            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1437            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Channel(CHAN), Epoch(1))
1438        );
1439    }
1440
1441    // ── 3303 event ─────────────────────────────────────────────────────────
1442
1443    fn root() -> [u8; 32] {
1444        [0x55u8; 32]
1445    }
1446
1447    #[test]
1448    fn channel_rekey_round_trips_through_the_stream() {
1449        let rotator = keys(1);
1450        let recipient = keys(8);
1451        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1452        let key = [0xABu8; 32];
1453        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &key).unwrap();
1454        let commit = epoch_key_commitment(Epoch(0), &[0xEEu8; 32]);
1455        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &commit, &[blob.clone()], 1, 1, 100, None, false).unwrap();
1456        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &rotator, Timestamp::from_secs(100)).unwrap();
1457
1458        // The wrap is signed by the group key, not the rotator (no identity on the wire).
1459        assert_ne!(wrap.pubkey, rotator.public_key());
1460        assert_eq!(wrap.pubkey, group.pk());
1461
1462        let opened = stream::open_wrap(&wrap, &group).unwrap();
1463        let chunk = parse_rekey_chunk(&opened).unwrap();
1464        assert_eq!(chunk.rotator, rotator.public_key(), "rotator recovered from the seal");
1465        assert!(matches!(chunk.scope, RekeyScope::Channel(c) if c.0 == CHAN.0));
1466        assert_eq!(chunk.new_epoch, Epoch(1));
1467        assert_eq!(chunk.prev_epoch, Epoch(0));
1468        assert_eq!(chunk.prev_commit, commit);
1469        assert_eq!(chunk.chunk, (1, 1));
1470        assert_eq!(chunk.blobs, vec![blob]);
1471    }
1472
1473    #[test]
1474    fn an_access_delivery_round_trips_and_never_reads_as_a_rotation() {
1475        let (deliverer, recipient) = (keys(1), keys(8));
1476        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1477        let key = [0xABu8; 32];
1478        let blob = build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(3), &key).unwrap();
1479        let rumor = build_access_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), std::slice::from_ref(&blob), 100).unwrap();
1480        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1481        let opened = stream::open_wrap(&wrap, &group).unwrap();
1482        let delivery = parse_access_delivery(&opened).unwrap();
1483        assert_eq!((delivery.deliverer, delivery.epoch), (deliverer.public_key(), Epoch(3)));
1484        let mine = find_my_blob(&delivery.blobs, &xonly(&deliverer), &xonly(&recipient), delivery.scope, delivery.epoch).unwrap();
1485        assert_eq!(open_blob_local(recipient.secret_key(), &deliverer.public_key(), delivery.scope, delivery.epoch, mine).unwrap(), key);
1486        assert!(parse_rekey_chunk(&opened).is_err(), "a delivery is no rotation");
1487        // Nor is a rotation a delivery.
1488        let commit = epoch_key_commitment(Epoch(2), &[0xEEu8; 32]);
1489        let rotation = build_rekey_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), Epoch(2), &commit, &[blob], 1, 1, 100, None, false).unwrap();
1490        let (wrap, _) = seal_rekey_chunk(&rotation, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1491        assert!(parse_access_delivery(&stream::open_wrap(&wrap, &group).unwrap()).is_err());
1492    }
1493
1494    #[test]
1495    fn a_history_delivery_round_trips_and_binds_its_channel_and_epoch() {
1496        let (deliverer, recipient) = (keys(1), keys(8));
1497        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1498        let past = crate::community::v2::derive::channel_group_key(&[0x42; 32], &CHAN, Epoch(2));
1499        let view = HistoryView::of(&past);
1500        let blob = build_history_blob_local(&deliverer, &recipient.public_key(), &CHAN, Epoch(2), &view).unwrap();
1501        let rumor = build_history_rumor(deliverer.public_key(), &CHAN, Epoch(2), std::slice::from_ref(&blob), 100).unwrap();
1502        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1503        let opened = stream::open_wrap(&wrap, &group).unwrap();
1504        let d = parse_history_delivery(&opened, &CHAN).unwrap();
1505        assert_eq!((d.deliverer, d.epoch), (deliverer.public_key(), Epoch(2)));
1506        assert_eq!(d.blobs[0].locator, history_locator(&xonly(&deliverer), &xonly(&recipient), &CHAN, Epoch(2)));
1507        assert_eq!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(2), &d.blobs[0]).unwrap(), view, "the address and key of that epoch");
1508        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(3), &d.blobs[0]), Err(RekeyError::EpochSplice)));
1509        let other = ChannelId([0x01; 32]);
1510        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &other, Epoch(2), &d.blobs[0]), Err(RekeyError::ScopeSplice)));
1511        assert!(parse_history_delivery(&opened, &other).is_err(), "another channel's history isn't this one's");
1512        assert!(parse_access_delivery(&opened).is_err() && parse_rekey_chunk(&opened).is_err(), "nor is it a key or a rotation");
1513        // The view really opens that epoch's plane.
1514        let msg = stream::build_rumor_secs(9, deliverer.public_key(), "old", vec![], 1);
1515        let (old_wrap, _) = stream::wrap_seal(&stream::build_seal(&msg, SealForm::Plaintext, &past, &deliverer).unwrap(), &past, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1516        let read = stream::open_wrap_at(&old_wrap, &PublicKey::from_slice(&view.address).unwrap(), &ConversationKey::new(view.conv_key), false).unwrap();
1517        assert_eq!(read.rumor.content, "old");
1518    }
1519
1520    #[test]
1521    fn base_rekey_addresses_under_the_prior_root() {
1522        // A base rotation rides the PRIOR root: a member holding the prior root
1523        // derives the same group key and opens it; a non-holder can't.
1524        let rotator = keys(1);
1525        let recipient = keys(8);
1526        let prior_root = [0x66u8; 32];
1527        let community = CommunityId([0x77u8; 32]);
1528        let new_root = [0x99u8; 32];
1529        let group = base_rekey_group(&prior_root, &community, Epoch(1));
1530        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &new_root).unwrap();
1531        let commit = epoch_key_commitment(Epoch(0), &prior_root);
1532        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &commit, &[blob], 100, None, false).unwrap();
1533        assert_eq!(chunks.len(), 1);
1534
1535        let opened = stream::open_wrap(&chunks[0], &group).unwrap();
1536        let chunk = parse_rekey_chunk(&opened).unwrap();
1537        assert!(matches!(chunk.scope, RekeyScope::Root));
1538        // The recipient recovers the NEW root from their blob.
1539        let mine = find_my_blob(&chunk.blobs, &chunk.rotator.to_bytes(), &xonly(&recipient), chunk.scope, chunk.new_epoch).unwrap();
1540        assert_eq!(open_blob_local(recipient.secret_key(), &chunk.rotator, chunk.scope, chunk.new_epoch, mine).unwrap(), new_root);
1541
1542        // A non-holder of the prior root can't even open the wrap.
1543        let wrong = base_rekey_group(&[0u8; 32], &community, Epoch(1));
1544        assert!(stream::open_wrap(&chunks[0], &wrong).is_err());
1545    }
1546
1547    #[test]
1548    fn a_full_send_chunk_stays_under_the_relay_size_limit() {
1549        // The send caps exist so one chunk fits a 64KB strfry event, each form at its own: a
1550        // base rotation's widest blob (136 bytes, a staff recipient), cited and severed, and a
1551        // Channel rotation's 72-byte one.
1552        let rotator = keys(1);
1553        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1554        let cite = crate::community::edition::AuthorityCitation { entity_id: [7; 32], version: u64::MAX, edition_hash: [8; 32] };
1555        let base: Vec<RekeyBlob> = (0..blobs_per_event(RekeyScope::Root))
1556            .map(|i| {
1557                let r = keys((i % 200 + 20) as u8);
1558                let inner = bound_base_plaintext_b64(Epoch(1), &[0xCD; 32], &[0xAB; 32], Some(&[0xEE; 32]));
1559                let ck = ConversationKey::derive(rotator.secret_key(), &r.public_key()).unwrap();
1560                let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).unwrap();
1561                RekeyBlob { locator: blob_locator(&xonly(&rotator), &r.public_key().to_bytes(), RekeyScope::Root, Epoch(1)), wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload) }
1562            })
1563            .collect();
1564        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &base, 100, Some(&cite), true).unwrap();
1565        assert_eq!(chunks.len(), 1, "a full base chunk is exactly one event");
1566        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full base chunk must fit a 64KB relay event", chunks[0].as_json().len());
1567
1568        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1569        let narrow: Vec<RekeyBlob> = (0..blobs_per_event(scope))
1570            .map(|i| build_blob_local(rotator.secret_key(), &xonly(&rotator), &keys((i % 200 + 20) as u8).public_key(), scope, Epoch(1), &[0xCDu8; 32]).unwrap())
1571            .collect();
1572        let chunks = build_rekey_chunks_local(&rotator, &group, scope, Epoch(1), Epoch(0), &[0u8; 32], &narrow, 100, Some(&cite), false).unwrap();
1573        assert_eq!(chunks.len(), 1);
1574        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full channel chunk must fit a 64KB relay event", chunks[0].as_json().len());
1575    }
1576
1577    #[test]
1578    fn a_full_history_delivery_stays_under_the_relay_size_limit() {
1579        let deliverer = keys(1);
1580        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1581        let channel = crate::community::ChannelId([3; 32]);
1582        let view = HistoryView { address: [0xAA; 32], conv_key: [0xBB; 32] };
1583        let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT).map(|i| build_history_blob_local(&deliverer, &keys((i % 200 + 20) as u8).public_key(), &channel, Epoch(1), &view).unwrap()).collect();
1584        let rumor = build_history_rumor(deliverer.public_key(), &channel, Epoch(1), &blobs, 100).unwrap();
1585        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1586        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1587        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full history delivery must fit a 64KB relay event", wrap.as_json().len());
1588    }
1589
1590    #[test]
1591    fn a_full_certified_delivery_stays_under_the_relay_size_limit() {
1592        let deliverer = keys(1);
1593        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1594        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1595        let recipients: Vec<Keys> = (0..MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| keys((i % 200 + 20) as u8)).collect();
1596        let blobs: Vec<RekeyBlob> = recipients.iter().map(|r| build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &r.public_key(), scope, Epoch(1), &[0xCD; 32]).unwrap()).collect();
1597        let certs: Vec<([u8; 32], [u8; 64])> = recipients.iter().map(|r| (r.public_key().to_bytes(), [0xEE; 64])).collect();
1598        let rumor = build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), Some([0x42; 32]), &blobs, &certs, 100).unwrap();
1599        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1600        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1601        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full certified chunk must fit a 64KB relay event", wrap.as_json().len());
1602    }
1603
1604    #[test]
1605    fn a_certified_delivery_past_its_cap_is_refused() {
1606        let deliverer = keys(1);
1607        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1608        let blobs: Vec<RekeyBlob> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() }).collect();
1609        let certs: Vec<([u8; 32], [u8; 64])> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| ([i as u8; 32], [0xEE; 64])).collect();
1610        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &certs, 100).is_err());
1611        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &[], 100).is_ok(), "keys alone fit more");
1612        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs[1..], &certs[1..], 100).is_ok());
1613    }
1614
1615    #[test]
1616    fn oversize_recipient_set_splits_into_chunks() {
1617        let rotator = keys(1);
1618        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1619        // One over the base rotation's send cap → 2 chunks, labeled (1,2) and (2,2).
1620        let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT + 1)
1621            .map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() })
1622            .collect();
1623        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(2), Epoch(1), &[0u8; 32], &blobs, 100, None, false).unwrap();
1624        assert_eq!(chunks.len(), 2);
1625        let parsed: Vec<RekeyChunk> = chunks.iter().map(|w| parse_rekey_chunk(&stream::open_wrap(w, &group).unwrap()).unwrap()).collect();
1626        assert_eq!(parsed[0].chunk, (1, 2));
1627        assert_eq!(parsed[1].chunk, (2, 2));
1628        assert_eq!(parsed[0].blobs.len(), MAX_WIDE_BLOBS_PER_EVENT);
1629        assert_eq!(parsed[1].blobs.len(), 1);
1630    }
1631
1632    #[test]
1633    fn plaintext_sealed_rekey_is_rejected() {
1634        let rotator = keys(1);
1635        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1636        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &[0u8; 32], &[], 1, 1, 100, None, false).unwrap();
1637        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &rotator).unwrap();
1638        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1639        let opened = stream::open_wrap(&wrap, &group).unwrap();
1640        assert!(parse_rekey_chunk(&opened).is_err(), "the rekey plane must be encrypted-sealed");
1641    }
1642
1643    #[test]
1644    fn non_monotonic_epoch_is_refused_at_mint_and_on_parse() {
1645        let rotator = keys(1);
1646        assert!(matches!(
1647            build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(1), &[0u8; 32], &[], 1, 1, 100, None, false),
1648            Err(RekeyError::NonMonotonicEpoch)
1649        ));
1650    }
1651
1652    #[test]
1653    fn bad_chunk_indices_are_refused() {
1654        let rotator = keys(1);
1655        for (i, n) in [(0u32, 1u32), (2, 1), (1, 0)] {
1656            assert!(
1657                matches!(build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &[], i, n, 100, None, false), Err(RekeyError::BadChunkIndex)),
1658                "chunk ({i},{n}) must be rejected"
1659            );
1660        }
1661    }
1662
1663    // ── continuity + removal + fork ──────────────────────────────────────────
1664
1665    fn chunk_at(rotator: &Keys, scope: RekeyScope, new_epoch: u64, prev_epoch: u64, prev_key: &[u8; 32], blobs: Vec<RekeyBlob>, i: u32, n: u32) -> RekeyChunk {
1666        RekeyChunk {
1667            rotator: rotator.public_key(),
1668            scope,
1669            new_epoch: Epoch(new_epoch),
1670            prev_epoch: Epoch(prev_epoch),
1671            prev_commit: epoch_key_commitment(Epoch(prev_epoch), prev_key),
1672            chunk: (i, n),
1673            blobs,
1674            citation: None,
1675            severed: false,
1676            at_ms: 0,
1677        }
1678    }
1679
1680    #[test]
1681    fn a_rotation_dates_from_its_earliest_chunk() {
1682        let rotator = Keys::generate();
1683        let prev = [3u8; 32];
1684        let mut late = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1685        late.at_ms = 9_000;
1686        let mut early = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1687        early.at_ms = 4_000;
1688        let rotations = collect_rotations(&[late, early]);
1689        assert_eq!(rotations.len(), 1);
1690        assert_eq!(rotations[0].at_ms, 4_000, "a re-sent chunk never moves a rotation later");
1691    }
1692
1693    #[test]
1694    fn a_colliding_chunk_index_must_not_swallow_a_recipients_blob() {
1695        // Chunks are correlated by index, and a second chunk claiming an index
1696        // already held is treated as idempotent re-delivery — its blobs dropped.
1697        // That is safe only while re-delivery is byte-identical. The catch-up path
1698        // that extends a rotation computes its starting index from a fetch that can
1699        // come back blind, and then re-claims index 1; whichever copy a client sees
1700        // first wins, so the original recipients in the loser vanish from the union.
1701        // A recipient whose blob vanishes reads as REMOVED — and removal deletes the
1702        // community locally. Losing a blob to a bookkeeping collision must never be
1703        // able to masquerade as a removal verdict.
1704        let rotator = keys(1);
1705        let prev = [0x55u8; 32];
1706        let mine = RekeyBlob { locator: "aa".repeat(32), wrapped: "mine".into() };
1707        let other = RekeyBlob { locator: "bb".repeat(32), wrapped: "other".into() };
1708
1709        // Two chunks both claiming index 1: the original (carrying my blob) and a
1710        // re-claim (carrying someone else's).
1711        let original = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![mine.clone()], 1, 1);
1712        let reclaim = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![other.clone()], 1, 1);
1713
1714        for (order, chunks) in [
1715            ("original first", vec![original.clone(), reclaim.clone()]),
1716            ("reclaim first", vec![reclaim.clone(), original.clone()]),
1717        ] {
1718            let rotations = collect_rotations(&chunks);
1719            assert_eq!(rotations.len(), 1, "{order}: same correlation key");
1720            let has_mine = rotations[0].blobs.iter().any(|b| b.locator == mine.locator);
1721            assert!(
1722                has_mine,
1723                "{order}: my blob was dropped by an index collision — that reads as a removal \
1724                 and removal deletes the community",
1725            );
1726        }
1727    }
1728
1729    #[test]
1730    fn a_severed_rotation_cannot_be_laundered_by_an_unmarked_chunk() {
1731        // The containment marker rides EVERY chunk of a rotation, but a rotation's
1732        // chunk set can be extended later (the catch-up path for members a rotation
1733        // forgot). An extension built without the marker would, under first-seen
1734        // semantics, present a severed epoch as an ordinary one — and an adopter
1735        // reading it that way refreshes the very invite links the containment meant
1736        // to bury, re-opening the door the raid came through. The fold is therefore
1737        // an OR across chunks, in either arrival order.
1738        let rotator = keys(1);
1739        let prev = [0x44u8; 32];
1740        let mut marked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1741        marked.severed = true;
1742        let unmarked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1743
1744        for (order, chunks) in [
1745            ("marked first", vec![marked.clone(), unmarked.clone()]),
1746            ("unmarked first", vec![unmarked.clone(), marked.clone()]),
1747        ] {
1748            let rotations = collect_rotations(&chunks);
1749            assert_eq!(rotations.len(), 1, "{order}: one correlation key, one rotation");
1750            assert!(
1751                rotations[0].severed,
1752                "{order}: an unmarked sibling must never launder the containment away",
1753            );
1754            assert!(rotations[0].is_complete(), "{order}: both chunks held");
1755        }
1756    }
1757
1758    #[test]
1759    fn continuity_extends_gaps_and_forks() {
1760        let rotator = keys(1);
1761        let held = [0x33u8; 32];
1762        // Extends: prev_epoch == held epoch AND commitment matches the held key.
1763        let good = chunk_at(&rotator, RekeyScope::Root, 3, 2, &held, vec![], 1, 1);
1764        assert_eq!(check_continuity(&good, Epoch(2), &held), Continuity::Extends);
1765        // Gap: the rotation is FROM a higher epoch than I hold — I missed one.
1766        let ahead = chunk_at(&rotator, RekeyScope::Root, 5, 4, &held, vec![], 1, 1);
1767        assert_eq!(check_continuity(&ahead, Epoch(2), &held), Continuity::Gap);
1768        // Fork: same epoch but the commitment names a different prior key.
1769        let fork = chunk_at(&rotator, RekeyScope::Root, 3, 2, &[0x99u8; 32], vec![], 1, 1);
1770        assert_eq!(check_continuity(&fork, Epoch(2), &held), Continuity::Fork);
1771        // Fork: a rotation older than where I am (stale).
1772        let stale = chunk_at(&rotator, RekeyScope::Root, 2, 1, &held, vec![], 1, 1);
1773        assert_eq!(check_continuity(&stale, Epoch(2), &held), Continuity::Fork);
1774    }
1775
1776    #[test]
1777    fn a_missing_chunk_is_never_a_removal() {
1778        // The core no-false-removal guarantee: until ALL n chunks are held, "am I
1779        // removed" is unanswerable, even if the chunks I DO hold lack my blob.
1780        let rotator = keys(1);
1781        let me = keys(8);
1782        // Two-chunk rotation; my blob is in chunk 2, which I haven't received.
1783        let my_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &me.public_key(), RekeyScope::Root, Epoch(1), &[0xAAu8; 32]).unwrap();
1784        let c1 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![RekeyBlob { locator: "bb".repeat(32), wrapped: "x".into() }], 1, 2);
1785        let rots = collect_rotations(&[c1.clone()]);
1786        assert_eq!(rots.len(), 1);
1787        assert!(!rots[0].is_complete(), "one of two chunks held → incomplete");
1788        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), None, "incomplete → keep recovering, never conclude removal");
1789
1790        // Now chunk 2 (with my blob) arrives → complete, and I am NOT removed.
1791        let c2 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![my_blob.clone()], 2, 2);
1792        let rots = collect_rotations(&[c1, c2]);
1793        assert!(rots[0].is_complete());
1794        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(false));
1795        // And my key is recoverable from the union.
1796        let mine = find_my_blob(&rots[0].blobs, &rots[0].rotator.to_bytes(), &xonly(&me), RekeyScope::Root, Epoch(1)).unwrap();
1797        assert_eq!(open_blob_local(me.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), mine).unwrap(), [0xAAu8; 32]);
1798    }
1799
1800    #[test]
1801    fn a_complete_rotation_without_my_blob_is_a_removal() {
1802        let rotator = keys(1);
1803        let me = keys(8);
1804        let other = keys(9);
1805        // A complete 1-chunk rotation carrying only someone else's blob.
1806        let their_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &other.public_key(), RekeyScope::Root, Epoch(1), &[0xBBu8; 32]).unwrap();
1807        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![their_blob], 1, 1);
1808        let rots = collect_rotations(&[c]);
1809        assert!(rots[0].is_complete());
1810        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(true), "complete rotation, no blob for me → removed");
1811    }
1812
1813    #[test]
1814    fn collect_rotations_separates_concurrent_rotators_and_scopes() {
1815        // Two rotators racing the same epoch, plus a channel rekey at the same
1816        // numbers — three distinct rotations, never merged.
1817        let rot_a = keys(1);
1818        let rot_b = keys(2);
1819        let ca = chunk_at(&rot_a, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1820        let cb = chunk_at(&rot_b, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1821        let cc = chunk_at(&rot_a, RekeyScope::Channel(CHAN), 2, 1, &[7u8; 32], vec![], 1, 1);
1822        let rots = collect_rotations(&[ca, cb, cc]);
1823        assert_eq!(rots.len(), 3, "different rotator or scope ⇒ different rotation");
1824    }
1825
1826    #[test]
1827    fn duplicate_chunk_delivery_is_idempotent() {
1828        let rotator = keys(1);
1829        let blob = RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() };
1830        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![blob.clone()], 1, 1);
1831        let rots = collect_rotations(&[c.clone(), c]);
1832        assert_eq!(rots.len(), 1);
1833        assert_eq!(rots[0].blobs.len(), 1, "re-delivering a chunk must not double its blobs");
1834    }
1835
1836    // ── base blob forms + control_wrap (CORD-06 §1, CORD-04 §3) ──────────────
1837
1838    #[test]
1839    fn base_blob_forms_are_width_declared() {
1840        let community = CommunityId([0x77u8; 32]);
1841        let new_root = [0xABu8; 32];
1842        let control_root = [0x5Cu8; 32];
1843        let epoch = Epoch(3);
1844        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1845
1846        // 104-byte member form: root + pk, no secret.
1847        let member = bound_base_plaintext(epoch, &new_root, &control_pk, None);
1848        assert_eq!(member.len(), 104);
1849        let d = parse_bound_base_plaintext(&member, &community, epoch).unwrap();
1850        assert_eq!(d.new_root, new_root);
1851        assert_eq!(d.control_pk, Some(control_pk));
1852        assert_eq!(d.control_root, None);
1853
1854        // 136-byte staff form carries the secret, verified against its own pk.
1855        let staff = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1856        assert_eq!(staff.len(), 136);
1857        let d = parse_bound_base_plaintext(&staff, &community, epoch).unwrap();
1858        assert_eq!(d.control_root, Some(control_root));
1859        assert_eq!(d.control_pk, Some(control_pk));
1860
1861        // Legacy 72-byte base form yields the root alone.
1862        let legacy = bound_plaintext(RekeyScope::Root, epoch, &new_root);
1863        let d = parse_bound_base_plaintext(&legacy, &community, epoch).unwrap();
1864        assert_eq!(d.new_root, new_root);
1865        assert_eq!(d.control_pk, None);
1866        assert_eq!(d.control_root, None);
1867    }
1868
1869    #[test]
1870    fn base_blob_mismatched_control_pair_is_refused_whole() {
1871        let community = CommunityId([0x77u8; 32]);
1872        let control_pk = control_signer_group_key(&[0x5Cu8; 32], &community, Epoch(3)).pk().to_bytes();
1873        // A secret that does NOT derive to the carried pk — the whole blob is
1874        // dropped, the new_root included (never a partial adoption).
1875        let bad = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &control_pk, Some(&[0x11u8; 32]));
1876        assert!(matches!(
1877            parse_bound_base_plaintext(&bad, &community, Epoch(3)),
1878            Err(RekeyError::ControlPairMismatch)
1879        ));
1880    }
1881
1882    #[test]
1883    fn base_blob_rejects_any_other_width_and_splices() {
1884        let community = CommunityId([0x77u8; 32]);
1885        // Below and between the defined forms: no append-only extension fits.
1886        for n in [0usize, 71, 73, 100, 105, 135] {
1887            assert!(matches!(
1888                parse_bound_base_plaintext(&vec![0u8; n], &community, Epoch(1)),
1889                Err(RekeyError::BadBaseBlobWidth(m)) if m == n
1890            ));
1891        }
1892        // The scope and epoch bind INSIDE the ciphertext (unspliceable).
1893        let control_root = [0x5Cu8; 32];
1894        let pk = control_signer_group_key(&control_root, &community, Epoch(3)).pk().to_bytes();
1895        let pt = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &pk, None);
1896        assert!(matches!(parse_bound_base_plaintext(&pt, &community, Epoch(4)), Err(RekeyError::EpochSplice)));
1897        let mut channel_scoped = pt.clone();
1898        channel_scoped[..32].copy_from_slice(&[0x42u8; 32]);
1899        assert!(matches!(parse_bound_base_plaintext(&channel_scoped, &community, Epoch(3)), Err(RekeyError::ScopeSplice)));
1900    }
1901
1902    #[tokio::test]
1903    async fn base_blob_round_trips_member_and_staff_forms() {
1904        let rotator = keys(7);
1905        let member = keys(8);
1906        let staffer = keys(9);
1907        let community = CommunityId([0x77u8; 32]);
1908        let epoch = Epoch(2);
1909        let new_root = [0xEEu8; 32];
1910        let control_root = [0xDDu8; 32];
1911        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1912
1913        let mb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), epoch, &new_root, &control_pk, None).await.unwrap();
1914        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &mb).await.unwrap();
1915        assert_eq!(d.new_root, new_root);
1916        assert_eq!(d.control_pk, Some(control_pk));
1917        assert_eq!(d.control_root, None, "a member blob never carries the secret");
1918
1919        let sb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &staffer.public_key(), epoch, &new_root, &control_pk, Some(&control_root)).await.unwrap();
1920        let d = open_base_blob(&as_signer(&staffer), &rotator.public_key(), &community, epoch, &sb).await.unwrap();
1921        assert_eq!(d.control_root, Some(control_root));
1922
1923        // The locator is the same public Root-scope slot the legacy form used.
1924        assert_eq!(mb.locator, blob_locator(&xonly(&rotator), &xonly(&member), RekeyScope::Root, epoch));
1925        // And a legacy 72-byte blob still opens through the base opener.
1926        let legacy = build_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), RekeyScope::Root, epoch, &new_root).await.unwrap();
1927        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &legacy).await.unwrap();
1928        assert_eq!(d.new_root, new_root);
1929        assert_eq!(d.control_pk, None);
1930    }
1931
1932    #[test]
1933    fn a_future_wider_base_blob_degrades_instead_of_forking() {
1934        // The pre-split lesson (CORD-06 §3): a width this build predates must
1935        // never park the member at the old epoch — extract the frozen prefix
1936        // and whatever appended fields still verify.
1937        let community = CommunityId([0x77u8; 32]);
1938        let new_root = [0xABu8; 32];
1939        let control_root = [0x5Cu8; 32];
1940        let epoch = Epoch(3);
1941        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1942
1943        // A hypothetical 168-byte form that appended a field after the secret.
1944        let mut future = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1945        future.extend_from_slice(&[0x99u8; 32]);
1946        let d = parse_bound_base_plaintext(&future, &community, epoch).unwrap();
1947        assert_eq!(d.new_root, new_root);
1948        assert_eq!(d.control_pk, Some(control_pk));
1949        assert_eq!(d.control_root, Some(control_root), "held offsets still verify → full function");
1950
1951        // One that REPLACED the secret's bytes: the derive check fails closed
1952        // to the verified prefix, never a refusal (membership must survive).
1953        let mut reordered = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&[0x44u8; 32]));
1954        reordered.extend_from_slice(&[0x99u8; 32]);
1955        let d = parse_bound_base_plaintext(&reordered, &community, epoch).unwrap();
1956        assert_eq!(d.new_root, new_root);
1957        assert_eq!(d.control_pk, Some(control_pk));
1958        assert_eq!(d.control_root, None, "an unverifiable secret is dropped, not adopted");
1959
1960        // The prefix's splice bindings still gate a future form.
1961        assert!(parse_bound_base_plaintext(&future, &community, Epoch(4)).is_err());
1962    }
1963
1964    #[test]
1965    fn control_wrap_layout_is_frozen_and_round_trips() {
1966        let pt = encode_control_wrap(Epoch(7), &[0xCDu8; 32]);
1967        assert_eq!(pt.len(), 40);
1968        let expected = format!("{}{}", "0000000000000007", "cd".repeat(32));
1969        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
1970        let (epoch, root) = parse_control_wrap(&pt).unwrap();
1971        assert_eq!(epoch, Epoch(7));
1972        assert_eq!(root, [0xCDu8; 32]);
1973        for n in [0usize, 39, 41, 72] {
1974            assert!(matches!(parse_control_wrap(&vec![0u8; n]), Err(RekeyError::BadControlWrapLength(m)) if m == n));
1975        }
1976    }
1977
1978    #[test]
1979    fn lowest_key_fork_winner_is_deterministic() {
1980        // CORD-06 §3: among candidates, the lexicographically lowest new key wins,
1981        // so every retained member converges. Input order must not change it.
1982        let keys_a = [[0x03u8; 32], [0x01u8; 32], [0x02u8; 32]];
1983        assert_eq!(lowest_key_winner(&keys_a), Some(1));
1984        let keys_b = [[0x01u8; 32], [0x02u8; 32], [0x03u8; 32]];
1985        assert_eq!(lowest_key_winner(&keys_b), Some(0));
1986        assert_eq!(lowest_key_winner(&[]), None);
1987    }
1988}