22
33use std:: { fmt, str:: FromStr } ;
44
5- use anyhow:: bail;
65use blake2b_simd:: Params ;
76use pallas_crypto:: hash:: Hash ;
7+ use thiserror:: Error ;
88
99/// Number of bytes in a blake2b 224 hash.
1010pub const BLAKE_2B224_SIZE : usize = 224 / 8 ;
@@ -24,6 +24,20 @@ pub const BLAKE_2B128_SIZE: usize = 128 / 8;
2424/// `Blake2B` 128bit Hash
2525pub type Blake2b128Hash = Blake2bHash < BLAKE_2B128_SIZE > ;
2626
27+ /// Errors that can occur when converting to a `Blake2bHash`.
28+ #[ derive( Debug , Error ) ]
29+ pub enum Blake2bHashError {
30+ /// Indicates that the input byte slice has invalid length of bytes to create a valid
31+ /// hash.
32+ #[ error( "Invalid length: expected {expected} bytes, got {actual}" ) ]
33+ InvalidLength {
34+ /// The expected number of bytes (must be 32 or 28).
35+ expected : usize ,
36+ /// The actual number of bytes in the provided input.
37+ actual : usize ,
38+ } ,
39+ }
40+
2741/// data that is a blake2b [`struct@Hash`] of `BYTES` long.
2842///
2943/// Possible values with Cardano are 32 bytes long (block hash or transaction
@@ -73,11 +87,14 @@ impl<const BYTES: usize> From<Blake2bHash<BYTES>> for Vec<u8> {
7387
7488/// Convert hash in a form of byte array into the `Blake2bHash` type.
7589impl < const BYTES : usize > TryFrom < & [ u8 ] > for Blake2bHash < BYTES > {
76- type Error = anyhow :: Error ;
90+ type Error = Blake2bHashError ;
7791
7892 fn try_from ( value : & [ u8 ] ) -> Result < Self , Self :: Error > {
7993 if value. len ( ) < BYTES {
80- bail ! ( "Invalid input length" ) ;
94+ return Err ( Blake2bHashError :: InvalidLength {
95+ expected : BYTES ,
96+ actual : value. len ( ) ,
97+ } ) ;
8198 }
8299
83100 let mut hash = [ 0 ; BYTES ] ;
@@ -88,15 +105,15 @@ impl<const BYTES: usize> TryFrom<&[u8]> for Blake2bHash<BYTES> {
88105}
89106
90107impl < const BYTES : usize > TryFrom < & Vec < u8 > > for Blake2bHash < BYTES > {
91- type Error = anyhow :: Error ;
108+ type Error = Blake2bHashError ;
92109
93110 fn try_from ( value : & Vec < u8 > ) -> Result < Self , Self :: Error > {
94111 value. as_slice ( ) . try_into ( )
95112 }
96113}
97114
98115impl < const BYTES : usize > TryFrom < Vec < u8 > > for Blake2bHash < BYTES > {
99- type Error = anyhow :: Error ;
116+ type Error = Blake2bHashError ;
100117
101118 fn try_from ( value : Vec < u8 > ) -> Result < Self , Self :: Error > {
102119 value. as_slice ( ) . try_into ( )
0 commit comments