Take Into<secp256k1::PublicKey> in PublicKey constructors

We can make the API more ergonomic by taking a generic argument that
implements `Into<secp256k1::PublicKey>` in the `bitcoin::PublicKey`
constructors.

The only thing than this is useful for is passing in `KeyPair` and the
`From` implementation already exists. Add a unit test to verify.

Fix: #1453
This commit is contained in:
Tobin C. Harding 2023-01-23 13:37:19 +11:00
parent b13a76407b
commit 1d3d5a9c5b
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 16 additions and 4 deletions

View File

@ -92,19 +92,19 @@ pub struct PublicKey {
impl PublicKey {
/// Constructs compressed ECDSA public key from the provided generic Secp256k1 public key
pub fn new(key: secp256k1::PublicKey) -> PublicKey {
pub fn new(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
PublicKey {
compressed: true,
inner: key,
inner: key.into(),
}
}
/// Constructs uncompressed (legacy) ECDSA public key from the provided generic Secp256k1
/// public key
pub fn new_uncompressed(key: secp256k1::PublicKey) -> PublicKey {
pub fn new_uncompressed(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
PublicKey {
compressed: false,
inner: key,
inner: key.into(),
}
}
@ -839,4 +839,16 @@ mod tests {
assert_eq!(vector.input, vector.expect);
}
}
#[test]
#[cfg(feature = "rand-std")]
fn public_key_constructors() {
use crate::secp256k1::rand;
let secp = Secp256k1::new();
let kp = KeyPair::new(&secp, &mut rand::thread_rng());
let _ = PublicKey::new(kp);
let _ = PublicKey::new_uncompressed(kp);
}
}