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(
569        script: &Script,
570        params: impl AsRef<Params>,
571    ) -> Result<Address, FromScriptError> {
572        let network = params.as_ref().network;
573        if script.is_p2pkh() {
574            let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long");
575            let hash = PubkeyHash::from_byte_array(bytes);
576            Ok(Address::p2pkh(hash, network))
577        } else if script.is_p2sh() {
578            let bytes = script.as_bytes()[2..22].try_into().expect("statically 20B long");
579            let hash = ScriptHash::from_byte_array(bytes);
580            Ok(Address::p2sh_from_hash(hash, network))
581        } else if script.is_witness_program() {
582            let opcode = script.first_opcode().expect("is_witness_program guarantees len > 4");
583
584            let version = WitnessVersion::try_from(opcode)?;
585            let program = WitnessProgram::new(version, &script.as_bytes()[2..])?;
586            Ok(Address::from_witness_program(program, network))
587        } else {
588            Err(FromScriptError::UnrecognizedScript)
589        }
590    }
591
592    /// Generates a script pubkey spending to this address.
593    pub fn script_pubkey(&self) -> ScriptBuf {
594        use AddressInner::*;
595        match self.0 {
596            P2pkh { ref hash, network: _ } => ScriptBuf::new_p2pkh(hash),
597            P2sh { ref hash, network: _ } => ScriptBuf::new_p2sh(hash),
598            Segwit { ref program, hrp: _ } => {
599                let prog = program.program();
600                let version = program.version();
601                ScriptBuf::new_witness_program_unchecked(version, prog)
602            }
603        }
604    }
605
606    /// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes.
607    ///
608    /// If the address is bech32, the address becomes uppercase.
609    /// If the address is base58, the address is left mixed case.
610    ///
611    /// Quoting BIP 173 "inside QR codes uppercase SHOULD be used, as those permit the use of
612    /// alphanumeric mode, which is 45% more compact than the normal byte mode."
613    ///
614    /// Note however that despite BIP21 explicitly stating that the `bitcoin:` prefix should be
615    /// parsed as case-insensitive many wallets got this wrong and don't parse correctly.
616    /// [See compatibility table.](https://github.com/btcpayserver/btcpayserver/issues/2110)
617    ///
618    /// If you want to avoid allocation you can use alternate display instead:
619    /// ```
620    /// # use core::fmt::Write;
621    /// # const ADDRESS: &str = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4";
622    /// # let address = ADDRESS.parse::<bitcoin::Address<_>>().unwrap().assume_checked();
623    /// # let mut writer = String::new();
624    /// # // magic trick to make error handling look better
625    /// # (|| -> Result<(), core::fmt::Error> {
626    ///
627    /// write!(writer, "{:#}", address)?;
628    ///
629    /// # Ok(())
630    /// # })().unwrap();
631    /// # assert_eq!(writer, ADDRESS);
632    /// ```
633    pub fn to_qr_uri(&self) -> String { format!("bitcoin:{:#}", self) }
634
635    /// Returns true if the given pubkey is directly related to the address payload.
636    ///
637    /// This is determined by directly comparing the address payload with either the
638    /// hash of the given public key or the segwit redeem hash generated from the
639    /// given key. For taproot addresses, the supplied key is assumed to be tweaked
640    pub fn is_related_to_pubkey(&self, pubkey: &PublicKey) -> bool {
641        let pubkey_hash = pubkey.pubkey_hash();
642        let payload = self.payload_as_bytes();
643        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
644
645        (*pubkey_hash.as_byte_array() == *payload)
646            || (xonly_pubkey.serialize() == *payload)
647            || (*segwit_redeem_hash(&pubkey_hash).as_byte_array() == *payload)
648    }
649
650    /// Returns true if the supplied xonly public key can be used to derive the address.
651    ///
652    /// This will only work for Taproot addresses. The Public Key is
653    /// assumed to have already been tweaked.
654    pub fn is_related_to_xonly_pubkey(&self, xonly_pubkey: &XOnlyPublicKey) -> bool {
655        xonly_pubkey.serialize() == *self.payload_as_bytes()
656    }
657
658    /// Returns true if the address creates a particular script
659    /// This function doesn't make any allocations.
660    pub fn matches_script_pubkey(&self, script: &Script) -> bool {
661        use AddressInner::*;
662        match self.0 {
663            P2pkh { ref hash, network: _ } if script.is_p2pkh() =>
664                &script.as_bytes()[3..23] == <PubkeyHash as AsRef<[u8; 20]>>::as_ref(hash),
665            P2sh { ref hash, network: _ } if script.is_p2sh() =>
666                &script.as_bytes()[2..22] == <ScriptHash as AsRef<[u8; 20]>>::as_ref(hash),
667            Segwit { ref program, hrp: _ } if script.is_witness_program() =>
668                &script.as_bytes()[2..] == program.program().as_bytes(),
669            P2pkh { .. } | P2sh { .. } | Segwit { .. } => false,
670        }
671    }
672
673    /// Returns the "payload" for this address.
674    ///
675    /// The "payload" is the useful stuff excluding serialization prefix, the exact payload is
676    /// dependent on the inner address:
677    ///
678    /// - For p2sh, the payload is the script hash.
679    /// - For p2pkh, the payload is the pubkey hash.
680    /// - For segwit addresses, the payload is the witness program.
681    fn payload_as_bytes(&self) -> &[u8] {
682        use AddressInner::*;
683        match self.0 {
684            P2sh { ref hash, network: _ } => hash.as_ref(),
685            P2pkh { ref hash, network: _ } => hash.as_ref(),
686            Segwit { ref program, hrp: _ } => program.program().as_bytes(),
687        }
688    }
689}
690
691/// Methods that can be called only on `Address<NetworkUnchecked>`.
692impl Address<NetworkUnchecked> {
693    /// Returns a reference to the checked address.
694    ///
695    /// This function is dangerous in case the address is not a valid checked address.
696    pub fn assume_checked_ref(&self) -> &Address {
697        unsafe { &*(self as *const Address<NetworkUnchecked> as *const Address) }
698    }
699
700    /// Parsed addresses do not always have *one* network. The problem is that legacy testnet,
701    /// regtest and signet addresse use the same prefix instead of multiple different ones. When
702    /// parsing, such addresses are always assumed to be testnet addresses (the same is true for
703    /// bech32 signet addresses). So if one wants to check if an address belongs to a certain
704    /// network a simple comparison is not enough anymore. Instead this function can be used.
705    ///
706    /// ```rust
707    /// use bitcoin::{Address, Network};
708    /// use bitcoin::address::NetworkUnchecked;
709    ///
710    /// let address: Address<NetworkUnchecked> = "2N83imGV3gPwBzKJQvWJ7cRUY2SpUyU6A5e".parse().unwrap();
711    /// assert!(address.is_valid_for_network(Network::Testnet));
712    /// assert!(address.is_valid_for_network(Network::Regtest));
713    /// assert!(address.is_valid_for_network(Network::Signet));
714    ///
715    /// assert_eq!(address.is_valid_for_network(Network::Bitcoin), false);
716    ///
717    /// let address: Address<NetworkUnchecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
718    /// assert!(address.is_valid_for_network(Network::Bitcoin));
719    /// assert_eq!(address.is_valid_for_network(Network::Testnet4), false);
720    /// ```
721    pub fn is_valid_for_network(&self, n: Network) -> bool {
722        use AddressInner::*;
723        match self.0 {
724            P2pkh { hash: _, ref network } => *network == NetworkKind::from(n),
725            P2sh { hash: _, ref network } => *network == NetworkKind::from(n),
726            Segwit { program: _, ref hrp } => *hrp == KnownHrp::from_network(n),
727        }
728    }
729
730    /// Checks whether network of this address is as required.
731    ///
732    /// For details about this mechanism, see section [*Parsing addresses*](Address#parsing-addresses)
733    /// on [`Address`].
734    ///
735    /// # Errors
736    ///
737    /// This function only ever returns the [`ParseError::NetworkValidation`] variant of
738    /// `ParseError`. This is not how we normally implement errors in this library but
739    /// `require_network` is not a typical function, it is conceptually part of string parsing.
740    ///
741    ///  # Examples
742    ///
743    /// ```
744    /// use bitcoin::address::{NetworkChecked, NetworkUnchecked, ParseError};
745    /// use bitcoin::{Address, Network};
746    ///
747    /// const ADDR: &str = "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs";
748    ///
749    /// fn parse_and_validate_address(network: Network) -> Result<Address, ParseError> {
750    ///     let address = ADDR.parse::<Address<_>>()?
751    ///                       .require_network(network)?;
752    ///     Ok(address)
753    /// }
754    ///
755    /// fn parse_and_validate_address_combinator(network: Network) -> Result<Address, ParseError> {
756    ///     let address = ADDR.parse::<Address<_>>()
757    ///                       .and_then(|a| a.require_network(network))?;
758    ///     Ok(address)
759    /// }
760    ///
761    /// fn parse_and_validate_address_show_types(network: Network) -> Result<Address, ParseError> {
762    ///     let address: Address<NetworkChecked> = ADDR.parse::<Address<NetworkUnchecked>>()?
763    ///                                                .require_network(network)?;
764    ///     Ok(address)
765    /// }
766    ///
767    /// let network = Network::Bitcoin;  // Don't hard code network in applications.
768    /// let _ = parse_and_validate_address(network).unwrap();
769    /// let _ = parse_and_validate_address_combinator(network).unwrap();
770    /// let _ = parse_and_validate_address_show_types(network).unwrap();
771    /// ```
772    #[inline]
773    pub fn require_network(self, required: Network) -> Result<Address, ParseError> {
774        if self.is_valid_for_network(required) {
775            Ok(self.assume_checked())
776        } else {
777            Err(NetworkValidationError { required, address: self }.into())
778        }
779    }
780
781    /// Marks, without any additional checks, network of this address as checked.
782    ///
783    /// Improper use of this method may lead to loss of funds. Reader will most likely prefer
784    /// [`require_network`](Address<NetworkUnchecked>::require_network) as a safe variant.
785    /// For details about this mechanism, see section [*Parsing addresses*](Address#parsing-addresses)
786    /// on [`Address`].
787    #[inline]
788    pub fn assume_checked(self) -> Address { Address(self.0, PhantomData) }
789}
790
791impl From<Address> for script::ScriptBuf {
792    fn from(a: Address) -> Self { a.script_pubkey() }
793}
794
795// Alternate formatting `{:#}` is used to return uppercase version of bech32 addresses which should
796// be used in QR codes, see [`Address::to_qr_uri`].
797impl fmt::Display for Address {
798    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, fmt) }
799}
800
801impl<V: NetworkValidation> fmt::Debug for Address<V> {
802    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
803        if V::IS_CHECKED {
804            fmt::Display::fmt(&self.0, f)
805        } else {
806            write!(f, "Address<NetworkUnchecked>(")?;
807            fmt::Display::fmt(&self.0, f)?;
808            write!(f, ")")
809        }
810    }
811}
812
813/// Address can be parsed only with `NetworkUnchecked`.
814impl FromStr for Address<NetworkUnchecked> {
815    type Err = ParseError;
816
817    fn from_str(s: &str) -> Result<Address<NetworkUnchecked>, ParseError> {
818        if let Ok((hrp, witness_version, data)) = bech32::segwit::decode(s) {
819            let version = WitnessVersion::try_from(witness_version)?;
820            let program = WitnessProgram::new(version, &data)
821                .expect("bech32 guarantees valid program length for witness");
822
823            let hrp = KnownHrp::from_hrp(hrp)?;
824            let inner = AddressInner::Segwit { program, hrp };
825            return Ok(Address(inner, PhantomData));
826        }
827
828        // If segwit decoding fails, assume its a legacy address.
829
830        if s.len() > 50 {
831            return Err(LegacyAddressTooLongError { length: s.len() }.into());
832        }
833        let data = base58::decode_check(s)?;
834        if data.len() != 21 {
835            return Err(InvalidBase58PayloadLengthError { length: s.len() }.into());
836        }
837
838        let (prefix, data) = data.split_first().expect("length checked above");
839        let data: [u8; 20] = data.try_into().expect("length checked above");
840
841        let inner = match *prefix {
842            PUBKEY_ADDRESS_PREFIX_MAIN => {
843                let hash = PubkeyHash::from_byte_array(data);
844                AddressInner::P2pkh { hash, network: NetworkKind::Main }
845            }
846            PUBKEY_ADDRESS_PREFIX_TEST => {
847                let hash = PubkeyHash::from_byte_array(data);
848                AddressInner::P2pkh { hash, network: NetworkKind::Test }
849            }
850            SCRIPT_ADDRESS_PREFIX_MAIN => {
851                let hash = ScriptHash::from_byte_array(data);
852                AddressInner::P2sh { hash, network: NetworkKind::Main }
853            }
854            SCRIPT_ADDRESS_PREFIX_TEST => {
855                let hash = ScriptHash::from_byte_array(data);
856                AddressInner::P2sh { hash, network: NetworkKind::Test }
857            }
858            invalid => return Err(InvalidLegacyPrefixError { invalid }.into()),
859        };
860
861        Ok(Address(inner, PhantomData))
862    }
863}
864
865/// Convert a byte array of a pubkey hash into a segwit redeem hash
866fn segwit_redeem_hash(pubkey_hash: &PubkeyHash) -> crate::hashes::hash160::Hash {
867    let mut sha_engine = sha256::Hash::engine();
868    sha_engine.input(&[0, 20]);
869    sha_engine.input(pubkey_hash.as_ref());
870    crate::hashes::hash160::Hash::from_engine(sha_engine)
871}
872
873#[cfg(test)]
874mod tests {
875    use hex_lit::hex;
876
877    use super::*;
878    use crate::consensus::params;
879    use crate::network::Network::{Bitcoin, Testnet};
880
881    fn roundtrips(addr: &Address, network: Network) {
882        assert_eq!(
883            Address::from_str(&addr.to_string()).unwrap().assume_checked(),
884            *addr,
885            "string round-trip failed for {}",
886            addr,
887        );
888        assert_eq!(
889            Address::from_script(&addr.script_pubkey(), network)
890                .expect("failed to create inner address from script_pubkey"),
891            *addr,
892            "script round-trip failed for {}",
893            addr,
894        );
895
896        #[cfg(feature = "serde")]
897        {
898            let ser = serde_json::to_string(addr).expect("failed to serialize address");
899            let back: Address<NetworkUnchecked> =
900                serde_json::from_str(&ser).expect("failed to deserialize address");
901            assert_eq!(back.assume_checked(), *addr, "serde round-trip failed for {}", addr)
902        }
903    }
904
905    #[test]
906    fn test_p2pkh_address_58() {
907        let hash = "162c5ea71c0b23f5b9022ef047c4a86470a5b070".parse::<PubkeyHash>().unwrap();
908        let addr = Address::p2pkh(hash, NetworkKind::Main);
909
910        assert_eq!(
911            addr.script_pubkey(),
912            ScriptBuf::from_hex("76a914162c5ea71c0b23f5b9022ef047c4a86470a5b07088ac").unwrap()
913        );
914        assert_eq!(&addr.to_string(), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
915        assert_eq!(addr.address_type(), Some(AddressType::P2pkh));
916        roundtrips(&addr, Bitcoin);
917    }
918
919    #[test]
920    fn test_p2pkh_from_key() {
921        let key = "048d5141948c1702e8c95f438815794b87f706a8d4cd2bffad1dc1570971032c9b6042a0431ded2478b5c9cf2d81c124a5e57347a3c63ef0e7716cf54d613ba183".parse::<PublicKey>().unwrap();
922        let addr = Address::p2pkh(key, NetworkKind::Main);
923        assert_eq!(&addr.to_string(), "1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY");
924
925        let key = "03df154ebfcf29d29cc10d5c2565018bce2d9edbab267c31d2caf44a63056cf99f"
926            .parse::<PublicKey>()
927            .unwrap();
928        let addr = Address::p2pkh(key, NetworkKind::Test);
929        assert_eq!(&addr.to_string(), "mqkhEMH6NCeYjFybv7pvFC22MFeaNT9AQC");
930        assert_eq!(addr.address_type(), Some(AddressType::P2pkh));
931        roundtrips(&addr, Testnet);
932    }
933
934    #[test]
935    fn test_p2sh_address_58() {
936        let hash = "162c5ea71c0b23f5b9022ef047c4a86470a5b070".parse::<ScriptHash>().unwrap();
937        let addr = Address::p2sh_from_hash(hash, NetworkKind::Main);
938
939        assert_eq!(
940            addr.script_pubkey(),
941            ScriptBuf::from_hex("a914162c5ea71c0b23f5b9022ef047c4a86470a5b07087").unwrap(),
942        );
943        assert_eq!(&addr.to_string(), "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k");
944        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
945        roundtrips(&addr, Bitcoin);
946    }
947
948    #[test]
949    fn test_p2sh_parse() {
950        let script = ScriptBuf::from_hex("552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae").unwrap();
951        let addr = Address::p2sh(&script, NetworkKind::Test).unwrap();
952        assert_eq!(&addr.to_string(), "2N3zXjbwdTcPsJiy8sUK9FhWJhqQCxA8Jjr");
953        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
954        roundtrips(&addr, Testnet);
955    }
956
957    #[test]
958    fn test_p2sh_parse_for_large_script() {
959        let script = ScriptBuf::from_hex("552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123552103a765fc35b3f210b95223846b36ef62a4e53e34e2925270c2c7906b92c9f718eb2103c327511374246759ec8d0b89fa6c6b23b33e11f92c5bc155409d86de0c79180121038cae7406af1f12f4786d820a1466eec7bc5785a1b5e4a387eca6d797753ef6db2103252bfb9dcaab0cd00353f2ac328954d791270203d66c2be8b430f115f451b8a12103e79412d42372c55dd336f2eb6eb639ef9d74a22041ba79382c74da2338fe58ad21035049459a4ebc00e876a9eef02e72a3e70202d3d1f591fc0dd542f93f642021f82102016f682920d9723c61b27f562eb530c926c00106004798b6471e8c52c60ee02057ae12123122313123123ac1231231231231313123131231231231313212313213123123").unwrap();
960        assert_eq!(Address::p2sh(&script, NetworkKind::Test), Err(P2shError::ExcessiveScriptSize));
961    }
962
963    #[test]
964    fn test_p2wpkh() {
965        // stolen from Bitcoin transaction: b3c8c2b6cfc335abbcb2c7823a8453f55d64b2b5125a9a61e8737230cdb8ce20
966        let key = "033bc8c83c52df5712229a2f72206d90192366c36428cb0c12b6af98324d97bfbc"
967            .parse::<CompressedPublicKey>()
968            .unwrap();
969        let addr = Address::p2wpkh(&key, KnownHrp::Mainnet);
970        assert_eq!(&addr.to_string(), "bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw");
971        assert_eq!(addr.address_type(), Some(AddressType::P2wpkh));
972        roundtrips(&addr, Bitcoin);
973    }
974
975    #[test]
976    fn test_p2wsh() {
977        // stolen from Bitcoin transaction 5df912fda4becb1c29e928bec8d64d93e9ba8efa9b5b405bd683c86fd2c65667
978        let script = ScriptBuf::from_hex("52210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae").unwrap();
979        let addr = Address::p2wsh(&script, KnownHrp::Mainnet);
980        assert_eq!(
981            &addr.to_string(),
982            "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej"
983        );
984        assert_eq!(addr.address_type(), Some(AddressType::P2wsh));
985        roundtrips(&addr, Bitcoin);
986    }
987
988    #[test]
989    fn test_p2shwpkh() {
990        // stolen from Bitcoin transaction: ad3fd9c6b52e752ba21425435ff3dd361d6ac271531fc1d2144843a9f550ad01
991        let key = "026c468be64d22761c30cd2f12cbc7de255d592d7904b1bab07236897cc4c2e766"
992            .parse::<CompressedPublicKey>()
993            .unwrap();
994        let addr = Address::p2shwpkh(&key, NetworkKind::Main);
995        assert_eq!(&addr.to_string(), "3QBRmWNqqBGme9er7fMkGqtZtp4gjMFxhE");
996        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
997        roundtrips(&addr, Bitcoin);
998    }
999
1000    #[test]
1001    fn test_p2shwsh() {
1002        // stolen from Bitcoin transaction f9ee2be4df05041d0e0a35d7caa3157495ca4f93b233234c9967b6901dacf7a9
1003        let script = ScriptBuf::from_hex("522103e5529d8eaa3d559903adb2e881eb06c86ac2574ffa503c45f4e942e2a693b33e2102e5f10fcdcdbab211e0af6a481f5532536ec61a5fdbf7183770cf8680fe729d8152ae").unwrap();
1004        let addr = Address::p2shwsh(&script, NetworkKind::Main);
1005        assert_eq!(&addr.to_string(), "36EqgNnsWW94SreZgBWc1ANC6wpFZwirHr");
1006        assert_eq!(addr.address_type(), Some(AddressType::P2sh));
1007        roundtrips(&addr, Bitcoin);
1008    }
1009
1010    #[test]
1011    fn test_non_existent_segwit_version() {
1012        // 40-byte program
1013        let program = hex!(
1014            "654f6ea368e0acdfd92976b7c2103a1b26313f430654f6ea368e0acdfd92976b7c2103a1b26313f4"
1015        );
1016        let program = WitnessProgram::new(WitnessVersion::V13, &program).expect("valid program");
1017
1018        let addr = Address::from_witness_program(program, KnownHrp::Mainnet);
1019        roundtrips(&addr, Bitcoin);
1020    }
1021
1022    #[test]
1023    fn test_address_debug() {
1024        // This is not really testing output of Debug but the ability and proper functioning
1025        // of Debug derivation on structs generic in NetworkValidation.
1026        #[derive(Debug)]
1027        #[allow(unused)]
1028        struct Test<V: NetworkValidation> {
1029            address: Address<V>,
1030        }
1031
1032        let addr_str = "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k";
1033        let unchecked = Address::from_str(addr_str).unwrap();
1034
1035        assert_eq!(
1036            format!("{:?}", Test { address: unchecked.clone() }),
1037            format!("Test {{ address: Address<NetworkUnchecked>({}) }}", addr_str)
1038        );
1039
1040        assert_eq!(
1041            format!("{:?}", Test { address: unchecked.assume_checked() }),
1042            format!("Test {{ address: {} }}", addr_str)
1043        );
1044    }
1045
1046    #[test]
1047    fn test_address_type() {
1048        let addresses = [
1049            ("1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY", Some(AddressType::P2pkh)),
1050            ("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k", Some(AddressType::P2sh)),
1051            ("bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw", Some(AddressType::P2wpkh)),
1052            (
1053                "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej",
1054                Some(AddressType::P2wsh),
1055            ),
1056            (
1057                "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr",
1058                Some(AddressType::P2tr),
1059            ),
1060            // Related to future extensions, addresses are valid but have no type
1061            // segwit v1 and len != 32
1062            ("bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y", None),
1063            // segwit v2
1064            ("bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs", None),
1065        ];
1066        for (address, expected_type) in &addresses {
1067            let addr = Address::from_str(address)
1068                .unwrap()
1069                .require_network(Network::Bitcoin)
1070                .expect("mainnet");
1071            assert_eq!(&addr.address_type(), expected_type);
1072        }
1073    }
1074
1075    #[test]
1076    #[cfg(feature = "serde")]
1077    fn test_json_serialize() {
1078        use serde_json;
1079
1080        let addr =
1081            Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM").unwrap().assume_checked();
1082        let json = serde_json::to_value(&addr).unwrap();
1083        assert_eq!(
1084            json,
1085            serde_json::Value::String("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM".to_owned())
1086        );
1087        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1088        assert_eq!(addr.to_string(), into.to_string());
1089        assert_eq!(
1090            into.script_pubkey(),
1091            ScriptBuf::from_hex("76a914162c5ea71c0b23f5b9022ef047c4a86470a5b07088ac").unwrap()
1092        );
1093
1094        let addr =
1095            Address::from_str("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k").unwrap().assume_checked();
1096        let json = serde_json::to_value(&addr).unwrap();
1097        assert_eq!(
1098            json,
1099            serde_json::Value::String("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k".to_owned())
1100        );
1101        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1102        assert_eq!(addr.to_string(), into.to_string());
1103        assert_eq!(
1104            into.script_pubkey(),
1105            ScriptBuf::from_hex("a914162c5ea71c0b23f5b9022ef047c4a86470a5b07087").unwrap()
1106        );
1107
1108        let addr: Address<NetworkUnchecked> =
1109            Address::from_str("tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7")
1110                .unwrap();
1111        let json = serde_json::to_value(addr).unwrap();
1112        assert_eq!(
1113            json,
1114            serde_json::Value::String(
1115                "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7".to_owned()
1116            )
1117        );
1118
1119        let addr =
1120            Address::from_str("tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7")
1121                .unwrap()
1122                .assume_checked();
1123        let json = serde_json::to_value(&addr).unwrap();
1124        assert_eq!(
1125            json,
1126            serde_json::Value::String(
1127                "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7".to_owned()
1128            )
1129        );
1130        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1131        assert_eq!(addr.to_string(), into.to_string());
1132        assert_eq!(
1133            into.script_pubkey(),
1134            ScriptBuf::from_hex(
1135                "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"
1136            )
1137            .unwrap()
1138        );
1139
1140        let addr = Address::from_str("bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl")
1141            .unwrap()
1142            .assume_checked();
1143        let json = serde_json::to_value(&addr).unwrap();
1144        assert_eq!(
1145            json,
1146            serde_json::Value::String("bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl".to_owned())
1147        );
1148        let into: Address = serde_json::from_value::<Address<_>>(json).unwrap().assume_checked();
1149        assert_eq!(addr.to_string(), into.to_string());
1150        assert_eq!(
1151            into.script_pubkey(),
1152            ScriptBuf::from_hex("001454d26dddb59c7073c6a197946ea1841951fa7a74").unwrap()
1153        );
1154    }
1155
1156    #[test]
1157    fn test_qr_string() {
1158        for el in
1159            ["132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM", "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k"].iter()
1160        {
1161            let addr =
1162                Address::from_str(el).unwrap().require_network(Network::Bitcoin).expect("mainnet");
1163            assert_eq!(addr.to_qr_uri(), format!("bitcoin:{}", el));
1164        }
1165
1166        for el in [
1167            "bcrt1q2nfxmhd4n3c8834pj72xagvyr9gl57n5r94fsl",
1168            "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej",
1169        ]
1170        .iter()
1171        {
1172            let addr = Address::from_str(el).unwrap().assume_checked();
1173            assert_eq!(addr.to_qr_uri(), format!("bitcoin:{}", el.to_ascii_uppercase()));
1174        }
1175    }
1176
1177    #[test]
1178    fn p2tr_from_untweaked() {
1179        //Test case from BIP-086
1180        let internal_key = XOnlyPublicKey::from_str(
1181            "cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115",
1182        )
1183        .unwrap();
1184        let secp = Secp256k1::verification_only();
1185        let address = Address::p2tr(&secp, internal_key, None, KnownHrp::Mainnet);
1186        assert_eq!(
1187            address.to_string(),
1188            "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr"
1189        );
1190        assert_eq!(address.address_type(), Some(AddressType::P2tr));
1191        roundtrips(&address, Bitcoin);
1192    }
1193
1194    #[test]
1195    fn test_is_related_to_pubkey_p2wpkh() {
1196        let address_string = "bc1qhvd6suvqzjcu9pxjhrwhtrlj85ny3n2mqql5w4";
1197        let address = Address::from_str(address_string)
1198            .expect("address")
1199            .require_network(Network::Bitcoin)
1200            .expect("mainnet");
1201
1202        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1203        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1204
1205        let result = address.is_related_to_pubkey(&pubkey);
1206        assert!(result);
1207
1208        let unused_pubkey = PublicKey::from_str(
1209            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1210        )
1211        .expect("pubkey");
1212        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1213    }
1214
1215    #[test]
1216    fn test_is_related_to_pubkey_p2shwpkh() {
1217        let address_string = "3EZQk4F8GURH5sqVMLTFisD17yNeKa7Dfs";
1218        let address = Address::from_str(address_string)
1219            .expect("address")
1220            .require_network(Network::Bitcoin)
1221            .expect("mainnet");
1222
1223        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1224        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1225
1226        let result = address.is_related_to_pubkey(&pubkey);
1227        assert!(result);
1228
1229        let unused_pubkey = PublicKey::from_str(
1230            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1231        )
1232        .expect("pubkey");
1233        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1234    }
1235
1236    #[test]
1237    fn test_is_related_to_pubkey_p2pkh() {
1238        let address_string = "1J4LVanjHMu3JkXbVrahNuQCTGCRRgfWWx";
1239        let address = Address::from_str(address_string)
1240            .expect("address")
1241            .require_network(Network::Bitcoin)
1242            .expect("mainnet");
1243
1244        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1245        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1246
1247        let result = address.is_related_to_pubkey(&pubkey);
1248        assert!(result);
1249
1250        let unused_pubkey = PublicKey::from_str(
1251            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1252        )
1253        .expect("pubkey");
1254        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1255    }
1256
1257    #[test]
1258    fn test_is_related_to_pubkey_p2pkh_uncompressed_key() {
1259        let address_string = "msvS7KzhReCDpQEJaV2hmGNvuQqVUDuC6p";
1260        let address = Address::from_str(address_string)
1261            .expect("address")
1262            .require_network(Network::Testnet)
1263            .expect("testnet");
1264
1265        let pubkey_string = "04e96e22004e3db93530de27ccddfdf1463975d2138ac018fc3e7ba1a2e5e0aad8e424d0b55e2436eb1d0dcd5cb2b8bcc6d53412c22f358de57803a6a655fbbd04";
1266        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1267
1268        let result = address.is_related_to_pubkey(&pubkey);
1269        assert!(result);
1270
1271        let unused_pubkey = PublicKey::from_str(
1272            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1273        )
1274        .expect("pubkey");
1275        assert!(!address.is_related_to_pubkey(&unused_pubkey))
1276    }
1277
1278    #[test]
1279    fn test_is_related_to_pubkey_p2tr() {
1280        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1281        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1282        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
1283        let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(xonly_pubkey);
1284        let address = Address::p2tr_tweaked(tweaked_pubkey, KnownHrp::Mainnet);
1285
1286        assert_eq!(
1287            address,
1288            Address::from_str("bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e")
1289                .expect("address")
1290                .require_network(Network::Bitcoin)
1291                .expect("mainnet")
1292        );
1293
1294        let result = address.is_related_to_pubkey(&pubkey);
1295        assert!(result);
1296
1297        let unused_pubkey = PublicKey::from_str(
1298            "02ba604e6ad9d3864eda8dc41c62668514ef7d5417d3b6db46e45cc4533bff001c",
1299        )
1300        .expect("pubkey");
1301        assert!(!address.is_related_to_pubkey(&unused_pubkey));
1302    }
1303
1304    #[test]
1305    fn test_is_related_to_xonly_pubkey() {
1306        let pubkey_string = "0347ff3dacd07a1f43805ec6808e801505a6e18245178609972a68afbc2777ff2b";
1307        let pubkey = PublicKey::from_str(pubkey_string).expect("pubkey");
1308        let xonly_pubkey = XOnlyPublicKey::from(pubkey.inner);
1309        let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(xonly_pubkey);
1310        let address = Address::p2tr_tweaked(tweaked_pubkey, KnownHrp::Mainnet);
1311
1312        assert_eq!(
1313            address,
1314            Address::from_str("bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e")
1315                .expect("address")
1316                .require_network(Network::Bitcoin)
1317                .expect("mainnet")
1318        );
1319
1320        let result = address.is_related_to_xonly_pubkey(&xonly_pubkey);
1321        assert!(result);
1322    }
1323
1324    #[test]
1325    fn test_fail_address_from_script() {
1326        use crate::witness_program;
1327
1328        let bad_p2wpkh = ScriptBuf::from_hex("0014dbc5b0a8f9d4353b4b54c3db48846bb15abfec").unwrap();
1329        let bad_p2wsh = ScriptBuf::from_hex(
1330            "00202d4fa2eb233d008cc83206fa2f4f2e60199000f5b857a835e3172323385623",
1331        )
1332        .unwrap();
1333        let invalid_segwitv0_script =
1334            ScriptBuf::from_hex("001161458e330389cd0437ee9fe3641d70cc18").unwrap();
1335        let expected = Err(FromScriptError::UnrecognizedScript);
1336
1337        assert_eq!(Address::from_script(&bad_p2wpkh, Network::Bitcoin), expected);
1338        assert_eq!(Address::from_script(&bad_p2wsh, Network::Bitcoin), expected);
1339        assert_eq!(
1340            Address::from_script(&invalid_segwitv0_script, &params::MAINNET),
1341            Err(FromScriptError::WitnessProgram(witness_program::Error::InvalidSegwitV0Length(17)))
1342        );
1343    }
1344
1345    #[test]
1346    fn valid_address_parses_correctly() {
1347        let addr = AddressType::from_str("p2tr").expect("false negative while parsing address");
1348        assert_eq!(addr, AddressType::P2tr);
1349    }
1350
1351    #[test]
1352    fn invalid_address_parses_error() {
1353        let got = AddressType::from_str("invalid");
1354        let want = Err(UnknownAddressTypeError("invalid".to_string()));
1355        assert_eq!(got, want);
1356    }
1357
1358    #[test]
1359    fn test_matches_script_pubkey() {
1360        let addresses = [
1361            "1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY",
1362            "1J4LVanjHMu3JkXbVrahNuQCTGCRRgfWWx",
1363            "33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k",
1364            "3QBRmWNqqBGme9er7fMkGqtZtp4gjMFxhE",
1365            "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs",
1366            "bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw",
1367            "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr",
1368            "bc1pgllnmtxs0g058qz7c6qgaqq4qknwrqj9z7rqn9e2dzhmcfmhlu4sfadf5e",
1369        ];
1370        for addr in &addresses {
1371            let addr = Address::from_str(addr).unwrap().require_network(Network::Bitcoin).unwrap();
1372            for another in &addresses {
1373                let another =
1374                    Address::from_str(another).unwrap().require_network(Network::Bitcoin).unwrap();
1375                assert_eq!(addr.matches_script_pubkey(&another.script_pubkey()), addr == another);
1376            }
1377        }
1378    }
1379
1380    #[test]
1381    fn pay_to_anchor_address_regtest() {
1382        // Verify that p2a uses the expected address for regtest.
1383        // This test-vector is borrowed from the bitcoin source code.
1384        let address_str = "bcrt1pfeesnyr2tx";
1385
1386        let script = ScriptBuf::new_p2a();
1387        let address_unchecked = address_str.parse().unwrap();
1388        let address = Address::from_script(&script, Network::Regtest).unwrap();
1389        assert_eq!(address.as_unchecked(), &address_unchecked);
1390        assert_eq!(address.to_string(), address_str);
1391
1392        // Verify that the address is considered standard
1393        // and that the output type is P2a
1394        assert!(address.is_spend_standard());
1395        assert_eq!(address.address_type(), Some(AddressType::P2a));
1396    }
1397}