use core::{fmt, ptr, str};
use core::ops::BitXor;
use core::convert::TryFrom;
use crate::{constants, from_hex, Secp256k1, Signing, Verification};
use crate::Error::{self, InvalidPublicKey, InvalidPublicKeySum, InvalidSecretKey};
use crate::ffi::{self, CPtr, impl_array_newtype};
use crate::ffi::types::c_uint;
#[cfg(feature = "serde")]
use serde::ser::SerializeTuple;
#[cfg(feature = "global-context")]
use crate::{Message, ecdsa, SECP256K1};
#[cfg(all(feature = "global-context", feature = "rand-std"))]
use crate::schnorr;
use crate::Scalar;
pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
impl_array_newtype!(SecretKey, u8, constants::SECRET_KEY_SIZE);
impl_display_secret!(SecretKey);
impl str::FromStr for SecretKey {
type Err = Error;
fn from_str(s: &str) -> Result<SecretKey, Error> {
let mut res = [0u8; constants::SECRET_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SECRET_KEY_SIZE) => SecretKey::from_slice(&res),
_ => Err(Error::InvalidSecretKey)
}
}
}
pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1]);
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(fuzzing, derive(PartialOrd, Ord))]
#[repr(transparent)]
pub struct PublicKey(ffi::PublicKey);
impl fmt::LowerHex for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ser = self.serialize();
for ch in &ser[..] {
write!(f, "{:02x}", *ch)?;
}
Ok(())
}
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl str::FromStr for PublicKey {
type Err = Error;
fn from_str(s: &str) -> Result<PublicKey, Error> {
let mut res = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::PUBLIC_KEY_SIZE) => {
PublicKey::from_slice(
&res[0..constants::PUBLIC_KEY_SIZE]
)
}
Ok(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE) => {
PublicKey::from_slice(&res)
}
_ => Err(Error::InvalidPublicKey)
}
}
}
#[cfg(any(test, feature = "rand"))]
fn random_32_bytes<R: rand::Rng + ?Sized>(rng: &mut R) -> [u8; 32] {
let mut ret = [0u8; 32];
rng.fill_bytes(&mut ret);
ret
}
impl SecretKey {
#[inline]
#[cfg(any(test, feature = "rand"))]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
pub fn new<R: rand::Rng + ?Sized>(rng: &mut R) -> SecretKey {
let mut data = random_32_bytes(rng);
unsafe {
while ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
data = random_32_bytes(rng);
}
}
SecretKey(data)
}
#[inline]
pub fn from_slice(data: &[u8])-> Result<SecretKey, Error> {
match <[u8; constants::SECRET_KEY_SIZE]>::try_from(data) {
Ok(data) => {
unsafe {
if ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
return Err(InvalidSecretKey);
}
}
Ok(SecretKey(data))
}
Err(_) => Err(InvalidSecretKey)
}
}
#[inline]
pub fn from_keypair(keypair: &KeyPair) -> Self {
let mut sk = [0u8; constants::SECRET_KEY_SIZE];
unsafe {
let ret = ffi::secp256k1_keypair_sec(
ffi::secp256k1_context_no_precomp,
sk.as_mut_c_ptr(),
keypair.as_ptr()
);
debug_assert_eq!(ret, 1);
}
SecretKey(sk)
}
#[inline]
pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] {
self.0
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use negate instead")]
pub fn negate_assign(&mut self) {
*self = self.negate()
}
#[inline]
#[must_use = "you forgot to use the negated secret key"]
pub fn negate(mut self) -> SecretKey {
unsafe {
let res = ffi::secp256k1_ec_seckey_negate(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr()
);
debug_assert_eq!(res, 1);
}
self
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use add_tweak instead")]
pub fn add_assign(&mut self, other: &Scalar) -> Result<(), Error> {
*self = self.add_tweak(other)?;
Ok(())
}
#[inline]
pub fn add_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
unsafe {
if ffi::secp256k1_ec_seckey_tweak_add(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
tweak.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(self)
}
}
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use mul_tweak instead")]
pub fn mul_assign(&mut self, other: &Scalar) -> Result<(), Error> {
*self = self.mul_tweak(other)?;
Ok(())
}
#[inline]
pub fn mul_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
unsafe {
if ffi::secp256k1_ec_seckey_tweak_mul(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
tweak.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(self)
}
}
}
#[inline]
#[cfg(feature = "global-context")]
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
pub fn sign_ecdsa(&self, msg: Message) -> ecdsa::Signature {
SECP256K1.sign_ecdsa(&msg, self)
}
#[inline]
pub fn keypair<C: Signing>(&self, secp: &Secp256k1<C>) -> KeyPair {
KeyPair::from_secret_key(secp, self)
}
#[inline]
pub fn public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
PublicKey::from_secret_key(secp, self)
}
#[inline]
pub fn x_only_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> (XOnlyPublicKey, Parity) {
let kp = self.keypair(secp);
XOnlyPublicKey::from_keypair(&kp)
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for SecretKey {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
} else {
let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
for byte in self.0.iter() {
tuple.serialize_element(byte)?;
}
tuple.end()
}
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for SecretKey {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"a hex string representing 32 byte SecretKey"
))
} else {
let visitor = super::serde_util::Tuple32Visitor::new(
"raw 32 bytes SecretKey",
SecretKey::from_slice
);
d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
}
}
}
impl PublicKey {
#[inline]
pub fn as_ptr(&self) -> *const ffi::PublicKey {
&self.0
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey {
&mut self.0
}
#[inline]
pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>,sk: &SecretKey) -> PublicKey {
unsafe {
let mut pk = ffi::PublicKey::new();
let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_c_ptr());
debug_assert_eq!(res, 1);
PublicKey(pk)
}
}
#[inline]
#[cfg(feature = "global-context")]
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
pub fn from_secret_key_global(sk: &SecretKey) -> PublicKey {
PublicKey::from_secret_key(SECP256K1, sk)
}
#[inline]
pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
if data.is_empty() {return Err(Error::InvalidPublicKey);}
unsafe {
let mut pk = ffi::PublicKey::new();
if ffi::secp256k1_ec_pubkey_parse(
ffi::secp256k1_context_no_precomp,
&mut pk,
data.as_c_ptr(),
data.len() as usize,
) == 1
{
Ok(PublicKey(pk))
} else {
Err(InvalidPublicKey)
}
}
}
#[inline]
pub fn from_keypair(keypair: &KeyPair) -> Self {
unsafe {
let mut pk = ffi::PublicKey::new();
let ret = ffi::secp256k1_keypair_pub(
ffi::secp256k1_context_no_precomp,
&mut pk,
keypair.as_ptr()
);
debug_assert_eq!(ret, 1);
PublicKey(pk)
}
}
pub fn from_x_only_public_key(pk: XOnlyPublicKey, parity: Parity) -> PublicKey {
let mut buf = [0u8; 33];
buf[0] = match parity {
Parity::Even => 0x02,
Parity::Odd => 0x03,
};
buf[1..].clone_from_slice(&pk.serialize());
PublicKey::from_slice(&buf).expect("we know the buffer is valid")
}
#[inline]
pub fn serialize(&self) -> [u8; constants::PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::PUBLIC_KEY_SIZE];
self.serialize_internal(&mut ret, ffi::SECP256K1_SER_COMPRESSED);
ret
}
#[inline]
pub fn serialize_uncompressed(&self) -> [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
self.serialize_internal(&mut ret, ffi::SECP256K1_SER_UNCOMPRESSED);
ret
}
#[inline(always)]
fn serialize_internal(&self, ret: &mut [u8], flag: c_uint) {
let mut ret_len = ret.len();
let res = unsafe {
ffi::secp256k1_ec_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
&mut ret_len,
self.as_c_ptr(),
flag,
)
};
debug_assert_eq!(res, 1);
debug_assert_eq!(ret_len, ret.len());
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use negate instead")]
pub fn negate_assign<C: Verification>(&mut self, secp: &Secp256k1<C>) {
*self = self.negate(secp)
}
#[inline]
#[must_use = "you forgot to use the negated public key"]
pub fn negate<C: Verification>(mut self, secp: &Secp256k1<C>) -> PublicKey {
unsafe {
let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx, &mut self.0);
debug_assert_eq!(res, 1);
}
self
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use add_exp_tweak instead")]
pub fn add_exp_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
other: &Scalar
) -> Result<(), Error> {
*self = self.add_exp_tweak(secp, other)?;
Ok(())
}
#[inline]
pub fn add_exp_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
tweak: &Scalar
) -> Result<PublicKey, Error> {
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx, &mut self.0, tweak.as_c_ptr()) == 1 {
Ok(self)
} else {
Err(Error::InvalidTweak)
}
}
}
#[deprecated(since = "0.23.0", note = "Use mul_tweak instead")]
#[inline]
pub fn mul_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
other: &Scalar,
) -> Result<(), Error> {
*self = self.mul_tweak(secp, other)?;
Ok(())
}
#[inline]
pub fn mul_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
other: &Scalar,
) -> Result<PublicKey, Error> {
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx, &mut self.0, other.as_c_ptr()) == 1 {
Ok(self)
} else {
Err(Error::InvalidTweak)
}
}
}
pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
PublicKey::combine_keys(&[self, other])
}
pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
use core::mem::transmute;
use core::i32::MAX;
if keys.is_empty() || keys.len() > MAX as usize {
return Err(InvalidPublicKeySum);
}
unsafe {
let mut ret = ffi::PublicKey::new();
let ptrs : &[*const ffi::PublicKey] =
transmute::<&[&PublicKey], &[*const ffi::PublicKey]>(keys);
if ffi::secp256k1_ec_pubkey_combine(
ffi::secp256k1_context_no_precomp,
&mut ret,
ptrs.as_c_ptr(),
keys.len() as i32
) == 1
{
Ok(PublicKey(ret))
} else {
Err(InvalidPublicKeySum)
}
}
}
#[inline]
pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
let mut pk_parity = 0;
unsafe {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let ret = ffi::secp256k1_xonly_pubkey_from_pubkey(
ffi::secp256k1_context_no_precomp,
&mut xonly_pk,
&mut pk_parity,
self.as_ptr(),
);
debug_assert_eq!(ret, 1);
let parity = Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
(XOnlyPublicKey(xonly_pk), parity)
}
}
}
impl CPtr for PublicKey {
type Target = ffi::PublicKey;
fn as_c_ptr(&self) -> *const Self::Target {
self.as_ptr()
}
fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
self.as_mut_ptr()
}
}
impl From<ffi::PublicKey> for PublicKey {
#[inline]
fn from(pk: ffi::PublicKey) -> PublicKey {
PublicKey(pk)
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for PublicKey {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.collect_str(self)
} else {
let mut tuple = s.serialize_tuple(constants::PUBLIC_KEY_SIZE)?;
for byte in self.serialize().iter() { tuple.serialize_element(&byte)?;
}
tuple.end()
}
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for PublicKey {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"an ASCII hex string representing a public key"
))
} else {
let visitor = super::serde_util::Tuple33Visitor::new(
"33 bytes compressed public key",
PublicKey::from_slice
);
d.deserialize_tuple(constants::PUBLIC_KEY_SIZE, visitor)
}
}
}
#[cfg(not(fuzzing))]
impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &PublicKey) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[cfg(not(fuzzing))]
impl Ord for PublicKey {
fn cmp(&self, other: &PublicKey) -> core::cmp::Ordering {
let ret = unsafe {
ffi::secp256k1_ec_pubkey_cmp(ffi::secp256k1_context_no_precomp, self.as_c_ptr(), other.as_c_ptr())
};
ret.cmp(&0i32)
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct KeyPair(ffi::KeyPair);
impl_display_secret!(KeyPair);
impl KeyPair {
#[inline]
pub fn as_ptr(&self) -> *const ffi::KeyPair {
&self.0
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::KeyPair {
&mut self.0
}
#[inline]
pub fn from_secret_key<C: Signing>(
secp: &Secp256k1<C>,
sk: &SecretKey,
) -> KeyPair {
unsafe {
let mut kp = ffi::KeyPair::new();
if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, sk.as_c_ptr()) == 1 {
KeyPair(kp)
} else {
panic!("the provided secret key is invalid: it is corrupted or was not produced by Secp256k1 library")
}
}
}
#[inline]
pub fn from_seckey_slice<C: Signing>(
secp: &Secp256k1<C>,
data: &[u8],
) -> Result<KeyPair, Error> {
if data.is_empty() || data.len() != constants::SECRET_KEY_SIZE {
return Err(Error::InvalidSecretKey);
}
unsafe {
let mut kp = ffi::KeyPair::new();
if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, data.as_c_ptr()) == 1 {
Ok(KeyPair(kp))
} else {
Err(Error::InvalidSecretKey)
}
}
}
#[inline]
pub fn from_seckey_str<C: Signing>(secp: &Secp256k1<C>, s: &str) -> Result<KeyPair, Error> {
let mut res = [0u8; constants::SECRET_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SECRET_KEY_SIZE) => {
KeyPair::from_seckey_slice(secp, &res[0..constants::SECRET_KEY_SIZE])
}
_ => Err(Error::InvalidPublicKey),
}
}
#[inline]
#[cfg(feature = "global-context")]
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
pub fn from_seckey_str_global(s: &str) -> Result<KeyPair, Error> {
KeyPair::from_seckey_str(SECP256K1, s)
}
#[inline]
#[cfg(any(test, feature = "rand"))]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
pub fn new<R: rand::Rng + ?Sized, C: Signing>(secp: &Secp256k1<C>, rng: &mut R) -> KeyPair {
let mut random_32_bytes = || {
let mut ret = [0u8; 32];
rng.fill_bytes(&mut ret);
ret
};
let mut data = random_32_bytes();
unsafe {
let mut keypair = ffi::KeyPair::new();
while ffi::secp256k1_keypair_create(secp.ctx, &mut keypair, data.as_c_ptr()) == 0 {
data = random_32_bytes();
}
KeyPair(keypair)
}
}
#[inline]
#[cfg(all(feature = "global-context", feature = "rand"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand"))))]
pub fn new_global<R: ::rand::Rng + ?Sized>(rng: &mut R) -> KeyPair {
KeyPair::new(SECP256K1, rng)
}
#[inline]
pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] {
*SecretKey::from_keypair(self).as_ref()
}
#[inline]
#[deprecated(since = "0.23.0", note = "Use add_xonly_tweak instead")]
pub fn tweak_add_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
tweak: &Scalar,
) -> Result<(), Error> {
*self = self.add_xonly_tweak(secp, tweak)?;
Ok(())
}
#[inline]
pub fn add_xonly_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
tweak: &Scalar,
) -> Result<KeyPair, Error> {
unsafe {
let err = ffi::secp256k1_keypair_xonly_tweak_add(
secp.ctx,
&mut self.0,
tweak.as_c_ptr(),
);
if err != 1 {
return Err(Error::InvalidTweak);
}
Ok(self)
}
}
#[inline]
pub fn secret_key(&self) -> SecretKey {
SecretKey::from_keypair(self)
}
#[inline]
pub fn public_key(&self) -> PublicKey {
PublicKey::from_keypair(self)
}
#[inline]
pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
XOnlyPublicKey::from_keypair(self)
}
#[inline]
#[cfg(all(feature = "global-context", feature = "rand-std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand-std"))))]
pub fn sign_schnorr(&self, msg: Message) -> schnorr::Signature {
SECP256K1.sign_schnorr(&msg, self)
}
}
impl From<KeyPair> for SecretKey {
#[inline]
fn from(pair: KeyPair) -> Self {
SecretKey::from_keypair(&pair)
}
}
impl<'a> From<&'a KeyPair> for SecretKey {
#[inline]
fn from(pair: &'a KeyPair) -> Self {
SecretKey::from_keypair(pair)
}
}
impl From<KeyPair> for PublicKey {
#[inline]
fn from(pair: KeyPair) -> Self {
PublicKey::from_keypair(&pair)
}
}
impl<'a> From<&'a KeyPair> for PublicKey {
#[inline]
fn from(pair: &'a KeyPair) -> Self {
PublicKey::from_keypair(pair)
}
}
impl str::FromStr for KeyPair {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
#[cfg(feature = "global-context")]
let ctx = SECP256K1;
#[cfg(all(not(feature = "global-context"), feature = "alloc"))]
let ctx = Secp256k1::signing_only();
#[cfg(not(any(feature = "global-context", feature = "alloc")))]
let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("The previous implementation was panicking too, please enable the global-context feature of rust-secp256k1");
#[allow(clippy::needless_borrow)]
KeyPair::from_seckey_str(&ctx, s)
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for KeyPair {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
s.serialize_str(crate::to_hex(&self.secret_bytes(), &mut buf)
.expect("fixed-size hex serialization"))
} else {
let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
for byte in self.secret_bytes().iter() {
tuple.serialize_element(&byte)?;
}
tuple.end()
}
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for KeyPair {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"a hex string representing 32 byte KeyPair"
))
} else {
let visitor = super::serde_util::Tuple32Visitor::new(
"raw 32 bytes KeyPair",
|data| {
#[cfg(feature = "global-context")]
let ctx = SECP256K1;
#[cfg(all(not(feature = "global-context"), feature = "alloc"))]
let ctx = Secp256k1::signing_only();
#[cfg(not(any(feature = "global-context", feature = "alloc")))]
let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("The previous implementation was panicking too, please enable the global-context feature of rust-secp256k1");
#[allow(clippy::needless_borrow)]
KeyPair::from_seckey_slice(&ctx, data)
}
);
d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);
impl fmt::LowerHex for XOnlyPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ser = self.serialize();
for ch in &ser[..] {
write!(f, "{:02x}", *ch)?;
}
Ok(())
}
}
impl fmt::Display for XOnlyPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl str::FromStr for XOnlyPublicKey {
type Err = Error;
fn from_str(s: &str) -> Result<XOnlyPublicKey, Error> {
let mut res = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SCHNORR_PUBLIC_KEY_SIZE) => {
XOnlyPublicKey::from_slice(&res[0..constants::SCHNORR_PUBLIC_KEY_SIZE])
}
_ => Err(Error::InvalidPublicKey),
}
}
}
impl XOnlyPublicKey {
#[inline]
pub fn as_ptr(&self) -> *const ffi::XOnlyPublicKey {
&self.0
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::XOnlyPublicKey {
&mut self.0
}
#[inline]
pub fn from_keypair(keypair: &KeyPair) -> (XOnlyPublicKey, Parity) {
let mut pk_parity = 0;
unsafe {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let ret = ffi::secp256k1_keypair_xonly_pub(
ffi::secp256k1_context_no_precomp,
&mut xonly_pk,
&mut pk_parity,
keypair.as_ptr(),
);
debug_assert_eq!(ret, 1);
let parity = Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
(XOnlyPublicKey(xonly_pk), parity)
}
}
#[inline]
pub fn from_slice(data: &[u8]) -> Result<XOnlyPublicKey, Error> {
if data.is_empty() || data.len() != constants::SCHNORR_PUBLIC_KEY_SIZE {
return Err(Error::InvalidPublicKey);
}
unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
if ffi::secp256k1_xonly_pubkey_parse(
ffi::secp256k1_context_no_precomp,
&mut pk,
data.as_c_ptr(),
) == 1
{
Ok(XOnlyPublicKey(pk))
} else {
Err(Error::InvalidPublicKey)
}
}
}
#[inline]
pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
unsafe {
let err = ffi::secp256k1_xonly_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
self.as_c_ptr(),
);
debug_assert_eq!(err, 1);
}
ret
}
#[deprecated(since = "0.23.0", note = "Use add_tweak instead")]
pub fn tweak_add_assign<V: Verification>(
&mut self,
secp: &Secp256k1<V>,
tweak: &Scalar,
) -> Result<Parity, Error> {
let (tweaked, parity) = self.add_tweak(secp, tweak)?;
*self = tweaked;
Ok(parity)
}
pub fn add_tweak<V: Verification>(
mut self,
secp: &Secp256k1<V>,
tweak: &Scalar,
) -> Result<(XOnlyPublicKey, Parity), Error> {
let mut pk_parity = 0;
unsafe {
let mut pubkey = ffi::PublicKey::new();
let mut err = ffi::secp256k1_xonly_pubkey_tweak_add(
secp.ctx,
&mut pubkey,
self.as_c_ptr(),
tweak.as_c_ptr(),
);
if err != 1 {
return Err(Error::InvalidTweak);
}
err = ffi::secp256k1_xonly_pubkey_from_pubkey(
secp.ctx,
&mut self.0,
&mut pk_parity,
&pubkey,
);
if err == 0 {
return Err(Error::InvalidPublicKey);
}
let parity = Parity::from_i32(pk_parity)?;
Ok((self, parity))
}
}
pub fn tweak_add_check<V: Verification>(
&self,
secp: &Secp256k1<V>,
tweaked_key: &Self,
tweaked_parity: Parity,
tweak: Scalar,
) -> bool {
let tweaked_ser = tweaked_key.serialize();
unsafe {
let err = ffi::secp256k1_xonly_pubkey_tweak_add_check(
secp.ctx,
tweaked_ser.as_c_ptr(),
tweaked_parity.to_i32(),
&self.0,
tweak.as_c_ptr(),
);
err == 1
}
}
#[inline]
pub fn public_key(&self, parity: Parity) -> PublicKey {
PublicKey::from_x_only_public_key(*self, parity)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
pub enum Parity {
Even = 0,
Odd = 1,
}
impl Parity {
pub fn to_u8(self) -> u8 {
self as u8
}
pub fn to_i32(self) -> i32 {
self as i32
}
pub fn from_u8(parity: u8) -> Result<Parity, InvalidParityValue> {
Parity::from_i32(parity.into())
}
pub fn from_i32(parity: i32) -> Result<Parity, InvalidParityValue> {
match parity {
0 => Ok(Parity::Even),
1 => Ok(Parity::Odd),
_ => Err(InvalidParityValue(parity)),
}
}
}
impl TryFrom<i32> for Parity {
type Error = InvalidParityValue;
fn try_from(parity: i32) -> Result<Self, Self::Error> {
Self::from_i32(parity)
}
}
impl TryFrom<u8> for Parity {
type Error = InvalidParityValue;
fn try_from(parity: u8) -> Result<Self, Self::Error> {
Self::from_u8(parity)
}
}
impl From<Parity> for i32 {
fn from(parity: Parity) -> i32 {
parity.to_i32()
}
}
impl From<Parity> for u8 {
fn from(parity: Parity) -> u8 {
parity.to_u8()
}
}
impl BitXor for Parity {
type Output = Parity;
fn bitxor(self, rhs: Parity) -> Self::Output {
if self == rhs {
Parity::Even } else {
Parity::Odd }
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct InvalidParityValue(i32);
impl fmt::Display for InvalidParityValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid value {} for Parity - must be 0 or 1", self.0)
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for InvalidParityValue {}
impl From<InvalidParityValue> for Error {
fn from(error: InvalidParityValue) -> Self {
Error::InvalidParityValue(error)
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for Parity {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_u8(self.to_u8())
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for Parity {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor
{
type Value = Parity;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("8-bit integer (byte) with value 0 or 1")
}
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
where E: serde::de::Error
{
use serde::de::Unexpected;
Parity::from_u8(v)
.map_err(|_| E::invalid_value(Unexpected::Unsigned(v.into()), &"0 or 1"))
}
}
d.deserialize_u8(Visitor)
}
}
impl CPtr for XOnlyPublicKey {
type Target = ffi::XOnlyPublicKey;
fn as_c_ptr(&self) -> *const Self::Target {
self.as_ptr()
}
fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
self.as_mut_ptr()
}
}
impl From<ffi::XOnlyPublicKey> for XOnlyPublicKey {
#[inline]
fn from(pk: ffi::XOnlyPublicKey) -> XOnlyPublicKey {
XOnlyPublicKey(pk)
}
}
impl From<PublicKey> for XOnlyPublicKey {
fn from(src: PublicKey) -> XOnlyPublicKey {
unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
assert_eq!(
1,
ffi::secp256k1_xonly_pubkey_from_pubkey(
ffi::secp256k1_context_no_precomp,
&mut pk,
ptr::null_mut(),
src.as_c_ptr(),
)
);
XOnlyPublicKey(pk)
}
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for XOnlyPublicKey {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.collect_str(self)
} else {
let mut tuple = s.serialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE)?;
for byte in self.serialize().iter() {
tuple.serialize_element(&byte)?;
}
tuple.end()
}
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"a hex string representing 32 byte schnorr public key"
))
} else {
let visitor = super::serde_util::Tuple32Visitor::new(
"raw 32 bytes schnorr public key",
XOnlyPublicKey::from_slice
);
d.deserialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE, visitor)
}
}
}
#[cfg(all(feature = "global-context", feature = "serde"))]
pub mod serde_keypair {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::key::{KeyPair, SecretKey};
#[allow(missing_docs)]
pub fn serialize<S>(key: &KeyPair, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
SecretKey::from_keypair(key).serialize(serializer)
}
#[allow(missing_docs)]
pub fn deserialize<'de, D>(deserializer: D) -> Result<KeyPair, D::Error>
where
D: Deserializer<'de>,
{
let secret_key = SecretKey::deserialize(deserializer)?;
Ok(KeyPair::from_secret_key(
crate::SECP256K1,
&secret_key,
))
}
}
#[cfg(test)]
#[allow(unused_imports)]
mod test {
use bitcoin_hashes::hex::ToHex;
use super::*;
use core::str::FromStr;
#[cfg(any(feature = "alloc", feature = "std"))]
use rand::{Error, RngCore, thread_rng, rngs::mock::StepRng};
use serde_test::{Configure, Token};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test as test;
use super::{XOnlyPublicKey, PublicKey, Secp256k1, SecretKey, KeyPair, Parity};
use crate::{constants, from_hex, to_hex};
use crate::Error::{InvalidPublicKey, InvalidSecretKey};
use crate::Scalar;
#[cfg(not(fuzzing))]
macro_rules! hex {
($hex:expr) => ({
let mut result = vec![0; $hex.len() / 2];
from_hex($hex, &mut result).expect("valid hex string");
result
});
}
#[test]
fn skey_from_slice() {
let sk = SecretKey::from_slice(&[1; 31]);
assert_eq!(sk, Err(InvalidSecretKey));
let sk = SecretKey::from_slice(&[1; 32]);
assert!(sk.is_ok());
}
#[test]
fn pubkey_from_slice() {
assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
assert_eq!(PublicKey::from_slice(&[1, 2, 3]), Err(InvalidPublicKey));
let uncompressed = PublicKey::from_slice(&[4, 54, 57, 149, 239, 162, 148, 175, 246, 254, 239, 75, 154, 152, 10, 82, 234, 224, 85, 220, 40, 100, 57, 121, 30, 162, 94, 156, 135, 67, 74, 49, 179, 57, 236, 53, 162, 124, 149, 144, 168, 77, 74, 30, 72, 211, 229, 110, 111, 55, 96, 193, 86, 227, 183, 152, 195, 155, 51, 247, 123, 113, 60, 228, 188]);
assert!(uncompressed.is_ok());
let compressed = PublicKey::from_slice(&[3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41, 111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78]);
assert!(compressed.is_ok());
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn keypair_slice_round_trip() {
let s = Secp256k1::new();
let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
assert_eq!(SecretKey::from_slice(&sk1[..]), Ok(sk1));
assert_eq!(PublicKey::from_slice(&pk1.serialize()[..]), Ok(pk1));
assert_eq!(PublicKey::from_slice(&pk1.serialize_uncompressed()[..]), Ok(pk1));
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn invalid_secret_key() {
assert_eq!(SecretKey::from_slice(&[0; 32]), Err(InvalidSecretKey));
assert_eq!(
SecretKey::from_str("0000000000000000000000000000000000000000000000000000000000000000"),
Err(InvalidSecretKey)
);
assert_eq!(SecretKey::from_slice(&[0xff; 32]), Err(InvalidSecretKey));
assert!(SecretKey::from_slice(&[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
]).is_ok());
assert!(SecretKey::from_slice(&[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41,
]).is_err());
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_out_of_range() {
struct BadRng(u8);
impl RngCore for BadRng {
fn next_u32(&mut self) -> u32 { unimplemented!() }
fn next_u64(&mut self) -> u64 { unimplemented!() }
fn fill_bytes(&mut self, data: &mut [u8]) {
let group_order: [u8; 32] = [
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41];
assert_eq!(data.len(), 32);
data.copy_from_slice(&group_order[..]);
data[31] = self.0;
self.0 -= 1;
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
let s = Secp256k1::new();
s.generate_keypair(&mut BadRng(0xff));
}
#[test]
fn test_pubkey_from_bad_slice() {
assert_eq!(
PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE - 1]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE + 1]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 1]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[0xff; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[0x55; constants::PUBLIC_KEY_SIZE]),
Err(InvalidPublicKey)
);
assert_eq!(
PublicKey::from_slice(&[]),
Err(InvalidPublicKey)
);
}
#[test]
fn test_seckey_from_bad_slice() {
assert_eq!(
SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE - 1]),
Err(InvalidSecretKey)
);
assert_eq!(
SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE + 1]),
Err(InvalidSecretKey)
);
assert_eq!(
SecretKey::from_slice(&[0xff; constants::SECRET_KEY_SIZE]),
Err(InvalidSecretKey)
);
assert_eq!(
SecretKey::from_slice(&[0x00; constants::SECRET_KEY_SIZE]),
Err(InvalidSecretKey)
);
assert_eq!(
SecretKey::from_slice(&[]),
Err(InvalidSecretKey)
);
}
#[test]
#[cfg(all(feature = "rand", any(feature = "alloc", feature = "std")))]
fn test_debug_output() {
let s = Secp256k1::new();
let (sk, _) = s.generate_keypair(&mut StepRng::new(1, 1));
assert_eq!(&format!("{:?}", sk),
"SecretKey(#d3e0c51a23169bb5)");
let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
assert_eq!(to_hex(&sk[..], &mut buf).unwrap(),
"0100000000000000020000000000000003000000000000000400000000000000");
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_display_output() {
static SK_BYTES: [u8; 32] = [
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
];
#[cfg(not(fuzzing))]
let s = Secp256k1::signing_only();
let sk = SecretKey::from_slice(&SK_BYTES).expect("sk");
#[cfg(not(fuzzing))]
let pk = PublicKey::from_secret_key(&s, &sk);
#[cfg(fuzzing)]
let pk = PublicKey::from_slice(&[0x02, 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f, 0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d, 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54, 0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66]).expect("pk");
assert_eq!(
sk.display_secret().to_string(),
"01010101010101010001020304050607ffff0000ffff00006363636363636363"
);
assert_eq!(
SecretKey::from_str("01010101010101010001020304050607ffff0000ffff00006363636363636363").unwrap(),
sk
);
assert_eq!(
pk.to_string(),
"0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
);
assert_eq!(
PublicKey::from_str("0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166").unwrap(),
pk
);
assert_eq!(
PublicKey::from_str("04\
18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
84B84DB303A340CD7D6823EE88174747D12A67D2F8F2F9BA40846EE5EE7A44F6"
).unwrap(),
pk
);
assert!(SecretKey::from_str("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").is_err());
assert!(SecretKey::from_str("01010101010101010001020304050607ffff0000ffff0000636363636363636363").is_err());
assert!(SecretKey::from_str("01010101010101010001020304050607ffff0000ffff0000636363636363636").is_err());
assert!(SecretKey::from_str("01010101010101010001020304050607ffff0000ffff000063636363636363").is_err());
assert!(SecretKey::from_str("01010101010101010001020304050607ffff0000ffff000063636363636363xx").is_err());
assert!(PublicKey::from_str("0300000000000000000000000000000000000000000000000000000000000000000").is_err());
assert!(PublicKey::from_str("0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16601").is_err());
assert!(PublicKey::from_str("0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16").is_err());
assert!(PublicKey::from_str("0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1").is_err());
assert!(PublicKey::from_str("xx0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1").is_err());
let long_str = "a".repeat(1024 * 1024);
assert!(SecretKey::from_str(&long_str).is_err());
assert!(PublicKey::from_str(&long_str).is_err());
}
#[test]
#[cfg(not(fuzzing))]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_pubkey_serialize() {
let s = Secp256k1::new();
let (_, pk1) = s.generate_keypair(&mut StepRng::new(1,1));
assert_eq!(&pk1.serialize_uncompressed()[..],
&[4, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126, 9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229, 185, 28, 165, 110, 27, 3, 162, 126, 238, 167, 157, 242, 221, 76, 251, 237, 34, 231, 72, 39, 245, 3, 191, 64, 111, 170, 117, 103, 82, 28, 102, 163][..]);
assert_eq!(&pk1.serialize()[..],
&[3, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126, 9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229][..]);
}
#[test]
#[cfg(feature = "rand-std")]
fn tweak_add_arbitrary_data() {
let s = Secp256k1::new();
let (sk, pk) = s.generate_keypair(&mut thread_rng());
assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let tweak = Scalar::random();
let tweaked_sk = sk.add_tweak(&tweak).unwrap();
assert_ne!(sk, tweaked_sk); let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
assert_ne!(pk, tweaked_pk);
assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn tweak_add_zero() {
let s = Secp256k1::new();
let (sk, pk) = s.generate_keypair(&mut thread_rng());
let tweak = Scalar::ZERO;
let tweaked_sk = sk.add_tweak(&tweak).unwrap();
assert_eq!(sk, tweaked_sk); let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
assert_eq!(pk, tweaked_pk);
}
#[test]
#[cfg(feature = "rand-std")]
fn tweak_mul_arbitrary_data() {
let s = Secp256k1::new();
let (sk, pk) = s.generate_keypair(&mut thread_rng());
assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let tweak = Scalar::random();
let tweaked_sk = sk.mul_tweak(&tweak).unwrap();
assert_ne!(sk, tweaked_sk); let tweaked_pk = pk.mul_tweak(&s, &tweak).unwrap();
assert_ne!(pk, tweaked_pk);
assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn tweak_mul_zero() {
let s = Secp256k1::new();
let (sk, _) = s.generate_keypair(&mut thread_rng());
let tweak = Scalar::ZERO;
assert!(sk.mul_tweak(&tweak).is_err())
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_negation() {
let s = Secp256k1::new();
let (sk, pk) = s.generate_keypair(&mut thread_rng());
assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let neg = sk.negate();
assert_ne!(sk, neg);
let back_sk = neg.negate();
assert_eq!(sk, back_sk);
let neg = pk.negate(&s);
assert_ne!(pk, neg);
let back_pk = neg.negate(&s);
assert_eq!(pk, back_pk);
assert_eq!(PublicKey::from_secret_key(&s, &back_sk), pk);
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn pubkey_hash() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::collections::HashSet;
fn hash<T: Hash>(t: &T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}
let s = Secp256k1::new();
let mut set = HashSet::new();
const COUNT : usize = 1024;
for _ in 0..COUNT {
let (_, pk) = s.generate_keypair(&mut thread_rng());
let hash = hash(&pk);
assert!(!set.contains(&hash));
set.insert(hash);
};
assert_eq!(set.len(), COUNT);
}
#[test]
#[cfg(not(fuzzing))]
fn pubkey_combine() {
let compressed1 = PublicKey::from_slice(
&hex!("0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"),
).unwrap();
let compressed2 = PublicKey::from_slice(
&hex!("02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"),
).unwrap();
let exp_sum = PublicKey::from_slice(
&hex!("0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07"),
).unwrap();
let sum1 = compressed1.combine(&compressed2);
assert!(sum1.is_ok());
let sum2 = compressed2.combine(&compressed1);
assert!(sum2.is_ok());
assert_eq!(sum1, sum2);
assert_eq!(sum1.unwrap(), exp_sum);
}
#[test]
#[cfg(not(fuzzing))]
fn pubkey_combine_keys() {
let compressed1 = PublicKey::from_slice(
&hex!("0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"),
).unwrap();
let compressed2 = PublicKey::from_slice(
&hex!("02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"),
).unwrap();
let compressed3 = PublicKey::from_slice(
&hex!("03e74897d8644eb3e5b391ca2ab257aec2080f4d1a95cad57e454e47f021168eb0")
).unwrap();
let exp_sum = PublicKey::from_slice(
&hex!("0252d73a47f66cf341e5651542f0348f452b7c793af62a6d8bff75ade703a451ad"),
).unwrap();
let sum1 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
assert!(sum1.is_ok());
let sum2 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
assert!(sum2.is_ok());
assert_eq!(sum1, sum2);
assert_eq!(sum1.unwrap(), exp_sum);
}
#[test]
#[cfg(not(fuzzing))]
fn pubkey_combine_keys_empty_slice() {
assert!(PublicKey::combine_keys(&[]).is_err());
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn create_pubkey_combine() {
let s = Secp256k1::new();
let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
let (sk2, pk2) = s.generate_keypair(&mut thread_rng());
let sum1 = pk1.combine(&pk2);
assert!(sum1.is_ok());
let sum2 = pk2.combine(&pk1);
assert!(sum2.is_ok());
assert_eq!(sum1, sum2);
let tweaked = sk1.add_tweak(&Scalar::from(sk2)).unwrap();
let sksum = PublicKey::from_secret_key(&s, &tweaked);
assert_eq!(Ok(sksum), sum1);
}
#[cfg(not(fuzzing))]
#[test]
#[allow(clippy::nonminimal_bool)]
fn pubkey_equal() {
let pk1 = PublicKey::from_slice(
&hex!("0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"),
).unwrap();
let pk2 = pk1;
let pk3 = PublicKey::from_slice(
&hex!("02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"),
).unwrap();
assert_eq!(pk1, pk2);
assert!(pk1 <= pk2);
assert!(pk2 <= pk1);
assert!(!(pk2 < pk1));
assert!(!(pk1 < pk2));
assert!(pk3 > pk1);
assert!(pk1 < pk3);
assert!(pk3 >= pk1);
assert!(pk1 <= pk3);
}
#[test]
#[cfg(all(feature = "serde", any(feature = "alloc", feature = "std")))]
fn test_serde() {
use serde_test::{Configure, Token, assert_tokens};
static SK_BYTES: [u8; 32] = [
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 2, 3, 4, 5, 6, 7,
0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
99, 99, 99, 99, 99, 99, 99, 99
];
static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
#[cfg(fuzzing)]
static PK_BYTES: [u8; 33] = [
0x02,
0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66,
];
static PK_STR: &str = "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
#[cfg(not(fuzzing))]
let s = Secp256k1::new();
let sk = SecretKey::from_slice(&SK_BYTES).unwrap();
#[cfg(not(fuzzing))]
let pk = PublicKey::from_secret_key(&s, &sk);
#[cfg(fuzzing)]
let pk = PublicKey::from_slice(&PK_BYTES).expect("pk");
assert_tokens(&sk.compact(), &[
Token::Tuple{ len: 32 },
Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
Token::TupleEnd
]);
assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
assert_tokens(&pk.compact(), &[
Token::Tuple{ len: 33 },
Token::U8(0x02),
Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
Token::TupleEnd
]);
assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
}
#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_tweak_add_then_tweak_add_check() {
let s = Secp256k1::new();
for _ in 0..10 {
let tweak = Scalar::random();
let kp = KeyPair::new(&s, &mut thread_rng());
let (xonly, _) = XOnlyPublicKey::from_keypair(&kp);
let tweaked_kp = kp.add_xonly_tweak(&s, &tweak).expect("keypair tweak add failed");
let (tweaked_xonly, parity) = xonly.add_tweak(&s, &tweak).expect("xonly pubkey tweak failed");
let (want_tweaked_xonly, tweaked_kp_parity) = XOnlyPublicKey::from_keypair(&tweaked_kp);
assert_eq!(tweaked_xonly, want_tweaked_xonly);
assert_eq!(parity, tweaked_kp_parity);
assert!(xonly.tweak_add_check(&s, &tweaked_xonly, parity, tweak));
}
}
#[test]
fn test_from_key_pubkey() {
let kpk1 = PublicKey::from_str(
"02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443",
)
.unwrap();
let kpk2 = PublicKey::from_str(
"0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07",
)
.unwrap();
let pk1 = XOnlyPublicKey::from(kpk1);
let pk2 = XOnlyPublicKey::from(kpk2);
assert_eq!(pk1.serialize()[..], kpk1.serialize()[1..]);
assert_eq!(pk2.serialize()[..], kpk2.serialize()[1..]);
}
#[test]
#[cfg(all(feature = "global-context", feature = "serde"))]
fn test_serde_keypair() {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_test::{Configure, Token, assert_tokens};
use super::serde_keypair;
use crate::key::KeyPair;
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct KeyPairWrapper(KeyPair);
impl<'de> Deserialize<'de> for KeyPairWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
serde_keypair::deserialize(deserializer).map(KeyPairWrapper)
}
}
impl Serialize for KeyPairWrapper {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
serde_keypair::serialize(&self.0, serializer)
}
}
static SK_BYTES: [u8; 32] = [
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 2, 3, 4, 5, 6, 7,
0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
99, 99, 99, 99, 99, 99, 99, 99
];
static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
let sk = KeyPairWrapper(KeyPair::from_seckey_slice(&crate::SECP256K1, &SK_BYTES).unwrap());
assert_tokens(&sk.compact(), &[
Token::Tuple{ len: 32 },
Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
Token::TupleEnd
]);
assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
}
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn keys() -> (SecretKey, PublicKey, KeyPair, XOnlyPublicKey) {
let secp = Secp256k1::new();
static SK_BYTES: [u8; 32] = [
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
];
static PK_BYTES: [u8; 32] = [
0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66
];
let mut pk_bytes = [0u8; 33];
pk_bytes[0] = 0x02; pk_bytes[1..].clone_from_slice(&PK_BYTES);
let sk = SecretKey::from_slice(&SK_BYTES).expect("failed to parse sk bytes");
let pk = PublicKey::from_slice(&pk_bytes).expect("failed to create pk from iterator");
let kp = KeyPair::from_secret_key(&secp, &sk);
let xonly = XOnlyPublicKey::from_slice(&PK_BYTES).expect("failed to get xonly from slice");
(sk, pk, kp, xonly)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn convert_public_key_to_xonly_public_key() {
let (_sk, pk, _kp, want) = keys();
let (got, parity) = pk.x_only_public_key();
assert_eq!(parity, Parity::Even);
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn convert_secret_key_to_public_key() {
let secp = Secp256k1::new();
let (sk, want, _kp, _xonly) = keys();
let got = sk.public_key(&secp);
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn convert_secret_key_to_x_only_public_key() {
let secp = Secp256k1::new();
let (sk, _pk, _kp, want) = keys();
let (got, parity) = sk.x_only_public_key(&secp);
assert_eq!(parity, Parity::Even);
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn convert_keypair_to_public_key() {
let (_sk, want, kp, _xonly) = keys();
let got = kp.public_key();
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn convert_keypair_to_x_only_public_key() {
let (_sk, _pk, kp, want) = keys();
let (got, parity) = kp.x_only_public_key();
assert_eq!(parity, Parity::Even);
assert_eq!(got, want)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn roundtrip_secret_key_via_keypair() {
let secp = Secp256k1::new();
let (sk, _pk, _kp, _xonly) = keys();
let kp = sk.keypair(&secp);
let back = kp.secret_key();
assert_eq!(back, sk)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn roundtrip_keypair_via_secret_key() {
let secp = Secp256k1::new();
let (_sk, _pk, kp, _xonly) = keys();
let sk = kp.secret_key();
let back = sk.keypair(&secp);
assert_eq!(back, kp)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn roundtrip_x_only_public_key_via_public_key() {
let (_sk, _pk, _kp, xonly) = keys();
let pk = xonly.public_key(Parity::Even);
let (back, parity) = pk.x_only_public_key();
assert_eq!(parity, Parity::Even);
assert_eq!(back, xonly)
}
#[test]
#[cfg(all(not(fuzzing), any(feature = "alloc", feature = "std")))]
fn roundtrip_public_key_via_x_only_public_key() {
let (_sk, pk, _kp, _xonly) = keys();
let (xonly, parity) = pk.x_only_public_key();
let back = xonly.public_key(parity);
assert_eq!(back, pk)
}
#[test]
fn public_key_from_x_only_public_key_and_odd_parity() {
let s = "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
let mut want = String::from("03");
want.push_str(s);
let xonly = XOnlyPublicKey::from_str(s).expect("failed to parse xonly pubkey string");
let pk = xonly.public_key(Parity::Odd);
let got = format!("{}", pk);
assert_eq!(got, want)
}
#[test]
#[cfg(not(fuzzing))]
#[cfg(all(feature = "global-context", feature = "serde"))]
fn test_serde_x_only_pubkey() {
use serde_test::{Configure, Token, assert_tokens};
static SK_BYTES: [u8; 32] = [
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 2, 3, 4, 5, 6, 7,
0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
99, 99, 99, 99, 99, 99, 99, 99
];
static PK_STR: &'static str = "\
18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
";
let kp = KeyPair::from_seckey_slice(&crate::SECP256K1, &SK_BYTES).unwrap();
let (pk, _parity) = XOnlyPublicKey::from_keypair(&kp);
assert_tokens(&pk.compact(), &[
Token::Tuple{ len: 32 },
Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
Token::TupleEnd
]);
assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
}
#[test]
#[cfg(any(feature = "alloc", feature = "global-context"))]
fn test_keypair_from_str() {
let ctx = crate::Secp256k1::new();
let keypair = KeyPair::new(&ctx, &mut thread_rng());
let msg = keypair.secret_key().secret_bytes().to_hex();
let parsed_key: KeyPair = msg.parse().unwrap();
assert_eq!(parsed_key, keypair);
}
#[test]
#[cfg(all(any(feature= "alloc", feature = "global-context"), feature = "serde"))]
fn test_keypair_deserialize_serde() {
let ctx = crate::Secp256k1::new();
let sec_key_str = "4242424242424242424242424242424242424242424242424242424242424242";
let keypair = KeyPair::from_seckey_str(&ctx, sec_key_str).unwrap();
serde_test::assert_tokens(&keypair.readable(), &[Token::String(&sec_key_str)]);
let sec_key_bytes = keypair.secret_key().secret_bytes();
let tokens = std::iter::once(Token::Tuple { len: 32 })
.chain(sec_key_bytes.iter().copied().map(Token::U8))
.chain(std::iter::once(Token::TupleEnd))
.collect::<Vec<_>>();
serde_test::assert_tokens(&keypair.compact(), &tokens);
}
#[test]
#[should_panic(expected = "The previous implementation was panicking too")]
#[cfg(not(any(feature = "alloc", feature = "global-context")))]
fn test_parse_keypair_no_alloc_panic() {
let key_hex = "4242424242424242424242424242424242424242424242424242424242424242";
let _: KeyPair = key_hex.parse().expect("We shouldn't even get this far");
}
}
#[cfg(bench)]
mod benches {
use test::Bencher;
use std::collections::BTreeSet;
use crate::PublicKey;
use crate::constants::GENERATOR_X;
#[bench]
fn bench_pk_ordering(b: &mut Bencher) {
let mut map = BTreeSet::new();
let mut g_slice = [02u8; 33];
g_slice[1..].copy_from_slice(&GENERATOR_X);
let g = PublicKey::from_slice(&g_slice).unwrap();
let mut pk = g;
b.iter(|| {
map.insert(pk);
pk = pk.combine(&pk).unwrap();
})
}
}