syncweb-core 0.1.1-alpha.4

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

use std::{
    collections::{HashMap, HashSet},
    sync::{Arc, Mutex},
    time::{SystemTime, UNIX_EPOCH},
};

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use iroh::PublicKey;
use iroh_blobs::Hash;
use iroh_docs::NamespaceId;
use serde::{Deserialize, Serialize};

use crate::{
    error::{Result, SyncwebError},
    gossip::SignedGossipMessage,
    indexing::{IndexingDatabase, IndexingService},
};

const METADATA_CONTEXT: &[u8] = b"syncweb/wot/metadata/v1\0";
const DELEGATION_CONTEXT: &[u8] = b"syncweb/wot/delegation/v1\0";
const REVOCATION_CONTEXT: &[u8] = b"syncweb/wot/revocation/v1\0";
const MODERATION_CONTEXT: &[u8] = b"syncweb/wot/moderation/v1\0";
const ATTESTATION_CONTEXT: &[u8] = b"syncweb/wot/attestation/v1\0";
const PROVIDER_TRUST_CONTEXT: &[u8] = b"syncweb/wot/provider-trust/v1\0";

/// Signed metadata appended to a content hash.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MetadataEntry {
    pub content: Hash,
    pub key: String,
    pub value: String,
    pub author: String,
    pub sequence: u64,
    pub created_at: u64,
    pub signature: Option<String>,
}

/// Alias emphasizing that the entry belongs to the Web-of-Trust layer.
pub type WotMetadata = MetadataEntry;

impl MetadataEntry {
    /// Create and sign metadata with an Ed25519 author key.
    ///
    /// # Errors
    ///
    /// Returns an error if metadata fields are invalid or signing fails.
    pub fn new(
        content: Hash,
        key: impl Into<String>,
        value: impl Into<String>,
        sequence: u64,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        Self::new_with_time(content, key, value, sequence, current_epoch_seconds(), signing_key)
    }

    /// Create and sign metadata with an explicit timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error if metadata fields are invalid or signing fails.
    pub fn new_with_time(
        content: Hash,
        key: impl Into<String>,
        value: impl Into<String>,
        sequence: u64,
        created_at: u64,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut entry = Self {
            content,
            key: key.into(),
            value: value.into(),
            author: author_id(&signing_key.verifying_key()),
            sequence,
            created_at,
            signature: None,
        };
        entry.sign(signing_key)?;
        Ok(entry)
    }

    /// Create unsigned metadata for a specific author identity.
    ///
    /// Call [`Self::sign`] before accepting or serializing the entry.
    ///
    /// # Errors
    ///
    /// Returns an error if metadata fields are invalid.
    pub fn unsigned(
        content: Hash,
        key: impl Into<String>,
        value: impl Into<String>,
        sequence: u64,
        created_at: u64,
        author: &VerifyingKey,
    ) -> Result<Self> {
        let entry = Self {
            content,
            key: key.into(),
            value: value.into(),
            author: author_id(author),
            sequence,
            created_at,
            signature: None,
        };
        entry.validate()?;
        Ok(entry)
    }

    /// Sign the entry with its declared author.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the author.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.author, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(METADATA_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the metadata signature and structure.
    ///
    /// # Errors
    ///
    /// Returns an error if the metadata or signature is invalid.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            METADATA_CONTEXT,
            &self.unsigned_bytes()?,
            &self.author,
            self.signature.as_deref(),
        )
    }

    /// Validate non-cryptographic metadata fields.
    ///
    /// # Errors
    ///
    /// Returns an error if a required field or author identity is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.key.trim().is_empty() {
            return Err(SyncwebError::InvalidConfig(
                "Web-of-Trust metadata key cannot be empty".to_owned(),
            ));
        }
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "Web-of-Trust metadata sequence must be greater than zero".to_owned(),
            ));
        }
        let _author = parse_author(&self.author)?;
        Ok(())
    }

    /// Encode the entry as JSON.
    ///
    /// # Errors
    ///
    /// Returns an error if the entry is invalid or cannot be serialized.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        self.validate()?;
        serde_json::to_vec(self)
            .map_err(|error| SyncwebError::operation("failed to serialize Web-of-Trust metadata", error))
    }

    /// Decode an entry from JSON.
    ///
    /// # Errors
    ///
    /// Returns an error if the entry is malformed.
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
        let entry: Self = serde_json::from_slice(bytes.as_ref())
            .map_err(|error| SyncwebError::operation("failed to deserialize Web-of-Trust metadata", error))?;
        entry.validate()?;
        Ok(entry)
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(METADATA_CONTEXT, &unsigned)
    }
}

/// A signed delegation from one trusted author to another.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TrustDelegation {
    pub delegator: String,
    pub delegate: String,
    pub scope: Option<Hash>,
    pub max_depth: Option<u32>,
    pub sequence: u64,
    pub issued_at: u64,
    pub expires_at: u64,
    pub revoked_at: Option<u64>,
    pub signature: Option<String>,
}

impl TrustDelegation {
    /// Create and sign a delegation.
    ///
    /// `scope` restricts the delegate to one content hash; `None` delegates
    /// generally.
    ///
    /// # Errors
    ///
    /// Returns an error if identities or timestamps are invalid.
    pub fn new(
        delegate: &VerifyingKey,
        scope: Option<Hash>,
        sequence: u64,
        expires_at: u64,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        Self::new_with_time(
            delegate,
            scope,
            sequence,
            current_epoch_seconds(),
            expires_at,
            signing_key,
        )
    }

    /// Create and sign a delegation with an explicit issue time.
    ///
    /// # Errors
    ///
    /// Returns an error if identities or timestamps are invalid.
    pub fn new_with_time(
        delegate: &VerifyingKey,
        scope: Option<Hash>,
        sequence: u64,
        issued_at: u64,
        expires_at: u64,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut delegation = Self {
            delegator: author_id(&signing_key.verifying_key()),
            delegate: author_id(delegate),
            scope,
            max_depth: None,
            sequence,
            issued_at,
            expires_at,
            revoked_at: None,
            signature: None,
        };
        delegation.sign(signing_key)?;
        Ok(delegation)
    }

