1use crate::chain::{ChainGrinder, GrindAttempt, KeyExport, KeypairResult};
9use crate::pattern::Pattern;
10use rand::rngs::OsRng;
11use secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
12
13use super::bitcoin_like::BitcoinLikeGrinder;
14use super::util::{grind_secp256k1, p2pkh_address, p2pkh_address_from_pubkey, secret_from_attempt};
15
16#[derive(Clone)]
18pub struct SplitKeypair {
19 pub address: String,
20 pub private_key_hex: String,
21 pub private_key_wif: String,
22 pub public_key_hex: String,
24}
25
26pub fn generate_split_keypair(coin: &BitcoinLikeGrinder) -> SplitKeypair {
28 let secp = Secp256k1::new();
29 let secret = SecretKey::new(&mut OsRng);
30 let public = secret.public_key(&secp);
31 let address = p2pkh_address(&secret, coin.version_byte);
32 SplitKeypair {
33 address,
34 private_key_hex: hex::encode(secret.secret_bytes()),
35 private_key_wif: wif_encode(secret.secret_bytes(), coin.wif_byte),
36 public_key_hex: hex::encode(public.serialize_uncompressed()),
37 }
38}
39
40pub fn parse_public_key(hex: &str) -> Result<PublicKey, String> {
42 let s = hex.trim().trim_start_matches("0x").trim_start_matches("0X");
43 let bytes = hex::decode(s).map_err(|_| "split public key is not valid hex".to_string())?;
44 PublicKey::from_slice(&bytes).map_err(|e| format!("invalid secp256k1 public key: {e}"))
45}
46
47pub fn parse_secret_key(input: &str) -> Result<SecretKey, String> {
49 let s = input.trim();
50 if let Ok(bytes) = hex::decode(s.trim_start_matches("0x").trim_start_matches("0X")) {
51 if bytes.len() == 32 {
52 return SecretKey::from_slice(&bytes)
53 .map_err(|e| format!("invalid private key hex: {e}"));
54 }
55 }
56 let decoded = bs58::decode(s)
58 .into_vec()
59 .map_err(|_| "private key must be 32-byte hex or WIF".to_string())?;
60 if decoded.len() < 37 {
61 return Err("WIF payload too short".into());
62 }
63 let (payload, checksum) = decoded.split_at(decoded.len() - 4);
64 let expect = {
65 use sha2::{Digest, Sha256};
66 let mid = Sha256::digest(payload);
67 let full = Sha256::digest(mid);
68 [full[0], full[1], full[2], full[3]]
69 };
70 if checksum != expect {
71 return Err("WIF checksum mismatch (typo or wrong network?)".into());
72 }
73 let body = &payload[1..];
75 let secret_bytes = if body.len() == 33 && body[32] == 0x01 {
76 &body[..32]
77 } else if body.len() == 32 {
78 body
79 } else {
80 return Err("unrecognized WIF payload length".into());
81 };
82 SecretKey::from_slice(secret_bytes).map_err(|e| format!("invalid WIF secret: {e}"))
83}
84
85pub fn combine_split_keys(
87 alice_secret: &SecretKey,
88 part_secret: &SecretKey,
89 coin: &BitcoinLikeGrinder,
90) -> Result<SplitKeypair, String> {
91 let tweak = Scalar::from_be_bytes(part_secret.secret_bytes())
92 .map_err(|_| "part private key is out of range for secp256k1".to_string())?;
93 let combined = alice_secret
94 .add_tweak(&tweak)
95 .map_err(|e| format!("failed to combine private keys: {e}"))?;
96 let secp = Secp256k1::new();
97 let public = combined.public_key(&secp);
98 Ok(SplitKeypair {
99 address: p2pkh_address(&combined, coin.version_byte),
100 private_key_hex: hex::encode(combined.secret_bytes()),
101 private_key_wif: wif_encode(combined.secret_bytes(), coin.wif_byte),
102 public_key_hex: hex::encode(public.serialize_uncompressed()),
103 })
104}
105
106fn wif_encode(secret: [u8; 32], version: u8) -> String {
107 let mut payload = vec![version];
108 payload.extend_from_slice(&secret);
109 payload.push(0x01);
110 super::util::base58_check_encode_raw(&payload)
111}
112
113#[derive(Clone)]
115pub struct SplitKeyGrinder {
116 base: PublicKey,
117 coin: BitcoinLikeGrinder,
118}
119
120impl SplitKeyGrinder {
121 pub fn new(base_pubkey_hex: &str, coin: BitcoinLikeGrinder) -> Result<Self, String> {
122 Ok(Self {
123 base: parse_public_key(base_pubkey_hex)?,
124 coin,
125 })
126 }
127
128 pub fn coin(&self) -> &BitcoinLikeGrinder {
129 &self.coin
130 }
131}
132
133impl ChainGrinder for SplitKeyGrinder {
134 fn id(&self) -> &'static str {
135 self.coin.id
137 }
138
139 fn display_name(&self) -> &'static str {
140 "Split-key (Bitcoin-family P2PKH)"
141 }
142
143 fn grind_attempt(&self) -> (String, GrindAttempt) {
144 let secp = Secp256k1::new();
145 loop {
146 let (addr, attempt) = grind_secp256k1(|part| {
147 let part_pk = part.public_key(&secp);
148 match self.base.combine(&part_pk) {
149 Ok(sum) => p2pkh_address_from_pubkey(&sum, self.coin.version_byte),
150 Err(_) => String::new(), }
152 });
153 if !addr.is_empty() {
154 return (addr, attempt);
155 }
156 }
157 }
158
159 fn finalize(&self, attempt: GrindAttempt) -> KeypairResult {
160 let part_bytes = secret_from_attempt(attempt);
161 let part = SecretKey::from_slice(&part_bytes).expect("valid part secret");
162 let secp = Secp256k1::new();
163 let sum = self
164 .base
165 .combine(&part.public_key(&secp))
166 .expect("valid combine");
167 let address = p2pkh_address_from_pubkey(&sum, self.coin.version_byte);
168 KeypairResult {
169 address: address.clone(),
170 exports: vec![
171 KeyExport {
172 label: "PrivkeyPart (hex)".into(),
173 value: hex::encode(part_bytes),
174 hint: Some(
175 "Send this part back to the key owner — it is NOT the final private key."
176 .into(),
177 ),
178 },
179 KeyExport {
180 label: "PrivkeyPart (WIF)".into(),
181 value: wif_encode(part_bytes, self.coin.wif_byte),
182 hint: Some("Same part as WIF for convenience".into()),
183 },
184 KeyExport {
185 label: "Vanity address".into(),
186 value: address,
187 hint: Some(
188 "Owner combines their secret + this part with `split-key combine`".into(),
189 ),
190 },
191 ],
192 }
193 }
194
195 fn build_pattern(
196 &self,
197 prefix: Option<&str>,
198 suffix: Option<&str>,
199 contains: Option<&str>,
200 exact: bool,
201 ) -> Result<Pattern, String> {
202 self.coin.build_pattern(prefix, suffix, contains, exact)
203 }
204
205 fn expected_attempts(&self, pattern: &Pattern) -> f64 {
206 self.coin.expected_attempts(pattern)
207 }
208
209 fn matches(&self, address: &str, pattern: &Pattern) -> bool {
210 self.coin.matches(address, pattern)
211 }
212
213 fn supports_exact_case(&self) -> bool {
214 true
215 }
216
217 fn pattern_hint(&self) -> &'static str {
218 "Split-key grind: you only produce a key *part*. The owner combines it offline."
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use crate::chains::BitcoinLikeGrinder;
226
227 #[test]
228 fn roundtrip_gen_grind_combine() {
229 let coin = BitcoinLikeGrinder::bitcoin();
230 let alice = generate_split_keypair(&coin);
231 let grinder = SplitKeyGrinder::new(&alice.public_key_hex, coin.clone()).unwrap();
232
233 let pattern = grinder.build_pattern(Some("1"), None, None, true).unwrap();
235 let (addr, attempt) = loop {
236 let (a, att) = grinder.grind_attempt();
237 if grinder.matches(&a, &pattern) {
238 break (a, att);
239 }
240 };
241 let fin = grinder.finalize(attempt);
242 assert_eq!(fin.address, addr);
243
244 let part_hex = fin
245 .exports
246 .iter()
247 .find(|e| e.label.starts_with("PrivkeyPart (hex)"))
248 .unwrap()
249 .value
250 .clone();
251 let alice_sk = parse_secret_key(&alice.private_key_hex).unwrap();
252 let part_sk = parse_secret_key(&part_hex).unwrap();
253 let combined = combine_split_keys(&alice_sk, &part_sk, &coin).unwrap();
254 assert_eq!(combined.address, addr);
255 let sk = parse_secret_key(&combined.private_key_hex).unwrap();
257 assert_eq!(p2pkh_address(&sk, coin.version_byte), addr);
258 }
259
260 #[test]
261 fn rejects_bad_pubkey() {
262 assert!(SplitKeyGrinder::new("00", BitcoinLikeGrinder::bitcoin()).is_err());
263 }
264
265 #[test]
266 fn wif_roundtrip_and_rejects_bad_checksum() {
267 let coin = BitcoinLikeGrinder::bitcoin();
268 let alice = generate_split_keypair(&coin);
269 let sk = parse_secret_key(&alice.private_key_wif).expect("valid WIF");
270 assert_eq!(hex::encode(sk.secret_bytes()), alice.private_key_hex);
271
272 let mut bad: Vec<u8> = alice.private_key_wif.bytes().collect();
274 let last = bad.len() - 1;
275 bad[last] = if bad[last] == b'1' { b'2' } else { b'1' };
276 let bad_wif = String::from_utf8(bad).unwrap();
277 let err = parse_secret_key(&bad_wif).unwrap_err();
278 assert!(
279 err.contains("checksum"),
280 "expected checksum error, got: {err}"
281 );
282 }
283}