Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

switch from libsecp256k1 to k256 and update other deps #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ repository = "https://github.com/maciejhirsz/tiny-hderive"
keywords = ["bitcoin", "ethereum", "bip32", "bip39", "bip44"]

[dependencies]
libsecp256k1 = "0.3.5"
base58 = "0.1.0"
sha2 = "0.8.0"
hmac = "0.7.0"
memzero = "0.1.0"
k256 = "0.13"
base58 = "0.2"
sha2 = "0.10"
hmac = "0.12"
memzero = "0.1"

[dev-dependencies]
ethsign = { version = "0.3", default-features = false, features = ["secp256k1-rs"] }
tiny-bip39 = "0.6"
ethsign = { version = "0.9", default-features = false, features = ["pure-rust"] }
tiny-bip39 = "1.0"
71 changes: 45 additions & 26 deletions src/bip32.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use secp256k1::{SecretKey, PublicKey};
use base58::FromBase58;
use sha2::Sha512;
use hmac::{Hmac, Mac};
use k256::SecretKey;
use memzero::Memzero;
use sha2::Sha512;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;
use std::fmt;

use crate::bip44::{ChildNumber, IntoDerivationPath};
use crate::Error;
Expand Down Expand Up @@ -49,14 +49,15 @@ impl ExtendedPrivKey {
where
Path: IntoDerivationPath,
{
let mut hmac: Hmac<Sha512> = Hmac::new_varkey(b"Bitcoin seed").expect("seed is always correct; qed");
hmac.input(seed);
let mut hmac: Hmac<Sha512> =
Hmac::new_from_slice(b"Bitcoin seed").expect("seed is always correct; qed");
hmac.update(seed);

let result = hmac.result().code();
let result = hmac.finalize().into_bytes();
let (secret_key, chain_code) = result.split_at(32);

let mut sk = ExtendedPrivKey {
secret_key: SecretKey::parse_slice(secret_key).map_err(Error::Secp256k1)?,
secret_key: SecretKey::from_slice(secret_key).map_err(Error::Secp256k1)?,
chain_code: Protected::from(chain_code),
};

Expand All @@ -68,31 +69,35 @@ impl ExtendedPrivKey {
}

pub fn secret(&self) -> [u8; 32] {
self.secret_key.serialize()
self.secret_key.to_bytes().into()
}

pub fn child(&self, child: ChildNumber) -> Result<ExtendedPrivKey, Error> {
let mut hmac: Hmac<Sha512> = Hmac::new_varkey(&self.chain_code)
.map_err(|_| Error::InvalidChildNumber)?;
let mut hmac: Hmac<Sha512> =
Hmac::new_from_slice(&self.chain_code).map_err(|_| Error::InvalidChildNumber)?;

if child.is_normal() {
hmac.input(&PublicKey::from_secret_key(&self.secret_key).serialize_compressed()[..]);
hmac.update(&self.secret_key.public_key().to_sec1_bytes());
} else {
hmac.input(&[0]);
hmac.input(&self.secret_key.serialize()[..]);
hmac.update(&[0]);
hmac.update(&self.secret());
}

hmac.input(&child.to_bytes());
hmac.update(&child.to_bytes());

let result = hmac.result().code();
let result = hmac.finalize().into_bytes();
let (secret_key, chain_code) = result.split_at(32);

let mut secret_key = SecretKey::parse_slice(&secret_key).map_err(Error::Secp256k1)?;
secret_key.tweak_add_assign(&self.secret_key).map_err(Error::Secp256k1)?;
let mut secret_key = SecretKey::from_slice(secret_key).map_err(Error::Secp256k1)?;
let raw = *secret_key.as_scalar_primitive() + self.secret_key.as_scalar_primitive();
if raw.is_zero().into() {
return Err(Error::ZeroChildKey);
}
secret_key = SecretKey::new(raw);

Ok(ExtendedPrivKey {
secret_key,
chain_code: Protected::from(&chain_code)
chain_code: Protected::from(&chain_code),
})
}
}
Expand All @@ -101,48 +106,62 @@ impl FromStr for ExtendedPrivKey {
type Err = Error;

fn from_str(xprv: &str) -> Result<ExtendedPrivKey, Error> {
let data = xprv.from_base58().map_err(|_| Error::InvalidExtendedPrivKey)?;
let data = xprv
.from_base58()
.map_err(|_| Error::InvalidExtendedPrivKey)?;

if data.len() != 82 {
return Err(Error::InvalidExtendedPrivKey);
}

Ok(ExtendedPrivKey {
chain_code: Protected::from(&data[13..45]),
secret_key: SecretKey::parse_slice(&data[46..78]).map_err(|e| Error::Secp256k1(e))?
secret_key: SecretKey::from_slice(&data[46..78]).map_err(Error::Secp256k1)?,
})
}
}

#[cfg(test)]
mod tests {
use super::*;
use bip39::{Mnemonic, Language, Seed};
use bip39::{Language, Mnemonic, Seed};
use ethsign::SecretKey;

#[test]
fn bip39_to_address() {
let phrase = "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside";

let expected_secret_key = b"\xff\x1e\x68\xeb\x7b\xf2\xf4\x86\x51\xc4\x7e\xf0\x17\x7e\xb8\x15\x85\x73\x22\x25\x7c\x58\x94\xbb\x4c\xfd\x11\x76\xc9\x98\x93\x14";
let expected_address: &[u8] = b"\x63\xF9\xA9\x2D\x8D\x61\xb4\x8a\x9f\xFF\x8d\x58\x08\x04\x25\xA3\x01\x2d\x05\xC8";
let expected_address: &[u8] =
b"\x63\xF9\xA9\x2D\x8D\x61\xb4\x8a\x9f\xFF\x8d\x58\x08\x04\x25\xA3\x01\x2d\x05\xC8";

let mnemonic = Mnemonic::from_phrase(phrase, Language::English).unwrap();
let seed = Seed::new(&mnemonic, "");

let account = ExtendedPrivKey::derive(seed.as_bytes(), "m/44'/60'/0'/0/0").unwrap();

assert_eq!(expected_secret_key, &account.secret(), "Secret key is invalid");
assert_eq!(
expected_secret_key,
&account.secret(),
"Secret key is invalid"
);

let secret_key = SecretKey::from_raw(&account.secret()).unwrap();
let public_key = secret_key.public();

assert_eq!(expected_address, public_key.address(), "Address is invalid");

// Test child method
let account = ExtendedPrivKey::derive(seed.as_bytes(), "m/44'/60'/0'/0").unwrap().child(ChildNumber::from_str("0").unwrap()).unwrap();

assert_eq!(expected_secret_key, &account.secret(), "Secret key is invalid");
let account = ExtendedPrivKey::derive(seed.as_bytes(), "m/44'/60'/0'/0")
.unwrap()
.child(ChildNumber::from_str("0").unwrap())
.unwrap();

assert_eq!(
expected_secret_key,
&account.secret(),
"Secret key is invalid"
);

let secret_key = SecretKey::from_raw(&account.secret()).unwrap();
let public_key = secret_key.public();
Expand Down
107 changes: 56 additions & 51 deletions src/bip44.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,43 @@ const HARDENED_BIT: u32 = 1 << 31;
pub struct ChildNumber(u32);

impl ChildNumber {
pub fn is_hardened(&self) -> bool {
self.0 & HARDENED_BIT == HARDENED_BIT
}
pub fn is_hardened(&self) -> bool {
self.0 & HARDENED_BIT == HARDENED_BIT
}

pub fn is_normal(&self) -> bool {
self.0 & HARDENED_BIT == 0
}
pub fn is_normal(&self) -> bool {
self.0 & HARDENED_BIT == 0
}

pub fn to_bytes(&self) -> [u8; 4] {
self.0.to_be_bytes()
}
pub fn to_bytes(&self) -> [u8; 4] {
self.0.to_be_bytes()
}

pub fn hardened_from_u32(index: u32) -> Self {
ChildNumber(index | HARDENED_BIT)
}
pub fn hardened_from_u32(index: u32) -> Self {
ChildNumber(index | HARDENED_BIT)
}

pub fn non_hardened_from_u32(index: u32) -> Self {
ChildNumber(index)
}
pub fn non_hardened_from_u32(index: u32) -> Self {
ChildNumber(index)
}
}

impl FromStr for ChildNumber {
type Err = Error;

fn from_str(child: &str) -> Result<ChildNumber, Error> {
let (child, mask) = if child.ends_with('\'') {
(&child[..child.len() - 1], HARDENED_BIT)
} else {
(child, 0)
};
let (child, mask) = if let Some(child) = child.strip_suffix('\'') {
(child, HARDENED_BIT)
} else {
(child, 0)
};

let index: u32 = child.parse().map_err(|_| Error::InvalidChildNumber)?;

if index & HARDENED_BIT == 0 {
Ok(ChildNumber(index | mask))
Ok(ChildNumber(index | mask))
} else {
Err(Error::InvalidChildNumber)
Err(Error::InvalidChildNumber)
}
}
}
Expand All @@ -66,52 +66,57 @@ impl FromStr for DerivationPath {
}

Ok(DerivationPath {
path: path.map(str::parse).collect::<Result<Vec<ChildNumber>, Error>>()?
path: path
.map(str::parse)
.collect::<Result<Vec<ChildNumber>, Error>>()?,
})
}
}

impl DerivationPath {
pub fn as_ref(&self) -> &[ChildNumber] {
&self.path
}
pub fn as_ref(&self) -> &[ChildNumber] {
&self.path
}

pub fn iter(&self) -> impl Iterator<Item = &ChildNumber> {
self.path.iter()
}
pub fn iter(&self) -> impl Iterator<Item = &ChildNumber> {
self.path.iter()
}
}

pub trait IntoDerivationPath {
fn into(self) -> Result<DerivationPath, Error>;
fn into(self) -> Result<DerivationPath, Error>;
}

impl IntoDerivationPath for DerivationPath {
fn into(self) -> Result<DerivationPath, Error> {
Ok(self)
}
fn into(self) -> Result<DerivationPath, Error> {
Ok(self)
}
}

impl IntoDerivationPath for &str {
fn into(self) -> Result<DerivationPath, Error> {
self.parse()
}
fn into(self) -> Result<DerivationPath, Error> {
self.parse()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn derive_path() {
let path: DerivationPath = "m/44'/60'/0'/0".parse().unwrap();

assert_eq!(path, DerivationPath {
path: vec![
ChildNumber(44 | HARDENED_BIT),
ChildNumber(60 | HARDENED_BIT),
ChildNumber(0 | HARDENED_BIT),
ChildNumber(0),
],
});
}
use super::*;

#[test]
fn derive_path() {
let path: DerivationPath = "m/44'/60'/0'/0".parse().unwrap();

assert_eq!(
path,
DerivationPath {
path: vec![
ChildNumber(44 | HARDENED_BIT),
ChildNumber(60 | HARDENED_BIT),
ChildNumber(0 | HARDENED_BIT),
ChildNumber(0),
],
}
);
}
}
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
//! assert_eq!(&ext.secret(), b"\x98\x84\xbf\x56\x24\xfa\xdd\x7f\xb2\x80\x4c\xfb\x0c\xb6\xf7\x1f\x28\x9e\x21\x1f\xcf\x0d\xe8\x36\xa3\x84\x17\x57\xda\xd9\x70\xd0");
//! ```

pub mod bip44;
pub mod bip32;
pub mod bip44;

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Error {
Secp256k1(secp256k1::Error),
Secp256k1(k256::elliptic_curve::Error),
InvalidChildNumber,
InvalidDerivationPath,
InvalidExtendedPrivKey,
ZeroChildKey,
}