    /// Set a maximum delegation chain depth and re-sign.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the delegator.
    pub fn with_max_depth(mut self, max_depth: u32, signing_key: &SigningKey) -> Result<Self> {
        self.max_depth = Some(max_depth);
        self.sign(signing_key)?;
        Ok(self)
    }

    /// Sign the delegation with its declared delegator.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the delegator.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.delegator, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(DELEGATION_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the delegation signature and structure.
    ///
    /// # Errors
    ///
    /// Returns an error if the delegation or signature is invalid.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            DELEGATION_CONTEXT,
            &self.unsigned_bytes()?,
            &self.delegator,
            self.signature.as_deref(),
        )
    }

    /// Verify the delegation and require it to be active at `now`.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature is invalid or the delegation expired.
    pub fn verify_at(&self, now: u64) -> Result<()> {
        self.verify_signature()?;
        if self.revoked_at.is_some_and(|revoked_at| revoked_at <= now) {
            return Err(SyncwebError::InvalidConfig(
                "trust delegation has been revoked".to_owned(),
            ));
        }
        if self.expires_at <= now {
            return Err(SyncwebError::InvalidConfig("trust delegation has expired".to_owned()));
        }
        Ok(())
    }

    /// Validate identities, sequence, and timestamps.
    ///
    /// # Errors
    ///
    /// Returns an error if a delegation field is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "trust delegation sequence must be greater than zero".to_owned(),
            ));
        }
        if self.expires_at <= self.issued_at {
            return Err(SyncwebError::InvalidConfig(
                "trust delegation expiration must be after its issue time".to_owned(),
            ));
        }
        if self.delegator == self.delegate {
            return Err(SyncwebError::InvalidConfig(
                "trust delegation cannot delegate to itself".to_owned(),
            ));
        }
        let _delegator = parse_author(&self.delegator)?;
        let _delegate = parse_author(&self.delegate)?;
        Ok(())
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(DELEGATION_CONTEXT, &unsigned)
    }
}

/// The result of evaluating a local trust policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TrustDecision {
    TrustedRoot,
    TrustedDelegation,
    Untrusted,
    Revoked,
}

impl TrustDecision {
    #[must_use]
    pub const fn is_trusted(self) -> bool {
        matches!(self, Self::TrustedRoot | Self::TrustedDelegation)
    }
}

/// Local trust roots and cryptographically signed delegations.
#[derive(Clone, Debug, Default)]
pub struct TrustPolicy {
    roots: HashSet<String>,
    delegations: HashMap<String, Vec<TrustDelegation>>,
    revoked_authors: HashSet<String>,
}

impl TrustPolicy {
    /// Create an empty local policy.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a policy with one trusted root.
    #[must_use]
    pub fn with_root(signing_key: &SigningKey) -> Self {
        let mut policy = Self::new();
        policy.trust_author(&signing_key.verifying_key());
        policy
    }

    /// Trust an author directly as a local root.
    pub fn trust_author(&mut self, author: &VerifyingKey) {
        self.roots.insert(author_id(author));
        self.revoked_authors.remove(&author_id(author));
    }

    /// Revoke a local trust root or delegate identity.
    pub fn revoke_author(&mut self, author: &VerifyingKey) {
        self.revoked_authors.insert(author_id(author));
    }

    /// Add a signed delegation issued by an already trusted author.
    ///
    /// # Errors
    ///
    /// Returns an error if the delegation is invalid, expired, or not issued
    /// by an identity trusted for its scope.
    pub fn add_delegation(&mut self, delegation: TrustDelegation) -> Result<bool> {
        self.add_delegation_at(delegation, current_epoch_seconds())
    }

    /// Revoke an active delegation matching the delegate, scope, and delegator.
    ///
    /// Returns `true` if any delegation was marked revoked.
    ///
    /// # Errors
    ///
    /// This method does not return errors.
    pub fn revoke_delegation(&mut self, delegator: &str, delegate: &str, scope: Option<&Hash>) -> Result<bool> {
        self.revoke_delegation_at(delegator, delegate, scope, current_epoch_seconds())
    }

    /// Revoke a delegation using an explicit revocation time.
    ///
    /// Returns `true` if any delegation was marked revoked.
    ///
    /// # Errors
    ///
    /// This method does not return errors.
    pub fn revoke_delegation_at(
        &mut self,
        delegator: &str,
        delegate: &str,
        scope: Option<&Hash>,
        at: u64,
    ) -> Result<bool> {
        let mut changed = false;
        if let Some(delegations) = self.delegations.get_mut(delegator) {
            for delegation in delegations.iter_mut() {
                if delegation.delegate == delegate
                    && delegation.scope.as_ref() == scope
                    && delegation.revoked_at.is_none()
                {
                    delegation.revoked_at = Some(at);
                    changed = true;
                }
            }
        }
        Ok(changed)
    }

    /// Add a signed delegation using an explicit validation time.
    ///
    /// # Errors
    ///
    /// Returns an error if the delegation is invalid, expired, or not issued
    /// by an identity trusted for its scope.
    pub fn add_delegation_at(&mut self, delegation: TrustDelegation, now: u64) -> Result<bool> {
        delegation.verify_at(now)?;
        let scope = delegation.scope;
        if !self.is_trusted_for_at(&delegation.delegator, scope.as_ref(), now) {
            return Err(SyncwebError::InvalidIdentity(
                "trust delegation issuer is not trusted for its scope".to_owned(),
            ));
        }
        let entries = self.delegations.entry(delegation.delegator.clone()).or_default();
        if entries.iter().any(|existing| {
            existing.delegate == delegation.delegate
                && existing.scope == delegation.scope
                && existing.sequence >= delegation.sequence
        }) {
            return Ok(false);
        }
        entries.retain(|existing| {
            !(existing.delegate == delegation.delegate
                && existing.scope == delegation.scope
                && existing.sequence < delegation.sequence)
        });
        entries.push(delegation);
        Ok(true)
    }

    /// Return the local trust decision for an author.
    #[must_use]
    pub fn evaluate(&self, author: &str) -> TrustDecision {
        self.evaluate_at(author, current_epoch_seconds())
    }

    /// Return the local trust decision at an explicit time.
    #[must_use]
    pub fn evaluate_at(&self, author: &str, now: u64) -> TrustDecision {
        self.evaluate_for_at(author, None, now)
    }

