mnemonic: refactor fromPhrase.

This commit is contained in:
Christopher Jeffrey 2017-07-21 23:44:13 -07:00
parent 63423c7748
commit 75adfe5ec0
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -230,15 +230,14 @@ Mnemonic.prototype.getPhrase = function getPhrase() {
*/
Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
let bits, ent, entropy, lang;
let chk, wordlist, cbits, cbytes, words;
let words = phrase.split(/[ \u3000]+/);
let bits = words.length * 11;
let cbits = bits % 32;
let cbytes = Math.ceil(cbits / 8);
let lang = Mnemonic.getLanguage(words[0]);
let wordlist = Mnemonic.getWordlist(lang);
let ent, entropy, chk;
assert(typeof phrase === 'string');
words = phrase.split(/[ \u3000]+/);
bits = words.length * 11;
cbits = bits % 32;
cbytes = Math.ceil(cbits / 8);
bits -= cbits;
assert(bits >= common.MIN_ENTROPY);
@ -249,9 +248,7 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
ent = Buffer.allocUnsafe(Math.ceil((bits + cbits) / 8));
ent.fill(0);
lang = Mnemonic.getLanguage(words[0]);
wordlist = Mnemonic.getWordlist(lang);
// Rebuild entropy bytes.
for (let i = 0; i < words.length; i++) {
let word = words[i];
let index = util.binarySearch(wordlist, word, util.strcmp);
@ -263,8 +260,8 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
let pos = i * 11 + j;
let bit = pos % 8;
let oct = (pos - bit) / 8;
let b = (index >>> (10 - j)) & 1;
ent[oct] |= b << (7 - bit);
let val = (index >>> (10 - j)) & 1;
ent[oct] |= val << (7 - bit);
}
}
@ -272,12 +269,13 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
ent = ent.slice(ent.length - cbytes);
chk = digest.sha256(entropy);
// Verify checksum.
for (let i = 0; i < cbits; i++) {
let bit = i % 8;
let oct = (i - bit) / 8;
let b = (ent[oct] >>> (7 - bit)) & 1;
let j = (chk[oct] >>> (7 - bit)) & 1;
if (b !== j)
let a = (ent[oct] >>> (7 - bit)) & 1;
let b = (chk[oct] >>> (7 - bit)) & 1;
if (a !== b)
throw new Error('Invalid checksum.');
}