Add `from_byte_array` to `PrivateKey`.

Private keys have statically-known length of 32 bytes and we are
migrating types with known lenths to use `from_byte_array` methods. This
adds the method to `PrivateKey` as well and uses it to implement
`from_slice`.
This commit is contained in:
Martin Habovstiak 2025-03-04 20:39:47 +01:00
parent 1778fea66e
commit 0d5cd7af43
1 changed files with 10 additions and 6 deletions

View File

@ -459,17 +459,21 @@ impl PrivateKey {
/// Serializes the private key to bytes.
pub fn to_vec(self) -> Vec<u8> { self.inner[..].to_vec() }
/// Deserializes a private key from a byte array.
pub fn from_byte_array(
data: [u8; 32],
network: impl Into<NetworkKind>
) -> Result<PrivateKey, secp256k1::Error> {
Ok(PrivateKey::new(secp256k1::SecretKey::from_byte_array(&data)?, network))
}
/// Deserializes a private key from a slice.
pub fn from_slice(
data: &[u8],
network: impl Into<NetworkKind>,
) -> Result<PrivateKey, secp256k1::Error> {
Ok(PrivateKey::new(
secp256k1::SecretKey::from_byte_array(
data.try_into().map_err(|_| secp256k1::Error::InvalidSecretKey)?,
)?,
network,
))
let array = data.try_into().map_err(|_| secp256k1::Error::InvalidSecretKey)?;
Self::from_byte_array(array, network)
}
/// Formats the private key to WIF format.