From f4f79f88eb2c6c80c46c95c69fcc43b17d306be2 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 17 Mar 2025 11:40:02 +1100 Subject: [PATCH] Enable getting the network kind from an address Users may wish to ask of an address 'what kind of address is this?' We have the `NetworkKind` struct that abstracts over the answer but currently no API to ask the question. The address may have been parsed or constructed and weather the network has been checked already is immaterial. Hence we add the function for both `NetworkChecked` and `NetworkUnchecked` addresses. Fix: #4247 --- bitcoin/src/address/mod.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/bitcoin/src/address/mod.rs b/bitcoin/src/address/mod.rs index a4588617a..36b6a553c 100644 --- a/bitcoin/src/address/mod.rs +++ b/bitcoin/src/address/mod.rs @@ -273,6 +273,16 @@ impl From for KnownHrp { fn from(n: Network) -> Self { Self::from_network(n) } } +impl From for NetworkKind { + fn from(hrp: KnownHrp) -> Self { + match hrp { + KnownHrp::Mainnet => NetworkKind::Main, + KnownHrp::Testnets => NetworkKind::Test, + KnownHrp::Regtest => NetworkKind::Test, + } + } +} + /// The data encoded by an `Address`. /// /// This is the data used to encumber an output that pays to this address i.e., it is the address @@ -450,6 +460,16 @@ impl Address { /// Marks the network of this address as unchecked. pub fn into_unchecked(self) -> Address { Address(self.0, PhantomData) } + + /// Returns the [`NetworkKind`] of this address. + pub fn network_kind(&self) -> NetworkKind { + use AddressInner::*; + match self.0 { + P2pkh { hash: _, ref network } => *network, + P2sh { hash: _, ref network } => *network, + Segwit { program: _, ref hrp } => NetworkKind::from(*hrp), + } + } } /// Methods and functions that can be called only on `Address`.