crtx-ledger 0.1.0

Append-only event log, hash chain, trace assembly, and audit records.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
//! Live OpenTimestamps submit + verify adapter (Gate 4).
//!
//! This is the trust-path consumer of [`super::OtsParser`]. It bridges
//! between the [`crate::external_sink::ExternalReceipt`] envelope and
//! the typed [`super::TypedOtsProof`] output of the trait wrapper.
//!
//! Doctrine bindings:
//!
//! - **HTTP injection.** Cargo.lock mutation is only authorized for
//!   `opentimestamps` itself (operator decision #4). The adapter does
//!   not pin a specific HTTP client; the [`CalendarClient`] trait is
//!   the seam an operator's deployment plugs into. The default
//!   [`NoopCalendarClient`] is hard-coded to refuse and exists so the
//!   CLI surface compiles without an HTTP dependency — a real
//!   submission requires an operator-supplied client.
//! - **Pending → Partial always.** [`verify_receipt`] maps Pending to
//!   [`OtsVerificationOutcome::Partial`] regardless of caller flag
//!   (hard rule). The CLI / verifier crate converts the local outcome
//!   to `cortex_verifier::state::VerifiedTrustState` so that this
//!   crate avoids depending on `cortex-verifier` (which already
//!   depends on `cortex-ledger`).
//! - **Bitcoin cross-check.** A `BitcoinConfirmed` proof is only
//!   promoted to [`OtsVerificationOutcome::FullChainVerified`] when
//!   the adapter has a [`BitcoinHeaderSource`] that confirms the
//!   attestation's block height carries a header whose merkle root
//!   matches the recomputed commitment-op digest. Without a header
//!   source (v1 default) the adapter degrades to `Partial` with the
//!   `ots.bitcoin_confirmed.block_header_mismatch` invariant.
//! - **N≥2 disjoint-authority calendar quorum** (council 2026-05-12
//!   Decision Q1, UNANIMOUS). A receipt history MAY produce
//!   `FullChainVerified` only when at least two calendars in the
//!   history witness the same anchor AND at least one of them belongs
//!   to a different operator. The three Todd-administered endpoints
//!   (`a.pool`, `alice`, `bob`) collapse to one authority for the
//!   disjointness check; the Eternitywall Finney endpoint is the
//!   default non-Todd witness. Failures surface the stable
//!   [`OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT`]
//!   (`ots.disjoint_authority.quorum_not_met`) token and the receipt
//!   is downgraded to `Partial`.
//! - **Headers-only HTTPS Bitcoin transport** (council 2026-05-12
//!   Decision Q2 + Q3, UNANIMOUS). The
//!   [`HttpsHeadersBitcoinHeaderSource`] fetches block headers from
//!   N administratively-disjoint HTTPS providers and requires
//!   byte-identical responses from at least N providers (default 2).
//!   Single-provider + local PoW alone cannot detect block
//!   withholding / stale-tip attacks (Q3 doctrinaire vote), so the
//!   quorum is mandatory. Failures surface
//!   `ots.bitcoin_header_quorum.providers_disagree` or
//!   `ots.bitcoin_header_quorum.unreachable`.

use chrono::{DateTime, Utc};
use serde_json::json;

use super::{
    DefaultOtsParser, OtsError, OtsParser, TypedOtsProof,
    OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT,
    OTS_BITCOIN_CONFIRMED_MERKLE_PATH_INVALID_INVARIANT, OTS_BITCOIN_HEADER_POW_INVALID_INVARIANT,
    OTS_BITCOIN_HEADER_QUORUM_PROVIDERS_DISAGREE_INVARIANT,
    OTS_BITCOIN_HEADER_QUORUM_UNREACHABLE_INVARIANT,
    OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT,
    OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT,
};
use crate::anchor::LedgerAnchor;
use crate::external_sink::{anchor_text_sha256, ExternalReceipt, ExternalSink};

/// Default public OTS calendar pool (council 2026-05-12 Q1 ratified
/// default set, UNANIMOUS). Operators may override via
/// `--sink-endpoint` on the CLI; this constant is the fallback used by
/// the documented happy path in `docs/RUNBOOK.md`.
///
/// Back-compat alias: points at the FIRST entry of
/// [`DEFAULT_OTS_CALENDAR_URLS`] (`a.pool.opentimestamps.org`,
/// Peter-Todd-operated). New code SHOULD prefer
/// [`DEFAULT_OTS_CALENDAR_URLS`] so the operator-disjoint quorum check
/// (see [`enforce_disjoint_authority_quorum`]) has more than one
/// authority to draw from.
pub const DEFAULT_OTS_CALENDAR_URL: &str = "https://a.pool.opentimestamps.org";

/// Default OpenTimestamps calendar list ratified by council
/// 2026-05-12 Decision Q1 (UNANIMOUS). The first three endpoints are
/// administered by Peter Todd and collapse to a single authority for
/// the disjoint-authority quorum check ([`calendar_operator`]); the
/// Eternitywall Finney endpoint is the default non-Todd witness.
///
/// Fan-out submission against this list is what makes a
/// `FullChainVerified` promotion reachable under the
/// N≥2-distinct-operators rule documented at the module level. Calling
/// only the first entry (`a.pool`) keeps the receipt history at a
/// single Todd-operated authority and pins promotion to `Partial` with
/// [`OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT`].
pub const DEFAULT_OTS_CALENDAR_URLS: &[&str] = &[
    "https://a.pool.opentimestamps.org",
    "https://alice.btc.calendar.opentimestamps.org",
    "https://bob.btc.calendar.opentimestamps.org",
    "https://finney.calendar.eternitywall.com",
];

/// Operator-of-record for each OTS calendar URL. Council 2026-05-12
/// Decision Q1 doctrinaire position: three Todd endpoints share a
/// single administrative authority and MUST collapse for any
/// disjoint-authority quorum check.
///
/// The mapping needles are **canonical hostnames** (no scheme, no path,
/// no port). [`calendar_operator`] parses the candidate URL, extracts
/// the host, and matches with `host == needle || host.ends_with(".{needle}")`
/// so that legitimate subdomains (e.g. `alice.btc.calendar.opentimestamps.org`
/// under the `calendar.opentimestamps.org` zone) resolve to the
/// expected operator while attacker-supplied URLs that embed a known
/// hostname in their path or query (e.g.
/// `https://attacker.example/?h=finney.calendar.eternitywall.com`) do
/// **not**. See [`calendar_operator`] and Bug Hunt 2026-05-12 finding
/// BH-1 for the substring-match regression this exact-host rule closes.
pub const OTS_CALENDAR_OPERATORS: &[(&str, &str)] = &[
    ("a.pool.opentimestamps.org", "peter_todd"),
    ("alice.btc.calendar.opentimestamps.org", "peter_todd"),
    ("bob.btc.calendar.opentimestamps.org", "peter_todd"),
    ("finney.calendar.eternitywall.com", "eternitywall"),
];

/// Extract the host component of `url` for [`calendar_operator`].
///
/// Returns `None` if the input cannot be parsed as an absolute URL
/// with a host. This is option B from Bug Hunt 2026-05-12 BH-1: avoid
/// pulling the `url` crate into the workspace (zero `Cargo.lock`
/// delta) and parse manually.
///
/// Recognized shape: `scheme://[userinfo@]host[:port][/path][?query][#frag]`.
/// `scheme` MUST be present (`://` delimiter); anything that fails the
/// recognized shape returns `None` and therefore matches no operator.
/// The host is lower-cased (DNS is case-insensitive) so the
/// exact-match comparison against the lower-case needles in
/// [`OTS_CALENDAR_OPERATORS`] is deterministic.
fn calendar_host_lower(url: &str) -> Option<String> {
    // Require `scheme://` — no scheme means we cannot trust which
    // component is the host. Refuse rather than guess.
    let after_scheme = {
        let idx = url.find("://")?;
        let scheme = &url[..idx];
        // RFC 3986 scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
        if scheme.is_empty()
            || !scheme
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
            || !scheme
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic())
        {
            return None;
        }
        &url[idx + 3..]
    };

    // Authority component ends at the first '/', '?', or '#'.
    let authority_end = after_scheme
        .find(['/', '?', '#'])
        .unwrap_or(after_scheme.len());
    let authority = &after_scheme[..authority_end];
    if authority.is_empty() {
        return None;
    }

    // Strip optional `userinfo@`. RFC 3986 allows '@' inside userinfo
    // only as a percent-encoded triplet (`%40`), so a literal '@' is
    // unambiguous. Use rfind so that a stray '@' inside userinfo (e.g.
    // `user@:p@ss@host`) still leaves the rightmost '@' as the
    // host-delimiter — same behavior as `url::Url`.
    let host_port = match authority.rfind('@') {
        Some(idx) => &authority[idx + 1..],
        None => authority,
    };

    // Strip optional `:port`. IPv6 literals are bracketed (`[::1]:443`)
    // — only treat the LAST `:` outside any bracket pair as the port
    // delimiter. We do not actually support OTS calendar URLs over
    // IPv6 today, but handle the shape correctly so a future bracket
    // form does not slip past the host check.
    let host = if let Some(stripped) = host_port.strip_prefix('[') {
        let close = stripped.find(']')?;
        &host_port[..close + 2] // include the closing ']' and bracketed host
    } else if let Some(colon) = host_port.rfind(':') {
        &host_port[..colon]
    } else {
        host_port
    };

    if host.is_empty() {
        return None;
    }

    // Reject any host that still contains characters outside the
    // RFC 3986 `reg-name` / IP-literal grammar. Notably refuse
    // whitespace, slashes, '?', '#', and '@' — defense in depth in
    // case a future refactor reorders the splits above.
    if host
        .chars()
        .any(|c| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '@'))
    {
        return None;
    }

    Some(host.to_ascii_lowercase())
}

