Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit b4c8112

Browse files
yzevmcgewecke
authored andcommitted
fix hexToNumber & hexToNumberString prefix validation
1 parent 35b2e22 commit b4c8112

File tree

3 files changed

+30
-6
lines changed

3 files changed

+30
-6
lines changed

packages/web3-utils/src/utils.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,10 @@ var hexToNumber = function (value) {
231231
return value;
232232
}
233233

234+
if (_.isString(value) && !isHexStrict(value)) {
235+
throw new Error('Given value "'+value+'" is not a valid hex string.');
236+
}
237+
234238
return toBN(value).toNumber();
235239
};
236240

@@ -244,6 +248,10 @@ var hexToNumber = function (value) {
244248
var hexToNumberString = function (value) {
245249
if (!value) return value;
246250

251+
if (_.isString(value) && !isHexStrict(value)) {
252+
throw new Error('Given value "'+value+'" is not a valid hex string.');
253+
}
254+
247255
return toBN(value).toString(10);
248256
};
249257

test/utils.toNumber.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,22 @@ var assert = require('assert');
22
var utils = require('../packages/web3-utils');
33

44
describe('lib/utils/utils', function () {
5-
describe('hexToNumberString', function () {
5+
describe('hexToNumber', function () {
66
it('should return the correct value', function () {
77

8-
assert.equal(utils.hexToNumberString("0x3e8"), 1000);
9-
assert.equal(utils.hexToNumberString('0x1f0fe294a36'), 2134567897654);
8+
assert.equal(utils.hexToNumber("0x3e8"), 1000);
9+
assert.equal(utils.hexToNumber('0x1f0fe294a36'), 2134567897654);
1010
// allow compatiblity
11-
assert.equal(utils.hexToNumberString(100000), 100000);
12-
assert.equal(utils.hexToNumberString('100000'), 100000);
11+
assert.equal(utils.hexToNumber(100000), 100000);
1312
});
13+
14+
it('should validate hex strings', function() {
15+
try {
16+
utils.hexToNumber('100000');
17+
assert.fail();
18+
} catch (error){
19+
assert(error.message.includes('is not a valid hex string'))
20+
}
21+
})
1422
});
1523
});

test/utils.toNumberString.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,15 @@ describe('lib/utils/utils', function () {
99
assert.equal(utils.hexToNumberString('0x1f0fe294a36'), '2134567897654');
1010
// allow compatiblity
1111
assert.equal(utils.hexToNumberString(100000), '100000');
12-
assert.equal(utils.hexToNumberString('100000'), '100000');
1312
});
13+
14+
it('should validate hex strings', function() {
15+
try {
16+
utils.hexToNumberString('100000');
17+
assert.fail();
18+
} catch (error){
19+
assert(error.message.includes('is not a valid hex string'))
20+
}
21+
})
1422
});
1523
});

0 commit comments

Comments
 (0)