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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::str::FromStr;
use std::convert::TryInto;

use crypto::hashes::blake2b::Blake2b256;
use crypto::hashes::Digest;
use serde;
use serde::Deserialize;
use serde::Serialize;

use identity_core::common::KeyComparable;
use identity_core::utils::BaseEncoding;
use identity_did::did::BaseDIDUrl;
use identity_did::did::CoreDID;
use identity_did::did::DIDError;
use identity_did::did::DIDUrl;
use identity_did::did::DID;

use crate::did::Segments;
use crate::error::Error;
use crate::error::Result;
use crate::tangle::Network;
use crate::tangle::NetworkName;
use crate::try_construct_did;

// The hash size of BLAKE2b-256 (32-bytes)
const BLAKE2B_256_LEN: usize = 32;

/// A DID URL conforming to the IOTA DID method specification.
///
/// See [`DIDUrl`].
pub type IotaDIDUrl = DIDUrl<IotaDID>;

/// A DID conforming to the IOTA DID method specification.
///
/// This is a thin wrapper around the [`DID`][`CoreDID`] type from the
/// [`identity_did`][`identity_did`] crate.
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[repr(transparent)]
#[serde(into = "CoreDID", try_from = "CoreDID")]
pub struct IotaDID(CoreDID);

impl IotaDID {
  /// The URL scheme for Decentralized Identifiers.
  pub const SCHEME: &'static str = CoreDID::SCHEME;

  /// The IOTA DID method name (`"iota"`).
  pub const METHOD: &'static str = "iota";

  /// The default Tangle network (`"main"`).
  pub const DEFAULT_NETWORK: &'static str = "main";

  /// Converts an owned [`CoreDID`] to an [`IotaDID`].
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  pub fn try_from_core(did: CoreDID) -> Result<Self> {
    Self::check_validity(&did)?;

    Ok(Self(Self::normalize(did)))
  }

  /// Parses an [`IotaDID`] from the given `input`.
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  pub fn parse(input: impl AsRef<str>) -> Result<Self> {
    CoreDID::parse(input).map_err(Into::into).and_then(Self::try_from_core)
  }

  /// Creates a new [`IotaDID`] with a tag derived from the given `public` key.
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input does not form a valid [`IotaDID`].
  pub fn new(public: &[u8]) -> Result<Self> {
    try_construct_did!(public).map_err(Into::into)
  }

  /// Creates a new [`IotaDID`] from the given `public` key and `network`.
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input does not form a valid [`IotaDID`] or the `network` is invalid.
  /// See [`NetworkName`] for validation requirements.
  pub fn new_with_network(public: &[u8], network: impl TryInto<NetworkName>) -> Result<Self> {
    let network_name = network.try_into().map_err(|_| Error::InvalidNetworkName)?;
    try_construct_did!(public, network_name.as_ref()).map_err(Into::into)
  }

  /// Checks if the given `DID` has a valid IOTA DID `method` (i.e. `"iota"`).
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  pub fn check_method<D: DID>(did: &D) -> Result<()> {
    if did.method() != Self::METHOD {
      Err(Error::InvalidDID(DIDError::InvalidMethodName))
    } else {
      Ok(())
    }
  }

  /// Checks if the given `DID` has a valid [`IotaDID`] `method_id`.
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  pub fn check_method_id<D: DID>(did: &D) -> Result<()> {
    let segments: Vec<&str> = did.method_id().split(':').collect();

    if segments.is_empty() || segments.len() > 2 {
      return Err(Error::InvalidDID(DIDError::InvalidMethodId));
    }

    // We checked if `id_segments` was empty so this should not panic
    let mid: &str = segments.last().unwrap();
    let len: usize = BaseEncoding::decode_base58(mid)
      .map_err(|_| Error::InvalidDID(DIDError::InvalidMethodId))?
      .len();

    if len == BLAKE2B_256_LEN {
      Ok(())
    } else {
      Err(Error::InvalidDID(DIDError::InvalidMethodId))
    }
  }