/// Look up the operator-of-record for an OTS calendar URL by
/// **exact-host** match against [`OTS_CALENDAR_OPERATORS`]. Returns
/// `None` for an unknown calendar, for any input that does not parse
/// as an absolute URL with a host, or for any host that is neither
/// the canonical needle nor a subdomain of it.
///
/// Matching rule per needle `n`: `host == n || host.ends_with(".{n}")`.
/// The subdomain clause covers the legitimate fan-out shape (e.g.
/// `alice.btc.calendar.opentimestamps.org` under the
/// `calendar.opentimestamps.org` zone) without admitting attacker
/// strings that embed a known hostname in a query or path component.
///
/// Council Q1 hard rule: the disjoint-authority quorum check treats
/// unknown calendars as their own (unverifiable) authority and refuses
/// to count them toward a `FullChainVerified` promotion. See Bug Hunt
/// 2026-05-12 BH-1 (substring-match bypass) for the regression this
/// closes.
#[must_use]
pub fn calendar_operator(url: &str) -> Option<&'static str> {
    let host = calendar_host_lower(url)?;
    for (needle, operator) in OTS_CALENDAR_OPERATORS {
        // Needles are stored lower-case; assert (debug only) that the
        // invariant holds so a future maintainer cannot quietly add a
        // mixed-case entry that bypasses the exact-host check.
        debug_assert_eq!(
            *needle,
            needle.to_ascii_lowercase(),
            "OTS_CALENDAR_OPERATORS needles MUST be lower-case to match calendar_host_lower output",
        );
        if host == *needle {
            return Some(*operator);
        }
        // Subdomain match: `alice.btc.calendar.opentimestamps.org`
        // matches `calendar.opentimestamps.org`. Use a leading-dot
        // check so `evilopentimestamps.org` does NOT match
        // `opentimestamps.org` and `xfinney.calendar.eternitywall.com`
        // does NOT match `finney.calendar.eternitywall.com`.
        if host.len() > needle.len() + 1
            && host.ends_with(needle)
            && host.as_bytes()[host.len() - needle.len() - 1] == b'.'
        {
            return Some(*operator);
        }
    }
    None
}

/// Pluggable calendar HTTP client. The trait exists so operators (and
/// tests) can supply their own transport without making `cortex-ledger`
/// depend on a heavyweight HTTP crate.
///
/// Contract: `digest` is exactly 32 bytes (SHA-256). The client POSTs
/// it to `<calendar_url>/digest` per the OpenTimestamps calendar API
/// and returns the raw `.ots` Pending proof bytes.
pub trait CalendarClient {
    /// Submit a SHA-256 digest to the calendar and return the Pending
    /// `.ots` bytes the server emits.
    fn submit_digest(&self, calendar_url: &str, digest: &[u8; 32]) -> Result<Vec<u8>, OtsError>;
}

/// Fail-closed default [`CalendarClient`]. Operators MUST inject a
/// real client to actually submit. Exists so the CLI surface compiles
/// without binding cortex-ledger to a specific HTTP stack and so a
/// missing-transport misconfiguration surfaces as an obvious adapter
/// error rather than silently working against a mock.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopCalendarClient;

impl CalendarClient for NoopCalendarClient {
    fn submit_digest(&self, calendar_url: &str, _digest: &[u8; 32]) -> Result<Vec<u8>, OtsError> {
        Err(OtsError::OtsCrateError(format!(
            "no live calendar HTTP client configured for `{calendar_url}` (NoopCalendarClient); \
             operator must inject a CalendarClient implementation"
        )))
    }
}

/// Default per-request HTTP timeout for the live [`UreqCalendarClient`].
/// Matches [`HTTPS_HEADER_PROVIDER_TIMEOUT`]: short enough that a slow
/// calendar does not strand the operator, long enough to absorb normal
/// jitter on public OTS infra.
const UREQ_CALENDAR_CLIENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);

/// Live [`CalendarClient`] backed by the workspace-authorized `ureq`
/// HTTP stack (council Q5 / Decision #4 of
/// `docs/decisions/COUNCIL_TIEBREAKS_2026_05_14.md`).
///
/// Mirrors the construction pattern already in use by
/// [`HttpsHeadersBitcoinHeaderSource::fetch_one_provider`] (this same
/// file) and `crates/cortex-ledger/src/external_sink/rekor.rs`. No new
/// direct dep edges — `ureq` is already a `cortex-ledger` workspace
/// dependency at `crates/cortex-ledger/Cargo.toml`.
///
/// Contract per [`CalendarClient::submit_digest`]:
///
/// - POSTs the 32-byte SHA-256 digest to `{calendar_url}/digest`.
/// - Returns the raw Pending `.ots` bytes the calendar emits.
/// - Wraps any transport error as
///   [`OtsError::OtsCrateError`] (consistent with the existing
///   `HttpsHeadersBitcoinHeaderSource::fetch_one_provider` convention
///   at this file).
/// - Retry policy: single-shot. The structural redundancy is the fan-out
///   across [`DEFAULT_OTS_CALENDAR_URLS`] (council Q1) at the caller —
///   per-URL retries inside this client double-count witnesses and can
///   mask a quorum-failing outage.
#[derive(Debug, Clone, Copy)]
pub struct UreqCalendarClient {
    timeout: std::time::Duration,
}

impl Default for UreqCalendarClient {
    fn default() -> Self {
        Self::new()
    }
}

impl UreqCalendarClient {
    /// Construct a new [`UreqCalendarClient`] with the default
    /// per-request timeout ([`UREQ_CALENDAR_CLIENT_TIMEOUT`], 15 s).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            timeout: UREQ_CALENDAR_CLIENT_TIMEOUT,
        }
    }

    /// Override the per-request HTTP timeout. Mirrors
    /// [`HttpsHeadersBitcoinHeaderSource::with_timeout`].
    #[must_use]
    pub const fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }
}

impl CalendarClient for UreqCalendarClient {
    fn submit_digest(&self, calendar_url: &str, digest: &[u8; 32]) -> Result<Vec<u8>, OtsError> {
        let agent = ureq::AgentBuilder::new().timeout(self.timeout).build();
        let url = format!("{}/digest", calendar_url.trim_end_matches('/'));
        let response = agent
            .post(&url)
            .set("Content-Type", "application/vnd.opentimestamps.v1")
            .send_bytes(digest)
            .map_err(|err| OtsError::OtsCrateError(format!("POST {url}: {err}")))?;
        let mut bytes = Vec::new();
        use std::io::Read as _;
        response
            .into_reader()
            .read_to_end(&mut bytes)
            .map_err(|err| OtsError::OtsCrateError(format!("read body {url}: {err}")))?;
        Ok(bytes)
    }
}

/// Submit a position-bound [`LedgerAnchor`] to an OpenTimestamps
/// calendar via the supplied [`CalendarClient`] and return the
/// `ExternalReceipt` sidecar.
///
/// The digest sent to the calendar is the SHA-256 of the canonical
/// anchor text — same value `verify_external_receipts` recomputes from
/// the local ledger. This keeps the round trip a closed contract:
/// `anchor_text_sha256` is the only digest the calendar ever sees, and
/// it is the only digest the receipt envelope carries.
pub fn submit<C>(
    anchor: &LedgerAnchor,
    calendar_url: &str,
    submitted_at: DateTime<Utc>,
    client: &C,
) -> Result<ExternalReceipt, OtsError>
where
    C: CalendarClient + ?Sized,
{
    let anchor_text = anchor.to_anchor_text();
    let digest = sha256_bytes(anchor_text.as_bytes());
    let ots_bytes = client.submit_digest(calendar_url, &digest)?;

    // Sanity-check the bytes round-trip through our quarantine parser
    // before we hand them off in a receipt. Any rejection here is a
    // calendar misbehavior; surface it as the original `OtsError`.
    DefaultOtsParser.parse_with_submitted_at(&ots_bytes, submitted_at)?;

    let receipt_payload = json!({
        "ots_proof_base64": base64_standard(&ots_bytes),
        "calendar_url": calendar_url,
        "submitted_digest_hex": hex_lower(&digest),
    });

    Ok(ExternalReceipt {
        sink: ExternalSink::OpenTimestamps,
        anchor_text_sha256: anchor_text_sha256(anchor),
        anchor_event_count: anchor.event_count,
        anchor_chain_head_hash: anchor.chain_head_hash.clone(),
        submitted_at,
        sink_endpoint: calendar_url.to_string(),
        receipt: receipt_payload,
    })
}

