multi-hash 2.0.0

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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// SPDX-License-Identifier: Apache-2.0
//! Error types for multi-hash

/// Errors produced by the multi-hash crate
///
/// All error variants include contextual information to help with debugging
/// and provide actionable error messages.
///
/// # Examples
///
/// ```
/// use multi_hash::Error;
/// use multi_codec::Codec;
///
/// // Unsupported algorithm error includes the codec
/// let err = Error::unsupported_hash(Codec::Identity);
/// assert!(matches!(err, Error::UnsupportedHash { .. }));
///
/// // Missing hash error
/// let err = Error::MissingHash;
/// assert_eq!(err.kind(), "MissingHash");
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Error from multi-codec crate
    ///
    /// This error occurs when codec operations fail, typically due to
    /// invalid codec identifiers or encoding/decoding issues.
    #[error(transparent)]
    Multicodec(#[from] multi_codec::Error),

    /// Error from multi-util crate
    ///
    /// This error occurs when utility operations fail, such as base encoding
    /// or variable-length integer operations.
    #[error(transparent)]
    Multiutil(#[from] multi_util::Error),

    /// Missing hash data
    ///
    /// The multihash builder was used without setting the hash digest data.
    ///
    /// # Resolution
    ///
    /// Call `Builder::with_hash()` to set a digest computed elsewhere. Call
    /// `Builder::update()` to stream data. One of them must run before
    /// `try_build()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    ///
    /// let err = Error::MissingHash;
    /// assert_eq!(err.kind(), "MissingHash");
    /// ```
    #[error(
        "Missing hash data\n\
             The multihash builder requires hash digest data.\n\
             Call with_hash() or update() before try_build()."
    )]
    MissingHash,

    /// Unsupported hash algorithm
    ///
    /// The specified codec is not a supported cryptographic hash algorithm
    /// or is not implemented in this crate.
    ///
    /// # Context
    ///
    /// - `codec`: The unsupported codec that was requested
    ///
    /// # Resolution
    ///
    /// Use one of the supported hash algorithms. See the `HASH_CODECS` or
    /// `SAFE_HASH_CODECS` constants for the list of supported algorithms.
    /// With the `fips` feature enabled, the `FIPS_CODECS` and
    /// `SAFE_FIPS_CODECS` constants list the NIST FIPS approved algorithms.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::unsupported_hash(Codec::Identity);
    /// assert!(matches!(err, Error::UnsupportedHash { .. }));
    /// ```
    #[error(
        "Unsupported hash algorithm: {codec:?}\n\
             The codec {codec:?} is not a supported cryptographic hash algorithm.\n\
             See HASH_CODECS or SAFE_HASH_CODECS for supported algorithms."
    )]
    UnsupportedHash {
        /// The unsupported codec that was requested
        codec: multi_codec::Codec,
    },

    /// Invalid hash digest length
    ///
    /// The provided hash digest length does not match the expected output
    /// size for the specified hash algorithm.
    ///
    /// # Context
    ///
    /// - `algorithm`: The hash algorithm codec
    /// - `expected`: The expected digest length in bytes
    /// - `actual`: The actual digest length provided
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::invalid_digest_length(Codec::Sha2256, 32, 16);
    /// assert!(matches!(err, Error::InvalidDigestLength { .. }));
    /// ```
    #[error(
        "Invalid hash digest length for {algorithm:?}\n\
             Expected {expected} bytes for {algorithm:?}, but got {actual} bytes.\n\
             Ensure the hash digest matches the algorithm's output size."
    )]
    InvalidDigestLength {
        /// The hash algorithm
        algorithm: multi_codec::Codec,
        /// Expected digest length in bytes
        expected: usize,
        /// Actual digest length provided
        actual: usize,
    },

    /// XOF output length required
    ///
    /// The builder tried to finalize an extendable-output codec
    /// (`Blake3`, `Shake128`, or `Shake256`) without an output length set
    /// through `Builder::output_len()`.
    ///
    /// # Context
    ///
    /// - `codec`: The XOF codec that requested an output length
    ///
    /// # Resolution
    ///
    /// Call `Builder::output_len()` with a value from 1 to `MAX_HASH_LENGTH`
    /// bytes before `try_build()` or `try_build_encoded()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::output_len_required(Codec::Shake128);
    /// assert!(matches!(err, Error::OutputLenRequired { .. }));
    /// ```
    #[error(
        "XOF output length required for {codec:?}\n\
             The {codec:?} XOF needs an output length set through Builder::output_len().\n\
             Set a value from 1 to MAX_HASH_LENGTH bytes before try_build()."
    )]
    OutputLenRequired {
        /// the XOF codec that requested an output length
        codec: multi_codec::Codec,
    },

    /// Invalid XOF output length
    ///
    /// The requested XOF output length is outside the allowed range of 1 to
    /// `MAX_HASH_LENGTH` bytes. The length is checked before any allocation
    /// or squeeze.
    ///
    /// # Context
    ///
    /// - `codec`: The XOF codec with the invalid output length
    /// - `output_len`: The requested output length in bytes
    /// - `max`: The maximum allowed output length in bytes
    ///
    /// # Resolution
    ///
    /// Set a value from 1 to `MAX_HASH_LENGTH` bytes through
    /// `Builder::output_len()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::output_len_invalid(Codec::Shake256, 0, 16 * 1024 * 1024);
    /// assert!(matches!(err, Error::OutputLenInvalid { .. }));
    /// ```
    #[error(
        "Invalid XOF output length for {codec:?}\n\
             The requested output length {output_len} is outside the allowed\n\
             range of 1 to {max} bytes for {codec:?}."
    )]
    OutputLenInvalid {
        /// the XOF codec with the invalid output length
        codec: multi_codec::Codec,
        /// the requested output length in bytes
        output_len: usize,
        /// the maximum allowed output length in bytes
        max: usize,
    },

    /// Hash computation failed
    ///
    /// An error occurred while computing the cryptographic hash.
    ///
    /// # Context
    ///
    /// - `algorithm`: The hash algorithm that failed
    /// - `message`: Description of what went wrong
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::hash_compute_failed(Codec::Sha2256, "input too large");
    /// assert!(matches!(err, Error::HashComputeFailed { .. }));
    /// ```
    #[error("Hash computation failed for {algorithm:?}: {message}")]
    HashComputeFailed {
        /// The hash algorithm
        algorithm: multi_codec::Codec,
        /// Error message
        message: String,
    },
}

