bip0039 0.14.1

Another Rust implementation of BIP-0039 standard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
mod bit_accumulator;
mod entropy;
mod phrase;
mod seed;

#[cfg(not(feature = "std"))]
use alloc::{
    borrow::Cow,
    string::{String, ToString},
    vec::Vec,
};
use core::{fmt, marker::PhantomData, mem, str};
#[cfg(feature = "std")]
use std::borrow::Cow;

use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfkd_quick};
use zeroize::Zeroizing;

use self::{
    bit_accumulator::BitAccumulator,
    entropy::{encode_entropy, encode_entropy_with},
    phrase::{DecodeMode, decode_phrase},
    seed::to_seed,
};
use crate::{
    error::Error,
    language::{AnyLanguage, English, Language},
};

const BITS_PER_WORD: usize = 11;
const BITS_PER_BYTE: usize = 8;

/// Determines the words count that will be present in a [`Mnemonic`](crate::Mnemonic) phrase.
#[derive(Copy, Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum Count {
    /// 12 words, entropy length: 128 bits, the checksum length: 4 bits.
    #[default]
    Words12,
    /// 15 words, entropy length: 160 bits, the checksum length: 5 bits.
    Words15,
    /// 18 words, entropy length: 192 bits, the checksum length: 6 bits.
    Words18,
    /// 21 words, entropy length: 224 bits, the checksum length: 7 bits.
    Words21,
    /// 24 words, entropy length: 256 bits, the checksum length: 8 bits.
    Words24,
}

impl fmt::Display for Count {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} words (entropy {} bits + checksum {} bits)",
            self.word_count(),
            self.entropy_bit_length(),
            self.checksum_bit_length()
        )
    }
}

impl From<Count> for usize {
    fn from(count: Count) -> Self {
        match count {
            Count::Words12 => 12,
            Count::Words15 => 15,
            Count::Words18 => 18,
            Count::Words21 => 21,
            Count::Words24 => 24,
        }
    }
}

impl TryFrom<usize> for Count {
    type Error = Error;

    fn try_from(count: usize) -> Result<Self, Self::Error> {
        Self::from_word_count(count)
    }
}

impl Count {
    /// Creates a [`Count`] for a mnemonic phrase with the given word count.
    const fn from_word_count(count: usize) -> Result<Self, Error> {
        Ok(match count {
            12 => Self::Words12,
            15 => Self::Words15,
            18 => Self::Words18,
            21 => Self::Words21,
            24 => Self::Words24,
            others => return Err(Error::BadWordCount(others)),
        })
    }

    /// Creates a [`Count`] for a mnemonic phrase with the given entropy bits size.
    const fn from_key_size(size: usize) -> Result<Self, Error> {
        Ok(match size {
            128 => Self::Words12,
            160 => Self::Words15,
            192 => Self::Words18,
            224 => Self::Words21,
            256 => Self::Words24,
            others => return Err(Error::BadEntropyBitCount(others)),
        })
    }

    /// Creates a [`Count`] for an existing mnemonic phrase.
    fn from_phrase<P: AsRef<str>>(phrase: P) -> Result<Self, Error> {
        let word_count = phrase.as_ref().split_whitespace().count();
        Self::from_word_count(word_count)
    }

    /// Returns the number of words.
    pub const fn word_count(&self) -> usize {
        match self {
            Self::Words12 => 12,
            Self::Words15 => 15,
            Self::Words18 => 18,
            Self::Words21 => 21,
            Self::Words24 => 24,
        }
    }

    /// Returns the size of `entropy + checksum` in bits.
    pub const fn total_bit_length(&self) -> usize {
        self.entropy_bit_length() + self.checksum_bit_length()
    }

    /// Returns the size of entropy in bits.
    pub const fn entropy_bit_length(&self) -> usize {
        match self {
            Self::Words12 => 128,
            Self::Words15 => 160,
            Self::Words18 => 192,
            Self::Words21 => 224,
            Self::Words24 => 256,
        }
    }

