Skip to content

Commit 635a1f6

Browse files
authored
feat: add pubsub example (#177)
Restores original pubsub example
1 parent 4ecc1db commit 635a1f6

File tree

13 files changed

+500
-0
lines changed

13 files changed

+500
-0
lines changed

.github/workflows/ci.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ jobs:
3030
- js-libp2p-example-peer-and-content-routing
3131
- js-libp2p-example-pnet
3232
- js-libp2p-example-protocol-and-stream-muxing
33+
- js-libp2p-example-pubsub
3334
- js-libp2p-example-webrtc-private-to-private
3435
defaults:
3536
run:
@@ -88,6 +89,7 @@ jobs:
8889
- js-libp2p-example-peer-and-content-routing
8990
- js-libp2p-example-pnet
9091
- js-libp2p-example-protocol-and-stream-muxing
92+
- js-libp2p-example-pubsub
9193
- js-libp2p-example-webrtc-private-to-private
9294
steps:
9395
- uses: convictional/trigger-workflow-and-wait@f69fa9eedd3c62a599220f4d5745230e237904be
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# ⚠️ IMPORTANT ⚠️
2+
3+
# Please do not create a Pull Request for this repository
4+
5+
The contents of this repository are automatically synced from the parent [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples) so any changes made to the standalone repository will be lost after the next sync.
6+
7+
Please open a PR against [js-libp2p Examples](https://github.com/libp2p/js-libp2p-examples) instead.
8+
9+
## Contributing
10+
11+
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
12+
13+
1. Fork the [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples)
14+
2. Create your Feature Branch (`git checkout -b feature/amazing-example`)
15+
3. Commit your Changes (`git commit -a -m 'feat: add some amazing example'`)
16+
4. Push to the Branch (`git push origin feature/amazing-example`)
17+
5. Open a Pull Request
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
name: pull
2+
3+
on:
4+
workflow_dispatch
5+
6+
jobs:
7+
sync:
8+
runs-on: ubuntu-latest
9+
steps:
10+
- uses: actions/checkout@v2
11+
- name: Pull from another repository
12+
uses: ipfs-examples/actions-pull-directory-from-repo@main
13+
with:
14+
source-repo: libp2p/js-libp2p-examples
15+
source-folder-path: examples/${{ github.event.repository.name }}
16+
source-branch: main
17+
target-branch: main
18+
git-username: github-actions
19+
git-email: [email protected]
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/* eslint-disable no-console */
2+
3+
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
4+
import { noise } from '@chainsafe/libp2p-noise'
5+
import { yamux } from '@chainsafe/libp2p-yamux'
6+
import { identify, identifyPush } from '@libp2p/identify'
7+
import { tcp } from '@libp2p/tcp'
8+
import { createLibp2p } from 'libp2p'
9+
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
10+
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
11+
12+
const createNode = async () => {
13+
const node = await createLibp2p({
14+
addresses: {
15+
listen: ['/ip4/0.0.0.0/tcp/0']
16+
},
17+
transports: [tcp()],
18+
streamMuxers: [yamux()],
19+
connectionEncrypters: [noise()],
20+
services: {
21+
pubsub: gossipsub(),
22+
identify: identify(),
23+
identifyPush: identifyPush()
24+
}
25+
})
26+
27+
return node
28+
}
29+
30+
const topic = 'news'
31+
32+
const [node1, node2] = await Promise.all([
33+
createNode(),
34+
createNode()
35+
])
36+
37+
// Connect the two nodes
38+
await node1.dial(node2.getMultiaddrs())
39+
40+
node1.services.pubsub.subscribe(topic)
41+
node1.services.pubsub.addEventListener('message', (evt) => {
42+
console.log(`node1 received: ${uint8ArrayToString(evt.detail.data)} on topic ${evt.detail.topic}`)
43+
})
44+
45+
// Will not receive own published messages by default
46+
node2.services.pubsub.subscribe(topic)
47+
node2.services.pubsub.addEventListener('message', (evt) => {
48+
console.log(`node2 received: ${uint8ArrayToString(evt.detail.data)} on topic ${evt.detail.topic}`)
49+
})
50+
51+
// node2 publishes "news" every second
52+
setInterval(() => {
53+
node2.services.pubsub.publish(topic, uint8ArrayFromString('Bird bird bird, bird is the word!')).catch(err => {
54+
console.error(err)
55+
})
56+
}, 1000)
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/* eslint-disable no-console */
2+
3+
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
4+
import { noise } from '@chainsafe/libp2p-noise'
5+
import { yamux } from '@chainsafe/libp2p-yamux'
6+
import { identify, identifyPush } from '@libp2p/identify'
7+
import { tcp } from '@libp2p/tcp'
8+
import { createLibp2p } from 'libp2p'
9+
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
10+
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
11+
12+
const createNode = async () => {
13+
const node = await createLibp2p({
14+
addresses: {
15+
listen: ['/ip4/0.0.0.0/tcp/0']
16+
},
17+
transports: [tcp()],
18+
streamMuxers: [yamux()],
19+
connectionEncrypters: [noise()],
20+
services: {
21+
pubsub: gossipsub(),
22+
identify: identify(),
23+
identifyPush: identifyPush()
24+
}
25+
})
26+
27+
return node
28+
}
29+
30+
const topic = 'fruit'
31+
32+
const [node1, node2, node3] = await Promise.all([
33+
createNode(),
34+
createNode(),
35+
createNode()
36+
])
37+
38+
// connect node1 to node2 and node2 to node3
39+
await node1.dial(node2.getMultiaddrs())
40+
await node2.dial(node3.getMultiaddrs())
41+
42+
// subscribe
43+
node1.services.pubsub.addEventListener('message', (evt) => {
44+
if (evt.detail.topic !== topic) {
45+
return
46+
}
47+
48+
// Will not receive own published messages by default
49+
console.log(`node1 received: ${uint8ArrayToString(evt.detail.data)}`)
50+
})
51+
node1.services.pubsub.subscribe(topic)
52+
53+
node2.services.pubsub.addEventListener('message', (evt) => {
54+
if (evt.detail.topic !== topic) {
55+
return
56+
}
57+
58+
console.log(`node2 received: ${uint8ArrayToString(evt.detail.data)}`)
59+
})
60+
node2.services.pubsub.subscribe(topic)
61+
62+
node3.services.pubsub.addEventListener('message', (evt) => {
63+
if (evt.detail.topic !== topic) {
64+
return
65+
}
66+
67+
console.log(`node3 received: ${uint8ArrayToString(evt.detail.data)}`)
68+
})
69+
node3.services.pubsub.subscribe(topic)
70+
71+
// wait for subscriptions to propagate
72+
await hasSubscription(node1, node2, topic)
73+
await hasSubscription(node2, node3, topic)
74+
75+
const validateFruit = (msgTopic, msg) => {
76+
const fruit = uint8ArrayToString(msg.data)
77+
const validFruit = ['banana', 'apple', 'orange']
78+
79+
return validFruit.includes(fruit) ? 'accept' : 'ignore'
80+
}
81+
82+
// validate fruit
83+
node1.services.pubsub.topicValidators.set(topic, validateFruit)
84+
node2.services.pubsub.topicValidators.set(topic, validateFruit)
85+
node3.services.pubsub.topicValidators.set(topic, validateFruit)
86+
87+
// node1 publishes "fruits"
88+
for (const fruit of ['banana', 'apple', 'car', 'orange']) {
89+
console.log('############## fruit ' + fruit + ' ##############')
90+
await node1.services.pubsub.publish(topic, uint8ArrayFromString(fruit))
91+
}
92+
93+
console.log('############## all messages sent ##############')
94+
95+
async function delay (ms) {
96+
await new Promise((resolve) => {
97+
setTimeout(() => resolve(), ms)
98+
})
99+
}
100+
101+
// Wait for node1 to see that node2 has subscribed to the topic
102+
async function hasSubscription (node1, node2, topic) {
103+
while (true) {
104+
const subs = await node1.services.pubsub.getSubscribers(topic)
105+
106+
if (subs.map(peer => peer.toString()).includes(node2.peerId.toString())) {
107+
return
108+
}
109+
110+
// wait for subscriptions to propagate
111+
await delay(100)
112+
}
113+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
This project is dual licensed under MIT and Apache-2.0.
2+
3+
MIT: https://www.opensource.org/licenses/mit
4+
Apache-2.0: https://www.apache.org/licenses/license-2.0
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
2+
3+
http://www.apache.org/licenses/LICENSE-2.0
4+
5+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
The MIT License (MIT)
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in
11+
all copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.

0 commit comments

Comments
 (0)