    /// Return the local trust decision for an author and optional content.
    #[must_use]
    pub fn evaluate_for(&self, author: &str, content: Option<&Hash>) -> TrustDecision {
        self.evaluate_for_at(author, content, current_epoch_seconds())
    }

    /// Return the local trust decision for an author and content at an
    /// explicit time.
    #[must_use]
    pub fn evaluate_for_at(&self, author: &str, content: Option<&Hash>, now: u64) -> TrustDecision {
        if self.revoked_authors.contains(author) {
            return TrustDecision::Revoked;
        }
        if self.roots.contains(author) {
            return TrustDecision::TrustedRoot;
        }
        if self.reaches_trusted_root(author, content, now, 0, &mut HashSet::new()) {
            TrustDecision::TrustedDelegation
        } else {
            TrustDecision::Untrusted
        }
    }

    /// Return whether an author is trusted for the requested content.
    #[must_use]
    pub fn is_trusted_for(&self, author: &str, content: Option<&Hash>) -> bool {
        self.is_trusted_for_at(author, content, current_epoch_seconds())
    }

    /// Return whether an author is trusted at an explicit time.
    #[must_use]
    pub fn is_trusted_for_at(&self, author: &str, content: Option<&Hash>, now: u64) -> bool {
        self.evaluate_for_at(author, content, now).is_trusted()
    }

    fn reaches_trusted_root(
        &self,
        target: &str,
        content: Option<&Hash>,
        now: u64,
        depth: u32,
        visited: &mut HashSet<String>,
    ) -> bool {
        if self.revoked_authors.contains(target) {
            return false;
        }
        if self.roots.contains(target) {
            return true;
        }
        if !visited.insert(target.to_owned()) {
            return false;
        }
        self.delegations.iter().any(|(delegator, delegations)| {
            delegations.iter().any(|delegation| {
                if delegation.delegate != target
                    || delegation.revoked_at.is_some_and(|revoked_at| revoked_at <= now)
                    || delegation.expires_at <= now
                    || (delegation.scope.is_some() && delegation.scope.as_ref() != content)
                {
                    return false;
                }
                let next_depth = depth.saturating_add(1);
                if delegation.max_depth.is_some_and(|max_depth| next_depth > max_depth) {
                    return false;
                }
                let mut branch_visited = visited.clone();
                self.reaches_trusted_root(delegator, content, now, next_depth, &mut branch_visited)
            })
        })
    }
}

/// A publisher-signed self-revocation for a content hash.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RevocationRecord {
    pub content: Hash,
    pub publisher: String,
    pub sequence: u64,
    pub revoked_at: u64,
    pub reason: String,
    pub signature: Option<String>,
}

impl RevocationRecord {
    /// Create and sign a self-revocation.
    ///
    /// # Errors
    ///
    /// Returns an error if the sequence or reason is invalid.
    pub fn new(content: Hash, sequence: u64, reason: impl Into<String>, signing_key: &SigningKey) -> Result<Self> {
        let mut record = Self {
            content,
            publisher: author_id(&signing_key.verifying_key()),
            sequence,
            revoked_at: current_epoch_seconds(),
            reason: reason.into(),
            signature: None,
        };
        record.sign(signing_key)?;
        Ok(record)
    }

    /// Sign the revocation with the declared publisher.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the publisher.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.publisher, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(REVOCATION_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the publisher signature.
    ///
    /// # Errors
    ///
    /// Returns an error if the record or signature is invalid.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            REVOCATION_CONTEXT,
            &self.unsigned_bytes()?,
            &self.publisher,
            self.signature.as_deref(),
        )
    }

    /// Validate revocation fields.
    ///
    /// # Errors
    ///
    /// Returns an error if the sequence, reason, or publisher is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "revocation sequence must be greater than zero".to_owned(),
            ));
        }
        if self.reason.trim().is_empty() {
            return Err(SyncwebError::InvalidConfig(
                "revocation reason cannot be empty".to_owned(),
            ));
        }
        let _publisher = parse_author(&self.publisher)?;
        Ok(())
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(REVOCATION_CONTEXT, &unsigned)
    }
}

/// Moderation outcomes that can be attached to a content hash.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ModerationAction {
    Show,
    Hide,
    Warn,
    Quarantine,
    Restore,
}

/// The evaluated moderation decision.
pub type ModerationDecision = ModerationAction;

impl ModerationAction {
    #[must_use]
    pub const fn hides_content(&self) -> bool {
        matches!(self, Self::Hide | Self::Quarantine)
    }

    #[must_use]
    pub const fn is_visible(self) -> bool {
        !self.hides_content()
    }
}

/// The area in which a moderation decision applies.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ModerationScope {
    #[default]
    Global,
    Network(String),
    Folder(NamespaceId),
    File {
        namespace_id: NamespaceId,
        key: Vec<u8>,
    },
}

impl ModerationScope {
    #[must_use]
    pub fn applies_to(&self, context: &ModerationContext) -> bool {
        match self {
            Self::Global => true,
            Self::Network(network) => context.network.as_deref() == Some(network),
            Self::Folder(namespace_id) => context.namespace_id == Some(*namespace_id),
            Self::File { namespace_id, key } => {
                context.namespace_id == Some(*namespace_id) && context.key.as_deref() == Some(key.as_slice())
            }
        }
    }

    #[must_use]
    pub const fn specificity(&self) -> u8 {
        match self {
            Self::Global => 0,
            Self::Network(_) => 1,
            Self::Folder(_) => 2,
            Self::File { .. } => 3,
        }
    }
}

/// Context used to evaluate scoped moderation records.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct ModerationContext {
    pub content: Hash,
    pub network: Option<String>,
    pub namespace_id: Option<NamespaceId>,
    pub key: Option<Vec<u8>>,
}

impl ModerationContext {
    #[must_use]
    pub const fn new(content: Hash) -> Self {
        Self {
            content,
            network: None,
            namespace_id: None,
            key: None,
        }
    }

    #[must_use]
    pub fn in_network(mut self, network: impl Into<String>) -> Self {
        self.network = Some(network.into());
        self
    }

    #[must_use]
    pub fn for_file(mut self, namespace_id: NamespaceId, key: impl AsRef<[u8]>) -> Self {
        self.namespace_id = Some(namespace_id);
        self.key = Some(key.as_ref().to_vec());
        self
    }
}