    /// Returns the size of checksum in bits.
    pub const fn checksum_bit_length(&self) -> usize {
        match self {
            Self::Words12 => 4,
            Self::Words15 => 5,
            Self::Words18 => 6,
            Self::Words21 => 7,
            Self::Words24 => 8,
        }
    }
}

/// A mnemonic representation.
///
/// First, an initial entropy of ENT bits is generated.
/// A checksum is generated by taking the first `ENT/32` bits of its SHA256 hash.
/// This checksum is appended to the end of the initial entropy.
///
/// Next, these concatenated bits are split into groups of `11` bits,
/// each encoding a number from 0-2047, serving as an index into a wordlist.
///
/// Finally, we convert these numbers into words and use the joined words as a mnemonic sentence.
///
/// - **ENT**: the initial entropy length
/// - **CS**: the checksum length
/// - **MS**: the length of the generated mnemonic sentence in words
///
/// **CS** = **ENT** / 32
///
/// **MS** = (**ENT** + **CS**) / 11
///
/// |  ENT  |  CS  | ENT+CS |  MS  |
/// | :---: | :--: | :----: | :--: |
/// |  128  |  4   |  132   |  12  |
/// |  160  |  5   |  165   |  15  |
/// |  192  |  6   |  198   |  18  |
/// |  224  |  7   |  231   |  21  |
/// |  256  |  8   |  264   |  24  |
///
/// For example, a 12 word mnemonic phrase is essentially a friendly representation of
/// a 128-bit key, while a 24 word mnemonic phrase is essentially a 256-bit key.
#[derive(Clone, Eq, PartialEq)]
pub struct Mnemonic<L = English> {
    lang: PhantomData<L>,
    phrase: Zeroizing<String>,
    entropy: Zeroizing<Vec<u8>>,
}

impl<L: Language> fmt::Debug for Mnemonic<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.phrase())
    }
}

impl<L: Language> fmt::Display for Mnemonic<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.phrase())
    }
}

impl<L: Language> str::FromStr for Mnemonic<L> {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_phrase(s)
    }
}

impl<L: Language> AsRef<str> for Mnemonic<L> {
    fn as_ref(&self) -> &str {
        self.phrase()
    }
}

