From b2ee34295bca2efd6455a341b7812dd16ec7909e Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Wed, 23 Sep 2020 19:07:28 +0200 Subject: [PATCH] feat: has inline public key method (#132) --- src/index.d.ts | 5 +++++ src/index.js | 17 +++++++++++++++++ test/peer-id.spec.js | 12 ++++++++++++ 3 files changed, 34 insertions(+) diff --git a/src/index.d.ts b/src/index.d.ts index d9e720f..0906fb3 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -183,6 +183,11 @@ declare class PeerId { * Check if this PeerId instance is valid (privKey -> pubKey -> Id) */ isValid(): boolean; + + /** + * Check if the PeerId has an inline public key. + */ + hasInlinePublicKey(): boolean; } export = PeerId; diff --git a/src/index.js b/src/index.js index 7af71f9..311f223 100644 --- a/src/index.js +++ b/src/index.js @@ -178,6 +178,23 @@ class PeerId { this.pubKey.bytes instanceof Uint8Array && uint8ArrayEquals(this.privKey.public.bytes, this.pubKey.bytes)) } + + /** + * Check if the PeerId has an inline public key. + * @returns {boolean} + */ + hasInlinePublicKey () { + try { + const decoded = mh.decode(this.id) + if (decoded.name === 'identity') { + return true + } + } catch (_) { + // Ignore, there is no valid public key + } + + return false + } } const PeerIdWithIs = withIs(PeerId, { diff --git a/test/peer-id.spec.js b/test/peer-id.spec.js index bf97ee9..66d88eb 100644 --- a/test/peer-id.spec.js +++ b/test/peer-id.spec.js @@ -243,6 +243,18 @@ describe('PeerId', () => { expect(ids[0].equals(ids[1].id)).to.equal(false) }) + describe('hasInlinePublicKey', () => { + it('returns true if uses a key type with inline public key', async () => { + const peerId = await PeerId.create({ keyType: 'secp256k1' }) + expect(peerId.hasInlinePublicKey()).to.equal(true) + }) + + it('returns false if uses a key type with no inline public key', async () => { + const peerId = await PeerId.create({ keyType: 'RSA' }) + expect(peerId.hasInlinePublicKey()).to.equal(false) + }) + }) + describe('fromJSON', () => { it('full node', async () => { const id = await PeerId.create(testOpts)