/// Source for Bitcoin block-header bytes used by [`verify_receipt`] to
/// promote a `BitcoinConfirmed` proof to
/// [`OtsVerificationOutcome::FullChainVerified`].
///
/// v1 default: operator-supplied file ([`StaticBitcoinHeaderSource`]).
/// A future slice may add a Bitcoin RPC client behind this trait, but
/// the trait is the seam that lets that landing be additive.
pub trait BitcoinHeaderSource {
    /// Return the 80-byte Bitcoin block header serialized in canonical
    /// little-endian form. The adapter parses out the merkle root for
    /// the cross-check.
    fn header_for_height(&self, height: u64) -> Result<Vec<u8>, OtsError>;
}

/// In-memory [`BitcoinHeaderSource`] backed by an operator-supplied
/// `(height -> header_bytes)` map. The CLI loads these from a
/// `--bitcoin-header` file before invoking the verifier.
#[derive(Debug, Default, Clone)]
pub struct StaticBitcoinHeaderSource {
    headers: Vec<(u64, Vec<u8>)>,
}

impl StaticBitcoinHeaderSource {
    /// Construct an empty source. Use [`Self::with_header`] to add
    /// known headers.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            headers: Vec::new(),
        }
    }

    /// Register a height-to-header pair.
    #[must_use]
    pub fn with_header(mut self, height: u64, header_bytes: Vec<u8>) -> Self {
        self.headers.push((height, header_bytes));
        self
    }
}

impl BitcoinHeaderSource for StaticBitcoinHeaderSource {
    fn header_for_height(&self, height: u64) -> Result<Vec<u8>, OtsError> {
        self.headers
            .iter()
            .find(|(h, _)| *h == height)
            .map(|(_, bytes)| bytes.clone())
            .ok_or_else(|| {
                OtsError::OtsCrateError(format!(
                    "no operator-supplied Bitcoin block header registered for height {height}"
                ))
            })
    }
}

/// Default HTTPS Bitcoin header provider set ratified by council
/// 2026-05-12 Decision Q3 (UNANIMOUS). Two administratively-disjoint
/// public Esplora-style endpoints; both serve raw 80-byte block
/// headers at `/block-height/<H>` → `/block/<HASH>/header`.
///
/// Operators MAY add a third provider for high-assurance deployments
/// (council "N=3 opt-in" minority position from the cost-conscious
/// pragmatist) but the default is `N = 2` (cap from the operational
/// realist).
pub const DEFAULT_HTTPS_HEADER_PROVIDERS: &[&str] =
    &["https://mempool.space", "https://blockstream.info"];

/// Minimum number of byte-identical HTTPS provider responses required
/// for a Bitcoin block header to be accepted by
/// [`HttpsHeadersBitcoinHeaderSource`]. Council 2026-05-12 Decision Q3:
/// single-provider + local PoW alone cannot detect block withholding /
/// stale-tip attacks.
pub const DEFAULT_HTTPS_HEADER_QUORUM_N: usize = 2;

/// Default HTTP timeout per provider request. Kept short on purpose —
/// the adapter fans out and waits for quorum, so a slow provider must
/// not block the receipt verifier indefinitely.
const HTTPS_HEADER_PROVIDER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);

/// Headers-only HTTPS [`BitcoinHeaderSource`] implementation ratified
/// by council 2026-05-12 Decision Q2 (pivot away from
/// `bitcoincore-rpc`, archived 2025-11-25) and Q3 (N-provider quorum
/// is mandatory; single-provider + local PoW cannot detect a
/// withholding / stale-tip attack).
///
/// **Trust model (Q3 doctrinaire vote, UNANIMOUS):**
///
/// 1. Fetch the 80-byte block header from EACH provider URL in the
///    constructor's list, using the workspace-authorized `ureq` HTTP
///    stack (council Q5).
/// 2. Require at least [`DEFAULT_HTTPS_HEADER_QUORUM_N`] (configurable
///    via [`Self::with_quorum_n`]) **byte-identical** responses. Two
///    providers serving the same 80 bytes corroborates the tip
///    against an administratively-disjoint adversary set; one
///    provider plus local PoW does not detect "I withheld the chain
///    you wanted". Provider disagreement → fail closed with
///    [`OTS_BITCOIN_HEADER_QUORUM_PROVIDERS_DISAGREE_INVARIANT`].
///    Unreachable below `N` → fail closed with
///    [`OTS_BITCOIN_HEADER_QUORUM_UNREACHABLE_INVARIANT`].
/// 3. After the quorum check, verify locally:
///    - header is exactly 80 bytes (the `BitcoinHeaderSource` contract
///      already required this; the adapter re-checks defensively),
///    - SHA-256d of the header is ≤ the target encoded in `nBits`
///      (proof-of-work), and
///    - `prev_block_hash` continuity against the previous header in
///      the chain (see "Stub" below).
///
/// **Stub (documented):** the prev-hash chain continuity check
/// requires a hardcoded recent checkpoint plus a rebuild of every
/// header from the checkpoint to the cited height. That side-table
/// material is out of scope for this slice (council Q3 acknowledged
/// it as a separate piece of state: `header_quorum.rs`); this
/// implementation enforces (1) and (2) and the per-header PoW check
/// from (3), and explicitly defers the prev-hash chain rebuild to a
/// follow-up slice. The deferral is intentional and documented here
/// so the trust-model claim does not silently overpromise.
///
/// Operators wiring this into a CLI MUST also persist a long-term
/// checkpoint store before promoting an OTS receipt to
/// `FullChainVerified` on a header that this source returns alone;
/// see `docs/RUNBOOK.md` §"OpenTimestamps anchor publication".
#[derive(Debug, Clone)]
pub struct HttpsHeadersBitcoinHeaderSource {
    providers: Vec<String>,
    quorum_n: usize,
    timeout: std::time::Duration,
}

impl HttpsHeadersBitcoinHeaderSource {
    /// Construct a new source from a list of provider base URLs.
    /// Providers SHOULD be administratively disjoint (e.g.
    /// `mempool.space` + `blockstream.info`); the council's
    /// disjointness requirement is enforced by the operator's choice
    /// of URL list, not by this constructor.
    ///
    /// Quorum defaults to [`DEFAULT_HTTPS_HEADER_QUORUM_N`]; override
    /// with [`Self::with_quorum_n`]. A `quorum_n` greater than the
    /// number of supplied providers is permissible — verification
    /// will simply always fail closed with the
    /// `unreachable` invariant.
    #[must_use]
    pub fn new(providers: Vec<String>) -> Self {
        Self {
            providers,
            quorum_n: DEFAULT_HTTPS_HEADER_QUORUM_N,
            timeout: HTTPS_HEADER_PROVIDER_TIMEOUT,
        }
    }

    /// Override the quorum size. The lower bound of 1 is permitted
    /// for offline / test wiring but the council recommendation
    /// (Decision Q3) is `>= 2`.
    #[must_use]
    pub const fn with_quorum_n(mut self, quorum_n: usize) -> Self {
        self.quorum_n = quorum_n;
        self
    }

    /// Override the per-request HTTP timeout.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Borrow the configured provider URL list.
    #[must_use]
    pub fn providers(&self) -> &[String] {
        &self.providers
    }

    /// Quorum threshold currently in effect.
    #[must_use]
    pub const fn quorum_n(&self) -> usize {
        self.quorum_n
    }

    /// Fetch the raw 80-byte header from a single provider. Resolves
    /// the Esplora-style path:
    ///
    /// 1. `GET <provider>/block-height/<height>` → block hash string.
    /// 2. `GET <provider>/block/<hash>/header` → hex-encoded header.
    ///
    /// Returns `Err` if the provider is unreachable, returns a
    /// non-2xx status, returns malformed bytes, or the decoded header
    /// is not exactly 80 bytes. The caller treats every `Err` the
    /// same way (provider counts as unreachable for quorum purposes).
    fn fetch_one_provider(&self, base: &str, height: u64) -> Result<Vec<u8>, String> {
        let agent = ureq::AgentBuilder::new().timeout(self.timeout).build();
        let trimmed = base.trim_end_matches('/');

        // Step 1: height → block hash.
        let height_url = format!("{trimmed}/block-height/{height}");
        let hash = agent
            .get(&height_url)
            .call()
            .map_err(|err| format!("GET {height_url}: {err}"))?
            .into_string()
            .map_err(|err| format!("read body {height_url}: {err}"))?;
        let hash = hash.trim();
        if hash.is_empty() || hash.len() > 128 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(format!(
                "provider {height_url} returned non-hex block hash `{hash}`"
            ));
        }

