@@ -25,6 +25,9 @@ use crate::Error::{self, InvalidPublicKey, InvalidPublicKeySum, InvalidSecretKey
25
25
use crate :: ffi:: { self , CPtr , impl_array_newtype} ;
26
26
use crate :: ffi:: types:: c_uint;
27
27
28
+ #[ cfg( feature = "bitcoin_hashes" ) ]
29
+ use crate :: { hashes, ThirtyTwoByteHash } ;
30
+
28
31
#[ cfg( feature = "serde" ) ]
29
32
use serde:: ser:: SerializeTuple ;
30
33
@@ -228,6 +231,31 @@ impl SecretKey {
228
231
SecretKey ( sk)
229
232
}
230
233
234
+ /// Constructs a [`SecretKey`] by hashing `data` with hash algorithm `H`.
235
+ ///
236
+ /// Requires the feature `bitcoin_hashes` to be enabled.
237
+ ///
238
+ /// # Examples
239
+ ///
240
+ /// ```
241
+ /// # #[cfg(feature="bitcoin_hashes")] {
242
+ /// use secp256k1::hashes::{sha256, Hash};
243
+ /// use secp256k1::SecretKey;
244
+ ///
245
+ /// let sk1 = SecretKey::from_hashed_data::<sha256::Hash>("Hello world!".as_bytes());
246
+ /// // is equivalent to
247
+ /// let sk2 = SecretKey::from(sha256::Hash::hash("Hello world!".as_bytes()));
248
+ ///
249
+ /// assert_eq!(sk1, sk2);
250
+ /// # }
251
+ /// ```
252
+ #[ cfg( feature = "bitcoin_hashes" ) ]
253
+ #[ cfg_attr( docsrs, doc( cfg( feature = "bitcoin_hashes" ) ) ) ]
254
+ #[ inline]
255
+ pub fn from_hashed_data < H : ThirtyTwoByteHash + hashes:: Hash > ( data : & [ u8 ] ) -> Self {
256
+ <H as hashes:: Hash >:: hash ( data) . into ( )
257
+ }
258
+
231
259
/// Returns the secret key as a byte value.
232
260
#[ inline]
233
261
pub fn secret_bytes ( & self ) -> [ u8 ; constants:: SECRET_KEY_SIZE ] {
@@ -352,6 +380,14 @@ impl SecretKey {
352
380
}
353
381
}
354
382
383
+ #[ cfg( feature = "bitcoin_hashes" ) ]
384
+ impl < T : ThirtyTwoByteHash > From < T > for SecretKey {
385
+ /// Converts a 32-byte hash directly to a secret key without error paths.
386
+ fn from ( t : T ) -> SecretKey {
387
+ SecretKey :: from_slice ( & t. into_32 ( ) ) . expect ( "failed to create secret key" )
388
+ }
389
+ }
390
+
355
391
#[ cfg( feature = "serde" ) ]
356
392
#[ cfg_attr( docsrs, doc( cfg( feature = "serde" ) ) ) ]
357
393
impl serde:: Serialize for SecretKey {
0 commit comments