1use std::fmt;
6use std::str::FromStr;
7
8use rand_core::CryptoRng;
9use sha2::{Digest, Sha256, Sha512};
10use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
11use zeroize::Zeroizing;
12
13pub static ENGLISH: [&str; 2048] = split_lines(include_str!("bip39/english.txt"));
15
16pub const ENGLISH_NOTICE: &str = include_str!("bip39/NOTICE");
18
19const fn split_lines(text: &str) -> [&str; 2048] {
21 let mut words = [""; 2048];
22 let mut rest = text;
23 let mut index = 0;
24 while index < words.len() {
25 let mut length = 0;
26 while rest.as_bytes()[length] != b'\n' {
27 length += 1;
28 }
29 let (word, tail) = rest.split_at(length);
30 words[index] = word;
31 rest = tail.split_at(1).1;
32 index += 1;
33 }
34 assert!(rest.is_empty(), "the word list has more than 2048 lines");
35 words
36}
37
38const MAX_WORD_LENGTH: usize = 8;
40const MAX_WORD_COUNT: usize = 24;
41const MAX_ENTROPY_LENGTH: usize = 32;
42const MAX_PHRASE_LENGTH: usize = MAX_WORD_COUNT * (MAX_WORD_LENGTH + 1) - 1;
44const MAX_PASSPHRASE_LENGTH: usize = 256;
45const SALT_PREFIX: &[u8] = b"mnemonic";
47
48pub struct Mnemonic {
51 entropy: Zeroizing<[u8; MAX_ENTROPY_LENGTH]>,
52 length: usize,
53}
54
55impl Mnemonic {
56 pub fn generate_with_rng<R: CryptoRng + ?Sized>(rng: &mut R, word_count: WordCount) -> Self {
58 let mut entropy = Zeroizing::new([0; MAX_ENTROPY_LENGTH]);
59 let length = word_count.entropy_length();
60 rng.fill_bytes(&mut entropy[..length]);
61 Self::from_entropy(&entropy[..length]).expect("the word count fixes the length")
62 }
63
64 #[cfg(feature = "getrandom")]
66 pub fn generate(word_count: WordCount) -> Result<Self, getrandom::Error> {
67 let mut entropy = Zeroizing::new([0; MAX_ENTROPY_LENGTH]);
68 let length = word_count.entropy_length();
69 getrandom::fill(&mut entropy[..length])?;
70 Ok(Self::from_entropy(&entropy[..length]).expect("the word count fixes the length"))
71 }
72
73 pub fn from_entropy(entropy: &[u8]) -> Result<Self, InvalidEntropyLength> {
75 if !matches!(entropy.len(), 16 | 20 | 24 | 28 | 32) {
76 return Err(InvalidEntropyLength);
77 }
78 let mut bytes = Zeroizing::new([0; MAX_ENTROPY_LENGTH]);
79 bytes[..entropy.len()].copy_from_slice(entropy);
80 Ok(Self {
81 entropy: bytes,
82 length: entropy.len(),
83 })
84 }
85
86 pub fn entropy(&self) -> &[u8] {
88 &self.entropy[..self.length]
89 }
90
91 pub fn word_count(&self) -> usize {
93 self.length * 3 / 4
94 }
95
96 pub fn to_phrase(&self) -> Zeroizing<String> {
98 let mut buffer = Zeroizing::new([0; MAX_PHRASE_LENGTH]);
99 let length = self.write_phrase(&mut buffer);
100 Zeroizing::new(
101 str::from_utf8(&buffer[..length])
102 .expect("the word list is ASCII")
103 .to_owned(),
104 )
105 }
106
107 pub fn to_seed(&self, passphrase: &str) -> Result<Seed, InvalidPassphrase> {
112 if !passphrase.is_ascii() {
113 return Err(InvalidPassphrase::NonAscii);
114 }
115 if passphrase.len() > MAX_PASSPHRASE_LENGTH {
116 return Err(InvalidPassphrase::TooLong);
117 }
118 let mut password = Zeroizing::new([0; MAX_PHRASE_LENGTH]);
119 let password_length = self.write_phrase(&mut password);
120 let mut salt = Zeroizing::new([0; SALT_PREFIX.len() + MAX_PASSPHRASE_LENGTH]);
121 let salt_length = SALT_PREFIX.len() + passphrase.len();
122 salt[..SALT_PREFIX.len()].copy_from_slice(SALT_PREFIX);
123 salt[SALT_PREFIX.len()..salt_length].copy_from_slice(passphrase.as_bytes());
124 let mut seed = Zeroizing::new([0; 64]);
125 pbkdf2::pbkdf2_hmac::<Sha512>(
126 &password[..password_length],
127 &salt[..salt_length],
128 2048,
129 &mut *seed,
130 );
131 Ok(Seed(seed))
132 }
133
134 fn write_phrase(&self, buffer: &mut [u8; MAX_PHRASE_LENGTH]) -> usize {
136 let mut cursor = 0;
137 for (position, &index) in self
138 .word_indices()
139 .iter()
140 .take(self.word_count())
141 .enumerate()
142 {
143 if position > 0 {
144 buffer[cursor] = b' ';
145 cursor += 1;
146 }
147 let word = Zeroizing::new(word_at(index).to_le_bytes());
148 let length = word_length(&word);
149 buffer[cursor..cursor + length].copy_from_slice(&word[..length]);
150 cursor += length;
151 }
152 cursor
153 }
154
155 fn word_indices(&self) -> Zeroizing<[u16; MAX_WORD_COUNT]> {
157 let mut bits = Zeroizing::new([0; MAX_ENTROPY_LENGTH + 3]);
158 bits[..self.length].copy_from_slice(self.entropy());
159 bits[self.length] = checksum(self.entropy());
160 let mut indices = Zeroizing::new([0; MAX_WORD_COUNT]);
161 for (position, index) in indices.iter_mut().take(self.word_count()).enumerate() {
162 let offset = position * 11;
163 let start = offset / 8;
164 let window = u32::from_be_bytes([0, bits[start], bits[start + 1], bits[start + 2]]);
165 *index = (window >> (24 - 11 - offset % 8)) as u16 & 0x7FF;
166 }
167 indices
168 }
169}
170
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum WordCount {
174 Words12,
175 Words15,
176 Words18,
177 Words21,
178 Words24,
179}
180
181impl WordCount {
182 pub fn get(self) -> usize {
184 match self {
185 Self::Words12 => 12,
186 Self::Words15 => 15,
187 Self::Words18 => 18,
188 Self::Words21 => 21,
189 Self::Words24 => 24,
190 }
191 }
192
193 fn entropy_length(self) -> usize {
195 self.get() * 4 / 3
196 }
197}
198
199impl fmt::Debug for Mnemonic {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.write_str("Mnemonic(..)")
202 }
203}
204
205impl FromStr for Mnemonic {
206 type Err = ParseMnemonicError;
207
208 fn from_str(text: &str) -> Result<Self, Self::Err> {
210 let word_count = text.split_whitespace().count();
211 if !matches!(word_count, 12 | 15 | 18 | 21 | 24) {
212 return Err(ParseMnemonicError::InvalidWordCount);
213 }
214 let mut bits = Zeroizing::new([0; MAX_ENTROPY_LENGTH + 3]);
215 for (position, word) in text.split_whitespace().enumerate() {
216 let index = index_of(word).ok_or(ParseMnemonicError::UnknownWord)?;
217 let offset = position * 11;
218 let start = offset / 8;
219 let window = Zeroizing::new((u32::from(index) << (24 - 11 - offset % 8)).to_be_bytes());
220 bits[start] |= window[1];
221 bits[start + 1] |= window[2];
222 bits[start + 2] |= window[3];
223 }
224 let length = word_count * 4 / 3;
225 let mnemonic =
226 Self::from_entropy(&bits[..length]).expect("the word count fixes the length");
227 let shift = 8 - word_count / 3;
229 if bits[length] >> shift != checksum(mnemonic.entropy()) >> shift {
230 return Err(ParseMnemonicError::InvalidChecksum);
231 }
232 Ok(mnemonic)
233 }
234}
235
236fn checksum(entropy: &[u8]) -> u8 {
238 let hash = Zeroizing::new(<[u8; 32]>::from(Sha256::digest(entropy)));
239 hash[0]
240}
241
242fn pack(word: &str) -> Option<u64> {
245 let bytes = word.as_bytes();
246 if bytes.len() > MAX_WORD_LENGTH {
247 return None;
248 }
249 let mut padded = Zeroizing::new([0; MAX_WORD_LENGTH]);
250 padded[..bytes.len()].copy_from_slice(bytes);
251 Some(u64::from_le_bytes(*padded))
252}
253
254fn word_length(padded: &[u8; MAX_WORD_LENGTH]) -> usize {
256 padded.iter().map(|&byte| usize::from(byte != 0)).sum()
257}
258
259fn index_of(word: &str) -> Option<u16> {
260 let target = Zeroizing::new(pack(word)?);
261 let mut found = Choice::from(0);
262 let mut index = Zeroizing::new(0u16);
263 for (candidate, entry) in (0..).zip(&ENGLISH) {
264 let matched = pack(entry).expect("the word list fits").ct_eq(&target);
265 index.conditional_assign(&candidate, matched);
266 found |= matched;
267 }
268 bool::from(found).then_some(*index)
269}
270
271fn word_at(index: u16) -> u64 {
272 let mut word = 0u64;
273 for (candidate, entry) in (0u16..).zip(&ENGLISH) {
274 let packed = pack(entry).expect("the word list fits");
275 word.conditional_assign(&packed, candidate.ct_eq(&index));
276 }
277 word
278}
279
280#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct InvalidEntropyLength;
283
284impl fmt::Display for InvalidEntropyLength {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 f.write_str("エントロピーは16、20、24、28、32バイトのどれかのはずです")
287 }
288}
289
290impl std::error::Error for InvalidEntropyLength {}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
294pub enum ParseMnemonicError {
295 InvalidWordCount,
297 UnknownWord,
299 InvalidChecksum,
301}
302
303impl fmt::Display for ParseMnemonicError {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 match self {
306 Self::InvalidWordCount => f.write_str("ニーモニックは12、15、18、21、24語のどれかのはずです"),
307 Self::UnknownWord => f.write_str("ニーモニックに単語リストにない単語が含まれています"),
308 Self::InvalidChecksum => f.write_str("ニーモニックのチェックサムが合いません。単語の書き間違いか順番の入れ違いがありそうです"),
309 }
310 }
311}
312
313impl std::error::Error for ParseMnemonicError {}
314
315pub struct Seed(Zeroizing<[u8; 64]>);
317
318impl Seed {
319 pub fn as_bytes(&self) -> &[u8; 64] {
320 &self.0
321 }
322}
323
324impl fmt::Debug for Seed {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.write_str("Seed(..)")
327 }
328}
329
330#[derive(Debug, Clone, PartialEq, Eq)]
332pub enum InvalidPassphrase {
333 NonAscii,
335 TooLong,
337}
338
339impl fmt::Display for InvalidPassphrase {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 match self {
342 Self::NonAscii => f.write_str("パスフレーズには ASCII の文字だけが使えます"),
343 Self::TooLong => f.write_str("パスフレーズは256バイトまでです"),
344 }
345 }
346}
347
348impl std::error::Error for InvalidPassphrase {}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353 use crate::testing::Replay;
354
355 #[test]
356 fn english_is_sorted_without_duplicates() {
357 assert!(ENGLISH.is_sorted_by(|a, b| a < b));
358 }
359
360 #[test]
361 fn english_words_are_lower_case_ascii() {
362 for word in &ENGLISH {
363 assert!(
364 !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase()),
365 "{word:?}"
366 );
367 }
368 }
369
370 #[test]
371 fn english_words_fit_in_max_word_length() {
372 assert_eq!(
373 ENGLISH.iter().map(|word| word.len()).max(),
374 Some(MAX_WORD_LENGTH)
375 );
376 }
377
378 #[test]
379 fn english_starts_and_ends_with_the_known_words() {
380 assert_eq!(ENGLISH[0], "abandon");
381 assert_eq!(ENGLISH[3], "about");
382 assert_eq!(ENGLISH[2047], "zoo");
383 }
384 const VECTORS: [(u8, usize, &str); 6] = [
386 (
387 0x00,
388 16,
389 "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
390 ),
391 (
392 0x7F,
393 16,
394 "legal winner thank year wave sausage worth useful legal winner thank yellow",
395 ),
396 (
397 0x80,
398 16,
399 "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
400 ),
401 (
402 0xFF,
403 16,
404 "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
405 ),
406 (
407 0x00,
408 24,
409 "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
410 ),
411 (
412 0xFF,
413 32,
414 "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote",
415 ),
416 ];
417
418 #[test]
419 fn converts_entropy_to_phrase() {
420 for (byte, length, phrase) in VECTORS {
421 let mnemonic = Mnemonic::from_entropy(&vec![byte; length]).unwrap();
422 assert_eq!(*mnemonic.to_phrase(), phrase);
423 assert_eq!(mnemonic.word_count(), length * 3 / 4);
424 }
425 }
426
427 #[test]
428 fn parses_phrase_to_entropy() {
429 for (byte, length, phrase) in VECTORS {
430 let mnemonic: Mnemonic = phrase.parse().unwrap();
431 assert_eq!(mnemonic.entropy(), vec![byte; length]);
432 }
433 }
434
435 #[test]
436 fn ignores_extra_whitespace() {
437 let phrase = format!(" {}\n", VECTORS[0].2.replace(' ', " \t "));
438 let mnemonic: Mnemonic = phrase.parse().unwrap();
439 assert_eq!(*mnemonic.to_phrase(), VECTORS[0].2);
440 }
441
442 #[test]
443 fn rejects_entropy_of_invalid_length() {
444 assert_eq!(
445 Mnemonic::from_entropy(&[0; 15]).unwrap_err(),
446 InvalidEntropyLength
447 );
448 }
449
450 #[test]
451 fn rejects_invalid_word_count() {
452 let phrase = VECTORS[0].2.rsplit_once(' ').unwrap().0;
453 assert_eq!(
454 phrase.parse::<Mnemonic>().unwrap_err(),
455 ParseMnemonicError::InvalidWordCount
456 );
457 }
458
459 #[test]
460 fn rejects_unknown_words_without_revealing_them() {
461 for typo in ["abandonn", "abandonment", "Abandon", "あ"] {
462 let phrase = VECTORS[0].2.replacen("abandon", typo, 1);
463 let error = phrase.parse::<Mnemonic>().unwrap_err();
464 assert_eq!(error, ParseMnemonicError::UnknownWord);
465 assert!(!error.to_string().contains(typo));
466 }
467 }
468
469 #[test]
470 fn rejects_invalid_checksum() {
471 let phrase = "abandon ".repeat(12);
472 assert_eq!(
473 phrase.parse::<Mnemonic>().unwrap_err(),
474 ParseMnemonicError::InvalidChecksum
475 );
476 }
477
478 #[test]
479 fn debug_hides_the_mnemonic() {
480 let mnemonic: Mnemonic = VECTORS[0].2.parse().unwrap();
481 assert_eq!(format!("{mnemonic:?}"), "Mnemonic(..)");
482 }
483
484 #[test]
485 fn derives_the_seed_with_a_passphrase() {
486 let mnemonic: Mnemonic = VECTORS[0].2.parse().unwrap();
488 let seed = mnemonic.to_seed("TREZOR").unwrap();
489 assert_eq!(
490 seed.as_bytes()[..],
491 hex(
492 "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04"
493 )
494 );
495 }
496
497 #[test]
498 fn accepts_a_passphrase_up_to_256_bytes() {
499 let mnemonic: Mnemonic = VECTORS[0].2.parse().unwrap();
500 assert!(mnemonic.to_seed(&"a".repeat(256)).is_ok());
501 assert_eq!(
502 mnemonic.to_seed(&"a".repeat(257)).unwrap_err(),
503 InvalidPassphrase::TooLong
504 );
505 }
506
507 #[test]
508 fn rejects_a_non_ascii_passphrase() {
509 let mnemonic: Mnemonic = VECTORS[0].2.parse().unwrap();
510 assert_eq!(
511 mnemonic.to_seed("パス").unwrap_err(),
512 InvalidPassphrase::NonAscii
513 );
514 }
515
516 #[test]
517 fn seed_debug_hides_the_seed() {
518 let mnemonic: Mnemonic = VECTORS[0].2.parse().unwrap();
519 assert_eq!(format!("{:?}", mnemonic.to_seed("").unwrap()), "Seed(..)");
520 }
521
522 #[test]
523 fn generates_from_the_given_rng() {
524 for (byte, length, phrase) in VECTORS {
525 let bytes = vec![byte; 32];
526 let word_count = match length {
527 16 => WordCount::Words12,
528 24 => WordCount::Words18,
529 32 => WordCount::Words24,
530 _ => unreachable!(),
531 };
532 let mnemonic = Mnemonic::generate_with_rng(&mut Replay(&bytes), word_count);
533 assert_eq!(*mnemonic.to_phrase(), phrase);
534 }
535 }
536
537 #[cfg(feature = "getrandom")]
538 #[test]
539 fn generates_different_mnemonics_from_the_os() {
540 let first = Mnemonic::generate(WordCount::Words24).unwrap();
541 let second = Mnemonic::generate(WordCount::Words24).unwrap();
542 assert_eq!(first.word_count(), 24);
543 assert_ne!(first.entropy(), second.entropy());
544 }
545
546 fn hex(text: &str) -> Vec<u8> {
547 (0..text.len())
548 .step_by(2)
549 .map(|index| u8::from_str_radix(&text[index..index + 2], 16).unwrap())
550 .collect()
551 }
552}