Skip to content

Commit b6048d0

Browse files
dozyiotabcat
andauthored
docs: use libp2p/gossipsub (#346)
--------- Co-authored-by: tabcat <tabcat00@proton.me>
1 parent d40e34d commit b6048d0

7 files changed

Lines changed: 91 additions & 40 deletions

File tree

‎examples/js-libp2p-example-browser-pubsub/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
This example leverages the [vite bundler](https://vitejs.dev/) to compile and serve the libp2p code in the browser. You can use other bundlers such as Webpack, but we will not be covering them here.
1111

1212
> [!TIP]
13-
> This example uses `@libp2p/floodsub` as a pubsub implementation - it is not suitable for production use, instead use `@chainsafe/libp2p-gossipsub`
13+
> This example uses `@libp2p/floodsub` as a pubsub implementation - it is not suitable for production use, instead use `@libp2p/gossipsub`
1414
1515
## Table of contents <!-- omit in toc -->
1616

‎examples/js-libp2p-example-discovery-mechanisms/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ Pub/sub based peer discovery is useful for deployments where other mechanisms ma
128128
You can find the complete solution at [3-pubsub.js](./3-pubsub.js).
129129

130130
> [!TIP]
131-
> The pubsub example uses `@libp2p/floodsub` - it is not suitable for production use, instead use `@chainsafe/libp2p-gossipsub`
131+
> The pubsub example uses `@libp2p/floodsub` - it is not suitable for production use, instead use `@libp2p/gossipsub`
132132
133133
In the example we create three nodes. The first is used to bootstrap the network. The second and third dial the bootstrapper, then discover each other via the pub/sub peer discovery topic.
134134

‎examples/js-libp2p-example-pubsub/1.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { noise } from '@chainsafe/libp2p-noise'
44
import { yamux } from '@chainsafe/libp2p-yamux'
5-
import { floodsub } from '@libp2p/floodsub'
5+
import { gossipsub } from '@libp2p/gossipsub'
66
import { identify, identifyPush } from '@libp2p/identify'
77
import { tcp } from '@libp2p/tcp'
88
import { createLibp2p } from 'libp2p'
@@ -18,7 +18,7 @@ const createNode = async () => {
1818
streamMuxers: [yamux()],
1919
connectionEncrypters: [noise()],
2020
services: {
21-
pubsub: floodsub(),
21+
pubsub: gossipsub(),
2222
identify: identify(),
2323
identifyPush: identifyPush()
2424
}

‎examples/js-libp2p-example-pubsub/2.js‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { noise } from '@chainsafe/libp2p-noise'
44
import { yamux } from '@chainsafe/libp2p-yamux'
5-
import { floodsub } from '@libp2p/floodsub'
5+
import { gossipsub, TopicValidatorResult } from '@libp2p/gossipsub'
66
import { identify, identifyPush } from '@libp2p/identify'
77
import { tcp } from '@libp2p/tcp'
88
import { createLibp2p } from 'libp2p'
@@ -18,7 +18,7 @@ const createNode = async () => {
1818
streamMuxers: [yamux()],
1919
connectionEncrypters: [noise()],
2020
services: {
21-
pubsub: floodsub(),
21+
pubsub: gossipsub(),
2222
identify: identify(),
2323
identifyPush: identifyPush()
2424
}
@@ -76,18 +76,25 @@ const validateFruit = (msgTopic, msg) => {
7676
const fruit = uint8ArrayToString(msg.data)
7777
const validFruit = ['banana', 'apple', 'orange']
7878

79-
return validFruit.includes(fruit) ? 'accept' : 'ignore'
79+
return validFruit.includes(fruit)
80+
? TopicValidatorResult.Accept
81+
: TopicValidatorResult.Ignore
8082
}
8183

8284
// validate fruit
8385
node1.services.pubsub.topicValidators.set(topic, validateFruit)
8486
node2.services.pubsub.topicValidators.set(topic, validateFruit)
8587
node3.services.pubsub.topicValidators.set(topic, validateFruit)
8688

87-
// node1 publishes "fruits"
89+
// node1 publishes "fruits", waiting for each to reach node3 before sending the
90+
// next so we can watch it propagate. 'car' fails validation and is never
91+
// re-shared, so waitForMessage gives up on it after a short timeout.
8892
for (const fruit of ['banana', 'apple', 'car', 'orange']) {
8993
console.log('############## fruit ' + fruit + ' ##############')
94+
95+
const received = waitForMessage(node3, topic, fruit)
9096
await node1.services.pubsub.publish(topic, uint8ArrayFromString(fruit))
97+
await received
9198
}
9299

93100
console.log('############## all messages sent ##############')
@@ -98,6 +105,28 @@ async function delay (ms) {
98105
})
99106
}
100107

108+
// Wait for `node` to receive `data` on `topic`. Fruit that fails validation is
109+
// never re-shared, so give up after `timeout` ms.
110+
async function waitForMessage (node, topic, data, timeout = 100) {
111+
await new Promise((resolve) => {
112+
const timer = setTimeout(done, timeout)
113+
114+
function done () {
115+
clearTimeout(timer)
116+
node.services.pubsub.removeEventListener('message', onMessage)
117+
resolve()
118+
}
119+
120+
function onMessage (evt) {
121+
if (evt.detail.topic === topic && uint8ArrayToString(evt.detail.data) === data) {
122+
done()
123+
}
124+
}
125+
126+
node.services.pubsub.addEventListener('message', onMessage)
127+
})
128+
}
129+
101130
// Wait for node1 to see that node2 has subscribed to the topic
102131
async function hasSubscription (node1, node2, topic) {
103132
while (true) {

‎examples/js-libp2p-example-pubsub/README.md‎

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,6 @@ We've seen many interesting use cases appear with this, here are some highlights
1313
- [IPFS PubSub (using libp2p-floodsub) for IoT](https://www.youtube.com/watch?v=qLpM5pBDGiE).
1414
- [Real Time distributed Applications](https://www.youtube.com/watch?v=vQrbxyDPSXg)
1515

16-
> [!TIP]
17-
> This example uses `@libp2p/floodsub` as a pubsub implementation - it is not suitable for production use, instead use `@chainsafe/libp2p-gossipsub`
18-
1916
## 0. Set up the example
2017

2118
Clone this repo and run `npm install` in the root.
@@ -34,7 +31,7 @@ choice and you are ready to go. No need for extra configuration.
3431
First, let's update our libp2p configuration with a PubSub implementation.
3532

3633
```JavaScript
37-
import { GossipSub } from '@chainsafe/libp2p-gossipsub'
34+
import { gossipsub } from '@libp2p/gossipsub'
3835
import { noise } from '@chainsafe/libp2p-noise'
3936
import { yamux } from '@chainsafe/libp2p-yamux'
4037
import { tcp } from '@libp2p/tcp'
@@ -98,9 +95,8 @@ The output of the program should look like:
9895

9996
```console
10097
> node 1.js
101-
connected to QmWpvkKm6qHLhoxpWrTswY6UMNWDyn8hN265Qp9ZYvgS82
102-
node1 received: Bird bird bird, bird is the word!
103-
node1 received: Bird bird bird, bird is the word!
98+
node1 received: Bird bird bird, bird is the word! on topic news
99+
node1 received: Bird bird bird, bird is the word! on topic news
104100
```
105101

106102
You can change the pubsub `emitSelf` option if you want the publishing node to receive its own messages.
@@ -113,11 +109,10 @@ The output of the program should look like:
113109

114110
```console
115111
> node 1.js
116-
connected to QmWpvkKm6qHLhoxpWrTswY6UMNWDyn8hN265Qp9ZYvgS82
117-
node1 received: Bird bird bird, bird is the word!
118-
node2 received: Bird bird bird, bird is the word!
119-
node1 received: Bird bird bird, bird is the word!
120-
node2 received: Bird bird bird, bird is the word!
112+
node2 received: Bird bird bird, bird is the word! on topic news
113+
node1 received: Bird bird bird, bird is the word! on topic news
114+
node2 received: Bird bird bird, bird is the word! on topic news
115+
node1 received: Bird bird bird, bird is the word! on topic news
121116
```
122117

123118
## 2. Filter Messages
@@ -127,17 +122,16 @@ filter to Gossipsub. Messages that fail validation in the filter will not be
127122
re-shared.
128123

129124
```JavaScript
130-
import { TopicValidatorResult } from '@libp2p/interface/pubsub'
125+
import { TopicValidatorResult } from '@libp2p/gossipsub'
131126

132127
const validateFruit = (msgTopic, msg) => {
133128
const fruit = uint8ArrayToString(msg.data)
134129
const validFruit = ['banana', 'apple', 'orange']
135130

136-
// car is not a fruit !
137-
if (!validFruit.includes(fruit)) {
138-
throw new Error('no valid fruit received')
139-
}
140-
return TopicValidatorResult.Accept
131+
// car is not a fruit, so it is ignored and not re-shared
132+
return validFruit.includes(fruit)
133+
? TopicValidatorResult.Accept
134+
: TopicValidatorResult.Ignore
141135
}
142136

143137
node1.services.pubsub.topicValidators.set(topic, validateFruit)
@@ -148,16 +142,44 @@ node3.services.pubsub.topicValidators.set(topic, validateFruit)
148142
In this example, node one has an outdated version of the system, or is a malicious node. When it tries to publish fruit, the messages are re-shared and all the nodes share the message. However, when it tries to publish a vehicle the message is not re-shared.
149143

150144
```JavaScript
145+
// Wait for `node` to receive `data` on `topic`. Fruit that fails validation is
146+
// never re-shared, so give up after `timeout` ms.
147+
async function waitForMessage (node, topic, data, timeout = 100) {
148+
await new Promise((resolve) => {
149+
const timer = setTimeout(done, timeout)
150+
151+
function done () {
152+
clearTimeout(timer)
153+
node.services.pubsub.removeEventListener('message', onMessage)
154+
resolve()
155+
}
156+
157+
function onMessage (evt) {
158+
if (evt.detail.topic === topic && uint8ArrayToString(evt.detail.data) === data) {
159+
done()
160+
}
161+
}
162+
163+
node.services.pubsub.addEventListener('message', onMessage)
164+
})
165+
}
166+
167+
// node1 publishes "fruits", waiting for each to reach node3 before sending the
168+
// next so we can watch it propagate. 'car' fails validation and is never
169+
// re-shared, so waitForMessage gives up on it after a short timeout.
151170
for (const fruit of ['banana', 'apple', 'car', 'orange']) {
152171
console.log('############## fruit ' + fruit + ' ##############')
172+
173+
const received = waitForMessage(node3, topic, fruit)
153174
await node1.services.pubsub.publish(topic, uint8ArrayFromString(fruit))
175+
await received
154176
}
155177
```
156178

157179
Result
158180

159181
```
160-
> node 1.js
182+
> node 2.js
161183
############## fruit banana ##############
162184
node2 received: banana
163185
node3 received: banana
@@ -166,9 +188,9 @@ node2 received: apple
166188
node3 received: apple
167189
############## fruit car ##############
168190
############## fruit orange ##############
169-
node1 received: orange
170191
node2 received: orange
171192
node3 received: orange
193+
############## all messages sent ##############
172194
```
173195

174196
You can find the complete version at [2.js](./2.js).

‎examples/js-libp2p-example-pubsub/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
"dependencies": {
3131
"@chainsafe/libp2p-noise": "^17.0.0",
3232
"@chainsafe/libp2p-yamux": "^8.0.0",
33-
"@libp2p/floodsub": "^11.0.1",
33+
"@libp2p/gossipsub": "^15.0.23",
3434
"@libp2p/identify": "^4.0.1",
3535
"@libp2p/tcp": "^11.0.1",
3636
"libp2p": "^3.0.2",
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
import path from 'path'
22
import { fileURLToPath } from 'url'
3-
import { waitForOutput } from 'test-ipfs-example/node'
3+
import { matchOutput } from 'test-ipfs-example/node'
44

55
const __dirname = path.dirname(fileURLToPath(import.meta.url))
66

77
export async function test () {
88
process.stdout.write('2.js\n')
99

10-
try {
11-
await waitForOutput('node3 received: car', 'node', [path.join(__dirname, '../2.js')], {
12-
cwd: __dirname,
13-
timeout: 2000
14-
})
10+
// run until node3 receives the last valid fruit - this fails if a valid fruit
11+
// never propagates node1 -> node2 -> node3
12+
const { process: proc, matches } = await matchOutput(/node3 received: orange/, 'node', [path.join(__dirname, '../2.js')], {
13+
cwd: __dirname
14+
})
15+
proc.kill()
1516

16-
throw new Error('Matched content when should not have')
17-
} catch (err) {
18-
if (err.message !== 'Timed out' && !err.message.includes('Did not see')) {
19-
throw err
20-
}
17+
// 'car' fails validation, so node2 never re-shares it - it must be absent
18+
// from everything printed up to the final valid message
19+
if (matches.input.includes('node3 received: car')) {
20+
throw new Error("node3 should not have received 'car'")
2121
}
2222
}

0 commit comments

Comments
 (0)