impl<L: Language> Mnemonic<L> {
    /// Generates a new [`Mnemonic`] randomly in the specified word count.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bip0039::{Count, Mnemonic};
    ///
    /// let mnemonic = <Mnemonic>::generate(Count::Words12);
    /// let phrase = mnemonic.phrase();
    /// ```
    #[cfg_attr(
        feature = "chinese-simplified",
        doc = r##"
```rust
use bip0039::{ChineseSimplified, Count, Mnemonic};

let mnemonic = <Mnemonic<ChineseSimplified>>::generate(Count::Words24);
let phrase = mnemonic.phrase();
```
"##
    )]
    #[cfg(feature = "rand")]
    pub fn generate(word_count: Count) -> Self {
        use rand::Rng;
        let mut rng = rand::rng();

        match word_count {
            Count::Words12 => {
                let mut entropy = [0u8; 16];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(entropy)
            },
            Count::Words15 => {
                let mut entropy = [0u8; 20];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(entropy)
            },
            Count::Words18 => {
                let mut entropy = [0u8; 24];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(entropy)
            },
            Count::Words21 => {
                let mut entropy = [0u8; 28];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(entropy)
            },
            Count::Words24 => {
                let mut entropy = [0u8; 32];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(entropy)
            },
        }
        .expect("valid entropy length won't fail to generate the mnemonic")
    }

    /// Creates a new [`Mnemonic`] from the given entropy.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::Mnemonic;
    ///
    /// let entropy = const_hex::decode("1a486a5fbe53639984cb64b070755f7b").unwrap();
    /// let mnemonic = <Mnemonic>::from_entropy(entropy).unwrap();
    /// assert_eq!(mnemonic.phrase(), "bottom drive obey lake curtain smoke basket hold race lonely fit walk");
    /// ```
    pub fn from_entropy<E: Into<Vec<u8>>>(entropy: E) -> Result<Self, Error> {
        let entropy = entropy.into();
        let phrase = encode_entropy::<L>(&entropy)?;

        Ok(Self {
            lang: PhantomData::<L>,
            phrase: Zeroizing::new(phrase),
            entropy: Zeroizing::new(entropy),
        })
    }

    /// Creates a [`Mnemonic`] from an existing mnemonic phrase.
    ///
    /// This method will normalize the input (UTF-8 NFKD) and normalize whitespace
    /// (single ASCII spaces).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bip0039::{Error, Mnemonic};
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = <Mnemonic>::from_phrase(phrase).unwrap();
    /// assert_eq!(mnemonic.phrase(), phrase);
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let mnemonic = <Mnemonic>::from_phrase(phrase);
    /// assert_eq!(mnemonic.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    pub fn from_phrase<'a, P: Into<Cow<'a, str>>>(phrase: P) -> Result<Self, Error> {
        let mut phrase = phrase.into();
        normalize_utf8(&mut phrase);

        Self::from_normalized_phrase(phrase)
    }

    /// Creates a [`Mnemonic`] from a phrase that is already normalized.
    ///
    /// Use this when you can guarantee the input is already normalized to UTF-8 NFKD.
    ///
    /// This avoids the UTF-8 NFKD normalization step during decoding, since the input is already
    /// normalized.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bip0039::{Error, Mnemonic};
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = <Mnemonic>::from_normalized_phrase(phrase).unwrap();
    /// assert_eq!(mnemonic.phrase(), phrase);
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let mnemonic = <Mnemonic>::from_normalized_phrase(phrase);
    /// assert_eq!(mnemonic.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    pub fn from_normalized_phrase<'a, P: Into<Cow<'a, str>>>(phrase: P) -> Result<Self, Error> {
        let phrase = phrase.into();

        let decoded = decode_phrase::<L>(&phrase, DecodeMode::BuildNormalizedPhrase)?;
        let entropy = decoded.entropy;
        let normalized_phrase = decoded
            .normalized_phrase
            .expect("BuildNormalizedPhrase always constructs a normalized phrase");

        Ok(Mnemonic {
            lang: PhantomData::<L>,
            phrase: Zeroizing::new(normalized_phrase),
            entropy: Zeroizing::new(entropy),
        })
    }

    /// Validates the word count and checksum of a mnemonic phrase.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bip0039::{Error, Mnemonic};
    /// use unicode_normalization::UnicodeNormalization;
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let result = <Mnemonic>::validate(phrase);
    /// assert!(result.is_ok());
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let result = <Mnemonic>::validate(phrase);
    /// assert_eq!(result.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    #[cfg_attr(
        feature = "japanese",
        doc = r##"