/// A signed moderation decision.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ModerationRecord {
    pub content: Hash,
    pub moderator: String,
    pub action: ModerationAction,
    #[serde(default)]
    pub scope: ModerationScope,
    pub sequence: u64,
    pub created_at: u64,
    pub reason: String,
    pub signature: Option<String>,
}

impl ModerationRecord {
    /// Create and sign a moderation record.
    ///
    /// # Errors
    ///
    /// Returns an error if moderation fields are invalid.
    pub fn new(
        content: Hash,
        action: ModerationAction,
        sequence: u64,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut record = Self {
            content,
            moderator: author_id(&signing_key.verifying_key()),
            action,
            scope: ModerationScope::Global,
            sequence,
            created_at: current_epoch_seconds(),
            reason: reason.into(),
            signature: None,
        };
        record.sign(signing_key)?;
        Ok(record)
    }

    /// Create and sign a global moderation record with an explicit timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error if moderation fields are invalid or signing fails.
    pub fn new_with_time(
        content: Hash,
        action: ModerationAction,
        sequence: u64,
        created_at: u64,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        Self::new_scoped_with_time(
            content,
            ModerationScope::Global,
            action,
            sequence,
            created_at,
            reason,
            signing_key,
        )
    }

    /// Create and sign a moderation record for a specific scope.
    ///
    /// # Errors
    ///
    /// Returns an error if moderation fields are invalid.
    pub fn new_scoped(
        content: Hash,
        scope: ModerationScope,
        action: ModerationAction,
        sequence: u64,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        Self::new_scoped_with_time(
            content,
            scope,
            action,
            sequence,
            current_epoch_seconds(),
            reason,
            signing_key,
        )
    }

    /// Create and sign a scoped moderation record with an explicit timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error if moderation fields are invalid.
    pub fn new_scoped_with_time(
        content: Hash,
        scope: ModerationScope,
        action: ModerationAction,
        sequence: u64,
        created_at: u64,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut record = Self {
            content,
            moderator: author_id(&signing_key.verifying_key()),
            action,
            scope,
            sequence,
            created_at,
            reason: reason.into(),
            signature: None,
        };
        record.sign(signing_key)?;
        Ok(record)
    }

    /// Return a copy of this record with a different scope, re-signing it.
    ///
    /// # Errors
    ///
    /// Returns an error if the record cannot be signed.
    pub fn with_scope(mut self, scope: ModerationScope, signing_key: &SigningKey) -> Result<Self> {
        self.scope = scope;
        self.sign(signing_key)?;
        Ok(self)
    }

    /// Sign the moderation record.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the moderator.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.moderator, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(MODERATION_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the moderation signature.
    ///
    /// # Errors
    ///
    /// Returns an error if the record or signature is invalid.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            MODERATION_CONTEXT,
            &self.unsigned_bytes()?,
            &self.moderator,
            self.signature.as_deref(),
        )
    }

    /// Validate moderation fields.
    ///
    /// # Errors
    ///
    /// Returns an error if a field is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "moderation sequence must be greater than zero".to_owned(),
            ));
        }
        if self.reason.trim().is_empty() {
            return Err(SyncwebError::InvalidConfig(
                "moderation reason cannot be empty".to_owned(),
            ));
        }
        if let ModerationScope::Network(network) = &self.scope
            && network.trim().is_empty()
        {
            return Err(SyncwebError::InvalidConfig(
                "moderation network scope cannot be empty".to_owned(),
            ));
        }
        if let ModerationScope::File { key, .. } = &self.scope
            && key.is_empty()
        {
            return Err(SyncwebError::InvalidConfig(
                "moderation file scope cannot be empty".to_owned(),
            ));
        }
        let _moderator = parse_author(&self.moderator)?;
        Ok(())
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(MODERATION_CONTEXT, &unsigned)
    }
}

/// Types of signed provenance metadata.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AttestationKind {
    License,
    Provenance,
    Derivative,
    Other(String),
}

impl std::fmt::Display for AttestationKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::License => write!(f, "License"),
            Self::Provenance => write!(f, "Provenance"),
            Self::Derivative => write!(f, "Derivative"),
            Self::Other(value) => write!(f, "{value}"),
        }
    }
}

/// A signed license, provenance, or derivative attestation.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Attestation {
    pub content: Hash,
    pub issuer: String,
    pub kind: AttestationKind,
    pub value: String,
    pub sequence: u64,
    pub issued_at: u64,
    pub signature: Option<String>,
}

impl Attestation {
    /// Create and sign an attestation.
    ///
    /// # Errors
    ///
    /// Returns an error if attestation fields are invalid.
    pub fn new(
        content: Hash,
        kind: AttestationKind,
        value: impl Into<String>,
        sequence: u64,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut attestation = Self {
            content,
            issuer: author_id(&signing_key.verifying_key()),
            kind,
            value: value.into(),
            sequence,
            issued_at: current_epoch_seconds(),
            signature: None,
        };
        attestation.sign(signing_key)?;
        Ok(attestation)
    }

    /// Sign the attestation with the declared issuer.
    ///
    /// # Errors
    ///
    /// Returns an error if the signing key does not match the issuer.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.issuer, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(ATTESTATION_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the attestation signature.
    ///
    /// # Errors
    ///
    /// Returns an error if the attestation or signature is invalid.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            ATTESTATION_CONTEXT,
            &self.unsigned_bytes()?,
            &self.issuer,
            self.signature.as_deref(),
        )
    }

    /// Validate attestation fields.
    ///
    /// # Errors
    ///
    /// Returns an error if a field is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "attestation sequence must be greater than zero".to_owned(),
            ));
        }
        if self.value.trim().is_empty() {
            return Err(SyncwebError::InvalidConfig(
                "attestation value cannot be empty".to_owned(),
            ));
        }
        let _issuer = parse_author(&self.issuer)?;
        Ok(())
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(ATTESTATION_CONTEXT, &unsigned)
    }
}

/// A manually authored reliability opinion about a provider.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ProviderTrustAction {
    Trust,
    Distrust,
    Vouch,
    Warn,
}