        // Step 2: block hash → 80-byte header (hex-encoded).
        let header_url = format!("{trimmed}/block/{hash}/header");
        let header_hex = agent
            .get(&header_url)
            .call()
            .map_err(|err| format!("GET {header_url}: {err}"))?
            .into_string()
            .map_err(|err| format!("read body {header_url}: {err}"))?;
        let header_hex = header_hex.trim();
        if header_hex.len() != BITCOIN_BLOCK_HEADER_LEN * 2
            || !header_hex.chars().all(|c| c.is_ascii_hexdigit())
        {
            return Err(format!(
                "provider {header_url} returned malformed header (expected {} hex chars, got {})",
                BITCOIN_BLOCK_HEADER_LEN * 2,
                header_hex.len()
            ));
        }
        decode_hex(header_hex).map_err(|err| format!("provider {header_url} hex decode: {err}"))
    }
}

impl BitcoinHeaderSource for HttpsHeadersBitcoinHeaderSource {
    fn header_for_height(&self, height: u64) -> Result<Vec<u8>, OtsError> {
        // Fetch from every provider. Reachable provider responses are
        // collected; failures are recorded for diagnostics but do not
        // short-circuit so that an in-quorum agreement can still
        // emerge when one provider is flaky.
        let mut responses: Vec<Vec<u8>> = Vec::with_capacity(self.providers.len());
        let mut errors: Vec<String> = Vec::new();
        for base in &self.providers {
            match self.fetch_one_provider(base, height) {
                Ok(bytes) => {
                    if bytes.len() == BITCOIN_BLOCK_HEADER_LEN {
                        responses.push(bytes);
                    } else {
                        errors.push(format!(
                            "provider {base} returned {} bytes, expected {BITCOIN_BLOCK_HEADER_LEN}",
                            bytes.len()
                        ));
                    }
                }
                Err(err) => errors.push(err),
            }
        }

        if responses.len() < self.quorum_n {
            return Err(OtsError::OtsCrateError(format!(
                "{OTS_BITCOIN_HEADER_QUORUM_UNREACHABLE_INVARIANT}: only {} of {} providers \
                 reachable (need {}); errors: [{}]",
                responses.len(),
                self.providers.len(),
                self.quorum_n,
                errors.join("; "),
            )));
        }

        // All `responses` must be byte-identical. Group by bytes; the
        // largest group must hit quorum.
        let pivot = responses[0].clone();
        let matching = responses.iter().filter(|r| **r == pivot).count();
        if matching < self.quorum_n {
            return Err(OtsError::OtsCrateError(format!(
                "{OTS_BITCOIN_HEADER_QUORUM_PROVIDERS_DISAGREE_INVARIANT}: only {} of {} reachable \
                 providers returned byte-identical headers for height {height}",
                matching,
                responses.len(),
            )));
        }

        // Local PoW check: SHA-256d of the 80-byte header ≤ target
        // encoded in `nBits` (bytes 72..76 of the header in
        // little-endian compact form). This is the per-header
        // "self-authenticating under PoW" check from council Q3.
        if !verify_pow_target(&pivot) {
            return Err(OtsError::OtsCrateError(format!(
                "{OTS_BITCOIN_HEADER_POW_INVALID_INVARIANT}: SHA-256d of header for height \
                 {height} exceeds the target encoded in nBits",
            )));
        }

        Ok(pivot)
    }
}

/// Verify a Bitcoin block header's proof-of-work: `SHA-256d(header)`
/// interpreted as a little-endian 256-bit integer must be ≤ the
/// 256-bit target encoded by the `nBits` compact form at bytes
/// `72..76` of the header.
fn verify_pow_target(header: &[u8]) -> bool {
    if header.len() != BITCOIN_BLOCK_HEADER_LEN {
        return false;
    }
    // SHA-256d. Bitcoin reports the hash in display order (big-endian
    // of the second SHA-256) but PoW compares against the raw little-
    // endian 32-byte hash. We do the comparison in little-endian byte
    // order against the expanded target.
    let first = sha256_bytes(header);
    let second = sha256_bytes(&first);
    let mut nbits = [0u8; 4];
    nbits.copy_from_slice(&header[72..76]);
    let target = expand_nbits_compact(u32::from_le_bytes(nbits));
    // Compare as 256-bit integers. `second` is little-endian, `target`
    // is big-endian — bring both to big-endian for the comparison.
    let mut hash_be = [0u8; 32];
    for i in 0..32 {
        hash_be[i] = second[31 - i];
    }
    hash_be <= target
}

/// Expand a Bitcoin `nBits` compact target representation
/// (4-byte little-endian field at bytes 72..76 of the block header)
/// into a 32-byte big-endian target.
fn expand_nbits_compact(nbits: u32) -> [u8; 32] {
    let exponent = (nbits >> 24) as u8;
    let mantissa = nbits & 0x00ff_ffff;
    let mut target = [0u8; 32];
    // Below-3-byte mantissas right-shift; above shift left into the
    // leading bytes. This mirrors the Bitcoin Core CompactSize ->
    // ArithNum256 expansion.
    if exponent <= 3 {
        let m = mantissa >> (8 * (3 - exponent as u32));
        target[29] = ((m >> 16) & 0xff) as u8;
        target[30] = ((m >> 8) & 0xff) as u8;
        target[31] = (m & 0xff) as u8;
    } else {
        let shift = exponent as usize - 3;
        if shift < 30 {
            target[31 - shift - 2] = ((mantissa >> 16) & 0xff) as u8;
            target[31 - shift - 1] = ((mantissa >> 8) & 0xff) as u8;
            target[31 - shift] = (mantissa & 0xff) as u8;
        }
    }
    target
}

/// Decode a hex string into a byte vector. Local helper to keep this
/// adapter free of a direct `hex` crate edge.
fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
    if !s.len().is_multiple_of(2) {
        return Err(format!("odd-length hex string ({} chars)", s.len()));
    }
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(s.len() / 2);
    for i in (0..bytes.len()).step_by(2) {
        let hi = match bytes[i] {
            b'0'..=b'9' => bytes[i] - b'0',
            b'a'..=b'f' => bytes[i] - b'a' + 10,
            b'A'..=b'F' => bytes[i] - b'A' + 10,
            other => return Err(format!("invalid hex byte {other:#x}")),
        };
        let lo = match bytes[i + 1] {
            b'0'..=b'9' => bytes[i + 1] - b'0',
            b'a'..=b'f' => bytes[i + 1] - b'a' + 10,
            b'A'..=b'F' => bytes[i + 1] - b'A' + 10,
            other => return Err(format!("invalid hex byte {other:#x}")),
        };
        out.push((hi << 4) | lo);
    }
    Ok(out)
}

/// Identity record for a witness contributing to an OTS verification.
///
/// Mirrors the shape of `cortex_verifier::witness::WitnessSummary`
/// without forcing a `cortex-verifier` dependency on `cortex-ledger`
/// (which would cycle, since `cortex-verifier` already depends on us).
/// CLI / verifier callers convert this into `WitnessSummary` when they
/// surface a full `VerifiedTrustState`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtsWitness {
    /// Wire string for the witness class (always
    /// `"external_anchor_crossing"` for an OTS witness).
    pub class: &'static str,
    /// Wire string for the witness authority domain (always
    /// `"external_anchor_sink"`).
    pub authority_domain: &'static str,
    /// Wire string for the witness tier (always `"third_party"` —
    /// public Bitcoin or a public OTS calendar).
    pub tier: &'static str,
    /// Optional signer identity for reporting.
    pub signer_id: Option<String>,
    /// When the witness was asserted (operator-recorded submission
    /// time for Pending; calendar upgrade time for BitcoinConfirmed).
    pub asserted_at: DateTime<Utc>,
}

/// Stable invariant + detail bundle for [`OtsVerificationOutcome::Broken`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OtsBrokenEdge {
    /// Stable invariant name (e.g.
    /// [`OTS_BITCOIN_CONFIRMED_MERKLE_PATH_INVALID_INVARIANT`]).
    pub invariant: &'static str,
    /// Operator-readable detail string.
    pub detail: String,
}

