Skip to content

Commit

Permalink
Perf and Rust idiomatic stuff (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
maciejhirsz authored Oct 17, 2018
1 parent ba0a207 commit 22bc5ad
Show file tree
Hide file tree
Showing 9 changed files with 241 additions and 193 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ path = "src/lib.rs"
[dependencies]
error-chain ="^0.11.0"
bitreader = "^0.3.0"
bit-vec = "^0.4.3"
ring = "^0.12"
rand = "^0.3.15"
data-encoding = "^2.0"
Expand Down
24 changes: 24 additions & 0 deletions benches/validate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#![feature(test)]

extern crate test;
extern crate bip39;

use test::Bencher;

use bip39::{Mnemonic, MnemonicType, Language};

#[bench]
fn validate(b: &mut Bencher) {
let phrase = "silly laptop awake length nature thunder category claim reveal supply attitude drip";

b.iter(|| {
let _ = Mnemonic::validate(phrase, Language::English);
});
}

#[bench]
fn new_mnemonic(b: &mut Bencher) {
b.iter(|| {
let _ = Mnemonic::new(MnemonicType::Type12Words, Language::English, "");
})
}
19 changes: 8 additions & 11 deletions src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,33 @@
//!

use ring::digest::{self, digest};
use ring::digest::{self, digest, Digest};
use ring::pbkdf2;

extern crate rand;
use self::rand::{OsRng, Rng};

use ::error::Error;
use ::error::Result;

static PBKDF2_ROUNDS: u32 = 2048;
static PBKDF2_BYTES: usize = 64;


/// SHA256 helper function, internal to the crate
///
pub(crate) fn sha256(input: &[u8]) -> Vec<u8> {
pub(crate) fn sha256(input: &[u8]) -> Digest {

static DIGEST_ALG: &'static digest::Algorithm = &digest::SHA256;

let hash = digest(DIGEST_ALG, input);

hash.as_ref().to_vec()
digest(DIGEST_ALG, input)
}

/// Random byte generator, used to create new mnemonics
///
pub(crate) fn gen_random_bytes(byte_length: usize) -> Result<Vec<u8>, Error> {
pub(crate) fn gen_random_bytes(byte_length: usize) -> Result<Vec<u8>> {

let mut rng = OsRng::new()?;
let entropy = rng.gen_iter::<u8>().take(byte_length).collect::<Vec<u8>>();
let entropy = rng.gen_iter().take(byte_length).collect();

Ok(entropy)
}
Expand All @@ -43,9 +41,8 @@ pub(crate) fn gen_random_bytes(byte_length: usize) -> Result<Vec<u8>, Error> {
///
/// [Mnemonic]: ../mnemonic/struct.Mnemonic.html
/// [Seed]: ../seed/struct.Seed.html
///
pub(crate) fn pbkdf2(input: &[u8],
salt: String) -> Vec<u8> {
///
pub(crate) fn pbkdf2(input: &[u8], salt: &str) -> Vec<u8> {

let mut seed = vec![0u8; PBKDF2_BYTES];

Expand Down
92 changes: 41 additions & 51 deletions src/language.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,30 @@
use ::error::{Error, ErrorKind};
use ::error::{ErrorKind, Result};
use std::collections::HashMap;

mod lazy {
use std::collections::HashMap;

/// lazy generation of the word list
fn gen_wordlist(lang_words: &str) -> Vec<String> {
use super::HashMap;

lang_words.split_whitespace()
.map(|s| s.into())
.collect()
}

/// lazy generation of the word map
fn gen_wordmap(word_list: &Vec<String>) -> HashMap<String, u16> {

let mut word_map: HashMap<String, u16> = HashMap::new();
for (i, item) in word_list.into_iter().enumerate() {
word_map.insert(item.to_owned(), i as u16);
}
/// lazy generation of the word list
fn gen_wordlist(lang_words: &str) -> Vec<&str> {
lang_words.split_whitespace().collect()
}

word_map
}
/// lazy generation of the word map
fn gen_wordmap(wordlist: &[&'static str]) -> HashMap<&'static str, u16> {
wordlist
.iter()
.enumerate()
.map(|(i, item)| (*item, i as u16))
.collect()
}

static BIP39_WORDLIST_ENGLISH: &'static str = include_str!("bip39_english.txt");
static BIP39_WORDLIST_ENGLISH: &str = include_str!("bip39_english.txt");

lazy_static! {
pub static ref VEC_BIP39_WORDLIST_ENGLISH: Vec<String> = { gen_wordlist(BIP39_WORDLIST_ENGLISH) };
}
lazy_static! {
pub static ref VEC_BIP39_WORDLIST_ENGLISH: Vec<&'static str> = gen_wordlist(BIP39_WORDLIST_ENGLISH);

lazy_static! {
pub static ref HASHMAP_BIP39_WORDMAP_ENGLISH: HashMap<String, u16> = { gen_wordmap(&VEC_BIP39_WORDLIST_ENGLISH) };
}
pub static ref HASHMAP_BIP39_WORDMAP_ENGLISH: HashMap<&'static str, u16> = gen_wordmap(&VEC_BIP39_WORDLIST_ENGLISH);
}
}

/// The language determines which words will be used in a mnemonic phrase, but also indirectly
Expand Down Expand Up @@ -60,45 +53,42 @@ impl Language {
///
/// ```
/// [Language]: ../language/struct.Language.html
pub fn for_locale<S>(locale: S) -> Result<Language, Error> where S: Into<String> {

let l = locale.into();

let lang = match &*l {
pub fn for_locale(locale: &str) -> Result<Language> {
let lang = match locale {
"en_US.UTF-8" => Language::English,
"en_GB.UTF-8" => Language::English,

_ => { return Err(ErrorKind::LanguageUnavailable.into()) }
_ => bail!(ErrorKind::LanguageUnavailable)
};

Ok(lang)
}

/// Get the word list for this language
pub fn get_wordlist(&self) -> &'static Vec<String> {
/// Get the word list for this language
pub fn get_wordlist(&self) -> &'static [&'static str] {

match *self {
Language::English => &lazy::VEC_BIP39_WORDLIST_ENGLISH
match *self {
Language::English => &*lazy::VEC_BIP39_WORDLIST_ENGLISH
}
}
}

/// Get a [`HashMap`][HashMap] that allows word -> index lookups in the word list
///
/// The index of an individual word in the word list is used as the binary value of that word
/// when the phrase is turned into a [`Seed`][Seed].
///
/// [HashMap]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
/// [Seed]: ../seed/struct.Seed.html
pub fn get_wordmap(&self) -> &'static HashMap<String, u16> {
/// Get a [`HashMap`][HashMap] that allows word -> index lookups in the word list
///
/// The index of an individual word in the word list is used as the binary value of that word
/// when the phrase is turned into a [`Seed`][Seed].
///
/// [HashMap]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
/// [Seed]: ../seed/struct.Seed.html
pub fn get_wordmap(&self) -> &'static HashMap<&'static str, u16> {

match *self {
Language::English => &lazy::HASHMAP_BIP39_WORDMAP_ENGLISH
match *self {
Language::English => &*lazy::HASHMAP_BIP39_WORDMAP_ENGLISH
}
}
}
}

impl Default for Language {
fn default() -> Language {
Language::English
}
fn default() -> Language {
Language::English
}
}
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
#[macro_use] extern crate lazy_static;
extern crate data_encoding;
extern crate bitreader;
extern crate bit_vec;
extern crate ring;

mod mnemonic;
Expand Down
Loading

0 comments on commit 22bc5ad

Please sign in to comment.