  /// Checks if the given `DID` has a valid [`IotaDID`] network name, e.g. "main", "dev".
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  /// See [`NetworkName`] for validation requirements.
  pub fn check_network<D: DID>(did: &D) -> Result<()> {
    let network_name = Segments(did.method_id()).network();
    NetworkName::validate_network_name(network_name)
  }

  /// Checks if the given `DID` is valid according to the [`IotaDID`] method specification.
  ///
  /// # Errors
  ///
  /// Returns `Err` if the input is not a valid [`IotaDID`].
  pub fn check_validity<D: DID>(did: &D) -> Result<()> {
    Self::check_method(did)?;
    Self::check_method_id(did)?;
    Self::check_network(did)?;

    Ok(())
  }

  /// Returns a `bool` indicating if the given `DID` is valid according to the
  /// [`IotaDID`] method specification.
  pub fn is_valid(did: &CoreDID) -> bool {
    Self::check_validity(did).is_ok()
  }

  /// Returns the Tangle `network` of the `DID`, if it is valid.
  pub fn network(&self) -> Result<Network> {
    Network::try_from_name(self.network_str().to_owned())
  }

  /// Returns the Tangle `network` name of the `DID`.
  pub fn network_str(&self) -> &str {
    self.segments().network()
  }

  /// Returns the unique Tangle tag of the `DID`.
  pub fn tag(&self) -> &str {
    self.segments().tag()
  }

  #[doc(hidden)]
  pub fn segments(&self) -> Segments<'_> {
    Segments(self.method_id())
  }

  /// Normalizes the DID `method_id` by removing the default network segment if present.
  ///
  /// E.g.
  /// - `"did:iota:main:123" -> "did:iota:123"` is normalized
  /// - `"did:iota:dev:123" -> "did:iota:dev:123"` is unchanged
  fn normalize(mut did: CoreDID) -> CoreDID {
    let segments: Segments<'_> = Segments(did.method_id());

    if segments.count() == 2 && segments.network() == Self::DEFAULT_NETWORK {
      let method_id: String = segments.tag().to_string();
      let _ = did
        .set_method_id(method_id)
        .expect("this method_id is from a valid did");
    }

    did
  }

  // Note: Must be `pub` for the `did` macro.
  #[doc(hidden)]
  pub fn encode_key(key: &[u8]) -> String {
    BaseEncoding::encode_base58(&Blake2b256::digest(key))
  }
}

impl DID for IotaDID {
  /// Returns the [`IotaDID`] scheme. See [`DID::SCHEME`].
  fn scheme(&self) -> &'static str {
    self.0.scheme()
  }

  /// Returns the [`IotaDID`] authority.
  fn authority(&self) -> &str {
    self.0.authority()
  }

  /// Returns the [`IotaDID`] method name.
  fn method(&self) -> &str {
    self.0.method()
  }

  /// Returns the [`IotaDID`] method-specific ID.
  fn method_id(&self) -> &str {
    self.0.method_id()
  }

  /// Returns the serialized [`IotaDID`].
  ///
  /// This is fast since the serialized value is stored in the [`DID`].
  fn as_str(&self) -> &str {
    self.0.as_str()
  }

  /// Consumes the [`IotaDID`] and returns the serialization.
  fn into_string(self) -> String {
    self.0.into_string()
  }

  /// Creates a new [`IotaDIDUrl`] by joining with a relative DID Url string.
  ///
  /// # Errors
  ///
  /// Returns `Err` if any base or relative DID segments are invalid.
  fn join(self, segment: impl AsRef<str>) -> std::result::Result<DIDUrl<Self>, DIDError> {
    self.into_url().join(segment)
  }

  fn to_url(&self) -> DIDUrl<Self> {
    DIDUrl::new(self.clone(), None)
  }

  fn into_url(self) -> DIDUrl<Self> {
    DIDUrl::new(self, None)
  }
}

impl Display for IotaDID {
  fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
    write!(f, "{}", self.0)
  }
}

impl Debug for IotaDID {
  fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
    write!(f, "{}", self.0)
  }
}

