sapio_secp256k1/
key.rs

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