nostro2-nips 0.4.1

NIP implementations (NIP-04, NIP-44, NIP-104, …) for the nostro2 Nostr toolset.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
//! NIP-104 — Group transport: distributions, outer events, and a manager.
//!
//! Builds on [`crate::nip_104_sender_key::SenderKeyState`] (the symmetric
//! chain) to give the hybrid group model from `mmalmi/nostr-double-ratchet`:
//!
//! 1. A sending device mints a per-group sender-key chain and an associated
//!    **sender-event keypair** (the pubkey that signs its one-to-many events).
//! 2. The chain seed travels to each member as a [`SenderKeyDistribution`],
//!    carried inside the authenticated 1:1 ratchet sessions (so only members
//!    learn it).
//! 3. Group messages are published **once** as a [`GroupSenderKeyMessage`]
//!    outer event, encrypted with the next key off the chain.
//! 4. Members decrypt with the chain state learned from the distribution.
//!
//! [`GroupManager`] is the pure, in-memory state machine tying these together:
//! it owns our sending chain per group, tracks received chains keyed by sender,
//! and is side-effect free — methods return the wire objects to publish or the
//! plaintext decrypted, leaving transport to the caller (exactly like
//! [`crate::nip_104::SessionManager`]).

use std::collections::BTreeMap;

use base64::engine::{Engine as _, general_purpose};
use nostro2_traits::NostrKeypair;
use nostro2_traits::hex::Hexable;
use zeroize::Zeroize;

use super::{MESSAGE_EVENT_KIND, Nip104Crypto, Nip104Error, SenderKeyState};

type Result<T> = std::result::Result<T, Nip104Error>;

/// Outer Nostr event kind for group messages.
///
/// Same kind as 1:1 ratchet messages (the reference's `MESSAGE_EVENT_KIND` =
/// 1060); members tell the two apart by whether the event `pubkey` maps to a
/// sender-key chain.
pub const GROUP_MESSAGE_KIND: u32 = MESSAGE_EVENT_KIND;

/// Inner-rumor kind for a sender-key distribution, delivered pairwise over
/// each member's 1:1 Double Ratchet session (reference
/// `GROUP_SENDER_KEY_DISTRIBUTION_KIND`).
pub const GROUP_SENDER_KEY_DISTRIBUTION_KIND: u32 = 10446;

/// Inner-rumor kind for a group chat message (reference `CHAT_MESSAGE_KIND`,
/// the NIP-17 private-DM kind). The plaintext inside an outer group event is a
/// JSON rumor of this kind.
pub const GROUP_CHAT_MESSAGE_KIND: u32 = 14;

/// Seed for one sender-key chain, distributed to members over their 1:1
/// sessions.
///
/// JSON field names are **camelCase** to match the reference
/// `SenderKeyDistribution` byte-for-byte on the wire; `chain_key` is
/// 64-char hex.
#[derive(Debug, Clone, PartialEq, Eq, json_bourne::FromJson, json_bourne::ToJson)]
pub struct SenderKeyDistribution {
    #[bourne(rename = "groupId")]
    pub group_id: String,
    #[bourne(rename = "keyId")]
    pub key_id: u32,
    #[bourne(rename = "senderEventPubkey")]
    pub sender_event_pubkey: String,
    #[bourne(rename = "chainKey")]
    pub chain_key: String,
    pub iteration: u32,
    #[bourne(rename = "createdAt")]
    pub created_at: i64,
}

/// A published one-to-many group message. The `sender_event_pubkey`
/// locates the receiving chain; `key_id` + `message_number` index it.
/// `ciphertext` is the base64 NIP-44 v2 payload from the chain.
#[derive(Debug, Clone, PartialEq, Eq, json_bourne::FromJson, json_bourne::ToJson)]
pub struct GroupSenderKeyMessage {
    pub group_id: String,
    pub sender_event_pubkey: String,
    pub key_id: u32,
    pub message_number: u32,
    pub created_at: i64,
    pub ciphertext: String,
}

/// Our own sending side for one group: the chain plus the sender-event keypair
/// it is published/signed under.
#[derive(Debug, Clone)]
struct SendingChain {
    sender_event_pubkey: String,
    sender_event_secret: [u8; 32],
    state: SenderKeyState,
}

/// Scrub the raw sender-event secret on drop. `state` (a [`SenderKeyState`])
/// scrubs itself via its own `Drop` impl.
impl Drop for SendingChain {
    fn drop(&mut self) {
        self.sender_event_secret.zeroize();
    }
}

/// All state for a single group.
#[derive(Debug, Clone, Default)]
struct GroupRecord {
    /// Our sending chain, once minted.
    sending: Option<SendingChain>,
    /// Received chains, keyed by their `sender_event_pubkey`.
    receiving: BTreeMap<String, SenderKeyState>,
}

/// A persistence snapshot of our sending side for one group.
///
/// Holds the sender-event keypair (pubkey + raw secret) plus the chain
/// [`SenderKeyState`]. Serialize the state via its getters
/// ([`SenderKeyState::key_id`], [`SenderKeyState::chain_key_hex`],
/// [`SenderKeyState::iteration`], [`SenderKeyState::skipped_keys`]) and
/// revive it with [`SenderKeyState::from_parts`].
#[derive(Debug, Clone)]
pub struct SendingChainSnapshot {
    /// The per-group sender-event pubkey our outer events are signed under.
    pub sender_event_pubkey: String,
    /// The raw 32-byte sender-event secret key.
    pub sender_event_secret: [u8; 32],
    /// The current sending chain state.
    pub state: SenderKeyState,
}

