Skip to content

Commit

Permalink
Use generic_array::sequence::Split
Browse files Browse the repository at this point in the history
  • Loading branch information
survived committed Dec 15, 2023
1 parent 1064a4c commit eda5afd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ generic-ec = { version = "0.1", default-features = false }
hmac = { version = "0.12", default-features = false }
sha2 = { version = "0.10", default-features = false }
subtle = { version = "2", default-features = false }
generic-array = "0.14"

[dev-dependencies]
hex-literal = "0.4"
Expand Down
25 changes: 15 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@

use core::ops;

use generic_array::{
typenum::{U32, U64},
GenericArray,
};
use generic_ec::{Curve, Point, Scalar, SecretScalar};
use hmac::Mac as _;

Expand Down Expand Up @@ -278,16 +282,13 @@ pub fn derive_master_key<E: Curve>(
let mut i = hmac.clone().chain_update(seed).finalize().into_bytes();

loop {
let i_left = &i[..32];
let i_right: [u8; 32] = i[32..]
.try_into()
.expect("this should never fail as size of output is fixed");
let (i_left, i_right) = split_into_two_halfes(&i);

if let Ok(mut sk) = Scalar::<E>::from_be_bytes(i_left) {
if !bool::from(subtle::ConstantTimeEq::ct_eq(&sk, &Scalar::zero())) {
return Ok(ExtendedSecretKey {
secret_key: SecretScalar::new(&mut sk),
chain_code: i_right,
chain_code: (*i_right).into(),
});
}
}
Expand Down Expand Up @@ -403,10 +404,7 @@ fn calculate_shift<E: Curve>(
mut i: hmac::digest::Output<HmacSha512>,
) -> DerivedShift<E> {
loop {
let i_left = &i[..32];
let i_right: [u8; 32] = i[32..]
.try_into()
.expect("this should never fail as size of output is fixed");
let (i_left, i_right) = split_into_two_halfes(&i);

if let Ok(shift) = Scalar::<E>::from_be_bytes(i_left) {
let child_pk = parent_public_key.public_key + Point::generator() * shift;
Expand All @@ -415,7 +413,7 @@ fn calculate_shift<E: Curve>(
shift,
child_public_key: ExtendedPublicKey {
public_key: child_pk,
chain_code: i_right,
chain_code: (*i_right).into(),
},
};
}
Expand All @@ -430,3 +428,10 @@ fn calculate_shift<E: Curve>(
.into_bytes()
}
}

/// Splits array `I` of 64 bytes into two arrays `I_L = I[..32]` and `I_R = I[32..]`
fn split_into_two_halfes(
i: &GenericArray<u8, U64>,
) -> (&GenericArray<u8, U32>, &GenericArray<u8, U32>) {
generic_array::sequence::Split::split(i)
}

0 comments on commit eda5afd

Please sign in to comment.