use crate::address::Address;
use crate::error::{Error, Result};
use crate::signer::{KeyType, PrivateKey, PublicKey};
use bip39::{Language, Mnemonic};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use sha2::Sha512;
#[derive(Clone)]
pub struct HDWallet {
mnemonic: Mnemonic,
seed: Vec<u8>,
}
impl HDWallet {
pub fn generate(word_count: WordCount) -> Result<Self> {
let word_count_num = match word_count {
WordCount::Words12 => 12,
WordCount::Words15 => 15,
WordCount::Words18 => 18,
WordCount::Words21 => 21,
WordCount::Words24 => 24,
};
let mnemonic = Mnemonic::generate_in(Language::English, word_count_num)
.map_err(|e| Error::InvalidKey(format!("Failed to generate mnemonic: {}", e)))?;
Self::from_mnemonic(mnemonic, "")
}
pub fn from_phrase(phrase: &str, passphrase: &str) -> Result<Self> {
let mnemonic = Mnemonic::parse_in(Language::English, phrase)
.map_err(|e| Error::InvalidKey(format!("Invalid mnemonic: {}", e)))?;
Self::from_mnemonic(mnemonic, passphrase)
}
fn from_mnemonic(mnemonic: Mnemonic, passphrase: &str) -> Result<Self> {
let seed_bytes = mnemonic.to_seed(passphrase);
Ok(Self {
mnemonic,
seed: seed_bytes.to_vec(),
})
}
pub fn mnemonic_phrase(&self) -> String {
self.mnemonic.words().collect::<Vec<&str>>().join(" ")
}
pub fn seed(&self) -> &[u8] {
&self.seed
}
pub fn derive_private_key(&self, path: &DerivationPath, key_type: KeyType) -> Result<PrivateKey> {
let path_str = path.to_string();
let mut derived_key = vec![0u8; 32];
pbkdf2::<Hmac<Sha512>>(
&self.seed,
path_str.as_bytes(),
2048,
&mut derived_key,
)
.map_err(|e| Error::InvalidKey(format!("Derivation failed: {:?}", e)))?;
match key_type {
KeyType::Secp256k1 => {
secp256k1::SecretKey::from_slice(&derived_key)
.map_err(|e| Error::InvalidKey(format!("Invalid derived key: {}", e)))?;
PrivateKey::new(KeyType::Secp256k1, derived_key.to_vec())
}
KeyType::Ed25519 => {
PrivateKey::new(KeyType::Ed25519, derived_key.to_vec())
}
KeyType::Secp256r1 => {
PrivateKey::new(KeyType::Secp256r1, derived_key.to_vec())
}
}
}
pub fn derive_public_key(&self, path: &DerivationPath, key_type: KeyType) -> Result<PublicKey> {
let private_key = self.derive_private_key(path, key_type)?;
private_key.public_key()
}
pub fn derive_address(&self, path: &DerivationPath, key_type: KeyType) -> Result<Address> {
let public_key = self.derive_public_key(path, key_type)?;
public_key.to_address()
}
pub fn generate_addresses(
&self,
account: u32,
key_type: KeyType,
count: usize,
) -> Result<Vec<(DerivationPath, Address)>> {
let mut addresses = Vec::new();
for index in 0..count {
let path = DerivationPath::bip44(account, 0, index as u32);
let address = self.derive_address(&path, key_type)?;
addresses.push((path, address));
}
Ok(addresses)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WordCount {
Words12,
Words15,
Words18,
Words21,
Words24,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DerivationPath {
purpose: u32,
coin_type: u32,
account: u32,
change: u32,
index: u32,
}
impl DerivationPath {
pub fn bip44(account: u32, change: u32, index: u32) -> Self {
Self {
purpose: 44,
coin_type: 1234, account,
change,
index,
}
}
pub fn custom(purpose: u32, coin_type: u32, account: u32, change: u32, index: u32) -> Self {
Self {
purpose,
coin_type,
account,
change,
index,
}
}
pub fn from_str(path: &str) -> Result<Self> {
let path = path.trim_start_matches("m/");
let parts: Vec<&str> = path.split('/').collect();
if parts.len() != 5 {
return Err(Error::InvalidValue("Invalid path format".to_string()));
}
let purpose = parts[0].trim_end_matches('\'').parse()
.map_err(|_| Error::InvalidValue("Invalid purpose".to_string()))?;
let coin_type = parts[1].trim_end_matches('\'').parse()
.map_err(|_| Error::InvalidValue("Invalid coin type".to_string()))?;
let account = parts[2].trim_end_matches('\'').parse()
.map_err(|_| Error::InvalidValue("Invalid account".to_string()))?;
let change = parts[3].parse()
.map_err(|_| Error::InvalidValue("Invalid change".to_string()))?;
let index = parts[4].parse()
.map_err(|_| Error::InvalidValue("Invalid index".to_string()))?;
Ok(Self {
purpose,
coin_type,
account,
change,
index,
})
}
}
impl std::fmt::Display for DerivationPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"m/{}'/{}'/{}'/{}/{}",
self.purpose, self.coin_type, self.account, self.change, self.index
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hd_wallet_generation() {
let wallet = HDWallet::generate(WordCount::Words12).unwrap();
let phrase = wallet.mnemonic_phrase();
assert_eq!(phrase.split_whitespace().count(), 12);
}
#[test]
fn test_hd_wallet_from_phrase() {
let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
let wallet = HDWallet::from_phrase(phrase, "").unwrap();
assert_eq!(wallet.mnemonic_phrase(), phrase);
}
#[test]
fn test_derivation_path_display() {
let path = DerivationPath::bip44(0, 0, 0);
assert_eq!(path.to_string(), "m/44'/1234'/0'/0/0");
}
#[test]
fn test_derivation_path_parsing() {
let path = DerivationPath::from_str("m/44'/1234'/0'/0/5").unwrap();
assert_eq!(path.purpose, 44);
assert_eq!(path.coin_type, 1234);
assert_eq!(path.account, 0);
assert_eq!(path.change, 0);
assert_eq!(path.index, 5);
}
#[test]
fn test_derive_address() {
let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
let wallet = HDWallet::from_phrase(phrase, "").unwrap();
let path = DerivationPath::bip44(0, 0, 0);
let address = wallet.derive_address(&path, KeyType::Secp256k1).unwrap();
assert!(!address.to_base58().is_empty());
}
#[test]
fn test_generate_multiple_addresses() {
let wallet = HDWallet::generate(WordCount::Words12).unwrap();
let addresses = wallet.generate_addresses(0, KeyType::Secp256k1, 5).unwrap();
assert_eq!(addresses.len(), 5);
let unique_addresses: std::collections::HashSet<_> =
addresses.iter().map(|(_, addr)| addr.to_base58()).collect();
assert_eq!(unique_addresses.len(), 5);
}
#[test]
fn test_deterministic_derivation() {
let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
let wallet1 = HDWallet::from_phrase(phrase, "").unwrap();
let wallet2 = HDWallet::from_phrase(phrase, "").unwrap();
let path = DerivationPath::bip44(0, 0, 0);
let addr1 = wallet1.derive_address(&path, KeyType::Secp256k1).unwrap();
let addr2 = wallet2.derive_address(&path, KeyType::Secp256k1).unwrap();
assert_eq!(addr1.to_base58(), addr2.to_base58());
}
}