dig-account 0.26.2

The DIG Network user Account: the fat, strictly-logical crate for everything an account does — the Account+Profile object model, unlock policy + keystore crypto, the in-process identity+money signer, per-profile key/DEK derivation, DID+dig-store mint/sign, and all wallet ops. Headless (no UI). Consumed by dig-app.
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
//! [`ProfileRegistry`] — the offline, always-readable list of an account's profiles.

use crate::error::{AccountError, Result};
use crate::id::ProfileIx;
use crate::mint::{ConfirmedStore, MintedDid, MAX_MINT_FEE_MOJOS};
use crate::registry::active::{ActiveProfile, ActiveSwitch, ProfileEndOutcome};
use crate::registry::anchor::ProfileAnchor;
use crate::registry::entry::{ProfileEnd, ProfileEntry};
use crate::registry::journal::{MintStage, ProfileMintInProgress};
use crate::registry::visibility::ProfileVisibility;

/// The offline state of an account's profiles: what is confirmed, what is being minted, and which
/// profile is active.
///
/// Every read is available while the account is LOCKED — the registry holds no key material and no
/// method takes an unlocked value, a residency, or a chain source. A host can therefore list
/// profiles on its first frame, before any unlock ceremony (`tests/lists_while_locked.rs` proves
/// this by importing nothing else).
///
/// # The four invariants
///
/// Enforced on construction, on EVERY mutation, and on deserialize:
///
/// 1. **An index is confirmed or in progress, never both**, and never twice.
/// 2. **`active` is `Some` iff `entries` is non-empty**, and names a present entry. An account with
///    no confirmed profile has NO active slot; fabricating one would record a profile the chain has
///    not confirmed.
/// 3. **The active entry is always `Shown`.** A hidden active profile is a trap: the UI lists
///    nothing while the wallet keeps deriving and receiving there.
/// 4. **Indices are SPARSE.** Gaps are legal and nothing derives an index from `entries.len()`.
/// 5. **An identity is registered once.** No two confirmed entries claim the same DID launcher id.
///    A profile IS its on-chain identity, so two entries claiming one DID would derive two
///    different wallet keys and two different DEKs while presenting as the same person.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "RawProfileRegistry", into = "RawProfileRegistry")]
pub struct ProfileRegistry {
    /// Confirmed profiles, sorted by index, unique.
    entries: Vec<ProfileEntry>,
    /// The active profile's index, present iff `entries` is non-empty.
    active: Option<ProfileIx>,
    /// Mints that have started and not finished, sorted by index, unique.
    in_progress: Vec<ProfileMintInProgress>,
}

/// The on-disk shape, before validation.
///
/// It exists so the invariants are checked on the DESERIALIZE path too: a file is untrusted input,
/// and a registry that only enforced its rules in constructors would accept a hand-edited one.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct RawProfileRegistry {
    #[serde(default)]
    entries: Vec<ProfileEntry>,
    #[serde(default)]
    active: Option<ProfileIx>,
    #[serde(default)]
    in_progress: Vec<ProfileMintInProgress>,
}

impl From<ProfileRegistry> for RawProfileRegistry {
    fn from(registry: ProfileRegistry) -> Self {
        Self {
            entries: registry.entries,
            active: registry.active,
            in_progress: registry.in_progress,
        }
    }
}

impl TryFrom<RawProfileRegistry> for ProfileRegistry {
    type Error = String;

    fn try_from(raw: RawProfileRegistry) -> std::result::Result<Self, Self::Error> {
        let mut registry = Self {
            entries: raw.entries,
            active: raw.active,
            in_progress: raw.in_progress,
        };
        registry.entries.sort_by_key(ProfileEntry::ix);
        registry.in_progress.sort_by_key(ProfileMintInProgress::ix);
        registry.check()?;
        Ok(registry)
    }
}

impl ProfileRegistry {
    /// A registry for an account that has never minted: no profiles, and therefore no active slot.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Whether the account has no CONFIRMED profile. In-progress mints do not count — they are not
    /// profiles.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Every confirmed profile, ordered by index.
    pub fn entries(&self) -> &[ProfileEntry] {
        &self.entries
    }

    /// The confirmed profiles a host should offer in its lists: live AND not locally hidden.
    ///
    /// Liveness is checked here, not only visibility, because a host that listed an ended profile
    /// would be asserting a fact about the chain that is false (dig_ecosystem#3067).
    pub fn shown(&self) -> impl Iterator<Item = &ProfileEntry> {
        self.entries
            .iter()
            .filter(|entry| entry.is_live() && entry.is_shown())
    }

    /// Every profile that still exists on chain, ordered by index.
    ///
    /// Distinct from [`entries`](Self::entries), which includes ended profiles so a host can still
    /// render what the account used to be.
    pub fn live(&self) -> impl Iterator<Item = &ProfileEntry> {
        self.entries.iter().filter(|entry| entry.is_live())
    }

    /// The confirmed profile at `ix`, if any.
    pub fn get(&self, ix: ProfileIx) -> Option<&ProfileEntry> {
        self.entries.iter().find(|entry| entry.ix() == ix)
    }

    /// Whether a CONFIRMED profile exists at `ix`.
    pub fn contains(&self, ix: ProfileIx) -> bool {
        self.get(ix).is_some()
    }

