aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/new.rs
blob: 825e19f255380d48d54ec0d3818c6bd6dd3a7966 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! Module implementing the `new` subcommand for generating a mnemonic for a new
//! hierarchical deterministic wallet.

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,
    sync::mpsc,
    thread,
};

#[derive(Debug, Parser)]
pub struct Options {
    /// The number of words for the mnemonic phrase.
    #[clap(short = 'n', long, default_value_t = 12)]
    length: usize,

    /// 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>,

    /// The number of parallel threads to use when searching for a vanity
    /// address. Defaults to the number of CPUs.
    #[clap(short = 'j', long, default_value_t = num_cpus::get())]
    vanity_threads: usize,
}

#[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 random_mnemonic = {
        let language = options.language;
        let length = options.length;
        move || Mnemonic::random(language, length)
    };

    let mnemonic = if let Some(prefix) = options.vanity_prefix {
        let vanity = {
            let prefix = prefix.clone();
            let mut account = AccountOptions {
                mnemonic: random_mnemonic()?,
                password: options.vanity_password,
                account_index: options.vanity_account_index,
                hd_path: options.vanity_hd_path,
            };
            move || -> Result<Mnemonic> {
                while !prefix.matches(account.private_key()?.address()) {
                    account.mnemonic = random_mnemonic()?;
                }
                Ok(account.mnemonic)
            }
        };

        if options.vanity_threads > 0 {
            let (sender, receiver) = mpsc::channel();
            let _threads = (0..options.vanity_threads)
                .map(|_| {
                    thread::spawn({
                        let vanity = vanity.clone();
                        let result = sender.clone();
                        move || {
                            let _ = result.send(vanity());
                        }
                    })
                })
                .collect::<Vec<_>>();

            receiver.recv().unwrap()?
        } else {
            vanity()?
        }
    } else {
        random_mnemonic()?
    };

    println!("{mnemonic}");
    Ok(())
}