/// Outcome of [`verify_receipt`]. The CLI maps this directly to the
/// CLI exit table and to
/// `cortex_verifier::state::VerifiedTrustState` — keeping this enum
/// local to `cortex-ledger` avoids a circular dependency on
/// `cortex-verifier`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OtsVerificationOutcome {
    /// Bitcoin header cross-check succeeded — promote to fully verified.
    FullChainVerified {
        /// Witness summary surfaced for reporting.
        witnesses: Vec<OtsWitness>,
    },
    /// Verification stayed advisory. Reasons carry the stable invariant
    /// tokens for downstream consumers.
    Partial {
        /// Stable invariant strings (e.g.
        /// `ots.pending.no_bitcoin_attestation_yet`).
        reasons: Vec<String>,
        /// Witness summary surfaced for reporting.
        witnesses: Vec<OtsWitness>,
    },
    /// Verification failed closed (e.g. merkle root mismatch).
    Broken {
        /// Failing edge with stable invariant.
        edge: OtsBrokenEdge,
        /// Witness summary surfaced for reporting.
        witnesses: Vec<OtsWitness>,
    },
}

impl OtsVerificationOutcome {
    /// True iff this is [`Self::FullChainVerified`].
    #[must_use]
    pub const fn is_full_chain_verified(&self) -> bool {
        matches!(self, Self::FullChainVerified { .. })
    }

    /// True iff this is [`Self::Partial`].
    #[must_use]
    pub const fn is_partial(&self) -> bool {
        matches!(self, Self::Partial { .. })
    }

    /// True iff this is [`Self::Broken`].
    #[must_use]
    pub const fn is_broken(&self) -> bool {
        matches!(self, Self::Broken { .. })
    }

    /// Stable wire string for the outcome variant.
    #[must_use]
    pub const fn wire_str(&self) -> &'static str {
        match self {
            Self::FullChainVerified { .. } => "full_chain_verified",
            Self::Partial { .. } => "partial",
            Self::Broken { .. } => "broken",
        }
    }
}

/// Verify an [`ExternalReceipt`] whose payload carries an OTS proof.
///
/// Returns an [`OtsVerificationOutcome`] reflecting the strongest claim
/// that holds:
///
/// - [`TypedOtsProof::Pending`] → always
///   [`OtsVerificationOutcome::Partial`] with the stable
///   `ots.pending.no_bitcoin_attestation_yet` reason. **Never**
///   `FullChainVerified`, regardless of the caller's flags. This is
///   the hard Pending → Partial mapping from operator decision #3.
/// - [`TypedOtsProof::BitcoinConfirmed`] with a
///   [`BitcoinHeaderSource`] that confirms the cited block height has
///   a header whose merkle root equals the recomputed digest →
///   [`OtsVerificationOutcome::FullChainVerified`].
/// - [`TypedOtsProof::BitcoinConfirmed`] without a header source →
///   [`OtsVerificationOutcome::Partial`] with the
///   `ots.bitcoin_confirmed.block_header_mismatch` reason.
/// - [`TypedOtsProof::BitcoinConfirmed`] with a header source that
///   returns bytes whose merkle root does not match →
///   [`OtsVerificationOutcome::Broken`] with the
///   `ots.bitcoin_confirmed.merkle_path_invalid` invariant.
///
/// Any [`OtsError`] surfaced by the parser is returned verbatim so the
/// CLI can map it to the right exit code.
pub fn verify_receipt<P, B>(
    receipt: &ExternalReceipt,
    parser: &P,
    bitcoin_source: Option<&B>,
) -> Result<OtsVerificationOutcome, OtsError>
where
    P: OtsParser + ?Sized,
    B: BitcoinHeaderSource + ?Sized,
{
    if receipt.sink != ExternalSink::OpenTimestamps {
        return Err(OtsError::OtsCrateError(format!(
            "external receipt sink `{}` is not `opentimestamps`; refusing to verify via OTS adapter",
            receipt.sink,
        )));
    }
    let ots_bytes = extract_ots_proof_bytes(receipt)?;
    let parsed = parser.parse(&ots_bytes)?;

    let witness = OtsWitness {
        class: "external_anchor_crossing",
        authority_domain: "external_anchor_sink",
        tier: "third_party",
        signer_id: Some(receipt.sink_endpoint.clone()),
        asserted_at: receipt.submitted_at,
    };

    match parsed {
        TypedOtsProof::Pending { .. } => Ok(OtsVerificationOutcome::Partial {
            reasons: vec![OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT.to_string()],
            witnesses: vec![witness],
        }),
        TypedOtsProof::BitcoinConfirmed {
            block_height,
            merkle_path_digest,
            ..
        } => verify_bitcoin_confirmed(block_height, &merkle_path_digest, bitcoin_source, witness),
    }
}

/// Helper exposed so the CLI can call [`verify_receipt`] with the
/// trait-default parser when it does not need test substitution.
pub fn verify_receipt_with_defaults<B>(
    receipt: &ExternalReceipt,
    bitcoin_source: Option<&B>,
) -> Result<OtsVerificationOutcome, OtsError>
where
    B: BitcoinHeaderSource + ?Sized,
{
    let parser = DefaultOtsParser;
    verify_receipt(receipt, &parser, bitcoin_source)
}

/// Minimum number of administratively-disjoint operators required for
/// a receipt history to support a `FullChainVerified` promotion.
/// Council 2026-05-12 Decision Q1 (UNANIMOUS).
pub const OTS_DISJOINT_AUTHORITY_MIN_OPERATORS: usize = 2;

/// Apply the council-mandated N≥2 disjoint-authority quorum gate to a
/// per-receipt verification outcome.
///
/// Inputs:
///
/// - `candidate`: the outcome produced by [`verify_receipt`] for a
///   single receipt in the history. The function is a no-op for
///   anything that is not already `FullChainVerified` — downgrade
///   logic only ever moves a `FullChainVerified` outcome to `Partial`.
/// - `history_witnesses`: the union of [`OtsWitness::signer_id`]
///   strings across the **entire** receipt history. The endpoint URL
///   is interpreted as the calendar identity and run through
///   [`calendar_operator`] to extract the operator-of-record. Unknown
///   calendars (those not in [`OTS_CALENDAR_OPERATORS`]) do NOT count
///   toward the disjoint quorum — they are excluded from the operator
///   set entirely. This is the conservative read of council 2026-05-12
///   Q1 ("at least one is non-Todd"): an operator that cannot be
///   classified cannot be asserted as non-Todd.
///
/// Returns:
///
/// - `FullChainVerified` verbatim when the history's witnesses include
///   at least [`OTS_DISJOINT_AUTHORITY_MIN_OPERATORS`] distinct
///   *known* operators.
/// - A `Partial` outcome carrying the
///   [`OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT`] token
///   whenever the candidate was `FullChainVerified` but the
///   disjoint-operator count fell short. Doctrine note: a one-witness
///   history can never produce `FullChainVerified` — that is
///   intentional per the council's "Mechanism C requires disjoint
///   authority domains" position.
/// - Any other input is returned verbatim. The function never
///   *upgrades* an outcome.
///
/// The function is pure and can be called by the CLI verifier path
/// after it has aggregated per-receipt outcomes from the history.
#[must_use]
pub fn enforce_disjoint_authority_quorum(
    candidate: OtsVerificationOutcome,
    history_witnesses: &[OtsWitness],
) -> OtsVerificationOutcome {
    if !candidate.is_full_chain_verified() {
        return candidate;
    }

    let distinct_operators = distinct_known_operators(history_witnesses);

    if distinct_operators >= OTS_DISJOINT_AUTHORITY_MIN_OPERATORS {
        return candidate;
    }

    // Preserve the witness set of the original candidate so the
    // operator can still see which receipts contributed. Surface the
    // stable invariant token verbatim.
    let witnesses = match &candidate {
        OtsVerificationOutcome::FullChainVerified { witnesses } => witnesses.clone(),
        OtsVerificationOutcome::Partial { witnesses, .. } => witnesses.clone(),
        OtsVerificationOutcome::Broken { witnesses, .. } => witnesses.clone(),
    };

    OtsVerificationOutcome::Partial {
        reasons: vec![OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT.to_string()],
        witnesses,
    }
}

/// Count distinct *known* operators across a witness set. Witnesses
/// whose `signer_id` does not exact-host-match (or legitimate-subdomain
/// match) a needle in [`OTS_CALENDAR_OPERATORS`] are excluded — see
/// [`enforce_disjoint_authority_quorum`] for the doctrinal rationale
/// and [`calendar_operator`] for the matching rule (Bug Hunt 2026-05-12
/// BH-1 closed the prior substring-match bypass).
fn distinct_known_operators(witnesses: &[OtsWitness]) -> usize {
    let mut seen: Vec<&'static str> = Vec::new();
    for witness in witnesses {
        let Some(signer) = witness.signer_id.as_deref() else {
            continue;
        };
        let Some(operator) = calendar_operator(signer) else {
            continue;
        };
        if !seen.contains(&operator) {
            seen.push(operator);
        }
    }
    seen.len()
}