    /// The active profile, or `None` when the account has no confirmed profile.
    ///
    /// The returned [`ActiveProfile`] borrows this registry, so the active slot cannot move while
    /// it is held (see [`ActiveProfile`]).
    pub fn active(&self) -> Option<ActiveProfile<'_>> {
        let ix = self.active?;
        self.get(ix).map(ActiveProfile::new)
    }

    /// Mints that have started and not finished, ordered by index.
    pub fn in_progress(&self) -> &[ProfileMintInProgress] {
        &self.in_progress
    }

    /// The index the NEXT mint should use: one past the highest index known, confirmed or in
    /// progress — or `None` when the index space is exhausted.
    ///
    /// # Why it can fail
    ///
    /// `ProfileIx` is a `u32`, so an account whose highest known index is `u32::MAX` has no next
    /// index. Returning the ceiling itself would hand the mint an OCCUPIED index, which
    /// [`record_minted`](Self::record_minted) then refuses forever — a silent, durable denial of
    /// the mint path rather than a reported one. `None` is the honest answer, and the type is what
    /// makes a caller confront it.
    ///
    /// # Why it never fills a gap
    ///
    /// A gap is not evidence that an index is free. This registry is one host's local view; an
    /// index that looks unused here may already hold a profile this host has not discovered
    /// (dig_ecosystem#2392). Minting there would produce a second profile at the same index —
    /// a state this registry cannot even represent, because invariant 1 forbids it — while the
    /// user pays twice.
    ///
    /// In-progress mints count for the same reason, and more urgently: the DID at that index is
    /// already paid for.
    #[must_use]
    pub fn next_free_ix(&self) -> Option<ProfileIx> {
        let highest = self
            .entries
            .iter()
            .map(ProfileEntry::ix)
            .chain(self.in_progress.iter().map(ProfileMintInProgress::ix))
            .max();
        match highest {
            // `checked_add`, never `saturating_add`: saturating at the ceiling returns the very
            // index the caller asked to avoid (dig-account#33).
            Some(ix) => ix.0.checked_add(1).map(ProfileIx),
            None => Some(ProfileIx::ROOT),
        }
    }

    /// Record a profile the chain has confirmed, from BOTH halves of its mint.
    ///
    /// It becomes the active profile when it is the account's first. Any in-progress mint at the
    /// same index is cleared: the mint it described has just finished.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileAlreadyRegistered`] if `ix` already names a confirmed profile. The
    /// existing entry is left untouched — re-recording would silently replace an anchor.
    ///
    /// [`AccountError::MismatchedMintHalves`] if `store` was not launched from `did`'s coin. The
    /// anchor is built BEFORE any mutation, so a refusal leaves the registry — including any
    /// journalled mint at `ix` — exactly as it was.
    pub fn record_minted(
        &mut self,
        ix: ProfileIx,
        did: &MintedDid,
        store: &ConfirmedStore,
        label: Option<String>,
    ) -> Result<&ProfileEntry> {
        if self.contains(ix) {
            return Err(AccountError::ProfileAlreadyRegistered(ix));
        }
        if let Some(existing) = self.holder_of(did.launcher_id()) {
            return Err(AccountError::ProfileIdentityAlreadyRegistered {
                existing,
                did: did.did().to_string(),
            });
        }

        let anchor = ProfileAnchor::from_confirmed(did, store)?;

        self.in_progress.retain(|mint| mint.ix() != ix);
        let entry = ProfileEntry::new(ix, anchor, label);
        let position = self.entries.partition_point(|e| e.ix() < ix);
        self.entries.insert(position, entry);
        if self.active.is_none() {
            self.active = Some(ix);
        }

        self.expect_valid();
        Ok(&self.entries[position])
    }

    /// Make `ix` the active profile, returning what changed so the host can disclose it.
    ///
    /// A hidden target is un-hidden: activating a profile the lists omit would otherwise leave the
    /// wallet deriving somewhere the user cannot see (invariant 3).
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if `ix` names no confirmed profile; the previous active
    /// profile is left unchanged (fail-closed).
    pub fn set_active(&mut self, ix: ProfileIx) -> Result<ActiveSwitch> {
        let Some(entry) = self.entries.iter_mut().find(|entry| entry.ix() == ix) else {
            return Err(AccountError::ProfileNotFound(ix));
        };
        if !entry.is_live() {
            return Err(AccountError::ProfileEnded(ix));
        }
        entry.set_visibility(ProfileVisibility::Shown);

        let switch = ActiveSwitch {
            from: self.active,
            to: ix,
        };
        self.active = Some(ix);
        self.expect_valid();
        Ok(switch)
    }

    /// Set whether `ix` is offered in the host's lists.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if `ix` names no confirmed profile, and
    /// [`AccountError::ActiveProfileCannotBeHidden`] when `ix` is the ACTIVE profile and `v` would
    /// hide it. In both cases the entry is left exactly as it was — fail-closed. Switch away first,
    /// then hide.
    pub fn set_visibility(&mut self, ix: ProfileIx, v: ProfileVisibility) -> Result<()> {
        if !self.contains(ix) {
            return Err(AccountError::ProfileNotFound(ix));
        }
        if v == ProfileVisibility::HiddenFromLists && self.active == Some(ix) {
            return Err(AccountError::ActiveProfileCannotBeHidden(ix));
        }

        self.entry_mut(ix).set_visibility(v);
        self.expect_valid();
        Ok(())
    }

    /// Record that `ix` ENDED on chain at `at_height` — both of its singletons melted, and the melts
    /// confirmed by a chain read (dig_ecosystem#3067).
    ///
    /// The entry is kept and marked ended rather than deleted, so the account can still say what it
    /// used to be. If `ix` was the ACTIVE profile the slot moves to the lowest-indexed remaining live
    /// profile, or is cleared when none remains — which is the state an account whose ONLY profile was
    /// deleted lands in, and the one the public surface previously had no way to express at all.
    ///
    /// Idempotent: recording an end on an already-ended profile changes nothing and returns `None`,
    /// so a host retrying after a crash mid-ceremony cannot move the active slot a second time.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if `ix` names no confirmed profile, and
    /// [`AccountError::ProfileEndHeightZero`] if `at_height` is 0 — a height of 0 is what an
    /// unconfirmed read looks like, and this record may only ever be written from a CONFIRMED melt.
    pub fn record_melted(&mut self, ix: ProfileIx, at_height: u32) -> Result<ProfileEndOutcome> {
        let end = ProfileEnd::at(at_height)?;
        let Some(entry) = self.entries.iter_mut().find(|entry| entry.ix() == ix) else {
            return Err(AccountError::ProfileNotFound(ix));
        };
        if !entry.is_live() {
            return Ok(ProfileEndOutcome::AlreadyEnded);
        }
        entry.end(end);

        if self.active != Some(ix) {
            self.expect_valid();
            return Ok(ProfileEndOutcome::Recorded);
        }

        let successor = self.live().next().map(ProfileEntry::ix);
        self.active = successor;
        self.expect_valid();
        Ok(match successor {
            Some(to) => ProfileEndOutcome::ActiveMoved(ActiveSwitch { from: Some(ix), to }),
            None => ProfileEndOutcome::NoLiveProfileRemains,
        })
    }

    /// Set (or clear, with `None`) the local label of `ix`.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if `ix` names no confirmed profile.
    pub fn set_label(&mut self, ix: ProfileIx, label: Option<String>) -> Result<()> {
        if !self.contains(ix) {
            return Err(AccountError::ProfileNotFound(ix));
        }
        self.entry_mut(ix).set_label(label);
        Ok(())
    }

    /// Reserve `ix` for a mint that has just started, at `stage`, with the disclosed `store_fee`.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileAlreadyRegistered`] if `ix` is already a confirmed profile, and
    /// [`AccountError::MintAlreadyInProgress`] if a mint is already journalled there — restarting
    /// one would re-mint a DID that may already be paid for.
    ///
    /// [`AccountError::MintFeeAboveCeiling`] if `store_fee` exceeds [`MAX_MINT_FEE_MOJOS`]. The
    /// journalled fee is what a resumed phase B may spend, so it is bounded by the same ceiling the
    /// DID half already enforces; [`check`](Self::check) applies it again on load, so the bound
    /// cannot be side-stepped by editing the file.
    pub fn begin_mint(&mut self, ix: ProfileIx, stage: MintStage, store_fee: u64) -> Result<()> {
        self.reserve(ProfileMintInProgress::new(ix, stage, store_fee))
    }

    /// Reserve `ix` for a PROFILE mint — a DID plus a store committed to `seed_root`.
    ///
    /// The same reservation as [`begin_mint`](Self::begin_mint), plus the seed root a resumed phase
    /// B needs to commit the store to the bytes the user actually chose (see
    /// [`ProfileMintInProgress::seed_root`]).
    ///
    /// # Errors
    ///
    /// Identical to [`begin_mint`](Self::begin_mint).
    pub fn begin_seeded_mint(
        &mut self,
        ix: ProfileIx,
        stage: MintStage,
        seed_root: [u8; 32],
        store_fee: u64,
    ) -> Result<()> {
        self.reserve(ProfileMintInProgress::with_seed_root(
            ix, stage, seed_root, store_fee,
        ))
    }

    /// Insert `mint` as the reservation of its index, after the checks both entry points share.
    fn reserve(&mut self, mint: ProfileMintInProgress) -> Result<()> {
        let ix = mint.ix();
        if self.contains(ix) {
            return Err(AccountError::ProfileAlreadyRegistered(ix));
        }
        if self.mint_position(ix).is_some() {
            return Err(AccountError::MintAlreadyInProgress(ix));
        }
        if mint.store_fee() > MAX_MINT_FEE_MOJOS {
            return Err(AccountError::MintFeeAboveCeiling {
                fee: mint.store_fee(),
                ceiling: MAX_MINT_FEE_MOJOS,
            });
        }

        let position = self.in_progress.partition_point(|m| m.ix() < ix);
        self.in_progress.insert(position, mint);
        self.expect_valid();
        Ok(())
    }

    /// Move the journalled mint at `ix` to a later stage.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if no mint is journalled at `ix`. A stage cannot be
    /// recorded for a mint that was never begun.
    pub fn advance_mint(&mut self, ix: ProfileIx, stage: MintStage) -> Result<()> {
        let Some(position) = self.mint_position(ix) else {
            return Err(AccountError::ProfileNotFound(ix));
        };
        self.in_progress[position].set_stage(stage);
        Ok(())
    }

    /// Forget the journalled mint at `ix`.
    ///
    /// This does NOT undo anything on chain: a DID already minted stays minted and stays paid for.
    /// It only stops this host tracking the attempt.
    ///
    /// # Errors
    ///
    /// [`AccountError::ProfileNotFound`] if no mint is journalled at `ix`.
    pub fn abandon_mint(&mut self, ix: ProfileIx) -> Result<()> {
        let Some(position) = self.mint_position(ix) else {
            return Err(AccountError::ProfileNotFound(ix));
        };
        self.in_progress.remove(position);
        self.expect_valid();
        Ok(())
    }

    /// Serialize to the on-disk JSON shape.
    ///
    /// # Errors
    ///
    /// [`AccountError::RegistryInvariant`] if serialization fails.
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(self)
            .map_err(|e| AccountError::RegistryInvariant(format!("serialize: {e}")))
    }

    /// Load from the on-disk JSON shape, re-checking every invariant.
    ///
    /// # Errors
    ///
    /// [`AccountError::RegistryInvariant`] if the JSON is malformed or violates an invariant. A
    /// registry is never partially loaded: an invalid file yields no registry at all rather than
    /// one a host would go on to act upon.
    pub fn from_json(json: &str) -> Result<Self> {
        serde_json::from_str(json).map_err(|e| AccountError::RegistryInvariant(e.to_string()))
    }

    /// The index of the confirmed profile whose identity is `launcher_id`, if any.
    ///
    /// The launcher id is the comparison key rather than the DID string because the string is
    /// DERIVED from it (`dig_did::did_string_from_launcher_id`): comparing the derived form would
    /// make the rule depend on an encoding, while the launcher id is the identity itself.
    fn holder_of(&self, launcher_id: chia_protocol::Bytes32) -> Option<ProfileIx> {
        self.entries
            .iter()
            .find(|entry| entry.anchor().launcher_id() == launcher_id)
            .map(ProfileEntry::ix)
    }

    /// The index of the journalled mint at `ix`, if any.
    fn mint_position(&self, ix: ProfileIx) -> Option<usize> {
        self.in_progress.iter().position(|mint| mint.ix() == ix)
    }

    /// The entry at `ix`, which the caller has already established is present.
    fn entry_mut(&mut self, ix: ProfileIx) -> &mut ProfileEntry {
        self.entries
            .iter_mut()
            .find(|entry| entry.ix() == ix)
            .expect("the caller checked the entry is present")
    }

    /// Re-check the four invariants after a mutation.
    ///
    /// A violation here is a bug in this module, never bad input — every public mutator refuses its
    /// bad cases before touching state — so it panics rather than returning an error a caller could
    /// swallow while carrying on with a corrupt registry.
    fn expect_valid(&self) {
        self.check()
            .expect("a ProfileRegistry mutation broke an invariant");
    }

    /// The invariants, as one check shared by construction, mutation and deserialization.
    ///
    /// Beyond the four (§2.4.1) it also enforces the two properties a FILE could otherwise state
    /// freely, because a file is untrusted input:
    ///
    /// - **Each anchor's DID string belongs to its launcher id.** The string is DERIVED, never
    ///   accepted from a caller (`MintedDid::from_confirmed`), so it is the one evidence property
    ///   that is checkable offline — and it is re-derived here with the same
    ///   `dig_did::did_string_from_launcher_id` the constructor uses, so the two cannot drift. This
    ///   closes a STRING SPOOF and nothing more: an attacker who computes the correct string for a
    ///   launcher id still loads a fabricated anchor. Asking a chain source
    ///   ([`verify_anchor`](crate::registry::verify_anchor)) raises the cost but does not close it
    ///   either — that pass checks the named coins EXIST at the claimed heights and does not bind
    ///   them to this anchor's identity, which is dig-account#37.
    /// - **No journalled mint discloses a store fee above the mint's ceiling**, so the bound
    ///   [`begin_mint`](Self::begin_mint) applies cannot be side-stepped by editing the file a
    ///   resumed phase B reads its spending limit from.
    /// - **The same DID binding holds for every DID the JOURNAL carries**, on every
    ///   [`MintStage`](crate::registry::MintStage) that carries one. A journalled DID is not inert
    ///   bookkeeping: `DidConfirmedStoreNotLaunched` tells the resume path to launch the store from
    ///   THAT record's DID coin, so a file that could redirect it would redirect a spend. Bounding
    ///   the fee beside an unchecked identity would be an asymmetry, not a scope boundary.
    /// - **No confirmation height is 0**, for anchors, journalled DIDs and recorded ENDS alike
    ///   (`ProfileEnd` derives `Deserialize`, so a file reaches the field without passing
    ///   `ProfileEnd::at`, and this is where the constructor and the deserializer agree). No
    ///   coin is created
    ///   in the genesis block, so a `0` is fabricated — the same reasoning
    ///   [`MintedDid::from_confirmed`](crate::mint::MintedDid::from_confirmed) applies to live
    ///   evidence, applied to the file that outlives it. Unlike fabrication in general this one IS
    ///   checkable offline, so there is no reason to wait for chain re-verification.
    fn check(&self) -> std::result::Result<(), String> {
        let mut seen = std::collections::BTreeSet::new();
        for ix in self
            .entries
            .iter()
            .map(ProfileEntry::ix)
            .chain(self.in_progress.iter().map(ProfileMintInProgress::ix))
        {
            if !seen.insert(ix) {
                return Err(format!(
                    "index {ix} appears twice: an index is confirmed or in progress, never both"
                ));
            }
        }

        // Invariant 2 is stated over the LIVE entries, not all of them: an account whose every
        // profile has ended has nothing it could honestly point at, and inventing an active slot
        // there would claim a profile the chain has retired is still in use (dig_ecosystem#3067).
        match (self.active, self.live().next().is_none()) {
            (None, false) => {
                return Err("live entries are present but no profile is active".to_string())
            }
            (Some(ix), true) => {
                return Err(format!(
                    "profile {ix} is active but the registry has no live profile"
                ))
            }
            (Some(ix), false) => {
                let Some(entry) = self.get(ix) else {
                    return Err(format!("the active index {ix} names no confirmed profile"));
                };
                if !entry.is_live() {
                    return Err(format!(
                        "the active profile {ix} has ended on chain, so every surface reading it \
                         would assert a profile that no longer exists"
                    ));
                }
                if !entry.is_shown() {
                    return Err(format!(
                        "the active profile {ix} is hidden, which would list nothing while the \
                         wallet derives there"
                    ));
                }
            }
            (None, true) => {}
        }

        let mut identities = std::collections::BTreeMap::new();
        for entry in &self.entries {
            if let Some(first) = identities.insert(entry.anchor().launcher_id(), entry.ix()) {
                return Err(format!(
                    "profiles {first} and {second} both claim identity {did}; one DID cannot be two profiles, because each index derives its own wallet key and its own DEK",
                    second = entry.ix(),
                    did = entry.anchor().did()
                ));
            }
        }

        for entry in &self.entries {
            let anchor = entry.anchor();
            let ix = entry.ix();
            let honest = dig_did::did_string_from_launcher_id(anchor.launcher_id());
            if anchor.did() != honest {
                return Err(format!(
                    "profile {ix}'s DID string does not belong to its launcher id"
                ));
            }
            if anchor.did_confirmed_height() == 0 {
                return Err(format!(
                    "profile {ix}'s did_confirmed_height is 0, which no on-chain confirmation can \
                     produce; MintedDid::from_confirmed refuses it"
                ));
            }
            if anchor.store_confirmed_height() == 0 {
                return Err(format!(
                    "profile {ix}'s store_confirmed_height is 0, which no on-chain confirmation \
                     can produce; ConfirmedStore::from_confirmed refuses it"
                ));
            }
            if !anchor.pairing_holds() {
                return Err(format!(
                    "profile {ix}'s store was launched from DID coin {launched_from}, not from its own DID coin {did_coin}; the two halves are not one mint",
                    launched_from = anchor
                        .store_launched_from()
                        .expect("pairing_holds is only false when the coin is recorded"),
                    did_coin = anchor.did_coin_id()
                ));
            }
            if entry.ended().is_some_and(|end| end.at_height() == 0) {
                return Err(format!(
                    "profile {ix}'s end height is 0, which no confirmed melt can produce; \
                     ProfileEnd::at refuses it"
                ));
            }
        }

        for mint in &self.in_progress {
            let ix = mint.ix();
            if mint.store_fee() > MAX_MINT_FEE_MOJOS {
                return Err(format!(
                    "the mint journalled at {ix} discloses a store fee of {fee} mojos, above the \
                     {MAX_MINT_FEE_MOJOS} mojo ceiling",
                    fee = mint.store_fee()
                ));
            }
            for did in mint.stage().minted_dids() {
                let honest = dig_did::did_string_from_launcher_id(did.launcher_id);
                if did.did != honest {
                    return Err(format!(
                        "the DID journalled at {ix} does not belong to its launcher id"
                    ));
                }
                if did.confirmed_height == 0 {
                    return Err(format!(
                        "the DID journalled at {ix} claims to have confirmed at height 0"
                    ));
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mint::fixtures::{bound_mint, minted_did};

    /// Record a profile at `ix`, panicking on the invariant errors this helper's callers never hit.
    fn record(registry: &mut ProfileRegistry, ix: u32) {
        let (did, store) = bound_mint(ix as u8);
        registry
            .record_minted(ProfileIx(ix), &did, &store, None)
            .expect("the fixture index is free");
    }

    fn with_profiles(indices: &[u32]) -> ProfileRegistry {
        let mut registry = ProfileRegistry::empty();
        for &ix in indices {
            record(&mut registry, ix);
        }
        registry
    }

    fn a_stage() -> MintStage {
        MintStage::DidConfirmedStoreNotLaunched {
            did: (&minted_did(9)).into(),
        }
    }

    /// An account that has never minted has no active profile. Inventing one would assert a
    /// profile the chain has not confirmed.
    #[test]
    fn an_empty_registry_has_no_active_slot() {
        let registry = ProfileRegistry::empty();
        assert!(registry.is_empty());
        assert!(registry.active().is_none());
        assert_eq!(registry.entries(), &[]);
    }

    /// The first confirmed profile takes the active slot, because an account with a profile and no
    /// active one has no usable state.
    #[test]
    fn the_first_recorded_profile_becomes_active() {
        let registry = with_profiles(&[0]);
        assert_eq!(registry.active().map(ActiveProfile::ix), Some(ProfileIx(0)));
    }

    /// The CONTROL for the test above: without it, "becomes active" could equally mean "whatever
    /// was recorded last is active", which would silently move a user's identity under them.
    #[test]
    fn a_second_profile_does_not_steal_the_active_slot() {
        let registry = with_profiles(&[0, 1]);
        assert_eq!(registry.active().map(ActiveProfile::ix), Some(ProfileIx(0)));
    }

    /// Re-recording an index is refused and the existing entry stands — an anchor is evidence of a
    /// specific on-chain mint, so overwriting one would replace a proof with a different proof.
    #[test]
    fn an_index_cannot_be_registered_twice() {
        let mut registry = ProfileRegistry::empty();
        let (did, store) = bound_mint(1);
        registry
            .record_minted(ProfileIx(0), &did, &store, Some("first".into()))
            .unwrap();
        let before = registry.get(ProfileIx(0)).unwrap().clone();

        let (other_did, other_store) = bound_mint(2);
        let result = registry.record_minted(ProfileIx(0), &other_did, &other_store, None);

        assert!(matches!(
            result,
            Err(AccountError::ProfileAlreadyRegistered(ProfileIx(0)))
        ));
        assert_eq!(registry.get(ProfileIx(0)), Some(&before));
        assert_eq!(registry.entries().len(), 1);
    }

    /// Invariant 3, fail-closed: hiding the ACTIVE profile is refused and it stays shown. Allowing
    /// it would list nothing while the wallet kept deriving and receiving at that index.
    #[test]
    fn hiding_the_active_profile_is_refused_and_leaves_it_shown() {
        let mut registry = with_profiles(&[0]);

        let result = registry.set_visibility(ProfileIx(0), ProfileVisibility::HiddenFromLists);

        assert!(matches!(
            result,
            Err(AccountError::ActiveProfileCannotBeHidden(ProfileIx(0)))
        ));
        assert!(registry.get(ProfileIx(0)).unwrap().is_shown());
        assert_eq!(registry.shown().count(), 1);
    }

    /// Without this, the rule above is bypassable in two moves: hide a non-active profile, then
    /// activate it. Activation un-hides.
    #[test]
    fn activating_a_hidden_profile_unhides_it() {
        let mut registry = with_profiles(&[0, 1]);
        registry
            .set_visibility(ProfileIx(1), ProfileVisibility::HiddenFromLists)
            .unwrap();
        assert!(!registry.get(ProfileIx(1)).unwrap().is_shown());

        let _switch = registry.set_active(ProfileIx(1)).unwrap();

        assert!(registry.get(ProfileIx(1)).unwrap().is_shown());
        assert_eq!(registry.shown().count(), 2);
    }

    /// The switch names both ends, because the host must disclose that the receive address, the
    /// per-profile DEK and the signing key have all moved.
    #[test]
    fn set_active_returns_the_switch_the_host_must_disclose() {
        let mut registry = with_profiles(&[0, 4]);

        let switch = registry.set_active(ProfileIx(4)).unwrap();

        assert_eq!(
            switch,
            ActiveSwitch {
                from: Some(ProfileIx(0)),
                to: ProfileIx(4)
            }
        );
    }

    /// A switch to an absent index changes nothing (fail-closed).
    #[test]
    fn set_active_rejects_an_absent_index_and_leaves_the_active_profile_unchanged() {
        let mut registry = with_profiles(&[0]);

        let result = registry.set_active(ProfileIx(7));

        assert!(matches!(result, Err(AccountError::ProfileNotFound(_))));
        assert_eq!(registry.active().map(ActiveProfile::ix), Some(ProfileIx(0)));
    }

    /// **Regression (dig-account#28, #32): one identity, two indices.**
    ///
    /// `record_minted` refused only a repeated INDEX, so the same `MintedDid` recorded at two
    /// indices produced two entries claiming one DID — two wallet keys and two DEKs for one
    /// person. The control below records a genuinely different mint at the same index that was
    /// just refused, so the refusal is the identity rule and not the index being unavailable.
    #[test]
    fn recording_one_identity_at_a_second_index_is_refused() {
        let (did, store) = bound_mint(1);
        let mut registry = ProfileRegistry::empty();
        registry
            .record_minted(ProfileIx(0), &did, &store, None)
            .expect("the first profile records");

        let result = registry.record_minted(ProfileIx(1), &did, &store, None);

        assert!(
            matches!(
                &result,
                Err(AccountError::ProfileIdentityAlreadyRegistered { existing, did: claimed })
                    if *existing == ProfileIx(0) && claimed == did.did()
            ),
            "the refusal must name the index that already holds the identity: {result:?}"
        );
        assert_eq!(
            registry.entries().len(),
            1,
            "a refused record must leave the registry exactly as it was"
        );

        let (other_did, other_store) = bound_mint(5);
        assert_ne!(other_did.launcher_id(), did.launcher_id());
        registry
            .record_minted(ProfileIx(1), &other_did, &other_store, None)
            .expect(
                "a DIFFERENT identity at that same index records, so the refusal was the identity",
            );
    }

    /// Invariant 4: a gap is not evidence that an index is free — it may hold a profile this host
    /// has not discovered — so the next mint goes past everything known.
    #[test]
    fn next_free_ix_skips_gaps_rather_than_filling_them() {
        let registry = with_profiles(&[0, 3]);
        assert_eq!(registry.next_free_ix(), Some(ProfileIx(4)));
    }

    /// An in-progress mint reserves its index just as firmly as a confirmed profile: the DID there
    /// may already be paid for.
    #[test]
    fn next_free_ix_counts_in_progress_mints() {
        let mut registry = with_profiles(&[0]);
        registry.begin_mint(ProfileIx(1), a_stage(), 1_000).unwrap();

        assert_eq!(registry.next_free_ix(), Some(ProfileIx(2)));
    }

    /// **The double-spend test. Do not delete this as redundant with the two above** — they cover
    /// gaps and counting, this covers the case that costs money: an app that restarted and forgot
    /// an in-flight mint would mint at index 1 again, paying a second time for a DID the user
    /// already owns and orphaning the first (dig_ecosystem#2377).
    #[test]
    fn an_amnesiac_restart_does_not_re_mint_at_the_same_index() {
        let mut registry = ProfileRegistry::empty();
        registry.begin_mint(ProfileIx(1), a_stage(), 1_000).unwrap();

        assert_eq!(registry.next_free_ix(), Some(ProfileIx(2)));
    }

    /// **Regression (dig-account#29, #33): the index ceiling wedged the mint path forever.**
    ///
    /// `next_free_ix` saturated, so a registry whose highest known index was `u32::MAX` handed the
    /// mint back that same OCCUPIED index, which `record_minted` then refused on every attempt —
    /// a permanent, silent denial living in durable state.
    ///
    /// The bound is pinned from BOTH sides in one test on purpose: the `MAX - 1` case is what
    /// stops the fix being "always return `None`", and it is the index immediately below the
    /// ceiling rather than a comfortable small one, so an off-by-one in the guard is visible.
    #[test]
    fn next_free_ix_reports_exhaustion_only_at_the_ceiling() {
        let mut at_ceiling = ProfileRegistry::empty();
        at_ceiling
            .begin_mint(ProfileIx(u32::MAX), a_stage(), 1_000)
            .unwrap();
        assert_eq!(
            at_ceiling.next_free_ix(),
            None,
            "there is no index past u32::MAX, and answering with the occupied ceiling wedges every future mint"
        );

        let mut below_ceiling = ProfileRegistry::empty();
        below_ceiling
            .begin_mint(ProfileIx(u32::MAX - 1), a_stage(), 1_000)
            .unwrap();
        assert_eq!(
            below_ceiling.next_free_ix(),
            Some(ProfileIx(u32::MAX)),
            "the last index is still mintable, so the refusal above is the ceiling and not a function that stopped answering"
        );
    }

    /// A begun mint is not a profile: it is absent from every confirmed-profile read.
    #[test]
    fn a_did_confirmed_mint_is_not_a_profile() {
        let mut registry = ProfileRegistry::empty();
        registry.begin_mint(ProfileIx(0), a_stage(), 1_000).unwrap();

        assert!(registry.is_empty());
        assert_eq!(registry.entries(), &[]);
        assert_eq!(registry.shown().count(), 0);
        assert!(registry.get(ProfileIx(0)).is_none());
        assert!(registry.active().is_none());
        assert_eq!(registry.in_progress().len(), 1);
    }

    /// Invariant 1: recording the profile the mint was for clears the journal entry, so the index
    /// is never both confirmed and pending.
    #[test]
    fn completing_a_mint_moves_the_index_out_of_in_progress() {
        let mut registry = ProfileRegistry::empty();
        registry.begin_mint(ProfileIx(2), a_stage(), 1_000).unwrap();

        record(&mut registry, 2);

        assert!(registry.in_progress().is_empty());
        assert!(registry.contains(ProfileIx(2)));
    }

    #[test]
    fn a_mint_cannot_be_begun_twice_at_one_index() {
        let mut registry = ProfileRegistry::empty();
        registry.begin_mint(ProfileIx(0), a_stage(), 1_000).unwrap();

        let result = registry.begin_mint(ProfileIx(0), a_stage(), 1_000);

        assert!(matches!(
            result,
            Err(AccountError::MintAlreadyInProgress(ProfileIx(0)))
        ));
    }

    #[test]
    fn a_mint_advances_and_can_be_abandoned() {
        let mut registry = ProfileRegistry::empty();
        registry.begin_mint(ProfileIx(0), a_stage(), 1_000).unwrap();

        let later = MintStage::DidPushed {
            pending: crate::registry::journal::PendingMintRecord {
                launcher_id: chia_protocol::Bytes32::new([1; 32]),
                did_coin_id: chia_protocol::Bytes32::new([2; 32]),
                source_coin_id: chia_protocol::Bytes32::new([3; 32]),
                pushed_at_height: 10,
            },
        };
        registry.advance_mint(ProfileIx(0), later.clone()).unwrap();
        assert_eq!(registry.in_progress()[0].stage(), &later);

        registry.abandon_mint(ProfileIx(0)).unwrap();
        assert!(registry.in_progress().is_empty());
        assert!(matches!(
            registry.abandon_mint(ProfileIx(0)),
            Err(AccountError::ProfileNotFound(_))
        ));
    }

    /// **The disclosed store fee is a spend ceiling, so it is bounded — from BOTH sides.** One mojo
    /// over is refused and exactly at the ceiling is accepted; a bound tested only from below can
    /// confirm nothing but itself. The same constant the DID half enforces, deliberately: a
    /// different limit for the second bundle would be a design decision, not a bound.
    #[test]
    fn a_journalled_store_fee_is_bounded_by_the_mint_ceiling() {
        let mut registry = ProfileRegistry::empty();

        let result = registry.begin_mint(ProfileIx(0), a_stage(), MAX_MINT_FEE_MOJOS + 1);
        assert!(
            matches!(
                result,
                Err(AccountError::MintFeeAboveCeiling { fee, ceiling })
                    if fee == MAX_MINT_FEE_MOJOS + 1 && ceiling == MAX_MINT_FEE_MOJOS
            ),
            "a fee above the ceiling must be refused: {result:?}"
        );
        assert!(
            registry.in_progress().is_empty(),
            "a refused mint reserves nothing"
        );

        registry
            .begin_mint(ProfileIx(0), a_stage(), MAX_MINT_FEE_MOJOS)
            .expect("exactly at the ceiling is allowed");
    }

    #[test]
    fn a_label_can_be_set_and_cleared() {
        let mut registry = with_profiles(&[0]);

        registry
            .set_label(ProfileIx(0), Some("work".into()))
            .unwrap();
        assert_eq!(registry.get(ProfileIx(0)).unwrap().label(), Some("work"));

        registry.set_label(ProfileIx(0), None).unwrap();
        assert_eq!(registry.get(ProfileIx(0)).unwrap().label(), None);
        assert!(matches!(
            registry.set_label(ProfileIx(9), None),
            Err(AccountError::ProfileNotFound(_))
        ));
    }

    /// A round trip preserves every field, and a `visibility` absent from the file reads back as
    /// `Shown` rather than failing the load.
    #[test]
    fn a_registry_round_trips_through_json() {
        let mut registry = with_profiles(&[0, 3]);
        registry
            .set_label(ProfileIx(3), Some("side".into()))
            .unwrap();
        registry
            .set_visibility(ProfileIx(3), ProfileVisibility::HiddenFromLists)
            .unwrap();
        registry.begin_mint(ProfileIx(5), a_stage(), 7_000).unwrap();

        let json = registry.to_json().unwrap();
        assert_eq!(ProfileRegistry::from_json(&json).unwrap(), registry);

        let stripped = json.replace(",\"visibility\":\"Shown\"", "");
        assert_ne!(stripped, json, "the fixture must contain a Shown entry");
        let loaded = ProfileRegistry::from_json(&stripped).unwrap();
        assert!(loaded.get(ProfileIx(0)).unwrap().is_shown());
    }

    /// The four deserialize rejections are driven from RAW JSON, not from constructed values:
    /// constructing them would prove something about the constructors, which already refuse these
    /// shapes, and nothing at all about the file path a hand-edited registry arrives through.
    mod deserialize_rejections {
        use super::*;

        /// A whole registry file, exactly as dig-account 0.8.1 wrote it under chia-protocol **0.26**.
        ///
        /// Committed as a literal for the same reason as the anchor fixture in `registry::anchor`:
        /// a string the current code generates can only agree with the current code. This is the
        /// file on a user's disk.
        const REGISTRY_JSON_0_26: &str = r#"{"entries":[{"ix":0,"anchor":{"did":"did:chia:1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqscdhf6s","launcher_id":"0x0101010101010101010101010101010101010101010101010101010101010101","did_coin_id":"0x0202020202020202020202020202020202020202020202020202020202020202","did_confirmed_height":4200000,"store_launcher_id":"0x0303030303030303030303030303030303030303030303030303030303030303","store_confirmed_height":4200001},"label":null,"visibility":"Shown"}],"active":0,"in_progress":[]}"#;

        /// **The on-disk registry survives the chia 0.26 -> 0.36.1 family migration unchanged.**
        ///
        /// `registry::anchor` proves the anchor's own encoding is stable; this proves the shape a
        /// host actually loads — entries, the active slot, the mint journal — is stable too, and
        /// that it still passes the invariant re-check the deserialize path performs. Losing this
        /// file loses every profile the account owns, and only a real on-chain mint restores one.
        ///
        /// Both directions are asserted: reading is what protects the file that already exists,
        /// re-writing byte-identically is what protects the version that wrote it from being unable
        /// to read the file this host writes back.
        #[test]
        fn a_registry_written_before_the_chia_0_36_migration_still_round_trips_byte_identically() {
            let registry = ProfileRegistry::from_json(REGISTRY_JSON_0_26)
                .expect("a registry written by 0.8.1 must still load, invariants and all");

            assert_eq!(
                registry.active().map(|entry| entry.ix()),
                Some(ProfileIx(0))
            );
            assert_eq!(registry.entries().len(), 1);

            assert_eq!(
                registry.to_json().expect("a loaded registry always serializes"),
                REGISTRY_JSON_0_26,
                "the new chia family must re-emit the OLD encoding, or the file this host writes becomes unreadable to the version that wrote the fixture"
            );
        }

        /// The launcher id every fixture anchor claims.
        const LAUNCHER_ID: [u8; 32] = [1; 32];

        /// The DID string that HONESTLY belongs to [`LAUNCHER_ID`], derived rather than typed —
        /// a literal here would drift from the derivation the check uses and the fixture would
        /// start failing for the wrong reason.
        fn honest_did() -> String {
            dig_did::did_string_from_launcher_id(chia_protocol::Bytes32::new(LAUNCHER_ID))
        }

        /// [`LAUNCHER_ID`] as the hex string serde emits for a `Bytes32`.
        const LAUNCHER_HEX: &str =
            "0x0101010101010101010101010101010101010101010101010101010101010101";
        const COIN_HEX: &str = "0x0202020202020202020202020202020202020202020202020202020202020202";

        fn anchor(did: &str) -> String {
            anchor_confirmed_at(did, 10, 11)
        }

        /// An entry at `ix` whose identity is `launcher`, with its DID string DERIVED so the only
        /// thing that varies between two such entries is the identity itself.
        fn entry_with_identity(ix: u32, launcher: [u8; 32]) -> String {
            let launcher_id = chia_protocol::Bytes32::new(launcher);
            let did = dig_did::did_string_from_launcher_id(launcher_id);
            let anchor = format!(
                r#"{{
            "did": "{did}",
            "launcher_id": "{launcher_id}",
            "did_coin_id": "{COIN_HEX}",
            "did_confirmed_height": 10,
            "store_launcher_id": "0x0303030303030303030303030303030303030303030303030303030303030303",
            "store_confirmed_height": 11
        }}"#
            );
            wrap_entry(ix, "Shown", anchor)
        }

        /// An entry at `ix` whose store claims to have been launched from `launched_from`.
        fn entry_launched_from(ix: u32, launched_from: &str) -> String {
            let did = honest_did();
            let anchor = format!(
                r#"{{
            "did": "{did}",
            "launcher_id": "{LAUNCHER_HEX}",
            "did_coin_id": "{COIN_HEX}",
            "did_confirmed_height": 10,
            "store_launcher_id": "0x0303030303030303030303030303030303030303030303030303030303030303",
            "store_confirmed_height": 11,
            "store_launched_from": "{launched_from}"
        }}"#
            );
            wrap_entry(ix, "Shown", anchor)
        }

        fn two_entries(first: String, second: String) -> String {
            format!(r#"{{"entries":[{first},{second}],"active":0,"in_progress":[]}}"#)
        }

        /// **Regression (dig-account#28, #32) on the FILE path.** The in-process guard lives in
        /// `record_minted`; a registry is persisted by the host and can be hand-edited, so the same
        /// rule has to hold on deserialize or it holds only where nobody was going to break it.
        ///
        /// The control varies exactly one thing — the second entry's launcher id — so a rejection
        /// cannot be a registry that refuses two entries in general.
        #[test]
        fn a_file_claiming_one_identity_at_two_indices_is_rejected() {
            assert_rejected(
                two_entries(
                    entry_with_identity(0, [1; 32]),
                    entry_with_identity(1, [1; 32]),
                ),
                "claiming one identity at two indices",
            );

            let distinct = two_entries(
                entry_with_identity(0, [1; 32]),
                entry_with_identity(1, [2; 32]),
            );
            assert!(
                ProfileRegistry::from_json(&distinct).is_ok(),
                "two DIFFERENT identities at two indices are an ordinary multi-profile account"
            );
        }

        /// **Regression (dig-account#34): the pairing check was construction-only.**
        ///
        /// `ProfileAnchor::from_confirmed` proves the store was launched from THIS DID's coin and
        /// then discarded the evidence, so `check()` had nothing to re-derive it from and a file
        /// could pair any DID with any store. The anchor now persists the launch coin, and the
        /// rule is re-run on every load.
        #[test]
        fn a_file_whose_store_was_launched_from_another_did_coin_is_rejected() {
            const STRANGER: &str =
                "0x0909090909090909090909090909090909090909090909090909090909090909";
            assert_ne!(STRANGER, COIN_HEX, "the fixture must genuinely differ");

            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                    entry_launched_from(0, STRANGER)
                ),
                "whose store was launched from another DID's coin",
            );

            let paired = format!(
                r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                entry_launched_from(0, COIN_HEX)
            );
            assert!(
                ProfileRegistry::from_json(&paired).is_ok(),
                "an anchor whose store WAS launched from its own DID coin must still load"
            );
        }

        /// A registry written before dig-account 0.22 records no launch coin, and must still load:
        /// absence is an old FILE, not a failed pairing, and refusing it would lose the user an
        /// identity that costs real XCH to recreate (CLAUDE.md §5.1).
        ///
        /// Paired with the rejection above, this is what stops the new rule being read as
        /// "an anchor without the field is unpaired".
        #[test]
        fn a_registry_written_before_the_launch_coin_field_still_loads() {
            let json = format!(
                r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                entry(0, "Shown")
            );
            let registry =
                ProfileRegistry::from_json(&json).expect("a pre-0.22 registry must still load");
            assert_eq!(
                registry.entries()[0].anchor().store_launched_from(),
                None,
                "the old file records no launch coin, and nothing may invent one for it"
            );
        }

        fn anchor_confirmed_at(did: &str, did_height: u32, store_height: u32) -> String {
            format!(
                r#"{{
            "did": "{did}",
            "launcher_id": "{LAUNCHER_HEX}",
            "did_coin_id": "{COIN_HEX}",
            "did_confirmed_height": {did_height},
            "store_launcher_id": "0x0303030303030303030303030303030303030303030303030303030303030303",
            "store_confirmed_height": {store_height}
        }}"#
            )
        }

        fn entry(ix: u32, visibility: &str) -> String {
            entry_claiming(ix, visibility, &honest_did())
        }

        fn entry_claiming(ix: u32, visibility: &str, did: &str) -> String {
            wrap_entry(ix, visibility, anchor(did))
        }

        fn entry_confirmed_at(ix: u32, did_height: u32, store_height: u32) -> String {
            wrap_entry(
                ix,
                "Shown",
                anchor_confirmed_at(&honest_did(), did_height, store_height),
            )
        }

        fn wrap_entry(ix: u32, visibility: &str, anchor: String) -> String {
            format!(r#"{{"ix":{ix},"anchor":{anchor},"label":null,"visibility":"{visibility}"}}"#)
        }

        /// A journalled `MintedDidRecord` claiming `did` and `confirmed_height`, against the same
        /// launcher id [`honest_did`] derives from — so a rejection can only be the field varied.
        fn did_record(did: &str, confirmed_height: u32) -> String {
            format!(
                r#"{{"did":"{did}","launcher_id":"{LAUNCHER_HEX}","coin_id":"{COIN_HEX}",
                    "confirmed_height":{confirmed_height}}}"#
            )
        }

        /// The stage that carries NO DID record, as a truthful control: it must keep loading, or a
        /// journal check that simply refused everything would look like a working rule.
        fn did_pushed_stage() -> String {
            format!(
                r#"{{"DidPushed":{{"pending":{{"launcher_id":"{LAUNCHER_HEX}",
                    "did_coin_id":"{COIN_HEX}","source_coin_id":"{COIN_HEX}",
                    "pushed_at_height":100}}}}}}"#
            )
        }

        fn did_confirmed_stage(did: &str, confirmed_height: u32) -> String {
            format!(
                r#"{{"DidConfirmedStoreNotLaunched":{{"did":{}}}}}"#,
                did_record(did, confirmed_height)
            )
        }

        fn store_pushed_stage(did: &str, confirmed_height: u32) -> String {
            let root = format!("{:?}", [7u8; 32]);
            format!(
                r#"{{"StorePushed":{{"did":{did_record},"pending_store":{{
                    "launcher_id":"{LAUNCHER_HEX}","store_coin_id":"{COIN_HEX}",
                    "did_coin_id":"{COIN_HEX}","committed_root":{root},
                    "pushed_at_height":100}}}}}}"#,
                did_record = did_record(did, confirmed_height)
            )
        }

        fn journalled(ix: u32, stage: String, store_fee: u64) -> String {
            format!(r#"{{"ix":{ix},"stage":{stage},"store_fee":{store_fee}}}"#)
        }

        fn pending(ix: u32) -> String {
            pending_with_fee(ix, 1_000)
        }

        fn pending_with_fee(ix: u32, store_fee: u64) -> String {
            journalled(ix, did_confirmed_stage(&honest_did(), 10), store_fee)
        }

        /// A registry carrying exactly one journalled mint at the stage given.
        fn registry_with_stage(stage: String) -> String {
            format!(
                r#"{{"entries":[],"active":null,"in_progress":[{}]}}"#,
                journalled(1, stage, 1_000)
            )
        }

        fn assert_rejected(json: String, because: &str) {
            let result = ProfileRegistry::from_json(&json);
            assert!(
                matches!(result, Err(AccountError::RegistryInvariant(_))),
                "a registry {because} must not load, got {result:?}"
            );
        }

        /// The control: the same shape, valid, DOES load — so each rejection below is the rule it
        /// names rather than a malformed fixture.
        #[test]
        fn a_valid_registry_loads() {
            let json = format!(
                r#"{{"entries":[{}],"active":0,"in_progress":[{}]}}"#,
                entry(0, "Shown"),
                pending(1)
            );
            let registry = ProfileRegistry::from_json(&json).expect("the control fixture is valid");
            assert_eq!(registry.entries().len(), 1);
            assert_eq!(registry.in_progress().len(), 1);
        }

        #[test]
        fn a_duplicate_index_is_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[{},{}],"active":0,"in_progress":[]}}"#,
                    entry(0, "Shown"),
                    entry(0, "Shown")
                ),
                "with the same index twice",
            );
        }

        #[test]
        fn an_active_index_naming_no_entry_is_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":7,"in_progress":[]}}"#,
                    entry(0, "Shown")
                ),
                "whose active index names no entry",
            );
        }

        #[test]
        fn a_hidden_active_profile_is_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                    entry(0, "HiddenFromLists")
                ),
                "whose active profile is hidden",
            );
        }

        /// **Regression: the DID string is spoofable.** The string is DERIVED from the launcher id
        /// by `MintedDid::from_confirmed` and never accepted from a caller, so a file claiming a
        /// different one is stating something no constructor could have produced. Every other field
        /// is the control fixture's, so only the derivation rule can reject it.
        ///
        /// This closes a STRING SPOOF, not fabrication: an attacker who derives the correct string
        /// for their launcher id still loads a fabricated anchor.
        #[test]
        fn a_did_string_that_does_not_belong_to_its_launcher_id_is_rejected() {
            let spoof = "did:chia:1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqvictim";
            assert_ne!(
                spoof,
                honest_did(),
                "the spoof must differ, or this proves nothing"
            );

            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                    entry_claiming(0, "Shown", spoof)
                ),
                "whose DID string does not belong to its launcher id",
            );
        }

        /// **Regression: an unbounded store fee arriving from a file.** The journalled fee is what a
        /// resumed phase B may spend, so a file is exactly the path that would let it exceed the
        /// amount the user approved — `begin_mint`'s ceiling alone would never see it.
        #[test]
        fn a_journalled_store_fee_above_the_ceiling_is_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[],"active":null,"in_progress":[{}]}}"#,
                    pending_with_fee(1, u64::MAX)
                ),
                "whose journalled store fee is above the mint ceiling",
            );
            // The control: exactly at the ceiling loads, so the rejection is the bound and not the
            // fixture.
            let at_bound = format!(
                r#"{{"entries":[],"active":null,"in_progress":[{}]}}"#,
                pending_with_fee(1, MAX_MINT_FEE_MOJOS)
            );
            assert!(ProfileRegistry::from_json(&at_bound).is_ok());
        }

        #[test]
        fn an_index_both_confirmed_and_pending_is_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":0,"in_progress":[{}]}}"#,
                    entry(0, "Shown"),
                    pending(0)
                ),
                "with one index both confirmed and pending",
            );
        }

        /// **Regression: the journalled DID is spoofable too, at every stage that carries one.**
        /// `DidConfirmedStoreNotLaunched` instructs the resume path to launch the store from THAT
        /// record's DID coin, so a file that redirects it redirects a spend. Asserted once per
        /// record-carrying variant, because a rule applied to one of them would leave the other
        /// wide open and a single-variant test would never say so.
        #[test]
        fn a_journalled_did_that_does_not_belong_to_its_launcher_id_is_rejected() {
            let spoof = "did:chia:1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqvictim";
            assert_ne!(
                spoof,
                honest_did(),
                "the spoof must differ, or this proves nothing"
            );

            assert_rejected(
                registry_with_stage(did_confirmed_stage(spoof, 10)),
                "whose DidConfirmedStoreNotLaunched DID does not belong to its launcher id",
            );
            assert_rejected(
                registry_with_stage(store_pushed_stage(spoof, 10)),
                "whose StorePushed DID does not belong to its launcher id",
            );
        }

        /// The stage-shaped control for the test above: each variant loads when its DID is honest,
        /// and `DidPushed` — which carries no DID at all — keeps loading. Without this a journal
        /// check that rejected every stage would read as three working rules.
        #[test]
        fn every_stage_loads_when_its_did_is_honest() {
            for stage in [
                did_pushed_stage(),
                did_confirmed_stage(&honest_did(), 10),
                store_pushed_stage(&honest_did(), 10),
                // Height 1 is the lowest HONEST confirmation, and it is carried here rather than
                // only beside the anchors: without it a journal guard written `confirmed_height
                // <= 1` — the over-rejecting sibling of the shipped `== 0` rule — passes the whole
                // suite, because every other journal fixture confirms at 10 (dig-account#35).
                did_confirmed_stage(&honest_did(), 1),
                store_pushed_stage(&honest_did(), 1),
            ] {
                ProfileRegistry::from_json(&registry_with_stage(stage.clone()))
                    .unwrap_or_else(|e| panic!("the honest stage {stage} must load: {e:?}"));
            }
        }

        /// **Regression: a fabricated genesis height on the journal.** No coin is created in block
        /// 0, so a `0` is a value no confirmation could have produced — the rule
        /// `MintedDid::from_confirmed` applies to live evidence, applied to the file.
        #[test]
        fn a_journalled_did_confirmed_at_height_zero_is_rejected() {
            assert_rejected(
                registry_with_stage(did_confirmed_stage(&honest_did(), 0)),
                "whose journalled DID confirmed at the genesis height",
            );
            assert_rejected(
                registry_with_stage(store_pushed_stage(&honest_did(), 0)),
                "whose StorePushed DID confirmed at the genesis height",
            );
        }

        /// A registry carrying exactly one anchor, confirmed at the two heights given.
        fn registry_with_anchor_at(did_height: u32, store_height: u32) -> String {
            format!(
                r#"{{"entries":[{}],"active":0,"in_progress":[]}}"#,
                entry_confirmed_at(0, did_height, store_height)
            )
        }

        /// The same fabricated height, on an anchor's DID half.
        ///
        /// **The two anchor heights are asserted in SEPARATE tests on purpose.** Asserting both here
        /// would make one test fail whichever guard was removed, so a revert-proof could not tell a
        /// working pair from one live guard beside one dead one — the store height is varied alone
        /// below, and the control keeps the other half honest in each.
        #[test]
        fn an_anchor_whose_did_confirmed_at_height_zero_is_rejected() {
            assert_rejected(
                registry_with_anchor_at(0, 11),
                "whose DID confirmed at the genesis height",
            );
        }

        /// The store half of the rule above, varied alone.
        #[test]
        fn an_anchor_whose_store_confirmed_at_height_zero_is_rejected() {
            assert_rejected(
                registry_with_anchor_at(10, 0),
                "whose store confirmed at the genesis height",
            );
        }

        /// The control for both: height 1 is the lowest honest value and must still load, so the
        /// two rejections above are the `0` and not an over-eager lower bound.
        #[test]
        fn an_anchor_confirmed_in_the_first_block_after_genesis_loads() {
            assert!(
                ProfileRegistry::from_json(&registry_with_anchor_at(1, 1)).is_ok(),
                "the first block after genesis is an honest height"
            );
        }

        /// Invariant 2's other half: entries with NO active index is equally invalid, since every
        /// key read would have nowhere to derive from.
        #[test]
        fn entries_without_an_active_index_are_rejected() {
            assert_rejected(
                format!(
                    r#"{{"entries":[{}],"active":null,"in_progress":[]}}"#,
                    entry(0, "Shown")
                ),
                "with entries but no active index",
            );
        }
    }
}

