1use bip39::Mnemonic;
2use hdkey::HDKey;
3use secp256k1::Secp256k1;
4use secp256k1::SecretKey;
5use std::str::FromStr;
6use tiny_keccak::{Hasher, Keccak};
7
8pub fn generate_ethereum_wallet(
9 mnemonic: &str,
10 index: u32,
11) -> Result<(String, String), Box<dyn std::error::Error>> {
12 let mnemonic = Mnemonic::from_str(mnemonic)?;
13
14 let seed = mnemonic.to_seed("");
15 let hd_wallet = HDKey::from_master_seed(&seed, None)?;
16
17 let derivation_path = format!("m/44'/60'/0'/0/{}", index);
18
19 let derived_key = hd_wallet.derive(&derivation_path)?;
20
21 let private_key = derived_key.private_key().unwrap();
22
23 let secp = Secp256k1::new();
24
25 let secret_key = SecretKey::from_slice(&private_key)?;
26 let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
27 let serialized_public_key = public_key.serialize_uncompressed();
28
29 let mut hasher = Keccak::v256();
30 hasher.update(&serialized_public_key[1..]); let mut hash = [0u8; 32];
32 hasher.finalize(&mut hash);
33
34 let address = &hash[12..];
35 let address_hex = format!("0x{}", hex::encode(address));
36
37 let private_key_hex = hex::encode(private_key);
38
39 Ok((address_hex, private_key_hex))
40}