dark_crystal_web3_core/secret/
bip39.rs

1//! A wrapper around the bip39 crate allowing us to
2//! validate and efficiently encode secrets given as a seed phrase
3pub use bip39::Error;
4use bip39::{Language, Mnemonic};
5
6/// Convert a seed phrase to a vector of bytes
7pub fn mnemonic_to_bytes(phrase: &str) -> Result<Vec<u8>, Error> {
8    let mnemonic = Mnemonic::parse_in_normalized(Language::English, phrase)?;
9    Ok(mnemonic.to_entropy())
10}
11
12/// Converts a vector of bytes to a seed phrase
13pub fn bytes_to_mnemonic(input: &Vec<u8>) -> Result<String, Error> {
14    let mnemonic = Mnemonic::from_entropy_in(Language::English, input)?;
15    Ok(mnemonic.to_string())
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21
22    #[test]
23    fn words_24() {
24        let input = "help avocado december frown result general supply meadow market alley manual dynamic balance turkey envelope sand patient imitate unit burst swamp modify lion correct";
25        let encoded = mnemonic_to_bytes(&input).unwrap();
26        assert_eq!(input, bytes_to_mnemonic(&encoded).unwrap());
27    }
28
29    #[test]
30    fn words_12() {
31        let input = "spare human danger common patch pioneer security pond push purity wear crane";
32        let encoded = mnemonic_to_bytes(&input).unwrap();
33        assert_eq!(input, bytes_to_mnemonic(&encoded).unwrap());
34    }
35}