/// Scrub the raw sender-event secret on drop. `state` scrubs itself.
impl Drop for SendingChainSnapshot {
    fn drop(&mut self) {
        self.sender_event_secret.zeroize();
    }
}

/// A full persistence snapshot of one group's transport state: our sending
/// chain (if minted) and every receiving chain keyed by its sender-event
/// pubkey. The inverse of [`GroupManager::restore_group`].
#[derive(Debug, Clone)]
pub struct GroupSnapshot {
    /// The group id.
    pub group_id: String,
    /// Our sending chain, if we have minted one.
    pub sending: Option<SendingChainSnapshot>,
    /// Receiving chains: `(sender_event_pubkey, state)`.
    pub receiving: Vec<(String, SenderKeyState)>,
}

/// A group message decrypted by [`GroupManager::decrypt`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupReceivedMessage {
    /// The group it belongs to.
    pub group_id: String,
    /// The sender-event pubkey that produced it.
    pub sender_event_pubkey: String,
    /// The recovered plaintext.
    pub plaintext: Vec<u8>,
}

/// Pure, in-memory group transport state machine.
///
/// Generic over the in-process keypair `K`, matching [`SenderKeyState`] and
/// [`crate::nip_104::SessionManager`].
#[derive(Debug, Clone)]
pub struct GroupManager<K: NostrKeypair> {
    our_pubkey: String,
    groups: BTreeMap<String, GroupRecord>,
    /// Reverse index: a sender-event pubkey → the `group_id` its chain belongs
    /// to. Lets us route a bare outer event (which carries no `group_id`) to
    /// the right chain by its author pubkey alone.
    sender_to_group: BTreeMap<String, String>,
    _marker: std::marker::PhantomData<fn() -> K>,
}

impl<K: NostrKeypair> GroupManager<K> {
    /// Create a manager owned by `our_pubkey` (our owner/device identity hex).
    #[must_use]
    pub fn new(our_pubkey: impl Into<String>) -> Self {
        Self {
            our_pubkey: our_pubkey.into(),
            groups: BTreeMap::new(),
            sender_to_group: BTreeMap::new(),
            _marker: std::marker::PhantomData,
        }
    }

    /// Our identity pubkey.
    #[must_use]
    pub fn our_pubkey(&self) -> &str {
        &self.our_pubkey
    }

    /// Whether we hold a sending chain for `group_id`.
    #[must_use]
    pub fn has_sending_chain(&self, group_id: &str) -> bool {
        self.groups
            .get(group_id)
            .is_some_and(|g| g.sending.is_some())
    }

