Skip to main content

vanity_core/chains/
stacks.rs

1//! Stacks mainnet singlesig addresses (`SP…`) via c32check.
2//!
3//! hash160(compressed secp256k1 pubkey) + version `0x16` + double-SHA256 checksum,
4//! Crockford base32, then prefixed with `S`.
5
6use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
7use crate::pattern::Pattern;
8use secp256k1::{Secp256k1, SecretKey};
9use sha2::{Digest, Sha256};
10
11use super::util::{grind_secp256k1, hash160, matches_pattern, secret_from_attempt, validate_chars};
12
13/// Mainnet P2PKH / singlesig version (c32check).
14const VERSION: u8 = 22; // 0x16
15/// Crockford base32 (no I, L, O, U).
16const C32: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
17const C32_ALPHABET: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
18
19#[derive(Clone, Default)]
20pub struct StacksGrinder;
21
22impl StacksGrinder {
23    fn derive(secret: &SecretKey) -> String {
24        let secp = Secp256k1::new();
25        let hash = hash160(&secret.public_key(&secp).serialize());
26        c32address(VERSION, &hash)
27    }
28
29    fn wif_encode(secret: [u8; 32]) -> String {
30        // Stacks often uses hex; WIF still useful for BTC-linked keys.
31        let mut payload = vec![0x80];
32        payload.extend_from_slice(&secret);
33        payload.push(0x01);
34        super::util::base58_check_encode_raw(&payload)
35    }
36}
37
38impl ChainGrinder for StacksGrinder {
39    fn id(&self) -> &'static str {
40        "stx"
41    }
42
43    fn display_name(&self) -> &'static str {
44        "Stacks (SP… c32)"
45    }
46
47    fn grind_attempt(&self) -> (String, GrindAttempt) {
48        grind_secp256k1(Self::derive)
49    }
50
51    fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
52        let secret_bytes = secret_from_attempt(attempt);
53        let secret_key = SecretKey::from_slice(&secret_bytes).expect("valid secp256k1 secret");
54        let address = Self::derive(&secret_key);
55
56        KeypairResult {
57            address,
58            exports: vec![
59                KeyExport {
60                    label: "Private Key (hex)".into(),
61                    value: hex::encode(secret_bytes),
62                    hint: Some("Hiro / Leather / Xverse import".into()),
63                },
64                KeyExport {
65                    label: "Private Key (WIF)".into(),
66                    value: Self::wif_encode(secret_bytes),
67                    hint: Some("Same key can derive linked BTC P2PKH".into()),
68                },
69            ],
70        }
71    }
72
73    fn build_pattern(
74        &self,
75        prefix: Option<&str>,
76        suffix: Option<&str>,
77        contains: Option<&str>,
78        exact: bool,
79    ) -> Result<Pattern, String> {
80        let clean = |raw: Option<&str>, label: &str| -> Result<Option<String>, String> {
81            match raw {
82                None => Ok(None),
83                Some(s) => Ok(Some(validate_chars(
84                    label,
85                    &s.to_ascii_uppercase(),
86                    C32_ALPHABET,
87                )?)),
88            }
89        };
90        let prefix = clean(prefix, "prefix")?;
91        let suffix = clean(suffix, "suffix")?;
92        let contains = clean(contains, "contains")?;
93        if prefix.is_none() && suffix.is_none() && contains.is_none() {
94            return Err("Provide at least one of prefix, suffix, or contains".into());
95        }
96        let prefix = prefix.unwrap_or_default();
97        let suffix = suffix.unwrap_or_default();
98        let contains = contains.unwrap_or_default();
99        let (prefix_match, suffix_match, contains_match) = if exact {
100            (prefix.clone(), suffix.clone(), contains.clone())
101        } else {
102            (
103                prefix.to_ascii_lowercase(),
104                suffix.to_ascii_lowercase(),
105                contains.to_ascii_lowercase(),
106            )
107        };
108        let mut pattern = Pattern {
109            prefix,
110            suffix,
111            contains,
112            prefix_match,
113            suffix_match,
114            contains_match,
115            ignore_case: !exact,
116            fixed_prefix_len: 0,
117        };
118        // Mainnet singlesig always starts with SP
119        if pattern.has_prefix() {
120            let p = pattern.prefix.to_ascii_uppercase();
121            pattern.prefix = if p.starts_with("SP") {
122                p
123            } else if p.starts_with('P') {
124                format!("S{p}")
125            } else {
126                format!("SP{p}")
127            };
128            pattern.prefix_match = if exact {
129                pattern.prefix.clone()
130            } else {
131                pattern.prefix.to_ascii_lowercase()
132            };
133            pattern.set_fixed_prefix("SP");
134        }
135        Ok(pattern)
136    }
137
138    fn expected_attempts(&self, pattern: &Pattern) -> f64 {
139        let mut attempts = 1.0_f64;
140        let count = |s: &str, skip_sp: bool| {
141            let mut chars: Vec<char> = s.chars().collect();
142            if skip_sp && chars.len() >= 2 {
143                let head: String = chars
144                    .iter()
145                    .take(2)
146                    .collect::<String>()
147                    .to_ascii_uppercase();
148                if head == "SP" {
149                    chars.drain(0..2);
150                }
151            }
152            chars.into_iter().filter(|&c| c != '*').count() as f64
153        };
154        attempts *= 32.0_f64.powf(count(&pattern.prefix, true));
155        attempts *= 32.0_f64.powf(count(&pattern.suffix, false));
156        attempts *= 32.0_f64.powf(count(&pattern.contains, false));
157        attempts.max(1.0)
158    }
159
160    fn matches(&self, address: &str, pattern: &Pattern) -> bool {
161        // c32 is uppercase; compare case-insensitively unless exact
162        matches_pattern(address, pattern, false)
163    }
164
165    fn supports_exact_case(&self) -> bool {
166        false
167    }
168
169    fn pattern_hint(&self) -> &'static str {
170        "Crockford base32 (no I L O U). Mainnet singlesig always starts with SP."
171    }
172}
173
174fn c32address(version: u8, hash160: &[u8; 20]) -> String {
175    // c32check: checksum over [version || hash160], encode hash160||checksum,
176    // then prepend c32 digit for `version` and a leading `S`.
177    let mut for_sum = Vec::with_capacity(21);
178    for_sum.push(version);
179    for_sum.extend_from_slice(hash160);
180    let checksum = &Sha256::digest(Sha256::digest(&for_sum))[..4];
181    let mut payload = Vec::with_capacity(24);
182    payload.extend_from_slice(hash160);
183    payload.extend_from_slice(checksum);
184    let ver_char = C32[version as usize] as char;
185    format!("S{ver_char}{}", c32encode(&payload))
186}
187
188fn c32encode(data: &[u8]) -> String {
189    // Big-endian base32 of the byte string (c32check / stacks convention).
190    if data.is_empty() {
191        return String::new();
192    }
193    let mut digits = vec![0u8];
194    for &byte in data {
195        let mut carry = byte as u32;
196        for d in &mut digits {
197            carry += (*d as u32) * 256;
198            *d = (carry % 32) as u8;
199            carry /= 32;
200        }
201        while carry > 0 {
202            digits.push((carry % 32) as u8);
203            carry /= 32;
204        }
205    }
206    // Leading zero bytes → '0' in c32
207    let mut out = String::new();
208    for &b in data {
209        if b == 0 {
210            out.push('0');
211        } else {
212            break;
213        }
214    }
215    for &d in digits.iter().rev() {
216        out.push(C32[d as usize] as char);
217    }
218    out
219}
220
221#[cfg(test)]
222mod tests {
223    use super::{c32address, StacksGrinder};
224    use crate::chain::ChainGrinder;
225
226    #[test]
227    fn known_vector_sp_address() {
228        // From c32check README
229        let hash = hex::decode("a46ff88886c2ef9762d970b4d2c63678835bd39d").unwrap();
230        let mut h = [0u8; 20];
231        h.copy_from_slice(&hash);
232        let addr = c32address(22, &h);
233        assert_eq!(addr, "SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7");
234    }
235
236    #[test]
237    fn grind_starts_with_sp() {
238        let g = StacksGrinder;
239        let (addr, attempt) = g.grind_attempt();
240        assert!(addr.starts_with("SP"), "got {addr}");
241        assert_eq!(g.finalize(attempt).address, addr);
242    }
243}