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