Skip to content

Commit a993667

Browse files
committed
feat!: update to [email protected]
Incorporates API changes from the upcoming [email protected] release. BREAKING CHANGE: Can only be used with [email protected] or later
1 parent 9e57215 commit a993667

12 files changed

+86
-85
lines changed

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@
9494
"@libp2p/floodsub": "^9.0.9",
9595
"@libp2p/interface-compliance-tests": "^5.2.0",
9696
"@libp2p/logger": "^4.0.5",
97-
"@libp2p/peer-id-factory": "^4.0.5",
9897
"@libp2p/peer-store": "^10.0.8",
9998
"@types/node": "^20.11.6",
10099
"abortable-iterator": "^5.1.0",

src/index.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { TypedEventEmitter, StrictSign, StrictNoSign, TopicValidatorResult, serviceCapabilities, serviceDependencies } from '@libp2p/interface'
2-
import { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'
2+
import { peerIdFromMultihash, peerIdFromString } from '@libp2p/peer-id'
33
import { encode } from 'it-length-prefixed'
44
import { pipe } from 'it-pipe'
55
import { pushable } from 'it-pushable'
6+
import * as Digest from 'multiformats/hashes/digest'
67
import * as constants from './constants.js'
78
import {
89
ACCEPT_FROM_WHITELIST_DURATION_MS,
@@ -73,7 +74,8 @@ import type {
7374
TopicValidatorFn,
7475
Logger,
7576
ComponentLogger,
76-
Topology
77+
Topology,
78+
PrivateKey
7779
} from '@libp2p/interface'
7880
import type { ConnectionManager, IncomingStreamData, Registrar } from '@libp2p/interface-internal'
7981
import type { Multiaddr } from '@multiformats/multiaddr'
@@ -166,13 +168,13 @@ export interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {
166168
maxOutboundStreams?: number
167169

168170
/**
169-
* Pass true to run on transient connections - data or time-limited
171+
* Pass true to run on limited connections - data or time-limited
170172
* connections that may be closed at any time such as circuit relay
171173
* connections.
172174
*
173175
* @default false
174176
*/
175-
runOnTransientConnection?: boolean
177+
runOnLimitedConnection?: boolean
176178

177179
/**
178180
* Specify max buffer size in bytes for OutboundStream.
@@ -259,6 +261,7 @@ interface AcceptFromWhitelistEntry {
259261
}
260262

261263
export interface GossipSubComponents {
264+
privateKey: PrivateKey
262265
peerId: PeerId
263266
peerStore: PeerStore
264267
registrar: Registrar
@@ -420,7 +423,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
420423
private status: GossipStatus = { code: GossipStatusCode.stopped }
421424
private readonly maxInboundStreams?: number
422425
private readonly maxOutboundStreams?: number
423-
private readonly runOnTransientConnection?: boolean
426+
private readonly runOnLimitedConnection?: boolean
424427
private readonly allowedTopics: Set<TopicStr> | null
425428

426429
private heartbeatTimer: {
@@ -554,7 +557,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
554557

555558
this.maxInboundStreams = options.maxInboundStreams
556559
this.maxOutboundStreams = options.maxOutboundStreams
557-
this.runOnTransientConnection = options.runOnTransientConnection
560+
this.runOnLimitedConnection = options.runOnLimitedConnection
558561

559562
this.allowedTopics = (opts.allowedTopics != null) ? new Set(opts.allowedTopics) : null
560563
}
@@ -591,7 +594,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
591594

592595
this.log('starting')
593596

594-
this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId)
597+
this.publishConfig = getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId, this.components.privateKey)
595598

596599
// Create the outbound inflight queue
597600
// This ensures that outbound stream creation happens sequentially
@@ -619,7 +622,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
619622
registrar.handle(multicodec, this.onIncomingStream.bind(this), {
620623
maxInboundStreams: this.maxInboundStreams,
621624
maxOutboundStreams: this.maxOutboundStreams,
622-
runOnTransientConnection: this.runOnTransientConnection
625+
runOnLimitedConnection: this.runOnLimitedConnection
623626
})
624627
)
625628
)
@@ -646,7 +649,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
646649
const topology: Topology = {
647650
onConnect: this.onPeerConnected.bind(this),
648651
onDisconnect: this.onPeerDisconnected.bind(this),
649-
notifyOnTransient: this.runOnTransientConnection
652+
notifyOnLimitedConnection: this.runOnLimitedConnection
650653
}
651654
const registrarTopologyIds = await Promise.all(
652655
this.multicodecs.map(async (multicodec) => registrar.register(multicodec, topology))
@@ -817,7 +820,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
817820
try {
818821
const stream = new OutboundStream(
819822
await connection.newStream(this.multicodecs, {
820-
runOnTransientConnection: this.runOnTransientConnection
823+
runOnLimitedConnection: this.runOnLimitedConnection
821824
}),
822825
(e) => { this.log.error('outbound pipe error', e) },
823826
{ maxBufferSize: this.opts.maxOutboundBufferSize }
@@ -1778,7 +1781,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
17781781
return
17791782
}
17801783

1781-
const peer = peerIdFromBytes(pi.peerID)
1784+
const peer = peerIdFromMultihash(Digest.decode(pi.peerID))
17821785
const p = peer.toString()
17831786

17841787
if (this.peers.has(p)) {
@@ -2616,7 +2619,7 @@ export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements Pub
26162619
}
26172620

26182621
return {
2619-
peerID: id.toBytes(),
2622+
peerID: id.toMultihash().bytes,
26202623
signedPeerRecord: peerInfo?.peerRecordEnvelope
26212624
}
26222625
})

src/utils/buildRawMessage.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { randomBytes } from '@libp2p/crypto'
2-
import { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'
2+
import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'
33
import { StrictSign, StrictNoSign, type Message, type PublicKey, type PeerId } from '@libp2p/interface'
4-
import { peerIdFromBytes } from '@libp2p/peer-id'
4+
import { peerIdFromMultihash } from '@libp2p/peer-id'
5+
import * as Digest from 'multiformats/hashes/digest'
56
import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
6-
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
77
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
88
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
99
import { RPC } from '../message/rpc.js'
@@ -25,7 +25,7 @@ export async function buildRawMessage (
2525
switch (publishConfig.type) {
2626
case PublishConfigType.Signing: {
2727
const rpcMsg: RPC.Message = {
28-
from: publishConfig.author.toBytes(),
28+
from: publishConfig.author.toMultihash().bytes,
2929
data: transformedData,
3030
seqno: randomBytes(8),
3131
topic,
@@ -47,7 +47,7 @@ export async function buildRawMessage (
4747
sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno as Uint8Array, 'base16')}`),
4848
topic,
4949
signature: rpcMsg.signature,
50-
key: rpcMsg.key
50+
key: publicKeyFromProtobuf(rpcMsg.key)
5151
}
5252
return {
5353
raw: rpcMsg,
@@ -108,7 +108,7 @@ export async function validateToRawMessage (
108108
let fromPeerId: PeerId
109109
try {
110110
// TODO: Fix PeerId types
111-
fromPeerId = peerIdFromBytes(msg.from)
111+
fromPeerId = peerIdFromMultihash(Digest.decode(msg.from))
112112
} catch (e) {
113113
return { valid: false, error: ValidateError.InvalidPeerId }
114114
}
@@ -122,16 +122,16 @@ export async function validateToRawMessage (
122122

123123
let publicKey: PublicKey
124124
if (msg.key != null) {
125-
publicKey = unmarshalPublicKey(msg.key)
125+
publicKey = publicKeyFromProtobuf(msg.key)
126126
// TODO: Should `fromPeerId.pubKey` be optional?
127-
if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) {
127+
if (fromPeerId.publicKey !== undefined && !publicKey.equals(fromPeerId.publicKey)) {
128128
return { valid: false, error: ValidateError.InvalidPeerId }
129129
}
130130
} else {
131131
if (fromPeerId.publicKey == null) {
132132
return { valid: false, error: ValidateError.InvalidPeerId }
133133
}
134-
publicKey = unmarshalPublicKey(fromPeerId.publicKey)
134+
publicKey = fromPeerId.publicKey
135135
}
136136

137137
const rpcMsgPreSign: RPC.Message = {
@@ -160,7 +160,7 @@ export async function validateToRawMessage (
160160
sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`),
161161
topic: msg.topic,
162162
signature: msg.signature,
163-
key: msg.key ?? marshalPublicKey(publicKey)
163+
key: msg.key != null ? publicKeyFromProtobuf(msg.key) : publicKey
164164
}
165165
}
166166
}

src/utils/msgIdFn.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function msgIdFnStrictSign (msg: Message): Uint8Array {
1313
if (msg.sequenceNumber == null) throw Error('missing seqno field')
1414

1515
// TODO: Should use .from here or key?
16-
return msgId(msg.from.toBytes(), msg.sequenceNumber)
16+
return msgId(msg.from.publicKey ?? msg.key, msg.sequenceNumber)
1717
}
1818

1919
/**

src/utils/publishConfig.ts

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,22 @@
1-
import { unmarshalPrivateKey } from '@libp2p/crypto/keys'
1+
import { publicKeyToProtobuf } from '@libp2p/crypto/keys'
22
import { StrictSign, StrictNoSign } from '@libp2p/interface'
33
import { type PublishConfig, PublishConfigType } from '../types.js'
4-
import type { PeerId } from '@libp2p/interface'
4+
import type { PeerId, PrivateKey } from '@libp2p/interface'
55

66
/**
77
* Prepare a PublishConfig object from a PeerId.
88
*/
9-
export async function getPublishConfigFromPeerId (
9+
export function getPublishConfigFromPeerId (
1010
signaturePolicy: typeof StrictSign | typeof StrictNoSign,
11-
peerId?: PeerId
12-
): Promise<PublishConfig> {
11+
peerId: PeerId,
12+
privateKey: PrivateKey
13+
): PublishConfig {
1314
switch (signaturePolicy) {
1415
case StrictSign: {
15-
if (peerId == null) {
16-
throw Error('Must provide PeerId')
17-
}
18-
19-
if (peerId.privateKey == null) {
20-
throw Error('Cannot sign message, no private key present')
21-
}
22-
23-
if (peerId.publicKey == null) {
24-
throw Error('Cannot sign message, no public key present')
25-
}
26-
27-
// Transform privateKey once at initialization time instead of once per message
28-
const privateKey = await unmarshalPrivateKey(peerId.privateKey)
29-
3016
return {
3117
type: PublishConfigType.Signing,
3218
author: peerId,
33-
key: peerId.publicKey,
19+
key: publicKeyToProtobuf(privateKey.publicKey),
3420
privateKey
3521
}
3622
}

test/accept-from.spec.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
import { generateKeyPair } from '@libp2p/crypto/keys'
12
import { type PeerStore } from '@libp2p/interface'
23
import { defaultLogger } from '@libp2p/logger'
4+
import { peerIdFromPrivateKey } from '@libp2p/peer-id'
35
import { expect } from 'aegir/chai'
46
import sinon from 'sinon'
57
import { stubInterface } from 'ts-sinon'
68
import { GossipSub } from '../src/index.js'
7-
import { createPeerId } from './utils/index.js'
89
import { fastMsgIdFn } from './utils/msgId.js'
910
import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
1011

@@ -20,9 +21,11 @@ describe('Gossipsub acceptFrom', () => {
2021
// not able to use fake timers or tests in browser are suspended
2122
// sandbox.useFakeTimers(Date.now())
2223

23-
const peerId = await createPeerId()
24+
const privateKey = await generateKeyPair('Ed25519')
25+
const peerId = peerIdFromPrivateKey(privateKey)
2426
gossipsub = new GossipSub(
2527
{
28+
privateKey,
2629
peerId,
2730
registrar: stubInterface<Registrar>(),
2831
peerStore: stubInterface<PeerStore>(),

test/gossip.spec.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
import { generateKeyPair } from '@libp2p/crypto/keys'
12
import { stop } from '@libp2p/interface'
23
import { mockNetwork } from '@libp2p/interface-compliance-tests/mocks'
34
import { defaultLogger } from '@libp2p/logger'
4-
import { createEd25519PeerId } from '@libp2p/peer-id-factory'
5+
import { peerIdFromPrivateKey } from '@libp2p/peer-id'
56
import { expect } from 'aegir/chai'
67
import { pEvent } from 'p-event'
78
import sinon, { type SinonStubbedInstance } from 'sinon'
@@ -273,10 +274,12 @@ describe('gossip', () => {
273274
const maxOutboundStreams = 5
274275

275276
const registrar = stubInterface<Registrar>()
276-
277+
const privateKey = await generateKeyPair('Ed25519')
278+
const peerId = peerIdFromPrivateKey(privateKey)
277279
const pubsub = new GossipSub(
278280
{
279-
peerId: await createEd25519PeerId(),
281+
privateKey,
282+
peerId,
280283
registrar,
281284
peerStore: stubInterface<PeerStore>(),
282285
connectionManager: stubInterface<ConnectionManager>(),

0 commit comments

Comments
 (0)