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
use noosphere_collections::hamt::Hash as HamtHash;
use serde::{Deserialize, Serialize};
use std::{fmt::Display, hash::Hash, ops::Deref};

/// A helper to stamp out trait implementations that promote coherence between
/// Rust strings and a given wrapper type
macro_rules! string_coherent {
    ($wrapper:ty) => {
        impl Deref for $wrapper {
            type Target = String;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl Hash for $wrapper {
            fn hash<H>(&self, hasher: &mut H)
            where
                H: std::hash::Hasher,
            {
                Hash::hash(&self.0, hasher)
            }
        }

        impl HamtHash for $wrapper {
            fn hash<H>(&self, hasher: &mut H)
            where
                H: std::hash::Hasher,
            {
                Hash::hash(&self.0, hasher)
            }
        }

        impl From<&str> for $wrapper {
            fn from(value: &str) -> Self {
                Self(value.to_owned())
            }
        }

        impl From<String> for $wrapper {
            fn from(value: String) -> Self {
                Self(value)
            }
        }

        impl From<$wrapper> for String {
            fn from(value: $wrapper) -> Self {
                value.0
            }
        }

        impl<'a> From<&'a $wrapper> for &'a str {
            fn from(value: &'a $wrapper) -> Self {
                &value.0
            }
        }

        impl PartialEq<String> for $wrapper {
            fn eq(&self, other: &String) -> bool {
                &self.0 == other
            }
        }

        impl PartialEq<$wrapper> for String {
            fn eq(&self, other: &$wrapper) -> bool {
                self == &other.0
            }
        }

        impl PartialEq<str> for $wrapper {
            fn eq(&self, other: &str) -> bool {
                &self.0 == other
            }
        }

        impl PartialEq<$wrapper> for str {
            fn eq(&self, other: &$wrapper) -> bool {
                self == &other.0
            }
        }

        impl PartialEq<&str> for $wrapper {
            fn eq(&self, other: &&str) -> bool {
                &self.0 == *other
            }
        }

        impl<'a> PartialEq<$wrapper> for &'a str {
            fn eq(&self, other: &$wrapper) -> bool {
                **self == *other.0
            }
        }

        impl Display for $wrapper {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                Display::fmt(&self.0, f)
            }
        }

        impl AsRef<[u8]> for $wrapper {
            fn as_ref(&self) -> &[u8] {
                self.0.as_ref()
            }
        }
    };
}

/// A DID, aka a Decentralized Identifier, is a string that can be parsed and
/// resolved into a so-called DID Document, usually in order to obtain PKI
/// details related to a particular user or process.
///
/// See: <https://en.wikipedia.org/wiki/Decentralized_identifier>
/// See: <https://www.w3.org/TR/did-core/>
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Did(pub String);

string_coherent!(Did);

/// A JWT, aka a JSON Web Token, is a specialized string-encoding of a
/// particular format of JSON and an associated signature, commonly used for
/// authorization flows on the web, but notably also used by the UCAN spec.
///
/// See: <https://jwt.io/>
/// See: <https://ucan.xyz/>
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Jwt(pub String);

string_coherent!(Jwt);

/// A BIP39-compatible mnemonic phrase that represents the data needed to
/// recover the private half of a cryptographic key pair.
///
/// See: <https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki>
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Mnemonic(pub String);

#[cfg(test)]
mod tests {
    use libipld_cbor::DagCborCodec;
    use noosphere_storage::{block_deserialize, block_serialize};
    use serde::{Deserialize, Serialize};

    use crate::data::Did;

    #[test]
    fn it_serializes_a_did_transparently_as_a_string() {
        #[derive(Serialize, Deserialize)]
        struct FooDid {
            foo: Did,
        }

        #[derive(Serialize, Deserialize)]
        struct FooString {
            foo: String,
        }

        let string_value = String::from("foobar");
        let (did_cid, did_block) = block_serialize::<DagCborCodec, _>(&FooDid {
            foo: Did(string_value.clone()),
        })
        .unwrap();

        let (string_cid, string_block) = block_serialize::<DagCborCodec, _>(&FooString {
            foo: string_value.clone(),
        })
        .unwrap();

        assert_eq!(did_cid, string_cid);
        assert_eq!(did_block, string_block);

        let did_from_string = block_deserialize::<DagCborCodec, FooDid>(&string_block).unwrap();
        let string_from_did = block_deserialize::<DagCborCodec, FooString>(&did_block).unwrap();

        assert_eq!(did_from_string.foo, Did(string_value.clone()));
        assert_eq!(string_from_did.foo, string_value);
    }

    #[test]
    fn it_enables_comparison_to_string_types() {
        let did_str = "did:key:z6MkoE19WHXJzpLqkxbGP7uXdJX38sWZNUWwyjcuCmjhPpUP";
        let did_string = String::from(did_str);
        let did = Did::from(did_str);

        // Did <-> &str
        assert_eq!(did, did_str);
        assert_eq!(did_str, did);

        // Did <-> String
        assert_eq!(did, did_string);
        assert_eq!(did_string, did);

        // &Did <-> &str
        assert_eq!(&did, did_str);
        assert_eq!(did_str, &did);

        // &Did <-> &String
        assert_eq!(&did, &did_string);
        assert_eq!(&did_string, &did);
    }
}