/// A signed provider reliability record in the local Web-of-Trust.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProviderTrustRecord {
    pub provider: PublicKey,
    pub action: ProviderTrustAction,
    pub scope: Option<Hash>,
    pub issuer: String,
    pub sequence: u64,
    pub issued_at: u64,
    pub expires_at: Option<u64>,
    pub reason: String,
    pub signature: Option<String>,
}

impl ProviderTrustRecord {
    /// Create and sign a provider trust record using the current time.
    ///
    /// # Errors
    ///
    /// Returns an error if the record is invalid or signing fails.
    pub fn new(
        provider: PublicKey,
        action: ProviderTrustAction,
        scope: Option<Hash>,
        sequence: u64,
        expires_at: Option<u64>,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut record = Self {
            provider,
            action,
            scope,
            issuer: author_id(&signing_key.verifying_key()),
            sequence,
            issued_at: current_epoch_seconds(),
            expires_at,
            reason: reason.into(),
            signature: None,
        };
        record.sign(signing_key)?;
        Ok(record)
    }

    /// Create and sign a provider trust record with an explicit issue time.
    ///
    /// # Errors
    ///
    /// Returns an error if the record is invalid or signing fails.
    pub fn new_with_time(
        provider: PublicKey,
        action: ProviderTrustAction,
        scope: Option<Hash>,
        sequence: u64,
        issued_at: u64,
        reason: impl Into<String>,
        signing_key: &SigningKey,
    ) -> Result<Self> {
        let mut record = Self {
            provider,
            action,
            scope,
            issuer: author_id(&signing_key.verifying_key()),
            sequence,
            issued_at,
            expires_at: None,
            reason: reason.into(),
            signature: None,
        };
        record.sign(signing_key)?;
        Ok(record)
    }

    /// Add or replace an expiration time and re-sign the record.
    ///
    /// # Errors
    ///
    /// Returns an error when the expiration is invalid or signing fails.
    pub fn with_expiration(mut self, expires_at: Option<u64>, signing_key: &SigningKey) -> Result<Self> {
        self.expires_at = expires_at;
        self.sign(signing_key)?;
        Ok(self)
    }

    /// Sign the record with its declared issuer.
    ///
    /// # Errors
    ///
    /// Returns an error when the signing key does not match the issuer.
    pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
        ensure_signer(&self.issuer, &signing_key.verifying_key())?;
        self.signature = Some(sign_text(PROVIDER_TRUST_CONTEXT, &self.unsigned_bytes()?, signing_key));
        Ok(())
    }

    /// Verify the cryptographic signature.
    ///
    /// # Errors
    ///
    /// Returns an error when the record is malformed or unsigned.
    pub fn verify_signature(&self) -> Result<()> {
        self.validate()?;
        verify_text(
            PROVIDER_TRUST_CONTEXT,
            &self.unsigned_bytes()?,
            &self.issuer,
            self.signature.as_deref(),
        )
    }

    /// Verify the signature and require the record to be active now.
    ///
    /// # Errors
    ///
    /// Returns an error when the record is malformed, unsigned, or expired.
    pub fn verify(&self) -> Result<()> {
        self.verify_at(current_epoch_seconds())
    }

    /// Verify the signature and reject expired records.
    ///
    /// # Errors
    ///
    /// Returns an error when the record is malformed, unsigned, or expired.
    pub fn verify_at(&self, now: u64) -> Result<()> {
        self.verify_signature()?;
        if self.expires_at.is_some_and(|expires_at| expires_at <= now) {
            return Err(SyncwebError::InvalidConfig(
                "provider trust record has expired".to_owned(),
            ));
        }
        Ok(())
    }

    /// Validate non-cryptographic record fields.
    ///
    /// # Errors
    ///
    /// Returns an error when an identity, sequence, reason, or timestamp is invalid.
    pub fn validate(&self) -> Result<()> {
        if self.sequence == 0 {
            return Err(SyncwebError::InvalidConfig(
                "provider trust record sequence must be greater than zero".to_owned(),
            ));
        }
        if self.reason.trim().is_empty() {
            return Err(SyncwebError::InvalidConfig(
                "provider trust record reason cannot be empty".to_owned(),
            ));
        }
        if self.expires_at.is_some_and(|expires_at| expires_at <= self.issued_at) {
            return Err(SyncwebError::InvalidConfig(
                "provider trust record expiration must be after issue time".to_owned(),
            ));
        }
        VerifyingKey::from_bytes(self.provider.as_bytes())
            .map_err(|error| SyncwebError::InvalidIdentity(format!("invalid provider identity: {error}")))?;
        parse_author(&self.issuer)?;
        Ok(())
    }

    /// Encode the record as JSON.
    ///
    /// # Errors
    ///
    /// Returns an error when the record is invalid or cannot be serialized.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        self.validate()?;
        serde_json::to_vec(self)
            .map_err(|error| SyncwebError::operation("failed to serialize provider trust record", error))
    }

    /// Decode a record from JSON.
    ///
    /// # Errors
    ///
    /// Returns an error when the bytes do not contain a valid record.
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
        let record: Self = serde_json::from_slice(bytes.as_ref())
            .map_err(|error| SyncwebError::operation("failed to deserialize provider trust record", error))?;
        record.validate()?;
        Ok(record)
    }

    fn unsigned_bytes(&self) -> Result<Vec<u8>> {
        let mut unsigned = self.clone();
        unsigned.signature = None;
        signed_bytes(PROVIDER_TRUST_CONTEXT, &unsigned)
    }
}

/// Result of evaluating manual provider trust records.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProviderTrustDecision {
    Trusted,
    Distrusted,
    Unknown,
    Conflicting,
}

impl ProviderTrustDecision {
    #[must_use]
    pub const fn is_trusted(self) -> bool {
        matches!(self, Self::Trusted)
    }

    #[must_use]
    pub const fn is_distrusted(self) -> bool {
        matches!(self, Self::Distrusted)
    }
}

#[derive(Clone, Debug, Default)]
struct WotState {
    revocations: HashMap<Hash, RevocationRecord>,
    moderation: HashMap<Hash, Vec<ModerationRecord>>,
    attestations: HashMap<(Hash, String, u64), Attestation>,
    provider_trust: HashMap<PublicKey, Vec<ProviderTrustRecord>>,
}

