secp256k1/
key.rs

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