vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
//! Concord v2 rekeys (CORD-06) — the per-recipient key-delivery atom + the 3303
//! event that carries a rotation.
//!
//! A rotation mints a fresh-random key for the next epoch and delivers it only
//! to the members who STAY, one **per-recipient blob** each. Two choices are
//! security-load-bearing:
//!
//! **D1 — the locator is PUBLIC and authenticates nothing.** A blob is located by
//! `HKDF(rotator_xonly || recipient_xonly, …)` — public inputs (full NIP-46 bunker
//! parity: a bunker computes it without a raw key). A public locator proves
//! NOTHING; it is a lookup index only. Authenticity rests entirely on (a) the crate's **rotator seal + roster authority** —
//! verified by the caller before any blob is trusted — and (b) the blob's
//! **bound plaintext** (scope+epoch checked after decrypt). So [`open_blob`]
//! does NOT gate on the locator: the decrypt itself (only the addressed recipient's key
//! opens a blob wrapped to them) plus the bound-plaintext check are the gate.
//!
//! **D5 — the blob wrap carries base64.** NIP-44/NIP-46 encrypt surfaces are
//! string-typed, and the 72 raw bytes aren't valid UTF-8, so the wrapped
//! plaintext is `base64(scope_id ‖ epoch_be ‖ new_key)` — a string a bunker can
//! `nip44_encrypt`/`nip44_decrypt` to the recipient's identity key with no raw
//! secret. The `wrapped` field is then the standard NIP-44 payload string, so a
//! local-keys wrap and a bunker wrap produce identical wire output.
//!
//! The 3303 event itself is a v2 stream event (kind-1059 wrap, ENCRYPTED seal
//! signed by the rotator's real identity) at the rekey address — reusing
//! [`super::stream`]. Its seal is what tells the recipient WHO rotated, which is
//! both the ECDH counterparty and the authority actor.
//!
//! What lives here: the blob atom, the 3303 build/parse, chunk-set assembly, and
//! the continuity/fork comparators — all PURE. The stateful orchestration
//! (recipient-set computation, the base+channels lockstep read-cut, DB epoch
//! archival, and the D2 BAN-vs-MANAGE_CHANNELS authority gate, which is an
//! apply-path concern keyed on prior-vs-current-root addressing) sits in the
//! service layer.

use nostr_sdk::prelude::nip44::v2::ConversationKey;
use nostr_sdk::prelude::{Event, Keys, PublicKey, SecretKey, Tag, Timestamp, UnsignedEvent};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use super::super::{ChannelId, CommunityId, Epoch};
use super::derive::{
    base_rekey_group_key, channel_rekey_group_key, control_signer_group_key, epoch_key_commitment,
    recipient_locator, GroupKey,
};
use super::stream::{self, OpenedStream, SealForm, StreamError};

/// Max recipients (blobs) in ONE 3303 event when sending (CORD-06 §1): the CORD-01
/// double wrap expands the blob array twice, and 80 blobs measure ~55 KB, under a 64 KB
/// relay event (size-guarded by test). A larger recipient set splits across chunk events.
pub const MAX_REKEY_BLOBS_PER_EVENT: usize = 80;

/// [`MAX_REKEY_BLOBS_PER_EVENT`] for the 104- and 136-byte forms (base rotations, history): 80 of
/// them push the rumor past a NIP-44 padding step that carries through the seal (~77 KB); 60 ~55 KB.
pub const MAX_WIDE_BLOBS_PER_EVENT: usize = 60;

/// How many blobs one event of a rotation at `scope` may carry: a base rotation's are the wide forms.
pub fn blobs_per_event(scope: RekeyScope) -> usize {
    if matches!(scope, RekeyScope::Root) { MAX_WIDE_BLOBS_PER_EVENT } else { MAX_REKEY_BLOBS_PER_EVENT }
}

/// Max blobs Vector will ACCEPT in one received 3303 chunk (a DoS bound checked
/// after decrypt). Kept at the spec's stated 120 — higher than the send cap — so
/// a chunk minted by another client at the spec limit (and delivered by a relay
/// with a larger `maxEventSize`) still parses. An array over this is rejected.
pub const MAX_REKEY_BLOBS_RECEIVED: usize = 120;

/// [`MAX_REKEY_BLOBS_PER_EVENT`] for a writer delivery, whose recipients' certificates ride the
/// same event (size-guarded by test).
pub const MAX_CERTIFIED_BLOBS_PER_EVENT: usize = 48;

const TAG_SCOPE: &str = "scope";
const TAG_NEW_EPOCH: &str = "newepoch";
const TAG_PREV_EPOCH: &str = "prevepoch";
const TAG_PREV_COMMIT: &str = "prevcommit";
const TAG_CHUNK: &str = "chunk";
/// Root-scope containment marker (CORD-06 Severing Refounding): an adopter
/// revokes its own public invite links instead of refreshing them into the new
/// epoch. Grants no authority of its own — it rides a rotation the adopt gate
/// has already verified.
const TAG_SEVER: &str = "sever";
/// Names how a 3303 delivers (CORD-03 §5); an access delivery is never a rotation.
const TAG_DELIVERY: &str = "delivery";
const DELIVERY_ACCESS: &str = "access";
const DELIVERY_HISTORY: &str = "history";

/// What a rekey rotates (CORD-06 §1). The 32-byte scope id is stamped into every
/// blob's plaintext so a blob can't be spliced onto another coordinate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RekeyScope {
    /// A specific private channel being rekeyed.
    Channel(ChannelId),
    /// The community_root (a base rotation / Refounding) — the all-zero sentinel
    /// (a random channel id never collides with it).
    Root,
}

impl RekeyScope {
    /// The 32-byte scope id: the channel id, or the all-zero root sentinel.
    pub fn id32(&self) -> [u8; 32] {
        match self {
            RekeyScope::Channel(c) => c.0,
            RekeyScope::Root => [0u8; 32],
        }
    }

    fn to_hex(self) -> String {
        crate::simd::hex::bytes_to_hex_32(&self.id32())
    }

    fn from_hex(hex: &str) -> Option<RekeyScope> {
        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        let bytes = crate::simd::hex::hex_to_bytes_32(hex);
        Some(if bytes == [0u8; 32] {
            RekeyScope::Root
        } else {
            RekeyScope::Channel(ChannelId(bytes))
        })
    }
}

/// One located, wrapped rekey blob — the unit a 3303 event carries N of.
///
/// `locator` is the public [`recipient_locator`] hex (a lookup index — proves
/// nothing, D1); `wrapped` is the NIP-44 payload string whose plaintext is
/// `base64(scope_id ‖ epoch_be ‖ new_key)` (D5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RekeyBlob {
    pub locator: String,
    pub wrapped: String,
}

/// Errors from the rekey layer.
#[derive(Debug)]
pub enum RekeyError {
    Stream(StreamError),
    Crypto(String),
    /// The wrapped plaintext isn't the expected 72-byte layout.
    BadBlobLength(usize),
    /// A base blob's plaintext isn't one of the three fixed widths (CORD-06 §1):
    /// 72 (legacy pre-split), 104 (member), 136 (staff).
    BadBaseBlobWidth(usize),
    /// A 136-byte base blob's `new_control_root` doesn't derive to its
    /// `new_control_pk` — refused whole rather than adopting a plane split from
    /// its readers (CORD-06 §1).
    ControlPairMismatch,
    /// A Grant's `control_wrap` plaintext isn't the fixed 40 bytes (CORD-04 §3).
    BadControlWrapLength(usize),
    /// The blob's bound scope ≠ the coordinate it's being opened under (splice).
    ScopeSplice,
    /// The blob's bound epoch ≠ the coordinate it's being opened under (splice).
    EpochSplice,
    /// The rumor isn't a kind-3303 rekey.
    NotARekey(u16),
    /// A required tag is absent, duplicated, or malformed.
    BadTag(&'static str),
    /// `new_epoch <= prev_epoch` — a rotation must advance the chain.
    NonMonotonicEpoch,
    /// A chunk index is out of range (`i < 1`, `i > n`, or `n < 1`).
    BadChunkIndex,
    /// The blob array exceeds the cap.
    TooManyBlobs(usize),
}

impl std::fmt::Display for RekeyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RekeyError::Stream(e) => write!(f, "stream: {e}"),
            RekeyError::Crypto(e) => write!(f, "crypto: {e}"),
            RekeyError::BadBlobLength(n) => write!(f, "rekey blob plaintext is {n} bytes, expected 72"),
            RekeyError::BadBaseBlobWidth(n) => write!(f, "base rekey blob plaintext is {n} bytes, expected 72, 104 or 136"),
            RekeyError::ControlPairMismatch => write!(f, "base rekey blob control_root does not derive to its control_pk"),
            RekeyError::BadControlWrapLength(n) => write!(f, "control_wrap plaintext is {n} bytes, expected 40"),
            RekeyError::ScopeSplice => write!(f, "rekey blob scope binding mismatch (splice)"),
            RekeyError::EpochSplice => write!(f, "rekey blob epoch binding mismatch (splice)"),
            RekeyError::NotARekey(k) => write!(f, "rumor kind {k} is not a rekey"),
            RekeyError::BadTag(t) => write!(f, "missing/duplicate/malformed rekey tag: {t}"),
            RekeyError::NonMonotonicEpoch => write!(f, "rekey new_epoch must exceed prev_epoch"),
            RekeyError::BadChunkIndex => write!(f, "rekey chunk index out of range"),
            RekeyError::TooManyBlobs(n) => write!(f, "rekey carries {n} blobs, over the cap"),
        }
    }
}

impl std::error::Error for RekeyError {}

impl From<StreamError> for RekeyError {
    fn from(e: StreamError) -> Self {
        RekeyError::Stream(e)
    }
}

// ── The blob atom ────────────────────────────────────────────────────────────

/// The 72-byte bound plaintext: `scope_id[32] ‖ epoch_be[8] ‖ new_key[32]`.
/// Fixed-width, so no separators are needed to parse it unambiguously.
fn bound_plaintext(scope: RekeyScope, epoch: Epoch, new_key: &[u8; 32]) -> [u8; 72] {
    let mut pt = [0u8; 72];
    pt[..32].copy_from_slice(&scope.id32());
    pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
    pt[40..].copy_from_slice(new_key);
    pt
}

/// The base64 string a blob's NIP-44 layer actually encrypts (D5). Exposed so
/// the service-layer bunker path can `signer.nip44_encrypt(recipient, this)`.
pub fn bound_plaintext_b64(scope: RekeyScope, epoch: Epoch, new_key: &[u8; 32]) -> String {
    crate::simd::base64::STANDARD.encode_to_string(bound_plaintext(scope, epoch, new_key))
}

/// Parse + verify a decrypted bound plaintext (the base64 already stripped),
/// checking scope+epoch strict-equal the coordinate it was opened under before
/// yielding `new_key`. Exposed for the bunker open path.
pub fn parse_bound_plaintext(pt: &[u8], scope: RekeyScope, epoch: Epoch) -> Result<[u8; 32], RekeyError> {
    if pt.len() != 72 {
        return Err(RekeyError::BadBlobLength(pt.len()));
    }
    if pt[..32] != scope.id32() {
        return Err(RekeyError::ScopeSplice);
    }
    let mut epoch_be = [0u8; 8];
    epoch_be.copy_from_slice(&pt[32..40]);
    if u64::from_be_bytes(epoch_be) != epoch.0 {
        return Err(RekeyError::EpochSplice);
    }
    let mut new_key = [0u8; 32];
    new_key.copy_from_slice(&pt[40..72]);
    Ok(new_key)
}

// ── The base-rotation blob forms (CORD-06 §1) ────────────────────────────────
//
// A base rotation's blob widens past the 72-byte channel layout to carry the
// next epoch's Control Plane keys (CORD-02 §2): every member's blob appends
// `new_control_pk[32]` (104 bytes), a staff recipient's additionally
// `new_control_root[32]` (136). The width declares the form; a 72-byte BASE
// blob is the legacy pre-split rotation — honored when reading old epochs,
// never minted by a compliant Rotator. Any other width is malformed.

