@@ -86,6 +86,28 @@ impl<T: Tag> HashTrait for Hash<T> {
8686 }
8787}
8888
89+ /// Macro used to define a newtype tagged hash.
90+ /// It creates two public types:
91+ /// - a sha246t::Tag struct,
92+ /// - a sha256t::Hash type alias.
93+ #[ macro_export]
94+ macro_rules! sha256t_hash_newtype {
95+ ( $newtype: ident, $tag: ident, $midstate: ident, $midstate_len: expr, $docs: meta, $reverse: expr) => {
96+ /// The tag used for [$newtype].
97+ #[ derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord , Default , Hash ) ]
98+ pub struct $tag;
99+
100+ impl $crate:: sha256t:: Tag for $tag {
101+ fn engine( ) -> $crate:: sha256:: HashEngine {
102+ let midstate = $crate:: sha256:: Midstate :: from_inner( $midstate) ;
103+ $crate:: sha256:: HashEngine :: from_midstate( midstate, $midstate_len)
104+ }
105+ }
106+
107+ $crate:: hash_newtype!( $newtype, $crate:: sha256t:: Hash <$tag>, 32 , $docs, $reverse) ;
108+ } ;
109+ }
110+
89111#[ cfg( feature="serde" ) ]
90112impl < T : Tag > :: serde:: Serialize for Hash < T > {
91113 fn serialize < S : :: serde:: Serializer > ( & self , s : S ) -> Result < S :: Ok , S :: Error > {
@@ -170,28 +192,36 @@ mod tests {
170192 use :: { Hash , sha256, sha256t} ;
171193 use :: hex:: ToHex ;
172194
195+ const TEST_MIDSTATE : [ u8 ; 32 ] = [
196+ 156 , 224 , 228 , 230 , 124 , 17 , 108 , 57 , 56 , 179 , 202 , 242 , 195 , 15 , 80 , 137 , 211 , 243 ,
197+ 147 , 108 , 71 , 99 , 110 , 96 , 125 , 179 , 62 , 234 , 221 , 198 , 240 , 201 ,
198+ ] ;
199+
173200 #[ derive( Copy , Clone , PartialEq , Eq , PartialOrd , Ord , Default , Hash ) ]
174201 pub struct TestHashTag ;
175202
176203 impl sha256t:: Tag for TestHashTag {
177204 fn engine ( ) -> sha256:: HashEngine {
178205 // The TapRoot TapLeaf midstate.
179- let midstate = sha256:: Midstate :: from_inner ( [
180- 156 , 224 , 228 , 230 , 124 , 17 , 108 , 57 , 56 , 179 , 202 , 242 , 195 , 15 , 80 , 137 , 211 , 243 ,
181- 147 , 108 , 71 , 99 , 110 , 96 , 125 , 179 , 62 , 234 , 221 , 198 , 240 , 201 ,
182- ] ) ;
206+ let midstate = sha256:: Midstate :: from_inner ( TEST_MIDSTATE ) ;
183207 sha256:: HashEngine :: from_midstate ( midstate, 64 )
184208 }
185209 }
186210
187211 /// A hash tagged with `$name`.
188212 pub type TestHash = sha256t:: Hash < TestHashTag > ;
189213
214+ sha256t_hash_newtype ! ( NewTypeHash , NewTypeTag , TEST_MIDSTATE , 64 , doc="test hash" , true ) ;
215+
190216 #[ test]
191217 fn test_sha256t ( ) {
192218 assert_eq ! (
193219 TestHash :: hash( & [ 0 ] ) . to_hex( ) ,
194220 "29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
195221 ) ;
222+ assert_eq ! (
223+ NewTypeHash :: hash( & [ 0 ] ) . to_hex( ) ,
224+ "29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
225+ ) ;
196226 }
197227}
0 commit comments