Browse Source

lib/hdkey: refactored derive()

master
JP Richardson 11 years ago
parent
commit
262e8f8401
  1. 42
      lib/hdkey.js

42
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

Loading…
Cancel
Save