@libp2p/floodsub 10.1.46 → 11.0.0-049bfa0fa

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -32,138 +32,266 @@
32
32
  * ```
33
33
  */
34
34
 
35
- import { pubSubSymbol, serviceCapabilities, serviceDependencies } from '@libp2p/interface'
36
- import { PubSubBaseProtocol } from '@libp2p/pubsub'
37
- import { toString } from 'uint8arrays/to-string'
38
- import { SimpleTimeCache } from './cache.js'
39
- import { multicodec } from './config.js'
40
- import { RPC } from './message/rpc.js'
41
- import type { PeerId, PubSubInit, Message, PubSubRPC, PubSubRPCMessage, PublishResult, PubSub } from '@libp2p/interface'
42
- import type { PubSubComponents } from '@libp2p/pubsub'
43
- import type { Uint8ArrayList } from 'uint8arraylist'
44
-
45
- export { multicodec }
46
-
47
- export interface FloodSubInit extends PubSubInit {
48
- seenTTL?: number
49
- }
35
+ import { pubSubSymbol } from './constants.ts'
36
+ import { FloodSub as FloodSubClass } from './floodsub.js'
37
+ import type { ComponentLogger, PeerId, PrivateKey, PublicKey, TypedEventTarget } from '@libp2p/interface'
38
+ import type { Registrar } from '@libp2p/interface-internal'
50
39
 
51
- export interface FloodSubComponents extends PubSubComponents {
40
+ export const protocol = '/floodsub/1.0.0'
52
41
 
53
- }
42
+ /**
43
+ * On the producing side:
44
+ * - Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.
45
+ *
46
+ * On the consuming side:
47
+ * - Enforce the fields to be present, reject otherwise.
48
+ * - Propagate only if the fields are valid and signature can be verified, reject otherwise.
49
+ */
50
+ export const StrictSign = 'StrictSign'
54
51
 
55
52
  /**
56
- * FloodSub (aka dumbsub is an implementation of pubsub focused on
57
- * delivering an API for Publish/Subscribe, but with no CastTree Forming
58
- * (it just floods the network).
53
+ * On the producing side:
54
+ * - Build messages without the signature, key, from and seqno fields.
55
+ * - The corresponding protobuf key-value pairs are absent from the marshaled message, not just empty.
56
+ *
57
+ * On the consuming side:
58
+ * - Enforce the fields to be absent, reject otherwise.
59
+ * - Propagate only if the fields are absent, reject otherwise.
60
+ * - A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.
59
61
  */
60
- class FloodSub extends PubSubBaseProtocol {
61
- public seenCache: SimpleTimeCache<boolean>
62
+ export const StrictNoSign = 'StrictNoSign'
62
63
 
63
- constructor (components: FloodSubComponents, init?: FloodSubInit) {
64
- super(components, {
65
- ...init,
66
- canRelayMessage: true,
67
- multicodecs: [multicodec]
68
- })
64
+ export type SignaturePolicy = typeof StrictSign | typeof StrictNoSign
69
65
 
70
- this.log = components.logger.forComponent('libp2p:floodsub')
66
+ export interface SignedMessage {
67
+ type: 'signed'
68
+ from: PeerId
69
+ topic: string
70
+ data: Uint8Array
71
+ sequenceNumber: bigint
72
+ signature: Uint8Array
73
+ key: PublicKey
74
+ }
71
75
 
72
- /**
73
- * Cache of seen messages
74
- *
75
- * @type {TimeCache}
76
- */
77
- this.seenCache = new SimpleTimeCache<boolean>({
78
- validityMs: init?.seenTTL ?? 30000
79
- })
80
- }
76
+ export interface UnsignedMessage {
77
+ type: 'unsigned'
78
+ topic: string
79
+ data: Uint8Array
80
+ }
81
81
 
82
- readonly [pubSubSymbol] = true
82
+ export type Message = SignedMessage | UnsignedMessage
83
83
 
84
- readonly [Symbol.toStringTag] = '@libp2p/floodsub'
84
+ export interface Subscription {
85
+ topic: string
86
+ subscribe: boolean
87
+ }
85
88
 
86
- readonly [serviceCapabilities]: string[] = [
87
- '@libp2p/pubsub'
88
- ]
89
+ export interface SubscriptionChangeData {
90
+ peerId: PeerId
91
+ subscriptions: Subscription[]
92
+ }
89
93
 
90
- readonly [serviceDependencies]: string[] = [
91
- '@libp2p/identify'
92
- ]
94
+ export interface FloodSubEvents {
95
+ 'subscription-change': CustomEvent<SubscriptionChangeData>
96
+ message: CustomEvent<Message>
97
+ }
93
98
 
99
+ export interface PublishResult {
100
+ recipients: PeerId[]
101
+ }
102
+
103
+ export enum TopicValidatorResult {
104
+ /**
105
+ * The message is considered valid, and it should be delivered and forwarded to the network
106
+ */
107
+ Accept = 'accept',
108
+ /**
109
+ * The message is neither delivered nor forwarded to the network
110
+ */
111
+ Ignore = 'ignore',
94
112
  /**
95
- * Decode a Uint8Array into an RPC object
113
+ * The message is considered invalid, and it should be rejected
96
114
  */
97
- decodeRpc (bytes: Uint8Array | Uint8ArrayList): PubSubRPC {
98
- return RPC.decode(bytes)
99
- }
115
+ Reject = 'reject'
116
+ }
117
+
118
+ export interface TopicValidatorFn {
119
+ (peer: PeerId, message: Message): TopicValidatorResult | Promise<TopicValidatorResult>
120
+ }
121
+
122
+ export interface PeerStreamEvents {
123
+ 'stream:inbound': CustomEvent<never>
124
+ 'stream:outbound': CustomEvent<never>
125
+ close: CustomEvent<never>
126
+ }
100
127
 
128
+ export { pubSubSymbol }
129
+
130
+ /**
131
+ * Returns true if the passed argument is a PubSub implementation
132
+ */
133
+ export function isPubSub (obj?: any): obj is FloodSub {
134
+ return Boolean(obj?.[pubSubSymbol])
135
+ }
136
+
137
+ export interface FloodSub extends TypedEventTarget<FloodSubEvents> {
101
138
  /**
102
- * Encode an RPC object into a Uint8Array
139
+ * The global signature policy controls whether or not we sill send and receive
140
+ * signed or unsigned messages.
141
+ *
142
+ * Signed messages prevent spoofing message senders and should be preferred to
143
+ * using unsigned messages.
103
144
  */
104
- encodeRpc (rpc: PubSubRPC): Uint8Array {
105
- return RPC.encode(rpc)
106
- }
145
+ globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign
107
146
 
108
- decodeMessage (bytes: Uint8Array | Uint8ArrayList): PubSubRPCMessage {
109
- return RPC.Message.decode(bytes)
110
- }
147
+ /**
148
+ * A list of multicodecs that contain the pubsub protocol name.
149
+ */
150
+ protocols: string[]
111
151
 
112
- encodeMessage (rpc: PubSubRPCMessage): Uint8Array {
113
- return RPC.Message.encode(rpc)
114
- }
152
+ /**
153
+ * Pubsub routers support message validators per topic, which will validate the message
154
+ * before its propagations. They are stored in a map where keys are the topic name and
155
+ * values are the validators.
156
+ *
157
+ * @example
158
+ *
159
+ * ```TypeScript
160
+ * const topic = 'topic'
161
+ * const validateMessage = (msgTopic, msg) => {
162
+ * const input = uint8ArrayToString(msg.data)
163
+ * const validInputs = ['a', 'b', 'c']
164
+ *
165
+ * if (!validInputs.includes(input)) {
166
+ * throw new Error('no valid input received')
167
+ * }
168
+ * }
169
+ * libp2p.pubsub.topicValidators.set(topic, validateMessage)
170
+ * ```
171
+ */
172
+ topicValidators: Map<string, TopicValidatorFn>
173
+
174
+ getPeers(): PeerId[]
115
175
 
116
176
  /**
117
- * Process incoming message
118
- * Extends base implementation to check router cache.
177
+ * Gets a list of topics the node is subscribed to.
178
+ *
179
+ * ```TypeScript
180
+ * const topics = libp2p.pubsub.getTopics()
181
+ * ```
119
182
  */
120
- async processMessage (from: PeerId, message: Message): Promise<void> {
121
- // Check if I've seen the message, if yes, ignore
122
- const seqno = await super.getMsgId(message)
123
- const msgIdStr = toString(seqno, 'base64')
183
+ getTopics(): string[]
124
184
 
125
- if (this.seenCache.has(msgIdStr)) {
126
- return
127
- }
185
+ /**
186
+ * Subscribes to a pubsub topic.
187
+ *
188
+ * @example
189
+ *
190
+ * ```TypeScript
191
+ * const topic = 'topic'
192
+ * const handler = (msg) => {
193
+ * if (msg.topic === topic) {
194
+ * // msg.data - pubsub data received
195
+ * }
196
+ * }
197
+ *
198
+ * libp2p.pubsub.addEventListener('message', handler)
199
+ * libp2p.pubsub.subscribe(topic)
200
+ * ```
201
+ */
202
+ subscribe(topic: string): void
128
203
 
129
- this.seenCache.put(msgIdStr, true)
204
+ /**
205
+ * Unsubscribes from a pubsub topic.
206
+ *
207
+ * @example
208
+ *
209
+ * ```TypeScript
210
+ * const topic = 'topic'
211
+ * const handler = (msg) => {
212
+ * // msg.data - pubsub data received
213
+ * }
214
+ *
215
+ * libp2p.pubsub.removeEventListener(topic handler)
216
+ * libp2p.pubsub.unsubscribe(topic)
217
+ * ```
218
+ */
219
+ unsubscribe(topic: string): void
130
220
 
131
- await super.processMessage(from, message)
132
- }
221
+ /**
222
+ * Gets a list of the PeerIds that are subscribed to one topic.
223
+ *
224
+ * @example
225
+ *
226
+ * ```TypeScript
227
+ * const peerIds = libp2p.pubsub.getSubscribers(topic)
228
+ * ```
229
+ */
230
+ getSubscribers(topic: string): PeerId[]
133
231
 
134
232
  /**
135
- * Publish message created. Forward it to the peers.
233
+ * Publishes messages to the given topic.
234
+ *
235
+ * @example
236
+ *
237
+ * ```TypeScript
238
+ * const topic = 'topic'
239
+ * const data = uint8ArrayFromString('data')
240
+ *
241
+ * await libp2p.pubsub.publish(topic, data)
242
+ * ```
136
243
  */
137
- async publishMessage (from: PeerId, message: Message): Promise<PublishResult> {
138
- const peers = this.getSubscribers(message.topic)
139
- const recipients: PeerId[] = []
244
+ publish(topic: string, data?: Uint8Array): Promise<PublishResult>
245
+ }
140
246
 
141
- if (peers == null || peers.length === 0) {
142
- this.log('no peers are subscribed to topic %s', message.topic)
143
- return { recipients }
144
- }
247
+ export interface FloodSubComponents {
248
+ peerId: PeerId
249
+ privateKey: PrivateKey
250
+ registrar: Registrar
251
+ logger: ComponentLogger
252
+ }
145
253
 
146
- peers.forEach(id => {
147
- if (this.components.peerId.equals(id)) {
148
- this.log('not sending message on topic %s to myself', message.topic)
149
- return
150
- }
254
+ export interface FloodSubInit {
255
+ seenTTL?: number
151
256
 
152
- if (id.equals(from)) {
153
- this.log('not sending message on topic %s to sender %p', message.topic, id)
154
- return
155
- }
257
+ /**
258
+ * Override the protocol registered with the registrar
259
+ *
260
+ * @default ['/floodsub/1.0.0']
261
+ */
262
+ protocols?: string[]
156
263
 
157
- this.log('publish msgs on topics %s %p', message.topic, id)
264
+ /**
265
+ * defines how signatures should be handled
266
+ */
267
+ globalSignaturePolicy?: SignaturePolicy
268
+
269
+ /**
270
+ * if can relay messages not subscribed
271
+ */
272
+ canRelayMessage?: boolean
273
+
274
+ /**
275
+ * if publish should emit to self, if subscribed
276
+ */
277
+ emitSelf?: boolean
158
278
 
159
- recipients.push(id)
160
- this.send(id, { messages: [message] })
161
- })
279
+ /**
280
+ * handle this many incoming pubsub messages concurrently
281
+ */
282
+ messageProcessingConcurrency?: number
162
283
 
163
- return { recipients }
164
- }
284
+ /**
285
+ * How many parallel incoming streams to allow on the pubsub protocol per-connection
286
+ */
287
+ maxInboundStreams?: number
288
+
289
+ /**
290
+ * How many parallel outgoing streams to allow on the pubsub protocol per-connection
291
+ */
292
+ maxOutboundStreams?: number
165
293
  }
166
294
 
167
- export function floodsub (init: FloodSubInit = {}): (components: FloodSubComponents) => PubSub {
168
- return (components: FloodSubComponents) => new FloodSub(components, init)
295
+ export function floodsub (init: FloodSubInit = {}): (components: FloodSubComponents) => FloodSub {
296
+ return (components: FloodSubComponents) => new FloodSubClass(components, init)
169
297
  }
@@ -0,0 +1,200 @@
1
+ import { AbortError } from '@libp2p/interface'
2
+ import { pipe } from '@libp2p/utils'
3
+ import * as lp from 'it-length-prefixed'
4
+ import { pushable } from 'it-pushable'
5
+ import { TypedEventEmitter } from 'main-event'
6
+ import { pEvent } from 'p-event'
7
+ import { Uint8ArrayList } from 'uint8arraylist'
8
+ import type { PeerStreamEvents } from './index.ts'
9
+ import type { ComponentLogger, Logger, Stream, PeerId } from '@libp2p/interface'
10
+ import type { DecoderOptions as LpDecoderOptions } from 'it-length-prefixed'
11
+ import type { Pushable } from 'it-pushable'
12
+
13
+ export interface PeerStreamsInit {
14
+ id: PeerId
15
+ protocol: string
16
+ }
17
+
18
+ export interface PeerStreamsComponents {
19
+ logger: ComponentLogger
20
+ }
21
+
22
+ export interface DecoderOptions extends LpDecoderOptions {
23
+ // other custom options we might want for `attachInboundStream`
24
+ }
25
+
26
+ /**
27
+ * Thin wrapper around a peer's inbound / outbound pubsub streams
28
+ */
29
+ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
30
+ public readonly id: PeerId
31
+ public readonly protocol: string
32
+ /**
33
+ * Write stream - it's preferable to use the write method
34
+ */
35
+ public outboundStream?: Pushable<Uint8ArrayList>
36
+ /**
37
+ * Read stream
38
+ */
39
+ public inboundStream?: AsyncIterable<Uint8ArrayList>
40
+ /**
41
+ * The raw outbound stream, as retrieved from conn.newStream
42
+ */
43
+ private _rawOutboundStream?: Stream
44
+ /**
45
+ * The raw inbound stream, as retrieved from the callback from libp2p.handle
46
+ */
47
+ private _rawInboundStream?: Stream
48
+ /**
49
+ * An AbortController for controlled shutdown of the inbound stream
50
+ */
51
+ private readonly _inboundAbortController: AbortController
52
+ private closed: boolean
53
+ private readonly log: Logger
54
+
55
+ constructor (components: PeerStreamsComponents, init: PeerStreamsInit) {
56
+ super()
57
+
58
+ this.log = components.logger.forComponent('libp2p-pubsub:peer-streams')
59
+ this.id = init.id
60
+ this.protocol = init.protocol
61
+
62
+ this._inboundAbortController = new AbortController()
63
+ this.closed = false
64
+ }
65
+
66
+ /**
67
+ * Do we have a connection to read from?
68
+ */
69
+ get isReadable (): boolean {
70
+ return Boolean(this.inboundStream)
71
+ }
72
+
73
+ /**
74
+ * Do we have a connection to write on?
75
+ */
76
+ get isWritable (): boolean {
77
+ return Boolean(this.outboundStream)
78
+ }
79
+
80
+ /**
81
+ * Send a message to this peer.
82
+ * Throws if there is no `stream` to write to available.
83
+ */
84
+ write (data: Uint8Array | Uint8ArrayList): void {
85
+ if (this.outboundStream == null) {
86
+ const id = this.id.toString()
87
+ throw new Error('No writable connection to ' + id)
88
+ }
89
+
90
+ this.outboundStream.push(data instanceof Uint8Array ? new Uint8ArrayList(data) : data)
91
+ }
92
+
93
+ /**
94
+ * Attach a raw inbound stream and setup a read stream
95
+ */
96
+ attachInboundStream (stream: Stream, decoderOptions?: DecoderOptions): AsyncIterable<Uint8ArrayList> {
97
+ const abortListener = (): void => {
98
+ stream.abort(new AbortError())
99
+ }
100
+
101
+ this._inboundAbortController.signal.addEventListener('abort', abortListener, {
102
+ once: true
103
+ })
104
+
105
+ // Create and attach a new inbound stream
106
+ // The inbound stream is:
107
+ // - abortable, set to only return on abort, rather than throw
108
+ // - transformed with length-prefix transform
109
+ this._rawInboundStream = stream
110
+ this.inboundStream = pipe(
111
+ this._rawInboundStream,
112
+ (source) => lp.decode(source, decoderOptions)
113
+ )
114
+
115
+ this.dispatchEvent(new CustomEvent('stream:inbound'))
116
+ return this.inboundStream
117
+ }
118
+
119
+ /**
120
+ * Attach a raw outbound stream and setup a write stream
121
+ */
122
+ async attachOutboundStream (stream: Stream): Promise<Pushable<Uint8ArrayList>> {
123
+ // If an outbound stream already exists, gently close it
124
+ const _prevStream = this.outboundStream
125
+ if (this.outboundStream != null) {
126
+ // End the stream without emitting a close event
127
+ this.outboundStream.end()
128
+ }
129
+
130
+ this._rawOutboundStream = stream
131
+ this.outboundStream = pushable<Uint8ArrayList>({
132
+ onEnd: (shouldEmit) => {
133
+ // close writable side of the stream if it exists
134
+ this._rawOutboundStream?.close()
135
+ .catch(err => {
136
+ this.log('error closing outbound stream', err)
137
+ })
138
+
139
+ this._rawOutboundStream = undefined
140
+ this.outboundStream = undefined
141
+ if (shouldEmit != null) {
142
+ this.dispatchEvent(new CustomEvent('close'))
143
+ }
144
+ }
145
+ })
146
+
147
+ pipe(
148
+ this.outboundStream,
149
+ (source) => lp.encode(source),
150
+ async (source) => {
151
+ for await (const buf of source) {
152
+ const sendMore = stream.send(buf)
153
+
154
+ if (sendMore === false) {
155
+ await pEvent(stream, 'drain', {
156
+ rejectionEvents: [
157
+ 'close'
158
+ ]
159
+ })
160
+ }
161
+ }
162
+ }
163
+ ).catch((err: Error) => {
164
+ this.log.error(err)
165
+ })
166
+
167
+ // Only emit if the connection is new
168
+ if (_prevStream == null) {
169
+ this.dispatchEvent(new CustomEvent('stream:outbound'))
170
+ }
171
+
172
+ return this.outboundStream
173
+ }
174
+
175
+ /**
176
+ * Closes the open connection to peer
177
+ */
178
+ close (): void {
179
+ if (this.closed) {
180
+ return
181
+ }
182
+
183
+ this.closed = true
184
+
185
+ // End the outbound stream
186
+ if (this.outboundStream != null) {
187
+ this.outboundStream.end()
188
+ }
189
+ // End the inbound stream
190
+ if (this.inboundStream != null) {
191
+ this._inboundAbortController.abort()
192
+ }
193
+
194
+ this._rawOutboundStream = undefined
195
+ this.outboundStream = undefined
196
+ this._rawInboundStream = undefined
197
+ this.inboundStream = undefined
198
+ this.dispatchEvent(new CustomEvent('close'))
199
+ }
200
+ }
package/src/sign.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { peerIdFromPrivateKey } from '@libp2p/peer-id'
2
+ import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
3
+ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
4
+ import { toRpcMessage } from './utils.js'
5
+ import type { PubSubRPCMessage } from './floodsub.ts'
6
+ import type { SignedMessage } from './index.ts'
7
+ import type { PeerId, PrivateKey, PublicKey } from '@libp2p/interface'
8
+
9
+ export const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')
10
+
11
+ /**
12
+ * Signs the provided message with the given `peerId`
13
+ */
14
+ export async function signMessage (privateKey: PrivateKey, message: { from: PeerId, topic: string, data: Uint8Array, sequenceNumber: bigint }, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<SignedMessage> {
15
+ // @ts-expect-error signature field is missing, added below
16
+ const outputMessage: SignedMessage = {
17
+ type: 'signed',
18
+ topic: message.topic,
19
+ data: message.data,
20
+ sequenceNumber: message.sequenceNumber,
21
+ from: peerIdFromPrivateKey(privateKey)
22
+ }
23
+
24
+ // Get the message in bytes, and prepend with the pubsub prefix
25
+ const bytes = uint8ArrayConcat([
26
+ SignPrefix,
27
+ encode(toRpcMessage(outputMessage)).subarray()
28
+ ])
29
+
30
+ outputMessage.signature = await privateKey.sign(bytes)
31
+ outputMessage.key = privateKey.publicKey
32
+
33
+ return outputMessage
34
+ }
35
+
36
+ /**
37
+ * Verifies the signature of the given message
38
+ */
39
+ export async function verifySignature (message: SignedMessage, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<boolean> {
40
+ if (message.type !== 'signed') {
41
+ throw new Error('Message type must be "signed" to be verified')
42
+ }
43
+
44
+ if (message.signature == null) {
45
+ throw new Error('Message must contain a signature to be verified')
46
+ }
47
+
48
+ if (message.from == null) {
49
+ throw new Error('Message must contain a from property to be verified')
50
+ }
51
+
52
+ // Get message sans the signature
53
+ const bytes = uint8ArrayConcat([
54
+ SignPrefix,
55
+ encode({
56
+ ...toRpcMessage(message),
57
+ signature: undefined,
58
+ key: undefined
59
+ }).subarray()
60
+ ])
61
+
62
+ // Get the public key
63
+ const pubKey = messagePublicKey(message)
64
+
65
+ // verify the base message
66
+ return pubKey.verify(bytes, message.signature)
67
+ }
68
+
69
+ /**
70
+ * Returns the PublicKey associated with the given message.
71
+ * If no valid PublicKey can be retrieved an error will be returned.
72
+ */
73
+ export function messagePublicKey (message: SignedMessage): PublicKey {
74
+ if (message.type !== 'signed') {
75
+ throw new Error('Message type must be "signed" to have a public key')
76
+ }
77
+
78
+ // should be available in the from property of the message (peer id)
79
+ if (message.from == null) {
80
+ throw new Error('Could not get the public key from the originator id')
81
+ }
82
+
83
+ if (message.key != null) {
84
+ return message.key
85
+ }
86
+
87
+ if (message.from.publicKey != null) {
88
+ return message.from.publicKey
89
+ }
90
+
91
+ // We couldn't validate pubkey is from the originator, error
92
+ throw new Error('Could not get the public key from the originator id')
93
+ }