vanity_core/chains/
bitcoin_segwit.rs1use 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 SegWit,
17 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 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 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 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 !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 Ok(pattern)
158 }
159
160 fn expected_attempts(&self, pattern: &Pattern) -> f64 {
161 expected_from_pattern(pattern, |p| {
162 let data = p
163 .strip_prefix("bc1q")
164 .or_else(|| p.strip_prefix("bc1p"))
165 .or_else(|| p.strip_prefix("bc1"))
166 .unwrap_or(p);
167 32f64.powi(data.chars().filter(|c| *c != '*').count() as i32)
168 })
169 }
170
171 fn matches(&self, address: &str, pattern: &Pattern) -> bool {
172 matches_pattern(address, pattern, true)
173 }
174
175 fn supports_exact_case(&self) -> bool {
176 false
177 }
178
179 fn pattern_hint(&self) -> &'static str {
180 match self.address_type {
181 BtcAddressType::SegWit => "Bech32 chars after bc1q (or full address). Lowercase only.",
182 BtcAddressType::Taproot => "Bech32 chars after bc1p (or full address). Lowercase only.",
183 }
184 }
185}
186
187fn wif_encode(secret: [u8; 32]) -> String {
188 let mut payload = vec![0x80];
189 payload.extend_from_slice(&secret);
190 payload.push(0x01);
191 super::util::base58_check_encode_raw(&payload)
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197 use crate::chain::ChainGrinder;
198
199 #[test]
200 fn segwit_starts_with_bc1q() {
201 let g = BitcoinSegwitGrinder::segwit();
202 let (addr, _) = g.grind_attempt();
203 assert!(addr.starts_with("bc1q"), "got {addr}");
204 }
205
206 #[test]
207 fn taproot_starts_with_bc1p() {
208 let g = BitcoinSegwitGrinder::taproot();
209 let (addr, _) = g.grind_attempt();
210 assert!(addr.starts_with("bc1p"), "got {addr}");
211 }
212
213 #[test]
214 fn segwit_roundtrip_finalize() {
215 let g = BitcoinSegwitGrinder::segwit();
216 let (addr, attempt) = g.grind_attempt();
217 let kp = g.finalize(attempt);
218 assert_eq!(kp.address, addr);
219 }
220}