2024-06-24 08:02:17 +01:00
|
|
|
use bdk::{
|
2024-06-24 17:20:52 +01:00
|
|
|
bitcoin::{bip32::ExtendedPrivKey, Network},
|
2024-06-24 08:02:17 +01:00
|
|
|
keys::{
|
|
|
|
|
bip39::{Language, Mnemonic, WordCount},
|
|
|
|
|
DerivableKey, ExtendedKey, GeneratableKey, GeneratedKey,
|
|
|
|
|
},
|
|
|
|
|
miniscript,
|
|
|
|
|
template::Bip84,
|
2024-06-24 17:20:52 +01:00
|
|
|
KeychainKind,
|
2024-06-24 08:02:17 +01:00
|
|
|
};
|
|
|
|
|
|
2024-06-18 16:32:32 +01:00
|
|
|
use std::{
|
|
|
|
|
fs::{self, File},
|
|
|
|
|
io::Write,
|
|
|
|
|
path::PathBuf,
|
|
|
|
|
};
|
|
|
|
|
|
2024-06-24 08:02:17 +01:00
|
|
|
pub fn make_mnemonic() -> String {
|
|
|
|
|
let mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
|
|
|
|
|
Mnemonic::generate((WordCount::Words12, Language::English)).unwrap();
|
|
|
|
|
mnemonic.to_string()
|
2024-06-18 17:03:31 +01:00
|
|
|
}
|
2024-06-18 16:32:32 +01:00
|
|
|
|
2024-06-24 08:02:17 +01:00
|
|
|
pub(crate) fn write(mnemonic_path: &PathBuf) -> Result<(), std::io::Error> {
|
|
|
|
|
let mnemonic = make_mnemonic();
|
|
|
|
|
let mut file = File::create(mnemonic_path)?;
|
|
|
|
|
println!("mnemonic: {mnemonic}");
|
|
|
|
|
file.write(mnemonic.as_bytes())?;
|
2024-06-18 16:32:32 +01:00
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-24 13:56:43 +01:00
|
|
|
/// Creates a Signet Bitcoin descriptor wallet from a mnemonic
|
2024-06-24 17:20:52 +01:00
|
|
|
pub fn get(
|
|
|
|
|
mnemonic_words: String,
|
|
|
|
|
) -> anyhow::Result<(Bip84<ExtendedPrivKey>, Option<Bip84<ExtendedPrivKey>>)> {
|
2024-06-24 08:02:17 +01:00
|
|
|
let mnemonic = Mnemonic::parse(mnemonic_words).unwrap();
|
|
|
|
|
|
|
|
|
|
// Generate the extended key
|
|
|
|
|
let xkey: ExtendedKey = mnemonic.into_extended_key()?;
|
2024-06-18 16:32:32 +01:00
|
|
|
|
2024-06-24 08:02:17 +01:00
|
|
|
// Get private key from the extended key
|
|
|
|
|
let xprv = xkey.into_xprv(Network::Signet).unwrap();
|
|
|
|
|
|
2024-06-24 17:20:52 +01:00
|
|
|
let external_descriptor = Bip84(xprv, KeychainKind::External);
|
|
|
|
|
let internal_descriptor = Some(Bip84(xprv, KeychainKind::Internal));
|
2024-06-24 08:02:17 +01:00
|
|
|
|
2024-06-24 17:20:52 +01:00
|
|
|
Ok((external_descriptor, internal_descriptor))
|
2024-06-24 08:02:17 +01:00
|
|
|
}
|
2024-06-18 16:32:32 +01:00
|
|
|
|
2024-06-24 17:20:52 +01:00
|
|
|
pub(crate) fn load_from_file(
|
|
|
|
|
side_dir: &PathBuf,
|
|
|
|
|
) -> anyhow::Result<(Bip84<ExtendedPrivKey>, Option<Bip84<ExtendedPrivKey>>)> {
|
2024-06-24 08:02:17 +01:00
|
|
|
let mnemonic_path = crate::utils::side_paths(side_dir.clone()).1; // TODO: this tuple stinks
|
|
|
|
|
let mnemonic_words = fs::read_to_string(mnemonic_path).expect("couldn't read bitcoin key file");
|
|
|
|
|
println!("Creating wallet from mnemonic: {mnemonic_words}");
|
2024-06-24 17:20:52 +01:00
|
|
|
get(mnemonic_words)
|
2024-06-18 16:32:32 +01:00
|
|
|
}
|