dtg-credentials 0.8.0

Decentralized Trust Graph (DTG) Credentials Library
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
/*!
*   Builder methods for creating new entities.
*/

#[allow(deprecated)]
use crate::{
    AuthorityGrant, CredentialSubject, CredentialSubjectAuthority, CredentialSubjectBasic,
    CredentialSubjectDelegation, CredentialSubjectEndorsement, CredentialSubjectMembership,
    CredentialSubjectRCard, CredentialSubjectWitness, DTGCommon, DTGCredential, DTGCredentialError,
    DTGCredentialType, DelegationGrant, WitnessContext,
};
use chrono::{DateTime, Utc};
use serde_json::Value;

impl DTGCredential {
    /// Creates a new community-issued Verifiable Membership Credential (VMC) — the
    /// membership **grant**, the community → member half of a membership edge.
    ///
    /// A membership edge is a *pair* of VMCs, and this is only one of them. The member
    /// answers with [DTGCredential::new_member_vmc], and the edge is not complete until
    /// they have: a community can always issue a credential naming somebody as a member,
    /// but it cannot produce the acknowledgement without that party's signature. The pair
    /// is what makes an unconsented membership claim unprovable.
    ///
    /// The grant MUST NOT carry a `digestMultibase` — that property is what marks the
    /// other direction — and this constructor does not set one.
    ///
    /// issuer: The identifier of the VTC or VTN granting membership
    /// subject: The member's identifier, or the member VTC's own for VTN membership
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    /// personhood: Whether this VMC can be used as a form of Personhood Credential
    ///             - Adds PersonhoodCredential to the type array if true
    ///
    /// # Give it an `id`
    ///
    /// Chain [DTGCredential::with_id] on: the member stores the grant under its `id`, and
    /// re-issuing is only recognisable as a renewal rather than a duplicate if there is one.
    pub fn new_vmc(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
        personhood: bool,
    ) -> Self {
        let mut vmc = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Membership(CredentialSubjectMembership {
                id: subject,
                digest_multibase: None,
            }),
            ..Default::default()
        };

        vmc.type_.push(DTGCredentialType::Membership.to_string());

        if personhood {
            vmc.type_.push("PersonhoodCredential".to_string());
        }

