parity_bip39/
lib.rs

1// Rust Bitcoin Library
2// Written in 2020 by
3//	 Steven Roose <steven@stevenroose.org>
4// To the extent possible under law, the author(s) have dedicated all
5// copyright and related and neighboring rights to this software to
6// the public domain worldwide. This software is distributed without
7// any warranty.
8//
9// You should have received a copy of the CC0 Public Domain Dedication
10// along with this software.
11// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
12//
13
14//! # BIP39 Mnemonic Codes
15//!
16//! Library crate implementing [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)
17//!
18
19#![deny(non_upper_case_globals)]
20#![deny(non_camel_case_types)]
21#![deny(non_snake_case)]
22#![deny(unused_mut)]
23#![deny(dead_code)]
24#![deny(unused_imports)]
25#![deny(missing_docs)]
26#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
27#![cfg_attr(docsrs, feature(doc_auto_cfg))]
28
29#[cfg(any(test, feature = "std"))]
30pub extern crate core;
31
32#[cfg(feature = "alloc")]
33extern crate alloc;
34
35extern crate bitcoin_hashes;
36
37#[cfg(feature = "unicode-normalization")]
38extern crate unicode_normalization;
39
40#[cfg(feature = "rand")]
41pub extern crate crate_rand as rand;
42#[cfg(feature = "rand_core")]
43pub extern crate rand_core;
44#[cfg(feature = "serde")]
45pub extern crate serde;
46
47#[cfg(feature = "alloc")]
48use alloc::{borrow::Cow, string::ToString, vec::Vec};
49use core::{fmt, str};
50
51/// We support a wide range of dependency versions for `rand` and `rand_core` and not
52/// all versions play nicely together. These re-exports fix that.
53#[cfg(all(feature = "rand", feature = "rand_core"))]
54use rand::{CryptoRng, RngCore};
55#[cfg(all(not(feature = "rand"), feature = "rand_core"))]
56use rand_core::{CryptoRng, RngCore};
57
58#[cfg(feature = "std")]
59use std::error;
60
61use bitcoin_hashes::{sha256, Hash};
62
63#[cfg(feature = "unicode-normalization")]
64use unicode_normalization::UnicodeNormalization;
65
66#[cfg(feature = "zeroize")]
67extern crate zeroize;
68#[cfg(feature = "zeroize")]
69use zeroize::{Zeroize, ZeroizeOnDrop};
70
71#[macro_use]
72mod internal_macros;
73mod language;
74mod pbkdf2;
75
76pub use language::Language;
77
78/// The minimum number of words in a mnemonic.
79#[allow(unused)]
80const MIN_NB_WORDS: usize = 12;
81
82/// The maximum number of words in a mnemonic.
83const MAX_NB_WORDS: usize = 24;
84
85/// The index used to indicate the mnemonic ended.
86const EOF: u16 = u16::max_value();
87
88/// A structured used in the [Error::AmbiguousLanguages] variant that iterates
89/// over the possible languages.
90#[derive(Debug, Clone, PartialEq, Eq, Copy)]
91pub struct AmbiguousLanguages([bool; language::MAX_NB_LANGUAGES]);
92
93impl AmbiguousLanguages {
94	/// Presents the possible languages in the form of a slice of booleans
95	/// that correspond to the occurrences in [Language::all()].
96	pub fn as_bools(&self) -> &[bool; language::MAX_NB_LANGUAGES] {
97		&self.0
98	}
99
100	/// An iterator over the possible languages.
101	pub fn iter(&self) -> impl Iterator<Item = Language> + '_ {
102		Language::all().iter().enumerate().filter(move |(i, _)| self.0[*i]).map(|(_, l)| *l)
103	}
104
105	/// Returns a vector of the possible languages.
106	#[cfg(feature = "alloc")]
107	pub fn to_vec(&self) -> Vec<Language> {
108		self.iter().collect()
109	}
110}
111
112/// A BIP39 error.
113#[derive(Debug, Clone, PartialEq, Eq, Copy)]
114pub enum Error {
115	/// Mnemonic has a word count that is not a multiple of 6.
116	BadWordCount(usize),
117	/// Mnemonic contains an unknown word.
118	/// Error contains the index of the word.
119	/// Use `mnemonic.split_whitespace().get(i)` to get the word.
120	UnknownWord(usize),
121	/// Entropy was not a multiple of 32 bits or between 128-256n bits in length.
122	BadEntropyBitCount(usize),
123	/// The mnemonic has an invalid checksum.
124	InvalidChecksum,
125	/// The mnemonic can be interpreted as multiple languages.
126	/// Use the helper methods of the inner struct to inspect
127	/// which languages are possible.
128	AmbiguousLanguages(AmbiguousLanguages),
129}
130
131impl fmt::Display for Error {
132	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133		match *self {
134			Error::BadWordCount(c) => {
135				write!(
136					f,
137					"mnemonic has an invalid word count: {}. Word count must be 12, 15, 18, 21, \
138					or 24",
139					c
140				)
141			}
142			Error::UnknownWord(i) => write!(f, "mnemonic contains an unknown word (word {})", i,),
143			Error::BadEntropyBitCount(c) => write!(
144				f,
145				"entropy was not between 128-256 bits or not a multiple of 32 bits: {} bits",
146				c,
147			),
148			Error::InvalidChecksum => write!(f, "the mnemonic has an invalid checksum"),
149			Error::AmbiguousLanguages(a) => {
150				write!(f, "ambiguous word list: ")?;
151				for (i, lang) in a.iter().enumerate() {
152					if i == 0 {
153						write!(f, "{}", lang)?;
154					} else {
155						write!(f, ", {}", lang)?;
156					}
157				}
158				Ok(())
159			}
160		}
161	}
162}
163
164#[cfg(feature = "std")]
165impl error::Error for Error {}
166
167/// A mnemonic code.
168///
169/// The [core::str::FromStr] implementation will try to determine the language of the
170/// mnemonic from all the supported languages. (Languages have to be explicitly enabled using
171/// the Cargo features.)
172///
173/// Supported number of words are 12, 15, 18, 21, and 24.
174#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
175#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
176pub struct Mnemonic {
177	/// The language the mnemonic.
178	lang: Language,
179	/// The indices of the words.
180	/// Mnemonics with less than the max nb of words are terminated with EOF.
181	words: [u16; MAX_NB_WORDS],
182}
183
184#[cfg(feature = "zeroize")]
185impl zeroize::DefaultIsZeroes for Language {}
186
187serde_string_impl!(Mnemonic, "a BIP-39 Mnemonic Code");
188
189impl Mnemonic {
190	/// Ensure the content of the [Cow] is normalized UTF8.
191	/// Performing this on a [Cow] means that all allocations for normalization
192	/// can be avoided for languages without special UTF8 characters.
193	#[inline]
194	#[cfg(feature = "unicode-normalization")]
195	pub fn normalize_utf8_cow<'a>(cow: &mut Cow<'a, str>) {
196		let is_nfkd = unicode_normalization::is_nfkd_quick(cow.as_ref().chars());
197		if is_nfkd != unicode_normalization::IsNormalized::Yes {
198			*cow = Cow::Owned(cow.as_ref().nfkd().to_string());
199		}
200	}
201
202	/// Create a new [Mnemonic] in the specified language from the given entropy.
203	/// Entropy must be a multiple of 32 bits (4 bytes) and 128-256 bits in length.
204	pub fn from_entropy_in(language: Language, entropy: &[u8]) -> Result<Mnemonic, Error> {
205		const MAX_ENTROPY_BITS: usize = 256;
206		const MIN_ENTROPY_BITS: usize = 128;
207		const MAX_CHECKSUM_BITS: usize = 8;
208
209		let nb_bytes = entropy.len();
210		let nb_bits = nb_bytes * 8;
211
212		if nb_bits % 32 != 0 {
213			return Err(Error::BadEntropyBitCount(nb_bits));
214		}
215		if nb_bits < MIN_ENTROPY_BITS || nb_bits > MAX_ENTROPY_BITS {
216			return Err(Error::BadEntropyBitCount(nb_bits));
217		}
218
219		let check = sha256::Hash::hash(&entropy);
220		let mut bits = [false; MAX_ENTROPY_BITS + MAX_CHECKSUM_BITS];
221		for i in 0..nb_bytes {
222			for j in 0..8 {
223				bits[i * 8 + j] = (entropy[i] & (1 << (7 - j))) > 0;
224			}
225		}
226		for i in 0..nb_bytes / 4 {
227			bits[8 * nb_bytes + i] = (check[i / 8] & (1 << (7 - (i % 8)))) > 0;
228		}
229
230		let mut words = [EOF; MAX_NB_WORDS];
231		let nb_words = nb_bytes * 3 / 4;
232		for i in 0..nb_words {
233			let mut idx = 0;
234			for j in 0..11 {
235				if bits[i * 11 + j] {
236					idx += 1 << (10 - j);
237				}
238			}
239			words[i] = idx;
240		}
241
242		Ok(Mnemonic {
243			lang: language,
244			words: words,
245		})
246	}
247
248	/// Create a new English [Mnemonic] from the given entropy.
249	/// Entropy must be a multiple of 32 bits (4 bytes) and 128-256 bits in length.
250	pub fn from_entropy(entropy: &[u8]) -> Result<Mnemonic, Error> {
251		Mnemonic::from_entropy_in(Language::English, entropy)
252	}
253
254	/// Generate a new [Mnemonic] in the given language
255	/// with the given randomness source.
256	/// For the different supported word counts, see documentation on [Mnemonic].
257	///
258	/// Example:
259	///
260	/// ```
261	/// use parity_bip39::{Mnemonic, Language};
262	///
263	/// let mut rng = parity_bip39::rand::thread_rng();
264	/// let m = Mnemonic::generate_in_with(&mut rng, Language::English, 24).unwrap();
265	/// ```
266	#[cfg(feature = "rand_core")]
267	pub fn generate_in_with<R>(
268		rng: &mut R,
269		language: Language,
270		word_count: usize,
271	) -> Result<Mnemonic, Error>
272	where
273		R: RngCore + CryptoRng,
274	{
275		if is_invalid_word_count(word_count) {
276			return Err(Error::BadWordCount(word_count));
277		}
278
279		let entropy_bytes = (word_count / 3) * 4;
280		let mut entropy = [0u8; (MAX_NB_WORDS / 3) * 4];
281		RngCore::fill_bytes(rng, &mut entropy[0..entropy_bytes]);
282		Mnemonic::from_entropy_in(language, &entropy[0..entropy_bytes])
283	}
284
285	/// Generate a new [Mnemonic] in the given language.
286	/// For the different supported word counts, see documentation on [Mnemonic].
287	///
288	/// Example:
289	///
290	/// ```
291	/// use parity_bip39::{Mnemonic, Language};
292	///
293	/// let m = Mnemonic::generate_in(Language::English, 24).unwrap();
294	/// ```
295	#[cfg(feature = "rand")]
296	pub fn generate_in(language: Language, word_count: usize) -> Result<Mnemonic, Error> {
297		Mnemonic::generate_in_with(&mut rand::thread_rng(), language, word_count)
298	}
299
300	/// Generate a new [Mnemonic] in English.
301	/// For the different supported word counts, see documentation on [Mnemonic].
302	///
303	/// Example:
304	///
305	/// ```
306	/// use parity_bip39::Mnemonic;
307	///
308	/// let m = Mnemonic::generate(24).unwrap();
309	/// ```
310	#[cfg(feature = "rand")]
311	pub fn generate(word_count: usize) -> Result<Mnemonic, Error> {
312		Mnemonic::generate_in(Language::English, word_count)
313	}
314
315	/// Get the language of the [Mnemonic].
316	pub fn language(&self) -> Language {
317		self.lang
318	}
319
320	/// Returns an iterator over the words of the [Mnemonic].
321	///
322	/// # Examples
323	///
324	/// Basic usage:
325	///
326	/// ```
327	/// use parity_bip39::Mnemonic;
328	///
329	/// let mnemonic = Mnemonic::from_entropy(&[0; 32]).unwrap();
330	/// for (i, word) in mnemonic.words().enumerate() {
331	///     println!("{}. {}", i, word);
332	/// }
333	/// ```
334	pub fn words(&self) -> impl Iterator<Item = &'static str> + Clone + '_ {
335		let list = self.lang.word_list();
336		self.word_indices().map(move |i| list[i])
337	}
338
339	/// Returns an iterator over the words of the [Mnemonic].
340	#[deprecated(note = "Use Mnemonic::words instead")]
341	pub fn word_iter(&self) -> impl Iterator<Item = &'static str> + Clone + '_ {
342		self.words()
343	}
344
345	/// Returns an iterator over [Mnemonic] word indices.
346	///
347	/// # Examples
348	///
349	/// Basic usage:
350	///
351	/// ```
352	/// use parity_bip39::{Language, Mnemonic};
353	///
354	/// let list = Language::English.word_list();
355	/// let mnemonic = Mnemonic::from_entropy(&[0; 32]).unwrap();
356	/// for i in mnemonic.word_indices() {
357	/// 	println!("{} ({})", list[i], i);
358	/// }
359	/// ```
360	pub fn word_indices(&self) -> impl Iterator<Item = usize> + Clone + '_ {
361		self.words.iter().take_while(|&&w| w != EOF).map(|w| *w as usize)
362	}
363
364	/// Determine the language of the mnemonic as a word iterator.
365	/// See documentation on [Mnemonic::language_of] for more info.
366	fn language_of_iter<'a, W: Iterator<Item = &'a str>>(words: W) -> Result<Language, Error> {
367		let mut words = words.peekable();
368		let langs = Language::all();
369		{
370			// Start scope to drop first_word so that words can be reborrowed later.
371			let first_word = words.peek().ok_or(Error::BadWordCount(0))?;
372			if first_word.len() == 0 {
373				return Err(Error::BadWordCount(0));
374			}
375
376			// We first try find the first word in wordlists that
377			// have guaranteed unique words.
378			for language in langs.iter().filter(|l| l.unique_words()) {
379				if language.find_word(first_word).is_some() {
380					return Ok(*language);
381				}
382			}
383		}
384
385		// If that didn't work, we start with all possible languages
386		// (those without unique words), and eliminate until there is
387		// just one left.
388		let mut possible = [false; language::MAX_NB_LANGUAGES];
389		for (i, lang) in langs.iter().enumerate() {
390			// To start, only consider lists that don't have unique words.
391			// Those were considered above.
392			possible[i] = !lang.unique_words();
393		}
394		for (idx, word) in words.enumerate() {
395			// Scrap languages that don't have this word.
396			for (i, lang) in langs.iter().enumerate() {
397				possible[i] &= lang.find_word(word).is_some();
398			}
399
400			// Get an iterator over remaining possible languages.
401			let mut iter = possible.iter().zip(langs.iter()).filter(|(p, _)| **p).map(|(_, l)| l);
402
403			match iter.next() {
404				// If all languages were eliminated, it's an invalid word.
405				None => return Err(Error::UnknownWord(idx)),
406				// If not, see if there is a second one remaining.
407				Some(remaining) => {
408					if iter.next().is_none() {
409						// No second remaining, we found our language.
410						return Ok(*remaining);
411					}
412				}
413			}
414		}
415
416		return Err(Error::AmbiguousLanguages(AmbiguousLanguages(possible)));
417	}
418
419	/// Determine the language of the mnemonic.
420	///
421	/// NOTE: This method only guarantees that the returned language is the
422	/// correct language on the assumption that the mnemonic is valid.
423	/// It does not itself validate the mnemonic.
424	///
425	/// Some word lists don't guarantee that their words don't occur in other
426	/// word lists. In the extremely unlikely case that a word list can be
427	/// interpreted in multiple languages, an [Error::AmbiguousLanguages] is
428	/// returned, containing the possible languages.
429	pub fn language_of<S: AsRef<str>>(mnemonic: S) -> Result<Language, Error> {
430		Mnemonic::language_of_iter(mnemonic.as_ref().split_whitespace())
431	}
432
433	/// Parse a mnemonic in normalized UTF8 in the given language.
434	pub fn parse_in_normalized(language: Language, s: &str) -> Result<Mnemonic, Error> {
435		let nb_words = s.split_whitespace().count();
436		if is_invalid_word_count(nb_words) {
437			return Err(Error::BadWordCount(nb_words));
438		}
439
440		// Here we will store the eventual words.
441		let mut words = [EOF; MAX_NB_WORDS];
442
443		// And here we keep track of the bits to calculate and validate the checksum.
444		// We only use `nb_words * 11` elements in this array.
445		let mut bits = [false; MAX_NB_WORDS * 11];
446
447		for (i, word) in s.split_whitespace().enumerate() {
448			let idx = language.find_word(word).ok_or(Error::UnknownWord(i))?;
449
450			words[i] = idx;
451
452			for j in 0..11 {
453				bits[i * 11 + j] = idx >> (10 - j) & 1 == 1;
454			}
455		}
456
457		// Verify the checksum.
458		// We only use `nb_words / 3 * 4` elements in this array.
459		let mut entropy = [0u8; MAX_NB_WORDS / 3 * 4];
460		let nb_bytes_entropy = nb_words / 3 * 4;
461		for i in 0..nb_bytes_entropy {
462			for j in 0..8 {
463				if bits[i * 8 + j] {
464					entropy[i] += 1 << (7 - j);
465				}
466			}
467		}
468		let check = sha256::Hash::hash(&entropy[0..nb_bytes_entropy]);
469		for i in 0..nb_bytes_entropy / 4 {
470			if bits[8 * nb_bytes_entropy + i] != ((check[i / 8] & (1 << (7 - (i % 8)))) > 0) {
471				return Err(Error::InvalidChecksum);
472			}
473		}
474
475		Ok(Mnemonic {
476			lang: language,
477			words: words,
478		})
479	}
480
481	/// Parse a mnemonic in normalized UTF8 in the given language without checksum check.
482	///
483	/// It is advised to use this method together with the utility methods
484	/// - [Mnemonic::normalize_utf8_cow]
485	/// - [Mnemonic::language_of]
486	pub fn parse_in_normalized_without_checksum_check(
487		language: Language,
488		s: &str,
489	) -> Result<Mnemonic, Error> {
490		let nb_words = s.split_whitespace().count();
491		if is_invalid_word_count(nb_words) {
492			return Err(Error::BadWordCount(nb_words));
493		}
494
495		// Here we will store the eventual words.
496		let mut words = [EOF; MAX_NB_WORDS];
497
498		for (i, word) in s.split_whitespace().enumerate() {
499			let idx = language.find_word(word).ok_or(Error::UnknownWord(i))?;
500
501			words[i] = idx;
502		}
503
504		Ok(Mnemonic {
505			lang: language,
506			words: words,
507		})
508	}
509
510	/// Parse a mnemonic in normalized UTF8.
511	pub fn parse_normalized(s: &str) -> Result<Mnemonic, Error> {
512		let lang = Mnemonic::language_of(s)?;
513		Mnemonic::parse_in_normalized(lang, s)
514	}
515
516	/// Parse a mnemonic in the given language.
517	#[cfg(feature = "unicode-normalization")]
518	pub fn parse_in<'a, S: Into<Cow<'a, str>>>(
519		language: Language,
520		s: S,
521	) -> Result<Mnemonic, Error> {
522		let mut cow = s.into();
523		Mnemonic::normalize_utf8_cow(&mut cow);
524		Ok(Mnemonic::parse_in_normalized(language, cow.as_ref())?)
525	}
526
527	/// Parse a mnemonic and detect the language from the enabled languages.
528	#[cfg(feature = "unicode-normalization")]
529	pub fn parse<'a, S: Into<Cow<'a, str>>>(s: S) -> Result<Mnemonic, Error> {
530		let mut cow = s.into();
531		Mnemonic::normalize_utf8_cow(&mut cow);
532
533		let language = if Language::all().len() == 1 {
534			Language::all()[0]
535		} else {
536			Mnemonic::language_of(cow.as_ref())?
537		};
538
539		Ok(Mnemonic::parse_in_normalized(language, cow.as_ref())?)
540	}
541
542	/// Get the number of words in the mnemonic.
543	pub fn word_count(&self) -> usize {
544		self.word_indices().count()
545	}
546
547	/// Convert to seed bytes with a passphrase in normalized UTF8.
548	pub fn to_seed_normalized(&self, normalized_passphrase: &str) -> [u8; 64] {
549		const PBKDF2_ROUNDS: usize = 2048;
550		const PBKDF2_BYTES: usize = 64;
551
552		let mut seed = [0u8; PBKDF2_BYTES];
553		pbkdf2::pbkdf2(self.words(), normalized_passphrase.as_bytes(), PBKDF2_ROUNDS, &mut seed);
554		seed
555	}
556
557	/// Convert to seed bytes.
558	#[cfg(feature = "unicode-normalization")]
559	pub fn to_seed<'a, P: Into<Cow<'a, str>>>(&self, passphrase: P) -> [u8; 64] {
560		let normalized_passphrase = {
561			let mut cow = passphrase.into();
562			Mnemonic::normalize_utf8_cow(&mut cow);
563			cow
564		};
565		self.to_seed_normalized(normalized_passphrase.as_ref())
566	}
567
568	/// Convert the mnemonic back to the entropy used to generate it.
569	/// The return value is a byte array and the size.
570	/// Use [Mnemonic::to_entropy] (needs `std`) to get a [`Vec<u8>`].
571	pub fn to_entropy_array(&self) -> ([u8; 33], usize) {
572		// We unwrap errors here because this method can only be called on
573		// values that were already previously validated.
574
575		let language = Mnemonic::language_of_iter(self.words()).unwrap();
576
577		// Preallocate enough space for the longest possible word list
578		let mut entropy = [0; 33];
579		let mut cursor = 0;
580		let mut offset = 0;
581		let mut remainder = 0;
582
583		let nb_words = self.word_count();
584		for word in self.words() {
585			let idx = language.find_word(word).expect("invalid mnemonic");
586
587			remainder |= ((idx as u32) << (32 - 11)) >> offset;
588			offset += 11;
589
590			while offset >= 8 {
591				entropy[cursor] = (remainder >> 24) as u8;
592				cursor += 1;
593				remainder <<= 8;
594				offset -= 8;
595			}
596		}
597
598		if offset != 0 {
599			entropy[cursor] = (remainder >> 24) as u8;
600		}
601
602		let entropy_bytes = (nb_words / 3) * 4;
603		(entropy, entropy_bytes)
604	}
605
606	/// Convert the mnemonic back to the entropy used to generate it.
607	#[cfg(feature = "alloc")]
608	pub fn to_entropy(&self) -> Vec<u8> {
609		let (arr, len) = self.to_entropy_array();
610		arr[0..len].to_vec()
611	}
612
613	/// Return checksum value for the Mnemonic.
614	///
615	/// The checksum value is the numerical value of the first `self.word_count() / 3` bits of the
616	/// [SHA256](https://en.wikipedia.org/wiki/SHA-2) digest of the Mnemonic's entropy, and is
617	/// encoded by the last word of the mnemonic sentence.
618	///
619	/// This is useful for validating the integrity of a mnemonic: For a valid mnemonic `m`, the
620	/// following assertion should hold:
621	///
622	/// ```rust
623	/// # use parity_bip39::Mnemonic;
624	/// # use bitcoin_hashes::{Hash, sha256, hex::FromHex};
625	/// # let ent = Vec::from_hex("98FE3D0FF6E955A484B0A1D0C9CE10F6").unwrap();
626	/// # let m = Mnemonic::from_entropy(&ent).unwrap();
627	/// let checksum_width = m.word_count() / 3;
628	/// let shift_width = 8 - checksum_width;
629	/// assert_eq!(sha256::Hash::hash(&m.to_entropy())[0] >> shift_width, m.checksum());
630	/// ```
631	///
632	/// Note that since this library constrains initialization of `Mnemonic` instances through an
633	/// API that guarantees validity, all `Mnemonic` instances should be valid and the above
634	/// condition should hold.
635	pub fn checksum(&self) -> u8 {
636		let word_count = self.word_count();
637		let last_word = self.words[word_count - 1];
638		let mask = 0xFF >> (8 - word_count / 3);
639		last_word as u8 & mask
640	}
641}
642
643impl fmt::Display for Mnemonic {
644	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
645		for (i, word) in self.words().enumerate() {
646			if i > 0 {
647				f.write_str(" ")?;
648			}
649			f.write_str(word)?;
650		}
651		Ok(())
652	}
653}
654
655impl str::FromStr for Mnemonic {
656	type Err = Error;
657
658	fn from_str(s: &str) -> Result<Mnemonic, Error> {
659		#[cfg(feature = "unicode-normalization")]
660		{
661			Mnemonic::parse(s)
662		}
663		#[cfg(not(feature = "unicode-normalization"))]
664		{
665			Mnemonic::parse_normalized(s)
666		}
667	}
668}
669
670fn is_invalid_word_count(word_count: usize) -> bool {
671	word_count < MIN_NB_WORDS || word_count % 3 != 0 || word_count > MAX_NB_WORDS
672}
673
674#[cfg(test)]
675mod tests {
676	use super::*;
677
678	use bitcoin_hashes::hex::FromHex;
679
680	#[cfg(feature = "rand")]
681	#[test]
682	fn test_language_of() {
683		for lang in Language::all() {
684			let m = Mnemonic::generate_in(*lang, 24).unwrap();
685			assert_eq!(*lang, Mnemonic::language_of_iter(m.words()).unwrap());
686			assert_eq!(
687				*lang,
688				Mnemonic::language_of_iter(m.to_string().split_whitespace()).unwrap()
689			);
690			assert_eq!(*lang, Mnemonic::language_of(m.to_string()).unwrap());
691			assert_eq!(*lang, Mnemonic::language_of(&m.to_string()).unwrap());
692		}
693	}
694
695	#[cfg(feature = "std")]
696	#[test]
697	fn test_ambiguous_languages() {
698		let mut present = [false; language::MAX_NB_LANGUAGES];
699		let mut present_vec = Vec::new();
700		let mut alternate = true;
701		for i in 0..Language::all().len() {
702			present[i] = alternate;
703			if alternate {
704				present_vec.push(Language::all()[i]);
705			}
706			alternate = !alternate;
707		}
708		let amb = AmbiguousLanguages(present);
709		assert_eq!(amb.to_vec(), present_vec);
710		assert_eq!(amb.iter().collect::<Vec<_>>(), present_vec);
711	}
712
713	#[cfg(feature = "rand")]
714	#[test]
715	fn test_generate() {
716		let _ = Mnemonic::generate(24).unwrap();
717		let _ = Mnemonic::generate_in(Language::English, 24).unwrap();
718		let _ = Mnemonic::generate_in_with(&mut rand::thread_rng(), Language::English, 24).unwrap();
719	}
720
721	#[cfg(feature = "rand")]
722	#[test]
723	fn test_generate_word_counts() {
724		for word_count in [12, 15, 18, 21, 24].iter() {
725			let _ = Mnemonic::generate(*word_count).unwrap();
726		}
727	}
728
729	#[test]
730	fn test_vectors_english() {
731		// These vectors are tuples of
732		// (entropy, mnemonic, seed)
733		let test_vectors = [
734			(
735				"00000000000000000000000000000000",
736				"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
737				"c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",
738			),
739			(
740				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
741				"legal winner thank year wave sausage worth useful legal winner thank yellow",
742				"2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607",
743			),
744			(
745				"80808080808080808080808080808080",
746				"letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
747				"d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8",
748			),
749			(
750				"ffffffffffffffffffffffffffffffff",
751				"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
752				"ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069",
753			),
754			(
755				"000000000000000000000000000000000000000000000000",
756				"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
757				"035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa",
758			),
759			(
760				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
761				"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will",
762				"f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd",
763			),
764			(
765				"808080808080808080808080808080808080808080808080",
766				"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always",
767				"107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65",
768			),
769			(
770				"ffffffffffffffffffffffffffffffffffffffffffffffff",
771				"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when",
772				"0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528",
773			),
774			(
775				"0000000000000000000000000000000000000000000000000000000000000000",
776				"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
777				"bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8",
778			),
779			(
780				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
781				"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title",
782				"bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87",
783			),
784			(
785				"8080808080808080808080808080808080808080808080808080808080808080",
786				"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless",
787				"c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f",
788			),
789			(
790				"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
791				"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote",
792				"dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad",
793			),
794			(
795				"9e885d952ad362caeb4efe34a8e91bd2",
796				"ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic",
797				"274ddc525802f7c828d8ef7ddbcdc5304e87ac3535913611fbbfa986d0c9e5476c91689f9c8a54fd55bd38606aa6a8595ad213d4c9c9f9aca3fb217069a41028",
798			),
799			(
800				"6610b25967cdcca9d59875f5cb50b0ea75433311869e930b",
801				"gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog",
802				"628c3827a8823298ee685db84f55caa34b5cc195a778e52d45f59bcf75aba68e4d7590e101dc414bc1bbd5737666fbbef35d1f1903953b66624f910feef245ac",
803			),
804			(
805				"68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c",
806				"hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length",
807				"64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d415665b8a9030c9ec653d75e65f847d8fc1fc440",
808			),
809			(
810				"c0ba5a8e914111210f2bd131f3d5e08d",
811				"scheme spot photo card baby mountain device kick cradle pact join borrow",
812				"ea725895aaae8d4c1cf682c1bfd2d358d52ed9f0f0591131b559e2724bb234fca05aa9c02c57407e04ee9dc3b454aa63fbff483a8b11de949624b9f1831a9612",
813			),
814			(
815				"6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3",
816				"horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave",
817				"fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d",
818			),
819			(
820				"9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863",
821				"panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside",
822				"72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeecbc469594a70e3dd50811b5067f3b88b28c3e8d",
823			),
824			(
825				"23db8160a31d3e0dca3688ed941adbf3",
826				"cat swing flag economy stadium alone churn speed unique patch report train",
827				"deb5f45449e615feff5640f2e49f933ff51895de3b4381832b3139941c57b59205a42480c52175b6efcffaa58a2503887c1e8b363a707256bdd2b587b46541f5",
828			),
829			(
830				"8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0",
831				"light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access",
832				"4cbdff1ca2db800fd61cae72a57475fdc6bab03e441fd63f96dabd1f183ef5b782925f00105f318309a7e9c3ea6967c7801e46c8a58082674c860a37b93eda02",
833			),
834			(
835				"066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad",
836				"all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform",
837				"26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d",
838			),
839			(
840				"f30f8c1da665478f49b001d94c5fc452",
841				"vessel ladder alter error federal sibling chat ability sun glass valve picture",
842				"2aaa9242daafcee6aa9d7269f17d4efe271e1b9a529178d7dc139cd18747090bf9d60295d0ce74309a78852a9caadf0af48aae1c6253839624076224374bc63f",
843			),
844			(
845				"c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05",
846				"scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump",
847				"7b4a10be9d98e6cba265566db7f136718e1398c71cb581e1b2f464cac1ceedf4f3e274dc270003c670ad8d02c4558b2f8e39edea2775c9e232c7cb798b069e88",
848			),
849			(
850				"f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f",
851				"void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold",
852				"01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998",
853			)
854		];
855
856		for vector in &test_vectors {
857			let entropy = Vec::<u8>::from_hex(&vector.0).unwrap();
858			let mnemonic_str = vector.1;
859			let seed = Vec::<u8>::from_hex(&vector.2).unwrap();
860
861			let mnemonic = Mnemonic::from_entropy(&entropy).unwrap();
862
863			assert_eq!(
864				mnemonic,
865				Mnemonic::parse_in_normalized(Language::English, mnemonic_str).unwrap(),
866				"failed vector: {}",
867				mnemonic_str
868			);
869			assert_eq!(
870				mnemonic,
871				Mnemonic::parse_normalized(mnemonic_str).unwrap(),
872				"failed vector: {}",
873				mnemonic_str
874			);
875			assert_eq!(
876				&seed[..],
877				&mnemonic.to_seed_normalized("TREZOR")[..],
878				"failed vector: {}",
879				mnemonic_str
880			);
881
882			#[cfg(feature = "unicode-normalization")]
883			{
884				assert_eq!(&mnemonic.to_string(), mnemonic_str, "failed vector: {}", mnemonic_str);
885				assert_eq!(
886					mnemonic,
887					Mnemonic::parse_in(Language::English, mnemonic_str).unwrap(),
888					"failed vector: {}",
889					mnemonic_str
890				);
891				assert_eq!(
892					mnemonic,
893					Mnemonic::parse(mnemonic_str).unwrap(),
894					"failed vector: {}",
895					mnemonic_str
896				);
897				assert_eq!(
898					&seed[..],
899					&mnemonic.to_seed("TREZOR")[..],
900					"failed vector: {}",
901					mnemonic_str
902				);
903				assert_eq!(&entropy, &mnemonic.to_entropy(), "failed vector: {}", mnemonic_str);
904				assert_eq!(
905					&entropy[..],
906					&mnemonic.to_entropy_array().0[0..entropy.len()],
907					"failed vector: {}",
908					mnemonic_str
909				);
910			}
911		}
912	}
913
914	#[test]
915	fn checksum() {
916		let vectors = [
917			"00000000000000000000000000000000",
918			"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
919			"80808080808080808080808080808080",
920			"ffffffffffffffffffffffffffffffff",
921			"000000000000000000000000000000000000000000000000",
922			"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
923			"808080808080808080808080808080808080808080808080",
924			"ffffffffffffffffffffffffffffffffffffffffffffffff",
925			"0000000000000000000000000000000000000000000000000000000000000000",
926			"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
927			"8080808080808080808080808080808080808080808080808080808080808080",
928			"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
929			"9e885d952ad362caeb4efe34a8e91bd2",
930			"6610b25967cdcca9d59875f5cb50b0ea75433311869e930b",
931			"68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c",
932			"c0ba5a8e914111210f2bd131f3d5e08d",
933			"6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3",
934			"9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863",
935			"23db8160a31d3e0dca3688ed941adbf3",
936			"8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0",
937			"066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad",
938			"f30f8c1da665478f49b001d94c5fc452",
939			"c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05",
940			"f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f",
941			"ed3b83f0d7913a19667a1cfd7298cd57",
942			"70639a4e81b151277b345476d169a3743ff3c141",
943			"ba2520298b92063a7a0ee1d453ba92513af81d4f86e1d336",
944			"9447d2cf44349cd88a58f5b4ff6f83b9a2d54c42f033e12b8e4d00cc",
945			"38711e550dc6557df8082b2a87f7860ebbe47ea5867a7068f5f0f5b85db68be8",
946		];
947
948		for entropy_hex in &vectors {
949			let ent = Vec::from_hex(entropy_hex).unwrap();
950			let m = Mnemonic::from_entropy(&ent).unwrap();
951			let word_count = m.word_count();
952			let cs = m.checksum();
953			let digest = sha256::Hash::hash(&ent);
954			dbg!(digest);
955			assert_eq!(digest[0] >> (8 - word_count / 3), cs);
956		}
957	}
958
959	#[test]
960	fn test_invalid_engish() {
961		// correct phrase:
962		// "letter advice cage absurd amount doctor acoustic avoid letter advice cage above"
963
964		assert_eq!(
965			Mnemonic::parse_normalized(
966				"getter advice cage absurd amount doctor acoustic avoid letter advice cage above",
967			),
968			Err(Error::UnknownWord(0))
969		);
970
971		assert_eq!(
972			Mnemonic::parse_normalized(
973				"letter advice cagex absurd amount doctor acoustic avoid letter advice cage above",
974			),
975			Err(Error::UnknownWord(2))
976		);
977
978		assert_eq!(
979			Mnemonic::parse_normalized(
980				"advice cage absurd amount doctor acoustic avoid letter advice cage above",
981			),
982			Err(Error::BadWordCount(11))
983		);
984
985		assert_eq!(
986			Mnemonic::parse_normalized(
987				"primary advice cage absurd amount doctor acoustic avoid letter advice cage above",
988			),
989			Err(Error::InvalidChecksum)
990		);
991	}
992
993	#[test]
994	fn test_invalid_entropy() {
995		//between 128 and 256 bits, but not divisible by 32
996		assert_eq!(Mnemonic::from_entropy(&vec![b'x'; 17]), Err(Error::BadEntropyBitCount(136)));
997
998		//less than 128 bits
999		assert_eq!(Mnemonic::from_entropy(&vec![b'x'; 4]), Err(Error::BadEntropyBitCount(32)));
1000
1001		//greater than 256 bits
1002		assert_eq!(Mnemonic::from_entropy(&vec![b'x'; 36]), Err(Error::BadEntropyBitCount(288)));
1003	}
1004
1005	#[cfg(all(feature = "japanese", feature = "std"))]
1006	#[test]
1007	fn test_vectors_japanese() {
1008		//! Test some Japanese language test vectors.
1009		//! For these test vectors, we seem to generate different mnemonic phrases than the test
1010		//! vectors expect us to. However, our generated seeds are correct and tiny-bip39,
1011		//! an alternative implementation of bip39 also does not fulfill the test vectors.
1012
1013		// These vectors are tuples of
1014		// (entropy, mnemonic, passphrase, seed)
1015		let vectors = [
1016			(
1017				"00000000000000000000000000000000",
1018				"あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あおぞら",
1019				"㍍ガバヴァぱばぐゞちぢ十人十色",
1020				"a262d6fb6122ecf45be09c50492b31f92e9beb7d9a845987a02cefda57a15f9c467a17872029a9e92299b5cbdf306e3a0ee620245cbd508959b6cb7ca637bd55",
1021			),
1022			(
1023				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
1024				"そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ",
1025				"㍍ガバヴァぱばぐゞちぢ十人十色",
1026				"aee025cbe6ca256862f889e48110a6a382365142f7d16f2b9545285b3af64e542143a577e9c144e101a6bdca18f8d97ec3366ebf5b088b1c1af9bc31346e60d9",
1027			),
1028			(
1029				"80808080808080808080808080808080",
1030				"そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あかちゃん",
1031				"㍍ガバヴァぱばぐゞちぢ十人十色",
1032				"e51736736ebdf77eda23fa17e31475fa1d9509c78f1deb6b4aacfbd760a7e2ad769c714352c95143b5c1241985bcb407df36d64e75dd5a2b78ca5d2ba82a3544",
1033			),
1034			(
1035				"ffffffffffffffffffffffffffffffff",
1036				"われる われる われる われる われる われる われる われる われる われる われる ろんぶん",
1037				"㍍ガバヴァぱばぐゞちぢ十人十色",
1038				"4cd2ef49b479af5e1efbbd1e0bdc117f6a29b1010211df4f78e2ed40082865793e57949236c43b9fe591ec70e5bb4298b8b71dc4b267bb96ed4ed282c8f7761c",
1039			),
1040			(
1041				"000000000000000000000000000000000000000000000000",
1042				"あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あらいぐま",
1043				"㍍ガバヴァぱばぐゞちぢ十人十色",
1044				"d99e8f1ce2d4288d30b9c815ae981edd923c01aa4ffdc5dee1ab5fe0d4a3e13966023324d119105aff266dac32e5cd11431eeca23bbd7202ff423f30d6776d69",
1045			),
1046			(
1047				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
1048				"そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れいぎ",
1049				"㍍ガバヴァぱばぐゞちぢ十人十色",
1050				"eaaf171efa5de4838c758a93d6c86d2677d4ccda4a064a7136344e975f91fe61340ec8a615464b461d67baaf12b62ab5e742f944c7bd4ab6c341fbafba435716",
1051			),
1052			(
1053				"808080808080808080808080808080808080808080808080",
1054				"そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら いきなり",
1055				"㍍ガバヴァぱばぐゞちぢ十人十色",
1056				"aec0f8d3167a10683374c222e6e632f2940c0826587ea0a73ac5d0493b6a632590179a6538287641a9fc9df8e6f24e01bf1be548e1f74fd7407ccd72ecebe425",
1057			),
1058			(
1059				"ffffffffffffffffffffffffffffffffffffffffffffffff",
1060				"われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる りんご",
1061				"㍍ガバヴァぱばぐゞちぢ十人十色",
1062				"f0f738128a65b8d1854d68de50ed97ac1831fc3a978c569e415bbcb431a6a671d4377e3b56abd518daa861676c4da75a19ccb41e00c37d086941e471a4374b95",
1063			),
1064			(
1065				"0000000000000000000000000000000000000000000000000000000000000000",
1066				"あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん いってい",
1067				"㍍ガバヴァぱばぐゞちぢ十人十色",
1068				"23f500eec4a563bf90cfda87b3e590b211b959985c555d17e88f46f7183590cd5793458b094a4dccc8f05807ec7bd2d19ce269e20568936a751f6f1ec7c14ddd",
1069			),
1070			(
1071				"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
1072				"そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかす りくつ ばいか ろせん まんきつ",
1073				"㍍ガバヴァぱばぐゞちぢ十人十色",
1074				"cd354a40aa2e241e8f306b3b752781b70dfd1c69190e510bc1297a9c5738e833bcdc179e81707d57263fb7564466f73d30bf979725ff783fb3eb4baa86560b05",
1075			),
1076			(
1077				"8080808080808080808080808080808080808080808080808080808080808080",
1078				"そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あこがれる いくぶん けいけん あたえる いよく そとづら あまど おおう あこがれる いくぶん けいけん あたえる うめる",
1079				"㍍ガバヴァぱばぐゞちぢ十人十色",
1080				"6b7cd1b2cdfeeef8615077cadd6a0625f417f287652991c80206dbd82db17bf317d5c50a80bd9edd836b39daa1b6973359944c46d3fcc0129198dc7dc5cd0e68",
1081			),
1082			(
1083				"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1084				"われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる われる らいう",
1085				"㍍ガバヴァぱばぐゞちぢ十人十色",
1086				"a44ba7054ac2f9226929d56505a51e13acdaa8a9097923ca07ea465c4c7e294c038f3f4e7e4b373726ba0057191aced6e48ac8d183f3a11569c426f0de414623",
1087			),
1088			(
1089				"77c2b00716cec7213839159e404db50d",
1090				"せまい うちがわ あずき かろう めずらしい だんち ますく おさめる ていぼう あたる すあな えしゃく",
1091				"㍍ガバヴァぱばぐゞちぢ十人十色",
1092				"344cef9efc37d0cb36d89def03d09144dd51167923487eec42c487f7428908546fa31a3c26b7391a2b3afe7db81b9f8c5007336b58e269ea0bd10749a87e0193",
1093			),
1094			(
1095				"b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b",
1096				"ぬすむ ふっかつ うどん こうりつ しつじ りょうり おたがい せもたれ あつめる いちりゅう はんしゃ ごますり そんけい たいちょう らしんばん ぶんせき やすみ ほいく",
1097				"㍍ガバヴァぱばぐゞちぢ十人十色",
1098				"b14e7d35904cb8569af0d6a016cee7066335a21c1c67891b01b83033cadb3e8a034a726e3909139ecd8b2eb9e9b05245684558f329b38480e262c1d6bc20ecc4",
1099			),
1100			(
1101				"3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982",
1102				"くのう てぬぐい そんかい すろっと ちきゅう ほあん とさか はくしゅ ひびく みえる そざい てんすう たんぴん くしょう すいようび みけん きさらぎ げざん ふくざつ あつかう はやい くろう おやゆび こすう",
1103				"㍍ガバヴァぱばぐゞちぢ十人十色",
1104				"32e78dce2aff5db25aa7a4a32b493b5d10b4089923f3320c8b287a77e512455443298351beb3f7eb2390c4662a2e566eec5217e1a37467af43b46668d515e41b",
1105			),
1106			(
1107				"0460ef47585604c5660618db2e6a7e7f",
1108				"あみもの いきおい ふいうち にげる ざんしょ じかん ついか はたん ほあん すんぽう てちがい わかめ",
1109				"㍍ガバヴァぱばぐゞちぢ十人十色",
1110				"0acf902cd391e30f3f5cb0605d72a4c849342f62bd6a360298c7013d714d7e58ddf9c7fdf141d0949f17a2c9c37ced1d8cb2edabab97c4199b142c829850154b",
1111			),
1112			(
1113				"72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f",
1114				"すろっと にくしみ なやむ たとえる へいこう すくう きない けってい とくべつ ねっしん いたみ せんせい おくりがな まかい とくい けあな いきおい そそぐ",
1115				"㍍ガバヴァぱばぐゞちぢ十人十色",
1116				"9869e220bec09b6f0c0011f46e1f9032b269f096344028f5006a6e69ea5b0b8afabbb6944a23e11ebd021f182dd056d96e4e3657df241ca40babda532d364f73",
1117			),
1118			(
1119				"2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416",
1120				"かほご きうい ゆたか みすえる もらう がっこう よそう ずっと ときどき したうけ にんか はっこう つみき すうじつ よけい くげん もくてき まわり せめる げざい にげる にんたい たんそく ほそく",
1121				"㍍ガバヴァぱばぐゞちぢ十人十色",
1122				"713b7e70c9fbc18c831bfd1f03302422822c3727a93a5efb9659bec6ad8d6f2c1b5c8ed8b0b77775feaf606e9d1cc0a84ac416a85514ad59f5541ff5e0382481",
1123			),
1124			(
1125				"eaebabb2383351fd31d703840b32e9e2",
1126				"めいえん さのう めだつ すてる きぬごし ろんぱ はんこ まける たいおう さかいし ねんいり はぶらし",
1127				"㍍ガバヴァぱばぐゞちぢ十人十色",
1128				"06e1d5289a97bcc95cb4a6360719131a786aba057d8efd603a547bd254261c2a97fcd3e8a4e766d5416437e956b388336d36c7ad2dba4ee6796f0249b10ee961",
1129			),
1130			(
1131				"7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78",
1132				"せんぱい おしえる ぐんかん もらう きあい きぼう やおや いせえび のいず じゅしん よゆう きみつ さといも ちんもく ちわわ しんせいじ とめる はちみつ",
1133				"㍍ガバヴァぱばぐゞちぢ十人十色",
1134				"1fef28785d08cbf41d7a20a3a6891043395779ed74503a5652760ee8c24dfe60972105ee71d5168071a35ab7b5bd2f8831f75488078a90f0926c8e9171b2bc4a",
1135			),
1136			(
1137				"4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef",
1138				"こころ いどう きあつ そうがんきょう へいあん せつりつ ごうせい はいち いびき きこく あんい おちつく きこえる けんとう たいこ すすめる はっけん ていど はんおん いんさつ うなぎ しねま れいぼう みつかる",
1139				"㍍ガバヴァぱばぐゞちぢ十人十色",
1140				"43de99b502e152d4c198542624511db3007c8f8f126a30818e856b2d8a20400d29e7a7e3fdd21f909e23be5e3c8d9aee3a739b0b65041ff0b8637276703f65c2",
1141			),
1142			(
1143				"18ab19a9f54a9274f03e5209a2ac8a91",
1144				"うりきれ さいせい じゆう むろん とどける ぐうたら はいれつ ひけつ いずれ うちあわせ おさめる おたく",
1145				"㍍ガバヴァぱばぐゞちぢ十人十色",
1146				"3d711f075ee44d8b535bb4561ad76d7d5350ea0b1f5d2eac054e869ff7963cdce9581097a477d697a2a9433a0c6884bea10a2193647677977c9820dd0921cbde",
1147			),
1148			(
1149				"18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4",
1150				"うりきれ うねる せっさたくま きもち めんきょ へいたく たまご ぜっく びじゅつかん さんそ むせる せいじ ねくたい しはらい せおう ねんど たんまつ がいけん",
1151				"㍍ガバヴァぱばぐゞちぢ十人十色",
1152				"753ec9e333e616e9471482b4b70a18d413241f1e335c65cd7996f32b66cf95546612c51dcf12ead6f805f9ee3d965846b894ae99b24204954be80810d292fcdd",
1153			),
1154			(
1155				"15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419",
1156				"うちゅう ふそく ひしょ がちょう うけもつ めいそう みかん そざい いばる うけとる さんま さこつ おうさま ぱんつ しひょう めした たはつ いちぶ つうじょう てさぎょう きつね みすえる いりぐち かめれおん",
1157				"㍍ガバヴァぱばぐゞちぢ十人十色",
1158				"346b7321d8c04f6f37b49fdf062a2fddc8e1bf8f1d33171b65074531ec546d1d3469974beccb1a09263440fc92e1042580a557fdce314e27ee4eabb25fa5e5fe",
1159			)
1160		];
1161
1162		for vector in &vectors {
1163			let entropy = Vec::<u8>::from_hex(&vector.0).unwrap();
1164			let mnemonic_str = vector.1;
1165			let passphrase = vector.2;
1166			let seed = Vec::<u8>::from_hex(&vector.3).unwrap();
1167
1168			let mnemonic = Mnemonic::from_entropy_in(Language::Japanese, &entropy).unwrap();
1169
1170			assert_eq!(seed, &mnemonic.to_seed(passphrase)[..], "failed vector: {}", mnemonic_str);
1171			let rt = Mnemonic::parse_in(Language::Japanese, mnemonic.to_string())
1172				.expect(&format!("vector: {}", mnemonic_str));
1173			assert_eq!(seed, &rt.to_seed(passphrase)[..]);
1174
1175			let mnemonic = Mnemonic::parse_in(Language::Japanese, mnemonic_str)
1176				.expect(&format!("vector: {}", mnemonic_str));
1177			assert_eq!(seed, &mnemonic.to_seed(passphrase)[..], "failed vector: {}", mnemonic_str);
1178		}
1179	}
1180}