Skip to content

Commit 126411b

Browse files
authored
feat: add transports example (#178)
Restores original transports example
1 parent 635a1f6 commit 126411b

File tree

19 files changed

+827
-0
lines changed

19 files changed

+827
-0
lines changed

.github/workflows/ci.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ jobs:
3131
- js-libp2p-example-pnet
3232
- js-libp2p-example-protocol-and-stream-muxing
3333
- js-libp2p-example-pubsub
34+
- js-libp2p-example-transports
3435
- js-libp2p-example-webrtc-private-to-private
3536
defaults:
3637
run:
@@ -90,6 +91,7 @@ jobs:
9091
- js-libp2p-example-pnet
9192
- js-libp2p-example-protocol-and-stream-muxing
9293
- js-libp2p-example-pubsub
94+
- js-libp2p-example-transports
9395
- js-libp2p-example-webrtc-private-to-private
9496
steps:
9597
- 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: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/* eslint-disable no-console */
2+
3+
import { noise } from '@chainsafe/libp2p-noise'
4+
import { tcp } from '@libp2p/tcp'
5+
import { createLibp2p } from 'libp2p'
6+
7+
const createNode = async () => {
8+
const node = await createLibp2p({
9+
addresses: {
10+
// To signal the addresses we want to be available, we use
11+
// the multiaddr format, a self describable address
12+
listen: [
13+
'/ip4/0.0.0.0/tcp/0'
14+
]
15+
},
16+
transports: [
17+
tcp()
18+
],
19+
connectionEncrypters: [
20+
noise()
21+
]
22+
})
23+
24+
return node
25+
}
26+
27+
const node = await createNode()
28+
29+
console.log('node has started')
30+
console.log('listening on:')
31+
node.getMultiaddrs().forEach((ma) => console.log(ma.toString()))
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/* eslint-disable no-console */
2+
3+
import { noise } from '@chainsafe/libp2p-noise'
4+
import { yamux } from '@chainsafe/libp2p-yamux'
5+
import { tcp } from '@libp2p/tcp'
6+
import { pipe } from 'it-pipe'
7+
import toBuffer from 'it-to-buffer'
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+
// To signal the addresses we want to be available, we use
16+
// the multiaddr format, a self describable address
17+
listen: ['/ip4/0.0.0.0/tcp/0']
18+
},
19+
transports: [tcp()],
20+
connectionEncrypters: [noise()],
21+
streamMuxers: [yamux()]
22+
})
23+
24+
return node
25+
}
26+
27+
function printAddrs (node, number) {
28+
console.log('node %s is listening on:', number)
29+
node.getMultiaddrs().forEach((ma) => console.log(ma.toString()))
30+
}
31+
32+
const [node1, node2] = await Promise.all([
33+
createNode(),
34+
createNode()
35+
])
36+
37+
printAddrs(node1, '1')
38+
printAddrs(node2, '2')
39+
40+
node2.handle('/print', async ({ stream }) => {
41+
const result = await pipe(
42+
stream,
43+
async function * (source) {
44+
for await (const list of source) {
45+
yield list.subarray()
46+
}
47+
},
48+
toBuffer
49+
)
50+
console.log(uint8ArrayToString(result))
51+
})
52+
53+
await node1.peerStore.patch(node2.peerId, {
54+
multiaddrs: node2.getMultiaddrs()
55+
})
56+
const stream = await node1.dialProtocol(node2.peerId, '/print')
57+
58+
await pipe(
59+
['Hello', ' ', 'p2p', ' ', 'world', '!'].map(str => uint8ArrayFromString(str)),
60+
stream
61+
)
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/* eslint-disable no-console */
2+
3+
import { noise } from '@chainsafe/libp2p-noise'
4+
import { yamux } from '@chainsafe/libp2p-yamux'
5+
import { tcp } from '@libp2p/tcp'
6+
import { webSockets } from '@libp2p/websockets'
7+
import { pipe } from 'it-pipe'
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 (transports, addresses = []) => {
13+
if (!Array.isArray(addresses)) {
14+
addresses = [addresses]
15+
}
16+
17+
const node = await createLibp2p({
18+
addresses: {
19+
listen: addresses
20+
},
21+
transports,
22+
connectionEncrypters: [noise()],
23+
streamMuxers: [yamux()]
24+
})
25+
26+
return node
27+
}
28+
29+
function printAddrs (node, number) {
30+
console.log('node %s is listening on:', number)
31+
node.getMultiaddrs().forEach((ma) => console.log(ma.toString()))
32+
}
33+
34+
function print ({ stream }) {
35+
pipe(
36+
stream,
37+
async function (source) {
38+
for await (const msg of source) {
39+
console.log(uint8ArrayToString(msg.subarray()))
40+
}
41+
}
42+
)
43+
}
44+
45+
const [node1, node2, node3] = await Promise.all([
46+
createNode([tcp()], '/ip4/0.0.0.0/tcp/0'),
47+
createNode([tcp(), webSockets()], ['/ip4/0.0.0.0/tcp/0', '/ip4/127.0.0.1/tcp/10000/ws']),
48+
createNode([webSockets()], '/ip4/127.0.0.1/tcp/20000/ws')
49+
])
50+
51+
printAddrs(node1, '1')
52+
printAddrs(node2, '2')
53+
printAddrs(node3, '3')
54+
55+
node1.handle('/print', print)
56+
node2.handle('/print', print)
57+
node3.handle('/print', print)
58+
59+
await node1.peerStore.patch(node2.peerId, {
60+
multiaddrs: node2.getMultiaddrs()
61+
})
62+
await node2.peerStore.patch(node3.peerId, {
63+
multiaddrs: node3.getMultiaddrs()
64+
})
65+
await node3.peerStore.patch(node1.peerId, {
66+
multiaddrs: node1.getMultiaddrs()
67+
})
68+
69+
// node 1 (TCP) dials to node 2 (TCP+WebSockets)
70+
const stream = await node1.dialProtocol(node2.peerId, '/print')
71+
await pipe(
72+
[uint8ArrayFromString('node 1 dialed to node 2 successfully')],
73+
stream
74+
)
75+
76+
// node 2 (TCP+WebSockets) dials to node 3 (WebSockets)
77+
const stream2 = await node2.dialProtocol(node3.peerId, '/print')
78+
await pipe(
79+
[uint8ArrayFromString('node 2 dialed to node 3 successfully')],
80+
stream2
81+
)
82+
83+
// node 3 (listening WebSockets) can dial node 1 (TCP)
84+
try {
85+
await node3.dialProtocol(node1.peerId, '/print')
86+
} catch (err) {
87+
console.log('node 3 failed to dial to node 1 with:', err.message)
88+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/* eslint-disable no-console */
2+
3+
import fs from 'fs'
4+
import https from 'https'
5+
import { noise } from '@chainsafe/libp2p-noise'
6+
import { yamux } from '@chainsafe/libp2p-yamux'
7+
import { tcp } from '@libp2p/tcp'
8+
import { webSockets } from '@libp2p/websockets'
9+
import { pipe } from 'it-pipe'
10+
import { createLibp2p } from 'libp2p'
11+
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
12+
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
13+
14+
const httpServer = https.createServer({
15+
cert: fs.readFileSync('./test_certs/cert.pem'),
16+
key: fs.readFileSync('./test_certs/key.pem')
17+
})
18+
19+
const createNode = async (addresses = []) => {
20+
if (!Array.isArray(addresses)) {
21+
addresses = [addresses]
22+
}
23+
24+
const node = await createLibp2p({
25+
addresses: {
26+
listen: addresses
27+
},
28+
transports: [
29+
tcp(),
30+
webSockets({
31+
server: httpServer,
32+
websocket: {
33+
rejectUnauthorized: false
34+
}
35+
})
36+
],
37+
connectionEncrypters: [noise()],
38+
streamMuxers: [yamux()]
39+
})
40+
41+
return node
42+
}
43+
44+
function printAddrs (node, number) {
45+
console.log('node %s is listening on:', number)
46+
node.getMultiaddrs().forEach((ma) => console.log(ma.toString()))
47+
}
48+
49+
function print ({ stream }) {
50+
pipe(
51+
stream,
52+
async function (source) {
53+
for await (const msg of source) {
54+
console.log(uint8ArrayToString(msg.subarray()))
55+
}
56+
}
57+
)
58+
}
59+
60+
const [node1, node2] = await Promise.all([
61+
createNode('/ip4/127.0.0.1/tcp/10000/wss'),
62+
createNode([])
63+
])
64+
65+
printAddrs(node1, '1')
66+
printAddrs(node2, '2')
67+
68+
node1.handle('/print', print)
69+
node2.handle('/print', print)
70+
71+
const targetAddr = node1.getMultiaddrs()[0]
72+
73+
// node 2 (Secure WebSockets) dials to node 1 (Secure Websockets)
74+
const stream = await node2.dialProtocol(targetAddr, '/print')
75+
await pipe(
76+
[uint8ArrayFromString('node 2 dialed to node 1 successfully')],
77+
stream
78+
)
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)