Skip to main content

vanity_core/chains/
bitcoin_segwit.rs

1use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
2use crate::pattern::Pattern;
3use bech32::{hrp, segwit};
4use rand::rngs::OsRng;
5use secp256k1::{Keypair, Scalar, Secp256k1, SecretKey};
6use sha2::{Digest, Sha256};
7
8use super::util::{
9    build_base58_pattern, expected_from_pattern, hash160, matches_pattern, secret_from_attempt,
10    BECH32_CHARSET,
11};
12
13#[derive(Clone, Copy, PartialEq, Eq)]
14pub enum BtcAddressType {
15    /// Native SegWit P2WPKH — `bc1q…`
16    SegWit,
17    /// Taproot P2TR — `bc1p…` (BIP341 key-path, empty script tree)
18    Taproot,
19}
20
21#[derive(Clone)]
22pub struct BitcoinSegwitGrinder {
23    pub address_type: BtcAddressType,
24}
25
26impl BitcoinSegwitGrinder {
27    pub fn segwit() -> Self {
28        Self {
29            address_type: BtcAddressType::SegWit,
30        }
31    }
32
33    pub fn taproot() -> Self {
34        Self {
35            address_type: BtcAddressType::Taproot,
36        }
37    }
38
39    fn derive_segwit(secret: &SecretKey) -> String {
40        let secp = Secp256k1::new();
41        let pubkey = secret.public_key(&secp).serialize();
42        let program = hash160(&pubkey);
43        segwit::encode_v0(hrp::BC, &program).expect("valid p2wpkh")
44    }
45
46    /// BIP341 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || msg)
47    fn tagged_hash(tag: &[u8], msg: &[u8]) -> [u8; 32] {
48        let tag_hash = Sha256::digest(tag);
49        let mut hasher = Sha256::new();
50        hasher.update(tag_hash);
51        hasher.update(tag_hash);
52        hasher.update(msg);
53        hasher.finalize().into()
54    }
55
56    /// Key-path-only Taproot: tweak internal key with empty merkle root.
57    /// Returns (address, tweaked secret bytes for wallet import).
58    fn derive_taproot(secret: &SecretKey) -> (String, [u8; 32]) {
59        let secp = Secp256k1::new();
60        let keypair = Keypair::from_secret_key(&secp, secret);
61        let (xonly, _parity) = keypair.x_only_public_key();
62        let tweak_hash = Self::tagged_hash(b"TapTweak", &xonly.serialize());
63        let tweak = Scalar::from_be_bytes(tweak_hash).unwrap_or(Scalar::ZERO);
64        let tweaked = keypair
65            .add_xonly_tweak(&secp, &tweak)
66            .expect("taproot tweak");
67        let (out_xonly, _) = tweaked.x_only_public_key();
68        let address =
69            segwit::encode_v1(hrp::BC, &out_xonly.serialize()).expect("valid p2tr address");
70        (address, tweaked.secret_key().secret_bytes())
71    }
72
73    fn derive(&self, secret: &SecretKey) -> String {
74        match self.address_type {
75            BtcAddressType::SegWit => Self::derive_segwit(secret),
76            BtcAddressType::Taproot => Self::derive_taproot(secret).0,
77        }
78    }
79}
80
81impl ChainGrinder for BitcoinSegwitGrinder {
82    fn id(&self) -> &'static str {
83        match self.address_type {
84            BtcAddressType::SegWit => "btc-segwit",
85            BtcAddressType::Taproot => "btc-taproot",
86        }
87    }
88
89    fn display_name(&self) -> &'static str {
90        match self.address_type {
91            BtcAddressType::SegWit => "Bitcoin SegWit (P2WPKH)",
92            BtcAddressType::Taproot => "Bitcoin Taproot (P2TR)",
93        }
94    }
95
96    fn grind_attempt(&self) -> (String, GrindAttempt) {
97        let secret = SecretKey::new(&mut OsRng);
98        let address = self.derive(&secret);
99        (address, GrindAttempt::Secret32(secret.secret_bytes()))
100    }
101
102    fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
103        let secret_bytes = secret_from_attempt(attempt);
104        let secret_key = SecretKey::from_slice(&secret_bytes).expect("valid secp256k1 secret");
105
106        let address = self.derive(&secret_key);
107
108        let hint = match self.address_type {
109            BtcAddressType::SegWit => "Sparrow / Electrum / hardware wallet (native SegWit)",
110            BtcAddressType::Taproot => {
111                "Sparrow / Electrum Taproot — internal key (empty script tree BIP341)"
112            }
113        };
114
115        KeypairResult {
116            address,
117            exports: vec![
118                KeyExport {
119                    label: "Private Key (hex)".into(),
120                    value: hex::encode(secret_bytes),
121                    hint: Some(hint.into()),
122                },
123                KeyExport {
124                    label: "Private Key (WIF)".into(),
125                    value: wif_encode(secret_bytes),
126                    hint: Some("Compressed WIF".into()),
127                },
128            ],
129        }
130    }
131
132    fn build_pattern(
133        &self,
134        prefix: Option<&str>,
135        suffix: Option<&str>,
136        contains: Option<&str>,
137        exact: bool,
138    ) -> Result<Pattern, String> {
139        // Bech32 charset; allow matching without forcing bc1q/bc1p in the pattern.
140        let mut pattern =
141            build_base58_pattern(prefix, suffix, contains, exact, BECH32_CHARSET, 62)?;
142        let hrp = match self.address_type {
143            BtcAddressType::SegWit => "bc1q",
144            BtcAddressType::Taproot => "bc1p",
145        };
146        if pattern.has_prefix() && !pattern.prefix.starts_with(hrp) {
147            // If user typed a data-only prefix, prepend the fixed witness HRP.
148            if !pattern.prefix.starts_with("bc1") {
149                pattern.prefix = format!("{hrp}{}", pattern.prefix);
150                pattern.prefix_match = if pattern.ignore_case {
151                    pattern.prefix.to_ascii_lowercase()
152                } else {
153                    pattern.prefix.clone()
154                };
155            }
156        }
157        pattern.set_fixed_prefix(hrp);
158        Ok(pattern)
159    }
160
161    fn expected_attempts(&self, pattern: &Pattern) -> f64 {
162        expected_from_pattern(pattern, |p| {
163            let data = p
164                .strip_prefix("bc1q")
165                .or_else(|| p.strip_prefix("bc1p"))
166                .or_else(|| p.strip_prefix("bc1"))
167                .unwrap_or(p);
168            32f64.powi(data.chars().filter(|c| *c != '*').count() as i32)
169        })
170    }
171
172    fn matches(&self, address: &str, pattern: &Pattern) -> bool {
173        matches_pattern(address, pattern, true)
174    }
175
176    fn supports_exact_case(&self) -> bool {
177        false
178    }
179
180    fn pattern_hint(&self) -> &'static str {
181        match self.address_type {
182            BtcAddressType::SegWit => "Bech32 chars after bc1q (or full address). Lowercase only.",
183            BtcAddressType::Taproot => "Bech32 chars after bc1p (or full address). Lowercase only.",
184        }
185    }
186}
187
188fn wif_encode(secret: [u8; 32]) -> String {
189    let mut payload = vec![0x80];
190    payload.extend_from_slice(&secret);
191    payload.push(0x01);
192    super::util::base58_check_encode_raw(&payload)
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::chain::ChainGrinder;
199
200    #[test]
201    fn segwit_starts_with_bc1q() {
202        let g = BitcoinSegwitGrinder::segwit();
203        let (addr, _) = g.grind_attempt();
204        assert!(addr.starts_with("bc1q"), "got {addr}");
205    }
206
207    #[test]
208    fn taproot_starts_with_bc1p() {
209        let g = BitcoinSegwitGrinder::taproot();
210        let (addr, _) = g.grind_attempt();
211        assert!(addr.starts_with("bc1p"), "got {addr}");
212    }
213
214    #[test]
215    fn segwit_roundtrip_finalize() {
216        let g = BitcoinSegwitGrinder::segwit();
217        let (addr, attempt) = g.grind_attempt();
218        let kp = g.finalize(attempt);
219        assert_eq!(kp.address, addr);
220    }
221}