2024-06-18 17:04:29 +01:00
|
|
|
use bitcoin::secp256k1::{rand, Keypair, Secp256k1, SecretKey};
|
2024-06-18 16:32:32 +01:00
|
|
|
use std::{
|
|
|
|
|
fs::{self, File},
|
|
|
|
|
io::Write,
|
|
|
|
|
path::PathBuf,
|
2024-06-18 16:56:24 +01:00
|
|
|
str::FromStr,
|
2024-06-18 16:32:32 +01:00
|
|
|
};
|
|
|
|
|
|
2024-06-18 17:03:31 +01:00
|
|
|
pub fn make_keypair() -> bitcoin::secp256k1::Keypair {
|
2024-06-18 16:32:32 +01:00
|
|
|
let secp = Secp256k1::new();
|
2024-06-18 17:03:31 +01:00
|
|
|
let (secret_key, _) = secp.generate_keypair(&mut rand::thread_rng());
|
|
|
|
|
Keypair::from_secret_key(&secp, &secret_key)
|
|
|
|
|
}
|
2024-06-18 16:32:32 +01:00
|
|
|
|
2024-06-18 17:03:31 +01:00
|
|
|
pub(crate) fn write(key_path: &PathBuf) -> Result<(), std::io::Error> {
|
|
|
|
|
let key_pair = make_keypair();
|
2024-06-18 16:32:32 +01:00
|
|
|
let mut file = File::create(key_path)?;
|
|
|
|
|
|
2024-06-18 17:03:31 +01:00
|
|
|
let pub_str = key_pair.public_key().to_string();
|
|
|
|
|
let priv_str = key_pair.display_secret().to_string();
|
2024-06-18 16:56:24 +01:00
|
|
|
println!("private key: {priv_str}");
|
2024-06-18 16:32:32 +01:00
|
|
|
let out = format!("{pub_str}/{priv_str}");
|
|
|
|
|
println!("out: {out}");
|
|
|
|
|
file.write(out.as_bytes())?;
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-18 16:56:24 +01:00
|
|
|
pub(crate) fn load_from_file(side_dir: &PathBuf) -> bitcoin::secp256k1::Keypair {
|
|
|
|
|
let bitcoin_key_path = crate::utils::side_paths(side_dir.clone()).1; // TODO: this tuple stinks
|
2024-06-18 16:32:32 +01:00
|
|
|
|
2024-06-18 16:56:24 +01:00
|
|
|
let data = fs::read_to_string(bitcoin_key_path).expect("couldn't read bitcoin key file");
|
|
|
|
|
println!("bitcoin keys: {:?}", data);
|
2024-06-18 16:32:32 +01:00
|
|
|
|
|
|
|
|
let secret_key_data = data.split("/").collect::<Vec<&str>>()[1];
|
|
|
|
|
let secp = Secp256k1::new();
|
2024-06-18 16:56:24 +01:00
|
|
|
let secret_key =
|
|
|
|
|
SecretKey::from_str(secret_key_data).expect("couldn't load secret key from file");
|
2024-06-18 16:32:32 +01:00
|
|
|
Keypair::from_secret_key(&secp, &secret_key)
|
|
|
|
|
}
|