/// What a base blob delivered (CORD-06 §1); the width declared the form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BaseKeyDelivery {
    pub new_root: [u8; 32],
    /// The next epoch's Control Plane address — absent on a legacy 72-byte
    /// blob, whose acceptor folds that epoch's Control at the legacy
    /// member-derivable address instead (CORD-06 §3).
    pub control_pk: Option<[u8; 32]>,
    /// The staff write secret (136-byte form only), already verified to derive
    /// to `control_pk`.
    pub control_root: Option<[u8; 32]>,
}

fn bound_base_plaintext(epoch: Epoch, new_root: &[u8; 32], control_pk: &[u8; 32], control_root: Option<&[u8; 32]>) -> Vec<u8> {
    let mut pt = Vec::with_capacity(if control_root.is_some() { 136 } else { 104 });
    pt.extend_from_slice(&bound_plaintext(RekeyScope::Root, epoch, new_root));
    pt.extend_from_slice(control_pk);
    if let Some(cr) = control_root {
        pt.extend_from_slice(cr);
    }
    pt
}

/// The base64 string a BASE blob's NIP-44 layer encrypts (D5) — the 104-byte
/// member form, or the 136-byte staff form when `control_root` rides.
pub fn bound_base_plaintext_b64(epoch: Epoch, new_root: &[u8; 32], control_pk: &[u8; 32], control_root: Option<&[u8; 32]>) -> String {
    crate::simd::base64::STANDARD.encode_to_string(bound_base_plaintext(epoch, new_root, control_pk, control_root))
}

/// Parse + verify a decrypted BASE blob plaintext (CORD-06 §1): 72 (legacy
/// pre-split), 104 (member), 136 (staff). The scope must be the all-zero base
/// sentinel and the epoch must match the coordinate (unspliceable), and a
/// 136-byte blob's `new_control_root` must derive to exactly its
/// `new_control_pk` (CORD-02 §5) — a mismatched pair refuses the WHOLE blob
/// rather than adopting a plane split from its readers.
///
/// A width ABOVE 136 is a future form this build predates. Refusing it would
/// re-create the pre-split brick (a member forks off at the rotation until
/// they update), so it degrades per CORD-06 §3's lenient grade instead: the
/// frozen 72-byte prefix yields the root (membership and every Chat plane
/// survive), the family's appended offsets yield the control pair when they
/// still verify (the derive check fails closed on a reordered layout), and
/// whatever the extra bytes govern freezes — a safe prompt to update, never a
/// fork. Widths between the defined forms fit no append-only extension and
/// stay malformed.
pub fn parse_bound_base_plaintext(pt: &[u8], community_id: &CommunityId, epoch: Epoch) -> Result<BaseKeyDelivery, RekeyError> {
    if !matches!(pt.len(), 72 | 104 | 136) && pt.len() < 137 {
        return Err(RekeyError::BadBaseBlobWidth(pt.len()));
    }
    let new_root = parse_bound_plaintext(&pt[..72], RekeyScope::Root, epoch)?;
    if pt.len() == 72 {
        return Ok(BaseKeyDelivery { new_root, control_pk: None, control_root: None });
    }
    let mut control_pk = [0u8; 32];
    control_pk.copy_from_slice(&pt[72..104]);
    if pt.len() == 104 {
        return Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: None });
    }
    let mut control_root = [0u8; 32];
    control_root.copy_from_slice(&pt[104..136]);
    if control_signer_group_key(&control_root, community_id, epoch).pk().to_bytes() != control_pk {
        if pt.len() == 136 {
            return Err(RekeyError::ControlPairMismatch);
        }
        // Future form whose 104..136 bytes are no longer the secret: keep the
        // verified prefix fields, drop the unverifiable ones.
        return Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: None });
    }
    Ok(BaseKeyDelivery { new_root, control_pk: Some(control_pk), control_root: Some(control_root) })
}

/// Build one BASE blob via a [`VectorSigner`](crate::signer::VectorSigner) — the 104-byte member form, or
/// 136 with `control_root` for a staff recipient (CORD-04 §3). Mirrors
/// [`build_blob`]; the locator is the same public Root-scope locator.
pub async fn build_base_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_xonly: &[u8; 32],
    recipient_pk: &PublicKey,
    epoch: Epoch,
    new_root: &[u8; 32],
    control_pk: &[u8; 32],
    control_root: Option<&[u8; 32]>,
) -> Result<RekeyBlob, RekeyError> {
    let inner_b64 = Zeroizing::new(bound_base_plaintext_b64(epoch, new_root, control_pk, control_root));
    let wrapped = signer
        .nip44_encrypt_async(recipient_pk, inner_b64.as_str())
        .await
        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
    Ok(RekeyBlob {
        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), RekeyScope::Root, epoch),
        wrapped,
    })
}

/// Open a BASE blob addressed to me via a [`VectorSigner`](crate::signer::VectorSigner). Mirror of
/// [`open_blob`], but width-tolerant per CORD-06 §1 — the returned delivery
/// says which form arrived.
pub async fn open_base_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_pk: &PublicKey,
    community_id: &CommunityId,
    epoch: Epoch,
    blob: &RekeyBlob,
) -> Result<BaseKeyDelivery, RekeyError> {
    let inner_b64 = Zeroizing::new(
        signer
            .nip44_decrypt_async(rotator_pk, &blob.wrapped)
            .await
            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
    );
    let pt = Zeroizing::new(
        crate::simd::base64::STANDARD
            .decode_to_vec(inner_b64.as_bytes())
            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
    );
    parse_bound_base_plaintext(&pt, community_id, epoch)
}

// ── The Grant's control_wrap plaintext (CORD-04 §3) ──────────────────────────

/// `epoch_be[8] ‖ control_root[32]` — the staff write key as delivered inside a
/// staff-making Grant, NIP-44-encrypted under the granter↔member pairwise key
/// (the rekey-blob discipline: fixed width, the epoch INSIDE the ciphertext).
pub fn encode_control_wrap(epoch: Epoch, control_root: &[u8; 32]) -> [u8; 40] {
    let mut pt = [0u8; 40];
    pt[..8].copy_from_slice(&epoch.0.to_be_bytes());
    pt[8..].copy_from_slice(control_root);
    pt
}

/// The base64 string a control_wrap's NIP-44 layer encrypts (string-typed
/// signer surfaces, the D5 transport discipline).
pub fn control_wrap_b64(epoch: Epoch, control_root: &[u8; 32]) -> String {
    crate::simd::base64::STANDARD.encode_to_string(encode_control_wrap(epoch, control_root))
}

/// Parse a decrypted 40-byte control_wrap plaintext. The caller verifies the
/// secret derives to the `control_pk` it holds for the named epoch — any
/// mismatch is dropped, never adopted (CORD-04 §3).
pub fn parse_control_wrap(pt: &[u8]) -> Result<(Epoch, [u8; 32]), RekeyError> {
    if pt.len() != 40 {
        return Err(RekeyError::BadControlWrapLength(pt.len()));
    }
    let mut epoch_be = [0u8; 8];
    epoch_be.copy_from_slice(&pt[..8]);
    let mut control_root = [0u8; 32];
    control_root.copy_from_slice(&pt[8..]);
    Ok((Epoch(u64::from_be_bytes(epoch_be)), control_root))
}

/// The public per-recipient locator (D1). Both parties compute it from public
/// keys alone; it addresses the blob and nothing more.
pub fn blob_locator(rotator_xonly: &[u8; 32], recipient_xonly: &[u8; 32], scope: RekeyScope, epoch: Epoch) -> String {
    crate::simd::hex::bytes_to_hex_32(&recipient_locator(rotator_xonly, recipient_xonly, &scope.id32(), epoch))
}

/// Build one blob with LOCAL keys (the bunker path drives the same wire via the
/// `_b64` helpers + a NIP-46 `nip44_encrypt`). The wrap is the pairwise
/// conversation key `ConversationKey::derive(rotator_sk, recipient_pk)`, so only
/// the recipient's identity key opens it.
pub fn build_blob_local(
    rotator_sk: &SecretKey,
    rotator_xonly: &[u8; 32],
    recipient_pk: &PublicKey,
    scope: RekeyScope,
    epoch: Epoch,
    new_key: &[u8; 32],
) -> Result<RekeyBlob, RekeyError> {
    let inner_b64 = Zeroizing::new(bound_plaintext_b64(scope, epoch, new_key));
    let ck = ConversationKey::derive(rotator_sk, recipient_pk).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner_b64.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    Ok(RekeyBlob {
        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), scope, epoch),
        wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
    })
}

/// Open a blob addressed to me with LOCAL keys. Per D1 this does NOT check the
/// locator: the decrypt (only my identity key opens a blob wrapped to me by the
/// rotator) plus the bound scope/epoch ARE the authenticity boundary. A blob
/// relocated to a foreign locator still won't decrypt for a non-recipient, and
/// a spliced one fails the bound check.
pub fn open_blob_local(
    my_sk: &SecretKey,
    rotator_pk: &PublicKey,
    scope: RekeyScope,
    epoch: Epoch,
    blob: &RekeyBlob,
) -> Result<[u8; 32], RekeyError> {
    let ck = ConversationKey::derive(my_sk, rotator_pk).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let payload = crate::simd::base64::STANDARD
        .decode_to_vec(blob.wrapped.as_bytes())
        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let inner_b64 = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
    let pt = Zeroizing::new(
        crate::simd::base64::STANDARD
            .decode_to_vec(inner_b64.as_slice())
            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
    );
    parse_bound_plaintext(&pt, scope, epoch)
}

/// Build one blob via a [`VectorSigner`](crate::signer::VectorSigner) (the bunker / NIP-55 path). Wire-identical
/// to [`build_blob_local`]: `signer.nip44_encrypt(recipient, bound_plaintext_b64)`
/// whose conversation key is ECDH(signer_identity, recipient) — the same key the
/// local path derives from the raw rotator secret. The `wrapped` field is the
/// standard NIP-44 payload string (D5), so both paths emit identical wire.
pub async fn build_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_xonly: &[u8; 32],
    recipient_pk: &PublicKey,
    scope: RekeyScope,
    epoch: Epoch,
    new_key: &[u8; 32],
) -> Result<RekeyBlob, RekeyError> {
    let inner_b64 = Zeroizing::new(bound_plaintext_b64(scope, epoch, new_key));
    let wrapped = signer
        .nip44_encrypt_async(recipient_pk, inner_b64.as_str())
        .await
        .map_err(|e| RekeyError::Crypto(e.to_string()))?;
    Ok(RekeyBlob {
        locator: blob_locator(rotator_xonly, &recipient_pk.to_bytes(), scope, epoch),
        wrapped,
    })
}

/// Open a blob addressed to me via a [`VectorSigner`](crate::signer::VectorSigner). Mirror of [`open_blob_local`]:
/// `signer.nip44_decrypt(rotator, blob.wrapped)` yields the base64 bound plaintext,
/// then the scope/epoch bound check gates it. Per D1 the locator is NOT gated.
pub async fn open_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_pk: &PublicKey,
    scope: RekeyScope,
    epoch: Epoch,
    blob: &RekeyBlob,
) -> Result<[u8; 32], RekeyError> {
    let inner_b64 = Zeroizing::new(
        signer
            .nip44_decrypt_async(rotator_pk, &blob.wrapped)
            .await
            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
    );
    let pt = Zeroizing::new(
        crate::simd::base64::STANDARD
            .decode_to_vec(inner_b64.as_bytes())
            .map_err(|e| RekeyError::Crypto(e.to_string()))?,
    );
    parse_bound_plaintext(&pt, scope, epoch)
}

/// Find my blob in a chunk's array by my public locator (the lookup step, D1).
/// `None` means this chunk doesn't carry my key — never a removal on its own
/// (only "removed" once ALL chunks are held and none has it).
pub fn find_my_blob<'a>(
    blobs: &'a [RekeyBlob],
    rotator_xonly: &[u8; 32],
    my_xonly: &[u8; 32],
    scope: RekeyScope,
    epoch: Epoch,
) -> Option<&'a RekeyBlob> {
    find_my_blobs(blobs, rotator_xonly, my_xonly, scope, epoch).next()
}

