bitcoin/address/
mod.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin addresses.
4//!
5//! Support for ordinary base58 Bitcoin addresses and private keys.
6//!
7//! # Example: creating a new address from a randomly-generated key pair
8//!
9//! ```rust
10//! # #[cfg(feature = "rand-std")] {
11//! use bitcoin::{Address, PublicKey, Network};
12//! use bitcoin::secp256k1::{rand, Secp256k1};
13//!
14//! // Generate random key pair.
15//! let s = Secp256k1::new();
16//! let public_key = PublicKey::new(s.generate_keypair(&mut rand::thread_rng()).1);
17//!
18//! // Generate pay-to-pubkey-hash address.
19//! let address = Address::p2pkh(&public_key, Network::Bitcoin);
20//! # }
21//! ```
22//!
23//! # Note: creating a new address requires the rand-std feature flag
24//!
25//! ```toml
26//! bitcoin = { version = "...", features = ["rand-std"] }
27//! ```
28
29pub mod error;
30
31use core::fmt;
32use core::marker::PhantomData;
33use core::str::FromStr;
34
35use bech32::primitives::hrp::Hrp;
36use hashes::{sha256, Hash, HashEngine};
37use secp256k1::{Secp256k1, Verification, XOnlyPublicKey};
38
39use crate::blockdata::constants::{
40    MAX_SCRIPT_ELEMENT_SIZE, PUBKEY_ADDRESS_PREFIX_MAIN, PUBKEY_ADDRESS_PREFIX_TEST,
41    SCRIPT_ADDRESS_PREFIX_MAIN, SCRIPT_ADDRESS_PREFIX_TEST,
42};
43use crate::blockdata::script::witness_program::WitnessProgram;
44use crate::blockdata::script::witness_version::WitnessVersion;
45use crate::blockdata::script::{self, Script, ScriptBuf, ScriptHash};
46use crate::consensus::Params;
47use crate::crypto::key::{
48    CompressedPublicKey, PubkeyHash, PublicKey, TweakedPublicKey, UntweakedPublicKey,
49};
50use crate::network::{Network, NetworkKind};
51use crate::prelude::*;
52use crate::taproot::TapNodeHash;
53
54#[rustfmt::skip]                // Keep public re-exports separate.
55#[doc(inline)]
56pub use self::{
57    error::{
58        FromScriptError, InvalidBase58PayloadLengthError, InvalidLegacyPrefixError, LegacyAddressTooLongError,
59        NetworkValidationError, ParseError, P2shError, UnknownAddressTypeError, UnknownHrpError
60    },
61};
62
63/// The different types of addresses.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
65#[non_exhaustive]
66pub enum AddressType {
67    /// Pay to pubkey hash.
68    P2pkh,
69    /// Pay to script hash.
70    P2sh,
71    /// Pay to witness pubkey hash.
72    P2wpkh,
73    /// Pay to witness script hash.
74    P2wsh,
75    /// Pay to taproot.
76    P2tr,
77}
78
79impl fmt::Display for AddressType {
80    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81        f.write_str(match *self {
82            AddressType::P2pkh => "p2pkh",
83            AddressType::P2sh => "p2sh",
84            AddressType::P2wpkh => "p2wpkh",
85            AddressType::P2wsh => "p2wsh",
86            AddressType::P2tr => "p2tr",
87        })
88    }
89}
90
91impl FromStr for AddressType {
92    type Err = UnknownAddressTypeError;
93    fn from_str(s: &str) -> Result<Self, Self::Err> {
94        match s {
95            "p2pkh" => Ok(AddressType::P2pkh),
96            "p2sh" => Ok(AddressType::P2sh),
97            "p2wpkh" => Ok(AddressType::P2wpkh),
98            "p2wsh" => Ok(AddressType::P2wsh),
99            "p2tr" => Ok(AddressType::P2tr),
100            _ => Err(UnknownAddressTypeError(s.to_owned())),
101        }
102    }
103}
104
105mod sealed {
106    pub trait NetworkValidation {}
107    impl NetworkValidation for super::NetworkChecked {}
108    impl NetworkValidation for super::NetworkUnchecked {}
109}
110
111/// Marker of status of address's network validation. See section [*Parsing addresses*](Address#parsing-addresses)
112/// on [`Address`] for details.
113pub trait NetworkValidation: sealed::NetworkValidation + Sync + Send + Sized + Unpin {
114    /// Indicates whether this `NetworkValidation` is `NetworkChecked` or not.
115    const IS_CHECKED: bool;
116}
117
118/// Marker that address's network has been successfully validated. See section [*Parsing addresses*](Address#parsing-addresses)
119/// on [`Address`] for details.
120#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
121pub enum NetworkChecked {}
122
123/// Marker that address's network has not yet been validated. See section [*Parsing addresses*](Address#parsing-addresses)
124/// on [`Address`] for details.
125#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
126pub enum NetworkUnchecked {}
127
128impl NetworkValidation for NetworkChecked {
129    const IS_CHECKED: bool = true;
130}
131impl NetworkValidation for NetworkUnchecked {
132    const IS_CHECKED: bool = false;
133}
134
135/// The inner representation of an address, without the network validation tag.
136///
137/// This struct represents the inner representation of an address without the network validation
138/// tag, which is used to ensure that addresses are used only on the appropriate network.
139#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
140enum AddressInner {
141    P2pkh { hash: PubkeyHash, network: NetworkKind },
142    P2sh { hash: ScriptHash, network: NetworkKind },
143    Segwit { program: WitnessProgram, hrp: KnownHrp },
144}
145
146/// Formats bech32 as upper case if alternate formatting is chosen (`{:#}`).
147impl fmt::Display for AddressInner {
148    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
149        use AddressInner::*;
150        match self {
151            P2pkh { hash, network } => {
152                let mut prefixed = [0; 21];
153                prefixed[0] = match network {
154                    NetworkKind::Main => PUBKEY_ADDRESS_PREFIX_MAIN,
155                    NetworkKind::Test => PUBKEY_ADDRESS_PREFIX_TEST,
156                };
157                prefixed[1..].copy_from_slice(&hash[..]);
158                base58::encode_check_to_fmt(fmt, &prefixed[..])
159            }
160            P2sh { hash, network } => {
161                let mut prefixed = [0; 21];
162                prefixed[0] = match network {
163                    NetworkKind::Main => SCRIPT_ADDRESS_PREFIX_MAIN,
164                    NetworkKind::Test => SCRIPT_ADDRESS_PREFIX_TEST,
165                };
166                prefixed[1..].copy_from_slice(&hash[..]);
167                base58::encode_check_to_fmt(fmt, &prefixed[..])
168            }
169            Segwit { program, hrp } => {
170                let hrp = hrp.to_hrp();
171                let version = program.version().to_fe();
172                let program = program.program().as_ref();
173
174                if fmt.alternate() {
175                    bech32::segwit::encode_upper_to_fmt_unchecked(fmt, hrp, version, program)
176                } else {
177                    bech32::segwit::encode_lower_to_fmt_unchecked(fmt, hrp, version, program)
178                }
179            }
180        }
181    }
182}
183
184/// Known bech32 human-readable parts.
185///
186/// This is the human-readable part before the separator (`1`) in a bech32 encoded address e.g.,
187/// the "bc" in "bc1p2wsldez5mud2yam29q22wgfh9439spgduvct83k3pm50fcxa5dps59h4z5".
188#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
189#[non_exhaustive]
190pub enum KnownHrp {
191    /// The main Bitcoin network.
192    Mainnet,
193    /// The test networks, testnet (testnet3), testnet4, and signet.
194    Testnets,
195    /// The regtest network.
196    Regtest,
197}
198
199impl KnownHrp {
200    /// Creates a `KnownHrp` from `network`.
201    fn from_network(network: Network) -> Self {
202        use Network::*;
203
204        match network {
205            Bitcoin => Self::Mainnet,
206            Testnet | Testnet4 | Signet => Self::Testnets,
207            Regtest => Self::Regtest,
208        }
209    }
210
211    /// Creates a `KnownHrp` from a [`bech32::Hrp`].
212    fn from_hrp(hrp: Hrp) -> Result<Self, UnknownHrpError> {
213        if hrp == bech32::hrp::BC {
214            Ok(Self::Mainnet)
215        } else if hrp.is_valid_on_testnet() || hrp.is_valid_on_signet() {
216            Ok(Self::Testnets)
217        } else if hrp == bech32::hrp::BCRT {
218            Ok(Self::Regtest)
219        } else {
220            Err(UnknownHrpError(hrp.to_lowercase()))
221        }
222    }
223
224    /// Converts, infallibly a known HRP to a [`bech32::Hrp`].
225    fn to_hrp(self) -> Hrp {
226        match self {
227            Self::Mainnet => bech32::hrp::BC,
228            Self::Testnets => bech32::hrp::TB,
229            Self::Regtest => bech32::hrp::BCRT,
230        }
231    }
232}
233
234impl From<Network> for KnownHrp {
235    fn from(n: Network) -> Self { Self::from_network(n) }
236}
237
238/// The data encoded by an `Address`.
239///
240/// This is the data used to encumber an output that pays to this address i.e., it is the address
241/// excluding the network information.
242#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
243#[non_exhaustive]
244pub enum AddressData {
245    /// Data encoded by a P2PKH address.
246    P2pkh {
247        /// The pubkey hash used to encumber outputs to this address.
248        pubkey_hash: PubkeyHash
249    },
250    /// Data encoded by a P2SH address.
251    P2sh {
252        /// The script hash used to encumber outputs to this address.
253        script_hash: ScriptHash
254    },
255    /// Data encoded by a Segwit address.
256    Segwit {
257        /// The witness program used to encumber outputs to this address.
258        witness_program: WitnessProgram
259    },
260}
261
262/// A Bitcoin address.
263///
264/// ### Parsing addresses
265///
266/// When parsing string as an address, one has to pay attention to the network, on which the parsed
267/// address is supposed to be valid. For the purpose of this validation, `Address` has
268/// [`is_valid_for_network`](Address<NetworkUnchecked>::is_valid_for_network) method. In order to provide more safety,
269/// enforced by compiler, `Address` also contains a special marker type, which indicates whether network of the parsed
270/// address has been checked. This marker type will prevent from calling certain functions unless the network
271/// verification has been successfully completed.
272///
273/// The result of parsing an address is `Address<NetworkUnchecked>` suggesting that network of the parsed address
274/// has not yet been verified. To perform this verification, method [`require_network`](Address<NetworkUnchecked>::require_network)
275/// can be called, providing network on which the address is supposed to be valid. If the verification succeeds,
276/// `Address<NetworkChecked>` is returned.
277///
278/// The types `Address` and `Address<NetworkChecked>` are synonymous, i. e. they can be used interchangeably.
279///
280/// ```rust
281/// use std::str::FromStr;
282/// use bitcoin::{Address, Network};
283/// use bitcoin::address::{NetworkUnchecked, NetworkChecked};
284///
285/// // variant 1
286/// let address: Address<NetworkUnchecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
287/// let address: Address<NetworkChecked> = address.require_network(Network::Bitcoin).unwrap();
288///
289/// // variant 2
290/// let address: Address = Address::from_str("32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf").unwrap()
291///                .require_network(Network::Bitcoin).unwrap();
292///
293/// // variant 3
294/// let address: Address<NetworkChecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse::<Address<_>>()
295///                .unwrap().require_network(Network::Bitcoin).unwrap();
296/// ```
297///
298/// ### Formatting addresses
299///
300/// To format address into its textual representation, both `Debug` (for usage in programmer-facing,
301/// debugging context) and `Display` (for user-facing output) can be used, with the following caveats:
302///
303/// 1. `Display` is implemented only for `Address<NetworkChecked>`:
304///
305/// ```
306/// # use std::str::FromStr;
307/// # use bitcoin::address::{Address, NetworkChecked};
308/// let address: Address<NetworkChecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
309///                .unwrap().assume_checked();
310/// assert_eq!(address.to_string(), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
311/// ```
312///
313/// ```ignore
314/// # use std::str::FromStr;
315/// # use bitcoin::address::{Address, NetworkChecked};
316/// let address: Address<NetworkUnchecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
317///                .unwrap();
318/// let s = address.to_string(); // does not compile
319/// ```
320///
321/// 2. `Debug` on `Address<NetworkUnchecked>` does not produce clean address but address wrapped by
322///    an indicator that its network has not been checked. This is to encourage programmer to properly
323///    check the network and use `Display` in user-facing context.
324///
325/// ```
326/// # use std::str::FromStr;
327/// # use bitcoin::address::{Address, NetworkUnchecked};
328/// let address: Address<NetworkUnchecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
329///                .unwrap();
330/// assert_eq!(format!("{:?}", address), "Address<NetworkUnchecked>(132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM)");
331/// ```
332///
333/// ```
334/// # use std::str::FromStr;
335/// # use bitcoin::address::{Address, NetworkChecked};
336/// let address: Address<NetworkChecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
337///                .unwrap().assume_checked();
338/// assert_eq!(format!("{:?}", address), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
339/// ```
340///
341/// ### Relevant BIPs
342///
343/// * [BIP13 - Address Format for pay-to-script-hash](https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki)
344/// * [BIP16 - Pay to Script Hash](https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki)
345/// * [BIP141 - Segregated Witness (Consensus layer)](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki)
346/// * [BIP142 - Address Format for Segregated Witness](https://github.com/bitcoin/bips/blob/master/bip-0142.mediawiki)
347/// * [BIP341 - Taproot: SegWit version 1 spending rules](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)
348/// * [BIP350 - Bech32m format for v1+ witness addresses](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki)
349#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
350// The `#[repr(transparent)]` attribute is used to guarantee the layout of the `Address` struct. It
351// is an implementation detail and users should not rely on it in their code.
352#[repr(transparent)]
353pub struct Address<V = NetworkChecked>(AddressInner, PhantomData<V>)
354where
355    V: NetworkValidation;
356
357#[cfg(feature = "serde")]
358struct DisplayUnchecked<'a, N: NetworkValidation>(&'a Address<N>);
359
360#[cfg(feature = "serde")]
361impl<N: NetworkValidation> fmt::Display for DisplayUnchecked<'_, N> {
362    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0 .0, fmt) }
363}
364
365#[cfg(feature = "serde")]
366crate::serde_utils::serde_string_deserialize_impl!(Address<NetworkUnchecked>, "a Bitcoin address");
367
368#[cfg(feature = "serde")]
369impl<N: NetworkValidation> serde::Serialize for Address<N> {
370    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
371    where
372        S: serde::Serializer,
373    {
374        serializer.collect_str(&DisplayUnchecked(self))
375    }
376}
377
378/// Methods on [`Address`] that can be called on both `Address<NetworkChecked>` and
379/// `Address<NetworkUnchecked>`.
380impl<V: NetworkValidation> Address<V> {
381    /// Returns a reference to the address as if it was unchecked.
382    pub fn as_unchecked(&self) -> &Address<NetworkUnchecked> {
383        unsafe { &*(self as *const Address<V> as *const Address<NetworkUnchecked>) }
384    }
385
386    /// Marks the network of this address as unchecked.
387    pub fn into_unchecked(self) -> Address<NetworkUnchecked> { Address(self.0, PhantomData) }
388}
389
390/// Methods and functions that can be called only on `Address<NetworkChecked>`.
391impl Address {
392    /// Creates a pay to (compressed) public key hash address from a public key.
393    ///
394    /// This is the preferred non-witness type address.
395    #[inline]
396    pub fn p2pkh(pk: impl Into<PubkeyHash>, network: impl Into<NetworkKind>) -> Address {
397        let hash = pk.into();
398        Self(AddressInner::P2pkh { hash, network: network.into() }, PhantomData)
399    }
400
401    /// Creates a pay to script hash P2SH address from a script.
402    ///
403    /// This address type was introduced with BIP16 and is the popular type to implement multi-sig
404    /// these days.
405    #[inline]
406    pub fn p2sh(script: &Script, network: impl Into<NetworkKind>) -> Result<Address, P2shError> {
407        if script.len() > MAX_SCRIPT_ELEMENT_SIZE {
408            return Err(P2shError::ExcessiveScriptSize);
409        }
410        let hash = script.script_hash();
411        Ok(Address::p2sh_from_hash(hash, network))
412    }
413
414    /// Creates a pay to script hash P2SH address from a script hash.
415    ///
416    /// # Warning
417    ///
418    /// The `hash` pre-image (redeem script) must not exceed 520 bytes in length
419    /// otherwise outputs created from the returned address will be un-spendable.
420    pub fn p2sh_from_hash(hash: ScriptHash, network: impl Into<NetworkKind>) -> Address {
421        Self(AddressInner::P2sh { hash, network: network.into() }, PhantomData)
422    }
423
424    /// Creates a witness pay to public key address from a public key.
425    ///
426    /// This is the native segwit address type for an output redeemable with a single signature.
427    pub fn p2wpkh(pk: &CompressedPublicKey, hrp: impl Into<KnownHrp>) -> Self {
428        let program = WitnessProgram::p2wpkh(pk);
429        Address::from_witness_program(program, hrp)
430    }
431
432    /// Creates a pay to script address that embeds a witness pay to public key.
433    ///
434    /// This is a segwit address type that looks familiar (as p2sh) to legacy clients.
435    pub fn p2shwpkh(pk: &CompressedPublicKey, network: impl Into<NetworkKind>) -> Address {
436        let builder = script::Builder::new().push_int(0).push_slice(pk.wpubkey_hash());
437        let script_hash = builder.as_script().script_hash();
438        Address::p2sh_from_hash(script_hash, network)
439    }
440
441    /// Creates a witness pay to script hash address.
442    pub fn p2wsh(script: &Script, hrp: impl Into<KnownHrp>) -> Address {
443        let program = WitnessProgram::p2wsh(script);
444        Address::from_witness_program(program, hrp)
445    }
446
447    /// Creates a pay to script address that embeds a witness pay to script hash address.
448    ///
449    /// This is a segwit address type that looks familiar (as p2sh) to legacy clients.
450    pub fn p2shwsh(script: &Script, network: impl Into<NetworkKind>) -> Address {
451        let builder = script::Builder::new().push_int(0).push_slice(script.wscript_hash());
452        let script_hash = builder.as_script().script_hash();
453        Address::p2sh_from_hash(script_hash, network)
454    }
455
456    /// Creates a pay to taproot address from an untweaked key.
457    pub fn p2tr<C: Verification>(
458        secp: &Secp256k1<C>,
459        internal_key: UntweakedPublicKey,
460        merkle_root: Option<TapNodeHash>,
461        hrp: impl Into<KnownHrp>,
462    ) -> Address {
463        let program = WitnessProgram::p2tr(secp, internal_key, merkle_root);
464        Address::from_witness_program(program, hrp)
465    }
466
467    /// Creates a pay to taproot address from a pre-tweaked output key.
468    pub fn p2tr_tweaked(output_key: TweakedPublicKey, hrp: impl Into<KnownHrp>) -> Address {
469        let program = WitnessProgram::p2tr_tweaked(output_key);
470        Address::from_witness_program(program, hrp)
471    }
472
473    /// Creates an address from an arbitrary witness program.
474    ///
475    /// This only exists to support future witness versions. If you are doing normal mainnet things
476    /// then you likely do not need this constructor.
477    pub fn from_witness_program(program: WitnessProgram, hrp: impl Into<KnownHrp>) -> Address {
478        let inner = AddressInner::Segwit { program, hrp: hrp.into() };
479        Address(inner, PhantomData)
480    }
481
482    /// Gets the address type of the address.
483    ///
484    /// # Returns
485    ///
486    /// None if unknown, non-standard or related to the future witness version.
487    #[inline]
488    pub fn address_type(&self) -> Option<AddressType> {
489        match self.0 {
490            AddressInner::P2pkh { .. } => Some(AddressType::P2pkh),
491            AddressInner::P2sh { .. } => Some(AddressType::P2sh),
492            AddressInner::Segwit { ref program, hrp: _ } =>
493                if program.is_p2wpkh() {
494                    Some(AddressType::P2wpkh)
495                } else if program.is_p2wsh() {
496                    Some(AddressType::P2wsh)
497                } else if program.is_p2tr() {
498                    Some(AddressType::P2tr)
499                } else {
500                    None
501                },
502        }
503    }
504
505    /// Gets the address data from this address.
506    pub fn to_address_data(&self) -> AddressData {
507        use AddressData::*;
508
509        match self.0 {
510            AddressInner::P2pkh { hash, network: _ } => P2pkh { pubkey_hash: hash },
511            AddressInner::P2sh { hash, network: _ } => P2sh { script_hash: hash },
512            AddressInner::Segwit { program, hrp: _ } => Segwit { witness_program: program },
513        }
514    }
515
516    /// Gets the pubkey hash for this address if this is a P2PKH address.
517    pub fn pubkey_hash(&self) -> Option<PubkeyHash> {
518        use AddressInner::*;
519
520        match self.0 {
521            P2pkh { ref hash, network: _ } => Some(*hash),
522            _ => None,
523        }
524    }
525
526    /// Gets the script hash for this address if this is a P2SH address.
527    pub fn script_hash(&self) -> Option<ScriptHash> {
528        use AddressInner::*;
529
530        match self.0 {
531            P2sh { ref hash, network: _ } => Some(*hash),
532            _ => None,
533        }
534    }
535
536    /// Gets the witness program for this address if this is a segwit address.
537    pub fn witness_program(&self) -> Option<WitnessProgram> {
538        use AddressInner::*;
539
540        match self.0 {
541            Segwit { ref program, hrp: _ } => Some(*program),
542            _ => None,
543        }
544    }
545
546    /// Checks whether or not the address is following Bitcoin standardness rules when
547    /// *spending* from this address. *NOT* to be called by senders.
548    ///
549    /// <details>
550    /// <summary>Spending Standardness</summary>
551    ///
552    /// For forward compatibility, the senders must send to any [`Address`]. Receivers
553    /// can use this method to check whether or not they can spend from this address.
554    ///
555    /// SegWit addresses with unassigned witness versions or non-standard program sizes are
556    /// considered non-standard.
557    /// </details>
558    ///
559    pub fn is_spend_standard(&self) -> bool { self.address_type().is_some() }
560
561    /// Constructs an [`Address`] from an output script (`scriptPubkey`).
562    pub fn from_script(script: &Script, params: impl AsRef<Params>) -> Result<Address, FromScriptError> {
563        let network = params.as_ref().network;
564        if script.is_p2pkh() {
565            let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long");
566            let hash = PubkeyHash::from_byte_array(bytes);
567            Ok(Address::p2pkh(hash, network))
568        } else if script.is_p2sh() {
569            let bytes = script.as_bytes()[2..22].try_into().expect("statically 20B long");
570            let hash = ScriptHash::from_byte_array(bytes);
571            Ok(Address::p2sh_from_hash(hash, network))
572        } else if script.is_witness_program() {
573            let opcode = script.first_opcode().expect("is_witness_program guarantees len > 4");
574
575            let version = WitnessVersion::try_from(opcode)?;
576            let program = WitnessProgram::new(version, &script.as_bytes()[2..])?;
577            Ok(Address::from_witness_program(program, network))
578        } else {
579            Err(FromScriptError::UnrecognizedScript)
580        }
581    }
582
583    /// Generates a script pubkey spending to this address.
584    pub fn script_pubkey(&self) -> ScriptBuf {
585        use AddressInner::*;
586        match self.0 {
587            P2pkh { ref hash, network: _ } => ScriptBuf::new_p2pkh(hash),
588            P2sh { ref hash, network: _ } => ScriptBuf::new_p2sh(hash),
589            Segwit { ref program, hrp: _ } => {
590                let prog = program.program();
591                let version = program.version();
592                ScriptBuf::new_witness_program_unchecked(version, prog)
593            }
594        }
595    }
596
597    /// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes.
598    ///
599    /// If the address is bech32, the address becomes uppercase.
600    /// If the address is base58, the address is left mixed case.
601    ///
602    /// Quoting BIP 173 "inside QR codes uppercase SHOULD be used, as those permit the use of
603    /// alphanumeric mode, which is 45% more compact than the normal byte mode."
604    ///
605    /// Note however that despite BIP21 explicitly stating that the `bitcoin:` prefix should be
606    /// parsed as case-insensitive many wallets got this wrong and don't parse correctly.
607    /// [See compatibility table.](https://github.com/btcpayserver/btcpayserver/issues/2110)
608    ///
609    /// If you want to avoid allocation you can use alternate display instead:
610    /// ```
611    /// # use core::fmt::Write;
612    /// # const ADDRESS: &str = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4";
613    /// # let address = ADDRESS.parse::<bitcoin::Address<_>>().unwrap().assume_checked();
614    /// # let mut writer = String::new();
615    /// # // magic trick to make error handling look better
616    /// # (|| -> Result<(), core::fmt::Error> {
617    ///
618    /// write!(writer, "{:#}", address)?;
619    ///
620    /// # Ok(())
621    /// # })().unwrap();
622    /// # assert_eq!(writer, ADDRESS);
623    /// ```
624    pub fn to_qr_uri(&self) -> String { format!("bitcoin:{:#}", self) }
625
626    /// Returns true if the given pubkey is directly related to the address payload.
627    ///
628    /// This is determined by directly comparing the address payload with either the
629    /// hash of the given public key or the segwit redeem hash generated from the
630    /// given key. For taproot addresses, the supplied key is assumed to be tweaked
631    pub fn is_related_to_pubkey(&self, pubkey: &PublicKey) -> bool {
632        let pubkey_hash = pubkey.pubkey_hash();
633        let payload = self.payload_as_bytes();
634        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
635
636        (*pubkey_hash.as_byte_array() == *payload)
637            || (xonly_pubkey.serialize() == *payload)
638            || (*segwit_redeem_hash(&pubkey_hash).as_byte_array() == *payload)
639    }
640
641    /// Returns true if the supplied xonly public key can be used to derive the address.
642    ///
643    /// This will only work for Taproot addresses. The Public Key is
644    /// assumed to have already been tweaked.
645    pub fn is_related_to_xonly_pubkey(&self, xonly_pubkey: &XOnlyPublicKey) -> bool {
646        xonly_pubkey.serialize() == *self.payload_as_bytes()
647    }
648
649    /// Returns true if the address creates a particular script
650    /// This function doesn't make any allocations.
651    pub fn matches_script_pubkey(&self, script: &Script) -> bool {
652        use AddressInner::*;
653        match self.0 {
654            P2pkh { ref hash, network: _ } if script.is_p2pkh() =>
655                &script.as_bytes()[3..23] == <PubkeyHash as AsRef<[u8; 20]>>::as_ref(hash),
656            P2sh { ref hash, network: _ } if script.is_p2sh() =>
657                &script.as_bytes()[2..22] == <ScriptHash as AsRef<[u8; 20]>>::as_ref(hash),
658            Segwit { ref program, hrp: _ } if script.is_witness_program() =>
659                &script.as_bytes()[2..] == program.program().as_bytes(),
660            P2pkh { .. } | P2sh { .. } | Segwit { .. } => false,
661        }
662    }
663
664    /// Returns the "payload" for this address.
665    ///
666    /// The "payload" is the useful stuff excluding serialization prefix, the exact payload is
667    /// dependent on the inner address:
668    ///
669    /// - For p2sh, the payload is the script hash.
670    /// - For p2pkh, the payload is the pubkey hash.
671    /// - For segwit addresses, the payload is the witness program.
672    fn payload_as_bytes(&self) -> &[u8] {
673        use AddressInner::*;
674        match self.0 {
675            P2sh { ref hash, network: _ } => hash.as_ref(),
676            P2pkh { ref hash, network: _ } => hash.as_ref(),
677            Segwit { ref program, hrp: _ } => program.program().as_bytes(),
678        }
679    }
680}
681
682/// Methods that can be called only on `Address<NetworkUnchecked>`.
683impl Address<NetworkUnchecked> {
684    /// Returns a reference to the checked address.
685    ///
686    /// This function is dangerous in case the address is not a valid checked address.
687    pub fn assume_checked_ref(&self) -> &Address {
688        unsafe { &*(self as *const Address<NetworkUnchecked> as *const Address) }
689    }
690
691    /// Parsed addresses do not always have *one* network. The problem is that legacy testnet,
692    /// regtest and signet addresse use the same prefix instead of multiple different ones. When
693    /// parsing, such addresses are always assumed to be testnet addresses (the same is true for
694    /// bech32 signet addresses). So if one wants to check if an address belongs to a certain
695    /// network a simple comparison is not enough anymore. Instead this function can be used.
696    ///
697    /// ```rust
698    /// use bitcoin::{Address, Network};
699    /// use bitcoin::address::NetworkUnchecked;
700    ///
701    /// let address: Address<NetworkUnchecked> = "2N83imGV3gPwBzKJQvWJ7cRUY2SpUyU6A5e".parse().unwrap();
702    /// assert!(address.is_valid_for_network(Network::Testnet));
703    /// assert!(address.is_valid_for_network(Network::Regtest));
704    /// assert!(address.is_valid_for_network(Network::Signet));
705    ///
706    /// assert_eq!(address.is_valid_for_network(Network::Bitcoin), false);
707    ///
708    /// let address: Address<NetworkUnchecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
709    /// assert!(address.is_valid_for_network(Network::Bitcoin));
710    /// assert_eq!(address.is_valid_for_network(Network::Testnet4), false);
711    /// ```
712    pub fn is_valid_for_network(&self, n: Network) -> bool {
713        use AddressInner::*;
714        match self.0 {
715            P2pkh { hash: _, ref network } => *network == NetworkKind::from(n),
716            P2sh { hash: _, ref network } => *network == NetworkKind::from(n),
717            Segwit { program: _, ref hrp } => *hrp == KnownHrp::from_network(n),
718        }
719    }
720
721    /// Checks whether network of this address is as required.
722    ///
723    /// For details about this mechanism, see section [*Parsing addresses*](Address#parsing-addresses)
724    /// on [`Address`].
725    ///
726    /// # Errors
727    ///
728    /// This function only ever returns the [`ParseError::NetworkValidation`] variant of
729    /// `ParseError`. This is not how we normally implement errors in this library but
730    /// `require_network` is not a typical function, it is conceptually part of string parsing.
731    ///
732    ///  # Examples
733    ///
734    /// ```
735    /// use bitcoin::address::{NetworkChecked, NetworkUnchecked, ParseError};
736    /// use bitcoin::{Address, Network};
737    ///
738    /// const ADDR: &str = "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs";
739    ///
740    /// fn parse_and_validate_address(network: Network) -> Result<Address, ParseError> {
741    ///     let address = ADDR.parse::<Address<_>>()?
742    ///                       .require_network(network)?;
743    ///     Ok(address)
744    /// }
745    ///
746    /// fn parse_and_validate_address_combinator(network: Network) -> Result<Address, ParseError> {
747    ///     let address = ADDR.parse::<Address<_>>()
748    ///                       .and_then(|a| a.require_network(network))?;
749    ///     Ok(address)
750    /// }
751    ///
752    /// fn parse_and_validate_address_show_types(network: Network) -> Result<Address, ParseError> {
753    ///     let address: Address<NetworkChecked> = ADDR.parse::<Address<NetworkUnchecked>>()?
754    ///                                                .require_network(network)?;
755    ///     Ok(address)
756    /// }
757    ///
758    /// let network = Network::Bitcoin;  // Don't hard code network in applications.
759    /// let _ = parse_and_validate_address(network).unwrap();
760    /// let _ = parse_and_validate_address_combinator(network).unwrap();
761    /// let _ = parse_and_validate_address_show_types(network).unwrap();
762    /// ```
763    #[inline]
764    pub fn require_network(self, required: Network) -> Result<Address, ParseError> {
765        if self.is_valid_for_network(required) {
766            Ok(self.assume_checked())
767        } else {
768            Err(NetworkValidationError { required, address: self }.into())
769        }
770    }
771
772    /// Marks, without any additional checks, network of this address as checked.
773    ///
774    /// Improper use of this method may lead to loss of funds. Reader will most likely prefer
775    /// [`require_network`](Address<NetworkUnchecked>::require_network) as a safe variant.
776    /// For details about this mechanism, see section [*Parsing addresses*](Address#parsing-addresses)
777    /// on [`Address`].
778    #[inline]
779    pub fn assume_checked(self) -> Address { Address(self.0, PhantomData) }
780}
781
782impl From<Address> for script::ScriptBuf {
783    fn from(a: Address) -> Self { a.script_pubkey() }
784}
785
786// Alternate formatting `{:#}` is used to return uppercase version of bech32 addresses which should
787// be used in QR codes, see [`Address::to_qr_uri`].
788impl fmt::Display for Address {
789    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, fmt) }
790}
791
792impl<V: NetworkValidation> fmt::Debug for Address<V> {
793    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
794        if V::IS_CHECKED {
795            fmt::Display::fmt(&self.0, f)
796        } else {
797            write!(f, "Address<NetworkUnchecked>(")?;
798            fmt::Display::fmt(&self.0, f)?;
799            write!(f, ")")
800        }
801    }
802}
803
804/// Address can be parsed only with `NetworkUnchecked`.
805impl FromStr for Address<NetworkUnchecked> {
806    type Err = ParseError;
807
808    fn from_str(s: &str) -> Result<Address<NetworkUnchecked>, ParseError> {
809        if let Ok((hrp, witness_version, data)) = bech32::segwit::decode(s) {
810            let version = WitnessVersion::try_from(witness_version)?;
811            let program = WitnessProgram::new(version, &data)
812                .expect("bech32 guarantees valid program length for witness");
813
814            let hrp = KnownHrp::from_hrp(hrp)?;
815            let inner = AddressInner::Segwit { program, hrp };
816            return Ok(Address(inner, PhantomData));
817        }
818
819        // If segwit decoding fails, assume its a legacy address.
820
821        if s.len() > 50 {
822            return Err(LegacyAddressTooLongError { length: s.len() }.into());
823        }
824        let data = base58::decode_check(s)?;
825        if data.len() != 21 {
826            return Err(InvalidBase58PayloadLengthError { length: s.len() }.into());
827        }
828
829        let (prefix, data) = data.split_first().expect("length checked above");
830        let data: [u8; 20] = data.try_into().expect("length checked above");
831
832        let inner = match *prefix {
833            PUBKEY_ADDRESS_PREFIX_MAIN => {
834                let hash = PubkeyHash::from_byte_array(data);
835                AddressInner::P2pkh { hash, network: NetworkKind::Main }
836            }
837            PUBKEY_ADDRESS_PREFIX_TEST => {
838                let hash = PubkeyHash::from_byte_array(data);
839                AddressInner::P2pkh { hash, network: NetworkKind::Test }
840            }
841            SCRIPT_ADDRESS_PREFIX_MAIN => {
842                let hash = ScriptHash::from_byte_array(data);
843                AddressInner::P2sh { hash, network: NetworkKind::Main }
844            }
845            SCRIPT_ADDRESS_PREFIX_TEST => {
846                let hash = ScriptHash::from_byte_array(data);
847                AddressInner::P2sh { hash, network: NetworkKind::Test }
848            }
849            invalid => return Err(InvalidLegacyPrefixError { invalid }.into()),
850        };
851
852        Ok(Address(inner, PhantomData))
853    }
854}
855
856/// Convert a byte array of a pubkey hash into a segwit redeem hash
857fn segwit_redeem_hash(pubkey_hash: &PubkeyHash) -> crate::hashes::hash160::Hash {
858    let mut sha_engine = sha256::Hash::engine();
859    sha_engine.input(&[0, 20]);
860    sha_engine.input(pubkey_hash.as_ref());
861    crate::hashes::hash160::Hash::from_engine(sha_engine)
862}
863
864#[cfg(test)]
865mod tests {
866    use hex_lit::hex;
867
868    use super::*;
869    use crate::consensus::params;
870    use crate::network::Network::{Bitcoin, Testnet};
871
872    fn roundtrips(addr: &Address, network: Network) {
873        assert_eq!(
874            Address::from_str(&addr.to_string()).unwrap().assume_checked(),
875            *addr,
876            "string round-trip failed for {}",
877            addr,
878        );
879        assert_eq!(
880            Address::from_script(&addr.script_pubkey(), network)
881                .expect("failed to create inner address from script_pubkey"),
882            *addr,
883            "script round-trip failed for {}",
884            addr,
885        );
886
887        #[cfg(feature = "serde")]
888        {
889            let ser = serde_json::to_string(addr).expect("failed to serialize address");
890            let back: Address<NetworkUnchecked> =
891                serde_json::from_str(&ser).expect("failed to deserialize address");
892            assert_eq!(back.assume_checked(), *addr, "serde round-trip failed for {}", addr)
893        }
894    }
895
896    #[test]
897    fn test_p2pkh_address_58() {
898        let hash = "162c5ea71c0b23f5b9022ef047c4a86470a5b070".parse::<PubkeyHash>().unwrap();
899        let addr = Address::p2pkh(hash, NetworkKind::Main);
900
901        assert_eq!(
902            addr.script_pubkey(),
903            ScriptBuf::from_hex("76a914162c5ea71c0b23f5b9022ef047c4a86470a5b07088ac").unwrap()
904        );
905        assert_eq!(&addr.to_string(), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
906        assert_eq!(addr.address_type(), Some(AddressType::P2pkh));
907        roundtrips(&addr, Bitcoin);
908    }
909
910    #[test]
911    fn test_p2pkh_from_key() {
912        let key = "048d5141948c1702e8c95f438815794b87f706a8d4cd2bffad1dc1570971032c9b6042a0431ded2478b5c9cf2d81c124a5e57347a3c63ef0e7716cf54d613ba183".parse::<PublicKey>().unwrap();
913        let addr = Address::p2pkh(key, NetworkKind::Main);
914        assert_eq!(&addr.to_string(), "1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY");
915
916        let key = "03df154ebfcf29d29cc10d5c2565018bce2d9edbab267c31d2caf44a63056cf99f"
917            .parse::<PublicKey>()
918            .unwrap();
919        let addr = Address::p2pkh(key, NetworkKind::Test);
920        assert_eq!(&addr.to_string(), "mqkhEMH6NCeYjFybv7pvFC22MFeaNT9AQC");
921        assert_eq!(addr.address_type(), Some(AddressType::P2pkh));
922        roundtrips(&addr, Testnet);
923    }
924
925    #[test]
926    fn test_p2sh_address_58() {
927        let hash = "162c5ea71c0b23f5b9022ef047c4a86470a5b070".parse::<ScriptHash>().unwrap();
928        let addr = Address::p2sh_from_hash(hash, NetworkKind::Main);
929
930        assert_eq!(
931            addr.script_pubkey(),
932            ScriptBuf::from_hex("a914162c5ea71c0b23f5b9022ef047c4a86470a5b07087").unwrap(),
933        );
934        assert_eq!(&addr.to_string(), "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k");
935        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
936        roundtrips(&addr, Bitcoin);
937    }
938
939    #[test]
940    fn test_p2sh_parse() {
941        let script = ScriptBuf::from_hex("552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae").unwrap();
942        let addr = Address::p2sh(&script, NetworkKind::Test).unwrap();
943        assert_eq!(&addr.to_string(), "2N3zXjbwdTcPsJiy8sUK9FhWJhqQCxA8Jjr");
944        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
945        roundtrips(&addr, Testnet);
946    }
947
948    #[test]
949    fn test_p2sh_parse_for_large_script() {
950        let script = ScriptBuf::from_hex("552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123").unwrap();
951        assert_eq!(Address::p2sh(&script, NetworkKind::Test), Err(P2shError::ExcessiveScriptSize));
952    }
953
954    #[test]
955    fn test_p2wpkh() {
956        // stolen from Bitcoin transaction: b3c8c2b6cfc335abbcb2c7823a8453f55d64b2b5125a9a61e8737230cdb8ce20
957        let key = "033bc8c83c52df5712229a2f72206d90192366c36428cb0c12b6af98324d97bfbc"
958            .parse::<CompressedPublicKey>()
959            .unwrap();
960        let addr = Address::p2wpkh(&key, KnownHrp::Mainnet);
961        assert_eq!(&addr.to_string(), "bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw");
962        assert_eq!(addr.address_type(), Some(AddressType::P2wpkh));
963        roundtrips(&addr, Bitcoin);
964    }
965
966    #[test]
967    fn test_p2wsh() {
968        // stolen from Bitcoin transaction 5df912fda4becb1c29e928bec8d64d93e9ba8efa9b5b405bd683c86fd2c65667
969        let script = ScriptBuf::from_hex("52210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae").unwrap();
970        let addr = Address::p2wsh(&script, KnownHrp::Mainnet);
971        assert_eq!(
972            &addr.to_string(),
973            "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej"
974        );
975        assert_eq!(addr.address_type(), Some(AddressType::P2wsh));
976        roundtrips(&addr, Bitcoin);
977    }
978
979    #[test]
980    fn test_p2shwpkh() {
981        // stolen from Bitcoin transaction: ad3fd9c6b52e752ba21425435ff3dd361d6ac271531fc1d2144843a9f550ad01
982        let key = "026c468be64d22761c30cd2f12cbc7de255d592d7904b1bab07236897cc4c2e766"
983            .parse::<CompressedPublicKey>()
984            .unwrap();
985        let addr = Address::p2shwpkh(&key, NetworkKind::Main);
986        assert_eq!(&addr.to_string(), "3QBRmWNqqBGme9er7fMkGqtZtp4gjMFxhE");
987        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
988        roundtrips(&addr, Bitcoin);
989    }
990
991    #[test]
992    fn test_p2shwsh() {
993        // stolen from Bitcoin transaction f9ee2be4df05041d0e0a35d7caa3157495ca4f93b233234c9967b6901dacf7a9
994        let script = ScriptBuf::from_hex("522103e5529d8eaa3d559903adb2e881eb06c86ac2574ffa503c45f4e942e2a693b33e2102e5f10fcdcdbab211e0af6a481f5532536ec61a5fdbf7183770cf8680fe729d8152ae").unwrap();
995        let addr = Address::p2shwsh(&script, NetworkKind::Main);
996        assert_eq!(&addr.to_string(), "36EqgNnsWW94SreZgBWc1ANC6wpFZwirHr");
997        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
998        roundtrips(&addr, Bitcoin);
999    }
1000
1001    #[test]
1002    fn test_non_existent_segwit_version() {
1003        // 40-byte program
1004        let program = hex!(
1005            "654f6ea368e0acdfd92976b7c2103a1b26313f430654f6ea368e0acdfd92976b7c2103a1b26313f4"
1006        );
1007        let program = WitnessProgram::new(WitnessVersion::V13, &program).expect("valid program");
1008
1009        let addr = Address::from_witness_program(program, KnownHrp::Mainnet);
1010        roundtrips(&addr, Bitcoin);
1011    }
1012
1013    #[test]
1014    fn test_address_debug() {
1015        // This is not really testing output of Debug but the ability and proper functioning
1016        // of Debug derivation on structs generic in NetworkValidation.
1017        #[derive(Debug)]
1018        #[allow(unused)]
1019        struct Test<V: NetworkValidation> {
1020            address: Address<V>,
1021        }
1022
1023        let addr_str = "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k";
1024        let unchecked = Address::from_str(addr_str).unwrap();
1025
1026        assert_eq!(
1027            format!("{:?}", Test { address: unchecked.clone() }),
1028            format!("Test {{ address: Address<NetworkUnchecked>({}) }}", addr_str)
1029        );
1030
1031        assert_eq!(
1032            format!("{:?}", Test { address: unchecked.assume_checked() }),
1033            format!("Test {{ address: {} }}", addr_str)
1034        );
1035    }
1036
1037    #[test]
1038    fn test_address_type() {
1039        let addresses = [
1040            ("1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY", Some(AddressType::P2pkh)),
1041            ("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k", Some(AddressType::P2sh)),
1042            ("bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw", Some(AddressType::P2wpkh)),
1043            (
1044                "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej",
1045                Some(AddressType::P2wsh),
1046            ),
1047            (
1048                "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr",
1049                Some(AddressType::P2tr),
1050            ),
1051            // Related to future extensions, addresses are valid but have no type
1052            // segwit v1 and len != 32
1053            ("bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y", None),
1054            // segwit v2
1055            ("bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs", None),
1056        ];
1057        for (address, expected_type) in &addresses {
1058            let addr = Address::from_str(address)
1059                .unwrap()
1060                .require_network(Network::Bitcoin)
1061                .expect("mainnet");
1062            assert_eq!(&addr.address_type(), expected_type);
1063        }
1064    }
1065
1066    #[test]
1067    #[cfg(feature = "serde")]
1068    fn test_json_serialize() {
1069        use serde_json;
1070
1071        let addr =
1072            Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM").unwrap().assume_checked();
1073        let json = serde_json::to_value(&addr).unwrap();
1074        assert_eq!(
1075            json,
1076            serde_json::Value::String("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM".to_owned())
1077        );
1078        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1079        assert_eq!(addr.to_string(), into.to_string());
1080        assert_eq!(
1081            into.script_pubkey(),
1082            ScriptBuf::from_hex("76a914162c5ea71c0b23f5b9022ef047c4a86470a5b07088ac").unwrap()
1083        );
1084
1085        let addr =
1086            Address::from_str("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k").unwrap().assume_checked();
1087        let json = serde_json::to_value(&addr).unwrap();
1088        assert_eq!(
1089            json,
1090            serde_json::Value::String("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k".to_owned())
1091        );
1092        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1093        assert_eq!(addr.to_string(), into.to_string());
1094        assert_eq!(
1095            into.script_pubkey(),
1096            ScriptBuf::from_hex("a914162c5ea71c0b23f5b9022ef047c4a86470a5b07087").unwrap()
1097        );
1098
1099        let addr: Address<NetworkUnchecked> =
1100            Address::from_str("tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7")
1101                .unwrap();
1102        let json = serde_json::to_value(addr).unwrap();
1103        assert_eq!(
1104            json,
1105            serde_json::Value::String(
1106                "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7".to_owned()
1107            )
1108        );
1109
1110        let addr =
1111            Address::from_str("tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7")
1112                .unwrap()
1113                .assume_checked();
1114        let json = serde_json::to_value(&addr).unwrap();
1115        assert_eq!(
1116            json,
1117            serde_json::Value::String(
1118                "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7".to_owned()
1119            )
1120        );
1121        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1122        assert_eq!(addr.to_string(), into.to_string());
1123        assert_eq!(
1124            into.script_pubkey(),
1125            ScriptBuf::from_hex(
1126                "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"
1127            )
1128            .unwrap()
1129        );
1130
1131        let addr = Address::from_str("bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl")
1132            .unwrap()
1133            .assume_checked();
1134        let json = serde_json::to_value(&addr).unwrap();
1135        assert_eq!(
1136            json,
1137            serde_json::Value::String("bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl".to_owned())
1138        );
1139        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1140        assert_eq!(addr.to_string(), into.to_string());
1141        assert_eq!(
1142            into.script_pubkey(),
1143            ScriptBuf::from_hex("001454d26dddb59c7073c6a197946ea1841951fa7a74").unwrap()
1144        );
1145    }
1146
1147    #[test]
1148    fn test_qr_string() {
1149        for el in
1150            ["132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM", "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k"].iter()
1151        {
1152            let addr =
1153                Address::from_str(el).unwrap().require_network(Network::Bitcoin).expect("mainnet");
1154            assert_eq!(addr.to_qr_uri(), format!("bitcoin:{}", el));
1155        }
1156
1157        for el in [
1158            "bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl",
1159            "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej",
1160        ]
1161        .iter()
1162        {
1163            let addr = Address::from_str(el).unwrap().assume_checked();
1164            assert_eq!(addr.to_qr_uri(), format!("bitcoin:{}", el.to_ascii_uppercase()));
1165        }
1166    }
1167
1168    #[test]
1169    fn p2tr_from_untweaked() {
1170        //Test case from BIP-086
1171        let internal_key = XOnlyPublicKey::from_str(
1172            "cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115",
1173        )
1174        .unwrap();
1175        let secp = Secp256k1::verification_only();
1176        let address = Address::p2tr(&secp, internal_key, None, KnownHrp::Mainnet);
1177        assert_eq!(
1178            address.to_string(),
1179            "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr"
1180        );
1181        assert_eq!(address.address_type(), Some(AddressType::P2tr));
1182        roundtrips(&address, Bitcoin);
1183    }
1184
1185    #[test]
1186    fn test_is_related_to_pubkey_p2wpkh() {
1187        let address_string = "bc1qhvd6suvqzjcu9pxjhrwhtrlj85ny3n2mqql5w4";
1188        let address = Address::from_str(address_string)
1189            .expect("address")
1190            .require_network(Network::Bitcoin)
1191            .expect("mainnet");
1192
1193        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1194        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1195
1196        let result = address.is_related_to_pubkey(&pubkey);
1197        assert!(result);
1198
1199        let unused_pubkey = PublicKey::from_str(
1200            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1201        )
1202        .expect("pubkey");
1203        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1204    }
1205
1206    #[test]
1207    fn test_is_related_to_pubkey_p2shwpkh() {
1208        let address_string = "3EZQk4F8GURH5sqVMLTFisD17yNeKa7Dfs";
1209        let address = Address::from_str(address_string)
1210            .expect("address")
1211            .require_network(Network::Bitcoin)
1212            .expect("mainnet");
1213
1214        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1215        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1216
1217        let result = address.is_related_to_pubkey(&pubkey);
1218        assert!(result);
1219
1220        let unused_pubkey = PublicKey::from_str(
1221            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1222        )
1223        .expect("pubkey");
1224        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1225    }
1226
1227    #[test]
1228    fn test_is_related_to_pubkey_p2pkh() {
1229        let address_string = "1J4LVanjHMu3JkXbVrahNuQCTGCRRgfWWx";
1230        let address = Address::from_str(address_string)
1231            .expect("address")
1232            .require_network(Network::Bitcoin)
1233            .expect("mainnet");
1234
1235        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1236        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1237
1238        let result = address.is_related_to_pubkey(&pubkey);
1239        assert!(result);
1240
1241        let unused_pubkey = PublicKey::from_str(
1242            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1243        )
1244        .expect("pubkey");
1245        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1246    }
1247
1248    #[test]
1249    fn test_is_related_to_pubkey_p2pkh_uncompressed_key() {
1250        let address_string = "msvS7KzhReCDpQEJaV2hmGNvuQqVUDuC6p";
1251        let address = Address::from_str(address_string)
1252            .expect("address")
1253            .require_network(Network::Testnet)
1254            .expect("testnet");
1255
1256        let pubkey_string = "04e96e22004e3db93530de27ccddfdf1463975d2138ac018fc3e7ba1a2e5e0aad8e424d0b55e2436eb1d0dcd5cb2b8bcc6d53412c22f358de57803a6a655fbbd04";
1257        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1258
1259        let result = address.is_related_to_pubkey(&pubkey);
1260        assert!(result);
1261
1262        let unused_pubkey = PublicKey::from_str(
1263            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1264        )
1265        .expect("pubkey");
1266        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1267    }
1268
1269    #[test]
1270    fn test_is_related_to_pubkey_p2tr() {
1271        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1272        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1273        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
1274        let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(xonly_pubkey);
1275        let address = Address::p2tr_tweaked(tweaked_pubkey, KnownHrp::Mainnet);
1276
1277        assert_eq!(
1278            address,
1279            Address::from_str("bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e")
1280                .expect("address")
1281                .require_network(Network::Bitcoin)
1282                .expect("mainnet")
1283        );
1284
1285        let result = address.is_related_to_pubkey(&pubkey);
1286        assert!(result);
1287
1288        let unused_pubkey = PublicKey::from_str(
1289            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1290        )
1291        .expect("pubkey");
1292        assert!(!address.is_related_to_pubkey(&unused_pubkey));
1293    }
1294
1295    #[test]
1296    fn test_is_related_to_xonly_pubkey() {
1297        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1298        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1299        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
1300        let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(xonly_pubkey);
1301        let address = Address::p2tr_tweaked(tweaked_pubkey, KnownHrp::Mainnet);
1302
1303        assert_eq!(
1304            address,
1305            Address::from_str("bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e")
1306                .expect("address")
1307                .require_network(Network::Bitcoin)
1308                .expect("mainnet")
1309        );
1310
1311        let result = address.is_related_to_xonly_pubkey(&xonly_pubkey);
1312        assert!(result);
1313    }
1314
1315    #[test]
1316    fn test_fail_address_from_script() {
1317        use crate::witness_program;
1318
1319        let bad_p2wpkh = ScriptBuf::from_hex("0014dbc5b0a8f9d4353b4b54c3db48846bb15abfec").unwrap();
1320        let bad_p2wsh = ScriptBuf::from_hex(
1321            "00202d4fa2eb233d008cc83206fa2f4f2e60199000f5b857a835e3172323385623",
1322        )
1323        .unwrap();
1324        let invalid_segwitv0_script =
1325            ScriptBuf::from_hex("001161458e330389cd0437ee9fe3641d70cc18").unwrap();
1326        let expected = Err(FromScriptError::UnrecognizedScript);
1327
1328        assert_eq!(Address::from_script(&bad_p2wpkh, Network::Bitcoin), expected);
1329        assert_eq!(Address::from_script(&bad_p2wsh, Network::Bitcoin), expected);
1330        assert_eq!(
1331            Address::from_script(&invalid_segwitv0_script, &params::MAINNET),
1332            Err(FromScriptError::WitnessProgram(witness_program::Error::InvalidSegwitV0Length(17)))
1333        );
1334    }
1335
1336    #[test]
1337    fn valid_address_parses_correctly() {
1338        let addr = AddressType::from_str("p2tr").expect("false negative while parsing address");
1339        assert_eq!(addr, AddressType::P2tr);
1340    }
1341
1342    #[test]
1343    fn invalid_address_parses_error() {
1344        let got = AddressType::from_str("invalid");
1345        let want = Err(UnknownAddressTypeError("invalid".to_string()));
1346        assert_eq!(got, want);
1347    }
1348
1349    #[test]
1350    fn test_matches_script_pubkey() {
1351        let addresses = [
1352            "1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY",
1353            "1J4LVanjHMu3JkXbVrahNuQCTGCRRgfWWx",
1354            "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k",
1355            "3QBRmWNqqBGme9er7fMkGqtZtp4gjMFxhE",
1356            "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs",
1357            "bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw",
1358            "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr",
1359            "bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e",
1360        ];
1361        for addr in &addresses {
1362            let addr = Address::from_str(addr).unwrap().require_network(Network::Bitcoin).unwrap();
1363            for another in &addresses {
1364                let another =
1365                    Address::from_str(another).unwrap().require_network(Network::Bitcoin).unwrap();
1366                assert_eq!(addr.matches_script_pubkey(&another.script_pubkey()), addr == another);
1367            }
1368        }
1369    }
1370}