Skip to main content

DidDocument

Struct DidDocument 

Source
#[non_exhaustive]
pub struct DidDocument { pub context: Option<Context>, pub id: Did, pub also_known_as: Vec<Uri>, pub controller: Option<OneOrMany<Did>>, pub verification_method: Vec<VerificationMethod>, pub authentication: Vec<MethodRef>, pub assertion_method: Vec<MethodRef>, pub key_agreement: Vec<MethodRef>, pub capability_invocation: Vec<MethodRef>, pub capability_delegation: Vec<MethodRef>, pub service: Vec<Service>, pub properties: IndexMap<String, Value>, }
Expand description

A DID document (DID Core §5): the core properties as fields, everything else in properties.

The JSON representation is deterministic: @context comes first, then id, the core properties in the order DID Core lists them, and extension properties in insertion order. None and empty lists are omitted. A document parsed from JSON and written again holds the same members with the same values; the bytes are identical when the input already used that order. Extension properties must not use a core property name (see CORE_PROPERTIES); the builder refuses one, and a document whose properties field holds one serializes a duplicate member.

The fields are public for reading and plain mutation; the methods keep the invariants that DID Core requires (unique method and service ids, references that point at listed methods). Deserialization enforces them too: a document that defines one verification method id twice with different content (listed or embedded) is rejected, so no lookup can pick different material for one id, and so is one with two services sharing an id, as DID Core §5.4 requires of a consumer. Embedding the same method under several relationships, as DID Core’s own examples do, is one definition and allowed.

§Examples

use identity_kit::did::{DidDocument, VerificationRelationship};

// DID Core §4.1, Example 1 (with its editorial typo fixed).
let json = r#"{
  "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2020/v1"],
  "id": "did:example:123456789abcdefghi",
  "authentication": [{
    "id": "did:example:123456789abcdefghi#keys-1",
    "type": "Ed25519VerificationKey2020",
    "controller": "did:example:123456789abcdefghi",
    "publicKeyMultibase": "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"
  }]
}"#;
let document: DidDocument = serde_json::from_str(json)?;
assert_eq!(document.id.as_str(), "did:example:123456789abcdefghi");

let key = document.id.join("#keys-1")?;
let method = document.resolve_verification_method(&key, Some(VerificationRelationship::Authentication))?;
assert_eq!(method.public_key_multibase(), Some("zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"));

// The method is embedded under `authentication` and usable for nothing else.
assert!(document.resolve_verification_method(&key, Some(VerificationRelationship::AssertionMethod)).is_err());

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§context: Option<Context>

@context, carried verbatim.

§id: Did

The DID of the subject.

§also_known_as: Vec<Uri>

Other identifiers of the subject.

§controller: Option<OneOrMany<Did>>

The DIDs whose controllers may change this document; omitted when None or empty, and None when read as an empty set.

§verification_method: Vec<VerificationMethod>

Verification methods that relationships may reference.

§authentication: Vec<MethodRef>

authentication

§assertion_method: Vec<MethodRef>

assertionMethod

§key_agreement: Vec<MethodRef>

keyAgreement

§capability_invocation: Vec<MethodRef>

capabilityInvocation

§capability_delegation: Vec<MethodRef>

capabilityDelegation

§service: Vec<Service>

Services.

§properties: IndexMap<String, Value>

Every other property, in insertion order.

Implementations§

Source§

impl DidDocument

Source

pub fn serialize<__S>( __self: &DidDocument, __serializer: __S, ) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Source§

impl<'de> DidDocument

Source

pub fn deserialize<__D>(__deserializer: __D) -> Result<DidDocument, __D::Error>
where __D: Deserializer<'de>,

Source§

impl DidDocument

Source

pub const CORE_PROPERTIES: &'static [&'static str]

The property names DID Core §5 defines, which properties must not contain.

Source

pub fn new(id: Did) -> Self

An empty document for id.

Source

pub fn builder(id: Did) -> DidDocumentBuilder

A builder for a document for id.

Source

pub fn relationship( &self, relationship: VerificationRelationship, ) -> &[MethodRef]

The entries of relationship.

Source

pub fn relationship_mut( &mut self, relationship: VerificationRelationship, ) -> &mut Vec<MethodRef>

The entries of relationship, mutably.

Source

pub fn verification_method(&self, id: &DidUrl) -> Option<&VerificationMethod>

The verification method with id, listed under verificationMethod or embedded in a relationship.

Source

pub fn methods( &self, relationship: Option<VerificationRelationship>, ) -> impl Iterator<Item = &VerificationMethod>

The verification methods usable for relationship, or every method in the document when relationship is None.

References are followed; a reference to a method that is not listed under verificationMethod yields nothing.

Source

pub fn resolve_verification_method( &self, id: &DidUrl, relationship: Option<VerificationRelationship>, ) -> Result<&VerificationMethod, DocumentError>

The verification method id, optionally restricted to those usable for relationship.

