mnemonic: use a binary search for word indexes.

This commit is contained in:
Christopher Jeffrey 2016-09-13 20:06:53 -07:00
parent 6dbbee19d6
commit 8daddcc458
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
3 changed files with 23 additions and 11 deletions

View File

@ -11,6 +11,7 @@ var assert = require('assert');
var random = require('./random');
var scrypt = require('./scrypt');
var scryptAsync = require('./scrypt-async');
var utils = require('../utils/utils');
var native = require('../utils/native');
var nativeCrypto, supersha, hash, aes;
@ -226,7 +227,7 @@ crypto.scrypt = function _scrypt(passwd, salt, N, r, p, len) {
* @param {Function} callback
*/
crypto.scryptAsync = function _scryptAsync(passwd, salt, N, r, p, len, callback) {
crypto.scryptAsync = function _scrypt(passwd, salt, N, r, p, len, callback) {
if (typeof passwd === 'string')
passwd = new Buffer(passwd, 'utf8');
@ -504,7 +505,7 @@ crypto.buildMerkleTree = function buildMerkleTree(leaves) {
right = tree[j + i2];
if (i2 === i + 1 && i2 + 1 === size
&& left.compare(right) === 0) {
&& utils.cmp(left, right) === 0) {
return;
}

View File

@ -261,7 +261,7 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
for (i = 0; i < words.length; i++) {
word = words[i];
index = wordlist.indexOf(word);
index = utils.binarySearch(wordlist, word, utils.strcmp);
if (index === -1)
throw new Error('Could not find word.');

View File

@ -1567,19 +1567,15 @@ utils.isZero = function isZero(data) {
};
/**
* Buffer comparator (memcmp + length comparison).
* String comparator (memcmp + length comparison).
* @param {Buffer} a
* @param {Buffer} b
* @returns {Number} -1, 1, or 0.
*/
utils.cmp = function cmp(a, b) {
var len, i;
if (a.compare)
return a.compare(b);
len = Math.min(a.length, b.length);
utils.strcmp = function strcmp(a, b) {
var len = Math.min(a.length, b.length);
var i;
for (i = 0; i < len; i++) {
if (a[i] < b[i])
@ -1597,6 +1593,21 @@ utils.cmp = function cmp(a, b) {
return 0;
};
/**
* Buffer comparator (memcmp + length comparison).
* @param {Buffer} a
* @param {Buffer} b
* @returns {Number} -1, 1, or 0.
*/
utils.cmp = function cmp(a, b) {
return a.compare(b);
};
// Warning: polymorphism.
if (!Buffer.prototype.compare)
utils.cmp = utils.strcmp;
/**
* Memcmp for comparing a needle to a haystack.
* @param {Buffer} target - Haystack.