/// Indexing-layer service for trusted metadata and local governance records.
#[derive(Clone)]
pub struct WotService {
    database: IndexingDatabase,
    policy: Arc<Mutex<TrustPolicy>>,
    state: Arc<Mutex<WotState>>,
}

impl std::fmt::Debug for WotService {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("WotService").finish_non_exhaustive()
    }
}

impl WotService {
    /// Create a Web-of-Trust service using an existing indexing service.
    #[must_use]
    pub fn new(indexing: &IndexingService, policy: TrustPolicy) -> Self {
        Self::with_database(indexing.database().clone(), policy)
    }

    /// Create a service backed by an indexing database.
    #[must_use]
    pub fn with_database(database: IndexingDatabase, policy: TrustPolicy) -> Self {
        let mut state = WotState::default();
        if let Ok(records) = database.load_provider_trust_records() {
            let now = current_epoch_seconds();
            for record in records {
                if record.expires_at.is_some_and(|e| e <= now) {
                    continue;
                }
                if record.verify_signature().is_err() {
                    tracing::warn!("skipping provider trust record with invalid signature on load");
                    continue;
                }
                state.provider_trust.entry(record.provider).or_default().push(record);
            }
        }
        Self {
            database,
            policy: Arc::new(Mutex::new(policy)),
            state: Arc::new(Mutex::new(state)),
        }
    }

    /// Create an isolated in-memory Web-of-Trust service.
    ///
    /// # Errors
    ///
    /// Returns an error if `SQLite` cannot initialize.
    pub fn in_memory(policy: TrustPolicy) -> Result<Self> {
        Ok(Self::with_database(IndexingDatabase::in_memory()?, policy))
    }

    #[must_use]
    pub const fn database(&self) -> &IndexingDatabase {
        &self.database
    }

    /// Return a copy of the current local trust policy.
    ///
    /// # Errors
    ///
    /// Returns an error if policy state is poisoned.
    pub fn policy(&self) -> Result<TrustPolicy> {
        Ok(self
            .policy
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust policy lock poisoned", error))?
            .clone())
    }

    /// Add a local trusted root.
    ///
    /// # Errors
    ///
    /// Returns an error if policy state is poisoned.
    pub fn trust_author(&self, author: &VerifyingKey) -> Result<()> {
        self.policy
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust policy lock poisoned", error))?
            .trust_author(author);
        Ok(())
    }

    /// Add a signed delegation to the local policy.
    ///
    /// # Errors
    ///
    /// Returns an error if the delegation is invalid or its issuer is not
    /// locally trusted.
    pub fn add_delegation(&self, delegation: TrustDelegation) -> Result<bool> {
        self.add_delegation_at(delegation, current_epoch_seconds())
    }

    /// Add a signed delegation using an explicit validation time.
    ///
    /// # Errors
    ///
    /// Returns an error if the delegation is invalid or its issuer is not
    /// locally trusted.
    pub fn add_delegation_at(&self, delegation: TrustDelegation, now: u64) -> Result<bool> {
        self.policy
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust policy lock poisoned", error))?
            .add_delegation_at(delegation, now)
    }

    /// Revoke a delegation matching the delegate, scope, and delegator.
    ///
    /// Returns `true` if any delegation was marked revoked.
    ///
    /// # Errors
    ///
    /// Returns an error if the policy lock is poisoned.
    pub fn revoke_delegation(&self, delegator: &str, delegate: &str, scope: Option<&Hash>) -> Result<bool> {
        self.revoke_delegation_at(delegator, delegate, scope, current_epoch_seconds())
    }

    /// Revoke a delegation using an explicit revocation time.
    ///
    /// Returns `true` if any delegation was marked revoked.
    ///
    /// # Errors
    ///
    /// Returns an error if the policy lock is poisoned.
    pub fn revoke_delegation_at(&self, delegator: &str, delegate: &str, scope: Option<&Hash>, at: u64) -> Result<bool> {
        self.policy
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust policy lock poisoned", error))?
            .revoke_delegation_at(delegator, delegate, scope, at)
    }

    /// Apply a signed manual provider trust record from a trusted issuer.
    ///
    /// A provider may always publish a signed self-distrust, which allows a
    /// compromised or retiring provider to withdraw its own availability.
    ///
    /// # Errors
    ///
    /// Returns an error when the record is invalid or its issuer is untrusted.
    pub fn apply_provider_trust(&self, record: ProviderTrustRecord) -> Result<bool> {
        let now = current_epoch_seconds();
        record.verify_at(now)?;
        let issuer_key = parse_author(&record.issuer)?;
        let is_self_distrust =
            issuer_key.as_bytes() == record.provider.as_bytes() && record.action == ProviderTrustAction::Distrust;
        if !is_self_distrust
            && !self
                .policy()?
                .is_trusted_for_at(&record.issuer, record.scope.as_ref(), now)
        {
            return Err(SyncwebError::InvalidIdentity(
                "provider trust record issuer is not trusted for its scope".to_owned(),
            ));
        }
        let all_records = {
            let mut state = self
                .state
                .lock()
                .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
            let records = state.provider_trust.entry(record.provider).or_default();
            if records.iter().any(|existing| {
                existing.issuer == record.issuer
                    && existing.scope == record.scope
                    && existing.sequence >= record.sequence
            }) {
                return Ok(false);
            }
            records.retain(|existing| {
                !(existing.issuer == record.issuer
                    && existing.scope == record.scope
                    && existing.sequence < record.sequence)
            });
            records.push(record);
            state
                .provider_trust
                .values()
                .flat_map(|v| v.iter().cloned())
                .collect::<Vec<_>>()
        };
        self.database.save_provider_trust_records(&all_records)?;
        Ok(true)
    }