```rust
use bip0039::{Error, Japanese, Mnemonic};
use unicode_normalization::UnicodeNormalization;

let phrase = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ";
let result = <Mnemonic<Japanese>>::validate(phrase);
assert!(result.is_ok());

let phrase = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく ばか";
let result = <Mnemonic<Japanese>>::validate(phrase);
assert_eq!(result.unwrap_err(), Error::UnknownWord("ばか".nfkd().to_string()));
```
"##
    )]
    pub fn validate<'a, P: Into<Cow<'a, str>>>(phrase: P) -> Result<(), Error> {
        let mut phrase = phrase.into();
        normalize_utf8(&mut phrase);

        let _decoded = decode_phrase::<L>(&phrase, DecodeMode::ValidateOnly)?;
        Ok(())
    }

    /// Generates the seed from the [`Mnemonic`] and the passphrase.
    ///
    /// If a passphrase is not present, an empty string `""` is used instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::Mnemonic;
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = <Mnemonic>::from_phrase(phrase).unwrap();
    /// assert_eq!(mnemonic.to_seed("").len(), 64);
    /// ```
    pub fn to_seed<P: AsRef<str>>(&self, passphrase: P) -> [u8; 64] {
        // the phrase has been normalized
        to_seed(self.phrase(), passphrase.as_ref())
    }

    /// Returns the mnemonic phrase as a string slice.
    ///
    /// Note: the returned phrase is normalized (UTF-8 NFKD; words separated by single ASCII
    /// spaces).
    pub fn phrase(&self) -> &str {
        &self.phrase
    }

    /// Consumes the `Mnemonic` and return the phrase as a `String`.
    pub fn into_phrase(mut self) -> String {
        // Create an empty string and swap values with the mnemonic's phrase.
        // This allows `Mnemonic` to implement `Drop`, while still returning the phrase.
        mem::take(&mut self.phrase)
    }

    /// Returns the original entropy of the mnemonic phrase.
    pub fn entropy(&self) -> &[u8] {
        &self.entropy
    }

    /// Consumes the `Mnemonic` and return the entropy as a `Vec<u8>`.
    pub fn into_entropy(mut self) -> Vec<u8> {
        // Create an empty bytes and swap values with the mnemonic's entropy.
        // This allows `Mnemonic` to implement `Drop`, while still returning the entropy.
        mem::take(&mut self.entropy)
    }
}

/// A mnemonic representation with a runtime-selected language.
///
/// This is a non-breaking alternative to `Mnemonic<L>` for applications that want to select a
/// language at runtime (e.g. from user configuration), while keeping the existing generic API
/// intact.
#[derive(Clone, Eq, PartialEq)]
pub struct AnyMnemonic {
    language: AnyLanguage,
    phrase: Zeroizing<String>,
    entropy: Zeroizing<Vec<u8>>,
}

impl fmt::Debug for AnyMnemonic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.phrase())
    }
}

impl fmt::Display for AnyMnemonic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.phrase())
    }
}

impl AsRef<str> for AnyMnemonic {
    fn as_ref(&self) -> &str {
        self.phrase()
    }
}

impl AnyMnemonic {
    /// Generates a new [`AnyMnemonic`] randomly in the specified word count using `language`.
    ///
    /// Note: this requires the `rand` feature.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage, Count};
    ///
    /// let mnemonic = AnyMnemonic::generate(BuiltInLanguage::English, Count::Words12);
    /// let phrase = mnemonic.phrase();
    /// ```
    #[cfg(feature = "rand")]
    pub fn generate(language: impl Into<AnyLanguage>, word_count: Count) -> Self {
        let language: AnyLanguage = language.into();
        use rand::Rng;
        let mut rng = rand::rng();

        match word_count {
            Count::Words12 => {
                let mut entropy = [0u8; 16];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(language, entropy)
            },
            Count::Words15 => {
                let mut entropy = [0u8; 20];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(language, entropy)
            },
            Count::Words18 => {
                let mut entropy = [0u8; 24];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(language, entropy)
            },
            Count::Words21 => {
                let mut entropy = [0u8; 28];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(language, entropy)
            },
            Count::Words24 => {
                let mut entropy = [0u8; 32];
                rng.fill_bytes(&mut entropy);
                Self::from_entropy(language, entropy)
            },
        }
        .expect("valid entropy length won't fail to generate the mnemonic")
    }

    /// Creates a new [`AnyMnemonic`] from the given entropy using `language`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage, Count};
    ///
    /// let entropy = const_hex::decode("1a486a5fbe53639984cb64b070755f7b").unwrap();
    /// let mnemonic = AnyMnemonic::from_entropy(BuiltInLanguage::English, entropy).unwrap();
    /// assert_eq!(mnemonic.phrase(), "bottom drive obey lake curtain smoke basket hold race lonely fit walk");
    /// ```
    pub fn from_entropy<E: Into<Vec<u8>>>(
        language: impl Into<AnyLanguage>,
        entropy: E,
    ) -> Result<Self, Error> {
        let language: AnyLanguage = language.into();
        let entropy = entropy.into();
        let phrase = encode_entropy_with(language, &entropy)?;

        Ok(Self { language, phrase: Zeroizing::new(phrase), entropy: Zeroizing::new(entropy) })
    }

