Merge pull request #342 from nodar-chkuaselidze/enhancement/cli-bech32

CLI to accept bech32 addresses
This commit is contained in:
Christopher Jeffrey (JJ) 2017-10-18 13:06:46 -07:00 committed by GitHub
commit 4bf7426566
3 changed files with 39 additions and 2 deletions

View File

@ -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;

View File

@ -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

View File

@ -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);
}
});
});