multi-hash 1.0.2

Multihash self-describing cryptographic hash data
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
// SPDX-License-Identifier: Apache-2.0
//! Multihash implementation with support for multiple cryptographic hash algorithms
//!
//! This module provides the core [`Multihash`] type and [`Builder`] for creating
//! self-describing hash digests.

use crate::Error;
use core::fmt;
use digest::{Digest, DynDigest, InvalidBufferSize};
use multi_base::Base;
use multi_codec::Codec;
use multi_trait::{Null, TryDecodeFrom};
use multi_util::{BaseEncoded, CodecInfo, DetectedEncoder, EncodingInfo, Varbytes};
use typenum::consts::*;

/// the hash codecs currently supported
pub const HASH_CODECS: [Codec; 23] = [
    Codec::Blake2B224,
    Codec::Blake2B256,
    Codec::Blake2B384,
    Codec::Blake2B512,
    Codec::Blake2S224,
    Codec::Blake2S256,
    Codec::Blake3,
    Codec::Md5,
    Codec::Ripemd128,
    Codec::Ripemd160,
    Codec::Ripemd256,
    Codec::Ripemd320,
    Codec::Sha1,
    Codec::Sha2224,
    Codec::Sha2256,
    Codec::Sha2384,
    Codec::Sha2512,
    Codec::Sha2512224,
    Codec::Sha2512256,
    Codec::Sha3224,
    Codec::Sha3256,
    Codec::Sha3384,
    Codec::Sha3512,
];

/// the safe hash codecs current supported
pub const SAFE_HASH_CODECS: [Codec; 8] = [
    Codec::Blake2B256,
    Codec::Blake2B384,
    Codec::Blake2B512,
    Codec::Blake2S256,
    Codec::Blake3,
    Codec::Sha3256,
    Codec::Sha3384,
    Codec::Sha3512,
];

/// the multicodec sigil for multihash
pub const SIGIL: Codec = Codec::Multihash;

/// a base encoded multihash
pub type EncodedMultihash = BaseEncoded<Multihash, DetectedEncoder>;

#[derive(Clone)]
struct Blake3DynDigest(blake3::Hasher);

impl Blake3DynDigest {
    fn new() -> Self {
        Self(blake3::Hasher::new())
    }
}

impl DynDigest for Blake3DynDigest {
    fn update(&mut self, data: &[u8]) {
        self.0.update(data);
    }

    fn finalize_into(self, buf: &mut [u8]) -> Result<(), InvalidBufferSize> {
        if buf.len() != self.output_size() {
            return Err(InvalidBufferSize);
        }
        buf.copy_from_slice(self.0.finalize().as_bytes());
        Ok(())
    }

    fn finalize_into_reset(&mut self, buf: &mut [u8]) -> Result<(), InvalidBufferSize> {
        if buf.len() != self.output_size() {
            return Err(InvalidBufferSize);
        }
        buf.copy_from_slice(self.0.finalize().as_bytes());
        self.reset();
        Ok(())
    }

    fn reset(&mut self) {
        self.0 = blake3::Hasher::new();
    }

    fn output_size(&self) -> usize {
        blake3::OUT_LEN
    }

    fn box_clone(&self) -> Box<dyn DynDigest> {
        Box::new(self.clone())
    }
}

/// inner implementation of the multihash
#[derive(Clone, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct Multihash {
    /// hash codec
    pub(crate) codec: Codec,

    /// hash value
    pub(crate) hash: Vec<u8>,
}

impl CodecInfo for Multihash {
    /// Return that we are a Multihash object
    fn preferred_codec() -> Codec {
        SIGIL
    }

    /// Return the hashing codec for the multihash
    fn codec(&self) -> Codec {
        self.codec
    }
}

impl EncodingInfo for Multihash {
    fn preferred_encoding() -> Base {
        Base::Base16Lower
    }

    fn encoding(&self) -> Base {
        Self::preferred_encoding()
    }
}

impl From<Multihash> for Vec<u8> {
    fn from(mh: Multihash) -> Vec<u8> {
        let mut v = Vec::default();
        // add in the hash codec
        v.append(&mut mh.codec.into());
        // add in the hash data
        v.append(&mut Varbytes::new(mh.hash).into());
        v
    }
}

impl<'a> TryFrom<&'a [u8]> for Multihash {
    type Error = Error;

    fn try_from(s: &'a [u8]) -> Result<Self, Self::Error> {
        let (mh, _) = Self::try_decode_from(s)?;
        Ok(mh)
    }
}

impl<'a> TryDecodeFrom<'a> for Multihash {
    type Error = Error;

    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        // decode the hashing codec
        let (codec, ptr) = Codec::try_decode_from(bytes)?;
        // decode the hash bytes
        let (hash, ptr) = Varbytes::try_decode_from(ptr)?;
        // pull the inner Vec<u8> out of Varbytes
        let hash = hash.to_inner();
        Ok((Self { codec, hash }, ptr))
    }
}