id must belong to this document’s DID. The method may be listed under verificationMethod or embedded in a relationship; with a relationship, it must be referenced (absolutely or relatively) or embedded under that relationship.

§Errors
Source

pub fn resolve_method_reference( &self, reference: &DidUrlReference, relationship: Option<VerificationRelationship>, ) -> Result<&VerificationMethod, DocumentError>

resolve_verification_method for a reference that may be relative (#key-1), resolved against this document’s id.

§Errors

As resolve_verification_method.

Source

pub fn insert_verification_method( &mut self, method: VerificationMethod, relationships: impl IntoIterator<Item = VerificationRelationship>, ) -> Result<(), DocumentError>

Adds method under verificationMethod and references it from each of relationships.

§Errors

DocumentError::DuplicateVerificationMethod when a method with that id exists, listed or embedded; the document is unchanged.

Source

pub fn check_unique_ids(&self) -> Result<(), DocumentError>

Checks that every verification method id (listed or embedded) has one definition and that no two services share an id: the invariant the mutating methods keep and deserialization enforces. The same method embedded under several relationships is one definition.

§Errors

DocumentError::DuplicateVerificationMethod naming the first id defined twice with different content, or DocumentError::DuplicateService naming the first repeated service id.

Source

pub fn remove_verification_method( &mut self, id: &DidUrl, ) -> Option<VerificationMethod>

Removes the method id, listed or embedded, and every relationship entry for it.

Source

pub fn attach_relationship( &mut self, id: &DidUrl, relationship: VerificationRelationship, ) -> Result<bool, DocumentError>

References the listed method id from relationship.

Returns whether an entry was added: Ok(false) when the relationship already references or embeds the method.

§Errors

DocumentError::VerificationMethodNotFound when id is not listed under verificationMethod (a reference to an embedded method would dangle).

Source

pub fn detach_relationship( &mut self, id: &DidUrl, relationship: VerificationRelationship, ) -> bool

Removes every entry for the method id from relationship, returning whether there was one.

Source

pub fn service(&self, id: &DidUrl) -> Option<&Service>

The service id.

Source

pub fn insert_service(&mut self, service: Service) -> Result<(), DocumentError>

Adds service.

§Errors

DocumentError::DuplicateService when a service with that id exists.

Source

pub fn remove_service(&mut self, id: &DidUrl) -> Option<Service>

Removes the service id.

Source

pub fn map_dids(&mut self, f: impl FnMut(Did) -> Did)

Rewrites every DID in the document through f: the id, the controllers, the ids and controllers of verification methods (listed and embedded), absolute relationship references and service ids. Relative references, alsoKnownAs and extension properties are left as they are.

This is how a method whose DID depends on the document (a did:web moving domains, a placeholder DID replaced by the registered one) produces its final document.

f is expected to map distinct DIDs to distinct DIDs. Merging two DIDs into one can give two methods or services the same id; that is not checked here, and check_unique_ids reports it.

§Examples
use identity_kit::did::{Did, DidDocument, MethodType, VerificationMaterial, VerificationMethod, VerificationRelationship};

let placeholder = Did::parse("did:example:placeholder")?;
let mut document = DidDocument::new(placeholder.clone());
document.insert_verification_method(
    VerificationMethod::new(
        placeholder.join("#key-1")?,
        MethodType::MULTIKEY,
        placeholder.clone(),
        VerificationMaterial::multibase("z6MkmM42vxfqZQsv4ehtTjFFxQ4sQKS2w6WR7emozFAn5cxu"),
    ),
    [VerificationRelationship::Authentication],
)?;

let registered = Did::parse("did:web:example.com")?;
document.map_dids(|did| if did == placeholder { registered.clone() } else { did });

assert_eq!(document.id, registered);
assert_eq!(document.verification_method[0].id.as_str(), "did:web:example.com#key-1");
assert_eq!(document.verification_method[0].controller, registered);
let key = registered.join("#key-1")?;
assert!(document.resolve_verification_method(&key, Some(VerificationRelationship::Authentication)).is_ok());

Trait Implementations§

Source§

impl Clone for DidDocument

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DidDocument

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for DidDocument

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Reads the document and rejects duplicate verification method or service ids. An empty controller set reads as no controller, which is how it is written.

Source§

impl Eq for DidDocument

Source§

impl PartialEq for DidDocument

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialSchema for DidDocument

Available on crate feature utoipa only.
Source§

fn schema() -> RefOr<Schema>

Return ref or schema of implementing type that can then be used to construct combined schemas.
Source§

impl Serialize for DidDocument

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for DidDocument

Source§

impl ToSchema for DidDocument

Available on crate feature utoipa only.
Source§

fn name() -> Cow<'static, str>

Return name of the schema. Read more
Source§

fn schemas(schemas: &mut Vec<(String, RefOr<Schema>)>)

Implement reference utoipa::openapi::schema::Schemas for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more