Skip to content

Commit 592ac08

Browse files
authored
feat: add custom protocols example (#93)
Adds an example of how to use libp2p to implement your own custom protocol
1 parent 6626094 commit 592ac08

File tree

13 files changed

+447
-4
lines changed

13 files changed

+447
-4
lines changed

.github/workflows/ci.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ jobs:
2424
- js-libp2p-example-chat
2525
- js-libp2p-example-circuit-relay
2626
- js-libp2p-example-connection-encryption
27+
- js-libp2p-example-custom-protocols
2728
- js-libp2p-example-delegated-routing
2829
- js-libp2p-example-discovery-mechanisms
2930
defaults:
@@ -77,6 +78,7 @@ jobs:
7778
- js-libp2p-example-chat
7879
- js-libp2p-example-circuit-relay
7980
- js-libp2p-example-connection-encryption
81+
- js-libp2p-example-custom-protocols
8082
- js-libp2p-example-delegated-routing
8183
- js-libp2p-example-discovery-mechanisms
8284
steps:

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,11 @@ Feel free to jump directly into the examples, however going through the followin
4848

4949
#### Understanding how libp2p works
5050

51-
- [Circuit Relay](./examples/js-libp2p-example-circuit-relay) - configuring Circuit Relay connections
52-
- [Connection Encryption](./examples/js-libp2p-example-connection-encryption) - how to encrypt connection between libp2p nodes
53-
- [Delegated routing](./examples/js-libp2p-example-delegated-routing) - how to offload network operations and queries onto more capable nodes
54-
- [Discovery mechanisms](./examples/js-libp2p-example-discovery-mechanisms) - how libp2p discovers other peers on the network
51+
- [Circuit Relay](https://github.com/libp2p/js-libp2p-example-circuit-relay) - configuring Circuit Relay connections
52+
- [Connection Encryption](https://github.com/libp2p/js-libp2p-example-connection-encryption) - how to encrypt connection between libp2p nodes
53+
- [Delegated routing](https://github.com/libp2p/js-libp2p-example-delegated-routing) - how to offload network operations and queries onto more capable nodes
54+
- [Discovery mechanisms](https://github.com/libp2p/js-libp2p-example-discovery-mechanisms) - how libp2p discovers other peers on the network
55+
- [Custom protocols](https://github.com/libp2p/js-libp2p-example-custom-protocols) - how to create a custom protocol for your application
5556

5657
#### Other examples
5758

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: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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 { createLibp2p } from 'libp2p'
8+
9+
async function createNode () {
10+
return await createLibp2p({
11+
addresses: {
12+
listen: [
13+
'/ip4/0.0.0.0/tcp/0'
14+
]
15+
},
16+
connectionEncryption: [
17+
noise()
18+
],
19+
streamMuxers: [
20+
yamux()
21+
],
22+
transports: [
23+
tcp()
24+
]
25+
})
26+
}
27+
28+
// create two nodes
29+
const remote = await createNode()
30+
const local = await createNode()
31+
32+
// this is our protocol id
33+
const ECHO_PROTOCOL = '/echo/1.0.0'
34+
35+
// the remote will handle incoming streams opened on the protocol
36+
await remote.handle(ECHO_PROTOCOL, ({ stream }) => {
37+
// pipe the stream output back to the stream input
38+
pipe(stream, stream)
39+
})
40+
41+
// the local will dial the remote on the protocol stream
42+
const stream = await local.dialProtocol(remote.getMultiaddrs(), ECHO_PROTOCOL)
43+
44+
// now it will write some data and read it back
45+
const output = await pipe(
46+
async function * () {
47+
// the stream input must be bytes
48+
yield new TextEncoder().encode('hello world')
49+
},
50+
stream,
51+
async (source) => {
52+
let string = ''
53+
const decoder = new TextDecoder()
54+
55+
for await (const buf of source) {
56+
// buf is a `Uint8ArrayList` so we must turn it into a `Uint8Array`
57+
// before decoding it
58+
string += decoder.decode(buf.subarray())
59+
}
60+
61+
return string
62+
}
63+
)
64+
65+
console.info(`Echoed back to us: "${output}"`)
66+
67+
await remote.stop()
68+
await local.stop()
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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 { lpStream } from 'it-length-prefixed-stream'
7+
import { createLibp2p } from 'libp2p'
8+
9+
async function createNode () {
10+
return await createLibp2p({
11+
addresses: {
12+
listen: [
13+
'/ip4/0.0.0.0/tcp/0'
14+
]
15+
},
16+
connectionEncryption: [
17+
noise()
18+
],
19+
streamMuxers: [
20+
yamux()
21+
],
22+
transports: [
23+
tcp()
24+
]
25+
})
26+
}
27+
28+
// create two nodes
29+
const remote = await createNode()
30+
const local = await createNode()
31+
32+
// this is our protocol id
33+
const REQ_RESP_PROTOCOL = '/request-response/1.0.0'
34+
35+
// the remote will handle incoming streams opened on the protocol
36+
await remote.handle(REQ_RESP_PROTOCOL, ({ stream }) => {
37+
Promise.resolve().then(async () => {
38+
// lpStream lets us read/write in a predetermined order
39+
const lp = lpStream(stream)
40+
41+
// read the incoming request
42+
const req = await lp.read()
43+
44+
// deserialize the query
45+
const query = JSON.parse(new TextDecoder().decode(req.subarray()))
46+
47+
if (query.question === 'What is the air-speed velocity of an unladen swallow?') {
48+
// write the response
49+
await lp.write(new TextEncoder().encode(JSON.stringify({
50+
answer: 'Is that an African or a European swallow?'
51+
})))
52+
} else {
53+
// write the response
54+
await lp.write(new TextEncoder().encode(JSON.stringify({
55+
error: "What? I don't know?!"
56+
})))
57+
}
58+
})
59+
.catch(err => {
60+
stream.abort(err)
61+
})
62+
})
63+
64+
// the local will dial the remote on the protocol stream
65+
const stream = await local.dialProtocol(remote.getMultiaddrs(), REQ_RESP_PROTOCOL)
66+
67+
// lpStream lets us read/write in a predetermined order
68+
const lp = lpStream(stream)
69+
70+
// send the query
71+
await lp.write(new TextEncoder().encode(JSON.stringify({
72+
question: 'What is the air-speed velocity of an unladen swallow?'
73+
})))
74+
75+
// read the response
76+
const res = await lp.read()
77+
const output = JSON.parse(new TextDecoder().decode(res.subarray()))
78+
79+
console.info(`The answer is: "${output.answer}"`)
80+
81+
await remote.stop()
82+
await local.stop()
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)