aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorNicholas Rodrigues Lordello <[email protected]>2023-10-22 17:56:01 +0000
committerNicholas Rodrigues Lordello <[email protected]>2023-10-22 17:56:01 +0000
commit1388ce8c4c2215ed029414d71833eab4b9bc8dc2 (patch)
tree93bbd822db9f7ddcf548f65e23fdbdf39db4d136 /src
parentca758736f76d9c32d7e5df44e270bf2879a1b86c (diff)
Add Support for Genereting Mnemonic for Vanity Address
Diffstat (limited to 'src')
-rw-r--r--src/cmd.rs13
-rw-r--r--src/cmd/new.rs109
-rw-r--r--src/hdk.rs6
-rw-r--r--src/hdk/path.rs7
4 files changed, 120 insertions, 15 deletions
diff --git a/src/cmd.rs b/src/cmd.rs
index def1ec2..31add32 100644
--- a/src/cmd.rs
+++ b/src/cmd.rs
@@ -29,8 +29,8 @@ struct AccountOptions {
#[clap(long, env, hide_env_values = true, default_value_t)]
password: String,
- /// The BIP-44 account index for deriving a private from the mnemonic seed
- /// phrase. The derived key will use the path "m/44'/60'/0'/0/{index}".
+ /// The BIP-44 account index for deriving a private key from the mnemonic
+ /// seed phrase. The derived key will use the path "m/44'/60'/0'/0/{index}".
#[clap(long, env, default_value_t = 0)]
account_index: usize,
@@ -44,10 +44,11 @@ impl AccountOptions {
/// Returns the private key for the specified account options.
pub fn private_key(&self) -> Result<PrivateKey> {
let seed = self.mnemonic.seed(&self.password);
- match &self.hd_path {
- None => hdk::derive_index(seed, self.account_index),
- Some(hd_path) => hdk::derive(seed, &hd_path.parse()?),
- }
+ let path = match &self.hd_path {
+ None => hdk::Path::for_index(self.account_index),
+ Some(hd_path) => hd_path.parse()?,
+ };
+ hdk::derive(seed, &path)
}
}
diff --git a/src/cmd/new.rs b/src/cmd/new.rs
index 1c73bb8..29d7c88 100644
--- a/src/cmd/new.rs
+++ b/src/cmd/new.rs
@@ -1,9 +1,15 @@
//! Module implementing the `new` subcommand for generating a mnemonic for a new
//! hierarchical deterministic wallet.
-use anyhow::Result;
+use crate::cmd::AccountOptions;
+use anyhow::{Context, Result};
use clap::Parser;
+use ethaddr::Address;
use hdwallet::mnemonic::{Language, Mnemonic};
+use std::{
+ fmt::{self, Display, Formatter},
+ str::FromStr,
+};
#[derive(Debug, Parser)]
pub struct Options {
@@ -14,10 +20,109 @@ pub struct Options {
/// The language to generate the mnemonic for.
#[clap(short, long, default_value_t)]
language: Language,
+
+ /// Choose a vanity prefix for a public for the new mnemonic.
+ #[clap(long)]
+ vanity_prefix: Option<Prefix>,
+
+ /// The password to use of the account whose private key should match the
+ /// vanity prefix specifed in "--vanity-prefix".
+ #[clap(long, default_value_t)]
+ vanity_password: String,
+
+ /// The BIP-44 account index that should of the account whose private key
+ /// should match the vanity prefix specifed in "--vanity-prefix".
+ #[clap(long, default_value_t = 0)]
+ vanity_account_index: usize,
+
+ /// Manually specified HD path for deriving the account key that should
+ /// match the vanity prefix. This option can not be used in conjunction
+ /// with the "--vanity-3account-index" option.
+ #[clap(long, conflicts_with = "vanity_account_index")]
+ vanity_hd_path: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+struct Prefix {
+ bytes: Vec<u8>,
+ nibble: Option<u8>,
+}
+
+impl Prefix {
+ fn matches(&self, addr: Address) -> bool {
+ let start = || addr.starts_with(&self.bytes);
+ let end = || {
+ if let Some(nibble) = self.nibble {
+ addr.get(self.bytes.len())
+ .map(|last| last >> 4 == nibble)
+ .unwrap_or(false)
+ } else {
+ true
+ }
+ };
+
+ start() && end()
+ }
+}
+
+impl Display for Prefix {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.write_str("0x")?;
+ for byte in &self.bytes {
+ write!(f, "{byte:02x}")?;
+ }
+ if let Some(nibble) = self.nibble {
+ write!(f, "{nibble:x}")?;
+ }
+ Ok(())
+ }
+}
+
+impl FromStr for Prefix {
+ type Err = anyhow::Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let s = s.strip_prefix("0x").context("missing '0x' prefix")?;
+
+ let parse_nibble = |n: u8| match n {
+ b'0'..=b'9' => Ok(n - b'0'),
+ b'a'..=b'f' => Ok(n - b'a' + 0xa),
+ b'A'..=b'F' => Ok(n - b'a' + 0xa),
+ _ => anyhow::bail!("invalid hex digit {n:#x}"),
+ };
+
+ let mut bytes = vec![0; s.len() / 2];
+ let mut nibble = None;
+ for (i, c) in s.as_bytes().chunks(2).enumerate() {
+ match c {
+ [hi, lo] => bytes[i] = (parse_nibble(*hi)? << 4) + parse_nibble(*lo)?,
+ [ni] => nibble = Some(parse_nibble(*ni)?),
+ _ => unreachable!(),
+ }
+ }
+
+ Ok(Self { bytes, nibble })
+ }
}
pub fn run(options: Options) -> Result<()> {
- let mnemonic = Mnemonic::random(options.language, options.length)?;
+ let random_mnemonic = || Mnemonic::random(options.language, options.length);
+ let mnemonic = if let Some(prefix) = options.vanity_prefix {
+ let mut account = AccountOptions {
+ mnemonic: random_mnemonic()?,
+ password: options.vanity_password,
+ account_index: options.vanity_account_index,
+ hd_path: options.vanity_hd_path,
+ };
+ while !prefix.matches(account.private_key()?.address()) {
+ account.mnemonic = random_mnemonic()?;
+ }
+
+ account.mnemonic
+ } else {
+ random_mnemonic()?
+ };
+
println!("{mnemonic}");
Ok(())
}
diff --git a/src/hdk.rs b/src/hdk.rs
index c058fba..b5d646e 100644
--- a/src/hdk.rs
+++ b/src/hdk.rs
@@ -12,12 +12,6 @@ use sha2::Sha512;
/// A value indicating a path component is hardened.
const HARDENED: u32 = 0x8000_0000;
-/// Creates a new extended private key for an account index using the standard
-/// Ethereum HD path.
-pub fn derive_index(seed: impl AsRef<[u8]>, account_index: usize) -> Result<PrivateKey> {
- derive(seed, &format!("m/44'/60'/0'/0/{account_index}").parse()?)
-}
-
/// Creates a new extended private key from a seed.
pub fn derive(seed: impl AsRef<[u8]>, path: &Path) -> Result<PrivateKey> {
derive_slice(seed.as_ref(), path)
diff --git a/src/hdk/path.rs b/src/hdk/path.rs
index 0d05110..333381c 100644
--- a/src/hdk/path.rs
+++ b/src/hdk/path.rs
@@ -13,7 +13,12 @@ pub struct Path {
}
impl Path {
- /// Returns an iterator
+ /// Creates the default Ethereum HD path for the specified account index.
+ pub fn for_index(index: usize) -> Self {
+ format!("m/44'/60'/0'/0/{index}").parse().unwrap()
+ }
+
+ /// Returns an iterator over the path components.
pub fn components(&self) -> impl Iterator<Item = Component> + '_ {
self.components.iter().copied()
}