From 3a802cacd6039cf06955fb2558bfa8d52e27fdb5 Mon Sep 17 00:00:00 2001 From: Node Date: Mon, 16 Oct 2017 23:49:02 +0400 Subject: [PATCH] cli: accept bech32 addresses in getTX/getCoin --- bin/cli | 4 ++-- lib/utils/util.js | 21 +++++++++++++++++++++ test/utils-test.js | 16 ++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/bin/cli b/bin/cli index 77abe537..cad7e5a7 100755 --- a/bin/cli +++ b/bin/cli @@ -165,7 +165,7 @@ CLI.prototype.getWallet = async function getWallet() { CLI.prototype.getTX = async function getTX() { const hash = this.config.str(0); - if (util.isBase58(hash)) { + if (util.isBase58(hash) || util.isBech32(hash)) { const txs = await this.client.getTXByAddress(hash); this.log(txs); return; @@ -201,7 +201,7 @@ CLI.prototype.getCoin = async function getCoin() { const hash = this.config.str(0); const index = this.config.uint(1); - if (util.isBase58(hash)) { + if (util.isBase58(hash) || util.isBech32(hash)) { const coins = await this.client.getCoinsByAddress(hash); this.log(coins); return; diff --git a/lib/utils/util.js b/lib/utils/util.js index f348c437..de43bb97 100644 --- a/lib/utils/util.js +++ b/lib/utils/util.js @@ -186,6 +186,27 @@ util.isBase58 = function isBase58(str) { return typeof str === 'string' && /^[1-9A-Za-z]+$/.test(str); }; +/** + * Test whether a string is bech32 (note that + * this doesn't guarantee address is bech32). + * @param {String?} str + * @returns {Boolean} + */ + +util.isBech32 = function isBech32(str) { + if (typeof str !== 'string') + return false; + + if (str.toUpperCase() !== str && str.toLowerCase() !== str) + return false; + + if (str.length < 8 || str.length > 90) + return false; + + // it's unlikely any network will have hrp other than a-z symbols. + return /^[a-z]{2}1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]+$/i.test(str); +}; + /** * Test whether a string is hex (length must be even). * Note that this _could_ await a false positive on diff --git a/test/utils-test.js b/test/utils-test.js index 8e7240ac..8f964c3e 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -32,6 +32,16 @@ const base58Tests = [ ['00000000000000000000', '1111111111'] ]; +const validBech32Tests = [ + 'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4', + 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', + 'bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw50' + + '8d6qejxtdg4y5r3zarvary0c5xw7k7grplx', + 'BC1SW50QA3JX3S', + 'bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj', + 'tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy' +]; + const unsigned = [ new U64('ffeeffee', 16), new U64('001fffeeffeeffee', 16), @@ -244,4 +254,10 @@ describe('Utils', function() { assert.strictEqual(validator.bool('shouldBeTrue'), true); assert.strictEqual(validator.bool('shouldBeFalse'), false); }); + + it('should validate bech32 addresses based only on string data', () => { + for (const bech32addr of validBech32Tests) { + assert.strictEqual(util.isBech32(bech32addr), true); + } + }); });