diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index 7a045cfb5..c1d67bb64 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -459,17 +459,22 @@ impl PrivateKey { /// Serializes the private key to bytes. pub fn to_vec(self) -> Vec { self.inner[..].to_vec() } + /// Deserializes a private key from a byte array. + pub fn from_byte_array( + data: [u8; 32], + network: impl Into + ) -> Result { + Ok(PrivateKey::new(secp256k1::SecretKey::from_byte_array(&data)?, network)) + } + /// Deserializes a private key from a slice. + #[deprecated(since = "TBD", note = "use from_byte_array instead")] pub fn from_slice( data: &[u8], network: impl Into, ) -> Result { - Ok(PrivateKey::new( - secp256k1::SecretKey::from_byte_array( - data[..32].try_into().expect("Slice should be exactly 32 bytes"), - )?, - network, - )) + let array = data.try_into().map_err(|_| secp256k1::Error::InvalidSecretKey)?; + Self::from_byte_array(array, network) } /// Formats the private key to WIF format. @@ -1600,4 +1605,13 @@ mod tests { panic!("Expected Invalid char error"); } } + + #[test] + #[allow(deprecated)] // tests the deprecated function + #[allow(deprecated_in_future)] + fn invalid_private_key_len() { + use crate::Network; + assert!(PrivateKey::from_slice(&[1u8; 31], Network::Regtest).is_err()); + assert!(PrivateKey::from_slice(&[1u8; 33], Network::Regtest).is_err()); + } } diff --git a/bitcoin/src/psbt/serialize.rs b/bitcoin/src/psbt/serialize.rs index 26bfc9b32..89de08dcb 100644 --- a/bitcoin/src/psbt/serialize.rs +++ b/bitcoin/src/psbt/serialize.rs @@ -261,7 +261,7 @@ impl Serialize for XOnlyPublicKey { impl Deserialize for XOnlyPublicKey { fn deserialize(bytes: &[u8]) -> Result { XOnlyPublicKey::from_byte_array( - bytes[..32].try_into().expect("statistically impossible to hit"), + bytes.try_into().map_err(|_| Error::InvalidXOnlyPublicKey)?, ) .map_err(|_| Error::InvalidXOnlyPublicKey) } @@ -461,6 +461,12 @@ mod tests { assert!(sighash.is_ok()) } + #[test] + fn deserialize_xonly_public_key_len() { + assert!(XOnlyPublicKey::deserialize(&[1; 31]).is_err()); + assert!(XOnlyPublicKey::deserialize(&[1; 33]).is_err()); + } + #[test] #[should_panic(expected = "InvalidMagic")] fn invalid_vector_1() {