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
use std::{borrow::Cow, marker::PhantomData};

use crate::{document::Document, resolution, DIDResolver, DID, DIDURL};
use iref::Iri;
use ssi_claims_core::ProofValidationError;
use ssi_jwk::{JWKResolver, JWK};
use ssi_verification_methods_core::{
    ControllerError, ControllerProvider, GenericVerificationMethod, InvalidVerificationMethod,
    MaybeJwkVerificationMethod, ProofPurposes, ReferenceOrOwnedRef, VerificationMethod,
    VerificationMethodResolutionError, VerificationMethodResolver, VerificationMethodSet,
};

pub struct VerificationMethodDIDResolver<T, M> {
    resolver: T,
    options: resolution::Options,
    method: PhantomData<M>,
}

impl<T: Default, M> Default for VerificationMethodDIDResolver<T, M> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T, M> VerificationMethodDIDResolver<T, M> {
    pub fn new(resolver: T) -> Self {
        Self {
            resolver,
            options: resolution::Options::default(),
            method: PhantomData,
        }
    }

    pub fn new_with_options(resolver: T, options: resolution::Options) -> Self {
        Self {
            resolver,
            options,
            method: PhantomData,
        }
    }

    pub fn resolver(&self) -> &T {
        &self.resolver
    }

    pub fn options(&self) -> &resolution::Options {
        &self.options
    }
}

impl ssi_verification_methods_core::Controller for Document {
    fn allows_verification_method(&self, id: &iref::Iri, proof_purposes: ProofPurposes) -> bool {
        DIDURL::new(id.as_bytes()).is_ok_and(|url| {
            self.verification_relationships
                .contains(&self.id, url, proof_purposes)
        })
    }
}

impl<T: DIDResolver, M> DIDResolver for VerificationMethodDIDResolver<T, M> {
    async fn resolve_representation<'a>(
        &'a self,
        did: &'a DID,
        options: resolution::Options,
    ) -> Result<resolution::Output<Vec<u8>>, resolution::Error> {
        T::resolve_representation(&self.resolver, did, options).await
    }
}

impl<T: DIDResolver, M> ControllerProvider for VerificationMethodDIDResolver<T, M> {
    type Controller<'a> = Document where Self: 'a;

    async fn get_controller<'a>(
        &'a self,
        id: &'a iref::Iri,
    ) -> Result<Option<Document>, ControllerError> {
        if id.scheme().as_str() == "did" {
            match DID::new(id.as_bytes()) {
                Ok(did) => match self.resolver.resolve_with(did, self.options.clone()).await {
                    Ok(output) => Ok(Some(output.document.into_document())),
                    Err(resolution::Error::NotFound) => Ok(None),
                    Err(e) => Err(ControllerError::InternalError(e.to_string())),
                },
                Err(_) => Err(ControllerError::Invalid),
            }
        } else {
            Err(ControllerError::Invalid)
        }
    }
}

// #[async_trait]
impl<T: DIDResolver, M> VerificationMethodResolver for VerificationMethodDIDResolver<T, M>
where
    M: VerificationMethod,
    M: TryFrom<GenericVerificationMethod, Error = InvalidVerificationMethod>,
{
    type Method = M;

    async fn resolve_verification_method_with(
        &self,
        _issuer: Option<&iref::Iri>,
        method: Option<ReferenceOrOwnedRef<'_, M>>,
        options: ssi_verification_methods_core::ResolutionOptions,
    ) -> Result<Cow<M>, VerificationMethodResolutionError> {
        let mut deref_options = self.options.clone();

        if let Some(set) = options.accept {
            if let Some(ty) = set.pick() {
                deref_options.parameters.public_key_format = Some(ty.to_owned());
            }
        }

        match method {
            Some(method) => {
                if method.id().scheme().as_str() == "did" {
                    match DIDURL::new(method.id().as_bytes()) {
                        Ok(url) => {
                            match self.resolver.dereference_with(url, deref_options).await {
                                Ok(deref) => match deref.content.into_verification_method() {
                                    Ok(any_method) => {
                                        Ok(Cow::Owned(M::try_from(any_method.into())?))
                                    }
                                    Err(_) => {
                                        // The IRI is not referring to a verification method.
                                        Err(VerificationMethodResolutionError::NotAVerificationMethod(
                                            method.id().to_string(),
                                        ))
                                    }
                                },
                                Err(e) => {
                                    // Dereferencing failed for some reason.
                                    Err(VerificationMethodResolutionError::InternalError(
                                        e.to_string(),
                                    ))
                                }
                            }
                            // ResolveVerificationMethod::dereference(&self.resolver, url, options)
                        }
                        Err(_) => {
                            // The IRI is not a valid DID URL.
                            Err(VerificationMethodResolutionError::InvalidKeyId(
                                method.id().to_string(),
                            ))
                        }
                    }
                } else {
                    // Not a DID scheme.
                    Err(VerificationMethodResolutionError::UnsupportedKeyId(
                        method.id().to_string(),
                    ))
                }
            }
            None => Err(VerificationMethodResolutionError::MissingVerificationMethod),
        }
    }
}

impl<T: DIDResolver, M> JWKResolver for VerificationMethodDIDResolver<T, M>
where
    M: MaybeJwkVerificationMethod
        + VerificationMethodSet
        + TryFrom<GenericVerificationMethod, Error = InvalidVerificationMethod>,
{
    async fn fetch_public_jwk(
        &self,
        key_id: Option<&str>,
    ) -> Result<Cow<JWK>, ProofValidationError> {
        let vm = match key_id {
            Some(id) => match Iri::new(id) {
                Ok(iri) => Some(ReferenceOrOwnedRef::Reference(iri)),
                Err(_) => return Err(ProofValidationError::MissingPublicKey),
            },
            None => None,
        };

        let options = ssi_verification_methods_core::ResolutionOptions {
            accept: Some(Box::new(M::type_set())),
        };

        self.resolve_verification_method_with(None, vm, options)
            .await?
            .try_to_jwk()
            .map(Cow::into_owned)
            .map(Cow::Owned)
            .ok_or(ProofValidationError::MissingPublicKey)
    }
}