impl Error {
    /// Create an `UnsupportedHash` error
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::unsupported_hash(Codec::Identity);
    /// assert!(matches!(err, Error::UnsupportedHash { .. }));
    /// ```
    #[must_use]
    pub const fn unsupported_hash(codec: multi_codec::Codec) -> Self {
        Self::UnsupportedHash { codec }
    }

    /// Create an `InvalidDigestLength` error
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::invalid_digest_length(Codec::Sha2256, 32, 16);
    /// assert!(matches!(err, Error::InvalidDigestLength { .. }));
    /// ```
    #[must_use]
    pub const fn invalid_digest_length(
        algorithm: multi_codec::Codec,
        expected: usize,
        actual: usize,
    ) -> Self {
        Self::InvalidDigestLength {
            algorithm,
            expected,
            actual,
        }
    }

    /// Create an `OutputLenRequired` error
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::output_len_required(Codec::Shake128);
    /// assert!(matches!(err, Error::OutputLenRequired { .. }));
    /// ```
    #[must_use]
    pub const fn output_len_required(codec: multi_codec::Codec) -> Self {
        Self::OutputLenRequired { codec }
    }

    /// Create an `OutputLenInvalid` error
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::output_len_invalid(Codec::Shake256, 0, 16 * 1024 * 1024);
    /// assert!(matches!(err, Error::OutputLenInvalid { .. }));
    /// ```
    #[must_use]
    pub const fn output_len_invalid(
        codec: multi_codec::Codec,
        output_len: usize,
        max: usize,
    ) -> Self {
        Self::OutputLenInvalid {
            codec,
            output_len,
            max,
        }
    }

    /// Create a `HashComputeFailed` error
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::hash_compute_failed(Codec::Sha2256, "internal error");
    /// assert!(matches!(err, Error::HashComputeFailed { .. }));
    /// ```
    pub fn hash_compute_failed(algorithm: multi_codec::Codec, message: impl Into<String>) -> Self {
        Self::HashComputeFailed {
            algorithm,
            message: message.into(),
        }
    }

    /// Get the error kind as a string
    ///
    /// Returns a short identifier for the error type, useful for
    /// programmatic error handling and logging.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::MissingHash;
    /// assert_eq!(err.kind(), "MissingHash");
    ///
    /// let err = Error::unsupported_hash(Codec::Identity);
    /// assert_eq!(err.kind(), "UnsupportedHash");
    /// ```
    #[must_use]
    pub const fn kind(&self) -> &str {
        match self {
            Self::Multicodec(_) => "Multicodec",
            Self::Multiutil(_) => "Multiutil",
            Self::MissingHash => "MissingHash",
            Self::UnsupportedHash { .. } => "UnsupportedHash",
            Self::InvalidDigestLength { .. } => "InvalidDigestLength",
            Self::OutputLenRequired { .. } => "OutputLenRequired",
            Self::OutputLenInvalid { .. } => "OutputLenInvalid",
            Self::HashComputeFailed { .. } => "HashComputeFailed",
        }
    }