    /// Creates an [`AnyMnemonic`] from an existing mnemonic phrase using `language`.
    ///
    /// This method will normalize the input (UTF-8 NFKD) and normalize whitespace
    /// (single ASCII spaces).
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage, Error};
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = AnyMnemonic::from_phrase(BuiltInLanguage::English, phrase).unwrap();
    /// assert_eq!(mnemonic.phrase(), phrase);
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let mnemonic = AnyMnemonic::from_phrase(BuiltInLanguage::English, phrase);
    /// assert_eq!(mnemonic.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    pub fn from_phrase<'a, P: Into<Cow<'a, str>>>(
        language: impl Into<AnyLanguage>,
        phrase: P,
    ) -> Result<Self, Error> {
        let language = language.into();
        let mut phrase = phrase.into();
        normalize_utf8(&mut phrase);
        Self::from_normalized_phrase(language, phrase)
    }

    /// Creates an [`AnyMnemonic`] from a phrase that is already normalized using `language`.
    ///
    /// Use this when you can guarantee the input is already normalized to UTF-8 NFKD.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage, Error};
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = AnyMnemonic::from_normalized_phrase(BuiltInLanguage::English, phrase).unwrap();
    /// assert_eq!(mnemonic.phrase(), phrase);
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let mnemonic = AnyMnemonic::from_normalized_phrase(BuiltInLanguage::English, phrase);
    /// assert_eq!(mnemonic.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    pub fn from_normalized_phrase<'a, P: Into<Cow<'a, str>>>(
        language: impl Into<AnyLanguage>,
        phrase: P,
    ) -> Result<Self, Error> {
        let language = language.into();
        let phrase = phrase.into();

        let decoded =
            phrase::decode_phrase_with(language, &phrase, DecodeMode::BuildNormalizedPhrase)?;
        let entropy = decoded.entropy;
        let normalized_phrase = decoded
            .normalized_phrase
            .expect("BuildNormalizedPhrase always constructs a normalized phrase");

        Ok(Self {
            language,
            phrase: Zeroizing::new(normalized_phrase),
            entropy: Zeroizing::new(entropy),
        })
    }

    /// Validates the word count and checksum of a mnemonic phrase using `language`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage, Error};
    /// use unicode_normalization::UnicodeNormalization;
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let result = AnyMnemonic::validate(BuiltInLanguage::English, phrase);
    /// assert!(result.is_ok());
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit shit";
    /// let result = AnyMnemonic::validate(BuiltInLanguage::English, phrase);
    /// assert_eq!(result.unwrap_err(), Error::UnknownWord("shit".into()));
    /// ```
    #[cfg_attr(
        feature = "japanese",
        doc = r##"
