did_toolkit/
document.rs

1use crate::{did::DID, jwk::JWK, multibase::MultiBase, registry::Registry, url::URL};
2use anyhow::anyhow;
3use either::Either;
4use serde::{Deserialize, Serialize};
5use std::{collections::BTreeSet, fmt::Display, hash::Hash, str::FromStr};
6use url::Url;
7
8#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
9pub enum VerificationMethodType {
10    JWK2020,
11    ECDSASECP256K12019,
12    Ed255192018,
13    Bls12381G12020,
14    Bls12381G22020,
15    PGP2021,
16    ECDSASECP256K1Recovery2020,
17    VerifiableCondition2021,
18}
19
20impl Default for VerificationMethodType {
21    fn default() -> Self {
22        VerificationMethodType::JWK2020
23    }
24}
25
26impl FromStr for VerificationMethodType {
27    type Err = anyhow::Error;
28
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        match s {
31            "JsonWebKey2020" => Ok(Self::JWK2020),
32            "EcdsaSecp256k1VerificationKey2019" => Ok(Self::ECDSASECP256K12019),
33            "Ed25519VerificationKey2018" => Ok(Self::Ed255192018),
34            "Bls12381G1Key2020" => Ok(Self::Bls12381G12020),
35            "Bls12381G2Key2020" => Ok(Self::Bls12381G22020),
36            "PgpVerificationKey2021" => Ok(Self::PGP2021),
37            "EcdsaSecp256k1RecoveryMethod2020" => Ok(Self::ECDSASECP256K1Recovery2020),
38            "VerifiableCondition2021" => Ok(Self::VerifiableCondition2021),
39            _ => Err(anyhow!("Property does not match")),
40        }
41    }
42}
43
44impl Display for VerificationMethodType {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.write_str(match self {
47            Self::JWK2020 => "JsonWebKey2020",
48            Self::ECDSASECP256K12019 => "EcdsaSecp256k1VerificationKey2019",
49            Self::Ed255192018 => "Ed25519VerificationKey2018",
50            Self::Bls12381G12020 => "Bls12381G1Key2020",
51            Self::Bls12381G22020 => "Bls12381G2Key2020",
52            Self::PGP2021 => "PgpVerificationKey2021",
53            Self::ECDSASECP256K1Recovery2020 => "EcdsaSecp256k1RecoveryMethod2020",
54            Self::VerifiableCondition2021 => "VerifiableCondition2021",
55        })
56    }
57}
58
59#[derive(Clone, Default, Debug, Eq, PartialOrd, Ord, Serialize, Deserialize)]
60pub struct VerificationMethod {
61    pub id: URL,
62    pub controller: DID,
63    #[serde(rename = "type")]
64    pub typ: VerificationMethodType,
65    #[serde(rename = "publicKeyJwk", skip_serializing_if = "Option::is_none")]
66    pub public_key_jwk: Option<JWK>,
67    #[serde(rename = "publicKeyMultibase", skip_serializing_if = "Option::is_none")]
68    pub public_key_multibase: Option<MultiBase>,
69}
70
71impl PartialEq for VerificationMethod {
72    fn eq(&self, other: &Self) -> bool {
73        self.id == other.id
74            && self.controller == other.controller
75            && self.typ == other.typ
76            && self.public_key_jwk == other.public_key_jwk
77            && self.public_key_multibase == other.public_key_multibase
78    }
79}
80
81// fixate the "key" for the hash on the verification method id. We don't want the rest considered,
82// so we can constrain uniqueness on the id, not, say, the key material.
83impl Hash for VerificationMethod {
84    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
85        self.id.hash(state)
86    }
87}
88
89impl VerificationMethod {
90    /// Determines if a verification method is valid. To be valid, it must only contain one public
91    /// key.
92    pub fn valid(&self) -> Result<(), anyhow::Error> {
93        if self.public_key_jwk.is_some() && self.public_key_multibase.is_some() {
94            return Err(anyhow!(
95                "Verification method {} provided both JWK and multibase keys",
96                self.id
97            ));
98        }
99
100        Ok(())
101    }
102}
103
104#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
105/// It's important to note here that the document that describes these is not very well formed.
106/// <https://www.w3.org/TR/did-spec-registries/#service-types>
107pub enum ServiceType {
108    /// <https://www.w3.org/TR/did-spec-registries/#credentialregistry>
109    CredentialRegistry,
110    /// <https://identity.foundation/.well-known/resources/did-configuration/#linked-domain-service-endpoint>
111    LinkedDomains,
112    // there are others (such as DIDCommMessaging) that I did not supply here because they don't
113    // appear to be finished.
114}
115
116impl Display for ServiceType {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.write_str(match self {
119            Self::LinkedDomains => "LinkedDomains",
120            Self::CredentialRegistry => "CredentialRegistry",
121        })
122    }
123}
124
125impl FromStr for ServiceType {
126    type Err = anyhow::Error;
127
128    fn from_str(s: &str) -> Result<Self, Self::Err> {
129        match s {
130            "LinkedDomains" => Ok(Self::LinkedDomains),
131            "CredentialRegistry" => Ok(Self::CredentialRegistry),
132            _ => Err(anyhow!("Property does not match")),
133        }
134    }
135}
136
137#[derive(Clone, Default, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
138pub struct ServiceEndpointProperties {
139    // only used for LinkedDomains
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub origins: Option<BTreeSet<Url>>,
142
143    // only used for CredentialRegistry
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub registries: Option<BTreeSet<Url>>,
146}
147
148#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
149pub struct ServiceTypes(pub Either<ServiceType, BTreeSet<ServiceType>>);
150
151#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
152pub struct ServiceEndpoints(pub Either<Url, ServiceEndpointProperties>);
153
154#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
155pub struct ServiceEndpoint {
156    pub id: Url,
157    #[serde(rename = "type")]
158    pub typ: ServiceTypes,
159    #[serde(rename = "serviceEndpoint")]
160    pub endpoint: ServiceEndpoints,
161}
162
163#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
164pub struct VerificationMethodEither(pub Either<VerificationMethod, URL>);
165
166#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
167pub struct VerificationMethods(pub BTreeSet<VerificationMethodEither>);
168
169impl VerificationMethods {
170    /// Determines if the set of verification methods is valid. Takes an optional registry to
171    /// lookup by [URL].
172    pub fn valid(&self, registry: Option<&Registry>) -> Result<(), anyhow::Error> {
173        for v in self.0.iter() {
174            match &v.0 {
175                Either::Left(vm) => vm.valid()?,
176                Either::Right(url) => {
177                    if let Some(registry) = &registry {
178                        if let Some(doc) = registry.get(&url.to_did()) {
179                            if let Some(vms) = doc.verification_method {
180                                if vms.iter().any(|vm| &(*vm).id == url) {
181                                    return Ok(());
182                                } else {
183                                    return Err(anyhow!("Could not locate verification method prescribed by {} in registry", url));
184                                }
185                            }
186                        } else {
187                            return Err(anyhow!(
188                                "Could not retrieve DID from DID URL {} in registry",
189                                url
190                            ));
191                        }
192                    } else {
193                        return Err(anyhow!("DID URL {} provided as verification method, but could not look up in registry because none was provided", url));
194                    }
195                }
196            }
197        }
198
199        Ok(())
200    }
201}
202
203#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
204pub struct AlsoKnownAsEither(pub Either<DID, Url>);
205
206#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
207pub struct AlsoKnownAs(pub BTreeSet<AlsoKnownAsEither>);
208
209#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
210pub struct Controller(pub Either<DID, BTreeSet<DID>>);
211
212impl Default for Controller {
213    fn default() -> Self {
214        Controller(Either::Right(BTreeSet::default()))
215    }
216}
217
218#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
219pub struct Context(pub Either<Url, BTreeSet<Url>>);
220
221impl Default for Context {
222    fn default() -> Self {
223        Context(Either::Right(BTreeSet::default()))
224    }
225}
226
227/// The encapsulation of a decentralized identity document, or DID. This conforms to the did-core
228/// spec in totality, according to the rules defined in
229/// <https://www.w3.org/TR/did-core/#core-properties>. Divergence from the spec will be considered a
230/// bug, unless otherwise noted.
231///
232/// Please see the individual properties regarding their use. Types in this module will remain
233/// undocumented for brevity's sake, with the exception of methods that live on those types.
234///
235/// One notable thing in this implementation is use of the [either] crate with wrapping types. This
236/// is used to aid in the (de)-serialization of documents properties that can consume multiple
237/// switched types. Unfortunately, the spec is not very kind to users of statically-typed
238/// languages, so we must take extra precautions to ensure all valid documents can be parsed. To
239/// utilize most of these types, there may be an "either wrapper" as well as the [either::Either]
240/// enum itself to encapsulate a type. For example, [AlsoKnownAs] encapsulates [AlsoKnownAsEither]
241/// as a [BTreeSet] which then encapsulates [either::Either] types depending on which style of
242/// attribute was used, as [DID]s and hypertext [url::Url]s can be used interchangeably. This
243/// approach reduces memory usage and computation time by storing structs instead of raw strings
244/// and "figuring it out later".
245///
246/// JSON-LD attributes (`@context`, specifically), are accounted for but not used by this
247/// implementation. This allows you to generate documents and consume ones that follow the JSON-LD
248/// specification but does not attempt to validate the document using the JSON-LD schema. See the
249/// crate's README for more information regarding this decision.
250///
251/// [serde] crate implementations are available for all types, to ensure valid [serde_json] and
252/// [ciborium] I/O, but other formats that [serde] supports should be technically possible to
253/// support without issue.
254///
255#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
256pub struct Document {
257    /// JSON-LD @context support
258    #[serde(rename = "@context", skip_serializing_if = "Option::is_none")]
259    pub context: Option<Context>,
260    /// The DID that this document corresponds to. Will be used as the key when storing in a
261    /// [Registry]. This is called the "DID Subject" in the specification.
262    pub id: DID,
263    /// alsoKnownAs determines equivalence for two documents for all purposes. See
264    /// <https://www.w3.org/TR/did-core/#also-known-as> for more.
265    #[serde(rename = "alsoKnownAs", skip_serializing_if = "Option::is_none")]
266    pub also_known_as: Option<AlsoKnownAs>,
267    // controller determines if another [DID] is capable of taking actions for this [DID]. See
268    // <https://www.w3.org/TR/did-core/#did-controller> for more.
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub controller: Option<Controller>,
271    /// [VerificationMethod]s are used to verify the identity claiming this document. See
272    /// <https://www.w3.org/TR/did-core/#verification-methods> for more. Most following properties
273    /// that use [VerificationMethods] may refer to this portion of the document by [URL] to add
274    /// additional capabilities to a specific [VerificationMethod].
275    #[serde(rename = "verificationMethod", skip_serializing_if = "Option::is_none")]
276    pub verification_method: Option<BTreeSet<VerificationMethod>>,
277    /// This set of [VerificationMethods] corresponds to authentication.
278    /// <https://www.w3.org/TR/did-core/#authentication>
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub authentication: Option<VerificationMethods>,
281    /// This set of [VerificationMethods] corresponds to assertions.
282    /// <https://www.w3.org/TR/did-core/#assertion>
283    #[serde(rename = "assertionMethod", skip_serializing_if = "Option::is_none")]
284    pub assertion_method: Option<VerificationMethods>,
285    /// This set of [VerificationMethods] refers to key agreement.
286    /// <https://www.w3.org/TR/did-core/#key-agreement>
287    #[serde(rename = "keyAgreement", skip_serializing_if = "Option::is_none")]
288    pub key_agreement: Option<VerificationMethods>,
289    /// This set of [VerificationMethods] refers to capability invocation.
290    /// <https://www.w3.org/TR/did-core/#capability-invocation>
291    #[serde(
292        rename = "capabilityInvocation",
293        skip_serializing_if = "Option::is_none"
294    )]
295    /// This set of [VerificationMethods] refers to capability delegation.
296    /// <https://www.w3.org/TR/did-core/#capability-delegation>
297    pub capability_invocation: Option<VerificationMethods>,
298    #[serde(
299        rename = "capabilityDelegation",
300        skip_serializing_if = "Option::is_none"
301    )]
302    pub capability_delegation: Option<VerificationMethods>,
303    /// This portion of the document refers to affected services. Services are specially provided
304    /// by the "DID registry": <https://www.w3.org/TR/did-spec-registries/> and rely on enums to
305    /// determine how the service is treated.
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub service: Option<BTreeSet<ServiceEndpoint>>,
308}
309
310impl Document {
311    /// Determines if a document is valid. Takes an optional registry to resolve [URL]s
312    pub fn valid(&self, registry: Option<&Registry>) -> Result<(), anyhow::Error> {
313        if let Some(vm) = &self.verification_method {
314            for v in vm.iter() {
315                v.valid()?;
316            }
317        }
318
319        // these are all basically the same, call the inner verification method, or do something
320        // with the DID URL.
321        for field in [
322            &self.authentication,
323            &self.assertion_method,
324            &self.key_agreement,
325            &self.capability_invocation,
326            &self.capability_delegation,
327        ] {
328            if let Some(field) = field {
329                field.valid(registry)?
330            }
331        }
332
333        Ok(())
334    }
335}
336
337mod serde_support {
338    use super::{
339        AlsoKnownAsEither, Context, Controller, ServiceEndpointProperties, ServiceEndpoints,
340        ServiceType, ServiceTypes, VerificationMethod, VerificationMethodEither,
341        VerificationMethodType,
342    };
343    use crate::{did::DID, url::URL};
344    use either::Either;
345    use serde::{de::Visitor, ser::SerializeSeq, Deserialize, Serialize, Serializer};
346    use std::{collections::BTreeSet, str::FromStr};
347    use url::Url;
348
349    struct ControllerVisitor;
350
351    impl<'de> Visitor<'de> for ControllerVisitor {
352        type Value = Controller;
353
354        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
355            formatter.write_str("Expecting a DID or set of DIDs")
356        }
357
358        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
359        where
360            E: serde::de::Error,
361        {
362            match DID::parse(v) {
363                Ok(did) => Ok(Controller(Either::Left(did))),
364                Err(e) => Err(E::custom(e)),
365            }
366        }
367
368        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
369        where
370            A: serde::de::SeqAccess<'de>,
371        {
372            let mut set = BTreeSet::default();
373
374            while let Some(elem) = seq.next_element::<String>()? {
375                match DID::parse(&elem) {
376                    Ok(did) => {
377                        set.insert(did);
378                    }
379                    Err(e) => return Err(serde::de::Error::custom(e)),
380                }
381            }
382
383            Ok(Controller(Either::Right(set)))
384        }
385    }
386
387    impl<'de> Deserialize<'de> for Controller {
388        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
389        where
390            D: serde::Deserializer<'de>,
391        {
392            deserializer.deserialize_any(ControllerVisitor)
393        }
394    }
395
396    impl Serialize for Controller {
397        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
398        where
399            S: Serializer,
400        {
401            match &self.0 {
402                Either::Left(did) => serializer.serialize_str(&did.to_string()),
403                Either::Right(set) => {
404                    let mut seq = serializer.serialize_seq(Some(set.len()))?;
405                    for item in set {
406                        seq.serialize_element(&item.to_string())?;
407                    }
408                    seq.end()
409                }
410            }
411        }
412    }
413
414    struct AlsoKnownAsVisitor;
415
416    impl<'de> Visitor<'de> for AlsoKnownAsVisitor {
417        type Value = AlsoKnownAsEither;
418
419        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
420            formatter.write_str("Expecting a set of inter-mixed DIDs and URLs")
421        }
422
423        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
424        where
425            E: serde::de::Error,
426        {
427            let res = match DID::parse(v) {
428                Ok(did) => Either::Left(did),
429                Err(_) => match Url::parse(v) {
430                    Ok(url) => Either::Right(url),
431                    Err(e) => return Err(serde::de::Error::custom(e)),
432                },
433            };
434
435            Ok(AlsoKnownAsEither(res))
436        }
437    }
438
439    impl<'de> Deserialize<'de> for AlsoKnownAsEither {
440        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
441        where
442            D: serde::Deserializer<'de>,
443        {
444            deserializer.deserialize_str(AlsoKnownAsVisitor)
445        }
446    }
447
448    impl Serialize for AlsoKnownAsEither {
449        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
450        where
451            S: Serializer,
452        {
453            serializer.serialize_str(&match &self.0 {
454                Either::Left(did) => did.to_string(),
455                Either::Right(url) => url.to_string(),
456            })
457        }
458    }
459
460    struct VerificationMethodVisitor;
461    impl<'de> Visitor<'de> for VerificationMethodVisitor {
462        type Value = VerificationMethodEither;
463
464        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
465            formatter.write_str("Expecting a set of verification methods or DID URLs")
466        }
467
468        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
469        where
470            E: serde::de::Error,
471        {
472            match URL::parse(v) {
473                Ok(url) => Ok(VerificationMethodEither(Either::Right(url))),
474                Err(e) => Err(serde::de::Error::custom(e)),
475            }
476        }
477
478        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
479        where
480            A: serde::de::MapAccess<'de>,
481        {
482            let mut vm = VerificationMethod::default();
483
484            while let Some(key) = map.next_key::<String>()? {
485                match key.as_str() {
486                    "id" => vm.id = map.next_value()?,
487                    "controller" => vm.controller = map.next_value()?,
488                    "type" => vm.typ = map.next_value()?,
489                    "publicKeyJwk" => vm.public_key_jwk = map.next_value()?,
490                    "publicKeyMultibase" => vm.public_key_multibase = map.next_value()?,
491                    _ => {
492                        return Err(serde::de::Error::unknown_field(
493                            &key,
494                            &[
495                                "id",
496                                "controller",
497                                "type",
498                                "publicKeyJwk",
499                                "publicKeyMultibase",
500                            ],
501                        ))
502                    }
503                }
504            }
505
506            Ok(VerificationMethodEither(Either::Left(vm)))
507        }
508    }
509
510    impl<'de> Deserialize<'de> for VerificationMethodEither {
511        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
512        where
513            D: serde::Deserializer<'de>,
514        {
515            deserializer.deserialize_any(VerificationMethodVisitor)
516        }
517    }
518
519    impl Serialize for VerificationMethodEither {
520        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
521        where
522            S: Serializer,
523        {
524            match &self.0 {
525                Either::Left(vm) => vm.serialize(serializer),
526                Either::Right(url) => url.serialize(serializer),
527            }
528        }
529    }
530
531    struct ServiceTypeVisitor;
532
533    impl<'de> Visitor<'de> for ServiceTypeVisitor {
534        type Value = ServiceTypes;
535
536        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
537            formatter.write_str("Expecting set of service types or a single service type")
538        }
539
540        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
541        where
542            A: serde::de::SeqAccess<'de>,
543        {
544            let mut set = BTreeSet::default();
545
546            while let Some(elem) = seq.next_element::<String>()? {
547                match ServiceType::from_str(&elem) {
548                    Ok(st) => {
549                        set.insert(st);
550                    }
551                    Err(e) => return Err(serde::de::Error::custom(e)),
552                }
553            }
554
555            Ok(ServiceTypes(Either::Right(set)))
556        }
557
558        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
559        where
560            E: serde::de::Error,
561        {
562            Ok(ServiceTypes(match ServiceType::from_str(v) {
563                Ok(st) => Either::Left(st),
564                Err(e) => return Err(serde::de::Error::custom(e)),
565            }))
566        }
567    }
568
569    impl<'de> Deserialize<'de> for ServiceTypes {
570        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
571        where
572            D: serde::Deserializer<'de>,
573        {
574            deserializer.deserialize_any(ServiceTypeVisitor)
575        }
576    }
577
578    impl Serialize for ServiceTypes {
579        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
580        where
581            S: Serializer,
582        {
583            match &self.0 {
584                Either::Left(typ) => typ.serialize(serializer),
585                Either::Right(set) => {
586                    let mut seq = serializer.serialize_seq(Some(set.len()))?;
587
588                    for item in set {
589                        seq.serialize_element(item)?;
590                    }
591
592                    seq.end()
593                }
594            }
595        }
596    }
597
598    struct ServiceEndpointVisitor;
599
600    impl<'de> Visitor<'de> for ServiceEndpointVisitor {
601        type Value = ServiceEndpoints;
602
603        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
604            formatter.write_str("Expected a service URL or service endpoint definition")
605        }
606
607        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
608        where
609            A: serde::de::MapAccess<'de>,
610        {
611            let mut se = ServiceEndpointProperties::default();
612
613            while let Some(key) = map.next_key::<String>()? {
614                match key.as_str() {
615                    "origins" => se.origins = map.next_value()?,
616                    "registries" => se.registries = map.next_value()?,
617                    _ => {
618                        return Err(serde::de::Error::unknown_field(
619                            &key,
620                            &["origins", "registries"],
621                        ))
622                    }
623                }
624            }
625
626            Ok(ServiceEndpoints(Either::Right(se)))
627        }
628
629        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
630        where
631            E: serde::de::Error,
632        {
633            match Url::parse(v) {
634                Ok(url) => Ok(ServiceEndpoints(Either::Left(url))),
635                Err(e) => Err(serde::de::Error::custom(e)),
636            }
637        }
638    }
639
640    impl<'de> Deserialize<'de> for ServiceEndpoints {
641        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
642        where
643            D: serde::Deserializer<'de>,
644        {
645            deserializer.deserialize_any(ServiceEndpointVisitor)
646        }
647    }
648
649    impl Serialize for ServiceEndpoints {
650        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
651        where
652            S: Serializer,
653        {
654            match &self.0 {
655                Either::Left(url) => serializer.serialize_str(&url.to_string()),
656                Either::Right(properties) => properties.serialize(serializer),
657            }
658        }
659    }
660
661    struct ContextVisitor;
662
663    impl<'de> Visitor<'de> for ContextVisitor {
664        type Value = Context;
665
666        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
667            formatter.write_str("Expecting a URL or set of URLs")
668        }
669
670        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
671        where
672            E: serde::de::Error,
673        {
674            match Url::parse(v) {
675                Ok(res) => Ok(Context(Either::Left(res))),
676                Err(e) => Err(serde::de::Error::custom(e)),
677            }
678        }
679
680        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
681        where
682            A: serde::de::SeqAccess<'de>,
683        {
684            let mut set = BTreeSet::default();
685
686            while let Some(elem) = seq.next_element::<String>()? {
687                match Url::parse(&elem) {
688                    Ok(res) => {
689                        set.insert(res);
690                    }
691                    Err(e) => return Err(serde::de::Error::custom(e)),
692                }
693            }
694
695            Ok(Context(Either::Right(set)))
696        }
697    }
698
699    impl<'de> Deserialize<'de> for Context {
700        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
701        where
702            D: serde::Deserializer<'de>,
703        {
704            deserializer.deserialize_any(ContextVisitor)
705        }
706    }
707
708    impl Serialize for Context {
709        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
710        where
711            S: Serializer,
712        {
713            match &self.0 {
714                Either::Left(url) => serializer.serialize_str(&url.to_string()),
715                Either::Right(set) => set.serialize(serializer),
716            }
717        }
718    }
719
720    struct VerificationMethodTypeVisitor;
721
722    impl<'de> Visitor<'de> for VerificationMethodTypeVisitor {
723        type Value = VerificationMethodType;
724
725        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
726            formatter.write_str("Expected a valid verification method type")
727        }
728
729        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
730        where
731            E: serde::de::Error,
732        {
733            match VerificationMethodType::from_str(v) {
734                Ok(typ) => Ok(typ),
735                Err(e) => Err(serde::de::Error::custom(e)),
736            }
737        }
738    }
739
740    impl<'de> Deserialize<'de> for VerificationMethodType {
741        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
742        where
743            D: serde::Deserializer<'de>,
744        {
745            deserializer.deserialize_str(VerificationMethodTypeVisitor)
746        }
747    }
748
749    impl Serialize for VerificationMethodType {
750        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
751        where
752            S: Serializer,
753        {
754            serializer.serialize_str(&self.to_string())
755        }
756    }
757
758    impl Serialize for ServiceType {
759        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
760        where
761            S: Serializer,
762        {
763            serializer.serialize_str(&self.to_string())
764        }
765    }
766}