    /// Get additional context about the error
    ///
    /// Returns human-readable context information that can help
    /// diagnose the error.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_hash::Error;
    /// use multi_codec::Codec;
    ///
    /// let err = Error::unsupported_hash(Codec::Identity);
    /// let context = err.context();
    /// assert!(!context.is_empty());
    /// ```
    #[must_use]
    pub fn context(&self) -> String {
        match self {
            Self::Multicodec(e) => format!("Multicodec error: {e}"),
            Self::Multiutil(e) => format!("Multiutil error: {e}"),
            Self::MissingHash => "Missing hash data in builder".to_string(),
            Self::UnsupportedHash { codec } => format!("Unsupported hash: {codec:?}"),
            Self::InvalidDigestLength {
                algorithm,
                expected,
                actual,
            } => format!(
                "Invalid digest length for {algorithm:?}: expected {expected}, got {actual}"
            ),
            Self::OutputLenRequired { codec } => {
                format!("XOF output length required for {codec:?}")
            }
            Self::OutputLenInvalid {
                codec,
                output_len,
                max,
            } => format!(
                "Invalid XOF output length for {codec:?}: {output_len} is outside the allowed range of 1 to {max}"
            ),
            Self::HashComputeFailed { algorithm, message } => {
                format!("Hash computation failed for {algorithm:?}: {message}")
            }
        }
    }
}

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

    #[test]
    fn test_missing_hash_error() {
        let err = Error::MissingHash;
        assert_eq!(err.kind(), "MissingHash");
        assert!(err.to_string().contains("Missing hash data"));
    }

    #[test]
    fn test_unsupported_hash_error() {
        let err = Error::unsupported_hash(Codec::Identity);
        assert_eq!(err.kind(), "UnsupportedHash");
        let msg = err.to_string();
        // Check error message is present and non-empty
        assert_ne!(msg, "");
        assert!(msg.len() > 10);
        // Check context contains codec info
        let context = err.context();
        assert_ne!(context, "");
    }

    #[test]
    fn test_invalid_digest_length_error() {
        let err = Error::invalid_digest_length(Codec::Sha2256, 32, 16);
        assert_eq!(err.kind(), "InvalidDigestLength");
        let msg = err.to_string();
        assert!(msg.contains("32"));
        assert!(msg.contains("16"));
    }

    #[test]
    fn test_hash_compute_failed_error() {
        let err = Error::hash_compute_failed(Codec::Sha2256, "test failure");
        assert_eq!(err.kind(), "HashComputeFailed");
        assert!(err.to_string().contains("test failure"));
    }

    #[test]
    fn test_output_len_required_error() {
        let err = Error::output_len_required(Codec::Shake128);
        assert_eq!(err.kind(), "OutputLenRequired");
        assert!(err.to_string().contains("output length"));
        let context = err.context();
        assert_ne!(context, "");
        assert!(context.contains("Shake128") || context.contains("shake-128"));
    }

    #[test]
    fn test_output_len_invalid_error() {
        let err = Error::output_len_invalid(Codec::Shake256, 0, 16 * 1024 * 1024);
        assert_eq!(err.kind(), "OutputLenInvalid");
        let msg = err.to_string();
        assert!(msg.contains('0'));
        assert!(msg.contains("16777216"));
        let context = err.context();
        assert_ne!(context, "");
        assert!(context.contains("Shake256") || context.contains("shake-256"));
    }

    #[test]
    fn test_error_kind_uniqueness() {
        let errors = [
            Error::MissingHash,
            Error::unsupported_hash(Codec::Identity),
            Error::invalid_digest_length(Codec::Sha2256, 32, 16),
            Error::output_len_required(Codec::Shake128),
            Error::output_len_invalid(Codec::Shake256, 0, 16 * 1024 * 1024),
            Error::hash_compute_failed(Codec::Sha2256, "test"),
        ];

        let kinds: Vec<_> = errors.iter().map(Error::kind).collect();
        assert_eq!(kinds.len(), 6);

        // All kinds should be unique
        for (i, k1) in kinds.iter().enumerate() {
            for (j, k2) in kinds.iter().enumerate() {
                if i != j {
                    assert_ne!(k1, k2);
                }
            }
        }
    }

    #[test]
    fn test_error_context_informative() {
        let err = Error::unsupported_hash(Codec::Sha2256);
        let context = err.context();
        assert_ne!(context, "");
        assert!(context.contains("Sha2256") || context.contains("sha2-256"));

        let err = Error::invalid_digest_length(Codec::Sha2512, 64, 32);
        let context = err.context();
        assert!(context.contains("64"));
        assert!(context.contains("32"));
    }

    #[test]
    fn test_error_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<Error>();
        assert_sync::<Error>();
    }
}