Validating a Bitcoin Address for a Network
The validateAddress
method allows you to verify the validity of a Bitcoin address and determine its type (e.g., P2PKH, P2WPKH, P2TR) on a specific network. This method is useful for ensuring that addresses are correctly formatted and compatible with the network you are interacting with.
Method
validateAddress(addr: string | Address, network: Network): AddressTypes | null;
-
Parameters:
addr: string | Address
: The Bitcoin address to validate. Can be a plain string or anAddress
object.network: Network
: The BitcoinJS network configuration (e.g.,networks.regtest
,networks.testnet
).
-
Returns:
AddressTypes
: Specifies the type of the address (e.g.,AddressTypes.P2PKH
,AddressTypes.P2WPKH
).null
: If the address is invalid or does not match the provided network.
Object Definitions
AddressTypes
EnumType | Description |
---|---|
P2PKH | Pay-to-Public-Key-Hash (Legacy address format). |
P2SH_OR_P2SH_P2WPKH | Pay-to-Script-Hash or P2SH-wrapped Pay-to-Witness-PKH. |
P2PK | Pay-to-Public-Key. |
P2TR | Pay-to-Taproot. |
P2WPKH | Pay-to-Witness-Public-Key-Hash (SegWit address). |
Example Usage
import { networks } from "@btc-vision/bitcoin";
import { AddressTypes } from "@btc-vision/transaction";
const address = "bcrt1q...";
const addressType = provider.validateAddress(address, networks.regtest);
if (addressType) {
console.log(`Address is valid and of type: ${addressType}`);
if (addressType === AddressTypes.P2TR) {
console.log("This is a Taproot address!");
}
} else {
console.log("Invalid address for the specified network.");
}
Best Practices
- Ensure the
network
parameter matches the address type you are validating. An address valid ontestnet
may not be valid onmainnet
. - Always check for
null
to avoid processing invalid addresses.
What’s Next?
After validating an address, you can: