1use crate::event_ext::FinalizeUnsignedWithId;
26use crate::event_ext::FinalizeOnClock;
27#[cfg(test)]
28use nostr_sdk::prelude::FinalizeEvent;
29use nostr_sdk::prelude::nip44::v2::ConversationKey;
30use nostr_sdk::prelude::{Event, EventBuilder, EventId, Keys, Kind, PublicKey, Tag, Timestamp, UnsignedEvent};
31
32use super::super::{ChannelId, Epoch};
33use super::derive::GroupKey;
34
35pub const KIND_WRAP: u16 = 1059;
37pub const KIND_WRAP_EPHEMERAL: u16 = 21059;
39pub const KIND_SEAL_ENCRYPTED: u16 = 20013;
41pub const KIND_SEAL_PLAINTEXT: u16 = 20014;
43
44pub const NIP44_MAX_PLAINTEXT: usize = 65_535;
46
47const TAG_MS: &str = "ms";
48const TAG_CHANNEL: &str = "channel";
49const TAG_EPOCH: &str = "epoch";
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SealForm {
55 Encrypted,
56 Plaintext,
57}
58
59impl SealForm {
60 pub fn kind(self) -> u16 {
61 match self {
62 SealForm::Encrypted => KIND_SEAL_ENCRYPTED,
63 SealForm::Plaintext => KIND_SEAL_PLAINTEXT,
64 }
65 }
66
67 fn from_kind(kind: u16) -> Option<Self> {
68 match kind {
69 KIND_SEAL_ENCRYPTED => Some(SealForm::Encrypted),
70 KIND_SEAL_PLAINTEXT => Some(SealForm::Plaintext),
71 _ => None,
72 }
73 }
74}
75
76#[derive(Debug)]
78pub enum StreamError {
79 Sign(String),
80 Encrypt(String),
81 Decrypt(String),
82 Parse(String),
83 Oversize(usize),
85 TooLarge(usize),
87 BadWrapKind(u16),
89 WrongStream,
91 BadWrapSignature,
95 BadSealKind(u16),
97 BadSealSignature,
99 AuthorMismatch,
101 BadRumorId,
103 BadMs,
106 ChannelMismatch,
108 EpochMismatch,
110 MissingTag(&'static str),
111 DuplicateTag(&'static str),
113 NotRewrappable,
116}
117
118impl std::fmt::Display for StreamError {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 match self {
121 StreamError::Sign(e) => write!(f, "sign: {e}"),
122 StreamError::Encrypt(e) => write!(f, "encrypt: {e}"),
123 StreamError::Decrypt(e) => write!(f, "decrypt: {e}"),
124 StreamError::Parse(e) => write!(f, "parse: {e}"),
125 StreamError::Oversize(n) => write!(f, "plaintext {n} bytes exceeds NIP-44 cap"),
126 StreamError::TooLarge(n) => f.write_str(&crate::event_size::too_large(*n)),
127 StreamError::BadWrapKind(k) => write!(f, "not a stream wrap kind: {k}"),
128 StreamError::WrongStream => write!(f, "wrap author is not this stream"),
129 StreamError::BadWrapSignature => write!(f, "write-restricted wrap signature invalid"),
130 StreamError::BadSealKind(k) => write!(f, "not a seal kind: {k}"),
131 StreamError::BadSealSignature => write!(f, "seal signature invalid"),
132 StreamError::AuthorMismatch => write!(f, "rumor pubkey != seal pubkey"),
133 StreamError::BadRumorId => write!(f, "rumor id != computed hash"),
134 StreamError::BadMs => write!(f, "ms tag outside 0..=999"),
135 StreamError::ChannelMismatch => write!(f, "channel-binding mismatch (splice)"),
136 StreamError::EpochMismatch => write!(f, "epoch-binding mismatch (splice/replay)"),
137 StreamError::MissingTag(t) => write!(f, "missing rumor tag: {t}"),
138 StreamError::DuplicateTag(t) => write!(f, "duplicate rumor tag: {t}"),
139 StreamError::NotRewrappable => write!(f, "only plaintext seals survive re-wrapping"),
140 }
141 }
142}
143
144impl std::error::Error for StreamError {}
145
146#[derive(Debug, Clone)]
148pub struct OpenedStream {
149 pub rumor: UnsignedEvent,
151 pub rumor_id: EventId,
153 pub author: PublicKey,
155 pub seal_form: SealForm,
157 pub seal: Event,
160 pub wrapper_id: EventId,
162 pub at_ms: u64,
164 pub held: bool,
166}
167
168pub fn split_ms(at_ms: u64) -> (u64, u16) {
172 (at_ms / 1000, (at_ms % 1000) as u16)
173}
174
175pub fn resolve_ms_strict(rumor: &UnsignedEvent) -> Result<u64, StreamError> {
186 let secs = rumor.created_at.as_secs();
187 let Some(raw) = rumor.tags.iter().find_map(|t| {
196 let s = t.as_slice();
197 (s.first().map(|k| k.as_str()) == Some(TAG_MS)).then(|| s.get(1).cloned())
198 }) else {
199 return Ok(secs.saturating_mul(1000));
200 };
201 let raw = raw.ok_or(StreamError::BadMs)?;
206 if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
207 return Err(StreamError::BadMs);
208 }
209 let n: u64 = raw.parse().map_err(|_| StreamError::BadMs)?;
210 if n > 999 || (raw.len() > 1 && raw.starts_with('0')) {
211 return Err(StreamError::BadMs);
212 }
213 Ok(secs.saturating_mul(1000).saturating_add(n))
214}
215
216pub fn build_rumor_ms(
221 kind: u16,
222 author: PublicKey,
223 content: &str,
224 mut tags: Vec<Tag>,
225 at_ms: u64,
226) -> UnsignedEvent {
227 let (secs, offset) = split_ms(at_ms);
228 tags.push(Tag::custom(TAG_MS, [offset.to_string()]));
229 build_rumor_secs(kind, author, content, tags, secs)
230}
231
232pub fn build_rumor_secs(
235 kind: u16,
236 author: PublicKey,
237 content: &str,
238 tags: Vec<Tag>,
239 at_secs: u64,
240) -> UnsignedEvent {
241 let mut rumor = EventBuilder::new(Kind::Custom(kind), content)
245 .tags(tags)
246 .custom_created_at(Timestamp::from_secs(at_secs))
247 .finalize_unsigned_with_id(author);
248 rumor.ensure_id();
249 rumor
250}
251
252pub fn seal_content(rumor: &UnsignedEvent, form: SealForm, group: &GroupKey) -> Result<String, StreamError> {
258 let json = rumor.as_json();
259 cap(json.len())?;
260 match form {
261 SealForm::Plaintext => Ok(json),
262 SealForm::Encrypted => {
263 let ct = crate::community::cipher::encrypt_with_random_nonce(group.conv_key(), json.as_bytes()).map_err(|e| StreamError::Encrypt(e.to_string()))?;
264 Ok(crate::simd::base64::STANDARD.encode_to_string(&ct))
265 }
266 }
267}
268
269pub fn build_seal(rumor: &UnsignedEvent, form: SealForm, group: &GroupKey, author_keys: &Keys) -> Result<Event, StreamError> {
273 let content = seal_content(rumor, form, group)?;
274 EventBuilder::new(Kind::Custom(form.kind()), content)
275 .custom_created_at(rumor.created_at)
276 .finalize_on_clock(author_keys)
277 .map_err(|e| StreamError::Sign(e.to_string()))
278}
279
280pub fn wrap_seal(seal: &Event, group: &GroupKey, wrap_kind: u16, wrap_at: Timestamp) -> Result<(Event, Keys), StreamError> {
289 wrap_seal_with_tags(seal, group, wrap_kind, wrap_at, &[])
290}
291
292pub fn wrap_seal_with_tags(
297 seal: &Event,
298 group: &GroupKey,
299 wrap_kind: u16,
300 wrap_at: Timestamp,
301 extra_tags: &[Tag],
302) -> Result<(Event, Keys), StreamError> {
303 let ephemeral = Keys::generate();
304 let wrap = wrap_seal_for(seal, group, wrap_kind, wrap_at, extra_tags, &ephemeral.public_key())?;
305 Ok((wrap, ephemeral))
306}
307
308pub fn wrap_seal_for(
311 seal: &Event,
312 group: &GroupKey,
313 wrap_kind: u16,
314 wrap_at: Timestamp,
315 extra_tags: &[Tag],
316 owner: &PublicKey,
317) -> Result<Event, StreamError> {
318 if wrap_kind != KIND_WRAP && wrap_kind != KIND_WRAP_EPHEMERAL {
319 return Err(StreamError::BadWrapKind(wrap_kind));
320 }
321 let seal_json = seal.as_json();
322 cap(seal_json.len())?;
323 let ct = crate::community::cipher::encrypt_with_random_nonce(group.conv_key(), seal_json.as_bytes()).map_err(|e| StreamError::Encrypt(e.to_string()))?;
324 let mut tags = vec![Tag::public_key(*owner)];
325 tags.extend_from_slice(extra_tags);
326 let wrap = EventBuilder::new(Kind::Custom(wrap_kind), crate::simd::base64::STANDARD.encode_to_string(&ct))
327 .tags(tags)
328 .custom_created_at(wrap_at)
329 .finalize_on_clock(group.keys())
330 .map_err(|e| StreamError::Sign(e.to_string()))?;
331 let len = wrap.as_json().len();
332 if len > crate::event_size::MAX_EVENT_BYTES {
333 return Err(StreamError::TooLarge(len));
334 }
335 Ok(wrap)
336}
337
338pub fn wrap_owner(wrap: &Event) -> Option<PublicKey> {
340 wrap.tags.iter().find_map(|t| {
341 let s = t.as_slice();
342 (s.len() >= 2 && s[0] == "p").then(|| PublicKey::from_hex(&s[1]).ok()).flatten()
343 })
344}
345
346#[allow(clippy::too_many_arguments)]
352pub async fn seal_and_wrap_signed<S: crate::signer::VectorSigner + ?Sized>(
353 signer: &S,
354 author: PublicKey,
355 rumor: &UnsignedEvent,
356 form: SealForm,
357 group: &GroupKey,
358 wrap_kind: u16,
359 wrap_at: Timestamp,
360 extra_tags: &[Tag],
361) -> Result<(Event, Keys), StreamError> {
362 let seal = sign_seal(signer, author, rumor, form, group).await?;
363 wrap_seal_with_tags(&seal, group, wrap_kind, wrap_at, extra_tags)
364}
365
366async fn sign_seal<S: crate::signer::VectorSigner + ?Sized>(
367 signer: &S,
368 author: PublicKey,
369 rumor: &UnsignedEvent,
370 form: SealForm,
371 group: &GroupKey,
372) -> Result<Event, StreamError> {
373 let content = seal_content(rumor, form, group)?;
374 let unsigned = EventBuilder::new(Kind::Custom(form.kind()), content)
375 .custom_created_at(rumor.created_at)
376 .finalize_unsigned_with_id(author);
377 signer
378 .sign_event_async(unsigned)
379 .await
380 .map_err(|e| StreamError::Sign(e.to_string()))
381}
382
383#[allow(clippy::too_many_arguments)]
385pub async fn seal_and_wrap_signed_for<S: crate::signer::VectorSigner + ?Sized>(
386 signer: &S,
387 author: PublicKey,
388 rumor: &UnsignedEvent,
389 form: SealForm,
390 group: &GroupKey,
391 wrap_kind: u16,
392 wrap_at: Timestamp,
393 extra_tags: &[Tag],
394 owner: &PublicKey,
395) -> Result<Event, StreamError> {
396 let seal = sign_seal(signer, author, rumor, form, group).await?;
397 wrap_seal_for(&seal, group, wrap_kind, wrap_at, extra_tags, owner)
398}
399
400pub fn rewrap_seal(seal: &Event, new_group: &GroupKey, wrap_at: Timestamp) -> Result<(Event, Keys), StreamError> {
405 if seal.kind.as_u16() != KIND_SEAL_PLAINTEXT {
406 return Err(StreamError::NotRewrappable);
407 }
408 wrap_seal(seal, new_group, KIND_WRAP, wrap_at)
409}
410
411pub fn open_wrap(wrap: &Event, group: &GroupKey) -> Result<OpenedStream, StreamError> {
422 open_wrap_at(wrap, &group.pk(), group.conv_key(), false)
423}
424
425pub fn open_wrap_at(
433 wrap: &Event,
434 address: &PublicKey,
435 conv_key: &nostr_sdk::prelude::nip44::v2::ConversationKey,
436 verify_wrap_sig: bool,
437) -> Result<OpenedStream, StreamError> {
438 let wrap_kind = wrap.kind.as_u16();
439 if wrap_kind != KIND_WRAP && wrap_kind != KIND_WRAP_EPHEMERAL {
440 return Err(StreamError::BadWrapKind(wrap_kind));
441 }
442 if wrap.pubkey != *address {
443 return Err(StreamError::WrongStream);
444 }
445 if verify_wrap_sig && !verified(wrap) {
446 return Err(StreamError::BadWrapSignature);
447 }
448
449 let seal = match batch_seal(wrap, conv_key) {
450 Some(seal) => seal,
451 None => crate::event_json::event(&open_nip44(conv_key, &wrap.content)?).map_err(|e| StreamError::Parse(e.to_string()))?,
452 };
453 let seal_form = SealForm::from_kind(seal.kind.as_u16()).ok_or(StreamError::BadSealKind(seal.kind.as_u16()))?;
454 if !verified(&seal) {
455 return Err(StreamError::BadSealSignature);
456 }
457
458 let rumor_json = match seal_form {
459 SealForm::Plaintext => seal.content.clone(),
460 SealForm::Encrypted => open_nip44(conv_key, &seal.content)?,
461 };
462 let mut rumor: UnsignedEvent = crate::event_json::unsigned(&rumor_json).map_err(|e| StreamError::Parse(e.to_string()))?;
463
464 if rumor.pubkey != seal.pubkey {
465 return Err(StreamError::AuthorMismatch);
466 }
467 let computed = EventId::compute(&rumor.pubkey, &rumor.created_at, &rumor.kind, &rumor.tags, &rumor.content);
471 if let Some(claimed) = rumor.id {
472 if claimed != computed {
473 return Err(StreamError::BadRumorId);
474 }
475 }
476 rumor.id = Some(computed);
477 let at_ms = resolve_ms_strict(&rumor)?;
478
479 Ok(OpenedStream {
480 rumor_id: computed,
481 author: seal.pubkey,
482 seal_form,
483 seal,
484 wrapper_id: wrap.id,
485 at_ms,
486 rumor,
487 held: false,
488 })
489}
490
491type CheckedSig = ([u8; 32], [u8; 32], [u8; 64]);
493
494fn checked_sig(e: &Event) -> CheckedSig {
495 (*e.pubkey.as_bytes(), *e.id.as_bytes(), *e.sig.as_bytes())
496}
497
498struct VerifiedSigs {
502 salt: [u8; 16],
503 cur: std::collections::HashSet<u128>,
504 prev: std::collections::HashSet<u128>,
505}
506
507const VERIFIED_SIGS_GEN: usize = 16_384;
508
509impl Default for VerifiedSigs {
510 fn default() -> Self {
511 let mut salt = [0u8; 16];
512 rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut salt);
513 VerifiedSigs { salt, cur: Default::default(), prev: Default::default() }
514 }
515}
516
517impl VerifiedSigs {
518 fn key(&self, sig: &CheckedSig) -> u128 {
519 let mut h = crate::crypto::sha256::Sha256::new();
520 h.update(self.salt);
521 h.update(sig.0);
522 h.update(sig.1);
523 h.update(sig.2);
524 u128::from_le_bytes(h.finalize()[..16].try_into().expect("16 of 32 bytes"))
525 }
526
527 fn contains(&mut self, key: u128) -> bool {
528 if self.cur.contains(&key) {
529 return true;
530 }
531 if self.prev.remove(&key) {
532 self.insert(key);
533 return true;
534 }
535 false
536 }
537
538 fn insert(&mut self, key: u128) {
539 if self.cur.len() >= VERIFIED_SIGS_GEN {
540 self.prev = std::mem::take(&mut self.cur);
541 }
542 self.cur.insert(key);
543 }
544}
545
546fn verified_sigs() -> std::sync::Arc<std::sync::Mutex<VerifiedSigs>> {
547 struct Key;
548 crate::db::current_session().scoped::<Key, std::sync::Mutex<VerifiedSigs>>()
549}
550
551#[cfg(test)]
552fn forget_verified() {
553 *verified_sigs().lock().unwrap() = VerifiedSigs::default();
554}
555
556fn verified(e: &Event) -> bool {
559 let sigs = verified_sigs();
560 let key = {
561 let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
562 let key = known.key(&checked_sig(e));
563 if known.contains(key) {
564 drop(known);
565 return e.verify_id();
566 }
567 key
568 };
569 let ok = e.verify_id() && crate::crypto::batch_verify::signature(e);
570 if ok {
571 sigs.lock().unwrap_or_else(|p| p.into_inner()).insert(key);
572 }
573 ok
574}
575
576thread_local! {
577 static BATCH_SEALS: std::cell::RefCell<std::collections::HashMap<EventId, (ConversationKey, Event)>> = Default::default();
580}
581
582fn batch_seal(wrap: &Event, conv_key: &ConversationKey) -> Option<Event> {
584 BATCH_SEALS.with_borrow_mut(|seals| match seals.get(&wrap.id) {
585 Some((ck, _)) if ck == conv_key => seals.remove(&wrap.id).map(|(_, seal)| seal),
586 _ => None,
587 })
588}
589
590pub struct BatchChecked(());
593
594impl Drop for BatchChecked {
595 fn drop(&mut self) {
596 BATCH_SEALS.with_borrow_mut(std::collections::HashMap::clear);
597 }
598}
599
600pub fn check_signatures_together(wraps: &[(&Event, Vec<&ConversationKey>, bool)]) -> BatchChecked {
607 let guard = BatchChecked(());
608 let mut seals: Vec<Event> = Vec::with_capacity(wraps.len());
609 BATCH_SEALS.with_borrow_mut(|kept| {
610 kept.clear();
611 for (wrap, keys, _) in wraps {
612 let opened = keys.iter().find_map(|ck| Some((**ck, crate::event_json::event(&open_nip44(ck, &wrap.content).ok()?).ok()?)));
613 if let Some((ck, seal)) = opened {
614 seals.push(seal.clone());
615 kept.insert(wrap.id, (ck, seal));
616 }
617 }
618 });
619 let sigs = verified_sigs();
620 let unchecked: Vec<(&Event, u128)> = {
621 let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
622 wraps
623 .iter()
624 .filter(|(.., own)| *own)
625 .map(|(wrap, ..)| *wrap)
626 .chain(&seals)
627 .filter_map(|e| {
628 let key = known.key(&checked_sig(e));
629 (!known.contains(key)).then_some((e, key))
630 })
631 .collect()
632 };
633 if unchecked.len() >= nostr_verify::MIN_BATCH {
634 let events: Vec<&Event> = unchecked.iter().map(|(e, _)| *e).collect();
635 let ok = crate::crypto::batch_verify::signatures(&events);
636 let mut known = sigs.lock().unwrap_or_else(|p| p.into_inner());
637 for ((_, key), ok) in unchecked.iter().zip(ok) {
638 if ok {
639 known.insert(*key);
640 }
641 }
642 }
643 guard
644}
645
646pub fn check_page(wraps: &[&Event], group: &GroupKey) -> BatchChecked {
648 let page: Vec<_> = wraps.iter().map(|w| (*w, vec![group.conv_key()], false)).collect();
649 check_signatures_together(&page)
650}
651
652pub fn check_channel_binding(rumor: &UnsignedEvent, channel_id: &ChannelId, epoch: Epoch) -> Result<(), StreamError> {
656 match unique_tag_unsigned(rumor, TAG_CHANNEL)? {
657 Some(c) if c == channel_id.to_hex() => {}
658 Some(_) => return Err(StreamError::ChannelMismatch),
659 None => return Err(StreamError::MissingTag(TAG_CHANNEL)),
660 }
661 match unique_tag_unsigned(rumor, TAG_EPOCH)? {
662 Some(e) if e == epoch.0.to_string() => {}
663 Some(_) => return Err(StreamError::EpochMismatch),
664 None => return Err(StreamError::MissingTag(TAG_EPOCH)),
665 }
666 Ok(())
667}
668
669pub fn channel_binding_tags(channel_id: &ChannelId, epoch: Epoch) -> Vec<Tag> {
671 vec![
672 Tag::custom(TAG_CHANNEL, [channel_id.to_hex()]),
673 Tag::custom(TAG_EPOCH, [epoch.0.to_string()]),
674 ]
675}
676
677fn cap(len: usize) -> Result<(), StreamError> {
680 if len > NIP44_MAX_PLAINTEXT {
681 return Err(StreamError::Oversize(len));
682 }
683 Ok(())
684}
685
686fn open_nip44(conv_key: &ConversationKey, content_b64: &str) -> Result<String, StreamError> {
687 let ct = crate::simd::base64::STANDARD
688 .decode_to_vec(content_b64.as_bytes())
689 .map_err(|e| StreamError::Decrypt(e.to_string()))?;
690 let pt = crate::crypto::nip44::decrypt(conv_key, ct).map_err(|e| StreamError::Decrypt(e.to_string()))?;
691 String::from_utf8(pt).map_err(|e| StreamError::Parse(e.to_string()))
692}
693
694fn unique_tag_unsigned(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, StreamError> {
698 let mut found: Option<String> = None;
699 for t in rumor.tags.iter() {
700 let s = t.as_slice();
701 if s.len() >= 2 && s[0] == name {
702 if found.is_some() {
703 return Err(StreamError::DuplicateTag(name));
704 }
705 found = Some(s[1].clone());
706 }
707 }
708 Ok(found)
709}
710
711#[cfg(test)]
712mod tests {
713
714 fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
718 crate::signer::ActiveSigner::Keys(k.clone())
719 }
720 use super::super::super::{ChannelId, Epoch};
721 use super::super::derive::channel_group_key;
722 use super::super::kind;
723 use super::*;
724
725 fn group() -> GroupKey {
726 channel_group_key(&[7u8; 32], &chan(), Epoch(0))
727 }
728
729 fn chan() -> ChannelId {
730 ChannelId([0xabu8; 32])
731 }
732
733 fn send(author: &Keys, group: &GroupKey, form: SealForm, content: &str, at_ms: u64) -> Event {
734 let tags = channel_binding_tags(&chan(), Epoch(0));
735 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), content, tags, at_ms);
736 let seal = build_seal(&rumor, form, group, author).unwrap();
737 wrap_seal(&seal, group, KIND_WRAP, Timestamp::from_secs(1_700_000_000)).unwrap().0
738 }
739
740 #[test]
741 fn encrypted_round_trip_preserves_author_content_and_ms() {
742 let author = Keys::generate();
743 let wrap = send(&author, &group(), SealForm::Encrypted, "Hey chat!", 1_686_840_217_417);
744 assert_eq!(wrap.kind.as_u16(), KIND_WRAP);
745 assert_eq!(wrap.pubkey, group().pk(), "wrap is signed by the stream key");
746
747 let opened = open_wrap(&wrap, &group()).unwrap();
748 assert_eq!(opened.author, author.public_key());
749 assert_eq!(opened.rumor.content, "Hey chat!");
750 assert_eq!(opened.at_ms, 1_686_840_217_417);
751 assert_eq!(opened.seal_form, SealForm::Encrypted);
752 check_channel_binding(&opened.rumor, &chan(), Epoch(0)).unwrap();
753 }
754
755 #[tokio::test]
756 async fn signer_seal_opens_identically_to_local_seal() {
757 let author = Keys::generate();
761 let g = group();
762 let tags = channel_binding_tags(&chan(), Epoch(0));
763 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "parity", tags, 1_686_840_217_000);
764 let wrap_at = Timestamp::from_secs(1_686_840_217);
765
766 let seal_l = build_seal(&rumor, SealForm::Encrypted, &g, &author).unwrap();
767 let (wrap_l, _) = wrap_seal(&seal_l, &g, KIND_WRAP, wrap_at).unwrap();
768 let (wrap_s, _) = seal_and_wrap_signed(&as_signer(&author), author.public_key(), &rumor, SealForm::Encrypted, &g, KIND_WRAP, wrap_at, &[])
769 .await
770 .unwrap();
771
772 let opened_l = open_wrap(&wrap_l, &g).unwrap();
773 let opened_s = open_wrap(&wrap_s, &g).unwrap();
774 assert_eq!(opened_l.rumor_id, opened_s.rumor_id, "same inner rumor id via either seal path");
775 assert_eq!(opened_s.author, author.public_key(), "signer seal carries the author identity");
776 assert_eq!(opened_l.seal_form, opened_s.seal_form);
777 assert_eq!(opened_s.rumor.content, "parity");
778 }
779
780 #[test]
781 fn plaintext_seal_round_trip_carries_rumor_verbatim() {
782 let author = Keys::generate();
783 let wrap = send(&author, &group(), SealForm::Plaintext, "an edition", 1_686_840_217_000);
784 let opened = open_wrap(&wrap, &group()).unwrap();
785 assert_eq!(opened.seal_form, SealForm::Plaintext);
786 assert_eq!(opened.seal.content, opened.rumor.as_json());
788 }
789
790 #[test]
791 fn wrong_stream_key_cannot_open() {
792 let author = Keys::generate();
793 let wrap = send(&author, &group(), SealForm::Encrypted, "secret", 1_000);
794 let other = channel_group_key(&[8u8; 32], &chan(), Epoch(0));
795 assert!(matches!(open_wrap(&wrap, &other), Err(StreamError::WrongStream)));
797 }
798
799 #[test]
800 fn tampered_wrap_content_fails_the_mac() {
801 let author = Keys::generate();
802 let mut wrap = send(&author, &group(), SealForm::Encrypted, "x", 1_000);
803 let mut json: serde_json::Value = serde_json::from_str(&wrap.as_json()).unwrap();
804 let ct = json["content"].as_str().unwrap().to_string();
805 let mut bytes = ct.into_bytes();
808 bytes[20] = if bytes[20] == b'B' { b'C' } else { b'B' };
809 json["content"] = serde_json::Value::String(String::from_utf8(bytes).unwrap());
810 wrap = Event::from_json(json.to_string()).unwrap();
811 assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::Decrypt(_))));
812 }
813
814 #[test]
815 fn forged_seal_signature_is_rejected() {
816 let author = Keys::generate();
817 let impostor = Keys::generate();
818 let tags = channel_binding_tags(&chan(), Epoch(0));
819 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "hi", tags, 1_000);
820 let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &impostor).unwrap();
823 let mut json: serde_json::Value = serde_json::from_str(&seal.as_json()).unwrap();
824 json["pubkey"] = serde_json::Value::String(author.public_key().to_hex());
825 let forged = Event::from_json(json.to_string());
828 let Ok(forged) = forged else { return }; let (wrap, _) = wrap_seal(&forged, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
830 assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::BadSealSignature)));
831 }
832
833 #[test]
837 fn a_page_checked_together_opens_as_one_at_a_time() {
838 let g = group();
839 let authors: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
840 let mut page: Vec<Event> =
841 (0..12).map(|i| send(&authors[i % 3], &g, SealForm::Encrypted, &format!("message {i}"), 1_000 + i as u64)).collect();
842 let seal_of = |w: &Event| crate::event_json::event(&open_nip44(g.conv_key(), &w.content).unwrap()).unwrap();
843 let (mut swapped, mut edited) = (seal_of(&page[0]), seal_of(&page[1]));
844 swapped.sig = seal_of(&page[2]).sig;
845 edited.content = seal_of(&page[3]).content;
846 for seal in [swapped, edited] {
847 page.push(wrap_seal(&seal, &g, KIND_WRAP, Timestamp::from_secs(1)).unwrap().0);
848 }
849 let open = |w: &Event, own: bool| open_wrap_at(w, &g.pk(), g.conv_key(), own).map(|o| o.rumor_id).map_err(|e| e.to_string());
850
851 forget_verified();
852 let alone: Vec<_> = page.iter().map(|w| open(w, false)).collect();
853 forget_verified();
854 let before = crate::crypto::batch_verify::stats();
855 let batch = check_signatures_together(&page.iter().map(|w| (w, vec![g.conv_key()], false)).collect::<Vec<_>>());
856 assert!(crate::crypto::batch_verify::stats().batches > before.batches, "the page went through a batch");
857 let together: Vec<_> = page.iter().map(|w| open(w, false)).collect();
858 drop(batch);
859 assert_eq!(together, alone);
860 assert_eq!(alone.iter().filter(|r| r.is_ok()).count(), 12);
861 assert!(alone[12..].iter().all(|r| *r == Err(StreamError::BadSealSignature.to_string())));
862 let again: Vec<_> = page.iter().map(|w| open(w, false)).collect();
864 assert_eq!(again, alone);
865
866 let mut forged = page[4].clone();
868 forged.sig = page[5].sig;
869 let restricted = [&page[4], &page[5], &page[6], &forged];
870 forget_verified();
871 let alone: Vec<_> = restricted.iter().map(|w| open(w, true)).collect();
872 forget_verified();
873 let batch = check_signatures_together(&restricted.iter().map(|w| (*w, vec![g.conv_key()], true)).collect::<Vec<_>>());
874 let together: Vec<_> = restricted.iter().map(|w| open(w, true)).collect();
875 drop(batch);
876 assert_eq!(together, alone);
877 assert_eq!(alone[3], Err(StreamError::BadWrapSignature.to_string()));
878 assert!(alone[..3].iter().all(Result::is_ok));
879 }
880
881 #[test]
882 fn rumor_author_must_match_seal_author() {
883 let author = Keys::generate();
884 let other = Keys::generate();
885 let tags = channel_binding_tags(&chan(), Epoch(0));
886 let rumor = build_rumor_ms(kind::MESSAGE, other.public_key(), "spoof", tags, 1_000);
888 let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
889 let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
890 assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::AuthorMismatch)));
891 }
892
893 #[test]
894 fn forged_rumor_id_is_rejected() {
895 let author = Keys::generate();
896 let tags = channel_binding_tags(&chan(), Epoch(0));
897 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "real", tags, 1_000);
898 let mut json: serde_json::Value = serde_json::from_str(&rumor.as_json()).unwrap();
899 json["id"] = serde_json::Value::String("00".repeat(32));
900 let forged_json = json.to_string();
901 let seal = EventBuilder::new(Kind::Custom(KIND_SEAL_PLAINTEXT), forged_json)
904 .custom_created_at(rumor.created_at)
905 .finalize(&author)
906 .unwrap();
907 let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP, Timestamp::from_secs(1)).unwrap();
908 assert!(matches!(open_wrap(&wrap, &group()), Err(StreamError::BadRumorId)));
909 }
910
911 #[test]
912 fn ms_is_strict_absent_is_zero_invalid_is_dropped() {
913 let author = Keys::generate();
914 let rumor = build_rumor_secs(kind::MESSAGE, author.public_key(), "x", vec![], 1_000);
916 assert_eq!(resolve_ms_strict(&rumor).unwrap(), 1_000_000);
917 let ok = build_rumor_secs(
919 kind::MESSAGE,
920 author.public_key(),
921 "x",
922 vec![Tag::custom("ms", ["999".to_string()])],
923 1_000,
924 );
925 assert_eq!(resolve_ms_strict(&ok).unwrap(), 1_000_999);
926 for bad in ["1000", "-1", "12.5", "abc", "007", "", "+5", "+0", "+000", "+999"] {
930 let r = build_rumor_secs(
931 kind::MESSAGE,
932 author.public_key(),
933 "x",
934 vec![Tag::custom("ms", [bad.to_string()])],
935 1_000,
936 );
937 assert!(
938 matches!(resolve_ms_strict(&r), Err(StreamError::BadMs)),
939 "ms={bad:?} must be malformed"
940 );
941 }
942 }
943
944 #[test]
945 fn a_valueless_ms_tag_is_malformed_and_a_duplicate_takes_the_first() {
946 let author = Keys::generate();
949 let bare = build_rumor_secs(
950 kind::MESSAGE,
951 author.public_key(),
952 "x",
953 vec![Tag::custom("ms", Vec::<String>::new())],
954 1_000,
955 );
956 assert!(matches!(resolve_ms_strict(&bare), Err(StreamError::BadMs)));
957 let two = build_rumor_secs(
960 kind::MESSAGE,
961 author.public_key(),
962 "x",
963 vec![
964 Tag::custom("ms", Vec::<String>::new()),
965 Tag::custom("ms", ["5".to_string()]),
966 ],
967 1_000,
968 );
969 assert!(matches!(resolve_ms_strict(&two), Err(StreamError::BadMs)));
970 let two_valued = build_rumor_secs(
977 kind::MESSAGE,
978 author.public_key(),
979 "x",
980 vec![
981 Tag::custom("ms", ["1".to_string()]),
982 Tag::custom("ms", ["2".to_string()]),
983 ],
984 1_000,
985 );
986 assert_eq!(resolve_ms_strict(&two_valued).unwrap(), 1_000_001, "the FIRST ms wins");
987 }
988
989 #[test]
990 fn tag_numbers_are_spec_shaped_decimals() {
991 use crate::community::edition::is_tag_decimal;
992 for good in ["4", "0", "1099511627776"] {
994 assert!(is_tag_decimal(good), "{good:?} is decimal form");
995 }
996 for bad in ["04", "007", "00", "+4", "-4", "0x4", "1e2", " 4", "4 ", "", "4.0"] {
997 assert!(!is_tag_decimal(bad), "{bad:?} is NOT decimal form");
998 }
999 }
1000
1001 #[test]
1002 fn a_citation_version_must_be_plain_digits() {
1003 let eid = "ab".repeat(32);
1008 let hash = "cd".repeat(32);
1009 let cite = |v: &str| {
1010 let tags = nostr_sdk::prelude::Tags::from_list(vec![Tag::custom(
1011 "vac",
1012 [eid.clone(), v.to_string(), hash.clone()],
1013 )]);
1014 crate::community::edition::AuthorityCitation::from_tags(&tags)
1015 };
1016 assert!(cite("5").is_some(), "a plain decimal is the shape the spec names");
1017 assert!(cite("+5").is_none(), "a leading plus is not decimal form");
1018 assert!(cite("").is_none());
1019 assert!(cite("5x").is_none());
1020 assert!(cite("05").is_none(), "no leading zeros (CORD-01 §5)");
1021 }
1022
1023 #[test]
1024 fn binding_rejects_splices_and_duplicates() {
1025 let author = Keys::generate();
1026 let tags = channel_binding_tags(&chan(), Epoch(0));
1027 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1028 assert!(matches!(
1030 check_channel_binding(&rumor, &ChannelId([0xcd; 32]), Epoch(0)),
1031 Err(StreamError::ChannelMismatch)
1032 ));
1033 assert!(matches!(
1034 check_channel_binding(&rumor, &chan(), Epoch(1)),
1035 Err(StreamError::EpochMismatch)
1036 ));
1037 let mut tags = channel_binding_tags(&chan(), Epoch(0));
1039 tags.extend(channel_binding_tags(&chan(), Epoch(0)));
1040 let dup = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1041 assert!(matches!(
1042 check_channel_binding(&dup, &chan(), Epoch(0)),
1043 Err(StreamError::DuplicateTag(_))
1044 ));
1045 let bare = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", vec![], 1_000);
1047 assert!(matches!(
1048 check_channel_binding(&bare, &chan(), Epoch(0)),
1049 Err(StreamError::MissingTag(_))
1050 ));
1051 }
1052
1053 #[test]
1054 fn oversize_plaintext_is_refused_at_build_time() {
1055 let author = Keys::generate();
1056 let big = "x".repeat(NIP44_MAX_PLAINTEXT + 1);
1057 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), &big, vec![], 1_000);
1058 assert!(matches!(
1059 seal_content(&rumor, SealForm::Encrypted, &group()),
1060 Err(StreamError::Oversize(_))
1061 ));
1062 }
1063
1064 #[test]
1065 fn ephemeral_wrap_round_trips_and_bad_wrap_kind_rejects() {
1066 let author = Keys::generate();
1067 let tags = channel_binding_tags(&chan(), Epoch(0));
1068 let rumor = build_rumor_ms(kind::TYPING, author.public_key(), "", tags, 5_000);
1069 let seal = build_seal(&rumor, SealForm::Encrypted, &group(), &author).unwrap();
1070 let (wrap, _) = wrap_seal(&seal, &group(), KIND_WRAP_EPHEMERAL, Timestamp::from_secs(5)).unwrap();
1071 assert_eq!(wrap.kind.as_u16(), KIND_WRAP_EPHEMERAL);
1072 assert_eq!(open_wrap(&wrap, &group()).unwrap().rumor.kind.as_u16(), kind::TYPING);
1073 assert!(matches!(
1074 wrap_seal(&seal, &group(), 1058, Timestamp::from_secs(5)),
1075 Err(StreamError::BadWrapKind(1058))
1076 ));
1077 }
1078
1079 #[test]
1080 fn rewrap_preserves_rumor_id_and_signature_across_epochs() {
1081 let author = Keys::generate();
1082 let wrap = send(&author, &group(), SealForm::Plaintext, "the head edition", 9_000);
1083 let opened = open_wrap(&wrap, &group()).unwrap();
1084
1085 let next = channel_group_key(&[7u8; 32], &chan(), Epoch(1));
1087 let (rewrapped, _) = rewrap_seal(&opened.seal, &next, Timestamp::from_secs(2_000)).unwrap();
1088 let reopened = open_wrap(&rewrapped, &next).unwrap();
1089
1090 assert_eq!(reopened.rumor_id, opened.rumor_id, "rumor id survives the re-wrap");
1091 assert_eq!(reopened.author, author.public_key(), "authorship survives");
1092 assert_eq!(reopened.seal.sig, opened.seal.sig, "the original signature rides verbatim");
1093 assert_ne!(reopened.wrapper_id, opened.wrapper_id, "outer identity differs per wrap");
1094
1095 let enc = send(&author, &group(), SealForm::Encrypted, "no", 9_000);
1097 let enc_opened = open_wrap(&enc, &group()).unwrap();
1098 assert!(matches!(
1099 rewrap_seal(&enc_opened.seal, &next, Timestamp::from_secs(2_000)),
1100 Err(StreamError::NotRewrappable)
1101 ));
1102 }
1103
1104 #[test]
1105 fn wrap_p_tag_is_ephemeral_not_the_stream_or_author() {
1106 let author = Keys::generate();
1107 let g = group();
1108 let tags = channel_binding_tags(&chan(), Epoch(0));
1109 let rumor = build_rumor_ms(kind::MESSAGE, author.public_key(), "x", tags, 1_000);
1110 let seal = build_seal(&rumor, SealForm::Encrypted, &g, &author).unwrap();
1111 let (wrap, ephemeral) = wrap_seal(&seal, &g, KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1112 let p = wrap
1113 .tags
1114 .iter()
1115 .find_map(|t| {
1116 let s = t.as_slice();
1117 (s.len() >= 2 && s[0] == "p").then(|| s[1].clone())
1118 })
1119 .expect("wrap carries a p tag");
1120 assert_eq!(p, ephemeral.public_key().to_hex());
1121 assert_ne!(p, g.pk_hex());
1122 assert_ne!(p, author.public_key().to_hex());
1123 }
1124}