tetsy_wordlist/
lib.rs

1// Copyright 2015-2017 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy.
3
4// Tetsy is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Tetsy Brain Wallet Generator.
18
19#![warn(missing_docs)]
20
21use std::fmt;
22use std::collections::HashSet;
23use rand::{rngs::OsRng, seq::SliceRandom};
24
25/// The list of dictionary words.
26// the wordlist JSON also happens to be valid Rust syntax for an array constant.
27pub const WORDS: &'static [&'static str] = &include!("../res/wordlist.json");
28
29/// Generate a string which is a random phrase of a number of lowercase words.
30///
31/// `words` is the number of words, chosen from a dictionary of 7,530. An value of
32/// 12 gives 155 bits of entropy (almost saturating address space); 20 gives 258 bits
33/// which is enough to saturate 32-byte key space
34pub fn random_phrase(no_of_words: usize) -> String {
35	let mut rng = OsRng;
36	(0..no_of_words).map(|_| WORDS.choose(&mut rng).unwrap()).fold(String::new(), |mut acc, word| {
37		acc.push_str(" ");
38		acc.push_str(word);
39		acc
40	}).trim_start().to_owned()
41}
42
43/// Phrase Validation Error
44#[derive(Debug, Clone, PartialEq)]
45pub enum Error {
46	/// Phrase is shorter than it was expected.
47	PhraseTooShort(usize),
48	/// Phrase contains a word that doesn't come from our dictionary.
49	WordNotFromDictionary(String),
50}
51
52impl fmt::Display for Error {
53    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
54        match *self {
55            Error::PhraseTooShort(len) => writeln!(fmt, "The phrase is too short ({})", len),
56            Error::WordNotFromDictionary(ref word) => writeln!(fmt, "The word '{}' does not come from the dictionary.", word),
57        }
58    }
59}
60
61/// Validates given phrase and checks if:
62/// 1. All the words are coming from the dictionary.
63/// 2. There are at least `expected_no_of_words` in the phrase.
64pub fn validate_phrase(phrase: &str, expected_no_of_words: usize) -> Result<(), Error> {
65	lazy_static::lazy_static! {
66		static ref WORD_SET: HashSet<&'static str> = WORDS.iter().cloned().collect();
67	}
68
69	let mut len = 0;
70	for word in phrase.split_whitespace() {
71		len += 1;
72		if !WORD_SET.contains(word) {
73			return Err(Error::WordNotFromDictionary(word.into()));
74		}
75	}
76
77	if len < expected_no_of_words {
78		return Err(Error::PhraseTooShort(len));
79	}
80
81	return Ok(());
82}
83
84#[cfg(test)]
85mod tests {
86	use super::{validate_phrase, random_phrase, Error};
87
88	#[test]
89	fn should_produce_right_number_of_words() {
90		let p = random_phrase(10);
91		assert_eq!(p.split(" ").count(), 10);
92	}
93
94	#[test]
95	fn should_not_include_carriage_return() {
96		let p = random_phrase(10);
97		assert!(!p.contains('\r'), "Carriage return should be trimmed.");
98	}
99
100	#[test]
101	fn should_validate_the_phrase() {
102		let p = random_phrase(10);
103
104		assert_eq!(validate_phrase(&p, 10), Ok(()));
105		assert_eq!(validate_phrase(&p, 12), Err(Error::PhraseTooShort(10)));
106		assert_eq!(validate_phrase("xxx", 0), Err(Error::WordNotFromDictionary("xxx".into())));
107	}
108}