Skip to content

Commit c8f18c8

Browse files
author
Chris Clark
committed
[FIX] Handle invalid input in parse_human
1 parent ba9af55 commit c8f18c8

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

src/js/ripple/amount.js

+13-6
Original file line numberDiff line numberDiff line change
@@ -466,25 +466,29 @@ Amount.prototype.parse_human = function(j, opts) {
466466

467467
var words = j.split(' ').filter(function(word) { return word !== ''; });
468468

469+
function isNumber(s) {
470+
return isFinite(s) && s !== '';
471+
}
472+
469473
if (words.length === 1) {
470-
if (isFinite(words[0])) {
474+
if (isNumber(words[0])) {
471475
value = words[0];
472476
currency = 'XRP';
473477
} else {
474478
value = words[0].slice(0, -3);
475479
currency = words[0].slice(-3);
476-
if (!(isFinite(value) && currency.match(currency_RE))) {
480+
if (!(isNumber(value) && currency.match(currency_RE))) {
477481
return Amount.NaN();
478482
}
479483
}
480484
} else if (words.length === 2) {
481-
if (isFinite(words[0]) && words[1].match(hex_RE)) {
485+
if (isNumber(words[0]) && words[1].match(hex_RE)) {
482486
value = words[0];
483487
currency = words[1];
484-
} else if (words[0].match(currency_RE) && isFinite(words[1])) {
488+
} else if (words[0].match(currency_RE) && isNumber(words[1])) {
485489
value = words[1];
486490
currency = words[0];
487-
} else if (isFinite(words[0]) && words[1].match(currency_RE)) {
491+
} else if (isNumber(words[0]) && words[1].match(currency_RE)) {
488492
value = words[0];
489493
currency = words[1];
490494
} else {
@@ -826,7 +830,7 @@ Amount.prototype.to_human = function(opts) {
826830
opts = opts || {};
827831

828832
if (!this.is_valid()) {
829-
return '';
833+
return 'NaN';
830834
}
831835

832836
// Default options
@@ -960,6 +964,9 @@ Amount.prototype.to_json = function() {
960964
};
961965

962966
Amount.prototype.to_text_full = function(opts) {
967+
if (!this.is_valid()) {
968+
return 'NaN';
969+
}
963970
return this._is_native
964971
? this.to_human() + '/XRP'
965972
: this.to_text() + '/' + this._currency.to_json() + '/' + this._issuer.to_json(opts);

test/amount-test.js

+6
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,12 @@ describe('Amount', function() {
120120
});
121121
});
122122
describe('from_human', function() {
123+
it('empty string', function() {
124+
assert.strictEqual(Amount.from_human('').to_text_full(), 'NaN');
125+
});
126+
it('missing value', function() {
127+
assert.strictEqual(Amount.from_human('USD').to_text_full(), 'NaN');
128+
});
123129
it('1 XRP', function() {
124130
assert.strictEqual(Amount.from_human("1 XRP").to_text_full(), '1/XRP');
125131
});

0 commit comments

Comments
 (0)