aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock25
-rw-r--r--Cargo.toml3
-rw-r--r--src/cmd.rs21
-rw-r--r--src/cmd/sign.rs48
-rw-r--r--src/hdk.rs29
-rw-r--r--src/hdk/path.rs25
-rw-r--r--src/main.rs2
-rw-r--r--src/mnemonic.rs82
8 files changed, 189 insertions, 46 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 18eca41..643c9fc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -123,6 +123,7 @@ dependencies = [
"sha2",
"sha3",
"structopt",
+ "unicode-normalization",
]
[[package]]
@@ -340,12 +341,36 @@ dependencies = [
]
[[package]]
+name = "tinyvec"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf8dbc19eb42fba10e8feaaec282fb50e2c14b2726d6301dbfeed0f73306a6f"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
+
+[[package]]
name = "typenum"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33"
[[package]]
+name = "unicode-normalization"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a13e63ab62dbe32aeee58d1c5408d35c36c392bba5d9d3142287219721afe606"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
name = "unicode-segmentation"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index 929dc9a..8839577 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,12 +8,13 @@ license = "GPL-3.0-or-later"
[dependencies]
anyhow = "1"
hex = "0.4"
-hmac = "0.10"
+hmac = { version = "0.10", features = ["std"] }
pbkdf2 = { version = "0.6", default-features = false }
secp256k1 = { version = "0.19", features = ["recovery"] }
sha2 = "0.9"
sha3 = "0.9"
structopt = "0.3"
+unicode-normalization = "0.1"
[dev-dependencies]
hex-literal = "0.3"
diff --git a/src/cmd.rs b/src/cmd.rs
index b648732..9497a96 100644
--- a/src/cmd.rs
+++ b/src/cmd.rs
@@ -2,6 +2,7 @@
pub mod address;
pub mod new;
+pub mod sign;
use crate::{account::PrivateKey, hdk, mnemonic::Mnemonic};
use anyhow::Result;
@@ -14,16 +15,30 @@ struct AccountOptions {
#[structopt(short, long, env)]
mnemonic: Mnemonic,
+ /// The password to use with the mnemonic phrase for salting the seed used
+ /// for the HD wallet.
+ #[structopt(long, env, default_value)]
+ password: String,
+
/// The BIP-44 account index for deriving a private from the mnemonic seed
- /// phrase.
+ /// phrase. The derived key will use the path "m/44'/60'/0'/0/{index}".
#[structopt(long, env, default_value = "0")]
account_index: usize,
+
+ /// Manually specified HD path for deriving the account key. This option can
+ /// not be used in conjunction with the "--account-index" option.
+ #[structopt(long, env, conflicts_with = "account-index")]
+ hd_path: Option<String>,
}
impl AccountOptions {
/// Returns the private key for the specified account options.
pub fn private_key(&self) -> Result<PrivateKey> {
- let path = format!("m/44'/60'/0'/0/{}", self.account_index).parse()?;
- hdk::derive(&self.mnemonic, &path)
+ let seed = self.mnemonic.seed(&self.password);
+ let path = match &self.hd_path {
+ None => format!("m/44'/60'/0'/0/{}", self.account_index).parse(),
+ Some(hd_path) => hd_path.parse(),
+ }?;
+ hdk::derive(seed, &path)
}
}
diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs
new file mode 100644
index 0000000..59095ae
--- /dev/null
+++ b/src/cmd/sign.rs
@@ -0,0 +1,48 @@
+//! Module implementing the `address` subcommand for displaying the public
+//! address for corresponding account.
+
+use crate::{cmd::AccountOptions, hash};
+use anyhow::{Context as _, Result};
+use std::convert::TryInto;
+use structopt::StructOpt;
+
+#[derive(Debug, StructOpt)]
+#[structopt(about = "print account public address")]
+pub struct Options {
+ #[structopt(flatten)]
+ account: AccountOptions,
+
+ /// The message should be Keccak-256 hashed for signing.
+ #[structopt(short, long)]
+ hash_message: bool,
+
+ /// The 32 byte message or binary data to sign specified as a hexadecimal
+ /// string. If "hash-data" is not specified, then the specified value must
+ /// be exactly 32 bytes long.
+ #[structopt(name = "MESSAGE", parse(try_from_str = permissive_hex))]
+ message: Box<[u8]>,
+}
+
+pub fn run(options: Options) -> Result<()> {
+ let message = if options.hash_message {
+ hash::keccak256(&options.message)
+ } else {
+ options
+ .message
+ .as_ref()
+ .try_into()
+ .context("message for signing must be exactly 32 bytes long or hashed")?
+ };
+ let signature = options.account.private_key()?.sign(message);
+ println!("{}", signature);
+ Ok(())
+}
+
+fn permissive_hex(s: &str) -> Result<Box<[u8]>> {
+ let trimmed = s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
+ let hex_string = trimmed.strip_prefix("0x").unwrap_or(&trimmed);
+ let bytes = hex::decode(&hex_string)?;
+ // NOTE: Use a boxed slice instead of a `Vec` as the former has special
+ // scemantics with `structopt`.
+ Ok(bytes.into_boxed_slice())
+}
diff --git a/src/hdk.rs b/src/hdk.rs
index 922bb68..ee1c942 100644
--- a/src/hdk.rs
+++ b/src/hdk.rs
@@ -3,8 +3,8 @@
mod path;
pub use self::path::{Component, Path};
-use crate::{account::PrivateKey, mnemonic::Mnemonic};
-use anyhow::{anyhow, Result};
+use crate::account::PrivateKey;
+use anyhow::{Context as _, Result};
use hmac::{Hmac, Mac as _, NewMac as _};
use secp256k1::{
key::{PublicKey, SecretKey},
@@ -16,21 +16,18 @@ use sha2::Sha512;
const HARDENED: u32 = 0x80000000;
/// Creates a new extended private key from a seed.
-pub fn derive(mnemonic: &Mnemonic, path: &Path) -> Result<PrivateKey> {
+pub fn derive(seed: impl AsRef<[u8]>, path: &Path) -> Result<PrivateKey> {
let mut extended_key = {
- let mut hmac =
- Hmac::<Sha512>::new_varkey(b"Bitcoin seed").map_err(|_| anyhow!("invalid HMAC key"))?;
- hmac.update(&mnemonic.seed());
+ let mut hmac = Hmac::<Sha512>::new_varkey(b"Bitcoin seed")?;
+ hmac.update(seed.as_ref());
hmac.finalize().into_bytes()
};
let secp = Secp256k1::signing_only();
- for component in path.components() {
+ for (i, component) in path.components().enumerate() {
let (secret, chain_code) = extended_key.split_at(32);
- let mut hmac: Hmac<Sha512> =
- Hmac::<Sha512>::new_varkey(chain_code).map_err(|_| anyhow!("invalid chain code"))?;
-
+ let mut hmac: Hmac<Sha512> = Hmac::<Sha512>::new_varkey(chain_code)?;
let value = match component {
Component::Hardened(value) => {
hmac.update(&[0]);
@@ -45,8 +42,14 @@ pub fn derive(mnemonic: &Mnemonic, path: &Path) -> Result<PrivateKey> {
hmac.update(&value.to_be_bytes());
let mut child_key = hmac.finalize().into_bytes();
- let mut child_secret = SecretKey::from_slice(&child_key[..32])?;
- child_secret.add_assign(secret)?;
+ let child_secret = SecretKey::from_slice(&child_key[..32])
+ .and_then(|mut key| {
+ key.add_assign(secret)?;
+ Ok(key)
+ })
+ .with_context(|| {
+ format!("path '{}' component #{} yields invalid child key", path, i)
+ })?;
child_key[..32].copy_from_slice(child_secret.as_ref());
extended_key = child_key
@@ -77,7 +80,7 @@ mod tests {
let mnemonic = GANACHE_DETERMINISTIC_MNEMONIC.parse::<Mnemonic>().unwrap();
let path = "m/44'/60'/0'/0/0".parse::<Path>().unwrap();
- let account = derive(&mnemonic, &path).unwrap();
+ let account = derive(mnemonic.seed(""), &path).unwrap();
assert_eq!(
account.address(),
Address(hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")),
diff --git a/src/hdk/path.rs b/src/hdk/path.rs
index f67446a..3d7c0a3 100644
--- a/src/hdk/path.rs
+++ b/src/hdk/path.rs
@@ -1,7 +1,10 @@
//! Module implementing parsing for BIP-0032 HD paths used for key derivation.
use anyhow::{anyhow, Context as _, Result};
-use std::str::FromStr;
+use std::{
+ fmt::{self, Display, Formatter},
+ str::FromStr,
+};
/// A parsed hierarchical derivation path.
#[derive(Debug)]
@@ -16,6 +19,17 @@ impl Path {
}
}
+impl Display for Path {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.write_str("m")?;
+ for component in self.components() {
+ write!(f, "/{}", component)?;
+ }
+
+ Ok(())
+ }
+}
+
impl FromStr for Path {
type Err = anyhow::Error;
@@ -40,6 +54,15 @@ pub enum Component {
Normal(u32),
}
+impl Display for Component {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ match self {
+ Self::Hardened(value) => write!(f, "{}'", value),
+ Self::Normal(value) => write!(f, "{}", value),
+ }
+ }
+}
+
impl FromStr for Component {
type Err = anyhow::Error;
diff --git a/src/main.rs b/src/main.rs
index fa6e576..7122b40 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -17,12 +17,14 @@ use structopt::StructOpt;
enum Options {
Address(address::Options),
New(new::Options),
+ Sign(sign::Options),
}
fn main() {
if let Err(err) = match Options::from_args() {
Options::Address(options) => address::run(options),
Options::New(options) => new::run(options),
+ Options::Sign(options) => sign::run(options),
} {
if cfg!(debug_assertions) {
eprintln!("ERROR: {:?}", err);
diff --git a/src/mnemonic.rs b/src/mnemonic.rs
index bb32d3a..836ceee 100644
--- a/src/mnemonic.rs
+++ b/src/mnemonic.rs
@@ -12,8 +12,10 @@ use std::{
convert::TryInto,
fmt::{self, Display, Formatter},
mem,
+ ops::Deref,
str::FromStr,
};
+use unicode_normalization::UnicodeNormalization as _;
/// A seed generated from a BIP-0039 mnemonic used for an HD wallet.
#[derive(Clone, Debug)]
@@ -140,22 +142,19 @@ impl Mnemonic {
}
/// Gets the PBKDF2 stretched binary seed for this mnemonic.
- pub fn seed(&self) -> [u8; 64] {
+ pub fn seed(&self, password: impl AsRef<str>) -> Seed {
const ROUNDS: u32 = 2048;
- // TODO(nlordell): Support mnemonic passwords. This requires the bytes
- // to be NFKD normalized.
- const PASSWORD: &str = "";
let mut buf = [0u8; 64];
- let salt = format!("mnemonic{}", PASSWORD);
+ let salt = format!("mnemonic{}", password.as_ref());
pbkdf2::pbkdf2::<Hmac<Sha512>>(
self.to_phrase().as_bytes(),
- salt.as_bytes(),
+ salt.nfkd().to_string().as_bytes(),
ROUNDS,
&mut buf,
);
- buf
+ Seed(buf)
}
}
@@ -173,6 +172,24 @@ impl FromStr for Mnemonic {
}
}
+/// A 64-byte seed derived from a BIP-0039 mnemonic.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Seed([u8; 64]);
+
+impl AsRef<[u8]> for Seed {
+ fn as_ref(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl Deref for Seed {
+ type Target = [u8; 64];
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
fn mnemonic_to_byte_length(len: usize) -> Result<usize> {
ensure!(matches!(len, 12..=24), "invalid mnemonic length {}", len);
@@ -206,16 +223,30 @@ mod tests {
#[test]
fn mnemonic_phrases() {
- for &(bytes, phrase) in &[
+ for &(bytes, phrase, password, seed) in &[
(
&hex!("00000000000000000000000000000000")[..],
"abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon about",
+ "TREZOR",
+ hex!(
+ "c552 57c3 60c0 7c72 029a ebc1 b53c 05ed
+ 0362 ada3 8ead 3e3e 9efa 3708 e534 9553
+ 1f09 a698 7599 d182 64c1 e1c9 2f2c f141
+ 630c 7a3c 4ab7 c81b 2f00 1698 e746 3b04"
+ ),
),
(
&hex!("92903465e029df56cab416a53b015396")[..],
"myth like bonus scare over problem \
client lizard pioneer submit female collect",
+ "",
+ hex!(
+ "15e7 bbc6 ac54 a721 ad44 0f8e f7d1 fa7c
+ 4f77 ae5e c71e 2418 7649 e9d2 2802 2655
+ b9e6 fb36 59f8 e4b2 274a c3b1 955b f9e5
+ 8f15 0492 c44e 7aa1 6109 5ba0 ad92 6e9e"
+ ),
),
(
&hex!("0000000000000000000000000000000000000000000000000000000000000000")[..],
@@ -223,6 +254,13 @@ mod tests {
abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon art",
+ "TREZOR",
+ hex!(
+ "bda8 5446 c684 1370 7090 a520 22ed d26a
+ 1c94 6229 5029 f2e6 0cd7 c4f2 bbd3 0971
+ 70af 7a4d 7324 5caf a9c3 cca8 d561 a7c3
+ de6f 5d4a 10be 8ed2 a5e6 08d6 8f92 fcc8"
+ ),
),
(
&hex!("f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f")[..],
@@ -230,31 +268,19 @@ mod tests {
warrior heavy shoot primary clutch crush \
open amazing screen patrol group space \
point ten exist slush involve unfold",
+ "TREZOR",
+ hex!(
+ "01f5 bced 59de c48e 362f 2c45 b5de 68b9
+ fd6c 92c6 634f 44d6 d40a ab69 0565 06f0
+ e355 24a5 1803 4ddc 1192 e1da cd32 c1ed
+ 3eaa 3c3b 131c 88ed 8e7e 54c4 9a5d 0998"
+ ),
),
] {
let mnemonic = Mnemonic::from_phrase(phrase).unwrap();
assert_eq!(mnemonic.as_bytes(), bytes);
+ assert_eq!(*mnemonic.seed(password), seed);
assert_eq!(mnemonic.to_phrase(), phrase);
}
}
-
- #[test]
- fn mnemonic_seed() {
- let seed = Mnemonic::from_str(
- "myth like bonus scare over problem \
- client lizard pioneer submit female collect",
- )
- .unwrap()
- .seed();
-
- assert_eq!(
- seed,
- hex!(
- "15e7bbc6ac54a721ad440f8ef7d1fa7c
- 4f77ae5ec71e24187649e9d228022655
- b9e6fb3659f8e4b2274ac3b1955bf9e5
- 8f150492c44e7aa161095ba0ad926e9e"
- )
- );
- }
}