From 86cbc02a53398a170aba6d7df4763ccc79716501 Mon Sep 17 00:00:00 2001 From: Kirill Fomichev Date: Mon, 28 Jan 2019 13:50:14 +0300 Subject: [PATCH] fix edge case for publicKeyTweakAdd (#140) After base point multiplication and adding point we should check that result is not infinity point. --- lib/elliptic/index.js | 5 ++++- lib/js/index.js | 5 ++++- test/publickey.js | 12 ++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/elliptic/index.js b/lib/elliptic/index.js index ac17b84..16e77e0 100644 --- a/lib/elliptic/index.js +++ b/lib/elliptic/index.js @@ -130,7 +130,10 @@ exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { tweak = new BN(tweak) if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - return Buffer.from(ecparams.g.mul(tweak).add(pair.pub).encode(true, compressed)) + var point = ecparams.g.mul(tweak).add(pair.pub) + if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + return Buffer.from(point.encode(true, compressed)) } exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { diff --git a/lib/js/index.js b/lib/js/index.js index 3a345b8..ccbfb9a 100644 --- a/lib/js/index.js +++ b/lib/js/index.js @@ -78,7 +78,10 @@ exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { tweak = BN.fromBuffer(tweak) if (tweak.isOverflow()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - return g.mul(tweak).add(point).toPublicKey(compressed) + var result = g.mul(tweak).add(point) + if (result.inf) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + return result.toPublicKey(compressed) } exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { diff --git a/test/publickey.js b/test/publickey.js index ea76b9e..1b246a3 100644 --- a/test/publickey.js +++ b/test/publickey.js @@ -241,6 +241,18 @@ module.exports = function (t, secp256k1) { t.end() }) + t.test('tweak produce infinity point', function (t) { + // G * 1 - G = 0 + t.throws(function () { + var publicKey = Buffer.from(util.ec.g.encode(null, true)) + publicKey[0] = publicKey[0] ^ 0x01 // change sign of G + var tweak = util.BN_ONE.toArrayLike(Buffer, 'be', 32) + secp256k1.publicKeyTweakAdd(publicKey, tweak, true) + }, new RegExp('^Error: ' + messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL + '$')) + + t.end() + }) + t.test('compressed should be a boolean', function (t) { t.throws(function () { var privateKey = util.getPrivateKey()