/// **A melted profile can be FORGOTTEN as live** (dig_ecosystem#3067).
///
/// Before this, `ProfileRegistry` could record and hide a profile but never end one, so after
/// dig-app's delete control melted both singletons the registry kept listing a profile the chain had
/// retired. The account whose ONLY profile was melted was the state with no remedy at all: it could
/// not be hidden (it was active) and there was nothing to switch to.
#[cfg(test)]
mod ended_profile_tests {
    use super::*;
    use crate::mint::fixtures::bound_mint;

    /// A registry holding confirmed profiles at each of `ixs`, the first of them active.
    fn registry_with(ixs: &[u32]) -> ProfileRegistry {
        let mut registry = ProfileRegistry::empty();
        for (n, ix) in ixs.iter().enumerate() {
            let (did, store) = bound_mint(n as u8 + 1);
            registry
                .record_minted(ProfileIx(*ix), &did, &store, None)
                .expect("a confirmed mint records");
        }
        registry
    }

    /// The single-profile account — the state #3067 named as having no remedy.
    ///
    /// Ending it must leave NO active profile rather than an active slot pointing at a profile whose
    /// DID no longer resolves.
    #[test]
    fn ending_an_accounts_only_profile_leaves_it_with_no_active_profile() {
        let mut registry = registry_with(&[0]);
        assert!(
            registry.active().is_some(),
            "the fixture starts with an active profile"
        );

        let outcome = registry
            .record_melted(ProfileIx(0), 5_000_000)
            .expect("a confirmed melt records");

        assert_eq!(outcome, ProfileEndOutcome::NoLiveProfileRemains);
        assert!(
            registry.active().is_none(),
            "an account whose every profile ended has no profile it could honestly point at"
        );
        assert_eq!(
            registry.shown().count(),
            0,
            "an ended profile leaves the lists"
        );
        assert_eq!(registry.live().count(), 0);
    }

