pub struct Address {
    pub payload: Payload,
    pub network: Network,
}
Expand description

Fields§

§payload: Payload

The type of the address.

§network: Network

The network on which this address is usable.

Implementations§

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

This is the preferred non-witness type address.

Examples found in repository?
src/util/misc.rs (line 164)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        pub fn is_signed_by_address<C: secp256k1::Verification>(
            &self,
            secp_ctx: &secp256k1::Secp256k1<C>,
            address: &Address,
            msg_hash: sha256d::Hash
        ) -> Result<bool, MessageSignatureError> {
            match address.address_type() {
                Some(AddressType::P2pkh) => {
                    let pubkey = self.recover_pubkey(secp_ctx, msg_hash)?;
                    Ok(*address == Address::p2pkh(&pubkey, address.network))
                }
                Some(address_type) => Err(MessageSignatureError::UnsupportedAddressType(address_type)),
                None => Ok(false),
            }
        }

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.

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.

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.

Creates a witness pay to script hash 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.

Creates a pay to taproot address from an untweaked key.

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.

Gets the address type of the address.

Returns

None if unknown, non-standard or related to the future witness version.

Examples found in repository?
src/util/address.rs (line 767)
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    pub fn is_standard(&self) -> bool {
        self.address_type().is_some()
    }

    /// Constructs an [`Address`] from an output script (`scriptPubkey`).
    pub fn from_script(script: &script::Script, network: Network) -> Result<Address, Error> {
        Ok(Address {
            payload: Payload::from_script(script)?,
            network,
        })
    }

    /// Generates a script pubkey spending to this address.
    pub fn script_pubkey(&self) -> script::Script {
        self.payload.script_pubkey()
    }

    /// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes.
    ///
    /// If the address is bech32, both the schema and the address become uppercase.
    /// If the address is base58, the schema is lowercase and 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."
    pub fn to_qr_uri(&self) -> String {
        let schema = match self.payload {
            Payload::WitnessProgram { .. } => "BITCOIN",
            _ => "bitcoin",
        };
        format!("{}:{:#}", schema, self)
    }

    /// 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.
    ///
    /// ```rust
    /// use bitcoincash::{Address, Network};
    ///
    /// let address: Address = "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::Scalenet));
    ///
    /// assert_eq!(address.is_valid_for_network(Network::Bitcoin), false);
    ///
    /// let address: Address = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
    /// assert!(address.is_valid_for_network(Network::Bitcoin));
    /// assert_eq!(address.is_valid_for_network(Network::Testnet), false);
    /// ```
    pub fn is_valid_for_network(&self, network: Network) -> bool {
        let is_legacy = match self.address_type() {
            Some(AddressType::P2pkh) | Some(AddressType::P2sh) => true,
            _ => false
        };

        match (self.network, network) {
            (a, b) if a == b => true,
            (Network::Bitcoin, _) | (_, Network::Bitcoin) => false,
            (Network::Regtest, _) | (_, Network::Regtest) if !is_legacy => false,
            (Network::Testnet, _) | (Network::Testnet4, _) | (Network::Regtest, _) | (Network::Scalenet, _) | (Network::Chipnet, _) => true
        }
    }
More examples
Hide additional examples
src/util/misc.rs (line 161)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        pub fn is_signed_by_address<C: secp256k1::Verification>(
            &self,
            secp_ctx: &secp256k1::Secp256k1<C>,
            address: &Address,
            msg_hash: sha256d::Hash
        ) -> Result<bool, MessageSignatureError> {
            match address.address_type() {
                Some(AddressType::P2pkh) => {
                    let pubkey = self.recover_pubkey(secp_ctx, msg_hash)?;
                    Ok(*address == Address::p2pkh(&pubkey, address.network))
                }
                Some(address_type) => Err(MessageSignatureError::UnsupportedAddressType(address_type)),
                None => Ok(false),
            }
        }

Checks whether or not the address is following Bitcoin standardness rules.

SegWit addresses with unassigned witness versions or non-standard program sizes are considered non-standard.

Constructs an Address from an output script (scriptPubkey).

Generates a script pubkey spending to this address.

Creates a URI string bitcoin:address optimized to be encoded in QR codes.

If the address is bech32, both the schema and the address become uppercase. If the address is base58, the schema is lowercase and 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.”

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 bitcoincash::{Address, Network};

let address: Address = "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::Scalenet));

assert_eq!(address.is_valid_for_network(Network::Bitcoin), false);

let address: Address = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf".parse().unwrap();
assert!(address.is_valid_for_network(Network::Bitcoin));
assert_eq!(address.is_valid_for_network(Network::Testnet), false);

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.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Formats the value using the given formatter. Read more
The associated error which can be returned from parsing.
Parses a string s to return a value of this type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.