/// Exposes direct access to the hash data
impl AsRef<[u8]> for Multihash {
    fn as_ref(&self) -> &[u8] {
        self.hash.as_ref()
    }
}

/// Multihashes can have a null value
impl Null for Multihash {
    fn null() -> Self {
        Multihash::default()
    }

    fn is_null(&self) -> bool {
        *self == Multihash::default()
    }
}

impl fmt::Debug for Multihash {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{:?} - {:?} - {}",
            SIGIL,
            self.codec(),
            hex::encode(&self.hash)
        )
    }
}

/// Hash builder that takes the codec and the data and produces a Multihash
#[derive(Clone, Debug, Default)]
pub struct Builder {
    codec: Codec,
    hash: Option<Vec<u8>>,
    base_encoding: Option<Base>,
}

impl Builder {
    /// create a hash with the given codec
    pub fn new(codec: Codec) -> Self {
        Builder {
            codec,
            ..Default::default()
        }
    }

    /// create a new builder from a hash
    pub fn new_from_bytes(codec: Codec, bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
        let mut hasher: Box<dyn DynDigest> = match codec {
            Codec::Blake2B224 => Box::new(blake2::Blake2b::<U28>::new()),
            Codec::Blake2B256 => Box::new(blake2::Blake2b::<U32>::new()),
            Codec::Blake2B384 => Box::new(blake2::Blake2b::<U48>::new()),
            Codec::Blake2B512 => Box::new(blake2::Blake2b::<U64>::new()),
            Codec::Blake2S224 => Box::new(blake2::Blake2s::<U28>::new()),
            Codec::Blake2S256 => Box::new(blake2::Blake2s::<U32>::new()),
            Codec::Blake3 => Box::new(Blake3DynDigest::new()),
            Codec::Md5 => Box::new(md5::Md5::new()),
            Codec::Ripemd128 => Box::new(ripemd::Ripemd128::new()),
            Codec::Ripemd160 => Box::new(ripemd::Ripemd160::new()),
            Codec::Ripemd256 => Box::new(ripemd::Ripemd256::new()),
            Codec::Ripemd320 => Box::new(ripemd::Ripemd320::new()),
            Codec::Sha1 => Box::new(sha1::Sha1::new()),
            Codec::Sha2224 => Box::new(sha2::Sha224::new()),
            Codec::Sha2256 => Box::new(sha2::Sha256::new()),
            Codec::Sha2384 => Box::new(sha2::Sha384::new()),
            Codec::Sha2512 => Box::new(sha2::Sha512::new()),
            Codec::Sha2512224 => Box::new(sha2::Sha512_224::new()),
            Codec::Sha2512256 => Box::new(sha2::Sha512_256::new()),
            Codec::Sha3224 => Box::new(sha3::Sha3_224::new()),
            Codec::Sha3256 => Box::new(sha3::Sha3_256::new()),
            Codec::Sha3384 => Box::new(sha3::Sha3_384::new()),
            Codec::Sha3512 => Box::new(sha3::Sha3_512::new()),
            _ => return Err(Error::unsupported_hash(codec)),
        };

        // hash the data
        hasher.update(bytes.as_ref());
        let hash = hasher.finalize().to_vec();
        Ok(Self {
            codec,
            hash: Some(hash),
            base_encoding: None,
        })
    }

    /// set the hash data
    pub fn with_hash(mut self, hash: impl Into<Vec<u8>>) -> Self {
        self.hash = Some(hash.into());
        self
    }

    /// set the base encoding codec
    pub fn with_base_encoding(mut self, base: Base) -> Self {
        self.base_encoding = Some(base);
        self
    }

    /// build a base encoded multihash
    pub fn try_build_encoded(&self) -> Result<EncodedMultihash, Error> {
        Ok(BaseEncoded::new(
            self.base_encoding
                .unwrap_or_else(Multihash::preferred_encoding),
            self.try_build()?,
        ))
    }