    /// The MULTI-profile account: ending the active one moves the slot rather than clearing it, and
    /// the move is reported because the user did not choose it.
    ///
    /// This is the case that distinguishes "the active slot is maintained" from "the active slot is
    /// merely cleared" — a registry that only ever cleared would pass the test above and strand a
    /// user who still has profiles left.
    #[test]
    fn ending_the_active_profile_moves_the_slot_to_a_remaining_live_one() {
        let mut registry = registry_with(&[0, 1]);
        let _ = registry
            .set_active(ProfileIx(0))
            .expect("profile 0 is active");

        let outcome = registry
            .record_melted(ProfileIx(0), 5_000_000)
            .expect("a confirmed melt records");

        assert_eq!(
            outcome,
            ProfileEndOutcome::ActiveMoved(ActiveSwitch {
                from: Some(ProfileIx(0)),
                to: ProfileIx(1),
            })
        );
        assert_eq!(registry.active().map(ActiveProfile::ix), Some(ProfileIx(1)));
    }

    /// Ending a NON-active profile leaves the active slot exactly where it was — the truthful control
    /// for the two tests above, which would both pass a registry that cleared the slot indiscriminately.
    #[test]
    fn ending_a_non_active_profile_does_not_disturb_the_active_slot() {
        let mut registry = registry_with(&[0, 1]);
        let _ = registry
            .set_active(ProfileIx(0))
            .expect("profile 0 is active");

        let outcome = registry
            .record_melted(ProfileIx(1), 5_000_000)
            .expect("a confirmed melt records");

        assert_eq!(outcome, ProfileEndOutcome::Recorded);
        assert_eq!(registry.active().map(ActiveProfile::ix), Some(ProfileIx(0)));
        assert_eq!(registry.live().count(), 1);
    }

