1use 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#[derive(Copy, Clone)]
58pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
59impl_display_secret!(SecretKey);
60impl_non_secure_erase!(SecretKey, 0, [1u8; constants::SECRET_KEY_SIZE]);
61
62impl PartialEq for SecretKey {
63 #[inline]
65 fn eq(&self, other: &Self) -> bool {
66 let accum = self.0.iter().zip(&other.0).fold(0, |accum, (a, b)| accum | a ^ b);
67 unsafe { core::ptr::read_volatile(&accum) == 0 }
68 }
69}
70
71impl Eq for SecretKey {}
72
73impl AsRef<[u8; constants::SECRET_KEY_SIZE]> for SecretKey {
74 #[inline]
83 fn as_ref(&self) -> &[u8; constants::SECRET_KEY_SIZE] {
84 let SecretKey(dat) = self;
85 dat
86 }
87}
88
89impl<I> ops::Index<I> for SecretKey
90where
91 [u8]: ops::Index<I>,
92{
93 type Output = <[u8] as ops::Index<I>>::Output;
94
95 #[inline]
96 fn index(&self, index: I) -> &Self::Output { &self.0[index] }
97}
98
99impl ffi::CPtr for SecretKey {
100 type Target = u8;
101
102 fn as_c_ptr(&self) -> *const Self::Target {
103 let SecretKey(dat) = self;
104 dat.as_ptr()
105 }
106
107 fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
108 let &mut SecretKey(ref mut dat) = self;
109 dat.as_mut_ptr()
110 }
111}
112
113impl str::FromStr for SecretKey {
114 type Err = Error;
115 fn from_str(s: &str) -> Result<SecretKey, Error> {
116 let mut res = [0u8; constants::SECRET_KEY_SIZE];
117 match from_hex(s, &mut res) {
118 Ok(constants::SECRET_KEY_SIZE) => SecretKey::from_slice(&res),
119 _ => Err(Error::InvalidSecretKey),
120 }
121 }
122}
123
124#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
148#[repr(transparent)]
149pub struct PublicKey(ffi::PublicKey);
150impl_fast_comparisons!(PublicKey);
151
152impl fmt::LowerHex for PublicKey {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 let ser = self.serialize();
155 for ch in &ser[..] {
156 write!(f, "{:02x}", *ch)?;
157 }
158 Ok(())
159 }
160}
161
162impl fmt::Display for PublicKey {
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
164}
165
166impl str::FromStr for PublicKey {
167 type Err = Error;
168 fn from_str(s: &str) -> Result<PublicKey, Error> {
169 let mut res = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
170 match from_hex(s, &mut res) {
171 Ok(constants::PUBLIC_KEY_SIZE) =>
172 PublicKey::from_slice(&res[0..constants::PUBLIC_KEY_SIZE]),
173 Ok(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE) => PublicKey::from_slice(&res),
174 _ => Err(Error::InvalidPublicKey),
175 }
176 }
177}
178
179impl SecretKey {
180 #[inline]
191 #[cfg(feature = "rand")]
192 pub fn new<R: rand::Rng + ?Sized>(rng: &mut R) -> SecretKey {
193 let mut data = crate::random_32_bytes(rng);
194 unsafe {
195 while ffi::secp256k1_ec_seckey_verify(
196 ffi::secp256k1_context_no_precomp,
197 data.as_c_ptr(),
198 ) == 0
199 {
200 data = crate::random_32_bytes(rng);
201 }
202 }
203 SecretKey(data)
204 }
205
206 #[inline]
215 pub fn from_slice(data: &[u8]) -> Result<SecretKey, Error> {
216 match <[u8; constants::SECRET_KEY_SIZE]>::try_from(data) {
217 Ok(data) => {
218 unsafe {
219 if ffi::secp256k1_ec_seckey_verify(
220 ffi::secp256k1_context_no_precomp,
221 data.as_c_ptr(),
222 ) == 0
223 {
224 return Err(InvalidSecretKey);
225 }
226 }
227 Ok(SecretKey(data))
228 }
229 Err(_) => Err(InvalidSecretKey),
230 }
231 }
232
233 #[inline]
247 pub fn from_keypair(keypair: &Keypair) -> Self {
248 let mut sk = [0u8; constants::SECRET_KEY_SIZE];
249 unsafe {
250 let ret = ffi::secp256k1_keypair_sec(
251 ffi::secp256k1_context_no_precomp,
252 sk.as_mut_c_ptr(),
253 keypair.as_c_ptr(),
254 );
255 debug_assert_eq!(ret, 1);
256 }
257 SecretKey(sk)
258 }
259
260 #[cfg(feature = "hashes")]
279 #[inline]
280 pub fn from_hashed_data<H: ThirtyTwoByteHash + hashes::Hash>(data: &[u8]) -> Self {
281 <H as hashes::Hash>::hash(data).into()
282 }
283
284 #[inline]
286 pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] { self.0 }
287
288 #[inline]
290 #[must_use = "you forgot to use the negated secret key"]
291 pub fn negate(mut self) -> SecretKey {
292 unsafe {
293 let res = ffi::secp256k1_ec_seckey_negate(
294 ffi::secp256k1_context_no_precomp,
295 self.as_mut_c_ptr(),
296 );
297 debug_assert_eq!(res, 1);
298 }
299 self
300 }
301
302 #[inline]
308 pub fn add_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
309 unsafe {
310 if ffi::secp256k1_ec_seckey_tweak_add(
311 ffi::secp256k1_context_no_precomp,
312 self.as_mut_c_ptr(),
313 tweak.as_c_ptr(),
314 ) != 1
315 {
316 Err(Error::InvalidTweak)
317 } else {
318 Ok(self)
319 }
320 }
321 }
322
323 #[inline]
329 pub fn mul_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
330 unsafe {
331 if ffi::secp256k1_ec_seckey_tweak_mul(
332 ffi::secp256k1_context_no_precomp,
333 self.as_mut_c_ptr(),
334 tweak.as_c_ptr(),
335 ) != 1
336 {
337 Err(Error::InvalidTweak)
338 } else {
339 Ok(self)
340 }
341 }
342 }
343
344 #[inline]
346 #[cfg(feature = "global-context")]
347 pub fn sign_ecdsa(&self, msg: Message) -> ecdsa::Signature { SECP256K1.sign_ecdsa(&msg, self) }
348
349 #[inline]
353 pub fn keypair<C: Signing>(&self, secp: &Secp256k1<C>) -> Keypair {
354 Keypair::from_secret_key(secp, self)
355 }
356
357 #[inline]
361 pub fn public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
362 PublicKey::from_secret_key(secp, self)
363 }
364
365 #[inline]
369 pub fn x_only_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> (XOnlyPublicKey, Parity) {
370 let kp = self.keypair(secp);
371 XOnlyPublicKey::from_keypair(&kp)
372 }
373}
374
375#[cfg(feature = "hashes")]
376impl<T: ThirtyTwoByteHash> From<T> for SecretKey {
377 fn from(t: T) -> SecretKey {
379 SecretKey::from_slice(&t.into_32()).expect("failed to create secret key")
380 }
381}
382
383#[cfg(feature = "serde")]
384impl serde::Serialize for SecretKey {
385 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
386 if s.is_human_readable() {
387 let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
388 s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
389 } else {
390 let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
391 for byte in self.0.iter() {
392 tuple.serialize_element(byte)?;
393 }
394 tuple.end()
395 }
396 }
397}
398
399#[cfg(feature = "serde")]
400impl<'de> serde::Deserialize<'de> for SecretKey {
401 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
402 if d.is_human_readable() {
403 d.deserialize_str(super::serde_util::FromStrVisitor::new(
404 "a hex string representing 32 byte SecretKey",
405 ))
406 } else {
407 let visitor = super::serde_util::Tuple32Visitor::new(
408 "raw 32 bytes SecretKey",
409 SecretKey::from_slice,
410 );
411 d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
412 }
413 }
414}
415
416impl PublicKey {
417 #[inline]
419 #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
420 pub fn as_ptr(&self) -> *const ffi::PublicKey { self.as_c_ptr() }
421
422 #[inline]
424 #[deprecated(
425 since = "0.25.0",
426 note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
427 )]
428 pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey { self.as_mut_c_ptr() }
429
430 #[inline]
444 pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> PublicKey {
445 unsafe {
446 let mut pk = ffi::PublicKey::new();
447 let res = ffi::secp256k1_ec_pubkey_create(secp.ctx.as_ptr(), &mut pk, sk.as_c_ptr());
450 debug_assert_eq!(res, 1);
451 PublicKey(pk)
452 }
453 }
454 #[inline]
456 pub fn from_ellswift(ellswift: ElligatorSwift) -> PublicKey { ElligatorSwift::decode(ellswift) }
457
458 #[inline]
460 #[cfg(feature = "global-context")]
461 pub fn from_secret_key_global(sk: &SecretKey) -> PublicKey {
462 PublicKey::from_secret_key(SECP256K1, sk)
463 }
464
465 #[inline]
467 pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
468 if data.is_empty() {
469 return Err(Error::InvalidPublicKey);
470 }
471
472 unsafe {
473 let mut pk = ffi::PublicKey::new();
474 if ffi::secp256k1_ec_pubkey_parse(
475 ffi::secp256k1_context_no_precomp,
476 &mut pk,
477 data.as_c_ptr(),
478 data.len(),
479 ) == 1
480 {
481 Ok(PublicKey(pk))
482 } else {
483 Err(InvalidPublicKey)
484 }
485 }
486 }
487
488 #[inline]
502 pub fn from_keypair(keypair: &Keypair) -> Self {
503 unsafe {
504 let mut pk = ffi::PublicKey::new();
505 let ret = ffi::secp256k1_keypair_pub(
506 ffi::secp256k1_context_no_precomp,
507 &mut pk,
508 keypair.as_c_ptr(),
509 );
510 debug_assert_eq!(ret, 1);
511 PublicKey(pk)
512 }
513 }
514
515 pub fn from_x_only_public_key(pk: XOnlyPublicKey, parity: Parity) -> PublicKey {
517 let mut buf = [0u8; 33];
518
519 buf[0] = match parity {
521 Parity::Even => 0x02,
522 Parity::Odd => 0x03,
523 };
524 buf[1..].clone_from_slice(&pk.serialize());
525
526 PublicKey::from_slice(&buf).expect("we know the buffer is valid")
527 }
528
529 #[inline]
530 pub fn serialize(&self) -> [u8; constants::PUBLIC_KEY_SIZE] {
533 let mut ret = [0u8; constants::PUBLIC_KEY_SIZE];
534 self.serialize_internal(&mut ret, ffi::SECP256K1_SER_COMPRESSED);
535 ret
536 }
537
538 #[inline]
539 pub fn serialize_uncompressed(&self) -> [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] {
541 let mut ret = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
542 self.serialize_internal(&mut ret, ffi::SECP256K1_SER_UNCOMPRESSED);
543 ret
544 }
545
546 #[inline(always)]
547 fn serialize_internal(&self, ret: &mut [u8], flag: c_uint) {
548 let mut ret_len = ret.len();
549 let res = unsafe {
550 ffi::secp256k1_ec_pubkey_serialize(
551 ffi::secp256k1_context_no_precomp,
552 ret.as_mut_c_ptr(),
553 &mut ret_len,
554 self.as_c_ptr(),
555 flag,
556 )
557 };
558 debug_assert_eq!(res, 1);
559 debug_assert_eq!(ret_len, ret.len());
560 }
561
562 #[inline]
564 #[must_use = "you forgot to use the negated public key"]
565 pub fn negate<C: Verification>(mut self, secp: &Secp256k1<C>) -> PublicKey {
566 unsafe {
567 let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx.as_ptr(), &mut self.0);
568 debug_assert_eq!(res, 1);
569 }
570 self
571 }
572
573 #[inline]
579 pub fn add_exp_tweak<C: Verification>(
580 mut self,
581 secp: &Secp256k1<C>,
582 tweak: &Scalar,
583 ) -> Result<PublicKey, Error> {
584 unsafe {
585 if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx.as_ptr(), &mut self.0, tweak.as_c_ptr())
586 == 1
587 {
588 Ok(self)
589 } else {
590 Err(Error::InvalidTweak)
591 }
592 }
593 }
594
595 #[inline]
601 pub fn mul_tweak<C: Verification>(
602 mut self,
603 secp: &Secp256k1<C>,
604 other: &Scalar,
605 ) -> Result<PublicKey, Error> {
606 unsafe {
607 if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx.as_ptr(), &mut self.0, other.as_c_ptr())
608 == 1
609 {
610 Ok(self)
611 } else {
612 Err(Error::InvalidTweak)
613 }
614 }
615 }
616
617 pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
637 PublicKey::combine_keys(&[self, other])
638 }
639
640 pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
664 use core::i32::MAX;
665 use core::mem::transmute;
666
667 if keys.is_empty() || keys.len() > MAX as usize {
668 return Err(InvalidPublicKeySum);
669 }
670
671 unsafe {
672 let mut ret = ffi::PublicKey::new();
673 let ptrs: &[*const ffi::PublicKey] =
674 transmute::<&[&PublicKey], &[*const ffi::PublicKey]>(keys);
675 if ffi::secp256k1_ec_pubkey_combine(
676 ffi::secp256k1_context_no_precomp,
677 &mut ret,
678 ptrs.as_c_ptr(),
679 keys.len(),
680 ) == 1
681 {
682 Ok(PublicKey(ret))
683 } else {
684 Err(InvalidPublicKeySum)
685 }
686 }
687 }
688
689 #[inline]
691 pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
692 let mut pk_parity = 0;
693 unsafe {
694 let mut xonly_pk = ffi::XOnlyPublicKey::new();
695 let ret = ffi::secp256k1_xonly_pubkey_from_pubkey(
696 ffi::secp256k1_context_no_precomp,
697 &mut xonly_pk,
698 &mut pk_parity,
699 self.as_c_ptr(),
700 );
701 debug_assert_eq!(ret, 1);
702 let parity =
703 Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
704
705 (XOnlyPublicKey(xonly_pk), parity)
706 }
707 }
708
709 pub fn verify<C: Verification>(
711 &self,
712 secp: &Secp256k1<C>,
713 msg: &Message,
714 sig: &ecdsa::Signature,
715 ) -> Result<(), Error> {
716 secp.verify_ecdsa(msg, sig, self)
717 }
718}
719
720impl CPtr for PublicKey {
723 type Target = ffi::PublicKey;
724
725 fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
727
728 fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
730}
731
732impl From<ffi::PublicKey> for PublicKey {
736 #[inline]
737 fn from(pk: ffi::PublicKey) -> PublicKey { PublicKey(pk) }
738}
739
740#[cfg(feature = "serde")]
741impl serde::Serialize for PublicKey {
742 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
743 if s.is_human_readable() {
744 s.collect_str(self)
745 } else {
746 let mut tuple = s.serialize_tuple(constants::PUBLIC_KEY_SIZE)?;
747 for byte in self.serialize().iter() {
749 tuple.serialize_element(&byte)?;
750 }
751 tuple.end()
752 }
753 }
754}
755
756#[cfg(feature = "serde")]
757impl<'de> serde::Deserialize<'de> for PublicKey {
758 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
759 if d.is_human_readable() {
760 d.deserialize_str(super::serde_util::FromStrVisitor::new(
761 "an ASCII hex string representing a public key",
762 ))
763 } else {
764 let visitor = super::serde_util::Tuple33Visitor::new(
765 "33 bytes compressed public key",
766 PublicKey::from_slice,
767 );
768 d.deserialize_tuple(constants::PUBLIC_KEY_SIZE, visitor)
769 }
770 }
771}
772
773#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
798pub struct Keypair(ffi::Keypair);
799impl_display_secret!(Keypair);
800impl_fast_comparisons!(Keypair);
801
802impl Keypair {
803 #[inline]
805 #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
806 pub fn as_ptr(&self) -> *const ffi::Keypair { self.as_c_ptr() }
807
808 #[inline]
810 #[deprecated(
811 since = "0.25.0",
812 note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
813 )]
814 pub fn as_mut_ptr(&mut self) -> *mut ffi::Keypair { self.as_mut_c_ptr() }
815
816 #[inline]
818 pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> Keypair {
819 unsafe {
820 let mut kp = ffi::Keypair::new();
821 if ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut kp, sk.as_c_ptr()) == 1 {
822 Keypair(kp)
823 } else {
824 panic!("the provided secret key is invalid: it is corrupted or was not produced by Secp256k1 library")
825 }
826 }
827 }
828
829 #[inline]
836 pub fn from_seckey_slice<C: Signing>(
837 secp: &Secp256k1<C>,
838 data: &[u8],
839 ) -> Result<Keypair, Error> {
840 if data.is_empty() || data.len() != constants::SECRET_KEY_SIZE {
841 return Err(Error::InvalidSecretKey);
842 }
843
844 unsafe {
845 let mut kp = ffi::Keypair::new();
846 if ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut kp, data.as_c_ptr()) == 1 {
847 Ok(Keypair(kp))
848 } else {
849 Err(Error::InvalidSecretKey)
850 }
851 }
852 }
853
854 #[inline]
860 pub fn from_seckey_str<C: Signing>(secp: &Secp256k1<C>, s: &str) -> Result<Keypair, Error> {
861 let mut res = [0u8; constants::SECRET_KEY_SIZE];
862 match from_hex(s, &mut res) {
863 Ok(constants::SECRET_KEY_SIZE) =>
864 Keypair::from_seckey_slice(secp, &res[0..constants::SECRET_KEY_SIZE]),
865 _ => Err(Error::InvalidPublicKey),
866 }
867 }
868
869 #[inline]
875 #[cfg(feature = "global-context")]
876 pub fn from_seckey_str_global(s: &str) -> Result<Keypair, Error> {
877 Keypair::from_seckey_str(SECP256K1, s)
878 }
879
880 #[inline]
892 #[cfg(feature = "rand")]
893 pub fn new<R: rand::Rng + ?Sized, C: Signing>(secp: &Secp256k1<C>, rng: &mut R) -> Keypair {
894 let mut data = crate::random_32_bytes(rng);
895 unsafe {
896 let mut keypair = ffi::Keypair::new();
897 while ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut keypair, data.as_c_ptr())
898 == 0
899 {
900 data = crate::random_32_bytes(rng);
901 }
902 Keypair(keypair)
903 }
904 }
905
906 #[inline]
908 #[cfg(all(feature = "global-context", feature = "rand"))]
909 pub fn new_global<R: ::rand::Rng + ?Sized>(rng: &mut R) -> Keypair {
910 Keypair::new(SECP256K1, rng)
911 }
912
913 #[inline]
915 pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] {
916 *SecretKey::from_keypair(self).as_ref()
917 }
918
919 #[inline]
943 pub fn add_xonly_tweak<C: Verification>(
944 mut self,
945 secp: &Secp256k1<C>,
946 tweak: &Scalar,
947 ) -> Result<Keypair, Error> {
948 unsafe {
949 let err = ffi::secp256k1_keypair_xonly_tweak_add(
950 secp.ctx.as_ptr(),
951 &mut self.0,
952 tweak.as_c_ptr(),
953 );
954 if err != 1 {
955 return Err(Error::InvalidTweak);
956 }
957
958 Ok(self)
959 }
960 }
961
962 #[inline]
966 pub fn secret_key(&self) -> SecretKey { SecretKey::from_keypair(self) }
967
968 #[inline]
972 pub fn public_key(&self) -> PublicKey { PublicKey::from_keypair(self) }
973
974 #[inline]
978 pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
979 XOnlyPublicKey::from_keypair(self)
980 }
981
982 #[inline]
984 #[cfg(all(feature = "global-context", feature = "rand-std"))]
985 pub fn sign_schnorr(&self, msg: Message) -> schnorr::Signature {
986 SECP256K1.sign_schnorr(&msg, self)
987 }
988
989 #[inline]
996 pub fn non_secure_erase(&mut self) { self.0.non_secure_erase(); }
997}
998
999impl From<Keypair> for SecretKey {
1000 #[inline]
1001 fn from(pair: Keypair) -> Self { SecretKey::from_keypair(&pair) }
1002}
1003
1004impl<'a> From<&'a Keypair> for SecretKey {
1005 #[inline]
1006 fn from(pair: &'a Keypair) -> Self { SecretKey::from_keypair(pair) }
1007}
1008
1009impl From<Keypair> for PublicKey {
1010 #[inline]
1011 fn from(pair: Keypair) -> Self { PublicKey::from_keypair(&pair) }
1012}
1013
1014impl<'a> From<&'a Keypair> for PublicKey {
1015 #[inline]
1016 fn from(pair: &'a Keypair) -> Self { PublicKey::from_keypair(pair) }
1017}
1018
1019impl str::FromStr for Keypair {
1020 type Err = Error;
1021
1022 #[allow(unused_variables, unreachable_code)] fn from_str(s: &str) -> Result<Self, Self::Err> {
1024 #[cfg(feature = "global-context")]
1025 let ctx = SECP256K1;
1026
1027 #[cfg(all(not(feature = "global-context"), feature = "alloc"))]
1028 let ctx = Secp256k1::signing_only();
1029
1030 #[cfg(not(any(feature = "global-context", feature = "alloc")))]
1031 let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("The previous implementation was panicking too, please enable the global-context feature of rust-secp256k1");
1032
1033 #[allow(clippy::needless_borrow)]
1034 Keypair::from_seckey_str(&ctx, s)
1035 }
1036}
1037
1038#[cfg(feature = "serde")]
1039impl serde::Serialize for Keypair {
1040 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1041 if s.is_human_readable() {
1042 let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
1043 s.serialize_str(
1044 crate::to_hex(&self.secret_bytes(), &mut buf)
1045 .expect("fixed-size hex serialization"),
1046 )
1047 } else {
1048 let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
1049 for byte in self.secret_bytes().iter() {
1050 tuple.serialize_element(&byte)?;
1051 }
1052 tuple.end()
1053 }
1054 }
1055}
1056
1057#[cfg(feature = "serde")]
1058#[allow(unused_variables)] #[allow(unreachable_code)] impl<'de> serde::Deserialize<'de> for Keypair {
1061 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1062 if d.is_human_readable() {
1063 d.deserialize_str(super::serde_util::FromStrVisitor::new(
1064 "a hex string representing 32 byte Keypair",
1065 ))
1066 } else {
1067 let visitor = super::serde_util::Tuple32Visitor::new("raw 32 bytes Keypair", |data| {
1068 #[cfg(feature = "global-context")]
1069 let ctx = SECP256K1;
1070
1071 #[cfg(all(not(feature = "global-context"), feature = "alloc"))]
1072 let ctx = Secp256k1::signing_only();
1073
1074 #[cfg(not(any(feature = "global-context", feature = "alloc")))]
1075 let ctx: Secp256k1<crate::SignOnlyPreallocated> = panic!("cannot deserialize key pair without a context (please enable either the global-context or alloc feature)");
1076
1077 #[allow(clippy::needless_borrow)]
1078 Keypair::from_seckey_slice(&ctx, data)
1079 });
1080 d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
1081 }
1082 }
1083}
1084
1085impl CPtr for Keypair {
1086 type Target = ffi::Keypair;
1087 fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
1088
1089 fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
1090}
1091
1092#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
1116pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);
1117impl_fast_comparisons!(XOnlyPublicKey);
1118
1119impl fmt::LowerHex for XOnlyPublicKey {
1120 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1121 let ser = self.serialize();
1122 for ch in &ser[..] {
1123 write!(f, "{:02x}", *ch)?;
1124 }
1125 Ok(())
1126 }
1127}
1128
1129impl fmt::Display for XOnlyPublicKey {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
1131}
1132
1133impl str::FromStr for XOnlyPublicKey {
1134 type Err = Error;
1135 fn from_str(s: &str) -> Result<XOnlyPublicKey, Error> {
1136 let mut res = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
1137 match from_hex(s, &mut res) {
1138 Ok(constants::SCHNORR_PUBLIC_KEY_SIZE) =>
1139 XOnlyPublicKey::from_slice(&res[0..constants::SCHNORR_PUBLIC_KEY_SIZE]),
1140 _ => Err(Error::InvalidPublicKey),
1141 }
1142 }
1143}
1144
1145impl XOnlyPublicKey {
1146 #[inline]
1148 #[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
1149 pub fn as_ptr(&self) -> *const ffi::XOnlyPublicKey { self.as_c_ptr() }
1150
1151 #[inline]
1153 #[deprecated(
1154 since = "0.25.0",
1155 note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
1156 )]
1157 pub fn as_mut_ptr(&mut self) -> *mut ffi::XOnlyPublicKey { self.as_mut_c_ptr() }
1158
1159 #[inline]
1161 pub fn from_keypair(keypair: &Keypair) -> (XOnlyPublicKey, Parity) {
1162 let mut pk_parity = 0;
1163 unsafe {
1164 let mut xonly_pk = ffi::XOnlyPublicKey::new();
1165 let ret = ffi::secp256k1_keypair_xonly_pub(
1166 ffi::secp256k1_context_no_precomp,
1167 &mut xonly_pk,
1168 &mut pk_parity,
1169 keypair.as_c_ptr(),
1170 );
1171 debug_assert_eq!(ret, 1);
1172 let parity =
1173 Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
1174
1175 (XOnlyPublicKey(xonly_pk), parity)
1176 }
1177 }
1178
1179 #[inline]
1186 pub fn from_slice(data: &[u8]) -> Result<XOnlyPublicKey, Error> {
1187 if data.is_empty() || data.len() != constants::SCHNORR_PUBLIC_KEY_SIZE {
1188 return Err(Error::InvalidPublicKey);
1189 }
1190
1191 unsafe {
1192 let mut pk = ffi::XOnlyPublicKey::new();
1193 if ffi::secp256k1_xonly_pubkey_parse(
1194 ffi::secp256k1_context_no_precomp,
1195 &mut pk,
1196 data.as_c_ptr(),
1197 ) == 1
1198 {
1199 Ok(XOnlyPublicKey(pk))
1200 } else {
1201 Err(Error::InvalidPublicKey)
1202 }
1203 }
1204 }
1205
1206 #[inline]
1207 pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
1209 let mut ret = [0u8; constants::SCHNORR_PUBLIC_KEY_SIZE];
1210
1211 unsafe {
1212 let err = ffi::secp256k1_xonly_pubkey_serialize(
1213 ffi::secp256k1_context_no_precomp,
1214 ret.as_mut_c_ptr(),
1215 self.as_c_ptr(),
1216 );
1217 debug_assert_eq!(err, 1);
1218 }
1219 ret
1220 }
1221
1222 pub fn add_tweak<V: Verification>(
1249 mut self,
1250 secp: &Secp256k1<V>,
1251 tweak: &Scalar,
1252 ) -> Result<(XOnlyPublicKey, Parity), Error> {
1253 let mut pk_parity = 0;
1254 unsafe {
1255 let mut pubkey = ffi::PublicKey::new();
1256 let mut err = ffi::secp256k1_xonly_pubkey_tweak_add(
1257 secp.ctx.as_ptr(),
1258 &mut pubkey,
1259 self.as_c_ptr(),
1260 tweak.as_c_ptr(),
1261 );
1262 if err != 1 {
1263 return Err(Error::InvalidTweak);
1264 }
1265
1266 err = ffi::secp256k1_xonly_pubkey_from_pubkey(
1267 secp.ctx.as_ptr(),
1268 &mut self.0,
1269 &mut pk_parity,
1270 &pubkey,
1271 );
1272 if err == 0 {
1273 return Err(Error::InvalidPublicKey);
1274 }
1275
1276 let parity = Parity::from_i32(pk_parity)?;
1277 Ok((self, parity))
1278 }
1279 }
1280
1281 pub fn tweak_add_check<V: Verification>(
1311 &self,
1312 secp: &Secp256k1<V>,
1313 tweaked_key: &Self,
1314 tweaked_parity: Parity,
1315 tweak: Scalar,
1316 ) -> bool {
1317 let tweaked_ser = tweaked_key.serialize();
1318 unsafe {
1319 let err = ffi::secp256k1_xonly_pubkey_tweak_add_check(
1320 secp.ctx.as_ptr(),
1321 tweaked_ser.as_c_ptr(),
1322 tweaked_parity.to_i32(),
1323 &self.0,
1324 tweak.as_c_ptr(),
1325 );
1326
1327 err == 1
1328 }
1329 }
1330
1331 #[inline]
1335 pub fn public_key(&self, parity: Parity) -> PublicKey {
1336 PublicKey::from_x_only_public_key(*self, parity)
1337 }
1338
1339 pub fn verify<C: Verification>(
1341 &self,
1342 secp: &Secp256k1<C>,
1343 msg: &Message,
1344 sig: &schnorr::Signature,
1345 ) -> Result<(), Error> {
1346 secp.verify_schnorr(sig, msg, self)
1347 }
1348}
1349
1350#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
1352pub enum Parity {
1353 Even = 0,
1355 Odd = 1,
1357}
1358
1359impl Parity {
1360 pub fn to_u8(self) -> u8 { self as u8 }
1364
1365 pub fn to_i32(self) -> i32 { self as i32 }
1369
1370 pub fn from_u8(parity: u8) -> Result<Parity, InvalidParityValue> {
1375 Parity::from_i32(parity.into())
1376 }
1377
1378 pub fn from_i32(parity: i32) -> Result<Parity, InvalidParityValue> {
1383 match parity {
1384 0 => Ok(Parity::Even),
1385 1 => Ok(Parity::Odd),
1386 _ => Err(InvalidParityValue(parity)),
1387 }
1388 }
1389}
1390
1391impl TryFrom<i32> for Parity {
1393 type Error = InvalidParityValue;
1394
1395 fn try_from(parity: i32) -> Result<Self, Self::Error> { Self::from_i32(parity) }
1396}
1397
1398impl TryFrom<u8> for Parity {
1400 type Error = InvalidParityValue;
1401
1402 fn try_from(parity: u8) -> Result<Self, Self::Error> { Self::from_u8(parity) }
1403}
1404
1405impl From<Parity> for i32 {
1407 fn from(parity: Parity) -> i32 { parity.to_i32() }
1408}
1409
1410impl From<Parity> for u8 {
1412 fn from(parity: Parity) -> u8 { parity.to_u8() }
1413}
1414
1415impl BitXor for Parity {
1417 type Output = Parity;
1418
1419 fn bitxor(self, rhs: Parity) -> Self::Output {
1420 if self == rhs {
1422 Parity::Even } else {
1424 Parity::Odd }
1426 }
1427}
1428
1429#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
1435pub struct InvalidParityValue(i32);
1436
1437impl fmt::Display for InvalidParityValue {
1438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1439 write!(f, "invalid value {} for Parity - must be 0 or 1", self.0)
1440 }
1441}
1442
1443#[cfg(feature = "std")]
1444impl std::error::Error for InvalidParityValue {}
1445
1446impl From<InvalidParityValue> for Error {
1447 fn from(error: InvalidParityValue) -> Self { Error::InvalidParityValue(error) }
1448}
1449
1450#[cfg(feature = "serde")]
1452impl serde::Serialize for Parity {
1453 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1454 s.serialize_u8(self.to_u8())
1455 }
1456}
1457
1458#[cfg(feature = "serde")]
1460impl<'de> serde::Deserialize<'de> for Parity {
1461 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1462 struct Visitor;
1463
1464 impl<'de> serde::de::Visitor<'de> for Visitor {
1465 type Value = Parity;
1466
1467 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1468 formatter.write_str("8-bit integer (byte) with value 0 or 1")
1469 }
1470
1471 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
1472 where
1473 E: serde::de::Error,
1474 {
1475 use serde::de::Unexpected;
1476
1477 Parity::from_u8(v)
1478 .map_err(|_| E::invalid_value(Unexpected::Unsigned(v.into()), &"0 or 1"))
1479 }
1480 }
1481
1482 d.deserialize_u8(Visitor)
1483 }
1484}
1485
1486impl CPtr for XOnlyPublicKey {
1487 type Target = ffi::XOnlyPublicKey;
1488 fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
1489
1490 fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
1491}
1492
1493impl From<ffi::XOnlyPublicKey> for XOnlyPublicKey {
1495 #[inline]
1496 fn from(pk: ffi::XOnlyPublicKey) -> XOnlyPublicKey { XOnlyPublicKey(pk) }
1497}
1498
1499impl From<PublicKey> for XOnlyPublicKey {
1500 fn from(src: PublicKey) -> XOnlyPublicKey {
1501 unsafe {
1502 let mut pk = ffi::XOnlyPublicKey::new();
1503 assert_eq!(
1504 1,
1505 ffi::secp256k1_xonly_pubkey_from_pubkey(
1506 ffi::secp256k1_context_no_precomp,
1507 &mut pk,
1508 ptr::null_mut(),
1509 src.as_c_ptr(),
1510 )
1511 );
1512 XOnlyPublicKey(pk)
1513 }
1514 }
1515}
1516
1517#[cfg(feature = "serde")]
1518impl serde::Serialize for XOnlyPublicKey {
1519 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1520 if s.is_human_readable() {
1521 s.collect_str(self)
1522 } else {
1523 let mut tuple = s.serialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE)?;
1524 for byte in self.serialize().iter() {
1525 tuple.serialize_element(&byte)?;
1526 }
1527 tuple.end()
1528 }
1529 }
1530}
1531
1532#[cfg(feature = "serde")]
1533impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
1534 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1535 if d.is_human_readable() {
1536 d.deserialize_str(super::serde_util::FromStrVisitor::new(
1537 "a hex string representing 32 byte schnorr public key",
1538 ))
1539 } else {
1540 let visitor = super::serde_util::Tuple32Visitor::new(
1541 "raw 32 bytes schnorr public key",
1542 XOnlyPublicKey::from_slice,
1543 );
1544 d.deserialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE, visitor)
1545 }
1546 }
1547}
1548
1549#[cfg(test)]
1550#[allow(unused_imports)]
1551mod test {
1552 use core::str::FromStr;
1553
1554 #[cfg(feature = "rand")]
1555 use rand::{self, rngs::mock::StepRng, RngCore};
1556 use serde_test::{Configure, Token};
1557 #[cfg(target_arch = "wasm32")]
1558 use wasm_bindgen_test::wasm_bindgen_test as test;
1559
1560 use super::{Keypair, Parity, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, *};
1561 use crate::Error::{InvalidPublicKey, InvalidSecretKey};
1562 use crate::{constants, from_hex, to_hex, Scalar};
1563
1564 #[cfg(not(secp256k1_fuzz))]
1565 macro_rules! hex {
1566 ($hex:expr) => {{
1567 let mut result = vec![0; $hex.len() / 2];
1568 from_hex($hex, &mut result).expect("valid hex string");
1569 result
1570 }};
1571 }
1572
1573 #[test]
1574 fn skey_from_slice() {
1575 let sk = SecretKey::from_slice(&[1; 31]);
1576 assert_eq!(sk, Err(InvalidSecretKey));
1577
1578 let sk = SecretKey::from_slice(&[1; 32]);
1579 assert!(sk.is_ok());
1580 }
1581
1582 #[test]
1583 fn pubkey_from_slice() {
1584 assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
1585 assert_eq!(PublicKey::from_slice(&[1, 2, 3]), Err(InvalidPublicKey));
1586
1587 let uncompressed = PublicKey::from_slice(&[
1588 4, 54, 57, 149, 239, 162, 148, 175, 246, 254, 239, 75, 154, 152, 10, 82, 234, 224, 85,
1589 220, 40, 100, 57, 121, 30, 162, 94, 156, 135, 67, 74, 49, 179, 57, 236, 53, 162, 124,
1590 149, 144, 168, 77, 74, 30, 72, 211, 229, 110, 111, 55, 96, 193, 86, 227, 183, 152, 195,
1591 155, 51, 247, 123, 113, 60, 228, 188,
1592 ]);
1593 assert!(uncompressed.is_ok());
1594
1595 let compressed = PublicKey::from_slice(&[
1596 3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41,
1597 111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78,
1598 ]);
1599 assert!(compressed.is_ok());
1600 }
1601
1602 #[test]
1603 #[cfg(feature = "rand-std")]
1604 fn keypair_slice_round_trip() {
1605 let s = Secp256k1::new();
1606
1607 let (sk1, pk1) = s.generate_keypair(&mut rand::thread_rng());
1608 assert_eq!(SecretKey::from_slice(&sk1[..]), Ok(sk1));
1609 assert_eq!(PublicKey::from_slice(&pk1.serialize()[..]), Ok(pk1));
1610 assert_eq!(PublicKey::from_slice(&pk1.serialize_uncompressed()[..]), Ok(pk1));
1611 }
1612
1613 #[test]
1614 #[cfg(all(feature = "std", not(secp256k1_fuzz)))]
1615 fn erased_keypair_is_valid() {
1616 let s = Secp256k1::new();
1617 let kp = Keypair::from_seckey_slice(&s, &[1u8; constants::SECRET_KEY_SIZE])
1618 .expect("valid secret key");
1619 let mut kp2 = kp;
1620 kp2.non_secure_erase();
1621 assert!(kp.eq_fast_unstable(&kp2));
1622 }
1623
1624 #[test]
1625 #[rustfmt::skip]
1626 fn invalid_secret_key() {
1627 assert_eq!(SecretKey::from_slice(&[0; 32]), Err(InvalidSecretKey));
1629 assert_eq!(
1630 SecretKey::from_str("0000000000000000000000000000000000000000000000000000000000000000"),
1631 Err(InvalidSecretKey)
1632 );
1633 assert_eq!(SecretKey::from_slice(&[0xff; 32]), Err(InvalidSecretKey));
1635 assert!(SecretKey::from_slice(&[
1637 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1638 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
1639 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
1640 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
1641 ]).is_ok());
1642 assert!(SecretKey::from_slice(&[
1644 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1645 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
1646 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
1647 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41,
1648 ]).is_err());
1649 }
1650
1651 #[test]
1652 #[cfg(all(feature = "rand", feature = "alloc"))]
1653 fn test_out_of_range() {
1654 struct BadRng(u8);
1655 impl RngCore for BadRng {
1656 fn next_u32(&mut self) -> u32 { unimplemented!() }
1657 fn next_u64(&mut self) -> u64 { unimplemented!() }
1658 fn fill_bytes(&mut self, data: &mut [u8]) {
1662 #[rustfmt::skip]
1663 let group_order: [u8; 32] = [
1664 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1665 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
1666 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
1667 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41];
1668 assert_eq!(data.len(), 32);
1669 data.copy_from_slice(&group_order[..]);
1670 data[31] = self.0;
1671 self.0 -= 1;
1672 }
1673 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
1674 self.fill_bytes(dest);
1675 Ok(())
1676 }
1677 }
1678
1679 let s = Secp256k1::new();
1680 s.generate_keypair(&mut BadRng(0xff));
1681 }
1682
1683 #[test]
1684 fn test_pubkey_from_bad_slice() {
1685 assert_eq!(
1687 PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE - 1]),
1688 Err(InvalidPublicKey)
1689 );
1690 assert_eq!(
1691 PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE + 1]),
1692 Err(InvalidPublicKey)
1693 );
1694 assert_eq!(
1695 PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1]),
1696 Err(InvalidPublicKey)
1697 );
1698 assert_eq!(
1699 PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 1]),
1700 Err(InvalidPublicKey)
1701 );
1702
1703 assert_eq!(
1705 PublicKey::from_slice(&[0xff; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE]),
1706 Err(InvalidPublicKey)
1707 );
1708 assert_eq!(
1709 PublicKey::from_slice(&[0x55; constants::PUBLIC_KEY_SIZE]),
1710 Err(InvalidPublicKey)
1711 );
1712 assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
1713 }
1714
1715 #[test]
1716 fn test_seckey_from_bad_slice() {
1717 assert_eq!(
1719 SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE - 1]),
1720 Err(InvalidSecretKey)
1721 );
1722 assert_eq!(
1723 SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE + 1]),
1724 Err(InvalidSecretKey)
1725 );
1726 assert_eq!(
1728 SecretKey::from_slice(&[0xff; constants::SECRET_KEY_SIZE]),
1729 Err(InvalidSecretKey)
1730 );
1731 assert_eq!(
1732 SecretKey::from_slice(&[0x00; constants::SECRET_KEY_SIZE]),
1733 Err(InvalidSecretKey)
1734 );
1735 assert_eq!(SecretKey::from_slice(&[]), Err(InvalidSecretKey));
1736 }
1737
1738 #[test]
1739 #[cfg(all(feature = "rand", feature = "alloc"))]
1740 fn test_debug_output() {
1741 let s = Secp256k1::new();
1742 let (sk, _) = s.generate_keypair(&mut StepRng::new(1, 1));
1743
1744 assert_eq!(&format!("{:?}", sk), "SecretKey(#d3e0c51a23169bb5)");
1745
1746 let mut buf = [0u8; constants::SECRET_KEY_SIZE * 2];
1747 assert_eq!(
1748 to_hex(&sk[..], &mut buf).unwrap(),
1749 "0100000000000000020000000000000003000000000000000400000000000000"
1750 );
1751 }
1752
1753 #[test]
1754 #[cfg(feature = "alloc")]
1755 fn test_display_output() {
1756 #[rustfmt::skip]
1757 static SK_BYTES: [u8; 32] = [
1758 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
1759 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1760 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
1761 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
1762 ];
1763
1764 #[cfg(not(secp256k1_fuzz))]
1765 let s = Secp256k1::signing_only();
1766 let sk = SecretKey::from_slice(&SK_BYTES).expect("sk");
1767
1768 #[cfg(not(secp256k1_fuzz))]
1771 let pk = PublicKey::from_secret_key(&s, &sk);
1772 #[cfg(secp256k1_fuzz)]
1773 let pk = PublicKey::from_slice(&[
1774 0x02, 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f, 0x1c, 0x97, 0x09, 0xe2, 0x30,
1775 0x92, 0x06, 0x7d, 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54, 0x4a, 0xc8, 0x87,
1776 0xfe, 0x91, 0xdd, 0xd1, 0x66,
1777 ])
1778 .expect("pk");
1779
1780 assert_eq!(
1781 sk.display_secret().to_string(),
1782 "01010101010101010001020304050607ffff0000ffff00006363636363636363"
1783 );
1784 assert_eq!(
1785 SecretKey::from_str("01010101010101010001020304050607ffff0000ffff00006363636363636363")
1786 .unwrap(),
1787 sk
1788 );
1789 assert_eq!(
1790 pk.to_string(),
1791 "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
1792 );
1793 assert_eq!(
1794 PublicKey::from_str(
1795 "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
1796 )
1797 .unwrap(),
1798 pk
1799 );
1800 assert_eq!(
1801 PublicKey::from_str(
1802 "04\
1803 18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
1804 84B84DB303A340CD7D6823EE88174747D12A67D2F8F2F9BA40846EE5EE7A44F6"
1805 )
1806 .unwrap(),
1807 pk
1808 );
1809
1810 assert!(SecretKey::from_str(
1811 "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1812 )
1813 .is_err());
1814 assert!(SecretKey::from_str(
1815 "01010101010101010001020304050607ffff0000ffff0000636363636363636363"
1816 )
1817 .is_err());
1818 assert!(SecretKey::from_str(
1819 "01010101010101010001020304050607ffff0000ffff0000636363636363636"
1820 )
1821 .is_err());
1822 assert!(SecretKey::from_str(
1823 "01010101010101010001020304050607ffff0000ffff000063636363636363"
1824 )
1825 .is_err());
1826 assert!(SecretKey::from_str(
1827 "01010101010101010001020304050607ffff0000ffff000063636363636363xx"
1828 )
1829 .is_err());
1830 assert!(PublicKey::from_str(
1831 "0300000000000000000000000000000000000000000000000000000000000000000"
1832 )
1833 .is_err());
1834 assert!(PublicKey::from_str(
1835 "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16601"
1836 )
1837 .is_err());
1838 assert!(PublicKey::from_str(
1839 "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16"
1840 )
1841 .is_err());
1842 assert!(PublicKey::from_str(
1843 "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
1844 )
1845 .is_err());
1846 assert!(PublicKey::from_str(
1847 "xx0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
1848 )
1849 .is_err());
1850
1851 let long_str = "a".repeat(1024 * 1024);
1852 assert!(SecretKey::from_str(&long_str).is_err());
1853 assert!(PublicKey::from_str(&long_str).is_err());
1854 }
1855
1856 #[test]
1857 #[cfg(not(secp256k1_fuzz))]
1860 #[cfg(all(feature = "alloc", feature = "rand"))]
1861 fn test_pubkey_serialize() {
1862 let s = Secp256k1::new();
1863 let (_, pk1) = s.generate_keypair(&mut StepRng::new(1, 1));
1864 assert_eq!(
1865 &pk1.serialize_uncompressed()[..],
1866 &[
1867 4, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
1868 9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229, 185, 28, 165,
1869 110, 27, 3, 162, 126, 238, 167, 157, 242, 221, 76, 251, 237, 34, 231, 72, 39, 245,
1870 3, 191, 64, 111, 170, 117, 103, 82, 28, 102, 163
1871 ][..]
1872 );
1873 assert_eq!(
1874 &pk1.serialize()[..],
1875 &[
1876 3, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
1877 9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229
1878 ][..]
1879 );
1880 }
1881
1882 #[test]
1883 #[cfg(feature = "rand-std")]
1884 fn tweak_add_arbitrary_data() {
1885 let s = Secp256k1::new();
1886
1887 let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1888 assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let tweak = Scalar::random();
1892
1893 let tweaked_sk = sk.add_tweak(&tweak).unwrap();
1894 assert_ne!(sk, tweaked_sk); let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
1896 assert_ne!(pk, tweaked_pk);
1897
1898 assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
1899 }
1900
1901 #[test]
1902 #[cfg(feature = "rand-std")]
1903 fn tweak_add_zero() {
1904 let s = Secp256k1::new();
1905
1906 let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1907
1908 let tweak = Scalar::ZERO;
1909
1910 let tweaked_sk = sk.add_tweak(&tweak).unwrap();
1911 assert_eq!(sk, tweaked_sk); let tweaked_pk = pk.add_exp_tweak(&s, &tweak).unwrap();
1913 assert_eq!(pk, tweaked_pk);
1914 }
1915
1916 #[test]
1917 #[cfg(feature = "rand-std")]
1918 fn tweak_mul_arbitrary_data() {
1919 let s = Secp256k1::new();
1920
1921 let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1922 assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let tweak = Scalar::random();
1926
1927 let tweaked_sk = sk.mul_tweak(&tweak).unwrap();
1928 assert_ne!(sk, tweaked_sk); let tweaked_pk = pk.mul_tweak(&s, &tweak).unwrap();
1930 assert_ne!(pk, tweaked_pk);
1931
1932 assert_eq!(PublicKey::from_secret_key(&s, &tweaked_sk), tweaked_pk);
1933 }
1934
1935 #[test]
1936 #[cfg(feature = "rand-std")]
1937 fn tweak_mul_zero() {
1938 let s = Secp256k1::new();
1939 let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
1940
1941 let tweak = Scalar::ZERO;
1942 assert!(sk.mul_tweak(&tweak).is_err())
1943 }
1944
1945 #[test]
1946 #[cfg(feature = "rand-std")]
1947 fn test_negation() {
1948 let s = Secp256k1::new();
1949
1950 let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
1951
1952 assert_eq!(PublicKey::from_secret_key(&s, &sk), pk); let neg = sk.negate();
1955 assert_ne!(sk, neg);
1956 let back_sk = neg.negate();
1957 assert_eq!(sk, back_sk);
1958
1959 let neg = pk.negate(&s);
1960 assert_ne!(pk, neg);
1961 let back_pk = neg.negate(&s);
1962 assert_eq!(pk, back_pk);
1963
1964 assert_eq!(PublicKey::from_secret_key(&s, &back_sk), pk);
1965 }
1966
1967 #[test]
1968 #[cfg(feature = "rand-std")]
1969 fn pubkey_hash() {
1970 use std::collections::hash_map::DefaultHasher;
1971 use std::collections::HashSet;
1972 use std::hash::{Hash, Hasher};
1973
1974 fn hash<T: Hash>(t: &T) -> u64 {
1975 let mut s = DefaultHasher::new();
1976 t.hash(&mut s);
1977 s.finish()
1978 }
1979
1980 let s = Secp256k1::new();
1981 let mut set = HashSet::new();
1982 const COUNT: usize = 1024;
1983 for _ in 0..COUNT {
1984 let (_, pk) = s.generate_keypair(&mut rand::thread_rng());
1985 let hash = hash(&pk);
1986 assert!(!set.contains(&hash));
1987 set.insert(hash);
1988 }
1989 assert_eq!(set.len(), COUNT);
1990 }
1991
1992 #[test]
1993 #[cfg(not(secp256k1_fuzz))]
1994 fn pubkey_combine() {
1995 let compressed1 = PublicKey::from_slice(&hex!(
1996 "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
1997 ))
1998 .unwrap();
1999 let compressed2 = PublicKey::from_slice(&hex!(
2000 "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2001 ))
2002 .unwrap();
2003 let exp_sum = PublicKey::from_slice(&hex!(
2004 "0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07"
2005 ))
2006 .unwrap();
2007
2008 let sum1 = compressed1.combine(&compressed2);
2009 assert!(sum1.is_ok());
2010 let sum2 = compressed2.combine(&compressed1);
2011 assert!(sum2.is_ok());
2012 assert_eq!(sum1, sum2);
2013 assert_eq!(sum1.unwrap(), exp_sum);
2014 }
2015
2016 #[test]
2017 #[cfg(not(secp256k1_fuzz))]
2018 fn pubkey_combine_keys() {
2019 let compressed1 = PublicKey::from_slice(&hex!(
2020 "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
2021 ))
2022 .unwrap();
2023 let compressed2 = PublicKey::from_slice(&hex!(
2024 "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2025 ))
2026 .unwrap();
2027 let compressed3 = PublicKey::from_slice(&hex!(
2028 "03e74897d8644eb3e5b391ca2ab257aec2080f4d1a95cad57e454e47f021168eb0"
2029 ))
2030 .unwrap();
2031 let exp_sum = PublicKey::from_slice(&hex!(
2032 "0252d73a47f66cf341e5651542f0348f452b7c793af62a6d8bff75ade703a451ad"
2033 ))
2034 .unwrap();
2035
2036 let sum1 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
2037 assert!(sum1.is_ok());
2038 let sum2 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
2039 assert!(sum2.is_ok());
2040 assert_eq!(sum1, sum2);
2041 assert_eq!(sum1.unwrap(), exp_sum);
2042 }
2043
2044 #[test]
2045 #[cfg(not(secp256k1_fuzz))]
2046 fn pubkey_combine_keys_empty_slice() {
2047 assert!(PublicKey::combine_keys(&[]).is_err());
2048 }
2049
2050 #[test]
2051 #[cfg(feature = "rand-std")]
2052 fn create_pubkey_combine() {
2053 let s = Secp256k1::new();
2054
2055 let (sk1, pk1) = s.generate_keypair(&mut rand::thread_rng());
2056 let (sk2, pk2) = s.generate_keypair(&mut rand::thread_rng());
2057
2058 let sum1 = pk1.combine(&pk2);
2059 assert!(sum1.is_ok());
2060 let sum2 = pk2.combine(&pk1);
2061 assert!(sum2.is_ok());
2062 assert_eq!(sum1, sum2);
2063
2064 let tweaked = sk1.add_tweak(&Scalar::from(sk2)).unwrap();
2065 let sksum = PublicKey::from_secret_key(&s, &tweaked);
2066 assert_eq!(Ok(sksum), sum1);
2067 }
2068
2069 #[cfg(not(secp256k1_fuzz))]
2070 #[test]
2071 #[allow(clippy::nonminimal_bool)]
2072 fn pubkey_equal() {
2073 let pk1 = PublicKey::from_slice(&hex!(
2074 "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
2075 ))
2076 .unwrap();
2077 let pk2 = pk1;
2078 let pk3 = PublicKey::from_slice(&hex!(
2079 "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
2080 ))
2081 .unwrap();
2082
2083 assert_eq!(pk1, pk2);
2084 assert!(pk1 <= pk2);
2085 assert!(pk2 <= pk1);
2086 assert!(!(pk2 < pk1));
2087 assert!(!(pk1 < pk2));
2088
2089 assert!(pk3 > pk1);
2090 assert!(pk1 < pk3);
2091 assert!(pk3 >= pk1);
2092 assert!(pk1 <= pk3);
2093 }
2094
2095 #[test]
2096 #[cfg(all(feature = "serde", feature = "alloc"))]
2097 fn test_serde() {
2098 use serde_test::{assert_tokens, Configure, Token};
2099 #[rustfmt::skip]
2100 static SK_BYTES: [u8; 32] = [
2101 1, 1, 1, 1, 1, 1, 1, 1,
2102 0, 1, 2, 3, 4, 5, 6, 7,
2103 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2104 99, 99, 99, 99, 99, 99, 99, 99
2105 ];
2106 static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
2107
2108 #[cfg(secp256k1_fuzz)]
2109 #[rustfmt::skip]
2110 static PK_BYTES: [u8; 33] = [
2111 0x02,
2112 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
2113 0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
2114 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
2115 0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66,
2116 ];
2117 static PK_STR: &str = "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2118
2119 #[cfg(not(secp256k1_fuzz))]
2120 let s = Secp256k1::new();
2121 let sk = SecretKey::from_slice(&SK_BYTES).unwrap();
2122
2123 #[cfg(not(secp256k1_fuzz))]
2126 let pk = PublicKey::from_secret_key(&s, &sk);
2127 #[cfg(secp256k1_fuzz)]
2128 let pk = PublicKey::from_slice(&PK_BYTES).expect("pk");
2129
2130 #[rustfmt::skip]
2131 assert_tokens(&sk.compact(), &[
2132 Token::Tuple{ len: 32 },
2133 Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
2134 Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
2135 Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
2136 Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
2137 Token::TupleEnd
2138 ]);
2139
2140 assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
2141 assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
2142 assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
2143
2144 #[rustfmt::skip]
2145 assert_tokens(&pk.compact(), &[
2146 Token::Tuple{ len: 33 },
2147 Token::U8(0x02),
2148 Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
2149 Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
2150 Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
2151 Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
2152 Token::TupleEnd
2153 ]);
2154
2155 assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
2156 assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
2157 assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
2158 }
2159
2160 #[test]
2161 #[cfg(feature = "rand-std")]
2162 fn test_tweak_add_then_tweak_add_check() {
2163 let s = Secp256k1::new();
2164
2165 for _ in 0..10 {
2167 let tweak = Scalar::random();
2168
2169 let kp = Keypair::new(&s, &mut rand::thread_rng());
2170 let (xonly, _) = XOnlyPublicKey::from_keypair(&kp);
2171
2172 let tweaked_kp = kp.add_xonly_tweak(&s, &tweak).expect("keypair tweak add failed");
2173 let (tweaked_xonly, parity) =
2174 xonly.add_tweak(&s, &tweak).expect("xonly pubkey tweak failed");
2175
2176 let (want_tweaked_xonly, tweaked_kp_parity) = XOnlyPublicKey::from_keypair(&tweaked_kp);
2177
2178 assert_eq!(tweaked_xonly, want_tweaked_xonly);
2179 assert_eq!(parity, tweaked_kp_parity);
2180
2181 assert!(xonly.tweak_add_check(&s, &tweaked_xonly, parity, tweak));
2182 }
2183 }
2184
2185 #[test]
2186 fn test_from_key_pubkey() {
2187 let kpk1 = PublicKey::from_str(
2188 "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443",
2189 )
2190 .unwrap();
2191 let kpk2 = PublicKey::from_str(
2192 "0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07",
2193 )
2194 .unwrap();
2195
2196 let pk1 = XOnlyPublicKey::from(kpk1);
2197 let pk2 = XOnlyPublicKey::from(kpk2);
2198
2199 assert_eq!(pk1.serialize()[..], kpk1.serialize()[1..]);
2200 assert_eq!(pk2.serialize()[..], kpk2.serialize()[1..]);
2201 }
2202
2203 #[test]
2204 #[cfg(all(feature = "global-context", feature = "serde"))]
2205 fn test_serde_keypair() {
2206 use serde::{Deserialize, Deserializer, Serialize, Serializer};
2207 use serde_test::{assert_tokens, Configure, Token};
2208
2209 use crate::key::Keypair;
2210 use crate::SECP256K1;
2211
2212 #[rustfmt::skip]
2213 static SK_BYTES: [u8; 32] = [
2214 1, 1, 1, 1, 1, 1, 1, 1,
2215 0, 1, 2, 3, 4, 5, 6, 7,
2216 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2217 99, 99, 99, 99, 99, 99, 99, 99
2218 ];
2219 static SK_STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
2220
2221 let sk = Keypair::from_seckey_slice(SECP256K1, &SK_BYTES).unwrap();
2222 #[rustfmt::skip]
2223 assert_tokens(&sk.compact(), &[
2224 Token::Tuple{ len: 32 },
2225 Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1), Token::U8(1),
2226 Token::U8(0), Token::U8(1), Token::U8(2), Token::U8(3), Token::U8(4), Token::U8(5), Token::U8(6), Token::U8(7),
2227 Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0), Token::U8(0xff), Token::U8(0xff), Token::U8(0), Token::U8(0),
2228 Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99), Token::U8(99),
2229 Token::TupleEnd
2230 ]);
2231
2232 assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
2233 assert_tokens(&sk.readable(), &[Token::Str(SK_STR)]);
2234 assert_tokens(&sk.readable(), &[Token::String(SK_STR)]);
2235 }
2236
2237 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2238 fn keys() -> (SecretKey, PublicKey, Keypair, XOnlyPublicKey) {
2239 let secp = Secp256k1::new();
2240
2241 #[rustfmt::skip]
2242 static SK_BYTES: [u8; 32] = [
2243 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
2244 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
2245 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
2246 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
2247 ];
2248
2249 #[rustfmt::skip]
2250 static PK_BYTES: [u8; 32] = [
2251 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f,
2252 0x1c, 0x97, 0x09, 0xe2, 0x30, 0x92, 0x06, 0x7d,
2253 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54,
2254 0x4a, 0xc8, 0x87, 0xfe, 0x91, 0xdd, 0xd1, 0x66
2255 ];
2256
2257 let mut pk_bytes = [0u8; 33];
2258 pk_bytes[0] = 0x02; pk_bytes[1..].clone_from_slice(&PK_BYTES);
2260
2261 let sk = SecretKey::from_slice(&SK_BYTES).expect("failed to parse sk bytes");
2262 let pk = PublicKey::from_slice(&pk_bytes).expect("failed to create pk from iterator");
2263 let kp = Keypair::from_secret_key(&secp, &sk);
2264 let xonly = XOnlyPublicKey::from_slice(&PK_BYTES).expect("failed to get xonly from slice");
2265
2266 (sk, pk, kp, xonly)
2267 }
2268
2269 #[test]
2270 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2271 fn convert_public_key_to_xonly_public_key() {
2272 let (_sk, pk, _kp, want) = keys();
2273 let (got, parity) = pk.x_only_public_key();
2274
2275 assert_eq!(parity, Parity::Even);
2276 assert_eq!(got, want)
2277 }
2278
2279 #[test]
2280 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2281 fn convert_secret_key_to_public_key() {
2282 let secp = Secp256k1::new();
2283
2284 let (sk, want, _kp, _xonly) = keys();
2285 let got = sk.public_key(&secp);
2286
2287 assert_eq!(got, want)
2288 }
2289
2290 #[test]
2291 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2292 fn convert_secret_key_to_x_only_public_key() {
2293 let secp = Secp256k1::new();
2294
2295 let (sk, _pk, _kp, want) = keys();
2296 let (got, parity) = sk.x_only_public_key(&secp);
2297
2298 assert_eq!(parity, Parity::Even);
2299 assert_eq!(got, want)
2300 }
2301
2302 #[test]
2303 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2304 fn convert_keypair_to_public_key() {
2305 let (_sk, want, kp, _xonly) = keys();
2306 let got = kp.public_key();
2307
2308 assert_eq!(got, want)
2309 }
2310
2311 #[test]
2312 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2313 fn convert_keypair_to_x_only_public_key() {
2314 let (_sk, _pk, kp, want) = keys();
2315 let (got, parity) = kp.x_only_public_key();
2316
2317 assert_eq!(parity, Parity::Even);
2318 assert_eq!(got, want)
2319 }
2320
2321 #[test]
2323 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2324 fn roundtrip_secret_key_via_keypair() {
2325 let secp = Secp256k1::new();
2326 let (sk, _pk, _kp, _xonly) = keys();
2327
2328 let kp = sk.keypair(&secp);
2329 let back = kp.secret_key();
2330
2331 assert_eq!(back, sk)
2332 }
2333
2334 #[test]
2336 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2337 fn roundtrip_keypair_via_secret_key() {
2338 let secp = Secp256k1::new();
2339 let (_sk, _pk, kp, _xonly) = keys();
2340
2341 let sk = kp.secret_key();
2342 let back = sk.keypair(&secp);
2343
2344 assert_eq!(back, kp)
2345 }
2346
2347 #[test]
2349 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2350 fn roundtrip_x_only_public_key_via_public_key() {
2351 let (_sk, _pk, _kp, xonly) = keys();
2352
2353 let pk = xonly.public_key(Parity::Even);
2354 let (back, parity) = pk.x_only_public_key();
2355
2356 assert_eq!(parity, Parity::Even);
2357 assert_eq!(back, xonly)
2358 }
2359
2360 #[test]
2362 #[cfg(all(not(secp256k1_fuzz), feature = "alloc"))]
2363 fn roundtrip_public_key_via_x_only_public_key() {
2364 let (_sk, pk, _kp, _xonly) = keys();
2365
2366 let (xonly, parity) = pk.x_only_public_key();
2367 let back = xonly.public_key(parity);
2368
2369 assert_eq!(back, pk)
2370 }
2371
2372 #[test]
2373 fn public_key_from_x_only_public_key_and_odd_parity() {
2374 let s = "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2375 let mut want = String::from("03");
2376 want.push_str(s);
2377
2378 let xonly = XOnlyPublicKey::from_str(s).expect("failed to parse xonly pubkey string");
2379 let pk = xonly.public_key(Parity::Odd);
2380 let got = format!("{}", pk);
2381
2382 assert_eq!(got, want)
2383 }
2384
2385 #[test]
2386 #[cfg(not(secp256k1_fuzz))]
2387 #[cfg(all(feature = "global-context", feature = "serde"))]
2388 fn test_serde_x_only_pubkey() {
2389 use serde_test::{assert_tokens, Configure, Token};
2390
2391 #[rustfmt::skip]
2392 static SK_BYTES: [u8; 32] = [
2393 1, 1, 1, 1, 1, 1, 1, 1,
2394 0, 1, 2, 3, 4, 5, 6, 7,
2395 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
2396 99, 99, 99, 99, 99, 99, 99, 99
2397 ];
2398
2399 static PK_STR: &str = "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166";
2400
2401 let kp = Keypair::from_seckey_slice(crate::SECP256K1, &SK_BYTES).unwrap();
2402 let (pk, _parity) = XOnlyPublicKey::from_keypair(&kp);
2403
2404 #[rustfmt::skip]
2405 assert_tokens(&pk.compact(), &[
2406 Token::Tuple{ len: 32 },
2407 Token::U8(0x18), Token::U8(0x84), Token::U8(0x57), Token::U8(0x81), Token::U8(0xf6), Token::U8(0x31), Token::U8(0xc4), Token::U8(0x8f),
2408 Token::U8(0x1c), Token::U8(0x97), Token::U8(0x09), Token::U8(0xe2), Token::U8(0x30), Token::U8(0x92), Token::U8(0x06), Token::U8(0x7d),
2409 Token::U8(0x06), Token::U8(0x83), Token::U8(0x7f), Token::U8(0x30), Token::U8(0xaa), Token::U8(0x0c), Token::U8(0xd0), Token::U8(0x54),
2410 Token::U8(0x4a), Token::U8(0xc8), Token::U8(0x87), Token::U8(0xfe), Token::U8(0x91), Token::U8(0xdd), Token::U8(0xd1), Token::U8(0x66),
2411 Token::TupleEnd
2412 ]);
2413
2414 assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
2415 assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
2416 assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
2417 }
2418
2419 #[test]
2420 #[cfg(feature = "rand-std")]
2421 fn test_keypair_from_str() {
2422 let ctx = crate::Secp256k1::new();
2423 let keypair = Keypair::new(&ctx, &mut rand::thread_rng());
2424 let mut buf = [0_u8; constants::SECRET_KEY_SIZE * 2]; let s = to_hex(&keypair.secret_key().secret_bytes(), &mut buf).unwrap();
2426 let parsed_key = Keypair::from_str(s).unwrap();
2427 assert_eq!(parsed_key, keypair);
2428 }
2429
2430 #[test]
2431 #[cfg(all(any(feature = "alloc", feature = "global-context"), feature = "serde"))]
2432 fn test_keypair_deserialize_serde() {
2433 let ctx = crate::Secp256k1::new();
2434 let sec_key_str = "4242424242424242424242424242424242424242424242424242424242424242";
2435 let keypair = Keypair::from_seckey_str(&ctx, sec_key_str).unwrap();
2436
2437 serde_test::assert_tokens(&keypair.readable(), &[Token::String(sec_key_str)]);
2438
2439 let sec_key_bytes = keypair.secret_key().secret_bytes();
2440 let tokens = std::iter::once(Token::Tuple { len: 32 })
2441 .chain(sec_key_bytes.iter().copied().map(Token::U8))
2442 .chain(std::iter::once(Token::TupleEnd))
2443 .collect::<Vec<_>>();
2444 serde_test::assert_tokens(&keypair.compact(), &tokens);
2445 }
2446
2447 #[test]
2448 #[should_panic(expected = "The previous implementation was panicking too")]
2449 #[cfg(not(any(feature = "alloc", feature = "global-context")))]
2450 fn test_parse_keypair_no_alloc_panic() {
2451 let key_hex = "4242424242424242424242424242424242424242424242424242424242424242";
2452 let _: Keypair = key_hex.parse().expect("We shouldn't even get this far");
2453 }
2454}
2455
2456#[cfg(bench)]
2457mod benches {
2458 use std::collections::BTreeSet;
2459
2460 use test::Bencher;
2461
2462 use crate::constants::GENERATOR_X;
2463 use crate::PublicKey;
2464
2465 #[bench]
2466 fn bench_pk_ordering(b: &mut Bencher) {
2467 let mut map = BTreeSet::new();
2468 let mut g_slice = [02u8; 33];
2469 g_slice[1..].copy_from_slice(&GENERATOR_X);
2470 let g = PublicKey::from_slice(&g_slice).unwrap();
2471 let mut pk = g;
2472 b.iter(|| {
2473 map.insert(pk);
2474 pk = pk.combine(&pk).unwrap();
2475 })
2476 }
2477}