    /// build the multihash by hashing the provided data
    pub fn try_build(&self) -> Result<Multihash, Error> {
        Ok(Multihash {
            codec: self.codec,
            hash: self.hash.clone().ok_or(Error::MissingHash)?,
        })
    }
}

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

    #[test]
    fn test_matrix() {
        let hashers = vec![
            Codec::Blake2B224,
            Codec::Blake2B256,
            Codec::Blake2B384,
            Codec::Blake2B512,
            Codec::Blake2S224,
            Codec::Blake2S256,
            Codec::Blake3,
            Codec::Md5,
            Codec::Ripemd128,
            Codec::Ripemd160,
            Codec::Ripemd256,
            Codec::Ripemd320,
            Codec::Sha1,
            Codec::Sha2224,
            Codec::Sha2256,
            Codec::Sha2384,
            Codec::Sha2512,
            Codec::Sha2512224,
            Codec::Sha2512256,
            Codec::Sha3224,
            Codec::Sha3256,
            Codec::Sha3384,
            Codec::Sha3512,
        ];

        let bases = vec![
            Base::Base2,
            Base::Base8,
            Base::Base10,
            Base::Base16Lower,
            Base::Base16Upper,
            Base::Base32Lower,
            Base::Base32Upper,
            Base::Base32PadLower,
            Base::Base32PadUpper,
            Base::Base32HexLower,
            Base::Base32HexUpper,
            Base::Base32HexPadLower,
            Base::Base32HexPadUpper,
            Base::Base32Z,
            Base::Base36Lower,
            Base::Base36Upper,
            Base::Base58Flickr,
            Base::Base58Btc,
            Base::Base64,
            Base::Base64Pad,
            Base::Base64Url,
            Base::Base64UrlPad,
        ];

        for h in &hashers {
            for b in &bases {
                let mh1 = Builder::new_from_bytes(*h, b"for great justice, move every zig!")
                    .unwrap()
                    .with_base_encoding(*b)
                    .try_build_encoded()
                    .unwrap();
                //println!("{:?}", mh1);
                let s = mh1.to_string();
                assert_eq!(mh1, EncodedMultihash::try_from(s.as_str()).unwrap());
            }
        }
    }

    #[test]
    fn test_binary_roundtrip() {
        let mh1 = Builder::new_from_bytes(Codec::Sha3384, b"for great justice, move every zig!")
            .unwrap()
            .try_build()
            .unwrap();
        let v: Vec<u8> = mh1.clone().into();
        let mh2 = Multihash::try_from(v.as_ref()).unwrap();
        assert_eq!(mh1, mh2);
    }

    #[test]
    fn test_encoded() {
        let mh = Builder::new_from_bytes(Codec::Sha3256, b"for great justice, move every zig!")
            .unwrap()
            .with_base_encoding(Base::Base58Btc)
            .try_build_encoded()
            .unwrap();
        let s = mh.to_string();
        println!("{:?}", mh);
        println!("{s}");
        assert_eq!(mh, EncodedMultihash::try_from(s.as_str()).unwrap());
    }

    #[test]
    fn test_matching() {
        let mh1 = Builder::new_from_bytes(Codec::Sha3256, b"for great justice, move every zig!")
            .unwrap()
            .try_build()
            .unwrap();
        let mh2 = Multihash::try_from(
            hex::decode("16206b761d3b2e7675e088e337a82207b55711d3957efdb877a3d261b0ca2c38e201")
                .unwrap()
                .as_ref(),
        )
        .unwrap();
        assert_eq!(mh1, mh2);
    }

    #[test]
    fn test_null() {
        let mh1 = Multihash::null();
        assert!(mh1.is_null());
        let mh2 = Multihash::default();
        assert_eq!(mh1, mh2);
        assert!(mh2.is_null());
    }

    #[test]
    fn test_multihash_sha1() {
        // test cases from: https://github.com/multiformats/multihash?tab=readme-ov-file#example
        let bases = vec![
            (
                Base::Base16Lower,
                "f111488c2f11fb2ce392acb5b2986e640211c4690073e",
            ),
            (Base::Base32Upper, "BCEKIRQXRD6ZM4OJKZNNSTBXGIAQRYRUQA47A"),
            (Base::Base58Btc, "z5dsgvJGnvAfiR3K6HCBc4hcokSfmjj"),
            (Base::Base64, "mERSIwvEfss45KstbKYbmQCEcRpAHPg"),
        ];

        for (b, h) in bases {
            let mh = Builder::new_from_bytes(Codec::Sha1, b"multihash")
                .unwrap()
                .with_base_encoding(b)
                .try_build_encoded()
                .unwrap();
            let s = mh.to_string();
            assert_eq!(h, s.as_str());
        }
    }

    #[test]
    fn test_multihash_sha2_256() {
        // test cases from: https://github.com/multiformats/multihash?tab=readme-ov-file#example
        let bases = vec![
            (
                Base::Base16Lower,
                "f12209cbc07c3f991725836a3aa2a581ca2029198aa420b9d99bc0e131d9f3e2cbe47",
            ),
            (
                Base::Base32Upper,
                "BCIQJZPAHYP4ZC4SYG2R2UKSYDSRAFEMYVJBAXHMZXQHBGHM7HYWL4RY",
            ),
            (
                Base::Base58Btc,
                "zQmYtUc4iTCbbfVSDNKvtQqrfyezPPnFvE33wFmutw9PBBk",
            ),
            (
                Base::Base64,
                "mEiCcvAfD+ZFyWDajqipYHKICkZiqQgudmbwOEx2fPiy+Rw",
            ),
        ];

        for (b, h) in bases {
            let mh = Builder::new_from_bytes(Codec::Sha2256, b"multihash")
                .unwrap()
                .with_base_encoding(b)
                .try_build_encoded()
                .unwrap();
            let s = mh.to_string();
            assert_eq!(h, s.as_str());
        }
    }
}