    /// An ended profile cannot be made active again. Without this, un-hiding or re-selecting would
    /// resurrect a dead profile on screen — the resurrection #3067 called out for the hide workaround.
    #[test]
    fn an_ended_profile_cannot_be_made_active_again() {
        let mut registry = registry_with(&[0, 1]);
        let _ = registry.record_melted(ProfileIx(1), 5_000_000).unwrap();

        let err = registry
            .set_active(ProfileIx(1))
            .expect_err("a profile the chain retired must not become active");
        assert!(
            matches!(err, AccountError::ProfileEnded(ProfileIx(1))),
            "{err:?}"
        );
    }

    /// The record is kept, not deleted: the DID string is still the right answer to what the account
    /// used to be, and the height gives a host something honest to draw.
    #[test]
    fn an_ended_profile_keeps_its_did_and_records_the_height_it_ended_at() {
        let mut registry = registry_with(&[0, 1]);
        let did = registry
            .get(ProfileIx(1))
            .unwrap()
            .anchor()
            .did()
            .to_string();

        let _ = registry.record_melted(ProfileIx(1), 5_000_123).unwrap();

        let entry = registry
            .get(ProfileIx(1))
            .expect("the record survives the end");
        assert_eq!(entry.anchor().did(), did);
        assert_eq!(entry.ended().map(ProfileEnd::at_height), Some(5_000_123));
        assert!(!entry.is_live());
    }

