-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathdid.rs
1518 lines (1406 loc) · 57.7 KB
/
did.rs
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
//! # Decentralized Identifiers (DIDs)
//!
//! As specified by [Decentralized Identifiers (DIDs) v1.0 - Core architecture, data model, and representations][did-core].
//!
//! [did-core]: https://www.w3.org/TR/did-core/
use crate::caip10::BlockchainAccountId;
use std::collections::BTreeMap as Map;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;
use thiserror::Error;
use crate::did_resolve::{
Content, ContentMetadata, DIDResolver, DereferencingInputMetadata, DereferencingMetadata,
DocumentMetadata, ResolutionInputMetadata, ResolutionMetadata, ERROR_INVALID_DID,
ERROR_METHOD_NOT_SUPPORTED, TYPE_DID_LD_JSON,
};
use crate::error::Error;
use crate::jwk::JWK;
use crate::one_or_many::OneOrMany;
/// A [verification relationship](https://w3c.github.io/did-core/#dfn-verification-relationship).
///
/// The relationship between a [verification method][VerificationMethod] and a DID
/// Subject (as described by a [DID Document][Document]) is considered analogous to a [proof
/// purpose](crate::vc::ProofPurpose).
pub type VerificationRelationship = crate::vc::ProofPurpose;
use async_trait::async_trait;
use chrono::prelude::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
// ***********************************************
// * Data Structures for Decentralized Identifiers
// * W3C Working Draft 29 May 2020
// * Accessed July 3, 2019
// * https://w3c.github.io/did-core/
// ***********************************************
// @TODO `id` must be URI
/// URI [required](https://www.w3.org/TR/did-core/#production-0) as the first value of the `@context` property for a DID Document in JSON-LD representation.
pub const DEFAULT_CONTEXT: &str = "https://www.w3.org/ns/did/v1";
/// Aliases for the [default required DID document context URI][DEFAULT_CONTEXT]. Allowed for compatibility reasons. [DEFAULT_CONTEXT][] should be used instead.
pub const DEFAULT_CONTEXT_NO_WWW: &str = crate::jsonld::DID_V1_CONTEXT_NO_WWW;
pub const ALT_DEFAULT_CONTEXT: &str = crate::jsonld::W3ID_DID_V1_CONTEXT;
/// DID Core v0.11 context URI. Allowed for legacy
/// reasons. The [v1.0 context URI][DEFAULT_CONTEXT] should be used instead.
pub const V0_11_CONTEXT: &str = "https://w3id.org/did/v0.11";
const MULTICODEC_ED25519_PREFIX: [u8; 2] = [0xed, 0x01];
// @TODO parsed data structs for DID and DIDURL
#[allow(clippy::upper_case_acronyms)]
type DID = String;
/// A [DID URL](https://w3c.github.io/did-core/#did-url-syntax).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct DIDURL {
/// [DID](https://www.w3.org/TR/did-core/#did-syntax).
pub did: String,
/// [DID path](https://www.w3.org/TR/did-core/#path). `path-abempty` component from
/// [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.3).
pub path_abempty: String,
/// [DID query](https://www.w3.org/TR/did-core/#query). `query` component from
/// [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.3).
pub query: Option<String>,
/// [DID fragment](https://www.w3.org/TR/did-core/#fragment). `fragment` component from
/// [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.3).
pub fragment: Option<String>,
}
/// Path component for a [Relative DID URL](https://w3c.github.io/did-core/#relative-did-urls).
///
/// `relative-part` from [RFC 3986 - 4.2 Relative
/// Reference](https://www.rfc-editor.org/rfc/rfc3986#section-4.2), excluding network-path references.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum RelativeDIDURLPath {
/// Absolute-path reference. `path-absolute` from [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.3)
Absolute(String),
/// Relative-path reference. `path-noscheme` from [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.3)
NoScheme(String),
/// Empty path. `path-empty` from [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.3)
Empty,
}
/// A [Relative DID URL](https://www.w3.org/TR/did-core/#relative-did-urls).
///
/// A kind of [relative reference (RFC 3986)](https://www.rfc-editor.org/rfc/rfc3986#section-4.2)
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct RelativeDIDURL {
/// Path component of a Relative DID URL.
pub path: RelativeDIDURLPath,
/// [DID query](https://www.w3.org/TR/did-core/#query) ([RFC 3986 - 3.4. Query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4))
pub query: Option<String>,
/// [DID fragment](https://www.w3.org/TR/did-core/#fragment) ([RFC 3986 - 3.5. Fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5))
pub fragment: Option<String>,
}
/// A [DID URL][DIDURL] without a fragment. Used for [Dereferencing the Primary
/// Resource](https://w3c-ccg.github.io/did-resolution/#dereferencing-algorithm-primary) in [DID URL Dereferencing][crate::did_resolve::dereference].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct PrimaryDIDURL {
/// [DID][DIDURL::did]
pub did: String,
/// [DID Path][DIDURL::path_abempty]
pub path: Option<String>,
/// [DID query][DIDURL::query]
pub query: Option<String>,
}
/// A [DID document]
///
/// [DID document]: https://www.w3.org/TR/did-core/#dfn-did-documents
#[derive(Debug, Serialize, Deserialize, Builder, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[builder(
setter(into, strip_option),
default,
build_fn(validate = "Self::validate")
)]
pub struct Document {
/// [`@context`](https://www.w3.org/TR/did-core/#dfn-context) property of a DID document.
#[serde(rename = "@context")]
pub context: Contexts,
/// [DID Subject id](https://www.w3.org/TR/did-core/#did-subject)
pub id: DID,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`alsoKnownAs`](https://www.w3.org/TR/did-core/#also-known-as) property of a DID document,
/// expressing other URIs for the DID subject.
pub also_known_as: Option<Vec<String>>, // TODO: URI
#[serde(skip_serializing_if = "Option::is_none")]
/// [`controller`](https://www.w3.org/TR/did-core/#dfn-controller) property of a DID document,
/// expressing [DID controllers(s)](https://www.w3.org/TR/did-core/#did-controller).
pub controller: Option<OneOrMany<DID>>,
/// [`verificationMethod`](https://www.w3.org/TR/did-core/#dfn-verificationmethod) property of a
/// DID document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods).
#[serde(skip_serializing_if = "Option::is_none")]
pub verification_method: Option<Vec<VerificationMethod>>,
/// [`authentication`](https://www.w3.org/TR/did-core/#dfn-authentication) property of a DID
/// document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods) for
/// [authentication](https://www.w3.org/TR/did-core/#authentication) purposes (e.g. generating [verifiable
/// presentations][crate::vc::Presentation]).
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`assertionMethod`](https://www.w3.org/TR/did-core/#dfn-assertionmethod) property of a DID document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods) for
/// [assertion](https://www.w3.org/TR/did-core/#assertion) purposes (e.g. issuing [verifiable
/// credentials](crate::vc::Credential)).
pub assertion_method: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`keyAgreement`](https://www.w3.org/TR/did-core/#dfn-keyagreement) property of a DID document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods) for
/// [key agreement](https://www.w3.org/TR/did-core/#key-agreement) purposes.
pub key_agreement: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`capabilityInvocation`](https://www.w3.org/TR/did-core/#dfn-capabilityinvocation) property of a DID document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods) for
/// [invoking cryptographic capabilities](https://www.w3.org/TR/did-core/#capability-invocation).
pub capability_invocation: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`capabilityDelegation`](https://www.w3.org/TR/did-core/#dfn-capabilitydelegation) property of a DID document, expressing [verification
/// methods](https://www.w3.org/TR/did-core/#verification-methods) for
/// [delegating cryptographic capabilities](https://www.w3.org/TR/did-core/#capability-delegation).
pub capability_delegation: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// [`publicKey`](https://www.w3.org/TR/did-spec-registries/#publickey) property of a DID
/// document (deprecated in favor of `verificationMethod`).
pub public_key: Option<Vec<VerificationMethod>>,
#[serde(skip_serializing_if = "Option::is_none")]
/// `service` property of a DID document, expressing
/// [services](https://www.w3.org/TR/did-core/#services), generally as endpoints.
pub service: Option<Vec<Service>>,
/// [Linked data proof](https://w3c-ccg.github.io/ld-proofs/#linked-data-proof-overview) over a
/// DID document.
#[serde(skip_serializing_if = "Option::is_none")]
pub proof: Option<OneOrMany<Proof>>,
/// Additional properties of a DID document. Some may be registered in [DID Specification
/// Registries](https://www.w3.org/TR/did-spec-registries/#did-document-properties).
#[serde(flatten)]
pub property_set: Option<Map<String, Value>>,
}
/// [JSON-LD Context](https://www.w3.org/TR/json-ld11/#the-context) URI or map, for use in the
/// [`@context`](https://www.w3.org/TR/did-core/#dfn-context) property of a [DID
/// document][Document] in JSON-LD representation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum Context {
/// Context referenced by a URL.
URI(String),
/// [Embedded context](https://www.w3.org/TR/json-ld11/#dfn-embedded-context).
Object(Map<String, Value>),
}
/// [JSON-LD Context](https://www.w3.org/TR/json-ld11/#the-context) value or array of context
/// values, for use in the [`@context`](https://www.w3.org/TR/did-core/#dfn-context) property of a
/// DID document in JSON-LD representation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
#[serde(try_from = "OneOrMany<Context>")]
pub enum Contexts {
/// A single context value.
One(Context),
/// An array of context values.
Many(Vec<Context>),
}
/// A [Verification method](https://www.w3.org/TR/did-core/#verification-methods) map (object) in a DID
/// document.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct VerificationMethodMap {
/// [@context](https://www.w3.org/TR/did-core/#dfn-context) property of a verification method map. Used if the verification method map uses
/// some terms not defined in the containing DID document.
#[serde(rename = "@context")]
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<Value>,
/// id property ([DID URL][DIDURL]) of a verification method map.
pub id: String,
#[serde(rename = "type")]
/// type [property](https://www.w3.org/TR/did-core/#dfn-did-urls) of a verification method map.
/// Should be registered in [DID Specification
/// registries - Verification method types](https://www.w3.org/TR/did-spec-registries/#verification-method-types).
pub type_: String,
// Note: different than when the DID Document is the subject:
// The value of the controller property, which identifies the
// controller of the corresponding private key, MUST be a valid DID.
/// [controller](https://w3c-ccg.github.io/ld-proofs/#controller) property of a verification
/// method map.
///
/// Not to be confused with the [controller](https://www.w3.org/TR/did-core/#dfn-controller) property of a DID document.
pub controller: DID,
#[serde(skip_serializing_if = "Option::is_none")]
/// [publicKeyJwk](https://www.w3.org/TR/did-core/#dfn-publickeyjwk) property of a verification
/// method map, representing a [JSON Web Key][JWK].
// TODO: make sure this JWK does not have private key material
pub public_key_jwk: Option<JWK>,
#[serde(skip_serializing_if = "Option::is_none")]
pub public_key_pgp: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
// TODO: make Base58 type like Base64urlUIntString
/// [publicKeyBase58](https://www.w3.org/TR/did-spec-registries/#publickeybase58) property
/// (deprecated; [Security Vocab definition](https://w3c-ccg.github.io/security-vocab/#publicKeyBase58)) - encodes public key material in Base58.
pub public_key_base58: Option<String>,
// TODO: ensure that not both key parameters are set
#[serde(skip_serializing_if = "Option::is_none")]
/// [blockchainAccountId](https://www.w3.org/TR/did-spec-registries/#blockchainaccountid)
/// property ([Security Vocab definition](https://w3c-ccg.github.io/security-vocab/#blockchainAccountId)), encoding a [CAIP-10 Blockchain account id](crate::caip10::BlockchainAccountId).
pub blockchain_account_id: Option<String>,
/// Additional JSON properties.
#[serde(flatten)]
pub property_set: Option<Map<String, Value>>,
}
/// A [Verification method](https://www.w3.org/TR/did-core/#verification-methods) in a DID
/// document, embedded or referenced.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum VerificationMethod {
/// Verification method URL [including a verification method by reference](https://www.w3.org/TR/did-core/#referring-to-verification-methods).
DIDURL(DIDURL),
/// Verification method URL (relative reference), [including a verification method by reference](https://www.w3.org/TR/did-core/#referring-to-verification-methods).
RelativeDIDURL(RelativeDIDURL),
/// Embedded verification method.
Map(VerificationMethodMap),
}
/// Value for a [serviceEndpoint](https://www.w3.org/TR/did-core/#dfn-serviceendpoint) property of
/// a [service](https://www.w3.org/TR/did-core/#services) map in a DID document.
///
/// "The value of the serviceEndpoint property MUST be a string \[URI], a map, or a set composed of one or
/// more strings \[URIs] and/or maps."
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ServiceEndpoint {
URI(String),
Map(Value),
}
// <https://w3c.github.io/did-core/#service-properties>
/// A [service](https://www.w3.org/TR/did-core/#services) map (object) in a DID document.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Service {
/// id property (URI) of a service map.
pub id: String,
#[serde(rename = "type")]
pub type_: OneOrMany<String>, // TODO: set
/// [serviceEndpoint](https://www.w3.org/TR/did-core/#dfn-serviceendpoint) property of a
/// service map
#[serde(skip_serializing_if = "Option::is_none")]
pub service_endpoint: Option<OneOrMany<ServiceEndpoint>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(flatten)]
pub property_set: Option<Map<String, Value>>,
}
/// A [linked data proof](https://w3c-ccg.github.io/data-integrity-spec/#proofs) ([proof
/// object](https://www.w3.org/TR/vc-data-model/#proofs-signatures)) that may
/// be on a [DID document][Document].
///
/// See also the Verifiable Credential [Proof][crate::vc::Proof] type.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Proof {
/// Proof type.
///
/// May be registered in [Linked Data Cryptographic Suite
/// Registry](https://w3c-ccg.github.io/ld-cryptosuite-registry/).
#[serde(rename = "type")]
pub type_: String,
/// Additional properties.
///
/// See [Linked Data Proof Overview](hhttps://w3c-ccg.github.io/data-integrity-spec/#proofs) for more info about expected properties.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(flatten)]
pub property_set: Option<Map<String, Value>>,
}
/// An object from a [DID document][Document] returned by [DID URL
/// dereferencing][crate::did_resolve::dereference].
#[derive(Debug, Serialize, Clone, PartialEq)]
#[non_exhaustive]
#[serde(untagged)]
pub enum Resource {
/// Verification method map.
///
/// This results from dereferencing a [verification method DID
/// URL][VerificationMethod::DIDURL].
VerificationMethod(VerificationMethodMap),
/// An arbitrary object (map).
Object(Map<String, Value>),
}
/// Something that can be used to derive (generate) a DID.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Source<'a> {
/// A public key.
Key(&'a JWK),
/// A public key and additional pattern.
KeyAndPattern(&'a JWK, &'a str),
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
/// [DID Parameters](https://www.w3.org/TR/did-core/#did-parameters).
///
/// As specified in DID Core and/or in [DID Specification
/// Registries](https://www.w3.org/TR/did-spec-registries/#parameters).
pub struct DIDParameters {
#[serde(skip_serializing_if = "Option::is_none")]
pub service: Option<String>, // ASCII
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "relative-ref")]
/// [`relativeRef`](https://www.w3.org/TR/did-spec-registries/#relativeRef-param) parameter.
pub relative_ref: Option<String>, // ASCII, percent-encoding
/// [`versionId`](https://www.w3.org/TR/did-spec-registries/#versionId-param) parameter.
#[serde(skip_serializing_if = "Option::is_none")]
pub version_id: Option<String>, // ASCII
/// [`versionTime`](https://www.w3.org/TR/did-spec-registries/#versionTime-param) parameter.
#[serde(skip_serializing_if = "Option::is_none")]
pub version_time: Option<DateTime<Utc>>, // ASCII
/// [`hl`](https://www.w3.org/TR/did-spec-registries/#hl-param) parameter.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "hl")]
pub hashlink: Option<String>, // ASCII
/// Additional parameters.
#[serde(flatten)]
pub property_set: Option<Map<String, Value>>,
}
/// DID Create Operation
///
/// <https://identity.foundation/did-registration/#create>
pub struct DIDCreate {
pub update_key: Option<JWK>,
pub recovery_key: Option<JWK>,
pub verification_key: Option<JWK>,
pub options: Map<String, Value>,
}
/// DID Update Operation
///
/// <https://identity.foundation/did-registration/#update>
pub struct DIDUpdate {
pub did: String,
pub update_key: Option<JWK>,
pub new_update_key: Option<JWK>,
pub operation: DIDDocumentOperation,
pub options: Map<String, Value>,
}
/// DID Recover Operation
///
/// <https://www.w3.org/TR/did-core/#did-recovery>
pub struct DIDRecover {
pub did: String,
pub recovery_key: Option<JWK>,
pub new_update_key: Option<JWK>,
pub new_recovery_key: Option<JWK>,
pub new_verification_key: Option<JWK>,
pub options: Map<String, Value>,
}
/// DID Deactivate Operation
///
/// <https://identity.foundation/did-registration/#deactivate>
pub struct DIDDeactivate {
pub did: String,
pub key: Option<JWK>,
pub options: Map<String, Value>,
}
/// DID Document Operation
///
/// This should represent [didDocument][dd] and [didDocumentOperation][ddo] specified by DID
/// Registration.
///
/// [dd]: https://identity.foundation/did-registration/#diddocumentoperation
/// [ddo]: https://identity.foundation/did-registration/#diddocument
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "didDocumentOperation", content = "didDocument")]
#[serde(rename_all = "camelCase")]
pub enum DIDDocumentOperation {
/// Set the contents of the DID document
///
/// setDidDocument operation defined by DIF DID Registration
SetDidDocument(Document),
/// Add properties to the DID document
///
/// addToDidDocument operation defined by DIF DID Registration
AddToDidDocument(HashMap<String, Value>),
/// Remove properties from the DID document
///
/// removeFromDidDocument operation defined by DIF Registration
RemoveFromDidDocument(Vec<String>),
/// Add or update a verification method in the DID document
SetVerificationMethod {
vmm: VerificationMethodMap,
purposes: Vec<VerificationRelationship>,
},
/// Add or update a service map in the DID document
SetService(Service),
/// Remove a verification method in the DID document
RemoveVerificationMethod(DIDURL),
/// Add or update a service map in the DID document
RemoveService(DIDURL),
}
/// A transaction for a DID method
#[derive(Debug, Serialize, Deserialize, Builder, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DIDMethodTransaction {
/// DID method name
pub did_method: String,
/// Method-specific transaction data
#[serde(flatten)]
pub value: Value,
}
/// An error having to do with a [DIDMethod].
#[derive(Error, Debug)]
pub enum DIDMethodError {
#[error("Not implemented for DID method: {0}")]
NotImplemented(&'static str),
#[error("Option '{option}' not supported for DID operation '{operation}'")]
OptionNotSupported {
operation: &'static str,
option: String,
},
#[error(transparent)]
Other(#[from] anyhow::Error),
}
/// An implementation of a [DID method](https://www.w3.org/TR/did-core/#dfn-did-methods).
///
/// Depends on the [DIDResolver][] trait.
/// Also includes functionality to [generate][DIDMethod::generate] DIDs.
///
/// Some DID Methods are registered in the [DID Specification
/// Registries](https://www.w3.org/TR/did-spec-registries/#did-methods).
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait DIDMethod: Sync {
/// Get the DID method's name.
///
/// `method-name` in [DID Syntax](https://w3c.github.io/did-core/#did-syntax).
fn name(&self) -> &'static str;
// TODO: allow returning errors
/// Generate a DID from some source.
fn generate(&self, _source: &Source) -> Option<String> {
None
}
/// Retrieve a DID from a DID method transaction
fn did_from_transaction(&self, _tx: DIDMethodTransaction) -> Result<String, DIDMethodError> {
Err(DIDMethodError::NotImplemented("DID from transaction"))
}
/// Submit a DID transaction
async fn submit_transaction(&self, _tx: DIDMethodTransaction) -> Result<Value, DIDMethodError> {
Err(DIDMethodError::NotImplemented("Transaction submission"))
}
/// Create a DID
fn create(&self, _create: DIDCreate) -> Result<DIDMethodTransaction, DIDMethodError> {
Err(DIDMethodError::NotImplemented("Create operation"))
}
/// Update a DID
fn update(&self, _update: DIDUpdate) -> Result<DIDMethodTransaction, DIDMethodError> {
Err(DIDMethodError::NotImplemented("Update operation"))
}
/// Recover a DID
fn recover(&self, _recover: DIDRecover) -> Result<DIDMethodTransaction, DIDMethodError> {
Err(DIDMethodError::NotImplemented("Recover operation"))
}
/// Deactivate a DID
fn deactivate(
&self,
_deactivate: DIDDeactivate,
) -> Result<DIDMethodTransaction, DIDMethodError> {
Err(DIDMethodError::NotImplemented("Deactivate operation"))
}
/// Upcast the DID method as a DID resolver.
///
/// This is a workaround for [not being able to cast a trait object to a supertrait object](https://github.com/rust-lang/rfcs/issues/2765).
///
/// Implementations should simply return `self`.
fn to_resolver(&self) -> &dyn DIDResolver;
}
/// A collection of DID methods that can be used as a single [DID resolver][DIDResolver].
#[derive(Clone, Default)]
pub struct DIDMethods<'a> {
/// Collection of DID methods by method id.
pub methods: HashMap<&'a str, &'a dyn DIDMethod>,
}
impl<'a> DIDMethods<'a> {
/// Add a DID method to the set. Returns the previous one set for the given method name, if any.
pub fn insert(&mut self, method: &'a dyn DIDMethod) -> Option<&'a dyn DIDMethod> {
let name = method.name();
self.methods.insert(name, method)
}
/// Get a DID method from the set.
pub fn get(&self, method_name: &str) -> Option<&&'a dyn DIDMethod> {
self.methods.get(method_name)
}
/// Upcast the DID method to a [DID resolver instance][DIDResolver].
pub fn to_resolver(&self) -> &dyn DIDResolver {
self
}
/// Get DID method to handle a given DID.
pub fn get_method(&self, did: &str) -> Result<&&'a dyn DIDMethod, &'static str> {
let mut parts = did.split(':');
if parts.next() != Some("did") {
return Err(ERROR_INVALID_DID);
};
let method_name = match parts.next() {
Some(method_name) => method_name,
None => {
return Err(ERROR_INVALID_DID);
}
};
let method = match self.methods.get(method_name) {
Some(method) => method,
None => {
return Err(ERROR_METHOD_NOT_SUPPORTED);
}
};
Ok(method)
}
/// Generate a DID given some input.
pub fn generate(&self, source: &Source) -> Option<String> {
let (jwk, pattern) = match source {
Source::Key(_) => {
// Need name/pattern to select DID method
return None;
}
Source::KeyAndPattern(jwk, pattern) => (jwk, pattern),
};
let mut parts = pattern.splitn(2, ':');
let method_name = parts.next().unwrap();
let method = match self.methods.get(method_name) {
Some(method) => method,
None => return None,
};
if let Some(method_pattern) = parts.next() {
let source = Source::KeyAndPattern(jwk, method_pattern);
method.generate(&source)
} else {
let source = Source::Key(jwk);
method.generate(&source)
}
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<'a> DIDResolver for DIDMethods<'a> {
/// Resolve a DID using the corresponding DID method, using the corresponding DID method in the
/// [DIDMethods][] instance.
async fn resolve(
&self,
did: &str,
input_metadata: &ResolutionInputMetadata,
) -> (
ResolutionMetadata,
Option<Document>,
Option<DocumentMetadata>,
) {
let method = match self.get_method(did) {
Ok(method) => method,
Err(err) => return (ResolutionMetadata::from_error(err), None, None),
};
method.to_resolver().resolve(did, input_metadata).await
}
/// Resolve a DID to a DID document representation, using the corresponding DID method in the
/// [DIDMethods][] instance.
async fn resolve_representation(
&self,
did: &str,
input_metadata: &ResolutionInputMetadata,
) -> (ResolutionMetadata, Vec<u8>, Option<DocumentMetadata>) {
let method = match self.get_method(did) {
Ok(method) => method,
Err(err) => return (ResolutionMetadata::from_error(err), Vec::new(), None),
};
method
.to_resolver()
.resolve_representation(did, input_metadata)
.await
}
/// Dereference a DID URL, using the corresponding DID method in the
/// [DIDMethods][] instance.
async fn dereference(
&self,
did_url: &PrimaryDIDURL,
input_metadata: &DereferencingInputMetadata,
) -> Option<(DereferencingMetadata, Content, ContentMetadata)> {
let method = match self.get_method(&did_url.did) {
Ok(method) => method,
Err(err) => {
return Some((
DereferencingMetadata::from_error(err),
Content::Null,
ContentMetadata::default(),
))
}
};
method
.to_resolver()
.dereference(did_url, input_metadata)
.await
}
}
impl DIDURL {
/// Convert a DID URL to a [Relative DID URL][RelativeDIDURL], given a DID as base URI.
pub fn to_relative(&self, base_did: &str) -> Option<RelativeDIDURL> {
// TODO: support [Reference Resolution](https://tools.ietf.org/html/rfc3986#section-5) more
// generally, i.e. where the base is a DID URL (not necessarily a DID), and including [path
// segment normalization](https://tools.ietf.org/html/rfc3986#section-6.2.2.3)
if self.did != base_did {
return None;
}
Some(RelativeDIDURL {
path: match RelativeDIDURLPath::from_str(&self.path_abempty) {
Ok(path) => path,
Err(_) => return None,
},
query: self.query.as_ref().cloned(),
fragment: self.fragment.as_ref().cloned(),
})
}
/// Convert to a fragment-less DID URL and return the removed fragment.
///
/// The DID URL can be reconstructed using [PrimaryDIDURL::with_fragment].
pub fn remove_fragment(self) -> (PrimaryDIDURL, Option<String>) {
(
PrimaryDIDURL {
did: self.did,
path: if !self.path_abempty.is_empty() {
Some(self.path_abempty)
} else {
None
},
query: self.query,
},
self.fragment,
)
}
}
impl RelativeDIDURL {
/// Convert a DID URL to a absolute DID URL, given a DID as base URI,
/// according to [DID Core - Relative DID URLs](https://w3c.github.io/did-core/#relative-did-urls).
pub fn to_absolute(&self, base_did: &str) -> DIDURL {
// TODO: support [Reference Resolution](https://tools.ietf.org/html/rfc3986#section-5) more
// generally, e.g. when base is not a DID
DIDURL {
did: base_did.to_string(),
path_abempty: self.path.to_string(),
query: self.query.as_ref().cloned(),
fragment: self.fragment.as_ref().cloned(),
}
}
}
impl PrimaryDIDURL {
/// Append a [fragment](https://www.w3.org/TR/did-core/#fragment) to construct a DID URL.
///
/// The opposite of [DIDURL::remove_fragment].
pub fn with_fragment(self, fragment: String) -> DIDURL {
DIDURL {
fragment: Some(fragment),
..DIDURL::from(self)
}
}
}
impl VerificationMethod {
/// Return a DID URL for this verification method, given a DID as base URI.
pub fn get_id(&self, did: &str) -> String {
match self {
Self::DIDURL(didurl) => didurl.to_string(),
Self::RelativeDIDURL(relative_did_url) => relative_did_url.to_absolute(did).to_string(),
Self::Map(map) => map.get_id(did),
}
}
}
impl VerificationMethodMap {
/// Return a DID URL for this verification method, given a DID as base URI
pub fn get_id(&self, did: &str) -> String {
if let Ok(rel_did_url) = RelativeDIDURL::from_str(&self.id) {
rel_did_url.to_absolute(did).to_string()
} else {
self.id.to_string()
}
}
/// Get the verification material as a JWK, from the publicKeyJwk property, or converting from other
/// public key properties as needed.
pub fn get_jwk(&self) -> Result<JWK, Error> {
let pk_hex_value = self
.property_set
.as_ref()
.and_then(|cc| cc.get("publicKeyHex"));
let pk_multibase_opt = match self.property_set {
Some(ref props) => match props.get("publicKeyMultibase") {
Some(Value::String(string)) => Some(string.clone()),
Some(Value::Null) => None,
Some(_) => return Err(Error::ExpectedStringPublicKeyMultibase),
None => None,
},
None => None,
};
let pk_bytes = match (
self.public_key_jwk.as_ref(),
self.public_key_base58.as_ref(),
pk_hex_value,
pk_multibase_opt,
) {
(Some(pk_jwk), None, None, None) => return Ok(pk_jwk.clone()),
(None, Some(pk_bs58), None, None) => bs58::decode(&pk_bs58).into_vec()?,
(None, None, Some(pk_hex), None) => {
let pk_hex = match pk_hex {
Value::String(string) => string,
_ => return Err(Error::HexString),
};
let pk_hex = pk_hex.strip_prefix("0x").unwrap_or(pk_hex);
hex::decode(pk_hex)?
}
(None, None, None, Some(pk_mb)) => multibase::decode(pk_mb)?.1,
(None, None, None, None) => return Err(Error::MissingKey),
_ => {
// https://w3c.github.io/did-core/#verification-material
// "expressing key material in a verification method using both publicKeyJwk and
// publicKeyBase58 at the same time is prohibited."
return Err(Error::MultipleKeyMaterial);
}
};
let params = match &self.type_[..] {
// TODO: check against IRIs when in JSON-LD
"Ed25519VerificationKey2018" => crate::jwk::Params::OKP(crate::jwk::OctetParams {
curve: "Ed25519".to_string(),
public_key: crate::jwk::Base64urlUInt(pk_bytes),
private_key: None,
}),
"Ed25519VerificationKey2020" => {
if pk_bytes.len() != 34 {
return Err(Error::MultibaseKeyLength(34, pk_bytes.len()));
}
if &pk_bytes[0..2] != MULTICODEC_ED25519_PREFIX {
return Err(Error::MultibaseKeyPrefix);
}
crate::jwk::Params::OKP(crate::jwk::OctetParams {
curve: "Ed25519".to_string(),
public_key: crate::jwk::Base64urlUInt(pk_bytes[2..].to_owned()),
private_key: None,
})
}
#[cfg(feature = "k256")]
"EcdsaSecp256k1VerificationKey2019" | "EcdsaSecp256k1RecoveryMethod2020" => {
use crate::jwk::secp256k1_parse;
return secp256k1_parse(&pk_bytes).map_err(Error::Secp256k1Parse);
}
_ => return Err(Error::UnsupportedKeyType),
};
Ok(JWK::from(params))
}
/// Verify that a given JWK can be used to satisfy this verification method.
pub fn match_jwk(&self, jwk: &JWK) -> Result<(), Error> {
if let Some(ref account_id) = self.blockchain_account_id {
let account_id = BlockchainAccountId::from_str(account_id)?;
account_id.verify(jwk)?;
} else {
let resolved_jwk = self.get_jwk()?;
if !resolved_jwk.equals_public(jwk) {
return Err(Error::KeyMismatch);
}
}
Ok(())
}
}
/// Parse a DID URL.
impl FromStr for DIDURL {
type Err = Error;
fn from_str(didurl: &str) -> Result<Self, Self::Err> {
let mut parts = didurl.splitn(2, '#');
let before_fragment = parts.next().unwrap().to_string();
let fragment = parts.next().map(|x| x.to_owned());
let primary_did_url = PrimaryDIDURL::try_from(before_fragment)?;
Ok(Self {
fragment,
..DIDURL::from(primary_did_url)
})
}
}
/// Parse a primary DID URL.
impl FromStr for PrimaryDIDURL {
type Err = Error;
fn from_str(didurl: &str) -> Result<Self, Self::Err> {
// Allow non-DID URL for testing lds-ed25519-2020-issuer0
#[cfg(not(test))]
if !didurl.starts_with("did:") {
return Err(Error::DIDURL);
}
if didurl.contains('#') {
return Err(Error::UnexpectedDIDFragment);
}
let mut parts = didurl.splitn(2, '?');
let before_query = parts.next().unwrap();
let query = parts.next().map(|x| x.to_owned());
let (did, path) = match before_query.find('/') {
Some(i) => {
let (did, path) = before_query.split_at(i);
(did.to_string(), Some(path.to_string()))
}
None => (before_query.to_string(), None),
};
Ok(Self { did, path, query })
}
}
/// Parse a relative DID URL.
impl FromStr for RelativeDIDURL {
type Err = Error;
fn from_str(didurl: &str) -> Result<Self, Self::Err> {
let mut parts = didurl.splitn(2, '#');
let before_fragment = parts.next().unwrap().to_string();
let fragment = parts.next().map(|x| x.to_owned());
let mut parts = before_fragment.splitn(2, '?');
let before_query = parts.next().unwrap().to_string();
let query = parts.next().map(|x| x.to_owned());
let path = RelativeDIDURLPath::from_str(&before_query)?;
Ok(Self {
path,
query,
fragment,
})
}
}
/// Parse a relative DID URL path.
impl FromStr for RelativeDIDURLPath {
type Err = Error;
fn from_str(path: &str) -> Result<Self, Self::Err> {
if path.is_empty() {
return Ok(Self::Empty);
}
if path.starts_with('/') {
// path-absolute = "/" [ segment-nz *( "/" segment ) ]
// segment-nz = 1*pchar
// segment = *pchar
if path.len() >= 2 && path.chars().nth(1) == Some('/') {
// Beginning with "//" would make a scheme-relative URI.
return Err(Error::DIDURL);
}
// TODO: validate segment and pchar
Ok(Self::Absolute(path.to_string()))
} else {
// path-noscheme = segment-nz-nc *( "/" segment )
// segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
let first_segment = path.splitn(2, '/').next().unwrap().to_string();
if first_segment.contains(':') {
// First path segment containing ":" would make an absolute URI.
return Err(Error::DIDURL);
}
// TODO: validate segment-nz-nc and pchar more
Ok(Self::NoScheme(path.to_string()))
}
}
}
/// Serialize a DID URL.
impl fmt::Display for DIDURL {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{}", self.did, self.path_abempty)?;
if let Some(ref query) = self.query {
write!(f, "?{}", query)?;
}
if let Some(ref fragment) = self.fragment {
write!(f, "#{}", fragment)?;
}
Ok(())
}
}
/// Serialize a relative DID URL.
impl fmt::Display for RelativeDIDURL {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.path.fmt(f)?;
if let Some(ref query) = self.query {
write!(f, "?{}", query)?;
}
if let Some(ref fragment) = self.fragment {
write!(f, "#{}", fragment)?;
}
Ok(())
}
}
/// Serialize a relative DID URL path.
impl fmt::Display for RelativeDIDURLPath {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Empty => Ok(()),
Self::Absolute(string) => string.fmt(f),
Self::NoScheme(string) => string.fmt(f),
}
}
}
/// Serialize a primary DID URL.
impl fmt::Display for PrimaryDIDURL {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.did)?;
if let Some(ref path) = self.path {