Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

Commit

Permalink
ECPair: simplify fromPrivateKeyBuffer
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
OttoAllmendinger committed Jan 6, 2020
1 parent 30984a9 commit 288f662
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 13 deletions.
15 changes: 3 additions & 12 deletions src/ecpair.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion test/ecpair.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit 288f662

Please sign in to comment.