diff --git a/packages/libp2p/src/libp2p.ts b/packages/libp2p/src/libp2p.ts index 022516beac..f104d67a30 100644 --- a/packages/libp2p/src/libp2p.ts +++ b/packages/libp2p/src/libp2p.ts @@ -311,10 +311,16 @@ export class Libp2pNode> extends return peer.publicKey } - const peerInfo = await this.peerStore.get(peer) + try { + const peerInfo = await this.peerStore.get(peer) - if (peerInfo.id.publicKey != null) { - return peerInfo.id.publicKey + if (peerInfo.id.publicKey != null) { + return peerInfo.id.publicKey + } + } catch (err: any) { + if (err.code !== codes.ERR_NOT_FOUND) { + throw err + } } const peerKey = uint8ArrayConcat([ @@ -324,6 +330,7 @@ export class Libp2pNode> extends // search any available content routing methods const bytes = await this.contentRouting.get(peerKey, options) + // ensure the returned key is valid unmarshalPublicKey(bytes) diff --git a/packages/libp2p/test/core/get-public-key.spec.ts b/packages/libp2p/test/core/get-public-key.spec.ts index 0b32e61076..0b3df73de7 100644 --- a/packages/libp2p/test/core/get-public-key.spec.ts +++ b/packages/libp2p/test/core/get-public-key.spec.ts @@ -1,6 +1,7 @@ /* eslint-env mocha */ import { contentRoutingSymbol } from '@libp2p/interface' +import { peerIdFromString } from '@libp2p/peer-id' import { createEd25519PeerId, createRSAPeerId } from '@libp2p/peer-id-factory' import { expect } from 'aegir/chai' import { stubInterface } from 'sinon-ts' @@ -13,9 +14,8 @@ describe('getPublicKey', () => { let router: StubbedInstance beforeEach(async () => { - router = stubInterface({ - [contentRoutingSymbol]: router - }) + router = stubInterface() + router[contentRoutingSymbol] = router node = await createLibp2p({ services: { @@ -57,14 +57,21 @@ describe('getPublicKey', () => { it('should query content routing when the key is not in the keystore', async () => { const otherPeer = await createRSAPeerId() - if (otherPeer.publicKey == null) { - throw new Error('Public key was missing') - } + router.get.callsFake(async () => { + if (otherPeer.publicKey == null) { + throw new Error('Public key was missing') + } + + return Promise.resolve(otherPeer.publicKey) + }) - router.get.resolves(otherPeer.publicKey) + // create a copy of the RSA key, this will not have the public key + const otherPeerWithoutPublicKey = peerIdFromString(otherPeer.toString()) + expect(otherPeerWithoutPublicKey).to.have.property('publicKey', undefined) - const key = await node.getPublicKey(otherPeer) + const key = await node.getPublicKey(otherPeerWithoutPublicKey) expect(otherPeer.publicKey).to.equalBytes(key) + expect(router.get.called).to.be.true('routing was not queried') }) })