impl AsRef<CoreDID> for IotaDID {
  fn as_ref(&self) -> &CoreDID {
    &self.0
  }
}

impl From<IotaDID> for CoreDID {
  fn from(other: IotaDID) -> Self {
    other.0
  }
}

impl TryFrom<BaseDIDUrl> for IotaDID {
  type Error = Error;

  fn try_from(other: BaseDIDUrl) -> Result<Self, Self::Error> {
    let core_did: CoreDID = CoreDID::try_from(other)?;
    Self::try_from(core_did)
  }
}

impl TryFrom<CoreDID> for IotaDID {
  type Error = Error;

  fn try_from(other: CoreDID) -> Result<Self, Self::Error> {
    Self::try_from_core(other)
  }
}

impl FromStr for IotaDID {
  type Err = Error;

  fn from_str(string: &str) -> Result<Self, Self::Err> {
    Self::parse(string)
  }
}

impl TryFrom<&str> for IotaDID {
  type Error = Error;

  fn try_from(other: &str) -> Result<Self, Self::Error> {
    Self::parse(other)
  }
}

impl TryFrom<String> for IotaDID {
  type Error = Error;

  fn try_from(other: String) -> Result<Self, Self::Error> {
    Self::parse(other)
  }
}

impl From<IotaDID> for String {
  fn from(did: IotaDID) -> Self {
    did.into_string()
  }
}

impl KeyComparable for IotaDID {
  type Key = CoreDID;

  #[inline]
  fn key(&self) -> &Self::Key {
    self.as_ref()
  }
}

#[cfg(test)]
mod tests {
  use identity_core::crypto::KeyPair;
  use identity_core::crypto::KeyType;
  use identity_did::did::CoreDID;
  use identity_did::did::DID;

  use crate::did::IotaDID;
  use crate::did::IotaDIDUrl;

  const TAG: &str = "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV";

  #[test]
  fn test_parse_did_valid() {
    assert!(IotaDID::parse(format!("did:iota:{}", TAG)).is_ok());
    assert!(IotaDID::parse(format!("did:iota:main:{}", TAG)).is_ok());
    assert!(IotaDID::parse(format!("did:iota:dev:{}", TAG)).is_ok());
    assert!(IotaDID::parse(format!("did:iota:custom:{}", TAG)).is_ok());
  }

