diff --git a/lib/bn.js b/lib/bn.js index 0854c1c..67c7b42 100644 --- a/lib/bn.js +++ b/lib/bn.js @@ -6,6 +6,14 @@ if (!val) throw new Error(msg || 'Assertion failed'); } + // compatibility replacement for Number.isInteger + // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Polyfill + function isInteger (value) { + return typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value; + } + // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { @@ -1918,8 +1926,9 @@ var isNegNum = num < 0; if (isNegNum) num = -num; - assert(typeof num === 'number'); - assert(num < 0x4000000); + assert(typeof num === 'number', 'Argument num must be a number'); + assert(isInteger(num), 'Argument must be an integer'); + assert(num < 0x4000000, 'Argument not in supported range -0x4000000 < num < 0x4000000'); // Carry var carry = 0; diff --git a/test/arithmetic-test.js b/test/arithmetic-test.js index 67956ff..b45f3ec 100644 --- a/test/arithmetic-test.js +++ b/test/arithmetic-test.js @@ -285,10 +285,42 @@ describe('BN.js/Arithmetic', function () { assert.equal(a.muln(0xdead).toString(16), c.toString(16)); }); + it('should throw error with num of type other than number', function () { + assert.throws(function () { + new BN(0).imuln('1'); + }, /^Error: Argument num must be a number$/); + + assert.throws(function () { + new BN(0).imuln(new BN(1)); + }, /^Error: Argument num must be a number$/); + }); + + it('should throw error with num eq 1.5, -1.5 and NaN', function () { + assert.throws(function () { + new BN(0).imuln(1.5); + }, /^Error: Argument must be an integer$/); + + assert.throws(function () { + new BN(0).imuln(-1.5); + }, /^Error: Argument must be an integer$/); + + assert.throws(function () { + new BN(0).imuln(Infinity); + }, /^Error: Argument must be an integer$/); + + assert.throws(function () { + new BN(0).imuln(-Infinity); + }, /^Error: Argument must be an integer$/); + + assert.throws(function () { + new BN(0).imuln(NaN); + }, /^Error: Argument must be an integer$/); + }); + it('should throw error with num eq 0x4000000', function () { assert.throws(function () { new BN(0).imuln(0x4000000); - }, /^Error: Assertion failed$/); + }, /^Error: Argument not in supported range -0x4000000 < num < 0x4000000$/); }); it('should negate number if number is negative', function () {