Skip to content

Commit e3f21eb

Browse files
committed
HDNode: avoid creating multiple buffers
1 parent b866dc8 commit e3f21eb

File tree

1 file changed

+9
-17
lines changed

1 file changed

+9
-17
lines changed

src/hdnode.js

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -90,23 +90,21 @@ HDNode.fromBase58 = function (string, networks) {
9090

9191
// 32 bytes: the chain code
9292
var chainCode = buffer.slice(13, 45)
93-
var data, keyPair
93+
var keyPair
9494

9595
// 33 bytes: private key data (0x00 + k)
9696
if (version === network.bip32.private) {
9797
if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
9898

99-
data = buffer.slice(46, 78)
100-
var d = BigInteger.fromBuffer(data)
99+
var d = BigInteger.fromBuffer(buffer.slice(46, 78))
101100

102101
keyPair = new ECPair(d, null, {
103102
network: network
104103
})
105104

106105
// 33 bytes: public key data (0x02 + X or 0x03 + X)
107106
} else {
108-
data = buffer.slice(45, 78)
109-
var Q = ecurve.Point.decodeFrom(curve, data)
107+
var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78))
110108
if (!Q.compressed) throw new Error('Invalid public key')
111109

112110
// Verify that the X coordinate in the public point corresponds to a point on the curve.
@@ -194,29 +192,23 @@ HDNode.prototype.toBase58 = function (__isPrivate) {
194192
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
195193
HDNode.prototype.derive = function (index) {
196194
var isHardened = index >= HDNode.HIGHEST_BIT
197-
var indexBuffer = new Buffer(4)
198-
indexBuffer.writeUInt32BE(index, 0)
199-
200-
var data
195+
var data = new Buffer(37)
201196

202197
// Hardened child
203198
if (isHardened) {
204199
if (!this.keyPair.d) throw new TypeError('Could not derive hardened child key')
205200

206201
// data = 0x00 || ser256(kpar) || ser32(index)
207-
data = Buffer.concat([
208-
this.keyPair.d.toBuffer(33),
209-
indexBuffer
210-
])
202+
data[0] = 0x00
203+
this.keyPair.d.toBuffer(32).copy(data, 1)
204+
data.writeUInt32BE(index, 33)
211205

212206
// Normal child
213207
} else {
214208
// data = serP(point(kpar)) || ser32(index)
215209
// = serP(Kpar) || ser32(index)
216-
data = Buffer.concat([
217-
this.keyPair.getPublicKeyBuffer(),
218-
indexBuffer
219-
])
210+
this.keyPair.getPublicKeyBuffer().copy(data, 0)
211+
data.writeUInt32BE(index, 33)
220212
}
221213

222214
var I = createHmac('sha512', this.chainCode).update(data).digest()

0 commit comments

Comments
 (0)