    /// Height 0 is what an UNCONFIRMED read looks like, so admitting it would store a submission as a
    /// confirmation — the same rule the mint anchors enforce. Pinned from both sides: 0 is refused and
    /// 1, the lowest real height, is accepted.
    #[test]
    fn an_end_at_height_zero_is_refused_and_the_first_real_height_is_accepted() {
        let mut registry = registry_with(&[0, 1]);

        let err = registry
            .record_melted(ProfileIx(1), 0)
            .expect_err("height 0 is not evidence of a confirmed melt");
        assert!(matches!(err, AccountError::ProfileEndHeightZero), "{err:?}");
        assert!(
            registry.get(ProfileIx(1)).unwrap().is_live(),
            "a refused end must leave the entry untouched, not half-written"
        );

        let _ = registry
            .record_melted(ProfileIx(1), 1)
            .expect("height 1 is a real height and must be accepted");
    }

    /// Recording an end twice is a no-op, so a host retrying after a crash mid-ceremony cannot move
    /// the active slot a second time and strand the user on a third profile they never chose.
    #[test]
    fn recording_an_end_twice_changes_nothing() {
        let mut registry = registry_with(&[0, 1, 2]);
        let _ = registry.set_active(ProfileIx(0)).unwrap();
        let _ = registry.record_melted(ProfileIx(0), 5_000_000).unwrap();
        let after_first = registry.active().map(ActiveProfile::ix);

        let outcome = registry.record_melted(ProfileIx(0), 5_000_999).unwrap();

        assert_eq!(outcome, ProfileEndOutcome::AlreadyEnded);
        assert_eq!(registry.active().map(ActiveProfile::ix), after_first);
        assert_eq!(
            registry
                .get(ProfileIx(0))
                .unwrap()
                .ended()
                .map(ProfileEnd::at_height),
            Some(5_000_000),
            "the FIRST confirmed height stands; a retry must not overwrite it"
        );
    }

