From e5c6acde7d2ead5f7c916c9dba8cf0964116b0fa Mon Sep 17 00:00:00 2001 From: Arthur Britto Date: Thu, 3 Jan 2013 00:54:20 -0800 Subject: [PATCH] JS: Restrict UInt160 parse_json to wire format. --- src/js/amount.js | 28 +++++++++++++++++++++++++++- test/amount-test.js | 6 +++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/js/amount.js b/src/js/amount.js index 489fbc24..0c1387b0 100644 --- a/src/js/amount.js +++ b/src/js/amount.js @@ -254,6 +254,13 @@ UInt160.json_rewrite = function (j) { return UInt160.from_json(j).to_json(); }; +// Return a new UInt160 from j. +UInt160.from_generic = function (j) { + return 'string' === typeof j + ? (new UInt160()).parse_generic(j) + : j.clone(); +}; + // Return a new UInt160 from j. UInt160.from_json = function (j) { return 'string' === typeof j @@ -285,7 +292,7 @@ UInt160.prototype.is_valid = function () { }; // value = NaN on error. -UInt160.prototype.parse_json = function (j) { +UInt160.prototype.parse_generic = function (j) { // Canonicalize and validate if (exports.config.accounts && j in exports.config.accounts) j = exports.config.accounts[j].account; @@ -329,6 +336,25 @@ UInt160.prototype.parse_json = function (j) { return this; }; +// value = NaN on error. +UInt160.prototype.parse_json = function (j) { + // Canonicalize and validate + if (exports.config.accounts && j in exports.config.accounts) + j = exports.config.accounts[j].account; + + if ('string' !== typeof j) { + this._value = NaN; + } + else if (j[0] === "r") { + this._value = decode_base_check(consts.VER_ACCOUNT_ID, j); + } + else { + this._value = NaN; + } + + return this; +}; + // Convert from internal form. // XXX Json form should allow 0 and 1, C++ doesn't currently allow it. UInt160.prototype.to_json = function () { diff --git a/test/amount-test.js b/test/amount-test.js index 712c2f8b..71279cbe 100644 --- a/test/amount-test.js +++ b/test/amount-test.js @@ -17,13 +17,13 @@ var config = require('./config.js'); buster.testCase("Amount", { "UInt160" : { "Parse 0" : function () { - buster.assert.equals(nbi(), UInt160.from_json("0")._value); + buster.assert.equals(nbi(), UInt160.from_generic("0")._value); }, "Parse 0 export" : function () { - buster.assert.equals(amount.consts.address_xns, UInt160.from_json("0").to_json()); + buster.assert.equals(amount.consts.address_xns, UInt160.from_generic("0").to_json()); }, "Parse 1" : function () { - buster.assert.equals(new BigInteger([1]), UInt160.from_json("1")._value); + buster.assert.equals(new BigInteger([1]), UInt160.from_generic("1")._value); }, "Parse rrrrrrrrrrrrrrrrrrrrrhoLvTp export" : function () { buster.assert.equals(amount.consts.address_xns, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrrhoLvTp").to_json());