Skip to main content

bitcoin/crypto/
key.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin keys.
4//!
5//! This module provides keys used in Bitcoin that can be roundtrip
6//! (de)serialized.
7
8use core::convert::Infallible;
9use core::fmt::{self, Write as _};
10use core::ops;
11use core::str::FromStr;
12
13use hashes::{hash160, Hash};
14use hex::{FromHex, HexToArrayError};
15use io::{Read, Write};
16
17use crate::array_vec::ArrayVec;
18use crate::blockdata::script::ScriptBuf;
19use crate::crypto::ecdsa;
20use crate::internal_macros::{impl_asref_push_bytes, write_err};
21use crate::network::NetworkKind;
22use crate::prelude::*;
23use crate::taproot::{TapNodeHash, TapTweakHash};
24
25#[rustfmt::skip]                // Keep public re-exports separate.
26pub use secp256k1::{constants, Keypair, Parity, Secp256k1, Verification, XOnlyPublicKey};
27
28#[cfg(feature = "rand-std")]
29pub use secp256k1::rand;
30
31/// A Bitcoin ECDSA public key
32#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
33pub struct PublicKey {
34    /// Whether this public key should be serialized as compressed
35    pub compressed: bool,
36    /// The actual ECDSA key
37    pub inner: secp256k1::PublicKey,
38}
39
40impl PublicKey {
41    /// Constructs compressed ECDSA public key from the provided generic Secp256k1 public key
42    pub fn new(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
43        PublicKey { compressed: true, inner: key.into() }
44    }
45
46    /// Constructs uncompressed (legacy) ECDSA public key from the provided generic Secp256k1
47    /// public key
48    pub fn new_uncompressed(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
49        PublicKey { compressed: false, inner: key.into() }
50    }
51
52    fn with_serialized<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
53        if self.compressed {
54            f(&self.inner.serialize())
55        } else {
56            f(&self.inner.serialize_uncompressed())
57        }
58    }
59
60    /// Returns bitcoin 160-bit hash of the public key
61    pub fn pubkey_hash(&self) -> PubkeyHash { self.with_serialized(PubkeyHash::hash) }
62
63    /// Returns bitcoin 160-bit hash of the public key for witness program
64    pub fn wpubkey_hash(&self) -> Result<WPubkeyHash, UncompressedPublicKeyError> {
65        if self.compressed {
66            Ok(WPubkeyHash::from_byte_array(
67                hash160::Hash::hash(&self.inner.serialize()).to_byte_array(),
68            ))
69        } else {
70            Err(UncompressedPublicKeyError)
71        }
72    }
73
74    /// Returns the script code used to spend a P2WPKH input.
75    pub fn p2wpkh_script_code(&self) -> Result<ScriptBuf, UncompressedPublicKeyError> {
76        let key = CompressedPublicKey::try_from(*self)?;
77        Ok(key.p2wpkh_script_code())
78    }
79
80    /// Write the public key into a writer
81    pub fn write_into<W: Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> {
82        self.with_serialized(|bytes| writer.write_all(bytes))
83    }
84
85    /// Read the public key from a reader
86    ///
87    /// This internally reads the first byte before reading the rest, so
88    /// use of a `BufReader` is recommended.
89    pub fn read_from<R: Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
90        let mut bytes = [0; 65];
91
92        reader.read_exact(&mut bytes[0..1])?;
93        let bytes = if bytes[0] < 4 { &mut bytes[..33] } else { &mut bytes[..65] };
94
95        reader.read_exact(&mut bytes[1..])?;
96        Self::from_slice(bytes).map_err(|e| {
97            // Need a static string for no-std io
98            #[cfg(feature = "std")]
99            let reason = e;
100            #[cfg(not(feature = "std"))]
101            let reason = match e {
102                FromSliceError::Secp256k1(_) => "secp256k1 error",
103                FromSliceError::InvalidKeyPrefix(_) => "invalid key prefix",
104                FromSliceError::InvalidLength(_) => "invalid length",
105            };
106            io::Error::new(io::ErrorKind::InvalidData, reason)
107        })
108    }
109
110    /// Serialize the public key to bytes
111    pub fn to_bytes(self) -> Vec<u8> {
112        let mut buf = Vec::new();
113        self.write_into(&mut buf).expect("vecs don't error");
114        buf
115    }
116
117    /// Serialize the public key into a `SortKey`.
118    ///
119    /// `SortKey` is not too useful by itself, but it can be used to sort a
120    /// `[PublicKey]` slice using `sort_unstable_by_key`, `sort_by_cached_key`,
121    /// `sort_by_key`, or any of the other `*_by_key` methods on slice.
122    /// Pass the method into the sort method directly. (ie. `PublicKey::to_sort_key`)
123    ///
124    /// This method of sorting is in line with Bitcoin Core's implementation of
125    /// sorting keys for output descriptors such as `sortedmulti()`.
126    ///
127    /// If every `PublicKey` in the slice is `compressed == true` then this will sort
128    /// the keys in a
129    /// [BIP67](https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki)
130    /// compliant way.
131    ///
132    /// # Example: Using with `sort_unstable_by_key`
133    ///
134    /// ```rust
135    /// use std::str::FromStr;
136    /// use bitcoin::PublicKey;
137    ///
138    /// let pk = |s| PublicKey::from_str(s).unwrap();
139    ///
140    /// let mut unsorted = [
141    ///     pk("04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35"),
142    ///     pk("038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354"),
143    ///     pk("028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa"),
144    ///     pk("04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa"),
145    ///     pk("032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b"),
146    ///     pk("045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8"),
147    ///     pk("0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68"),
148    /// ];
149    /// let sorted = [
150    ///     // These first 4 keys are in a BIP67 compatible sorted order
151    ///     // (since they are compressed)
152    ///     pk("0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68"),
153    ///     pk("028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa"),
154    ///     pk("032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b"),
155    ///     pk("038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354"),
156    ///     // Uncompressed keys are not BIP67 compliant, but are sorted
157    ///     // after compressed keys in Bitcoin Core using `sortedmulti()`
158    ///     pk("045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8"),
159    ///     pk("04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa"),
160    ///     pk("04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35"),
161    /// ];
162    ///
163    /// unsorted.sort_unstable_by_key(|k| PublicKey::to_sort_key(*k));
164    ///
165    /// assert_eq!(unsorted, sorted);
166    /// ```
167    pub fn to_sort_key(self) -> SortKey {
168        if self.compressed {
169            let buf = ArrayVec::from_slice(&self.inner.serialize());
170            SortKey(buf)
171        } else {
172            let buf = ArrayVec::from_slice(&self.inner.serialize_uncompressed());
173            SortKey(buf)
174        }
175    }
176
177    /// Deserialize a public key from a slice
178    pub fn from_slice(data: &[u8]) -> Result<PublicKey, FromSliceError> {
179        let compressed = match data.len() {
180            33 => true,
181            65 => false,
182            len => {
183                return Err(FromSliceError::InvalidLength(len));
184            }
185        };
186
187        if !compressed && data[0] != 0x04 {
188            return Err(FromSliceError::InvalidKeyPrefix(data[0]));
189        }
190
191        Ok(PublicKey { compressed, inner: secp256k1::PublicKey::from_slice(data)? })
192    }
193
194    /// Computes the public key as supposed to be used with this secret
195    pub fn from_private_key<C: secp256k1::Signing>(
196        secp: &Secp256k1<C>,
197        sk: &PrivateKey,
198    ) -> PublicKey {
199        sk.public_key(secp)
200    }
201
202    /// Checks that `sig` is a valid ECDSA signature for `msg` using this public key.
203    pub fn verify<C: secp256k1::Verification>(
204        &self,
205        secp: &Secp256k1<C>,
206        msg: &secp256k1::Message,
207        sig: &ecdsa::Signature,
208    ) -> Result<(), secp256k1::Error> {
209        secp.verify_ecdsa(msg, &sig.signature, &self.inner)
210    }
211}
212
213impl From<secp256k1::PublicKey> for PublicKey {
214    fn from(pk: secp256k1::PublicKey) -> PublicKey { PublicKey::new(pk) }
215}
216
217impl From<PublicKey> for XOnlyPublicKey {
218    fn from(pk: PublicKey) -> XOnlyPublicKey { pk.inner.into() }
219}
220
221/// An opaque return type for PublicKey::to_sort_key
222#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
223pub struct SortKey(ArrayVec<u8, 65>);
224
225impl fmt::Display for PublicKey {
226    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227        self.with_serialized(|bytes| fmt::Display::fmt(&bytes.as_hex(), f))
228    }
229}
230
231impl FromStr for PublicKey {
232    type Err = ParsePublicKeyError;
233    fn from_str(s: &str) -> Result<PublicKey, ParsePublicKeyError> {
234        use HexToArrayError::*;
235
236        match s.len() {
237            66 => {
238                let bytes = <[u8; 33]>::from_hex(s).map_err(|e| match e {
239                    InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
240                    InvalidLength(_) => unreachable!("length checked already"),
241                })?;
242                Ok(PublicKey::from_slice(&bytes)?)
243            }
244            130 => {
245                let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e {
246                    InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
247                    InvalidLength(_) => unreachable!("length checked already"),
248                })?;
249                Ok(PublicKey::from_slice(&bytes)?)
250            }
251            len => Err(ParsePublicKeyError::InvalidHexLength(len)),
252        }
253    }
254}
255
256hashes::hash_newtype! {
257    /// A hash of a public key.
258    pub struct PubkeyHash(hash160::Hash);
259    /// SegWit version of a public key hash.
260    pub struct WPubkeyHash(hash160::Hash);
261}
262impl_asref_push_bytes!(PubkeyHash, WPubkeyHash);
263
264impl From<PublicKey> for PubkeyHash {
265    fn from(key: PublicKey) -> PubkeyHash { key.pubkey_hash() }
266}
267
268impl From<&PublicKey> for PubkeyHash {
269    fn from(key: &PublicKey) -> PubkeyHash { key.pubkey_hash() }
270}
271
272/// An always-compressed Bitcoin ECDSA public key
273#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
274pub struct CompressedPublicKey(pub secp256k1::PublicKey);
275
276impl CompressedPublicKey {
277    /// Returns bitcoin 160-bit hash of the public key
278    pub fn pubkey_hash(&self) -> PubkeyHash { PubkeyHash::hash(&self.to_bytes()) }
279
280    /// Returns bitcoin 160-bit hash of the public key for witness program
281    pub fn wpubkey_hash(&self) -> WPubkeyHash {
282        WPubkeyHash::from_byte_array(hash160::Hash::hash(&self.to_bytes()).to_byte_array())
283    }
284
285    /// Returns the script code used to spend a P2WPKH input.
286    pub fn p2wpkh_script_code(&self) -> ScriptBuf {
287        ScriptBuf::p2wpkh_script_code(self.wpubkey_hash())
288    }
289
290    /// Write the public key into a writer
291    pub fn write_into<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> {
292        writer.write_all(&self.to_bytes())
293    }
294
295    /// Read the public key from a reader
296    ///
297    /// This internally reads the first byte before reading the rest, so
298    /// use of a `BufReader` is recommended.
299    pub fn read_from<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
300        let mut bytes = [0; 33];
301
302        reader.read_exact(&mut bytes)?;
303        #[allow(unused_variables)] // e when std not enabled
304        Self::from_slice(&bytes).map_err(|e| {
305            // Need a static string for no-std io
306            #[cfg(feature = "std")]
307            let reason = e;
308            #[cfg(not(feature = "std"))]
309            let reason = "secp256k1 error";
310            io::Error::new(io::ErrorKind::InvalidData, reason)
311        })
312    }
313
314    /// Serializes the public key.
315    ///
316    /// As the type name suggests, the key is serialzied in compressed format.
317    ///
318    /// Note that this can be used as a sort key to get BIP67-compliant sorting.
319    /// That's why this type doesn't have the `to_sort_key` method - it would duplicate this one.
320    pub fn to_bytes(&self) -> [u8; 33] { self.0.serialize() }
321
322    /// Deserialize a public key from a slice
323    pub fn from_slice(data: &[u8]) -> Result<Self, secp256k1::Error> {
324        secp256k1::PublicKey::from_slice(data).map(CompressedPublicKey)
325    }
326
327    /// Computes the public key as supposed to be used with this secret
328    pub fn from_private_key<C: secp256k1::Signing>(
329        secp: &Secp256k1<C>,
330        sk: &PrivateKey,
331    ) -> Result<Self, UncompressedPublicKeyError> {
332        sk.public_key(secp).try_into()
333    }
334
335    /// Checks that `sig` is a valid ECDSA signature for `msg` using this public key.
336    pub fn verify<C: secp256k1::Verification>(
337        &self,
338        secp: &Secp256k1<C>,
339        msg: &secp256k1::Message,
340        sig: &ecdsa::Signature,
341    ) -> Result<(), secp256k1::Error> {
342        Ok(secp.verify_ecdsa(msg, &sig.signature, &self.0)?)
343    }
344}
345
346impl fmt::Display for CompressedPublicKey {
347    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
348        fmt::LowerHex::fmt(&self.to_bytes().as_hex(), f)
349    }
350}
351
352impl FromStr for CompressedPublicKey {
353    type Err = ParseCompressedPublicKeyError;
354
355    fn from_str(s: &str) -> Result<Self, Self::Err> {
356        CompressedPublicKey::from_slice(&<[u8; 33]>::from_hex(s)?).map_err(Into::into)
357    }
358}
359
360impl TryFrom<PublicKey> for CompressedPublicKey {
361    type Error = UncompressedPublicKeyError;
362
363    fn try_from(value: PublicKey) -> Result<Self, Self::Error> {
364        if value.compressed {
365            Ok(CompressedPublicKey(value.inner))
366        } else {
367            Err(UncompressedPublicKeyError)
368        }
369    }
370}
371
372impl From<CompressedPublicKey> for PublicKey {
373    fn from(value: CompressedPublicKey) -> Self { PublicKey::new(value.0) }
374}
375
376impl From<CompressedPublicKey> for XOnlyPublicKey {
377    fn from(pk: CompressedPublicKey) -> Self { pk.0.into() }
378}
379
380impl From<CompressedPublicKey> for PubkeyHash {
381    fn from(key: CompressedPublicKey) -> Self { key.pubkey_hash() }
382}
383
384impl From<&CompressedPublicKey> for PubkeyHash {
385    fn from(key: &CompressedPublicKey) -> Self { key.pubkey_hash() }
386}
387
388impl From<CompressedPublicKey> for WPubkeyHash {
389    fn from(key: CompressedPublicKey) -> Self { key.wpubkey_hash() }
390}
391
392impl From<&CompressedPublicKey> for WPubkeyHash {
393    fn from(key: &CompressedPublicKey) -> Self { key.wpubkey_hash() }
394}
395
396/// A Bitcoin ECDSA private key
397#[derive(Debug, Copy, Clone, PartialEq, Eq)]
398pub struct PrivateKey {
399    /// Whether this private key should be serialized as compressed
400    pub compressed: bool,
401    /// The network kind on which this key should be used
402    pub network: NetworkKind,
403    /// The actual ECDSA key
404    pub inner: secp256k1::SecretKey,
405}
406
407impl PrivateKey {
408    /// Constructs new compressed ECDSA private key using the secp256k1 algorithm and
409    /// a secure random number generator.
410    #[cfg(feature = "rand-std")]
411    pub fn generate(network: impl Into<NetworkKind>) -> PrivateKey {
412        let secret_key = secp256k1::SecretKey::new(&mut rand::thread_rng());
413        PrivateKey::new(secret_key, network.into())
414    }
415    /// Constructs compressed ECDSA private key from the provided generic Secp256k1 private key
416    /// and the specified network
417    pub fn new(key: secp256k1::SecretKey, network: impl Into<NetworkKind>) -> PrivateKey {
418        PrivateKey { compressed: true, network: network.into(), inner: key }
419    }
420
421    /// Constructs uncompressed (legacy) ECDSA private key from the provided generic Secp256k1
422    /// private key and the specified network
423    pub fn new_uncompressed(
424        key: secp256k1::SecretKey,
425        network: impl Into<NetworkKind>,
426    ) -> PrivateKey {
427        PrivateKey { compressed: false, network: network.into(), inner: key }
428    }
429
430    /// Creates a public key from this private key
431    pub fn public_key<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
432        PublicKey {
433            compressed: self.compressed,
434            inner: secp256k1::PublicKey::from_secret_key(secp, &self.inner),
435        }
436    }
437
438    /// Serialize the private key to bytes
439    pub fn to_bytes(self) -> Vec<u8> { self.inner[..].to_vec() }
440
441    /// Deserialize a private key from a slice
442    pub fn from_slice(
443        data: &[u8],
444        network: impl Into<NetworkKind>,
445    ) -> Result<PrivateKey, secp256k1::Error> {
446        Ok(PrivateKey::new(secp256k1::SecretKey::from_slice(data)?, network))
447    }
448
449    /// Format the private key to WIF format.
450    #[rustfmt::skip]
451    pub fn fmt_wif(&self, fmt: &mut dyn fmt::Write) -> fmt::Result {
452        let mut ret = [0; 34];
453        ret[0] = if self.network.is_mainnet() { 128 } else { 239 };
454
455        ret[1..33].copy_from_slice(&self.inner[..]);
456        let privkey = if self.compressed {
457            ret[33] = 1;
458            base58::encode_check(&ret[..])
459        } else {
460            base58::encode_check(&ret[..33])
461        };
462        fmt.write_str(&privkey)
463    }
464
465    /// Get WIF encoding of this private key.
466    pub fn to_wif(self) -> String {
467        let mut buf = String::new();
468        buf.write_fmt(format_args!("{}", self)).unwrap();
469        buf.shrink_to_fit();
470        buf
471    }
472
473    /// Parse WIF encoded private key.
474    pub fn from_wif(wif: &str) -> Result<PrivateKey, FromWifError> {
475        let data = base58::decode_check(wif)?;
476
477        let compressed = match data.len() {
478            33 => false,
479            34 => true,
480            length => {
481                return Err(InvalidBase58PayloadLengthError { length }.into());
482            }
483        };
484
485        let network = match data[0] {
486            128 => NetworkKind::Main,
487            239 => NetworkKind::Test,
488            invalid => {
489                return Err(InvalidAddressVersionError { invalid }.into());
490            }
491        };
492
493        Ok(PrivateKey {
494            compressed,
495            network,
496            inner: secp256k1::SecretKey::from_slice(&data[1..33])?,
497        })
498    }
499
500    /// Returns a new private key with the negated secret value.
501    ///
502    /// The resulting key corresponds to the same x-only public key (identical x-coordinate)
503    /// but with the opposite y-coordinate parity. This is useful for ensuring compatibility
504    /// with specific public key formats and BIP-340 requirements.
505    #[inline]
506    pub fn negate(&self) -> Self {
507        PrivateKey {
508            compressed: self.compressed,
509            network: self.network,
510            inner: self.inner.negate(),
511        }
512    }
513}
514
515impl fmt::Display for PrivateKey {
516    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.fmt_wif(f) }
517}
518
519impl FromStr for PrivateKey {
520    type Err = FromWifError;
521    fn from_str(s: &str) -> Result<PrivateKey, FromWifError> { PrivateKey::from_wif(s) }
522}
523
524impl ops::Index<ops::RangeFull> for PrivateKey {
525    type Output = [u8];
526    fn index(&self, _: ops::RangeFull) -> &[u8] { &self.inner[..] }
527}
528
529#[cfg(feature = "serde")]
530impl serde::Serialize for PrivateKey {
531    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
532        s.collect_str(self)
533    }
534}
535
536#[cfg(feature = "serde")]
537impl<'de> serde::Deserialize<'de> for PrivateKey {
538    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PrivateKey, D::Error> {
539        struct WifVisitor;
540
541        impl<'de> serde::de::Visitor<'de> for WifVisitor {
542            type Value = PrivateKey;
543
544            fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
545                formatter.write_str("an ASCII WIF string")
546            }
547
548            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
549            where
550                E: serde::de::Error,
551            {
552                if let Ok(s) = core::str::from_utf8(v) {
553                    PrivateKey::from_str(s).map_err(E::custom)
554                } else {
555                    Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
556                }
557            }
558
559            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
560            where
561                E: serde::de::Error,
562            {
563                PrivateKey::from_str(v).map_err(E::custom)
564            }
565        }
566
567        d.deserialize_str(WifVisitor)
568    }
569}
570
571#[cfg(feature = "serde")]
572#[allow(clippy::collapsible_else_if)] // Aids readability.
573impl serde::Serialize for PublicKey {
574    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
575        if s.is_human_readable() {
576            s.collect_str(self)
577        } else {
578            self.with_serialized(|bytes| s.serialize_bytes(bytes))
579        }
580    }
581}
582
583#[cfg(feature = "serde")]
584impl<'de> serde::Deserialize<'de> for PublicKey {
585    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
586        if d.is_human_readable() {
587            struct HexVisitor;
588
589            impl<'de> serde::de::Visitor<'de> for HexVisitor {
590                type Value = PublicKey;
591
592                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
593                    formatter.write_str("an ASCII hex string")
594                }
595
596                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
597                where
598                    E: serde::de::Error,
599                {
600                    if let Ok(hex) = core::str::from_utf8(v) {
601                        PublicKey::from_str(hex).map_err(E::custom)
602                    } else {
603                        Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
604                    }
605                }
606
607                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
608                where
609                    E: serde::de::Error,
610                {
611                    PublicKey::from_str(v).map_err(E::custom)
612                }
613            }
614            d.deserialize_str(HexVisitor)
615        } else {
616            struct BytesVisitor;
617
618            impl<'de> serde::de::Visitor<'de> for BytesVisitor {
619                type Value = PublicKey;
620
621                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
622                    formatter.write_str("a bytestring")
623                }
624
625                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
626                where
627                    E: serde::de::Error,
628                {
629                    PublicKey::from_slice(v).map_err(E::custom)
630                }
631            }
632
633            d.deserialize_bytes(BytesVisitor)
634        }
635    }
636}
637
638#[cfg(feature = "serde")]
639impl serde::Serialize for CompressedPublicKey {
640    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
641        if s.is_human_readable() {
642            s.collect_str(self)
643        } else {
644            s.serialize_bytes(&self.to_bytes())
645        }
646    }
647}
648
649#[cfg(feature = "serde")]
650impl<'de> serde::Deserialize<'de> for CompressedPublicKey {
651    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
652        if d.is_human_readable() {
653            struct HexVisitor;
654
655            impl<'de> serde::de::Visitor<'de> for HexVisitor {
656                type Value = CompressedPublicKey;
657
658                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
659                    formatter.write_str("a 66 digits long ASCII hex string")
660                }
661
662                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
663                where
664                    E: serde::de::Error,
665                {
666                    if let Ok(hex) = core::str::from_utf8(v) {
667                        CompressedPublicKey::from_str(hex).map_err(E::custom)
668                    } else {
669                        Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
670                    }
671                }
672
673                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
674                where
675                    E: serde::de::Error,
676                {
677                    CompressedPublicKey::from_str(v).map_err(E::custom)
678                }
679            }
680            d.deserialize_str(HexVisitor)
681        } else {
682            struct BytesVisitor;
683
684            impl<'de> serde::de::Visitor<'de> for BytesVisitor {
685                type Value = CompressedPublicKey;
686
687                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
688                    formatter.write_str("a bytestring")
689                }
690
691                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
692                where
693                    E: serde::de::Error,
694                {
695                    CompressedPublicKey::from_slice(v).map_err(E::custom)
696                }
697            }
698
699            d.deserialize_bytes(BytesVisitor)
700        }
701    }
702}
703/// Untweaked BIP-340 X-coord-only public key
704pub type UntweakedPublicKey = XOnlyPublicKey;
705
706/// Tweaked BIP-340 X-coord-only public key
707#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
708#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
709#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
710#[cfg_attr(feature = "serde", serde(transparent))]
711pub struct TweakedPublicKey(XOnlyPublicKey);
712
713impl fmt::LowerHex for TweakedPublicKey {
714    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
715}
716
717impl fmt::Display for TweakedPublicKey {
718    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
719}
720
721/// Untweaked BIP-340 key pair
722pub type UntweakedKeypair = Keypair;
723
724/// Tweaked BIP-340 key pair
725///
726/// # Examples
727/// ```
728/// # #[cfg(feature = "rand-std")] {
729/// # use bitcoin::key::{Keypair, TweakedKeypair, TweakedPublicKey};
730/// # use bitcoin::secp256k1::{rand, Secp256k1};
731/// # let secp = Secp256k1::new();
732/// # let keypair = TweakedKeypair::dangerous_assume_tweaked(Keypair::new(&secp, &mut rand::thread_rng()));
733/// // There are various conversion methods available to get a tweaked pubkey from a tweaked keypair.
734/// let (_pk, _parity) = keypair.public_parts();
735/// let _pk  = TweakedPublicKey::from_keypair(keypair);
736/// let _pk = TweakedPublicKey::from(keypair);
737/// # }
738/// ```
739#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
740#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
741#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
742#[cfg_attr(feature = "serde", serde(transparent))]
743pub struct TweakedKeypair(Keypair);
744
745/// A trait for tweaking BIP340 key types (x-only public keys and key pairs).
746pub trait TapTweak {
747    /// Tweaked key type with optional auxiliary information
748    type TweakedAux;
749    /// Tweaked key type
750    type TweakedKey;
751
752    /// Tweaks an untweaked key with corresponding public key value and optional script tree merkle
753    /// root. For the [`Keypair`] type this also tweaks the private key in the pair.
754    ///
755    /// This is done by using the equation Q = P + H(P|c)G, where
756    ///  * Q is the tweaked public key
757    ///  * P is the internal public key
758    ///  * H is the hash function
759    ///  * c is the commitment data
760    ///  * G is the generator point
761    ///
762    /// # Returns
763    /// The tweaked key and its parity.
764    fn tap_tweak<C: Verification>(
765        self,
766        secp: &Secp256k1<C>,
767        merkle_root: Option<TapNodeHash>,
768    ) -> Self::TweakedAux;
769
770    /// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`]
771    ///
772    /// This method is dangerous and can lead to loss of funds if used incorrectly.
773    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
774    fn dangerous_assume_tweaked(self) -> Self::TweakedKey;
775}
776
777impl TapTweak for UntweakedPublicKey {
778    type TweakedAux = (TweakedPublicKey, Parity);
779    type TweakedKey = TweakedPublicKey;
780
781    /// Tweaks an untweaked public key with corresponding public key value and optional script tree
782    /// merkle root.
783    ///
784    /// This is done by using the equation Q = P + H(P|c)G, where
785    ///  * Q is the tweaked public key
786    ///  * P is the internal public key
787    ///  * H is the hash function
788    ///  * c is the commitment data
789    ///  * G is the generator point
790    ///
791    /// # Returns
792    /// The tweaked key and its parity.
793    fn tap_tweak<C: Verification>(
794        self,
795        secp: &Secp256k1<C>,
796        merkle_root: Option<TapNodeHash>,
797    ) -> (TweakedPublicKey, Parity) {
798        let tweak = TapTweakHash::from_key_and_tweak(self, merkle_root).to_scalar();
799        let (output_key, parity) = self.add_tweak(secp, &tweak).expect("Tap tweak failed");
800
801        debug_assert!(self.tweak_add_check(secp, &output_key, parity, tweak));
802        (TweakedPublicKey(output_key), parity)
803    }
804
805    fn dangerous_assume_tweaked(self) -> TweakedPublicKey { TweakedPublicKey(self) }
806}
807
808impl TapTweak for UntweakedKeypair {
809    type TweakedAux = TweakedKeypair;
810    type TweakedKey = TweakedKeypair;
811
812    /// Tweaks private and public keys within an untweaked [`Keypair`] with corresponding public key
813    /// value and optional script tree merkle root.
814    ///
815    /// This is done by tweaking private key within the pair using the equation q = p + H(P|c), where
816    ///  * q is the tweaked private key
817    ///  * p is the internal private key
818    ///  * H is the hash function
819    ///  * c is the commitment data
820    ///
821    /// The public key is generated from a private key by multiplying with generator point, Q = qG.
822    ///
823    /// # Returns
824    ///
825    /// The tweaked key and its parity.
826    fn tap_tweak<C: Verification>(
827        self,
828        secp: &Secp256k1<C>,
829        merkle_root: Option<TapNodeHash>,
830    ) -> TweakedKeypair {
831        let (pubkey, _parity) = XOnlyPublicKey::from_keypair(&self);
832        let tweak = TapTweakHash::from_key_and_tweak(pubkey, merkle_root).to_scalar();
833        let tweaked = self.add_xonly_tweak(secp, &tweak).expect("Tap tweak failed");
834        TweakedKeypair(tweaked)
835    }
836
837    fn dangerous_assume_tweaked(self) -> TweakedKeypair { TweakedKeypair(self) }
838}
839
840impl TweakedPublicKey {
841    /// Returns the [`TweakedPublicKey`] for `keypair`.
842    #[inline]
843    pub fn from_keypair(keypair: TweakedKeypair) -> Self {
844        let (xonly, _parity) = keypair.0.x_only_public_key();
845        TweakedPublicKey(xonly)
846    }
847
848    /// Creates a new [`TweakedPublicKey`] from a [`XOnlyPublicKey`]. No tweak is applied, consider
849    /// calling `tap_tweak` on an [`UntweakedPublicKey`] instead of using this constructor.
850    ///
851    /// This method is dangerous and can lead to loss of funds if used incorrectly.
852    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
853    #[inline]
854    pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> TweakedPublicKey {
855        TweakedPublicKey(key)
856    }
857
858    #[doc(hidden)]
859    #[deprecated(since = "0.32.6", note = "use to_x_only_public_key() instead")]
860    pub fn to_inner(self) -> XOnlyPublicKey { self.0 }
861
862    /// Returns the underlying x-only public key.
863    #[inline]
864    pub fn to_x_only_public_key(self) -> XOnlyPublicKey { self.0 }
865
866    /// Returns a reference to the underlying x-only public key.
867    #[inline]
868    pub fn as_x_only_public_key(&self) -> &XOnlyPublicKey { &self.0 }
869
870    /// Serialize the key as a byte-encoded pair of values. In compressed form
871    /// the y-coordinate is represented by only a single bit, as x determines
872    /// it up to one bit.
873    #[inline]
874    pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] { self.0.serialize() }
875}
876
877impl TweakedKeypair {
878    /// Creates a new [`TweakedKeypair`] from a [`Keypair`]. No tweak is applied, consider
879    /// calling `tap_tweak` on an [`UntweakedKeypair`] instead of using this constructor.
880    ///
881    /// This method is dangerous and can lead to loss of funds if used incorrectly.
882    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
883    #[inline]
884    pub fn dangerous_assume_tweaked(pair: Keypair) -> TweakedKeypair { TweakedKeypair(pair) }
885
886    #[doc(hidden)]
887    #[deprecated(since = "0.32.6", note = "use to_keypair() instead")]
888    pub fn to_inner(self) -> Keypair { self.0 }
889
890    /// Returns the underlying key pair.
891    #[inline]
892    pub fn to_keypair(self) -> Keypair { self.0 }
893
894    /// Returns a reference to the underlying key pair.
895    #[inline]
896    pub fn as_keypair(&self) -> &Keypair { &self.0 }
897
898    /// Returns the [`TweakedPublicKey`] and its [`Parity`] for this [`TweakedKeypair`].
899    #[inline]
900    pub fn public_parts(&self) -> (TweakedPublicKey, Parity) {
901        let (xonly, parity) = self.0.x_only_public_key();
902        (TweakedPublicKey(xonly), parity)
903    }
904}
905
906impl From<TweakedPublicKey> for XOnlyPublicKey {
907    #[inline]
908    fn from(pair: TweakedPublicKey) -> Self { pair.0 }
909}
910
911impl From<TweakedKeypair> for Keypair {
912    #[inline]
913    fn from(pair: TweakedKeypair) -> Self { pair.0 }
914}
915
916impl From<TweakedKeypair> for TweakedPublicKey {
917    #[inline]
918    fn from(pair: TweakedKeypair) -> Self { TweakedPublicKey::from_keypair(pair) }
919}
920
921/// Error returned while generating key from slice.
922#[derive(Debug, Clone, PartialEq, Eq)]
923#[non_exhaustive]
924pub enum FromSliceError {
925    /// Invalid key prefix error.
926    InvalidKeyPrefix(u8),
927    /// A Secp256k1 error.
928    Secp256k1(secp256k1::Error),
929    /// Invalid Length of the slice.
930    InvalidLength(usize),
931}
932
933impl From<Infallible> for FromSliceError {
934    fn from(never: Infallible) -> Self { match never {} }
935}
936
937impl fmt::Display for FromSliceError {
938    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
939        use FromSliceError::*;
940
941        match self {
942            Secp256k1(e) => write_err!(f, "secp256k1"; e),
943            InvalidKeyPrefix(b) => write!(f, "key prefix invalid: {}", b),
944            InvalidLength(got) => write!(f, "slice length should be 33 or 65 bytes, got: {}", got),
945        }
946    }
947}
948
949#[cfg(feature = "std")]
950impl std::error::Error for FromSliceError {
951    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
952        use FromSliceError::*;
953
954        match *self {
955            Secp256k1(ref e) => Some(e),
956            InvalidKeyPrefix(_) | InvalidLength(_) => None,
957        }
958    }
959}
960
961impl From<secp256k1::Error> for FromSliceError {
962    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
963}
964
965/// Error generated from WIF key format.
966#[derive(Debug, Clone, PartialEq, Eq)]
967#[non_exhaustive]
968pub enum FromWifError {
969    /// A base58 decoding error.
970    Base58(base58::Error),
971    /// Base58 decoded data was an invalid length.
972    InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
973    /// Base58 decoded data contained an invalid address version byte.
974    InvalidAddressVersion(InvalidAddressVersionError),
975    /// A secp256k1 error.
976    Secp256k1(secp256k1::Error),
977}
978
979impl From<Infallible> for FromWifError {
980    fn from(never: Infallible) -> Self { match never {} }
981}
982
983impl fmt::Display for FromWifError {
984    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
985        use FromWifError::*;
986
987        match *self {
988            Base58(ref e) => write_err!(f, "invalid base58"; e),
989            InvalidBase58PayloadLength(ref e) =>
990                write_err!(f, "decoded base58 data was an invalid length"; e),
991            InvalidAddressVersion(ref e) =>
992                write_err!(f, "decoded base58 data contained an invalid address version btye"; e),
993            Secp256k1(ref e) => write_err!(f, "private key validation failed"; e),
994        }
995    }
996}
997
998#[cfg(feature = "std")]
999impl std::error::Error for FromWifError {
1000    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1001        use FromWifError::*;
1002
1003        match *self {
1004            Base58(ref e) => Some(e),
1005            InvalidBase58PayloadLength(ref e) => Some(e),
1006            InvalidAddressVersion(ref e) => Some(e),
1007            Secp256k1(ref e) => Some(e),
1008        }
1009    }
1010}
1011
1012impl From<base58::Error> for FromWifError {
1013    fn from(e: base58::Error) -> Self { Self::Base58(e) }
1014}
1015
1016impl From<secp256k1::Error> for FromWifError {
1017    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
1018}
1019
1020impl From<InvalidBase58PayloadLengthError> for FromWifError {
1021    fn from(e: InvalidBase58PayloadLengthError) -> FromWifError {
1022        Self::InvalidBase58PayloadLength(e)
1023    }
1024}
1025
1026impl From<InvalidAddressVersionError> for FromWifError {
1027    fn from(e: InvalidAddressVersionError) -> FromWifError { Self::InvalidAddressVersion(e) }
1028}
1029
1030/// Error returned while constructing public key from string.
1031#[derive(Debug, Clone, PartialEq, Eq)]
1032pub enum ParsePublicKeyError {
1033    /// Error originated while parsing string.
1034    Encoding(FromSliceError),
1035    /// Hex decoding error.
1036    InvalidChar(u8),
1037    /// `PublicKey` hex should be 66 or 130 digits long.
1038    InvalidHexLength(usize),
1039}
1040
1041impl From<Infallible> for ParsePublicKeyError {
1042    fn from(never: Infallible) -> Self { match never {} }
1043}
1044
1045impl fmt::Display for ParsePublicKeyError {
1046    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1047        use ParsePublicKeyError::*;
1048        match self {
1049            Encoding(e) => write_err!(f, "string error"; e),
1050            InvalidChar(char) => write!(f, "hex error {}", char),
1051            InvalidHexLength(got) =>
1052                write!(f, "pubkey string should be 66 or 130 digits long, got: {}", got),
1053        }
1054    }
1055}
1056
1057#[cfg(feature = "std")]
1058impl std::error::Error for ParsePublicKeyError {
1059    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1060        use ParsePublicKeyError::*;
1061
1062        match self {
1063            Encoding(e) => Some(e),
1064            InvalidChar(_) | InvalidHexLength(_) => None,
1065        }
1066    }
1067}
1068
1069impl From<FromSliceError> for ParsePublicKeyError {
1070    fn from(e: FromSliceError) -> Self { Self::Encoding(e) }
1071}
1072
1073/// Error returned when parsing a [`CompressedPublicKey`] from a string.
1074#[derive(Debug, Clone, PartialEq, Eq)]
1075pub enum ParseCompressedPublicKeyError {
1076    /// Secp256k1 Error.
1077    Secp256k1(secp256k1::Error),
1078    /// hex to array conversion error.
1079    Hex(hex::HexToArrayError),
1080}
1081
1082impl From<Infallible> for ParseCompressedPublicKeyError {
1083    fn from(never: Infallible) -> Self { match never {} }
1084}
1085
1086impl fmt::Display for ParseCompressedPublicKeyError {
1087    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1088        use ParseCompressedPublicKeyError::*;
1089        match self {
1090            Secp256k1(e) => write_err!(f, "secp256k1 error"; e),
1091            Hex(e) => write_err!(f, "invalid hex"; e),
1092        }
1093    }
1094}
1095
1096#[cfg(feature = "std")]
1097impl std::error::Error for ParseCompressedPublicKeyError {
1098    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1099        use ParseCompressedPublicKeyError::*;
1100
1101        match self {
1102            Secp256k1(e) => Some(e),
1103            Hex(e) => Some(e),
1104        }
1105    }
1106}
1107
1108impl From<secp256k1::Error> for ParseCompressedPublicKeyError {
1109    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
1110}
1111
1112impl From<hex::HexToArrayError> for ParseCompressedPublicKeyError {
1113    fn from(e: hex::HexToArrayError) -> Self { Self::Hex(e) }
1114}
1115
1116/// Segwit public keys must always be compressed.
1117#[derive(Debug, Clone, PartialEq, Eq)]
1118#[non_exhaustive]
1119pub struct UncompressedPublicKeyError;
1120
1121impl fmt::Display for UncompressedPublicKeyError {
1122    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1123        f.write_str("segwit public keys must always be compressed")
1124    }
1125}
1126
1127#[cfg(feature = "std")]
1128impl std::error::Error for UncompressedPublicKeyError {
1129    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
1130}
1131
1132/// Decoded base58 data was an invalid length.
1133#[derive(Debug, Clone, PartialEq, Eq)]
1134pub struct InvalidBase58PayloadLengthError {
1135    /// The base58 payload length we got after decoding WIF string.
1136    pub(crate) length: usize,
1137}
1138
1139impl InvalidBase58PayloadLengthError {
1140    /// Returns the invalid payload length.
1141    pub fn invalid_base58_payload_length(&self) -> usize { self.length }
1142}
1143
1144impl fmt::Display for InvalidBase58PayloadLengthError {
1145    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1146        write!(f, "decoded base58 data was an invalid length: {} (expected 33 or 34)", self.length)
1147    }
1148}
1149
1150#[cfg(feature = "std")]
1151impl std::error::Error for InvalidBase58PayloadLengthError {}
1152
1153/// Invalid address version in decoded base58 data.
1154#[derive(Debug, Clone, PartialEq, Eq)]
1155pub struct InvalidAddressVersionError {
1156    /// The invalid version.
1157    pub(crate) invalid: u8,
1158}
1159
1160impl InvalidAddressVersionError {
1161    /// Returns the invalid version.
1162    pub fn invalid_address_version(&self) -> u8 { self.invalid }
1163}
1164
1165impl fmt::Display for InvalidAddressVersionError {
1166    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1167        write!(f, "invalid address version in decoded base58 data {}", self.invalid)
1168    }
1169}
1170
1171#[cfg(feature = "std")]
1172impl std::error::Error for InvalidAddressVersionError {}
1173
1174#[cfg(test)]
1175mod tests {
1176    use super::*;
1177    use crate::address::Address;
1178
1179    #[test]
1180    fn test_key_derivation() {
1181        // testnet compressed
1182        let sk =
1183            PrivateKey::from_wif("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1184        assert_eq!(sk.network, NetworkKind::Test);
1185        assert!(sk.compressed);
1186        assert_eq!(&sk.to_wif(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1187
1188        let secp = Secp256k1::new();
1189        let pk = Address::p2pkh(sk.public_key(&secp), sk.network);
1190        assert_eq!(&pk.to_string(), "mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx");
1191
1192        // test string conversion
1193        assert_eq!(&sk.to_string(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1194        let sk_str =
1195            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1196        assert_eq!(&sk.to_wif(), &sk_str.to_wif());
1197
1198        // mainnet uncompressed
1199        let sk =
1200            PrivateKey::from_wif("5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3").unwrap();
1201        assert_eq!(sk.network, NetworkKind::Main);
1202        assert!(!sk.compressed);
1203        assert_eq!(&sk.to_wif(), "5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3");
1204
1205        let secp = Secp256k1::new();
1206        let mut pk = sk.public_key(&secp);
1207        assert!(!pk.compressed);
1208        assert_eq!(&pk.to_string(), "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133");
1209        assert_eq!(pk, PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap());
1210        let addr = Address::p2pkh(pk, sk.network);
1211        assert_eq!(&addr.to_string(), "1GhQvF6dL8xa6wBxLnWmHcQsurx9RxiMc8");
1212        pk.compressed = true;
1213        assert_eq!(
1214            &pk.to_string(),
1215            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1216        );
1217        assert_eq!(
1218            pk,
1219            PublicKey::from_str(
1220                "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1221            )
1222            .unwrap()
1223        );
1224    }
1225
1226    #[test]
1227    fn test_pubkey_hash() {
1228        let pk = PublicKey::from_str(
1229            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1230        )
1231        .unwrap();
1232        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1233        assert_eq!(pk.pubkey_hash().to_string(), "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4");
1234        assert_eq!(upk.pubkey_hash().to_string(), "ac2e7daf42d2c97418fd9f78af2de552bb9c6a7a");
1235    }
1236
1237    #[test]
1238    fn test_wpubkey_hash() {
1239        let pk = PublicKey::from_str(
1240            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1241        )
1242        .unwrap();
1243        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1244        assert_eq!(
1245            pk.wpubkey_hash().unwrap().to_string(),
1246            "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4"
1247        );
1248        assert!(upk.wpubkey_hash().is_err());
1249    }
1250
1251    #[cfg(feature = "serde")]
1252    #[test]
1253    fn test_key_serde() {
1254        use serde_test::{assert_tokens, Configure, Token};
1255
1256        static KEY_WIF: &str = "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy";
1257        static PK_STR: &str = "039b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef";
1258        static PK_STR_U: &str = "\
1259            04\
1260            9b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef\
1261            87288ed73ce47fc4f5c79d19ebfa57da7cff3aff6e819e4ee971d86b5e61875d\
1262        ";
1263        #[rustfmt::skip]
1264        static PK_BYTES: [u8; 33] = [
1265            0x03,
1266            0x9b, 0x63, 0x47, 0x39, 0x85, 0x05, 0xf5, 0xec,
1267            0x93, 0x82, 0x6d, 0xc6, 0x1c, 0x19, 0xf4, 0x7c,
1268            0x66, 0xc0, 0x28, 0x3e, 0xe9, 0xbe, 0x98, 0x0e,
1269            0x29, 0xce, 0x32, 0x5a, 0x0f, 0x46, 0x79, 0xef,
1270        ];
1271        #[rustfmt::skip]
1272        static PK_BYTES_U: [u8; 65] = [
1273            0x04,
1274            0x9b, 0x63, 0x47, 0x39, 0x85, 0x05, 0xf5, 0xec,
1275            0x93, 0x82, 0x6d, 0xc6, 0x1c, 0x19, 0xf4, 0x7c,
1276            0x66, 0xc0, 0x28, 0x3e, 0xe9, 0xbe, 0x98, 0x0e,
1277            0x29, 0xce, 0x32, 0x5a, 0x0f, 0x46, 0x79, 0xef,
1278            0x87, 0x28, 0x8e, 0xd7, 0x3c, 0xe4, 0x7f, 0xc4,
1279            0xf5, 0xc7, 0x9d, 0x19, 0xeb, 0xfa, 0x57, 0xda,
1280            0x7c, 0xff, 0x3a, 0xff, 0x6e, 0x81, 0x9e, 0x4e,
1281            0xe9, 0x71, 0xd8, 0x6b, 0x5e, 0x61, 0x87, 0x5d,
1282        ];
1283
1284        let s = Secp256k1::new();
1285        let sk = PrivateKey::from_str(KEY_WIF).unwrap();
1286        let pk = PublicKey::from_private_key(&s, &sk);
1287        let pk_u = PublicKey { inner: pk.inner, compressed: false };
1288
1289        assert_tokens(&sk, &[Token::BorrowedStr(KEY_WIF)]);
1290        assert_tokens(&pk.compact(), &[Token::BorrowedBytes(&PK_BYTES[..])]);
1291        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
1292        assert_tokens(&pk_u.compact(), &[Token::BorrowedBytes(&PK_BYTES_U[..])]);
1293        assert_tokens(&pk_u.readable(), &[Token::BorrowedStr(PK_STR_U)]);
1294    }
1295
1296    fn random_key(mut seed: u8) -> PublicKey {
1297        loop {
1298            let mut data = [0; 65];
1299            for byte in &mut data[..] {
1300                *byte = seed;
1301                // totally a rng
1302                seed = seed.wrapping_mul(41).wrapping_add(43);
1303            }
1304            if data[0] % 2 == 0 {
1305                data[0] = 4;
1306                if let Ok(key) = PublicKey::from_slice(&data[..]) {
1307                    return key;
1308                }
1309            } else {
1310                data[0] = 2 + (data[0] >> 7);
1311                if let Ok(key) = PublicKey::from_slice(&data[..33]) {
1312                    return key;
1313                }
1314            }
1315        }
1316    }
1317
1318    #[test]
1319    fn pubkey_read_write() {
1320        const N_KEYS: usize = 20;
1321        let keys: Vec<_> = (0..N_KEYS).map(|i| random_key(i as u8)).collect();
1322
1323        let mut v = vec![];
1324        for k in &keys {
1325            k.write_into(&mut v).expect("writing into vec");
1326        }
1327
1328        let mut reader = v.as_slice();
1329        let mut dec_keys = vec![];
1330        for _ in 0..N_KEYS {
1331            dec_keys.push(PublicKey::read_from(&mut reader).expect("reading from vec"));
1332        }
1333        assert_eq!(keys, dec_keys);
1334        assert!(PublicKey::read_from(&mut reader).is_err());
1335
1336        // sanity checks
1337        let mut empty: &[u8] = &[];
1338        assert!(PublicKey::read_from(&mut empty).is_err());
1339        assert!(PublicKey::read_from(&mut &[0; 33][..]).is_err());
1340        assert!(PublicKey::read_from(&mut &[2; 32][..]).is_err());
1341        assert!(PublicKey::read_from(&mut &[0; 65][..]).is_err());
1342        assert!(PublicKey::read_from(&mut &[4; 64][..]).is_err());
1343    }
1344
1345    #[test]
1346    fn pubkey_to_sort_key() {
1347        let key1 = PublicKey::from_str(
1348            "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1349        )
1350        .unwrap();
1351        let key2 = PublicKey { inner: key1.inner, compressed: false };
1352        let arrayvec1 = ArrayVec::from_slice(
1353            &<[u8; 33]>::from_hex(
1354                "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1355            )
1356            .unwrap(),
1357        );
1358        let expected1 = SortKey(arrayvec1);
1359        let arrayvec2 = ArrayVec::from_slice(&<[u8; 65]>::from_hex(
1360            "04ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f81794e7f3d5e420641a3bc690067df5541470c966cbca8c694bf39aa16d836918",
1361        ).unwrap());
1362        let expected2 = SortKey(arrayvec2);
1363        assert_eq!(key1.to_sort_key(), expected1);
1364        assert_eq!(key2.to_sort_key(), expected2);
1365    }
1366
1367    #[test]
1368    fn pubkey_sort() {
1369        struct Vector {
1370            input: Vec<PublicKey>,
1371            expect: Vec<PublicKey>,
1372        }
1373        let fmt =
1374            |v: Vec<_>| v.into_iter().map(|s| PublicKey::from_str(s).unwrap()).collect::<Vec<_>>();
1375        let vectors = vec![
1376            // Start BIP67 vectors
1377            // Vector 1
1378            Vector {
1379                input: fmt(vec![
1380                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1381                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1382                ]),
1383                expect: fmt(vec![
1384                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1385                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1386                ]),
1387            },
1388            // Vector 2 (Already sorted, no action required)
1389            Vector {
1390                input: fmt(vec![
1391                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1392                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1393                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1394                ]),
1395                expect: fmt(vec![
1396                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1397                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1398                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1399                ]),
1400            },
1401            // Vector 3
1402            Vector {
1403                input: fmt(vec![
1404                    "030000000000000000000000000000000000004141414141414141414141414141",
1405                    "020000000000000000000000000000000000004141414141414141414141414141",
1406                    "020000000000000000000000000000000000004141414141414141414141414140",
1407                    "030000000000000000000000000000000000004141414141414141414141414140",
1408                ]),
1409                expect: fmt(vec![
1410                    "020000000000000000000000000000000000004141414141414141414141414140",
1411                    "020000000000000000000000000000000000004141414141414141414141414141",
1412                    "030000000000000000000000000000000000004141414141414141414141414140",
1413                    "030000000000000000000000000000000000004141414141414141414141414141",
1414                ]),
1415            },
1416            // Vector 4: (from bitcore)
1417            Vector {
1418                input: fmt(vec![
1419                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1420                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1421                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1422                ]),
1423                expect: fmt(vec![
1424                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1425                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1426                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1427                ]),
1428            },
1429            // Non-BIP67 vectors
1430            Vector {
1431                input: fmt(vec![
1432                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1433                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1434                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1435                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1436                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1437                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1438                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1439                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1440                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1441                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1442                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1443                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1444                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1445                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1446                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1447                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1448                ]),
1449                expect: fmt(vec![
1450                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1451                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1452                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1453                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1454                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1455                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1456                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1457                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1458                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1459                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1460                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1461                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1462                    // These two pubkeys are mirrored. This helps verify the sort past the x value.
1463                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1464                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1465                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1466                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1467                ]),
1468            },
1469        ];
1470        for mut vector in vectors {
1471            vector.input.sort_by_cached_key(|k| PublicKey::to_sort_key(*k));
1472            assert_eq!(vector.input, vector.expect);
1473        }
1474    }
1475
1476    #[test]
1477    #[cfg(feature = "rand-std")]
1478    fn public_key_constructors() {
1479        use secp256k1::rand;
1480
1481        let secp = Secp256k1::new();
1482        let kp = Keypair::new(&secp, &mut rand::thread_rng());
1483
1484        let _ = PublicKey::new(kp);
1485        let _ = PublicKey::new_uncompressed(kp);
1486    }
1487
1488    #[test]
1489    fn public_key_from_str_wrong_length() {
1490        // Sanity checks, we accept string length 130 digits.
1491        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1492        assert_eq!(s.len(), 130);
1493        assert!(PublicKey::from_str(s).is_ok());
1494        // And 66 digits.
1495        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af";
1496        assert_eq!(s.len(), 66);
1497        assert!(PublicKey::from_str(s).is_ok());
1498
1499        let s = "aoeusthb";
1500        assert_eq!(s.len(), 8);
1501        let res = PublicKey::from_str(s);
1502        assert!(res.is_err());
1503        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidHexLength(8));
1504    }
1505
1506    #[test]
1507    fn public_key_from_str_invalid_str() {
1508        // Ensuring test cases fail when PublicKey::from_str is used on invalid keys
1509        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b142";
1510        assert_eq!(s.len(), 130);
1511        let res = PublicKey::from_str(s);
1512        assert!(res.is_err());
1513        assert_eq!(
1514            res.unwrap_err(),
1515            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1516                secp256k1::Error::InvalidPublicKey
1517            ))
1518        );
1519
1520        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd169";
1521        assert_eq!(s.len(), 66);
1522        let res = PublicKey::from_str(s);
1523        assert!(res.is_err());
1524        assert_eq!(
1525            res.unwrap_err(),
1526            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1527                secp256k1::Error::InvalidPublicKey
1528            ))
1529        );
1530
1531        let s = "062e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1532        assert_eq!(s.len(), 130);
1533        let res = PublicKey::from_str(s);
1534        assert!(res.is_err());
1535        assert_eq!(
1536            res.unwrap_err(),
1537            ParsePublicKeyError::Encoding(FromSliceError::InvalidKeyPrefix(6))
1538        );
1539
1540        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b13g";
1541        assert_eq!(s.len(), 130);
1542        let res = PublicKey::from_str(s);
1543        assert!(res.is_err());
1544        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1545
1546        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1ag";
1547        assert_eq!(s.len(), 66);
1548        let res = PublicKey::from_str(s);
1549        assert!(res.is_err());
1550        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1551    }
1552
1553    #[test]
1554    #[cfg(feature = "std")]
1555    fn private_key_debug_is_obfuscated() {
1556        let sk =
1557            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1558        let want =
1559            "PrivateKey { compressed: true, network: Test, inner: SecretKey(#32014e414fdce702) }";
1560        let got = format!("{:?}", sk);
1561        assert_eq!(got, want)
1562    }
1563
1564    #[test]
1565    #[cfg(not(feature = "std"))]
1566    fn private_key_debug_is_obfuscated() {
1567        let sk =
1568            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1569        // Why is this not shortened? In rust-secp256k1/src/secret it is printed with "#{:016x}"?
1570        let want = "PrivateKey { compressed: true, network: Test, inner: SecretKey(#7217ac58fbad8880a91032107b82cb6c5422544b426c350ee005cf509f3dbf7b) }";
1571        let got = format!("{:?}", sk);
1572        assert_eq!(got, want)
1573    }
1574}