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    /// Scoped writer certificates, by recipient, with the CORD-04 bits each covers.
813    pub scoped: Vec<([u8; 32], [u8; 64], u64)>,
814    /// For one part of a writer epoch's minting delivery, which part of how many.
815    pub mint: Option<(u32, u32)>,
816}
817
818/// Marks one event of a writer epoch's minting delivery: `["mint", <part>, <parts>]`, from 1.
819const TAG_MINT: &str = "mint";
820
821/// `rumor` as part `part` of `parts` of a minting delivery, its id recomputed.
822pub fn as_mint_part(rumor: UnsignedEvent, part: usize, parts: usize) -> UnsignedEvent {
823    use crate::event_ext::FinalizeUnsignedWithId as _;
824    let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
825    tags.push(Tag::custom(TAG_MINT, [part.to_string(), parts.to_string()]));
826    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);
827    out.ensure_id();
828    out
829}
830
831/// A writer-scope delivery's claimed address.
832const TAG_WRITER: &str = "writer";
833
834/// A writer certificate for one recipient: `["cert", <recipient hex>, <signature hex>]`.
835const TAG_CERT: &str = "cert";
836
837/// A scoped writer certificate for one recipient: `["rcert", <recipient hex>, <signature hex>,
838/// <rights decimal>]`.
839const TAG_SCOPED_CERT: &str = "rcert";
840
841/// The unsigned access-plane 3303 rumor.
842pub fn build_access_rumor(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
843    build_access_rumor_for(deliverer, scope, epoch, None, blobs, at_secs)
844}
845
846/// [`build_access_rumor`] naming, for a writer key, the address it derives to.
847pub fn build_access_rumor_for(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
848    build_access_rumor_certified(deliverer, scope, epoch, writer, blobs, &[], at_secs)
849}
850
851/// [`build_access_rumor_for`], handing writer certificates to its recipients.
852pub 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> {
853    build_access_rumor_scoped(deliverer, scope, epoch, writer, blobs, certs, &[], at_secs)
854}
855
856/// [`build_access_rumor_certified`], with scoped certificates for recipients who may write only
857/// some kinds.
858#[allow(clippy::too_many_arguments)]
859pub fn build_access_rumor_scoped(
860    deliverer: PublicKey,
861    scope: RekeyScope,
862    epoch: Epoch,
863    writer: Option<[u8; 32]>,
864    blobs: &[RekeyBlob],
865    certs: &[([u8; 32], [u8; 64])],
866    scoped: &[([u8; 32], [u8; 64], u64)],
867    at_secs: u64,
868) -> Result<UnsignedEvent, RekeyError> {
869    let carried = certs.len() + scoped.len();
870    let cap = if carried == 0 { MAX_REKEY_BLOBS_PER_EVENT } else { MAX_CERTIFIED_BLOBS_PER_EVENT };
871    if blobs.len() > cap || carried > MAX_CERTIFIED_BLOBS_PER_EVENT {
872        return Err(RekeyError::TooManyBlobs(blobs.len().max(carried)));
873    }
874    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
875    let mut tags = vec![
876        Tag::custom(TAG_SCOPE, [scope.to_hex()]),
877        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
878        Tag::custom(TAG_DELIVERY, [DELIVERY_ACCESS]),
879    ];
880    if let Some(pk) = writer {
881        tags.push(Tag::custom(TAG_WRITER, [crate::simd::hex::bytes_to_hex_32(&pk)]));
882    }
883    for (who, cert) in certs {
884        tags.push(Tag::custom(TAG_CERT, [crate::simd::hex::bytes_to_hex_32(who), crate::simd::hex::bytes_to_hex_string(cert)]));
885    }
886    for (who, cert, rights) in scoped {
887        tags.push(Tag::custom(TAG_SCOPED_CERT, [crate::simd::hex::bytes_to_hex_32(who), crate::simd::hex::bytes_to_hex_string(cert), rights.to_string()]));
888    }
889    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
890}
891
892/// Parse an opened access-plane event. Anything not tagged as an access delivery is refused.
893pub fn parse_access_delivery(opened: &OpenedStream) -> Result<AccessDelivery, RekeyError> {
894    if opened.seal_form != SealForm::Encrypted {
895        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
896    }
897    let rumor = &opened.rumor;
898    if rumor.kind.as_u16() != super::kind::REKEY {
899        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
900    }
901    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_ACCESS) {
902        return Err(RekeyError::BadTag(TAG_DELIVERY));
903    }
904    let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
905        .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
906    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
907    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
908    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
909        return Err(RekeyError::TooManyBlobs(blobs.len()));
910    }
911    let writer = match unique_tag(rumor, TAG_WRITER)? {
912        None => None,
913        Some(hex) => Some(crate::simd::hex::hex_to_bytes_32_checked(&hex).ok_or(RekeyError::BadTag(TAG_WRITER))?),
914    };
915    // A malformed certificate is no certificate; it never refuses the delivery it rides.
916    let certs = rumor
917        .tags
918        .iter()
919        .filter_map(|t| {
920            let s = t.as_slice();
921            (s.first().map(String::as_str) == Some(TAG_CERT) && s.len() == 3).then_some(())?;
922            let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
923            let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
924            Some((who, cert))
925        })
926        .take(MAX_REKEY_BLOBS_RECEIVED)
927        .collect();
928    let scoped = rumor
929        .tags
930        .iter()
931        .filter_map(|t| {
932            let s = t.as_slice();
933            (s.first().map(String::as_str) == Some(TAG_SCOPED_CERT) && s.len() == 4).then_some(())?;
934            let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
935            let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
936            let rights = s[3].parse::<u64>().ok().filter(|n| n.to_string() == s[3])?;
937            Some((who, cert, rights))
938        })
939        .take(MAX_REKEY_BLOBS_RECEIVED)
940        .collect();
941    let mint = rumor
942        .tags
943        .iter()
944        .map(|t| t.as_slice())
945        .find(|t| t.first().map(String::as_str) == Some(TAG_MINT))
946        .and_then(|t| Some((t.get(1)?.parse::<u32>().ok()?, t.get(2)?.parse::<u32>().ok()?)))
947        .filter(|(part, parts)| *part >= 1 && part <= parts);
948    Ok(AccessDelivery { deliverer: opened.author, scope, epoch, blobs, writer, certs, scoped, mint })
949}
950
951/// A Channel's history scope (CORD-03 §5): what history blobs bind to, so one can never be
952/// spliced in as a current key.
953pub fn history_scope(channel: &ChannelId) -> [u8; 32] {
954    use sha2::{Digest, Sha256};
955    let mut h = Sha256::new();
956    h.update(b"concord/history-scope");
957    h.update(channel.0);
958    h.finalize().into()
959}
960
961/// A past epoch's read view of a Channel (CORD-03 §5): where its messages are and the key that
962/// opens them, never the secret that signs into it.
963#[derive(Clone, PartialEq, Eq)]
964pub struct HistoryView {
965    pub address: [u8; 32],
966    pub conv_key: [u8; 32],
967}
968
969impl std::fmt::Debug for HistoryView {
970    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
971        f.debug_struct("HistoryView").field("address", &crate::simd::hex::bytes_to_hex_32(&self.address)).finish_non_exhaustive()
972    }
973}
974
975impl HistoryView {
976    pub fn of(group: &GroupKey) -> Self {
977        let mut conv_key = [0u8; 32];
978        conv_key.copy_from_slice(group.conv_key().as_bytes());
979        HistoryView { address: group.pk().to_bytes(), conv_key }
980    }
981}
982
983/// `history_scope[32] ‖ epoch_be[8] ‖ address[32] ‖ conv_key[32]`.
984fn history_plaintext_b64(channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Zeroizing<String> {
985    let mut pt = Zeroizing::new([0u8; 104]);
986    pt[..32].copy_from_slice(&history_scope(channel));
987    pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
988    pt[40..72].copy_from_slice(&view.address);
989    pt[72..].copy_from_slice(&view.conv_key);
990    Zeroizing::new(crate::simd::base64::STANDARD.encode_to_string(&pt[..]))
991}
992
993fn parse_history_plaintext(pt: &[u8], channel: &ChannelId, epoch: Epoch) -> Result<HistoryView, RekeyError> {
994    if pt.len() != 104 {
995        return Err(RekeyError::BadBlobLength(pt.len()));
996    }
997    if pt[..32] != history_scope(channel) {
998        return Err(RekeyError::ScopeSplice);
999    }
1000    if pt[32..40] != epoch.0.to_be_bytes() {
1001        return Err(RekeyError::EpochSplice);
1002    }
1003    let (mut address, mut conv_key) = ([0u8; 32], [0u8; 32]);
1004    address.copy_from_slice(&pt[40..72]);
1005    conv_key.copy_from_slice(&pt[72..]);
1006    Ok(HistoryView { address, conv_key })
1007}
1008
1009/// The public locator of `recipient`'s history blob for `epoch` from `deliverer`.
1010pub fn history_locator(deliverer_xonly: &[u8; 32], recipient_xonly: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> String {
1011    crate::simd::hex::bytes_to_hex_32(&recipient_locator(deliverer_xonly, recipient_xonly, &history_scope(channel), epoch))
1012}
1013
1014pub async fn build_history_blob<S: crate::signer::VectorSigner + ?Sized>(
1015    signer: &S,
1016    deliverer_xonly: &[u8; 32],
1017    recipient: &PublicKey,
1018    channel: &ChannelId,
1019    epoch: Epoch,
1020    view: &HistoryView,
1021) -> Result<RekeyBlob, RekeyError> {
1022    let inner = history_plaintext_b64(channel, epoch, view);
1023    let wrapped = signer.nip44_encrypt_async(recipient, inner.as_str()).await.map_err(|e| RekeyError::Crypto(e.to_string()))?;
1024    Ok(RekeyBlob { locator: history_locator(deliverer_xonly, &recipient.to_bytes(), channel, epoch), wrapped })
1025}
1026
1027pub async fn open_history_blob<S: crate::signer::VectorSigner + ?Sized>(
1028    signer: &S,
1029    deliverer: &PublicKey,
1030    channel: &ChannelId,
1031    epoch: Epoch,
1032    blob: &RekeyBlob,
1033) -> Result<HistoryView, RekeyError> {
1034    let inner = Zeroizing::new(signer.nip44_decrypt_async(deliverer, &blob.wrapped).await.map_err(|e| RekeyError::Crypto(e.to_string()))?);
1035    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1036    parse_history_plaintext(&pt, channel, epoch)
1037}
1038
1039/// [`build_history_blob`] with local keys.
1040pub fn build_history_blob_local(deliverer: &Keys, recipient: &PublicKey, channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Result<RekeyBlob, RekeyError> {
1041    let inner = history_plaintext_b64(channel, epoch, view);
1042    let ck = ConversationKey::derive(deliverer.secret_key(), recipient).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1043    let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1044    Ok(RekeyBlob {
1045        locator: history_locator(&deliverer.public_key().to_bytes(), &recipient.to_bytes(), channel, epoch),
1046        wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
1047    })
1048}
1049
1050/// [`open_history_blob`] with local keys.
1051pub fn open_history_blob_local(me: &SecretKey, deliverer: &PublicKey, channel: &ChannelId, epoch: Epoch, blob: &RekeyBlob) -> Result<HistoryView, RekeyError> {
1052    let ck = ConversationKey::derive(me, deliverer).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1053    let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1054    let inner = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1055    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_slice()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1056    parse_history_plaintext(&pt, channel, epoch)
1057}
1058
1059/// One epoch's history blobs on a Channel's access plane.
1060#[derive(Debug, Clone)]
1061pub struct HistoryDelivery {
1062    pub deliverer: PublicKey,
1063    pub epoch: Epoch,
1064    pub blobs: Vec<RekeyBlob>,
1065}
1066
1067pub fn build_history_rumor(deliverer: PublicKey, channel: &ChannelId, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
1068    if blobs.len() > MAX_WIDE_BLOBS_PER_EVENT {
1069        return Err(RekeyError::TooManyBlobs(blobs.len()));
1070    }
1071    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1072    let tags = vec![
1073        Tag::custom(TAG_SCOPE, [crate::simd::hex::bytes_to_hex_32(&history_scope(channel))]),
1074        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
1075        Tag::custom(TAG_DELIVERY, [DELIVERY_HISTORY]),
1076    ];
1077    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
1078}
1079
1080/// Parse an opened access-plane event as `channel`'s history, refusing anything else.
1081pub fn parse_history_delivery(opened: &OpenedStream, channel: &ChannelId) -> Result<HistoryDelivery, RekeyError> {
1082    if opened.seal_form != SealForm::Encrypted {
1083        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
1084    }
1085    let rumor = &opened.rumor;
1086    if rumor.kind.as_u16() != super::kind::REKEY {
1087        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
1088    }
1089    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_HISTORY) {
1090        return Err(RekeyError::BadTag(TAG_DELIVERY));
1091    }
1092    if unique_tag(rumor, TAG_SCOPE)?.as_deref() != Some(crate::simd::hex::bytes_to_hex_32(&history_scope(channel)).as_str()) {
1093        return Err(RekeyError::BadTag(TAG_SCOPE));
1094    }
1095    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
1096    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
1097    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
1098        return Err(RekeyError::TooManyBlobs(blobs.len()));
1099    }
1100    Ok(HistoryDelivery { deliverer: opened.author, epoch, blobs })
1101}
1102
1103// ── Continuity + removal + fork resolution (CORD-06 §2/§3) ───────────────────
1104
1105/// The verdict of the prevcommit continuity check (CORD-06 §2).
1106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1107pub enum Continuity {
1108    /// The commitment matches the key I hold at `prev_epoch` — this rotation
1109    /// extends my chain; adopt it.
1110    Extends,
1111    /// `prev_epoch` is higher than the key I hold — I missed a rotation; fetch
1112    /// the gap first, don't adopt yet.
1113    Gap,
1114    /// The commitment doesn't match at the same epoch — a fork or garbage.
1115    Fork,
1116}
1117
1118/// Check a rotation's `prev_commit` against the `(epoch, key)` I currently hold
1119/// for its scope. A match proves the rotation extends the very key I hold; a
1120/// higher `prev_epoch` means I'm behind; anything else is a fork/garbage.
1121pub fn check_continuity(chunk: &RekeyChunk, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1122    if chunk.prev_epoch.0 == held_epoch.0 {
1123        if epoch_key_commitment(held_epoch, held_key) == chunk.prev_commit {
1124            Continuity::Extends
1125        } else {
1126            Continuity::Fork
1127        }
1128    } else if chunk.prev_epoch.0 > held_epoch.0 {
1129        Continuity::Gap
1130    } else {
1131        // prev_epoch < held: this rotation is older than where I am — a stale
1132        // fork; a settled epoch only ever heals DOWN to a sibling, never back.
1133        Continuity::Fork
1134    }
1135}
1136
1137/// A collected rotation: all chunks sharing one correlation key, and whether the
1138/// set is complete (all `n` chunks present).
1139#[derive(Debug, Clone)]
1140pub struct Rotation {
1141    pub rotator: PublicKey,
1142    pub scope: RekeyScope,
1143    pub new_epoch: Epoch,
1144    pub prev_epoch: Epoch,
1145    pub prev_commit: [u8; 32],
1146    /// The union of every chunk's blobs.
1147    pub blobs: Vec<RekeyBlob>,
1148    /// Total chunk count `n` declared by the chunks.
1149    pub declared_chunks: u32,
1150    /// Distinct chunk indices actually held.
1151    pub held_chunks: std::collections::BTreeSet<u32>,
1152    /// The rotator's `vac`, taken from the first chunk seen (every chunk of one
1153    /// rotation carries the same citation — they share a signer and an action).
1154    pub citation: Option<crate::community::edition::AuthorityCitation>,
1155    /// OR across chunks: any severed chunk marks the whole rotation severed, so
1156    /// an extension (rescue) can never launder the flag away.
1157    pub severed: bool,
1158    /// When it was sent: its earliest chunk's time, in ms.
1159    pub at_ms: u64,
1160}
1161
1162impl Rotation {
1163    /// True once every declared chunk index `1..=n` is held — the precondition
1164    /// for concluding removal (a missing chunk is "keep recovering", never a
1165    /// removal).
1166    pub fn is_complete(&self) -> bool {
1167        self.declared_chunks >= 1 && (1..=self.declared_chunks).all(|i| self.held_chunks.contains(&i))
1168    }
1169
1170    /// This rotation's continuity against the `(epoch, key)` I hold for its scope
1171    /// — the [`check_continuity`] verdict at the aggregated-rotation level (same
1172    /// prevcommit test), so a follower can gate adoption without a raw chunk.
1173    pub fn continuity(&self, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1174        if self.prev_epoch.0 == held_epoch.0 {
1175            if epoch_key_commitment(held_epoch, held_key) == self.prev_commit {
1176                Continuity::Extends
1177            } else {
1178                Continuity::Fork
1179            }
1180        } else if self.prev_epoch.0 > held_epoch.0 {
1181            Continuity::Gap
1182        } else {
1183            Continuity::Fork
1184        }
1185    }
1186}
1187
1188/// Group a batch of parsed chunks into rotations by correlation key. Chunks whose
1189/// `n` disagrees with their siblings, or that repeat an index, are the caller's
1190/// concern to police; here the largest `n` any chunk declares sets the total, and a
1191/// second chunk at a held index unions its blobs.
1192pub fn collect_rotations(chunks: &[RekeyChunk]) -> Vec<Rotation> {
1193    use std::collections::BTreeMap;
1194    let mut by_key: BTreeMap<RotationKey, Rotation> = BTreeMap::new();
1195    for c in chunks {
1196        let entry = by_key.entry(c.correlation()).or_insert_with(|| Rotation {
1197            rotator: c.rotator,
1198            scope: c.scope,
1199            new_epoch: c.new_epoch,
1200            prev_epoch: c.prev_epoch,
1201            prev_commit: c.prev_commit,
1202            blobs: Vec::new(),
1203            declared_chunks: c.chunk.1,
1204            held_chunks: std::collections::BTreeSet::new(),
1205            citation: c.citation.clone(),
1206            severed: c.severed,
1207            at_ms: c.at_ms,
1208        });
1209        entry.severed |= c.severed;
1210        entry.at_ms = entry.at_ms.min(c.at_ms);
1211        // An extension declares the larger total: complete only once every index up to it is held.
1212        entry.declared_chunks = entry.declared_chunks.max(c.chunk.1);
1213        // UNION the blobs, even when the index is already held. Treating a second
1214        // chunk at a known index as pure idempotent re-delivery is safe only while
1215        // re-delivery is byte-identical; when two chunks genuinely differ (a
1216        // catch-up extension that re-claimed a slot), dropping the loser silently
1217        // deletes its recipients from the union — and a recipient with no blob reads
1218        // as REMOVED, which tears their community down. Union can only ever ADD
1219        // blobs, so it can turn a false removal into an adoption but never the
1220        // reverse. Exact duplicates are dropped so ordinary re-delivery stays free.
1221        entry.held_chunks.insert(c.chunk.0);
1222        for b in &c.blobs {
1223            if !entry.blobs.iter().any(|held| held.locator == b.locator && held.wrapped == b.wrapped) {
1224                entry.blobs.push(b.clone());
1225            }
1226        }
1227    }
1228    by_key.into_values().collect()
1229}
1230
1231/// Have I been removed by this rotation? Only answerable on a COMPLETE rotation
1232/// (all `n` chunks held): I'm removed iff none of the union's blobs carries my
1233/// locator. On an incomplete rotation the answer is `None` — keep recovering.
1234pub fn am_i_removed(rotation: &Rotation, my_xonly: &[u8; 32]) -> Option<bool> {
1235    if !rotation.is_complete() {
1236        return None;
1237    }
1238    let mine = find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), my_xonly, rotation.scope, rotation.new_epoch);
1239    Some(mine.is_none())
1240}
1241
1242/// Deterministic same-epoch fork winner (CORD-06 §3): among candidate rotations
1243/// at one continuity point, the one whose decrypted `new_key` is lexicographically
1244/// lowest wins. Every retained member decrypts its own blob from each fork and
1245/// computes the identical winner. Returns the index into `candidates` of the
1246/// winner, or `None` if the caller decrypted no candidate.
1247pub fn lowest_key_winner(candidate_keys: &[[u8; 32]]) -> Option<usize> {
1248    candidate_keys
1249        .iter()
1250        .enumerate()
1251        .min_by(|(_, a), (_, b)| a.cmp(b))
1252        .map(|(i, _)| i)
1253}
1254
1255// ── helpers ──────────────────────────────────────────────────────────────────
1256
1257fn unique_tag(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, RekeyError> {
1258    let mut found: Option<String> = None;
1259    for t in rumor.tags.iter() {
1260        let s = t.as_slice();
1261        if s.len() >= 2 && s[0] == name {
1262            if found.is_some() {
1263                return Err(RekeyError::BadTag(name));
1264            }
1265            found = Some(s[1].clone());
1266        }
1267    }
1268    Ok(found)
1269}
1270
1271fn parse_u64(rumor: &UnsignedEvent, name: &'static str) -> Result<u64, RekeyError> {
1272    let raw = unique_tag(rumor, name)?.ok_or(RekeyError::BadTag(name))?;
1273    // Spec-shaped decimal, not a bare `parse` — that takes "+2" and "02" as
1274    // epochs a stricter peer refuses (CORD-01 §5).
1275    if !crate::community::edition::is_tag_decimal(&raw) {
1276        return Err(RekeyError::BadTag(name));
1277    }
1278    raw.parse::<u64>().map_err(|_| RekeyError::BadTag(name))
1279}
1280
1281fn parse_chunk(rumor: &UnsignedEvent) -> Result<(u32, u32), RekeyError> {
1282    let mut found: Option<(u32, u32)> = None;
1283    for t in rumor.tags.iter() {
1284        let s = t.as_slice();
1285        if s.len() >= 3 && s[0] == TAG_CHUNK {
1286            if found.is_some() {
1287                return Err(RekeyError::BadTag(TAG_CHUNK));
1288            }
1289            if !crate::community::edition::is_tag_decimal(&s[1]) || !crate::community::edition::is_tag_decimal(&s[2]) {
1290                return Err(RekeyError::BadTag(TAG_CHUNK));
1291            }
1292            let i: u32 = s[1].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1293            let n: u32 = s[2].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1294            found = Some((i, n));
1295        }
1296    }
1297    let (i, n) = found.ok_or(RekeyError::BadTag(TAG_CHUNK))?;
1298    if n < 1 || i < 1 || i > n {
1299        return Err(RekeyError::BadChunkIndex);
1300    }
1301    Ok((i, n))
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306
1307    /// Wrap raw `Keys` as the polymorphic signer. `VectorSigner` pins its error to
1308    /// `SignerError`, which bare `Keys` doesn't satisfy, so tests go through the
1309    /// same enum the app uses.
1310    fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
1311        crate::signer::ActiveSigner::Keys(k.clone())
1312    }
1313    use super::*;
1314
1315    fn keys(byte: u8) -> Keys {
1316        Keys::new(SecretKey::from_slice(&[byte; 32]).unwrap())
1317    }
1318
1319    fn xonly(k: &Keys) -> [u8; 32] {
1320        k.public_key().to_bytes()
1321    }
1322
1323    const CHAN: ChannelId = ChannelId([0x42u8; 32]);
1324
1325    // ── blob atom ────────────────────────────────────────────────────────────
1326
1327    #[test]
1328    fn bound_plaintext_layout_is_frozen() {
1329        let pt = bound_plaintext(RekeyScope::Root, Epoch(1), &[0xABu8; 32]);
1330        let expected = format!("{}{}{}", "00".repeat(32), "0000000000000001", "ab".repeat(32));
1331        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
1332        let pt2 = bound_plaintext(RekeyScope::Channel(ChannelId([0x11u8; 32])), Epoch(0x0102), &[0xCDu8; 32]);
1333        let expected2 = format!("{}{}{}", "11".repeat(32), "0000000000000102", "cd".repeat(32));
1334        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt2), expected2);
1335    }
1336
1337    #[test]
1338    fn blob_round_trips_both_scopes() {
1339        let rotator = keys(7);
1340        let recipient = keys(8);
1341        for (scope, epoch, key) in [
1342            (RekeyScope::Root, Epoch(1), [0xABu8; 32]),
1343            (RekeyScope::Channel(CHAN), Epoch(5), [0xCDu8; 32]),
1344        ] {
1345            let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1346            let got = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob).unwrap();
1347            assert_eq!(got, key, "the recipient recovers the fresh key");
1348        }
1349    }
1350
1351    #[tokio::test]
1352    async fn signer_blob_is_wire_compatible_with_local_both_directions() {
1353        // A remote signer (here a plain Keys, which impls VectorSigner) must build
1354        // AND open blobs interchangeably with the raw-key path — the CORD-06 D5
1355        // "identical wire" guarantee the bunker/NIP-55 integration rests on.
1356        let rotator = keys(7);
1357        let recipient = keys(8);
1358        let scope = RekeyScope::Root;
1359        let epoch = Epoch(3);
1360        let key = [0x5Au8; 32];
1361
1362        // local build -> signer open
1363        let blob_l = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1364        let got_s = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_l).await.unwrap();
1365        assert_eq!(got_s, key, "signer opens a local-built blob");
1366
1367        // signer build -> local open (+ identical public locator)
1368        let blob_s = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).await.unwrap();
1369        assert_eq!(blob_s.locator, blob_l.locator, "same public locator regardless of build path");
1370        let got_l = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob_s).unwrap();
1371        assert_eq!(got_l, key, "local opens a signer-built blob");
1372
1373        // signer build -> signer open
1374        let got_ss = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_s).await.unwrap();
1375        assert_eq!(got_ss, key, "signer round-trips its own blob");
1376    }
1377
1378    #[tokio::test]
1379    async fn signer_blob_bound_check_still_gates_scope_epoch_splice() {
1380        let rotator = keys(7);
1381        let recipient = keys(8);
1382        let blob = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[9u8; 32]).await.unwrap();
1383        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob).await.is_err(), "epoch splice rejected");
1384        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob).await.is_err(), "scope splice rejected");
1385    }
1386
1387    #[test]
1388    fn locator_is_public_and_computable_from_pubkeys_alone() {
1389        // D1: the locator derives from PUBLIC inputs, so the rotator computing a
1390        // recipient's slot and the recipient computing their own must agree — no
1391        // secret needed either side (bunker parity).
1392        let rotator = keys(7);
1393        let recipient = keys(8);
1394        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(2), &[1u8; 32]).unwrap();
1395        let recomputed = blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(2));
1396        assert_eq!(blob.locator, recomputed, "both sides compute the same public locator");
1397    }
1398
1399    #[test]
1400    fn a_non_recipient_cannot_open_even_holding_the_public_locator() {
1401        // The D1 security relocation: the locator authenticates NOTHING (anyone
1402        // holding both npubs computes it), yet an outsider still can't open —
1403        // the pairwise decrypt is the gate, not the locator.
1404        let rotator = keys(7);
1405        let recipient = keys(8);
1406        let outsider = keys(9);
1407        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[2u8; 32]).unwrap();
1408        // The outsider can trivially recompute the (public) locator...
1409        assert_eq!(blob.locator, blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)));
1410        // ...but pairing (outsider_sk, rotator_pk) yields a different conversation
1411        // key, so the decrypt fails.
1412        assert!(open_blob_local(outsider.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).is_err());
1413    }
1414
1415    #[test]
1416    fn a_relocated_blob_still_opens_by_decrypt_not_locator() {
1417        // Because open ignores the locator (D1), corrupting the locator does NOT
1418        // break a legitimate recipient's open — the decrypt + bound check govern.
1419        // The FIND step uses the locator; OPEN does not.
1420        let rotator = keys(7);
1421        let recipient = keys(8);
1422        let mut blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[3u8; 32]).unwrap();
1423        blob.locator = "ff".repeat(32);
1424        // Handed the blob directly (locator bypassed), the recipient still opens it.
1425        assert_eq!(
1426            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).unwrap(),
1427            [3u8; 32]
1428        );
1429        // But find_my_blob won't LOCATE it under the corrupted locator.
1430        assert!(find_my_blob(std::slice::from_ref(&blob), &xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)).is_none());
1431    }
1432
1433    #[test]
1434    fn scope_and_epoch_splices_are_rejected_on_open() {
1435        let rotator = keys(7);
1436        let recipient = keys(8);
1437        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[4u8; 32]).unwrap();
1438        // Opened under a different scope → bound scope mismatch.
1439        assert!(matches!(
1440            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob),
1441            Err(RekeyError::ScopeSplice)
1442        ));
1443        // Opened under a different epoch → bound epoch mismatch.
1444        assert!(matches!(
1445            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob),
1446            Err(RekeyError::EpochSplice)
1447        ));
1448    }
1449
1450    #[test]
1451    fn wrapped_carries_base64_of_the_72_bytes_for_bunker_parity() {
1452        // D5: the NIP-44 layer's plaintext is base64(72 bytes) — a UTF-8 string a
1453        // NIP-46 signer can nip44_encrypt/decrypt. Prove the decrypted inner is
1454        // exactly that base64 string, matching the `_b64` helper the bunker uses.
1455        let rotator = keys(7);
1456        let recipient = keys(8);
1457        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[5u8; 32]).unwrap();
1458        let ck = ConversationKey::derive(recipient.secret_key(), &rotator.public_key()).unwrap();
1459        let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).unwrap();
1460        let inner = nostr_sdk::prelude::nip44::v2::decrypt_to_bytes(&ck, &payload).unwrap();
1461        assert_eq!(String::from_utf8(inner).unwrap(), bound_plaintext_b64(RekeyScope::Root, Epoch(1), &[5u8; 32]));
1462    }
1463
1464    #[test]
1465    fn distinct_recipients_and_scopes_get_distinct_locators() {
1466        let rotator = keys(7);
1467        let r1 = keys(8);
1468        let r2 = keys(9);
1469        assert_ne!(
1470            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1471            blob_locator(&xonly(&rotator), &xonly(&r2), RekeyScope::Root, Epoch(1))
1472        );
1473        // Same pair, a base blob and a channel blob at one epoch don't collide.
1474        assert_ne!(
1475            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1476            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Channel(CHAN), Epoch(1))
1477        );
1478    }
1479
1480    // ── 3303 event ─────────────────────────────────────────────────────────
1481
1482    fn root() -> [u8; 32] {
1483        [0x55u8; 32]
1484    }
1485
1486    #[test]
1487    fn channel_rekey_round_trips_through_the_stream() {
1488        let rotator = keys(1);
1489        let recipient = keys(8);
1490        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1491        let key = [0xABu8; 32];
1492        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &key).unwrap();
1493        let commit = epoch_key_commitment(Epoch(0), &[0xEEu8; 32]);
1494        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &commit, &[blob.clone()], 1, 1, 100, None, false).unwrap();
1495        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &rotator, Timestamp::from_secs(100)).unwrap();
1496
1497        // The wrap is signed by the group key, not the rotator (no identity on the wire).
1498        assert_ne!(wrap.pubkey, rotator.public_key());
1499        assert_eq!(wrap.pubkey, group.pk());
1500
1501        let opened = stream::open_wrap(&wrap, &group).unwrap();
1502        let chunk = parse_rekey_chunk(&opened).unwrap();
1503        assert_eq!(chunk.rotator, rotator.public_key(), "rotator recovered from the seal");
1504        assert!(matches!(chunk.scope, RekeyScope::Channel(c) if c.0 == CHAN.0));
1505        assert_eq!(chunk.new_epoch, Epoch(1));
1506        assert_eq!(chunk.prev_epoch, Epoch(0));
1507        assert_eq!(chunk.prev_commit, commit);
1508        assert_eq!(chunk.chunk, (1, 1));
1509        assert_eq!(chunk.blobs, vec![blob]);
1510    }
1511
1512    #[test]
1513    fn an_access_delivery_round_trips_and_never_reads_as_a_rotation() {
1514        let (deliverer, recipient) = (keys(1), keys(8));
1515        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1516        let key = [0xABu8; 32];
1517        let blob = build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(3), &key).unwrap();
1518        let rumor = build_access_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), std::slice::from_ref(&blob), 100).unwrap();
1519        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1520        let opened = stream::open_wrap(&wrap, &group).unwrap();
1521        let delivery = parse_access_delivery(&opened).unwrap();
1522        assert_eq!((delivery.deliverer, delivery.epoch), (deliverer.public_key(), Epoch(3)));
1523        let mine = find_my_blob(&delivery.blobs, &xonly(&deliverer), &xonly(&recipient), delivery.scope, delivery.epoch).unwrap();
1524        assert_eq!(open_blob_local(recipient.secret_key(), &deliverer.public_key(), delivery.scope, delivery.epoch, mine).unwrap(), key);
1525        assert!(parse_rekey_chunk(&opened).is_err(), "a delivery is no rotation");
1526        // Nor is a rotation a delivery.
1527        let commit = epoch_key_commitment(Epoch(2), &[0xEEu8; 32]);
1528        let rotation = build_rekey_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), Epoch(2), &commit, &[blob], 1, 1, 100, None, false).unwrap();
1529        let (wrap, _) = seal_rekey_chunk(&rotation, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1530        assert!(parse_access_delivery(&stream::open_wrap(&wrap, &group).unwrap()).is_err());
1531    }
1532
1533    #[test]
1534    fn a_history_delivery_round_trips_and_binds_its_channel_and_epoch() {
1535        let (deliverer, recipient) = (keys(1), keys(8));
1536        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1537        let past = crate::community::v2::derive::channel_group_key(&[0x42; 32], &CHAN, Epoch(2));
1538        let view = HistoryView::of(&past);
1539        let blob = build_history_blob_local(&deliverer, &recipient.public_key(), &CHAN, Epoch(2), &view).unwrap();
1540        let rumor = build_history_rumor(deliverer.public_key(), &CHAN, Epoch(2), std::slice::from_ref(&blob), 100).unwrap();
1541        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1542        let opened = stream::open_wrap(&wrap, &group).unwrap();
1543        let d = parse_history_delivery(&opened, &CHAN).unwrap();
1544        assert_eq!((d.deliverer, d.epoch), (deliverer.public_key(), Epoch(2)));
1545        assert_eq!(d.blobs[0].locator, history_locator(&xonly(&deliverer), &xonly(&recipient), &CHAN, Epoch(2)));
1546        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");
1547        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(3), &d.blobs[0]), Err(RekeyError::EpochSplice)));
1548        let other = ChannelId([0x01; 32]);
1549        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &other, Epoch(2), &d.blobs[0]), Err(RekeyError::ScopeSplice)));
1550        assert!(parse_history_delivery(&opened, &other).is_err(), "another channel's history isn't this one's");
1551        assert!(parse_access_delivery(&opened).is_err() && parse_rekey_chunk(&opened).is_err(), "nor is it a key or a rotation");
1552        // The view really opens that epoch's plane.
1553        let msg = stream::build_rumor_secs(9, deliverer.public_key(), "old", vec![], 1);
1554        let (old_wrap, _) = stream::wrap_seal(&stream::build_seal(&msg, SealForm::Plaintext, &past, &deliverer).unwrap(), &past, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1555        let read = stream::open_wrap_at(&old_wrap, &PublicKey::from_slice(&view.address).unwrap(), &ConversationKey::new(view.conv_key), false).unwrap();
1556        assert_eq!(read.rumor.content, "old");
1557    }
1558
1559    #[test]
1560    fn base_rekey_addresses_under_the_prior_root() {
1561        // A base rotation rides the PRIOR root: a member holding the prior root
1562        // derives the same group key and opens it; a non-holder can't.
1563        let rotator = keys(1);
1564        let recipient = keys(8);
1565        let prior_root = [0x66u8; 32];
1566        let community = CommunityId([0x77u8; 32]);
1567        let new_root = [0x99u8; 32];
1568        let group = base_rekey_group(&prior_root, &community, Epoch(1));
1569        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &new_root).unwrap();
1570        let commit = epoch_key_commitment(Epoch(0), &prior_root);
1571        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &commit, &[blob], 100, None, false).unwrap();
1572        assert_eq!(chunks.len(), 1);
1573
1574        let opened = stream::open_wrap(&chunks[0], &group).unwrap();
1575        let chunk = parse_rekey_chunk(&opened).unwrap();
1576        assert!(matches!(chunk.scope, RekeyScope::Root));
1577        // The recipient recovers the NEW root from their blob.
1578        let mine = find_my_blob(&chunk.blobs, &chunk.rotator.to_bytes(), &xonly(&recipient), chunk.scope, chunk.new_epoch).unwrap();
1579        assert_eq!(open_blob_local(recipient.secret_key(), &chunk.rotator, chunk.scope, chunk.new_epoch, mine).unwrap(), new_root);
1580
1581        // A non-holder of the prior root can't even open the wrap.
1582        let wrong = base_rekey_group(&[0u8; 32], &community, Epoch(1));
1583        assert!(stream::open_wrap(&chunks[0], &wrong).is_err());
1584    }
1585
1586    #[test]
1587    fn a_full_send_chunk_stays_under_the_relay_size_limit() {
1588        // The send caps exist so one chunk fits a 64KB strfry event, each form at its own: a
1589        // base rotation's widest blob (136 bytes, a staff recipient), cited and severed, and a
1590        // Channel rotation's 72-byte one.
1591        let rotator = keys(1);
1592        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1593        let cite = crate::community::edition::AuthorityCitation { entity_id: [7; 32], version: u64::MAX, edition_hash: [8; 32] };
1594        let base: Vec<RekeyBlob> = (0..blobs_per_event(RekeyScope::Root))
1595            .map(|i| {
1596                let r = keys((i % 200 + 20) as u8);
1597                let inner = bound_base_plaintext_b64(Epoch(1), &[0xCD; 32], &[0xAB; 32], Some(&[0xEE; 32]));
1598                let ck = ConversationKey::derive(rotator.secret_key(), &r.public_key()).unwrap();
1599                let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).unwrap();
1600                RekeyBlob { locator: blob_locator(&xonly(&rotator), &r.public_key().to_bytes(), RekeyScope::Root, Epoch(1)), wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload) }
1601            })
1602            .collect();
1603        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &base, 100, Some(&cite), true).unwrap();
1604        assert_eq!(chunks.len(), 1, "a full base chunk is exactly one event");
1605        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full base chunk must fit a 64KB relay event", chunks[0].as_json().len());
1606
1607        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1608        let narrow: Vec<RekeyBlob> = (0..blobs_per_event(scope))
1609            .map(|i| build_blob_local(rotator.secret_key(), &xonly(&rotator), &keys((i % 200 + 20) as u8).public_key(), scope, Epoch(1), &[0xCDu8; 32]).unwrap())
1610            .collect();
1611        let chunks = build_rekey_chunks_local(&rotator, &group, scope, Epoch(1), Epoch(0), &[0u8; 32], &narrow, 100, Some(&cite), false).unwrap();
1612        assert_eq!(chunks.len(), 1);
1613        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full channel chunk must fit a 64KB relay event", chunks[0].as_json().len());
1614    }
1615
1616    #[test]
1617    fn a_full_history_delivery_stays_under_the_relay_size_limit() {
1618        let deliverer = keys(1);
1619        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1620        let channel = crate::community::ChannelId([3; 32]);
1621        let view = HistoryView { address: [0xAA; 32], conv_key: [0xBB; 32] };
1622        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();
1623        let rumor = build_history_rumor(deliverer.public_key(), &channel, Epoch(1), &blobs, 100).unwrap();
1624        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1625        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1626        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full history delivery must fit a 64KB relay event", wrap.as_json().len());
1627    }
1628
1629    #[test]
1630    fn a_full_certified_delivery_stays_under_the_relay_size_limit() {
1631        let deliverer = keys(1);
1632        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1633        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1634        let recipients: Vec<Keys> = (0..MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| keys((i % 200 + 20) as u8)).collect();
1635        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();
1636        let certs: Vec<([u8; 32], [u8; 64])> = recipients.iter().map(|r| (r.public_key().to_bytes(), [0xEE; 64])).collect();
1637        let rumor = build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), Some([0x42; 32]), &blobs, &certs, 100).unwrap();
1638        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1639        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1640        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full certified chunk must fit a 64KB relay event", wrap.as_json().len());
1641    }
1642
1643    #[test]
1644    fn a_certified_delivery_past_its_cap_is_refused() {
1645        let deliverer = keys(1);
1646        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1647        let blobs: Vec<RekeyBlob> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() }).collect();
1648        let certs: Vec<([u8; 32], [u8; 64])> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| ([i as u8; 32], [0xEE; 64])).collect();
1649        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &certs, 100).is_err());
1650        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &[], 100).is_ok(), "keys alone fit more");
1651        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs[1..], &certs[1..], 100).is_ok());
1652    }
1653
1654    #[test]
1655    fn oversize_recipient_set_splits_into_chunks() {
1656        let rotator = keys(1);
1657        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1658        // One over the base rotation's send cap → 2 chunks, labeled (1,2) and (2,2).
1659        let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT + 1)
1660            .map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() })
1661            .collect();
1662        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(2), Epoch(1), &[0u8; 32], &blobs, 100, None, false).unwrap();
1663        assert_eq!(chunks.len(), 2);
1664        let parsed: Vec<RekeyChunk> = chunks.iter().map(|w| parse_rekey_chunk(&stream::open_wrap(w, &group).unwrap()).unwrap()).collect();
1665        assert_eq!(parsed[0].chunk, (1, 2));
1666        assert_eq!(parsed[1].chunk, (2, 2));
1667        assert_eq!(parsed[0].blobs.len(), MAX_WIDE_BLOBS_PER_EVENT);
1668        assert_eq!(parsed[1].blobs.len(), 1);
1669    }
1670
1671    #[test]
1672    fn plaintext_sealed_rekey_is_rejected() {
1673        let rotator = keys(1);
1674        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1675        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &[0u8; 32], &[], 1, 1, 100, None, false).unwrap();
1676        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &rotator).unwrap();
1677        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1678        let opened = stream::open_wrap(&wrap, &group).unwrap();
1679        assert!(parse_rekey_chunk(&opened).is_err(), "the rekey plane must be encrypted-sealed");
1680    }
1681
1682    #[test]
1683    fn non_monotonic_epoch_is_refused_at_mint_and_on_parse() {
1684        let rotator = keys(1);
1685        assert!(matches!(
1686            build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(1), &[0u8; 32], &[], 1, 1, 100, None, false),
1687            Err(RekeyError::NonMonotonicEpoch)
1688        ));
1689    }
1690
1691    #[test]
1692    fn bad_chunk_indices_are_refused() {
1693        let rotator = keys(1);
1694        for (i, n) in [(0u32, 1u32), (2, 1), (1, 0)] {
1695            assert!(
1696                matches!(build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &[], i, n, 100, None, false), Err(RekeyError::BadChunkIndex)),
1697                "chunk ({i},{n}) must be rejected"
1698            );
1699        }
1700    }
1701
1702    // ── continuity + removal + fork ──────────────────────────────────────────
1703
1704    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 {
1705        RekeyChunk {
1706            rotator: rotator.public_key(),
1707            scope,
1708            new_epoch: Epoch(new_epoch),
1709            prev_epoch: Epoch(prev_epoch),
1710            prev_commit: epoch_key_commitment(Epoch(prev_epoch), prev_key),
1711            chunk: (i, n),
1712            blobs,
1713            citation: None,
1714            severed: false,
1715            at_ms: 0,
1716        }
1717    }
1718
1719    #[test]
1720    fn a_rotation_dates_from_its_earliest_chunk() {
1721        let rotator = Keys::generate();
1722        let prev = [3u8; 32];
1723        let mut late = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1724        late.at_ms = 9_000;
1725        let mut early = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1726        early.at_ms = 4_000;
1727        let rotations = collect_rotations(&[late, early]);
1728        assert_eq!(rotations.len(), 1);
1729        assert_eq!(rotations[0].at_ms, 4_000, "a re-sent chunk never moves a rotation later");
1730    }
1731
1732    #[test]
1733    fn a_colliding_chunk_index_must_not_swallow_a_recipients_blob() {
1734        // Chunks are correlated by index, and a second chunk claiming an index
1735        // already held is treated as idempotent re-delivery — its blobs dropped.
1736        // That is safe only while re-delivery is byte-identical. The catch-up path
1737        // that extends a rotation computes its starting index from a fetch that can
1738        // come back blind, and then re-claims index 1; whichever copy a client sees
1739        // first wins, so the original recipients in the loser vanish from the union.
1740        // A recipient whose blob vanishes reads as REMOVED — and removal deletes the
1741        // community locally. Losing a blob to a bookkeeping collision must never be
1742        // able to masquerade as a removal verdict.
1743        let rotator = keys(1);
1744        let prev = [0x55u8; 32];
1745        let mine = RekeyBlob { locator: "aa".repeat(32), wrapped: "mine".into() };
1746        let other = RekeyBlob { locator: "bb".repeat(32), wrapped: "other".into() };
1747
1748        // Two chunks both claiming index 1: the original (carrying my blob) and a
1749        // re-claim (carrying someone else's).
1750        let original = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![mine.clone()], 1, 1);
1751        let reclaim = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![other.clone()], 1, 1);
1752
1753        for (order, chunks) in [
1754            ("original first", vec![original.clone(), reclaim.clone()]),
1755            ("reclaim first", vec![reclaim.clone(), original.clone()]),
1756        ] {
1757            let rotations = collect_rotations(&chunks);
1758            assert_eq!(rotations.len(), 1, "{order}: same correlation key");
1759            let has_mine = rotations[0].blobs.iter().any(|b| b.locator == mine.locator);
1760            assert!(
1761                has_mine,
1762                "{order}: my blob was dropped by an index collision — that reads as a removal \
1763                 and removal deletes the community",
1764            );
1765        }
1766    }
1767
1768    #[test]
1769    fn a_severed_rotation_cannot_be_laundered_by_an_unmarked_chunk() {
1770        // The containment marker rides EVERY chunk of a rotation, but a rotation's
1771        // chunk set can be extended later (the catch-up path for members a rotation
1772        // forgot). An extension built without the marker would, under first-seen
1773        // semantics, present a severed epoch as an ordinary one — and an adopter
1774        // reading it that way refreshes the very invite links the containment meant
1775        // to bury, re-opening the door the raid came through. The fold is therefore
1776        // an OR across chunks, in either arrival order.
1777        let rotator = keys(1);
1778        let prev = [0x44u8; 32];
1779        let mut marked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1780        marked.severed = true;
1781        let unmarked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1782
1783        for (order, chunks) in [
1784            ("marked first", vec![marked.clone(), unmarked.clone()]),
1785            ("unmarked first", vec![unmarked.clone(), marked.clone()]),
1786        ] {
1787            let rotations = collect_rotations(&chunks);
1788            assert_eq!(rotations.len(), 1, "{order}: one correlation key, one rotation");
1789            assert!(
1790                rotations[0].severed,
1791                "{order}: an unmarked sibling must never launder the containment away",
1792            );
1793            assert!(rotations[0].is_complete(), "{order}: both chunks held");
1794        }
1795    }
1796
1797    #[test]
1798    fn continuity_extends_gaps_and_forks() {
1799        let rotator = keys(1);
1800        let held = [0x33u8; 32];
1801        // Extends: prev_epoch == held epoch AND commitment matches the held key.
1802        let good = chunk_at(&rotator, RekeyScope::Root, 3, 2, &held, vec![], 1, 1);
1803        assert_eq!(check_continuity(&good, Epoch(2), &held), Continuity::Extends);
1804        // Gap: the rotation is FROM a higher epoch than I hold — I missed one.
1805        let ahead = chunk_at(&rotator, RekeyScope::Root, 5, 4, &held, vec![], 1, 1);
1806        assert_eq!(check_continuity(&ahead, Epoch(2), &held), Continuity::Gap);
1807        // Fork: same epoch but the commitment names a different prior key.
1808        let fork = chunk_at(&rotator, RekeyScope::Root, 3, 2, &[0x99u8; 32], vec![], 1, 1);
1809        assert_eq!(check_continuity(&fork, Epoch(2), &held), Continuity::Fork);
1810        // Fork: a rotation older than where I am (stale).
1811        let stale = chunk_at(&rotator, RekeyScope::Root, 2, 1, &held, vec![], 1, 1);
1812        assert_eq!(check_continuity(&stale, Epoch(2), &held), Continuity::Fork);
1813    }
1814
1815    #[test]
1816    fn a_missing_chunk_is_never_a_removal() {
1817        // The core no-false-removal guarantee: until ALL n chunks are held, "am I
1818        // removed" is unanswerable, even if the chunks I DO hold lack my blob.
1819        let rotator = keys(1);
1820        let me = keys(8);
1821        // Two-chunk rotation; my blob is in chunk 2, which I haven't received.
1822        let my_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &me.public_key(), RekeyScope::Root, Epoch(1), &[0xAAu8; 32]).unwrap();
1823        let c1 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![RekeyBlob { locator: "bb".repeat(32), wrapped: "x".into() }], 1, 2);
1824        let rots = collect_rotations(&[c1.clone()]);
1825        assert_eq!(rots.len(), 1);
1826        assert!(!rots[0].is_complete(), "one of two chunks held → incomplete");
1827        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), None, "incomplete → keep recovering, never conclude removal");
1828
1829        // Now chunk 2 (with my blob) arrives → complete, and I am NOT removed.
1830        let c2 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![my_blob.clone()], 2, 2);
1831        let rots = collect_rotations(&[c1, c2]);
1832        assert!(rots[0].is_complete());
1833        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(false));
1834        // And my key is recoverable from the union.
1835        let mine = find_my_blob(&rots[0].blobs, &rots[0].rotator.to_bytes(), &xonly(&me), RekeyScope::Root, Epoch(1)).unwrap();
1836        assert_eq!(open_blob_local(me.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), mine).unwrap(), [0xAAu8; 32]);
1837    }
1838
1839    #[test]
1840    fn a_complete_rotation_without_my_blob_is_a_removal() {
1841        let rotator = keys(1);
1842        let me = keys(8);
1843        let other = keys(9);
1844        // A complete 1-chunk rotation carrying only someone else's blob.
1845        let their_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &other.public_key(), RekeyScope::Root, Epoch(1), &[0xBBu8; 32]).unwrap();
1846        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![their_blob], 1, 1);
1847        let rots = collect_rotations(&[c]);
1848        assert!(rots[0].is_complete());
1849        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(true), "complete rotation, no blob for me → removed");
1850    }
1851
1852    #[test]
1853    fn collect_rotations_separates_concurrent_rotators_and_scopes() {
1854        // Two rotators racing the same epoch, plus a channel rekey at the same
1855        // numbers — three distinct rotations, never merged.
1856        let rot_a = keys(1);
1857        let rot_b = keys(2);
1858        let ca = chunk_at(&rot_a, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1859        let cb = chunk_at(&rot_b, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1860        let cc = chunk_at(&rot_a, RekeyScope::Channel(CHAN), 2, 1, &[7u8; 32], vec![], 1, 1);
1861        let rots = collect_rotations(&[ca, cb, cc]);
1862        assert_eq!(rots.len(), 3, "different rotator or scope ⇒ different rotation");
1863    }
1864
1865    #[test]
1866    fn duplicate_chunk_delivery_is_idempotent() {
1867        let rotator = keys(1);
1868        let blob = RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() };
1869        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![blob.clone()], 1, 1);
1870        let rots = collect_rotations(&[c.clone(), c]);
1871        assert_eq!(rots.len(), 1);
1872        assert_eq!(rots[0].blobs.len(), 1, "re-delivering a chunk must not double its blobs");
1873    }
1874
1875    // ── base blob forms + control_wrap (CORD-06 §1, CORD-04 §3) ──────────────
1876
1877    #[test]
1878    fn base_blob_forms_are_width_declared() {
1879        let community = CommunityId([0x77u8; 32]);
1880        let new_root = [0xABu8; 32];
1881        let control_root = [0x5Cu8; 32];
1882        let epoch = Epoch(3);
1883        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1884
1885        // 104-byte member form: root + pk, no secret.
1886        let member = bound_base_plaintext(epoch, &new_root, &control_pk, None);
1887        assert_eq!(member.len(), 104);
1888        let d = parse_bound_base_plaintext(&member, &community, epoch).unwrap();
1889        assert_eq!(d.new_root, new_root);
1890        assert_eq!(d.control_pk, Some(control_pk));
1891        assert_eq!(d.control_root, None);
1892
1893        // 136-byte staff form carries the secret, verified against its own pk.
1894        let staff = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1895        assert_eq!(staff.len(), 136);
1896        let d = parse_bound_base_plaintext(&staff, &community, epoch).unwrap();
1897        assert_eq!(d.control_root, Some(control_root));
1898        assert_eq!(d.control_pk, Some(control_pk));
1899
1900        // Legacy 72-byte base form yields the root alone.
1901        let legacy = bound_plaintext(RekeyScope::Root, epoch, &new_root);
1902        let d = parse_bound_base_plaintext(&legacy, &community, epoch).unwrap();
1903        assert_eq!(d.new_root, new_root);
1904        assert_eq!(d.control_pk, None);
1905        assert_eq!(d.control_root, None);
1906    }
1907
1908    #[test]
1909    fn base_blob_mismatched_control_pair_is_refused_whole() {
1910        let community = CommunityId([0x77u8; 32]);
1911        let control_pk = control_signer_group_key(&[0x5Cu8; 32], &community, Epoch(3)).pk().to_bytes();
1912        // A secret that does NOT derive to the carried pk — the whole blob is
1913        // dropped, the new_root included (never a partial adoption).
1914        let bad = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &control_pk, Some(&[0x11u8; 32]));
1915        assert!(matches!(
1916            parse_bound_base_plaintext(&bad, &community, Epoch(3)),
1917            Err(RekeyError::ControlPairMismatch)
1918        ));
1919    }
1920
1921    #[test]
1922    fn base_blob_rejects_any_other_width_and_splices() {
1923        let community = CommunityId([0x77u8; 32]);
1924        // Below and between the defined forms: no append-only extension fits.
1925        for n in [0usize, 71, 73, 100, 105, 135] {
1926            assert!(matches!(
1927                parse_bound_base_plaintext(&vec![0u8; n], &community, Epoch(1)),
1928                Err(RekeyError::BadBaseBlobWidth(m)) if m == n
1929            ));
1930        }
1931        // The scope and epoch bind INSIDE the ciphertext (unspliceable).
1932        let control_root = [0x5Cu8; 32];
1933        let pk = control_signer_group_key(&control_root, &community, Epoch(3)).pk().to_bytes();
1934        let pt = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &pk, None);
1935        assert!(matches!(parse_bound_base_plaintext(&pt, &community, Epoch(4)), Err(RekeyError::EpochSplice)));
1936        let mut channel_scoped = pt.clone();
1937        channel_scoped[..32].copy_from_slice(&[0x42u8; 32]);
1938        assert!(matches!(parse_bound_base_plaintext(&channel_scoped, &community, Epoch(3)), Err(RekeyError::ScopeSplice)));
1939    }
1940
1941    #[tokio::test]
1942    async fn base_blob_round_trips_member_and_staff_forms() {
1943        let rotator = keys(7);
1944        let member = keys(8);
1945        let staffer = keys(9);
1946        let community = CommunityId([0x77u8; 32]);
1947        let epoch = Epoch(2);
1948        let new_root = [0xEEu8; 32];
1949        let control_root = [0xDDu8; 32];
1950        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1951
1952        let mb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), epoch, &new_root, &control_pk, None).await.unwrap();
1953        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &mb).await.unwrap();
1954        assert_eq!(d.new_root, new_root);
1955        assert_eq!(d.control_pk, Some(control_pk));
1956        assert_eq!(d.control_root, None, "a member blob never carries the secret");
1957
1958        let sb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &staffer.public_key(), epoch, &new_root, &control_pk, Some(&control_root)).await.unwrap();
1959        let d = open_base_blob(&as_signer(&staffer), &rotator.public_key(), &community, epoch, &sb).await.unwrap();
1960        assert_eq!(d.control_root, Some(control_root));
1961
1962        // The locator is the same public Root-scope slot the legacy form used.
1963        assert_eq!(mb.locator, blob_locator(&xonly(&rotator), &xonly(&member), RekeyScope::Root, epoch));
1964        // And a legacy 72-byte blob still opens through the base opener.
1965        let legacy = build_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), RekeyScope::Root, epoch, &new_root).await.unwrap();
1966        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &legacy).await.unwrap();
1967        assert_eq!(d.new_root, new_root);
1968        assert_eq!(d.control_pk, None);
1969    }
1970
1971    #[test]
1972    fn a_future_wider_base_blob_degrades_instead_of_forking() {
1973        // The pre-split lesson (CORD-06 §3): a width this build predates must
1974        // never park the member at the old epoch — extract the frozen prefix
1975        // and whatever appended fields still verify.
1976        let community = CommunityId([0x77u8; 32]);
1977        let new_root = [0xABu8; 32];
1978        let control_root = [0x5Cu8; 32];
1979        let epoch = Epoch(3);
1980        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1981
1982        // A hypothetical 168-byte form that appended a field after the secret.
1983        let mut future = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1984        future.extend_from_slice(&[0x99u8; 32]);
1985        let d = parse_bound_base_plaintext(&future, &community, epoch).unwrap();
1986        assert_eq!(d.new_root, new_root);
1987        assert_eq!(d.control_pk, Some(control_pk));
1988        assert_eq!(d.control_root, Some(control_root), "held offsets still verify → full function");
1989
1990        // One that REPLACED the secret's bytes: the derive check fails closed
1991        // to the verified prefix, never a refusal (membership must survive).
1992        let mut reordered = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&[0x44u8; 32]));
1993        reordered.extend_from_slice(&[0x99u8; 32]);
1994        let d = parse_bound_base_plaintext(&reordered, &community, epoch).unwrap();
1995        assert_eq!(d.new_root, new_root);
1996        assert_eq!(d.control_pk, Some(control_pk));
1997        assert_eq!(d.control_root, None, "an unverifiable secret is dropped, not adopted");
1998
1999        // The prefix's splice bindings still gate a future form.
2000        assert!(parse_bound_base_plaintext(&future, &community, Epoch(4)).is_err());
2001    }
2002
2003    #[test]
2004    fn control_wrap_layout_is_frozen_and_round_trips() {
2005        let pt = encode_control_wrap(Epoch(7), &[0xCDu8; 32]);
2006        assert_eq!(pt.len(), 40);
2007        let expected = format!("{}{}", "0000000000000007", "cd".repeat(32));
2008        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
2009        let (epoch, root) = parse_control_wrap(&pt).unwrap();
2010        assert_eq!(epoch, Epoch(7));
2011        assert_eq!(root, [0xCDu8; 32]);
2012        for n in [0usize, 39, 41, 72] {
2013            assert!(matches!(parse_control_wrap(&vec![0u8; n]), Err(RekeyError::BadControlWrapLength(m)) if m == n));
2014        }
2015    }
2016
2017    #[test]
2018    fn lowest_key_fork_winner_is_deterministic() {
2019        // CORD-06 §3: among candidates, the lexicographically lowest new key wins,
2020        // so every retained member converges. Input order must not change it.
2021        let keys_a = [[0x03u8; 32], [0x01u8; 32], [0x02u8; 32]];
2022        assert_eq!(lowest_key_winner(&keys_a), Some(1));
2023        let keys_b = [[0x01u8; 32], [0x02u8; 32], [0x03u8; 32]];
2024        assert_eq!(lowest_key_winner(&keys_b), Some(0));
2025        assert_eq!(lowest_key_winner(&[]), None);
2026    }
2027}