doubleentry 0.7.0

An immutable, tamper-evident double-entry bookkeeping engine. Balanced-by-construction entries, exact integer money, deterministic identity, and an append-only Merkle log with inclusion and consistency proofs. Zero I/O. No async. No chart of accounts.
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
//! Accounts and the account tree.
//!
//! An account is a path in a user-defined hierarchy, such as
//! `Assets:Current:Bank:Main`. The engine imposes no chart of accounts: it does
//! not know what `Assets` means, does not require that name, and does not
//! validate against any national or corporate scheme.
//!
//! Two rules are enforced, because both are structural rather than
//! jurisdictional:
//!
//! - **Only leaves are postable.** An account with registered descendants is an
//!   aggregation path. An account that is both a bucket and a container has two
//!   defensible balances — its own postings, and its subtree's — and every
//!   report has to pick one silently. Nothing downstream can un-mix them,
//!   because both readings are of the same rows.
//!
//!   The rule is checked when an entry is validated, and again when an account
//!   is registered: a leaf that has been posted to cannot acquire a child.
//!   Without the second half the first is a trap — registering the child turns
//!   the parent into a node, every later entry on it is refused *including the
//!   reversal that would correct it*, and the balance already there can never be
//!   moved. The registry cannot see that, since it holds no postings, so the
//!   check lives on [`Journal`](crate::Journal) and on every
//!   [`LedgerStore`](crate::LedgerStore).
//! - **Postings fall inside the account's open window.** An account has an
//!   opening date and an optional closing date.
//!
//! A third is offered rather than imposed. A [`BalanceLimit`] forbids an
//! account's net from crossing zero in one direction — a cash box that cannot be
//! overdrawn, a wallet that cannot be drawn beyond what was funded. It is off by
//! default, because most accounts legitimately sit on either side; where it is
//! set it is checked when an entry is recorded, against the balance that entry
//! would leave behind.

use std::collections::BTreeMap;

use time::Date;

use crate::balance::Balance;
use crate::canonical::{Canonical, CanonicalWriter};
use crate::hash::{Hash, tag, tagged};
use crate::merkle::{InclusionProof, MerkleLog, TreeHead};

/// Maximum number of characters in one path segment.
pub const MAX_SEGMENT_LEN: usize = 64;

/// Maximum depth of an account path.
pub const MAX_DEPTH: usize = 16;

/// The separator between path segments.
pub const SEPARATOR: char = ':';

/// Maximum number of accounts one registry may hold.
///
/// A handle is a `u32` position, so this is how many distinct ones exist. The
/// bound is stated rather than left implicit because passing it must be an
/// error: a registry that wrapped, saturated, or reused a handle would silently
/// repoint every posting and every sealed balance that names it.
pub const MAX_ACCOUNTS: usize = u32::MAX as usize;

/// Failure constructing or registering an account.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum AccountError {
    /// The path had no segments.
    #[error("account path is empty")]
    Empty,
    /// A segment was empty, e.g. from a doubled or trailing separator.
    #[error("account path has an empty segment at position {position}")]
    EmptySegment {
        /// Zero-based segment position.
        position: usize,
    },
    /// A segment exceeded [`MAX_SEGMENT_LEN`].
    #[error("account path segment {position} exceeds {MAX_SEGMENT_LEN} characters")]
    SegmentTooLong {
        /// Zero-based segment position.
        position: usize,
    },
    /// The path exceeded [`MAX_DEPTH`].
    #[error("account path is deeper than {MAX_DEPTH} segments")]
    TooDeep,
    /// A segment contained a control character.
    #[error("account path segment {position} contains a control character")]
    ControlCharacter {
        /// Zero-based segment position.
        position: usize,
    },
    /// The account was already registered.
    #[error("account {path} is already registered")]
    AlreadyRegistered {
        /// The duplicate path.
        path: AccountPath,
    },
    /// The account handle does not belong to this registry.
    #[error("account {id} is not registered")]
    UnknownAccount {
        /// The offending handle.
        id: AccountId,
    },
    /// Stored bindings were not a dense range starting at zero.
    ///
    /// Handles are positions, so a gap or a duplicate means the stored set is
    /// not the set the handles were issued against.
    #[error("stored account bindings are not dense: expected index {expected}, found {found}")]
    NotDense {
        /// The index the sequence required.
        expected: u32,
        /// The index actually present.
        found: u32,
    },
    /// The registry has issued every handle its index space allows.
    ///
    /// Handles are `u32` positions written into every posting row and into every
    /// trial-balance leaf a seal commits to, so reusing one would repoint
    /// history. Refusing the registration is the only safe answer.
    #[error("account registry is full: all {MAX_ACCOUNTS} handles have been issued")]
    RegistryFull,
    /// The closing date preceded the opening date.
    #[error("account {path} closes on {closed} before it opens on {opened}")]
    ClosedBeforeOpened {
        /// The offending path.
        path: AccountPath,
        /// Opening date.
        opened: Date,
        /// Closing date.
        closed: Date,
    },
}

/// A validated account path.
///
/// Paths are compared and ordered segment-wise, so sorting a set of paths yields
/// a stable, tree-like order regardless of platform.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AccountPath {
    segments: Vec<String>,
}

#[cfg(feature = "serde")]
impl serde::Serialize for AccountPath {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for AccountPath {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = <std::borrow::Cow<'_, str> as serde::Deserialize>::deserialize(d)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

impl AccountPath {
    /// Parses a separator-delimited path such as `"Assets:Bank"`.
    pub fn parse(s: &str) -> Result<Self, AccountError> {
        if s.is_empty() {
            return Err(AccountError::Empty);
        }
        let segments: Vec<&str> = s.split(SEPARATOR).collect();
        Self::from_segments(segments)
    }

    /// Builds a path from already-split segments.
    pub fn from_segments<S: AsRef<str>>(
        segments: impl IntoIterator<Item = S>,
    ) -> Result<Self, AccountError> {
        let raw: Vec<String> = segments
            .into_iter()
            .map(|s| s.as_ref().to_owned())
            .collect();

        if raw.is_empty() {
            return Err(AccountError::Empty);
        }
        if raw.len() > MAX_DEPTH {
            return Err(AccountError::TooDeep);
        }
        for (position, seg) in raw.iter().enumerate() {
            if seg.is_empty() {
                return Err(AccountError::EmptySegment { position });
            }
            if seg.chars().count() > MAX_SEGMENT_LEN {
                return Err(AccountError::SegmentTooLong { position });
            }
            if seg.chars().any(char::is_control) {
                return Err(AccountError::ControlCharacter { position });
            }
        }
        Ok(Self { segments: raw })
    }

    /// The path segments, outermost first.
    #[must_use]
    pub fn segments(&self) -> &[String] {
        &self.segments
    }

    /// Number of segments.
    #[must_use]
    pub fn depth(&self) -> usize {
        self.segments.len()
    }

    /// The parent path, or `None` for a top-level account.
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        if self.segments.len() <= 1 {
            return None;
        }
        let mut segments = self.segments.clone();
        segments.pop();
        Some(Self { segments })
    }

