From f1c116746ab82b15b93a7875ed1b05861b8c0d32 Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Thu, 28 Dec 2023 08:38:11 +0100 Subject: [PATCH] fix: make peerid optional in peerid.equals (#2335) This makes the code a bit more flexible, for example when taking action based on an optional peerid having been passed to a function when an existing peer id is known. --- packages/interface/src/peer-id/index.ts | 2 +- packages/peer-id/src/index.ts | 6 +++++- packages/peer-id/test/index.spec.ts | 12 ++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/interface/src/peer-id/index.ts b/packages/interface/src/peer-id/index.ts index 1ee6dee4ac..13d0b77c82 100644 --- a/packages/interface/src/peer-id/index.ts +++ b/packages/interface/src/peer-id/index.ts @@ -12,7 +12,7 @@ interface BasePeerId { toString(): string toCID(): CID toBytes(): Uint8Array - equals(other: PeerId | Uint8Array | string): boolean + equals(other?: PeerId | Uint8Array | string): boolean } export interface RSAPeerId extends BasePeerId { diff --git a/packages/peer-id/src/index.ts b/packages/peer-id/src/index.ts index 15cdc237ad..bc2022afbe 100644 --- a/packages/peer-id/src/index.ts +++ b/packages/peer-id/src/index.ts @@ -115,7 +115,11 @@ class PeerIdImpl { /** * Checks the equality of `this` peer against a given PeerId */ - equals (id: PeerId | Uint8Array | string): boolean { + equals (id?: PeerId | Uint8Array | string): boolean { + if (id == null) { + return false + } + if (id instanceof Uint8Array) { return uint8ArrayEquals(this.multihash.bytes, id) } else if (typeof id === 'string') { diff --git a/packages/peer-id/test/index.spec.ts b/packages/peer-id/test/index.spec.ts index 98af69f365..559a49fea7 100644 --- a/packages/peer-id/test/index.spec.ts +++ b/packages/peer-id/test/index.spec.ts @@ -47,6 +47,18 @@ describe('PeerId', () => { expect(id.equals(peerIdFromBytes(buf))).to.be.true() }) + it('equals nothing', async () => { + const buf = uint8ArrayFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa', 'base58btc') + const id = peerIdFromBytes(buf) + expect(id.equals()).to.be.false() + }) + + it('equals undefined', async () => { + const buf = uint8ArrayFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa', 'base58btc') + const id = peerIdFromBytes(buf) + expect(id.equals(undefined)).to.be.false() + }) + it('parses a PeerId as Ed25519', async () => { const id = peerIdFromString('12D3KooWbtp1AcgweFSArD7dbKWYpAr8MZR1tofwNwLFLjeNGLWa') expect(id).to.have.property('type', 'Ed25519')