Struct bitcoin::address::Address

source ·
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:

  1. Display is implemented only for Address<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
  1. Debug on Address<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 use Display 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

The #[repr(transparent)] attribute is used to guarantee that the layout of the Address struct is the same as the layout of the AddressInner struct. This attribute is an implementation detail and users should not rely on it in their code.

Implementations§

source§

impl<V: NetworkValidation> Address<V>

Methods on Address that can be called on both Address<NetworkChecked> and Address<NetworkUnchecked>.

source

pub fn payload(&self) -> &Payload

Returns a reference to the payload of this address.

source

pub fn network(&self) -> &Network

Returns a reference to the network of this address.

source

pub fn as_unchecked(&self) -> &Address<NetworkUnchecked>

Returns a reference to the unchecked address, which is dangerous to use if the address is invalid in the context of NetworkUnchecked.

source

pub fn into_parts(self) -> (Network, Payload)

Extracts and returns the network and payload components of the Address.

source

pub fn new(network: Network, payload: Payload) -> Self

Create new address from given components, infering the network validation marker type of the address.

source§

impl Address

Methods and functions that can be called only on Address<NetworkChecked>.

source

pub fn p2pkh(pk: &PublicKey, network: Network) -> Address

Creates a pay to (compressed) public key hash address from a public key.

This is the preferred non-witness type address.

source

pub fn p2sh(script: &Script, network: Network) -> Result<Address, Error>

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.

source

pub fn p2wpkh(pk: &PublicKey, network: Network) -> Result<Address, Error>

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.

Errors

Will only return an error if an uncompressed public key is provided.

source

pub fn p2shwpkh(pk: &PublicKey, network: Network) -> Result<Address, Error>

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.

Errors

Will only return an Error if an uncompressed public key is provided.

source

pub fn p2wsh(script: &Script, network: Network) -> Address

Creates a witness pay to script hash address.

source

pub fn p2shwsh(script: &Script, network: Network) -> 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.

source

pub fn p2tr<C: Verification>( secp: &Secp256k1<C>, internal_key: UntweakedPublicKey, merkle_root: Option<TapNodeHash>, network: Network ) -> Address

Creates a pay to taproot address from an untweaked key.

source

pub fn p2tr_tweaked(output_key: TweakedPublicKey, network: Network) -> Address

Creates a pay to taproot address from a pre-tweaked output key.

This method is not recommended for use, Address::p2tr() should be used where possible.

source

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.

source

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.

source

pub fn from_script(script: &Script, network: Network) -> Result<Address, Error>

Constructs an Address from an output script (scriptPubkey).

source

pub fn script_pubkey(&self) -> ScriptBuf

Generates a script pubkey spending to this address.

source

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.

source

pub fn matches_script_pubkey(&self, script_pubkey: &Script) -> bool

Returns true if the address creates a particular script This function doesn’t make any allocations.

source§

impl Address<NetworkUnchecked>

Methods that can be called only on Address<NetworkUnchecked>.

source

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.

source

pub fn is_valid_for_network(&self, network: 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::Testnet), false);
source

pub fn require_network(self, required: Network) -> Result<Address, Error>

Checks whether network of this address is as required.

For details about this mechanism, see section Parsing addresses on Address.

source

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§

source§

impl<V> Clone for Address<V>where V: NetworkValidation + Clone,

source§

fn clone(&self) -> Address<V>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<V: NetworkValidation> Debug for Address<V>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Address<NetworkUnchecked>

source§

fn deserialize<D>( deserializer: D ) -> Result<Address<NetworkUnchecked>, D::Error>where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Address

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<Address> for ScriptBuf

source§

fn from(a: Address) -> Self

Converts to this type from the input type.
source§

impl FromStr for Address<NetworkUnchecked>

Address can be parsed only with NetworkUnchecked.

§

type Err = ParseError

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl<V> Hash for Address<V>where V: NetworkValidation + Hash,

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<V> Ord for Address<V>where V: NetworkValidation + Ord,

source§

fn cmp(&self, other: &Address<V>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<Address<NetworkUnchecked>> for Address

source§

fn eq(&self, other: &Address<NetworkUnchecked>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq<Address> for Address<NetworkUnchecked>

source§

fn eq(&self, other: &Address) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<V> PartialEq for Address<V>where V: NetworkValidation + PartialEq,

source§

fn eq(&self, other: &Address<V>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<V> PartialOrd for Address<V>where V: NetworkValidation + PartialOrd,

source§

fn partial_cmp(&self, other: &Address<V>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<N: NetworkValidation> Serialize for Address<N>

Available on crate feature serde only.
source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<V> Eq for Address<V>where V: NetworkValidation + Eq,

source§

impl<V> StructuralEq for Address<V>where V: NetworkValidation,

source§

impl<V> StructuralPartialEq for Address<V>where V: NetworkValidation,

Auto Trait Implementations§

§

impl<V> RefUnwindSafe for Address<V>where V: RefUnwindSafe,

§

impl<V> Send for Address<V>

§

impl<V> Sync for Address<V>

§

impl<V> Unpin for Address<V>

§

impl<V> UnwindSafe for Address<V>where V: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,