    /// Evaluate the newest applicable provider trust records.
    /// # Errors
    ///
    /// Returns an error when the `WoT` state lock is poisoned.
    pub fn evaluate_provider_trust(
        &self,
        provider: PublicKey,
        hash: Option<&Hash>,
        now: u64,
    ) -> Result<ProviderTrustDecision> {
        let records = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .provider_trust
            .get(&provider)
            .cloned()
            .unwrap_or_default();
        let maybe_latest_sequence = records
            .iter()
            .filter(|record| {
                record.expires_at.is_none_or(|expires_at| expires_at > now)
                    && record.scope.as_ref().is_none_or(|scope| Some(scope) == hash)
            })
            .map(|record| record.sequence)
            .max();
        let Some(latest_sequence) = maybe_latest_sequence else {
            return Ok(ProviderTrustDecision::Unknown);
        };
        let latest = records
            .iter()
            .filter(|record| {
                record.sequence == latest_sequence
                    && record.expires_at.is_none_or(|expires_at| expires_at > now)
                    && record.scope.as_ref().is_none_or(|scope| Some(scope) == hash)
            })
            .collect::<Vec<_>>();
        let trusted = latest
            .iter()
            .any(|record| matches!(record.action, ProviderTrustAction::Trust | ProviderTrustAction::Vouch));
        let distrusted = latest
            .iter()
            .any(|record| matches!(record.action, ProviderTrustAction::Distrust));
        Ok(match (trusted, distrusted) {
            (true, true) => ProviderTrustDecision::Conflicting,
            (true, false) => ProviderTrustDecision::Trusted,
            (false, true) => ProviderTrustDecision::Distrusted,
            (false, false) => ProviderTrustDecision::Unknown,
        })
    }

    /// Evaluate a provider trust decision for a concrete content hash.
    ///
    /// # Errors
    ///
    /// Returns an error when the `WoT` state lock is poisoned.
    pub fn evaluate_provider_trust_for_hash(
        &self,
        provider: PublicKey,
        hash: Hash,
        now: u64,
    ) -> Result<ProviderTrustDecision> {
        self.evaluate_provider_trust(provider, Some(&hash), now)
    }

    /// Return all records for a provider, newest first.
    ///
    /// # Errors
    ///
    /// Returns an error when the `WoT` state lock is poisoned.
    pub fn provider_trust_records(&self, provider: PublicKey) -> Result<Vec<ProviderTrustRecord>> {
        let mut records = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .provider_trust
            .get(&provider)
            .cloned()
            .unwrap_or_default();
        records.sort_by(|left, right| {
            right
                .sequence
                .cmp(&left.sequence)
                .then_with(|| right.issued_at.cmp(&left.issued_at))
        });
        Ok(records)
    }

    /// Append metadata after signature and local trust checks.
    ///
    /// # Errors
    ///
    /// Returns an error if the metadata is not signed, trusted, or the content
    /// has been self-revoked.
    pub fn append_metadata(&self, entry: &MetadataEntry) -> Result<bool> {
        entry.verify_signature()?;
        let now = current_epoch_seconds();
        let policy = self
            .policy
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust policy lock poisoned", error))?;
        if !policy.is_trusted_for_at(&entry.author, Some(&entry.content), now) {
            return Err(SyncwebError::InvalidIdentity(
                "metadata author is not trusted for this content".to_owned(),
            ));
        }
        drop(policy);
        if self.is_revoked(&entry.content)? {
            return Err(SyncwebError::InvalidConfig(
                "metadata cannot be appended to self-revoked content".to_owned(),
            ));
        }
        self.database.append_wot_metadata(entry)
    }

    /// Search trusted metadata while applying local revocation and moderation.
    ///
    /// # Errors
    ///
    /// Returns an error if the query or index is invalid.
    pub fn search_metadata(&self, query: &str, limit: usize) -> Result<Vec<MetadataEntry>> {
        let records = self.database.search_wot_metadata(query, limit)?;
        let state = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
        Ok(records
            .into_iter()
            .filter(|entry| !state.revocations.contains_key(&entry.content))
            .filter(|entry| {
                state.moderation.get(&entry.content).is_none_or(|moderation_records| {
                    moderation_records
                        .iter()
                        .filter(|record| matches!(&record.scope, ModerationScope::Global))
                        .max_by_key(|record| record.sequence)
                        .is_none_or(|record| !record.action.hides_content())
                })
            })
            .collect())
    }

    /// Alias for [`Self::search_metadata`].
    ///
    /// # Errors
    ///
    /// Returns an error if the query or index is invalid.
    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<MetadataEntry>> {
        self.search_metadata(query, limit)
    }

    /// Accept a publisher's self-revocation.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature is invalid or an older sequence was
    /// already recorded.
    pub fn revoke_self(&self, record: RevocationRecord) -> Result<bool> {
        record.verify_signature()?;
        let mut state = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
        if state
            .revocations
            .get(&record.content)
            .is_some_and(|existing| existing.sequence >= record.sequence)
        {
            return Ok(false);
        }
        state.revocations.insert(record.content, record);
        drop(state);
        Ok(true)
    }

    /// Return whether a content hash has a valid self-revocation.
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn is_revoked(&self, content: &Hash) -> Result<bool> {
        Ok(self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .revocations
            .contains_key(content))
    }

    /// Accept a trusted moderation record.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature is invalid, the moderator is not
    /// trusted, or an older sequence was already recorded.
    pub fn apply_moderation(&self, record: ModerationRecord) -> Result<bool> {
        record.verify_signature()?;
        let now = current_epoch_seconds();
        if !self
            .policy()?
            .is_trusted_for_at(&record.moderator, Some(&record.content), now)
        {
            return Err(SyncwebError::InvalidIdentity(
                "moderator is not trusted for this content".to_owned(),
            ));
        }
        let mut state = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
        let records = state.moderation.entry(record.content).or_default();
        if records
            .iter()
            .filter(|existing| existing.scope == record.scope)
            .any(|existing| existing.sequence >= record.sequence)
        {
            return Ok(false);
        }
        records.push(record);
        drop(state);
        Ok(true)
    }

    /// Return the latest moderation record for a content hash.
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn moderation(&self, content: &Hash) -> Result<Option<ModerationRecord>> {
        Ok(self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .moderation
            .get(content)
            .and_then(|records| {
                records
                    .iter()
                    .max_by_key(|record| (record.sequence, record.scope.specificity()))
                    .cloned()
            }))
    }

    /// Return all moderation records for a content hash, newest first.
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn moderation_records(&self, content: &Hash) -> Result<Vec<ModerationRecord>> {
        let mut records = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .moderation
            .get(content)
            .cloned()
            .unwrap_or_default();
        records.sort_by(|left, right| {
            right
                .sequence
                .cmp(&left.sequence)
                .then_with(|| right.scope.specificity().cmp(&left.scope.specificity()))
        });
        Ok(records)
    }