    /// The sender-event pubkeys whose chains we can currently decrypt for
    /// `group_id`, sorted.
    #[must_use]
    pub fn known_senders(&self, group_id: &str) -> Vec<String> {
        self.groups
            .get(group_id)
            .map(|g| g.receiving.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// **Mint** our sending chain for `group_id`. Generates a fresh sender-event
    /// keypair and a random chain key, then returns the
    /// [`SenderKeyDistribution`] to hand to every member over their 1:1
    /// session. Replaces any prior sending chain (a key rotation).
    ///
    /// # Errors
    /// Propagates key/derivation failures.
    pub fn rotate_sending_chain(
        &mut self,
        group_id: &str,
        key_id: u32,
        created_at: i64,
    ) -> Result<SenderKeyDistribution> {
        let sender_event = K::generate();
        let sender_event_pubkey = sender_event.public_key();
        let sender_event_secret = sender_event.secret_bytes();
        let chain_key = K::generate().secret_bytes();
        let state = SenderKeyState::new(key_id, &chain_key, 0);

        let dist = SenderKeyDistribution {
            group_id: group_id.to_owned(),
            key_id,
            sender_event_pubkey: sender_event_pubkey.clone(),
            chain_key: chain_key.to_hex(),
            iteration: 0,
            created_at,
        };

        self.sender_to_group
            .insert(sender_event_pubkey.clone(), group_id.to_owned());
        self.groups.entry(group_id.to_owned()).or_default().sending = Some(SendingChain {
            sender_event_pubkey,
            sender_event_secret,
            state,
        });
        Ok(dist)
    }

    /// Re-derive the current [`SenderKeyDistribution`] for our sending chain —
    /// e.g. to hand the chain to a member who joined after we minted it. Note
    /// the `iteration` reflects the chain's *current* position, so a late
    /// joiner only decrypts messages from here forward.
    ///
    /// # Errors
    /// [`Nip104Error::SessionNotReady`] if we have no sending chain yet.
    pub fn current_distribution(
        &self,
        group_id: &str,
        created_at: i64,
    ) -> Result<SenderKeyDistribution> {
        let send = self
            .groups
            .get(group_id)
            .and_then(|g| g.sending.as_ref())
            .ok_or(Nip104Error::SessionNotReady)?;
        Ok(SenderKeyDistribution {
            group_id: group_id.to_owned(),
            key_id: send.state.key_id(),
            sender_event_pubkey: send.sender_event_pubkey.clone(),
            chain_key: send.state.chain_key_hex(),
            iteration: send.state.iteration(),
            created_at,
        })
    }

    /// **Install** a [`SenderKeyDistribution`] received from a member — the
    /// receiving chain we use to decrypt that sender's group messages. A newer
    /// distribution for the same sender (same `sender_event_pubkey`) replaces
    /// the old chain (handles rotation).
    ///
    /// # Errors
    /// [`Nip104Error`] if the chain key is malformed hex.
    pub fn apply_distribution(&mut self, dist: &SenderKeyDistribution) -> Result<()> {
        let chain_key = K::decode_hex_32(&dist.chain_key)?;
        let state = SenderKeyState::new(dist.key_id, &chain_key, dist.iteration);
        self.sender_to_group
            .insert(dist.sender_event_pubkey.clone(), dist.group_id.clone());
        self.groups
            .entry(dist.group_id.clone())
            .or_default()
            .receiving
            .insert(dist.sender_event_pubkey.clone(), state);
        Ok(())
    }

    /// Frame a distribution as the unsigned kind-10446 session rumor to hand to
    /// the `SessionManager` for every member; its serialized JSON becomes the
    /// inner ratchet plaintext. Tags match the reference: l/key/ms; pubkey is
    /// our device identity; id is the rumor hash.
    ///
    /// # Errors
    /// JSON serialization failure of the distribution payload.
    pub fn distribution_to_rumor(
        &self,
        dist: &SenderKeyDistribution,
        created_at: i64,
        now_ms: i64,
    ) -> Result<nostro2::NostrNote> {
        let mut tags = nostro2::NostrTags::new();
        tags.add_custom_tag("l", &dist.group_id);
        tags.add_custom_tag("key", &dist.key_id.to_string());
        tags.add_custom_tag("ms", &now_ms.to_string());
        let mut rumor = nostro2::NostrNote {
            pubkey: self.our_pubkey.clone(),
            kind: GROUP_SENDER_KEY_DISTRIBUTION_KIND,
            content: json_bourne::to_string(dist)?,
            created_at,
            tags,
            ..Default::default()
        };
        rumor
            .serialize_id()
            .map_err(|e| Nip104Error::Json(e.to_string()))?;
        Ok(rumor)
    }

    /// Consume an inbound session rumor. If it is a kind-10446 distribution,
    /// parse and install it, returning the applied distribution. Returns
    /// Ok(None) for any other rumor kind, so it composes with a 1:1 loop.
    ///
    /// # Errors
    /// Malformed payload or bad chain-key hex.
    pub fn apply_distribution_rumor(
        &mut self,
        rumor: &nostro2::NostrNote,
    ) -> Result<Option<SenderKeyDistribution>> {
        if rumor.kind != GROUP_SENDER_KEY_DISTRIBUTION_KIND {
            return Ok(None);
        }
        let dist: SenderKeyDistribution = json_bourne::parse_str(&rumor.content)?;
        self.apply_distribution(&dist)?;
        Ok(Some(dist))
    }

    /// **Encrypt** `plaintext` as the next message on our sending chain for
    /// `group_id`, returning the [`GroupSenderKeyMessage`] to publish once.
    ///
    /// # Errors
    /// [`Nip104Error::SessionNotReady`] if we have no sending chain; plus
    /// cipher failures.
    pub fn encrypt(
        &mut self,
        group_id: &str,
        plaintext: &[u8],
        created_at: i64,
    ) -> Result<GroupSenderKeyMessage> {
        let send = self
            .groups
            .get_mut(group_id)
            .and_then(|g| g.sending.as_mut())
            .ok_or(Nip104Error::SessionNotReady)?;
        let key_id = send.state.key_id();
        let (message_number, ciphertext) = send.state.encrypt::<K>(plaintext)?;
        Ok(GroupSenderKeyMessage {
            group_id: group_id.to_owned(),
            sender_event_pubkey: send.sender_event_pubkey.clone(),
            key_id,
            message_number,
            created_at,
            ciphertext,
        })
    }

    /// **Decrypt** an inbound [`GroupSenderKeyMessage`], routing it to the
    /// receiving chain for its `sender_event_pubkey`.
    ///
    /// # Errors
    /// [`Nip104Error::SessionNotReady`] if we hold no chain for that sender
    /// (we are missing their distribution); plus key-id/ordering/cipher
    /// failures from the chain.
    pub fn decrypt(&mut self, msg: &GroupSenderKeyMessage) -> Result<GroupReceivedMessage> {
        let chain = self
            .groups
            .get_mut(&msg.group_id)
            .and_then(|g| g.receiving.get_mut(&msg.sender_event_pubkey))
            .ok_or(Nip104Error::SessionNotReady)?;
        let plan = chain.plan_decrypt::<K>(msg.key_id, msg.message_number, &msg.ciphertext)?;
        let plaintext = chain.apply_decrypt(plan);
        Ok(GroupReceivedMessage {
            group_id: msg.group_id.clone(),
            sender_event_pubkey: msg.sender_event_pubkey.clone(),
            plaintext,
        })
    }

    /// **Encrypt and build the publishable outer event** for `group_id`. The
    /// returned [`nostro2::NostrNote`] is a signed kind-[`GROUP_MESSAGE_KIND`]
    /// event authored by our per-group sender-event key, with
    /// `content = base64(key_id_be32 || message_number_be32 || nip44_bytes)`
    /// and empty tags — byte-compatible with the reference `OneToManyChannel`.
    /// Publish it **once**; every member decrypts it.
    ///
    /// # Errors
    /// [`Nip104Error::SessionNotReady`] if we have no sending chain; plus
    /// cipher/signing failures.
    pub fn encrypt_to_event(
        &mut self,
        group_id: &str,
        plaintext: &[u8],
        created_at: i64,
    ) -> Result<nostro2::NostrNote> {
        let send = self
            .groups
            .get_mut(group_id)
            .and_then(|g| g.sending.as_mut())
            .ok_or(Nip104Error::SessionNotReady)?;
        let key_id = send.state.key_id();
        let (message_number, ciphertext_b64) = send.state.encrypt::<K>(plaintext)?;
        let content = Self::encode_outer_content(key_id, message_number, &ciphertext_b64)?;

        let signer =
            K::from_secret_bytes(&send.sender_event_secret).map_err(Nip104Error::Signer)?;
        let mut note = nostro2::NostrNote {
            kind: GROUP_MESSAGE_KIND,
            content,
            created_at,
            tags: nostro2::NostrTags::new(),
            ..Default::default()
        };
        note.sign_with(&signer)
            .map_err(|_| Nip104Error::Signer(nostro2_traits::SignerError::InvalidSignature))?;
        Ok(note)
    }

    /// **Decrypt an inbound outer event.** Verifies the event, routes by its
    /// `pubkey` (the sender-event key) to the matching receiving chain, parses
    /// the compact payload, and decrypts. Returns `Ok(None)` if the author is
    /// not a sender-key chain we know (e.g. a 1:1 message, or a member whose
    /// distribution we have not yet received).
    ///
    /// # Errors
    /// [`Nip104Error`] on a bad signature, malformed payload, or chain
    /// decrypt failure.
    pub fn decrypt_event(
        &mut self,
        event: &nostro2::NostrNote,
    ) -> Result<Option<GroupReceivedMessage>> {
        use nostro2::NostrEvent as _;
        if event.kind != GROUP_MESSAGE_KIND {
            return Ok(None);
        }
        // Route by author: do we hold a receiving chain for this sender?
        let Some(group_id) = self.sender_to_group.get(&event.pubkey).cloned() else {
            return Ok(None);
        };
        let known = self
            .groups
            .get(&group_id)
            .is_some_and(|g| g.receiving.contains_key(&event.pubkey));
        if !known {
            return Ok(None);
        }
        if !event.verify() {
            return Err(Nip104Error::InvalidHeader);
        }
        let (key_id, message_number, ciphertext_b64) = Self::decode_outer_content(&event.content)?;
        let msg = GroupSenderKeyMessage {
            group_id,
            sender_event_pubkey: event.pubkey.clone(),
            key_id,
            message_number,
            created_at: event.created_at,
            ciphertext: ciphertext_b64,
        };
        Ok(Some(self.decrypt(&msg)?))
    }

    /// Snapshot every group's transport state for persistence — the inverse of
    /// [`Self::restore_group`]. Returns one [`GroupSnapshot`] per group in
    /// sorted `group_id` order, each carrying our sending chain (if any) and
    /// all receiving chains. Combined with `our_pubkey()`, this is everything
    /// needed to revive the manager across a restart.
    #[must_use]
    pub fn snapshot(&self) -> Vec<GroupSnapshot> {
        self.groups
            .iter()
            .map(|(group_id, record)| GroupSnapshot {
                group_id: group_id.clone(),
                sending: record.sending.as_ref().map(|s| SendingChainSnapshot {
                    sender_event_pubkey: s.sender_event_pubkey.clone(),
                    sender_event_secret: s.sender_event_secret,
                    state: s.state.clone(),
                }),
                receiving: record
                    .receiving
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
            })
            .collect()
    }

    /// Restore one group's transport state from a [`GroupSnapshot`], replacing
    /// any existing record for that group and rebuilding the sender-routing
    /// index for both the sending and receiving chains. The inverse of
    /// [`Self::snapshot`].
    pub fn restore_group(&mut self, snap: GroupSnapshot) {
        let mut record = GroupRecord::default();
        // Borrow rather than move: `SendingChainSnapshot` scrubs its secret on
        // `Drop`, which forbids destructuring it by value.
        if let Some(s) = snap.sending.as_ref() {
            self.sender_to_group
                .insert(s.sender_event_pubkey.clone(), snap.group_id.clone());
            record.sending = Some(SendingChain {
                sender_event_pubkey: s.sender_event_pubkey.clone(),
                sender_event_secret: s.sender_event_secret,
                state: s.state.clone(),
            });
        }
        for (sender_event_pubkey, state) in snap.receiving {
            self.sender_to_group
                .insert(sender_event_pubkey.clone(), snap.group_id.clone());
            record.receiving.insert(sender_event_pubkey, state);
        }
        self.groups.insert(snap.group_id, record);
    }

    /// Build the reference's compact outer payload:
    /// `base64(key_id_be32 || message_number_be32 || raw_nip44_bytes)`.
    ///
    /// Our [`SenderKeyState`] ciphertext is the **base64** NIP-44 payload; we
    /// decode it back to the raw bytes the reference frames.
    fn encode_outer_content(
        key_id: u32,
        message_number: u32,
        ciphertext_b64: &str,
    ) -> Result<String> {
        let nip44_bytes = general_purpose::STANDARD
            .decode(ciphertext_b64)
            .map_err(|_| Nip104Error::InvalidHeader)?;
        let mut payload = Vec::with_capacity(8 + nip44_bytes.len());
        payload.extend_from_slice(&key_id.to_be_bytes());
        payload.extend_from_slice(&message_number.to_be_bytes());
        payload.extend_from_slice(&nip44_bytes);
        Ok(general_purpose::STANDARD.encode(&payload))
    }

    /// Inverse of [`encode_outer_content`](Self::encode_outer_content),
    /// returning `(key_id, message_number, base64 nip44 ciphertext)` ready for
    /// the chain.
    fn decode_outer_content(content: &str) -> Result<(u32, u32, String)> {
        let bytes = general_purpose::STANDARD
            .decode(content)
            .map_err(|_| Nip104Error::InvalidHeader)?;
        if bytes.len() < 8 {
            return Err(Nip104Error::InvalidHeader);
        }
        let key_id = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let message_number = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        let ciphertext_b64 = general_purpose::STANDARD.encode(&bytes[8..]);
        Ok((key_id, message_number, ciphertext_b64))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    type K = crate::tests::NipTester;

    fn mgr(id: &str) -> GroupManager<K> {
        GroupManager::<K>::new(id.to_owned())
    }

    #[test]
    fn one_to_many_two_members() {
        // Alice mints a chain and distributes it to Bob and Carol.
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let mut carol = mgr("carol");

        let dist = alice.rotate_sending_chain("g1", 1, 1000).unwrap();
        bob.apply_distribution(&dist).unwrap();
        carol.apply_distribution(&dist).unwrap();

        // One published message decrypts for every member.
        let msg = alice.encrypt("g1", b"gm everyone", 1001).unwrap();
        assert_eq!(bob.decrypt(&msg).unwrap().plaintext, b"gm everyone");
        assert_eq!(carol.decrypt(&msg).unwrap().plaintext, b"gm everyone");
    }

    /// Snapshot a `GroupManager` mid-conversation, rebuild a fresh one purely
    /// from the snapshot, and confirm both sending and receiving chains resume
    /// exactly where they left off (no key reuse, no decrypt gaps).
    #[test]
    fn snapshot_round_trip_resumes_both_directions() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");

        // Alice mints, Bob installs; exchange one message each way.
        let dist = alice.rotate_sending_chain("g1", 1, 1000).unwrap();
        bob.apply_distribution(&dist).unwrap();
        let m1 = alice.encrypt("g1", b"first", 1001).unwrap();
        assert_eq!(bob.decrypt(&m1).unwrap().plaintext, b"first");

        // Snapshot Alice's sending side and Bob's receiving side mid-stream.
        let alice_snaps = alice.snapshot();
        let bob_snaps = bob.snapshot();

        // Revive both from scratch.
        let mut alice2 = GroupManager::<K>::new(alice.our_pubkey().to_owned());
        for s in alice_snaps {
            alice2.restore_group(s);
        }
        let mut bob2 = GroupManager::<K>::new(bob.our_pubkey().to_owned());
        for s in bob_snaps {
            bob2.restore_group(s);
        }

        // The restored sender continues the chain (iteration advanced past m1);
        // the restored receiver decrypts it with no gap.
        let m2 = alice2.encrypt("g1", b"after restore", 1002).unwrap();
        assert_eq!(bob2.decrypt(&m2).unwrap().plaintext, b"after restore");

        // And routing-by-author survives: bob2 knows the sender chain.
        assert!(bob2.known_senders("g1").contains(&dist.sender_event_pubkey));
    }

    /// A receiving chain with banked skipped keys (out-of-order delivery) must
    /// survive a snapshot — the gap remains decryptable after restore.
    #[test]
    fn snapshot_preserves_skipped_keys() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist = alice.rotate_sending_chain("g1", 7, 2000).unwrap();
        bob.apply_distribution(&dist).unwrap();

        // Alice produces three messages; Bob receives #2 first (banking the
        // key for #0 and #1 as skipped).
        let a0 = alice.encrypt("g1", b"msg0", 2001).unwrap();
        let a1 = alice.encrypt("g1", b"msg1", 2002).unwrap();
        let a2 = alice.encrypt("g1", b"msg2", 2003).unwrap();
        assert_eq!(bob.decrypt(&a2).unwrap().plaintext, b"msg2");

        // Snapshot Bob now, while #0 and #1 are banked skipped keys.
        let bob_snaps = bob.snapshot();
        let mut bob2 = GroupManager::<K>::new(bob.our_pubkey().to_owned());
        for s in bob_snaps {
            bob2.restore_group(s);
        }

        // The restored receiver still decrypts the earlier, out-of-order msgs.
        assert_eq!(bob2.decrypt(&a0).unwrap().plaintext, b"msg0");
        assert_eq!(bob2.decrypt(&a1).unwrap().plaintext, b"msg1");
    }

    #[test]
    fn sequential_messages_advance_all() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist).unwrap();

