From 6ce119f9e14576a04dc8d2ffe1603c8e162eaecb Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Fri, 4 Dec 2026 18:38:08 +0800 Subject: [PATCH] Derive hardened children from the 32-byte private key, as BIP32 says Hardened derivation hashed the parent private key without its leading zero bytes. For about 1 in 256 parent keys the child then differed from BIP32 and from other wallets (test vectors 3 and 4). BitPay fixed this upstream in 2016 (bitpay/bitcore-lib b79a9b27, v0.14.0), a month after the Zcash fork this library comes from was taken. derive now uses the key as 32 bytes. deriveNonCompliant returns what 0.16.x derived, so keys made with it can still be recovered, and the HD key cache keeps the two apart. toObject also writes the key as 32 bytes; before, fromObject rejected a key that starts with a zero byte. Adds BIP32 test vectors 3 and 4 and BitPay's two tests for this. --- docs/hierarchical.md | 9 ++++ lib/hdkeycache.js | 15 ++++--- lib/hdprivatekey.js | 50 ++++++++++++++++++----- test/hdkeycache.js | 10 ++--- test/hdkeys.js | 97 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 159 insertions(+), 22 deletions(-) diff --git a/docs/hierarchical.md b/docs/hierarchical.md index dc35571e5..05d17b81d 100644 --- a/docs/hierarchical.md +++ b/docs/hierarchical.md @@ -26,6 +26,15 @@ var address = derived.privateKey.toAddress(); var hdPublicKey = hdPrivateKey.hdPublicKey; ``` +### Keys derived with 0.16.x or earlier +Up to 0.16.x, hardened derivation hashed the parent private key without its leading zero bytes, which BIP32 does not allow. For about 1 in 256 parent keys this gave a different hardened child than other BIP32 wallets. `derive` now follows BIP32. If you derived keys with an older version, `deriveNonCompliant` takes the same arguments as `derive` and returns the old result, so you can find and move funds sent to those addresses: + +```javascript +var oldChild = hdPrivateKey.deriveNonCompliant("m/44'/19167'/0'/0/0"); +``` + +Don't use `deriveNonCompliant` for new keys. + ## HDPublicKey An instance of a PublicKey that can be derived to build extended public keys. Note that hardened paths are not available when deriving an HDPublicKey. diff --git a/lib/hdkeycache.js b/lib/hdkeycache.js index 721d9da48..2b9bbb9d7 100644 --- a/lib/hdkeycache.js +++ b/lib/hdkeycache.js @@ -8,20 +8,23 @@ module.exports = { _usedIndex: {}, _CACHE_SIZE: 5000, - get: function(xkey, number, hardened) { - hardened = !!hardened; - var key = xkey + '/' + number + '/' + hardened; + get: function(xkey, number, hardened, nonCompliant) { + var key = this._key(xkey, number, hardened, nonCompliant); if (this._cache[key]) { this._cacheHit(key); return this._cache[key]; } }, - set: function(xkey, number, hardened, derived) { - hardened = !!hardened; - var key = xkey + '/' + number + '/' + hardened; + set: function(xkey, number, hardened, derived, nonCompliant) { + var key = this._key(xkey, number, hardened, nonCompliant); this._cache[key] = derived; this._cacheHit(key); }, + // Compliant and non-compliant derivations of the same index can differ, so they are cached + // under different keys. + _key: function(xkey, number, hardened, nonCompliant) { + return (nonCompliant ? '1' : '0') + xkey + '/' + number + '/' + !!hardened; + }, _cacheHit: function(key) { if (this._usedIndex[key]) { delete this._usedList[this._usedIndex[key]]; diff --git a/lib/hdprivatekey.js b/lib/hdprivatekey.js index 03cc70548..66d211b1e 100644 --- a/lib/hdprivatekey.js +++ b/lib/hdprivatekey.js @@ -147,20 +147,41 @@ HDPrivateKey._getDerivationIndexes = function(path) { * assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h); * ``` * + * Hardened derivation follows BIP32: the parent private key is hashed as 32 bytes, with + * leading zeros. Versions up to 0.16.x dropped those zeros, so for about 1 in 256 parent + * keys they derived a different hardened child. Use `deriveNonCompliant` only to recover + * keys that were derived with those versions. + * * @param {string|number} arg * @param {boolean?} hardened + * @param {boolean?} nonCompliant - only for keys derived with 0.16.x or earlier; see `deriveNonCompliant` */ -HDPrivateKey.prototype.derive = function(arg, hardened) { +HDPrivateKey.prototype.derive = function(arg, hardened, nonCompliant) { if (_.isNumber(arg)) { - return this._deriveWithNumber(arg, hardened); + return this._deriveWithNumber(arg, hardened, nonCompliant); } else if (_.isString(arg)) { - return this._deriveFromString(arg); + return this._deriveFromString(arg, nonCompliant); } else { throw new hdErrors.InvalidDerivationArgument(arg); } }; -HDPrivateKey.prototype._deriveWithNumber = function(index, hardened) { +/** + * Derives a child the way bitcore-lib 0.16.x and earlier did, which is not BIP32 compliant: + * in hardened steps the parent private key is hashed without its leading zero bytes. + * + * Do not use this for new keys. It exists so that funds sent to addresses derived with an + * older version can still be found and spent. For parent keys that do not start with a zero + * byte, the result is the same as `derive`. + * + * @param {string|number} arg + * @param {boolean?} hardened + */ +HDPrivateKey.prototype.deriveNonCompliant = function(arg, hardened) { + return this.derive(arg, hardened, true); +}; + +HDPrivateKey.prototype._deriveWithNumber = function(index, hardened, nonCompliant) { /* jshint maxstatements: 20 */ /* jshint maxcomplexity: 10 */ if (!HDPrivateKey.isValidPath(index, hardened)) { @@ -172,15 +193,21 @@ HDPrivateKey.prototype._deriveWithNumber = function(index, hardened) { index += HDPrivateKey.Hardened; } - var cached = HDKeyCache.get(this.xprivkey, index, hardened); + var cached = HDKeyCache.get(this.xprivkey, index, hardened, nonCompliant); if (cached) { return cached; } var indexBuffer = BufferUtil.integerAsBuffer(index); var data; - if (hardened) { - data = BufferUtil.concat([buffer.Buffer.from([0]), this.privateKey.toBuffer(), indexBuffer]); + if (hardened && nonCompliant) { + // 0.16.x and earlier: the private key without its leading zero bytes (shorter than 32) + data = BufferUtil.concat([buffer.Buffer.from([0]), this.privateKey.bn.toBuffer(), indexBuffer]); + } else if (hardened) { + // BIP32: ser256(k), always 32 bytes + var privateKeyBuffer = this.privateKey.bn.toBuffer({size: 32}); + assert(privateKeyBuffer.length === 32, 'length of private key buffer is expected to be 32 bytes'); + data = BufferUtil.concat([buffer.Buffer.from([0]), privateKeyBuffer, indexBuffer]); } else { data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); } @@ -202,18 +229,18 @@ HDPrivateKey.prototype._deriveWithNumber = function(index, hardened) { chainCode: chainCode, privateKey: privateKey }); - HDKeyCache.set(this.xprivkey, index, hardened, derived); + HDKeyCache.set(this.xprivkey, index, hardened, derived, nonCompliant); return derived; }; -HDPrivateKey.prototype._deriveFromString = function(path) { +HDPrivateKey.prototype._deriveFromString = function(path, nonCompliant) { if (!HDPrivateKey.isValidPath(path)) { throw new hdErrors.InvalidPath(path); } var indexes = HDPrivateKey._getDerivationIndexes(path); var derived = indexes.reduce(function(prev, index) { - return prev._deriveWithNumber(index); + return prev._deriveWithNumber(index, null, nonCompliant); }, this); return derived; @@ -513,7 +540,8 @@ HDPrivateKey.prototype.toObject = HDPrivateKey.prototype.toJSON = function toObj parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), - privateKey: this.privateKey.toBuffer().toString('hex'), + // 32 bytes with leading zeros, or fromObject rejects the key + privateKey: this.privateKey.bn.toBuffer({size: 32}).toString('hex'), checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), xprivkey: this.xprivkey }; diff --git a/test/hdkeycache.js b/test/hdkeycache.js index db1f4fc18..692c01d3e 100644 --- a/test/hdkeycache.js +++ b/test/hdkeycache.js @@ -25,22 +25,22 @@ describe('HDKey cache', function() { it('saves a derived key', function() { var child = master.derive(0); - expect(cache._cache[master.xprivkey + '/0/false'].xprivkey).to.equal(child.xprivkey); + expect(cache._cache['0' + master.xprivkey + '/0/false'].xprivkey).to.equal(child.xprivkey); }); it('starts erasing unused keys', function() { var child1 = master.derive(0); var child2 = child1.derive(0); var child3 = child2.derive(0); - expect(cache._cache[master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); + expect(cache._cache['0' + master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); var child4 = child3.derive(0); - expect(cache._cache[master.xprivkey + '/0/false']).to.equal(undefined); + expect(cache._cache['0' + master.xprivkey + '/0/false']).to.equal(undefined); }); it('avoids erasing keys that get cache hits ("hot keys")', function() { var child1 = master.derive(0); var child2 = master.derive(0).derive(0); - expect(cache._cache[master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); + expect(cache._cache['0' + master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); var child1_copy = master.derive(0); - expect(cache._cache[master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); + expect(cache._cache['0' + master.xprivkey + '/0/false'].xprivkey).to.equal(child1.xprivkey); }); it('keeps the size of the cache small', function() { var child1 = master.derive(0); diff --git a/test/hdkeys.js b/test/hdkeys.js index d4bd6bda7..d03a0a670 100644 --- a/test/hdkeys.js +++ b/test/hdkeys.js @@ -221,6 +221,86 @@ describe('BIP32 compliance', function() { .xpubkey.should.equal(vector2_m02147483647h12147483646h2_public); }); + describe('leading zeros in the private key (test vectors 3 and 4)', function() { + + it('should derive m/0h from test vector 3', function() { + var master = HDPrivateKey.fromSeed(vector3_master, Networks.livenet); + master.xprivkey.should.equal(vector3_m_private); + master.xpubkey.should.equal(vector3_m_public); + var child = master.derive("m/0'"); + child.xprivkey.should.equal(vector3_m0h_private); + child.xpubkey.should.equal(vector3_m0h_public); + }); + + it('should derive m/0h/1h from test vector 4', function() { + var master = HDPrivateKey.fromSeed(vector4_master, Networks.livenet); + master.xprivkey.should.equal(vector4_m_private); + master.xpubkey.should.equal(vector4_m_public); + master.derive("m/0'").xprivkey.should.equal(vector4_m0h_private); + master.derive("m/0'").xpubkey.should.equal(vector4_m0h_public); + master.derive("m/0'/1'").xprivkey.should.equal(vector4_m0h1h_private); + master.derive("m/0'/1'").xpubkey.should.equal(vector4_m0h1h_public); + }); + + it('should derive the same child by number as by path', function() { + var master = HDPrivateKey.fromSeed(vector4_master, Networks.livenet); + master.derive(0, true).derive(1, true).xprivkey.should.equal(vector4_m0h1h_private); + }); + + it('should use full 32 bytes for private key data that is hashed (as per bip32)', function() { + var key = HDPrivateKey.fromObject({ + network: 'testnet', + depth: 0, + parentFingerPrint: 0, + childIndex: 0, + privateKey: Buffer.from('00000055378cf5fafb56c711c674143f9b0ee82ab0ba2924f19b64f5ae7cdbfd', 'hex'), + chainCode: Buffer.from('9c8a5c863e5941f3d99453e6ba66b328bb17cf0b8dec89ed4fc5ace397a1c089', 'hex') + }); + var derived = key.derive("m/44'/0'/0'/0/0'"); + derived.privateKey.toString().should.equal('3348069561d2a0fb925e74bf198762acc47dce7db27372257d2d959a9e6f8aeb'); + }); + + it('should NOT use full 32 bytes for private key data that is hashed with nonCompliant flag', function() { + var key = HDPrivateKey.fromObject({ + network: 'testnet', + depth: 0, + parentFingerPrint: 0, + childIndex: 0, + privateKey: Buffer.from('00000055378cf5fafb56c711c674143f9b0ee82ab0ba2924f19b64f5ae7cdbfd', 'hex'), + chainCode: Buffer.from('9c8a5c863e5941f3d99453e6ba66b328bb17cf0b8dec89ed4fc5ace397a1c089', 'hex') + }); + var derived = key.deriveNonCompliant("m/44'/0'/0'/0/0'"); + derived.privateKey.toString().should.equal('4811a079bab267bfdca855b3bddff20231ff7044e648514fa099158472df2836'); + }); + + it('deriveNonCompliant should return what 0.16.x derived, to recover old keys', function() { + var master3 = HDPrivateKey.fromSeed(vector3_master, Networks.livenet); + master3.deriveNonCompliant("m/0'").xprivkey.should.equal(vector3_m0h_private_noncompliant); + master3.deriveNonCompliant(0, true).xprivkey.should.equal(vector3_m0h_private_noncompliant); + var master4 = HDPrivateKey.fromSeed(vector4_master, Networks.livenet); + master4.deriveNonCompliant("m/0'/1'").xprivkey.should.equal(vector4_m0h1h_private_noncompliant); + }); + + it('deriveNonCompliant should equal derive when the parent key has no leading zero', function() { + var master = HDPrivateKey.fromSeed(vector1_master, Networks.livenet); + master.deriveNonCompliant("m/0'/1/2'").xprivkey.should.equal(vector1_m0h12h_private); + }); + + it('should not mix compliant and non-compliant children in the cache', function() { + var master = HDPrivateKey.fromSeed(vector3_master, Networks.livenet); + master.deriveNonCompliant("m/0'").xprivkey.should.equal(vector3_m0h_private_noncompliant); + master.derive("m/0'").xprivkey.should.equal(vector3_m0h_private); + master.deriveNonCompliant("m/0'").xprivkey.should.equal(vector3_m0h_private_noncompliant); + }); + + it('should round-trip a key with a leading zero through toObject and fromObject', function() { + var master = HDPrivateKey.fromSeed(vector3_master, Networks.livenet); + var obj = master.toObject(); + obj.privateKey.length.should.equal(64); + HDPrivateKey.fromObject(obj).xprivkey.should.equal(vector3_m_private); + }); + }); + describe('seed', function() { it('should initialize a new BIP32 correctly from test vector 1 seed', function() { @@ -264,3 +344,20 @@ var vector2_m02147483647h12147483646h_public = 'xpub6ERApfZwUNrhLCkDtcHTcxd75Rbz var vector2_m02147483647h12147483646h_private = 'xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc'; var vector2_m02147483647h12147483646h2_public = 'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt'; var vector2_m02147483647h12147483646h2_private = 'xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j'; + +// Vectors 3 and 4 test that leading zeros of the private key are kept. +var vector3_master = '4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be'; +var vector3_m_public = 'xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13'; +var vector3_m_private = 'xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6'; +var vector3_m0h_public = 'xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y'; +var vector3_m0h_private = 'xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L'; +var vector4_master = '3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678'; +var vector4_m_public = 'xpub661MyMwAqRbcGczjuMoRm6dXaLDEhW1u34gKenbeYqAix21mdUKJyuyu5F1rzYGVxyL6tmgBUAEPrEz92mBXjByMRiJdba9wpnN37RLLAXa'; +var vector4_m_private = 'xprv9s21ZrQH143K48vGoLGRPxgo2JNkJ3J3fqkirQC2zVdk5Dgd5w14S7fRDyHH4dWNHUgkvsvNDCkvAwcSHNAQwhwgNMgZhLtQC63zxwhQmRv'; +var vector4_m0h_public = 'xpub69AUMk3qDBi3uW1sXgjCmVjJ2G6WQoYSnNHyzkmdCHEhSZ4tBok37xfFEqHd2AddP56Tqp4o56AePAgCjYdvpW2PU2jbUPFKsav5ut6Ch1m'; +var vector4_m0h_private = 'xprv9vB7xEWwNp9kh1wQRfCCQMnZUEG21LpbR9NPCNN1dwhiZkjjeGRnaALmPXCX7SgjFTiCTT6bXes17boXtjq3xLpcDjzEuGLQBM5ohqkao9G'; +var vector4_m0h1h_public = 'xpub6BJA1jSqiukeaesWfxe6sNK9CCGaujFFSJLomWHprUL9DePQ4JDkM5d88n49sMGJxrhpjazuXYWdMf17C9T5XnxkopaeS7jGk1GyyVziaMt'; +var vector4_m0h1h_private = 'xprv9xJocDuwtYCMNAo3Zw76WENQeAS6WGXQ55RCy7tDJ8oALr4FWkuVoHJeHVAcAqiZLE7Je3vZJHxspZdFHfnBEjHqU5hG1Jaj32dVoS6XLT1'; +// What 0.16.x and earlier derived for these paths (deriveNonCompliant must keep returning it) +var vector3_m0h_private_noncompliant = 'xprv9uPDJpEQgRQfCURKREBmjvADDMr5jtUWMuEfVnbiPCyYkzAeSTAAQe87TiqnSGEsmyzNG87rqVGs9hcYbRYV383aMDhE1cAGGLf6HaiozTW'; +var vector4_m0h1h_private_noncompliant = 'xprv9xJocDuwtYCMNxr9MAWm8LWeVvK9WM1f5kJT1SyqaT1JMhgHjtjK7FDfLEQSr1nGu5eBfTS75ZkTs6L8PR8gE6Wb3A8DZeNA3X3m8FQ2qHx';