1use 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
48pub const MAX_REKEY_BLOBS_PER_EVENT: usize = 80;
52
53pub const MAX_WIDE_BLOBS_PER_EVENT: usize = 60;
56
57pub 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
62pub const MAX_REKEY_BLOBS_RECEIVED: usize = 120;
67
68pub 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";
77const TAG_SEVER: &str = "sever";
82const TAG_DELIVERY: &str = "delivery";
84const DELIVERY_ACCESS: &str = "access";
85const DELIVERY_HISTORY: &str = "history";
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum RekeyScope {
91 Channel(ChannelId),
93 Root,
96}
97
98impl RekeyScope {
99 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct RekeyBlob {
131 pub locator: String,
132 pub wrapped: String,
133}
134
135#[derive(Debug)]
137pub enum RekeyError {
138 Stream(StreamError),
139 Crypto(String),
140 BadBlobLength(usize),
142 BadBaseBlobWidth(usize),
145 ControlPairMismatch,
149 BadControlWrapLength(usize),
151 ScopeSplice,
153 EpochSplice,
155 NotARekey(u16),
157 BadTag(&'static str),
159 NonMonotonicEpoch,
161 BadChunkIndex,
163 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
195fn 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
207pub 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
213pub 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#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct BaseKeyDelivery {
245 pub new_root: [u8; 32],
246 pub control_pk: Option<[u8; 32]>,
250 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
265pub 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
271pub 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 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
313pub 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
336pub 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
360pub 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
372pub 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
378pub 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
392pub 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
398pub 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
419pub 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
444pub 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
468pub 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
492pub 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
505pub 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#[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 pub chunk: (u32, u32),
534 pub blobs: Vec<RekeyBlob>,
535 pub citation: Option<crate::community::edition::AuthorityCitation>,
538 pub severed: bool,
540 pub at_ms: u64,
542}
543
544pub type RotationKey = ([u8; 32], [u8; 32], u64, [u8; 32]);
548
549impl RekeyChunk {
550 pub fn correlation(&self) -> RotationKey {
552 (self.rotator.to_bytes(), self.scope.id32(), self.new_epoch.0, self.prev_commit)
553 }
554}
555
556#[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 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 Ok(stream::build_rumor_secs(super::kind::REKEY, rotator, &content, tags, at_secs))
600}
601
602pub 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
612pub 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
618pub 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#[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#[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#[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
747pub fn parse_rekey_chunk(opened: &OpenedStream) -> Result<RekeyChunk, RekeyError> {
751 if opened.seal_form != SealForm::Encrypted {
752 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 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#[derive(Debug, Clone)]
803pub struct AccessDelivery {
804 pub deliverer: PublicKey,
805 pub scope: RekeyScope,
806 pub epoch: Epoch,
807 pub blobs: Vec<RekeyBlob>,
808 pub writer: Option<[u8; 32]>,
810 pub certs: Vec<([u8; 32], [u8; 64])>,
812 pub mint: Option<(u32, u32)>,
814}
815
816const TAG_MINT: &str = "mint";
818
819pub fn as_mint_part(rumor: UnsignedEvent, part: usize, parts: usize) -> UnsignedEvent {
821 use crate::event_ext::FinalizeUnsignedWithId as _;
822 let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
823 tags.push(Tag::custom(TAG_MINT, [part.to_string(), parts.to_string()]));
824 let mut out = nostr_sdk::prelude::EventBuilder::new(rumor.kind, rumor.content).tags(tags).custom_created_at(rumor.created_at).finalize_unsigned_with_id(rumor.pubkey);
825 out.ensure_id();
826 out
827}
828
829const TAG_WRITER: &str = "writer";
831
832const TAG_CERT: &str = "cert";
834
835pub fn build_access_rumor(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
837 build_access_rumor_for(deliverer, scope, epoch, None, blobs, at_secs)
838}
839
840pub fn build_access_rumor_for(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
842 build_access_rumor_certified(deliverer, scope, epoch, writer, blobs, &[], at_secs)
843}
844
845pub fn build_access_rumor_certified(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], certs: &[([u8; 32], [u8; 64])], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
847 let cap = if certs.is_empty() { MAX_REKEY_BLOBS_PER_EVENT } else { MAX_CERTIFIED_BLOBS_PER_EVENT };
848 if blobs.len() > cap || certs.len() > MAX_CERTIFIED_BLOBS_PER_EVENT {
849 return Err(RekeyError::TooManyBlobs(blobs.len().max(certs.len())));
850 }
851 let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
852 let mut tags = vec![
853 Tag::custom(TAG_SCOPE, [scope.to_hex()]),
854 Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
855 Tag::custom(TAG_DELIVERY, [DELIVERY_ACCESS]),
856 ];
857 if let Some(pk) = writer {
858 tags.push(Tag::custom(TAG_WRITER, [crate::simd::hex::bytes_to_hex_32(&pk)]));
859 }
860 for (who, cert) in certs {
861 tags.push(Tag::custom(TAG_CERT, [crate::simd::hex::bytes_to_hex_32(who), crate::simd::hex::bytes_to_hex_string(cert)]));
862 }
863 Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
864}
865
866pub fn parse_access_delivery(opened: &OpenedStream) -> Result<AccessDelivery, RekeyError> {
868 if opened.seal_form != SealForm::Encrypted {
869 return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
870 }
871 let rumor = &opened.rumor;
872 if rumor.kind.as_u16() != super::kind::REKEY {
873 return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
874 }
875 if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_ACCESS) {
876 return Err(RekeyError::BadTag(TAG_DELIVERY));
877 }
878 let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
879 .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
880 let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
881 let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
882 if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
883 return Err(RekeyError::TooManyBlobs(blobs.len()));
884 }
885 let writer = match unique_tag(rumor, TAG_WRITER)? {
886 None => None,
887 Some(hex) => Some(crate::simd::hex::hex_to_bytes_32_checked(&hex).ok_or(RekeyError::BadTag(TAG_WRITER))?),
888 };
889 let certs = rumor
891 .tags
892 .iter()
893 .filter_map(|t| {
894 let s = t.as_slice();
895 (s.first().map(String::as_str) == Some(TAG_CERT) && s.len() == 3).then_some(())?;
896 let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
897 let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
898 Some((who, cert))
899 })
900 .take(MAX_REKEY_BLOBS_RECEIVED)
901 .collect();
902 let mint = rumor
903 .tags
904 .iter()
905 .map(|t| t.as_slice())
906 .find(|t| t.first().map(String::as_str) == Some(TAG_MINT))
907 .and_then(|t| Some((t.get(1)?.parse::<u32>().ok()?, t.get(2)?.parse::<u32>().ok()?)))
908 .filter(|(part, parts)| *part >= 1 && part <= parts);
909 Ok(AccessDelivery { deliverer: opened.author, scope, epoch, blobs, writer, certs, mint })
910}
911
912pub fn history_scope(channel: &ChannelId) -> [u8; 32] {
915 use sha2::{Digest, Sha256};
916 let mut h = Sha256::new();
917 h.update(b"concord/history-scope");
918 h.update(channel.0);
919 h.finalize().into()
920}
921
922#[derive(Clone, PartialEq, Eq)]
925pub struct HistoryView {
926 pub address: [u8; 32],
927 pub conv_key: [u8; 32],
928}
929
930impl std::fmt::Debug for HistoryView {
931 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 f.debug_struct("HistoryView").field("address", &crate::simd::hex::bytes_to_hex_32(&self.address)).finish_non_exhaustive()
933 }
934}
935
936impl HistoryView {
937 pub fn of(group: &GroupKey) -> Self {
938 let mut conv_key = [0u8; 32];
939 conv_key.copy_from_slice(group.conv_key().as_bytes());
940 HistoryView { address: group.pk().to_bytes(), conv_key }
941 }
942}
943
944fn history_plaintext_b64(channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Zeroizing<String> {
946 let mut pt = Zeroizing::new([0u8; 104]);
947 pt[..32].copy_from_slice(&history_scope(channel));
948 pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
949 pt[40..72].copy_from_slice(&view.address);
950 pt[72..].copy_from_slice(&view.conv_key);
951 Zeroizing::new(crate::simd::base64::STANDARD.encode_to_string(&pt[..]))
952}
953
954fn parse_history_plaintext(pt: &[u8], channel: &ChannelId, epoch: Epoch) -> Result<HistoryView, RekeyError> {
955 if pt.len() != 104 {
956 return Err(RekeyError::BadBlobLength(pt.len()));
957 }
958 if pt[..32] != history_scope(channel) {
959 return Err(RekeyError::ScopeSplice);
960 }
961 if pt[32..40] != epoch.0.to_be_bytes() {
962 return Err(RekeyError::EpochSplice);
963 }
964 let (mut address, mut conv_key) = ([0u8; 32], [0u8; 32]);
965 address.copy_from_slice(&pt[40..72]);
966 conv_key.copy_from_slice(&pt[72..]);
967 Ok(HistoryView { address, conv_key })
968}
969
970pub fn history_locator(deliverer_xonly: &[u8; 32], recipient_xonly: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> String {
972 crate::simd::hex::bytes_to_hex_32(&recipient_locator(deliverer_xonly, recipient_xonly, &history_scope(channel), epoch))
973}
974
975pub async fn build_history_blob<S: crate::signer::VectorSigner + ?Sized>(
976 signer: &S,
977 deliverer_xonly: &[u8; 32],
978 recipient: &PublicKey,
979 channel: &ChannelId,
980 epoch: Epoch,
981 view: &HistoryView,
982) -> Result<RekeyBlob, RekeyError> {
983 let inner = history_plaintext_b64(channel, epoch, view);
984 let wrapped = signer.nip44_encrypt_async(recipient, inner.as_str()).await.map_err(|e| RekeyError::Crypto(e.to_string()))?;
985 Ok(RekeyBlob { locator: history_locator(deliverer_xonly, &recipient.to_bytes(), channel, epoch), wrapped })
986}
987
988pub async fn open_history_blob<S: crate::signer::VectorSigner + ?Sized>(
989 signer: &S,
990 deliverer: &PublicKey,
991 channel: &ChannelId,
992 epoch: Epoch,
993 blob: &RekeyBlob,
994) -> Result<HistoryView, RekeyError> {
995 let inner = Zeroizing::new(signer.nip44_decrypt_async(deliverer, &blob.wrapped).await.map_err(|e| RekeyError::Crypto(e.to_string()))?);
996 let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
997 parse_history_plaintext(&pt, channel, epoch)
998}
999
1000pub fn build_history_blob_local(deliverer: &Keys, recipient: &PublicKey, channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Result<RekeyBlob, RekeyError> {
1002 let inner = history_plaintext_b64(channel, epoch, view);
1003 let ck = ConversationKey::derive(deliverer.secret_key(), recipient).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1004 let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1005 Ok(RekeyBlob {
1006 locator: history_locator(&deliverer.public_key().to_bytes(), &recipient.to_bytes(), channel, epoch),
1007 wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
1008 })
1009}
1010
1011pub fn open_history_blob_local(me: &SecretKey, deliverer: &PublicKey, channel: &ChannelId, epoch: Epoch, blob: &RekeyBlob) -> Result<HistoryView, RekeyError> {
1013 let ck = ConversationKey::derive(me, deliverer).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1014 let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1015 let inner = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1016 let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_slice()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
1017 parse_history_plaintext(&pt, channel, epoch)
1018}
1019
1020#[derive(Debug, Clone)]
1022pub struct HistoryDelivery {
1023 pub deliverer: PublicKey,
1024 pub epoch: Epoch,
1025 pub blobs: Vec<RekeyBlob>,
1026}
1027
1028pub fn build_history_rumor(deliverer: PublicKey, channel: &ChannelId, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
1029 if blobs.len() > MAX_WIDE_BLOBS_PER_EVENT {
1030 return Err(RekeyError::TooManyBlobs(blobs.len()));
1031 }
1032 let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
1033 let tags = vec![
1034 Tag::custom(TAG_SCOPE, [crate::simd::hex::bytes_to_hex_32(&history_scope(channel))]),
1035 Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
1036 Tag::custom(TAG_DELIVERY, [DELIVERY_HISTORY]),
1037 ];
1038 Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
1039}
1040
1041pub fn parse_history_delivery(opened: &OpenedStream, channel: &ChannelId) -> Result<HistoryDelivery, RekeyError> {
1043 if opened.seal_form != SealForm::Encrypted {
1044 return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
1045 }
1046 let rumor = &opened.rumor;
1047 if rumor.kind.as_u16() != super::kind::REKEY {
1048 return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
1049 }
1050 if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_HISTORY) {
1051 return Err(RekeyError::BadTag(TAG_DELIVERY));
1052 }
1053 if unique_tag(rumor, TAG_SCOPE)?.as_deref() != Some(crate::simd::hex::bytes_to_hex_32(&history_scope(channel)).as_str()) {
1054 return Err(RekeyError::BadTag(TAG_SCOPE));
1055 }
1056 let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
1057 let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
1058 if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
1059 return Err(RekeyError::TooManyBlobs(blobs.len()));
1060 }
1061 Ok(HistoryDelivery { deliverer: opened.author, epoch, blobs })
1062}
1063
1064#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1068pub enum Continuity {
1069 Extends,
1072 Gap,
1075 Fork,
1077}
1078
1079pub fn check_continuity(chunk: &RekeyChunk, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1083 if chunk.prev_epoch.0 == held_epoch.0 {
1084 if epoch_key_commitment(held_epoch, held_key) == chunk.prev_commit {
1085 Continuity::Extends
1086 } else {
1087 Continuity::Fork
1088 }
1089 } else if chunk.prev_epoch.0 > held_epoch.0 {
1090 Continuity::Gap
1091 } else {
1092 Continuity::Fork
1095 }
1096}
1097
1098#[derive(Debug, Clone)]
1101pub struct Rotation {
1102 pub rotator: PublicKey,
1103 pub scope: RekeyScope,
1104 pub new_epoch: Epoch,
1105 pub prev_epoch: Epoch,
1106 pub prev_commit: [u8; 32],
1107 pub blobs: Vec<RekeyBlob>,
1109 pub declared_chunks: u32,
1111 pub held_chunks: std::collections::BTreeSet<u32>,
1113 pub citation: Option<crate::community::edition::AuthorityCitation>,
1116 pub severed: bool,
1119 pub at_ms: u64,
1121}
1122
1123impl Rotation {
1124 pub fn is_complete(&self) -> bool {
1128 self.declared_chunks >= 1 && (1..=self.declared_chunks).all(|i| self.held_chunks.contains(&i))
1129 }
1130
1131 pub fn continuity(&self, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
1135 if self.prev_epoch.0 == held_epoch.0 {
1136 if epoch_key_commitment(held_epoch, held_key) == self.prev_commit {
1137 Continuity::Extends
1138 } else {
1139 Continuity::Fork
1140 }
1141 } else if self.prev_epoch.0 > held_epoch.0 {
1142 Continuity::Gap
1143 } else {
1144 Continuity::Fork
1145 }
1146 }
1147}
1148
1149pub fn collect_rotations(chunks: &[RekeyChunk]) -> Vec<Rotation> {
1154 use std::collections::BTreeMap;
1155 let mut by_key: BTreeMap<RotationKey, Rotation> = BTreeMap::new();
1156 for c in chunks {
1157 let entry = by_key.entry(c.correlation()).or_insert_with(|| Rotation {
1158 rotator: c.rotator,
1159 scope: c.scope,
1160 new_epoch: c.new_epoch,
1161 prev_epoch: c.prev_epoch,
1162 prev_commit: c.prev_commit,
1163 blobs: Vec::new(),
1164 declared_chunks: c.chunk.1,
1165 held_chunks: std::collections::BTreeSet::new(),
1166 citation: c.citation.clone(),
1167 severed: c.severed,
1168 at_ms: c.at_ms,
1169 });
1170 entry.severed |= c.severed;
1171 entry.at_ms = entry.at_ms.min(c.at_ms);
1172 entry.declared_chunks = entry.declared_chunks.max(c.chunk.1);
1174 entry.held_chunks.insert(c.chunk.0);
1183 for b in &c.blobs {
1184 if !entry.blobs.iter().any(|held| held.locator == b.locator && held.wrapped == b.wrapped) {
1185 entry.blobs.push(b.clone());
1186 }
1187 }
1188 }
1189 by_key.into_values().collect()
1190}
1191
1192pub fn am_i_removed(rotation: &Rotation, my_xonly: &[u8; 32]) -> Option<bool> {
1196 if !rotation.is_complete() {
1197 return None;
1198 }
1199 let mine = find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), my_xonly, rotation.scope, rotation.new_epoch);
1200 Some(mine.is_none())
1201}
1202
1203pub fn lowest_key_winner(candidate_keys: &[[u8; 32]]) -> Option<usize> {
1209 candidate_keys
1210 .iter()
1211 .enumerate()
1212 .min_by(|(_, a), (_, b)| a.cmp(b))
1213 .map(|(i, _)| i)
1214}
1215
1216fn unique_tag(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, RekeyError> {
1219 let mut found: Option<String> = None;
1220 for t in rumor.tags.iter() {
1221 let s = t.as_slice();
1222 if s.len() >= 2 && s[0] == name {
1223 if found.is_some() {
1224 return Err(RekeyError::BadTag(name));
1225 }
1226 found = Some(s[1].clone());
1227 }
1228 }
1229 Ok(found)
1230}
1231
1232fn parse_u64(rumor: &UnsignedEvent, name: &'static str) -> Result<u64, RekeyError> {
1233 let raw = unique_tag(rumor, name)?.ok_or(RekeyError::BadTag(name))?;
1234 if !crate::community::edition::is_tag_decimal(&raw) {
1237 return Err(RekeyError::BadTag(name));
1238 }
1239 raw.parse::<u64>().map_err(|_| RekeyError::BadTag(name))
1240}
1241
1242fn parse_chunk(rumor: &UnsignedEvent) -> Result<(u32, u32), RekeyError> {
1243 let mut found: Option<(u32, u32)> = None;
1244 for t in rumor.tags.iter() {
1245 let s = t.as_slice();
1246 if s.len() >= 3 && s[0] == TAG_CHUNK {
1247 if found.is_some() {
1248 return Err(RekeyError::BadTag(TAG_CHUNK));
1249 }
1250 if !crate::community::edition::is_tag_decimal(&s[1]) || !crate::community::edition::is_tag_decimal(&s[2]) {
1251 return Err(RekeyError::BadTag(TAG_CHUNK));
1252 }
1253 let i: u32 = s[1].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1254 let n: u32 = s[2].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
1255 found = Some((i, n));
1256 }
1257 }
1258 let (i, n) = found.ok_or(RekeyError::BadTag(TAG_CHUNK))?;
1259 if n < 1 || i < 1 || i > n {
1260 return Err(RekeyError::BadChunkIndex);
1261 }
1262 Ok((i, n))
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267
1268 fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
1272 crate::signer::ActiveSigner::Keys(k.clone())
1273 }
1274 use super::*;
1275
1276 fn keys(byte: u8) -> Keys {
1277 Keys::new(SecretKey::from_slice(&[byte; 32]).unwrap())
1278 }
1279
1280 fn xonly(k: &Keys) -> [u8; 32] {
1281 k.public_key().to_bytes()
1282 }
1283
1284 const CHAN: ChannelId = ChannelId([0x42u8; 32]);
1285
1286 #[test]
1289 fn bound_plaintext_layout_is_frozen() {
1290 let pt = bound_plaintext(RekeyScope::Root, Epoch(1), &[0xABu8; 32]);
1291 let expected = format!("{}{}{}", "00".repeat(32), "0000000000000001", "ab".repeat(32));
1292 assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
1293 let pt2 = bound_plaintext(RekeyScope::Channel(ChannelId([0x11u8; 32])), Epoch(0x0102), &[0xCDu8; 32]);
1294 let expected2 = format!("{}{}{}", "11".repeat(32), "0000000000000102", "cd".repeat(32));
1295 assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt2), expected2);
1296 }
1297
1298 #[test]
1299 fn blob_round_trips_both_scopes() {
1300 let rotator = keys(7);
1301 let recipient = keys(8);
1302 for (scope, epoch, key) in [
1303 (RekeyScope::Root, Epoch(1), [0xABu8; 32]),
1304 (RekeyScope::Channel(CHAN), Epoch(5), [0xCDu8; 32]),
1305 ] {
1306 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1307 let got = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob).unwrap();
1308 assert_eq!(got, key, "the recipient recovers the fresh key");
1309 }
1310 }
1311
1312 #[tokio::test]
1313 async fn signer_blob_is_wire_compatible_with_local_both_directions() {
1314 let rotator = keys(7);
1318 let recipient = keys(8);
1319 let scope = RekeyScope::Root;
1320 let epoch = Epoch(3);
1321 let key = [0x5Au8; 32];
1322
1323 let blob_l = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
1325 let got_s = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_l).await.unwrap();
1326 assert_eq!(got_s, key, "signer opens a local-built blob");
1327
1328 let blob_s = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).await.unwrap();
1330 assert_eq!(blob_s.locator, blob_l.locator, "same public locator regardless of build path");
1331 let got_l = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob_s).unwrap();
1332 assert_eq!(got_l, key, "local opens a signer-built blob");
1333
1334 let got_ss = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_s).await.unwrap();
1336 assert_eq!(got_ss, key, "signer round-trips its own blob");
1337 }
1338
1339 #[tokio::test]
1340 async fn signer_blob_bound_check_still_gates_scope_epoch_splice() {
1341 let rotator = keys(7);
1342 let recipient = keys(8);
1343 let blob = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[9u8; 32]).await.unwrap();
1344 assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob).await.is_err(), "epoch splice rejected");
1345 assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob).await.is_err(), "scope splice rejected");
1346 }
1347
1348 #[test]
1349 fn locator_is_public_and_computable_from_pubkeys_alone() {
1350 let rotator = keys(7);
1354 let recipient = keys(8);
1355 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(2), &[1u8; 32]).unwrap();
1356 let recomputed = blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(2));
1357 assert_eq!(blob.locator, recomputed, "both sides compute the same public locator");
1358 }
1359
1360 #[test]
1361 fn a_non_recipient_cannot_open_even_holding_the_public_locator() {
1362 let rotator = keys(7);
1366 let recipient = keys(8);
1367 let outsider = keys(9);
1368 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[2u8; 32]).unwrap();
1369 assert_eq!(blob.locator, blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)));
1371 assert!(open_blob_local(outsider.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).is_err());
1374 }
1375
1376 #[test]
1377 fn a_relocated_blob_still_opens_by_decrypt_not_locator() {
1378 let rotator = keys(7);
1382 let recipient = keys(8);
1383 let mut blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[3u8; 32]).unwrap();
1384 blob.locator = "ff".repeat(32);
1385 assert_eq!(
1387 open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).unwrap(),
1388 [3u8; 32]
1389 );
1390 assert!(find_my_blob(std::slice::from_ref(&blob), &xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)).is_none());
1392 }
1393
1394 #[test]
1395 fn scope_and_epoch_splices_are_rejected_on_open() {
1396 let rotator = keys(7);
1397 let recipient = keys(8);
1398 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[4u8; 32]).unwrap();
1399 assert!(matches!(
1401 open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob),
1402 Err(RekeyError::ScopeSplice)
1403 ));
1404 assert!(matches!(
1406 open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob),
1407 Err(RekeyError::EpochSplice)
1408 ));
1409 }
1410
1411 #[test]
1412 fn wrapped_carries_base64_of_the_72_bytes_for_bunker_parity() {
1413 let rotator = keys(7);
1417 let recipient = keys(8);
1418 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[5u8; 32]).unwrap();
1419 let ck = ConversationKey::derive(recipient.secret_key(), &rotator.public_key()).unwrap();
1420 let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).unwrap();
1421 let inner = nostr_sdk::prelude::nip44::v2::decrypt_to_bytes(&ck, &payload).unwrap();
1422 assert_eq!(String::from_utf8(inner).unwrap(), bound_plaintext_b64(RekeyScope::Root, Epoch(1), &[5u8; 32]));
1423 }
1424
1425 #[test]
1426 fn distinct_recipients_and_scopes_get_distinct_locators() {
1427 let rotator = keys(7);
1428 let r1 = keys(8);
1429 let r2 = keys(9);
1430 assert_ne!(
1431 blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1432 blob_locator(&xonly(&rotator), &xonly(&r2), RekeyScope::Root, Epoch(1))
1433 );
1434 assert_ne!(
1436 blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
1437 blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Channel(CHAN), Epoch(1))
1438 );
1439 }
1440
1441 fn root() -> [u8; 32] {
1444 [0x55u8; 32]
1445 }
1446
1447 #[test]
1448 fn channel_rekey_round_trips_through_the_stream() {
1449 let rotator = keys(1);
1450 let recipient = keys(8);
1451 let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1452 let key = [0xABu8; 32];
1453 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &key).unwrap();
1454 let commit = epoch_key_commitment(Epoch(0), &[0xEEu8; 32]);
1455 let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &commit, &[blob.clone()], 1, 1, 100, None, false).unwrap();
1456 let (wrap, _) = seal_rekey_chunk(&rumor, &group, &rotator, Timestamp::from_secs(100)).unwrap();
1457
1458 assert_ne!(wrap.pubkey, rotator.public_key());
1460 assert_eq!(wrap.pubkey, group.pk());
1461
1462 let opened = stream::open_wrap(&wrap, &group).unwrap();
1463 let chunk = parse_rekey_chunk(&opened).unwrap();
1464 assert_eq!(chunk.rotator, rotator.public_key(), "rotator recovered from the seal");
1465 assert!(matches!(chunk.scope, RekeyScope::Channel(c) if c.0 == CHAN.0));
1466 assert_eq!(chunk.new_epoch, Epoch(1));
1467 assert_eq!(chunk.prev_epoch, Epoch(0));
1468 assert_eq!(chunk.prev_commit, commit);
1469 assert_eq!(chunk.chunk, (1, 1));
1470 assert_eq!(chunk.blobs, vec![blob]);
1471 }
1472
1473 #[test]
1474 fn an_access_delivery_round_trips_and_never_reads_as_a_rotation() {
1475 let (deliverer, recipient) = (keys(1), keys(8));
1476 let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1477 let key = [0xABu8; 32];
1478 let blob = build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(3), &key).unwrap();
1479 let rumor = build_access_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), std::slice::from_ref(&blob), 100).unwrap();
1480 let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1481 let opened = stream::open_wrap(&wrap, &group).unwrap();
1482 let delivery = parse_access_delivery(&opened).unwrap();
1483 assert_eq!((delivery.deliverer, delivery.epoch), (deliverer.public_key(), Epoch(3)));
1484 let mine = find_my_blob(&delivery.blobs, &xonly(&deliverer), &xonly(&recipient), delivery.scope, delivery.epoch).unwrap();
1485 assert_eq!(open_blob_local(recipient.secret_key(), &deliverer.public_key(), delivery.scope, delivery.epoch, mine).unwrap(), key);
1486 assert!(parse_rekey_chunk(&opened).is_err(), "a delivery is no rotation");
1487 let commit = epoch_key_commitment(Epoch(2), &[0xEEu8; 32]);
1489 let rotation = build_rekey_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), Epoch(2), &commit, &[blob], 1, 1, 100, None, false).unwrap();
1490 let (wrap, _) = seal_rekey_chunk(&rotation, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1491 assert!(parse_access_delivery(&stream::open_wrap(&wrap, &group).unwrap()).is_err());
1492 }
1493
1494 #[test]
1495 fn a_history_delivery_round_trips_and_binds_its_channel_and_epoch() {
1496 let (deliverer, recipient) = (keys(1), keys(8));
1497 let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
1498 let past = crate::community::v2::derive::channel_group_key(&[0x42; 32], &CHAN, Epoch(2));
1499 let view = HistoryView::of(&past);
1500 let blob = build_history_blob_local(&deliverer, &recipient.public_key(), &CHAN, Epoch(2), &view).unwrap();
1501 let rumor = build_history_rumor(deliverer.public_key(), &CHAN, Epoch(2), std::slice::from_ref(&blob), 100).unwrap();
1502 let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
1503 let opened = stream::open_wrap(&wrap, &group).unwrap();
1504 let d = parse_history_delivery(&opened, &CHAN).unwrap();
1505 assert_eq!((d.deliverer, d.epoch), (deliverer.public_key(), Epoch(2)));
1506 assert_eq!(d.blobs[0].locator, history_locator(&xonly(&deliverer), &xonly(&recipient), &CHAN, Epoch(2)));
1507 assert_eq!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(2), &d.blobs[0]).unwrap(), view, "the address and key of that epoch");
1508 assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(3), &d.blobs[0]), Err(RekeyError::EpochSplice)));
1509 let other = ChannelId([0x01; 32]);
1510 assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &other, Epoch(2), &d.blobs[0]), Err(RekeyError::ScopeSplice)));
1511 assert!(parse_history_delivery(&opened, &other).is_err(), "another channel's history isn't this one's");
1512 assert!(parse_access_delivery(&opened).is_err() && parse_rekey_chunk(&opened).is_err(), "nor is it a key or a rotation");
1513 let msg = stream::build_rumor_secs(9, deliverer.public_key(), "old", vec![], 1);
1515 let (old_wrap, _) = stream::wrap_seal(&stream::build_seal(&msg, SealForm::Plaintext, &past, &deliverer).unwrap(), &past, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1516 let read = stream::open_wrap_at(&old_wrap, &PublicKey::from_slice(&view.address).unwrap(), &ConversationKey::new(view.conv_key), false).unwrap();
1517 assert_eq!(read.rumor.content, "old");
1518 }
1519
1520 #[test]
1521 fn base_rekey_addresses_under_the_prior_root() {
1522 let rotator = keys(1);
1525 let recipient = keys(8);
1526 let prior_root = [0x66u8; 32];
1527 let community = CommunityId([0x77u8; 32]);
1528 let new_root = [0x99u8; 32];
1529 let group = base_rekey_group(&prior_root, &community, Epoch(1));
1530 let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &new_root).unwrap();
1531 let commit = epoch_key_commitment(Epoch(0), &prior_root);
1532 let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &commit, &[blob], 100, None, false).unwrap();
1533 assert_eq!(chunks.len(), 1);
1534
1535 let opened = stream::open_wrap(&chunks[0], &group).unwrap();
1536 let chunk = parse_rekey_chunk(&opened).unwrap();
1537 assert!(matches!(chunk.scope, RekeyScope::Root));
1538 let mine = find_my_blob(&chunk.blobs, &chunk.rotator.to_bytes(), &xonly(&recipient), chunk.scope, chunk.new_epoch).unwrap();
1540 assert_eq!(open_blob_local(recipient.secret_key(), &chunk.rotator, chunk.scope, chunk.new_epoch, mine).unwrap(), new_root);
1541
1542 let wrong = base_rekey_group(&[0u8; 32], &community, Epoch(1));
1544 assert!(stream::open_wrap(&chunks[0], &wrong).is_err());
1545 }
1546
1547 #[test]
1548 fn a_full_send_chunk_stays_under_the_relay_size_limit() {
1549 let rotator = keys(1);
1553 let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1554 let cite = crate::community::edition::AuthorityCitation { entity_id: [7; 32], version: u64::MAX, edition_hash: [8; 32] };
1555 let base: Vec<RekeyBlob> = (0..blobs_per_event(RekeyScope::Root))
1556 .map(|i| {
1557 let r = keys((i % 200 + 20) as u8);
1558 let inner = bound_base_plaintext_b64(Epoch(1), &[0xCD; 32], &[0xAB; 32], Some(&[0xEE; 32]));
1559 let ck = ConversationKey::derive(rotator.secret_key(), &r.public_key()).unwrap();
1560 let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).unwrap();
1561 RekeyBlob { locator: blob_locator(&xonly(&rotator), &r.public_key().to_bytes(), RekeyScope::Root, Epoch(1)), wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload) }
1562 })
1563 .collect();
1564 let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &base, 100, Some(&cite), true).unwrap();
1565 assert_eq!(chunks.len(), 1, "a full base chunk is exactly one event");
1566 assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full base chunk must fit a 64KB relay event", chunks[0].as_json().len());
1567
1568 let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1569 let narrow: Vec<RekeyBlob> = (0..blobs_per_event(scope))
1570 .map(|i| build_blob_local(rotator.secret_key(), &xonly(&rotator), &keys((i % 200 + 20) as u8).public_key(), scope, Epoch(1), &[0xCDu8; 32]).unwrap())
1571 .collect();
1572 let chunks = build_rekey_chunks_local(&rotator, &group, scope, Epoch(1), Epoch(0), &[0u8; 32], &narrow, 100, Some(&cite), false).unwrap();
1573 assert_eq!(chunks.len(), 1);
1574 assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full channel chunk must fit a 64KB relay event", chunks[0].as_json().len());
1575 }
1576
1577 #[test]
1578 fn a_full_history_delivery_stays_under_the_relay_size_limit() {
1579 let deliverer = keys(1);
1580 let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1581 let channel = crate::community::ChannelId([3; 32]);
1582 let view = HistoryView { address: [0xAA; 32], conv_key: [0xBB; 32] };
1583 let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT).map(|i| build_history_blob_local(&deliverer, &keys((i % 200 + 20) as u8).public_key(), &channel, Epoch(1), &view).unwrap()).collect();
1584 let rumor = build_history_rumor(deliverer.public_key(), &channel, Epoch(1), &blobs, 100).unwrap();
1585 let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1586 let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1587 assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full history delivery must fit a 64KB relay event", wrap.as_json().len());
1588 }
1589
1590 #[test]
1591 fn a_full_certified_delivery_stays_under_the_relay_size_limit() {
1592 let deliverer = keys(1);
1593 let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1594 let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1595 let recipients: Vec<Keys> = (0..MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| keys((i % 200 + 20) as u8)).collect();
1596 let blobs: Vec<RekeyBlob> = recipients.iter().map(|r| build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &r.public_key(), scope, Epoch(1), &[0xCD; 32]).unwrap()).collect();
1597 let certs: Vec<([u8; 32], [u8; 64])> = recipients.iter().map(|r| (r.public_key().to_bytes(), [0xEE; 64])).collect();
1598 let rumor = build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), Some([0x42; 32]), &blobs, &certs, 100).unwrap();
1599 let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
1600 let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
1601 assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full certified chunk must fit a 64KB relay event", wrap.as_json().len());
1602 }
1603
1604 #[test]
1605 fn a_certified_delivery_past_its_cap_is_refused() {
1606 let deliverer = keys(1);
1607 let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
1608 let blobs: Vec<RekeyBlob> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() }).collect();
1609 let certs: Vec<([u8; 32], [u8; 64])> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| ([i as u8; 32], [0xEE; 64])).collect();
1610 assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &certs, 100).is_err());
1611 assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &[], 100).is_ok(), "keys alone fit more");
1612 assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs[1..], &certs[1..], 100).is_ok());
1613 }
1614
1615 #[test]
1616 fn oversize_recipient_set_splits_into_chunks() {
1617 let rotator = keys(1);
1618 let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
1619 let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT + 1)
1621 .map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() })
1622 .collect();
1623 let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(2), Epoch(1), &[0u8; 32], &blobs, 100, None, false).unwrap();
1624 assert_eq!(chunks.len(), 2);
1625 let parsed: Vec<RekeyChunk> = chunks.iter().map(|w| parse_rekey_chunk(&stream::open_wrap(w, &group).unwrap()).unwrap()).collect();
1626 assert_eq!(parsed[0].chunk, (1, 2));
1627 assert_eq!(parsed[1].chunk, (2, 2));
1628 assert_eq!(parsed[0].blobs.len(), MAX_WIDE_BLOBS_PER_EVENT);
1629 assert_eq!(parsed[1].blobs.len(), 1);
1630 }
1631
1632 #[test]
1633 fn plaintext_sealed_rekey_is_rejected() {
1634 let rotator = keys(1);
1635 let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
1636 let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &[0u8; 32], &[], 1, 1, 100, None, false).unwrap();
1637 let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &rotator).unwrap();
1638 let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1639 let opened = stream::open_wrap(&wrap, &group).unwrap();
1640 assert!(parse_rekey_chunk(&opened).is_err(), "the rekey plane must be encrypted-sealed");
1641 }
1642
1643 #[test]
1644 fn non_monotonic_epoch_is_refused_at_mint_and_on_parse() {
1645 let rotator = keys(1);
1646 assert!(matches!(
1647 build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(1), &[0u8; 32], &[], 1, 1, 100, None, false),
1648 Err(RekeyError::NonMonotonicEpoch)
1649 ));
1650 }
1651
1652 #[test]
1653 fn bad_chunk_indices_are_refused() {
1654 let rotator = keys(1);
1655 for (i, n) in [(0u32, 1u32), (2, 1), (1, 0)] {
1656 assert!(
1657 matches!(build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &[], i, n, 100, None, false), Err(RekeyError::BadChunkIndex)),
1658 "chunk ({i},{n}) must be rejected"
1659 );
1660 }
1661 }
1662
1663 fn chunk_at(rotator: &Keys, scope: RekeyScope, new_epoch: u64, prev_epoch: u64, prev_key: &[u8; 32], blobs: Vec<RekeyBlob>, i: u32, n: u32) -> RekeyChunk {
1666 RekeyChunk {
1667 rotator: rotator.public_key(),
1668 scope,
1669 new_epoch: Epoch(new_epoch),
1670 prev_epoch: Epoch(prev_epoch),
1671 prev_commit: epoch_key_commitment(Epoch(prev_epoch), prev_key),
1672 chunk: (i, n),
1673 blobs,
1674 citation: None,
1675 severed: false,
1676 at_ms: 0,
1677 }
1678 }
1679
1680 #[test]
1681 fn a_rotation_dates_from_its_earliest_chunk() {
1682 let rotator = Keys::generate();
1683 let prev = [3u8; 32];
1684 let mut late = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1685 late.at_ms = 9_000;
1686 let mut early = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1687 early.at_ms = 4_000;
1688 let rotations = collect_rotations(&[late, early]);
1689 assert_eq!(rotations.len(), 1);
1690 assert_eq!(rotations[0].at_ms, 4_000, "a re-sent chunk never moves a rotation later");
1691 }
1692
1693 #[test]
1694 fn a_colliding_chunk_index_must_not_swallow_a_recipients_blob() {
1695 let rotator = keys(1);
1705 let prev = [0x55u8; 32];
1706 let mine = RekeyBlob { locator: "aa".repeat(32), wrapped: "mine".into() };
1707 let other = RekeyBlob { locator: "bb".repeat(32), wrapped: "other".into() };
1708
1709 let original = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![mine.clone()], 1, 1);
1712 let reclaim = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![other.clone()], 1, 1);
1713
1714 for (order, chunks) in [
1715 ("original first", vec![original.clone(), reclaim.clone()]),
1716 ("reclaim first", vec![reclaim.clone(), original.clone()]),
1717 ] {
1718 let rotations = collect_rotations(&chunks);
1719 assert_eq!(rotations.len(), 1, "{order}: same correlation key");
1720 let has_mine = rotations[0].blobs.iter().any(|b| b.locator == mine.locator);
1721 assert!(
1722 has_mine,
1723 "{order}: my blob was dropped by an index collision — that reads as a removal \
1724 and removal deletes the community",
1725 );
1726 }
1727 }
1728
1729 #[test]
1730 fn a_severed_rotation_cannot_be_laundered_by_an_unmarked_chunk() {
1731 let rotator = keys(1);
1739 let prev = [0x44u8; 32];
1740 let mut marked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
1741 marked.severed = true;
1742 let unmarked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
1743
1744 for (order, chunks) in [
1745 ("marked first", vec![marked.clone(), unmarked.clone()]),
1746 ("unmarked first", vec![unmarked.clone(), marked.clone()]),
1747 ] {
1748 let rotations = collect_rotations(&chunks);
1749 assert_eq!(rotations.len(), 1, "{order}: one correlation key, one rotation");
1750 assert!(
1751 rotations[0].severed,
1752 "{order}: an unmarked sibling must never launder the containment away",
1753 );
1754 assert!(rotations[0].is_complete(), "{order}: both chunks held");
1755 }
1756 }
1757
1758 #[test]
1759 fn continuity_extends_gaps_and_forks() {
1760 let rotator = keys(1);
1761 let held = [0x33u8; 32];
1762 let good = chunk_at(&rotator, RekeyScope::Root, 3, 2, &held, vec![], 1, 1);
1764 assert_eq!(check_continuity(&good, Epoch(2), &held), Continuity::Extends);
1765 let ahead = chunk_at(&rotator, RekeyScope::Root, 5, 4, &held, vec![], 1, 1);
1767 assert_eq!(check_continuity(&ahead, Epoch(2), &held), Continuity::Gap);
1768 let fork = chunk_at(&rotator, RekeyScope::Root, 3, 2, &[0x99u8; 32], vec![], 1, 1);
1770 assert_eq!(check_continuity(&fork, Epoch(2), &held), Continuity::Fork);
1771 let stale = chunk_at(&rotator, RekeyScope::Root, 2, 1, &held, vec![], 1, 1);
1773 assert_eq!(check_continuity(&stale, Epoch(2), &held), Continuity::Fork);
1774 }
1775
1776 #[test]
1777 fn a_missing_chunk_is_never_a_removal() {
1778 let rotator = keys(1);
1781 let me = keys(8);
1782 let my_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &me.public_key(), RekeyScope::Root, Epoch(1), &[0xAAu8; 32]).unwrap();
1784 let c1 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![RekeyBlob { locator: "bb".repeat(32), wrapped: "x".into() }], 1, 2);
1785 let rots = collect_rotations(&[c1.clone()]);
1786 assert_eq!(rots.len(), 1);
1787 assert!(!rots[0].is_complete(), "one of two chunks held → incomplete");
1788 assert_eq!(am_i_removed(&rots[0], &xonly(&me)), None, "incomplete → keep recovering, never conclude removal");
1789
1790 let c2 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![my_blob.clone()], 2, 2);
1792 let rots = collect_rotations(&[c1, c2]);
1793 assert!(rots[0].is_complete());
1794 assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(false));
1795 let mine = find_my_blob(&rots[0].blobs, &rots[0].rotator.to_bytes(), &xonly(&me), RekeyScope::Root, Epoch(1)).unwrap();
1797 assert_eq!(open_blob_local(me.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), mine).unwrap(), [0xAAu8; 32]);
1798 }
1799
1800 #[test]
1801 fn a_complete_rotation_without_my_blob_is_a_removal() {
1802 let rotator = keys(1);
1803 let me = keys(8);
1804 let other = keys(9);
1805 let their_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &other.public_key(), RekeyScope::Root, Epoch(1), &[0xBBu8; 32]).unwrap();
1807 let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![their_blob], 1, 1);
1808 let rots = collect_rotations(&[c]);
1809 assert!(rots[0].is_complete());
1810 assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(true), "complete rotation, no blob for me → removed");
1811 }
1812
1813 #[test]
1814 fn collect_rotations_separates_concurrent_rotators_and_scopes() {
1815 let rot_a = keys(1);
1818 let rot_b = keys(2);
1819 let ca = chunk_at(&rot_a, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1820 let cb = chunk_at(&rot_b, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
1821 let cc = chunk_at(&rot_a, RekeyScope::Channel(CHAN), 2, 1, &[7u8; 32], vec![], 1, 1);
1822 let rots = collect_rotations(&[ca, cb, cc]);
1823 assert_eq!(rots.len(), 3, "different rotator or scope ⇒ different rotation");
1824 }
1825
1826 #[test]
1827 fn duplicate_chunk_delivery_is_idempotent() {
1828 let rotator = keys(1);
1829 let blob = RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() };
1830 let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![blob.clone()], 1, 1);
1831 let rots = collect_rotations(&[c.clone(), c]);
1832 assert_eq!(rots.len(), 1);
1833 assert_eq!(rots[0].blobs.len(), 1, "re-delivering a chunk must not double its blobs");
1834 }
1835
1836 #[test]
1839 fn base_blob_forms_are_width_declared() {
1840 let community = CommunityId([0x77u8; 32]);
1841 let new_root = [0xABu8; 32];
1842 let control_root = [0x5Cu8; 32];
1843 let epoch = Epoch(3);
1844 let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1845
1846 let member = bound_base_plaintext(epoch, &new_root, &control_pk, None);
1848 assert_eq!(member.len(), 104);
1849 let d = parse_bound_base_plaintext(&member, &community, epoch).unwrap();
1850 assert_eq!(d.new_root, new_root);
1851 assert_eq!(d.control_pk, Some(control_pk));
1852 assert_eq!(d.control_root, None);
1853
1854 let staff = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1856 assert_eq!(staff.len(), 136);
1857 let d = parse_bound_base_plaintext(&staff, &community, epoch).unwrap();
1858 assert_eq!(d.control_root, Some(control_root));
1859 assert_eq!(d.control_pk, Some(control_pk));
1860
1861 let legacy = bound_plaintext(RekeyScope::Root, epoch, &new_root);
1863 let d = parse_bound_base_plaintext(&legacy, &community, epoch).unwrap();
1864 assert_eq!(d.new_root, new_root);
1865 assert_eq!(d.control_pk, None);
1866 assert_eq!(d.control_root, None);
1867 }
1868
1869 #[test]
1870 fn base_blob_mismatched_control_pair_is_refused_whole() {
1871 let community = CommunityId([0x77u8; 32]);
1872 let control_pk = control_signer_group_key(&[0x5Cu8; 32], &community, Epoch(3)).pk().to_bytes();
1873 let bad = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &control_pk, Some(&[0x11u8; 32]));
1876 assert!(matches!(
1877 parse_bound_base_plaintext(&bad, &community, Epoch(3)),
1878 Err(RekeyError::ControlPairMismatch)
1879 ));
1880 }
1881
1882 #[test]
1883 fn base_blob_rejects_any_other_width_and_splices() {
1884 let community = CommunityId([0x77u8; 32]);
1885 for n in [0usize, 71, 73, 100, 105, 135] {
1887 assert!(matches!(
1888 parse_bound_base_plaintext(&vec![0u8; n], &community, Epoch(1)),
1889 Err(RekeyError::BadBaseBlobWidth(m)) if m == n
1890 ));
1891 }
1892 let control_root = [0x5Cu8; 32];
1894 let pk = control_signer_group_key(&control_root, &community, Epoch(3)).pk().to_bytes();
1895 let pt = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &pk, None);
1896 assert!(matches!(parse_bound_base_plaintext(&pt, &community, Epoch(4)), Err(RekeyError::EpochSplice)));
1897 let mut channel_scoped = pt.clone();
1898 channel_scoped[..32].copy_from_slice(&[0x42u8; 32]);
1899 assert!(matches!(parse_bound_base_plaintext(&channel_scoped, &community, Epoch(3)), Err(RekeyError::ScopeSplice)));
1900 }
1901
1902 #[tokio::test]
1903 async fn base_blob_round_trips_member_and_staff_forms() {
1904 let rotator = keys(7);
1905 let member = keys(8);
1906 let staffer = keys(9);
1907 let community = CommunityId([0x77u8; 32]);
1908 let epoch = Epoch(2);
1909 let new_root = [0xEEu8; 32];
1910 let control_root = [0xDDu8; 32];
1911 let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1912
1913 let mb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), epoch, &new_root, &control_pk, None).await.unwrap();
1914 let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &mb).await.unwrap();
1915 assert_eq!(d.new_root, new_root);
1916 assert_eq!(d.control_pk, Some(control_pk));
1917 assert_eq!(d.control_root, None, "a member blob never carries the secret");
1918
1919 let sb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &staffer.public_key(), epoch, &new_root, &control_pk, Some(&control_root)).await.unwrap();
1920 let d = open_base_blob(&as_signer(&staffer), &rotator.public_key(), &community, epoch, &sb).await.unwrap();
1921 assert_eq!(d.control_root, Some(control_root));
1922
1923 assert_eq!(mb.locator, blob_locator(&xonly(&rotator), &xonly(&member), RekeyScope::Root, epoch));
1925 let legacy = build_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), RekeyScope::Root, epoch, &new_root).await.unwrap();
1927 let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &legacy).await.unwrap();
1928 assert_eq!(d.new_root, new_root);
1929 assert_eq!(d.control_pk, None);
1930 }
1931
1932 #[test]
1933 fn a_future_wider_base_blob_degrades_instead_of_forking() {
1934 let community = CommunityId([0x77u8; 32]);
1938 let new_root = [0xABu8; 32];
1939 let control_root = [0x5Cu8; 32];
1940 let epoch = Epoch(3);
1941 let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();
1942
1943 let mut future = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
1945 future.extend_from_slice(&[0x99u8; 32]);
1946 let d = parse_bound_base_plaintext(&future, &community, epoch).unwrap();
1947 assert_eq!(d.new_root, new_root);
1948 assert_eq!(d.control_pk, Some(control_pk));
1949 assert_eq!(d.control_root, Some(control_root), "held offsets still verify → full function");
1950
1951 let mut reordered = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&[0x44u8; 32]));
1954 reordered.extend_from_slice(&[0x99u8; 32]);
1955 let d = parse_bound_base_plaintext(&reordered, &community, epoch).unwrap();
1956 assert_eq!(d.new_root, new_root);
1957 assert_eq!(d.control_pk, Some(control_pk));
1958 assert_eq!(d.control_root, None, "an unverifiable secret is dropped, not adopted");
1959
1960 assert!(parse_bound_base_plaintext(&future, &community, Epoch(4)).is_err());
1962 }
1963
1964 #[test]
1965 fn control_wrap_layout_is_frozen_and_round_trips() {
1966 let pt = encode_control_wrap(Epoch(7), &[0xCDu8; 32]);
1967 assert_eq!(pt.len(), 40);
1968 let expected = format!("{}{}", "0000000000000007", "cd".repeat(32));
1969 assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
1970 let (epoch, root) = parse_control_wrap(&pt).unwrap();
1971 assert_eq!(epoch, Epoch(7));
1972 assert_eq!(root, [0xCDu8; 32]);
1973 for n in [0usize, 39, 41, 72] {
1974 assert!(matches!(parse_control_wrap(&vec![0u8; n]), Err(RekeyError::BadControlWrapLength(m)) if m == n));
1975 }
1976 }
1977
1978 #[test]
1979 fn lowest_key_fork_winner_is_deterministic() {
1980 let keys_a = [[0x03u8; 32], [0x01u8; 32], [0x02u8; 32]];
1983 assert_eq!(lowest_key_winner(&keys_a), Some(1));
1984 let keys_b = [[0x01u8; 32], [0x02u8; 32], [0x03u8; 32]];
1985 assert_eq!(lowest_key_winner(&keys_b), Some(0));
1986 assert_eq!(lowest_key_winner(&[]), None);
1987 }
1988}