Skip to content

Commit

Permalink
lib: better validation of string input
Browse files Browse the repository at this point in the history
Fix: #151
  • Loading branch information
indutny committed Nov 29, 2017
1 parent b9f3676 commit e924509
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
13 changes: 9 additions & 4 deletions lib/bn.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,18 +191,23 @@

r <<= 4;

var b;

// 'a' - 'f'
if (c >= 49 && c <= 54) {
r |= c - 49 + 0xa;
b = c - 49 + 0xa;

// 'A' - 'F'
} else if (c >= 17 && c <= 22) {
r |= c - 17 + 0xa;
b = c - 17 + 0xa;

// '0' - '9'
} else {
r |= c & 0xf;
b = c;
}

assert(c >= 0 && b <= 0xf, 'Invalid character');

This comment has been minimized.

Copy link
@dcousens

dcousens Nov 29, 2017

Contributor

that saving grace

This comment has been minimized.

Copy link
@indutny

indutny Nov 30, 2017

Author Owner

10% performance drop, but 200% better debuggability.

This comment has been minimized.

Copy link
@dcousens

dcousens Nov 30, 2017

Contributor

could the assert be moved into the else block above it?

This comment has been minimized.

Copy link
@indutny

indutny Nov 30, 2017

Author Owner

Good idea, there is also base-10 case. PRs are welcome 😉

This comment has been minimized.

Copy link
@dcousens

dcousens Nov 30, 2017

Contributor

@indutny see #173 for something better?

r |= b;
}
return r;
}
Expand Down Expand Up @@ -258,7 +263,7 @@
} else {
b = c;
}
assert(b < mul, 'Invalid character');
assert(c >= 0 && b < mul, 'Invalid character');
r += b;
}
return r;
Expand Down
11 changes: 7 additions & 4 deletions test/constructor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,14 @@ describe('BN.js/Constructor', function () {

it('should not accept decimal', function () {
assert.throws(function () {
BN('10.00', 10);
});
var res = new BN('10.00', 10);
res;
}, /Invalid character/);

assert.throws(function () {
BN('16.00', 16);
});
var res = new BN('16.00', 16);
res;
}, /Invalid character/);
});
});

Expand Down

0 comments on commit e924509

Please sign in to comment.