```rust
use bip0039::{Error, Japanese, Mnemonic};
use unicode_normalization::UnicodeNormalization;

let phrase = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ";
let result = <Mnemonic<Japanese>>::validate(phrase);
assert!(result.is_ok());

let phrase = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく ばか";
let result = <Mnemonic<Japanese>>::validate(phrase);
assert_eq!(result.unwrap_err(), Error::UnknownWord("ばか".nfkd().to_string()));
```
"##
    )]
    ///
    pub fn validate<'a, P: Into<Cow<'a, str>>>(
        language: impl Into<AnyLanguage>,
        phrase: P,
    ) -> Result<(), Error> {
        let language = language.into();
        let mut phrase = phrase.into();
        normalize_utf8(&mut phrase);

        let _decoded = phrase::decode_phrase_with(language, &phrase, DecodeMode::ValidateOnly)?;
        Ok(())
    }

    /// Generates the seed from the [`AnyMnemonic`] and the passphrase.
    ///
    /// If a passphrase is not present, an empty string `""` is used instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyMnemonic, BuiltInLanguage};
    ///
    /// let phrase = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
    /// let mnemonic = AnyMnemonic::from_phrase(BuiltInLanguage::English, phrase).unwrap();
    /// let seed = mnemonic.to_seed("");
    /// assert_eq!(seed.len(), 64);
    /// ```
    pub fn to_seed<P: AsRef<str>>(&self, passphrase: P) -> [u8; 64] {
        // phrase is already normalized
        to_seed(self.phrase(), passphrase.as_ref())
    }

    /// Returns the language used to encode/decode this mnemonic.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bip0039::{AnyLanguage, AnyMnemonic, BuiltInLanguage, English};
    ///
    /// let m = AnyMnemonic::from_entropy(BuiltInLanguage::English, [1u8; 16]).unwrap();
    /// assert_eq!(m.language(), AnyLanguage::of::<English>());
    /// ```
    #[inline]
    pub fn language(&self) -> AnyLanguage {
        self.language
    }

    /// Returns the mnemonic phrase as a string slice.
    ///
    /// Note: the returned phrase is normalized (UTF-8 NFKD; words separated by single ASCII
    /// spaces).
    pub fn phrase(&self) -> &str {
        &self.phrase
    }

    /// Consumes the `AnyMnemonic` and return the phrase as a `String`.
    pub fn into_phrase(mut self) -> String {
        // Create an empty string and swap values with the mnemonic's phrase.
        // This allows `Mnemonic` to implement `Drop`, while still returning the phrase.
        mem::take(&mut self.phrase)
    }

    /// Returns the original entropy of the mnemonic phrase.
    pub fn entropy(&self) -> &[u8] {
        &self.entropy
    }

    /// Consumes the `AnyMnemonic` and return the entropy as a `Vec<u8>`.
    pub fn into_entropy(mut self) -> Vec<u8> {
        // Create an empty bytes and swap values with the mnemonic's entropy.
        // This allows `Mnemonic` to implement `Drop`, while still returning the entropy.
        mem::take(&mut self.entropy)
    }
}

impl<L: Language> From<Mnemonic<L>> for AnyMnemonic {
    fn from(mut value: Mnemonic<L>) -> Self {
        let language = AnyLanguage::of::<L>();
        Self {
            language,
            phrase: Zeroizing::new(mem::take(&mut value.phrase)),
            entropy: Zeroizing::new(mem::take(&mut value.entropy)),
        }
    }
}

