rust_mempool/common/
address_types.rs

1use std::str::FromStr;
2
3use bitcoin::{bip32::DerivationPath, Address, CompressedPublicKey, Network};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub enum AddressType {
7    P2PKH,  // Legacy addresses (1...)
8    P2WPKH, // Native SegWit addresses (bc1q...)
9    P2TR,   // Taproot addresses (bc1p...)
10}
11
12impl AddressType {
13    pub fn generate_address(
14        &self,
15        public_key: &CompressedPublicKey,
16        network: Network,
17    ) -> anyhow::Result<Address> {
18        let address = match self {
19            AddressType::P2PKH => Address::p2pkh(public_key, network),
20            AddressType::P2WPKH => Address::p2wpkh(public_key, network),
21            AddressType::P2TR => {
22                let secp = bitcoin::secp256k1::Secp256k1::new();
23                let xonly_pubkey = public_key.0.x_only_public_key();
24                let xonly_pubkey = xonly_pubkey.0;
25                Address::p2tr(&secp, xonly_pubkey, None, network)
26            }
27        };
28        Ok(address)
29    }
30
31    pub fn get_derivation_path(&self) -> DerivationPath {
32        match self {
33            AddressType::P2PKH => DerivationPath::from_str("m/44'/0'/0'/0").unwrap(), // BIP44
34            AddressType::P2WPKH => DerivationPath::from_str("m/84'/0'/0'/0").unwrap(), // BIP84
35            AddressType::P2TR => DerivationPath::from_str("m/86'/0'/0'/0").unwrap(),  // BIP86
36        }
37    }
38}