Struct Address
pub struct Address<V = NetworkChecked>(/* private fields */)
where
V: NetworkValidation;
Expand description
A Bitcoin address.
§Parsing addresses
When parsing string as an address, one has to pay attention to the network, on which the parsed
address is supposed to be valid. For the purpose of this validation, Address
has
is_valid_for_network
method. In order to provide more safety,
enforced by compiler, Address
also contains a special marker type, which indicates whether network of the parsed
address has been checked. This marker type will prevent from calling certain functions unless the network
verification has been successfully completed.
The result of parsing an address is Address<NetworkUnchecked>
suggesting that network of the parsed address
has not yet been verified. To perform this verification, method require_network
can be called, providing network on which the address is supposed to be valid. If the verification succeeds,
Address<NetworkChecked>
is returned.
The types Address
and Address<NetworkChecked>
are synonymous, i. e. they can be used interchangeably.
use std::str::FromStr;
use bitcoin::{Address, Network};
use bitcoin::address::{NetworkUnchecked, NetworkChecked};
// variant 1
let address: Address<NetworkUnchecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
let address: Address<NetworkChecked> = address.require_network(Network::Bitcoin).unwrap();
// variant 2
let address: Address = Address::from_str("32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf").unwrap()
.require_network(Network::Bitcoin).unwrap();
// variant 3
let address: Address<NetworkChecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse::<Address<_>>()
.unwrap().require_network(Network::Bitcoin).unwrap();
§Formatting addresses
To format address into its textual representation, both Debug
(for usage in programmer-facing,
debugging context) and Display
(for user-facing output) can be used, with the following caveats:
Display
is implemented only forAddress<NetworkChecked>
:
let address: Address<NetworkChecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
.unwrap().assume_checked();
assert_eq!(address.to_string(), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
let address: Address<NetworkUnchecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
.unwrap();
let s = address.to_string(); // does not compile
Debug
onAddress<NetworkUnchecked>
does not produce clean address but address wrapped by an indicator that its network has not been checked. This is to encourage programmer to properly check the network and useDisplay
in user-facing context.
let address: Address<NetworkUnchecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
.unwrap();
assert_eq!(format!("{:?}", address), "Address<NetworkUnchecked>(132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM)");
let address: Address<NetworkChecked> = Address::from_str("132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM")
.unwrap().assume_checked();
assert_eq!(format!("{:?}", address), "132F25rTsvBdp9JzLLBHP5mvGY66i1xdiM");
§Relevant BIPs
Implementations§
§impl<V> Address<V>where
V: NetworkValidation,
Methods on Address
that can be called on both Address<NetworkChecked>
and
Address<NetworkUnchecked>
.
impl<V> Address<V>where
V: NetworkValidation,
Methods on Address
that can be called on both Address<NetworkChecked>
and
Address<NetworkUnchecked>
.
pub fn as_unchecked(&self) -> &Address<NetworkUnchecked>
pub fn as_unchecked(&self) -> &Address<NetworkUnchecked>
Returns a reference to the address as if it was unchecked.
pub fn into_unchecked(self) -> Address<NetworkUnchecked>
pub fn into_unchecked(self) -> Address<NetworkUnchecked>
Marks the network of this address as unchecked.
§impl Address
Methods and functions that can be called only on Address<NetworkChecked>
.
impl Address
Methods and functions that can be called only on Address<NetworkChecked>
.
pub fn p2pkh(
pk: impl Into<PubkeyHash>,
network: impl Into<NetworkKind>,
) -> Address
pub fn p2pkh( pk: impl Into<PubkeyHash>, network: impl Into<NetworkKind>, ) -> Address
Creates a pay to (compressed) public key hash address from a public key.
This is the preferred non-witness type address.
pub fn p2sh(
script: &Script,
network: impl Into<NetworkKind>,
) -> Result<Address, P2shError>
pub fn p2sh( script: &Script, network: impl Into<NetworkKind>, ) -> Result<Address, P2shError>
Creates a pay to script hash P2SH address from a script.
This address type was introduced with BIP16 and is the popular type to implement multi-sig these days.
pub fn p2sh_from_hash(
hash: ScriptHash,
network: impl Into<NetworkKind>,
) -> Address
pub fn p2sh_from_hash( hash: ScriptHash, network: impl Into<NetworkKind>, ) -> Address
Creates a pay to script hash P2SH address from a script hash.
§Warning
The hash
pre-image (redeem script) must not exceed 520 bytes in length
otherwise outputs created from the returned address will be un-spendable.
pub fn p2wpkh(pk: &CompressedPublicKey, hrp: impl Into<KnownHrp>) -> Address
pub fn p2wpkh(pk: &CompressedPublicKey, hrp: impl Into<KnownHrp>) -> Address
Creates a witness pay to public key address from a public key.
This is the native segwit address type for an output redeemable with a single signature.
pub fn p2shwpkh(
pk: &CompressedPublicKey,
network: impl Into<NetworkKind>,
) -> Address
pub fn p2shwpkh( pk: &CompressedPublicKey, network: impl Into<NetworkKind>, ) -> Address
Creates a pay to script address that embeds a witness pay to public key.
This is a segwit address type that looks familiar (as p2sh) to legacy clients.
pub fn p2wsh(script: &Script, hrp: impl Into<KnownHrp>) -> Address
pub fn p2wsh(script: &Script, hrp: impl Into<KnownHrp>) -> Address
Creates a witness pay to script hash address.
pub fn p2shwsh(script: &Script, network: impl Into<NetworkKind>) -> Address
pub fn p2shwsh(script: &Script, network: impl Into<NetworkKind>) -> Address
Creates a pay to script address that embeds a witness pay to script hash address.
This is a segwit address type that looks familiar (as p2sh) to legacy clients.
pub fn p2tr<C>(
secp: &Secp256k1<C>,
internal_key: XOnlyPublicKey,
merkle_root: Option<TapNodeHash>,
hrp: impl Into<KnownHrp>,
) -> Addresswhere
C: Verification,
pub fn p2tr<C>(
secp: &Secp256k1<C>,
internal_key: XOnlyPublicKey,
merkle_root: Option<TapNodeHash>,
hrp: impl Into<KnownHrp>,
) -> Addresswhere
C: Verification,
Creates a pay to taproot address from an untweaked key.
pub fn p2tr_tweaked(
output_key: TweakedPublicKey,
hrp: impl Into<KnownHrp>,
) -> Address
pub fn p2tr_tweaked( output_key: TweakedPublicKey, hrp: impl Into<KnownHrp>, ) -> Address
Creates a pay to taproot address from a pre-tweaked output key.
pub fn from_witness_program(
program: WitnessProgram,
hrp: impl Into<KnownHrp>,
) -> Address
pub fn from_witness_program( program: WitnessProgram, hrp: impl Into<KnownHrp>, ) -> Address
Creates an address from an arbitrary witness program.
This only exists to support future witness versions. If you are doing normal mainnet things then you likely do not need this constructor.
pub fn address_type(&self) -> Option<AddressType>
pub fn address_type(&self) -> Option<AddressType>
Gets the address type of the address.
§Returns
None if unknown, non-standard or related to the future witness version.
pub fn to_address_data(&self) -> AddressData
pub fn to_address_data(&self) -> AddressData
Gets the address data from this address.
pub fn pubkey_hash(&self) -> Option<PubkeyHash>
pub fn pubkey_hash(&self) -> Option<PubkeyHash>
Gets the pubkey hash for this address if this is a P2PKH address.
pub fn script_hash(&self) -> Option<ScriptHash>
pub fn script_hash(&self) -> Option<ScriptHash>
Gets the script hash for this address if this is a P2SH address.
pub fn witness_program(&self) -> Option<WitnessProgram>
pub fn witness_program(&self) -> Option<WitnessProgram>
Gets the witness program for this address if this is a segwit address.
pub fn is_spend_standard(&self) -> bool
pub fn is_spend_standard(&self) -> bool
Checks whether or not the address is following Bitcoin standardness rules when spending from this address. NOT to be called by senders.
Spending Standardness
For forward compatibility, the senders must send to any Address
. Receivers
can use this method to check whether or not they can spend from this address.
SegWit addresses with unassigned witness versions or non-standard program sizes are considered non-standard.
pub fn from_script(
script: &Script,
params: impl AsRef<Params>,
) -> Result<Address, FromScriptError>
pub fn from_script( script: &Script, params: impl AsRef<Params>, ) -> Result<Address, FromScriptError>
Constructs an Address
from an output script (scriptPubkey
).
pub fn script_pubkey(&self) -> ScriptBuf
pub fn script_pubkey(&self) -> ScriptBuf
Generates a script pubkey spending to this address.
pub fn to_qr_uri(&self) -> String
pub fn to_qr_uri(&self) -> String
Creates a URI string bitcoin:address optimized to be encoded in QR codes.
If the address is bech32, the address becomes uppercase. If the address is base58, the address is left mixed case.
Quoting BIP 173 “inside QR codes uppercase SHOULD be used, as those permit the use of alphanumeric mode, which is 45% more compact than the normal byte mode.”
Note however that despite BIP21 explicitly stating that the bitcoin:
prefix should be
parsed as case-insensitive many wallets got this wrong and don’t parse correctly.
See compatibility table.
If you want to avoid allocation you can use alternate display instead:
write!(writer, "{:#}", address)?;
Returns true if the given pubkey is directly related to the address payload.
This is determined by directly comparing the address payload with either the hash of the given public key or the segwit redeem hash generated from the given key. For taproot addresses, the supplied key is assumed to be tweaked
Returns true if the supplied xonly public key can be used to derive the address.
This will only work for Taproot addresses. The Public Key is assumed to have already been tweaked.
pub fn matches_script_pubkey(&self, script: &Script) -> bool
pub fn matches_script_pubkey(&self, script: &Script) -> bool
Returns true if the address creates a particular script This function doesn’t make any allocations.
§impl Address<NetworkUnchecked>
Methods that can be called only on Address<NetworkUnchecked>
.
impl Address<NetworkUnchecked>
Methods that can be called only on Address<NetworkUnchecked>
.
pub fn assume_checked_ref(&self) -> &Address
pub fn assume_checked_ref(&self) -> &Address
Returns a reference to the checked address.
This function is dangerous in case the address is not a valid checked address.
pub fn is_valid_for_network(&self, n: Network) -> bool
pub fn is_valid_for_network(&self, n: Network) -> bool
Parsed addresses do not always have one network. The problem is that legacy testnet, regtest and signet addresse use the same prefix instead of multiple different ones. When parsing, such addresses are always assumed to be testnet addresses (the same is true for bech32 signet addresses). So if one wants to check if an address belongs to a certain network a simple comparison is not enough anymore. Instead this function can be used.
use bitcoin::{Address, Network};
use bitcoin::address::NetworkUnchecked;
let address: Address<NetworkUnchecked> = "2N83imGV3gPwBzKJQvWJ7cRUY2SpUyU6A5e".parse().unwrap();
assert!(address.is_valid_for_network(Network::Testnet));
assert!(address.is_valid_for_network(Network::Regtest));
assert!(address.is_valid_for_network(Network::Signet));
assert_eq!(address.is_valid_for_network(Network::Bitcoin), false);
let address: Address<NetworkUnchecked> = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
assert!(address.is_valid_for_network(Network::Bitcoin));
assert_eq!(address.is_valid_for_network(Network::Testnet4), false);
pub fn require_network(self, required: Network) -> Result<Address, ParseError>
pub fn require_network(self, required: Network) -> Result<Address, ParseError>
Checks whether network of this address is as required.
For details about this mechanism, see section Parsing addresses
on Address
.
§Errors
This function only ever returns the ParseError::NetworkValidation
variant of
ParseError
. This is not how we normally implement errors in this library but
require_network
is not a typical function, it is conceptually part of string parsing.
§Examples
use bitcoin::address::{NetworkChecked, NetworkUnchecked, ParseError};
use bitcoin::{Address, Network};
const ADDR: &str = "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs";
fn parse_and_validate_address(network: Network) -> Result<Address, ParseError> {
let address = ADDR.parse::<Address<_>>()?
.require_network(network)?;
Ok(address)
}
fn parse_and_validate_address_combinator(network: Network) -> Result<Address, ParseError> {
let address = ADDR.parse::<Address<_>>()
.and_then(|a| a.require_network(network))?;
Ok(address)
}
fn parse_and_validate_address_show_types(network: Network) -> Result<Address, ParseError> {
let address: Address<NetworkChecked> = ADDR.parse::<Address<NetworkUnchecked>>()?
.require_network(network)?;
Ok(address)
}
let network = Network::Bitcoin; // Don't hard code network in applications.
let _ = parse_and_validate_address(network).unwrap();
let _ = parse_and_validate_address_combinator(network).unwrap();
let _ = parse_and_validate_address_show_types(network).unwrap();
pub fn assume_checked(self) -> Address
pub fn assume_checked(self) -> Address
Marks, without any additional checks, network of this address as checked.
Improper use of this method may lead to loss of funds. Reader will most likely prefer
require_network
as a safe variant.
For details about this mechanism, see section Parsing addresses
on Address
.
Trait Implementations§
§impl<V> Clone for Address<V>where
V: Clone + NetworkValidation,
impl<V> Clone for Address<V>where
V: Clone + NetworkValidation,
§impl<V> Debug for Address<V>where
V: NetworkValidation,
impl<V> Debug for Address<V>where
V: NetworkValidation,
§impl<'de> Deserialize<'de> for Address<NetworkUnchecked>
impl<'de> Deserialize<'de> for Address<NetworkUnchecked>
§fn deserialize<D>(
deserializer: D,
) -> Result<Address<NetworkUnchecked>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Address<NetworkUnchecked>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
§impl FromStr for Address<NetworkUnchecked>
Address can be parsed only with NetworkUnchecked
.
impl FromStr for Address<NetworkUnchecked>
Address can be parsed only with NetworkUnchecked
.
§type Err = ParseError
type Err = ParseError
§fn from_str(s: &str) -> Result<Address<NetworkUnchecked>, ParseError>
fn from_str(s: &str) -> Result<Address<NetworkUnchecked>, ParseError>
s
to return a value of this type. Read more