From 95efc7c3b0bd5d152db68f09964e9710bf20f520 Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Sun, 30 Sep 2018 21:27:55 -0700 Subject: [PATCH] fix: support creating a PublicKey from a base58 string --- web3.js/.gitignore | 2 +- web3.js/src/publickey.js | 23 ++++++++++++++++++----- web3.js/test/publickey.test.js | 3 ++- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/web3.js/.gitignore b/web3.js/.gitignore index 5558b8e798..dfae3cb105 100644 --- a/web3.js/.gitignore +++ b/web3.js/.gitignore @@ -23,4 +23,4 @@ lib doc # VIM swap files -*.sw[po] +*.sw. diff --git a/web3.js/src/publickey.js b/web3.js/src/publickey.js index 3af8d5ec4b..a319195185 100644 --- a/web3.js/src/publickey.js +++ b/web3.js/src/publickey.js @@ -13,13 +13,26 @@ export class PublicKey { * Create a new PublicKey object */ constructor(number: string | Buffer | Array) { - let radix = 10; - if (typeof number === 'string' && number.startsWith('0x')) { - this._bn = new BN(number.substring(2), 16); - } else { - this._bn = new BN(number, radix); + for (;;) { + if (typeof number === 'string') { + // base 58 encoded? + if (/^[1-9A-HJ-NP-Za-km-z]{43,44}$/.test(number)) { + this._bn = new BN(bs58.decode(number)); + break; + } + + // hexadecimal number + if (number.startsWith('0x')) { + this._bn = new BN(number.substring(2), 16); + break; + } + } + + this._bn = new BN(number); + break; } + if (this._bn.byteLength() > 32) { throw new Error(`Invalid public key input`); } diff --git a/web3.js/test/publickey.test.js b/web3.js/test/publickey.test.js index 6ec4d2f754..2bb0bef543 100644 --- a/web3.js/test/publickey.test.js +++ b/web3.js/test/publickey.test.js @@ -23,9 +23,11 @@ test('equals', () => { ]); const hexKey = new PublicKey('0x300000000000000000000000000000000000000000000000000000000000000'); const decimalKey = new PublicKey('1356938545749799165119972480570561420155507632800475359837393562592731987968'); + const base56Key = new PublicKey('CiDwVBFgWV9E5MvXWoLgnEgn2hK7rJikbvfWavzAQz3'); expect(arrayKey.equals(hexKey)).toBeTruthy(); expect(arrayKey.equals(decimalKey)).toBeTruthy(); + expect(arrayKey.equals(base56Key)).toBeTruthy(); }); test('isPublicKey', () => { @@ -40,7 +42,6 @@ test('toBase58', () => { const key2 = new PublicKey('123456789'); expect(key2.toBase58()).toBe('Vj3WURvtMv1mii1vhTqLhcSwVWDRs2E135KtTYUXtTq'); - console.log(key2.toBuffer()); }); test('toBuffer', () => {