    /// List all moderation records, optionally restricted to one content hash.
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn list_moderation(&self, content: Option<&Hash>) -> Result<Vec<ModerationRecord>> {
        let state = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
        let mut records = state
            .moderation
            .iter()
            .filter(|(hash, _)| content.is_none_or(|requested| requested == *hash))
            .flat_map(|(_, records)| records.iter().cloned())
            .collect::<Vec<_>>();
        drop(state);
        records.sort_by(|left, right| {
            right
                .sequence
                .cmp(&left.sequence)
                .then_with(|| right.scope.specificity().cmp(&left.scope.specificity()))
        });
        Ok(records)
    }

    /// Evaluate the latest applicable moderation decision for a context.
    ///
    /// More recent decisions win; when sequence numbers tie, the more
    /// specific scope wins.
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn moderation_decision(&self, context: &ModerationContext) -> Result<ModerationAction> {
        let selected_record = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?
            .moderation
            .get(&context.content)
            .and_then(|records| {
                records
                    .iter()
                    .filter(|record| record.scope.applies_to(context))
                    .max_by_key(|record| (record.sequence, record.scope.specificity()))
                    .cloned()
            });
        Ok(selected_record.map_or(ModerationAction::Show, |selected| selected.action))
    }

    /// Alias for [`Self::moderation_decision`].
    ///
    /// # Errors
    ///
    /// Returns an error if state is poisoned.
    pub fn evaluate_moderation(&self, context: &ModerationContext) -> Result<ModerationAction> {
        self.moderation_decision(context)
    }

    /// Store an attestation after cryptographic and local trust checks.
    ///
    /// # Errors
    ///
    /// Returns an error if the attestation is invalid or its issuer is not
    /// trusted.
    pub fn append_attestation(&self, attestation: Attestation) -> Result<bool> {
        attestation.verify_signature()?;
        let now = current_epoch_seconds();
        if !self
            .policy()?
            .is_trusted_for_at(&attestation.issuer, Some(&attestation.content), now)
        {
            return Err(SyncwebError::InvalidIdentity(
                "attestation issuer is not trusted for this content".to_owned(),
            ));
        }
        let mut state = self
            .state
            .lock()
            .map_err(|error| SyncwebError::operation("Web-of-Trust state lock poisoned", error))?;
        let key = (attestation.content, attestation.issuer.clone(), attestation.sequence);
        if state.attestations.contains_key(&key) {
            return Ok(false);
        }
        state.attestations.insert(key, attestation);
        drop(state);
        Ok(true)
    }

    /// Verify an attestation's cryptographic signature without applying local
    /// trust policy.
    ///
    /// # Errors
    ///
    /// Returns an error if the attestation is malformed or tampered with.
    pub fn verify_attestation(&self, attestation: &Attestation) -> Result<()> {
        attestation.verify_signature()
    }
}

fn signed_bytes<T: Serialize>(context: &[u8], value: &T) -> Result<Vec<u8>> {
    let encoded = serde_json::to_vec(value)
        .map_err(|error| SyncwebError::operation("failed to serialize signed Web-of-Trust record", error))?;
    let mut bytes = Vec::with_capacity(context.len().saturating_add(encoded.len()));
    bytes.extend_from_slice(context);
    bytes.extend_from_slice(&encoded);
    Ok(bytes)
}

fn sign_text(context: &[u8], unsigned: &[u8], signing_key: &SigningKey) -> String {
    let mut bytes = Vec::with_capacity(context.len().saturating_add(unsigned.len()));
    bytes.extend_from_slice(context);
    bytes.extend_from_slice(unsigned);
    hex::encode(signing_key.sign(&bytes).to_bytes())
}

fn verify_text(context: &[u8], unsigned: &[u8], author: &str, signature: Option<&str>) -> Result<()> {
    let signature_text = signature
        .ok_or_else(|| SyncwebError::InvalidConfig("signed Web-of-Trust record has no signature".to_owned()))?;
    let signature_bytes = hex::decode(signature_text)
        .map_err(|error| SyncwebError::InvalidConfig(format!("invalid Web-of-Trust signature encoding: {error}")))?;
    let parsed_signature = Signature::from_slice(&signature_bytes)
        .map_err(|error| SyncwebError::InvalidConfig(format!("invalid Web-of-Trust signature: {error}")))?;
    let verifying_key = parse_author(author)?;
    let mut bytes = Vec::with_capacity(context.len().saturating_add(unsigned.len()));
    bytes.extend_from_slice(context);
    bytes.extend_from_slice(unsigned);
    verifying_key
        .verify(&bytes, &parsed_signature)
        .map_err(|error| SyncwebError::InvalidConfig(format!("Web-of-Trust signature is invalid: {error}")))
}

fn ensure_signer(author: &str, signing_key: &VerifyingKey) -> Result<()> {
    if author == author_id(signing_key) {
        Ok(())
    } else {
        Err(SyncwebError::InvalidIdentity(
            "Web-of-Trust signer does not match the declared author".to_owned(),
        ))
    }
}

fn author_id(author: &VerifyingKey) -> String {
    hex::encode(author.to_bytes())
}

fn parse_author(author: &str) -> Result<VerifyingKey> {
    let bytes = hex::decode(author)
        .map_err(|error| SyncwebError::InvalidIdentity(format!("invalid Web-of-Trust author encoding: {error}")))?;
    let key_bytes: [u8; 32] = bytes.try_into().map_err(|error: Vec<u8>| {
        SyncwebError::InvalidIdentity(format!("Web-of-Trust author must be 32 bytes, got {}", error.len()))
    })?;
    VerifyingKey::from_bytes(&key_bytes)
        .map_err(|error| SyncwebError::InvalidIdentity(format!("invalid Web-of-Trust author key: {error}")))
}

impl SignedGossipMessage for Attestation {
    fn verify_signature(&self) -> Result<()> {
        self.verify_signature()
    }
}

/// Deterministic gossip topic for broadcasting attestations.
pub const ATTESTATION_GOSSIP_TOPIC: &[u8] = b"syncweb/attestations/v1";

fn current_epoch_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_secs())
}