    /// Every ancestor, from the top-level account down to the direct parent.
    #[must_use]
    pub fn ancestors(&self) -> Vec<Self> {
        let mut out = Vec::new();
        let mut current = self.parent();
        while let Some(p) = current {
            current = p.parent();
            out.push(p);
        }
        out.reverse();
        out
    }

    /// True when `self` is `other` or a descendant of it.
    #[must_use]
    pub fn is_under(&self, other: &Self) -> bool {
        if self.segments.len() < other.segments.len() {
            return false;
        }
        self.segments
            .iter()
            .zip(other.segments.iter())
            .all(|(a, b)| a == b)
    }

    /// A stable content hash of this path.
    #[must_use]
    pub fn content_hash(&self) -> Hash {
        tagged(tag::ACCOUNT_V1, &self.to_canonical_bytes())
    }
}

impl Canonical for AccountPath {
    fn encode(&self, w: &mut CanonicalWriter) {
        w.seq(self.segments.iter(), |w, s| {
            w.str(s);
        });
    }
}

impl std::fmt::Display for AccountPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut first = true;
        for seg in &self.segments {
            if !first {
                f.write_str(":")?;
            }
            f.write_str(seg)?;
            first = false;
        }
        Ok(())
    }
}

impl std::str::FromStr for AccountPath {
    type Err = AccountError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// The classification of an account for reporting purposes.
///
/// This is metadata only. The engine records it, exposes it, and never uses it
/// to constrain a posting — a chart of accounts is the caller's concern.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AccountKind {
    /// Resources controlled by the entity.
    Asset,
    /// Obligations owed by the entity.
    Liability,
    /// Residual interest in the assets.
    Equity,
    /// Inflows increasing equity.
    Income,
    /// Outflows decreasing equity.
    Expense,
}

impl AccountKind {
    /// The side on which this kind of account normally carries a balance.
    #[must_use]
    pub const fn normal_side(self) -> crate::posting::Direction {
        use crate::posting::Direction;
        match self {
            Self::Asset | Self::Expense => Direction::Debit,
            Self::Liability | Self::Equity | Self::Income => Direction::Credit,
        }
    }

    fn discriminant(self) -> u8 {
        match self {
            Self::Asset => 0,
            Self::Liability => 1,
            Self::Equity => 2,
            Self::Income => 3,
            Self::Expense => 4,
        }
    }
}

/// Which side an account's net balance is allowed to fall on.
///
/// Unconstrained by default. Set it where the books would be wrong rather than
/// merely surprising if the balance crossed zero — a cash account that cannot be
/// overdrawn, a customer prepayment that cannot go into debit, a control account
/// that must never carry the wrong sign.
///
/// The limit is checked when an entry is recorded, against the balance the entry
/// would leave behind, **per currency**, folding the settled and pending layers
/// into one answer — see [`headroom_minor`](BalanceLimit::headroom_minor). It is
/// a rule about what may be written next, exactly like an account's open window:
/// it never invalidates what is already recorded, and an entry that breaches it
/// is refused whole rather than partly applied.
///
/// Gross totals are irrelevant to it — only the net crosses zero — so an account
/// with heavy offsetting turnover is unaffected as long as the net stays on the
/// permitted side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BalanceLimit {
    /// The balance may fall on either side. The default.
    #[default]
    Unlimited,
    /// Credits may never exceed debits: the net stays on the debit side or zero.
    ///
    /// The rule for an asset that cannot go negative — a cash box, a bank
    /// account without an overdraft facility, an inventory quantity.
    NoCreditBalance,
    /// Debits may never exceed credits: the net stays on the credit side or zero.
    ///
    /// The rule for a liability that cannot be drawn beyond what was funded — a
    /// customer wallet, a prepayment, a reserve.
    NoDebitBalance,
}

impl BalanceLimit {
    /// How much room is left under this limit, in minor units.
    ///
    /// Negative when the limit is breached, and the magnitude is what would have
    /// to come back the other way to restore it. `None` for
    /// [`Unlimited`](BalanceLimit::Unlimited), which has no room to run out of.
    ///
    /// # What the reservations do
    ///
    /// The settled net alone is not the answer, because a reservation is money
    /// already promised. Both layers are folded, but **asymmetrically**: a
    /// pending net working *against* the limit consumes room, and one working
    /// *for* it grants none. An outflow you have committed to is gone; an inflow
    /// you have merely reserved has not arrived.
    ///
    /// So a wallet limited to [`NoDebitBalance`](BalanceLimit::NoDebitBalance),
    /// funded with 100 and holding a reservation of 30, has 70 left — and a
    /// second reservation of 80 is refused, which is the whole point of putting
    /// a limit on a wallet. Discharging the first reservation nets its pending
    /// side back to zero and the room returns.
    ///
    /// Computed in `i128` from two `i64` totals, so it is **total**: no balance
    /// exists that this cannot answer for, and there is no overflow to report.
    #[must_use]
    // Every operand is an `i64` widened to `i128`, so each net is bounded by
    // `2^64` and the sum of two by `2^65` — six orders of magnitude short of
    // `i128::MAX`. Nothing here can overflow, which is what makes the answer
    // total, and routing it through `checked_*` would return an `Option` that
    // is never `None` and obscure that.
    #[allow(clippy::arithmetic_side_effects)]
    pub fn headroom_minor<const P: u8>(
        self,
        settled: &Balance<P>,
        pending: &Balance<P>,
    ) -> Option<i128> {
        // Signed nets, debit positive.
        let s = i128::from(settled.debits.to_minor()) - i128::from(settled.credits.to_minor());
        let q = i128::from(pending.debits.to_minor()) - i128::from(pending.credits.to_minor());
        match self {
            Self::Unlimited => None,
            // The net must stay on the debit side. A pending *credit* net is the
            // adverse direction, so only that is subtracted.
            Self::NoCreditBalance => Some(s + q.min(0)),
            // Mirrored: the net must stay on the credit side, and a pending
            // *debit* net is the adverse one.
            Self::NoDebitBalance => Some(-(s + q.max(0))),
        }
    }

    /// True when `settled` and `pending` together satisfy this limit.
    ///
    /// See [`headroom_minor`](Self::headroom_minor) for how the two layers are
    /// folded, and why the fold is asymmetric.
    #[must_use]
    pub fn permits<const P: u8>(self, settled: &Balance<P>, pending: &Balance<P>) -> bool {
        self.headroom_minor(settled, pending)
            .is_none_or(|room| room >= 0)
    }

    /// True for [`BalanceLimit::Unlimited`].
    #[must_use]
    pub const fn is_unlimited(self) -> bool {
        matches!(self, Self::Unlimited)
    }

    const fn discriminant(self) -> u8 {
        match self {
            Self::Unlimited => 0,
            Self::NoCreditBalance => 1,
            Self::NoDebitBalance => 2,
        }
    }
}

impl std::fmt::Display for BalanceLimit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Unlimited => "unlimited",
            Self::NoCreditBalance => "no credit balance",
            Self::NoDebitBalance => "no debit balance",
        })
    }
}

/// A handle to a registered account.
///
/// Handles are dense and assigned in registration order, which makes them cheap
/// to compare and to use as indices. They are meaningful only relative to the
/// [`AccountRegistry`] that issued them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountId(u32);

