From 262e8f8401ed54b9592f4b08723795fcdd7f66b9 Mon Sep 17 00:00:00 2001 From: JP Richardson Date: Sat, 14 Jun 2014 12:49:52 -0500 Subject: [PATCH] lib/hdkey: refactored derive() --- lib/hdkey.js | 42 ++++++++++++++---------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/lib/hdkey.js b/lib/hdkey.js index c72c811..d2ff8fa 100644 --- a/lib/hdkey.js +++ b/lib/hdkey.js @@ -70,29 +70,24 @@ Object.defineProperty(HDKey.prototype, 'publicOld', { HDKey.prototype.derive = function(path) { - var e = path.split('/') - - // Special cases: if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this + var entries = path.split('/') var hkey = this - for (var i in e) { - var c = e[i] - - if (i == 0 ) { - if (c != 'm') throw new Error('invalid path') - continue + entries.forEach(function(c, i) { + if (i == 0) { + assert(c, 'm', 'Invalid path') + return } - var usePrivate = (c.length > 1) && (c[c.length-1] == '\'') - var childIndex = parseInt(usePrivate ? c.slice(0, c.length - 1) : c) & (HARDENED_OFFSET - 1) - - if (usePrivate) - childIndex += HARDENED_OFFSET + var hardened = (c.length > 1) && (c[c.length-1] == '\'') + var childIndex = parseInt(c, 10) //& (HARDENED_OFFSET - 1) + assert(childIndex < HARDENED_OFFSET, 'Invalid index') + if (hardened) childIndex += HARDENED_OFFSET hkey = hkey.deriveChild(childIndex) - } + }) return hkey } @@ -104,8 +99,7 @@ HDKey.prototype.deriveChild = function(index) { var data - // Hardened child - if (isHardened) { + if (isHardened) { // Hardened child assert(this.privateKey, 'Could not derive hardened child key') var pk = this.privateKey @@ -113,19 +107,13 @@ HDKey.prototype.deriveChild = function(index) { pk = Buffer.concat([zb, pk]) // data = 0x00 || ser256(kpar) || ser32(index) - data = Buffer.concat([pk, indexBuffer]) - - // Normal child - } else { + data = Buffer.concat([pk, indexBuffer]) + } else { // Normal child // data = serP(point(kpar)) || ser32(index) // = serP(Kpar) || ser32(index) - data = Buffer.concat([ - this.publicKey, - indexBuffer - ]) + data = Buffer.concat([this.publicKey, indexBuffer]) } - //var I = crypto.HmacSHA512(data, this.chaincode) var I = sha512.hmac(this.chainCode).finalize(data) var IL = I.slice(0, 32) var IR = I.slice(32) @@ -143,8 +131,6 @@ HDKey.prototype.deriveChild = function(index) { return this.derive(index + 1) } - //hd.priv = new ECKey(ki.toBuffer(), true) - //hd.pub = hd.priv.publicPoint hd.privateKey = ki.toBuffer() // Public parent key -> public child key