secp256k1/
key.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Public and secret keys.
4//!
5
6use core::convert::TryFrom;
7use core::ops::{self, BitXor};
8use core::{fmt, ptr, str};
9
10#[cfg(feature = "serde")]
11use serde::ser::SerializeTuple;
12
13use crate::ellswift::ElligatorSwift;
14use crate::ffi::types::c_uint;
15use crate::ffi::{self, CPtr};
16use crate::Error::{self, InvalidPublicKey, InvalidPublicKeySum, InvalidSecretKey};
17#[cfg(feature = "global-context")]
18use crate::SECP256K1;
19use crate::{
20    constants, ecdsa, from_hex, schnorr, Message, Scalar, Secp256k1, Signing, Verification,
21};
22#[cfg(feature = "hashes")]
23use crate::{hashes, ThirtyTwoByteHash};
24
25/// Secret key - a 256-bit key used to create ECDSA and Taproot signatures.
26///
27/// This value should be generated using a [cryptographically secure pseudorandom number generator].
28///
29/// # Side channel attacks
30///
31/// We have attempted to reduce the side channel attack surface by implementing a constant time `eq`
32/// method. For similar reasons we explicitly do not implement `PartialOrd`, `Ord`, or `Hash` on
33/// `SecretKey`. If you really want to order secrets keys then you can use `AsRef` to get at the
34/// underlying bytes and compare them - however this is almost certainly a bad idea.
35///
36/// # Serde support
37///
38/// Implements de/serialization with the `serde` feature enabled. We treat the byte value as a tuple
39/// of 32 `u8`s for non-human-readable formats. This representation is optimal for for some formats
40/// (e.g. [`bincode`]) however other formats may be less optimal (e.g. [`cbor`]).
41///
42/// # Examples
43///
44/// Basic usage:
45///
46/// ```
47/// # #[cfg(feature =  "rand-std")] {
48/// use secp256k1::{rand, Secp256k1, SecretKey};
49///
50/// let secp = Secp256k1::new();
51/// let secret_key = SecretKey::new(&mut rand::thread_rng());
52/// # }
53/// ```
54/// [`bincode`]: https://docs.rs/bincode
55/// [`cbor`]: https://docs.rs/cbor
56/// [cryptographically secure pseudorandom number generator]: https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
57#[derive(Copy, Clone)]
58pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
59impl_display_secret!(SecretKey);
60impl_non_secure_erase!(SecretKey, 0, [1u8; constants::SECRET_KEY_SIZE]);
61
62impl PartialEq for SecretKey {
63    /// This implementation is designed to be constant time to help prevent side channel attacks.
64    #[inline]
65    fn eq(&self, other: &Self) -> bool {
66        let accum = self.0.iter().zip(&other.0).fold(0, |accum, (a, b)| accum | a ^ b);
67        unsafe { core::ptr::read_volatile(&accum) == 0 }
68    }
69}
70
71impl Eq for SecretKey {}
72
73impl AsRef<[u8; constants::SECRET_KEY_SIZE]> for SecretKey {
74    /// Gets a reference to the underlying array.
75    ///
76    /// # Side channel attacks
77    ///
78    /// Using ordering functions (`PartialOrd`/`Ord`) on a reference to secret keys leaks data
79    /// because the implementations are not constant time. Doing so will make your code vulnerable
80    /// to side channel attacks. [`SecretKey::eq`] is implemented using a constant time algorithm,
81    /// please consider using it to do comparisons of secret keys.
82    #[inline]
83    fn as_ref(&self) -> &[u8; constants::SECRET_KEY_SIZE] {
84        let SecretKey(dat) = self;
85        dat
86    }
87}
88
89impl<I> ops::Index<I> for SecretKey
90where
91    [u8]: ops::Index<I>,
92{
93    type Output = <[u8] as ops::Index<I>>::Output;
94
95    #[inline]
96    fn index(&self, index: I) -> &Self::Output { &self.0[index] }
97}
98
99impl ffi::CPtr for SecretKey {
100    type Target = u8;
101
102    fn as_c_ptr(&self) -> *const Self::Target {
103        let SecretKey(dat) = self;
104        dat.as_ptr()
105    }
106
107    fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
108        let &mut SecretKey(ref mut dat) = self;
109        dat.as_mut_ptr()
110    }
111}
112
113impl str::FromStr for SecretKey {
114    type Err = Error;
115    fn from_str(s: &str) -> Result<SecretKey, Error> {
116        let mut res = [0u8; constants::SECRET_KEY_SIZE];
117        match from_hex(s, &mut res) {
118            Ok(constants::SECRET_KEY_SIZE) => SecretKey::from_slice(&res),
119            _ => Err(Error::InvalidSecretKey),
120        }
121    }
122}
123
124/// Public key - used to verify ECDSA signatures and to do Taproot tweaks.
125///
126/// # Serde support
127///
128/// Implements de/serialization with the `serde` feature enabled. We treat the byte value as a tuple
129/// of 33 `u8`s for non-human-readable formats. This representation is optimal for for some formats
130/// (e.g. [`bincode`]) however other formats may be less optimal (e.g. [`cbor`]).
131///
132/// # Examples
133///
134/// Basic usage:
135///
136/// ```
137/// # #[cfg(feature =  "alloc")] {
138/// use secp256k1::{SecretKey, Secp256k1, PublicKey};
139///
140/// let secp = Secp256k1::new();
141/// let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("32 bytes, within curve order");
142/// let public_key = PublicKey::from_secret_key(&secp, &secret_key);
143/// # }
144/// ```
145/// [`bincode`]: https://docs.rs/bincode
146/// [`cbor`]: https://docs.rs/cbor
147#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
148#[repr(transparent)]
149pub struct PublicKey(ffi::PublicKey);
150impl_fast_comparisons!(PublicKey);
151
152impl fmt::LowerHex for PublicKey {
153    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154        let ser = self.serialize();
155        for ch in &ser[..] {
156            write!(f, "{:02x}", *ch)?;
157        }
158        Ok(())
159    }
160}
161
162impl fmt::Display for PublicKey {
163    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
164}
165
166impl str::FromStr for PublicKey {
167    type Err = Error;
168    fn from_str(s: &str) -> Result<PublicKey, Error> {
169        let mut res = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
170        match from_hex(s, &mut res) {
171            Ok(constants::PUBLIC_KEY_SIZE) =>
172                PublicKey::from_slice(&res[0..constants::PUBLIC_KEY_SIZE]),
173            Ok(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE) => PublicKey::from_slice(&res),
174            _ => Err(Error::InvalidPublicKey),
175        }
176    }
177}
178
179impl SecretKey {
180    /// Generates a new random secret key.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// # #[cfg(all(feature = "std", feature =  "rand-std"))] {
186    /// use secp256k1::{rand, SecretKey};
187    /// let secret_key = SecretKey::new(&mut rand::thread_rng());
188    /// # }
189    /// ```
190    #[inline]
191    #[cfg(feature = "rand")]
192    pub fn new<R: rand::Rng + ?Sized>(rng: &mut R) -> SecretKey {
193        let mut data = crate::random_32_bytes(rng);
194        unsafe {
195            while ffi::secp256k1_ec_seckey_verify(
196                ffi::secp256k1_context_no_precomp,
197                data.as_c_ptr(),
198            ) == 0
199            {
200                data = crate::random_32_bytes(rng);
201            }
202        }
203        SecretKey(data)
204    }
205
206    /// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// use secp256k1::SecretKey;
212    /// let sk = SecretKey::from_slice(&[0xcd; 32]).expect("32 bytes, within curve order");
213    /// ```
214    #[inline]
215    pub fn from_slice(data: &[u8]) -> Result<SecretKey, Error> {
216        match <[u8; constants::SECRET_KEY_SIZE]>::try_from(data) {
217            Ok(data) => {
218                unsafe {
219                    if ffi::secp256k1_ec_seckey_verify(
220                        ffi::secp256k1_context_no_precomp,
221                        data.as_c_ptr(),
222                    ) == 0
223                    {
224                        return Err(InvalidSecretKey);
225                    }
226                }
227                Ok(SecretKey(data))
228            }
229            Err(_) => Err(InvalidSecretKey),
230        }
231    }
232
233    /// Creates a new secret key using data from BIP-340 [`Keypair`].
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// # #[cfg(feature =  "rand-std")] {
239    /// use secp256k1::{rand, Secp256k1, SecretKey, Keypair};
240    ///
241    /// let secp = Secp256k1::new();
242    /// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
243    /// let secret_key = SecretKey::from_keypair(&keypair);
244    /// # }
245    /// ```
246    #[inline]
247    pub fn from_keypair(keypair: &Keypair) -> Self {
248        let mut sk = [0u8; constants::SECRET_KEY_SIZE];
249        unsafe {
250            let ret = ffi::secp256k1_keypair_sec(
251                ffi::secp256k1_context_no_precomp,
252                sk.as_mut_c_ptr(),
253                keypair.as_c_ptr(),
254            );
255            debug_assert_eq!(ret, 1);
256        }
257        SecretKey(sk)
258    }
259
260    /// Constructs a [`SecretKey`] by hashing `data` with hash algorithm `H`.
261    ///
262    /// Requires the feature `hashes` to be enabled.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// # #[cfg(feature="hashes")] {
268    /// use secp256k1::hashes::{sha256, Hash};
269    /// use secp256k1::SecretKey;
270    ///
271    /// let sk1 = SecretKey::from_hashed_data::<sha256::Hash>("Hello world!".as_bytes());
272    /// // is equivalent to
273    /// let sk2 = SecretKey::from(sha256::Hash::hash("Hello world!".as_bytes()));
274    ///
275    /// assert_eq!(sk1, sk2);
276    /// # }
277    /// ```
278    #[cfg(feature = "hashes")]
279    #[inline]
280    pub fn from_hashed_data<H: ThirtyTwoByteHash + hashes::Hash>(data: &[u8]) -> Self {
281        <H as hashes::Hash>::hash(data).into()
282    }
283
284    /// Returns the secret key as a byte value.
285    #[inline]
286    pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] { self.0 }
287
288    /// Negates the secret key.
289    #[inline]
290    #[must_use = "you forgot to use the negated secret key"]
291    pub fn negate(mut self) -> SecretKey {
292        unsafe {
293            let res = ffi::secp256k1_ec_seckey_negate(
294                ffi::secp256k1_context_no_precomp,
295                self.as_mut_c_ptr(),
296            );
297            debug_assert_eq!(res, 1);
298        }
299        self
300    }
301
302    /// Tweaks a [`SecretKey`] by adding `tweak` modulo the curve order.
303    ///
304    /// # Errors
305    ///
306    /// Returns an error if the resulting key would be invalid.
307    #[inline]
308    pub fn add_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
309        unsafe {
310            if ffi::secp256k1_ec_seckey_tweak_add(
311                ffi::secp256k1_context_no_precomp,
312                self.as_mut_c_ptr(),
313                tweak.as_c_ptr(),
314            ) != 1
315            {
316                Err(Error::InvalidTweak)
317            } else {
318                Ok(self)
319            }
320        }
321    }
322
323    /// Tweaks a [`SecretKey`] by multiplying by `tweak` modulo the curve order.
324    ///
325    /// # Errors
326    ///
327    /// Returns an error if the resulting key would be invalid.
328    #[inline]
329    pub fn mul_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
330        unsafe {
331            if ffi::secp256k1_ec_seckey_tweak_mul(
332                ffi::secp256k1_context_no_precomp,
333                self.as_mut_c_ptr(),
334                tweak.as_c_ptr(),
335            ) != 1
336            {
337                Err(Error::InvalidTweak)
338            } else {
339                Ok(self)
340            }
341        }
342    }
343
344    /// Constructs an ECDSA signature for `msg` using the global [`SECP256K1`] context.
345    #[inline]
346    #[cfg(feature = "global-context")]
347    pub fn sign_ecdsa(&self, msg: Message) -> ecdsa::Signature { SECP256K1.sign_ecdsa(&msg, self) }
348
349    /// Returns the [`Keypair`] for this [`SecretKey`].
350    ///
351    /// This is equivalent to using [`Keypair::from_secret_key`].
352    #[inline]
353    pub fn keypair<C: Signing>(&self, secp: &Secp256k1<C>) -> Keypair {
354        Keypair::from_secret_key(secp, self)
355    }
356
357    /// Returns the [`PublicKey`] for this [`SecretKey`].
358    ///
359    /// This is equivalent to using [`PublicKey::from_secret_key`].
360    #[inline]
361    pub fn public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
362        PublicKey::from_secret_key(secp, self)
363    }
364
365    /// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`SecretKey`].
366    ///
367    /// This is equivalent to `XOnlyPublicKey::from_keypair(self.keypair(secp))`.
368    #[inline]
369    pub fn x_only_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> (XOnlyPublicKey, Parity) {
370        let kp = self.keypair(secp);
371        XOnlyPublicKey::from_keypair(&kp)
372    }
373}
374
375#[cfg(feature = "hashes")]
376impl<T: ThirtyTwoByteHash> From<T> for SecretKey {
377    /// Converts a 32-byte hash directly to a secret key without error paths.
378    fn from(t: T) -> SecretKey {
379        SecretKey::from_slice(&t.into_32()).expect("failed to create secret key")
380    }
381}
382
383#[cfg(feature = "serde")]
384impl serde::Serialize for SecretKey {
385    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
386        if s.is_human_readable() {
387            let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
388            s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
389        } else {
390            let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
391            for byte in self.0.iter() {
392                tuple.serialize_element(byte)?;
393            }
394            tuple.end()
395        }
396    }
397}
398
399#[cfg(feature = "serde")]
400impl<'de> serde::Deserialize<'de> for SecretKey {
401    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
402        if d.is_human_readable() {
403            d.deserialize_str(super::serde_util::FromStrVisitor::new(
404                "a hex string representing 32 byte SecretKey",
405            ))
406        } else {
407            let visitor = super::serde_util::Tuple32Visitor::new(
408                "raw 32 bytes SecretKey",
409                SecretKey::from_slice,
410            );
411            d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
412        }
413    }
414}
415
416impl PublicKey {
417    /// Obtains a raw const pointer suitable for use with FFI functions.
418    #[inline]
419    #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
420    pub fn as_ptr(&self) -> *const ffi::PublicKey { self.as_c_ptr() }
421
422    /// Obtains a raw mutable pointer suitable for use with FFI functions.
423    #[inline]
424    #[deprecated(
425        since = "0.25.0",
426        note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
427    )]
428    pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey { self.as_mut_c_ptr() }
429
430    /// Creates a new public key from a [`SecretKey`].
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// # #[cfg(feature =  "rand-std")] {
436    /// use secp256k1::{rand, Secp256k1, SecretKey, PublicKey};
437    ///
438    /// let secp = Secp256k1::new();
439    /// let secret_key = SecretKey::new(&mut rand::thread_rng());
440    /// let public_key = PublicKey::from_secret_key(&secp, &secret_key);
441    /// # }
442    /// ```
443    #[inline]
444    pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> PublicKey {
445        unsafe {
446            let mut pk = ffi::PublicKey::new();
447            // We can assume the return value because it's not possible to construct
448            // an invalid `SecretKey` without transmute trickery or something.
449            let res = ffi::secp256k1_ec_pubkey_create(secp.ctx.as_ptr(), &mut pk, sk.as_c_ptr());
450            debug_assert_eq!(res, 1);
451            PublicKey(pk)
452        }
453    }
454    /// Creates a new public key from an [`ElligatorSwift`].
455    #[inline]
456    pub fn from_ellswift(ellswift: ElligatorSwift) -> PublicKey { ElligatorSwift::decode(ellswift) }
457
458    /// Creates a new public key from a [`SecretKey`] and the global [`SECP256K1`] context.
459    #[inline]
460    #[cfg(feature = "global-context")]
461    pub fn from_secret_key_global(sk: &SecretKey) -> PublicKey {
462        PublicKey::from_secret_key(SECP256K1, sk)
463    }
464
465    /// Creates a public key directly from a slice.
466    #[inline]
467    pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
468        if data.is_empty() {
469            return Err(Error::InvalidPublicKey);
470        }
471
472        unsafe {
473            let mut pk = ffi::PublicKey::new();
474            if ffi::secp256k1_ec_pubkey_parse(
475                ffi::secp256k1_context_no_precomp,
476                &mut pk,
477                data.as_c_ptr(),
478                data.len(),
479            ) == 1
480            {
481                Ok(PublicKey(pk))
482            } else {
483                Err(InvalidPublicKey)
484            }
485        }
486    }
487
488    /// Creates a new compressed public key using data from BIP-340 [`Keypair`].
489    ///
490    /// # Examples
491    ///
492    /// ```
493    /// # #[cfg(feature =  "rand-std")] {
494    /// use secp256k1::{rand, Secp256k1, PublicKey, Keypair};
495    ///
496    /// let secp = Secp256k1::new();
497    /// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
498    /// let public_key = PublicKey::from_keypair(&keypair);
499    /// # }
500    /// ```
501    #[inline]
502    pub fn from_keypair(keypair: &Keypair) -> Self {
503        unsafe {
504            let mut pk = ffi::PublicKey::new();
505            let ret = ffi::secp256k1_keypair_pub(
506                ffi::secp256k1_context_no_precomp,
507                &mut pk,
508                keypair.as_c_ptr(),
509            );
510            debug_assert_eq!(ret, 1);
511            PublicKey(pk)
512        }
513    }
514
515    /// Creates a [`PublicKey`] using the key material from `pk` combined with the `parity`.
516    pub fn from_x_only_public_key(pk: XOnlyPublicKey, parity: Parity) -> PublicKey {
517        let mut buf = [0u8; 33];
518
519        // First byte of a compressed key should be `0x02 AND parity`.
520        buf[0] = match parity {
521            Parity::Even => 0x02,
522            Parity::Odd => 0x03,
523        };
524        buf[1..].clone_from_slice(&pk.serialize());
525
526        PublicKey::from_slice(&buf).expect("we know the buffer is valid")
527    }
528
529    #[inline]
530    /// Serializes the key as a byte-encoded pair of values. In compressed form the y-coordinate is
531    /// represented by only a single bit, as x determines it up to one bit.
532    pub fn serialize(&self) -> [u8; constants::PUBLIC_KEY_SIZE] {
533        let mut ret = [0u8; constants::PUBLIC_KEY_SIZE];
534        self.serialize_internal(&mut ret, ffi::SECP256K1_SER_COMPRESSED);
535        ret
536    }
537
538    #[inline]
539    /// Serializes the key as a byte-encoded pair of values, in uncompressed form.
540    pub fn serialize_uncompressed(&self) -> [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] {
541        let mut ret = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
542        self.serialize_internal(&mut ret, ffi::SECP256K1_SER_UNCOMPRESSED);
543        ret
544    }
545
546    #[inline(always)]
547    fn serialize_internal(&self, ret: &mut [u8], flag: c_uint) {
548        let mut ret_len = ret.len();
549        let res = unsafe {
550            ffi::secp256k1_ec_pubkey_serialize(
551                ffi::secp256k1_context_no_precomp,
552                ret.as_mut_c_ptr(),
553                &mut ret_len,
554                self.as_c_ptr(),
555                flag,
556            )
557        };
558        debug_assert_eq!(res, 1);
559        debug_assert_eq!(ret_len, ret.len());
560    }
561
562    /// Negates the public key.
563    #[inline]
564    #[must_use = "you forgot to use the negated public key"]
565    pub fn negate<C: Verification>(mut self, secp: &Secp256k1<C>) -> PublicKey {
566        unsafe {
567            let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx.as_ptr(), &mut self.0);
568            debug_assert_eq!(res, 1);
569        }
570        self
571    }
572
573    /// Tweaks a [`PublicKey`] by adding `tweak * G` modulo the curve order.
574    ///
575    /// # Errors
576    ///
577    /// Returns an error if the resulting key would be invalid.
578    #[inline]
579    pub fn add_exp_tweak<C: Verification>(
580        mut self,
581        secp: &Secp256k1<C>,
582        tweak: &Scalar,
583    ) -> Result<PublicKey, Error> {
584        unsafe {
585            if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx.as_ptr(), &mut self.0, tweak.as_c_ptr())
586                == 1
587            {
588                Ok(self)
589            } else {
590                Err(Error::InvalidTweak)
591            }
592        }
593    }
594
595    /// Tweaks a [`PublicKey`] by multiplying by `tweak` modulo the curve order.
596    ///
597    /// # Errors
598    ///
599    /// Returns an error if the resulting key would be invalid.
600    #[inline]
601    pub fn mul_tweak<C: Verification>(
602        mut self,
603        secp: &Secp256k1<C>,
604        other: &Scalar,
605    ) -> Result<PublicKey, Error> {
606        unsafe {
607            if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx.as_ptr(), &mut self.0, other.as_c_ptr())
608                == 1
609            {
610                Ok(self)
611            } else {
612                Err(Error::InvalidTweak)
613            }
614        }
615    }
616
617    /// Adds a second key to this one, returning the sum.
618    ///
619    /// # Errors
620    ///
621    /// If the result would be the point at infinity, i.e. adding this point to its own negation.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// # #[cfg(feature = "rand-std")] {
627    /// use secp256k1::{rand, Secp256k1};
628    ///
629    /// let secp = Secp256k1::new();
630    /// let mut rng = rand::thread_rng();
631    /// let (_, pk1) = secp.generate_keypair(&mut rng);
632    /// let (_, pk2) = secp.generate_keypair(&mut rng);
633    /// let sum = pk1.combine(&pk2).expect("It's improbable to fail for 2 random public keys");
634    /// # }
635    /// ```
636    pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
637        PublicKey::combine_keys(&[self, other])
638    }
639
640    /// Adds the keys in the provided slice together, returning the sum.
641    ///
642    /// # Errors
643    ///
644    /// Errors under any of the following conditions:
645    /// - The result would be the point at infinity, i.e. adding a point to its own negation.
646    /// - The provided slice is empty.
647    /// - The number of elements in the provided slice is greater than `i32::MAX`.
648    ///
649    /// # Examples
650    ///
651    /// ```
652    /// # #[cfg(feature =  "rand-std")] {
653    /// use secp256k1::{rand, Secp256k1, PublicKey};
654    ///
655    /// let secp = Secp256k1::new();
656    /// let mut rng = rand::thread_rng();
657    /// let (_, pk1) = secp.generate_keypair(&mut rng);
658    /// let (_, pk2) = secp.generate_keypair(&mut rng);
659    /// let (_, pk3) = secp.generate_keypair(&mut rng);
660    /// let sum = PublicKey::combine_keys(&[&pk1, &pk2, &pk3]).expect("It's improbable to fail for 3 random public keys");
661    /// # }
662    /// ```
663    pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
664        use core::i32::MAX;
665        use core::mem::transmute;
666
667        if keys.is_empty() || keys.len() > MAX as usize {
668            return Err(InvalidPublicKeySum);
669        }
670
671        unsafe {
672            let mut ret = ffi::PublicKey::new();
673            let ptrs: &[*const ffi::PublicKey] =
674                transmute::<&[&PublicKey], &[*const ffi::PublicKey]>(keys);
675            if ffi::secp256k1_ec_pubkey_combine(
676                ffi::secp256k1_context_no_precomp,
677                &mut ret,
678                ptrs.as_c_ptr(),
679                keys.len(),
680            ) == 1
681            {
682                Ok(PublicKey(ret))
683            } else {
684                Err(InvalidPublicKeySum)
685            }
686        }
687    }
688
689    /// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`PublicKey`].
690    #[inline]
691    pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
692        let mut pk_parity = 0;
693        unsafe {
694            let mut xonly_pk = ffi::XOnlyPublicKey::new();
695            let ret = ffi::secp256k1_xonly_pubkey_from_pubkey(
696                ffi::secp256k1_context_no_precomp,
697                &mut xonly_pk,
698                &mut pk_parity,
699                self.as_c_ptr(),
700            );
701            debug_assert_eq!(ret, 1);
702            let parity =
703                Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
704
705            (XOnlyPublicKey(xonly_pk), parity)
706        }
707    }
708
709    /// Checks that `sig` is a valid ECDSA signature for `msg` using this public key.
710    pub fn verify<C: Verification>(
711        &self,
712        secp: &Secp256k1<C>,
713        msg: &Message,
714        sig: &ecdsa::Signature,
715    ) -> Result<(), Error> {
716        secp.verify_ecdsa(msg, sig, self)
717    }
718}
719
720/// This trait enables interaction with the FFI layer and even though it is part of the public API
721/// normal users should never need to directly interact with FFI types.
722impl CPtr for PublicKey {
723    type Target = ffi::PublicKey;
724
725    /// Obtains a const pointer suitable for use with FFI functions.
726    fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
727
728    /// Obtains a mutable pointer suitable for use with FFI functions.
729    fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
730}
731
732/// Creates a new public key from a FFI public key.
733///
734/// Note, normal users should never need to interact directly with FFI types.
735impl From<ffi::PublicKey> for PublicKey {
736    #[inline]
737    fn from(pk: ffi::PublicKey) -> PublicKey { PublicKey(pk) }
738}
739
740#[cfg(feature = "serde")]
741impl serde::Serialize for PublicKey {
742    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
743        if s.is_human_readable() {
744            s.collect_str(self)
745        } else {
746            let mut tuple = s.serialize_tuple(constants::PUBLIC_KEY_SIZE)?;
747            // Serialize in compressed form.
748            for byte in self.serialize().iter() {
749                tuple.serialize_element(&byte)?;
750            }
751            tuple.end()
752        }
753    }
754}
755
756#[cfg(feature = "serde")]
757impl<'de> serde::Deserialize<'de> for PublicKey {
758    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
759        if d.is_human_readable() {
760            d.deserialize_str(super::serde_util::FromStrVisitor::new(
761                "an ASCII hex string representing a public key",
762            ))
763        } else {
764            let visitor = super::serde_util::Tuple33Visitor::new(
765                "33 bytes compressed public key",
766                PublicKey::from_slice,
767            );
768            d.deserialize_tuple(constants::PUBLIC_KEY_SIZE, visitor)
769        }
770    }
771}
772
773/// Opaque data structure that holds a keypair consisting of a secret and a public key.
774///
775/// # Serde support
776///
777/// Implements de/serialization with the `serde` and_`global-context` features enabled. Serializes
778/// the secret bytes only. We treat the byte value as a tuple of 32 `u8`s for non-human-readable
779/// formats. This representation is optimal for for some formats (e.g. [`bincode`]) however other
780/// formats may be less optimal (e.g. [`cbor`]). For human-readable formats we use a hex string.
781///
782/// # Examples
783///
784/// Basic usage:
785///
786/// ```
787/// # #[cfg(feature =  "rand-std")] {
788/// use secp256k1::{rand, Keypair, Secp256k1};
789///
790/// let secp = Secp256k1::new();
791/// let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
792/// let keypair = Keypair::from_secret_key(&secp, &secret_key);
793/// # }
794/// ```
795/// [`bincode`]: https://docs.rs/bincode
796/// [`cbor`]: https://docs.rs/cbor
797#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
798pub struct Keypair(ffi::Keypair);
799impl_display_secret!(Keypair);
800impl_fast_comparisons!(Keypair);
801
802impl Keypair {
803    /// Obtains a raw const pointer suitable for use with FFI functions.
804    #[inline]
805    #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
806    pub fn as_ptr(&self) -> *const ffi::Keypair { self.as_c_ptr() }
807
808    /// Obtains a raw mutable pointer suitable for use with FFI functions.
809    #[inline]
810    #[deprecated(
811        since = "0.25.0",
812        note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
813    )]
814    pub fn as_mut_ptr(&mut self) -> *mut ffi::Keypair { self.as_mut_c_ptr() }
815
816    /// Creates a [`Keypair`] directly from a Secp256k1 secret key.
817    #[inline]
818    pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> Keypair {
819        unsafe {
820            let mut kp = ffi::Keypair::new();
821            if ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut kp, sk.as_c_ptr()) == 1 {
822                Keypair(kp)
823            } else {
824                panic!("the provided secret key is invalid: it is corrupted or was not produced by Secp256k1 library")
825            }
826        }
827    }
828
829    /// Creates a [`Keypair`] directly from a secret key slice.
830    ///
831    /// # Errors
832    ///
833    /// [`Error::InvalidSecretKey`] if the provided data has an incorrect length, exceeds Secp256k1
834    /// field `p` value or the corresponding public key is not even.
835    #[inline]
836    pub fn from_seckey_slice<C: Signing>(
837        secp: &Secp256k1<C>,
838        data: &[u8],
839    ) -> Result<Keypair, Error> {
840        if data.is_empty() || data.len() != constants::SECRET_KEY_SIZE {
841            return Err(Error::InvalidSecretKey);
842        }
843
844        unsafe {
845            let mut kp = ffi::Keypair::new();
846            if ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut kp, data.as_c_ptr()) == 1 {
847                Ok(Keypair(kp))
848            } else {
849                Err(Error::InvalidSecretKey)
850            }
851        }
852    }
853
854    /// Creates a [`Keypair`] directly from a secret key string.
855    ///
856    /// # Errors
857    ///
858    /// [`Error::InvalidSecretKey`] if corresponding public key for the provided secret key is not even.
859    #[inline]
860    pub fn from_seckey_str<C: Signing>(secp: &Secp256k1<C>, s: &str) -> Result<Keypair, Error> {
861        let mut res = [0u8; constants::SECRET_KEY_SIZE];
862        match from_hex(s, &mut res) {
863            Ok(constants::SECRET_KEY_SIZE) =>
864                Keypair::from_seckey_slice(secp, &res[0..constants::SECRET_KEY_SIZE]),
865            _ => Err(Error::InvalidPublicKey),
866        }
867    }
868
869    /// Creates a [`Keypair`] directly from a secret key string and the global [`SECP256K1`] context.
870    ///
871    /// # Errors
872    ///
873    /// [`Error::InvalidSecretKey`] if corresponding public key for the provided secret key is not even.
874    #[inline]
875    #[cfg(feature = "global-context")]
876    pub fn from_seckey_str_global(s: &str) -> Result<Keypair, Error> {
877        Keypair::from_seckey_str(SECP256K1, s)
878    }
879
880    /// Generates a new random secret key.
881    /// # Examples
882    ///
883    /// ```
884    /// # #[cfg(feature =  "rand-std")] {
885    /// use secp256k1::{rand, Secp256k1, SecretKey, Keypair};
886    ///
887    /// let secp = Secp256k1::new();
888    /// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
889    /// # }
890    /// ```
891    #[inline]
892    #[cfg(feature = "rand")]
893    pub fn new<R: rand::Rng + ?Sized, C: Signing>(secp: &Secp256k1<C>, rng: &mut R) -> Keypair {
894        let mut data = crate::random_32_bytes(rng);
895        unsafe {
896            let mut keypair = ffi::Keypair::new();
897            while ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut keypair, data.as_c_ptr())
898                == 0
899            {
900                data = crate::random_32_bytes(rng);
901            }
902            Keypair(keypair)
903        }
904    }
905
906    /// Generates a new random secret key using the global [`SECP256K1`] context.
907    #[inline]
908    #[cfg(all(feature = "global-context", feature = "rand"))]
909    pub fn new_global<R: ::rand::Rng + ?Sized>(rng: &mut R) -> Keypair {
910        Keypair::new(SECP256K1, rng)
911    }
912
913    /// Returns the secret bytes for this key pair.
914    #[inline]
915    pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] {
916        *SecretKey::from_keypair(self).as_ref()
917    }
918
919    /// Tweaks a keypair by first converting the public key to an xonly key and tweaking it.
920    ///
921    /// # Errors
922    ///
923    /// Returns an error if the resulting key would be invalid.
924    ///
925    /// NB: Will not error if the tweaked public key has an odd value and can't be used for
926    ///     BIP 340-342 purposes.
927    ///
928    /// # Examples
929    ///
930    /// ```
931    /// # #[cfg(feature =  "rand-std")] {
932    /// use secp256k1::{Secp256k1, Keypair, Scalar};
933    ///
934    /// let secp = Secp256k1::new();
935    /// let tweak = Scalar::random();
936    ///
937    /// let mut keypair = Keypair::new(&secp, &mut rand::thread_rng());
938    /// let tweaked = keypair.add_xonly_tweak(&secp, &tweak).expect("Improbable to fail with a randomly generated tweak");
939    /// # }
940    /// ```
941    // TODO: Add checked implementation
942    #[inline]
943    pub fn add_xonly_tweak<C: Verification>(
944        mut self,
945        secp: &Secp256k1<C>,
946        tweak: &Scalar,
947    ) -> Result<Keypair, Error> {
948        unsafe {
949            let err = ffi::secp256k1_keypair_xonly_tweak_add(
950                secp.ctx.as_ptr(),
951                &mut self.0,
952                tweak.as_c_ptr(),
953            );
954            if err != 1 {
955                return Err(Error::InvalidTweak);
956            }
957
958            Ok(self)
959        }
960    }
961
962    /// Returns the [`SecretKey`] for this [`Keypair`].
963    ///
964    /// This is equivalent to using [`SecretKey::from_keypair`].
965    #[inline]
966    pub fn secret_key(&self) -> SecretKey { SecretKey::from_keypair(self) }
967
968    /// Returns the [`PublicKey`] for this [`Keypair`].
969    ///
970    /// This is equivalent to using [`PublicKey::from_keypair`].
971    #[inline]
972    pub fn public_key(&self) -> PublicKey { PublicKey::from_keypair(self) }
973
974    /// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`Keypair`].
975    ///
976    /// This is equivalent to using [`XOnlyPublicKey::from_keypair`].
977    #[inline]
978    pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
979        XOnlyPublicKey::from_keypair(self)
980    }
981
982    /// Constructs an schnorr signature for `msg` using the global [`SECP256K1`] context.
983    #[inline]
984    #[cfg(all(feature = "global-context", feature = "rand-std"))]
985    pub fn sign_schnorr(&self, msg: Message) -> schnorr::Signature {
986        SECP256K1.sign_schnorr(&msg, self)
987    }
988
989    /// Attempts to erase the secret within the underlying array.
990    ///
991    /// Note, however, that the compiler is allowed to freely copy or move the contents
992    /// of this array to other places in memory. Preventing this behavior is very subtle.
993    /// For more discussion on this, please see the documentation of the
994    /// [`zeroize`](https://docs.rs/zeroize) crate.
995    #[inline]
996    pub fn non_secure_erase(&mut self) { self.0.non_secure_erase(); }
997}
998
999impl From<Keypair> for SecretKey {
1000    #[inline]
1001    fn from(pair: Keypair) -> Self { SecretKey::from_keypair(&pair) }
1002}
1003
1004impl<'a> From<&'a Keypair> for SecretKey {
1005    #[inline]
1006    fn from(pair: &'a Keypair) -> Self { SecretKey::from_keypair(pair) }
1007}
1008
1009impl From<Keypair> for PublicKey {
1010    #[inline]
1011    fn from(pair: Keypair) -> Self { PublicKey::from_keypair(&pair) }
1012}
1013
1014impl<'a> From<&'a Keypair> for PublicKey {
1015    #[inline]
1016    fn from(pair: &'a Keypair) -> Self { PublicKey::from_keypair(pair) }
1017}
1018
1019impl str::FromStr for Keypair {
1020    type Err = Error;
1021
1022    #[allow(unused_variables, unreachable_code)] // When built with no default features.
1023    fn from_str(s: &str) -> Result<Self, Self::Err> {
1024        #[cfg(feature = "global-context")]
1025        let ctx = SECP256K1;
1026
1027        #[cfg(all(not(feature = "global-context"), feature = "alloc"))]
1028        let ctx = Secp256k1::signing_only();
1029
1030        #[cfg(not(any(feature = "global-context", feature = "alloc")))]
1031        let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("The previous implementation was panicking too, please enable the global-context feature of rust-secp256k1");
1032
1033        #[allow(clippy::needless_borrow)]
1034        Keypair::from_seckey_str(&ctx, s)
1035    }
1036}
1037
1038#[cfg(feature = "serde")]
1039impl serde::Serialize for Keypair {
1040    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1041        if s.is_human_readable() {
1042            let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
1043            s.serialize_str(
1044                crate::to_hex(&self.secret_bytes(), &mut buf)
1045                    .expect("fixed-size hex serialization"),
1046            )
1047        } else {
1048            let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
1049            for byte in self.secret_bytes().iter() {
1050                tuple.serialize_element(&byte)?;
1051            }
1052            tuple.end()
1053        }
1054    }
1055}
1056
1057#[cfg(feature = "serde")]
1058#[allow(unused_variables)] // For `data` under some feature combinations (the unconditional panic below).
1059#[allow(unreachable_code)] // For `Keypair::from_seckey_slice` after unconditional panic.
1060impl<'de> serde::Deserialize<'de> for Keypair {
1061    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1062        if d.is_human_readable() {
1063            d.deserialize_str(super::serde_util::FromStrVisitor::new(
1064                "a hex string representing 32 byte Keypair",
1065            ))
1066        } else {
1067            let visitor = super::serde_util::Tuple32Visitor::new("raw 32 bytes Keypair", |data| {
1068                #[cfg(feature = "global-context")]
1069                let ctx = SECP256K1;
1070
1071                #[cfg(all(not(feature = "global-context"), feature = "alloc"))]
1072                let ctx = Secp256k1::signing_only();
1073
1074                #[cfg(not(any(feature = "global-context", feature = "alloc")))]
1075                let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("cannot deserialize key pair without a context (please enable either the global-context or alloc feature)");
1076
1077                #[allow(clippy::needless_borrow)]
1078                Keypair::from_seckey_slice(&ctx, data)
1079            });
1080            d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
1081        }
1082    }
1083}
1084
1085impl CPtr for Keypair {
1086    type Target = ffi::Keypair;
1087    fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
1088
1089    fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
1090}
1091
1092/// An x-only public key, used for verification of Taproot signatures and serialized according to BIP-340.
1093///
1094/// # Serde support
1095///
1096/// Implements de/serialization with the `serde` feature enabled. We treat the byte value as a tuple
1097/// of 32 `u8`s for non-human-readable formats. This representation is optimal for for some formats
1098/// (e.g. [`bincode`]) however other formats may be less optimal (e.g. [`cbor`]).
1099///
1100/// # Examples
1101///
1102/// Basic usage:
1103///
1104/// ```
1105/// # #[cfg(feature =  "rand-std")] {
1106/// use secp256k1::{rand, Secp256k1, Keypair, XOnlyPublicKey};
1107///
1108/// let secp = Secp256k1::new();
1109/// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
1110/// let xonly = XOnlyPublicKey::from_keypair(&keypair);
1111/// # }
1112/// ```
1113/// [`bincode`]: https://docs.rs/bincode
1114/// [`cbor`]: https://docs.rs/cbor
1115#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
1116pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);
1117impl_fast_comparisons!(XOnlyPublicKey);
1118
1119impl fmt::LowerHex for XOnlyPublicKey {
1120    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1121        let ser = self.serialize();
1122        for ch in &ser[..] {
1123            write!(f, "{:02x}", *ch)?;
1124        }
1125        Ok(())
1126    }
1127}
1128
1129impl fmt::Display for XOnlyPublicKey {
1130    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
1131}
1132
1133impl str::FromStr for XOnlyPublicKey {
1134    type Err = Error;
1135    fn from_str(s: &str) -> Result<XOnlyPublicKey, Error> {
1136        let mut res = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
1137        match from_hex(s, &mut res) {
1138            Ok(constants::SCHNORR_PUBLIC_KEY_SIZE) =>
1139                XOnlyPublicKey::from_slice(&res[0..constants::SCHNORR_PUBLIC_KEY_SIZE]),
1140            _ => Err(Error::InvalidPublicKey),
1141        }
1142    }
1143}
1144
1145impl XOnlyPublicKey {
1146    /// Obtains a raw const pointer suitable for use with FFI functions.
1147    #[inline]
1148    #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
1149    pub fn as_ptr(&self) -> *const ffi::XOnlyPublicKey { self.as_c_ptr() }
1150
1151    /// Obtains a raw mutable pointer suitable for use with FFI functions.
1152    #[inline]
1153    #[deprecated(
1154        since = "0.25.0",
1155        note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
1156    )]
1157    pub fn as_mut_ptr(&mut self) -> *mut ffi::XOnlyPublicKey { self.as_mut_c_ptr() }
1158
1159    /// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for `keypair`.
1160    #[inline]
1161    pub fn from_keypair(keypair: &Keypair) -> (XOnlyPublicKey, Parity) {
1162        let mut pk_parity = 0;
1163        unsafe {
1164            let mut xonly_pk = ffi::XOnlyPublicKey::new();
1165            let ret = ffi::secp256k1_keypair_xonly_pub(
1166                ffi::secp256k1_context_no_precomp,
1167                &mut xonly_pk,
1168                &mut pk_parity,
1169                keypair.as_c_ptr(),
1170            );
1171            debug_assert_eq!(ret, 1);
1172            let parity =
1173                Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
1174
1175            (XOnlyPublicKey(xonly_pk), parity)
1176        }
1177    }
1178
1179    /// Creates a schnorr public key directly from a slice.
1180    ///
1181    /// # Errors
1182    ///
1183    /// Returns [`Error::InvalidPublicKey`] if the length of the data slice is not 32 bytes or the
1184    /// slice does not represent a valid Secp256k1 point x coordinate.
1185    #[inline]
1186    pub fn from_slice(data: &[u8]) -> Result<XOnlyPublicKey, Error> {
1187        if data.is_empty() || data.len() != constants::SCHNORR_PUBLIC_KEY_SIZE {
1188            return Err(Error::InvalidPublicKey);
1189        }
1190
1191        unsafe {
1192            let mut pk = ffi::XOnlyPublicKey::new();
1193            if ffi::secp256k1_xonly_pubkey_parse(
1194                ffi::secp256k1_context_no_precomp,
1195                &mut pk,
1196                data.as_c_ptr(),
1197            ) == 1
1198            {
1199                Ok(XOnlyPublicKey(pk))
1200            } else {
1201                Err(Error::InvalidPublicKey)
1202            }
1203        }
1204    }
1205
1206    #[inline]
1207    /// Serializes the key as a byte-encoded x coordinate value (32 bytes).
1208    pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
1209        let mut ret = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
1210
1211        unsafe {
1212            let err = ffi::secp256k1_xonly_pubkey_serialize(
1213                ffi::secp256k1_context_no_precomp,
1214                ret.as_mut_c_ptr(),
1215                self.as_c_ptr(),
1216            );
1217            debug_assert_eq!(err, 1);
1218        }
1219        ret
1220    }
1221
1222    /// Tweaks an [`XOnlyPublicKey`] by adding the generator multiplied with the given tweak to it.
1223    ///
1224    /// # Returns
1225    ///
1226    /// The newly tweaked key plus an opaque type representing the parity of the tweaked key, this
1227    /// should be provided to `tweak_add_check` which can be used to verify a tweak more efficiently
1228    /// than regenerating it and checking equality.
1229    ///
1230    /// # Errors
1231    ///
1232    /// If the resulting key would be invalid.
1233    ///
1234    /// # Examples
1235    ///
1236    /// ```
1237    /// # #[cfg(feature =  "rand-std")] {
1238    /// use secp256k1::{Secp256k1, Keypair, Scalar, XOnlyPublicKey};
1239    ///
1240    /// let secp = Secp256k1::new();
1241    /// let tweak = Scalar::random();
1242    ///
1243    /// let mut keypair = Keypair::new(&secp, &mut rand::thread_rng());
1244    /// let (xonly, _parity) = keypair.x_only_public_key();
1245    /// let tweaked = xonly.add_tweak(&secp, &tweak).expect("Improbable to fail with a randomly generated tweak");
1246    /// # }
1247    /// ```
1248    pub fn add_tweak<V: Verification>(
1249        mut self,
1250        secp: &Secp256k1<V>,
1251        tweak: &Scalar,
1252    ) -> Result<(XOnlyPublicKey, Parity), Error> {
1253        let mut pk_parity = 0;
1254        unsafe {
1255            let mut pubkey = ffi::PublicKey::new();
1256            let mut err = ffi::secp256k1_xonly_pubkey_tweak_add(
1257                secp.ctx.as_ptr(),
1258                &mut pubkey,
1259                self.as_c_ptr(),
1260                tweak.as_c_ptr(),
1261            );
1262            if err != 1 {
1263                return Err(Error::InvalidTweak);
1264            }
1265
1266            err = ffi::secp256k1_xonly_pubkey_from_pubkey(
1267                secp.ctx.as_ptr(),
1268                &mut self.0,
1269                &mut pk_parity,
1270                &pubkey,
1271            );
1272            if err == 0 {
1273                return Err(Error::InvalidPublicKey);
1274            }
1275
1276            let parity = Parity::from_i32(pk_parity)?;
1277            Ok((self, parity))
1278        }
1279    }
1280
1281    /// Verifies that a tweak produced by [`XOnlyPublicKey::add_tweak`] was computed correctly.
1282    ///
1283    /// Should be called on the original untweaked key. Takes the tweaked key and output parity from
1284    /// [`XOnlyPublicKey::add_tweak`] as input.
1285    ///
1286    /// Currently this is not much more efficient than just recomputing the tweak and checking
1287    /// equality. However, in future this API will support batch verification, which is
1288    /// significantly faster, so it is wise to design protocols with this in mind.
1289    ///
1290    /// # Returns
1291    ///
1292    /// True if tweak and check is successful, false otherwise.
1293    ///
1294    /// # Examples
1295    ///
1296    /// ```
1297    /// # #[cfg(feature =  "rand-std")] {
1298    /// use secp256k1::{Secp256k1, Keypair, Scalar};
1299    ///
1300    /// let secp = Secp256k1::new();
1301    /// let tweak = Scalar::random();
1302    ///
1303    /// let mut keypair = Keypair::new(&secp, &mut rand::thread_rng());
1304    /// let (mut public_key, _) = keypair.x_only_public_key();
1305    /// let original = public_key;
1306    /// let (tweaked, parity) = public_key.add_tweak(&secp, &tweak).expect("Improbable to fail with a randomly generated tweak");
1307    /// assert!(original.tweak_add_check(&secp, &tweaked, parity, tweak));
1308    /// # }
1309    /// ```
1310    pub fn tweak_add_check<V: Verification>(
1311        &self,
1312        secp: &Secp256k1<V>,
1313        tweaked_key: &Self,
1314        tweaked_parity: Parity,
1315        tweak: Scalar,
1316    ) -> bool {
1317        let tweaked_ser = tweaked_key.serialize();
1318        unsafe {
1319            let err = ffi::secp256k1_xonly_pubkey_tweak_add_check(
1320                secp.ctx.as_ptr(),
1321                tweaked_ser.as_c_ptr(),
1322                tweaked_parity.to_i32(),
1323                &self.0,
1324                tweak.as_c_ptr(),
1325            );
1326
1327            err == 1
1328        }
1329    }
1330
1331    /// Returns the [`PublicKey`] for this [`XOnlyPublicKey`].
1332    ///
1333    /// This is equivalent to using [`PublicKey::from_xonly_and_parity(self, parity)`].
1334    #[inline]
1335    pub fn public_key(&self, parity: Parity) -> PublicKey {
1336        PublicKey::from_x_only_public_key(*self, parity)
1337    }
1338
1339    /// Checks that `sig` is a valid schnorr signature for `msg` using this public key.
1340    pub fn verify<C: Verification>(
1341        &self,
1342        secp: &Secp256k1<C>,
1343        msg: &Message,
1344        sig: &schnorr::Signature,
1345    ) -> Result<(), Error> {
1346        secp.verify_schnorr(sig, msg, self)
1347    }
1348}
1349
1350/// Represents the parity passed between FFI function calls.
1351#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
1352pub enum Parity {
1353    /// Even parity.
1354    Even = 0,
1355    /// Odd parity.
1356    Odd = 1,
1357}
1358
1359impl Parity {
1360    /// Converts parity into an integer (byte) value.
1361    ///
1362    /// This returns `0` for even parity and `1` for odd parity.
1363    pub fn to_u8(self) -> u8 { self as u8 }
1364
1365    /// Converts parity into an integer value.
1366    ///
1367    /// This returns `0` for even parity and `1` for odd parity.
1368    pub fn to_i32(self) -> i32 { self as i32 }
1369
1370    /// Constructs a [`Parity`] from a byte.
1371    ///
1372    /// The only allowed values are `0` meaning even parity and `1` meaning odd.
1373    /// Other values result in error being returned.
1374    pub fn from_u8(parity: u8) -> Result<Parity, InvalidParityValue> {
1375        Parity::from_i32(parity.into())
1376    }
1377
1378    /// Constructs a [`Parity`] from a signed integer.
1379    ///
1380    /// The only allowed values are `0` meaning even parity and `1` meaning odd.
1381    /// Other values result in error being returned.
1382    pub fn from_i32(parity: i32) -> Result<Parity, InvalidParityValue> {
1383        match parity {
1384            0 => Ok(Parity::Even),
1385            1 => Ok(Parity::Odd),
1386            _ => Err(InvalidParityValue(parity)),
1387        }
1388    }
1389}
1390
1391/// `Even` for `0`, `Odd` for `1`, error for anything else
1392impl TryFrom<i32> for Parity {
1393    type Error = InvalidParityValue;
1394
1395    fn try_from(parity: i32) -> Result<Self, Self::Error> { Self::from_i32(parity) }
1396}
1397
1398/// `Even` for `0`, `Odd` for `1`, error for anything else
1399impl TryFrom<u8> for Parity {
1400    type Error = InvalidParityValue;
1401
1402    fn try_from(parity: u8) -> Result<Self, Self::Error> { Self::from_u8(parity) }
1403}
1404
1405/// The conversion returns `0` for even parity and `1` for odd.
1406impl From<Parity> for i32 {
1407    fn from(parity: Parity) -> i32 { parity.to_i32() }
1408}
1409
1410/// The conversion returns `0` for even parity and `1` for odd.
1411impl From<Parity> for u8 {
1412    fn from(parity: Parity) -> u8 { parity.to_u8() }
1413}
1414
1415/// Returns even parity if the operands are equal, odd otherwise.
1416impl BitXor for Parity {
1417    type Output = Parity;
1418
1419    fn bitxor(self, rhs: Parity) -> Self::Output {
1420        // This works because Parity has only two values (i.e. only 1 bit of information).
1421        if self == rhs {
1422            Parity::Even // 1^1==0 and 0^0==0
1423        } else {
1424            Parity::Odd // 1^0==1 and 0^1==1
1425        }
1426    }
1427}
1428
1429/// Error returned when conversion from an integer to `Parity` fails.
1430//
1431// Note that we don't allow inspecting the value because we may change the type.
1432// Yes, this comment is intentionally NOT doc comment.
1433// Too many derives for compatibility with current Error type.
1434#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
1435pub struct InvalidParityValue(i32);
1436
1437impl fmt::Display for InvalidParityValue {
1438    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1439        write!(f, "invalid value {} for Parity - must be 0 or 1", self.0)
1440    }
1441}
1442
1443#[cfg(feature = "std")]
1444impl std::error::Error for InvalidParityValue {}
1445
1446impl From<InvalidParityValue> for Error {
1447    fn from(error: InvalidParityValue) -> Self { Error::InvalidParityValue(error) }
1448}
1449
1450/// The parity is serialized as `u8` - `0` for even, `1` for odd.
1451#[cfg(feature = "serde")]
1452impl serde::Serialize for Parity {
1453    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1454        s.serialize_u8(self.to_u8())
1455    }
1456}
1457
1458/// The parity is deserialized as `u8` - `0` for even, `1` for odd.
1459#[cfg(feature = "serde")]
1460impl<'de> serde::Deserialize<'de> for Parity {
1461    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1462        struct Visitor;
1463
1464        impl<'de> serde::de::Visitor<'de> for Visitor {
1465            type Value = Parity;
1466
1467            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1468                formatter.write_str("8-bit integer (byte) with value 0 or 1")
1469            }
1470
1471            fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1472            where
1473                E: serde::de::Error,
1474            {
1475                use serde::de::Unexpected;
1476
1477                Parity::from_u8(v)
1478                    .map_err(|_| E::invalid_value(Unexpected::Unsigned(v.into()), &"0 or 1"))
1479            }
1480        }
1481
1482        d.deserialize_u8(Visitor)
1483    }
1484}
1485
1486impl CPtr for XOnlyPublicKey {
1487    type Target = ffi::XOnlyPublicKey;
1488    fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
1489
1490    fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
1491}
1492
1493/// Creates a new schnorr public key from a FFI x-only public key.
1494impl From<ffi::XOnlyPublicKey> for XOnlyPublicKey {
1495    #[inline]
1496    fn from(pk: ffi::XOnlyPublicKey) -> XOnlyPublicKey { XOnlyPublicKey(pk) }
1497}
1498
1499impl From<PublicKey> for XOnlyPublicKey {
1500    fn from(src: PublicKey) -> XOnlyPublicKey {
1501        unsafe {
1502            let mut pk = ffi::XOnlyPublicKey::new();
1503            assert_eq!(
1504                1,
1505                ffi::secp256k1_xonly_pubkey_from_pubkey(
1506                    ffi::secp256k1_context_no_precomp,
1507                    &mut pk,
1508                    ptr::null_mut(),
1509                    src.as_c_ptr(),
1510                )
1511            );
1512            XOnlyPublicKey(pk)
1513        }
1514    }
1515}
1516
1517#[cfg(feature = "serde")]
1518impl serde::Serialize for XOnlyPublicKey {
1519    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1520        if s.is_human_readable() {
1521            s.collect_str(self)
1522        } else {
1523            let mut tuple = s.serialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE)?;
1524            for byte in self.serialize().iter() {
1525                tuple.serialize_element(&byte)?;
1526            }
1527            tuple.end()
1528        }
1529    }
1530}
1531
1532#[cfg(feature = "serde")]
1533impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
1534    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1535        if d.is_human_readable() {
1536            d.deserialize_str(super::serde_util::FromStrVisitor::new(
1537                "a hex string representing 32 byte schnorr public key",
1538            ))
1539        } else {
1540            let visitor = super::serde_util::Tuple32Visitor::new(
1541                "raw 32 bytes schnorr public key",
1542                XOnlyPublicKey::from_slice,
1543            );
1544            d.deserialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE, visitor)
1545        }
1546    }
1547}
1548
1549#[cfg(test)]
1550#[allow(unused_imports)]
1551mod test {
1552    use core::str::FromStr;
1553
1554    #[cfg(feature = "rand")]
1555    use rand::{self, rngs::mock::StepRng, RngCore};
1556    use serde_test::{Configure, Token};
1557    #[cfg(target_arch = "wasm32")]
1558    use wasm_bindgen_test::wasm_bindgen_test as test;
1559
1560    use super::{Keypair, Parity, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, *};
1561    use crate::Error::{InvalidPublicKey, InvalidSecretKey};
1562    use crate::{constants, from_hex, to_hex, Scalar};
1563
1564    #[cfg(not(secp256k1_fuzz))]
1565    macro_rules! hex {
1566        ($hex:expr) => {{
1567            let mut result = vec![0; $hex.len() / 2];
1568            from_hex($hex, &mut result).expect("valid hex string");
1569            result
1570        }};
1571    }
1572
1573    #[test]
1574    fn skey_from_slice() {
1575        let sk = SecretKey::from_slice(&[1; 31]);
1576        assert_eq!(sk, Err(InvalidSecretKey));
1577
1578        let sk = SecretKey::from_slice(&[1; 32]);
1579        assert!(sk.is_ok());
1580    }
1581
1582    #[test]
1583    fn pubkey_from_slice() {
1584        assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
1585        assert_eq!(PublicKey::from_slice(&[1, 2, 3]), Err(InvalidPublicKey));
1586
1587        let uncompressed = PublicKey::from_slice(&[
1588            4, 54, 57, 149, 239, 162, 148, 175, 246, 254, 239, 75, 154, 152, 10, 82, 234, 224, 85,
1589            220, 40, 100, 57, 121, 30, 162, 94, 156, 135, 67, 74, 49, 179, 57, 236, 53, 162, 124,
1590            149, 144, 168, 77, 74, 30, 72, 211, 229, 110, 111, 55, 96, 193, 86, 227, 183, 152, 195,
1591            155, 51, 247, 123, 113, 60, 228, 188,
1592        ]);
1593        assert!(uncompressed.is_ok());
1594
1595        let compressed = PublicKey::from_slice(&[
1596            3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41,
1597            111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78,
1598        ]);
1599        assert!(compressed.is_ok());
1600    }
1601
1602    #[test]
1603    #[cfg(feature = "rand-std")]
1604    fn keypair_slice_round_trip() {
1605        let s = Secp256k1::new();
1606
1607        let (sk1, pk1) = s.generate_keypair(&mut rand::thread_rng());
1608        assert_eq!(SecretKey::from_slice(&sk1[..]), Ok(sk1));
1609        assert_eq!(PublicKey::from_slice(&pk1.serialize()[..]), Ok(pk1));
1610        assert_eq!(PublicKey::from_slice(&pk1.serialize_uncompressed()[..]), Ok(pk1));
1611    }
1612
1613    #[test]
1614    #[cfg(all(feature = "std", not(secp256k1_fuzz)))]
1615    fn erased_keypair_is_valid() {
1616        let s = Secp256k1::new();
1617        let kp = Keypair::from_seckey_slice(&s, &[1u8; constants::SECRET_KEY_SIZE])
1618            .expect("valid secret key");
1619        let mut kp2 = kp;
1620        kp2.non_secure_erase();
1621        assert!(kp.eq_fast_unstable(&kp2));
1622    }
1623
1624    #[test]
1625    #[rustfmt::skip]
1626    fn invalid_secret_key() {
1627        // Zero
1628        assert_eq!(SecretKey::from_slice(&[0; 32]), Err(InvalidSecretKey));
1629        assert_eq!(
1630            SecretKey::from_str("0000000000000000000000000000000000000000000000000000000000000000"),
1631            Err(InvalidSecretKey)
1632        );
1633        // -1
1634        assert_eq!(SecretKey::from_slice(&[0xff; 32]), Err(InvalidSecretKey));
1635        // Top of range
1636        assert!(SecretKey::from_slice(&[
1637            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1638            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
1639            0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
1640            0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
1641        ]).is_ok());
1642        // One past top of range
1643        assert!(SecretKey::from_slice(&[
1644            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1645            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
1646            0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
1647            0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41,
1648        ]).is_err());
1649    }
1650
1651    #[test]
1652    #[cfg(all(feature = "rand", feature = "alloc"))]
1653    fn test_out_of_range() {
1654        struct BadRng(u8);
1655        impl RngCore for BadRng {
1656            fn next_u32(&mut self) -> u32 { unimplemented!() }
1657            fn next_u64(&mut self) -> u64 { unimplemented!() }
1658            // This will set a secret key to a little over the
1659            // group order, then decrement with repeated calls
1660            // until it returns a valid key
1661            fn fill_bytes(&mut self, data: &mut [u8]) {
1662                #[rustfmt::skip]
1663                let group_order: [u8; 32] = [
1664                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1665                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
1666                    0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
1667                    0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41];
1668                assert_eq!(data.len(), 32);
1669                data.copy_from_slice(&group_order[..]);
1670                data[31] = self.0;
1671                self.0 -= 1;
1672            }
1673            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
1674                self.fill_bytes(dest);
1675                Ok(())
1676            }
1677        }
1678
1679        let s = Secp256k1::new();
1680        s.generate_keypair(&mut BadRng(0xff));
1681    }
1682
1683    #[test]
1684    fn test_pubkey_from_bad_slice() {
1685        // Bad sizes
1686        assert_eq!(
1687            PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE - 1]),
1688            Err(InvalidPublicKey)
1689        );
1690        assert_eq!(
1691            PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE + 1]),
1692            Err(InvalidPublicKey)
1693        );
1694        assert_eq!(
1695            PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1]),
1696            Err(InvalidPublicKey)
1697        );
1698        assert_eq!(
1699            PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 1]),
1700            Err(InvalidPublicKey)
1701        );
1702
1703        // Bad parse
1704        assert_eq!(
1705            PublicKey::from_slice(&[0xff; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE]),
1706            Err(InvalidPublicKey)
1707        );
1708        assert_eq!(
1709            PublicKey::from_slice(&[0x55; constants::PUBLIC_KEY_SIZE]),
1710            Err(InvalidPublicKey)
1711        );
1712        assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
1713    }
1714
1715    #[test]
1716    fn test_seckey_from_bad_slice() {
1717        // Bad sizes
1718        assert_eq!(
1719            SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE - 1]),
1720            Err(InvalidSecretKey)
1721        );
1722        assert_eq!(
1723            SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE + 1]),
1724            Err(InvalidSecretKey)
1725        );
1726        // Bad parse
1727        assert_eq!(
1728            SecretKey::from_slice(&[0xff; constants::SECRET_KEY_SIZE]),
1729            Err(InvalidSecretKey)
1730        );
1731        assert_eq!(
1732            SecretKey::from_slice(&[0x00; constants::SECRET_KEY_SIZE]),
1733            Err(InvalidSecretKey)
1734        );
1735        assert_eq!(SecretKey::from_slice(&[]), Err(InvalidSecretKey));
1736    }
1737
1738    #[test]
1739    #[cfg(all(feature = "rand", feature = "alloc"))]
1740    fn test_debug_output() {
1741        let s = Secp256k1::new();
1742        let (sk, _) = s.generate_keypair(&mut StepRng::new(1, 1));
1743
1744        assert_eq!(&format!("{:?}", sk), "SecretKey(#d3e0c51a23169bb5)");
1745
1746        let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
1747        assert_eq!(
1748            to_hex(&sk[..], &mut buf).unwrap(),
1749            "0100000000000000020000000000000003000000000000000400000000000000"
1750        );
1751    }
1752
1753    #[test]
1754    #[cfg(feature = "alloc")]
1755    fn test_display_output() {
1756        #[rustfmt::skip]
1757        static SK_BYTES: [u8; 32] = [
1758            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
1759            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1760            0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
1761            0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1762        ];
1763
1764        #[cfg(not(secp256k1_fuzz))]
1765        let s = Secp256k1::signing_only();
1766        let sk = SecretKey::from_slice(&SK_BYTES).expect("sk");
1767
1768        // In fuzzing mode secret->public key derivation is different, so
1769        // hard-code the expected result.
1770        #[cfg(not(secp256k1_fuzz))]
1771        let pk = PublicKey::from_secret_key(&s, &sk);
1772        #[cfg(secp256k1_fuzz)]
1773        let pk = PublicKey::from_slice(&[
1774            0x02, 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f, 0x1c, 0x97, 0x09, 0xe2, 0x30,
1775            0x92, 0x06, 0x7d, 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54, 0x4a, 0xc8, 0x87,
1776            0xfe, 0x91, 0xdd, 0xd1, 0x66,
1777        ])
1778        .expect("pk");
1779
1780        assert_eq!(
1781            sk.display_secret().to_string(),
1782            "01010101010101010001020304050607ffff0000ffff00006363636363636363"
1783        );
1784        assert_eq!(
1785            SecretKey::from_str("01010101010101010001020304050607ffff0000ffff00006363636363636363")
1786                .unwrap(),
1787            sk
1788        );
1789        assert_eq!(
1790            pk.to_string(),
1791            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
1792        );
1793        assert_eq!(
1794            PublicKey::from_str(
1795                "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
1796            )
1797            .unwrap(),
1798            pk
1799        );
1800        assert_eq!(
1801            PublicKey::from_str(
1802                "04\
1803                18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
1804                84B84DB303A340CD7D6823EE88174747D12A67D2F8F2F9BA40846EE5EE7A44F6"
1805            )
1806            .unwrap(),
1807            pk
1808        );
1809
1810        assert!(SecretKey::from_str(
1811            "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1812        )
1813        .is_err());
1814        assert!(SecretKey::from_str(
1815            "01010101010101010001020304050607ffff0000ffff0000636363636363636363"
1816        )
1817        .is_err());
1818        assert!(SecretKey::from_str(
1819            "01010101010101010001020304050607ffff0000ffff0000636363636363636"
1820        )
1821        .is_err());
1822        assert!(SecretKey::from_str(
1823            "01010101010101010001020304050607ffff0000ffff000063636363636363"
1824        )
1825        .is_err());
1826        assert!(SecretKey::from_str(
1827            "01010101010101010001020304050607ffff0000ffff000063636363636363xx"
1828        )
1829        .is_err());
1830        assert!(PublicKey::from_str(
1831            "0300000000000000000000000000000000000000000000000000000000000000000"
1832        )
1833        .is_err());
1834        assert!(PublicKey::from_str(
1835            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16601"
1836        )
1837        .is_err());
1838        assert!(PublicKey::from_str(
1839            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16"
1840        )
1841        .is_err());
1842        assert!(PublicKey::from_str(
1843            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
1844        )
1845        .is_err());
1846        assert!(PublicKey::from_str(
1847            "xx0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
1848        )
1849        .is_err());
1850
1851        let long_str = "a".repeat(1024 * 1024);
1852        assert!(SecretKey::from_str(&long_str).is_err());
1853        assert!(PublicKey::from_str(&long_str).is_err());
1854    }
1855
1856    #[test]
1857    // In fuzzing mode the Y coordinate is expected to match the X, so this
1858    // test uses invalid public keys.
1859    #[cfg(not(secp256k1_fuzz))]
1860    #[cfg(all(feature = "alloc", feature = "rand"))]
1861    fn test_pubkey_serialize() {
1862        let s = Secp256k1::new();
1863        let (_, pk1) = s.generate_keypair(&mut StepRng::new(1, 1));
1864        assert_eq!(
1865            &pk1.serialize_uncompressed()[..],
1866            &[
1867                4, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
1868                9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229, 185, 28, 165,
1869                110, 27, 3, 162, 126, 238, 167, 157, 242, 221, 76, 251, 237, 34, 231, 72, 39, 245,
1870                3, 191, 64, 111, 170, 117, 103, 82, 28, 102, 163
1871            ][..]
1872        );
1873        assert_eq!(
1874            &pk1.serialize()[..],
1875            &[
1876                3, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
1877                9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229
1878            ][..]
1879        );
1880    }
1881
1882    #[test]
1883    #[cfg(feature = "rand-std")]
1884    fn tweak_add_arbitrary_data() {
1885        let s = Secp256k1::new();
1886
1887        let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1888        assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); // Sanity check.
1889
1890        // TODO: This would be better tested with a _lot_ of different tweaks.
1891        let tweak = Scalar::random();
1892
1893        let tweaked_sk = sk.add_tweak(&tweak).unwrap();
1894        assert_ne!(sk, tweaked_sk); // Make sure we did something.
1895        let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
1896        assert_ne!(pk, tweaked_pk);
1897
1898        assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
1899    }
1900
1901    #[test]
1902    #[cfg(feature = "rand-std")]
1903    fn tweak_add_zero() {
1904        let s = Secp256k1::new();
1905
1906        let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1907
1908        let tweak = Scalar::ZERO;
1909
1910        let tweaked_sk = sk.add_tweak(&tweak).unwrap();
1911        assert_eq!(sk, tweaked_sk); // Tweak by zero does nothing.
1912        let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
1913        assert_eq!(pk, tweaked_pk);
1914    }
1915
1916    #[test]
1917    #[cfg(feature = "rand-std")]
1918    fn tweak_mul_arbitrary_data() {
1919        let s = Secp256k1::new();
1920
1921        let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1922        assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); // Sanity check.
1923
1924        // TODO: This would be better tested with a _lot_ of different tweaks.
1925        let tweak = Scalar::random();
1926
1927        let tweaked_sk = sk.mul_tweak(&tweak).unwrap();
1928        assert_ne!(sk, tweaked_sk); // Make sure we did something.
1929        let tweaked_pk = pk.mul_tweak(&s, &tweak).unwrap();
1930        assert_ne!(pk, tweaked_pk);
1931
1932        assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
1933    }
1934
1935    #[test]
1936    #[cfg(feature = "rand-std")]
1937    fn tweak_mul_zero() {
1938        let s = Secp256k1::new();
1939        let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
1940
1941        let tweak = Scalar::ZERO;
1942        assert!(sk.mul_tweak(&tweak).is_err())
1943    }
1944
1945    #[test]
1946    #[cfg(feature = "rand-std")]
1947    fn test_negation() {
1948        let s = Secp256k1::new();
1949
1950        let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1951
1952        assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); // Sanity check.
1953
1954        let neg = sk.negate();
1955        assert_ne!(sk, neg);
1956        let back_sk = neg.negate();
1957        assert_eq!(sk, back_sk);
1958
1959        let neg = pk.negate(&s);
1960        assert_ne!(pk, neg);
1961        let back_pk = neg.negate(&s);
1962        assert_eq!(pk, back_pk);
1963
1964        assert_eq!(PublicKey::from_secret_key(&s, &back_sk), pk);
1965    }
1966
1967    #[test]
1968    #[cfg(feature = "rand-std")]
1969    fn pubkey_hash() {
1970        use std::collections::hash_map::DefaultHasher;
1971        use std::collections::HashSet;
1972        use std::hash::{Hash, Hasher};
1973
1974        fn hash<T: Hash>(t: &T) -> u64 {
1975            let mut s = DefaultHasher::new();
1976            t.hash(&mut s);
1977            s.finish()
1978        }
1979
1980        let s = Secp256k1::new();
1981        let mut set = HashSet::new();
1982        const COUNT: usize = 1024;
1983        for _ in 0..COUNT {
1984            let (_, pk) = s.generate_keypair(&mut rand::thread_rng());
1985            let hash = hash(&pk);
1986            assert!(!set.contains(&hash));
1987            set.insert(hash);
1988        }
1989        assert_eq!(set.len(), COUNT);
1990    }
1991
1992    #[test]
1993    #[cfg(not(secp256k1_fuzz))]
1994    fn pubkey_combine() {
1995        let compressed1 = PublicKey::from_slice(&hex!(
1996            "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
1997        ))
1998        .unwrap();
1999        let compressed2 = PublicKey::from_slice(&hex!(
2000            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2001        ))
2002        .unwrap();
2003        let exp_sum = PublicKey::from_slice(&hex!(
2004            "0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07"
2005        ))
2006        .unwrap();
2007
2008        let sum1 = compressed1.combine(&compressed2);
2009        assert!(sum1.is_ok());
2010        let sum2 = compressed2.combine(&compressed1);
2011        assert!(sum2.is_ok());
2012        assert_eq!(sum1, sum2);
2013        assert_eq!(sum1.unwrap(), exp_sum);
2014    }
2015
2016    #[test]
2017    #[cfg(not(secp256k1_fuzz))]
2018    fn pubkey_combine_keys() {
2019        let compressed1 = PublicKey::from_slice(&hex!(
2020            "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
2021        ))
2022        .unwrap();
2023        let compressed2 = PublicKey::from_slice(&hex!(
2024            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2025        ))
2026        .unwrap();
2027        let compressed3 = PublicKey::from_slice(&hex!(
2028            "03e74897d8644eb3e5b391ca2ab257aec2080f4d1a95cad57e454e47f021168eb0"
2029        ))
2030        .unwrap();
2031        let exp_sum = PublicKey::from_slice(&hex!(
2032            "0252d73a47f66cf341e5651542f0348f452b7c793af62a6d8bff75ade703a451ad"
2033        ))
2034        .unwrap();
2035
2036        let sum1 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
2037        assert!(sum1.is_ok());
2038        let sum2 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
2039        assert!(sum2.is_ok());
2040        assert_eq!(sum1, sum2);
2041        assert_eq!(sum1.unwrap(), exp_sum);
2042    }
2043
2044    #[test]
2045    #[cfg(not(secp256k1_fuzz))]
2046    fn pubkey_combine_keys_empty_slice() {
2047        assert!(PublicKey::combine_keys(&[]).is_err());
2048    }
2049
2050    #[test]
2051    #[cfg(feature = "rand-std")]
2052    fn create_pubkey_combine() {
2053        let s = Secp256k1::new();
2054
2055        let (sk1, pk1) = s.generate_keypair(&mut rand::thread_rng());
2056        let (sk2, pk2) = s.generate_keypair(&mut rand::thread_rng());
2057
2058        let sum1 = pk1.combine(&pk2);
2059        assert!(sum1.is_ok());
2060        let sum2 = pk2.combine(&pk1);
2061        assert!(sum2.is_ok());
2062        assert_eq!(sum1, sum2);
2063
2064        let tweaked = sk1.add_tweak(&Scalar::from(sk2)).unwrap();
2065        let sksum = PublicKey::from_secret_key(&s, &tweaked);
2066        assert_eq!(Ok(sksum), sum1);
2067    }
2068
2069    #[cfg(not(secp256k1_fuzz))]
2070    #[test]
2071    #[allow(clippy::nonminimal_bool)]
2072    fn pubkey_equal() {
2073        let pk1 = PublicKey::from_slice(&hex!(
2074            "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
2075        ))
2076        .unwrap();
2077        let pk2 = pk1;
2078        let pk3 = PublicKey::from_slice(&hex!(
2079            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2080        ))
2081        .unwrap();
2082
2083        assert_eq!(pk1, pk2);
2084        assert!(pk1 <= pk2);
2085        assert!(pk2 <= pk1);
2086        assert!(!(pk2 < pk1));
2087        assert!(!(pk1 < pk2));
2088
2089        assert!(pk3 > pk1);
2090        assert!(pk1 < pk3);
2091        assert!(pk3 >= pk1);
2092        assert!(pk1 <= pk3);
2093    }
2094
2095    #[test]
2096    #[cfg(all(feature = "serde", feature = "alloc"))]
2097    fn test_serde() {
2098        use serde_test::{assert_tokens, Configure, Token};
2099        #[rustfmt::skip]
2100        static SK_BYTES: [u8; 32] = [
2101            1, 1, 1, 1, 1, 1, 1, 1,
2102            0, 1, 2, 3, 4, 5, 6, 7,
2103            0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2104            99, 99, 99, 99, 99, 99, 99, 99
2105        ];
2106        static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
2107
2108        #[cfg(secp256k1_fuzz)]
2109        #[rustfmt::skip]
2110        static PK_BYTES: [u8; 33] = [
2111            0x02,
2112            0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
2113            0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
2114            0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
2115            0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66,
2116        ];
2117        static PK_STR: &str = "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2118
2119        #[cfg(not(secp256k1_fuzz))]
2120        let s = Secp256k1::new();
2121        let sk = SecretKey::from_slice(&SK_BYTES).unwrap();
2122
2123        // In fuzzing mode secret->public key derivation is different, so
2124        // hard-code the expected result.
2125        #[cfg(not(secp256k1_fuzz))]
2126        let pk = PublicKey::from_secret_key(&s, &sk);
2127        #[cfg(secp256k1_fuzz)]
2128        let pk = PublicKey::from_slice(&PK_BYTES).expect("pk");
2129
2130        #[rustfmt::skip]
2131        assert_tokens(&sk.compact(), &[
2132            Token::Tuple{ len: 32 },
2133            Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
2134            Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
2135            Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
2136            Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
2137            Token::TupleEnd
2138        ]);
2139
2140        assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
2141        assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
2142        assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
2143
2144        #[rustfmt::skip]
2145        assert_tokens(&pk.compact(), &[
2146            Token::Tuple{ len: 33 },
2147            Token::U8(0x02),
2148            Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
2149            Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
2150            Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
2151            Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
2152            Token::TupleEnd
2153        ]);
2154
2155        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
2156        assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
2157        assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
2158    }
2159
2160    #[test]
2161    #[cfg(feature = "rand-std")]
2162    fn test_tweak_add_then_tweak_add_check() {
2163        let s = Secp256k1::new();
2164
2165        // TODO: 10 times is arbitrary, we should test this a _lot_ of times.
2166        for _ in 0..10 {
2167            let tweak = Scalar::random();
2168
2169            let kp = Keypair::new(&s, &mut rand::thread_rng());
2170            let (xonly, _) = XOnlyPublicKey::from_keypair(&kp);
2171
2172            let tweaked_kp = kp.add_xonly_tweak(&s, &tweak).expect("keypair tweak add failed");
2173            let (tweaked_xonly, parity) =
2174                xonly.add_tweak(&s, &tweak).expect("xonly pubkey tweak failed");
2175
2176            let (want_tweaked_xonly, tweaked_kp_parity) = XOnlyPublicKey::from_keypair(&tweaked_kp);
2177
2178            assert_eq!(tweaked_xonly, want_tweaked_xonly);
2179            assert_eq!(parity, tweaked_kp_parity);
2180
2181            assert!(xonly.tweak_add_check(&s, &tweaked_xonly, parity, tweak));
2182        }
2183    }
2184
2185    #[test]
2186    fn test_from_key_pubkey() {
2187        let kpk1 = PublicKey::from_str(
2188            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443",
2189        )
2190        .unwrap();
2191        let kpk2 = PublicKey::from_str(
2192            "0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07",
2193        )
2194        .unwrap();
2195
2196        let pk1 = XOnlyPublicKey::from(kpk1);
2197        let pk2 = XOnlyPublicKey::from(kpk2);
2198
2199        assert_eq!(pk1.serialize()[..], kpk1.serialize()[1..]);
2200        assert_eq!(pk2.serialize()[..], kpk2.serialize()[1..]);
2201    }
2202
2203    #[test]
2204    #[cfg(all(feature = "global-context", feature = "serde"))]
2205    fn test_serde_keypair() {
2206        use serde::{Deserialize, Deserializer, Serialize, Serializer};
2207        use serde_test::{assert_tokens, Configure, Token};
2208
2209        use crate::key::Keypair;
2210        use crate::SECP256K1;
2211
2212        #[rustfmt::skip]
2213        static SK_BYTES: [u8; 32] = [
2214            1, 1, 1, 1, 1, 1, 1, 1,
2215            0, 1, 2, 3, 4, 5, 6, 7,
2216            0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2217            99, 99, 99, 99, 99, 99, 99, 99
2218        ];
2219        static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
2220
2221        let sk = Keypair::from_seckey_slice(SECP256K1, &SK_BYTES).unwrap();
2222        #[rustfmt::skip]
2223        assert_tokens(&sk.compact(), &[
2224            Token::Tuple{ len: 32 },
2225            Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
2226            Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
2227            Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
2228            Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
2229            Token::TupleEnd
2230        ]);
2231
2232        assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
2233        assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
2234        assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
2235    }
2236
2237    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2238    fn keys() -> (SecretKey, PublicKey, Keypair, XOnlyPublicKey) {
2239        let secp = Secp256k1::new();
2240
2241        #[rustfmt::skip]
2242        static SK_BYTES: [u8; 32] = [
2243            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
2244            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
2245            0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
2246            0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
2247        ];
2248
2249        #[rustfmt::skip]
2250        static PK_BYTES: [u8; 32] = [
2251            0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
2252            0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
2253            0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
2254            0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66
2255        ];
2256
2257        let mut pk_bytes = [0u8; 33];
2258        pk_bytes[0] = 0x02; // Use positive Y co-ordinate.
2259        pk_bytes[1..].clone_from_slice(&PK_BYTES);
2260
2261        let sk = SecretKey::from_slice(&SK_BYTES).expect("failed to parse sk bytes");
2262        let pk = PublicKey::from_slice(&pk_bytes).expect("failed to create pk from iterator");
2263        let kp = Keypair::from_secret_key(&secp, &sk);
2264        let xonly = XOnlyPublicKey::from_slice(&PK_BYTES).expect("failed to get xonly from slice");
2265
2266        (sk, pk, kp, xonly)
2267    }
2268
2269    #[test]
2270    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2271    fn convert_public_key_to_xonly_public_key() {
2272        let (_sk, pk, _kp, want) = keys();
2273        let (got, parity) = pk.x_only_public_key();
2274
2275        assert_eq!(parity, Parity::Even);
2276        assert_eq!(got, want)
2277    }
2278
2279    #[test]
2280    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2281    fn convert_secret_key_to_public_key() {
2282        let secp = Secp256k1::new();
2283
2284        let (sk, want, _kp, _xonly) = keys();
2285        let got = sk.public_key(&secp);
2286
2287        assert_eq!(got, want)
2288    }
2289
2290    #[test]
2291    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2292    fn convert_secret_key_to_x_only_public_key() {
2293        let secp = Secp256k1::new();
2294
2295        let (sk, _pk, _kp, want) = keys();
2296        let (got, parity) = sk.x_only_public_key(&secp);
2297
2298        assert_eq!(parity, Parity::Even);
2299        assert_eq!(got, want)
2300    }
2301
2302    #[test]
2303    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2304    fn convert_keypair_to_public_key() {
2305        let (_sk, want, kp, _xonly) = keys();
2306        let got = kp.public_key();
2307
2308        assert_eq!(got, want)
2309    }
2310
2311    #[test]
2312    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2313    fn convert_keypair_to_x_only_public_key() {
2314        let (_sk, _pk, kp, want) = keys();
2315        let (got, parity) = kp.x_only_public_key();
2316
2317        assert_eq!(parity, Parity::Even);
2318        assert_eq!(got, want)
2319    }
2320
2321    // SecretKey -> Keypair -> SecretKey
2322    #[test]
2323    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2324    fn roundtrip_secret_key_via_keypair() {
2325        let secp = Secp256k1::new();
2326        let (sk, _pk, _kp, _xonly) = keys();
2327
2328        let kp = sk.keypair(&secp);
2329        let back = kp.secret_key();
2330
2331        assert_eq!(back, sk)
2332    }
2333
2334    // Keypair -> SecretKey -> Keypair
2335    #[test]
2336    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2337    fn roundtrip_keypair_via_secret_key() {
2338        let secp = Secp256k1::new();
2339        let (_sk, _pk, kp, _xonly) = keys();
2340
2341        let sk = kp.secret_key();
2342        let back = sk.keypair(&secp);
2343
2344        assert_eq!(back, kp)
2345    }
2346
2347    // XOnlyPublicKey -> PublicKey -> XOnlyPublicKey
2348    #[test]
2349    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2350    fn roundtrip_x_only_public_key_via_public_key() {
2351        let (_sk, _pk, _kp, xonly) = keys();
2352
2353        let pk = xonly.public_key(Parity::Even);
2354        let (back, parity) = pk.x_only_public_key();
2355
2356        assert_eq!(parity, Parity::Even);
2357        assert_eq!(back, xonly)
2358    }
2359
2360    // PublicKey -> XOnlyPublicKey -> PublicKey
2361    #[test]
2362    #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2363    fn roundtrip_public_key_via_x_only_public_key() {
2364        let (_sk, pk, _kp, _xonly) = keys();
2365
2366        let (xonly, parity) = pk.x_only_public_key();
2367        let back = xonly.public_key(parity);
2368
2369        assert_eq!(back, pk)
2370    }
2371
2372    #[test]
2373    fn public_key_from_x_only_public_key_and_odd_parity() {
2374        let s = "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2375        let mut want = String::from("03");
2376        want.push_str(s);
2377
2378        let xonly = XOnlyPublicKey::from_str(s).expect("failed to parse xonly pubkey string");
2379        let pk = xonly.public_key(Parity::Odd);
2380        let got = format!("{}", pk);
2381
2382        assert_eq!(got, want)
2383    }
2384
2385    #[test]
2386    #[cfg(not(secp256k1_fuzz))]
2387    #[cfg(all(feature = "global-context", feature = "serde"))]
2388    fn test_serde_x_only_pubkey() {
2389        use serde_test::{assert_tokens, Configure, Token};
2390
2391        #[rustfmt::skip]
2392        static SK_BYTES: [u8; 32] = [
2393            1, 1, 1, 1, 1, 1, 1, 1,
2394            0, 1, 2, 3, 4, 5, 6, 7,
2395            0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2396            99, 99, 99, 99, 99, 99, 99, 99
2397        ];
2398
2399        static PK_STR: &str = "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2400
2401        let kp = Keypair::from_seckey_slice(crate::SECP256K1, &SK_BYTES).unwrap();
2402        let (pk, _parity) = XOnlyPublicKey::from_keypair(&kp);
2403
2404        #[rustfmt::skip]
2405        assert_tokens(&pk.compact(), &[
2406            Token::Tuple{ len: 32 },
2407            Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
2408            Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
2409            Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
2410            Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
2411            Token::TupleEnd
2412        ]);
2413
2414        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
2415        assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
2416        assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
2417    }
2418
2419    #[test]
2420    #[cfg(feature = "rand-std")]
2421    fn test_keypair_from_str() {
2422        let ctx = crate::Secp256k1::new();
2423        let keypair = Keypair::new(&ctx, &mut rand::thread_rng());
2424        let mut buf = [0_u8; constants::SECRET_KEY_SIZE * 2]; // Holds hex digits.
2425        let s = to_hex(&keypair.secret_key().secret_bytes(), &mut buf).unwrap();
2426        let parsed_key = Keypair::from_str(s).unwrap();
2427        assert_eq!(parsed_key, keypair);
2428    }
2429
2430    #[test]
2431    #[cfg(all(any(feature = "alloc", feature = "global-context"), feature = "serde"))]
2432    fn test_keypair_deserialize_serde() {
2433        let ctx = crate::Secp256k1::new();
2434        let sec_key_str = "4242424242424242424242424242424242424242424242424242424242424242";
2435        let keypair = Keypair::from_seckey_str(&ctx, sec_key_str).unwrap();
2436
2437        serde_test::assert_tokens(&keypair.readable(), &[Token::String(sec_key_str)]);
2438
2439        let sec_key_bytes = keypair.secret_key().secret_bytes();
2440        let tokens = std::iter::once(Token::Tuple { len: 32 })
2441            .chain(sec_key_bytes.iter().copied().map(Token::U8))
2442            .chain(std::iter::once(Token::TupleEnd))
2443            .collect::<Vec<_>>();
2444        serde_test::assert_tokens(&keypair.compact(), &tokens);
2445    }
2446
2447    #[test]
2448    #[should_panic(expected = "The previous implementation was panicking too")]
2449    #[cfg(not(any(feature = "alloc", feature = "global-context")))]
2450    fn test_parse_keypair_no_alloc_panic() {
2451        let key_hex = "4242424242424242424242424242424242424242424242424242424242424242";
2452        let _: Keypair = key_hex.parse().expect("We shouldn't even get this far");
2453    }
2454}
2455
2456#[cfg(bench)]
2457mod benches {
2458    use std::collections::BTreeSet;
2459
2460    use test::Bencher;
2461
2462    use crate::constants::GENERATOR_X;
2463    use crate::PublicKey;
2464
2465    #[bench]
2466    fn bench_pk_ordering(b: &mut Bencher) {
2467        let mut map = BTreeSet::new();
2468        let mut g_slice = [02u8; 33];
2469        g_slice[1..].copy_from_slice(&GENERATOR_X);
2470        let g = PublicKey::from_slice(&g_slice).unwrap();
2471        let mut pk = g;
2472        b.iter(|| {
2473            map.insert(pk);
2474            pk = pk.combine(&pk).unwrap();
2475        })
2476    }
2477}