impl AccountId {
    /// The underlying index.
    #[must_use]
    pub const fn index(self) -> u32 {
        self.0
    }

    /// Wraps a raw index.
    ///
    /// Only meaningful against the registry that issued it. Provided so a
    /// persistence layer can rehydrate handles; a handle built this way is
    /// validated when the entry referencing it is sealed.
    #[must_use]
    pub const fn from_index(index: u32) -> Self {
        Self(index)
    }
}

impl std::fmt::Display for AccountId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// Registration details for one account.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Account {
    /// The account's path.
    pub path: AccountPath,
    /// Optional reporting classification.
    pub kind: Option<AccountKind>,
    /// First date on which the account may be posted to.
    pub opened_on: Date,
    /// Last date on which the account may be posted to, if it has closed.
    pub closed_on: Option<Date>,
    /// Which side the account's net balance may fall on.
    pub limit: BalanceLimit,
}

impl Account {
    /// Creates an account open from `opened_on`, with no closing date and no
    /// balance limit.
    #[must_use]
    pub fn new(path: AccountPath, opened_on: Date) -> Self {
        Self {
            path,
            kind: None,
            opened_on,
            closed_on: None,
            limit: BalanceLimit::Unlimited,
        }
    }

    /// Sets the reporting classification.
    #[must_use]
    pub fn with_kind(mut self, kind: AccountKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// Sets the closing date.
    #[must_use]
    pub fn closing_on(mut self, date: Date) -> Self {
        self.closed_on = Some(date);
        self
    }

    /// Constrains which side the account's net balance may fall on.
    #[must_use]
    pub fn limited_to(mut self, limit: BalanceLimit) -> Self {
        self.limit = limit;
        self
    }

    /// True when the account accepts postings on `date`.
    #[must_use]
    pub fn is_open_on(&self, date: Date) -> bool {
        date >= self.opened_on && self.closed_on.is_none_or(|c| date <= c)
    }
}

impl Canonical for Account {
    fn encode(&self, w: &mut CanonicalWriter) {
        self.path.encode(w);
        w.option(self.kind.as_ref(), |w, k| {
            w.u8(k.discriminant());
        });
        encode_date(w, self.opened_on);
        w.option(self.closed_on.as_ref(), |w, d| encode_date(w, *d));
        // Encoded unconditionally rather than as an option: the limit is part of
        // what the account *is*, so a registry that quietly relaxed one must
        // produce a different binding commitment.
        w.u8(self.limit.discriminant());
    }
}

/// Encodes a date as year, month, day.
///
/// The year is a signed `i32` — the type [`Date::year`] returns, covering every
/// date `time` can represent under any feature set. Splitting it into a magnitude
/// and a sign bit would need a clamp, and a clamp inside a hash preimage is a
/// silent collision waiting for a wider date range to be enabled.
pub(crate) fn encode_date(w: &mut CanonicalWriter, d: Date) {
    w.i32(d.year());
    w.u8(u8::from(d.month()));
    w.u8(d.day());
}

/// One account together with the handle it was issued.
///
/// The handle is the account's position in registration order, and that
/// position is written into every posting row and into the trial balance leaves
/// a seal commits to. It is therefore part of the ledger's persistent state,
/// not a runtime detail: a registry rebuilt in a different order would repoint
/// history. Records carry the binding explicitly so it survives a restart.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountRecord {
    /// The handle this account was issued.
    pub id: AccountId,
    /// The account itself.
    pub account: Account,
}

impl Canonical for AccountRecord {
    fn encode(&self, w: &mut CanonicalWriter) {
        w.u32(self.id.index());
        self.account.encode(w);
    }
}

/// The leaf one handle-to-account binding hashes to.
///
/// Covers the handle and the path, and **nothing else**.
///
/// Those two are exactly the account's identity, and exactly the fields that
/// never change: [`AccountRegistry::restore`] refuses to move a path onto a
/// handle that already holds a different one, because a rebound handle would
/// repoint every posting row and every sealed balance that names it.
///
/// The classification, the open window and the balance limit are deliberately
/// *out*. They are master data — the registry's own mutators
/// ([`AccountRegistry::close`], [`AccountRegistry::reopen`],
/// [`AccountRegistry::set_limit`]) exist to change them, and they govern what
/// may be booked next rather than what was booked already. Hashing them in would
/// move the commitment every time an account was legitimately closed,
/// invalidating every binding proof against every earlier seal: a normal Tuesday
/// afternoon reading as evidence of tampering.
///
/// A seal names handles; it is not a snapshot of the chart of accounts.
///
/// # What that costs
///
/// The ledger therefore records master data's **current** state, not its
/// history: nothing says when an account was closed or by whom, and none of it
/// is tamper-evident. Keep that history where you keep your other administrative
/// events. What *is* guaranteed is narrower — a handle's path is immutable, and
/// renumbering the handle space is caught against every seal by
/// [`SealChain::verify_against_accounts`](crate::SealChain::verify_against_accounts).
#[must_use]
pub fn account_binding_leaf(id: AccountId, path: &AccountPath) -> Hash {
    let mut w = CanonicalWriter::new();
    w.u32(id.index());
    path.encode(&mut w);
    tagged(tag::ACCOUNT_BINDING_V1, &w.finish())
}

/// Proof that a handle was issued to a particular account path.
///
/// Self-contained: it carries the binding it proves, so a verifier needs nothing
/// but this and an [`AccountRegistry::commitment`] — which a
/// [`Seal`](crate::Seal) publishes as [`accounts`](crate::Seal::accounts).
///
/// This is what makes a sealed balance legible. A
/// [`BalanceProof`](crate::BalanceProof) proves that handle `#7` held a
/// balance; on its own that is a statement about an integer. Pairing it with
/// this proof, against the same seal, turns it into a statement about
/// `Assets:Cash` — without disclosing any other account, balance, or entry.
///
/// It carries the handle and the path and no other account field, because those
/// are the only ones it establishes. A verifier reading `closed_on` off a
/// "verified" proof would be reading whatever the prover put there.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountBindingProof {
    /// The handle being proven.
    pub id: AccountId,
    /// The path that handle was issued to.
    pub path: AccountPath,
    /// Path from the binding's leaf up to the registry commitment.
    pub proof: InclusionProof,
}

impl AccountBindingProof {
    /// The handle being proven.
    #[must_use]
    pub fn id(&self) -> AccountId {
        self.id
    }

    /// The account path the handle names.
    #[must_use]
    pub fn path(&self) -> &AccountPath {
        &self.path
    }

    /// Verifies the binding against an [`AccountRegistry::commitment`].
    ///
    /// Returns `false` on any inconsistency rather than distinguishing failure
    /// modes: a verifier cannot act differently on a malformed proof than on a
    /// forged one.
    #[must_use]
    pub fn verify(&self, accounts: &TreeHead) -> bool {
        // The handle *is* the leaf index, so a proof for one binding cannot be
        // replayed at another position without failing here.
        self.proof.leaf_index == u64::from(self.id.index())
            && self
                .proof
                .verify(&account_binding_leaf(self.id, &self.path), accounts)
    }
}

