From 288f66223126a0b1a4b20e90547c780508799b03 Mon Sep 17 00:00:00 2001 From: Otto Allmendinger Date: Thu, 19 Dec 2019 09:40:27 +0100 Subject: [PATCH] ECPair: simplify `fromPrivateKeyBuffer` * Remove buggy precomputation of `__Q` using `fastcurve`. Since `fastcurve` funcs can return `undefined` if the native bindings are unavailable, the `decodeFrom` call could have failed. Instead of precomputing `__Q`, use the existing getter for `Q` and correctly use `fastcurve.publicKeyCreate` there while accounting for an `undefined` return value. * Remove redundant sanity checks that are already performed by the ECPair constructor Issue: BLOCK-261 --- src/ecpair.js | 15 +++------------ test/ecpair.js | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/src/ecpair.js b/src/ecpair.js index a9525afa..30235282 100644 --- a/src/ecpair.js +++ b/src/ecpair.js @@ -44,7 +44,8 @@ function ECPair (d, Q, options) { Object.defineProperty(ECPair.prototype, 'Q', { get: function () { if (!this.__Q && this.d) { - this.__Q = secp256k1.G.multiply(this.d) + const qBuf = fastcurve.publicKeyCreate(this.d.toBuffer(32), false) + this.__Q = qBuf ? ecurve.Point.decodeFrom(curve, qBuf) : secp256k1.G.multiply(this.d) } return this.__Q @@ -72,17 +73,7 @@ ECPair.fromPrivateKeyBuffer = function (buffer, network) { } var d = BigInteger.fromBuffer(buffer) - - if (d.signum() <= 0 || d.compareTo(curve.n) >= 0) { - throw new Error('private key out of range') - } - - var ecPair = new ECPair(d, null, { network: network }) - if (!ecPair.__Q && curve) { - ecPair.__Q = ecurve.Point.decodeFrom(curve, fastcurve.publicKeyCreate(d.toBuffer(32), false)) - } - - return ecPair + return new ECPair(d, null, { network: network }) } ECPair.fromWIF = function (string, network) { diff --git a/test/ecpair.js b/test/ecpair.js index 301d3f54..402a1d3b 100644 --- a/test/ecpair.js +++ b/test/ecpair.js @@ -313,7 +313,7 @@ describe('ECPair', function () { var prvKeyBuffer = Buffer.alloc(32, 0xff) assert.throws(function () { ECPair.fromPrivateKeyBuffer(prvKeyBuffer) - }, new RegExp('private key out of range')) + }, new RegExp('Private key must be less than the curve order')) }) it('throws if the private key buffer is not a buffer', function () {