        DTGCredential {
            credential: vmc,
            type_: DTGCredentialType::Membership,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new member-issued Verifiable Membership Credential (VMC) — the membership
    /// **acknowledgement**, the member → community half of a membership edge.
    ///
    /// The roles of [DTGCredential::new_vmc] are reversed (the member issues, the community
    /// is the subject) and the subject carries a `digestMultibase` of the grant being
    /// acknowledged.
    /// That digest is what binds the two halves into one edge: an acknowledgement whose
    /// digest matches no valid grant does not complete anything, and the binding forces an
    /// order — the grant must exist before this can reference it.
    ///
    /// This is the member's consent artifact. Because the member is its issuer, withdrawing
    /// consent needs no cooperation from the community.
    ///
    /// # Takes the grant in its wire form, deliberately
    ///
    /// `grant` is the JSON the community sent, not a parsed [DTGCredential]. The digest has
    /// to cover the document the community will recompute it over, and this library does
    /// not model every member a credential may carry — `credentialStatus`, which every VMC
    /// issued against a status list carries, is dropped by a parse-then-re-serialise round
    /// trip. Building the acknowledgement from a parsed grant would produce a digest that
    /// verifies nowhere, and would do it silently.
    ///
    /// So: keep the bytes you were given, and pass them here.
    ///
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    ///
    /// # Errors
    ///
    /// [DTGCredentialError::NotAMembershipGrant] if `grant` is not a JSON object, does not
    /// carry `MembershipCredential` in its `type`, has no `issuer` or
    /// `credentialSubject.id`, or already carries a `digest` — that last is an
    /// acknowledgement, and acknowledging one does not form an edge.
    ///
    /// # Give it an `id`
    ///
    /// Chain [DTGCredential::with_id] on before signing. A community keys a member's VMC by
    /// `id` to tell a re-send from a renewal.
    pub fn new_member_vmc(
        grant: &Value,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
    ) -> Result<Self, DTGCredentialError> {
        let object = grant
            .as_object()
            .ok_or_else(|| DTGCredentialError::NotAMembershipGrant("not a JSON object".into()))?;

        let is_membership = object
            .get("type")
            .and_then(Value::as_array)
            .is_some_and(|types| {
                types
                    .iter()
                    .filter_map(Value::as_str)
                    .any(|t| t == "MembershipCredential")
            });
        if !is_membership {
            return Err(DTGCredentialError::NotAMembershipGrant(
                "`type` does not include `MembershipCredential`".into(),
            ));
        }

        let subject = object
            .get("credentialSubject")
            .and_then(Value::as_object)
            .ok_or_else(|| {
                DTGCredentialError::NotAMembershipGrant("no `credentialSubject`".into())
            })?;

        // Both spellings: `digestMultibase` is the Working Draft 02 name, `digest` the
        // Working Draft 01 one this library also accepts on the wire. Probing only the
        // current name would let an acknowledgement issued against the older draft be
        // acknowledged in turn, which forms no edge.
        if subject.contains_key("digestMultibase") || subject.contains_key("digest") {
            return Err(DTGCredentialError::NotAMembershipGrant(
                "the credential carries a digest of another credential, so it is itself a \
                 member-issued acknowledgement rather than a community-issued grant"
                    .into(),
            ));
        }

        // The member is the grant's subject and the community its issuer: reading both off
        // the grant is what keeps the two halves naming the same pair. Taking them as
        // parameters would let a caller acknowledge one grant while naming the parties of
        // another, which verifies as a digest match and means nothing.
        let member = subject
            .get("id")
            .and_then(Value::as_str)
            .ok_or_else(|| {
                DTGCredentialError::NotAMembershipGrant("no `credentialSubject.id`".into())
            })?
            .to_string();

        // `issuer` is a string or an object with an `id`, per the W3C data model.
        let community = object
            .get("issuer")
            .and_then(|i| {
                i.as_str()
                    .map(str::to_string)
                    .or_else(|| i.get("id").and_then(Value::as_str).map(str::to_string))
            })
            .ok_or_else(|| DTGCredentialError::NotAMembershipGrant("no `issuer`".into()))?;

        let mut vmc = DTGCommon {
            issuer: member,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Membership(CredentialSubjectMembership {
                id: community,
                digest_multibase: Some(crate::digest_multibase_json(grant)?),
            }),
            ..Default::default()
        };

        vmc.type_.push(DTGCredentialType::Membership.to_string());

        Ok(DTGCredential {
            credential: vmc,
            type_: DTGCredentialType::Membership,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Creates a new Verified Relationship Credential (VRC)
    /// issuer: The issuer DID of the credential
    /// subject: The DID of the subject of this credential
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    pub fn new_vrc(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
    ) -> Self {
        let mut vrc = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Basic(CredentialSubjectBasic { id: subject }),
            ..Default::default()
        };

        vrc.type_.push(DTGCredentialType::Relationship.to_string());

        DTGCredential {
            credential: vrc,
            type_: DTGCredentialType::Relationship,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new Verified Invitation Credential (VIC)
    /// issuer: The issuer DID of the credential
    /// subject: The DID of the subject of this credential
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    pub fn new_vic(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
    ) -> Self {
        let mut vic = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Basic(CredentialSubjectBasic { id: subject }),
            ..Default::default()
        };

        vic.type_.push(DTGCredentialType::Invitation.to_string());

        DTGCredential {
            credential: vic,
            type_: DTGCredentialType::Invitation,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new Verifiable Authority Credential (VAC) — a chain root.
    ///
    /// The issuer is the party governing `scope`. To derive a narrower VAC from one you
    /// already hold, use [DTGCredential::attenuate] instead: a chain root is a grant made
    /// by the governing party, and minting one directly is how a self-issued grant of
    /// arbitrary authority gets in.
    ///
    /// `actions` MUST NOT be empty — an empty list confers nothing rather than everything.
    ///
    /// # `valid_until` is required
    ///
    /// Not optional, unlike the base structure and unlike every other `new_*` constructor
    /// here. Nothing about the subject's current standing is consulted when a VAC is
    /// verified, so authority that does not expire is authority nobody can withdraw by
    /// waiting.
    pub fn new_vac(
        issuer: String,
        subject: String,
        scope: String,
        actions: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        if actions.is_empty() {
            return Err(DTGCredentialError::EmptyAuthorityActions);
        }
        let mut vac = DTGCommon {
            issuer,
            valid_from,
            valid_until: Some(valid_until),
            credential_subject: CredentialSubject::Authority(CredentialSubjectAuthority {
                id: subject,
                authority: AuthorityGrant {
                    scope,
                    actions,
                    parent: None,
                },
            }),
            ..Default::default()
        };

        vac.type_.push(DTGCredentialType::Authority.to_string());

        Ok(DTGCredential {
            credential: vac,
            type_: DTGCredentialType::Authority,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Derive a narrower VAC from one this holder already holds.
    ///
    /// This is what lets a member equip an agent, a device, or a short-lived session with
    /// only the authority that task needs, rather than lending it their own. The derived
    /// credential is issued by the *holder*, not by the party governing the scope, and
    /// carries `parent` — the **digest** of the credential it narrows — so a verifier can
    /// walk back to a root.
    ///
    /// Refuses anything that would widen. The checks here mirror
    /// [crate::authority::verify_chain] on purpose: a holder should be unable to *build* a
    /// chain a verifier would reject, so the failure surfaces at issue time rather than at
    /// use — but the verifier's checks remain authoritative, because nothing stops a
    /// different implementation constructing the JSON by hand.
    ///
    /// - `self` must be a VAC.
    /// - `actions` must be a subset of what `self` confers.
    /// - `valid_until` must not exceed `self`'s.
    ///
    /// # Binding the derivative to the agent is `subject`, not a separate field
    ///
    /// A VAC is not a bearer credential: [crate::authority::verify_chain] requires the
    /// party presenting the leaf to be its subject. So equipping an agent means naming the
    /// agent in `subject`, and there is nothing further to bind. An earlier version of this
    /// method took an `audience` for that job; it was removed with the property.
    ///
    /// # Digests the model
    ///
    /// The `parent` digest is computed with [DTGCredential::digest_multibase], which hashes
    /// this in-memory credential. That is right for a VAC this process built and signed.
    /// For one that **arrived from a counterparty**, use
    /// [DTGCredential::attenuate_from_json] and give it the bytes you received — the same
    /// distinction [DTGCredential::new_member_vmc] draws, and for the same reason.
    pub fn attenuate(
        &self,
        subject: String,
        actions: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        let parent_grant = self
            .credential()
            .authority()
            .ok_or(DTGCredentialError::NotAnAuthorityCredential)?;

        Self::attenuate_inner(
            parent_grant.clone(),
            self.credential().subject().to_string(),
            self.credential().valid_until(),
            self.digest_multibase()?,
            subject,
            actions,
            valid_from,
            valid_until,
        )
    }

    /// Derive a narrower VAC from a parent in its **wire form**.
    ///
    /// Identical to [DTGCredential::attenuate] except that the parent is the JSON a
    /// counterparty sent rather than a parsed credential, so the `parent` digest covers
    /// the document the verifier will recompute it over. Use this whenever the VAC being
    /// narrowed came from somewhere else.
    ///
    /// # Errors
    ///
    /// [DTGCredentialError::NotAnAuthorityCredential] if `parent` is not a JSON object
    /// carrying `AuthorityCredential` in its `type` and a well-formed
    /// `credentialSubject.authority`, and the same widening errors as
    /// [DTGCredential::attenuate].
    pub fn attenuate_from_json(
        parent: &Value,
        subject: String,
        actions: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        let object = parent
            .as_object()
            .ok_or(DTGCredentialError::NotAnAuthorityCredential)?;

        let is_authority = object
            .get("type")
            .and_then(Value::as_array)
            .is_some_and(|types| {
                types
                    .iter()
                    .filter_map(Value::as_str)
                    .any(|t| t == "AuthorityCredential")
            });
        if !is_authority {
            return Err(DTGCredentialError::NotAnAuthorityCredential);
        }

        let parent_subject = object
            .get("credentialSubject")
            .and_then(Value::as_object)
            .ok_or(DTGCredentialError::NotAnAuthorityCredential)?;

        // The holder attenuating is the parent's subject; reading it off the parent is what
        // keeps a derived VAC from citing a chain its issuer never held.
        let holder = parent_subject
            .get("id")
            .and_then(Value::as_str)
            .ok_or(DTGCredentialError::NotAnAuthorityCredential)?
            .to_string();

        let parent_grant: AuthorityGrant = parent_subject
            .get("authority")
            .ok_or(DTGCredentialError::NotAnAuthorityCredential)
            .and_then(|a| {
                serde_json::from_value(a.clone())
                    .map_err(|_| DTGCredentialError::NotAnAuthorityCredential)
            })?;

        let parent_until = object
            .get("validUntil")
            .or_else(|| object.get("expirationDate"))
            .and_then(Value::as_str)
            .and_then(|t| DateTime::parse_from_rfc3339(t).ok())
            .map(|t| t.with_timezone(&Utc));

        Self::attenuate_inner(
            parent_grant,
            holder,
            parent_until,
            crate::digest_multibase_json(parent)?,
            subject,
            actions,
            valid_from,
            valid_until,
        )
    }

    /// The narrowing checks and the assembly, shared by both attenuation entry points.
    #[allow(clippy::too_many_arguments)]
    fn attenuate_inner(
        parent_grant: AuthorityGrant,
        holder: String,
        parent_until: Option<DateTime<Utc>>,
        parent_digest: String,
        subject: String,
        actions: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        if actions.is_empty() {
            return Err(DTGCredentialError::EmptyAuthorityActions);
        }
        for action in &actions {
            if !parent_grant.actions.contains(action) {
                return Err(DTGCredentialError::AttenuationWidens(format!(
                    "action `{action}` is not conferred by the parent"
                )));
            }
        }
        if let Some(parent_until) = parent_until
            && valid_until > parent_until
        {
            return Err(DTGCredentialError::AttenuationWidens(format!(
                "validUntil {valid_until} is beyond the parent's {parent_until}"
            )));
        }

        let mut vac = DTGCommon {
            // The holder issues: they are the subject of the parent grant.
            issuer: holder,
            valid_from,
            valid_until: Some(valid_until),
            credential_subject: CredentialSubject::Authority(CredentialSubjectAuthority {
                id: subject,
                authority: AuthorityGrant {
                    // Scope never changes down a chain.
                    scope: parent_grant.scope.clone(),
                    actions,
                    parent: Some(parent_digest),
                },
            }),
            ..Default::default()
        };

        vac.type_.push(DTGCredentialType::Authority.to_string());

        Ok(DTGCredential {
            credential: vac,
            type_: DTGCredentialType::Authority,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Creates a new Verifiable Delegation Credential (VDC) — the delegation **grant**,
    /// the delegator → delegate half of a delegation edge.
    ///
    /// Establishes that `subject` may act **in the issuer's name**, for the acts named in
    /// `scope`, until `valid_until`. Within that scope what the delegate does is
    /// attributable to the delegator.
    ///
    /// # This is not authority
    ///
    /// A VDC never supplies permission the delegator did not itself hold. A verifier
    /// substitutes the delegator for the delegate and then asks the permission question it
    /// would have asked of the delegator directly — so withdrawing the delegator's own
    /// permission ends the delegate's ability to act immediately, without revoking
    /// anything. See [DTGCredential::new_vac] for the credential that answers that
    /// question.
    ///
    /// # The edge is not complete without the acceptance
    ///
    /// This is one half. The delegate answers with [DTGCredential::new_delegate_vdc], and
    /// a verifier MUST obtain and verify that half before accepting any party as acting
    /// under the delegation: a grant alone establishes what the delegator appointed, not
    /// what the delegate agreed to. Same consent rule as a membership edge, and for the
    /// same reason — a delegator can always name someone as its delegate, but cannot
    /// produce the countersignature.
    ///
    /// `scope` MUST NOT be empty: a VDC cannot express an unbounded appointment by
    /// omitting it.
    ///
    /// `max_depth` is the number of further re-delegations permitted below this one.
    /// `None` and `Some(0)` both prohibit re-delegation — the default is a single hop, and
    /// setting it above zero is the delegator's explicit authorisation, of which there is
    /// no other kind.
    ///
    /// # `valid_until` is required
    ///
    /// An appointment with no expiry cannot be reasoned about by a verifier that cannot
    /// reach the delegator.
    ///
    /// # Errors
    ///
    /// [DTGCredentialError::MalformedDelegation] if `scope` is empty.
    pub fn new_vdc(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
        scope: Vec<String>,
        max_depth: Option<u32>,
    ) -> Result<Self, DTGCredentialError> {
        if scope.is_empty() {
            return Err(DTGCredentialError::MalformedDelegation(
                "a grant MUST carry at least one `scope` entry — a VDC cannot express an \
                 unbounded appointment by emptying it"
                    .into(),
            ));
        }

        let mut vdc = DTGCommon {
            issuer,
            valid_from,
            valid_until: Some(valid_until),
            credential_subject: CredentialSubject::Delegation(CredentialSubjectDelegation {
                id: subject,
                delegation: DelegationGrant {
                    scope: Some(scope),
                    parent: None,
                    max_depth,
                    accepts: None,
                },
            }),
            ..Default::default()
        };

        vdc.type_.push(DTGCredentialType::Delegation.to_string());

        Ok(DTGCredential {
            credential: vdc,
            type_: DTGCredentialType::Delegation,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Derive a further VDC from one this delegate already holds — a **re-delegation**.
    ///
    /// Only permitted where the held VDC sets `maxDepth` above zero, and only for a subset
    /// of the acts it was itself appointed for. The default is a single hop: a delegate
    /// that needs a further delegate and is not authorised to re-delegate asks the
    /// principal, who issues a fresh root delegation directly — so that the principal
    /// always holds the complete register of who may speak in its name.
    ///
    /// The derived VDC carries `parent`, the digest of the VDC it derives from, and a
    /// `maxDepth` one less than its parent's.
    ///
    /// Like [DTGCredential::attenuate], this digests the in-memory model; for a grant that
    /// arrived from a counterparty, use [DTGCredential::redelegate_from_json].
    ///
    /// # Errors
    ///
    /// [DTGCredentialError::MalformedDelegation] if `self` is not a delegation grant, if
    /// it does not permit re-delegation, if `scope` is empty or not a subset of the
    /// parent's, or if `valid_until` is later than the parent's.
    pub fn redelegate(
        &self,
        subject: String,
        scope: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        let parent = self.credential().delegation().ok_or_else(|| {
            DTGCredentialError::MalformedDelegation("not a DelegationCredential".into())
        })?;

        Self::redelegate_inner(
            parent.clone(),
            self.credential().subject().to_string(),
            self.credential().valid_until(),
            self.digest_multibase()?,
            subject,
            scope,
            valid_from,
            valid_until,
        )
    }

    /// Derive a further VDC from a parent grant in its **wire form**.
    ///
    /// Identical to [DTGCredential::redelegate] except that the parent is the JSON the
    /// delegator sent, so the `parent` digest covers the document a verifier will
    /// recompute it over.
    pub fn redelegate_from_json(
        parent: &Value,
        subject: String,
        scope: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        let (delegate, grant, parent_until) = Self::read_delegation_json(parent)?;

        Self::redelegate_inner(
            grant,
            delegate,
            parent_until,
            crate::digest_multibase_json(parent)?,
            subject,
            scope,
            valid_from,
            valid_until,
        )
    }

    /// The narrowing checks and the assembly, shared by both re-delegation entry points.
    #[allow(clippy::too_many_arguments)]
    fn redelegate_inner(
        parent_grant: DelegationGrant,
        holder: String,
        parent_until: Option<DateTime<Utc>>,
        parent_digest: String,
        subject: String,
        scope: Vec<String>,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        if parent_grant.accepts.is_some() {
            return Err(DTGCredentialError::MalformedDelegation(
                "the parent is an acceptance, not a grant — an acceptance appoints nobody \
                 and cannot be re-delegated from"
                    .into(),
            ));
        }

        // Absence prohibits re-delegation just as `0` does. This is the opposite default
        // from a VAC, deliberately: a delegate speaks in the principal's name, so the
        // principal keeps the register of who may do so.
        let parent_depth = parent_grant.max_depth.unwrap_or(0);
        if parent_depth == 0 {
            return Err(DTGCredentialError::MalformedDelegation(
                "the parent does not permit re-delegation — `maxDepth` is absent or zero, \
                 and setting it above zero is the delegator's only way to authorise one"
                    .into(),
            ));
        }

        if scope.is_empty() {
            return Err(DTGCredentialError::MalformedDelegation(
                "a grant MUST carry at least one `scope` entry".into(),
            ));
        }
        let parent_scope = parent_grant.scope.as_deref().unwrap_or(&[]);
        for act in &scope {
            if !parent_scope.contains(act) {
                return Err(DTGCredentialError::MalformedDelegation(format!(
                    "`{act}` is not in the scope this delegation derives from"
                )));
            }
        }
        if let Some(parent_until) = parent_until
            && valid_until > parent_until
        {
            return Err(DTGCredentialError::MalformedDelegation(format!(
                "validUntil {valid_until} is beyond the parent's {parent_until}"
            )));
        }

        let mut vdc = DTGCommon {
            issuer: holder,
            valid_from,
            valid_until: Some(valid_until),
            credential_subject: CredentialSubject::Delegation(CredentialSubjectDelegation {
                id: subject,
                delegation: DelegationGrant {
                    scope: Some(scope),
                    parent: Some(parent_digest),
                    max_depth: Some(parent_depth - 1),
                    accepts: None,
                },
            }),
            ..Default::default()
        };

        vdc.type_.push(DTGCredentialType::Delegation.to_string());

        Ok(DTGCredential {
            credential: vdc,
            type_: DTGCredentialType::Delegation,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Creates the delegate-issued half of a delegation edge — the **acceptance**.
    ///
    /// The roles of [DTGCredential::new_vdc] are reversed (the delegate issues, the
    /// delegator is the subject) and the subject carries `accepts`, the digest of the
    /// grant being taken on. That digest is what binds the two halves into one edge.
    ///
    /// An acceptance carries no `scope` of its own. What the delegate consented to is the
    /// scope of the grant it names, which a verifier holds in any case; restating it would
    /// require an equality check across the two credentials that cannot be satisfied under
    /// selective disclosure of either.
    ///
    /// This is the delegate's consent artifact, and its accountability for acting in
    /// another's name. Because a delegator cannot produce it, a party holding only the
    /// delegate's key cannot manufacture appointments either.
    ///
    /// # Takes the grant in its wire form, deliberately
    ///
    /// Same reasoning as [DTGCredential::new_member_vmc]: the digest has to cover the
    /// document the delegator will recompute it over. Keep the bytes you were given and
    /// pass them here.
    ///
    /// # Errors
    ///
    /// [DTGCredentialError::NotADelegationGrant] if `grant` is not a JSON object carrying
    /// `DelegationCredential` in its `type`, has no `issuer` or `credentialSubject.id`, or
    /// already carries `accepts` — that last is itself an acceptance, and accepting one
    /// forms no edge.
    pub fn new_delegate_vdc(
        grant: &Value,
        valid_from: DateTime<Utc>,
        valid_until: DateTime<Utc>,
    ) -> Result<Self, DTGCredentialError> {
        let object = grant
            .as_object()
            .ok_or_else(|| DTGCredentialError::NotADelegationGrant("not a JSON object".into()))?;

        let is_delegation = object
            .get("type")
            .and_then(Value::as_array)
            .is_some_and(|types| {
                types
                    .iter()
                    .filter_map(Value::as_str)
                    .any(|t| t == "DelegationCredential")
            });
        if !is_delegation {
            return Err(DTGCredentialError::NotADelegationGrant(
                "`type` does not include `DelegationCredential`".into(),
            ));
        }

        let subject = object
            .get("credentialSubject")
            .and_then(Value::as_object)
            .ok_or_else(|| {
                DTGCredentialError::NotADelegationGrant("no `credentialSubject`".into())
            })?;

        let delegation = subject
            .get("delegation")
            .and_then(Value::as_object)
            .ok_or_else(|| {
                DTGCredentialError::NotADelegationGrant("no `credentialSubject.delegation`".into())
            })?;

        if delegation.contains_key("accepts") {
            return Err(DTGCredentialError::NotADelegationGrant(
                "the credential carries `accepts`, so it is itself an acceptance rather \
                 than a grant"
                    .into(),
            ));
        }
        if !delegation.contains_key("scope") {
            return Err(DTGCredentialError::NotADelegationGrant(
                "the grant carries no `scope`, so there is no appointment to accept".into(),
            ));
        }

        // The delegate is the grant's subject and the delegator its issuer. Reading both
        // off the grant is what keeps the two halves naming the same pair — taking them as
        // parameters would let a caller accept one grant while naming the parties of
        // another, which verifies as a digest match and means nothing.
        let delegate = subject
            .get("id")
            .and_then(Value::as_str)
            .ok_or_else(|| {
                DTGCredentialError::NotADelegationGrant("no `credentialSubject.id`".into())
            })?
            .to_string();

        // `issuer` is a string or an object with an `id`, per the W3C data model.
        let delegator = object
            .get("issuer")
            .and_then(|i| {
                i.as_str()
                    .map(str::to_string)
                    .or_else(|| i.get("id").and_then(Value::as_str).map(str::to_string))
            })
            .ok_or_else(|| DTGCredentialError::NotADelegationGrant("no `issuer`".into()))?;

        let mut vdc = DTGCommon {
            issuer: delegate,
            valid_from,
            valid_until: Some(valid_until),
            credential_subject: CredentialSubject::Delegation(CredentialSubjectDelegation {
                id: delegator,
                delegation: DelegationGrant {
                    scope: None,
                    parent: None,
                    max_depth: None,
                    accepts: Some(crate::digest_multibase_json(grant)?),
                },
            }),
            ..Default::default()
        };

        vdc.type_.push(DTGCredentialType::Delegation.to_string());

        Ok(DTGCredential {
            credential: vdc,
            type_: DTGCredentialType::Delegation,
            version: crate::W3CVCVersion::V2_0,
        })
    }

    /// Reads the delegate, the grant, and the parent's expiry off a VDC in its wire form.
    fn read_delegation_json(
        doc: &Value,
    ) -> Result<(String, DelegationGrant, Option<DateTime<Utc>>), DTGCredentialError> {
        let object = doc
            .as_object()
            .ok_or_else(|| DTGCredentialError::MalformedDelegation("not a JSON object".into()))?;

        let is_delegation = object
            .get("type")
            .and_then(Value::as_array)
            .is_some_and(|types| {
                types
                    .iter()
                    .filter_map(Value::as_str)
                    .any(|t| t == "DelegationCredential")
            });
        if !is_delegation {
            return Err(DTGCredentialError::MalformedDelegation(
                "`type` does not include `DelegationCredential`".into(),
            ));
        }

        let subject = object
            .get("credentialSubject")
            .and_then(Value::as_object)
            .ok_or_else(|| {
                DTGCredentialError::MalformedDelegation("no `credentialSubject`".into())
            })?;

        let delegate = subject
            .get("id")
            .and_then(Value::as_str)
            .ok_or_else(|| {
                DTGCredentialError::MalformedDelegation("no `credentialSubject.id`".into())
            })?
            .to_string();

        let grant: DelegationGrant = subject
            .get("delegation")
            .ok_or_else(|| {
                DTGCredentialError::MalformedDelegation("no `credentialSubject.delegation`".into())
            })
            .and_then(|d| {
                serde_json::from_value(d.clone()).map_err(|e| {
                    DTGCredentialError::MalformedDelegation(format!("malformed `delegation`: {e}"))
                })
            })?;

        let until = object
            .get("validUntil")
            .or_else(|| object.get("expirationDate"))
            .and_then(Value::as_str)
            .and_then(|t| DateTime::parse_from_rfc3339(t).ok())
            .map(|t| t.with_timezone(&Utc));

        Ok((delegate, grant, until))
    }

    /// Creates a new Verified Persona Credential (VPC)
    /// issuer: The issuer DID of the credential
    /// subject: The DID of the subject of this credential
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    pub fn new_vpc(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
    ) -> Self {
        let mut vpc = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Basic(CredentialSubjectBasic { id: subject }),
            ..Default::default()
        };

        vpc.type_.push(DTGCredentialType::Persona.to_string());

        DTGCredential {
            credential: vpc,
            type_: DTGCredentialType::Persona,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new Verified Endorsement Credential (VEC)
    /// issuer: The issuer DID of the credential
    /// subject: The DID of the subject of this credential
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    /// endorsement: The endorsement details for this credential
    pub fn new_vec(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
        endorsement: Value,
    ) -> Self {
        let mut vec = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::Endorsement(CredentialSubjectEndorsement {
                id: subject,
                endorsement,
            }),
            ..Default::default()
        };

        vec.type_.push(DTGCredentialType::Endorsement.to_string());

        DTGCredential {
            credential: vec,
            type_: DTGCredentialType::Endorsement,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new Verified Witness Credential (VWC)
    /// issuer: The issuer DID of the credential - a member's identifier, or the DID of a
    ///         VTA acting according to VTC policy
    /// subject: The DID of the observed party. For a witnessed bi-directional exchange this
    ///          MUST be the issuer of the VRC that this VWC attests (the VRC referenced by
    ///          `digestMultibase`), so that the two VWCs of an exchange are unambiguously bound to
    ///          their respective directions. The witness should issue one VWC per direction.
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    /// task_context: Required `threadId` of the trust task exchange the witnessing occurred in
    /// digest: Cryptographic hash of the witnessed edge credential, binding this VWC to the
    ///         specific edge. Produce it with [DTGCredential::digest_multibase] on that
    ///         credential, or [crate::digest_multibase_json] on the bytes you received.
    ///         REQUIRED by the specification; `Option` here because a VWC that predates the
    ///         requirement still has to deserialize. A VWC without one identifies the
    ///         observed party and the exchange, but not which edge was witnessed.
    /// witness_context: Optional Semantic context for the witness
    pub fn new_vwc(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
        task_context: String,
        digest: Option<String>,
        witness_context: Option<WitnessContext>,
    ) -> Self {
        let mut vwc = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            task_context: Some(task_context),
            credential_subject: CredentialSubject::Witness(CredentialSubjectWitness {
                id: subject,
                digest_multibase: digest,
                witness_context,
            }),
            ..Default::default()
        };

        vwc.type_.push(DTGCredentialType::Witness.to_string());

        DTGCredential {
            credential: vwc,
            type_: DTGCredentialType::Witness,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Creates a new Verified RCard Credential (VWC)
    /// issuer: The issuer DID of the credential
    /// subject: The DID of the subject of this credential
    /// valid_from: The datetime from which this credential is valid
    /// valid_until: Optional: The datetime this credential is valid until
    /// card: JSON Value representing a Jcard (RFC 7095) format
    #[deprecated(
        since = "0.2.0",
        note = "The r-card is a verifiable data structure (VDS), not a DTGCredential subtype. \
                It was removed from the DTG Core Credentials specification in Working Draft 01 \
                and will be defined by the planned DTG Verifiable Data Structures specification. \
                This constructor will be removed in a future release."
    )]
    #[allow(deprecated)]
    pub fn new_rcard(
        issuer: String,
        subject: String,
        valid_from: DateTime<Utc>,
        valid_until: Option<DateTime<Utc>>,
        card: Value,
    ) -> Self {
        let mut rcard = DTGCommon {
            issuer,
            valid_from,
            valid_until,
            credential_subject: CredentialSubject::RCard(CredentialSubjectRCard {
                id: subject,
                card,
            }),
            ..Default::default()
        };

        rcard.type_.push(DTGCredentialType::RCard.to_string());

        DTGCredential {
            credential: rcard,
            type_: DTGCredentialType::RCard,
            version: crate::W3CVCVersion::V2_0,
        }
    }

    /// Sets this credential's own identifier, consuming and returning it so it chains onto
    /// any of the `new_*` constructors above.
    ///
    /// `id` MUST be a single URL per the W3C VC Data Model; `urn:uuid:<uuid>` is the usual
    /// choice for a credential with no dereferenceable home. This crate does not validate it.
    ///
    /// ```
    /// # use chrono::Utc;
    /// # use dtg_credentials::DTGCredential;
    /// let vmc = DTGCredential::new_vmc(
    ///     "did:example:member".to_string(),
    ///     "did:example:community".to_string(),
    ///     Utc::now(),
    ///     None,
    ///     false,
    /// )
    /// .with_id("urn:uuid:2a4e1d90-6e0c-4d3f-9a4a-6d0a8f7c1b52");
    /// assert_eq!(vmc.id(), Some("urn:uuid:2a4e1d90-6e0c-4d3f-9a4a-6d0a8f7c1b52"));
    /// ```
    ///
    /// # Set it before signing
    ///
    /// A Data Integrity proof covers the credential minus its `proof`, so `id` is part of what
    /// is signed. Chain this onto the constructor, before [DTGCredential::sign] — adding an id
    /// to an already-signed credential leaves a document whose proof no longer verifies.
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.credential.id = Some(id.into());
        self
    }

    /// Sets this credential's own identifier in place.
    ///
    /// The non-consuming form of [DTGCredential::with_id]; the same "before signing" caveat
    /// applies.
    pub fn set_id(&mut self, id: impl Into<String>) {
        self.credential.id = Some(id.into());
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use crate::{DTGCredential, WitnessContext};
    use chrono::{DateTime, Utc};
    use serde_json::json;

    #[test]
    fn test_vmc_serialization() {
        let vmc = DTGCredential::new_vmc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            false,
        );

        let txt = serde_json::to_string_pretty(&vmc).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "MembershipCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_vmc_phc_serialization() {
        let vmc = DTGCredential::new_vmc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            true,
        );

        let txt = serde_json::to_string_pretty(&vmc).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "MembershipCredential",
    "PersonhoodCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }
    /// `id` is OPTIONAL, and a credential that was never given one must keep serializing the
    /// shape it always did — no `"id": null`, no empty string.
    #[test]
    fn test_vmc_without_id_omits_the_property() {
        let vmc = DTGCredential::new_vmc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            false,
        );

        assert_eq!(vmc.id(), None);
        let value: serde_json::Value = serde_json::to_value(&vmc).unwrap();
        assert!(
            value.get("id").is_none(),
            "an unset id must not appear on the wire at all: {value}"
        );
    }

    /// `with_id` puts the identifier at the top level of the credential — a sibling of
    /// `issuer`, not something nested under `credentialSubject` (which carries the *subject's*
    /// id, a different thing entirely).
    #[test]
    fn test_vmc_with_id_serialization() {
        let vmc = DTGCredential::new_vmc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            false,
        )
        .with_id("urn:uuid:1e2d3c4b-5a69-4788-9099-aabbccddeeff");

        let txt = serde_json::to_string_pretty(&vmc).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "MembershipCredential"
  ],
  "id": "urn:uuid:1e2d3c4b-5a69-4788-9099-aabbccddeeff",
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }

    /// The identifier has to survive a round trip. It arrives on the wire and is read back
    /// through `TryFrom<DTGCommon>`, which is where `taskContext` was previously being dropped
    /// — a field that deserializes into nothing breaks signing and verification silently.
    #[test]
    fn test_id_round_trips_through_deserialization() {
        let vmc = DTGCredential::new_vmc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            Utc::now(),
            None,
            false,
        )
        .with_id("urn:uuid:1e2d3c4b-5a69-4788-9099-aabbccddeeff");

        let txt = serde_json::to_string(&vmc).unwrap();
        let parsed: DTGCredential = serde_json::from_str(&txt).unwrap();
        assert_eq!(
            parsed.id(),
            Some("urn:uuid:1e2d3c4b-5a69-4788-9099-aabbccddeeff")
        );
    }

    /// A credential with no `id` still deserializes — the property is OPTIONAL, and every
    /// credential issued before this field existed has none.
    #[test]
    fn test_missing_id_deserializes_as_none() {
        let parsed: DTGCredential = serde_json::from_str(
            r#"{
              "@context": ["https://www.w3.org/ns/credentials/v2"],
              "type": ["VerifiableCredential", "DTGCredential", "MembershipCredential"],
              "issuer": "did:example:issuer",
              "validFrom": "2025-12-11T00:00:00Z",
              "credentialSubject": { "id": "did:example:subject" }
            }"#,
        )
        .unwrap();
        assert_eq!(parsed.id(), None);
    }

    /// `set_id` is the in-place form of `with_id`; both write the same property.
    #[test]
    fn test_set_id_matches_with_id() {
        let build = || {
            DTGCredential::new_vrc(
                "did:example:issuer".to_string(),
                "did:example:subject".to_string(),
                DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
                None,
            )
        };
        let mut in_place = build();
        in_place.set_id("urn:uuid:abc");
        assert_eq!(
            serde_json::to_value(&in_place).unwrap(),
            serde_json::to_value(build().with_id("urn:uuid:abc")).unwrap()
        );
    }

    #[test]
    fn test_vrc_serialization() {
        let vrc = DTGCredential::new_vrc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
        );

        let txt = serde_json::to_string_pretty(&vrc).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "RelationshipCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_vic_serialization() {
        let vic = DTGCredential::new_vic(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
        );

        let txt = serde_json::to_string_pretty(&vic).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "InvitationCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_vpc_serialization() {
        let vpc = DTGCredential::new_vpc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
        );

        let txt = serde_json::to_string_pretty(&vpc).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "PersonaCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject"
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_vec_serialization() {
        let vec = DTGCredential::new_vec(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            json!({
              "type": "SkillEndorsement",
              "name": "Software Development",
              "competencyLevel": "expert"
            }),
        );

        let txt = serde_json::to_string_pretty(&vec).unwrap();
        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "EndorsementCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject",
    "endorsement": {
      "competencyLevel": "expert",
      "name": "Software Development",
      "type": "SkillEndorsement"
    }
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_vwc_serialization() {
        let vwc = DTGCredential::new_vwc(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            "thread-abc-123".to_string(),
            Some("zQmbGXRT3v1RmfWkQ7Y3Z5Uj9pKq2NcXhLd8sVtA4eB6nMw".to_string()),
            Some(WitnessContext {
                event: Some("EthDenver 2024".to_string()),
                session_id: Some("session-8822-nonce".to_string()),
                method: Some("in-person-proximity".to_string()),
            }),
        );

        let txt = serde_json::to_string_pretty(&vwc).unwrap();

        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "WitnessCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "taskContext": "thread-abc-123",
  "credentialSubject": {
    "id": "did:example:subject",
    "digestMultibase": "zQmbGXRT3v1RmfWkQ7Y3Z5Uj9pKq2NcXhLd8sVtA4eB6nMw",
    "witnessContext": {
      "event": "EthDenver 2024",
      "sessionId": "session-8822-nonce",
      "method": "in-person-proximity"
    }
  }
}"#;

        assert_eq!(txt, sample);
    }

    #[test]
    fn test_rcard_serialization() {
        let rcard = DTGCredential::new_rcard(
            "did:example:issuer".to_string(),
            "did:example:subject".to_string(),
            DateTime::parse_from_rfc3339("2025-12-11T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            None,
            json!([
                "vcard",
                [
                    ["fn", {}, "text", "Alice Smith"],
                    ["email", {}, "text", "alice@example.com"]
                ]
            ]),
        );

        let txt = serde_json::to_string_pretty(&rcard).unwrap();

        let sample = r#"{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://firstperson.network/credentials/dtg/v1"
  ],
  "type": [
    "VerifiableCredential",
    "DTGCredential",
    "RCardCredential"
  ],
  "issuer": "did:example:issuer",
  "validFrom": "2025-12-11T00:00:00Z",
  "credentialSubject": {
    "id": "did:example:subject",
    "card": [
      "vcard",
      [
        [
          "fn",
          {},
          "text",
          "Alice Smith"
        ],
        [
          "email",
          {},
          "text",
          "alice@example.com"
        ]
      ]
    ]
  }
}"#;

        assert_eq!(txt, sample);
    }
}