@@ -78,6 +78,28 @@ impl<T: Tag> HashTrait for Hash<T> {
7878 }
7979}
8080
81+ /// Macro used to define a newtype tagged hash.
82+ /// It creates two public types:
83+ /// - a sha246t::Tag struct,
84+ /// - a sha256t::Hash type alias.
85+ #[ macro_export]
86+ macro_rules! sha256t_hash_newtype {
87+ ( $newtype: ident, $tag: ident, $midstate: ident, $midstate_len: expr, $docs: meta, $reverse: expr) => {
88+ /// The tag used for [$newtype].
89+ #[ derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord , Default , Hash ) ]
90+ pub struct $tag;
91+
92+ impl $crate:: sha256t:: Tag for $tag {
93+ fn engine( ) -> $crate:: sha256:: HashEngine {
94+ let midstate = $crate:: sha256:: Midstate :: from_inner( $midstate) ;
95+ $crate:: sha256:: HashEngine :: from_midstate( midstate, $midstate_len)
96+ }
97+ }
98+
99+ $crate:: hash_newtype!( $newtype, $crate:: sha256t:: Hash <$tag>, 32 , $docs, $reverse) ;
100+ } ;
101+ }
102+
81103#[ cfg( feature="serde" ) ]
82104impl < T : Tag > :: serde:: Serialize for Hash < T > {
83105 fn serialize < S : :: serde:: Serializer > ( & self , s : S ) -> Result < S :: Ok , S :: Error > {
@@ -162,28 +184,36 @@ mod tests {
162184 use :: { Hash , sha256, sha256t} ;
163185 use :: hex:: ToHex ;
164186
187+ const TEST_MIDSTATE : [ u8 ; 32 ] = [
188+ 156 , 224 , 228 , 230 , 124 , 17 , 108 , 57 , 56 , 179 , 202 , 242 , 195 , 15 , 80 , 137 , 211 , 243 ,
189+ 147 , 108 , 71 , 99 , 110 , 96 , 125 , 179 , 62 , 234 , 221 , 198 , 240 , 201 ,
190+ ] ;
191+
165192 #[ derive( Copy , Clone , PartialEq , Eq , PartialOrd , Ord , Default , Hash ) ]
166193 pub struct TestHashTag ;
167194
168195 impl sha256t:: Tag for TestHashTag {
169196 fn engine ( ) -> sha256:: HashEngine {
170197 // The TapRoot TapLeaf midstate.
171- let midstate = sha256:: Midstate :: from_inner ( [
172- 156 , 224 , 228 , 230 , 124 , 17 , 108 , 57 , 56 , 179 , 202 , 242 , 195 , 15 , 80 , 137 , 211 , 243 ,
173- 147 , 108 , 71 , 99 , 110 , 96 , 125 , 179 , 62 , 234 , 221 , 198 , 240 , 201 ,
174- ] ) ;
198+ let midstate = sha256:: Midstate :: from_inner ( TEST_MIDSTATE ) ;
175199 sha256:: HashEngine :: from_midstate ( midstate, 64 )
176200 }
177201 }
178202
179203 /// A hash tagged with `$name`.
180204 pub type TestHash = sha256t:: Hash < TestHashTag > ;
181205
206+ sha256t_hash_newtype ! ( NewTypeHash , NewTypeTag , TEST_MIDSTATE , 64 , true , doc="test hash" ) ;
207+
182208 #[ test]
183209 fn test_sha256t ( ) {
184210 assert_eq ! (
185211 TestHash :: hash( & [ 0 ] ) . to_hex( ) ,
186212 "29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
187213 ) ;
214+ assert_eq ! (
215+ NewTypeHash :: hash( & [ 0 ] ) . to_hex( ) ,
216+ "29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
217+ ) ;
188218 }
189219}
0 commit comments