Add a generation method that doesn't need rand

This commit is contained in:
Steven Roose 2021-03-24 18:35:02 +00:00
parent ca454327b2
commit 8b3e901b35
No known key found for this signature in database
GPG Key ID: 2F2A88D7F8D68E87
2 changed files with 16 additions and 5 deletions

View File

@ -42,6 +42,7 @@ all-languages = [
[dependencies]
bitcoin_hashes = "0.9.4"
rand_core = "0.4.0"
unicode-normalization = { version = "=0.1.9", optional = true }
rand = { version = "0.6.0", optional = true }

View File

@ -32,6 +32,8 @@
pub extern crate core;
extern crate bitcoin_hashes;
extern crate rand_core;
#[cfg(feature = "std")]
extern crate unicode_normalization;
@ -217,21 +219,29 @@ impl Mnemonic {
Mnemonic::from_entropy_in(Language::English, entropy)
}
/// Generate a new [Mnemonic] in the given language.
/// Generate a new [Mnemonic] in the given language
/// with the given randomness source.
/// For the different supported word counts, see documentation on [Mnemonic].
#[cfg(feature = "rand")]
pub fn generate_in(language: Language, word_count: usize) -> Result<Mnemonic, Error> {
pub fn generate_in_with<R>(rng: &mut R, language: Language, word_count: usize) -> Result<Mnemonic, Error>
where R: rand_core::RngCore + rand_core::CryptoRng,
{
if word_count < MIN_NB_WORDS || word_count % 6 != 0 || word_count > MAX_NB_WORDS {
return Err(Error::BadWordCount(word_count));
}
let entropy_bytes = (word_count / 3) * 4;
let mut rng = rand::thread_rng();
let mut entropy = [0u8; (MAX_NB_WORDS / 3) * 4];
rand::RngCore::fill_bytes(&mut rng, &mut entropy[0..entropy_bytes]);
rand_core::RngCore::fill_bytes(rng, &mut entropy[0..entropy_bytes]);
Mnemonic::from_entropy_in(language, &entropy[0..entropy_bytes])
}
/// Generate a new [Mnemonic] in the given language.
/// For the different supported word counts, see documentation on [Mnemonic].
#[cfg(feature = "rand")]
pub fn generate_in(language: Language, word_count: usize) -> Result<Mnemonic, Error> {
Mnemonic::generate_in_with(&mut rand::thread_rng(), language, word_count)
}
/// Generate a new [Mnemonic] in English.
/// For the different supported word counts, see documentation on [Mnemonic].
#[cfg(feature = "rand")]