/// Ensure the content of the `s` is normalized UTF8.
/// Avoid allocation for normalization when there are no special UTF8 characters in the string.
#[inline]
fn normalize_utf8(s: &mut Cow<'_, str>) {
    if is_nfkd_quick(s.as_ref().chars()) != IsNormalized::Yes {
        *s = Cow::Owned(s.as_ref().nfkd().to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mnemonic_roundtrip() {
        let mnemonic = <Mnemonic>::generate(Count::Words12);
        let entropy = mnemonic.entropy();
        let phrase = mnemonic.phrase();

        {
            let m = <Mnemonic>::from_entropy(entropy).unwrap();
            assert_eq!(phrase, m.phrase());
        }

        {
            let m = <Mnemonic>::from_phrase(phrase).unwrap();
            assert_eq!(entropy, m.entropy());
        }
    }

    #[test]
    fn test_any_mnemonic_roundtrip() {
        let english = AnyLanguage::of::<English>();

        let mnemonic = AnyMnemonic::generate(english, Count::Words12);
        let entropy = mnemonic.entropy();
        let phrase = mnemonic.phrase();

        {
            let m = AnyMnemonic::from_entropy(english, entropy).unwrap();
            assert_eq!(phrase, m.phrase());
        }

        {
            let m = <AnyMnemonic>::from_phrase(english, phrase).unwrap();
            assert_eq!(entropy, m.entropy());
        }
    }

    #[test]
    fn test_mnemonic_zeroize_on_drop_mechanism() {
        // There is no sound, deterministic way to verify heap memory is wiped *after* drop
        // without instrumentation (e.g. allocator hooks). Reading freed memory is UB.
        //
        // Instead, we:
        // 1) Assert `Mnemonic` stores secrets in `Zeroizing<...>` fields.
        // 2) Assert `Zeroizing` actually calls `Zeroize` on drop, using a drop-checking type.

        let m = <Mnemonic>::from_entropy([1u8; 16]).unwrap();

        fn assert_phrase(_: &Zeroizing<String>) {}
        fn assert_entropy(_: &Zeroizing<Vec<u8>>) {}

        assert_phrase(&m.phrase);
        assert_entropy(&m.entropy);
        drop(m);

        #[derive(Clone, Debug, PartialEq)]
        struct PanicOnNonZeroDrop(u8);

        impl zeroize::Zeroize for PanicOnNonZeroDrop {
            fn zeroize(&mut self) {
                self.0 = 0;
            }
        }

        impl Drop for PanicOnNonZeroDrop {
            fn drop(&mut self) {
                assert_eq!(self.0, 0, "dropped non-zeroized data");
            }
        }

        let wrapped = Zeroizing::new(vec![PanicOnNonZeroDrop(42); 16]);
        drop(wrapped);
    }

    #[test]
    fn test_mnemonic_consume() {
        // Validate the "consume one field, then drop zeroizes the other field" pattern in a
        // non-UB way, using drop-checking types (inspired by `zeroize`'s own tests).
        #[derive(Clone, Debug, PartialEq)]
        struct DropCheckVec(Vec<u8>);

        impl zeroize::Zeroize for DropCheckVec {
            fn zeroize(&mut self) {
                for byte in &mut self.0 {
                    *byte = 0;
                }
            }
        }

        impl Drop for DropCheckVec {
            fn drop(&mut self) {
                assert!(self.0.iter().all(|&b| b == 0), "dropped non-zeroized data");
            }
        }

        #[derive(Clone, Debug, PartialEq)]
        struct DropCheckString {
            s: String,
            was_zeroized: bool,
        }

        impl DropCheckString {
            fn new(s: impl Into<String>) -> Self {
                DropCheckString { s: s.into(), was_zeroized: false }
            }
        }

        impl zeroize::Zeroize for DropCheckString {
            fn zeroize(&mut self) {
                self.s.zeroize();
                self.was_zeroized = true;
            }
        }

        impl Drop for DropCheckString {
            fn drop(&mut self) {
                assert!(self.was_zeroized, "string was not zeroized before drop");
                assert!(self.s.is_empty(), "zeroized string should be empty");
            }
        }

        // Consuming the phrase/entropy should still ensure the entropy/phrase is zeroized
        // when the mnemonic is dropped.
        struct ConsumeMnemonic {
            phrase: Zeroizing<DropCheckString>,
            entropy: Zeroizing<DropCheckVec>,
        }

        impl ConsumeMnemonic {
            fn into_phrase(mut self) -> String {
                mem::take(&mut self.phrase.s)
            }

            fn into_entropy(mut self) -> Vec<u8> {
                mem::take(&mut self.entropy.0)
            }
        }

        let expected_entropy = vec![1u8; 16];
        let expected_phrase =
            "absurd amount doctor acoustic avoid letter advice cage absurd amount doctor adjust";

        let phrase = {
            ConsumeMnemonic {
                phrase: Zeroizing::new(DropCheckString::new(expected_phrase)),
                entropy: Zeroizing::new(DropCheckVec(expected_entropy.clone())),
            }
            .into_phrase()
        };
        assert_eq!(phrase, expected_phrase);

        let entropy = {
            ConsumeMnemonic {
                phrase: Zeroizing::new(DropCheckString::new(expected_phrase)),
                entropy: Zeroizing::new(DropCheckVec(expected_entropy.clone())),
            }
            .into_entropy()
        };

        assert_eq!(entropy, expected_entropy);
    }
}