    /// A registry whose only profile has ended round-trips through JSON, and its no-active-profile
    /// state survives the load. A file is untrusted input, so the invariants are checked on the
    /// deserialize path too — an end that only held in memory would be undone by a restart.
    #[test]
    fn an_account_with_no_live_profile_round_trips_through_json() {
        let mut registry = registry_with(&[0]);
        let _ = registry.record_melted(ProfileIx(0), 5_000_000).unwrap();

        let loaded = ProfileRegistry::from_json(&registry.to_json().unwrap())
            .expect("a registry with no live profile is a legal state, not a corrupt file");

        assert!(loaded.active().is_none());
        assert_eq!(loaded.entries().len(), 1, "the ended record is still there");
        assert_eq!(loaded.live().count(), 0);
    }

    /// A hand-edited file that marks the ACTIVE profile as ended is refused on load: it would leave
    /// every identity surface reading an active profile the chain has retired.
    #[test]
    fn a_file_whose_active_profile_has_ended_is_refused_on_load() {
        let mut registry = registry_with(&[0, 1]);
        let _ = registry.set_active(ProfileIx(0)).unwrap();
        let mut json: serde_json::Value =
            serde_json::from_str(&registry.to_json().unwrap()).unwrap();

        json["entries"][0]["ended"] = serde_json::json!({ "at_height": 5_000_000 });

        ProfileRegistry::from_json(&json.to_string())
            .expect_err("an active profile that has ended is not a loadable state");
    }

