-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnemonic_recover.mjs
40 lines (34 loc) · 1.23 KB
/
mnemonic_recover.mjs
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
import words from "./internal/mnemonic-words.mjs";
/**
* Recovers an antelope based private key from BIP39 mnemonic.
* @param {Array<String>} recoveryPhrase 32 bytes of data.
* @returns {Uint8Array}
* import recoverMnemonic from "antelope-ecc/mnemonic-recover.mjs"
*
* recoverMnemonic([your, twenty, four, words, go, here, ]).then(console.log)
* ```
* The logged output was [abandon, busy, …].
*/
export default async function recoverMnemonic(recoveryPhrase) {
recoveryPhrase = recoveryPhrase.normalize("NFKD").trim().toLowerCase();
let ints = [];
recoveryPhrase.split(/[\s,:-]+/gmu).forEach((word) => {
let index = words.indexOf(word);
if (index < 0) throw new Error(`unknown word: '${word}'`);
ints.push(index);
});
let digits = ints.map((n) => n.toString(2).padStart(11, "0")).join("");
let sumBitLen = Math.floor(digits.length / 32);
let bitLen = digits.length - sumBitLen;
let bytesArr = [];
for (let bit = 0; bit < bitLen; bit += 8) {
let bytestring = digits.slice(bit, bit + 8);
let n = parseInt(bytestring, 2);
if (n >= 0) {
bytesArr.push(n);
}
}
// the original random bytes used to generate the 12-24 words
let entropyBytes = Uint8Array.from(bytesArr);
return entropyBytes;
}