/// The set of accounts a ledger may post to.
///
/// The registry owns the account tree and answers the two questions validation
/// needs: does this account exist, and may it be posted to on this date.
#[derive(Debug, Clone, Default)]
pub struct AccountRegistry {
    accounts: Vec<Account>,
    /// Ordered so that iteration and any derived output is deterministic.
    index: BTreeMap<AccountPath, AccountId>,
    child_count: Vec<u32>,
}

impl AccountRegistry {
    /// Creates an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers an account and returns its handle.
    ///
    /// Ancestors are not created implicitly: a path may be registered without
    /// its parents existing, and registering a parent later reclassifies it as a
    /// non-postable node.
    pub fn register(&mut self, account: Account) -> Result<AccountId, AccountError> {
        if let Some(closed) = account.closed_on
            && closed < account.opened_on
        {
            return Err(AccountError::ClosedBeforeOpened {
                path: account.path.clone(),
                opened: account.opened_on,
                closed,
            });
        }
        if self.index.contains_key(&account.path) {
            return Err(AccountError::AlreadyRegistered { path: account.path });
        }

        // Refused rather than saturated: a reused handle repoints history.
        let id =
            AccountId(u32::try_from(self.accounts.len()).map_err(|_| AccountError::RegistryFull)?);
        let path = account.path.clone();

        // Registering a child turns its registered ancestors into path nodes.
        for ancestor in path.ancestors() {
            if let Some(parent_id) = self.index.get(&ancestor)
                && let Some(count) = self.child_count.get_mut(parent_id.0 as usize)
            {
                *count = count.saturating_add(1);
            }
        }
        // A newly registered account may already have descendants. Paths sort
        // segment-wise, so every descendant is contiguous with `path` in the
        // index and the scan stops at the first non-descendant — rather than
        // walking the whole registry once per registration.
        let existing_children = self.descendant_range(&path).count();

        self.accounts.push(account);
        self.child_count
            .push(u32::try_from(existing_children).unwrap_or(u32::MAX));
        self.index.insert(path, id);
        Ok(id)
    }