  #[test]
  fn test_parse_did_url_valid() {
    assert!(IotaDIDUrl::parse(format!("did:iota:{}", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:{}#fragment", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:{}?somequery=somevalue", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:{}?somequery=somevalue#fragment", TAG)).is_ok());

    assert!(IotaDIDUrl::parse(format!("did:iota:main:{}", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:main:{}#fragment", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:main:{}?somequery=somevalue", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:main:{}?somequery=somevalue#fragment", TAG)).is_ok());

    assert!(IotaDIDUrl::parse(format!("did:iota:dev:{}", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:dev:{}#fragment", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:dev:{}?somequery=somevalue", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:dev:{}?somequery=somevalue#fragment", TAG)).is_ok());

    assert!(IotaDIDUrl::parse(format!("did:iota:custom:{}", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:custom:{}#fragment", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:custom:{}?somequery=somevalue", TAG)).is_ok());
    assert!(IotaDIDUrl::parse(format!("did:iota:custom:{}?somequery=somevalue#fragment", TAG)).is_ok());
  }

  #[test]
  fn test_parse_did_invalid() {
    // A non-"iota" DID method is invalid.
    assert!(IotaDID::parse("did:foo::").is_err());
    // An empty DID method is invalid.
    assert!(IotaDID::parse("did:::").is_err());
    assert!(IotaDID::parse(format!("did::main:{}", TAG)).is_err());
    // A non-"iota" DID method is invalid.
    assert!(IotaDID::parse("did:iota---::").is_err());
    // An empty `iota-specific-idstring` is invalid.
    assert!(IotaDID::parse("did:iota:").is_err());
    // Too many components is invalid.
    assert!(IotaDID::parse(format!("did:iota:custom:shard-1:random:{}", TAG)).is_err());
    assert!(IotaDID::parse(format!("did:iota:custom:random:{}", TAG)).is_err());
    // Explicit empty network name is invalid (omitting it is still fine)
    assert!(IotaDID::parse(format!("did:iota::{}", TAG)).is_err());
    // Invalid network name is invalid.
    assert!(IotaDID::parse(format!("did:iota:Invalid-Network:{}", TAG)).is_err());
  }

  #[test]
  fn test_from_did() {
    let key: String = IotaDID::encode_key(b"123");

    let did: CoreDID = format!("did:iota:{}", key).parse().unwrap();
    let iota_did = IotaDID::try_from_core(did).unwrap();
    assert_eq!(iota_did.network_str(), "main");
    assert_eq!(iota_did.tag(), key);

    let did: CoreDID = "did:iota:123".parse().unwrap();
    assert!(IotaDID::try_from_core(did).is_err());

    let did: CoreDID = format!("did:web:{}", key).parse().unwrap();
    assert!(IotaDID::try_from_core(did).is_err());
  }

  #[test]
  fn test_network() {
    let key: String = IotaDID::encode_key(b"123");

    let did: IotaDID = format!("did:iota:{}", key).parse().unwrap();
    assert_eq!(did.network_str(), "main");

    let did: IotaDID = format!("did:iota:dev:{}", key).parse().unwrap();
    assert_eq!(did.network_str(), "dev");

    let did: IotaDID = format!("did:iota:test:{}", key).parse().unwrap();
    assert_eq!(did.network_str(), "test");

    let did: IotaDID = format!("did:iota:custom:{}", key).parse().unwrap();
    assert_eq!(did.network_str(), "custom");
  }

  #[test]
  fn test_tag() {
    let did: IotaDID = format!("did:iota:{}", TAG).parse().unwrap();
    assert_eq!(did.tag(), TAG);

    let did: IotaDID = format!("did:iota:main:{}", TAG).parse().unwrap();
    assert_eq!(did.tag(), TAG);
  }

  #[test]
  fn test_new() {
    let key: KeyPair = KeyPair::new(KeyType::Ed25519).unwrap();
    let tag: String = IotaDID::encode_key(key.public().as_ref());

    let did: IotaDID = IotaDID::new(key.public().as_ref()).unwrap();
    assert_eq!(did.tag(), tag);
    assert_eq!(did.network_str(), IotaDID::DEFAULT_NETWORK);
  }

  #[test]
  fn test_new_with_network() {
    let key: KeyPair = KeyPair::new(KeyType::Ed25519).unwrap();
    let did: IotaDID = IotaDID::new_with_network(key.public().as_ref(), "foo").unwrap();
    let tag: String = IotaDID::encode_key(key.public().as_ref());

    assert_eq!(did.tag(), tag);
    assert_eq!(did.network_str(), "foo");
  }

  #[test]
  fn test_normalize() {
    let key: KeyPair = KeyPair::new(KeyType::Ed25519).unwrap();
    let tag: String = IotaDID::encode_key(key.public().as_ref());

    // An IotaDID with "main" as the network can be normalized ("main" removed)
    let did1: IotaDID = format!("did:iota:{}", tag).parse().unwrap();
    let did2: IotaDID = format!("did:iota:main:{}", tag).parse().unwrap();
    assert_eq!(did1, did2);
  }

  #[test]
  fn test_setter() {
    let key: KeyPair = KeyPair::new(KeyType::Ed25519).unwrap();
    let did: IotaDID = IotaDID::new(key.public().as_ref()).unwrap();
    let mut did_url: IotaDIDUrl = did.into_url();

    did_url.set_path(Some("/foo")).unwrap();
    did_url.set_query(Some("diff=true")).unwrap();
    did_url.set_fragment(Some("foo")).unwrap();

    assert_eq!(did_url.path(), Some("/foo"));
    assert_eq!(did_url.query(), Some("diff=true"));
    assert_eq!(did_url.fragment(), Some("foo"));
  }
}