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
/// A representation of a 32 byte digest
#[derive(Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub struct Digest(
    #[cfg_attr(feature = "serde", serde(with = "DigestSerialization"))]
    #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::Base58"))]
    [u8; Self::LENGTH],
);

impl Digest {
    pub const LENGTH: usize = 32;
    pub const ZERO: Self = Self([0; Self::LENGTH]);

    pub const fn new(digest: [u8; Self::LENGTH]) -> Self {
        Self(digest)
    }

    #[cfg(feature = "rand")]
    #[cfg_attr(doc_cfg, doc(cfg(feature = "rand")))]
    pub fn generate<R>(mut rng: R) -> Self
    where
        R: rand_core::RngCore + rand_core::CryptoRng,
    {
        let mut buf: [u8; Self::LENGTH] = [0; Self::LENGTH];
        rng.fill_bytes(&mut buf);
        Self::new(buf)
    }

    pub const fn inner(&self) -> &[u8; Self::LENGTH] {
        &self.0
    }

    pub const fn into_inner(self) -> [u8; Self::LENGTH] {
        self.0
    }

    pub const fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    pub fn from_base58<T: AsRef<[u8]>>(base58: T) -> Result<Self, DigestParseError> {
        let mut buf = [0; Self::LENGTH];

        bs58::decode(base58)
            .onto(&mut buf)
            //TODO fix error to contain bs58 parse error
            .map_err(|_| DigestParseError)?;

        Ok(Self(buf))
    }

    pub fn to_base58(&self) -> String {
        self.to_string()
    }

    pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self, DigestParseError> {
        <[u8; Self::LENGTH]>::try_from(bytes.as_ref())
            .map_err(|_| DigestParseError)
            .map(Self)
    }
}

impl std::str::FromStr for Digest {
    type Err = DigestParseError;

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

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

impl AsRef<[u8; Self::LENGTH]> for Digest {
    fn as_ref(&self) -> &[u8; Self::LENGTH] {
        &self.0
    }
}

impl From<Digest> for [u8; Digest::LENGTH] {
    fn from(digest: Digest) -> Self {
        digest.into_inner()
    }
}

impl From<[u8; Self::LENGTH]> for Digest {
    fn from(digest: [u8; Self::LENGTH]) -> Self {
        Self::new(digest)
    }
}

impl std::fmt::Display for Digest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // output size is determined via the following formula:
        //      N * log(256) / log(58) + 1 (round up)
        // where N = 32 this results in a value of 45
        let mut buf = [0; 45];

        let len = bs58::encode(&self.0).onto(&mut buf[..]).unwrap();
        let encoded = std::str::from_utf8(&buf[..len]).unwrap();

        f.write_str(encoded)
    }
}

impl std::fmt::Debug for Digest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Digest")
            .field(&format_args!("\"{}\"", self))
            .finish()
    }
}

impl std::fmt::LowerHex for Digest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if f.alternate() {
            write!(f, "0x")?;
        }

        for byte in self.0 {
            write!(f, "{:02x}", byte)?;
        }

        Ok(())
    }
}

// Unfortunately sui's binary representation of digests is prefixed with its length meaning its
// serialized binary form is 33 bytes long (in bcs) vs a more compact 32 bytes.
#[cfg(feature = "serde")]
type DigestSerialization =
    ::serde_with::As<::serde_with::IfIsHumanReadable<ReadableDigest, ::serde_with::Bytes>>;

#[cfg(feature = "serde")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
struct ReadableDigest;

#[cfg(feature = "serde")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
impl serde_with::SerializeAs<[u8; Digest::LENGTH]> for ReadableDigest {
    fn serialize_as<S>(source: &[u8; Digest::LENGTH], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let digest = Digest::new(*source);
        serde_with::DisplayFromStr::serialize_as(&digest, serializer)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
impl<'de> serde_with::DeserializeAs<'de, [u8; Digest::LENGTH]> for ReadableDigest {
    fn deserialize_as<D>(deserializer: D) -> Result<[u8; Digest::LENGTH], D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let digest: Digest = serde_with::DisplayFromStr::deserialize_as(deserializer)?;
        Ok(digest.into_inner())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DigestParseError;

impl std::fmt::Display for DigestParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "Unable to parse Digest (must be Base58 string of length {})",
            Digest::LENGTH
        )
    }
}

impl std::error::Error for DigestParseError {}

//
// Implement Various Digest wrappers
//

macro_rules! impl_digest {
    ($t:ident) => {
        #[derive(Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
        #[cfg_attr(
            feature = "serde",
            derive(serde_derive::Serialize, serde_derive::Deserialize)
        )]
        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
        #[cfg_attr(test, derive(test_strategy::Arbitrary))]
        pub struct $t(Digest);

        impl $t {
            pub const LENGTH: usize = Digest::LENGTH;
            pub const ZERO: Self = Self::new([0; Self::LENGTH]);

            pub const fn new(digest: [u8; Self::LENGTH]) -> Self {
                Self(Digest::new(digest))
            }

            #[cfg(feature = "rand")]
            #[cfg_attr(doc_cfg, doc(cfg(feature = "rand")))]
            pub fn generate<R>(rng: R) -> Self
            where
                R: rand_core::RngCore + rand_core::CryptoRng,
            {
                Self(Digest::generate(rng))
            }

            pub const fn inner(&self) -> &[u8; Self::LENGTH] {
                self.0.inner()
            }

            pub const fn into_inner(self) -> [u8; Self::LENGTH] {
                self.0.into_inner()
            }

            pub const fn as_bytes(&self) -> &[u8] {
                self.0.as_bytes()
            }

            pub fn from_base58<T: AsRef<[u8]>>(base58: T) -> Result<Self, DigestParseError> {
                Digest::from_base58(base58).map(Self)
            }

            #[allow(clippy::wrong_self_convention)]
            pub fn to_base58(&self) -> String {
                self.to_string()
            }

            pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self, DigestParseError> {
                Digest::from_bytes(bytes).map(Self)
            }
        }

        impl std::str::FromStr for $t {
            type Err = DigestParseError;

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

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

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

        impl From<$t> for [u8; $t::LENGTH] {
            fn from(digest: $t) -> Self {
                digest.into_inner()
            }
        }

        impl From<[u8; Self::LENGTH]> for $t {
            fn from(digest: [u8; Self::LENGTH]) -> Self {
                Self::new(digest)
            }
        }

        impl From<Digest> for $t {
            fn from(digest: Digest) -> Self {
                Self(digest)
            }
        }

        impl From<$t> for Digest {
            fn from(digest: $t) -> Self {
                digest.0
            }
        }

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

        impl std::fmt::Debug for $t {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_tuple(stringify!($t))
                    .field(&format_args!("\"{}\"", self))
                    .finish()
            }
        }

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

impl_digest!(CheckpointDigest);
impl_digest!(CheckpointContentsDigest);
impl_digest!(TransactionDigest);
impl_digest!(TransactionEffectsDigest);
impl_digest!(TransactionEventsDigest);
impl_digest!(ObjectDigest);
impl_digest!(ConsensusCommitDigest);
impl_digest!(EffectsAuxiliaryDataDigest);

// Don't implement like the other digest types since this isn't intended to be serialized
pub type SigningDigest = [u8; Digest::LENGTH];

#[cfg(test)]
mod test {
    use super::*;
    use test_strategy::proptest;

    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::wasm_bindgen_test as test;

    #[proptest]
    fn roundtrip_display_fromstr(digest: Digest) {
        let s = digest.to_string();
        let d = s.parse::<Digest>().unwrap();
        assert_eq!(digest, d);
    }
}