use crate::prelude::*;
pub(crate) fn derive_child_key(
parent_key: &[u8],
chain_code: &[u8],
index: u32,
) -> (SecretKey, [u8; 32]) {
let parent_key = &SecretKey::from_slice(parent_key).unwrap();
let mut hmac = Hmac::<Sha512>::new_from_slice(chain_code).expect("HMAC initialization failed");
hmac.update(&serialize_private_key(parent_key, index));
let result = hmac.finalize();
let hmac_output = result.into_bytes();
let secret_key = SecretKey::from_slice(&hmac_output[0..32]).expect("Invalid secret key");
let child_chain_code: [u8; 32] = hmac_output[32..].try_into().expect("Invalid chain code");
(secret_key, child_chain_code)
}
pub(crate) fn serialize_private_key(key: &SecretKey, index: u32) -> Vec<u8> {
let mut serialized_key = Vec::new();
serialized_key.extend_from_slice(&key[..]);
serialized_key.extend_from_slice(&index.to_be_bytes());
serialized_key
}
pub(crate) fn generate_public_key(private_key: &SecretKey) -> PublicKey {
let secp = Secp256k1::new();
PublicKey::from_secret_key(&secp, private_key)
}
#[test]
fn show_child_key_1() {
use crate::CONFIG;
dotenv().ok();
assert_debug_snapshot!(CONFIG.derive_child_key(1).2);
}