/// EVERY blob at my locator, in order. A locator is a public lookup index that
/// proves nothing, so anyone can publish a blob at mine; with the union in
/// [`collect_rotations`] more than one can survive to the open. Taking only the
/// first would let a junk blob shadow the real key and park an adopter that in
/// fact holds it — so the caller tries each and adopts on the first that opens.
pub fn find_my_blobs<'a>(
    blobs: &'a [RekeyBlob],
    rotator_xonly: &[u8; 32],
    my_xonly: &[u8; 32],
    scope: RekeyScope,
    epoch: Epoch,
) -> impl Iterator<Item = &'a RekeyBlob> {
    let want = blob_locator(rotator_xonly, my_xonly, scope, epoch);
    blobs.iter().filter(move |b| b.locator == want)
}

// ── The 3303 event (a v2 stream event) ───────────────────────────────────────

/// A parsed, seal-verified 3303 chunk. The `rotator` is the seal's real signer
/// (the ECDH counterparty AND the authority actor the caller gates on).
#[derive(Debug, Clone)]
pub struct RekeyChunk {
    pub rotator: PublicKey,
    pub scope: RekeyScope,
    pub new_epoch: Epoch,
    pub prev_epoch: Epoch,
    pub prev_commit: [u8; 32],
    /// This chunk's `(i, n)` — 1-based, `i <= n`.
    pub chunk: (u32, u32),
    pub blobs: Vec<RekeyBlob>,
    /// The rotator's `vac` (CORD-06 §Authority: "a rotation cites the Grant it
    /// acts under like any authority action"). `None` when the owner rotates.
    pub citation: Option<crate::community::edition::AuthorityCitation>,
    /// Severing containment marker (`TAG_SEVER`, root scope only).
    pub severed: bool,
    /// When the rotator sent it, in ms.
    pub at_ms: u64,
}

/// The key that groups chunks of ONE rotation: `(rotator, scope_id, new_epoch,
/// prev_commit)`. Two rotators racing the same epoch, or one rotator over two
/// channels, never alias.
pub type RotationKey = ([u8; 32], [u8; 32], u64, [u8; 32]);

impl RekeyChunk {
    /// This chunk's [`RotationKey`].
    pub fn correlation(&self) -> RotationKey {
        (self.rotator.to_bytes(), self.scope.id32(), self.new_epoch.0, self.prev_commit)
    }
}

/// Build the unsigned 3303 rumor (rotator is the pubkey; the seal will carry the
/// signature). Enforces the monotonic-epoch and chunk-range invariants at mint.
#[allow(clippy::too_many_arguments)]
pub fn build_rekey_rumor(
    rotator: PublicKey,
    scope: RekeyScope,
    new_epoch: Epoch,
    prev_epoch: Epoch,
    prev_commit: &[u8; 32],
    blobs: &[RekeyBlob],
    chunk_i: u32,
    chunk_n: u32,
    at_secs: u64,
    citation: Option<&crate::community::edition::AuthorityCitation>,
    severed: bool,
) -> Result<UnsignedEvent, RekeyError> {
    if new_epoch.0 <= prev_epoch.0 {
        return Err(RekeyError::NonMonotonicEpoch);
    }
    if chunk_n < 1 || chunk_i < 1 || chunk_i > chunk_n {
        return Err(RekeyError::BadChunkIndex);
    }
    if blobs.len() > blobs_per_event(scope) {
        return Err(RekeyError::TooManyBlobs(blobs.len()));
    }
    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let mut tags = vec![
        Tag::custom(TAG_SCOPE, [scope.to_hex()]),
        Tag::custom(TAG_NEW_EPOCH, [new_epoch.0.to_string()]),
        Tag::custom(TAG_PREV_EPOCH, [prev_epoch.0.to_string()]),
        Tag::custom(TAG_PREV_COMMIT, [crate::simd::hex::bytes_to_hex_32(prev_commit)]),
        Tag::custom(TAG_CHUNK, [chunk_i.to_string(), chunk_n.to_string()]),
    ];
    // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
    // authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
    // never honored by a lagging client." The owner cites nothing.
    if let Some(c) = citation {
        tags.push(c.to_tag());
    }
    if severed {
        tags.push(Tag::custom(TAG_SEVER, ["1"]));
    }
    // Rekeys fold by their tags, not time; still stamp created_at for the wire.
    Ok(stream::build_rumor_secs(super::kind::REKEY, rotator, &content, tags, at_secs))
}

/// The rekey group key for a CHANNEL rekey addressed under `addressing_root`.
/// The caller chooses the root: a STANDALONE channel rekey rides the CURRENT
/// root (`MANAGE_CHANNELS`); a channel rekey forced by a removal rides the PRIOR
/// root alongside the base rekey (D2 — inherits the removal's `BAN` authority,
/// and the prior-root address is exactly what distinguishes the two classes on
/// the wire so a base-fork loser can still open it).
pub fn channel_rekey_group(addressing_root: &[u8; 32], channel_id: &ChannelId, new_epoch: Epoch) -> GroupKey {
    channel_rekey_group_key(addressing_root, channel_id, new_epoch)
}

/// The rekey group key for a BASE rotation — always under the PRIOR root (the
/// one handle every retained member still holds through the rotation).
pub fn base_rekey_group(prior_root: &[u8; 32], community_id: &CommunityId, new_epoch: Epoch) -> GroupKey {
    base_rekey_group_key(prior_root, community_id, new_epoch)
}

/// Seal + wrap a 3303 rumor into its stream event at the rekey address. The seal
/// is ENCRYPTED (20013 — the rekey plane MUST NOT be plaintext-sealed) and
/// signed by the rotator; the wrap by the rekey group key.
pub fn seal_rekey_chunk(
    rumor: &UnsignedEvent,
    rekey_group: &GroupKey,
    rotator_keys: &Keys,
    wrap_at: Timestamp,
) -> Result<(Event, Keys), RekeyError> {
    let seal = stream::build_seal(rumor, SealForm::Encrypted, rekey_group, rotator_keys)?;
    Ok(stream::wrap_seal(&seal, rekey_group, stream::KIND_WRAP, wrap_at)?)
}

/// Split a full recipient blob set into 3303 chunk events ([`blobs_per_event`] each),
/// all sharing the rotation's `(scope, new_epoch, prev_commit)` so a receiver
/// correlates them. Local-keys convenience.
#[allow(clippy::too_many_arguments)]
pub fn build_rekey_chunks_local(
    rotator_keys: &Keys,
    rekey_group: &GroupKey,
    scope: RekeyScope,
    new_epoch: Epoch,
    prev_epoch: Epoch,
    prev_commit: &[u8; 32],
    blobs: &[RekeyBlob],
    at_secs: u64,
    citation: Option<&crate::community::edition::AuthorityCitation>,
    severed: bool,
) -> Result<Vec<Event>, RekeyError> {
    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
        vec![&[]]
    } else {
        blobs.chunks(blobs_per_event(scope)).collect()
    };
    let n = groups.len() as u32;
    let mut out = Vec::with_capacity(groups.len());
    for (idx, group_blobs) in groups.iter().enumerate() {
        let rumor = build_rekey_rumor(
            rotator_keys.public_key(),
            scope,
            new_epoch,
            prev_epoch,
            prev_commit,
            group_blobs,
            idx as u32 + 1,
            n,
            at_secs,
            citation,
            severed,
        )?;
        let (wrap, _) = seal_rekey_chunk(&rumor, rekey_group, rotator_keys, Timestamp::from_secs(at_secs))?;
        out.push(wrap);
    }
    Ok(out)
}

/// Signer-driven twin of [`build_rekey_chunks_local`] for bunker / NIP-55 accounts:
/// each chunk's encrypted seal signs through a [`VectorSigner`](crate::signer::VectorSigner). `rotator_pk` must
/// equal `my_public_key()`. Wire-identical to the local path.
#[allow(clippy::too_many_arguments)]
pub async fn build_rekey_chunks<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_pk: PublicKey,
    rekey_group: &GroupKey,
    scope: RekeyScope,
    new_epoch: Epoch,
    prev_epoch: Epoch,
    prev_commit: &[u8; 32],
    blobs: &[RekeyBlob],
    at_secs: u64,
    citation: Option<&crate::community::edition::AuthorityCitation>,
    severed: bool,
) -> Result<Vec<Event>, RekeyError> {
    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
        vec![&[]]
    } else {
        blobs.chunks(blobs_per_event(scope)).collect()
    };
    let n = groups.len() as u32;
    let mut out = Vec::with_capacity(groups.len());
    for (idx, group_blobs) in groups.iter().enumerate() {
        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)?;
        let (wrap, _) = stream::seal_and_wrap_signed(signer, rotator_pk, &rumor, SealForm::Encrypted, rekey_group, stream::KIND_WRAP, Timestamp::from_secs(at_secs), &[]).await?;
        out.push(wrap);
    }
    Ok(out)
}

/// Extend an already-published rotation's chunk set with additional blobs — the
/// catch-up path for members a rotation forgot.
///
/// Indices start at `start_after + 1` and the declared total covers them, so no
/// reader ever sees two chunks claiming the same slot. That constraint is load-
/// bearing on DEPLOYED clients: [`collect_rotations`] keeps the first chunk seen
/// per index, so a colliding slot silently drops the loser's blobs — and for an
/// original recipient that reads as their own removal. Disjoint indices merge as
/// a pure union under every fetch order, and [`Rotation::is_complete`] only
/// requires `1..=declared_first_seen`, which extras never break.
#[allow(clippy::too_many_arguments)]
pub async fn build_rekey_chunk_extension<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    rotator_pk: PublicKey,
    rekey_group: &GroupKey,
    scope: RekeyScope,
    new_epoch: Epoch,
    prev_epoch: Epoch,
    prev_commit: &[u8; 32],
    blobs: &[RekeyBlob],
    at_secs: u64,
    citation: Option<&crate::community::edition::AuthorityCitation>,
    severed: bool,
    start_after: u32,
) -> Result<Vec<Event>, RekeyError> {
    let groups: Vec<&[RekeyBlob]> = if blobs.is_empty() {
        vec![&[]]
    } else {
        blobs.chunks(blobs_per_event(scope)).collect()
    };
    let n = start_after + groups.len() as u32;
    let mut out = Vec::with_capacity(groups.len());
    for (idx, group_blobs) in groups.iter().enumerate() {
        let i = start_after + idx as u32 + 1;
        let rumor = build_rekey_rumor(rotator_pk, scope, new_epoch, prev_epoch, prev_commit, group_blobs, i, n, at_secs, citation, severed)?;
        let (wrap, _) = stream::seal_and_wrap_signed(signer, rotator_pk, &rumor, SealForm::Encrypted, rekey_group, stream::KIND_WRAP, Timestamp::from_secs(at_secs), &[]).await?;
        out.push(wrap);
    }
    Ok(out)
}

/// Parse a 3303 chunk from a seal-verified stream open. Rejects a non-3303
/// rumor, a plaintext seal (the rekey plane is encrypted-only), malformed or
/// duplicate machinery tags, a bad chunk range, and an over-cap blob array.
pub fn parse_rekey_chunk(opened: &OpenedStream) -> Result<RekeyChunk, RekeyError> {
    if opened.seal_form != SealForm::Encrypted {
        // A plaintext-sealed rekey would be a liftable public artifact — reject.
        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
    }
    let rumor = &opened.rumor;
    if rumor.kind.as_u16() != super::kind::REKEY {
        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
    }
    let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
        .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
    let new_epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
    let prev_epoch = Epoch(parse_u64(rumor, TAG_PREV_EPOCH)?);
    if new_epoch.0 <= prev_epoch.0 {
        return Err(RekeyError::NonMonotonicEpoch);
    }
    let prev_hex = unique_tag(rumor, TAG_PREV_COMMIT)?.ok_or(RekeyError::BadTag(TAG_PREV_COMMIT))?;
    if prev_hex.len() != 64 || !prev_hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(RekeyError::BadTag(TAG_PREV_COMMIT));
    }
    let prev_commit = crate::simd::hex::hex_to_bytes_32(&prev_hex);

    let (chunk_i, chunk_n) = parse_chunk(rumor)?;

    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
        return Err(RekeyError::TooManyBlobs(blobs.len()));
    }

    // Spec-shaped: present means exactly "1" (CORD-01 §5 strictness), absent means false.
    let severed = match unique_tag(rumor, TAG_SEVER)?.as_deref() {
        None => false,
        Some("1") => true,
        Some(_) => return Err(RekeyError::BadTag(TAG_SEVER)),
    };

    Ok(RekeyChunk {
        rotator: opened.author,
        scope,
        new_epoch,
        prev_epoch,
        prev_commit,
        chunk: (chunk_i, chunk_n),
        blobs,
        citation: crate::community::edition::AuthorityCitation::from_tags(&rumor.tags),
        severed,
        at_ms: opened.at_ms,
    })
}