        for i in 0..5 {
            let m = alice.encrypt("g", format!("m{i}").as_bytes(), i).unwrap();
            assert_eq!(
                bob.decrypt(&m).unwrap().plaintext,
                format!("m{i}").as_bytes()
            );
        }
    }

    #[test]
    fn late_joiner_gets_current_distribution() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let mut dave = mgr("dave");

        let dist0 = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist0).unwrap();
        let _m0 = alice.encrypt("g", b"before dave", 1).unwrap();

        // Dave joins now: he gets the chain at its current iteration.
        let dist_now = alice.current_distribution("g", 2).unwrap();
        assert_eq!(dist_now.iteration, 1);
        dave.apply_distribution(&dist_now).unwrap();

        // New message: both Bob (iter 1) and Dave (iter 1) decrypt.
        let m1 = alice.encrypt("g", b"after dave", 3).unwrap();
        assert_eq!(bob.decrypt(&m1).unwrap().plaintext, b"after dave");
        assert_eq!(dave.decrypt(&m1).unwrap().plaintext, b"after dave");
    }

    #[test]
    fn two_senders_route_independently() {
        // Alice and Bob each have their own chain; Carol decrypts both.
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let mut carol = mgr("carol");

        let da = alice.rotate_sending_chain("g", 1, 0).unwrap();
        let db = bob.rotate_sending_chain("g", 1, 0).unwrap();
        assert_ne!(da.sender_event_pubkey, db.sender_event_pubkey);
        carol.apply_distribution(&da).unwrap();
        carol.apply_distribution(&db).unwrap();

        let ma = alice.encrypt("g", b"from alice", 1).unwrap();
        let mb = bob.encrypt("g", b"from bob", 1).unwrap();
        assert_eq!(carol.decrypt(&mb).unwrap().plaintext, b"from bob");
        assert_eq!(carol.decrypt(&ma).unwrap().plaintext, b"from alice");
        assert_eq!(carol.known_senders("g").len(), 2);
    }

    #[test]
    fn decrypt_without_distribution_fails() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        alice.rotate_sending_chain("g", 1, 0).unwrap();
        let m = alice.encrypt("g", b"secret", 1).unwrap();
        // Bob never got the distribution.
        assert!(matches!(bob.decrypt(&m), Err(Nip104Error::SessionNotReady)));
    }

    #[test]
    fn rotation_replaces_sending_chain() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let d1 = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&d1).unwrap();
        let _ = alice.encrypt("g", b"old", 1).unwrap();

        // Rotate to a new key id → fresh sender-event pubkey + chain.
        let d2 = alice.rotate_sending_chain("g", 2, 2).unwrap();
        assert_ne!(d1.sender_event_pubkey, d2.sender_event_pubkey);
        bob.apply_distribution(&d2).unwrap();
        let m = alice.encrypt("g", b"new", 3).unwrap();
        assert_eq!(m.key_id, 2);
        assert_eq!(bob.decrypt(&m).unwrap().plaintext, b"new");
    }

    #[test]
    fn distribution_json_roundtrips() {
        let mut alice = mgr("alice");
        let dist = alice.rotate_sending_chain("g", 1, 1234).unwrap();
        let json = json_bourne::to_string(&dist).unwrap();
        let back: SenderKeyDistribution = json_bourne::parse_str(&json).unwrap();
        assert_eq!(dist, back);
    }

    #[test]
    fn message_json_roundtrips() {
        let mut alice = mgr("alice");
        alice.rotate_sending_chain("g", 1, 0).unwrap();
        let msg = alice.encrypt("g", b"hi", 7).unwrap();
        let json = json_bourne::to_string(&msg).unwrap();
        let back: GroupSenderKeyMessage = json_bourne::parse_str(&json).unwrap();
        assert_eq!(msg, back);
    }

    #[test]
    fn distribution_rumor_roundtrips_over_session() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");

        let dist = alice.rotate_sending_chain("g7", 1, 1000).unwrap();
        // Alice frames the kind-10446 rumor she'd send Bob over their 1:1 session.
        let rumor = alice.distribution_to_rumor(&dist, 1000, 1_000_000).unwrap();
        assert_eq!(rumor.kind, GROUP_SENDER_KEY_DISTRIBUTION_KIND);
        assert_eq!(rumor.pubkey, "alice");
        assert!(rumor.id.is_some());
        assert_eq!(rumor.tags.find_tags("l"), vec!["g7".to_owned()]);
        assert_eq!(rumor.tags.find_tags("key"), vec!["1".to_owned()]);
        assert_eq!(rumor.tags.find_tags("ms"), vec!["1000000".to_owned()]);

        // Bob receives that rumor (out of his session) and installs the chain.
        let applied = bob.apply_distribution_rumor(&rumor).unwrap().unwrap();
        assert_eq!(applied, dist);

        // Now the one-to-many outer event decrypts for Bob.
        let ev = alice.encrypt_to_event("g7", b"after distro", 1001).unwrap();
        let got = bob.decrypt_event(&ev).unwrap().unwrap();
        assert_eq!(got.plaintext, b"after distro");
    }

    #[test]
    fn apply_distribution_rumor_ignores_other_kinds() {
        let mut bob = mgr("bob");
        let mut other = nostro2::NostrNote {
            kind: GROUP_CHAT_MESSAGE_KIND,
            content: "hi".to_owned(),
            ..Default::default()
        };
        let _ = other.serialize_id();
        assert!(bob.apply_distribution_rumor(&other).unwrap().is_none());
    }

    #[test]
    fn outer_event_roundtrip_one_to_many() {
        use nostro2::NostrEvent as _;
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let mut carol = mgr("carol");

        let dist = alice.rotate_sending_chain("g1", 1, 1000).unwrap();
        bob.apply_distribution(&dist).unwrap();
        carol.apply_distribution(&dist).unwrap();

        // One signed outer event, published once.
        let ev = alice.encrypt_to_event("g1", b"gm group", 1001).unwrap();
        assert_eq!(ev.kind, GROUP_MESSAGE_KIND);
        assert_eq!(ev.pubkey, dist.sender_event_pubkey);
        assert!(ev.verify());
        assert_eq!(ev.tags.iter().count(), 0);

        // Every member decrypts the same wire event.
        let b = bob.decrypt_event(&ev).unwrap().unwrap();
        let c = carol.decrypt_event(&ev).unwrap().unwrap();
        assert_eq!(b.plaintext, b"gm group");
        assert_eq!(c.plaintext, b"gm group");
        assert_eq!(b.group_id, "g1");
    }

    #[test]
    fn decrypt_event_ignores_unknown_author() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        alice.rotate_sending_chain("g", 1, 0).unwrap();
        // Bob has no distribution → unknown author → Ok(None), not an error.
        let ev = alice.encrypt_to_event("g", b"secret", 1).unwrap();
        assert!(bob.decrypt_event(&ev).unwrap().is_none());
    }

    // ── Adversarial / scale ───────────────────────────────────────

    /// One mint, fan out to a large membership: a single published event must
    /// decrypt identically for every one of N members.
    #[test]
    fn large_group_fan_out() {
        const MEMBERS: usize = 256;
        let mut alice = mgr("alice");
        let dist = alice.rotate_sending_chain("big", 1, 1000).unwrap();

        let mut members: Vec<GroupManager<K>> = (0..MEMBERS)
            .map(|i| {
                let mut m = mgr(&format!("member-{i}"));
                m.apply_distribution(&dist).unwrap();
                m
            })
            .collect();

        // Publish ONCE.
        let ev = alice
            .encrypt_to_event("big", b"hello everyone", 1001)
            .unwrap();
        for (i, m) in members.iter_mut().enumerate() {
            let got = m
                .decrypt_event(&ev)
                .unwrap()
                .unwrap_or_else(|| panic!("member {i} failed to decrypt"));
            assert_eq!(got.plaintext, b"hello everyone");
        }
    }

    /// A busy group: many sequential messages, each decrypting for two members
    /// who advance in lockstep with no skipped-key residue.
    #[test]
    fn high_message_volume_group() {
        const N: i64 = 2_000;
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let mut carol = mgr("carol");
        let dist = alice.rotate_sending_chain("busy", 1, 0).unwrap();
        bob.apply_distribution(&dist).unwrap();
        carol.apply_distribution(&dist).unwrap();

        for i in 0..N {
            let body = format!("event #{i}");
            let ev = alice.encrypt_to_event("busy", body.as_bytes(), i).unwrap();
            assert_eq!(
                bob.decrypt_event(&ev).unwrap().unwrap().plaintext,
                body.as_bytes()
            );
            assert_eq!(
                carol.decrypt_event(&ev).unwrap().unwrap().plaintext,
                body.as_bytes()
            );
        }
    }

    /// A member who joins after thousands of messages, via `current_distribution`,
    /// decrypts from that point forward — and cannot read the backlog (he never
    /// had the earlier chain keys, and the message indices are in his past).
    #[test]
    fn late_joiner_after_heavy_traffic() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist0 = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist0).unwrap();

        let mut backlog = Vec::new();
        for i in 0..1_000 {
            backlog.push(
                alice
                    .encrypt_to_event("g", format!("old-{i}").as_bytes(), i)
                    .unwrap(),
            );
        }

        // Eve joins now at the current iteration.
        let mut eve = mgr("eve");
        let dist_now = alice.current_distribution("g", 2000).unwrap();
        assert_eq!(dist_now.iteration, 1000);
        eve.apply_distribution(&dist_now).unwrap();

        // Forward secrecy for the future: a new message decrypts for Eve.
        let fresh = alice.encrypt_to_event("g", b"after eve", 3000).unwrap();
        assert_eq!(
            eve.decrypt_event(&fresh).unwrap().unwrap().plaintext,
            b"after eve"
        );

        // The backlog is in Eve's past with no stored keys → unrecoverable.
        let old = backlog.last().unwrap();
        assert!(eve.decrypt_event(old).is_err());
    }

    /// A tampered outer event (content mutated after signing) breaks the
    /// Schnorr signature and is rejected — and the receiver chain is left
    /// untouched so the genuine event still decrypts.
    #[test]
    fn tampered_outer_event_rejected_without_advancing() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist).unwrap();

        let ev = alice.encrypt_to_event("g", b"genuine", 1).unwrap();
        let mut forged = ev.clone();
        forged.content.push('A'); // invalidates id + signature

        assert!(matches!(
            bob.decrypt_event(&forged),
            Err(Nip104Error::InvalidHeader)
        ));
        // Untouched chain: the authentic event still decrypts.
        assert_eq!(
            bob.decrypt_event(&ev).unwrap().unwrap().plaintext,
            b"genuine"
        );
    }

    /// An event whose signature is valid but whose content is structurally
    /// malformed (too short to hold the `key_id`/`message_number` prefix) is a
    /// decode error, not a panic.
    #[test]
    fn malformed_outer_content_is_an_error() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist).unwrap();

        // Re-sign a too-short payload under the real sender-event key so the
        // signature passes and we reach the decoder.
        let sender_pk = dist.sender_event_pubkey.clone();
        // Build via the genuine path then swap content + re-sign is not exposed;
        // instead exercise the pure decoder directly for the structural cases.
        assert!(matches!(
            GroupManager::<K>::decode_outer_content(""),
            Err(Nip104Error::InvalidHeader)
        ));
        assert!(matches!(
            GroupManager::<K>::decode_outer_content("!!!not base64!!!"),
            Err(Nip104Error::InvalidHeader)
        ));
        // 4 bytes base64 — present but shorter than the 8-byte header.
        let short = general_purpose::STANDARD.encode([0_u8; 4]);
        assert!(matches!(
            GroupManager::<K>::decode_outer_content(&short),
            Err(Nip104Error::InvalidHeader)
        ));
        let _ = sender_pk;
    }

    /// Replaying a group message a second time is rejected: the chain has moved
    /// past that index and kept no skipped key for it.
    #[test]
    fn replayed_group_message_rejected() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let dist = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&dist).unwrap();

        let ev = alice.encrypt_to_event("g", b"once", 1).unwrap();
        assert_eq!(bob.decrypt_event(&ev).unwrap().unwrap().plaintext, b"once");
        // Second delivery of the identical event: past index, no stored key.
        assert!(bob.decrypt_event(&ev).is_err());
    }

    /// Two groups, one device: a message minted in group A must not be
    /// decryptable as group B even though the same manager holds both chains —
    /// routing is strictly by sender-event pubkey.
    #[test]
    fn cross_group_messages_do_not_leak() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let da = alice.rotate_sending_chain("groupA", 1, 0).unwrap();
        let db = alice.rotate_sending_chain("groupB", 1, 0).unwrap();
        assert_ne!(da.sender_event_pubkey, db.sender_event_pubkey);
        bob.apply_distribution(&da).unwrap();
        bob.apply_distribution(&db).unwrap();

        let ev_a = alice.encrypt_to_event("groupA", b"secret A", 1).unwrap();
        let got = bob.decrypt_event(&ev_a).unwrap().unwrap();
        assert_eq!(got.group_id, "groupA");
        assert_eq!(got.plaintext, b"secret A");
        assert!(
            bob.known_senders("groupA")
                .contains(&da.sender_event_pubkey)
        );
        assert!(
            !bob.known_senders("groupB")
                .contains(&da.sender_event_pubkey)
        );
    }

    /// After a key rotation, a message from the *retired* chain no longer
    /// decrypts if the receiver has replaced it (rotation supersedes the old
    /// sender-event pubkey only when reused; distinct pubkeys coexist). Here we
    /// assert a stale message under the old `key_id` against the new chain fails.
    #[test]
    fn stale_key_id_after_rotation_rejected() {
        let mut alice = mgr("alice");
        let mut bob = mgr("bob");
        let d1 = alice.rotate_sending_chain("g", 1, 0).unwrap();
        bob.apply_distribution(&d1).unwrap();
        let stale = alice.encrypt("g", b"old-key", 1).unwrap();

        // Rotate to key_id 2 and install; the receiving chain for the old
        // sender pubkey is still present, but a message carrying key_id 1 routed
        // to a key_id-2 chain is an InvalidHeader.
        let d2 = alice.rotate_sending_chain("g", 2, 2).unwrap();
        bob.apply_distribution(&d2).unwrap();
        let mut wrong = stale;
        wrong.sender_event_pubkey = d2.sender_event_pubkey.clone();
        assert!(matches!(
            bob.decrypt(&wrong),
            Err(Nip104Error::InvalidHeader)
        ));
    }

    #[test]
    fn outer_content_frames_match_reference_layout() {
        // key_id and message_number are big-endian u32 prefixes.
        let content = GroupManager::<K>::encode_outer_content(0x0102_0304, 0x0506_0708, &{
            // a minimal valid base64 of some bytes
            general_purpose::STANDARD.encode([0xAA_u8; 40])
        })
        .unwrap();
        let raw = general_purpose::STANDARD.decode(&content).unwrap();
        assert_eq!(&raw[..4], &[0x01, 0x02, 0x03, 0x04]);
        assert_eq!(&raw[4..8], &[0x05, 0x06, 0x07, 0x08]);
        assert_eq!(&raw[8..], &[0xAA_u8; 40]);

        let (k, n, ct) = GroupManager::<K>::decode_outer_content(&content).unwrap();
        assert_eq!(k, 0x0102_0304);
        assert_eq!(n, 0x0506_0708);
        assert_eq!(general_purpose::STANDARD.decode(ct).unwrap(), [0xAA_u8; 40]);
    }
}