diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-28 10:48:42 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-28 10:48:42 +0100 |
| commit | bd7a6880f5dce74fd154f593a5a5f7034affeee4 (patch) | |
| tree | 09fc799b239632a5ebe854d62cb2c7c3574d55ac /src | |
| parent | cd7beb199e654825cb1b3ab6ac85b805ffdb7871 (diff) | |
started implementing mnemonic word lists
Diffstat (limited to 'src')
| -rw-r--r-- | src/cmd.rs | 1 | ||||
| -rw-r--r-- | src/cmd/new.rs | 11 | ||||
| -rw-r--r-- | src/main.rs | 19 | ||||
| -rw-r--r-- | src/mnemonic.rs | 6 | ||||
| -rw-r--r-- | src/mnemonic/language.rs | 60 | ||||
| -rw-r--r-- | src/mnemonic/wordlist.rs | 67 |
6 files changed, 163 insertions, 1 deletions
diff --git a/src/cmd.rs b/src/cmd.rs new file mode 100644 index 0000000..9d52a2b --- /dev/null +++ b/src/cmd.rs @@ -0,0 +1 @@ +pub mod new; diff --git a/src/cmd/new.rs b/src/cmd/new.rs new file mode 100644 index 0000000..5a2c6e4 --- /dev/null +++ b/src/cmd/new.rs @@ -0,0 +1,11 @@ +//! Module implementing the `new` command for generating a mnemonic for a new +//! hierarchical deterministic wallet. + +use crate::mnemonic::Language; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt(about = "generate a new HD wallet mnemonic")] +pub struct Options { + language: Language, +} diff --git a/src/main.rs b/src/main.rs index e7a11a9..74b1bc5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,20 @@ +mod cmd; +mod mnemonic; + +use crate::cmd::*; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt( + name = "hdwallet", + about = "Hierarchical deterministic wallet for Ethereum", +)] +enum Options { + New(new::Options), +} + fn main() { - println!("Hello, world!"); + match Options::from_args() { + Options::New(options) => new::run(options), + } } diff --git a/src/mnemonic.rs b/src/mnemonic.rs new file mode 100644 index 0000000..61663b4 --- /dev/null +++ b/src/mnemonic.rs @@ -0,0 +1,6 @@ +//! BIP-0039 mnemonic phrase implementation. + +mod language; +mod wordlist; + +pub use self::language::Language; diff --git a/src/mnemonic/language.rs b/src/mnemonic/language.rs new file mode 100644 index 0000000..87950d8 --- /dev/null +++ b/src/mnemonic/language.rs @@ -0,0 +1,60 @@ +//! Mnemonic language for selecting word lists. + +use anyhow::{bail, Result}; +use std::{ + fmt::{self, Display, Formatter}, + str::FromStr, +}; + +/// The mnemonic langage used to select the word list. +#[derive(Clone, Copy, Debug)] +pub enum Language { + English, + // TODO(nlordell): Support more languages. Note that this is not necessarily + // trivial as some have specific considerations (like 'ñ' being equivalent + // to 'n' in Spanish, and Japanese using '\u{3000}` for spaces). +} + +impl Language { + /// Splits a mnemonic phrase into its words, returning the detected language + /// and a vector of **normalized** words. + pub fn split(phrase: impl AsRef<str>) -> Result<(Self, Vec<String>)> { + // TODO(nlordell): A lot to do here... + Ok(( + Language::English, + phrase + .as_ref() + .trim() + .split_whitespace() + .filter(|word| !word.is_empty()) + .map(|word| word.to_lowercase()) + .collect(), + )) + } +} + +impl Default for Language { + fn default() -> Self { + // TODO(nlordell): Read the default language from the system locale. + Language::English + } +} + +impl Display for Language { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.write_str(match self { + Language::English => "english", + }) + } +} + +impl FromStr for Language { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result<Self> { + Ok(match s.to_lowercase().as_str() { + "english" => Language::English, + _ => bail!("unsupported language '{}'", s), + }) + } +} diff --git a/src/mnemonic/wordlist.rs b/src/mnemonic/wordlist.rs new file mode 100644 index 0000000..b2e2383 --- /dev/null +++ b/src/mnemonic/wordlist.rs @@ -0,0 +1,67 @@ +//! Module containing the embedded BIP-0039 word lists. + +use std::borrow::Cow; + +/// A parsed word list. +pub struct Wordlist<'a>(Vec<Cow<'a, str>>); + +/// The number of words in a list, as defined in BIP-0039. +pub const WORD_COUNT: usize = 1024; + +impl<'a> Wordlist<'a> { + /// Parses a list of newline-separated words. + fn parse(words: &'a str) -> Wordlist<'a> { + let words = words + .trim() + .split('\n') + .map(|word| { + // TODO(nlordell): The words here need to be normalized for its + // language, like converting 'ñ' to 'n' in Spanish. + Cow::Borrowed(word.trim()) + }) + .collect::<Vec<_>>(); + + debug_assert_eq!(words.len(), WORD_COUNT); + debug_assert!(words + .iter() + .all(|word| word.chars().all(char::is_lowercase))); + debug_assert!(words.windows(2).all(|pair| pair[0] < pair[1])); + + Wordlist(words) + } + + /// Searches the word list for the specified word returning its numerical + /// value representing its index in the list. This method returns `None` + /// if the word does not belong to the list. + pub fn search(&self, word: impl AsRef<str>) -> Option<usize> { + // TODO(nlordell): It is possible to be generous here and fix common + // spelling mistakes as well as only consider the first letters of the + // word as long as it is unique. + self.0 + .binary_search_by_key(&word.as_ref(), |word| &word) + .ok() + } + + /// Returns the word for the specified index. + /// + /// # Panics + /// + /// This method panics if the index is out of range for the BIP-0039 word + /// list: it must be less than `WORD_COUNT` or `1024`. + pub fn word(&'a self, index: usize) -> &'a str { + assert!(index < WORD_COUNT, "invalid word index"); + &self.0[index] + } +} + +macro_rules! define { + ($( + $(#[$attr:meta])* + $vis:vis $lang:ident = $f:expr; + )*) => {$( + $(#[$attr])* + $vis fn $lang() -> &'static Wordlist; + )*}; +} + +define!(); |