/// A key delivery on a Channel's access plane (CORD-03 §5): blobs carrying the key of the
/// Channel's current epoch. It carries no removal verdict, whatever it omits.
#[derive(Debug, Clone)]
pub struct AccessDelivery {
    pub deliverer: PublicKey,
    pub scope: RekeyScope,
    pub epoch: Epoch,
    pub blobs: Vec<RekeyBlob>,
    /// The writer address a writer-scope delivery's key claims to derive to (CORD-03 §1).
    pub writer: Option<[u8; 32]>,
    /// Writer certificates it hands its recipients, by recipient (CORD-03 §1).
    pub certs: Vec<([u8; 32], [u8; 64])>,
    /// Scoped writer certificates, by recipient, with the CORD-04 bits each covers.
    pub scoped: Vec<([u8; 32], [u8; 64], u64)>,
    /// For one part of a writer epoch's minting delivery, which part of how many.
    pub mint: Option<(u32, u32)>,
}

/// Marks one event of a writer epoch's minting delivery: `["mint", <part>, <parts>]`, from 1.
const TAG_MINT: &str = "mint";

/// `rumor` as part `part` of `parts` of a minting delivery, its id recomputed.
pub fn as_mint_part(rumor: UnsignedEvent, part: usize, parts: usize) -> UnsignedEvent {
    use crate::event_ext::FinalizeUnsignedWithId as _;
    let mut tags: Vec<Tag> = rumor.tags.iter().cloned().collect();
    tags.push(Tag::custom(TAG_MINT, [part.to_string(), parts.to_string()]));
    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);
    out.ensure_id();
    out
}

/// A writer-scope delivery's claimed address.
const TAG_WRITER: &str = "writer";

/// A writer certificate for one recipient: `["cert", <recipient hex>, <signature hex>]`.
const TAG_CERT: &str = "cert";

/// A scoped writer certificate for one recipient: `["rcert", <recipient hex>, <signature hex>,
/// <rights decimal>]`.
const TAG_SCOPED_CERT: &str = "rcert";

/// The unsigned access-plane 3303 rumor.
pub fn build_access_rumor(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
    build_access_rumor_for(deliverer, scope, epoch, None, blobs, at_secs)
}

/// [`build_access_rumor`] naming, for a writer key, the address it derives to.
pub fn build_access_rumor_for(deliverer: PublicKey, scope: RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
    build_access_rumor_certified(deliverer, scope, epoch, writer, blobs, &[], at_secs)
}

/// [`build_access_rumor_for`], handing writer certificates to its recipients.
pub 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> {
    build_access_rumor_scoped(deliverer, scope, epoch, writer, blobs, certs, &[], at_secs)
}

/// [`build_access_rumor_certified`], with scoped certificates for recipients who may write only
/// some kinds.
#[allow(clippy::too_many_arguments)]
pub fn build_access_rumor_scoped(
    deliverer: PublicKey,
    scope: RekeyScope,
    epoch: Epoch,
    writer: Option<[u8; 32]>,
    blobs: &[RekeyBlob],
    certs: &[([u8; 32], [u8; 64])],
    scoped: &[([u8; 32], [u8; 64], u64)],
    at_secs: u64,
) -> Result<UnsignedEvent, RekeyError> {
    let carried = certs.len() + scoped.len();
    let cap = if carried == 0 { MAX_REKEY_BLOBS_PER_EVENT } else { MAX_CERTIFIED_BLOBS_PER_EVENT };
    if blobs.len() > cap || carried > MAX_CERTIFIED_BLOBS_PER_EVENT {
        return Err(RekeyError::TooManyBlobs(blobs.len().max(carried)));
    }
    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let mut tags = vec![
        Tag::custom(TAG_SCOPE, [scope.to_hex()]),
        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
        Tag::custom(TAG_DELIVERY, [DELIVERY_ACCESS]),
    ];
    if let Some(pk) = writer {
        tags.push(Tag::custom(TAG_WRITER, [crate::simd::hex::bytes_to_hex_32(&pk)]));
    }
    for (who, cert) in certs {
        tags.push(Tag::custom(TAG_CERT, [crate::simd::hex::bytes_to_hex_32(who), crate::simd::hex::bytes_to_hex_string(cert)]));
    }
    for (who, cert, rights) in scoped {
        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()]));
    }
    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
}

/// Parse an opened access-plane event. Anything not tagged as an access delivery is refused.
pub fn parse_access_delivery(opened: &OpenedStream) -> Result<AccessDelivery, RekeyError> {
    if opened.seal_form != SealForm::Encrypted {
        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
    }
    let rumor = &opened.rumor;
    if rumor.kind.as_u16() != super::kind::REKEY {
        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
    }
    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_ACCESS) {
        return Err(RekeyError::BadTag(TAG_DELIVERY));
    }
    let scope = RekeyScope::from_hex(&unique_tag(rumor, TAG_SCOPE)?.ok_or(RekeyError::BadTag(TAG_SCOPE))?)
        .ok_or(RekeyError::BadTag(TAG_SCOPE))?;
    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
        return Err(RekeyError::TooManyBlobs(blobs.len()));
    }
    let writer = match unique_tag(rumor, TAG_WRITER)? {
        None => None,
        Some(hex) => Some(crate::simd::hex::hex_to_bytes_32_checked(&hex).ok_or(RekeyError::BadTag(TAG_WRITER))?),
    };
    // A malformed certificate is no certificate; it never refuses the delivery it rides.
    let certs = rumor
        .tags
        .iter()
        .filter_map(|t| {
            let s = t.as_slice();
            (s.first().map(String::as_str) == Some(TAG_CERT) && s.len() == 3).then_some(())?;
            let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
            let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
            Some((who, cert))
        })
        .take(MAX_REKEY_BLOBS_RECEIVED)
        .collect();
    let scoped = rumor
        .tags
        .iter()
        .filter_map(|t| {
            let s = t.as_slice();
            (s.first().map(String::as_str) == Some(TAG_SCOPED_CERT) && s.len() == 4).then_some(())?;
            let who = crate::simd::hex::hex_to_bytes_32_checked(&s[1])?;
            let cert: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked(&s[2])?.try_into().ok()?;
            let rights = s[3].parse::<u64>().ok().filter(|n| n.to_string() == s[3])?;
            Some((who, cert, rights))
        })
        .take(MAX_REKEY_BLOBS_RECEIVED)
        .collect();
    let mint = rumor
        .tags
        .iter()
        .map(|t| t.as_slice())
        .find(|t| t.first().map(String::as_str) == Some(TAG_MINT))
        .and_then(|t| Some((t.get(1)?.parse::<u32>().ok()?, t.get(2)?.parse::<u32>().ok()?)))
        .filter(|(part, parts)| *part >= 1 && part <= parts);
    Ok(AccessDelivery { deliverer: opened.author, scope, epoch, blobs, writer, certs, scoped, mint })
}

/// A Channel's history scope (CORD-03 §5): what history blobs bind to, so one can never be
/// spliced in as a current key.
pub fn history_scope(channel: &ChannelId) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(b"concord/history-scope");
    h.update(channel.0);
    h.finalize().into()
}

/// A past epoch's read view of a Channel (CORD-03 §5): where its messages are and the key that
/// opens them, never the secret that signs into it.
#[derive(Clone, PartialEq, Eq)]
pub struct HistoryView {
    pub address: [u8; 32],
    pub conv_key: [u8; 32],
}

impl std::fmt::Debug for HistoryView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HistoryView").field("address", &crate::simd::hex::bytes_to_hex_32(&self.address)).finish_non_exhaustive()
    }
}

impl HistoryView {
    pub fn of(group: &GroupKey) -> Self {
        let mut conv_key = [0u8; 32];
        conv_key.copy_from_slice(group.conv_key().as_bytes());
        HistoryView { address: group.pk().to_bytes(), conv_key }
    }
}

/// `history_scope[32] ‖ epoch_be[8] ‖ address[32] ‖ conv_key[32]`.
fn history_plaintext_b64(channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Zeroizing<String> {
    let mut pt = Zeroizing::new([0u8; 104]);
    pt[..32].copy_from_slice(&history_scope(channel));
    pt[32..40].copy_from_slice(&epoch.0.to_be_bytes());
    pt[40..72].copy_from_slice(&view.address);
    pt[72..].copy_from_slice(&view.conv_key);
    Zeroizing::new(crate::simd::base64::STANDARD.encode_to_string(&pt[..]))
}

fn parse_history_plaintext(pt: &[u8], channel: &ChannelId, epoch: Epoch) -> Result<HistoryView, RekeyError> {
    if pt.len() != 104 {
        return Err(RekeyError::BadBlobLength(pt.len()));
    }
    if pt[..32] != history_scope(channel) {
        return Err(RekeyError::ScopeSplice);
    }
    if pt[32..40] != epoch.0.to_be_bytes() {
        return Err(RekeyError::EpochSplice);
    }
    let (mut address, mut conv_key) = ([0u8; 32], [0u8; 32]);
    address.copy_from_slice(&pt[40..72]);
    conv_key.copy_from_slice(&pt[72..]);
    Ok(HistoryView { address, conv_key })
}

/// The public locator of `recipient`'s history blob for `epoch` from `deliverer`.
pub fn history_locator(deliverer_xonly: &[u8; 32], recipient_xonly: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> String {
    crate::simd::hex::bytes_to_hex_32(&recipient_locator(deliverer_xonly, recipient_xonly, &history_scope(channel), epoch))
}

pub async fn build_history_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    deliverer_xonly: &[u8; 32],
    recipient: &PublicKey,
    channel: &ChannelId,
    epoch: Epoch,
    view: &HistoryView,
) -> Result<RekeyBlob, RekeyError> {
    let inner = history_plaintext_b64(channel, epoch, view);
    let wrapped = signer.nip44_encrypt_async(recipient, inner.as_str()).await.map_err(|e| RekeyError::Crypto(e.to_string()))?;
    Ok(RekeyBlob { locator: history_locator(deliverer_xonly, &recipient.to_bytes(), channel, epoch), wrapped })
}

pub async fn open_history_blob<S: crate::signer::VectorSigner + ?Sized>(
    signer: &S,
    deliverer: &PublicKey,
    channel: &ChannelId,
    epoch: Epoch,
    blob: &RekeyBlob,
) -> Result<HistoryView, RekeyError> {
    let inner = Zeroizing::new(signer.nip44_decrypt_async(deliverer, &blob.wrapped).await.map_err(|e| RekeyError::Crypto(e.to_string()))?);
    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
    parse_history_plaintext(&pt, channel, epoch)
}

/// [`build_history_blob`] with local keys.
pub fn build_history_blob_local(deliverer: &Keys, recipient: &PublicKey, channel: &ChannelId, epoch: Epoch, view: &HistoryView) -> Result<RekeyBlob, RekeyError> {
    let inner = history_plaintext_b64(channel, epoch, view);
    let ck = ConversationKey::derive(deliverer.secret_key(), recipient).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    Ok(RekeyBlob {
        locator: history_locator(&deliverer.public_key().to_bytes(), &recipient.to_bytes(), channel, epoch),
        wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload),
    })
}

/// [`open_history_blob`] with local keys.
pub fn open_history_blob_local(me: &SecretKey, deliverer: &PublicKey, channel: &ChannelId, epoch: Epoch, blob: &RekeyBlob) -> Result<HistoryView, RekeyError> {
    let ck = ConversationKey::derive(me, deliverer).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let inner = Zeroizing::new(crate::crypto::nip44::decrypt(&ck, payload).map_err(|e| RekeyError::Crypto(e.to_string()))?);
    let pt = Zeroizing::new(crate::simd::base64::STANDARD.decode_to_vec(inner.as_slice()).map_err(|e| RekeyError::Crypto(e.to_string()))?);
    parse_history_plaintext(&pt, channel, epoch)
}

