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
use pyo3::exceptions;
use pyo3::prelude::*;
use pyo3::{wrap_pyfunction};
use bip39::{Mnemonic, Language, MnemonicType, Seed};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use sha2::Sha512;
#[pyfunction]
#[text_signature = "(phrase, password)"]
pub fn bip39_to_mini_secret(phrase: &str, password: &str) -> PyResult<Vec<u8>> {
let salt = format!("mnemonic{}", password);
let mnemonic = match Mnemonic::from_phrase(phrase, Language::English) {
Ok(some_mnemomic) => some_mnemomic,
Err(err) => return Err(exceptions::ValueError::py_err(format!("Invalid mnemonic: {}", err.to_string())))
};
let mut result = [0u8; 64];
pbkdf2::<Hmac<Sha512>>(mnemonic.entropy(), salt.as_bytes(), 2048, &mut result);
Ok(result[..32].to_vec())
}
#[pyfunction]
#[text_signature = "(words)"]
pub fn bip39_generate(words: u32) -> PyResult<String> {
let word_count_type = match MnemonicType::for_word_count(words as usize) {
Ok(some_work_count) => some_work_count,
Err(err) => return Err(exceptions::ValueError::py_err(err.to_string()))
};
let phrase = Mnemonic::new(word_count_type, Language::English).into_phrase();
assert_eq!(phrase.split(" ").count(), words as usize);
Ok(phrase.to_owned())
}
#[pyfunction]
#[text_signature = "(phrase, password)"]
pub fn bip39_to_seed(phrase: &str, password: &str) -> PyResult<Vec<u8>> {
let mnemonic = match Mnemonic::from_phrase(phrase, Language::English) {
Ok(some_mnemomic) => some_mnemomic,
Err(err) => return Err(exceptions::ValueError::py_err(format!("Invalid mnemonic: {}", err.to_string())))
};
Ok(Seed::new(&mnemonic, password)
.as_bytes()[..32]
.to_vec())
}
#[pyfunction]
#[text_signature = "(phrase)"]
pub fn bip39_validate(phrase: &str) -> bool {
match Mnemonic::validate(phrase, Language::English) {
Err(_) => false,
_ => true
}
}
#[pymodule]
fn bip39(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(bip39_to_mini_secret))?;
m.add_wrapped(wrap_pyfunction!(bip39_generate))?;
m.add_wrapped(wrap_pyfunction!(bip39_to_seed))?;
m.add_wrapped(wrap_pyfunction!(bip39_validate))?;
Ok(())
}