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
501impl fmt::Display for PrivateKey {
502    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.fmt_wif(f) }
503}
504
505impl FromStr for PrivateKey {
506    type Err = FromWifError;
507    fn from_str(s: &str) -> Result<PrivateKey, FromWifError> { PrivateKey::from_wif(s) }
508}
509
510impl ops::Index<ops::RangeFull> for PrivateKey {
511    type Output = [u8];
512    fn index(&self, _: ops::RangeFull) -> &[u8] { &self.inner[..] }
513}
514
515#[cfg(feature = "serde")]
516impl serde::Serialize for PrivateKey {
517    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
518        s.collect_str(self)
519    }
520}
521
522#[cfg(feature = "serde")]
523impl<'de> serde::Deserialize<'de> for PrivateKey {
524    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PrivateKey, D::Error> {
525        struct WifVisitor;
526
527        impl<'de> serde::de::Visitor<'de> for WifVisitor {
528            type Value = PrivateKey;
529
530            fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
531                formatter.write_str("an ASCII WIF string")
532            }
533
534            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
535            where
536                E: serde::de::Error,
537            {
538                if let Ok(s) = core::str::from_utf8(v) {
539                    PrivateKey::from_str(s).map_err(E::custom)
540                } else {
541                    Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
542                }
543            }
544
545            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
546            where
547                E: serde::de::Error,
548            {
549                PrivateKey::from_str(v).map_err(E::custom)
550            }
551        }
552
553        d.deserialize_str(WifVisitor)
554    }
555}
556
557#[cfg(feature = "serde")]
558#[allow(clippy::collapsible_else_if)] // Aids readability.
559impl serde::Serialize for PublicKey {
560    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
561        if s.is_human_readable() {
562            s.collect_str(self)
563        } else {
564            self.with_serialized(|bytes| s.serialize_bytes(bytes))
565        }
566    }
567}
568
569#[cfg(feature = "serde")]
570impl<'de> serde::Deserialize<'de> for PublicKey {
571    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
572        if d.is_human_readable() {
573            struct HexVisitor;
574
575            impl<'de> serde::de::Visitor<'de> for HexVisitor {
576                type Value = PublicKey;
577
578                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
579                    formatter.write_str("an ASCII hex string")
580                }
581
582                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
583                where
584                    E: serde::de::Error,
585                {
586                    if let Ok(hex) = core::str::from_utf8(v) {
587                        PublicKey::from_str(hex).map_err(E::custom)
588                    } else {
589                        Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
590                    }
591                }
592
593                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
594                where
595                    E: serde::de::Error,
596                {
597                    PublicKey::from_str(v).map_err(E::custom)
598                }
599            }
600            d.deserialize_str(HexVisitor)
601        } else {
602            struct BytesVisitor;
603
604            impl<'de> serde::de::Visitor<'de> for BytesVisitor {
605                type Value = PublicKey;
606
607                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
608                    formatter.write_str("a bytestring")
609                }
610
611                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
612                where
613                    E: serde::de::Error,
614                {
615                    PublicKey::from_slice(v).map_err(E::custom)
616                }
617            }
618
619            d.deserialize_bytes(BytesVisitor)
620        }
621    }
622}
623
624#[cfg(feature = "serde")]
625impl serde::Serialize for CompressedPublicKey {
626    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
627        if s.is_human_readable() {
628            s.collect_str(self)
629        } else {
630            s.serialize_bytes(&self.to_bytes())
631        }
632    }
633}
634
635#[cfg(feature = "serde")]
636impl<'de> serde::Deserialize<'de> for CompressedPublicKey {
637    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
638        if d.is_human_readable() {
639            struct HexVisitor;
640
641            impl<'de> serde::de::Visitor<'de> for HexVisitor {
642                type Value = CompressedPublicKey;
643
644                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
645                    formatter.write_str("a 66 digits long ASCII hex string")
646                }
647
648                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
649                where
650                    E: serde::de::Error,
651                {
652                    if let Ok(hex) = core::str::from_utf8(v) {
653                        CompressedPublicKey::from_str(hex).map_err(E::custom)
654                    } else {
655                        Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
656                    }
657                }
658
659                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
660                where
661                    E: serde::de::Error,
662                {
663                    CompressedPublicKey::from_str(v).map_err(E::custom)
664                }
665            }
666            d.deserialize_str(HexVisitor)
667        } else {
668            struct BytesVisitor;
669
670            impl<'de> serde::de::Visitor<'de> for BytesVisitor {
671                type Value = CompressedPublicKey;
672
673                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
674                    formatter.write_str("a bytestring")
675                }
676
677                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
678                where
679                    E: serde::de::Error,
680                {
681                    CompressedPublicKey::from_slice(v).map_err(E::custom)
682                }
683            }
684
685            d.deserialize_bytes(BytesVisitor)
686        }
687    }
688}
689/// Untweaked BIP-340 X-coord-only public key
690pub type UntweakedPublicKey = XOnlyPublicKey;
691
692/// Tweaked BIP-340 X-coord-only public key
693#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
694#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
695#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
696#[cfg_attr(feature = "serde", serde(transparent))]
697pub struct TweakedPublicKey(XOnlyPublicKey);
698
699impl fmt::LowerHex for TweakedPublicKey {
700    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
701}
702
703impl fmt::Display for TweakedPublicKey {
704    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
705}
706
707/// Untweaked BIP-340 key pair
708pub type UntweakedKeypair = Keypair;
709
710/// Tweaked BIP-340 key pair
711///
712/// # Examples
713/// ```
714/// # #[cfg(feature = "rand-std")] {
715/// # use bitcoin::key::{Keypair, TweakedKeypair, TweakedPublicKey};
716/// # use bitcoin::secp256k1::{rand, Secp256k1};
717/// # let secp = Secp256k1::new();
718/// # let keypair = TweakedKeypair::dangerous_assume_tweaked(Keypair::new(&secp, &mut rand::thread_rng()));
719/// // There are various conversion methods available to get a tweaked pubkey from a tweaked keypair.
720/// let (_pk, _parity) = keypair.public_parts();
721/// let _pk  = TweakedPublicKey::from_keypair(keypair);
722/// let _pk = TweakedPublicKey::from(keypair);
723/// # }
724/// ```
725#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
726#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
727#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
728#[cfg_attr(feature = "serde", serde(transparent))]
729pub struct TweakedKeypair(Keypair);
730
731/// A trait for tweaking BIP340 key types (x-only public keys and key pairs).
732pub trait TapTweak {
733    /// Tweaked key type with optional auxiliary information
734    type TweakedAux;
735    /// Tweaked key type
736    type TweakedKey;
737
738    /// Tweaks an untweaked key with corresponding public key value and optional script tree merkle
739    /// root. For the [`Keypair`] type this also tweaks the private key in the pair.
740    ///
741    /// This is done by using the equation Q = P + H(P|c)G, where
742    ///  * Q is the tweaked public key
743    ///  * P is the internal public key
744    ///  * H is the hash function
745    ///  * c is the commitment data
746    ///  * G is the generator point
747    ///
748    /// # Returns
749    /// The tweaked key and its parity.
750    fn tap_tweak<C: Verification>(
751        self,
752        secp: &Secp256k1<C>,
753        merkle_root: Option<TapNodeHash>,
754    ) -> Self::TweakedAux;
755
756    /// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`]
757    ///
758    /// This method is dangerous and can lead to loss of funds if used incorrectly.
759    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
760    fn dangerous_assume_tweaked(self) -> Self::TweakedKey;
761}
762
763impl TapTweak for UntweakedPublicKey {
764    type TweakedAux = (TweakedPublicKey, Parity);
765    type TweakedKey = TweakedPublicKey;
766
767    /// Tweaks an untweaked public key with corresponding public key value and optional script tree
768    /// merkle root.
769    ///
770    /// This is done by using the equation Q = P + H(P|c)G, where
771    ///  * Q is the tweaked public key
772    ///  * P is the internal public key
773    ///  * H is the hash function
774    ///  * c is the commitment data
775    ///  * G is the generator point
776    ///
777    /// # Returns
778    /// The tweaked key and its parity.
779    fn tap_tweak<C: Verification>(
780        self,
781        secp: &Secp256k1<C>,
782        merkle_root: Option<TapNodeHash>,
783    ) -> (TweakedPublicKey, Parity) {
784        let tweak = TapTweakHash::from_key_and_tweak(self, merkle_root).to_scalar();
785        let (output_key, parity) = self.add_tweak(secp, &tweak).expect("Tap tweak failed");
786
787        debug_assert!(self.tweak_add_check(secp, &output_key, parity, tweak));
788        (TweakedPublicKey(output_key), parity)
789    }
790
791    fn dangerous_assume_tweaked(self) -> TweakedPublicKey { TweakedPublicKey(self) }
792}
793
794impl TapTweak for UntweakedKeypair {
795    type TweakedAux = TweakedKeypair;
796    type TweakedKey = TweakedKeypair;
797
798    /// Tweaks private and public keys within an untweaked [`Keypair`] with corresponding public key
799    /// value and optional script tree merkle root.
800    ///
801    /// This is done by tweaking private key within the pair using the equation q = p + H(P|c), where
802    ///  * q is the tweaked private key
803    ///  * p is the internal private key
804    ///  * H is the hash function
805    ///  * c is the commitment data
806    ///
807    /// The public key is generated from a private key by multiplying with generator point, Q = qG.
808    ///
809    /// # Returns
810    ///
811    /// The tweaked key and its parity.
812    fn tap_tweak<C: Verification>(
813        self,
814        secp: &Secp256k1<C>,
815        merkle_root: Option<TapNodeHash>,
816    ) -> TweakedKeypair {
817        let (pubkey, _parity) = XOnlyPublicKey::from_keypair(&self);
818        let tweak = TapTweakHash::from_key_and_tweak(pubkey, merkle_root).to_scalar();
819        let tweaked = self.add_xonly_tweak(secp, &tweak).expect("Tap tweak failed");
820        TweakedKeypair(tweaked)
821    }
822
823    fn dangerous_assume_tweaked(self) -> TweakedKeypair { TweakedKeypair(self) }
824}
825
826impl TweakedPublicKey {
827    /// Returns the [`TweakedPublicKey`] for `keypair`.
828    #[inline]
829    pub fn from_keypair(keypair: TweakedKeypair) -> Self {
830        let (xonly, _parity) = keypair.0.x_only_public_key();
831        TweakedPublicKey(xonly)
832    }
833
834    /// Creates a new [`TweakedPublicKey`] from a [`XOnlyPublicKey`]. No tweak is applied, consider
835    /// calling `tap_tweak` on an [`UntweakedPublicKey`] instead of using this constructor.
836    ///
837    /// This method is dangerous and can lead to loss of funds if used incorrectly.
838    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
839    #[inline]
840    pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> TweakedPublicKey {
841        TweakedPublicKey(key)
842    }
843
844    /// Returns the underlying public key.
845    pub fn to_inner(self) -> XOnlyPublicKey { self.0 }
846
847    /// Serialize the key as a byte-encoded pair of values. In compressed form
848    /// the y-coordinate is represented by only a single bit, as x determines
849    /// it up to one bit.
850    #[inline]
851    pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] { self.0.serialize() }
852}
853
854impl TweakedKeypair {
855    /// Creates a new [`TweakedKeypair`] from a [`Keypair`]. No tweak is applied, consider
856    /// calling `tap_tweak` on an [`UntweakedKeypair`] instead of using this constructor.
857    ///
858    /// This method is dangerous and can lead to loss of funds if used incorrectly.
859    /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
860    #[inline]
861    pub fn dangerous_assume_tweaked(pair: Keypair) -> TweakedKeypair { TweakedKeypair(pair) }
862
863    /// Returns the underlying key pair.
864    #[inline]
865    pub fn to_inner(self) -> Keypair { self.0 }
866
867    /// Returns the [`TweakedPublicKey`] and its [`Parity`] for this [`TweakedKeypair`].
868    #[inline]
869    pub fn public_parts(&self) -> (TweakedPublicKey, Parity) {
870        let (xonly, parity) = self.0.x_only_public_key();
871        (TweakedPublicKey(xonly), parity)
872    }
873}
874
875impl From<TweakedPublicKey> for XOnlyPublicKey {
876    #[inline]
877    fn from(pair: TweakedPublicKey) -> Self { pair.0 }
878}
879
880impl From<TweakedKeypair> for Keypair {
881    #[inline]
882    fn from(pair: TweakedKeypair) -> Self { pair.0 }
883}
884
885impl From<TweakedKeypair> for TweakedPublicKey {
886    #[inline]
887    fn from(pair: TweakedKeypair) -> Self { TweakedPublicKey::from_keypair(pair) }
888}
889
890/// Error returned while generating key from slice.
891#[derive(Debug, Clone, PartialEq, Eq)]
892#[non_exhaustive]
893pub enum FromSliceError {
894    /// Invalid key prefix error.
895    InvalidKeyPrefix(u8),
896    /// A Secp256k1 error.
897    Secp256k1(secp256k1::Error),
898    /// Invalid Length of the slice.
899    InvalidLength(usize),
900}
901
902internals::impl_from_infallible!(FromSliceError);
903
904impl fmt::Display for FromSliceError {
905    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
906        use FromSliceError::*;
907
908        match self {
909            Secp256k1(e) => write_err!(f, "secp256k1"; e),
910            InvalidKeyPrefix(b) => write!(f, "key prefix invalid: {}", b),
911            InvalidLength(got) => write!(f, "slice length should be 33 or 65 bytes, got: {}", got),
912        }
913    }
914}
915
916#[cfg(feature = "std")]
917impl std::error::Error for FromSliceError {
918    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
919        use FromSliceError::*;
920
921        match *self {
922            Secp256k1(ref e) => Some(e),
923            InvalidKeyPrefix(_) | InvalidLength(_) => None,
924        }
925    }
926}
927
928impl From<secp256k1::Error> for FromSliceError {
929    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
930}
931
932/// Error generated from WIF key format.
933#[derive(Debug, Clone, PartialEq, Eq)]
934#[non_exhaustive]
935pub enum FromWifError {
936    /// A base58 decoding error.
937    Base58(base58::Error),
938    /// Base58 decoded data was an invalid length.
939    InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
940    /// Base58 decoded data contained an invalid address version byte.
941    InvalidAddressVersion(InvalidAddressVersionError),
942    /// A secp256k1 error.
943    Secp256k1(secp256k1::Error),
944}
945
946internals::impl_from_infallible!(FromWifError);
947
948impl fmt::Display for FromWifError {
949    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
950        use FromWifError::*;
951
952        match *self {
953            Base58(ref e) => write_err!(f, "invalid base58"; e),
954            InvalidBase58PayloadLength(ref e) =>
955                write_err!(f, "decoded base58 data was an invalid length"; e),
956            InvalidAddressVersion(ref e) =>
957                write_err!(f, "decoded base58 data contained an invalid address version btye"; e),
958            Secp256k1(ref e) => write_err!(f, "private key validation failed"; e),
959        }
960    }
961}
962
963#[cfg(feature = "std")]
964impl std::error::Error for FromWifError {
965    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
966        use FromWifError::*;
967
968        match *self {
969            Base58(ref e) => Some(e),
970            InvalidBase58PayloadLength(ref e) => Some(e),
971            InvalidAddressVersion(ref e) => Some(e),
972            Secp256k1(ref e) => Some(e),
973        }
974    }
975}
976
977impl From<base58::Error> for FromWifError {
978    fn from(e: base58::Error) -> Self { Self::Base58(e) }
979}
980
981impl From<secp256k1::Error> for FromWifError {
982    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
983}
984
985impl From<InvalidBase58PayloadLengthError> for FromWifError {
986    fn from(e: InvalidBase58PayloadLengthError) -> FromWifError {
987        Self::InvalidBase58PayloadLength(e)
988    }
989}
990
991impl From<InvalidAddressVersionError> for FromWifError {
992    fn from(e: InvalidAddressVersionError) -> FromWifError { Self::InvalidAddressVersion(e) }
993}
994
995/// Error returned while constructing public key from string.
996#[derive(Debug, Clone, PartialEq, Eq)]
997pub enum ParsePublicKeyError {
998    /// Error originated while parsing string.
999    Encoding(FromSliceError),
1000    /// Hex decoding error.
1001    InvalidChar(u8),
1002    /// `PublicKey` hex should be 66 or 130 digits long.
1003    InvalidHexLength(usize),
1004}
1005
1006internals::impl_from_infallible!(ParsePublicKeyError);
1007
1008impl fmt::Display for ParsePublicKeyError {
1009    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1010        use ParsePublicKeyError::*;
1011        match self {
1012            Encoding(e) => write_err!(f, "string error"; e),
1013            InvalidChar(char) => write!(f, "hex error {}", char),
1014            InvalidHexLength(got) =>
1015                write!(f, "pubkey string should be 66 or 130 digits long, got: {}", got),
1016        }
1017    }
1018}
1019
1020#[cfg(feature = "std")]
1021impl std::error::Error for ParsePublicKeyError {
1022    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1023        use ParsePublicKeyError::*;
1024
1025        match self {
1026            Encoding(e) => Some(e),
1027            InvalidChar(_) | InvalidHexLength(_) => None,
1028        }
1029    }
1030}
1031
1032impl From<FromSliceError> for ParsePublicKeyError {
1033    fn from(e: FromSliceError) -> Self { Self::Encoding(e) }
1034}
1035
1036/// Error returned when parsing a [`CompressedPublicKey`] from a string.
1037#[derive(Debug, Clone, PartialEq, Eq)]
1038pub enum ParseCompressedPublicKeyError {
1039    /// Secp256k1 Error.
1040    Secp256k1(secp256k1::Error),
1041    /// hex to array conversion error.
1042    Hex(hex::HexToArrayError),
1043}
1044
1045internals::impl_from_infallible!(ParseCompressedPublicKeyError);
1046
1047impl fmt::Display for ParseCompressedPublicKeyError {
1048    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1049        use ParseCompressedPublicKeyError::*;
1050        match self {
1051            Secp256k1(e) => write_err!(f, "secp256k1 error"; e),
1052            Hex(e) => write_err!(f, "invalid hex"; e),
1053        }
1054    }
1055}
1056
1057#[cfg(feature = "std")]
1058impl std::error::Error for ParseCompressedPublicKeyError {
1059    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1060        use ParseCompressedPublicKeyError::*;
1061
1062        match self {
1063            Secp256k1(e) => Some(e),
1064            Hex(e) => Some(e),
1065        }
1066    }
1067}
1068
1069impl From<secp256k1::Error> for ParseCompressedPublicKeyError {
1070    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
1071}
1072
1073impl From<hex::HexToArrayError> for ParseCompressedPublicKeyError {
1074    fn from(e: hex::HexToArrayError) -> Self { Self::Hex(e) }
1075}
1076
1077/// Segwit public keys must always be compressed.
1078#[derive(Debug, Clone, PartialEq, Eq)]
1079#[non_exhaustive]
1080pub struct UncompressedPublicKeyError;
1081
1082impl fmt::Display for UncompressedPublicKeyError {
1083    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1084        f.write_str("segwit public keys must always be compressed")
1085    }
1086}
1087
1088#[cfg(feature = "std")]
1089impl std::error::Error for UncompressedPublicKeyError {
1090    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
1091}
1092
1093/// Decoded base58 data was an invalid length.
1094#[derive(Debug, Clone, PartialEq, Eq)]
1095pub struct InvalidBase58PayloadLengthError {
1096    /// The base58 payload length we got after decoding WIF string.
1097    pub(crate) length: usize,
1098}
1099
1100impl InvalidBase58PayloadLengthError {
1101    /// Returns the invalid payload length.
1102    pub fn invalid_base58_payload_length(&self) -> usize { self.length }
1103}
1104
1105impl fmt::Display for InvalidBase58PayloadLengthError {
1106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1107        write!(f, "decoded base58 data was an invalid length: {} (expected 33 or 34)", self.length)
1108    }
1109}
1110
1111#[cfg(feature = "std")]
1112impl std::error::Error for InvalidBase58PayloadLengthError {}
1113
1114/// Invalid address version in decoded base58 data.
1115#[derive(Debug, Clone, PartialEq, Eq)]
1116pub struct InvalidAddressVersionError {
1117    /// The invalid version.
1118    pub(crate) invalid: u8,
1119}
1120
1121impl InvalidAddressVersionError {
1122    /// Returns the invalid version.
1123    pub fn invalid_address_version(&self) -> u8 { self.invalid }
1124}
1125
1126impl fmt::Display for InvalidAddressVersionError {
1127    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128        write!(f, "invalid address version in decoded base58 data {}", self.invalid)
1129    }
1130}
1131
1132#[cfg(feature = "std")]
1133impl std::error::Error for InvalidAddressVersionError {}
1134
1135#[cfg(test)]
1136mod tests {
1137    use super::*;
1138    use crate::address::Address;
1139
1140    #[test]
1141    fn test_key_derivation() {
1142        // testnet compressed
1143        let sk =
1144            PrivateKey::from_wif("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1145        assert_eq!(sk.network, NetworkKind::Test);
1146        assert!(sk.compressed);
1147        assert_eq!(&sk.to_wif(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1148
1149        let secp = Secp256k1::new();
1150        let pk = Address::p2pkh(sk.public_key(&secp), sk.network);
1151        assert_eq!(&pk.to_string(), "mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx");
1152
1153        // test string conversion
1154        assert_eq!(&sk.to_string(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
1155        let sk_str =
1156            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1157        assert_eq!(&sk.to_wif(), &sk_str.to_wif());
1158
1159        // mainnet uncompressed
1160        let sk =
1161            PrivateKey::from_wif("5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3").unwrap();
1162        assert_eq!(sk.network, NetworkKind::Main);
1163        assert!(!sk.compressed);
1164        assert_eq!(&sk.to_wif(), "5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3");
1165
1166        let secp = Secp256k1::new();
1167        let mut pk = sk.public_key(&secp);
1168        assert!(!pk.compressed);
1169        assert_eq!(&pk.to_string(), "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133");
1170        assert_eq!(pk, PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap());
1171        let addr = Address::p2pkh(pk, sk.network);
1172        assert_eq!(&addr.to_string(), "1GhQvF6dL8xa6wBxLnWmHcQsurx9RxiMc8");
1173        pk.compressed = true;
1174        assert_eq!(
1175            &pk.to_string(),
1176            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1177        );
1178        assert_eq!(
1179            pk,
1180            PublicKey::from_str(
1181                "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"
1182            )
1183            .unwrap()
1184        );
1185    }
1186
1187    #[test]
1188    fn test_pubkey_hash() {
1189        let pk = PublicKey::from_str(
1190            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1191        )
1192        .unwrap();
1193        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1194        assert_eq!(pk.pubkey_hash().to_string(), "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4");
1195        assert_eq!(upk.pubkey_hash().to_string(), "ac2e7daf42d2c97418fd9f78af2de552bb9c6a7a");
1196    }
1197
1198    #[test]
1199    fn test_wpubkey_hash() {
1200        let pk = PublicKey::from_str(
1201            "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
1202        )
1203        .unwrap();
1204        let upk = PublicKey::from_str("042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133").unwrap();
1205        assert_eq!(
1206            pk.wpubkey_hash().unwrap().to_string(),
1207            "9511aa27ef39bbfa4e4f3dd15f4d66ea57f475b4"
1208        );
1209        assert!(upk.wpubkey_hash().is_err());
1210    }
1211
1212    #[cfg(feature = "serde")]
1213    #[test]
1214    fn test_key_serde() {
1215        use serde_test::{assert_tokens, Configure, Token};
1216
1217        static KEY_WIF: &str = "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy";
1218        static PK_STR: &str = "039b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef";
1219        static PK_STR_U: &str = "\
1220            04\
1221            9b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef\
1222            87288ed73ce47fc4f5c79d19ebfa57da7cff3aff6e819e4ee971d86b5e61875d\
1223        ";
1224        #[rustfmt::skip]
1225        static PK_BYTES: [u8; 33] = [
1226            0x03,
1227            0x9b, 0x63, 0x47, 0x39, 0x85, 0x05, 0xf5, 0xec,
1228            0x93, 0x82, 0x6d, 0xc6, 0x1c, 0x19, 0xf4, 0x7c,
1229            0x66, 0xc0, 0x28, 0x3e, 0xe9, 0xbe, 0x98, 0x0e,
1230            0x29, 0xce, 0x32, 0x5a, 0x0f, 0x46, 0x79, 0xef,
1231        ];
1232        #[rustfmt::skip]
1233        static PK_BYTES_U: [u8; 65] = [
1234            0x04,
1235            0x9b, 0x63, 0x47, 0x39, 0x85, 0x05, 0xf5, 0xec,
1236            0x93, 0x82, 0x6d, 0xc6, 0x1c, 0x19, 0xf4, 0x7c,
1237            0x66, 0xc0, 0x28, 0x3e, 0xe9, 0xbe, 0x98, 0x0e,
1238            0x29, 0xce, 0x32, 0x5a, 0x0f, 0x46, 0x79, 0xef,
1239            0x87, 0x28, 0x8e, 0xd7, 0x3c, 0xe4, 0x7f, 0xc4,
1240            0xf5, 0xc7, 0x9d, 0x19, 0xeb, 0xfa, 0x57, 0xda,
1241            0x7c, 0xff, 0x3a, 0xff, 0x6e, 0x81, 0x9e, 0x4e,
1242            0xe9, 0x71, 0xd8, 0x6b, 0x5e, 0x61, 0x87, 0x5d,
1243        ];
1244
1245        let s = Secp256k1::new();
1246        let sk = PrivateKey::from_str(KEY_WIF).unwrap();
1247        let pk = PublicKey::from_private_key(&s, &sk);
1248        let pk_u = PublicKey { inner: pk.inner, compressed: false };
1249
1250        assert_tokens(&sk, &[Token::BorrowedStr(KEY_WIF)]);
1251        assert_tokens(&pk.compact(), &[Token::BorrowedBytes(&PK_BYTES[..])]);
1252        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
1253        assert_tokens(&pk_u.compact(), &[Token::BorrowedBytes(&PK_BYTES_U[..])]);
1254        assert_tokens(&pk_u.readable(), &[Token::BorrowedStr(PK_STR_U)]);
1255    }
1256
1257    fn random_key(mut seed: u8) -> PublicKey {
1258        loop {
1259            let mut data = [0; 65];
1260            for byte in &mut data[..] {
1261                *byte = seed;
1262                // totally a rng
1263                seed = seed.wrapping_mul(41).wrapping_add(43);
1264            }
1265            if data[0] % 2 == 0 {
1266                data[0] = 4;
1267                if let Ok(key) = PublicKey::from_slice(&data[..]) {
1268                    return key;
1269                }
1270            } else {
1271                data[0] = 2 + (data[0] >> 7);
1272                if let Ok(key) = PublicKey::from_slice(&data[..33]) {
1273                    return key;
1274                }
1275            }
1276        }
1277    }
1278
1279    #[test]
1280    fn pubkey_read_write() {
1281        const N_KEYS: usize = 20;
1282        let keys: Vec<_> = (0..N_KEYS).map(|i| random_key(i as u8)).collect();
1283
1284        let mut v = vec![];
1285        for k in &keys {
1286            k.write_into(&mut v).expect("writing into vec");
1287        }
1288
1289        let mut reader = v.as_slice();
1290        let mut dec_keys = vec![];
1291        for _ in 0..N_KEYS {
1292            dec_keys.push(PublicKey::read_from(&mut reader).expect("reading from vec"));
1293        }
1294        assert_eq!(keys, dec_keys);
1295        assert!(PublicKey::read_from(&mut reader).is_err());
1296
1297        // sanity checks
1298        let mut empty: &[u8] = &[];
1299        assert!(PublicKey::read_from(&mut empty).is_err());
1300        assert!(PublicKey::read_from(&mut &[0; 33][..]).is_err());
1301        assert!(PublicKey::read_from(&mut &[2; 32][..]).is_err());
1302        assert!(PublicKey::read_from(&mut &[0; 65][..]).is_err());
1303        assert!(PublicKey::read_from(&mut &[4; 64][..]).is_err());
1304    }
1305
1306    #[test]
1307    fn pubkey_to_sort_key() {
1308        let key1 = PublicKey::from_str(
1309            "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1310        )
1311        .unwrap();
1312        let key2 = PublicKey { inner: key1.inner, compressed: false };
1313        let arrayvec1 = ArrayVec::from_slice(
1314            &<[u8; 33]>::from_hex(
1315                "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1316            )
1317            .unwrap(),
1318        );
1319        let expected1 = SortKey(arrayvec1);
1320        let arrayvec2 = ArrayVec::from_slice(&<[u8; 65]>::from_hex(
1321            "04ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f81794e7f3d5e420641a3bc690067df5541470c966cbca8c694bf39aa16d836918",
1322        ).unwrap());
1323        let expected2 = SortKey(arrayvec2);
1324        assert_eq!(key1.to_sort_key(), expected1);
1325        assert_eq!(key2.to_sort_key(), expected2);
1326    }
1327
1328    #[test]
1329    fn pubkey_sort() {
1330        struct Vector {
1331            input: Vec<PublicKey>,
1332            expect: Vec<PublicKey>,
1333        }
1334        let fmt =
1335            |v: Vec<_>| v.into_iter().map(|s| PublicKey::from_str(s).unwrap()).collect::<Vec<_>>();
1336        let vectors = vec![
1337            // Start BIP67 vectors
1338            // Vector 1
1339            Vector {
1340                input: fmt(vec![
1341                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1342                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1343                ]),
1344                expect: fmt(vec![
1345                    "02fe6f0a5a297eb38c391581c4413e084773ea23954d93f7753db7dc0adc188b2f",
1346                    "02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8",
1347                ]),
1348            },
1349            // Vector 2 (Already sorted, no action required)
1350            Vector {
1351                input: fmt(vec![
1352                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1353                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1354                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1355                ]),
1356                expect: fmt(vec![
1357                    "02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0",
1358                    "027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77",
1359                    "02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404",
1360                ]),
1361            },
1362            // Vector 3
1363            Vector {
1364                input: fmt(vec![
1365                    "030000000000000000000000000000000000004141414141414141414141414141",
1366                    "020000000000000000000000000000000000004141414141414141414141414141",
1367                    "020000000000000000000000000000000000004141414141414141414141414140",
1368                    "030000000000000000000000000000000000004141414141414141414141414140",
1369                ]),
1370                expect: fmt(vec![
1371                    "020000000000000000000000000000000000004141414141414141414141414140",
1372                    "020000000000000000000000000000000000004141414141414141414141414141",
1373                    "030000000000000000000000000000000000004141414141414141414141414140",
1374                    "030000000000000000000000000000000000004141414141414141414141414141",
1375                ]),
1376            },
1377            // Vector 4: (from bitcore)
1378            Vector {
1379                input: fmt(vec![
1380                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1381                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1382                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1383                ]),
1384                expect: fmt(vec![
1385                    "021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18",
1386                    "022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da",
1387                    "03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9",
1388                ]),
1389            },
1390            // Non-BIP67 vectors
1391            Vector {
1392                input: fmt(vec![
1393                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1394                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1395                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1396                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1397                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1398                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1399                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1400                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1401                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1402                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1403                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1404                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1405                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1406                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1407                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1408                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1409                ]),
1410                expect: fmt(vec![
1411                    "0234dd69c56c36a41230d573d68adeae0030c9bc0bf26f24d3e1b64c604d293c68",
1412                    "028bde91b10013e08949a318018fedbd896534a549a278e220169ee2a36517c7aa",
1413                    "028d3a2d9f1b1c5c75845944f93bc183ba23aecde53f1978b8aa1b77661be6114f",
1414                    "028e1c947c8c0b8ed021088b8e981491ac7af2b8fabebea1abdb448424c8ed75b7",
1415                    "02c690d642c1310f3a1ababad94e3930e4023c930ea472e7f37f660fe485263b88",
1416                    "03004a8a3d242d7957c0b60fb7208d386fa6a0193aabd1f3f095ffd0ac097e447b",
1417                    "032b8324c93575034047a52e9bca05a46d8347046b91a032eff07d5de8d3f2730b",
1418                    "038f47dcd43ba6d97fc9ed2e3bba09b175a45fac55f0683e8cf771e8ced4572354",
1419                    "03e1a1cfa9eaff604ae237b7af31ffe4c01be22eb96f3da0e62c5850dd4b4386c1",
1420                    "041a181bd0e79974bd7ca552e09fc42ba9c3d5dbb3753741d6f0ab3015dbfd9a22d6b001a32f5f51ac6f2c0f35e73a6a62f59e848fa854d3d21f3f231594eeaa46",
1421                    "04516cde23e14f2319423b7a4a7ae48b1dadceb5e9c123198d417d10895684c42eb05e210f90ccbc72448803a22312e3f122ff2939956ccef4f7316f836295ddd5",
1422                    "045d753414fa292ea5b8f56e39cfb6a0287b2546231a5cb05c4b14ab4b463d171f5128148985b23eccb1e2905374873b1f09b9487f47afa6b1f2b0083ac8b4f7e8",
1423                    // These two pubkeys are mirrored. This helps verify the sort past the x value.
1424                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc3816753d96001fd7cba3ce5372f5c9a0d63708183033538d07b1e532fc43aaacfa",
1425                    "04c4b0bbb339aa236bff38dbe6a451e111972a7909a126bc424013cba2ec33bc38e98ac269ffe028345c31ac8d0a365f29c8f7e7cfccac72f84e1acd02bc554f35",
1426                    "04c6bec3b07586a4b085a78cbb97e9bab6f1d3c9ebf299b65dec85213c5eacd44487de86017183120bb7ea3b6c6660c5037615fe1add2a73f800cbeeae22c60438",
1427                    "04eb0db2d71ccbb0edd8fb35092cbcae2f7fa1f06d4c170804bf52007924b569a8d2d6f6bc8fd2b3caa3253fa1bb674443743bf7fb9f94f9c0b0831a252894cfa8",
1428                ]),
1429            },
1430        ];
1431        for mut vector in vectors {
1432            vector.input.sort_by_cached_key(|k| PublicKey::to_sort_key(*k));
1433            assert_eq!(vector.input, vector.expect);
1434        }
1435    }
1436
1437    #[test]
1438    #[cfg(feature = "rand-std")]
1439    fn public_key_constructors() {
1440        use secp256k1::rand;
1441
1442        let secp = Secp256k1::new();
1443        let kp = Keypair::new(&secp, &mut rand::thread_rng());
1444
1445        let _ = PublicKey::new(kp);
1446        let _ = PublicKey::new_uncompressed(kp);
1447    }
1448
1449    #[test]
1450    fn public_key_from_str_wrong_length() {
1451        // Sanity checks, we accept string length 130 digits.
1452        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1453        assert_eq!(s.len(), 130);
1454        assert!(PublicKey::from_str(s).is_ok());
1455        // And 66 digits.
1456        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af";
1457        assert_eq!(s.len(), 66);
1458        assert!(PublicKey::from_str(s).is_ok());
1459
1460        let s = "aoeusthb";
1461        assert_eq!(s.len(), 8);
1462        let res = PublicKey::from_str(s);
1463        assert!(res.is_err());
1464        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidHexLength(8));
1465    }
1466
1467    #[test]
1468    fn public_key_from_str_invalid_str() {
1469        // Ensuring test cases fail when PublicKey::from_str is used on invalid keys
1470        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b142";
1471        assert_eq!(s.len(), 130);
1472        let res = PublicKey::from_str(s);
1473        assert!(res.is_err());
1474        assert_eq!(
1475            res.unwrap_err(),
1476            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1477                secp256k1::Error::InvalidPublicKey
1478            ))
1479        );
1480
1481        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd169";
1482        assert_eq!(s.len(), 66);
1483        let res = PublicKey::from_str(s);
1484        assert!(res.is_err());
1485        assert_eq!(
1486            res.unwrap_err(),
1487            ParsePublicKeyError::Encoding(FromSliceError::Secp256k1(
1488                secp256k1::Error::InvalidPublicKey
1489            ))
1490        );
1491
1492        let s = "062e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
1493        assert_eq!(s.len(), 130);
1494        let res = PublicKey::from_str(s);
1495        assert!(res.is_err());
1496        assert_eq!(
1497            res.unwrap_err(),
1498            ParsePublicKeyError::Encoding(FromSliceError::InvalidKeyPrefix(6))
1499        );
1500
1501        let s = "042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b13g";
1502        assert_eq!(s.len(), 130);
1503        let res = PublicKey::from_str(s);
1504        assert!(res.is_err());
1505        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1506
1507        let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1ag";
1508        assert_eq!(s.len(), 66);
1509        let res = PublicKey::from_str(s);
1510        assert!(res.is_err());
1511        assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1512    }
1513
1514    #[test]
1515    #[cfg(feature = "std")]
1516    fn private_key_debug_is_obfuscated() {
1517        let sk =
1518            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1519        let want =
1520            "PrivateKey { compressed: true, network: Test, inner: SecretKey(#32014e414fdce702) }";
1521        let got = format!("{:?}", sk);
1522        assert_eq!(got, want)
1523    }
1524
1525    #[test]
1526    #[cfg(not(feature = "std"))]
1527    fn private_key_debug_is_obfuscated() {
1528        let sk =
1529            PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
1530        // Why is this not shortened? In rust-secp256k1/src/secret it is printed with "#{:016x}"?
1531        let want = "PrivateKey { compressed: true, network: Test, inner: SecretKey(#7217ac58fbad8880a91032107b82cb6c5422544b426c350ee005cf509f3dbf7b) }";
1532        let got = format!("{:?}", sk);
1533        assert_eq!(got, want)
1534    }
1535}