|
|
@ -65,6 +65,22 @@ function HDPublicKey(arg) { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
* Verifies that a given path is valid. |
|
|
|
* |
|
|
|
* @param {string|number} arg |
|
|
|
* @return {boolean} |
|
|
|
*/ |
|
|
|
HDPublicKey.prototype.isValidPath = function(arg) { |
|
|
|
try { |
|
|
|
this.derive(arg); |
|
|
|
return true; |
|
|
|
} catch (err) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
/** |
|
|
|
* Get a derivated child based on a string or number. |
|
|
|
* |
|
|
@ -86,11 +102,10 @@ function HDPublicKey(arg) { |
|
|
|
* ``` |
|
|
|
* |
|
|
|
* @param {string|number} arg |
|
|
|
* @param {boolean?} hardened |
|
|
|
*/ |
|
|
|
HDPublicKey.prototype.derive = function (arg, hardened) { |
|
|
|
HDPublicKey.prototype.derive = function (arg) { |
|
|
|
if (_.isNumber(arg)) { |
|
|
|
return this._deriveWithNumber(arg, hardened); |
|
|
|
return this._deriveWithNumber(arg); |
|
|
|
} else if (_.isString(arg)) { |
|
|
|
return this._deriveFromString(arg); |
|
|
|
} else { |
|
|
@ -98,11 +113,14 @@ HDPublicKey.prototype.derive = function (arg, hardened) { |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
HDPublicKey.prototype._deriveWithNumber = function (index, hardened) { |
|
|
|
if (hardened || index >= HDPublicKey.Hardened) { |
|
|
|
HDPublicKey.prototype._deriveWithNumber = function (index) { |
|
|
|
if (index >= HDPublicKey.Hardened) { |
|
|
|
throw new hdErrors.InvalidIndexCantDeriveHardened(); |
|
|
|
} |
|
|
|
var cached = HDKeyCache.get(this.xpubkey, index, hardened); |
|
|
|
if (index < 0) { |
|
|
|
throw new hdErrors.InvalidPath(index); |
|
|
|
} |
|
|
|
var cached = HDKeyCache.get(this.xpubkey, index, false); |
|
|
|
if (cached) { |
|
|
|
return cached; |
|
|
|
} |
|
|
@ -123,12 +141,16 @@ HDPublicKey.prototype._deriveWithNumber = function (index, hardened) { |
|
|
|
chainCode: chainCode, |
|
|
|
publicKey: publicKey |
|
|
|
}); |
|
|
|
HDKeyCache.set(this.xpubkey, index, hardened, derived); |
|
|
|
HDKeyCache.set(this.xpubkey, index, false, derived); |
|
|
|
return derived; |
|
|
|
}; |
|
|
|
|
|
|
|
HDPublicKey.prototype._deriveFromString = function (path) { |
|
|
|
/* jshint maxcomplexity: 8 */ |
|
|
|
if (_.contains(path, "'")) { |
|
|
|
throw new hdErrors.InvalidIndexCantDeriveHardened(); |
|
|
|
} |
|
|
|
|
|
|
|
var steps = path.split('/'); |
|
|
|
|
|
|
|
// Special cases:
|
|
|
@ -143,8 +165,7 @@ HDPublicKey.prototype._deriveFromString = function (path) { |
|
|
|
var result = this; |
|
|
|
for (var step in steps) { |
|
|
|
var index = parseInt(steps[step]); |
|
|
|
var hardened = steps[step] !== index.toString(); |
|
|
|
result = result._deriveWithNumber(index, hardened); |
|
|
|
result = result._deriveWithNumber(index); |
|
|
|
} |
|
|
|
return result; |
|
|
|
}; |
|
|
|