dtg-credentials 0.12.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
# Decentralized Trust Graph (DTG) Credentials

**_NOTE:_** This is an early implementation of the [DTG Core Credentials
specification](https://github.com/trustoverip/dtgwg-cred-spec) (v1.0, Document
Status Working Draft 0.6.0), using the frozen v1 credential context
`https://registry.trustoverip.org/dtg/context/v1` published by the DTG VSC
Predicate Registry.

See the [First Person Project Whitepaper](https://www.firstperson.network/white-paper)
for more information.

This library issues W3C VC 2.0 credentials and also parses 1.1 ones (the spec's
legacy compatibility profile), provided they list the DTG v1 context second.

See [CHANGELOG.md](CHANGELOG.md) for release history.

## Examples

```bash
cargo run --example sign_and_verify   # create, sign, verify one credential
cargo run --example data_room         # a whole data room, end to end
```

`data_room` runs the room story in one process with real DIDs, real signed credentials,
real AEAD and real chain verification: a room issues its owner a VAC, invites a member by
VIC, completes the VMC pair on their acknowledgement, seals a record, watches that member
equip an **agent with strictly less authority than they hold themselves**, then appoints a
service to act **in that member's name** by VDC — the same member, two credentials, and a
verifier that can always tell which it was shown — rotates the epoch on removal, and
finally prints exactly what the host can see, which is ciphertext, an epoch number, and
nothing else.

The credential types each have their own tests; `tests/authority_chain.rs` and
`tests/delegation_chain.rs` are mostly *attacks*, since what makes a VAC or a VDC
safe is a verifier refusing a chain that widens.

## Credential Type Hierarchy

All credentials inherit from the abstract `DTGCredential`.

```text
VerifiableCredential
└── DTGCredential
    ├── MembershipCredential (VMC)
    ├── RelationshipCredential (VRC)
    ├── DelegationCredential (VDC)
    ├── InvitationCredential (VIC)
    ├── PersonaCredential (VPC)
    ├── StatementCredential (VSC)
    │     ├── profile endorses/1 (VEC)
    │     ├── profile witnessed/1 (VWC)
    │     ├── profile vetted/1
    │     └── profile presented/1
    └── AuthorityCredential (VAC)
```

Every credential this library emits looks like this:

```json
{
  "@context": [
    "https://www.w3.org/ns/credentials/v2",
    "https://registry.trustoverip.org/dtg/context/v1"
  ],
  "type": ["VerifiableCredential", "DTGCredential", "MembershipCredential"],
  "issuer": "did:example:community",
  "issuerScope": "public",
  "validFrom": "2026-01-06T10:00:00Z",
  "credentialSubject": { "id": "did:example:member" }
}
```

A parse refuses anything else: the W3C context first and the DTG v1 context second
(compared as exact strings — the pre-v1 `https://firstperson.network/credentials/dtg/v1`
is not recognized), `type` holding `VerifiableCredential`, `DTGCredential` and **exactly
one** concrete subtype, with `PersonhoodCredential` allowed only as a non-authoritative
hint on a VMC, and a REQUIRED `issuerScope`.

`EndorsementCredential`, `WitnessCredential` and `RCardCredential` are refused by name.
The first two are now predicate profiles of the VSC; the r-card is a verifiable data
structure, not a DTG credential.

Two of those confer rather than assert, and a verifier has to be able to tell
which it was shown:

| | Question it answers | The act is attributed to |
| --- | --- | --- |
| **VAC** (authority) | may this party do this thing, *as itself*? | the party itself |
| **VDC** (delegation) | may this party act *in another's name*? | the entity it stands in for |

Neither implies the other, and a VDC never supplies authority the delegator did
not itself hold. See [Authority](#authority-vac) and [Delegation](#delegation-vdc).

## Issuer scope

Every DTG credential declares the **correlation scope** of its *issuer's* identifier in
the REQUIRED top-level `issuerScope`: `pairwise`, `directed` or `public`, narrowest first
and compared case-sensitively. It is the issuer's own declaration and covers nothing else
— never the subject's scope, never the counterparty's.

```Rust
use dtg_credentials::IssuerScope;

let vrc = DTGCredential::new_vrc(alice_pairwise, IssuerScope::Pairwise, bob_pairwise, now, None);
assert!(IssuerScope::Public.satisfies(IssuerScope::Directed));
```

Every constructor takes it explicitly, except where the specification fixes it: a
community-issued VMC is always `public` (a community that cannot be found cannot be
joined), so `new_vmc` sets it and a grant declaring anything else is refused at parse.
`new_community_role_vac` fixes `public` for the same reason. Profiles may set a minimum:
`witnessed/1`, `vetted/1` and `presented/1` refuse `pairwise`.

## Statements (VSC)

A VSC is one signed statement, by one node about another, whose meaning is fixed by its
`predicate` — an absolute IRI, matched byte for byte:

```json
"credentialSubject": {
  "id": "did:example:subject",
  "predicate": "https://registry.trustoverip.org/dtg/vsc/endorses/1",
  "object": { "value": { "type": "SkillEndorsement", "name": "Software Development" } }
}
```

`object` carries **exactly one** of `id`, `digestMultibase` or `value` (`StatementObject`).
A compact form such as `dtg:endorses`, a bare term, a relative reference or an IRI not in
Unicode NFC is refused (`check_predicate_iri`): nothing is ever expanded.

| Constant | `object` | `taskContext` | min. `issuerScope` | Constructor |
| --- | --- | --- | --- | --- |
| `ENDORSES_V1` | `value` | optional | — | `new_endorses_vsc` |
| `WITNESSED_V1` | `digestMultibase` | required | `directed` | `new_witnessed_vsc` |
| `VETTED_V1` | `value` | required | `directed` | `new_vetted_vsc` |
| `PRESENTED_V1` | `digestMultibase` | required | `directed` | `new_presented_vsc` |

`new_vsc` builds a statement under any predicate — a community's own, say. The profile
constructors additionally read the parts that must agree from the documents themselves:

```Rust
// The witness observed Alice issue her VRC, in the session she opened with it.
let vwc = DTGCredential::new_witnessed_vsc(
  witness_did, IssuerScope::Public,
  &alices_vrc_json,   // subject := its issuer; object.digestMultibase := its digest
  &session,           // taskContext := its id; taskDigestMultibase := its task digest
  now, None, witness_context,
)?;
assert!(vwc.witnesses_issuance_of(&alices_vrc_json)?);   // the verifier's subject–object check
```

`new_presented_vsc` is the counterpart with the referenced credential's *subject* as the
statement's subject (`witnesses_presentation_of` checks it). `new_vetted_vsc` takes the
vetting payload as a `serde_json::Value`; its schema belongs to the registry definition and
the code that fills it in.

A core statement is held to its profile when parsed, built, validated and signed: a
`witnessed/1` statement without `taskContext` and `taskDigestMultibase`, with a `value`
object, or declaring `pairwise`, does not parse and cannot be signed.

### Accepting a predicate

A statement whose signature verifies is not thereby meaningful. `PredicateAcceptList` is
the verifier's configuration, and fails closed: an exact byte match or a rejection, with no
equivalence (`owl:sameAs` and the like) ever followed.

```Rust
// From the IRIs your governance names...
let accepted = PredicateAcceptList::from_iris([WITNESSED_V1, "https://vtc.example/vocab#vetted"])?;

// ...or from the registry's accept-list.json, keeping the statuses you admit and applying
// each entry's constraints (object kind, taskContext, minimum issuerScope, required members).
let accepted = PredicateAcceptList::from_registry_json(
  &accept_list_json, &[PredicateStatus::Candidate, PredicateStatus::Standard],
)?;

let predicate = accepted.accept(&statement)?;   // Err(PredicateNotAccepted) otherwise
```

Acceptance says what a statement *means*, never more: a VSC attests and never establishes
membership, authority or personhood.

## Trust Task Context

Credentials issued inside a multi-step trust task exchange may carry a
`taskContext` property naming that exchange: the `id` of the document that
initiated the innermost exchange attesting what the credential states. It is
REQUIRED on a statement whose profile requires it — `witnessed/1`, `vetted/1`,
`presented/1` — and OPTIONAL everywhere else.

An `id` is only a name, and anyone can write a different document that reuses it.
So a citation also carries `taskDigestMultibase`, the *task digest* of the
document `taskContext` names (Trust Tasks §4.9.3): the document **with its
top-level `proof` removed**, canonicalized with JCS, hashed with sha2-256 and
encoded as a base58btc multibase multihash — the same encoding as every other
digest in DTG Core Credentials, over a Trust Task document instead of a
credential. It is REQUIRED wherever `taskContext` is, and a statement missing it
is refused with `MissingTaskDigest`.

The profile constructors set both from the session document, so the pair cannot
disagree; `with_task_citation(&document)` sets both on any other credential.
`new_witnessed_vsc` also refuses a document that is not the opening
`witness/session` — the `submit` document, the witness's response, or anything
whose `threadId` is not its own `id` — because naming the wrong exchange is the
easy mistake.

A verifier checks both halves with `cites_task`:

```Rust
if vwc.cites_task(&session)? {
  // `taskContext` is the session's `id`, and `taskDigestMultibase` matches its
  // recomputed task digest, compared as decoded bytes.
}
```

It returns `false` for a credential with no `taskDigestMultibase` rather than
falling back to comparing `id`s, which Trust Tasks forbids.

> [!IMPORTANT]
> The task digest is **not** the digest of the document as it arrived. Trust
> Tasks also defines a *step digest*, which includes the `proof` — the
> `idConflict` identity, and what `witness/session/submit`'s
> `vwcDigestMultibase` is taken over. Do not use one for the other.

A credential without a `taskContext` must be interpretable standing alone. A
credential *with* one must not be read as proof that the trust task completed
unless the matching outcome evidence is also present and verified;
`cites_task` establishes which document a credential names, not that the
exchange completed.

## Digests

A credential can be referenced by another through a `digestMultibase` of it: a
member-issued VMC digests the membership grant it acknowledges, a VSC's
`object.digestMultibase` digests the credential it is about (a VWC, the edge
credential it attests), an attenuated VAC digests the VAC it narrows, and a VDC
digests the delegation it derives from or the grant it accepts. All of them use the
same computation.

```Rust
// A credential you received: digest the JSON as it arrived.
let digest = dtg_credentials::digest_multibase_json(&grant_json)?;

// A credential this library just built: `digest_multibase()` is equivalent.
let digest = grant.digest_multibase()?;
```

That is the SHA-256 of the credential canonicalized with JCS (RFC 8785) and
**excluding its top-level `proof`**, wrapped in a `sha2-256` multihash and
encoded base58btc with a multibase `z` prefix — the encoding [VC Data Integrity
§2.6](https://www.w3.org/TR/vc-data-integrity/#resource-integrity) defines for
`digestMultibase`. Leaving `proof` out binds the digest to what the credential
says rather than to one signature over it, so a reference survives its referent
being re-signed, and the digest can be computed before signing.

> [!IMPORTANT]
> Digest what you **received**, not what you parsed, wherever you still hold the
> bytes. `DTGCommon` now models `credentialStatus` and preserves unmodelled
> top-level members through a round trip, so for most credentials the two agree —
> but a timestamp is normalized on the way out, and
> `2026-01-06T10:00:00.000+00:00` hashes differently from the
> `2026-01-06T10:00:00Z` this library re-emits. `digest_multibase()` is safe for a
> credential built in-process; anything that arrived from elsewhere goes through
> `digest_multibase_json()`.

`verify_digest()` checks that a credential's digest matches the one it names:

```Rust
if vwc.verify_digest(&vrc)? {
  println!("this VWC attests that VRC");
}
```

It compares **decoded bytes**, not strings — the specification requires it,
because one digest has more than one spelling. `digests_match()` and
`decode_digest_multibase()` are exposed for callers doing the comparison
themselves.

For a membership pair, prefer `acknowledges()` — it checks the digest *and* that
the two halves are of the right types and name the same parties in mirrored
roles. See [Membership edges](#membership-edges). `accepts()` is its counterpart
for a delegation edge.

> [!NOTE]
> `digest()` and `digest_json()` are deprecated. They emit the Working Draft 01
> `sha256:<lowercase hex>` form, which Working Draft 02 replaced. They are kept
> so a caller migrating can recompute an old digest to compare against one they
> stored; new code uses `digest_multibase()` / `digest_multibase_json()`.
>
> On the wire, `digestMultibase` is the only name accepted; the Working Draft 01
> name `digest` is no longer read. A `sha256:<hex>` *value* under the current name
> parses and then fails to compare, with `InvalidDigest` rather than a silent
> mismatch.

## Membership edges

Membership is a **pair** of VMCs, not a single directed credential:

| | `issuer` | `issuerScope` | `credentialSubject.id` | `digestMultibase` |
| --- | --- | --- | --- | --- |
| **Community-issued** (the grant) | community | `public`, always | member | MUST be absent |
| **Member-issued** (the acknowledgement) | member | the member's choice | community | MUST be present |

The member-issued half is the member's *consent artifact*. A community can
always issue a credential naming somebody as a member; what it cannot do is
produce the acknowledgement, because that needs the member's signature. So an
unconsented membership claim is unprovable — a community that cannot show the
acknowledgement is visibly asserting a membership nobody agreed to.

```Rust
// Community side: grant membership.
let grant = DTGCredential::new_vmc(
  community_did, member_did, valid_from, valid_until, personhood,
).with_id(format!("urn:uuid:{}", Uuid::new_v4()));
grant.sign(&community_key, None).await?;

// Member side: verify the grant before answering it. `grant_json` is the JSON the
// community sent — the wire form, not a parse of it — and the key is resolved
// from the community's DID document.
verify_grant_with_public_key(&grant_json, &community_public_key, Utc::now())?;

// Then acknowledge it, as yourself. The parties are read off the grant, so the
// two halves cannot disagree about who they are between, and a grant naming
// anyone but `member_did` is refused.
let mut ack = DTGCredential::new_member_vmc_for(
  &grant_json, &member_did, IssuerScope::Directed, Utc::now(), valid_until,
)?
  .with_id(format!("urn:uuid:{}", Uuid::new_v4()));
ack.sign(&member_key, None).await?;

// Either side: is this edge complete?
assert!(ack.acknowledges(&grant)?);
```

`acknowledges()` checks the binding — types, mirrored parties, and the digest.
It deliberately does **not** check either credential's proof or validity window:
proof verification needs a resolver this crate does not hold, and whether a
window is current is a question about an instant the caller chooses. An edge is
complete when both halves are valid *and* bound; this covers the binding.

Building the acknowledgement checks the binding too, and does not ask who signed
the grant. What `new_member_vmc_for()` does check is that the grant names the
member you pass — so pass the identity whose key you hold, never one read out of
the grant — and that the acknowledgement does not outlive the grant.
`verify_grant_with_public_key()` (feature `affinidi-signing`) covers the rest
before you answer: the proof, that the proof's verification method belongs to
the grant's issuer, and that the grant is in force.

Because the digest covers the grant's claims, a **re-issued** grant carries a
different digest and the earlier acknowledgement no longer matches it. Renewal
therefore forces re-acknowledgement rather than letting a stale consent carry
over to a membership the member never agreed to.

## Authority (VAC)

A VAC states what a party **may do** within a scope some node governs. Its holder
can narrow it without involving the governing party — which is what lets a member
equip an agent with four hours of read-only access instead of lending it their own
standing authority.

```Rust
// The governing party grants Bob read+write+curate for a month.
let root = DTGCredential::new_vac(
  room_did, IssuerScope::Public, bob_did, room_did.clone(),
  vec!["read".into(), "write".into(), "curate".into()],
  now, now + Duration::days(30),   // validUntil is REQUIRED on a VAC
)?;

// Bob equips his agent with strictly less, bound to that agent, and forbids the
// agent attenuating it any further.
let agent = root.attenuate(
  IssuerScope::Directed, agent_did, vec!["read".into()],
  now, now + Duration::hours(4),
  Some(0),                         // maxAttenuation
)?;
```

`attenuate()` refuses anything that would widen, but **the verifier's check is the
authoritative one** — nothing stops another implementation building the JSON by
hand. `authority::verify_chain` is where the security of this credential lives:

```Rust
let permitted = verify_chain(
  &[agent, root],   // leaf first; the holder presents every link
  room_did, room_did, "read", agent_did, Utc::now(),
)?;
```

Anyone can mint a well-formed VAC naming any scope and any actions, and it will
verify perfectly as a *credential*. What makes it worthless is that its chain does
not reach the party governing the scope. A verifier that checks only the credential
it was handed has verified nothing.

`parent` is a **digest**, not an identifier. So there is nothing a verifier could be
induced to fetch, verification never depends on network availability, and a link
binds to the exact claims its issuer narrowed from — re-issuing a parent with
different claims orphans its children, while re-proofing it leaves them alone.
For a VAC that arrived from a counterparty, use `attenuate_from_json()` and give it
the bytes you received.

**A VAC is not a bearer credential.** `verify_chain()` takes the presenter and requires
the leaf to grant to it, so a captured presentation is worthless to whoever captured it.
Pass an identifier whose key control you have already established for *this* request — the
DID a transport authenticated, or one a signature over the request proved — never one read
out of the request body.

That rule is why there is no `audience`. Equipping an agent means naming the agent in
`subject`; a second field naming who may present could then only repeat the subject or
contradict it. Where a presentation may be *sent* is a different question, and it belongs
to the trust task carrying it rather than to the credential.

`authority.maxAttenuation` bounds how far a chain may extend below the VAC carrying
it; `0` forbids attenuation outright, and absence permits it (the opposite default from
a VDC's `maxDepth`). Set it on a root with `with_max_attenuation(n)`; `attenuate()` takes
the child's and refuses one above what the parent permits. `verify_chain` enforces both
the per-link rule and the per-ancestor depth, alongside the global `MAX_CHAIN_DEPTH`.

### Roles are community-issued VACs

A role conferred by a community — the vetter role, say — is authority, not reputation,
so it is a VAC the community issues: `scope` the community's own DID, `actions` the
`role:<name>` convention.

```Rust
let vetter = DTGCredential::new_community_role_vac(
  community_did.clone(), member_did.clone(), "vetter", now, now + Duration::days(90),
)?;   // issuerScope "public"; authority { scope: community_did, actions: ["role:vetter"] }

verify_chain(&[vetter], &community_did, &community_did, "role:vetter", &member_did, now)?;
```

`actions` stays a plain string set: a member holding several roles holds several such
VACs, or one `new_vac` listing each `role_action(name)`.

> [!NOTE]
> Revocation via `credentialStatus` is modelled but not resolved: check it on every link
> that carries one.

## Delegation (VDC)

A VDC establishes that one party may act **in another's name**. It is not authority,
and the distinction decides which credential to reach for: ask whose name the act is
performed in. The actor's own — that is a VAC. Another entity's — that is a VDC.

Like membership, a delegation is a **pair**:

| | `issuer` | `credentialSubject.id` | carries |
| --- | --- | --- | --- |
| **Grant** | delegator | delegate | `scope`, optionally `maxDepth` |
| **Acceptance** | delegate | delegator | `accepts` only |

```Rust
// Alice appoints her agent, permitting one further hop.
let grant = DTGCredential::new_vdc(
  alice_did, IssuerScope::Directed, agent_did, now, now + Duration::days(90),
  vec!["schedule:read".into(), "schedule:propose".into()],
  Some(1),                          // maxDepth; None or 0 prohibits re-delegation
)?;

// The agent verifies the grant, then accepts it as itself. `grant_json` is the
// wire form, not a parse of it.
verify_grant_with_public_key(&grant_json, &alice_public_key, now)?;
let acceptance = DTGCredential::new_delegate_vdc_for(
  &grant_json, &agent_did, IssuerScope::Directed, now, valid_until,
)?;
assert!(acceptance.accepts(&grant)?);
```

The acceptance is **required**. A grant alone establishes what the delegator
appointed, not what the delegate agreed to — and a delegator cannot produce the
countersignature. It is also why a party holding only the delegate's key cannot
manufacture new appointments.

Re-delegation is **opt-in**, the opposite default from a VAC's attenuation. A
delegate speaks in the principal's name, so the principal keeps the register of who
may do that; a delegate needing a further delegate ordinarily asks for a fresh root
delegation rather than minting one.

```Rust
let sub = grant.redelegate(IssuerScope::Directed, subagent_did, vec!["schedule:read".into()], now, until)?;

let appointed = delegation::verify_chain(&[sub, grant], alice_did, "schedule:read", Utc::now())?;
assert_eq!(appointed.principal, alice_did);   // the acts are attributed to Alice
```

### A VDC moves the permission question; it does not answer it

`verify_chain` tells you the chain appoints this delegate to act in the principal's
name for this act. That is one of two checks. The other — *may the principal do this
thing?* — is yours to make, against whatever the act requires of them: membership, a
governance framework, an IDVC, a VAC. This crate does not answer it, and a VDC never
influences its outcome.

The reach of a delegated act is the **intersection** of what the principal may do
and what the chain appoints for. Two consequences worth stating: nothing the
delegator holds is copied to the delegate, and withdrawing the delegator's own
permission stops every delegate at once, without revoking a single VDC.

### A VDC is not a bearer credential

`verify_chain` takes a `presenter` and requires the leaf to appoint it, refusing
otherwise with `NotTheDelegate`. That is Working Draft 02's **Invocation Binding**
rule, and it is the same rule the VAC carries — sharper here, if anything: a captured
VAC replays whatever it confers, while a captured VDC replays *as somebody*, and
every act it carries is attributed to the principal.

Pass the identifier of a party whose key control you have already established for
**this request** — the DID a transport authenticated, or one a signature over the
request proved. An identifier read out of the request body reduces the check to a
string comparison an attacker chooses both sides of.

Only the leaf's delegate is asked for anything. The parties above it in the chain are
not present, which is what keeps re-delegation working.

Not implemented here: revocation — `credentialStatus` is modelled and settable, but
never resolved.

## Upgrading

**Upgrade verifiers before issuers.** Both directions of a version skew are errors,
but only one of them says so clearly.

A new credential reaching an old verifier is the confusing direction. 0.7 changed
`authority.parent` and `delegation.parent` from an `id` to a `digestMultibase`, so a
0.6 verifier compares a digest against an `id`, finds them unequal, and reports a
broken chain:

```
chain link 0 names parent `zQmPvoSXm7pYriaeeE3DRWVybmhYDkMt1UtNrxiRdFfRcrT`,
but was presented after `urn:uuid:064710ef-90ab-4013-9f95-f224af758754`
```

Both values are printed and nothing says they are different *kinds* of identifier, so
it reads exactly like a tampered or interleaved chain. It is not: it is a 0.6 verifier
being handed a 0.7 credential. Old verifiers cannot be taught to say this — the fix is
ordering.

The other direction is safe and loud. An old credential reaching a new verifier fails
with `InvalidDigest`, which names the Working Draft 01 `sha256:<hex>` form explicitly
rather than reporting it as a mismatch.

Since clients commonly upgrade ahead of the services they talk to, that ordering is
worth stating for each breaking release:

| Release | What changed on the wire or at the boundary | Ordering |
| --- | --- | --- |
| 0.7.0 | `parent` became a `digestMultibase`; `digest` → `digestMultibase` | Verifiers first |
| 0.8.0 | `authority::verify_chain` requires the leaf to grant to `presenter`; `audience` removed | Verifiers first |
| 0.9.1 | `delegation::verify_chain` requires the leaf to appoint `presenter` | Verifiers first |
| 0.10.0 (first published in 0.11.0) | Validity-window and JSON-depth checks at issue and verify; `DTGCredentialError` is `#[non_exhaustive]` | Verifiers first |
| 0.11.0 | `taskDigestMultibase` added; `DTGCommon` gains a field; `new_vwc` deprecated | Any order |
| 0.12.0 | v1 context IRI; `issuerScope` REQUIRED; `StatementCredential` replaces VEC/VWC; `maxAttenuation` | **Both at once** — see below |

Every one through 0.10.0 is *verifiers first*, and for the same reason: each made a
verifier stricter or changed what it reads, so a verifier that moves first accepts
everything it did before and is ready for what issuers send next. 0.11.0 has no ordering:
an older release carries `taskDigestMultibase` through a round trip in `DTGCommon::extra`,
and nothing changes on the wire for a credential without it. 0.10.0 was never published
to crates.io, so a consumer on 0.9.x takes 0.10.0 and 0.11.0 together, and verifiers
first still applies.

**0.12.0 cannot be ordered.** It is the first release on the specification's frozen v1
context, and the change is a clean break by design: a 0.12 verifier refuses every
credential a 0.11 issuer emits (pre-v1 context, no `issuerScope`, retired types), and a
0.11 verifier refuses every credential a 0.12 issuer emits (unknown context, unknown
`StatementCredential`). Credentials issued before the Implementers Draft are not
conformant, so there is no compatibility mode to stage through. Upgrade the issuers and
verifiers of one deployment together, and re-issue the credentials they hold: grants,
acknowledgements, VACs and VDCs alike, since every digest changes with the new members.

`0.8.0` and `0.9.1` are API breaks rather than wire changes — no credential changes
shape — but they land in the same place: a caller that upgrades gets a compile error
naming the new parameter, which is the intended way to find out.

`0.10.0` breaks the API in a smaller way: `DTGCredentialError` becomes
`#[non_exhaustive]`, so an exhaustive `match` on it needs a wildcard arm. It also refuses
more, on both sides. Every constructor that returns a `Result`, and `sign()`, refuse a
validity window that closes before it opens and JSON nested past `MAX_JSON_DEPTH`;
`verify_proof_with_public_key()` refuses the same before it looks at a proof. A conforming
issuer emits neither, so verifiers-first still holds. `new_member_vmc()` and
`new_delegate_vdc()` are deprecated rather than removed: they still compile, and a build
with `-D warnings` names the `_for` replacement.

## End to End Example

An end-to-end example of creating, signing and verifying a DTG Credential exists
in `examples`

```bash
cargo run --example sign_and_verify
```

## Creating credentials

Each credential type has it's own `new_*()` function to create a new credential
of that type.

Example:

```Rust
let vpc = DTGCredential::new_vpc(issuer, IssuerScope::Directed, subject, valid_from, valid_to);
```

The created `DTGCredential` can be serialized to JSON using `serde_json` allowing
it to be passed into various signing libraries

## Credential identifiers

A credential may carry its own top-level `id` — the OPTIONAL identifier of the
W3C VC Data Model, distinct from `credentialSubject.id`, which names the
*subject*. When present it MUST be a single URL; `urn:uuid:<uuid>` is the usual
choice for a credential with no dereferenceable home.

The `new_*()` constructors leave it unset. Chain `with_id()` to add one:

```Rust
let vmc = DTGCredential::new_vmc(issuer, subject, valid_from, valid_to, false)
  .with_id(format!("urn:uuid:{}", Uuid::new_v4()));

assert_eq!(vmc.id(), Some(...));
```

Issue with an `id` unless you know no counterparty needs one. It is the handle a
holder or verifier stores the credential *under*, so it is what makes
re-delivery of the same credential idempotent, and re-issuance of a different
one recognisable as a renewal rather than a duplicate. A verifier that keys
credentials by `id` has no way to accept one that has none.

> [!IMPORTANT]
> Set the `id` **before** signing. A Data Integrity proof covers the credential
> minus its `proof`, so the identifier is part of what is signed. Splicing one
> into the JSON after `sign()` produces a document whose proof no longer
> verifies.

## Revocation status

A credential may carry `credentialStatus`, the W3C VC mechanism through which a
verifier determines whether it has been revoked. The entry is opaque here: the
mechanism is chosen by the governing VTC or VTN, and this library neither
selects one nor resolves it. `BitstringStatusListEntry` is the common choice.

The `new_*()` constructors leave it unset. Chain `with_credential_status()`:

```Rust
let vdc = DTGCredential::new_vdc(delegator, IssuerScope::Directed, delegate, valid_from, valid_to, scope, None)?
  .with_credential_status(json!({
      "id": "https://example.com/status/3#94567",
      "type": "BitstringStatusListEntry",
      "statusPurpose": "revocation",
      "statusListIndex": "94567",
      "statusListCredential": "https://example.com/status/3"
  }));
```

On a VDC this is CONDITIONAL, not required. A verifier MUST be able to establish
that an appointment is currently in force without contacting the delegator, and
two things satisfy that: a `validUntil` short enough that expiry alone bounds the
exposure, with the delegator withdrawing by declining to re-issue; or a status
entry the verifier can check. A VDC MUST carry one where its validity period
exceeds the freshness window the governing VTC or VTN defines for delegations,
and MAY omit it otherwise.

That window is governance this library does not know, which is why this is a
setter rather than a constructor parameter — nothing here can tell which side of
the condition a given VDC falls on. Prefer short validity and re-issuance
wherever the delegator is reachable: a status check is a live lookup that reveals
the verification event to whoever hosts the status list. A long-lived appointment
made in advance of a delegator's unavailability is the case status exists for.

> [!IMPORTANT]
> Set it **before** signing, for the same reason as `id`.

> [!NOTE]
> Neither `delegation::verify_chain` nor `authority::verify_chain` resolves a
> status entry — both verify structure, scope and validity only. Revocation is a
> live lookup you perform.

## Signing credentials

By default the `affinidi-signing` feature is enabled which allows you to sign a
credential

```Rust
let mut vpc = DTGCredential::new_vpc(issuer, IssuerScope::Directed, subject, valid_from, valid_to);

vpc.sign(&signing_key, None).await?;
```

### Verifying credentials

There are two ways to validate a credential:

**Method 1:** If you have the public key bytes that correspond to the signing
key, then you can directly verify the credential:

```Rust
let signing_key = Secret::generate_ed25519(None, None);
let mut vpc = DTGCredential::new_vpc(issuer, IssuerScope::Directed, subject, valid_from, valid_to);

vpc.sign(&signing_key, None).await?;

vpc.verify_proof_with_public_key(signing_key.get_public_bytes())?;
```

**Method 2:** If you do not have the public key material, you are likely going to
need to resolve the DID VerificationMethod and derive the public key bytes used
when creating the credential.

```Rust
let mut credential = serde_json::from_str(<raw_credential_string>);

// Get the proof
let proof = if let Some(proof) = &credential.credential().proof {
  proof.clone()
} else {
    bail!("credential is not signed!");
};

// Strip proof from the credential
let unsigned = DTGCommon {
  proof: None,
  ..credential.credential().clone()
};

tdk.verify_data(&unsigned, None, &proof).await?;
```

## Common functions

You can deal with the raw credential as required.

```Rust
let vrc = DTGCredential::new_vrc(issuer, IssuerScope::Pairwise, subject, valid_from, valid_to);

let credential = vrc.credential();
```

You can determine the credential type easily using:

```Rust
let vmc = DTGCredential::new_vmc(issuer, subject, valid_from, valid_to, false);

if vmc.type_() == DTGCredentialType::Membership {
  // Good
}
```

Has this Credential been signed?

```Rust
let vmc = DTGCredential::new_vmc(issuer, subject, valid_from, valid_to, false);

if vmc.signed() {
  println!("Credential has been signed");
} else {
  println!("Credential has not been signed");
}
```