Skip to content

Commit 2fe8d77

Browse files
committed
Add Arbitrary impl for SecretKey, Parity, and XOnlyPublicKey
1 parent 92acea7 commit 2fe8d77

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

src/key.rs

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1658,17 +1658,50 @@ impl<C: Verification> Secp256k1<C> {
16581658
#[cfg(feature = "arbitrary")]
16591659
impl<'a> Arbitrary<'a> for PublicKey {
16601660
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1661-
let mut bytes = [0u8; 33];
1661+
Ok(PublicKey::from_x_only_public_key(u.arbitrary()?, u.arbitrary()?))
1662+
}
1663+
}
1664+
1665+
#[cfg(feature = "arbitrary")]
1666+
impl<'a> Arbitrary<'a> for Parity {
1667+
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1668+
match bool::arbitrary(u)? {
1669+
true => Ok(Parity::Even),
1670+
false => Ok(Parity::Odd)
1671+
}
1672+
}
1673+
}
1674+
1675+
#[cfg(feature = "arbitrary")]
1676+
impl<'a> Arbitrary<'a> for SecretKey {
1677+
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1678+
let mut bytes = [0u8; constants::SECRET_KEY_SIZE];
16621679
loop {
16631680
// Unstructured::fill_buffer pads the buffer with zeroes if it runs out of data
1664-
if u.len() < 33 {
1681+
if u.len() < constants::SECRET_KEY_SIZE {
16651682
return Err(arbitrary::Error::NotEnoughData);
16661683
}
1684+
u.fill_buffer(&mut bytes[..])?;
16671685

1668-
bytes[0] = if u.arbitrary::<bool>()? { 0x02 } else { 0x03 };
1669-
u.fill_buffer(&mut bytes[1..])?;
1686+
if let Ok(sk) = SecretKey::from_byte_array(bytes) {
1687+
return Ok(sk);
1688+
}
1689+
}
1690+
}
1691+
}
1692+
1693+
#[cfg(feature = "arbitrary")]
1694+
impl<'a> Arbitrary<'a> for XOnlyPublicKey {
1695+
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1696+
let mut bytes = [0u8; 32];
1697+
loop {
1698+
// Unstructured::fill_buffer pads the buffer with zeroes if it runs out of data
1699+
if u.len() < 32 {
1700+
return Err(arbitrary::Error::NotEnoughData);
1701+
}
16701702

1671-
if let Ok(pk) = PublicKey::from_slice(&bytes) {
1703+
u.fill_buffer(&mut bytes[..])?;
1704+
if let Ok(pk) = XOnlyPublicKey::from_byte_array(bytes) {
16721705
return Ok(pk);
16731706
}
16741707
}

0 commit comments

Comments
 (0)