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::fmt::{self, Write as _};
9use core::ops;
10use core::str::FromStr;
11
12use hashes::{hash160, Hash};
13use hex::{FromHex, HexToArrayError};
14use internals::array_vec::ArrayVec;
15use internals::write_err;
16use io::{Read, Write};
17
18use crate::blockdata::script::ScriptBuf;
19use crate::crypto::ecdsa;
20use crate::internal_macros::impl_asref_push_bytes;
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
933internals::impl_from_infallible!(FromSliceError);
934
935impl fmt::Display for FromSliceError {
936    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
937        use FromSliceError::*;
938
939        match self {
940            Secp256k1(e) => write_err!(f, "secp256k1"; e),
941            InvalidKeyPrefix(b) => write!(f, "key prefix invalid: {}", b),
942            InvalidLength(got) => write!(f, "slice length should be 33 or 65 bytes, got: {}", got),
943        }
944    }
945}
946
947#[cfg(feature = "std")]
948impl std::error::Error for FromSliceError {
949    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
950        use FromSliceError::*;
951
952        match *self {
953            Secp256k1(ref e) => Some(e),
954            InvalidKeyPrefix(_) | InvalidLength(_) => None,
955        }
956    }
957}
958
959impl From<secp256k1::Error> for FromSliceError {
960    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
961}
962
963/// Error generated from WIF key format.
964#[derive(Debug, Clone, PartialEq, Eq)]
965#[non_exhaustive]
966pub enum FromWifError {
967    /// A base58 decoding error.
968    Base58(base58::Error),
969    /// Base58 decoded data was an invalid length.
970    InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
971    /// Base58 decoded data contained an invalid address version byte.
972    InvalidAddressVersion(InvalidAddressVersionError),
973    /// A secp256k1 error.
974    Secp256k1(secp256k1::Error),
975}
976
977internals::impl_from_infallible!(FromWifError);
978
979impl fmt::Display for FromWifError {
980    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
981        use FromWifError::*;
982
983        match *self {
984            Base58(ref e) => write_err!(f, "invalid base58"; e),
985            InvalidBase58PayloadLength(ref e) =>
986                write_err!(f, "decoded base58 data was an invalid length"; e),
987            InvalidAddressVersion(ref e) =>
988                write_err!(f, "decoded base58 data contained an invalid address version btye"; e),
989            Secp256k1(ref e) => write_err!(f, "private key validation failed"; e),
990        }
991    }
992}
993
994#[cfg(feature = "std")]
995impl std::error::Error for FromWifError {
996    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
997        use FromWifError::*;
998
999        match *self {
1000            Base58(ref e) => Some(e),
1001            InvalidBase58PayloadLength(ref e) => Some(e),
1002            InvalidAddressVersion(ref e) => Some(e),
1003            Secp256k1(ref e) => Some(e),
1004        }
1005    }
1006}
1007
1008impl From<base58::Error> for FromWifError {
1009    fn from(e: base58::Error) -> Self { Self::Base58(e) }
1010}
1011
1012impl From<secp256k1::Error> for FromWifError {
1013    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
1014}
1015
1016impl From<InvalidBase58PayloadLengthError> for FromWifError {
1017    fn from(e: InvalidBase58PayloadLengthError) -> FromWifError {
1018        Self::InvalidBase58PayloadLength(e)
1019    }
1020}
1021
1022impl From<InvalidAddressVersionError> for FromWifError {
1023    fn from(e: InvalidAddressVersionError) -> FromWifError { Self::InvalidAddressVersion(e) }
1024}
1025
1026/// Error returned while constructing public key from string.
1027#[derive(Debug, Clone, PartialEq, Eq)]
1028pub enum ParsePublicKeyError {
1029    /// Error originated while parsing string.
1030    Encoding(FromSliceError),
1031    /// Hex decoding error.
1032    InvalidChar(u8),
1033    /// `PublicKey` hex should be 66 or 130 digits long.
1034    InvalidHexLength(usize),
1035}
1036
1037internals::impl_from_infallible!(ParsePublicKeyError);
1038
1039impl fmt::Display for ParsePublicKeyError {
1040    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041        use ParsePublicKeyError::*;
1042        match self {
1043            Encoding(e) => write_err!(f, "string error"; e),
1044            InvalidChar(char) => write!(f, "hex error {}", char),
1045            InvalidHexLength(got) =>
1046                write!(f, "pubkey string should be 66 or 130 digits long, got: {}", got),
1047        }
1048    }
1049}
1050
1051#[cfg(feature = "std")]
1052impl std::error::Error for ParsePublicKeyError {
1053    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1054        use ParsePublicKeyError::*;
1055
1056        match self {
1057            Encoding(e) => Some(e),
1058            InvalidChar(_) | InvalidHexLength(_) => None,
1059        }
1060    }
1061}
1062
1063impl From<FromSliceError> for ParsePublicKeyError {
1064    fn from(e: FromSliceError) -> Self { Self::Encoding(e) }
1065}
1066
1067/// Error returned when parsing a [`CompressedPublicKey`] from a string.
1068#[derive(Debug, Clone, PartialEq, Eq)]
1069pub enum ParseCompressedPublicKeyError {
1070    /// Secp256k1 Error.
1071    Secp256k1(secp256k1::Error),
1072    /// hex to array conversion error.
1073    Hex(hex::HexToArrayError),
1074}
1075
1076internals::impl_from_infallible!(ParseCompressedPublicKeyError);
1077
1078impl fmt::Display for ParseCompressedPublicKeyError {
1079    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1080        use ParseCompressedPublicKeyError::*;
1081        match self {
1082            Secp256k1(e) => write_err!(f, "secp256k1 error"; e),
1083            Hex(e) => write_err!(f, "invalid hex"; e),
1084        }
1085    }
1086}
1087
1088#[cfg(feature = "std")]
1089impl std::error::Error for ParseCompressedPublicKeyError {
1090    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1091        use ParseCompressedPublicKeyError::*;
1092
1093        match self {
1094            Secp256k1(e) => Some(e),
1095            Hex(e) => Some(e),
1096        }
1097    }
1098}
1099
1100impl From<secp256k1::Error> for ParseCompressedPublicKeyError {
1101    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
1102}
1103
1104impl From<hex::HexToArrayError> for ParseCompressedPublicKeyError {
1105    fn from(e: hex::HexToArrayError) -> Self { Self::Hex(e) }
1106}
1107
1108/// Segwit public keys must always be compressed.
1109#[derive(Debug, Clone, PartialEq, Eq)]
1110#[non_exhaustive]
1111pub struct UncompressedPublicKeyError;
1112
1113impl fmt::Display for UncompressedPublicKeyError {
1114    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1115        f.write_str("segwit public keys must always be compressed")
1116    }
1117}
1118
1119#[cfg(feature = "std")]
1120impl std::error::Error for UncompressedPublicKeyError {
1121    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
1122}
1123
1124/// Decoded base58 data was an invalid length.
1125#[derive(Debug, Clone, PartialEq, Eq)]
1126pub struct InvalidBase58PayloadLengthError {
1127    /// The base58 payload length we got after decoding WIF string.
1128    pub(crate) length: usize,
1129}
1130
1131impl InvalidBase58PayloadLengthError {
1132    /// Returns the invalid payload length.
1133    pub fn invalid_base58_payload_length(&self) -> usize { self.length }
1134}
1135
1136impl fmt::Display for InvalidBase58PayloadLengthError {
1137    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1138        write!(f, "decoded base58 data was an invalid length: {} (expected 33 or 34)", self.length)
1139    }
1140}
1141
1142#[cfg(feature = "std")]
1143impl std::error::Error for InvalidBase58PayloadLengthError {}
1144
1145/// Invalid address version in decoded base58 data.
1146#[derive(Debug, Clone, PartialEq, Eq)]
1147pub struct InvalidAddressVersionError {
1148    /// The invalid version.
1149    pub(crate) invalid: u8,
1150}
1151
1152impl InvalidAddressVersionError {
1153    /// Returns the invalid version.
1154    pub fn invalid_address_version(&self) -> u8 { self.invalid }
1155}
1156
1157impl fmt::Display for InvalidAddressVersionError {
1158    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159        write!(f, "invalid address version in decoded base58 data {}", self.invalid)
1160    }
1161}
1162
1163#[cfg(feature = "std")]
1164impl std::error::Error for InvalidAddressVersionError {}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use crate::address::Address;
1170
1171    #[test]
1172    fn test_key_derivation() {
1173        // testnet compressed
1174        let sk =
1175            PrivateKey::from_wif("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1176        assert_eq!(sk.network, NetworkKind::Test);
1177        assert!(sk.compressed);
1178        assert_eq!(&sk.to_wif(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1179
1180        let secp = Secp256k1::new();
1181        let pk = Address::p2pkh(sk.public_key(&secp), sk.network);
1182        assert_eq!(&pk.to_string(), "mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx");
1183
1184        // test string conversion
1185        assert_eq!(&sk.to_string(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1186        let sk_str =
1187            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1188        assert_eq!(&sk.to_wif(), &sk_str.to_wif());
1189
1190        // mainnet uncompressed
1191        let sk =
1192            PrivateKey::from_wif("5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3").unwrap();
1193        assert_eq!(sk.network, NetworkKind::Main);
1194        assert!(!sk.compressed);
1195        assert_eq!(&sk.to_wif(), "5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3");
1196
1197        let secp = Secp256k1::new();
1198        let mut pk = sk.public_key(&secp);
1199        assert!(!pk.compressed);
1200        assert_eq!(&pk.to_string(), "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133");
1201        assert_eq!(pk, PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap());
1202        let addr = Address::p2pkh(pk, sk.network);
1203        assert_eq!(&addr.to_string(), "1GhQvF6dL8xa6wBxLnWmHcQsurx9RxiMc8");
1204        pk.compressed = true;
1205        assert_eq!(
1206            &pk.to_string(),
1207            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1208        );
1209        assert_eq!(
1210            pk,
1211            PublicKey::from_str(
1212                "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1213            )
1214            .unwrap()
1215        );
1216    }
1217
1218    #[test]
1219    fn test_pubkey_hash() {
1220        let pk = PublicKey::from_str(
1221            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1222        )
1223        .unwrap();
1224        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1225        assert_eq!(pk.pubkey_hash().to_string(), "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4");
1226        assert_eq!(upk.pubkey_hash().to_string(), "ac2e7daf42d2c97418fd9f78af2de552bb9c6a7a");
1227    }
1228
1229    #[test]
1230    fn test_wpubkey_hash() {
1231        let pk = PublicKey::from_str(
1232            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1233        )
1234        .unwrap();
1235        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1236        assert_eq!(
1237            pk.wpubkey_hash().unwrap().to_string(),
1238            "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4"
1239        );
1240        assert!(upk.wpubkey_hash().is_err());
1241    }
1242
1243    #[cfg(feature = "serde")]
1244    #[test]
1245    fn test_key_serde() {
1246        use serde_test::{assert_tokens, Configure, Token};
1247
1248        static KEY_WIF: &str = "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy";
1249        static PK_STR: &str = "039b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef";
1250        static PK_STR_U: &str = "\
1251            04\
1252            9b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef\
1253            87288ed73ce47fc4f5c79d19ebfa57da7cff3aff6e819e4ee971d86b5e61875d\
1254        ";
1255        #[rustfmt::skip]
1256        static PK_BYTES: [u8; 33] = [
1257            0x03,
1258            0x9b, 0x63, 0x47, 0x39, 0x85, 0x05, 0xf5, 0xec,
1259            0x93, 0x82, 0x6d, 0xc6, 0x1c, 0x19, 0xf4, 0x7c,
1260            0x66, 0xc0, 0x28, 0x3e, 0xe9, 0xbe, 0x98, 0x0e,
1261            0x29, 0xce, 0x32, 0x5a, 0x0f, 0x46, 0x79, 0xef,
1262        ];
1263        #[rustfmt::skip]
1264        static PK_BYTES_U: [u8; 65] = [
1265            0x04,
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            0x87, 0x28, 0x8e, 0xd7, 0x3c, 0xe4, 0x7f, 0xc4,
1271            0xf5, 0xc7, 0x9d, 0x19, 0xeb, 0xfa, 0x57, 0xda,
1272            0x7c, 0xff, 0x3a, 0xff, 0x6e, 0x81, 0x9e, 0x4e,
1273            0xe9, 0x71, 0xd8, 0x6b, 0x5e, 0x61, 0x87, 0x5d,
1274        ];
1275
1276        let s = Secp256k1::new();
1277        let sk = PrivateKey::from_str(KEY_WIF).unwrap();
1278        let pk = PublicKey::from_private_key(&s, &sk);
1279        let pk_u = PublicKey { inner: pk.inner, compressed: false };
1280
1281        assert_tokens(&sk, &[Token::BorrowedStr(KEY_WIF)]);
1282        assert_tokens(&pk.compact(), &[Token::BorrowedBytes(&PK_BYTES[..])]);
1283        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
1284        assert_tokens(&pk_u.compact(), &[Token::BorrowedBytes(&PK_BYTES_U[..])]);
1285        assert_tokens(&pk_u.readable(), &[Token::BorrowedStr(PK_STR_U)]);
1286    }
1287
1288    fn random_key(mut seed: u8) -> PublicKey {
1289        loop {
1290            let mut data = [0; 65];
1291            for byte in &mut data[..] {
1292                *byte = seed;
1293                // totally a rng
1294                seed = seed.wrapping_mul(41).wrapping_add(43);
1295            }
1296            if data[0] % 2 == 0 {
1297                data[0] = 4;
1298                if let Ok(key) = PublicKey::from_slice(&data[..]) {
1299                    return key;
1300                }
1301            } else {
1302                data[0] = 2 + (data[0] >> 7);
1303                if let Ok(key) = PublicKey::from_slice(&data[..33]) {
1304                    return key;
1305                }
1306            }
1307        }
1308    }
1309
1310    #[test]
1311    fn pubkey_read_write() {
1312        const N_KEYS: usize = 20;
1313        let keys: Vec<_> = (0..N_KEYS).map(|i| random_key(i as u8)).collect();
1314
1315        let mut v = vec![];
1316        for k in &keys {
1317            k.write_into(&mut v).expect("writing into vec");
1318        }
1319
1320        let mut reader = v.as_slice();
1321        let mut dec_keys = vec![];
1322        for _ in 0..N_KEYS {
1323            dec_keys.push(PublicKey::read_from(&mut reader).expect("reading from vec"));
1324        }
1325        assert_eq!(keys, dec_keys);
1326        assert!(PublicKey::read_from(&mut reader).is_err());
1327
1328        // sanity checks
1329        let mut empty: &[u8] = &[];
1330        assert!(PublicKey::read_from(&mut empty).is_err());
1331        assert!(PublicKey::read_from(&mut &[0; 33][..]).is_err());
1332        assert!(PublicKey::read_from(&mut &[2; 32][..]).is_err());
1333        assert!(PublicKey::read_from(&mut &[0; 65][..]).is_err());
1334        assert!(PublicKey::read_from(&mut &[4; 64][..]).is_err());
1335    }
1336
1337    #[test]
1338    fn pubkey_to_sort_key() {
1339        let key1 = PublicKey::from_str(
1340            "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1341        )
1342        .unwrap();
1343        let key2 = PublicKey { inner: key1.inner, compressed: false };
1344        let arrayvec1 = ArrayVec::from_slice(
1345            &<[u8; 33]>::from_hex(
1346                "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1347            )
1348            .unwrap(),
1349        );
1350        let expected1 = SortKey(arrayvec1);
1351        let arrayvec2 = ArrayVec::from_slice(&<[u8; 65]>::from_hex(
1352            "04ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f81794e7f3d5e420641a3bc690067df5541470c966cbca8c694bf39aa16d836918",
1353        ).unwrap());
1354        let expected2 = SortKey(arrayvec2);
1355        assert_eq!(key1.to_sort_key(), expected1);
1356        assert_eq!(key2.to_sort_key(), expected2);
1357    }
1358
1359    #[test]
1360    fn pubkey_sort() {
1361        struct Vector {
1362            input: Vec<PublicKey>,
1363            expect: Vec<PublicKey>,
1364        }
1365        let fmt =
1366            |v: Vec<_>| v.into_iter().map(|s| PublicKey::from_str(s).unwrap()).collect::<Vec<_>>();
1367        let vectors = vec![
1368            // Start BIP67 vectors
1369            // Vector 1
1370            Vector {
1371                input: fmt(vec![
1372                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1373                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1374                ]),
1375                expect: fmt(vec![
1376                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1377                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1378                ]),
1379            },
1380            // Vector 2 (Already sorted, no action required)
1381            Vector {
1382                input: fmt(vec![
1383                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1384                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1385                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1386                ]),
1387                expect: fmt(vec![
1388                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1389                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1390                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1391                ]),
1392            },
1393            // Vector 3
1394            Vector {
1395                input: fmt(vec![
1396                    "030000000000000000000000000000000000004141414141414141414141414141",
1397                    "020000000000000000000000000000000000004141414141414141414141414141",
1398                    "020000000000000000000000000000000000004141414141414141414141414140",
1399                    "030000000000000000000000000000000000004141414141414141414141414140",
1400                ]),
1401                expect: fmt(vec![
1402                    "020000000000000000000000000000000000004141414141414141414141414140",
1403                    "020000000000000000000000000000000000004141414141414141414141414141",
1404                    "030000000000000000000000000000000000004141414141414141414141414140",
1405                    "030000000000000000000000000000000000004141414141414141414141414141",
1406                ]),
1407            },
1408            // Vector 4: (from bitcore)
1409            Vector {
1410                input: fmt(vec![
1411                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1412                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1413                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1414                ]),
1415                expect: fmt(vec![
1416                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1417                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1418                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1419                ]),
1420            },
1421            // Non-BIP67 vectors
1422            Vector {
1423                input: fmt(vec![
1424                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1425                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1426                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1427                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1428                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1429                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1430                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1431                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1432                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1433                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1434                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1435                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1436                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1437                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1438                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1439                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1440                ]),
1441                expect: fmt(vec![
1442                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1443                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1444                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1445                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1446                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1447                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1448                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1449                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1450                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1451                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1452                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1453                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1454                    // These two pubkeys are mirrored. This helps verify the sort past the x value.
1455                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1456                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1457                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1458                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1459                ]),
1460            },
1461        ];
1462        for mut vector in vectors {
1463            vector.input.sort_by_cached_key(|k| PublicKey::to_sort_key(*k));
1464            assert_eq!(vector.input, vector.expect);
1465        }
1466    }
1467
1468    #[test]
1469    #[cfg(feature = "rand-std")]
1470    fn public_key_constructors() {
1471        use secp256k1::rand;
1472
1473        let secp = Secp256k1::new();
1474        let kp = Keypair::new(&secp, &mut rand::thread_rng());
1475
1476        let _ = PublicKey::new(kp);
1477        let _ = PublicKey::new_uncompressed(kp);
1478    }
1479
1480    #[test]
1481    fn public_key_from_str_wrong_length() {
1482        // Sanity checks, we accept string length 130 digits.
1483        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1484        assert_eq!(s.len(), 130);
1485        assert!(PublicKey::from_str(s).is_ok());
1486        // And 66 digits.
1487        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af";
1488        assert_eq!(s.len(), 66);
1489        assert!(PublicKey::from_str(s).is_ok());
1490
1491        let s = "aoeusthb";
1492        assert_eq!(s.len(), 8);
1493        let res = PublicKey::from_str(s);
1494        assert!(res.is_err());
1495        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidHexLength(8));
1496    }
1497
1498    #[test]
1499    fn public_key_from_str_invalid_str() {
1500        // Ensuring test cases fail when PublicKey::from_str is used on invalid keys
1501        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b142";
1502        assert_eq!(s.len(), 130);
1503        let res = PublicKey::from_str(s);
1504        assert!(res.is_err());
1505        assert_eq!(
1506            res.unwrap_err(),
1507            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1508                secp256k1::Error::InvalidPublicKey
1509            ))
1510        );
1511
1512        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd169";
1513        assert_eq!(s.len(), 66);
1514        let res = PublicKey::from_str(s);
1515        assert!(res.is_err());
1516        assert_eq!(
1517            res.unwrap_err(),
1518            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1519                secp256k1::Error::InvalidPublicKey
1520            ))
1521        );
1522
1523        let s = "062e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1524        assert_eq!(s.len(), 130);
1525        let res = PublicKey::from_str(s);
1526        assert!(res.is_err());
1527        assert_eq!(
1528            res.unwrap_err(),
1529            ParsePublicKeyError::Encoding(FromSliceError::InvalidKeyPrefix(6))
1530        );
1531
1532        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b13g";
1533        assert_eq!(s.len(), 130);
1534        let res = PublicKey::from_str(s);
1535        assert!(res.is_err());
1536        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1537
1538        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1ag";
1539        assert_eq!(s.len(), 66);
1540        let res = PublicKey::from_str(s);
1541        assert!(res.is_err());
1542        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1543    }
1544
1545    #[test]
1546    #[cfg(feature = "std")]
1547    fn private_key_debug_is_obfuscated() {
1548        let sk =
1549            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1550        let want =
1551            "PrivateKey { compressed: true, network: Test, inner: SecretKey(#32014e414fdce702) }";
1552        let got = format!("{:?}", sk);
1553        assert_eq!(got, want)
1554    }
1555
1556    #[test]
1557    #[cfg(not(feature = "std"))]
1558    fn private_key_debug_is_obfuscated() {
1559        let sk =
1560            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1561        // Why is this not shortened? In rust-secp256k1/src/secret it is printed with "#{:016x}"?
1562        let want = "PrivateKey { compressed: true, network: Test, inner: SecretKey(#7217ac58fbad8880a91032107b82cb6c5422544b426c350ee005cf509f3dbf7b) }";
1563        let got = format!("{:?}", sk);
1564        assert_eq!(got, want)
1565    }
1566}