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
// Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use log::debug;
use log::trace;

use identity_account_storage::storage::Storage;
use identity_account_storage::types::KeyLocation;
use identity_core::common::Fragment;
use identity_core::common::Object;
use identity_core::common::OneOrSet;
use identity_core::common::OrderedSet;
use identity_core::common::Timestamp;
use identity_core::common::Url;
use identity_core::crypto::KeyPair;
use identity_core::crypto::KeyType;
use identity_core::crypto::PrivateKey;
use identity_core::crypto::PublicKey;
use identity_did::did::DID;
use identity_did::service::Service;
use identity_did::service::ServiceEndpoint;
use identity_did::utils::Queryable;
use identity_did::verification::MethodRef;
use identity_did::verification::MethodRelationship;
use identity_did::verification::MethodScope;
use identity_iota_client::tangle::Client;
use identity_iota_client::tangle::SharedPtr;
use identity_iota_core::did::IotaDID;
use identity_iota_core::did::IotaDIDUrl;
use identity_iota_core::document::IotaDocument;
use identity_iota_core::document::IotaService;
use identity_iota_core::document::IotaVerificationMethod;
use identity_iota_core::tangle::NetworkName;

use crate::account::Account;
use crate::error::Result;
use crate::types::IdentitySetup;
use crate::types::MethodContent;
use crate::updates::UpdateError;

pub(crate) async fn create_identity(
  setup: IdentitySetup,
  network: NetworkName,
  store: &dyn Storage,
) -> Result<IotaDocument> {
  let fragment: &str = IotaDocument::DEFAULT_METHOD_FRAGMENT;

  if let Some(private_key) = &setup.private_key {
    KeyPair::try_from_private_key_bytes(KeyType::Ed25519, private_key.as_ref())
      .map_err(|err| UpdateError::InvalidMethodContent(err.to_string()))?;
  };

  let (did, location) = store.did_create(network.clone(), fragment, setup.private_key).await?;

  let public_key: PublicKey = store.key_public(&did, &location).await?;

  let method: IotaVerificationMethod =
    IotaVerificationMethod::new(did.clone(), KeyType::Ed25519, &public_key, fragment)?;

  let document = IotaDocument::from_verification_method(method)?;

  Ok(document)
}

#[derive(Clone, Debug)]
pub(crate) enum Update {
  CreateMethod {
    scope: MethodScope,
    content: MethodContent,
    fragment: String,
  },
  DeleteMethod {
    fragment: String,
  },
  AttachMethodRelationship {
    fragment: String,
    relationships: Vec<MethodRelationship>,
  },
  DetachMethodRelationship {
    fragment: String,
    relationships: Vec<MethodRelationship>,
  },
  CreateService {
    fragment: String,
    type_: String,
    endpoint: ServiceEndpoint,
    properties: Option<Object>,
  },
  DeleteService {
    fragment: String,
  },
  SetController {
    controllers: Option<OneOrSet<IotaDID>>,
  },
  SetAlsoKnownAs {
    urls: OrderedSet<Url>,
  },
}

impl Update {
  pub(crate) async fn process(self, did: &IotaDID, document: &mut IotaDocument, storage: &dyn Storage) -> Result<()> {
    debug!("[Update::process] Update = {:?}", self);
    trace!("[Update::process] Document = {:?}", document);
    trace!("[Update::process] Store = {:?}", storage);

    match self {
      Self::CreateMethod {
        scope,
        content,
        fragment,
      } => {
        let fragment: Fragment = Fragment::new(fragment);

        // Check method identifier is not duplicated.
        let method_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;
        if document.resolve_method(method_url, None).is_some() {
          return Err(crate::Error::DIDError(identity_did::Error::MethodAlreadyExists));
        }

        // Generate or extract the private key and/or retrieve the public key.
        let key_type: KeyType = content.key_type();

        let public: PublicKey = match content {
          MethodContent::GenerateEd25519 | MethodContent::GenerateX25519 => {
            let location: KeyLocation = storage.key_generate(did, key_type, fragment.name()).await?;
            storage.key_public(did, &location).await?
          }
          MethodContent::PrivateEd25519(private_key) | MethodContent::PrivateX25519(private_key) => {
            let location: KeyLocation =
              insert_method_secret(storage, did, key_type, fragment.name(), private_key).await?;
            storage.key_public(did, &location).await?
          }
          MethodContent::PublicEd25519(public_key) => public_key,
          MethodContent::PublicX25519(public_key) => public_key,
        };

        // Insert a new method.
        let method: IotaVerificationMethod =
          IotaVerificationMethod::new(did.clone(), key_type, &public, fragment.name())?;

        document.insert_method(method, scope)?;
      }
      Self::DeleteMethod { fragment } => {
        let fragment: Fragment = Fragment::new(fragment);

        let method_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;

        // Prevent deleting the last method capable of signing the DID document.
        let capability_invocation_set = document.core_document().capability_invocation();
        let is_capability_invocation = capability_invocation_set
          .iter()
          .any(|method_ref| method_ref.id() == &method_url);

        ensure!(
          !(is_capability_invocation && capability_invocation_set.len() == 1),
          UpdateError::InvalidMethodFragment("cannot remove last signing method")
        );

        document.remove_method(&method_url)?;
      }
      Self::AttachMethodRelationship {
        fragment,
        relationships,
      } => {
        let fragment: Fragment = Fragment::new(fragment);

        let method_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;

        for relationship in relationships {
          // Ignore result: attaching is idempotent.
          let _ = document.attach_method_relationship(&method_url, relationship)?;
        }
      }
      Self::DetachMethodRelationship {
        fragment,
        relationships,
      } => {
        let fragment: Fragment = Fragment::new(fragment);

        let method_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;

        // Prevent detaching the last method capable of signing the DID document.
        let capability_invocation_set: &OrderedSet<MethodRef<IotaDID>> =
          document.core_document().capability_invocation();
        let is_capability_invocation = capability_invocation_set
          .iter()
          .any(|method_ref| method_ref.id() == &method_url);

        ensure!(
          !(is_capability_invocation && capability_invocation_set.len() == 1),
          UpdateError::InvalidMethodFragment("cannot remove last signing method")
        );

        for relationship in relationships {
          // Ignore result: detaching is idempotent.
          let _ = document.detach_method_relationship(&method_url, relationship)?;
        }
      }
      Self::CreateService {
        fragment,
        type_,
        endpoint,
        properties,
      } => {
        let fragment = Fragment::new(fragment);
        let did_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;

        // The service must not exist.
        ensure!(
          document.service().query(&did_url).is_none(),
          UpdateError::DuplicateServiceFragment(fragment.name().to_owned()),
        );

        let service: IotaService = Service::builder(properties.unwrap_or_default())
          .id(did_url)
          .service_endpoint(endpoint)
          .type_(type_)
          .build()?;

        document.insert_service(service);
      }
      Self::DeleteService { fragment } => {
        let fragment: Fragment = Fragment::new(fragment);
        let service_url: IotaDIDUrl = did.to_url().join(fragment.identifier())?;

        // The service must exist
        ensure!(
          document.service().query(&service_url).is_some(),
          UpdateError::ServiceNotFound
        );

        document.remove_service(&service_url);
      }
      Self::SetController { controllers } => {
        *document.controller_mut() = controllers;
      }

      Self::SetAlsoKnownAs { urls } => {
        *document.also_known_as_mut() = urls;
      }
    }

    document.metadata.updated = Some(Timestamp::now_utc());

    Ok(())
  }
}

