From a99366794decf221d7f08c9b2f2838942c45a349 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Mon, 2 Sep 2024 08:36:00 +0100 Subject: [PATCH] feat!: update to libp2p@2.x.x Incorporates API changes from the upcoming libp2p@2.x.x release. BREAKING CHANGE: Can only be used with libp2p@2.x.x or later --- package.json | 1 - src/index.ts | 27 ++++++++++++--------- src/utils/buildRawMessage.ts | 20 +++++++-------- src/utils/msgIdFn.ts | 2 +- src/utils/publishConfig.ts | 28 ++++++--------------- test/accept-from.spec.ts | 7 ++++-- test/gossip.spec.ts | 9 ++++--- test/peer-score.spec.ts | 47 ++++++++++++++++++------------------ test/scoreMetrics.spec.ts | 5 ++-- test/tracer.spec.ts | 11 +++++---- test/utils/create-pubsub.ts | 7 ++++-- test/utils/index.ts | 7 +++--- 12 files changed, 86 insertions(+), 85 deletions(-) diff --git a/package.json b/package.json index a674ef65..27de5e00 100644 --- a/package.json +++ b/package.json @@ -94,7 +94,6 @@ "@libp2p/floodsub": "^9.0.9", "@libp2p/interface-compliance-tests": "^5.2.0", "@libp2p/logger": "^4.0.5", - "@libp2p/peer-id-factory": "^4.0.5", "@libp2p/peer-store": "^10.0.8", "@types/node": "^20.11.6", "abortable-iterator": "^5.1.0", diff --git a/src/index.ts b/src/index.ts index 1f821e2c..72227e60 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,9 @@ import { TypedEventEmitter, StrictSign, StrictNoSign, TopicValidatorResult, serviceCapabilities, serviceDependencies } from '@libp2p/interface' -import { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id' +import { peerIdFromMultihash, peerIdFromString } from '@libp2p/peer-id' import { encode } from 'it-length-prefixed' import { pipe } from 'it-pipe' import { pushable } from 'it-pushable' +import * as Digest from 'multiformats/hashes/digest' import * as constants from './constants.js' import { ACCEPT_FROM_WHITELIST_DURATION_MS, @@ -73,7 +74,8 @@ import type { TopicValidatorFn, Logger, ComponentLogger, - Topology + Topology, + PrivateKey } from '@libp2p/interface' import type { ConnectionManager, IncomingStreamData, Registrar } from '@libp2p/interface-internal' import type { Multiaddr } from '@multiformats/multiaddr' @@ -166,13 +168,13 @@ export interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit { maxOutboundStreams?: number /** - * Pass true to run on transient connections - data or time-limited + * Pass true to run on limited connections - data or time-limited * connections that may be closed at any time such as circuit relay * connections. * * @default false */ - runOnTransientConnection?: boolean + runOnLimitedConnection?: boolean /** * Specify max buffer size in bytes for OutboundStream. @@ -259,6 +261,7 @@ interface AcceptFromWhitelistEntry { } export interface GossipSubComponents { + privateKey: PrivateKey peerId: PeerId peerStore: PeerStore registrar: Registrar @@ -420,7 +423,7 @@ export class GossipSub extends TypedEventEmitter implements Pub private status: GossipStatus = { code: GossipStatusCode.stopped } private readonly maxInboundStreams?: number private readonly maxOutboundStreams?: number - private readonly runOnTransientConnection?: boolean + private readonly runOnLimitedConnection?: boolean private readonly allowedTopics: Set | null private heartbeatTimer: { @@ -554,7 +557,7 @@ export class GossipSub extends TypedEventEmitter implements Pub this.maxInboundStreams = options.maxInboundStreams this.maxOutboundStreams = options.maxOutboundStreams - this.runOnTransientConnection = options.runOnTransientConnection + this.runOnLimitedConnection = options.runOnLimitedConnection this.allowedTopics = (opts.allowedTopics != null) ? new Set(opts.allowedTopics) : null } @@ -591,7 +594,7 @@ export class GossipSub extends TypedEventEmitter implements Pub this.log('starting') - this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId) + this.publishConfig = getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId, this.components.privateKey) // Create the outbound inflight queue // This ensures that outbound stream creation happens sequentially @@ -619,7 +622,7 @@ export class GossipSub extends TypedEventEmitter implements Pub registrar.handle(multicodec, this.onIncomingStream.bind(this), { maxInboundStreams: this.maxInboundStreams, maxOutboundStreams: this.maxOutboundStreams, - runOnTransientConnection: this.runOnTransientConnection + runOnLimitedConnection: this.runOnLimitedConnection }) ) ) @@ -646,7 +649,7 @@ export class GossipSub extends TypedEventEmitter implements Pub const topology: Topology = { onConnect: this.onPeerConnected.bind(this), onDisconnect: this.onPeerDisconnected.bind(this), - notifyOnTransient: this.runOnTransientConnection + notifyOnLimitedConnection: this.runOnLimitedConnection } const registrarTopologyIds = await Promise.all( this.multicodecs.map(async (multicodec) => registrar.register(multicodec, topology)) @@ -817,7 +820,7 @@ export class GossipSub extends TypedEventEmitter implements Pub try { const stream = new OutboundStream( await connection.newStream(this.multicodecs, { - runOnTransientConnection: this.runOnTransientConnection + runOnLimitedConnection: this.runOnLimitedConnection }), (e) => { this.log.error('outbound pipe error', e) }, { maxBufferSize: this.opts.maxOutboundBufferSize } @@ -1778,7 +1781,7 @@ export class GossipSub extends TypedEventEmitter implements Pub return } - const peer = peerIdFromBytes(pi.peerID) + const peer = peerIdFromMultihash(Digest.decode(pi.peerID)) const p = peer.toString() if (this.peers.has(p)) { @@ -2616,7 +2619,7 @@ export class GossipSub extends TypedEventEmitter implements Pub } return { - peerID: id.toBytes(), + peerID: id.toMultihash().bytes, signedPeerRecord: peerInfo?.peerRecordEnvelope } }) diff --git a/src/utils/buildRawMessage.ts b/src/utils/buildRawMessage.ts index 71b40072..3771dead 100644 --- a/src/utils/buildRawMessage.ts +++ b/src/utils/buildRawMessage.ts @@ -1,9 +1,9 @@ import { randomBytes } from '@libp2p/crypto' -import { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys' +import { publicKeyFromProtobuf } from '@libp2p/crypto/keys' import { StrictSign, StrictNoSign, type Message, type PublicKey, type PeerId } from '@libp2p/interface' -import { peerIdFromBytes } from '@libp2p/peer-id' +import { peerIdFromMultihash } from '@libp2p/peer-id' +import * as Digest from 'multiformats/hashes/digest' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' -import { equals as uint8ArrayEquals } from 'uint8arrays/equals' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { RPC } from '../message/rpc.js' @@ -25,7 +25,7 @@ export async function buildRawMessage ( switch (publishConfig.type) { case PublishConfigType.Signing: { const rpcMsg: RPC.Message = { - from: publishConfig.author.toBytes(), + from: publishConfig.author.toMultihash().bytes, data: transformedData, seqno: randomBytes(8), topic, @@ -47,7 +47,7 @@ export async function buildRawMessage ( sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno as Uint8Array, 'base16')}`), topic, signature: rpcMsg.signature, - key: rpcMsg.key + key: publicKeyFromProtobuf(rpcMsg.key) } return { raw: rpcMsg, @@ -108,7 +108,7 @@ export async function validateToRawMessage ( let fromPeerId: PeerId try { // TODO: Fix PeerId types - fromPeerId = peerIdFromBytes(msg.from) + fromPeerId = peerIdFromMultihash(Digest.decode(msg.from)) } catch (e) { return { valid: false, error: ValidateError.InvalidPeerId } } @@ -122,16 +122,16 @@ export async function validateToRawMessage ( let publicKey: PublicKey if (msg.key != null) { - publicKey = unmarshalPublicKey(msg.key) + publicKey = publicKeyFromProtobuf(msg.key) // TODO: Should `fromPeerId.pubKey` be optional? - if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) { + if (fromPeerId.publicKey !== undefined && !publicKey.equals(fromPeerId.publicKey)) { return { valid: false, error: ValidateError.InvalidPeerId } } } else { if (fromPeerId.publicKey == null) { return { valid: false, error: ValidateError.InvalidPeerId } } - publicKey = unmarshalPublicKey(fromPeerId.publicKey) + publicKey = fromPeerId.publicKey } const rpcMsgPreSign: RPC.Message = { @@ -160,7 +160,7 @@ export async function validateToRawMessage ( sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`), topic: msg.topic, signature: msg.signature, - key: msg.key ?? marshalPublicKey(publicKey) + key: msg.key != null ? publicKeyFromProtobuf(msg.key) : publicKey } } } diff --git a/src/utils/msgIdFn.ts b/src/utils/msgIdFn.ts index a36d40ab..510378de 100644 --- a/src/utils/msgIdFn.ts +++ b/src/utils/msgIdFn.ts @@ -13,7 +13,7 @@ export function msgIdFnStrictSign (msg: Message): Uint8Array { if (msg.sequenceNumber == null) throw Error('missing seqno field') // TODO: Should use .from here or key? - return msgId(msg.from.toBytes(), msg.sequenceNumber) + return msgId(msg.from.publicKey ?? msg.key, msg.sequenceNumber) } /** diff --git a/src/utils/publishConfig.ts b/src/utils/publishConfig.ts index 7d3acdad..cec74c98 100644 --- a/src/utils/publishConfig.ts +++ b/src/utils/publishConfig.ts @@ -1,36 +1,22 @@ -import { unmarshalPrivateKey } from '@libp2p/crypto/keys' +import { publicKeyToProtobuf } from '@libp2p/crypto/keys' import { StrictSign, StrictNoSign } from '@libp2p/interface' import { type PublishConfig, PublishConfigType } from '../types.js' -import type { PeerId } from '@libp2p/interface' +import type { PeerId, PrivateKey } from '@libp2p/interface' /** * Prepare a PublishConfig object from a PeerId. */ -export async function getPublishConfigFromPeerId ( +export function getPublishConfigFromPeerId ( signaturePolicy: typeof StrictSign | typeof StrictNoSign, - peerId?: PeerId -): Promise { + peerId: PeerId, + privateKey: PrivateKey +): PublishConfig { switch (signaturePolicy) { case StrictSign: { - if (peerId == null) { - throw Error('Must provide PeerId') - } - - if (peerId.privateKey == null) { - throw Error('Cannot sign message, no private key present') - } - - if (peerId.publicKey == null) { - throw Error('Cannot sign message, no public key present') - } - - // Transform privateKey once at initialization time instead of once per message - const privateKey = await unmarshalPrivateKey(peerId.privateKey) - return { type: PublishConfigType.Signing, author: peerId, - key: peerId.publicKey, + key: publicKeyToProtobuf(privateKey.publicKey), privateKey } } diff --git a/test/accept-from.spec.ts b/test/accept-from.spec.ts index ac220970..5f114fa6 100644 --- a/test/accept-from.spec.ts +++ b/test/accept-from.spec.ts @@ -1,10 +1,11 @@ +import { generateKeyPair } from '@libp2p/crypto/keys' import { type PeerStore } from '@libp2p/interface' import { defaultLogger } from '@libp2p/logger' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import sinon from 'sinon' import { stubInterface } from 'ts-sinon' import { GossipSub } from '../src/index.js' -import { createPeerId } from './utils/index.js' import { fastMsgIdFn } from './utils/msgId.js' import type { ConnectionManager, Registrar } from '@libp2p/interface-internal' @@ -20,9 +21,11 @@ describe('Gossipsub acceptFrom', () => { // not able to use fake timers or tests in browser are suspended // sandbox.useFakeTimers(Date.now()) - const peerId = await createPeerId() + const privateKey = await generateKeyPair('Ed25519') + const peerId = peerIdFromPrivateKey(privateKey) gossipsub = new GossipSub( { + privateKey, peerId, registrar: stubInterface(), peerStore: stubInterface(), diff --git a/test/gossip.spec.ts b/test/gossip.spec.ts index 6c4cfeb7..3d466bf2 100644 --- a/test/gossip.spec.ts +++ b/test/gossip.spec.ts @@ -1,7 +1,8 @@ +import { generateKeyPair } from '@libp2p/crypto/keys' import { stop } from '@libp2p/interface' import { mockNetwork } from '@libp2p/interface-compliance-tests/mocks' import { defaultLogger } from '@libp2p/logger' -import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import { pEvent } from 'p-event' import sinon, { type SinonStubbedInstance } from 'sinon' @@ -273,10 +274,12 @@ describe('gossip', () => { const maxOutboundStreams = 5 const registrar = stubInterface() - + const privateKey = await generateKeyPair('Ed25519') + const peerId = peerIdFromPrivateKey(privateKey) const pubsub = new GossipSub( { - peerId: await createEd25519PeerId(), + privateKey, + peerId, registrar, peerStore: stubInterface(), connectionManager: stubInterface(), diff --git a/test/peer-score.spec.ts b/test/peer-score.spec.ts index 2c01a08b..2234ff93 100644 --- a/test/peer-score.spec.ts +++ b/test/peer-score.spec.ts @@ -1,5 +1,6 @@ +import { generateKeyPair } from '@libp2p/crypto/keys' import { defaultLogger } from '@libp2p/logger' -import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import delay from 'delay' import sinon from 'sinon' @@ -28,7 +29,7 @@ describe('PeerScore', () => { timeInMeshQuantum: 1, timeInMeshCap: 3600 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -57,7 +58,7 @@ describe('PeerScore', () => { timeInMeshCap: 10, invalidMessageDeliveriesDecay: 0.1 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -89,7 +90,7 @@ describe('PeerScore', () => { firstMessageDeliveriesCap: 50000, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -124,7 +125,7 @@ describe('PeerScore', () => { firstMessageDeliveriesCap: 50, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -167,7 +168,7 @@ describe('PeerScore', () => { firstMessageDeliveriesCap: 50, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -227,9 +228,9 @@ describe('PeerScore', () => { // peer C delivers outside the delivery window // we expect peers A and B to have a score of zero, since all other param weights are zero // peer C should have a negative score - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() - const peerC = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerC = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const peers = [peerA, peerB, peerC] // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) @@ -291,7 +292,7 @@ describe('PeerScore', () => { firstMessageDeliveriesWeight: 0, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) @@ -350,8 +351,8 @@ describe('PeerScore', () => { firstMessageDeliveriesWeight: 0, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const peers = [peerA, peerB] const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) peers.forEach((p) => { @@ -400,7 +401,7 @@ describe('PeerScore', () => { invalidMessageDeliveriesDecay: 0.9, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) ps.graft(peerA, mytopic) @@ -431,7 +432,7 @@ describe('PeerScore', () => { invalidMessageDeliveriesDecay: 0.9, timeInMeshWeight: 0 })) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) ps.graft(peerA, mytopic) @@ -470,8 +471,8 @@ describe('PeerScore', () => { invalidMessageDeliveriesDecay: 0.9, timeInMeshQuantum: 1000 }) - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) ps.addPeer(peerB) @@ -549,7 +550,7 @@ describe('PeerScore', () => { appSpecificScore: () => appScoreValue, appSpecificWeight: 0.5 }) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) ps.graft(peerA, mytopic) @@ -569,10 +570,10 @@ describe('PeerScore', () => { IPColocationFactorThreshold: 1, IPColocationFactorWeight: -1 }) - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() - const peerC = (await createEd25519PeerId()).toString() - const peerD = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerC = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerD = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const peers = [peerA, peerB, peerC, peerD] const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) @@ -614,7 +615,7 @@ describe('PeerScore', () => { behaviourPenaltyWeight: -1, behaviourPenaltyDecay: 0.99 }) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) @@ -650,7 +651,7 @@ describe('PeerScore', () => { appSpecificWeight: 1, retainScore: 800 }) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) diff --git a/test/scoreMetrics.spec.ts b/test/scoreMetrics.spec.ts index eafc1e14..4c9575ec 100644 --- a/test/scoreMetrics.spec.ts +++ b/test/scoreMetrics.spec.ts @@ -1,5 +1,6 @@ +import { generateKeyPair } from '@libp2p/crypto/keys' import { defaultLogger } from '@libp2p/logger' -import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import { ScorePenalty } from '../src/metrics.js' import { createPeerScoreParams, createTopicScoreParams, PeerScore } from '../src/score/index.js' @@ -26,7 +27,7 @@ describe('score / scoreMetrics', () => { const topicStrToLabel = new Map() topicStrToLabel.set(topic, topic) - const peerA = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() // Peer score should start at 0 const ps = new PeerScore(params, null, logger, { scoreCacheValidityMs: 0 }) ps.addPeer(peerA) diff --git a/test/tracer.spec.ts b/test/tracer.spec.ts index bbe61f9e..a6769365 100644 --- a/test/tracer.spec.ts +++ b/test/tracer.spec.ts @@ -1,4 +1,5 @@ -import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { generateKeyPair } from '@libp2p/crypto/keys' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import delay from 'delay' import * as constants from '../src/constants.js' @@ -11,8 +12,8 @@ describe('IWantTracer', () => { // tests that unfulfilled promises are tracked correctly this.timeout(6000) const t = new IWantTracer(constants.GossipsubIWantFollowupTime, messageIdToString, null) - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const msgIds: Uint8Array[] = [] for (let i = 0; i < 100; i++) { @@ -39,8 +40,8 @@ describe('IWantTracer', () => { // like above, but this time we deliver messages to fullfil the promises this.timeout(6000) const t = new IWantTracer(constants.GossipsubIWantFollowupTime, messageIdToString, null) - const peerA = (await createEd25519PeerId()).toString() - const peerB = (await createEd25519PeerId()).toString() + const peerA = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() + const peerB = peerIdFromPrivateKey(await generateKeyPair('Ed25519')).toString() const msgs = [] const msgIds = [] diff --git a/test/utils/create-pubsub.ts b/test/utils/create-pubsub.ts index 75025e41..fc7292dc 100644 --- a/test/utils/create-pubsub.ts +++ b/test/utils/create-pubsub.ts @@ -1,8 +1,9 @@ import { setMaxListeners } from 'events' +import { generateKeyPair } from '@libp2p/crypto/keys' import { TypedEventEmitter, start } from '@libp2p/interface' import { mockRegistrar, mockConnectionManager, mockNetwork } from '@libp2p/interface-compliance-tests/mocks' import { defaultLogger } from '@libp2p/logger' -import { createRSAPeerId } from '@libp2p/peer-id-factory' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { PersistentPeerStore } from '@libp2p/peer-store' import { MemoryDatastore } from 'datastore-core' import { stubInterface } from 'ts-sinon' @@ -26,12 +27,14 @@ export interface GossipSubAndComponents { export const createComponents = async (opts: CreateComponentsOpts): Promise => { const Ctor = opts.pubsub ?? GossipSub - const peerId = await createRSAPeerId({ bits: 512 }) + const privateKey = await generateKeyPair('Ed25519') + const peerId = peerIdFromPrivateKey(privateKey) const events = new TypedEventEmitter() const logger = defaultLogger() const components: GossipSubTestComponents = { + privateKey, peerId, registrar: mockRegistrar(), connectionManager: stubInterface(), diff --git a/test/utils/index.ts b/test/utils/index.ts index 97faa349..47f7ab23 100644 --- a/test/utils/index.ts +++ b/test/utils/index.ts @@ -1,4 +1,5 @@ -import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { generateKeyPair } from '@libp2p/crypto/keys' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import type { RPC } from '../../src/message/rpc.js' import type { TopicStr } from '../../src/types.js' @@ -7,7 +8,7 @@ import type { PeerId } from '@libp2p/interface' export * from './msgId.js' export const createPeerId = async (): Promise => { - const peerId = await createEd25519PeerId() + const peerId = peerIdFromPrivateKey(await generateKeyPair('Ed25519')) return peerId } @@ -19,7 +20,7 @@ export function makeTestMessage (i: number, topic: TopicStr, from?: PeerId): RPC return { seqno: uint8ArrayFromString((seq++).toString(16).padStart(16, '0'), 'base16'), data: Uint8Array.from([i]), - from: from?.toBytes() ?? defaultPeer, + from: from?.toMultihash().bytes ?? defaultPeer, topic } }