    /// Every strict descendant of `prefix` already in the index, in path order.
    ///
    /// Relies on the segment-wise `Ord` on [`AccountPath`]: a path under
    /// `prefix` sorts after `prefix` and before the first path that is not under
    /// it, so the descendants form one contiguous run.
    fn descendant_range<'a>(
        &'a self,
        prefix: &'a AccountPath,
    ) -> impl Iterator<Item = (&'a AccountPath, &'a AccountId)> {
        self.index
            .range(prefix.clone()..)
            .skip_while(move |(path, _)| *path == prefix)
            .take_while(move |(path, _)| path.is_under(prefix))
    }

    /// Convenience registration from a path string.
    pub fn register_path(
        &mut self,
        path: &str,
        opened_on: Date,
    ) -> Result<AccountId, AccountError> {
        self.register(Account::new(AccountPath::parse(path)?, opened_on))
    }

    /// Looks up an account by path.
    #[must_use]
    pub fn id_of(&self, path: &AccountPath) -> Option<AccountId> {
        self.index.get(path).copied()
    }

    /// Returns the account behind a handle.
    #[must_use]
    pub fn get(&self, id: AccountId) -> Option<&Account> {
        self.accounts.get(id.0 as usize)
    }

    /// True when the account has no registered descendants and may be posted to.
    #[must_use]
    pub fn is_leaf(&self, id: AccountId) -> bool {
        self.child_count.get(id.0 as usize).copied().unwrap_or(0) == 0
    }

    /// Number of registered accounts.
    #[must_use]
    pub fn len(&self) -> usize {
        self.accounts.len()
    }

    /// True when nothing is registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.accounts.is_empty()
    }

    /// Every registered account with its handle, in path order.
    pub fn iter(&self) -> impl Iterator<Item = (AccountId, &Account)> {
        self.index
            .values()
            .filter_map(|id| self.get(*id).map(|a| (*id, a)))
    }

    /// Closes an account from `on`, so postings after that date are refused.
    ///
    /// Closing is master data, not a journal event: it changes what may be
    /// booked next, and never what was booked already.
    pub fn close(&mut self, id: AccountId, on: Date) -> Result<(), AccountError> {
        let Some(account) = self.accounts.get_mut(id.index() as usize) else {
            return Err(AccountError::UnknownAccount { id });
        };
        if on < account.opened_on {
            return Err(AccountError::ClosedBeforeOpened {
                path: account.path.clone(),
                opened: account.opened_on,
                closed: on,
            });
        }
        account.closed_on = Some(on);
        Ok(())
    }

    /// Reopens a closed account.
    pub fn reopen(&mut self, id: AccountId) -> Result<(), AccountError> {
        let Some(account) = self.accounts.get_mut(id.index() as usize) else {
            return Err(AccountError::UnknownAccount { id });
        };
        account.closed_on = None;
        Ok(())
    }

    /// Sets which side an account's net balance may fall on.
    ///
    /// Master data, like closing: it governs what may be booked next and never
    /// what was booked already. Tightening a limit on an account that already
    /// breaches it is therefore permitted, and nothing recorded is invalidated.
    ///
    /// What it does mean is that the account is then frozen against any further
    /// movement the wrong way, *including a partial repair*: the rule is that
    /// the balance an accepted entry leaves behind satisfies the limit, and a
    /// half-repaired balance does not. One entry that brings it back over the
    /// line is accepted; two that each get halfway are not. Lift the limit if
    /// that is what you need, so the exception is a deliberate act on the
    /// record rather than a rule that quietly bends.
    pub fn set_limit(&mut self, id: AccountId, limit: BalanceLimit) -> Result<(), AccountError> {
        let Some(account) = self.accounts.get_mut(id.index() as usize) else {
            return Err(AccountError::UnknownAccount { id });
        };
        account.limit = limit;
        Ok(())
    }

    /// The limit on an account, or [`BalanceLimit::Unlimited`] if it is not
    /// registered.
    #[must_use]
    pub fn limit_of(&self, id: AccountId) -> BalanceLimit {
        self.get(id).map_or(BalanceLimit::Unlimited, |a| a.limit)
    }

    /// Every account with its handle, in handle order.
    ///
    /// The index cast cannot saturate: [`AccountRegistry::register`] refuses to
    /// issue a handle beyond [`MAX_ACCOUNTS`], so every position here fits.
    #[must_use]
    pub fn records(&self) -> Vec<AccountRecord> {
        self.accounts
            .iter()
            .enumerate()
            .map(|(i, account)| AccountRecord {
                id: AccountId(u32::try_from(i).unwrap_or(u32::MAX)),
                account: account.clone(),
            })
            .collect()
    }

    /// Restores one stored binding, at the handle it was issued.
    ///
    /// For a backend rehydrating a registry one record at a time, and for
    /// pushing a master-data change back to one. Unlike
    /// [`AccountRegistry::register`], which issues the next free handle, this
    /// insists the record land where it says it belongs — a binding restored at
    /// a different position would repoint every posting row that names it.
    ///
    /// At a handle already held, the **path is immutable** and everything else
    /// is master data: the classification, the open window and the balance limit
    /// are taken from the record. That is what makes closing an account or
    /// tightening a limit durable, and it is safe for the same reason those are
    /// mutable in the first place — they govern what may be booked next, never
    /// what was booked already. Restoring an unchanged record is therefore a
    /// no-op, so a backend may replay its whole account table on start-up.
    ///
    /// # Errors
    ///
    /// Returns [`AccountError::NotDense`] when the handle is neither held nor
    /// the next one, and [`AccountError::AlreadyRegistered`] when the handle is
    /// held by a *different path* — which would repoint history.
    pub fn restore(&mut self, record: AccountRecord) -> Result<(), AccountError> {
        let next = u32::try_from(self.accounts.len()).unwrap_or(u32::MAX);
        if let Some(existing) = self.get(record.id) {
            if existing.path != record.account.path {
                return Err(AccountError::AlreadyRegistered {
                    path: existing.path.clone(),
                });
            }
            if let Some(closed) = record.account.closed_on
                && closed < record.account.opened_on
            {
                return Err(AccountError::ClosedBeforeOpened {
                    path: record.account.path,
                    opened: record.account.opened_on,
                    closed,
                });
            }
            // The path is unchanged, so the index, the child counts and every
            // handle stay exactly as they were; only the mutable fields move.
            if let Some(slot) = self.accounts.get_mut(record.id.index() as usize) {
                *slot = record.account;
            }
            return Ok(());
        }
        if record.id.index() != next {
            return Err(AccountError::NotDense {
                expected: next,
                found: record.id.index(),
            });
        }
        self.register(record.account).map(|_| ())
    }

    /// Rebuilds a registry from stored bindings.
    ///
    /// Restores each account at the handle it was issued rather than reissuing
    /// handles in iteration order, which is what makes a restart safe.
    ///
    /// # Errors
    ///
    /// Returns [`AccountError::NotDense`] if the handles are not `0..n` exactly
    /// once each, and [`AccountError::AlreadyRegistered`] if two records share a
    /// path. Either means the stored set is not the one the handles were issued
    /// against, and posting against it would corrupt history.
    pub fn from_records(
        records: impl IntoIterator<Item = AccountRecord>,
    ) -> Result<Self, AccountError> {
        let mut records: Vec<_> = records.into_iter().collect();
        records.sort_by_key(|r| r.id.index());

        let mut registry = Self::new();
        for record in records {
            registry.restore(record)?;
        }
        Ok(registry)
    }

    /// A Merkle head over every handle-to-account binding, in handle order.
    ///
    /// Two registries agree on this only if they agree on every account *and*
    /// on the handle each was issued. Comparing a locally built registry
    /// against the stored one turns a silent repointing into a caught mismatch.
    ///
    /// A [`Seal`](crate::Seal) records this alongside its trial-balance head, so
    /// the handles that head is keyed on are pinned to the paths they meant at
    /// the moment of sealing. Without it, renumbering the registry afterwards
    /// would leave every seal and every balance proof verifying while every
    /// balance referred to a different account.
    ///
    /// A head and not a bare root, because the size is half of what an
    /// [`AccountBindingProof`] is checked against — see
    /// [`InclusionProof::verify`](crate::merkle::InclusionProof::verify). It
    /// also states how many handles the registry had issued, which is the number
    /// a verifier needs to know that a handle it was shown is one the registry
    /// had actually reached.
    #[must_use]
    pub fn commitment(&self) -> TreeHead {
        self.binding_log().head()
    }

    /// The commitment the registry had when it held `size` handles.
    ///
    /// A registry only ever grows — handles are dense positions and are never
    /// reissued — so its history is exactly its own prefixes, and this
    /// reconstructs any of them.
    ///
    /// A [`Seal`](crate::Seal) records
    /// [`accounts`](crate::Seal::accounts) as it stood when the period closed,
    /// and the registry has grown since — so comparing against the *current*
    /// commitment would fail for every seal but the last.
    /// [`SealChain::verify_against_accounts`](crate::SealChain::verify_against_accounts)
    /// compares against this.
    ///
    /// `None` when the registry has not issued that many handles: it cannot
    /// speak for a size it never reached.
    #[must_use]
    pub fn commitment_at(&self, size: u64) -> Option<TreeHead> {
        let n = usize::try_from(size).ok()?;
        let prefix = self.accounts.get(..n)?;
        let leaves = prefix
            .iter()
            .enumerate()
            .map(|(i, account)| {
                account_binding_leaf(
                    AccountId(u32::try_from(i).unwrap_or(u32::MAX)),
                    &account.path,
                )
            })
            .collect();
        Some(MerkleLog::from_leaves(leaves).head())
    }

    /// The Merkle log the commitment is the root of.
    ///
    /// Leaves are in handle order, so a handle is its own leaf index — which is
    /// what makes [`AccountRegistry::prove_binding`] a direct lookup.
    fn binding_log(&self) -> MerkleLog {
        MerkleLog::from_leaves(
            self.accounts
                .iter()
                .enumerate()
                .map(|(i, account)| {
                    account_binding_leaf(
                        AccountId(u32::try_from(i).unwrap_or(u32::MAX)),
                        &account.path,
                    )
                })
                .collect(),
        )
    }

    /// Proves which account a handle was issued to, against the registry as it
    /// stands now.
    ///
    /// The companion to a [`BalanceProof`](crate::BalanceProof). That proof
    /// establishes what handle `#7` held; this one establishes that `#7` is
    /// `Assets:Cash`. Together with a [`Seal`](crate::Seal) they make a closing
    /// balance a self-describing claim, checkable by someone who holds neither
    /// the trial balance nor the chart of accounts.
    ///
    /// To check against a seal taken earlier, use
    /// [`prove_binding_at`](Self::prove_binding_at): a registry that has since
    /// issued even one more handle has a different commitment, and a proof
    /// against the current one will not verify under the seal's.
    ///
    /// Returns `None` when the handle is not registered.
    #[must_use]
    pub fn prove_binding(&self, id: AccountId) -> Option<AccountBindingProof> {
        self.prove_binding_at(id, self.len() as u64)
    }

    /// Proves a binding against the commitment the registry had at `size`.
    ///
    /// The registry's counterpart to
    /// [`MerkleLog::inclusion_proof_at`](crate::MerkleLog::inclusion_proof_at),
    /// and needed for the same reason: a [`Seal`](crate::Seal) records the
    /// commitment as it stood when the period closed, and the registry has
    /// grown since. Pass [`Seal::accounts`](crate::Seal::accounts)`.size` and
    /// the proof will verify under [`Seal::accounts`](crate::Seal::accounts).
    ///
    /// This is exact rather than approximate because the leaf covers only the
    /// handle and the path. Handles are dense and issued in order and a path is
    /// never rebound, so the first `size` bindings are *the* bindings the
    /// registry held at that size — master data may have moved since and it
    /// does not matter, because the commitment never covered it.
    ///
    /// ```
    /// # use doubleentry::{AccountRegistry, AccountId};
    /// # use time::macros::date;
    /// let mut registry = AccountRegistry::new();
    /// let cash = registry.register_path("Assets:Cash", date!(2026-01-01))?;
    /// registry.register_path("Income:Sales", date!(2026-01-01))?;
    /// let sealed = registry.commitment();
    ///
    /// // The books move on: a new account, and the old one closes.
    /// registry.register_path("Assets:Bank", date!(2026-04-01))?;
    /// registry.close(cash, date!(2026-04-30))?;
    ///
    /// // The binding as of the seal still proves.
    /// let binding = registry.prove_binding_at(cash, sealed.size).expect("issued by then");
    /// assert!(binding.verify(&sealed));
    /// assert_eq!(binding.path().to_string(), "Assets:Cash");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Returns `None` when `size` is beyond the registry, or when the handle had
    /// not been issued by then — which is the honest answer: an account the
    /// registry had not reached is not one that seal can name.
    #[must_use]
    pub fn prove_binding_at(&self, id: AccountId, size: u64) -> Option<AccountBindingProof> {
        let n = usize::try_from(size).ok()?;
        if n > self.accounts.len() || usize::try_from(id.index()).ok()? >= n {
            return None;
        }
        let path = self.get(id)?.path.clone();
        let leaves = self
            .accounts
            .get(..n)?
            .iter()
            .enumerate()
            .map(|(i, account)| {
                account_binding_leaf(
                    AccountId(u32::try_from(i).unwrap_or(u32::MAX)),
                    &account.path,
                )
            })
            .collect();
        let proof = MerkleLog::from_leaves(leaves)
            .inclusion_proof(u64::from(id.index()))
            .ok()?;
        Some(AccountBindingProof { id, path, proof })
    }

    /// Handles of every account at or below `prefix`, in path order.
    ///
    /// Includes `prefix` itself when it is registered, so this is the set a
    /// rollup over that node covers.
    #[must_use]
    pub fn descendants_of(&self, prefix: &AccountPath) -> Vec<AccountId> {
        self.index
            .range(prefix.clone()..)
            .take_while(|(path, _)| path.is_under(prefix))
            .map(|(_, id)| *id)
            .collect()
    }
}

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

    fn reg() -> AccountRegistry {
        AccountRegistry::new()
    }

    #[test]
    fn parses_and_displays_a_path() {
        let p = AccountPath::parse("Assets:Bank:Main").expect("valid");
        assert_eq!(p.depth(), 3);
        assert_eq!(p.to_string(), "Assets:Bank:Main");
    }

    #[test]
    fn rejects_malformed_paths() {
        assert_eq!(AccountPath::parse(""), Err(AccountError::Empty));
        assert!(matches!(
            AccountPath::parse("Assets::Main"),
            Err(AccountError::EmptySegment { position: 1 })
        ));
        assert!(matches!(
            AccountPath::parse("Assets:"),
            Err(AccountError::EmptySegment { position: 1 })
        ));
        assert!(matches!(
            AccountPath::parse(&"x".repeat(MAX_SEGMENT_LEN + 1)),
            Err(AccountError::SegmentTooLong { position: 0 })
        ));
        assert!(matches!(
            AccountPath::parse("Assets:Ba\nk"),
            Err(AccountError::ControlCharacter { position: 1 })
        ));
    }

    #[test]
    fn rejects_excessive_depth() {
        let deep = (0..=MAX_DEPTH).map(|i| i.to_string()).collect::<Vec<_>>();
        assert_eq!(AccountPath::from_segments(deep), Err(AccountError::TooDeep));
    }

    #[test]
    fn computes_ancestry() {
        let p = AccountPath::parse("A:B:C").expect("valid");
        assert_eq!(p.parent().expect("has parent").to_string(), "A:B");
        let ancestors: Vec<String> = p.ancestors().iter().map(ToString::to_string).collect();
        assert_eq!(ancestors, vec!["A", "A:B"]);
        assert!(AccountPath::parse("A").expect("valid").parent().is_none());
    }

    #[test]
    fn a_historical_commitment_is_the_registry_that_stopped_there() {
        let mut registry = reg();
        for path in ["A:One", "B:Two", "C:Three"] {
            registry
                .register_path(path, date!(2020 - 01 - 01))
                .expect("registers");
        }
        for n in 0..=3usize {
            let mut partial = reg();
            for path in ["A:One", "B:Two", "C:Three"].iter().take(n) {
                partial
                    .register_path(path, date!(2020 - 01 - 01))
                    .expect("registers");
            }
            assert_eq!(
                registry
                    .commitment_at(n as u64)
                    .expect("within the registry"),
                partial.commitment(),
                "at {n} handles"
            );
        }
        // It cannot speak for a size it never reached.
        assert!(registry.commitment_at(4).is_none());
    }

    #[test]
    fn master_data_does_not_move_the_commitment() {
        // The property the whole design of the binding leaf rests on: closing an
        // account on a Tuesday must not invalidate every binding proof against
        // every seal ever issued.
        let mut registry = reg();
        let id = registry
            .register_path("Assets:Cash", date!(2020 - 01 - 01))
            .expect("registers");
        registry
            .register_path("Income:Sales", date!(2020 - 01 - 01))
            .expect("registers");
        let before = registry.commitment();

        registry.close(id, date!(2026 - 06 - 30)).expect("closes");
        registry
            .set_limit(id, BalanceLimit::NoCreditBalance)
            .expect("limits");
        assert_eq!(registry.commitment(), before);
        assert_eq!(registry.commitment_at(2).expect("in range"), before);
    }

    #[test]
    fn is_under_matches_whole_segments_only() {
        let child = AccountPath::parse("Assets:Bank").expect("valid");
        let prefix = AccountPath::parse("Assets").expect("valid");
        let decoy = AccountPath::parse("Asset").expect("valid");
        assert!(child.is_under(&prefix));
        assert!(child.is_under(&child));
        assert!(!child.is_under(&decoy));
    }

    #[test]
    fn registers_and_looks_up() {
        let mut r = reg();
        let id = r
            .register_path("Assets:Bank", date!(2026 - 01 - 01))
            .expect("registers");
        let path = AccountPath::parse("Assets:Bank").expect("valid");
        assert_eq!(r.id_of(&path), Some(id));
        assert_eq!(r.get(id).expect("exists").path, path);
        assert_eq!(r.len(), 1);
    }

    #[test]
    fn rejects_duplicate_registration() {
        let mut r = reg();
        r.register_path("Assets", date!(2026 - 01 - 01))
            .expect("registers");
        assert!(matches!(
            r.register_path("Assets", date!(2026 - 01 - 01)),
            Err(AccountError::AlreadyRegistered { .. })
        ));
    }

    #[test]
    fn rejects_closing_before_opening() {
        let mut r = reg();
        let acct = Account::new(
            AccountPath::parse("A").expect("valid"),
            date!(2026 - 06 - 01),
        )
        .closing_on(date!(2026 - 01 - 01));
        assert!(matches!(
            r.register(acct),
            Err(AccountError::ClosedBeforeOpened { .. })
        ));
    }

    #[test]
    fn a_parent_registered_first_stops_being_a_leaf() {
        let mut r = reg();
        let parent = r
            .register_path("Assets", date!(2026 - 01 - 01))
            .expect("registers");
        assert!(r.is_leaf(parent));
        r.register_path("Assets:Bank", date!(2026 - 01 - 01))
            .expect("registers");
        assert!(!r.is_leaf(parent));
    }

    #[test]
    fn a_parent_registered_later_is_not_a_leaf() {
        let mut r = reg();
        let child = r
            .register_path("Assets:Bank", date!(2026 - 01 - 01))
            .expect("registers");
        let parent = r
            .register_path("Assets", date!(2026 - 01 - 01))
            .expect("registers");
        assert!(!r.is_leaf(parent));
        assert!(r.is_leaf(child));
    }

    #[test]
    fn open_window_is_inclusive() {
        let a = Account::new(
            AccountPath::parse("A").expect("valid"),
            date!(2026 - 01 - 01),
        )
        .closing_on(date!(2026 - 12 - 31));
        assert!(!a.is_open_on(date!(2025 - 12 - 31)));
        assert!(a.is_open_on(date!(2026 - 01 - 01)));
        assert!(a.is_open_on(date!(2026 - 12 - 31)));
        assert!(!a.is_open_on(date!(2027 - 01 - 01)));
    }

    #[test]
    fn account_without_closing_date_stays_open() {
        let a = Account::new(
            AccountPath::parse("A").expect("valid"),
            date!(2026 - 01 - 01),
        );
        assert!(a.is_open_on(date!(2999 - 01 - 01)));
    }

    #[test]
    fn descendants_are_returned_in_path_order() {
        let mut r = reg();
        r.register_path("Assets:Cash", date!(2026 - 01 - 01))
            .expect("registers");
        r.register_path("Assets:Bank", date!(2026 - 01 - 01))
            .expect("registers");
        r.register_path("Income:Sales", date!(2026 - 01 - 01))
            .expect("registers");
        let prefix = AccountPath::parse("Assets").expect("valid");
        let found: Vec<String> = r
            .descendants_of(&prefix)
            .into_iter()
            .filter_map(|id| r.get(id).map(|a| a.path.to_string()))
            .collect();
        assert_eq!(found, vec!["Assets:Bank", "Assets:Cash"]);
    }

    #[test]
    fn normal_sides_follow_the_accounting_equation() {
        use crate::posting::Direction;
        assert_eq!(AccountKind::Asset.normal_side(), Direction::Debit);
        assert_eq!(AccountKind::Expense.normal_side(), Direction::Debit);
        assert_eq!(AccountKind::Liability.normal_side(), Direction::Credit);
        assert_eq!(AccountKind::Equity.normal_side(), Direction::Credit);
        assert_eq!(AccountKind::Income.normal_side(), Direction::Credit);
    }

    #[test]
    fn the_commitment_changes_when_a_handle_moves() {
        // The property the whole binding commitment exists for: two registries
        // holding the same paths, issued in different orders, are not the same
        // registry — because every posting row and every sealed balance names
        // an account by its handle.
        let build = |paths: [&str; 2]| {
            let mut r = reg();
            for p in paths {
                r.register_path(p, date!(2026 - 01 - 01))
                    .expect("registers");
            }
            r
        };
        let forward = build(["Assets:Cash", "Income:Sales"]);
        let swapped = build(["Income:Sales", "Assets:Cash"]);

        assert_ne!(forward.commitment(), swapped.commitment());
        // … and rebuilding the same order reproduces it exactly.
        assert_eq!(
            forward.commitment(),
            build(["Assets:Cash", "Income:Sales"]).commitment()
        );
    }

    #[test]
    fn every_binding_proves_against_the_commitment() {
        let mut r = reg();
        for i in 0..17 {
            r.register_path(&format!("Assets:A{i}"), date!(2026 - 01 - 01))
                .expect("registers");
        }
        let root = r.commitment();
        for (id, account) in r.iter() {
            let proof = r.prove_binding(id).expect("registered");
            assert!(proof.verify(&root), "binding for {id} must prove");
            assert_eq!(*proof.path(), account.path);
        }
        assert!(r.prove_binding(AccountId::from_index(99)).is_none());
    }

    #[test]
    fn a_binding_proof_pins_the_path_and_the_handle() {
        let mut r = reg();
        let id = r
            .register_path("Assets:Cash", date!(2026 - 01 - 01))
            .expect("registers");
        r.register_path("Income:Sales", date!(2026 - 01 - 01))
            .expect("registers");
        let root = r.commitment();
        let proof = r.prove_binding(id).expect("registered");
        assert!(proof.verify(&root));

        // Claiming a different path under the same handle.
        let mut renamed = proof.clone();
        renamed.path = AccountPath::parse("Assets:Slush").expect("valid");
        assert!(!renamed.verify(&root));

        // Claiming a different handle for the same path.
        let mut moved = proof;
        moved.id = AccountId::from_index(1);
        assert!(!moved.verify(&root));
    }

    #[test]
    fn master_data_does_not_move_the_binding_commitment() {
        // The property the whole seal-naming path depends on. Closing an account
        // or tightening its limit is an ordinary Tuesday — the registry's own
        // mutators exist to do it — and it must not retroactively invalidate
        // every binding proof against every seal ever issued.
        let mut r = reg();
        let id = r
            .register_path("Assets:Cash", date!(2026 - 01 - 01))
            .expect("registers");
        r.register_path("Income:Sales", date!(2026 - 01 - 01))
            .expect("registers");

        let sealed = r.commitment();
        let proof = r.prove_binding(id).expect("registered");
        assert!(proof.verify(&sealed));

        r.close(id, date!(2026 - 06 - 30)).expect("registered");
        r.set_limit(id, BalanceLimit::NoCreditBalance)
            .expect("registered");
        assert_eq!(r.commitment(), sealed, "master data is not identity");
        assert!(
            proof.verify(&sealed),
            "a proof taken before the change must still hold"
        );
        assert!(
            r.prove_binding(id).expect("registered").verify(&sealed),
            "and one taken after must hold against the same head"
        );
    }

    #[test]
    fn a_binding_proves_against_the_commitment_the_registry_had_at_a_size() {
        // What a seal actually needs. `Seal::accounts` is the commitment as it
        // stood when the period closed; the registry has grown since, and a
        // proof against the current one does not verify under it.
        let mut r = reg();
        let mut sealed_at = Vec::new();
        for i in 0..9u32 {
            r.register_path(&format!("Assets:A{i}"), date!(2026 - 01 - 01))
                .expect("registers");
            sealed_at.push(r.commitment());
        }

        for (i, head) in sealed_at.iter().enumerate() {
            let issued_by_then = u32::try_from(i).expect("small") + 1;
            for handle in 0..issued_by_then {
                let id = AccountId::from_index(handle);
                let binding = r
                    .prove_binding_at(id, head.size)
                    .expect("issued by that size");
                assert!(
                    binding.verify(head),
                    "handle {handle} under size {}",
                    head.size
                );
                // And it is worthless against any other size's head.
                for other in sealed_at.iter().filter(|h| h.size != head.size) {
                    assert!(!binding.verify(other));
                }
            }
            // A handle the registry had not reached is not one that head names.
            assert!(
                r.prove_binding_at(AccountId::from_index(issued_by_then), head.size)
                    .is_none()
            );
        }

        // Beyond the registry entirely.
        assert!(r.prove_binding_at(AccountId::from_index(0), 99).is_none());
    }

    /// Builds a balance from `(debit, credit)` gross totals in minor units.
    fn bal(debits: i64, credits: i64) -> Balance<2> {
        Balance {
            debits: crate::money::Amount::<2>::from_minor(debits),
            credits: crate::money::Amount::<2>::from_minor(credits),
        }
    }

    #[test]
    fn a_limit_constrains_the_net_and_ignores_the_gross() {
        // Turnover in both directions, net zero: every limit tolerates it.
        let heavy = bal(1_000, 1_000);
        for limit in [
            BalanceLimit::Unlimited,
            BalanceLimit::NoCreditBalance,
            BalanceLimit::NoDebitBalance,
        ] {
            assert!(
                limit.permits(&heavy, &Balance::ZERO),
                "{limit} should permit a zero net"
            );
        }

        let overdrawn = bal(0, 1);
        assert!(BalanceLimit::Unlimited.permits(&overdrawn, &Balance::ZERO));
        assert!(!BalanceLimit::NoCreditBalance.permits(&overdrawn, &Balance::ZERO));
        assert!(BalanceLimit::NoDebitBalance.permits(&overdrawn, &Balance::ZERO));
    }

    #[test]
    fn a_reservation_consumes_headroom_and_an_expected_inflow_does_not() {
        // A wallet funded with 100, limited so it cannot be drawn past what it
        // holds. This is the case the whole two-layer fold exists for.
        let funded = bal(0, 100);
        let limit = BalanceLimit::NoDebitBalance;
        assert_eq!(limit.headroom_minor(&funded, &Balance::ZERO), Some(100));

        // A reservation of 30 is money already promised: it takes 30 of room.
        let held = bal(30, 0);
        assert_eq!(limit.headroom_minor(&funded, &held), Some(70));
        assert!(limit.permits(&funded, &held));

        // A second reservation of 80 would put it 10 past the limit.
        assert_eq!(limit.headroom_minor(&funded, &bal(110, 0)), Some(-10));
        assert!(!limit.permits(&funded, &bal(110, 0)));

        // Discharging the first reservation nets its pending side to zero and
        // moves 30 into the settled layer. The room comes back.
        assert_eq!(limit.headroom_minor(&bal(30, 100), &bal(30, 30)), Some(70));

        // A reservation the *other* way is an inflow that has not arrived, and
        // grants no room at all.
        assert_eq!(limit.headroom_minor(&funded, &bal(0, 500)), Some(100));
    }

    #[test]
    fn the_two_limits_are_mirror_images() {
        // Same arithmetic, opposite side: a cash box that cannot be overdrawn.
        let funded = bal(500, 0);
        let limit = BalanceLimit::NoCreditBalance;
        assert_eq!(limit.headroom_minor(&funded, &Balance::ZERO), Some(500));
        // A reserved outflow from an asset is a pending credit.
        assert_eq!(limit.headroom_minor(&funded, &bal(0, 100)), Some(400));
        assert_eq!(limit.headroom_minor(&funded, &bal(0, 550)), Some(-50));
        // A reserved inflow grants nothing until it settles.
        assert_eq!(limit.headroom_minor(&funded, &bal(900, 0)), Some(500));
        // And an unlimited account has no room to run out of.
        assert_eq!(
            BalanceLimit::Unlimited.headroom_minor(&funded, &bal(0, 9_999)),
            None
        );
    }

    #[test]
    fn headroom_is_total_at_the_extremes() {
        // Every path is `i128` arithmetic over two `i64`s, so no balance exists
        // that this cannot answer for — including ones that would overflow if
        // the totals were added in `i64`.
        let extreme = bal(i64::MAX, i64::MIN);
        for limit in [
            BalanceLimit::Unlimited,
            BalanceLimit::NoCreditBalance,
            BalanceLimit::NoDebitBalance,
        ] {
            let _ = limit.headroom_minor(&extreme, &extreme);
            let _ = limit.permits(&extreme, &extreme);
        }
    }

    #[test]
    fn a_limit_is_master_data_and_not_identity() {
        // A limit governs what may be booked next, so it is mutable by design —
        // and therefore must stay *out* of the binding commitment. Hashing it in
        // meant that tightening a limit invalidated every binding proof against
        // every seal already issued, which is a routine operation reading as
        // evidence of tampering.
        let mut r = reg();
        let id = r
            .register_path("Assets:Cash", date!(2026 - 01 - 01))
            .expect("registers");
        let before = r.commitment();
        r.set_limit(id, BalanceLimit::NoCreditBalance)
            .expect("registered");
        assert_eq!(r.limit_of(id), BalanceLimit::NoCreditBalance);
        assert_eq!(r.commitment(), before);

        assert!(matches!(
            r.set_limit(AccountId::from_index(9), BalanceLimit::Unlimited),
            Err(AccountError::UnknownAccount { .. })
        ));
        assert_eq!(
            r.limit_of(AccountId::from_index(9)),
            BalanceLimit::Unlimited
        );
    }

    #[test]
    fn restoring_a_binding_updates_its_master_data_but_never_its_path() {
        // The write direction of a restart. A store that could only ever insert
        // could not close an account or tighten a limit — the registry's own
        // mutators would have nowhere to go the moment a ledger became durable.
        let mut r = reg();
        let id = r
            .register_path("Assets:Cash", date!(2026 - 01 - 01))
            .expect("registers");

        let mut record = AccountRecord {
            id,
            account: Account::new(
                AccountPath::parse("Assets:Cash").expect("valid"),
                date!(2026 - 01 - 01),
            ),
        };
        // Restoring it unchanged is a no-op, so a backend may replay its table.
        r.restore(record.clone()).expect("unchanged");
        assert_eq!(r.len(), 1);

        record.account = record
            .account
            .clone()
            .with_kind(AccountKind::Asset)
            .closing_on(date!(2026 - 12 - 31))
            .limited_to(BalanceLimit::NoCreditBalance);
        r.restore(record.clone()).expect("master data moves");
        let stored = r.get(id).expect("registered");
        assert_eq!(stored.kind, Some(AccountKind::Asset));
        assert_eq!(stored.closed_on, Some(date!(2026 - 12 - 31)));
        assert_eq!(stored.limit, BalanceLimit::NoCreditBalance);
        assert_eq!(r.len(), 1, "an update must not issue a second handle");

        // The path is not master data: rebinding a handle would repoint every
        // posting row and every sealed balance that names it.
        let mut rebound = record.clone();
        rebound.account.path = AccountPath::parse("Assets:Slush").expect("valid");
        assert!(matches!(
            r.restore(rebound),
            Err(AccountError::AlreadyRegistered { .. })
        ));
        assert_eq!(
            r.get(id).expect("registered").path.to_string(),
            "Assets:Cash"
        );

        // An update is still refused if it would invert the open window.
        let mut inverted = record;
        inverted.account.closed_on = Some(date!(2020 - 01 - 01));
        assert!(matches!(
            r.restore(inverted),
            Err(AccountError::ClosedBeforeOpened { .. })
        ));
    }

    #[test]
    fn path_hash_is_stable_and_distinguishing() {
        let a = AccountPath::parse("A:B").expect("valid");
        let b = AccountPath::parse("A:B").expect("valid");
        let c = AccountPath::parse("AB").expect("valid");
        assert_eq!(a.content_hash(), b.content_hash());
        assert_ne!(a.content_hash(), c.content_hash());
    }
}