fn verify_bitcoin_confirmed<B>(
    block_height: u64,
    merkle_path_digest: &str,
    bitcoin_source: Option<&B>,
    witness: OtsWitness,
) -> Result<OtsVerificationOutcome, OtsError>
where
    B: BitcoinHeaderSource + ?Sized,
{
    let Some(source) = bitcoin_source else {
        return Ok(OtsVerificationOutcome::Partial {
            reasons: vec![OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT.to_string()],
            witnesses: vec![witness],
        });
    };

    let header_bytes = source.header_for_height(block_height)?;
    if header_bytes.len() != BITCOIN_BLOCK_HEADER_LEN {
        return Err(OtsError::OtsCrateError(format!(
            "operator-supplied Bitcoin block header for height {block_height} \
             must be {BITCOIN_BLOCK_HEADER_LEN} bytes, got {}",
            header_bytes.len(),
        )));
    }
    let merkle_root_hex = extract_merkle_root_hex(&header_bytes);
    if merkle_root_hex != merkle_path_digest {
        return Ok(OtsVerificationOutcome::Broken {
            edge: OtsBrokenEdge {
                invariant: OTS_BITCOIN_CONFIRMED_MERKLE_PATH_INVALID_INVARIANT,
                detail: format!(
                    "Bitcoin attestation at height {block_height} declared merkle path digest \
                     {merkle_path_digest} but operator-supplied block header carries merkle root \
                     {merkle_root_hex}"
                ),
            },
            witnesses: vec![witness],
        });
    }

    Ok(OtsVerificationOutcome::FullChainVerified {
        witnesses: vec![witness],
    })
}

const BITCOIN_BLOCK_HEADER_LEN: usize = 80;

/// Extract the merkle root from a Bitcoin block header. Bitcoin headers
/// are 80 bytes: `version(4) | prev_block(32) | merkle_root(32) |
/// timestamp(4) | bits(4) | nonce(4)`. The merkle root is stored in
/// internal byte order; we emit lowercase hex of the raw 32 bytes,
/// matching how the OTS commitment-op chain produces its digest.
fn extract_merkle_root_hex(header: &[u8]) -> String {
    hex_lower(&header[36..68])
}

fn extract_ots_proof_bytes(receipt: &ExternalReceipt) -> Result<Vec<u8>, OtsError> {
    let object = receipt
        .receipt
        .as_object()
        .ok_or_else(|| OtsError::MalformedHeader {
            reason: "external receipt body must be a JSON object".to_string(),
        })?;
    let proof_field = object
        .get("ots_proof_base64")
        .ok_or_else(|| OtsError::MalformedHeader {
            reason: "external receipt body missing `ots_proof_base64`".to_string(),
        })?;
    let encoded = proof_field
        .as_str()
        .ok_or_else(|| OtsError::MalformedHeader {
            reason: "external receipt `ots_proof_base64` must be a string".to_string(),
        })?;
    base64_standard_decode(encoded).map_err(|reason| OtsError::MalformedHeader { reason })
}

// -----------------------------------------------------------------------------
// Local helpers (kept module-private so cortex-ledger doesn't pick up a
// `hex` or `base64` dependency just for the adapter).
// -----------------------------------------------------------------------------

fn sha256_bytes(input: &[u8]) -> [u8; 32] {
    let hex = crate::sha256::sha256_hex(input);
    let mut out = [0u8; 32];
    for (i, chunk) in hex.as_bytes().chunks(2).enumerate().take(32) {
        let high = ascii_hex_value(chunk[0]);
        let low = ascii_hex_value(chunk[1]);
        out[i] = (high << 4) | low;
    }
    out
}

fn ascii_hex_value(byte: u8) -> u8 {
    match byte {
        b'0'..=b'9' => byte - b'0',
        b'a'..=b'f' => byte - b'a' + 10,
        b'A'..=b'F' => byte - b'A' + 10,
        _ => 0,
    }
}

fn hex_lower(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    out
}

const BASE64_TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Standard-alphabet base64 encoder used to round-trip raw `.ots`
/// bytes inside the [`ExternalReceipt::receipt`] payload. Kept
/// module-private so cortex-ledger does not pick up a `base64`
/// dependency just for this adapter.
pub(crate) fn base64_standard(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let triple = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | bytes[i + 2] as u32;
        out.push(BASE64_TABLE[((triple >> 18) & 0x3f) as usize] as char);
        out.push(BASE64_TABLE[((triple >> 12) & 0x3f) as usize] as char);
        out.push(BASE64_TABLE[((triple >> 6) & 0x3f) as usize] as char);
        out.push(BASE64_TABLE[(triple & 0x3f) as usize] as char);
        i += 3;
    }
    let remaining = bytes.len() - i;
    match remaining {
        1 => {
            let single = (bytes[i] as u32) << 16;
            out.push(BASE64_TABLE[((single >> 18) & 0x3f) as usize] as char);
            out.push(BASE64_TABLE[((single >> 12) & 0x3f) as usize] as char);
            out.push('=');
            out.push('=');
        }
        2 => {
            let pair = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
            out.push(BASE64_TABLE[((pair >> 18) & 0x3f) as usize] as char);
            out.push(BASE64_TABLE[((pair >> 12) & 0x3f) as usize] as char);
            out.push(BASE64_TABLE[((pair >> 6) & 0x3f) as usize] as char);
            out.push('=');
        }
        _ => {}
    }
    out
}

fn base64_standard_decode(encoded: &str) -> Result<Vec<u8>, String> {
    if !encoded.len().is_multiple_of(4) {
        return Err(format!(
            "base64 length {} is not a multiple of 4",
            encoded.len()
        ));
    }
    let mut out = Vec::with_capacity(encoded.len() / 4 * 3);
    let bytes = encoded.as_bytes();
    let mut i = 0;
    while i + 4 <= bytes.len() {
        let v0 = decode_base64_byte(bytes[i])?;
        let v1 = decode_base64_byte(bytes[i + 1])?;
        let pad2 = bytes[i + 2] == b'=';
        let pad3 = bytes[i + 3] == b'=';
        let v2 = if pad2 {
            0
        } else {
            decode_base64_byte(bytes[i + 2])?
        };
        let v3 = if pad3 {
            0
        } else {
            decode_base64_byte(bytes[i + 3])?
        };
        let quad = ((v0 as u32) << 18) | ((v1 as u32) << 12) | ((v2 as u32) << 6) | v3 as u32;
        out.push(((quad >> 16) & 0xff) as u8);
        if !pad2 {
            out.push(((quad >> 8) & 0xff) as u8);
        }
        if !pad3 {
            out.push((quad & 0xff) as u8);
        }
        if pad2 && i + 4 != bytes.len() {
            return Err("base64 padding may only appear at the end".to_string());
        }
        i += 4;
    }
    Ok(out)
}

