1use crate::types::{KaspaError, NetworkType, Result};
3use crate::types::{
4 Outpoint, ScriptPublicKey, Transaction, TransactionInput, TransactionOutput, UtxoEntry,
5};
6use bech32::{self, ToBase32, Variant};
7use ripemd::Ripemd160;
8use secp256k1::rand;
9use secp256k1::{Message, PublicKey, Secp256k1, SecretKey, ecdsa::Signature};
10use sha2::{Digest, Sha256};
11use std::collections::{HashMap, HashSet};
12
13const MAIN_NET_ID: &str = "0000000000000000000000000000000000000000";
14
15pub struct KaspaKeypair {
16 pub secret_key: SecretKey,
17 pub public_key: PublicKey,
18}
19
20pub struct Wallet {
21 keys: HashMap<String, KaspaKeypair>, utxos: HashMap<String, Vec<UtxoEntry>>, addresses: HashSet<String>,
24 network: NetworkType,
25}
26
27impl Wallet {
28 pub fn new(network: NetworkType) -> Self {
29 Self {
30 keys: HashMap::new(),
31 utxos: HashMap::new(),
32 addresses: HashSet::new(),
33 network,
34 }
35 }
36
37 pub fn create_new_address(&mut self) -> Result<String> {
39 let secp = Secp256k1::new();
40 let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
41 let keypair = KaspaKeypair {
42 secret_key,
43 public_key,
44 };
45 let address = self.public_key_to_kaspa_address(&public_key)?;
46 self.keys.insert(address.clone(), keypair);
47 self.addresses.insert(address.clone());
48 Ok(address)
49 }
50
51 fn public_key_to_kaspa_address(&self, public_key: &PublicKey) -> Result<String> {
53 let public_key_bytes = public_key.serialize();
54 let sha256_hash = Sha256::digest(&public_key_bytes);
55 let ripemd160_hash = Ripemd160::digest(&sha256_hash);
56 let byte_version = match self.network {
58 NetworkType::Mainnet => 0x00,
59 NetworkType::Testnet => 0x6f,
60 NetworkType::Devnet => 0x6f,
61 NetworkType::Simnet => 0x6f,
62 };
63 let mut payload = Vec::with_capacity(21);
64 payload.push(byte_version);
65 payload.extend_from_slice(&ripemd160_hash);
66 let checksum = Self::calculate_checksum(&payload);
67 payload.extend_from_slice(&checksum[..4]);
68 let address = bs58::encode(&payload).into_string();
70 Ok(address)
71 }
72
73 fn calculate_checksum(data: &[u8]) -> [u8; 4] {
75 let first_sha = Sha256::digest(data);
76 let second_sha = Sha256::digest(&first_sha);
77 let mut checksum = [0u8; 4];
78 checksum.copy_from_slice(&second_sha[..4]);
79 checksum
80 }
81
82 fn public_key_to_bech32_address(&self, public_key: &PublicKey) -> Result<String> {
84 let public_key_bytes = public_key.serialize();
85 let sha256_hash = Sha256::digest(&public_key_bytes);
87 let ripemd160_hash = Ripemd160::digest(&sha256_hash);
88 let hrp = match self.network {
90 NetworkType::Mainnet => "kaspa",
91 NetworkType::Testnet => "kaspatest",
92 NetworkType::Devnet => "kaspadev",
93 NetworkType::Simnet => "kaspasim",
94 };
95 let encoded = bech32::encode(hrp, ripemd160_hash.to_base32(), Variant::Bech32)
96 .map_err(|e| KaspaError::Custom(format!("Bech32 encoding failed: {}", e)))?;
97 Ok(encoded)
98 }
99
100 pub fn import_private_key(&mut self, private_key_hex: &str) -> Result<String> {
102 let private_key_bytes = hex::decode(private_key_hex)
103 .map_err(|e| KaspaError::Custom(format!("Invalid hex: {}", e)))?;
104 let secret_key = SecretKey::from_slice(&private_key_bytes)
105 .map_err(|e| KaspaError::Custom(format!("Invalid private key: {}", e)))?;
106 let secp = Secp256k1::new();
107 let public_key = PublicKey::from_secret_key(&secp, &secret_key);
108 let keypair = KaspaKeypair {
109 secret_key,
110 public_key,
111 };
112 let address = self.public_key_to_kaspa_address(&public_key)?;
113 self.keys.insert(address.clone(), keypair);
114 self.addresses.insert(address.clone());
115 Ok(address)
116 }
117
118 pub fn export_private_key(&self, address: &str) -> Result<String> {
120 let keypair = self
121 .keys
122 .get(address)
123 .ok_or_else(|| KaspaError::Custom("Address not found in wallet".to_string()))?;
124 Ok(hex::encode(keypair.secret_key.secret_bytes()))
125 }
126
127 pub fn get_balance(&self, address: &str) -> u64 {
129 self.utxos
130 .get(address)
131 .map(|utxos| utxos.iter().map(|utxo| utxo.amount).sum())
132 .unwrap_or(0)
133 }
134
135 pub fn get_total_balance(&self) -> u64 {
137 self.addresses
138 .iter()
139 .map(|addr| self.get_balance(addr))
140 .sum()
141 }
142
143 pub fn add_utxo(&mut self, address: &str, utxo: UtxoEntry) {
145 self.utxos
146 .entry(address.to_string())
147 .or_insert_with(Vec::new)
148 .push(utxo);
149 }
150
151 pub fn remove_utxo(&mut self, address: &str, outpoint: &Outpoint) -> Result<()> {
153 if let Some(utxos) = self.utxos.get_mut(address) {
154 utxos.retain(|utxo| true);
155 }
156 Ok(())
157 }
158
159 pub fn build_transaction(
161 &self,
162 from_address: &str,
163 to_address: &str,
164 amount: u64,
165 fee_per_input: u64,
166 ) -> Result<Transaction> {
167 let keypair = self
168 .keys
169 .get(from_address)
170 .ok_or_else(|| KaspaError::Custom("From address not found".to_string()))?;
171 let utxos = self
172 .utxos
173 .get(from_address)
174 .ok_or_else(|| KaspaError::Custom("No UTXOs for address".to_string()))?;
175 let (selected_indices, total_input) = self.select_utxos(utxos, amount, fee_per_input)?;
176 let selected_utxos: Vec<&UtxoEntry> = selected_indices
177 .iter()
178 .map(|&index| &utxos[index])
179 .collect();
180 let total_fee = selected_utxos.len() as u64 * fee_per_input;
181 let change = total_input
182 .checked_sub(amount + total_fee)
183 .ok_or_else(|| KaspaError::Custom("Insufficient balance".to_string()))?;
184 let inputs = self.build_inputs(&selected_utxos)?;
186 let outputs = self.build_outputs(to_address, amount, from_address, change)?;
188 let transaction = Transaction {
190 version: 0,
191 inputs,
192 outputs,
193 lock_time: 0,
194 subnetwork_id: MAIN_NET_ID.to_string(), gas: 0,
196 payload: "".to_string(),
197 verbose_data: None,
198 };
199 Ok(transaction)
200 }
201
202 fn select_utxos(
204 &self,
205 utxos: &[UtxoEntry],
206 amount: u64,
207 fee_per_input: u64,
208 ) -> Result<(Vec<usize>, u64)> {
209 let mut selected_indices = Vec::new();
210 let mut total = 0u64;
211 let mut indices: Vec<usize> = (0..utxos.len()).collect();
212 indices.sort_by_key(|&i| utxos[i].amount);
213 for index in indices {
214 selected_indices.push(index);
215 total += utxos[index].amount;
216 let estimated_fee = selected_indices.len() as u64 * fee_per_input;
217 if total >= amount + estimated_fee {
218 break;
219 }
220 }
221 if total < amount {
222 return Err(KaspaError::Custom("Insufficient balance".to_string()));
223 }
224 Ok((selected_indices, total))
225 }
226
227 fn build_inputs(&self, utxos: &[&UtxoEntry]) -> Result<Vec<TransactionInput>> {
229 let mut inputs = Vec::new();
230 for (index, utxo) in utxos.iter().enumerate() {
231 let input = TransactionInput {
232 previous_outpoint: Outpoint {
233 transaction_id: format!("tx_{}", index),
234 index: 0,
235 },
236 signature_script: "".to_string(),
237 sequence: 0xFFFFFFFF,
238 sig_op_count: 1,
239 };
240 inputs.push(input);
241 }
242 Ok(inputs)
243 }
244
245 fn build_outputs(
247 &self,
248 to_address: &str,
249 amount: u64,
250 change_address: &str,
251 change_amount: u64,
252 ) -> Result<Vec<TransactionOutput>> {
253 let mut outputs = Vec::new();
254 let to_script = self.address_to_script(to_address)?;
255 outputs.push(TransactionOutput {
256 value: amount,
257 script_public_key: to_script,
258 verbose_data: None,
259 });
260 if change_amount > 0 {
261 let change_script = self.address_to_script(change_address)?;
262 outputs.push(TransactionOutput {
263 value: change_amount,
264 script_public_key: change_script,
265 verbose_data: None,
266 });
267 }
268 Ok(outputs)
269 }
270
271 fn address_to_script(&self, address: &str) -> Result<ScriptPublicKey> {
273 let script = format!(
274 "76a914{}88ac",
275 hex::encode(Sha256::digest(address.as_bytes()))
276 );
277 Ok(ScriptPublicKey {
278 version: 0,
279 script_public_key: script,
280 })
281 }
282
283 pub fn sign_message(&self, address: &str, message: &str) -> Result<String> {
285 let keypair = self
286 .keys
287 .get(address)
288 .ok_or_else(|| KaspaError::Custom("Address not found".to_string()))?;
289
290 let secp = Secp256k1::new();
291 let message_hash = Sha256::digest(message.as_bytes());
292 let message = Message::from_slice(&message_hash)
293 .map_err(|e| KaspaError::Custom(format!("Invalid message hash: {}", e)))?;
294 let signature = secp.sign_ecdsa(&message, &keypair.secret_key);
295 Ok(hex::encode(signature.serialize_compact()))
296 }
297
298 pub fn verify_message(
300 &self,
301 address: &str,
302 message: &str,
303 signature_hex: &str,
304 ) -> Result<bool> {
305 let keypair = self
306 .keys
307 .get(address)
308 .ok_or_else(|| KaspaError::Custom("Address not found".to_string()))?;
309 let signature_bytes = hex::decode(signature_hex)
310 .map_err(|e| KaspaError::Custom(format!("Invalid signature hex: {}", e)))?;
311 let secp = Secp256k1::new();
312 let message_hash = Sha256::digest(message.as_bytes());
313 let message = Message::from_slice(&message_hash)
314 .map_err(|e| KaspaError::Custom(format!("Invalid message hash: {}", e)))?;
315 let signature = Signature::from_compact(&signature_bytes)
316 .map_err(|e| KaspaError::Custom(format!("Invalid signature: {}", e)))?;
317 Ok(secp
318 .verify_ecdsa(&message, &signature, &keypair.public_key)
319 .is_ok())
320 }
321
322 pub fn is_my_address(&self, address: &str) -> bool {
324 self.addresses.contains(address)
325 }
326
327 pub fn get_all_address(&self) -> Vec<String> {
329 self.addresses.iter().cloned().collect()
330 }
331
332 pub fn backup_wallet(&self) -> WalletBackup {
334 let mut key_backups = Vec::new();
335 for (address, keypair) in &self.keys {
336 key_backups.push(KeyBackup {
337 address: address.clone(),
338 private_key: hex::encode(keypair.secret_key.secret_bytes()),
339 public_key: hex::encode(keypair.public_key.serialize()),
340 });
341 }
342 WalletBackup {
343 network: self.network,
344 keys: key_backups,
345 }
346 }
347
348 pub fn restore_from_backup(backup: WalletBackup) -> Result<Self> {
350 let mut wallet = Wallet::new(backup.network);
351 for key_backup in backup.keys {
352 wallet.import_private_key(&key_backup.private_key)?;
353 }
354 Ok(wallet)
355 }
356}
357
358#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
360pub struct WalletBackup {
361 pub network: NetworkType,
362 pub keys: Vec<KeyBackup>,
363}
364
365#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
366pub struct KeyBackup {
367 pub address: String,
368 pub private_key: String,
369 pub public_key: String,
370}
371
372impl<'de> serde::Deserialize<'de> for NetworkType {
373 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
374 where
375 D: serde::Deserializer<'de>,
376 {
377 let s = String::deserialize(deserializer)?;
378 match s.as_str() {
379 "mainnet" => Ok(NetworkType::Mainnet),
380 "testnet" => Ok(NetworkType::Testnet),
381 "devnet" => Ok(NetworkType::Devnet),
382 "simnet" => Ok(NetworkType::Simnet),
383 _ => Err(serde::de::Error::custom("Invalid network type")),
384 }
385 }
386}
387
388pub struct HDWallet {
390 base_wallet: Wallet,
391 seed: [u8; 64],
392 derivation_path: String,
393 key_index: u32,
394}
395
396impl HDWallet {
397 pub fn new(network: NetworkType, seed_phrase: &str) -> Result<Self> {
398 let seed = Self::phrase_to_seed(seed_phrase);
399 Ok(Self {
400 base_wallet: Wallet::new(network),
401 seed,
402 derivation_path: "m/44'/111111'/0'/0".to_string(), key_index: 0,
404 })
405 }
406
407 pub fn generate_next_address(&mut self) -> Result<String> {
408 let derived_key = self.derive_key(self.key_index)?;
409 let address = self
410 .base_wallet
411 .public_key_to_kaspa_address(&derived_key.public_key)?;
412 self.base_wallet.keys.insert(address.clone(), derived_key);
413 self.base_wallet.addresses.insert(address.clone());
414 self.key_index += 1;
415 Ok(address)
416 }
417
418 fn derive_key(&self, index: u32) -> Result<KaspaKeypair> {
419 let secp = Secp256k1::new();
420 let mut hasher = Sha256::new();
421 hasher.update(&self.seed);
422 hasher.update(&index.to_be_bytes());
423 let hash_result = hasher.finalize();
424 let secret_key = SecretKey::from_slice(&hash_result)
425 .map_err(|e| KaspaError::Custom(format!("Key derivation failed: {}", e)))?;
426 let public_key = PublicKey::from_secret_key(&secp, &secret_key);
427 Ok(KaspaKeypair {
428 secret_key,
429 public_key,
430 })
431 }
432
433 fn phrase_to_seed(phrase: &str) -> [u8; 64] {
434 let mut seed = [0u8; 64];
435 let phrase_bytes = phrase.as_bytes();
436 let len = phrase_bytes.len().min(64);
437 seed[..len].copy_from_slice(&phrase_bytes[..len]);
438 seed
439 }
440}