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 scoped: Vec<([u8; 32], [u8; 64], u64)>,
814 pub mint: Option<(u32, u32)>,
816}
817
818const TAG_MINT: &str = "mint";
820
821pub 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
831const TAG_WRITER: &str = "writer";
833
834const TAG_CERT: &str = "cert";
836
837const TAG_SCOPED_CERT: &str = "rcert";
840
841pub 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
846pub 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
851pub 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#[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
892pub 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 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
951pub 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#[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
983fn 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
1009pub 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
1039pub 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
1050pub 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#[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
1080pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1107pub enum Continuity {
1108 Extends,
1111 Gap,
1114 Fork,
1116}
1117
1118pub 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 Continuity::Fork
1134 }
1135}
1136
1137#[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 pub blobs: Vec<RekeyBlob>,
1148 pub declared_chunks: u32,
1150 pub held_chunks: std::collections::BTreeSet<u32>,
1152 pub citation: Option<crate::community::edition::AuthorityCitation>,
1155 pub severed: bool,
1158 pub at_ms: u64,
1160}
1161
1162impl Rotation {
1163 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 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
1188pub 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 entry.declared_chunks = entry.declared_chunks.max(c.chunk.1);
1213 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
1231pub 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
1242pub 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
1255fn 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 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 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 #[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 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 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 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 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 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 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 assert_eq!(blob.locator, blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)));
1410 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 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 assert_eq!(
1426 open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).unwrap(),
1427 [3u8; 32]
1428 );
1429 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 assert!(matches!(
1440 open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob),
1441 Err(RekeyError::ScopeSplice)
1442 ));
1443 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let rotator = keys(1);
1820 let me = keys(8);
1821 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 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 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 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 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 #[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 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 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 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 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 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 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 assert_eq!(mb.locator, blob_locator(&xonly(&rotator), &xonly(&member), RekeyScope::Root, epoch));
1964 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 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 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 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 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 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}