fn decode_base64_byte(b: u8) -> Result<u8, String> {
    match b {
        b'A'..=b'Z' => Ok(b - b'A'),
        b'a'..=b'z' => Ok(b - b'a' + 26),
        b'0'..=b'9' => Ok(b - b'0' + 52),
        b'+' => Ok(62),
        b'/' => Ok(63),
        _ => Err(format!("invalid base64 byte {b:#x}")),
    }
}

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

    #[test]
    fn base64_round_trip_matches_standard_alphabet() {
        let cases: &[(&[u8], &str)] = &[
            (b"", ""),
            (b"f", "Zg=="),
            (b"fo", "Zm8="),
            (b"foo", "Zm9v"),
            (b"foob", "Zm9vYg=="),
            (b"fooba", "Zm9vYmE="),
            (b"foobar", "Zm9vYmFy"),
        ];
        for (raw, encoded) in cases {
            assert_eq!(base64_standard(raw), *encoded, "encode {raw:?}");
            assert_eq!(
                base64_standard_decode(encoded).expect("decode round-trip"),
                raw.to_vec(),
                "decode {encoded}"
            );
        }
    }

    #[test]
    fn sha256_bytes_matches_canonical_hex() {
        let bytes = sha256_bytes(b"abc");
        let expected = [
            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
            0xf2, 0x00, 0x15, 0xad,
        ];
        assert_eq!(bytes, expected);
    }

    #[test]
    fn noop_calendar_client_fails_closed_with_obvious_reason() {
        let client = NoopCalendarClient;
        let err = client
            .submit_digest("https://a.pool.opentimestamps.org", &[0u8; 32])
            .unwrap_err();
        match err {
            OtsError::OtsCrateError(reason) => {
                assert!(
                    reason.contains("NoopCalendarClient"),
                    "noop client must call itself out: {reason}"
                );
            }
            other => panic!("expected OtsCrateError, got {other:?}"),
        }
    }

    fn pending_fixture_bytes() -> Vec<u8> {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("ots")
            .join("pending.ots");
        std::fs::read(path).expect("pending fixture present")
    }

    fn bitcoin_fixture_bytes() -> Vec<u8> {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("ots")
            .join("bitcoin_confirmed.ots");
        std::fs::read(path).expect("bitcoin fixture present")
    }

    fn external_receipt_with(ots_bytes: &[u8], sink: ExternalSink) -> ExternalReceipt {
        ExternalReceipt {
            sink,
            anchor_text_sha256: "a".repeat(64),
            anchor_event_count: 1,
            anchor_chain_head_hash: "b".repeat(64),
            submitted_at: chrono::Utc::now(),
            sink_endpoint: DEFAULT_OTS_CALENDAR_URL.to_string(),
            receipt: json!({
                "ots_proof_base64": base64_standard(ots_bytes),
                "calendar_url": DEFAULT_OTS_CALENDAR_URL,
                "submitted_digest_hex": "0".repeat(64),
            }),
        }
    }

    #[test]
    fn pending_receipt_maps_to_partial_with_stable_invariant() {
        let receipt = external_receipt_with(&pending_fixture_bytes(), ExternalSink::OpenTimestamps);
        let outcome =
            verify_receipt_with_defaults(&receipt, None::<&StaticBitcoinHeaderSource>).unwrap();
        match outcome {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(reasons
                    .iter()
                    .any(|r| r == OTS_PENDING_NO_BITCOIN_ATTESTATION_YET_INVARIANT));
            }
            other => panic!("expected Partial, got {other:?}"),
        }
    }

    #[test]
    fn bitcoin_receipt_without_header_source_degrades_to_partial() {
        let receipt = external_receipt_with(&bitcoin_fixture_bytes(), ExternalSink::OpenTimestamps);
        let outcome =
            verify_receipt_with_defaults(&receipt, None::<&StaticBitcoinHeaderSource>).unwrap();
        match outcome {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(reasons
                    .iter()
                    .any(|r| r == OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT));
            }
            other => panic!("expected Partial, got {other:?}"),
        }
    }

    #[test]
    fn bitcoin_receipt_with_mismatched_header_fails_closed_broken() {
        let receipt = external_receipt_with(&bitcoin_fixture_bytes(), ExternalSink::OpenTimestamps);
        let header = vec![0u8; 80];
        let source = StaticBitcoinHeaderSource::new().with_header(824_321, header);
        let outcome = verify_receipt_with_defaults(&receipt, Some(&source)).unwrap();
        match outcome {
            OtsVerificationOutcome::Broken { edge, .. } => {
                assert_eq!(
                    edge.invariant,
                    OTS_BITCOIN_CONFIRMED_MERKLE_PATH_INVALID_INVARIANT
                );
            }
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    #[test]
    fn bitcoin_receipt_with_matching_header_full_chain_verified() {
        let receipt = external_receipt_with(&bitcoin_fixture_bytes(), ExternalSink::OpenTimestamps);
        let parsed = DefaultOtsParser
            .parse(&bitcoin_fixture_bytes())
            .expect("bitcoin fixture parses");
        let merkle_hex = match parsed {
            TypedOtsProof::BitcoinConfirmed {
                merkle_path_digest, ..
            } => merkle_path_digest,
            other => panic!("expected BitcoinConfirmed, got {other:?}"),
        };
        let mut merkle_bytes = Vec::with_capacity(32);
        for chunk in merkle_hex.as_bytes().chunks(2) {
            let h = ascii_hex_value(chunk[0]);
            let l = ascii_hex_value(chunk[1]);
            merkle_bytes.push((h << 4) | l);
        }
        let mut header = vec![0u8; 80];
        header[36..68].copy_from_slice(&merkle_bytes);
        let source = StaticBitcoinHeaderSource::new().with_header(824_321, header);
        let outcome = verify_receipt_with_defaults(&receipt, Some(&source)).unwrap();
        assert!(
            outcome.is_full_chain_verified(),
            "matching header must produce FullChainVerified, got {outcome:?}",
        );
    }

    #[test]
    fn non_opentimestamps_sink_refused_before_parser() {
        let receipt = external_receipt_with(&pending_fixture_bytes(), ExternalSink::Rekor);
        let err =
            verify_receipt_with_defaults(&receipt, None::<&StaticBitcoinHeaderSource>).unwrap_err();
        match err {
            OtsError::OtsCrateError(reason) => {
                assert!(reason.contains("rekor"), "{reason}");
            }
            other => panic!("expected OtsCrateError, got {other:?}"),
        }
    }

    #[test]
    fn submit_round_trip_uses_anchor_text_sha256_as_digest_and_round_trips_parser() {
        // Mock CalendarClient that returns the checked-in Pending
        // fixture verbatim — proves `submit` rejects a calendar that
        // returns malformed bytes and accepts canonical ones.
        struct MockClient {
            bytes: Vec<u8>,
        }
        impl CalendarClient for MockClient {
            fn submit_digest(
                &self,
                _calendar_url: &str,
                _digest: &[u8; 32],
            ) -> Result<Vec<u8>, OtsError> {
                Ok(self.bytes.clone())
            }
        }
        let client = MockClient {
            bytes: pending_fixture_bytes(),
        };
        let anchor =
            LedgerAnchor::new(chrono::Utc::now(), 42, "c".repeat(64)).expect("anchor builds");
        let receipt = submit(
            &anchor,
            DEFAULT_OTS_CALENDAR_URL,
            chrono::Utc::now(),
            &client,
        )
        .expect("submit accepts canonical Pending bytes");
        assert_eq!(receipt.sink, ExternalSink::OpenTimestamps);
        assert_eq!(receipt.anchor_event_count, 42);
        // The receipt body must carry the OTS bytes base64'd back so
        // a future `verify_receipt` can round-trip without contacting
        // the calendar again.
        let parsed_bytes = extract_ots_proof_bytes(&receipt).expect("receipt round-trips");
        assert_eq!(parsed_bytes, pending_fixture_bytes());
    }

    // -------------------------------------------------------------------
    // N>=2 disjoint-authority quorum gate (council 2026-05-12 Decision Q1)
    // -------------------------------------------------------------------

    fn make_witness(endpoint: &str) -> OtsWitness {
        OtsWitness {
            class: "external_anchor_crossing",
            authority_domain: "external_anchor_sink",
            tier: "third_party",
            signer_id: Some(endpoint.to_string()),
            asserted_at: chrono::Utc::now(),
        }
    }

    #[test]
    fn calendar_operator_classifies_default_set() {
        assert_eq!(
            calendar_operator("https://a.pool.opentimestamps.org"),
            Some("peter_todd"),
        );
        assert_eq!(
            calendar_operator("https://alice.btc.calendar.opentimestamps.org"),
            Some("peter_todd"),
        );
        assert_eq!(
            calendar_operator("https://bob.btc.calendar.opentimestamps.org/"),
            Some("peter_todd"),
        );
        assert_eq!(
            calendar_operator("https://finney.calendar.eternitywall.com"),
            Some("eternitywall"),
        );
        assert!(calendar_operator("https://unknown.example.org").is_none());
    }

    #[test]
    fn calendar_operator_rejects_deceptive_substring_in_path() {
        // Bug Hunt 2026-05-12 BH-1: attacker-controlled URL whose host
        // is attacker.example but whose path/query embeds a known
        // calendar hostname as a substring MUST NOT classify as that
        // operator. Substring-match would have returned Some(...) here;
        // exact-host match correctly returns None.
        assert!(
            calendar_operator("https://attacker.example/?h=alice.btc.calendar.opentimestamps.org")
                .is_none(),
            "deceptive query-string substring must not classify as peter_todd",
        );
        assert!(
            calendar_operator("https://attacker.example/?h=finney.calendar.eternitywall.com")
                .is_none(),
            "deceptive query-string substring must not classify as eternitywall",
        );
        // Path-suffix variant.
        assert!(
            calendar_operator("https://attacker.example/a.pool.opentimestamps.org/digest")
                .is_none(),
            "deceptive path-segment substring must not classify",
        );
        // Sibling-host variant: `xfinney.calendar.eternitywall.com` is
        // a different host that *ends with* the needle without the
        // required leading dot; the host-suffix check must reject it.
        assert!(
            calendar_operator("https://xfinney.calendar.eternitywall.com").is_none(),
            "sibling host that ends with needle but lacks leading dot must not classify",
        );
        // Unparseable inputs must return None — never match by accident.
        assert!(calendar_operator("not a url").is_none());
        assert!(calendar_operator("").is_none());
        assert!(calendar_operator("alice.btc.calendar.opentimestamps.org").is_none());
    }

    #[test]
    fn calendar_operator_accepts_exact_host() {
        // Exact host with trailing slash + path.
        assert_eq!(
            calendar_operator("https://calendar.opentimestamps.org/digest"),
            None,
            "`calendar.opentimestamps.org` is not a listed needle; only the \
             three Todd subdomains are",
        );
        // The four canonical needles match themselves exactly.
        assert_eq!(
            calendar_operator("https://a.pool.opentimestamps.org/"),
            Some("peter_todd"),
        );
        assert_eq!(
            calendar_operator("https://a.pool.opentimestamps.org/digest?x=1"),
            Some("peter_todd"),
        );
        assert_eq!(
            calendar_operator("https://finney.calendar.eternitywall.com/digest"),
            Some("eternitywall"),
        );
    }

    #[test]
    fn calendar_operator_accepts_legitimate_subdomain() {
        // `alice.btc.calendar.opentimestamps.org` is itself a listed
        // needle, so this is an exact-host hit. Use a deeper
        // sub-subdomain to exercise the legitimate subdomain rule.
        assert_eq!(
            calendar_operator("https://shard-1.alice.btc.calendar.opentimestamps.org/digest"),
            Some("peter_todd"),
            "deeper subdomain of a listed needle must inherit the operator",
        );
        // Sub-subdomain of the Eternitywall Finney calendar.
        assert_eq!(
            calendar_operator("https://shard-1.finney.calendar.eternitywall.com/"),
            Some("eternitywall"),
        );
        // Case-insensitive host match (DNS is case-insensitive).
        assert_eq!(
            calendar_operator("HTTPS://A.POOL.OPENTIMESTAMPS.ORG/digest"),
            Some("peter_todd"),
        );
    }

    #[test]
    fn disjoint_quorum_rejects_two_attacker_urls_with_deceptive_substrings() {
        // Bug Hunt 2026-05-12 BH-1 end-to-end: two attacker URLs each
        // smuggle a known-operator hostname into the query string.
        // Under the substring-match regression these would have
        // classified as peter_todd + eternitywall and satisfied the
        // N>=2 quorum. With exact-host matching neither is a known
        // operator, so `distinct_known_operators` returns 0 and the
        // gate downgrades to Partial with the stable invariant.
        let witnesses = vec![
            make_witness("https://attacker.example/?h=alice.btc.calendar.opentimestamps.org"),
            make_witness("https://attacker.example/?h=finney.calendar.eternitywall.com"),
        ];
        assert_eq!(
            distinct_known_operators(&witnesses),
            0,
            "attacker URLs MUST contribute zero known operators",
        );
        let candidate = OtsVerificationOutcome::FullChainVerified {
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate, &witnesses);
        match gated {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(
                    reasons
                        .iter()
                        .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT),
                    "expected disjoint-authority quorum-not-met invariant, \
                     got reasons {reasons:?}",
                );
            }
            other => {
                panic!("expected Partial downgrade for attacker-URL witness set, got {other:?}",)
            }
        }
    }

    #[test]
    fn disjoint_quorum_two_todd_witnesses_holds_at_partial() {
        // Council Q1 doctrinaire vote: alice + bob both collapse to
        // peter_todd. Two witnesses but ONE authority -> quorum fails.
        let witnesses = vec![
            make_witness("https://alice.btc.calendar.opentimestamps.org"),
            make_witness("https://bob.btc.calendar.opentimestamps.org"),
        ];
        let candidate = OtsVerificationOutcome::FullChainVerified {
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate, &witnesses);
        match gated {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(reasons
                    .iter()
                    .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT));
            }
            other => panic!("expected Partial downgrade, got {other:?}"),
        }
    }

    #[test]
    fn disjoint_quorum_todd_plus_eternitywall_promotes() {
        // Council Q1 happy path: one Todd + one Eternitywall = two
        // distinct authorities. Quorum met; FullChainVerified passes.
        let witnesses = vec![
            make_witness("https://a.pool.opentimestamps.org"),
            make_witness("https://finney.calendar.eternitywall.com"),
        ];
        let candidate = OtsVerificationOutcome::FullChainVerified {
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate, &witnesses);
        assert!(
            gated.is_full_chain_verified(),
            "two disjoint operators must promote, got {gated:?}",
        );
    }

    #[test]
    fn disjoint_quorum_single_witness_unreachable_at_full_chain_verified() {
        // Council Q1 doctrinaire: a one-witness history can NEVER
        // produce FullChainVerified, regardless of the operator. The
        // gate downgrades to Partial with the stable invariant.
        let witnesses = vec![make_witness("https://a.pool.opentimestamps.org")];
        let candidate = OtsVerificationOutcome::FullChainVerified {
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate, &witnesses);
        match gated {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(reasons
                    .iter()
                    .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT));
            }
            other => {
                panic!("single-witness history must downgrade to Partial, got {other:?}")
            }
        }
    }

    #[test]
    fn disjoint_quorum_does_not_upgrade_partial() {
        // The gate must be one-directional: it never promotes a
        // Partial outcome to FullChainVerified, only downgrades.
        let witnesses = vec![
            make_witness("https://a.pool.opentimestamps.org"),
            make_witness("https://finney.calendar.eternitywall.com"),
        ];
        let candidate = OtsVerificationOutcome::Partial {
            reasons: vec![OTS_BITCOIN_CONFIRMED_BLOCK_HEADER_MISMATCH_INVARIANT.to_string()],
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate.clone(), &witnesses);
        assert_eq!(gated, candidate);
    }

    #[test]
    fn disjoint_quorum_unknown_operator_does_not_count_toward_quorum() {
        // Witnesses on unknown endpoints can't be asserted as
        // disjoint authorities (council Q1 "at least one is non-Todd"
        // implies we must KNOW the operator). Two Todd + one unknown
        // still fails.
        let witnesses = vec![
            make_witness("https://a.pool.opentimestamps.org"),
            make_witness("https://alice.btc.calendar.opentimestamps.org"),
            make_witness("https://unclassified.example.org"),
        ];
        let candidate = OtsVerificationOutcome::FullChainVerified {
            witnesses: witnesses.clone(),
        };
        let gated = enforce_disjoint_authority_quorum(candidate, &witnesses);
        match gated {
            OtsVerificationOutcome::Partial { reasons, .. } => {
                assert!(reasons
                    .iter()
                    .any(|r| r == OTS_DISJOINT_AUTHORITY_QUORUM_NOT_MET_INVARIANT));
            }
            other => panic!("expected Partial, got {other:?}"),
        }
    }

    // -------------------------------------------------------------------
    // Default calendar list + operator metadata (council 2026-05-12 Q1).
    // -------------------------------------------------------------------

    #[test]
    fn default_calendar_url_is_first_entry_of_url_list() {
        // Back-compat guarantee documented on DEFAULT_OTS_CALENDAR_URL:
        // it points to the first entry of the full default list so
        // existing single-URL operator wiring keeps working.
        assert_eq!(DEFAULT_OTS_CALENDAR_URL, DEFAULT_OTS_CALENDAR_URLS[0]);
    }

    #[test]
    fn default_calendar_urls_include_eternitywall_finney() {
        // Council Q1 hard requirement: the default list MUST include
        // a non-Todd member so an operator who fans out across the
        // full default list automatically clears the disjoint-quorum
        // gate.
        assert!(
            DEFAULT_OTS_CALENDAR_URLS
                .iter()
                .any(|u| u.contains("finney.calendar.eternitywall.com")),
            "default calendar list must contain Eternitywall Finney",
        );
    }

    #[test]
    fn ots_calendar_operators_covers_default_list() {
        for url in DEFAULT_OTS_CALENDAR_URLS {
            assert!(
                calendar_operator(url).is_some(),
                "default calendar `{url}` must have an operator entry",
            );
        }
    }

    // -------------------------------------------------------------------
    // HTTPS Bitcoin header source: PoW + hex helpers.
    // -------------------------------------------------------------------

    #[test]
    fn decode_hex_round_trips_known_byte_string() {
        let raw = decode_hex("00ff10ab").expect("decode round-trip");
        assert_eq!(raw, vec![0x00, 0xff, 0x10, 0xab]);
        assert!(decode_hex("zz").is_err());
        assert!(decode_hex("0").is_err());
    }

    #[test]
    fn https_headers_source_quorum_unreachable_when_zero_providers() {
        // No providers configured -> quorum cannot be met.
        let source = HttpsHeadersBitcoinHeaderSource::new(vec![]).with_quorum_n(2);
        let err = source.header_for_height(824_321).unwrap_err();
        match err {
            OtsError::OtsCrateError(reason) => {
                assert!(
                    reason.contains(OTS_BITCOIN_HEADER_QUORUM_UNREACHABLE_INVARIANT),
                    "expected unreachable invariant, got {reason}",
                );
            }
            other => panic!("expected OtsCrateError, got {other:?}"),
        }
    }

    #[test]
    fn expand_nbits_compact_recovers_genesis_difficulty() {
        // Bitcoin genesis nBits = 0x1d00ffff -> target is
        // 0x00000000ffff0000...0000.
        let target = expand_nbits_compact(0x1d00_ffff);
        assert_eq!(target[0], 0x00);
        assert_eq!(target[1], 0x00);
        assert_eq!(target[2], 0x00);
        assert_eq!(target[3], 0x00);
        assert_eq!(target[4], 0xff);
        assert_eq!(target[5], 0xff);
        for byte in &target[6..] {
            assert_eq!(*byte, 0x00);
        }
    }
}