1use core::fmt;
4use core::mem;
5use core::str::FromStr;
6use std::borrow::Cow;
7use std::collections::{HashMap, HashSet};
8
9use indexmap::{IndexMap, IndexSet};
10use serde::de::{self, MapAccess, SeqAccess, Visitor};
11use serde::ser::SerializeMap as _;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use serde_json::Value;
14
15use super::{Did, DidUrl, DidUrlReference, Uri};
16use crate::jose::{Jwk, OneOrMany};
17
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20#[non_exhaustive]
21pub enum DocumentError {
22 #[error("`@context` must be a string, a map or a non-empty array")]
24 InvalidContext,
25 #[error("verification method `{0}` already exists")]
28 DuplicateVerificationMethod(DidUrl),
29 #[error("service `{0}` already exists")]
31 DuplicateService(DidUrl),
32 #[error("verification method `{0}` not found")]
34 VerificationMethodNotFound(DidUrl),
35 #[error("`{url}` does not belong to document `{document}`")]
37 ForeignDid {
38 url: DidUrl,
40 document: Did,
42 },
43 #[error("verification method `{id}` is not listed under `{relationship}`")]
45 NotInRelationship {
46 id: DidUrl,
48 relationship: VerificationRelationship,
50 },
51 #[error("unknown verification relationship `{0}`")]
53 UnknownRelationship(String),
54 #[error("`{0}` is a core property, not an extension property")]
56 ReservedProperty(String),
57}
58
59fn is_none_or_empty<T>(value: &Option<OneOrMany<T>>) -> bool {
65 value.as_ref().is_none_or(OneOrMany::is_empty)
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87#[serde(transparent)]
88pub struct Context(Value);
89
90impl Context {
91 pub const DID_V1: &'static str = "https://www.w3.org/ns/did/v1";
93
94 pub fn did_v1() -> Self {
96 Self::uri(Self::DID_V1)
97 }
98
99 pub fn uri(uri: impl Into<String>) -> Self {
101 Self(Value::String(uri.into()))
102 }
103
104 pub fn uris<I, S>(uris: I) -> Self
106 where
107 I: IntoIterator<Item = S>,
108 S: Into<String>,
109 {
110 Self(Value::Array(
111 uris.into_iter().map(|s| Value::String(s.into())).collect(),
112 ))
113 }
114
115 pub fn new(value: Value) -> Result<Self, DocumentError> {
121 match &value {
122 Value::String(_) | Value::Object(_) => Ok(Self(value)),
123 Value::Array(items) if !items.is_empty() => Ok(Self(value)),
124 _ => Err(DocumentError::InvalidContext),
125 }
126 }
127
128 pub fn as_value(&self) -> &Value {
130 &self.0
131 }
132
133 pub fn into_value(self) -> Value {
135 self.0
136 }
137
138 pub fn contains(&self, uri: &str) -> bool {
140 match &self.0 {
141 Value::String(s) => s == uri,
142 Value::Array(items) => items.iter().any(|item| item.as_str() == Some(uri)),
143 _ => false,
144 }
145 }
146}
147
148impl<'de> Deserialize<'de> for Context {
149 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
150 Self::new(Value::deserialize(deserializer)?).map_err(de::Error::custom)
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
157#[serde(rename_all = "camelCase")]
158pub enum VerificationRelationship {
159 Authentication,
161 AssertionMethod,
163 KeyAgreement,
165 CapabilityInvocation,
167 CapabilityDelegation,
169}
170
171impl VerificationRelationship {
172 pub const ALL: &'static [VerificationRelationship] = &[
174 Self::Authentication,
175 Self::AssertionMethod,
176 Self::KeyAgreement,
177 Self::CapabilityInvocation,
178 Self::CapabilityDelegation,
179 ];
180
181 pub const fn as_str(self) -> &'static str {
183 match self {
184 Self::Authentication => "authentication",
185 Self::AssertionMethod => "assertionMethod",
186 Self::KeyAgreement => "keyAgreement",
187 Self::CapabilityInvocation => "capabilityInvocation",
188 Self::CapabilityDelegation => "capabilityDelegation",
189 }
190 }
191}
192
193impl fmt::Display for VerificationRelationship {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.write_str(self.as_str())
196 }
197}
198
199impl FromStr for VerificationRelationship {
200 type Err = DocumentError;
201
202 fn from_str(s: &str) -> Result<Self, Self::Err> {
203 Self::ALL
204 .iter()
205 .copied()
206 .find(|rel| rel.as_str() == s)
207 .ok_or_else(|| DocumentError::UnknownRelationship(s.to_owned()))
208 }
209}
210
211#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
225pub struct MethodType(Cow<'static, str>);
226
227impl MethodType {
228 pub const JSON_WEB_KEY_2020: MethodType = MethodType(Cow::Borrowed("JsonWebKey2020"));
230 pub const JSON_WEB_KEY: MethodType = MethodType(Cow::Borrowed("JsonWebKey"));
232 pub const MULTIKEY: MethodType = MethodType(Cow::Borrowed("Multikey"));
234 pub const ED25519_VERIFICATION_KEY_2020: MethodType =
236 MethodType(Cow::Borrowed("Ed25519VerificationKey2020"));
237
238 pub fn new(name: impl Into<String>) -> Self {
240 Self(Cow::Owned(name.into()))
241 }
242
243 pub fn as_str(&self) -> &str {
245 &self.0
246 }
247}
248
249impl fmt::Debug for MethodType {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 fmt::Debug::fmt(self.as_str(), f)
252 }
253}
254
255impl fmt::Display for MethodType {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 f.write_str(self.as_str())
258 }
259}
260
261impl From<&str> for MethodType {
262 fn from(name: &str) -> Self {
263 Self::new(name)
264 }
265}
266
267impl From<String> for MethodType {
268 fn from(name: String) -> Self {
269 Self::new(name)
270 }
271}
272
273impl PartialEq<str> for MethodType {
274 fn eq(&self, other: &str) -> bool {
275 self.as_str() == other
276 }
277}
278
279impl PartialEq<&str> for MethodType {
280 fn eq(&self, other: &&str) -> bool {
281 self.as_str() == *other
282 }
283}
284
285impl Serialize for MethodType {
286 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
287 serializer.serialize_str(self.as_str())
288 }
289}
290
291impl<'de> Deserialize<'de> for MethodType {
292 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
293 String::deserialize(deserializer).map(Self::new)
294 }
295}
296
297#[derive(Debug, Clone, PartialEq, Eq)]
307#[non_exhaustive]
308pub enum VerificationMaterial {
309 PublicKeyJwk(Box<Jwk>),
311 PublicKeyMultibase(String),
313}
314
315impl VerificationMaterial {
316 pub fn jwk(jwk: &Jwk) -> Self {
318 Self::PublicKeyJwk(Box::new(jwk.public()))
319 }
320
321 pub fn multibase(value: impl Into<String>) -> Self {
323 Self::PublicKeyMultibase(value.into())
324 }
325
326 pub fn as_jwk(&self) -> Option<&Jwk> {
328 match self {
329 Self::PublicKeyJwk(jwk) => Some(jwk),
330 Self::PublicKeyMultibase(_) => None,
331 }
332 }
333
334 pub fn as_multibase(&self) -> Option<&str> {
336 match self {
337 Self::PublicKeyMultibase(value) => Some(value),
338 Self::PublicKeyJwk(_) => None,
339 }
340 }
341}
342
343impl Serialize for VerificationMaterial {
344 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
345 let mut map = serializer.serialize_map(Some(1))?;
346 match self {
347 Self::PublicKeyJwk(jwk) => {
348 if jwk.is_private() {
349 return Err(serde::ser::Error::custom(
350 "`publicKeyJwk` must not contain private parameters",
351 ));
352 }
353 map.serialize_entry("publicKeyJwk", jwk)?;
354 }
355 Self::PublicKeyMultibase(value) => map.serialize_entry("publicKeyMultibase", value)?,
356 }
357 map.end()
358 }
359}
360
361#[derive(Deserialize)]
363struct MaterialMembers {
364 #[serde(rename = "publicKeyJwk", default)]
365 public_key_jwk: Option<Jwk>,
366 #[serde(rename = "publicKeyMultibase", default)]
367 public_key_multibase: Option<String>,
368}
369
370impl<'de> Deserialize<'de> for VerificationMaterial {
371 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
372 let members = MaterialMembers::deserialize(deserializer)?;
373 match (members.public_key_jwk, members.public_key_multibase) {
374 (Some(jwk), None) if jwk.is_private() => Err(de::Error::custom(
375 "`publicKeyJwk` must not contain private parameters",
376 )),
377 (Some(jwk), None) => Ok(Self::PublicKeyJwk(Box::new(jwk))),
378 (None, Some(value)) => Ok(Self::PublicKeyMultibase(value)),
379 (None, None) => Err(de::Error::custom(
380 "verification method has neither `publicKeyJwk` nor `publicKeyMultibase`",
381 )),
382 (Some(_), Some(_)) => Err(de::Error::custom(
383 "verification method has both `publicKeyJwk` and `publicKeyMultibase`",
384 )),
385 }
386 }
387}
388
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414#[non_exhaustive]
415pub struct VerificationMethod {
416 pub id: DidUrl,
418 #[serde(rename = "type")]
420 pub method_type: MethodType,
421 pub controller: Did,
423 #[serde(flatten)]
425 pub material: VerificationMaterial,
426 #[serde(flatten)]
428 pub properties: IndexMap<String, Value>,
429}
430
431impl VerificationMethod {
432 pub fn new(
434 id: DidUrl,
435 method_type: MethodType,
436 controller: Did,
437 material: VerificationMaterial,
438 ) -> Self {
439 Self {
440 id,
441 method_type,
442 controller,
443 material,
444 properties: IndexMap::new(),
445 }
446 }
447
448 pub fn public_key_jwk(&self) -> Option<&Jwk> {
450 self.material.as_jwk()
451 }
452
453 pub fn public_key_multibase(&self) -> Option<&str> {
455 self.material.as_multibase()
456 }
457}
458
459#[derive(Debug, Clone, PartialEq, Eq)]
462pub enum MethodRef {
463 Reference(DidUrlReference),
465 Embedded(Box<VerificationMethod>),
467}
468
469impl MethodRef {
470 pub fn reference(id: impl Into<DidUrlReference>) -> Self {
472 Self::Reference(id.into())
473 }
474
475 pub fn embedded(method: VerificationMethod) -> Self {
477 Self::Embedded(Box::new(method))
478 }
479
480 pub fn as_embedded(&self) -> Option<&VerificationMethod> {
482 match self {
483 Self::Embedded(method) => Some(method),
484 Self::Reference(_) => None,
485 }
486 }
487
488 pub fn as_reference(&self) -> Option<&DidUrlReference> {
490 match self {
491 Self::Reference(reference) => Some(reference),
492 Self::Embedded(_) => None,
493 }
494 }
495
496 pub fn refers_to(&self, id: &DidUrl, base: &Did) -> bool {
498 match self {
499 Self::Reference(reference) => reference.refers_to(id, base),
500 Self::Embedded(method) => method.id == *id,
501 }
502 }
503}
504
505impl From<DidUrl> for MethodRef {
506 fn from(id: DidUrl) -> Self {
507 Self::Reference(id.into())
508 }
509}
510
511impl From<DidUrlReference> for MethodRef {
512 fn from(reference: DidUrlReference) -> Self {
513 Self::Reference(reference)
514 }
515}
516
517impl From<VerificationMethod> for MethodRef {
518 fn from(method: VerificationMethod) -> Self {
519 Self::embedded(method)
520 }
521}
522
523impl Serialize for MethodRef {
524 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
525 match self {
526 Self::Reference(reference) => reference.serialize(serializer),
527 Self::Embedded(method) => method.serialize(serializer),
528 }
529 }
530}
531
532impl<'de> Deserialize<'de> for MethodRef {
533 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
534 struct MethodRefVisitor;
535
536 impl<'de> Visitor<'de> for MethodRefVisitor {
537 type Value = MethodRef;
538
539 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 f.write_str("a DID URL string or a verification method object")
541 }
542
543 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
544 DidUrlReference::parse(value)
545 .map(MethodRef::Reference)
546 .map_err(E::custom)
547 }
548
549 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
550 VerificationMethod::deserialize(de::value::MapAccessDeserializer::new(map))
551 .map(MethodRef::embedded)
552 }
553 }
554
555 deserializer.deserialize_any(MethodRefVisitor)
556 }
557}
558
559#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
565#[serde(untagged)]
566pub enum ServiceEndpoint {
567 Uri(Uri),
569 Set(IndexSet<Uri>),
571 Map(IndexMap<String, Value>),
573}
574
575impl ServiceEndpoint {
576 pub fn uri(uri: Uri) -> Self {
578 Self::Uri(uri)
579 }
580
581 pub fn uris(&self) -> impl Iterator<Item = &Uri> {
583 let slice: Box<dyn Iterator<Item = &Uri>> = match self {
584 Self::Uri(uri) => Box::new(core::iter::once(uri)),
585 Self::Set(set) => Box::new(set.iter()),
586 Self::Map(_) => Box::new(core::iter::empty()),
587 };
588 slice
589 }
590}
591
592impl From<Uri> for ServiceEndpoint {
593 fn from(uri: Uri) -> Self {
594 Self::Uri(uri)
595 }
596}
597
598impl<'de> Deserialize<'de> for ServiceEndpoint {
599 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
600 struct EndpointVisitor;
601
602 impl<'de> Visitor<'de> for EndpointVisitor {
603 type Value = ServiceEndpoint;
604
605 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 f.write_str("a URI string, a non-empty array of URI strings, or an object")
607 }
608
609 fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
610 Uri::parse(value)
611 .map(ServiceEndpoint::Uri)
612 .map_err(E::custom)
613 }
614
615 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
616 let mut set = IndexSet::new();
617 while let Some(uri) = seq.next_element::<Uri>()? {
618 set.insert(uri);
619 }
620 if set.is_empty() {
621 return Err(de::Error::custom(
622 "`serviceEndpoint` set must contain at least one URI",
623 ));
624 }
625 Ok(ServiceEndpoint::Set(set))
626 }
627
628 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
629 let mut entries = IndexMap::new();
630 while let Some((key, value)) = map.next_entry::<String, Value>()? {
631 entries.insert(key, value);
632 }
633 Ok(ServiceEndpoint::Map(entries))
634 }
635 }
636
637 deserializer.deserialize_any(EndpointVisitor)
638 }
639}
640
641#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646#[non_exhaustive]
647pub struct Service {
648 pub id: DidUrl,
650 #[serde(rename = "type")]
652 pub service_type: OneOrMany<String>,
653 #[serde(rename = "serviceEndpoint")]
655 pub service_endpoint: ServiceEndpoint,
656 #[serde(flatten)]
658 pub properties: IndexMap<String, Value>,
659}
660
661impl Service {
662 pub fn new(
664 id: DidUrl,
665 service_type: impl Into<OneOrMany<String>>,
666 service_endpoint: impl Into<ServiceEndpoint>,
667 ) -> Self {
668 Self {
669 id,
670 service_type: service_type.into(),
671 service_endpoint: service_endpoint.into(),
672 properties: IndexMap::new(),
673 }
674 }
675
676 pub fn has_type(&self, service_type: &str) -> bool {
678 self.service_type.iter().any(|t| t == service_type)
679 }
680}
681
682#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
732#[non_exhaustive]
733#[serde(remote = "Self")]
734pub struct DidDocument {
735 #[serde(rename = "@context", default, skip_serializing_if = "Option::is_none")]
737 pub context: Option<Context>,
738 pub id: Did,
740 #[serde(rename = "alsoKnownAs", default, skip_serializing_if = "Vec::is_empty")]
742 pub also_known_as: Vec<Uri>,
743 #[serde(default, skip_serializing_if = "is_none_or_empty")]
746 pub controller: Option<OneOrMany<Did>>,
747 #[serde(
749 rename = "verificationMethod",
750 default,
751 skip_serializing_if = "Vec::is_empty"
752 )]
753 pub verification_method: Vec<VerificationMethod>,
754 #[serde(default, skip_serializing_if = "Vec::is_empty")]
756 pub authentication: Vec<MethodRef>,
757 #[serde(
759 rename = "assertionMethod",
760 default,
761 skip_serializing_if = "Vec::is_empty"
762 )]
763 pub assertion_method: Vec<MethodRef>,
764 #[serde(
766 rename = "keyAgreement",
767 default,
768 skip_serializing_if = "Vec::is_empty"
769 )]
770 pub key_agreement: Vec<MethodRef>,
771 #[serde(
773 rename = "capabilityInvocation",
774 default,
775 skip_serializing_if = "Vec::is_empty"
776 )]
777 pub capability_invocation: Vec<MethodRef>,
778 #[serde(
780 rename = "capabilityDelegation",
781 default,
782 skip_serializing_if = "Vec::is_empty"
783 )]
784 pub capability_delegation: Vec<MethodRef>,
785 #[serde(default, skip_serializing_if = "Vec::is_empty")]
787 pub service: Vec<Service>,
788 #[serde(flatten)]
790 pub properties: IndexMap<String, Value>,
791}
792
793impl Serialize for DidDocument {
794 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
795 Self::serialize(self, serializer)
796 }
797}
798
799impl<'de> Deserialize<'de> for DidDocument {
800 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
803 let mut document = Self::deserialize(deserializer)?;
804 document.check_unique_ids().map_err(de::Error::custom)?;
805 if is_none_or_empty(&document.controller) {
806 document.controller = None;
807 }
808 Ok(document)
809 }
810}
811
812impl DidDocument {
813 pub const CORE_PROPERTIES: &'static [&'static str] = &[
815 "@context",
816 "id",
817 "alsoKnownAs",
818 "controller",
819 "verificationMethod",
820 "authentication",
821 "assertionMethod",
822 "keyAgreement",
823 "capabilityInvocation",
824 "capabilityDelegation",
825 "service",
826 ];
827
828 pub fn new(id: Did) -> Self {
830 Self {
831 context: None,
832 id,
833 also_known_as: Vec::new(),
834 controller: None,
835 verification_method: Vec::new(),
836 authentication: Vec::new(),
837 assertion_method: Vec::new(),
838 key_agreement: Vec::new(),
839 capability_invocation: Vec::new(),
840 capability_delegation: Vec::new(),
841 service: Vec::new(),
842 properties: IndexMap::new(),
843 }
844 }
845
846 pub fn builder(id: Did) -> DidDocumentBuilder {
848 DidDocumentBuilder {
849 document: Self::new(id),
850 error: None,
851 }
852 }
853
854 pub fn relationship(&self, relationship: VerificationRelationship) -> &[MethodRef] {
856 match relationship {
857 VerificationRelationship::Authentication => &self.authentication,
858 VerificationRelationship::AssertionMethod => &self.assertion_method,
859 VerificationRelationship::KeyAgreement => &self.key_agreement,
860 VerificationRelationship::CapabilityInvocation => &self.capability_invocation,
861 VerificationRelationship::CapabilityDelegation => &self.capability_delegation,
862 }
863 }
864
865 pub fn relationship_mut(
867 &mut self,
868 relationship: VerificationRelationship,
869 ) -> &mut Vec<MethodRef> {
870 match relationship {
871 VerificationRelationship::Authentication => &mut self.authentication,
872 VerificationRelationship::AssertionMethod => &mut self.assertion_method,
873 VerificationRelationship::KeyAgreement => &mut self.key_agreement,
874 VerificationRelationship::CapabilityInvocation => &mut self.capability_invocation,
875 VerificationRelationship::CapabilityDelegation => &mut self.capability_delegation,
876 }
877 }
878
879 fn embedded_methods(&self) -> impl Iterator<Item = &VerificationMethod> {
881 VerificationRelationship::ALL
882 .iter()
883 .flat_map(|rel| self.relationship(*rel))
884 .filter_map(MethodRef::as_embedded)
885 }
886
887 pub fn verification_method(&self, id: &DidUrl) -> Option<&VerificationMethod> {
890 self.verification_method
891 .iter()
892 .chain(self.embedded_methods())
893 .find(|method| method.id == *id)
894 }
895
896 pub fn methods(
902 &self,
903 relationship: Option<VerificationRelationship>,
904 ) -> impl Iterator<Item = &VerificationMethod> {
905 let entries: Box<dyn Iterator<Item = &VerificationMethod>> =
906 match relationship {
907 None => Box::new(
908 self.verification_method
909 .iter()
910 .chain(self.embedded_methods()),
911 ),
912 Some(rel) => Box::new(self.relationship(rel).iter().filter_map(
913 |entry| match entry {
914 MethodRef::Embedded(method) => Some(&**method),
915 MethodRef::Reference(reference) => {
916 let id = reference.resolve(&self.id).ok()?;
917 self.verification_method.iter().find(|m| m.id == id)
918 }
919 },
920 )),
921 };
922 entries
923 }
924
925 pub fn resolve_verification_method(
937 &self,
938 id: &DidUrl,
939 relationship: Option<VerificationRelationship>,
940 ) -> Result<&VerificationMethod, DocumentError> {
941 if id.did() != &self.id {
942 return Err(DocumentError::ForeignDid {
943 url: id.clone(),
944 document: self.id.clone(),
945 });
946 }
947 let Some(relationship) = relationship else {
948 return self
949 .verification_method(id)
950 .ok_or_else(|| DocumentError::VerificationMethodNotFound(id.clone()));
951 };
952 for entry in self.relationship(relationship) {
953 match entry {
954 MethodRef::Embedded(method) if method.id == *id => return Ok(method),
955 MethodRef::Reference(reference) if reference.refers_to(id, &self.id) => {
956 return self
957 .verification_method
958 .iter()
959 .find(|method| method.id == *id)
960 .ok_or_else(|| DocumentError::VerificationMethodNotFound(id.clone()));
961 }
962 _ => {}
963 }
964 }
965 if self.verification_method(id).is_some() {
966 Err(DocumentError::NotInRelationship {
967 id: id.clone(),
968 relationship,
969 })
970 } else {
971 Err(DocumentError::VerificationMethodNotFound(id.clone()))
972 }
973 }
974
975 pub fn resolve_method_reference(
982 &self,
983 reference: &DidUrlReference,
984 relationship: Option<VerificationRelationship>,
985 ) -> Result<&VerificationMethod, DocumentError> {
986 let id = reference.resolve(&self.id).map_err(|_| match reference {
988 DidUrlReference::Absolute(url) => DocumentError::ForeignDid {
989 url: url.clone(),
990 document: self.id.clone(),
991 },
992 DidUrlReference::Relative(_) => {
993 DocumentError::VerificationMethodNotFound(self.id.to_url())
994 }
995 })?;
996 self.resolve_verification_method(&id, relationship)
997 }
998
999 pub fn insert_verification_method(
1006 &mut self,
1007 method: VerificationMethod,
1008 relationships: impl IntoIterator<Item = VerificationRelationship>,
1009 ) -> Result<(), DocumentError> {
1010 if self.verification_method(&method.id).is_some() {
1011 return Err(DocumentError::DuplicateVerificationMethod(method.id));
1012 }
1013 let id = method.id.clone();
1014 self.verification_method.push(method);
1015 for relationship in relationships {
1016 self.attach_relationship(&id, relationship)?;
1017 }
1018 Ok(())
1019 }
1020
1021 pub fn check_unique_ids(&self) -> Result<(), DocumentError> {
1031 let mut seen = HashMap::new();
1032 for method in self
1033 .verification_method
1034 .iter()
1035 .chain(self.embedded_methods())
1036 {
1037 if *seen.entry(&method.id).or_insert(method) != method {
1038 return Err(DocumentError::DuplicateVerificationMethod(
1039 method.id.clone(),
1040 ));
1041 }
1042 }
1043 let mut seen = HashSet::new();
1044 for service in &self.service {
1045 if !seen.insert(&service.id) {
1046 return Err(DocumentError::DuplicateService(service.id.clone()));
1047 }
1048 }
1049 Ok(())
1050 }
1051
1052 pub fn remove_verification_method(&mut self, id: &DidUrl) -> Option<VerificationMethod> {
1054 let (matching, rest): (Vec<_>, Vec<_>) = mem::take(&mut self.verification_method)
1056 .into_iter()
1057 .partition(|method| method.id == *id);
1058 self.verification_method = rest;
1059 let listed = matching.into_iter().next();
1060 let mut embedded = None;
1061 let base = self.id.clone();
1062 for relationship in VerificationRelationship::ALL {
1063 let entries = self.relationship_mut(*relationship);
1064 let mut index = 0;
1065 while index < entries.len() {
1066 if entries[index].refers_to(id, &base) {
1067 if let MethodRef::Embedded(method) = entries.remove(index) {
1068 embedded.get_or_insert(*method);
1069 }
1070 } else {
1071 index += 1;
1072 }
1073 }
1074 }
1075 listed.or(embedded)
1076 }
1077
1078 pub fn attach_relationship(
1088 &mut self,
1089 id: &DidUrl,
1090 relationship: VerificationRelationship,
1091 ) -> Result<bool, DocumentError> {
1092 if !self.verification_method.iter().any(|m| m.id == *id) {
1093 return Err(DocumentError::VerificationMethodNotFound(id.clone()));
1094 }
1095 let base = self.id.clone();
1096 let entries = self.relationship_mut(relationship);
1097 if entries.iter().any(|entry| entry.refers_to(id, &base)) {
1098 return Ok(false);
1099 }
1100 entries.push(MethodRef::Reference(id.clone().into()));
1101 Ok(true)
1102 }
1103
1104 pub fn detach_relationship(
1107 &mut self,
1108 id: &DidUrl,
1109 relationship: VerificationRelationship,
1110 ) -> bool {
1111 let base = self.id.clone();
1112 let entries = self.relationship_mut(relationship);
1113 let before = entries.len();
1114 entries.retain(|entry| !entry.refers_to(id, &base));
1115 entries.len() != before
1116 }
1117
1118 pub fn service(&self, id: &DidUrl) -> Option<&Service> {
1120 self.service.iter().find(|service| service.id == *id)
1121 }
1122
1123 pub fn insert_service(&mut self, service: Service) -> Result<(), DocumentError> {
1129 if self.service(&service.id).is_some() {
1130 return Err(DocumentError::DuplicateService(service.id));
1131 }
1132 self.service.push(service);
1133 Ok(())
1134 }
1135
1136 pub fn remove_service(&mut self, id: &DidUrl) -> Option<Service> {
1138 self.service
1139 .iter()
1140 .position(|service| service.id == *id)
1141 .map(|index| self.service.remove(index))
1142 }
1143
1144 pub fn map_dids(&mut self, mut f: impl FnMut(Did) -> Did) {
1184 fn map_url(url: &mut DidUrl, f: &mut impl FnMut(Did) -> Did) {
1185 let did = f(url.did().clone());
1186 if &did != url.did() {
1187 *url = url.with_did(did);
1188 }
1189 }
1190 fn map_method(method: &mut VerificationMethod, f: &mut impl FnMut(Did) -> Did) {
1191 map_url(&mut method.id, f);
1192 method.controller = f(method.controller.clone());
1193 }
1194
1195 self.id = f(self.id.clone());
1196 if let Some(controller) = &mut self.controller {
1197 for did in controller.iter_mut() {
1198 *did = f(did.clone());
1199 }
1200 }
1201 for method in &mut self.verification_method {
1202 map_method(method, &mut f);
1203 }
1204 for relationship in VerificationRelationship::ALL {
1205 for entry in self.relationship_mut(*relationship) {
1206 match entry {
1207 MethodRef::Reference(DidUrlReference::Absolute(url)) => map_url(url, &mut f),
1208 MethodRef::Reference(DidUrlReference::Relative(_)) => {}
1209 MethodRef::Embedded(method) => map_method(method, &mut f),
1210 }
1211 }
1212 }
1213 for service in &mut self.service {
1214 map_url(&mut service.id, &mut f);
1215 }
1216 }
1217}
1218
1219#[derive(Debug, Clone)]
1221pub struct DidDocumentBuilder {
1222 document: DidDocument,
1223 error: Option<DocumentError>,
1224}
1225
1226impl DidDocumentBuilder {
1227 #[must_use]
1229 pub fn context(mut self, context: Context) -> Self {
1230 self.document.context = Some(context);
1231 self
1232 }
1233
1234 #[must_use]
1236 pub fn also_known_as(mut self, uri: Uri) -> Self {
1237 self.document.also_known_as.push(uri);
1238 self
1239 }
1240
1241 #[must_use]
1243 pub fn controller(mut self, did: Did) -> Self {
1244 self.document.controller = Some(match self.document.controller.take() {
1245 None => OneOrMany::One(did),
1246 Some(existing) => {
1247 let mut dids = existing.into_vec();
1248 dids.push(did);
1249 OneOrMany::Many(dids)
1250 }
1251 });
1252 self
1253 }
1254
1255 #[must_use]
1257 pub fn verification_method(
1258 mut self,
1259 method: VerificationMethod,
1260 relationships: impl IntoIterator<Item = VerificationRelationship>,
1261 ) -> Self {
1262 if self.error.is_none() {
1263 self.error = self
1264 .document
1265 .insert_verification_method(method, relationships)
1266 .err();
1267 }
1268 self
1269 }
1270
1271 #[must_use]
1273 pub fn embedded_method(
1274 mut self,
1275 relationship: VerificationRelationship,
1276 method: VerificationMethod,
1277 ) -> Self {
1278 if self.error.is_none() {
1279 if self.document.verification_method(&method.id).is_some() {
1280 self.error = Some(DocumentError::DuplicateVerificationMethod(method.id));
1281 } else {
1282 self.document
1283 .relationship_mut(relationship)
1284 .push(MethodRef::embedded(method));
1285 }
1286 }
1287 self
1288 }
1289
1290 #[must_use]
1292 pub fn service(mut self, service: Service) -> Self {
1293 if self.error.is_none() {
1294 self.error = self.document.insert_service(service).err();
1295 }
1296 self
1297 }
1298
1299 #[must_use]
1302 pub fn property(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
1303 let name = name.into();
1304 if DidDocument::CORE_PROPERTIES.contains(&name.as_str()) {
1305 if self.error.is_none() {
1306 self.error = Some(DocumentError::ReservedProperty(name));
1307 }
1308 } else {
1309 self.document.properties.insert(name, value.into());
1310 }
1311 self
1312 }
1313
1314 pub fn build(self) -> Result<DidDocument, DocumentError> {
1320 match self.error {
1321 Some(error) => Err(error),
1322 None => Ok(self.document),
1323 }
1324 }
1325}