/// One epoch's history blobs on a Channel's access plane.
#[derive(Debug, Clone)]
pub struct HistoryDelivery {
    pub deliverer: PublicKey,
    pub epoch: Epoch,
    pub blobs: Vec<RekeyBlob>,
}

pub fn build_history_rumor(deliverer: PublicKey, channel: &ChannelId, epoch: Epoch, blobs: &[RekeyBlob], at_secs: u64) -> Result<UnsignedEvent, RekeyError> {
    if blobs.len() > MAX_WIDE_BLOBS_PER_EVENT {
        return Err(RekeyError::TooManyBlobs(blobs.len()));
    }
    let content = serde_json::to_string(blobs).map_err(|e| RekeyError::Crypto(e.to_string()))?;
    let tags = vec![
        Tag::custom(TAG_SCOPE, [crate::simd::hex::bytes_to_hex_32(&history_scope(channel))]),
        Tag::custom(TAG_NEW_EPOCH, [epoch.0.to_string()]),
        Tag::custom(TAG_DELIVERY, [DELIVERY_HISTORY]),
    ];
    Ok(stream::build_rumor_secs(super::kind::REKEY, deliverer, &content, tags, at_secs))
}

/// Parse an opened access-plane event as `channel`'s history, refusing anything else.
pub fn parse_history_delivery(opened: &OpenedStream, channel: &ChannelId) -> Result<HistoryDelivery, RekeyError> {
    if opened.seal_form != SealForm::Encrypted {
        return Err(RekeyError::Stream(StreamError::BadSealKind(stream::KIND_SEAL_PLAINTEXT)));
    }
    let rumor = &opened.rumor;
    if rumor.kind.as_u16() != super::kind::REKEY {
        return Err(RekeyError::NotARekey(rumor.kind.as_u16()));
    }
    if unique_tag(rumor, TAG_DELIVERY)?.as_deref() != Some(DELIVERY_HISTORY) {
        return Err(RekeyError::BadTag(TAG_DELIVERY));
    }
    if unique_tag(rumor, TAG_SCOPE)?.as_deref() != Some(crate::simd::hex::bytes_to_hex_32(&history_scope(channel)).as_str()) {
        return Err(RekeyError::BadTag(TAG_SCOPE));
    }
    let epoch = Epoch(parse_u64(rumor, TAG_NEW_EPOCH)?);
    let blobs: Vec<RekeyBlob> = serde_json::from_str(&rumor.content).map_err(|_| RekeyError::BadTag("blobs"))?;
    if blobs.len() > MAX_REKEY_BLOBS_RECEIVED {
        return Err(RekeyError::TooManyBlobs(blobs.len()));
    }
    Ok(HistoryDelivery { deliverer: opened.author, epoch, blobs })
}

// ── Continuity + removal + fork resolution (CORD-06 §2/§3) ───────────────────

/// The verdict of the prevcommit continuity check (CORD-06 §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Continuity {
    /// The commitment matches the key I hold at `prev_epoch` — this rotation
    /// extends my chain; adopt it.
    Extends,
    /// `prev_epoch` is higher than the key I hold — I missed a rotation; fetch
    /// the gap first, don't adopt yet.
    Gap,
    /// The commitment doesn't match at the same epoch — a fork or garbage.
    Fork,
}

/// Check a rotation's `prev_commit` against the `(epoch, key)` I currently hold
/// for its scope. A match proves the rotation extends the very key I hold; a
/// higher `prev_epoch` means I'm behind; anything else is a fork/garbage.
pub fn check_continuity(chunk: &RekeyChunk, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
    if chunk.prev_epoch.0 == held_epoch.0 {
        if epoch_key_commitment(held_epoch, held_key) == chunk.prev_commit {
            Continuity::Extends
        } else {
            Continuity::Fork
        }
    } else if chunk.prev_epoch.0 > held_epoch.0 {
        Continuity::Gap
    } else {
        // prev_epoch < held: this rotation is older than where I am — a stale
        // fork; a settled epoch only ever heals DOWN to a sibling, never back.
        Continuity::Fork
    }
}

/// A collected rotation: all chunks sharing one correlation key, and whether the
/// set is complete (all `n` chunks present).
#[derive(Debug, Clone)]
pub struct Rotation {
    pub rotator: PublicKey,
    pub scope: RekeyScope,
    pub new_epoch: Epoch,
    pub prev_epoch: Epoch,
    pub prev_commit: [u8; 32],
    /// The union of every chunk's blobs.
    pub blobs: Vec<RekeyBlob>,
    /// Total chunk count `n` declared by the chunks.
    pub declared_chunks: u32,
    /// Distinct chunk indices actually held.
    pub held_chunks: std::collections::BTreeSet<u32>,
    /// The rotator's `vac`, taken from the first chunk seen (every chunk of one
    /// rotation carries the same citation — they share a signer and an action).
    pub citation: Option<crate::community::edition::AuthorityCitation>,
    /// OR across chunks: any severed chunk marks the whole rotation severed, so
    /// an extension (rescue) can never launder the flag away.
    pub severed: bool,
    /// When it was sent: its earliest chunk's time, in ms.
    pub at_ms: u64,
}

impl Rotation {
    /// True once every declared chunk index `1..=n` is held — the precondition
    /// for concluding removal (a missing chunk is "keep recovering", never a
    /// removal).
    pub fn is_complete(&self) -> bool {
        self.declared_chunks >= 1 && (1..=self.declared_chunks).all(|i| self.held_chunks.contains(&i))
    }

    /// This rotation's continuity against the `(epoch, key)` I hold for its scope
    /// — the [`check_continuity`] verdict at the aggregated-rotation level (same
    /// prevcommit test), so a follower can gate adoption without a raw chunk.
    pub fn continuity(&self, held_epoch: Epoch, held_key: &[u8; 32]) -> Continuity {
        if self.prev_epoch.0 == held_epoch.0 {
            if epoch_key_commitment(held_epoch, held_key) == self.prev_commit {
                Continuity::Extends
            } else {
                Continuity::Fork
            }
        } else if self.prev_epoch.0 > held_epoch.0 {
            Continuity::Gap
        } else {
            Continuity::Fork
        }
    }
}

/// Group a batch of parsed chunks into rotations by correlation key. Chunks whose
/// `n` disagrees with their siblings, or that repeat an index, are the caller's
/// concern to police; here the largest `n` any chunk declares sets the total, and a
/// second chunk at a held index unions its blobs.
pub fn collect_rotations(chunks: &[RekeyChunk]) -> Vec<Rotation> {
    use std::collections::BTreeMap;
    let mut by_key: BTreeMap<RotationKey, Rotation> = BTreeMap::new();
    for c in chunks {
        let entry = by_key.entry(c.correlation()).or_insert_with(|| Rotation {
            rotator: c.rotator,
            scope: c.scope,
            new_epoch: c.new_epoch,
            prev_epoch: c.prev_epoch,
            prev_commit: c.prev_commit,
            blobs: Vec::new(),
            declared_chunks: c.chunk.1,
            held_chunks: std::collections::BTreeSet::new(),
            citation: c.citation.clone(),
            severed: c.severed,
            at_ms: c.at_ms,
        });
        entry.severed |= c.severed;
        entry.at_ms = entry.at_ms.min(c.at_ms);
        // An extension declares the larger total: complete only once every index up to it is held.
        entry.declared_chunks = entry.declared_chunks.max(c.chunk.1);
        // UNION the blobs, even when the index is already held. Treating a second
        // chunk at a known index as pure idempotent re-delivery is safe only while
        // re-delivery is byte-identical; when two chunks genuinely differ (a
        // catch-up extension that re-claimed a slot), dropping the loser silently
        // deletes its recipients from the union — and a recipient with no blob reads
        // as REMOVED, which tears their community down. Union can only ever ADD
        // blobs, so it can turn a false removal into an adoption but never the
        // reverse. Exact duplicates are dropped so ordinary re-delivery stays free.
        entry.held_chunks.insert(c.chunk.0);
        for b in &c.blobs {
            if !entry.blobs.iter().any(|held| held.locator == b.locator && held.wrapped == b.wrapped) {
                entry.blobs.push(b.clone());
            }
        }
    }
    by_key.into_values().collect()
}

/// Have I been removed by this rotation? Only answerable on a COMPLETE rotation
/// (all `n` chunks held): I'm removed iff none of the union's blobs carries my
/// locator. On an incomplete rotation the answer is `None` — keep recovering.
pub fn am_i_removed(rotation: &Rotation, my_xonly: &[u8; 32]) -> Option<bool> {
    if !rotation.is_complete() {
        return None;
    }
    let mine = find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), my_xonly, rotation.scope, rotation.new_epoch);
    Some(mine.is_none())
}

/// Deterministic same-epoch fork winner (CORD-06 §3): among candidate rotations
/// at one continuity point, the one whose decrypted `new_key` is lexicographically
/// lowest wins. Every retained member decrypts its own blob from each fork and
/// computes the identical winner. Returns the index into `candidates` of the
/// winner, or `None` if the caller decrypted no candidate.
pub fn lowest_key_winner(candidate_keys: &[[u8; 32]]) -> Option<usize> {
    candidate_keys
        .iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| a.cmp(b))
        .map(|(i, _)| i)
}

// ── helpers ──────────────────────────────────────────────────────────────────

fn unique_tag(rumor: &UnsignedEvent, name: &'static str) -> Result<Option<String>, RekeyError> {
    let mut found: Option<String> = None;
    for t in rumor.tags.iter() {
        let s = t.as_slice();
        if s.len() >= 2 && s[0] == name {
            if found.is_some() {
                return Err(RekeyError::BadTag(name));
            }
            found = Some(s[1].clone());
        }
    }
    Ok(found)
}

fn parse_u64(rumor: &UnsignedEvent, name: &'static str) -> Result<u64, RekeyError> {
    let raw = unique_tag(rumor, name)?.ok_or(RekeyError::BadTag(name))?;
    // Spec-shaped decimal, not a bare `parse` — that takes "+2" and "02" as
    // epochs a stricter peer refuses (CORD-01 §5).
    if !crate::community::edition::is_tag_decimal(&raw) {
        return Err(RekeyError::BadTag(name));
    }
    raw.parse::<u64>().map_err(|_| RekeyError::BadTag(name))
}

fn parse_chunk(rumor: &UnsignedEvent) -> Result<(u32, u32), RekeyError> {
    let mut found: Option<(u32, u32)> = None;
    for t in rumor.tags.iter() {
        let s = t.as_slice();
        if s.len() >= 3 && s[0] == TAG_CHUNK {
            if found.is_some() {
                return Err(RekeyError::BadTag(TAG_CHUNK));
            }
            if !crate::community::edition::is_tag_decimal(&s[1]) || !crate::community::edition::is_tag_decimal(&s[2]) {
                return Err(RekeyError::BadTag(TAG_CHUNK));
            }
            let i: u32 = s[1].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
            let n: u32 = s[2].parse().map_err(|_| RekeyError::BadTag(TAG_CHUNK))?;
            found = Some((i, n));
        }
    }
    let (i, n) = found.ok_or(RekeyError::BadTag(TAG_CHUNK))?;
    if n < 1 || i < 1 || i > n {
        return Err(RekeyError::BadChunkIndex);
    }
    Ok((i, n))
}

#[cfg(test)]
mod tests {

    /// Wrap raw `Keys` as the polymorphic signer. `VectorSigner` pins its error to
    /// `SignerError`, which bare `Keys` doesn't satisfy, so tests go through the
    /// same enum the app uses.
    fn as_signer(k: &Keys) -> crate::signer::ActiveSigner {
        crate::signer::ActiveSigner::Keys(k.clone())
    }
    use super::*;

    fn keys(byte: u8) -> Keys {
        Keys::new(SecretKey::from_slice(&[byte; 32]).unwrap())
    }

    fn xonly(k: &Keys) -> [u8; 32] {
        k.public_key().to_bytes()
    }