    /// A registry whose only profile has ended, as JSON, with the end height rewritten to
    /// `at_height`. The profile is the ONLY one and no profile is active, so the sole invariant the
    /// end height could trip is the one under test — an active-slot rejection cannot stand in for it.
    fn json_with_end_height(at_height: u32) -> String {
        let mut registry = registry_with(&[0]);
        let _ = registry.record_melted(ProfileIx(0), 5_000_000).unwrap();
        let mut json: serde_json::Value =
            serde_json::from_str(&registry.to_json().unwrap()).unwrap();

        json["entries"][0]["ended"] = serde_json::json!({ "at_height": at_height });
        json.to_string()
    }

    /// **Regression: height 0 was enforced on the WRITE path only.** `ProfileEnd` derives
    /// `Deserialize`, so a file reaches the field without passing `ProfileEnd::at` — before this
    /// check a registry stating `"ended": {"at_height": 0}` loaded clean, and an unconfirmed melt
    /// read as a confirmed one. SPEC.md §2.4.5 states the rejection as a MUST.
    #[test]
    fn a_file_whose_end_height_is_zero_is_refused_on_load() {
        let error = ProfileRegistry::from_json(&json_with_end_height(0))
            .expect_err("height 0 is what an unconfirmed melt read looks like");

        assert!(
            matches!(&error, AccountError::RegistryInvariant(why) if why.contains("end height is 0")),
            "the load must fail on the END height rather than another invariant, got {error:?}"
        );
    }

    /// The control for the rejection above: height 1 is the lowest honest end height and must still
    /// load, so the refusal is the `0` and not a rule against recording an end at all.
    #[test]
    fn a_file_whose_end_height_is_the_first_block_after_genesis_loads() {
        ProfileRegistry::from_json(&json_with_end_height(1))
            .expect("the first block after genesis is an honest end height");
    }
}