async fn insert_method_secret(
  store: &dyn Storage,
  did: &IotaDID,
  key_type: KeyType,
  fragment: &str,
  private_key: PrivateKey,
) -> Result<KeyLocation> {
  let keypair: KeyPair = KeyPair::try_from_private_key_bytes(key_type, private_key.as_ref())
    .map_err(|err| UpdateError::InvalidMethodContent(err.to_string()))?;

  let location: KeyLocation = KeyLocation::new(key_type, fragment.to_owned(), keypair.public().as_ref());
  std::mem::drop(keypair);

  ensure!(
    !store.key_exists(did, &location).await?,
    UpdateError::DuplicateKeyLocation(location)
  );

  store.key_insert(did, &location, private_key).await?;

  Ok(location)
}

// =============================================================================

// =============================================================================
// Update Builders
impl_update_builder!(
/// Create a new method on an identity.
///
/// # Parameters
/// - `scope`: the scope of the method, defaults to [`MethodScope::default`].
/// - `fragment`: the identifier of the method in the document, required.
/// - `content`: the key material to use for the method or key type to generate.
CreateMethod {
  @default scope MethodScope,
  @required fragment String,
  @required content MethodContent,
});

impl_update_builder!(
/// Delete a method on an identity.
///
/// # Parameters
/// - `fragment`: the identifier of the method in the document, required.
DeleteMethod {
  @required fragment String,
});

impl_update_builder!(
/// Attach one or more verification relationships to a method on an identity.
///
/// # Parameters
/// - `relationships`: the relationships to add, defaults to an empty [`Vec`].
/// - `fragment`: the identifier of the method in the document, required.
AttachMethodRelationship {
  @required fragment String,
  @default relationships Vec<MethodRelationship>,
});

impl<'account, C> AttachMethodRelationshipBuilder<'account, C>
where
  C: SharedPtr<Client>,
{
  #[must_use]
  pub fn relationship(mut self, value: MethodRelationship) -> Self {
    self.relationships.get_or_insert_with(Default::default).push(value);
    self
  }
}

impl_update_builder!(
/// Detaches one or more verification relationships from a method on an identity.
///
/// # Parameters
/// - `relationships`: the relationships to remove, defaults to an empty [`Vec`].
/// - `fragment`: the identifier of the method in the document, required.
DetachMethodRelationship {
  @required fragment String,
  @default relationships Vec<MethodRelationship>,
});

impl<'account, C> DetachMethodRelationshipBuilder<'account, C>
where
  C: SharedPtr<Client>,
{
  #[must_use]
  pub fn relationship(mut self, value: MethodRelationship) -> Self {
    self.relationships.get_or_insert_with(Default::default).push(value);
    self
  }
}

impl_update_builder!(
/// Create a new service on an identity.
///
/// # Parameters
/// - `type_`: the type of the service, e.g. `"LinkedDomains"`, required.
/// - `fragment`: the identifier of the service in the document, required.
/// - `endpoint`: the `ServiceEndpoint` of the service, required.
/// - `properties`: additional properties of the service, optional.
CreateService {
  @required fragment String,
  @required type_ String,
  @required endpoint ServiceEndpoint,
  @optional properties Object,
});

impl_update_builder!(
/// Delete a service on an identity.
///
/// # Parameters
/// - `fragment`: the identifier of the service in the document, required.
DeleteService {
  @required fragment String,
});

impl_update_builder!(
SetController {
    @required controllers Option<OneOrSet<IotaDID>>,
});

impl_update_builder!(
SetAlsoKnownAs {
    @required urls OrderedSet<Url>,
});