Skip to content

Commit

Permalink
Fix serious issue in .toString(16) (#309)
Browse files Browse the repository at this point in the history
* Add test for `.toString(16)`

* Fix serious issue in `.toString(16)`

The hex encoding of some numbers is wrong. Since the string representation
is also used for interoperability between BigInt libraries, this bug is
causing a number modification when a BN.js number is converted into
another BigInt class, for example the BigNumber of ethers.js.

Co-authored-by: Alex Dupre <sysadmin@alexdupre.com>
  • Loading branch information
ChALkeR and alexdupre authored Nov 11, 2024
1 parent 0cd2661 commit a5f14b4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/bn.js
Original file line number Diff line number Diff line change
Expand Up @@ -452,16 +452,16 @@
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
}
if (carry !== 0) {
out = carry.toString(16) + out;
Expand Down
10 changes: 10 additions & 0 deletions test/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ var BN = require('../').BN;

describe('BN.js/Utils', function () {
describe('.toString()', function () {
describe('hex no padding', function () {
it('should have same length as input', function () {
var hex = '1';
for (var i = 1; i <= 128; i++) {
var n = new BN(hex, 16);
assert.equal(n.toString(16).length, i);
hex = hex + '0';
}
});
});
describe('binary padding', function () {
it('should have a length of 256', function () {
var a = new BN(0);
Expand Down

0 comments on commit a5f14b4

Please sign in to comment.