use generic_ec::{curves, Point, Scalar};
use hmac::Mac;
use crate::{
DeriveShift, DerivedShift, ExtendedKeyPair, ExtendedPublicKey, HardenedIndex, NonHardenedIndex,
};
type HmacSha512 = hmac::Hmac<sha2::Sha512>;
pub struct Edwards;
impl DeriveShift<curves::Ed25519> for Edwards {
fn derive_public_shift(
parent_public_key: &ExtendedPublicKey<curves::Ed25519>,
child_index: NonHardenedIndex,
) -> DerivedShift<curves::Ed25519> {
let hmac = HmacSha512::new_from_slice(&parent_public_key.chain_code)
.expect("this never fails: hmac can handle keys of any size");
let i = hmac
.chain_update(parent_public_key.public_key.to_bytes(true))
.chain_update([0x00])
.chain_update(child_index.to_be_bytes())
.finalize()
.into_bytes();
Self::calculate_shift(parent_public_key, i)
}
fn derive_hardened_shift(
parent_key: &ExtendedKeyPair<curves::Ed25519>,
child_index: HardenedIndex,
) -> DerivedShift<curves::Ed25519> {
let hmac = HmacSha512::new_from_slice(parent_key.chain_code())
.expect("this never fails: hmac can handle keys of any size");
let i = hmac
.chain_update([0x00])
.chain_update(parent_key.secret_key.secret_key.as_ref().to_be_bytes())
.chain_update(child_index.to_be_bytes())
.finalize()
.into_bytes();
Self::calculate_shift(&parent_key.public_key, i)
}
}
impl Edwards {
fn calculate_shift(
parent_public_key: &ExtendedPublicKey<curves::Ed25519>,
i: hmac::digest::Output<HmacSha512>,
) -> DerivedShift<curves::Ed25519> {
let (i_left, i_right) = split_into_two_halves(&i);
let shift = Scalar::from_be_bytes_mod_order(i_left);
let child_pk = parent_public_key.public_key + Point::generator() * shift;
DerivedShift {
shift,
child_public_key: ExtendedPublicKey {
public_key: child_pk,
chain_code: (*i_right).into(),
},
}
}
}
fn split_into_two_halves(
i: &generic_array::GenericArray<u8, generic_array::typenum::U64>,
) -> (
&generic_array::GenericArray<u8, generic_array::typenum::U32>,
&generic_array::GenericArray<u8, generic_array::typenum::U32>,
) {
generic_array::sequence::Split::split(i)
}
super::create_aliases!(Edwards, edwards, hd_wallet::curves::Ed25519);