    const CHAN: ChannelId = ChannelId([0x42u8; 32]);

    // ── blob atom ────────────────────────────────────────────────────────────

    #[test]
    fn bound_plaintext_layout_is_frozen() {
        let pt = bound_plaintext(RekeyScope::Root, Epoch(1), &[0xABu8; 32]);
        let expected = format!("{}{}{}", "00".repeat(32), "0000000000000001", "ab".repeat(32));
        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
        let pt2 = bound_plaintext(RekeyScope::Channel(ChannelId([0x11u8; 32])), Epoch(0x0102), &[0xCDu8; 32]);
        let expected2 = format!("{}{}{}", "11".repeat(32), "0000000000000102", "cd".repeat(32));
        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt2), expected2);
    }

    #[test]
    fn blob_round_trips_both_scopes() {
        let rotator = keys(7);
        let recipient = keys(8);
        for (scope, epoch, key) in [
            (RekeyScope::Root, Epoch(1), [0xABu8; 32]),
            (RekeyScope::Channel(CHAN), Epoch(5), [0xCDu8; 32]),
        ] {
            let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
            let got = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob).unwrap();
            assert_eq!(got, key, "the recipient recovers the fresh key");
        }
    }

    #[tokio::test]
    async fn signer_blob_is_wire_compatible_with_local_both_directions() {
        // A remote signer (here a plain Keys, which impls VectorSigner) must build
        // AND open blobs interchangeably with the raw-key path — the CORD-06 D5
        // "identical wire" guarantee the bunker/NIP-55 integration rests on.
        let rotator = keys(7);
        let recipient = keys(8);
        let scope = RekeyScope::Root;
        let epoch = Epoch(3);
        let key = [0x5Au8; 32];

        // local build -> signer open
        let blob_l = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).unwrap();
        let got_s = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_l).await.unwrap();
        assert_eq!(got_s, key, "signer opens a local-built blob");

        // signer build -> local open (+ identical public locator)
        let blob_s = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), scope, epoch, &key).await.unwrap();
        assert_eq!(blob_s.locator, blob_l.locator, "same public locator regardless of build path");
        let got_l = open_blob_local(recipient.secret_key(), &rotator.public_key(), scope, epoch, &blob_s).unwrap();
        assert_eq!(got_l, key, "local opens a signer-built blob");

        // signer build -> signer open
        let got_ss = open_blob(&as_signer(&recipient), &rotator.public_key(), scope, epoch, &blob_s).await.unwrap();
        assert_eq!(got_ss, key, "signer round-trips its own blob");
    }

    #[tokio::test]
    async fn signer_blob_bound_check_still_gates_scope_epoch_splice() {
        let rotator = keys(7);
        let recipient = keys(8);
        let blob = build_blob(&as_signer(&rotator), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[9u8; 32]).await.unwrap();
        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob).await.is_err(), "epoch splice rejected");
        assert!(open_blob(&as_signer(&recipient), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob).await.is_err(), "scope splice rejected");
    }

    #[test]
    fn locator_is_public_and_computable_from_pubkeys_alone() {
        // D1: the locator derives from PUBLIC inputs, so the rotator computing a
        // recipient's slot and the recipient computing their own must agree — no
        // secret needed either side (bunker parity).
        let rotator = keys(7);
        let recipient = keys(8);
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(2), &[1u8; 32]).unwrap();
        let recomputed = blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(2));
        assert_eq!(blob.locator, recomputed, "both sides compute the same public locator");
    }

    #[test]
    fn a_non_recipient_cannot_open_even_holding_the_public_locator() {
        // The D1 security relocation: the locator authenticates NOTHING (anyone
        // holding both npubs computes it), yet an outsider still can't open —
        // the pairwise decrypt is the gate, not the locator.
        let rotator = keys(7);
        let recipient = keys(8);
        let outsider = keys(9);
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[2u8; 32]).unwrap();
        // The outsider can trivially recompute the (public) locator...
        assert_eq!(blob.locator, blob_locator(&xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)));
        // ...but pairing (outsider_sk, rotator_pk) yields a different conversation
        // key, so the decrypt fails.
        assert!(open_blob_local(outsider.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).is_err());
    }

    #[test]
    fn a_relocated_blob_still_opens_by_decrypt_not_locator() {
        // Because open ignores the locator (D1), corrupting the locator does NOT
        // break a legitimate recipient's open — the decrypt + bound check govern.
        // The FIND step uses the locator; OPEN does not.
        let rotator = keys(7);
        let recipient = keys(8);
        let mut blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[3u8; 32]).unwrap();
        blob.locator = "ff".repeat(32);
        // Handed the blob directly (locator bypassed), the recipient still opens it.
        assert_eq!(
            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), &blob).unwrap(),
            [3u8; 32]
        );
        // But find_my_blob won't LOCATE it under the corrupted locator.
        assert!(find_my_blob(std::slice::from_ref(&blob), &xonly(&rotator), &xonly(&recipient), RekeyScope::Root, Epoch(1)).is_none());
    }

    #[test]
    fn scope_and_epoch_splices_are_rejected_on_open() {
        let rotator = keys(7);
        let recipient = keys(8);
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[4u8; 32]).unwrap();
        // Opened under a different scope → bound scope mismatch.
        assert!(matches!(
            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &blob),
            Err(RekeyError::ScopeSplice)
        ));
        // Opened under a different epoch → bound epoch mismatch.
        assert!(matches!(
            open_blob_local(recipient.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(2), &blob),
            Err(RekeyError::EpochSplice)
        ));
    }

    #[test]
    fn wrapped_carries_base64_of_the_72_bytes_for_bunker_parity() {
        // D5: the NIP-44 layer's plaintext is base64(72 bytes) — a UTF-8 string a
        // NIP-46 signer can nip44_encrypt/decrypt. Prove the decrypted inner is
        // exactly that base64 string, matching the `_b64` helper the bunker uses.
        let rotator = keys(7);
        let recipient = keys(8);
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &[5u8; 32]).unwrap();
        let ck = ConversationKey::derive(recipient.secret_key(), &rotator.public_key()).unwrap();
        let payload = crate::simd::base64::STANDARD.decode_to_vec(blob.wrapped.as_bytes()).unwrap();
        let inner = nostr_sdk::prelude::nip44::v2::decrypt_to_bytes(&ck, &payload).unwrap();
        assert_eq!(String::from_utf8(inner).unwrap(), bound_plaintext_b64(RekeyScope::Root, Epoch(1), &[5u8; 32]));
    }

    #[test]
    fn distinct_recipients_and_scopes_get_distinct_locators() {
        let rotator = keys(7);
        let r1 = keys(8);
        let r2 = keys(9);
        assert_ne!(
            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
            blob_locator(&xonly(&rotator), &xonly(&r2), RekeyScope::Root, Epoch(1))
        );
        // Same pair, a base blob and a channel blob at one epoch don't collide.
        assert_ne!(
            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Root, Epoch(1)),
            blob_locator(&xonly(&rotator), &xonly(&r1), RekeyScope::Channel(CHAN), Epoch(1))
        );
    }

    // ── 3303 event ─────────────────────────────────────────────────────────

    fn root() -> [u8; 32] {
        [0x55u8; 32]
    }

    #[test]
    fn channel_rekey_round_trips_through_the_stream() {
        let rotator = keys(1);
        let recipient = keys(8);
        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
        let key = [0xABu8; 32];
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(1), &key).unwrap();
        let commit = epoch_key_commitment(Epoch(0), &[0xEEu8; 32]);
        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &commit, &[blob.clone()], 1, 1, 100, None, false).unwrap();
        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &rotator, Timestamp::from_secs(100)).unwrap();

        // The wrap is signed by the group key, not the rotator (no identity on the wire).
        assert_ne!(wrap.pubkey, rotator.public_key());
        assert_eq!(wrap.pubkey, group.pk());

        let opened = stream::open_wrap(&wrap, &group).unwrap();
        let chunk = parse_rekey_chunk(&opened).unwrap();
        assert_eq!(chunk.rotator, rotator.public_key(), "rotator recovered from the seal");
        assert!(matches!(chunk.scope, RekeyScope::Channel(c) if c.0 == CHAN.0));
        assert_eq!(chunk.new_epoch, Epoch(1));
        assert_eq!(chunk.prev_epoch, Epoch(0));
        assert_eq!(chunk.prev_commit, commit);
        assert_eq!(chunk.chunk, (1, 1));
        assert_eq!(chunk.blobs, vec![blob]);
    }

    #[test]
    fn an_access_delivery_round_trips_and_never_reads_as_a_rotation() {
        let (deliverer, recipient) = (keys(1), keys(8));
        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
        let key = [0xABu8; 32];
        let blob = build_blob_local(deliverer.secret_key(), &xonly(&deliverer), &recipient.public_key(), RekeyScope::Channel(CHAN), Epoch(3), &key).unwrap();
        let rumor = build_access_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), std::slice::from_ref(&blob), 100).unwrap();
        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
        let opened = stream::open_wrap(&wrap, &group).unwrap();
        let delivery = parse_access_delivery(&opened).unwrap();
        assert_eq!((delivery.deliverer, delivery.epoch), (deliverer.public_key(), Epoch(3)));
        let mine = find_my_blob(&delivery.blobs, &xonly(&deliverer), &xonly(&recipient), delivery.scope, delivery.epoch).unwrap();
        assert_eq!(open_blob_local(recipient.secret_key(), &deliverer.public_key(), delivery.scope, delivery.epoch, mine).unwrap(), key);
        assert!(parse_rekey_chunk(&opened).is_err(), "a delivery is no rotation");
        // Nor is a rotation a delivery.
        let commit = epoch_key_commitment(Epoch(2), &[0xEEu8; 32]);
        let rotation = build_rekey_rumor(deliverer.public_key(), RekeyScope::Channel(CHAN), Epoch(3), Epoch(2), &commit, &[blob], 1, 1, 100, None, false).unwrap();
        let (wrap, _) = seal_rekey_chunk(&rotation, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
        assert!(parse_access_delivery(&stream::open_wrap(&wrap, &group).unwrap()).is_err());
    }

    #[test]
    fn a_history_delivery_round_trips_and_binds_its_channel_and_epoch() {
        let (deliverer, recipient) = (keys(1), keys(8));
        let group = crate::community::v2::derive::channel_access_group_key(&root(), &CHAN, Epoch(0));
        let past = crate::community::v2::derive::channel_group_key(&[0x42; 32], &CHAN, Epoch(2));
        let view = HistoryView::of(&past);
        let blob = build_history_blob_local(&deliverer, &recipient.public_key(), &CHAN, Epoch(2), &view).unwrap();
        let rumor = build_history_rumor(deliverer.public_key(), &CHAN, Epoch(2), std::slice::from_ref(&blob), 100).unwrap();
        let (wrap, _) = seal_rekey_chunk(&rumor, &group, &deliverer, Timestamp::from_secs(100)).unwrap();
        let opened = stream::open_wrap(&wrap, &group).unwrap();
        let d = parse_history_delivery(&opened, &CHAN).unwrap();
        assert_eq!((d.deliverer, d.epoch), (deliverer.public_key(), Epoch(2)));
        assert_eq!(d.blobs[0].locator, history_locator(&xonly(&deliverer), &xonly(&recipient), &CHAN, Epoch(2)));
        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");
        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &CHAN, Epoch(3), &d.blobs[0]), Err(RekeyError::EpochSplice)));
        let other = ChannelId([0x01; 32]);
        assert!(matches!(open_history_blob_local(recipient.secret_key(), &deliverer.public_key(), &other, Epoch(2), &d.blobs[0]), Err(RekeyError::ScopeSplice)));
        assert!(parse_history_delivery(&opened, &other).is_err(), "another channel's history isn't this one's");
        assert!(parse_access_delivery(&opened).is_err() && parse_rekey_chunk(&opened).is_err(), "nor is it a key or a rotation");
        // The view really opens that epoch's plane.
        let msg = stream::build_rumor_secs(9, deliverer.public_key(), "old", vec![], 1);
        let (old_wrap, _) = stream::wrap_seal(&stream::build_seal(&msg, SealForm::Plaintext, &past, &deliverer).unwrap(), &past, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
        let read = stream::open_wrap_at(&old_wrap, &PublicKey::from_slice(&view.address).unwrap(), &ConversationKey::new(view.conv_key), false).unwrap();
        assert_eq!(read.rumor.content, "old");
    }

    #[test]
    fn base_rekey_addresses_under_the_prior_root() {
        // A base rotation rides the PRIOR root: a member holding the prior root
        // derives the same group key and opens it; a non-holder can't.
        let rotator = keys(1);
        let recipient = keys(8);
        let prior_root = [0x66u8; 32];
        let community = CommunityId([0x77u8; 32]);
        let new_root = [0x99u8; 32];
        let group = base_rekey_group(&prior_root, &community, Epoch(1));
        let blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &recipient.public_key(), RekeyScope::Root, Epoch(1), &new_root).unwrap();
        let commit = epoch_key_commitment(Epoch(0), &prior_root);
        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &commit, &[blob], 100, None, false).unwrap();
        assert_eq!(chunks.len(), 1);

        let opened = stream::open_wrap(&chunks[0], &group).unwrap();
        let chunk = parse_rekey_chunk(&opened).unwrap();
        assert!(matches!(chunk.scope, RekeyScope::Root));
        // The recipient recovers the NEW root from their blob.
        let mine = find_my_blob(&chunk.blobs, &chunk.rotator.to_bytes(), &xonly(&recipient), chunk.scope, chunk.new_epoch).unwrap();
        assert_eq!(open_blob_local(recipient.secret_key(), &chunk.rotator, chunk.scope, chunk.new_epoch, mine).unwrap(), new_root);

        // A non-holder of the prior root can't even open the wrap.
        let wrong = base_rekey_group(&[0u8; 32], &community, Epoch(1));
        assert!(stream::open_wrap(&chunks[0], &wrong).is_err());
    }

    #[test]
    fn a_full_send_chunk_stays_under_the_relay_size_limit() {
        // The send caps exist so one chunk fits a 64KB strfry event, each form at its own: a
        // base rotation's widest blob (136 bytes, a staff recipient), cited and severed, and a
        // Channel rotation's 72-byte one.
        let rotator = keys(1);
        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
        let cite = crate::community::edition::AuthorityCitation { entity_id: [7; 32], version: u64::MAX, edition_hash: [8; 32] };
        let base: Vec<RekeyBlob> = (0..blobs_per_event(RekeyScope::Root))
            .map(|i| {
                let r = keys((i % 200 + 20) as u8);
                let inner = bound_base_plaintext_b64(Epoch(1), &[0xCD; 32], &[0xAB; 32], Some(&[0xEE; 32]));
                let ck = ConversationKey::derive(rotator.secret_key(), &r.public_key()).unwrap();
                let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, inner.as_bytes()).unwrap();
                RekeyBlob { locator: blob_locator(&xonly(&rotator), &r.public_key().to_bytes(), RekeyScope::Root, Epoch(1)), wrapped: crate::simd::base64::STANDARD.encode_to_string(&payload) }
            })
            .collect();
        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &base, 100, Some(&cite), true).unwrap();
        assert_eq!(chunks.len(), 1, "a full base chunk is exactly one event");
        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full base chunk must fit a 64KB relay event", chunks[0].as_json().len());

        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
        let narrow: Vec<RekeyBlob> = (0..blobs_per_event(scope))
            .map(|i| build_blob_local(rotator.secret_key(), &xonly(&rotator), &keys((i % 200 + 20) as u8).public_key(), scope, Epoch(1), &[0xCDu8; 32]).unwrap())
            .collect();
        let chunks = build_rekey_chunks_local(&rotator, &group, scope, Epoch(1), Epoch(0), &[0u8; 32], &narrow, 100, Some(&cite), false).unwrap();
        assert_eq!(chunks.len(), 1);
        assert!(chunks[0].as_json().len() <= 65_536, "{} bytes: a full channel chunk must fit a 64KB relay event", chunks[0].as_json().len());
    }

    #[test]
    fn a_full_history_delivery_stays_under_the_relay_size_limit() {
        let deliverer = keys(1);
        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
        let channel = crate::community::ChannelId([3; 32]);
        let view = HistoryView { address: [0xAA; 32], conv_key: [0xBB; 32] };
        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();
        let rumor = build_history_rumor(deliverer.public_key(), &channel, Epoch(1), &blobs, 100).unwrap();
        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full history delivery must fit a 64KB relay event", wrap.as_json().len());
    }

    #[test]
    fn a_full_certified_delivery_stays_under_the_relay_size_limit() {
        let deliverer = keys(1);
        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
        let recipients: Vec<Keys> = (0..MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| keys((i % 200 + 20) as u8)).collect();
        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();
        let certs: Vec<([u8; 32], [u8; 64])> = recipients.iter().map(|r| (r.public_key().to_bytes(), [0xEE; 64])).collect();
        let rumor = build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), Some([0x42; 32]), &blobs, &certs, 100).unwrap();
        let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &deliverer).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(100)).unwrap();
        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full certified chunk must fit a 64KB relay event", wrap.as_json().len());
    }

    #[test]
    fn a_certified_delivery_past_its_cap_is_refused() {
        let deliverer = keys(1);
        let scope = RekeyScope::Channel(crate::community::ChannelId([3; 32]));
        let blobs: Vec<RekeyBlob> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() }).collect();
        let certs: Vec<([u8; 32], [u8; 64])> = (0..=MAX_CERTIFIED_BLOBS_PER_EVENT).map(|i| ([i as u8; 32], [0xEE; 64])).collect();
        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &certs, 100).is_err());
        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs, &[], 100).is_ok(), "keys alone fit more");
        assert!(build_access_rumor_certified(deliverer.public_key(), scope, Epoch(1), None, &blobs[1..], &certs[1..], 100).is_ok());
    }

    #[test]
    fn oversize_recipient_set_splits_into_chunks() {
        let rotator = keys(1);
        let group = base_rekey_group(&root(), &CommunityId([9u8; 32]), Epoch(1));
        // One over the base rotation's send cap → 2 chunks, labeled (1,2) and (2,2).
        let blobs: Vec<RekeyBlob> = (0..MAX_WIDE_BLOBS_PER_EVENT + 1)
            .map(|_| RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() })
            .collect();
        let chunks = build_rekey_chunks_local(&rotator, &group, RekeyScope::Root, Epoch(2), Epoch(1), &[0u8; 32], &blobs, 100, None, false).unwrap();
        assert_eq!(chunks.len(), 2);
        let parsed: Vec<RekeyChunk> = chunks.iter().map(|w| parse_rekey_chunk(&stream::open_wrap(w, &group).unwrap()).unwrap()).collect();
        assert_eq!(parsed[0].chunk, (1, 2));
        assert_eq!(parsed[1].chunk, (2, 2));
        assert_eq!(parsed[0].blobs.len(), MAX_WIDE_BLOBS_PER_EVENT);
        assert_eq!(parsed[1].blobs.len(), 1);
    }

    #[test]
    fn plaintext_sealed_rekey_is_rejected() {
        let rotator = keys(1);
        let group = channel_rekey_group(&root(), &CHAN, Epoch(1));
        let rumor = build_rekey_rumor(rotator.public_key(), RekeyScope::Channel(CHAN), Epoch(1), Epoch(0), &[0u8; 32], &[], 1, 1, 100, None, false).unwrap();
        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &group, &rotator).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
        let opened = stream::open_wrap(&wrap, &group).unwrap();
        assert!(parse_rekey_chunk(&opened).is_err(), "the rekey plane must be encrypted-sealed");
    }

    #[test]
    fn non_monotonic_epoch_is_refused_at_mint_and_on_parse() {
        let rotator = keys(1);
        assert!(matches!(
            build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(1), &[0u8; 32], &[], 1, 1, 100, None, false),
            Err(RekeyError::NonMonotonicEpoch)
        ));
    }

    #[test]
    fn bad_chunk_indices_are_refused() {
        let rotator = keys(1);
        for (i, n) in [(0u32, 1u32), (2, 1), (1, 0)] {
            assert!(
                matches!(build_rekey_rumor(rotator.public_key(), RekeyScope::Root, Epoch(1), Epoch(0), &[0u8; 32], &[], i, n, 100, None, false), Err(RekeyError::BadChunkIndex)),
                "chunk ({i},{n}) must be rejected"
            );
        }
    }

    // ── continuity + removal + fork ──────────────────────────────────────────

    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 {
        RekeyChunk {
            rotator: rotator.public_key(),
            scope,
            new_epoch: Epoch(new_epoch),
            prev_epoch: Epoch(prev_epoch),
            prev_commit: epoch_key_commitment(Epoch(prev_epoch), prev_key),
            chunk: (i, n),
            blobs,
            citation: None,
            severed: false,
            at_ms: 0,
        }
    }

    #[test]
    fn a_rotation_dates_from_its_earliest_chunk() {
        let rotator = Keys::generate();
        let prev = [3u8; 32];
        let mut late = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
        late.at_ms = 9_000;
        let mut early = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);
        early.at_ms = 4_000;
        let rotations = collect_rotations(&[late, early]);
        assert_eq!(rotations.len(), 1);
        assert_eq!(rotations[0].at_ms, 4_000, "a re-sent chunk never moves a rotation later");
    }

    #[test]
    fn a_colliding_chunk_index_must_not_swallow_a_recipients_blob() {
        // Chunks are correlated by index, and a second chunk claiming an index
        // already held is treated as idempotent re-delivery — its blobs dropped.
        // That is safe only while re-delivery is byte-identical. The catch-up path
        // that extends a rotation computes its starting index from a fetch that can
        // come back blind, and then re-claims index 1; whichever copy a client sees
        // first wins, so the original recipients in the loser vanish from the union.
        // A recipient whose blob vanishes reads as REMOVED — and removal deletes the
        // community locally. Losing a blob to a bookkeeping collision must never be
        // able to masquerade as a removal verdict.
        let rotator = keys(1);
        let prev = [0x55u8; 32];
        let mine = RekeyBlob { locator: "aa".repeat(32), wrapped: "mine".into() };
        let other = RekeyBlob { locator: "bb".repeat(32), wrapped: "other".into() };

        // Two chunks both claiming index 1: the original (carrying my blob) and a
        // re-claim (carrying someone else's).
        let original = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![mine.clone()], 1, 1);
        let reclaim = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![other.clone()], 1, 1);

        for (order, chunks) in [
            ("original first", vec![original.clone(), reclaim.clone()]),
            ("reclaim first", vec![reclaim.clone(), original.clone()]),
        ] {
            let rotations = collect_rotations(&chunks);
            assert_eq!(rotations.len(), 1, "{order}: same correlation key");
            let has_mine = rotations[0].blobs.iter().any(|b| b.locator == mine.locator);
            assert!(
                has_mine,
                "{order}: my blob was dropped by an index collision — that reads as a removal \
                 and removal deletes the community",
            );
        }
    }

    #[test]
    fn a_severed_rotation_cannot_be_laundered_by_an_unmarked_chunk() {
        // The containment marker rides EVERY chunk of a rotation, but a rotation's
        // chunk set can be extended later (the catch-up path for members a rotation
        // forgot). An extension built without the marker would, under first-seen
        // semantics, present a severed epoch as an ordinary one — and an adopter
        // reading it that way refreshes the very invite links the containment meant
        // to bury, re-opening the door the raid came through. The fold is therefore
        // an OR across chunks, in either arrival order.
        let rotator = keys(1);
        let prev = [0x44u8; 32];
        let mut marked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 1, 2);
        marked.severed = true;
        let unmarked = chunk_at(&rotator, RekeyScope::Root, 2, 1, &prev, vec![], 2, 2);

        for (order, chunks) in [
            ("marked first", vec![marked.clone(), unmarked.clone()]),
            ("unmarked first", vec![unmarked.clone(), marked.clone()]),
        ] {
            let rotations = collect_rotations(&chunks);
            assert_eq!(rotations.len(), 1, "{order}: one correlation key, one rotation");
            assert!(
                rotations[0].severed,
                "{order}: an unmarked sibling must never launder the containment away",
            );
            assert!(rotations[0].is_complete(), "{order}: both chunks held");
        }
    }

    #[test]
    fn continuity_extends_gaps_and_forks() {
        let rotator = keys(1);
        let held = [0x33u8; 32];
        // Extends: prev_epoch == held epoch AND commitment matches the held key.
        let good = chunk_at(&rotator, RekeyScope::Root, 3, 2, &held, vec![], 1, 1);
        assert_eq!(check_continuity(&good, Epoch(2), &held), Continuity::Extends);
        // Gap: the rotation is FROM a higher epoch than I hold — I missed one.
        let ahead = chunk_at(&rotator, RekeyScope::Root, 5, 4, &held, vec![], 1, 1);
        assert_eq!(check_continuity(&ahead, Epoch(2), &held), Continuity::Gap);
        // Fork: same epoch but the commitment names a different prior key.
        let fork = chunk_at(&rotator, RekeyScope::Root, 3, 2, &[0x99u8; 32], vec![], 1, 1);
        assert_eq!(check_continuity(&fork, Epoch(2), &held), Continuity::Fork);
        // Fork: a rotation older than where I am (stale).
        let stale = chunk_at(&rotator, RekeyScope::Root, 2, 1, &held, vec![], 1, 1);
        assert_eq!(check_continuity(&stale, Epoch(2), &held), Continuity::Fork);
    }

    #[test]
    fn a_missing_chunk_is_never_a_removal() {
        // The core no-false-removal guarantee: until ALL n chunks are held, "am I
        // removed" is unanswerable, even if the chunks I DO hold lack my blob.
        let rotator = keys(1);
        let me = keys(8);
        // Two-chunk rotation; my blob is in chunk 2, which I haven't received.
        let my_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &me.public_key(), RekeyScope::Root, Epoch(1), &[0xAAu8; 32]).unwrap();
        let c1 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![RekeyBlob { locator: "bb".repeat(32), wrapped: "x".into() }], 1, 2);
        let rots = collect_rotations(&[c1.clone()]);
        assert_eq!(rots.len(), 1);
        assert!(!rots[0].is_complete(), "one of two chunks held → incomplete");
        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), None, "incomplete → keep recovering, never conclude removal");

        // Now chunk 2 (with my blob) arrives → complete, and I am NOT removed.
        let c2 = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![my_blob.clone()], 2, 2);
        let rots = collect_rotations(&[c1, c2]);
        assert!(rots[0].is_complete());
        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(false));
        // And my key is recoverable from the union.
        let mine = find_my_blob(&rots[0].blobs, &rots[0].rotator.to_bytes(), &xonly(&me), RekeyScope::Root, Epoch(1)).unwrap();
        assert_eq!(open_blob_local(me.secret_key(), &rotator.public_key(), RekeyScope::Root, Epoch(1), mine).unwrap(), [0xAAu8; 32]);
    }

    #[test]
    fn a_complete_rotation_without_my_blob_is_a_removal() {
        let rotator = keys(1);
        let me = keys(8);
        let other = keys(9);
        // A complete 1-chunk rotation carrying only someone else's blob.
        let their_blob = build_blob_local(rotator.secret_key(), &xonly(&rotator), &other.public_key(), RekeyScope::Root, Epoch(1), &[0xBBu8; 32]).unwrap();
        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![their_blob], 1, 1);
        let rots = collect_rotations(&[c]);
        assert!(rots[0].is_complete());
        assert_eq!(am_i_removed(&rots[0], &xonly(&me)), Some(true), "complete rotation, no blob for me → removed");
    }

    #[test]
    fn collect_rotations_separates_concurrent_rotators_and_scopes() {
        // Two rotators racing the same epoch, plus a channel rekey at the same
        // numbers — three distinct rotations, never merged.
        let rot_a = keys(1);
        let rot_b = keys(2);
        let ca = chunk_at(&rot_a, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
        let cb = chunk_at(&rot_b, RekeyScope::Root, 2, 1, &[7u8; 32], vec![], 1, 1);
        let cc = chunk_at(&rot_a, RekeyScope::Channel(CHAN), 2, 1, &[7u8; 32], vec![], 1, 1);
        let rots = collect_rotations(&[ca, cb, cc]);
        assert_eq!(rots.len(), 3, "different rotator or scope ⇒ different rotation");
    }

    #[test]
    fn duplicate_chunk_delivery_is_idempotent() {
        let rotator = keys(1);
        let blob = RekeyBlob { locator: "aa".repeat(32), wrapped: "x".into() };
        let c = chunk_at(&rotator, RekeyScope::Root, 1, 0, &[0u8; 32], vec![blob.clone()], 1, 1);
        let rots = collect_rotations(&[c.clone(), c]);
        assert_eq!(rots.len(), 1);
        assert_eq!(rots[0].blobs.len(), 1, "re-delivering a chunk must not double its blobs");
    }

    // ── base blob forms + control_wrap (CORD-06 §1, CORD-04 §3) ──────────────

    #[test]
    fn base_blob_forms_are_width_declared() {
        let community = CommunityId([0x77u8; 32]);
        let new_root = [0xABu8; 32];
        let control_root = [0x5Cu8; 32];
        let epoch = Epoch(3);
        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();

        // 104-byte member form: root + pk, no secret.
        let member = bound_base_plaintext(epoch, &new_root, &control_pk, None);
        assert_eq!(member.len(), 104);
        let d = parse_bound_base_plaintext(&member, &community, epoch).unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, Some(control_pk));
        assert_eq!(d.control_root, None);

        // 136-byte staff form carries the secret, verified against its own pk.
        let staff = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
        assert_eq!(staff.len(), 136);
        let d = parse_bound_base_plaintext(&staff, &community, epoch).unwrap();
        assert_eq!(d.control_root, Some(control_root));
        assert_eq!(d.control_pk, Some(control_pk));

        // Legacy 72-byte base form yields the root alone.
        let legacy = bound_plaintext(RekeyScope::Root, epoch, &new_root);
        let d = parse_bound_base_plaintext(&legacy, &community, epoch).unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, None);
        assert_eq!(d.control_root, None);
    }

    #[test]
    fn base_blob_mismatched_control_pair_is_refused_whole() {
        let community = CommunityId([0x77u8; 32]);
        let control_pk = control_signer_group_key(&[0x5Cu8; 32], &community, Epoch(3)).pk().to_bytes();
        // A secret that does NOT derive to the carried pk — the whole blob is
        // dropped, the new_root included (never a partial adoption).
        let bad = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &control_pk, Some(&[0x11u8; 32]));
        assert!(matches!(
            parse_bound_base_plaintext(&bad, &community, Epoch(3)),
            Err(RekeyError::ControlPairMismatch)
        ));
    }

    #[test]
    fn base_blob_rejects_any_other_width_and_splices() {
        let community = CommunityId([0x77u8; 32]);
        // Below and between the defined forms: no append-only extension fits.
        for n in [0usize, 71, 73, 100, 105, 135] {
            assert!(matches!(
                parse_bound_base_plaintext(&vec![0u8; n], &community, Epoch(1)),
                Err(RekeyError::BadBaseBlobWidth(m)) if m == n
            ));
        }
        // The scope and epoch bind INSIDE the ciphertext (unspliceable).
        let control_root = [0x5Cu8; 32];
        let pk = control_signer_group_key(&control_root, &community, Epoch(3)).pk().to_bytes();
        let pt = bound_base_plaintext(Epoch(3), &[0xABu8; 32], &pk, None);
        assert!(matches!(parse_bound_base_plaintext(&pt, &community, Epoch(4)), Err(RekeyError::EpochSplice)));
        let mut channel_scoped = pt.clone();
        channel_scoped[..32].copy_from_slice(&[0x42u8; 32]);
        assert!(matches!(parse_bound_base_plaintext(&channel_scoped, &community, Epoch(3)), Err(RekeyError::ScopeSplice)));
    }

    #[tokio::test]
    async fn base_blob_round_trips_member_and_staff_forms() {
        let rotator = keys(7);
        let member = keys(8);
        let staffer = keys(9);
        let community = CommunityId([0x77u8; 32]);
        let epoch = Epoch(2);
        let new_root = [0xEEu8; 32];
        let control_root = [0xDDu8; 32];
        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();

        let mb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), epoch, &new_root, &control_pk, None).await.unwrap();
        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &mb).await.unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, Some(control_pk));
        assert_eq!(d.control_root, None, "a member blob never carries the secret");

        let sb = build_base_blob(&as_signer(&rotator), &xonly(&rotator), &staffer.public_key(), epoch, &new_root, &control_pk, Some(&control_root)).await.unwrap();
        let d = open_base_blob(&as_signer(&staffer), &rotator.public_key(), &community, epoch, &sb).await.unwrap();
        assert_eq!(d.control_root, Some(control_root));

        // The locator is the same public Root-scope slot the legacy form used.
        assert_eq!(mb.locator, blob_locator(&xonly(&rotator), &xonly(&member), RekeyScope::Root, epoch));
        // And a legacy 72-byte blob still opens through the base opener.
        let legacy = build_blob(&as_signer(&rotator), &xonly(&rotator), &member.public_key(), RekeyScope::Root, epoch, &new_root).await.unwrap();
        let d = open_base_blob(&as_signer(&member), &rotator.public_key(), &community, epoch, &legacy).await.unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, None);
    }

    #[test]
    fn a_future_wider_base_blob_degrades_instead_of_forking() {
        // The pre-split lesson (CORD-06 §3): a width this build predates must
        // never park the member at the old epoch — extract the frozen prefix
        // and whatever appended fields still verify.
        let community = CommunityId([0x77u8; 32]);
        let new_root = [0xABu8; 32];
        let control_root = [0x5Cu8; 32];
        let epoch = Epoch(3);
        let control_pk = control_signer_group_key(&control_root, &community, epoch).pk().to_bytes();

        // A hypothetical 168-byte form that appended a field after the secret.
        let mut future = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&control_root));
        future.extend_from_slice(&[0x99u8; 32]);
        let d = parse_bound_base_plaintext(&future, &community, epoch).unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, Some(control_pk));
        assert_eq!(d.control_root, Some(control_root), "held offsets still verify → full function");

        // One that REPLACED the secret's bytes: the derive check fails closed
        // to the verified prefix, never a refusal (membership must survive).
        let mut reordered = bound_base_plaintext(epoch, &new_root, &control_pk, Some(&[0x44u8; 32]));
        reordered.extend_from_slice(&[0x99u8; 32]);
        let d = parse_bound_base_plaintext(&reordered, &community, epoch).unwrap();
        assert_eq!(d.new_root, new_root);
        assert_eq!(d.control_pk, Some(control_pk));
        assert_eq!(d.control_root, None, "an unverifiable secret is dropped, not adopted");

        // The prefix's splice bindings still gate a future form.
        assert!(parse_bound_base_plaintext(&future, &community, Epoch(4)).is_err());
    }

    #[test]
    fn control_wrap_layout_is_frozen_and_round_trips() {
        let pt = encode_control_wrap(Epoch(7), &[0xCDu8; 32]);
        assert_eq!(pt.len(), 40);
        let expected = format!("{}{}", "0000000000000007", "cd".repeat(32));
        assert_eq!(crate::simd::hex::bytes_to_hex_string(&pt), expected);
        let (epoch, root) = parse_control_wrap(&pt).unwrap();
        assert_eq!(epoch, Epoch(7));
        assert_eq!(root, [0xCDu8; 32]);
        for n in [0usize, 39, 41, 72] {
            assert!(matches!(parse_control_wrap(&vec![0u8; n]), Err(RekeyError::BadControlWrapLength(m)) if m == n));
        }
    }

    #[test]
    fn lowest_key_fork_winner_is_deterministic() {
        // CORD-06 §3: among candidates, the lexicographically lowest new key wins,
        // so every retained member converges. Input order must not change it.
        let keys_a = [[0x03u8; 32], [0x01u8; 32], [0x02u8; 32]];
        assert_eq!(lowest_key_winner(&keys_a), Some(1));
        let keys_b = [[0x01u8; 32], [0x02u8; 32], [0x03u8; 32]];
        assert_eq!(lowest_key_winner(&keys_b), Some(0));
        assert_eq!(lowest_key_winner(&[]), None);
    }
}