mirror of
https://github.com/fluencelabs/js-libp2p
synced 2025-08-01 00:41:57 +00:00
Compare commits
3 Commits
v0.30.3
...
chore/rend
Author | SHA1 | Date | |
---|---|---|---|
|
162a68f807 | ||
|
4d7b3b397f | ||
|
762062b904 |
@@ -45,7 +45,7 @@ const after = async () => {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
bundlesize: { maxSize: '260kB' },
|
||||
bundlesize: { maxSize: '225kB' },
|
||||
hooks: {
|
||||
pre: before,
|
||||
post: after
|
||||
|
21
.github/workflows/main.yml
vendored
21
.github/workflows/main.yml
vendored
@@ -72,20 +72,6 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
- run: yarn
|
||||
- run: cd examples && yarn && npm run test -- chat
|
||||
test-connection-encryption-example:
|
||||
needs: check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: yarn
|
||||
- run: cd examples && yarn && npm run test -- connection-encryption
|
||||
test-echo-example:
|
||||
needs: check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: yarn
|
||||
- run: cd examples && yarn && npm run test -- echo
|
||||
test-libp2p-in-the-browser-example:
|
||||
needs: check
|
||||
runs-on: macos-latest
|
||||
@@ -100,10 +86,3 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
- run: yarn
|
||||
- run: cd examples && yarn && npm run test -- discovery-mechanisms
|
||||
test-pnet-example:
|
||||
needs: check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: yarn
|
||||
- run: cd examples && yarn && npm run test -- pnet
|
||||
|
13
CHANGELOG.md
13
CHANGELOG.md
@@ -1,16 +1,3 @@
|
||||
## [0.30.3](https://github.com/libp2p/js-libp2p/compare/v0.30.2...v0.30.3) (2021-01-27)
|
||||
|
||||
|
||||
|
||||
## [0.30.2](https://github.com/libp2p/js-libp2p/compare/v0.30.1...v0.30.2) (2021-01-21)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* store multiaddrs during content and peer routing queries ([#865](https://github.com/libp2p/js-libp2p/issues/865)) ([45c3367](https://github.com/libp2p/js-libp2p/commit/45c33675a7412c66d0fd4e113ef8506077b6f492))
|
||||
|
||||
|
||||
|
||||
## [0.30.1](https://github.com/libp2p/js-libp2p/compare/v0.30.0...v0.30.1) (2021-01-18)
|
||||
|
||||
|
||||
|
@@ -161,6 +161,8 @@ List of packages currently in existence for libp2p
|
||||
| **peer routing** |
|
||||
| [`libp2p-delegated-peer-routing`](//github.com/libp2p/js-libp2p-delegated-peer-routing) | [](//github.com/libp2p/js-libp2p-delegated-peer-routing/releases) | [](https://david-dm.org/libp2p/js-libp2p-delegated-peer-routing) | [](https://travis-ci.com/libp2p/js-libp2p-delegated-peer-routing) | [](https://codecov.io/gh/libp2p/js-libp2p-delegated-peer-routing) | [Jacob Heun](mailto:jacobheun@gmail.com) |
|
||||
| [`libp2p-kad-dht`](//github.com/libp2p/js-libp2p-kad-dht) | [](//github.com/libp2p/js-libp2p-kad-dht/releases) | [](https://david-dm.org/libp2p/js-libp2p-kad-dht) | [](https://travis-ci.com/libp2p/js-libp2p-kad-dht) | [](https://codecov.io/gh/libp2p/js-libp2p-kad-dht) | [Vasco Santos](mailto:vasco.santos@moxy.studio) |
|
||||
| **service discovery** |
|
||||
| [`libp2p-rendezvous`](//github.com/libp2p/js-libp2p-rendezvous) | [](//github.com/libp2p/js-libp2p-rendezvous/releases) | [](https://david-dm.org/libp2p/js-libp2p-rendezvous) | [](https://travis-ci.com/libp2p/js-libp2p-rendezvous) | [](https://codecov.io/gh/libp2p/js-libp2p-rendezvous) | [Vasco Santos](mailto:santos.vasco10@gmail.com) |
|
||||
| **utilities** |
|
||||
| [`libp2p-crypto`](//github.com/libp2p/js-libp2p-crypto) | [](//github.com/libp2p/js-libp2p-crypto/releases) | [](https://david-dm.org/libp2p/js-libp2p-crypto) | [](https://travis-ci.com/libp2p/js-libp2p-crypto) | [](https://codecov.io/gh/libp2p/js-libp2p-crypto) | [Jacob Heun](mailto:jacobheun@gmail.com) |
|
||||
| [`libp2p-crypto-secp256k1`](//github.com/libp2p/js-libp2p-crypto-secp256k1) | [](//github.com/libp2p/js-libp2p-crypto-secp256k1/releases) | [](https://david-dm.org/libp2p/js-libp2p-crypto-secp256k1) | [](https://travis-ci.com/libp2p/js-libp2p-crypto-secp256k1) | [](https://codecov.io/gh/libp2p/js-libp2p-crypto-secp256k1) | [Friedel Ziegelmayer](mailto:dignifiedquire@gmail.com) |
|
||||
|
85
doc/API.md
85
doc/API.md
@@ -51,6 +51,9 @@
|
||||
* [`pubsub.removeListener`](#pubsubremovelistener)
|
||||
* [`pubsub.topicValidators.set`](#pubsubtopicvalidatorsset)
|
||||
* [`pubsub.topicValidators.delete`](#pubsubtopicvalidatorsdelete)
|
||||
* [`rendezvous.discover`](#rendezvousdiscover)
|
||||
* [`rendezvous.register`](#rendezvousregister)
|
||||
* [`rendezvous.unregister`](#rendezvousunregister)
|
||||
* [`connectionManager.get`](#connectionmanagerget)
|
||||
* [`connectionManager.setPeerValue`](#connectionmanagersetpeervalue)
|
||||
* [`connectionManager.size`](#connectionmanagersize)
|
||||
@@ -1600,6 +1603,88 @@ Get a connection with a given peer, if it exists.
|
||||
libp2p.connectionManager.get(peerId)
|
||||
```
|
||||
|
||||
### rendezvous.register
|
||||
|
||||
Registers the peer in a given namespace.
|
||||
|
||||
`rendezvous.register(namespace, [options])`
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| namespace | `string` | namespace to register |
|
||||
| [options] | `Object` | rendezvous registrations options |
|
||||
| [options.ttl=7.2e6] | `number` | registration ttl in ms |
|
||||
|
||||
#### Returns
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `Promise<number>` | Remaining ttl value |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
// ...
|
||||
const ttl = await rendezvous.register(namespace)
|
||||
```
|
||||
|
||||
### rendezvous.unregister
|
||||
|
||||
Unregisters the peer from a given namespace.
|
||||
|
||||
`rendezvous.unregister(namespace)`
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| namespace | `string` | namespace to unregister |
|
||||
|
||||
#### Returns
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `Promise<void>` | Operation resolved |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
// ...
|
||||
await rendezvous.register(namespace)
|
||||
await rendezvous.unregister(namespace)
|
||||
```
|
||||
|
||||
### rendezvous.discover
|
||||
|
||||
Discovers peers registered under a given namespace.
|
||||
|
||||
`rendezvous.discover(namespace, [limit])`
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| namespace | `string` | namespace to discover |
|
||||
| limit | `number` | limit of peers to discover |
|
||||
|
||||
#### Returns
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `AsyncIterable<{ signedPeerRecord: Uint8Array, ns: string, ttl: number }>` | Async Iterable with registrations |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
// ...
|
||||
await rendezvous.register(namespace)
|
||||
for await (const reg of rendezvous.discover(namespace)) {
|
||||
console.log(reg.signedPeerRecord, reg.ns, reg.ttl)
|
||||
}
|
||||
```
|
||||
|
||||
### connectionManager.setPeerValue
|
||||
|
||||
Enables users to change the value of certain peers in a range of 0 to 1. Peers with the lowest values will have their Connections pruned first, if any Connection Manager limits are exceeded. See [./CONFIGURATION.md#configuring-connection-manager](./CONFIGURATION.md#configuring-connection-manager) for details on how to configure these limits.
|
||||
|
@@ -21,6 +21,7 @@
|
||||
- [Setup with Content and Peer Routing](#setup-with-content-and-peer-routing)
|
||||
- [Setup with Relay](#setup-with-relay)
|
||||
- [Setup with Auto Relay](#setup-with-auto-relay)
|
||||
- [Setup with Rendezvous](#setup-with-rendezvous)
|
||||
- [Setup with Keychain](#setup-with-keychain)
|
||||
- [Configuring Dialing](#configuring-dialing)
|
||||
- [Configuring Connection Manager](#configuring-connection-manager)
|
||||
@@ -475,6 +476,34 @@ const node = await Libp2p.create({
|
||||
})
|
||||
```
|
||||
|
||||
#### Setup with Rendezvous
|
||||
|
||||
You will need to setup a rendezvous server, which will be used by rendezvous client nodes. You can see how to setup a rendezvous server in [libp2p/js-libp2p-rendezvous](https://github.com/libp2p/js-libp2p-rendezvous)
|
||||
|
||||
For setting up libp2p with a rendezvous client, you should configure libp2p as follows:
|
||||
|
||||
```js
|
||||
const Libp2p = require('libp2p')
|
||||
const TCP = require('libp2p-tcp')
|
||||
const MPLEX = require('libp2p-mplex')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const Rendezvous = require('libp2p-rendezvous')
|
||||
const Bootstrap = require('libp2p-bootstrap')
|
||||
const node = await Libp2p.create({
|
||||
modules: {
|
||||
transport: [TCP],
|
||||
streamMuxer: [MPLEX],
|
||||
connEncryption: [NOISE],
|
||||
peerDiscovery: [Bootstrap]
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
// Insert your rendezvous servers multiaddrs
|
||||
rendezvousPoints: ['/dnsaddr/rendezvous.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJP']
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Setup with Keychain
|
||||
|
||||
Libp2p allows you to setup a secure keychain to manage your keys. The keychain configuration object should have the following properties:
|
||||
|
@@ -1,30 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const execa = require('execa')
|
||||
const pDefer = require('p-defer')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
|
||||
async function test () {
|
||||
const messageReceived = pDefer()
|
||||
process.stdout.write('1.js\n')
|
||||
|
||||
const proc = execa('node', [path.join(__dirname, '1.js')], {
|
||||
cwd: path.resolve(__dirname),
|
||||
all: true
|
||||
})
|
||||
|
||||
proc.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
|
||||
const s = uint8ArrayToString(data)
|
||||
if (s.includes('This information is sent out encrypted to the other peer')) {
|
||||
messageReceived.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
await messageReceived.promise
|
||||
proc.kill()
|
||||
}
|
||||
|
||||
module.exports = test
|
68
examples/discovery-mechanisms/3.js
Normal file
68
examples/discovery-mechanisms/3.js
Normal file
@@ -0,0 +1,68 @@
|
||||
/* eslint-disable no-console */
|
||||
'use strict'
|
||||
|
||||
const Libp2p = require('../../')
|
||||
const TCP = require('libp2p-tcp')
|
||||
const Mplex = require('libp2p-mplex')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const Gossipsub = require('libp2p-gossipsub')
|
||||
const Bootstrap = require('libp2p-bootstrap')
|
||||
const PubsubPeerDiscovery = require('libp2p-pubsub-peer-discovery')
|
||||
|
||||
const createRelayServer = require('libp2p-relay-server')
|
||||
|
||||
const createNode = async (bootstrapers) => {
|
||||
const node = await Libp2p.create({
|
||||
addresses: {
|
||||
listen: ['/ip4/0.0.0.0/tcp/0']
|
||||
},
|
||||
modules: {
|
||||
transport: [TCP],
|
||||
streamMuxer: [Mplex],
|
||||
connEncryption: [NOISE],
|
||||
pubsub: Gossipsub,
|
||||
peerDiscovery: [Bootstrap, PubsubPeerDiscovery]
|
||||
},
|
||||
config: {
|
||||
peerDiscovery: {
|
||||
[PubsubPeerDiscovery.tag]: {
|
||||
interval: 1000,
|
||||
enabled: true
|
||||
},
|
||||
[Bootstrap.tag]: {
|
||||
enabled: true,
|
||||
list: bootstrapers
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
;(async () => {
|
||||
const relay = await createRelayServer({
|
||||
listenAddresses: ['/ip4/0.0.0.0/tcp/0']
|
||||
})
|
||||
console.log(`libp2p relay starting with id: ${relay.peerId.toB58String()}`)
|
||||
await relay.start()
|
||||
const relayMultiaddrs = relay.multiaddrs.map((m) => `${m.toString()}/p2p/${relay.peerId.toB58String()}`)
|
||||
|
||||
const [node1, node2] = await Promise.all([
|
||||
createNode(relayMultiaddrs),
|
||||
createNode(relayMultiaddrs)
|
||||
])
|
||||
|
||||
node1.on('peer:discovery', (peerId) => {
|
||||
console.log(`Peer ${node1.peerId.toB58String()} discovered: ${peerId.toB58String()}`)
|
||||
})
|
||||
node2.on('peer:discovery', (peerId) => {
|
||||
console.log(`Peer ${node2.peerId.toB58String()} discovered: ${peerId.toB58String()}`)
|
||||
})
|
||||
|
||||
;[node1, node2].forEach((node, index) => console.log(`Node ${index} starting with id: ${node.peerId.toB58String()}`))
|
||||
await Promise.all([
|
||||
node1.start(),
|
||||
node2.start()
|
||||
])
|
||||
})();
|
@@ -156,7 +156,100 @@ Discovered: QmSSbQpuKrxkoXHm1v4Pi35hPN5hUHMZoBoawEs2Nhvi8m
|
||||
Discovered: QmRcXXhtG8vTqwVBRonKWtV4ovDoC1Fe56WYtcrw694eiJ
|
||||
```
|
||||
|
||||
## 3. Where to find other Peer Discovery Mechanisms
|
||||
## 3. Pubsub based Peer Discovery
|
||||
|
||||
For this example, we need [`libp2p-pubsub-peer-discovery`](https://github.com/libp2p/js-libp2p-pubsub-peer-discovery/), go ahead and `npm install` it. You also need to spin up a set of [`libp2p-relay-servers`](https://github.com/libp2p/js-libp2p-relay-server). These servers act as relay servers and a peer discovery source.
|
||||
|
||||
In the context of this example, we will create and run the `libp2p-relay-server` in the same code snippet. You can find the complete solution at [3.js](./3.js).
|
||||
|
||||
You can create your libp2p nodes as follows:
|
||||
|
||||
```js
|
||||
const Libp2p = require('libp2p')
|
||||
const TCP = require('libp2p-tcp')
|
||||
const Mplex = require('libp2p-mplex')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const Gossipsub = require('libp2p-gossipsub')
|
||||
const Bootstrap = require('libp2p-bootstrap')
|
||||
const PubsubPeerDiscovery = require('libp2p-pubsub-peer-discovery')
|
||||
|
||||
const createNode = async (bootstrapers) => {
|
||||
const node = await Libp2p.create({
|
||||
addresses: {
|
||||
listen: ['/ip4/0.0.0.0/tcp/0']
|
||||
},
|
||||
modules: {
|
||||
transport: [TCP],
|
||||
streamMuxer: [Mplex],
|
||||
connEncryption: [NOISE],
|
||||
pubsub: Gossipsub,
|
||||
peerDiscovery: [Bootstrap, PubsubPeerDiscovery]
|
||||
},
|
||||
config: {
|
||||
peerDiscovery: {
|
||||
[PubsubPeerDiscovery.tag]: {
|
||||
interval: 1000,
|
||||
enabled: true
|
||||
},
|
||||
[Bootstrap.tag]: {
|
||||
enabled: true,
|
||||
list: bootstrapers
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return node
|
||||
}
|
||||
```
|
||||
|
||||
We will use the `libp2p-relay-server` as bootstrap nodes for the libp2p nodes, so that they establish a connection with the relay after starting. As a result, after they establish a connection with the relay, the pubsub discovery will kick in an the relay will advertise them.
|
||||
|
||||
```js
|
||||
const relay = await createRelayServer({
|
||||
listenAddresses: ['/ip4/0.0.0.0/tcp/0']
|
||||
})
|
||||
console.log(`libp2p relay starting with id: ${relay.peerId.toB58String()}`)
|
||||
await relay.start()
|
||||
const relayMultiaddrs = relay.multiaddrs.map((m) => `${m.toString()}/p2p/${relay.peerId.toB58String()}`)
|
||||
|
||||
const [node1, node2] = await Promise.all([
|
||||
createNode(relayMultiaddrs),
|
||||
createNode(relayMultiaddrs)
|
||||
])
|
||||
|
||||
node1.on('peer:discovery', (peerId) => {
|
||||
console.log(`Peer ${node1.peerId.toB58String()} discovered: ${peerId.toB58String()}`)
|
||||
})
|
||||
node2.on('peer:discovery', (peerId) => {
|
||||
console.log(`Peer ${node2.peerId.toB58String()} discovered: ${peerId.toB58String()}`)
|
||||
})
|
||||
|
||||
;[node1, node2].forEach((node, index) => console.log(`Node ${index} starting with id: ${node.peerId.toB58String()}`))
|
||||
await Promise.all([
|
||||
node1.start(),
|
||||
node2.start()
|
||||
])
|
||||
```
|
||||
|
||||
If you run this example, you will see the other peers being discovered.
|
||||
|
||||
```bash
|
||||
> node 3.js
|
||||
libp2p relay starting with id: QmW6FqVV6RsyoGC5zaeFGW9gSWA3LcBRVZrjkKMruh38Bo
|
||||
Node 0 starting with id: QmezqDTmEjZ5BfMgVqjSpLY19mVVLTQ9bE9mRpZwtGxL8N
|
||||
Node 1 starting with id: QmYWeom2odTkm79DzB68NHULqVHDaNDqHhoyqLdcV1fqdv
|
||||
Peer QmezqDTmEjZ5BfMgVqjSpLY19mVVLTQ9bE9mRpZwtGxL8N discovered: QmW6FqVV6RsyoGC5zaeFGW9gSWA3LcBRVZrjkKMruh38Bo
|
||||
Peer QmYWeom2odTkm79DzB68NHULqVHDaNDqHhoyqLdcV1fqdv discovered: QmW6FqVV6RsyoGC5zaeFGW9gSWA3LcBRVZrjkKMruh38Bo
|
||||
Peer QmYWeom2odTkm79DzB68NHULqVHDaNDqHhoyqLdcV1fqdv discovered: QmezqDTmEjZ5BfMgVqjSpLY19mVVLTQ9bE9mRpZwtGxL8N
|
||||
Peer QmezqDTmEjZ5BfMgVqjSpLY19mVVLTQ9bE9mRpZwtGxL8N discovered: QmYWeom2odTkm79DzB68NHULqVHDaNDqHhoyqLdcV1fqdv
|
||||
```
|
||||
|
||||
Taking into account the output, after the relay and both libp2p nodes start, both libp2p nodes will discover the bootstrap node (relay) and connect with it. After establishing a connection with the relay, they will discover each other.
|
||||
|
||||
This is really useful when running libp2p in constrained environments like a browser. You can run a set of `libp2p-relay-server` nodes that will be responsible for both relaying websocket connections between browser nodes and for discovering other browser peers.
|
||||
|
||||
## 4. Where to find other Peer Discovery Mechanisms
|
||||
|
||||
There are plenty more Peer Discovery Mechanisms out there, you can:
|
||||
|
||||
|
146
examples/discovery-mechanisms/rendezvous/README.md
Normal file
146
examples/discovery-mechanisms/rendezvous/README.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# Rendezvous
|
||||
|
||||
During the lifetime of a libp2p node, particularly during its startup, establishing connections with other peers will be crucial to create a network topology able to fulfill the needs of the node.
|
||||
|
||||
Each connection to a different peer might have different outcomes. Accordingly, each peer will need to find peers providing a given service or playing a given role over time, so that they can operate more efficiently. These services and roles can range from circuit relays to enable connectivity between restricted nodes, subscribers of a given pubsub topic, or even application specific routing.
|
||||
|
||||
One of the possible ways to register and discover certain roles/services is using the [rendezvous protocol](https://github.com/libp2p/specs/tree/master/rendezvous). For using it, the network needs to have well known libp2p nodes acting as rendezvous servers. They will collect and maintain a list of registrations per rendezvous namespace. Other peers in the network will act as rendezvous clients and will register themselves on given namespaces by messaging a rendezvous server node. Taking into account these registrations, a rendezvous client is also able to discover other peers in a given namespace by querying a server. Each registration has a time to live, in order to avoid finding invalid registrations.
|
||||
|
||||
## 0. Set up the example
|
||||
|
||||
Before moving into the examples, you should run `npm install` on the top level `js-libp2p` folder, in order to install all the dependencies needed for this example. Once the install finishes, you should move into the example folder with `cd examples/discovery-mechanisms/rendezvous`.
|
||||
|
||||
You will also need to install and run a `libp2p-rendezvous` server. In the context of this example, we can just install `libp2p-rendezvous` globally and run a server locally with:
|
||||
|
||||
```sh
|
||||
npm i -g libp2p-rendezvous
|
||||
libp2p-rendezvous-server --enableMemoryDatabase
|
||||
```
|
||||
|
||||
We will be using a memory database for demonstration purposes. For using this in production you should read [libp2p/js-libp2p-rendezvous instructions](https://github.com/libp2p/js-libp2p-rendezvous) and use a database to back it up.
|
||||
|
||||
It should print out the addresses the server is listening on as:
|
||||
|
||||
```sh
|
||||
Rendezvous server listening on:
|
||||
/ip4/127.0.0.1/tcp/15003/ws/p2p/QmeSKXKKfkQzE45WTLY7Me1RaC8ZhG9aFfSPVEnGHbFQXM
|
||||
/ip4/127.0.0.1/tcp/8000/p2p/QmeSKXKKfkQzE45WTLY7Me1RaC8ZhG9aFfSPVEnGHbFQXM
|
||||
```
|
||||
|
||||
## 1. Set up a listener node providing a service
|
||||
|
||||
One of the typical use cases for Rendezvous is to easily make discoverable nodes that provide services to boost the network. These libp2p nodes should make themselves discoverable by using rendezvous namespaces.
|
||||
|
||||
```js
|
||||
const Libp2p = require('libp2p')
|
||||
const Websockets = require('libp2p-websockets')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const MPLEX = require('libp2p-mplex')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
|
||||
const rendezvousServerAddr = process.argv[2]
|
||||
if (!rendezvousServerAddr) {
|
||||
throw new Error('the relay address needs to be specified as a parameter')
|
||||
}
|
||||
|
||||
const rendezvousServerMultiaddr = multiaddr(rendezvousServerAddr)
|
||||
|
||||
const node = await Libp2p.create({
|
||||
modules: {
|
||||
transport: [Websockets],
|
||||
connEncryption: [NOISE],
|
||||
streamMuxer: [MPLEX]
|
||||
},
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/0/ws']
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: [rendezvousServerMultiaddr]
|
||||
}
|
||||
})
|
||||
|
||||
await node.start()
|
||||
console.log(`Node started with id ${node.peerId.toB58String()}`)
|
||||
console.log('Node listening on:')
|
||||
node.multiaddrs.forEach((m) => console.log(`${m}/p2p/${node.peerId.toB58String()}`))
|
||||
|
||||
await node.rendezvous.register('example-namespace')
|
||||
console.log('Registered to: ', ns)
|
||||
```
|
||||
|
||||
As you can see in the code, we need to provide the rendezvous server address, `rendezvousServerAddr`, as a process argument.
|
||||
|
||||
You should now run the following to start the node providing the service:
|
||||
|
||||
```sh
|
||||
node listener.js /ip4/127.0.0.1/tcp/15003/ws/p2p/QmeSKXKKfkQzE45WTLY7Me1RaC8ZhG9aFfSPVEnGHbFQXM
|
||||
```
|
||||
|
||||
This should print out something similar to the following:
|
||||
|
||||
```sh
|
||||
Node started with id QmV4sitaJ5ZC2Vpgza8NyjeTSWV4FvHd5cNmyPPPKpoRE7
|
||||
Node listening on:
|
||||
/ip4/127.0.0.1/tcp/50347/ws/p2p/QmV4sitaJ5ZC2Vpgza8NyjeTSWV4FvHd5cNmyPPPKpoRE7
|
||||
Registered to: example-namespace
|
||||
```
|
||||
|
||||
## 2. Set up a Dialer node discovering the service
|
||||
|
||||
Now that you have a node providing a given service, you can discover it via the rendezvous server.
|
||||
|
||||
```js
|
||||
const rendezvousServerAddr = process.argv[2]
|
||||
if (!rendezvousServerAddr) {
|
||||
throw new Error('the rendezvous server address needs to be specified as a parameter')
|
||||
}
|
||||
|
||||
const rendezvousServerMultiaddr = multiaddr(rendezvousServerAddr)
|
||||
const ns = 'example-namespace'
|
||||
|
||||
const node = await Libp2p.create({
|
||||
modules: {
|
||||
transport: [Websockets],
|
||||
connEncryption: [NOISE],
|
||||
streamMuxer: [MPLEX]
|
||||
},
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/0/ws']
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: [rendezvousServerMultiaddr]
|
||||
}
|
||||
})
|
||||
|
||||
await node.start()
|
||||
console.log(`Node started with id ${node.peerId.toB58String()}`)
|
||||
|
||||
for await (const reg of node.rendezvous.discover(ns)) {
|
||||
const e = await Envelope.openAndCertify(reg.signedPeerRecord, PeerRecord.DOMAIN)
|
||||
const rec = PeerRecord.createFromProtobuf(e.payload)
|
||||
|
||||
console.log(`Discovered peer with id: ${rec.peerId.toB58String()} and multiaddrs ${rec.multiaddrs}`)
|
||||
}
|
||||
```
|
||||
|
||||
You should now run the following to start the node discovering the service:
|
||||
|
||||
```sh
|
||||
node dialer.js /ip4/127.0.0.1/tcp/15003/ws/p2p/QmeSKXKKfkQzE45WTLY7Me1RaC8ZhG9aFfSPVEnGHbFQXM
|
||||
```
|
||||
|
||||
This should print out something similar to the following:
|
||||
|
||||
```sh
|
||||
Node started with id QmanTJphnwpKTeRaoDpEiMoNytvKyFUh61Ri9ifptbvJdb
|
||||
Discovered peer with id: QmV4sitaJ5ZC2Vpgza8NyjeTSWV4FvHd5cNmyPPPKpoRE7 and multiaddrs /ip4/127.0.0.1/tcp/50347/ws
|
||||
```
|
||||
|
||||
As you can see, the dialer discovered the node providing the `example-namespace` service and can now use its multiaddr and id to dial it.
|
||||
|
||||
## 3. What's next?
|
||||
|
||||
Libp2p does not support re-registering over time. This means that the application layer will need to handle triggering the `rendezvous.register` over time to refresh the registration of the node in the given rendezvous servers. The minimum ttl of a registration is 2 hours.
|
47
examples/discovery-mechanisms/rendezvous/dialer.js
Normal file
47
examples/discovery-mechanisms/rendezvous/dialer.js
Normal file
@@ -0,0 +1,47 @@
|
||||
'use strict'
|
||||
|
||||
const Libp2p = require('../../../src')
|
||||
const Envelope = require('../../../src/record/envelope')
|
||||
const PeerRecord = require('../../../src/record/peer-record')
|
||||
const Websockets = require('libp2p-websockets')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const MPLEX = require('libp2p-mplex')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
|
||||
async function main () {
|
||||
const rendezvousServerAddr = process.argv[2]
|
||||
if (!rendezvousServerAddr) {
|
||||
throw new Error('the rendezvous server address needs to be specified as a parameter')
|
||||
}
|
||||
|
||||
const rendezvousServerMultiaddr = multiaddr(rendezvousServerAddr)
|
||||
const ns = 'example-namespace'
|
||||
|
||||
const node = await Libp2p.create({
|
||||
modules: {
|
||||
transport: [Websockets],
|
||||
connEncryption: [NOISE],
|
||||
streamMuxer: [MPLEX]
|
||||
},
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/0/ws']
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: [rendezvousServerMultiaddr]
|
||||
}
|
||||
})
|
||||
|
||||
await node.start()
|
||||
console.log(`Node started with id ${node.peerId.toB58String()}`)
|
||||
|
||||
for await (const reg of node.rendezvous.discover(ns)) {
|
||||
const e = await Envelope.openAndCertify(reg.signedPeerRecord, PeerRecord.DOMAIN)
|
||||
const rec = PeerRecord.createFromProtobuf(e.payload)
|
||||
|
||||
console.log(`Discovered peer with id: ${rec.peerId.toB58String()} and multiaddrs ${rec.multiaddrs}`)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
43
examples/discovery-mechanisms/rendezvous/listener.js
Normal file
43
examples/discovery-mechanisms/rendezvous/listener.js
Normal file
@@ -0,0 +1,43 @@
|
||||
'use strict'
|
||||
|
||||
const Libp2p = require('../../../src')
|
||||
const Websockets = require('libp2p-websockets')
|
||||
const { NOISE } = require('libp2p-noise')
|
||||
const MPLEX = require('libp2p-mplex')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
|
||||
async function main () {
|
||||
const rendezvousServerAddr = process.argv[2]
|
||||
if (!rendezvousServerAddr) {
|
||||
throw new Error('the rendezvous server address needs to be specified as a parameter')
|
||||
}
|
||||
|
||||
const rendezvousServerMultiaddr = multiaddr(rendezvousServerAddr)
|
||||
const ns = 'example-namespace'
|
||||
|
||||
const node = await Libp2p.create({
|
||||
modules: {
|
||||
transport: [Websockets],
|
||||
connEncryption: [NOISE],
|
||||
streamMuxer: [MPLEX]
|
||||
},
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/0/ws']
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: [rendezvousServerMultiaddr]
|
||||
}
|
||||
})
|
||||
|
||||
await node.start()
|
||||
console.log(`Node started with id ${node.peerId.toB58String()}`)
|
||||
console.log('Node listening on:')
|
||||
node.multiaddrs.forEach((m) => console.log(`${m}/p2p/${node.peerId.toB58String()}`))
|
||||
|
||||
await node.rendezvous.register(ns)
|
||||
console.log('Registered to: ', ns)
|
||||
}
|
||||
|
||||
main()
|
84
examples/discovery-mechanisms/rendezvous/test.js
Normal file
84
examples/discovery-mechanisms/rendezvous/test.js
Normal file
@@ -0,0 +1,84 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const execa = require('execa')
|
||||
const delay = require('delay')
|
||||
const pDefer = require('p-defer')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
|
||||
const { createRendezvousServer } = require('../../../test/rendezvous/utils')
|
||||
|
||||
function startProcess(name, args = []) {
|
||||
return execa('node', [path.join(__dirname, name), ...args], {
|
||||
cwd: path.resolve(__dirname),
|
||||
all: true
|
||||
})
|
||||
}
|
||||
|
||||
async function test() {
|
||||
let output1 = ''
|
||||
let output2 = ''
|
||||
const proc1Ready = pDefer()
|
||||
const proc2Ready = pDefer()
|
||||
|
||||
// Start Rendezvous Server
|
||||
const rendezvousServer = await createRendezvousServer({
|
||||
config: {
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/0/ws']
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Wait for server to be listenning
|
||||
await delay(1000)
|
||||
const rendezvousServerMa = `${rendezvousServer.multiaddrs[0]}/p2p/${rendezvousServer.peerId.toB58String()}`
|
||||
|
||||
// Step 1 process
|
||||
process.stdout.write('listener.js\n')
|
||||
|
||||
const proc1 = startProcess('listener.js', [rendezvousServerMa])
|
||||
proc1.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
|
||||
output1 += uint8ArrayToString(data)
|
||||
|
||||
if (output1.includes('Node listening on:') && output1.includes('Registered to:')) {
|
||||
proc1Ready.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
await proc1Ready.promise
|
||||
process.stdout.write('==================================================================\n')
|
||||
|
||||
// Step 2 process
|
||||
process.stdout.write('dialer.js\n')
|
||||
|
||||
const proc2 = startProcess('dialer.js', [rendezvousServerMa])
|
||||
proc2.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
|
||||
output2 += uint8ArrayToString(data)
|
||||
|
||||
if (output2.includes('Discovered peer with id:')) {
|
||||
proc2Ready.resolve()
|
||||
proc2.kill()
|
||||
proc1.kill()
|
||||
}
|
||||
})
|
||||
|
||||
await proc2Ready.promise
|
||||
|
||||
await Promise.all([
|
||||
proc1,
|
||||
proc2
|
||||
]).catch((err) => {
|
||||
if (err.signal !== 'SIGTERM') {
|
||||
throw err
|
||||
}
|
||||
})
|
||||
|
||||
await rendezvousServer.stop()
|
||||
}
|
||||
|
||||
module.exports = test
|
35
examples/discovery-mechanisms/test-3.js
Normal file
35
examples/discovery-mechanisms/test-3.js
Normal file
@@ -0,0 +1,35 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const execa = require('execa')
|
||||
const pWaitFor = require('p-wait-for')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
|
||||
const discoveredCopy = 'discovered:'
|
||||
|
||||
async function test() {
|
||||
let discoverCount = 0
|
||||
|
||||
process.stdout.write('3.js\n')
|
||||
|
||||
const proc = execa('node', [path.join(__dirname, '3.js')], {
|
||||
cwd: path.resolve(__dirname),
|
||||
all: true
|
||||
})
|
||||
|
||||
proc.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
const line = uint8ArrayToString(data)
|
||||
|
||||
// Discovered or Connected
|
||||
if (line.includes(discoveredCopy)) {
|
||||
discoverCount++
|
||||
}
|
||||
})
|
||||
|
||||
await pWaitFor(() => discoverCount === 4)
|
||||
|
||||
proc.kill()
|
||||
}
|
||||
|
||||
module.exports = test
|
@@ -2,10 +2,14 @@
|
||||
|
||||
const test1 = require('./test-1')
|
||||
const test2 = require('./test-2')
|
||||
const test3 = require('./test-3')
|
||||
const testRendezvous = require('./rendezvous/test')
|
||||
|
||||
async function test () {
|
||||
await test1()
|
||||
await test2()
|
||||
await test3()
|
||||
await testRendezvous()
|
||||
}
|
||||
|
||||
module.exports = test
|
||||
|
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const createLibp2p = require('./libp2p')
|
||||
const createLibp2p = require('./libp2p-bundle')
|
||||
const pipe = require('it-pipe')
|
||||
|
||||
async function run() {
|
||||
|
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const createLibp2p = require('./libp2p')
|
||||
const createLibp2p = require('./libp2p-bundle')
|
||||
const pipe = require('it-pipe')
|
||||
|
||||
async function run() {
|
||||
|
@@ -1,61 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const execa = require('execa')
|
||||
const pDefer = require('p-defer')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
|
||||
function startProcess(name) {
|
||||
return execa('node', [path.join(__dirname, name)], {
|
||||
cwd: path.resolve(__dirname),
|
||||
all: true
|
||||
})
|
||||
}
|
||||
|
||||
async function test () {
|
||||
const listenerReady = pDefer()
|
||||
const messageReceived = pDefer()
|
||||
|
||||
// Step 1 process
|
||||
process.stdout.write('node listener.js\n')
|
||||
const listenerProc = startProcess('src/listener.js')
|
||||
listenerProc.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
const s = uint8ArrayToString(data)
|
||||
|
||||
if (s.includes('Listener ready, listening on:')) {
|
||||
listenerReady.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
await listenerReady.promise
|
||||
process.stdout.write('==================================================================\n')
|
||||
|
||||
// Step 2 process
|
||||
process.stdout.write('node dialer.js\n')
|
||||
const dialerProc = startProcess('src/dialer.js')
|
||||
dialerProc.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
const s = uint8ArrayToString(data)
|
||||
|
||||
if (s.includes('received echo:')) {
|
||||
messageReceived.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
await messageReceived.promise
|
||||
process.stdout.write('echo message received\n')
|
||||
|
||||
listenerProc.kill()
|
||||
dialerProc.kill()
|
||||
await Promise.all([
|
||||
listenerProc,
|
||||
dialerProc
|
||||
]).catch((err) => {
|
||||
if (err.signal !== 'SIGTERM') {
|
||||
throw err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = test
|
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Libp2p = require('../..')
|
||||
const Libp2p = require('../../')
|
||||
const TCP = require('libp2p-tcp')
|
||||
const Mplex = require('libp2p-mplex')
|
||||
const { NOISE } = require('libp2p-noise')
|
@@ -1,4 +1,4 @@
|
||||
# Connection Encryption
|
||||
# Encrypted Communications
|
||||
|
||||
libp2p can leverage the encrypted communications from the transports it uses (i.e WebRTC). To ensure that every connection is encrypted, independently of how it was set up, libp2p also supports a set of modules that encrypt every communication established.
|
||||
|
@@ -10,6 +10,8 @@
|
||||
"dependencies": {
|
||||
"execa": "^2.1.0",
|
||||
"fs-extra": "^8.1.0",
|
||||
"libp2p-pubsub-peer-discovery": "^3.0.0",
|
||||
"libp2p-relay-server": "^0.1.2",
|
||||
"p-defer": "^3.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
|
@@ -1,30 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const path = require('path')
|
||||
const execa = require('execa')
|
||||
const pDefer = require('p-defer')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
|
||||
async function test () {
|
||||
const messageReceived = pDefer()
|
||||
process.stdout.write('index.js\n')
|
||||
|
||||
const proc = execa('node', [path.join(__dirname, 'index.js')], {
|
||||
cwd: path.resolve(__dirname),
|
||||
all: true
|
||||
})
|
||||
|
||||
proc.all.on('data', async (data) => {
|
||||
process.stdout.write(data)
|
||||
|
||||
const s = uint8ArrayToString(data)
|
||||
if (s.includes('This message is sent on a private network')) {
|
||||
messageReceived.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
await messageReceived.promise
|
||||
proc.kill()
|
||||
}
|
||||
|
||||
module.exports = test
|
@@ -42,6 +42,9 @@
|
||||
["libp2p/js-libp2p-delegated-peer-routing", "libp2p-delegated-peer-routing"],
|
||||
["libp2p/js-libp2p-kad-dht", "libp2p-kad-dht"],
|
||||
|
||||
"service discovery",
|
||||
["libp2p/js-libp2p-rendezvous", "libp2p-rendezvous"],
|
||||
|
||||
"utilities",
|
||||
["libp2p/js-libp2p-crypto", "libp2p-crypto"],
|
||||
["libp2p/js-libp2p-crypto-secp256k1", "libp2p-crypto-secp256k1"],
|
||||
|
71
package.json
71
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "libp2p",
|
||||
"version": "0.30.3",
|
||||
"version": "0.30.1",
|
||||
"description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
|
||||
"leadMaintainer": "Jacob Heun <jacobheun@gmail.com>",
|
||||
"main": "src/index.js",
|
||||
@@ -52,41 +52,35 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"aggregate-error": "^3.1.0",
|
||||
"any-signal": "^2.1.1",
|
||||
"bignumber.js": "^9.0.1",
|
||||
"cids": "^1.1.5",
|
||||
"aggregate-error": "^3.0.1",
|
||||
"any-signal": "^1.1.0",
|
||||
"bignumber.js": "^9.0.0",
|
||||
"cids": "^1.0.0",
|
||||
"class-is": "^1.1.0",
|
||||
"debug": "^4.3.1",
|
||||
"debug": "^4.1.1",
|
||||
"err-code": "^2.0.0",
|
||||
"events": "^3.2.0",
|
||||
"events": "^3.1.0",
|
||||
"hashlru": "^2.3.0",
|
||||
"interface-datastore": "^3.0.3",
|
||||
"ipfs-utils": "^6.0.0",
|
||||
"it-all": "^1.0.4",
|
||||
"interface-datastore": "^2.0.0",
|
||||
"ipfs-utils": "^5.0.1",
|
||||
"it-all": "^1.0.1",
|
||||
"it-buffer": "^0.1.2",
|
||||
"it-drain": "^1.0.3",
|
||||
"it-filter": "^1.0.1",
|
||||
"it-first": "^1.0.4",
|
||||
"it-handshake": "^1.0.2",
|
||||
"it-length-prefixed": "^3.1.0",
|
||||
"it-map": "^1.0.4",
|
||||
"it-merge": "1.0.0",
|
||||
"it-handshake": "^1.0.1",
|
||||
"it-length-prefixed": "^3.0.1",
|
||||
"it-pipe": "^1.1.0",
|
||||
"it-protocol-buffers": "^0.2.0",
|
||||
"it-take": "1.0.0",
|
||||
"libp2p-crypto": "^0.19.0",
|
||||
"libp2p-crypto": "^0.18.0",
|
||||
"libp2p-interfaces": "^0.8.1",
|
||||
"libp2p-utils": "^0.2.2",
|
||||
"mafmt": "^8.0.0",
|
||||
"merge-options": "^3.0.4",
|
||||
"merge-options": "^2.0.0",
|
||||
"moving-average": "^1.0.0",
|
||||
"multiaddr": "^8.1.0",
|
||||
"multicodec": "^2.1.0",
|
||||
"multicodec": "^2.0.0",
|
||||
"multihashing-async": "^2.0.1",
|
||||
"multistream-select": "^1.0.0",
|
||||
"mutable-proxy": "^1.0.0",
|
||||
"node-forge": "^0.10.0",
|
||||
"node-forge": "^0.9.1",
|
||||
"p-any": "^3.0.0",
|
||||
"p-fifo": "^1.0.0",
|
||||
"p-settle": "^4.0.1",
|
||||
@@ -97,7 +91,7 @@
|
||||
"set-delayed-interval": "^1.0.0",
|
||||
"streaming-iterables": "^5.0.2",
|
||||
"timeout-abort-controller": "^1.1.1",
|
||||
"varint": "^6.0.0",
|
||||
"varint": "^5.0.0",
|
||||
"xsalsa20": "^1.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -106,23 +100,24 @@
|
||||
"aegir": "^29.2.0",
|
||||
"chai-bytes": "^0.1.2",
|
||||
"chai-string": "^1.5.0",
|
||||
"delay": "^4.4.0",
|
||||
"delay": "^4.3.0",
|
||||
"interop-libp2p": "^0.3.0",
|
||||
"into-stream": "^6.0.0",
|
||||
"ipfs-http-client": "^48.2.2",
|
||||
"ipfs-http-client": "^47.0.1",
|
||||
"it-concat": "^1.0.0",
|
||||
"it-pair": "^1.0.0",
|
||||
"it-pushable": "^1.4.0",
|
||||
"libp2p": ".",
|
||||
"libp2p-bootstrap": "^0.12.0",
|
||||
"libp2p-delegated-content-routing": "^0.9.0",
|
||||
"libp2p-delegated-content-routing": "^0.8.0",
|
||||
"libp2p-delegated-peer-routing": "^0.8.0",
|
||||
"libp2p-floodsub": "^0.24.0",
|
||||
"libp2p-gossipsub": "^0.8.0",
|
||||
"libp2p-kad-dht": "^0.20.5",
|
||||
"libp2p-gossipsub": "^0.7.0",
|
||||
"libp2p-kad-dht": "^0.20.0",
|
||||
"libp2p-mdns": "^0.15.0",
|
||||
"libp2p-mplex": "^0.10.1",
|
||||
"libp2p-noise": "^2.0.0",
|
||||
"libp2p-rendezvous": "libp2p/js-libp2p-rendezvous#feat/rendezvous-protocol-full-implementation",
|
||||
"libp2p-secio": "^0.13.1",
|
||||
"libp2p-tcp": "^0.15.1",
|
||||
"libp2p-webrtc-star": "^0.20.0",
|
||||
@@ -131,11 +126,11 @@
|
||||
"nock": "^13.0.3",
|
||||
"p-defer": "^3.0.0",
|
||||
"p-times": "^3.0.0",
|
||||
"p-wait-for": "^3.2.0",
|
||||
"p-wait-for": "^3.1.0",
|
||||
"promisify-es6": "^1.0.3",
|
||||
"rimraf": "^3.0.2",
|
||||
"sinon": "^9.2.4",
|
||||
"uint8arrays": "^2.0.5"
|
||||
"sinon": "^9.0.2",
|
||||
"uint8arrays": "^1.1.0"
|
||||
},
|
||||
"contributors": [
|
||||
"David Dias <daviddias.p@gmail.com>",
|
||||
@@ -156,11 +151,11 @@
|
||||
"Andrew Nesbitt <andrewnez@gmail.com>",
|
||||
"Giovanni T. Parra <fiatjaf@gmail.com>",
|
||||
"Ryan Bell <ryan@piing.net>",
|
||||
"Samlior <samlior@foxmail.com>",
|
||||
"Thomas Eizinger <thomas@eizinger.io>",
|
||||
"ᴠɪᴄᴛᴏʀ ʙᴊᴇʟᴋʜᴏʟᴍ <victorbjelkholm@gmail.com>",
|
||||
"Didrik Nordström <didrik@betamos.se>",
|
||||
"Irakli Gozalishvili <rfobic@gmail.com>",
|
||||
"Fei Liu <liu.feiwood@gmail.com>",
|
||||
"Ethan Lam <elmemphis2000@gmail.com>",
|
||||
"Joel Gustafson <joelg@mit.edu>",
|
||||
"Julien Bouquillon <contact@revolunet.com>",
|
||||
"Kevin Kwok <antimatter15@gmail.com>",
|
||||
@@ -168,7 +163,7 @@
|
||||
"Dmitriy Ryajov <dryajov@gmail.com>",
|
||||
"RasmusErik Voel Jensen <github@solsort.com>",
|
||||
"Diogo Silva <fsdiogo@gmail.com>",
|
||||
"isan_rivkin <isanrivkin@gmail.com>",
|
||||
"Samlior <samlior@foxmail.com>",
|
||||
"Smite Chow <xiaopengyou@live.com>",
|
||||
"Soeren <nikorpoulsen@gmail.com>",
|
||||
"Sönke Hahn <soenkehahn@gmail.com>",
|
||||
@@ -179,13 +174,13 @@
|
||||
"robertkiel <robert.kiel@validitylabs.org>",
|
||||
"Cindy Wu <ciindy.wu@gmail.com>",
|
||||
"Chris Bratlien <chrisbratlien@gmail.com>",
|
||||
"ebinks <elizabethjbinks@gmail.com>",
|
||||
"Florian-Merle <florian.david.merle@gmail.com>",
|
||||
"Francis Gulotta <wizard@roborooter.com>",
|
||||
"Felipe Martins <felipebrasil93@gmail.com>",
|
||||
"ebinks <elizabethjbinks@gmail.com>",
|
||||
"Henrique Dias <hacdias@gmail.com>",
|
||||
"Bernd Strehl <bernd.strehl@gmail.com>",
|
||||
"Fei Liu <liu.feiwood@gmail.com>",
|
||||
"Ethan Lam <elmemphis2000@gmail.com>"
|
||||
"Henrique Dias <hacdias@gmail.com>",
|
||||
"isan_rivkin <isanrivkin@gmail.com>",
|
||||
"Irakli Gozalishvili <rfobic@gmail.com>"
|
||||
]
|
||||
}
|
||||
|
@@ -12,7 +12,7 @@ const TextEncoder = require('ipfs-utils/src/text-encoder')
|
||||
* @returns {Promise<CID>}
|
||||
*/
|
||||
module.exports.namespaceToCid = async (namespace) => {
|
||||
const bytes = new TextEncoder().encode(namespace)
|
||||
const bytes = new TextEncoder('utf8').encode(namespace)
|
||||
const hash = await multihashing(bytes, 'sha2-256')
|
||||
|
||||
return new CID(hash)
|
||||
|
@@ -48,6 +48,10 @@ const DefaultConfig = {
|
||||
bootDelay: 10e3
|
||||
}
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: false,
|
||||
rendezvousPoints: []
|
||||
},
|
||||
config: {
|
||||
dht: {
|
||||
enabled: false,
|
||||
|
@@ -160,7 +160,7 @@ class ConnectionManager extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(tasks)
|
||||
await tasks
|
||||
this.connections.clear()
|
||||
}
|
||||
|
||||
|
@@ -5,6 +5,8 @@
|
||||
* This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)
|
||||
*/
|
||||
|
||||
/* global window */
|
||||
const globalThis = require('ipfs-utils/src/globalthis')
|
||||
/** @typedef {import('../types').EventEmitterFactory} Events */
|
||||
/** @type Events */
|
||||
const EventEmitter = require('events')
|
||||
@@ -72,9 +74,9 @@ class LatencyMonitor extends EventEmitter {
|
||||
that.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency
|
||||
|
||||
// If process: use high resolution timer
|
||||
if (globalThis.process && globalThis.process.hrtime) { // eslint-disable-line no-undef
|
||||
if (globalThis.process && globalThis.process.hrtime) {
|
||||
debug('Using process.hrtime for timing')
|
||||
that.now = globalThis.process.hrtime // eslint-disable-line no-undef
|
||||
that.now = globalThis.process.hrtime
|
||||
that.getDeltaMS = (startTime) => {
|
||||
const hrtime = that.now(startTime)
|
||||
return (hrtime[0] * 1000) + (hrtime[1] / 1000000)
|
||||
|
@@ -1,16 +1,10 @@
|
||||
'use strict'
|
||||
|
||||
const errCode = require('err-code')
|
||||
const { messages, codes } = require('../errors')
|
||||
const {
|
||||
storeAddresses,
|
||||
uniquePeers,
|
||||
requirePeers,
|
||||
maybeLimitSource
|
||||
} = require('./utils')
|
||||
const { messages, codes } = require('./errors')
|
||||
|
||||
const merge = require('it-merge')
|
||||
const { pipe } = require('it-pipe')
|
||||
const all = require('it-all')
|
||||
const pAny = require('p-any')
|
||||
|
||||
/**
|
||||
* @typedef {import('peer-id')} PeerId
|
||||
@@ -27,21 +21,22 @@ const { pipe } = require('it-pipe')
|
||||
class ContentRouting {
|
||||
/**
|
||||
* @class
|
||||
* @param {import('..')} libp2p
|
||||
* @param {import('./')} libp2p
|
||||
*/
|
||||
constructor (libp2p) {
|
||||
this.libp2p = libp2p
|
||||
this.routers = libp2p._modules.contentRouting || []
|
||||
this.dht = libp2p._dht
|
||||
|
||||
// If we have the dht, add it to the available content routers
|
||||
// If we have the dht, make it first
|
||||
if (this.dht) {
|
||||
this.routers.push(this.dht)
|
||||
this.routers.unshift(this.dht)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over all content routers in parallel to find providers of the given key.
|
||||
* Iterates over all content routers in series to find providers of the given key.
|
||||
* Once a content router succeeds, iteration will stop.
|
||||
*
|
||||
* @param {CID} key - The CID key of the content to find
|
||||
* @param {object} [options]
|
||||
@@ -49,20 +44,25 @@ class ContentRouting {
|
||||
* @param {number} [options.maxNumProviders] - maximum number of providers to find
|
||||
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
|
||||
*/
|
||||
async * findProviders (key, options = {}) {
|
||||
async * findProviders (key, options) {
|
||||
if (!this.routers.length) {
|
||||
throw errCode(new Error('No content this.routers available'), 'NO_ROUTERS_AVAILABLE')
|
||||
}
|
||||
|
||||
yield * pipe(
|
||||
merge(
|
||||
...this.routers.map(router => router.findProviders(key, options))
|
||||
),
|
||||
(source) => storeAddresses(source, this.libp2p.peerStore),
|
||||
(source) => uniquePeers(source),
|
||||
(source) => maybeLimitSource(source, options.maxNumProviders),
|
||||
(source) => requirePeers(source)
|
||||
const result = await pAny(
|
||||
this.routers.map(async (router) => {
|
||||
const provs = await all(router.findProviders(key, options))
|
||||
|
||||
if (!provs || !provs.length) {
|
||||
throw errCode(new Error('not found'), 'NOT_FOUND')
|
||||
}
|
||||
return provs
|
||||
})
|
||||
)
|
||||
|
||||
for (const peer of result) {
|
||||
yield peer
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
@@ -1,89 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const errCode = require('err-code')
|
||||
const filter = require('it-filter')
|
||||
const map = require('it-map')
|
||||
const take = require('it-take')
|
||||
|
||||
/**
|
||||
* @typedef {import('peer-id')} PeerId
|
||||
* @typedef {import('multiaddr')} Multiaddr
|
||||
*/
|
||||
|
||||
/**
|
||||
* Store the multiaddrs from every peer in the passed peer store
|
||||
*
|
||||
* @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source
|
||||
* @param {import('../peer-store')} peerStore
|
||||
*/
|
||||
function storeAddresses (source, peerStore) {
|
||||
return map(source, (peer) => {
|
||||
// ensure we have the addresses for a given peer
|
||||
peerStore.addressBook.add(peer.id, peer.multiaddrs)
|
||||
|
||||
return peer
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter peers by unique peer id
|
||||
*
|
||||
* @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source
|
||||
*/
|
||||
function uniquePeers (source) {
|
||||
/** @type Set<string> */
|
||||
const seen = new Set()
|
||||
|
||||
return filter(source, (peer) => {
|
||||
// dedupe by peer id
|
||||
if (seen.has(peer.id.toString())) {
|
||||
return false
|
||||
}
|
||||
|
||||
seen.add(peer.id.toString())
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Require at least `min` peers to be yielded from `source`
|
||||
*
|
||||
* @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source
|
||||
* @param {number} min
|
||||
*/
|
||||
async function * requirePeers (source, min = 1) {
|
||||
let seen = 0
|
||||
|
||||
for await (const peer of source) {
|
||||
seen++
|
||||
|
||||
yield peer
|
||||
}
|
||||
|
||||
if (seen < min) {
|
||||
throw errCode(new Error('not found'), 'NOT_FOUND')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If `max` is passed, only take that number of peers from the source
|
||||
* otherwise take all the peers
|
||||
*
|
||||
* @param {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>} source
|
||||
* @param {number} [max]
|
||||
*/
|
||||
function maybeLimitSource (source, max) {
|
||||
if (max) {
|
||||
return take(source, max)
|
||||
}
|
||||
|
||||
return source
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
storeAddresses,
|
||||
uniquePeers,
|
||||
requirePeers,
|
||||
maybeLimitSource
|
||||
}
|
@@ -2,7 +2,7 @@
|
||||
|
||||
const errCode = require('err-code')
|
||||
const AbortController = require('abort-controller').default
|
||||
const { anySignal } = require('any-signal')
|
||||
const anySignal = require('any-signal')
|
||||
const FIFO = require('p-fifo')
|
||||
const pAny = require('p-any')
|
||||
|
||||
@@ -67,7 +67,7 @@ class DialRequest {
|
||||
let conn
|
||||
try {
|
||||
const signal = dialAbortControllers[i].signal
|
||||
conn = await this.dialAction(addr, { ...options, signal: options.signal ? anySignal([signal, options.signal]) : signal })
|
||||
conn = await this.dialAction(addr, { ...options, signal: anySignal([signal, options.signal]) })
|
||||
// Remove the successful AbortController so it is not aborted
|
||||
dialAbortControllers.splice(i, 1)
|
||||
} finally {
|
||||
|
@@ -7,7 +7,7 @@ const log = Object.assign(debug('libp2p:dialer'), {
|
||||
const errCode = require('err-code')
|
||||
const multiaddr = require('multiaddr')
|
||||
const TimeoutController = require('timeout-abort-controller')
|
||||
const { anySignal } = require('any-signal')
|
||||
const anySignal = require('any-signal')
|
||||
|
||||
const DialRequest = require('./dial-request')
|
||||
const { publicAddressesFirst } = require('libp2p-utils/src/address-sort')
|
||||
|
16
src/index.js
16
src/index.js
@@ -7,6 +7,7 @@ const log = Object.assign(debug('libp2p'), {
|
||||
/** @typedef {import('./types').EventEmitterFactory} Events */
|
||||
/** @type Events */
|
||||
const EventEmitter = require('events')
|
||||
const globalThis = require('ipfs-utils/src/globalthis')
|
||||
|
||||
const errCode = require('err-code')
|
||||
const PeerId = require('peer-id')
|
||||
@@ -29,6 +30,7 @@ const Upgrader = require('./upgrader')
|
||||
const PeerStore = require('./peer-store')
|
||||
const PubsubAdapter = require('./pubsub-adapter')
|
||||
const PersistentPeerStore = require('./peer-store/persistent')
|
||||
const Rendezvous = require('./rendezvous')
|
||||
const Registrar = require('./registrar')
|
||||
const ping = require('./ping')
|
||||
const IdentifyService = require('./identify')
|
||||
@@ -242,7 +244,7 @@ class Libp2p extends EventEmitter {
|
||||
// Attach private network protector
|
||||
if (this._modules.connProtector) {
|
||||
this.upgrader.protector = this._modules.connProtector
|
||||
} else if (globalThis.process !== undefined && globalThis.process.env && globalThis.process.env.LIBP2P_FORCE_PNET) { // eslint-disable-line no-undef
|
||||
} else if (globalThis.process !== undefined && globalThis.process.env && globalThis.process.env.LIBP2P_FORCE_PNET) {
|
||||
throw new Error('Private network is enforced, but no protector was provided')
|
||||
}
|
||||
|
||||
@@ -268,6 +270,14 @@ class Libp2p extends EventEmitter {
|
||||
this.pubsub = PubsubAdapter(Pubsub, this, this._config.pubsub)
|
||||
}
|
||||
|
||||
// Create rendezvous client if enabled
|
||||
if (this._options.rendezvous.enabled) {
|
||||
this.rendezvous = new Rendezvous({
|
||||
libp2p: this,
|
||||
rendezvousPoints: this._options.rendezvous.rendezvousPoints
|
||||
})
|
||||
}
|
||||
|
||||
// Attach remaining APIs
|
||||
// peer and content routing will automatically get modules from _modules and _dht
|
||||
this.peerRouting = new PeerRouting(this)
|
||||
@@ -330,6 +340,7 @@ class Libp2p extends EventEmitter {
|
||||
try {
|
||||
this._isStarted = false
|
||||
|
||||
this.rendezvous && this.rendezvous.start()
|
||||
this.relay && this.relay.stop()
|
||||
this.peerRouting.stop()
|
||||
|
||||
@@ -583,6 +594,9 @@ class Libp2p extends EventEmitter {
|
||||
// Peer discovery
|
||||
await this._setupPeerDiscovery()
|
||||
|
||||
// Rendezvous
|
||||
this.rendezvous && this.rendezvous.start()
|
||||
|
||||
// Relay
|
||||
this.relay && this.relay.start()
|
||||
|
||||
|
@@ -4,9 +4,10 @@
|
||||
const sanitize = require('sanitize-filename')
|
||||
const mergeOptions = require('merge-options')
|
||||
const crypto = require('libp2p-crypto')
|
||||
const { Key } = require('interface-datastore')
|
||||
const Datastore = require('interface-datastore')
|
||||
const CMS = require('./cms')
|
||||
const errcode = require('err-code')
|
||||
const { Number } = require('ipfs-utils/src/globalthis')
|
||||
const uint8ArrayToString = require('uint8arrays/to-string')
|
||||
const uint8ArrayFromString = require('uint8arrays/from-string')
|
||||
|
||||
@@ -14,7 +15,7 @@ require('node-forge/lib/sha512')
|
||||
|
||||
/**
|
||||
* @typedef {import('peer-id')} PeerId
|
||||
* @typedef {import('interface-datastore/src/types').Datastore} Datastore
|
||||
* @typedef {import('interface-datastore/src/key')} Key
|
||||
*/
|
||||
|
||||
const keyPrefix = '/pkcs8/'
|
||||
@@ -71,7 +72,7 @@ async function throwDelayed (err) {
|
||||
* @private
|
||||
*/
|
||||
function DsName (name) {
|
||||
return new Key(keyPrefix + name)
|
||||
return new Datastore.Key(keyPrefix + name)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,7 +83,7 @@ function DsName (name) {
|
||||
* @private
|
||||
*/
|
||||
function DsInfoName (name) {
|
||||
return new Key(infoPrefix + name)
|
||||
return new Datastore.Key(infoPrefix + name)
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -5,24 +5,16 @@ const log = Object.assign(debug('libp2p:peer-routing'), {
|
||||
error: debug('libp2p:peer-routing:err')
|
||||
})
|
||||
const errCode = require('err-code')
|
||||
const {
|
||||
storeAddresses,
|
||||
uniquePeers,
|
||||
requirePeers
|
||||
} = require('./content-routing/utils')
|
||||
|
||||
const merge = require('it-merge')
|
||||
const { pipe } = require('it-pipe')
|
||||
const first = require('it-first')
|
||||
const drain = require('it-drain')
|
||||
const filter = require('it-filter')
|
||||
const all = require('it-all')
|
||||
const pAny = require('p-any')
|
||||
const {
|
||||
setDelayedInterval,
|
||||
clearDelayedInterval
|
||||
} = require('set-delayed-interval')
|
||||
const PeerId = require('peer-id')
|
||||
|
||||
/**
|
||||
* @typedef {import('peer-id')} PeerId
|
||||
* @typedef {import('multiaddr')} Multiaddr
|
||||
*/
|
||||
class PeerRouting {
|
||||
@@ -35,9 +27,9 @@ class PeerRouting {
|
||||
this._peerStore = libp2p.peerStore
|
||||
this._routers = libp2p._modules.peerRouting || []
|
||||
|
||||
// If we have the dht, add it to the available peer routers
|
||||
// If we have the dht, make it first
|
||||
if (libp2p._dht) {
|
||||
this._routers.push(libp2p._dht)
|
||||
this._routers.unshift(libp2p._dht)
|
||||
}
|
||||
|
||||
this._refreshManagerOptions = libp2p._options.peerRouting.refreshManager
|
||||
@@ -63,8 +55,9 @@ class PeerRouting {
|
||||
*/
|
||||
async _findClosestPeersTask () {
|
||||
try {
|
||||
// nb getClosestPeers adds the addresses to the address book
|
||||
await drain(this.getClosestPeers(this._peerId.id))
|
||||
for await (const { id, multiaddrs } of this.getClosestPeers(this._peerId.id)) {
|
||||
this._peerStore.addressBook.add(id, multiaddrs)
|
||||
}
|
||||
} catch (err) {
|
||||
log.error(err)
|
||||
}
|
||||
@@ -78,7 +71,7 @@ class PeerRouting {
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over all peer routers in parallel to find the given peer.
|
||||
* Iterates over all peer routers in series to find the given peer.
|
||||
*
|
||||
* @param {PeerId} id - The id of the peer to find
|
||||
* @param {object} [options]
|
||||
@@ -90,20 +83,16 @@ class PeerRouting {
|
||||
throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
|
||||
}
|
||||
|
||||
const output = await pipe(
|
||||
merge(
|
||||
...this._routers.map(router => [router.findPeer(id, options)])
|
||||
),
|
||||
(source) => filter(source, Boolean),
|
||||
(source) => storeAddresses(source, this._peerStore),
|
||||
(source) => first(source)
|
||||
)
|
||||
return pAny(this._routers.map(async (router) => {
|
||||
const result = await router.findPeer(id, options)
|
||||
|
||||
if (output) {
|
||||
return output
|
||||
}
|
||||
// If we don't have a result, we need to provide an error to keep trying
|
||||
if (!result || Object.keys(result).length === 0) {
|
||||
throw errCode(new Error('not found'), 'NOT_FOUND')
|
||||
}
|
||||
|
||||
throw errCode(new Error('not found'), 'NOT_FOUND')
|
||||
return result
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,14 +108,20 @@ class PeerRouting {
|
||||
throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
|
||||
}
|
||||
|
||||
yield * pipe(
|
||||
merge(
|
||||
...this._routers.map(router => router.getClosestPeers(key, options))
|
||||
),
|
||||
(source) => storeAddresses(source, this._peerStore),
|
||||
(source) => uniquePeers(source),
|
||||
(source) => requirePeers(source)
|
||||
const result = await pAny(
|
||||
this._routers.map(async (router) => {
|
||||
const peers = await all(router.getClosestPeers(key, options))
|
||||
|
||||
if (!peers || !peers.length) {
|
||||
throw errCode(new Error('not found'), 'NOT_FOUND')
|
||||
}
|
||||
return peers
|
||||
})
|
||||
)
|
||||
|
||||
for (const peer of result) {
|
||||
yield peer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -63,10 +63,9 @@ module.exports.decodeV1PSK = (pskBuffer) => {
|
||||
const metadata = uint8ArrayToString(pskBuffer).split(/(?:\r\n|\r|\n)/g)
|
||||
const pskTag = metadata.shift()
|
||||
const codec = metadata.shift()
|
||||
const pskString = metadata.shift()
|
||||
const psk = pskString && uint8ArrayFromString(pskString, 'base16')
|
||||
const psk = uint8ArrayFromString(metadata.shift(), 'base16')
|
||||
|
||||
if (!psk || psk.byteLength !== KEY_LENGTH) {
|
||||
if (psk.byteLength !== KEY_LENGTH) {
|
||||
throw new Error(Errors.INVALID_PSK)
|
||||
}
|
||||
|
||||
|
32
src/rendezvous/README.md
Normal file
32
src/rendezvous/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Rendezvous Protocol in js-libp2p
|
||||
|
||||
The rendezvous protocol can be used in different contexts across libp2p. For using it, the libp2p network needs to have well known libp2p nodes acting as rendezvous servers. These nodes will have an extra role in the network. They will collect and maintain a list of registrations per rendezvous namespace. Other peers in the network will act as rendezvous clients and will register themselves on given namespaces by messaging a rendezvous server node. Taking into account these registrations, a rendezvous client is able to discover other peers in a given namespace by querying a server. A registration should have a `ttl`, in order to avoid having invalid registrations.
|
||||
|
||||
An example of a namespace could be a relay namespace, so that undialable nodes can register themselves as reachable through that relay.
|
||||
|
||||
## Usage
|
||||
|
||||
`js-libp2p` supports the usage of the rendezvous protocol through its configuration. It allows the rendezvous protocol to be enabled and customized. You will need to setup a rendezvous server, which will be used by rendezvous client nodes. You can see how to setup a rendezvous server in [libp2p/js-libp2p-rendezvous](https://github.com/libp2p/js-libp2p-rendezvous)
|
||||
|
||||
You can configure it through libp2p as follows:
|
||||
|
||||
```js
|
||||
const Libp2p = require('libp2p')
|
||||
const node = await Libp2p.create({
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: ['/dnsaddr/rendezvous.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJP']
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Libp2p Flow
|
||||
|
||||
Every time a rendezvous operation is performed through libpsp's API, libp2p will attempt to connect to the given rendezvous servers and exchange the appropriate rendezvous protocol per the [spec](https://github.com/libp2p/specs/tree/master/rendezvous).
|
||||
|
||||
## Future Work
|
||||
|
||||
- Libp2p can handle re-registers when properly configured
|
||||
- Libp2p automatically unregisters previously registered namespaces on stop.
|
||||
- Rendezvous client should be able to register namespaces given in configuration on startup
|
||||
- Not supported at the moment, as we would need to deal with re-register over time
|
6
src/rendezvous/constants.js
Normal file
6
src/rendezvous/constants.js
Normal file
@@ -0,0 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = {
|
||||
PROTOCOL_MULTICODEC: '/rendezvous/1.0.0',
|
||||
MAX_DISCOVER_LIMIT: 50
|
||||
}
|
6
src/rendezvous/errors.js
Normal file
6
src/rendezvous/errors.js
Normal file
@@ -0,0 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
exports.codes = {
|
||||
INVALID_NAMESPACE: 'ERR_INVALID_NAMESPACE',
|
||||
NO_CONNECTED_RENDEZVOUS_SERVERS: 'ERR_NO_CONNECTED_RENDEZVOUS_SERVERS'
|
||||
}
|
304
src/rendezvous/index.js
Normal file
304
src/rendezvous/index.js
Normal file
@@ -0,0 +1,304 @@
|
||||
'use strict'
|
||||
|
||||
const debug = require('debug')
|
||||
const log = Object.assign(debug('libp2p:rendezvous'), {
|
||||
error: debug('libp2p:rendezvous:err')
|
||||
})
|
||||
|
||||
const errCode = require('err-code')
|
||||
const { pipe } = require('it-pipe')
|
||||
const lp = require('it-length-prefixed')
|
||||
const { collect } = require('streaming-iterables')
|
||||
const { toBuffer } = require('it-buffer')
|
||||
const fromString = require('uint8arrays/from-string')
|
||||
const toString = require('uint8arrays/to-string')
|
||||
|
||||
const { codes: errCodes } = require('./errors')
|
||||
const {
|
||||
MAX_DISCOVER_LIMIT,
|
||||
PROTOCOL_MULTICODEC
|
||||
} = require('./constants')
|
||||
// @ts-ignore TODO: needs release for types
|
||||
const { Message } = require('libp2p-rendezvous/src/proto')
|
||||
const MESSAGE_TYPE = Message.MessageType
|
||||
|
||||
/**
|
||||
* @typedef {import('..')} Libp2p
|
||||
* @typedef {import('multiaddr')} Multiaddr
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} RendezvousProperties
|
||||
* @property {Libp2p} libp2p
|
||||
*
|
||||
* @typedef {Object} RendezvousOptions
|
||||
* @property {Multiaddr[]} rendezvousPoints
|
||||
*/
|
||||
|
||||
class Rendezvous {
|
||||
/**
|
||||
* Libp2p Rendezvous. A lightweight mechanism for generalized peer discovery.
|
||||
*
|
||||
* @class
|
||||
* @param {RendezvousProperties & RendezvousOptions} params
|
||||
*/
|
||||
constructor ({ libp2p, rendezvousPoints }) {
|
||||
this._libp2p = libp2p
|
||||
this._peerId = libp2p.peerId
|
||||
this._peerStore = libp2p.peerStore
|
||||
this._connectionManager = libp2p.connectionManager
|
||||
this._rendezvousPoints = rendezvousPoints
|
||||
|
||||
this._isStarted = false
|
||||
|
||||
/**
|
||||
* Map namespaces to a map of rendezvous point identifier to cookie.
|
||||
*
|
||||
* @type {Map<string, Map<string, string>>}
|
||||
*/
|
||||
this._cookies = new Map()
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the rendezvous client in the libp2p node.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
start () {
|
||||
if (this._isStarted) {
|
||||
return
|
||||
}
|
||||
|
||||
this._isStarted = true
|
||||
log('started')
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the rendezvous state and unregister from namespaces.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
stop () {
|
||||
if (!this._isStarted) {
|
||||
return
|
||||
}
|
||||
|
||||
this._isStarted = false
|
||||
this._cookies.clear()
|
||||
log('stopped')
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the peer in a given namespace
|
||||
*
|
||||
* @param {string} ns
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.ttl = 7.2e6] - registration ttl in ms
|
||||
* @returns {Promise<number>} rendezvous register ttl.
|
||||
*/
|
||||
async register (ns, { ttl = 7.2e6 } = {}) {
|
||||
if (!ns) {
|
||||
throw errCode(new Error('a namespace must be provided'), errCodes.INVALID_NAMESPACE)
|
||||
}
|
||||
|
||||
// Are there available rendezvous servers?
|
||||
if (!this._rendezvousPoints || !this._rendezvousPoints.length) {
|
||||
throw errCode(new Error('no rendezvous servers connected'), errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
}
|
||||
|
||||
const message = Message.encode({
|
||||
type: MESSAGE_TYPE.REGISTER,
|
||||
register: {
|
||||
signedPeerRecord: this._libp2p.peerStore.addressBook.getRawEnvelope(this._peerId),
|
||||
ns,
|
||||
ttl: ttl * 1e-3 // Convert to seconds
|
||||
}
|
||||
})
|
||||
|
||||
const registerTasks = []
|
||||
|
||||
/**
|
||||
* @param {Multiaddr} m
|
||||
* @returns {Promise<number>}
|
||||
*/
|
||||
const taskFn = async (m) => {
|
||||
const connection = await this._libp2p.dial(m)
|
||||
const { stream } = await connection.newStream(PROTOCOL_MULTICODEC)
|
||||
|
||||
const [response] = await pipe(
|
||||
[message],
|
||||
lp.encode(),
|
||||
stream,
|
||||
lp.decode(),
|
||||
toBuffer,
|
||||
collect
|
||||
)
|
||||
|
||||
// Close connection if not any other open streams
|
||||
if (!connection.streams.length) {
|
||||
await connection.close()
|
||||
}
|
||||
|
||||
const recMessage = Message.decode(response)
|
||||
|
||||
if (!recMessage.type === MESSAGE_TYPE.REGISTER_RESPONSE) {
|
||||
throw new Error('unexpected message received')
|
||||
}
|
||||
|
||||
if (recMessage.registerResponse.status !== Message.ResponseStatus.OK) {
|
||||
throw errCode(new Error(recMessage.registerResponse.statusText), recMessage.registerResponse.status)
|
||||
}
|
||||
|
||||
return recMessage.registerResponse.ttl * 1e3 // convert to ms
|
||||
}
|
||||
|
||||
for (const m of this._rendezvousPoints) {
|
||||
registerTasks.push(taskFn(m))
|
||||
}
|
||||
|
||||
// Return first ttl
|
||||
// TODO: consider pAny instead of Promise.all?
|
||||
const [returnTtl] = await Promise.all(registerTasks)
|
||||
|
||||
return returnTtl
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister peer from the nampesapce.
|
||||
*
|
||||
* @param {string} ns
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async unregister (ns) {
|
||||
if (!ns) {
|
||||
throw errCode(new Error('a namespace must be provided'), errCodes.INVALID_NAMESPACE)
|
||||
}
|
||||
|
||||
// Are there available rendezvous servers?
|
||||
if (!this._rendezvousPoints || !this._rendezvousPoints.length) {
|
||||
throw errCode(new Error('no rendezvous servers connected'), errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
}
|
||||
|
||||
const message = Message.encode({
|
||||
type: MESSAGE_TYPE.UNREGISTER,
|
||||
unregister: {
|
||||
id: this._peerId.toBytes(),
|
||||
ns
|
||||
}
|
||||
})
|
||||
|
||||
const unregisterTasks = []
|
||||
/**
|
||||
* @param {Multiaddr} m
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const taskFn = async (m) => {
|
||||
const connection = await this._libp2p.dial(m)
|
||||
const { stream } = await connection.newStream(PROTOCOL_MULTICODEC)
|
||||
|
||||
await pipe(
|
||||
[message],
|
||||
lp.encode(),
|
||||
stream,
|
||||
async (source) => {
|
||||
for await (const _ of source) { } // eslint-disable-line
|
||||
}
|
||||
)
|
||||
|
||||
// Close connection if not any other open streams
|
||||
if (!connection.streams.length) {
|
||||
await connection.close()
|
||||
}
|
||||
}
|
||||
|
||||
for (const m of this._rendezvousPoints) {
|
||||
unregisterTasks.push(taskFn(m))
|
||||
}
|
||||
|
||||
await Promise.all(unregisterTasks)
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover peers registered under a given namespace
|
||||
*
|
||||
* @param {string} ns
|
||||
* @param {number} [limit = MAX_DISCOVER_LIMIT]
|
||||
* @returns {AsyncIterable<{ signedPeerRecord: Uint8Array, ns: string, ttl: number }>}
|
||||
*/
|
||||
async * discover (ns, limit = MAX_DISCOVER_LIMIT) {
|
||||
// TODO: consider opening the envelope in the dicover
|
||||
// This would store the addresses in the AddressBook
|
||||
|
||||
// Are there available rendezvous servers?
|
||||
if (!this._rendezvousPoints || !this._rendezvousPoints.length) {
|
||||
throw errCode(new Error('no rendezvous servers connected'), errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
}
|
||||
|
||||
const registrationTransformer = (r) => ({
|
||||
signedPeerRecord: r.signedPeerRecord,
|
||||
ns: r.ns,
|
||||
ttl: r.ttl * 1e3 // convert to ms
|
||||
})
|
||||
|
||||
// Iterate over all rendezvous points
|
||||
for (const m of this._rendezvousPoints) {
|
||||
const namespaseCookies = this._cookies.get(ns) || new Map()
|
||||
|
||||
// Check if we have a cookie and encode discover message
|
||||
const cookie = namespaseCookies.get(m.toString())
|
||||
const message = Message.encode({
|
||||
type: MESSAGE_TYPE.DISCOVER,
|
||||
discover: {
|
||||
ns,
|
||||
limit,
|
||||
cookie: cookie ? fromString(cookie) : undefined
|
||||
}
|
||||
})
|
||||
|
||||
// Send discover message and wait for response
|
||||
const connection = await this._libp2p.dial(m)
|
||||
const { stream } = await connection.newStream(PROTOCOL_MULTICODEC)
|
||||
const [response] = await pipe(
|
||||
[message],
|
||||
lp.encode(),
|
||||
stream,
|
||||
lp.decode(),
|
||||
toBuffer,
|
||||
collect
|
||||
)
|
||||
|
||||
if (!connection.streams.length) {
|
||||
await connection.close()
|
||||
}
|
||||
|
||||
const recMessage = Message.decode(response)
|
||||
|
||||
if (!recMessage.type === MESSAGE_TYPE.DISCOVER_RESPONSE) {
|
||||
throw new Error('unexpected message received')
|
||||
} else if (recMessage.discoverResponse.status !== Message.ResponseStatus.OK) {
|
||||
throw errCode(new Error(recMessage.discoverResponse.statusText), recMessage.discoverResponse.status)
|
||||
}
|
||||
|
||||
// Iterate over registrations response
|
||||
for (const r of recMessage.discoverResponse.registrations) {
|
||||
// track registrations
|
||||
yield registrationTransformer(r)
|
||||
|
||||
limit--
|
||||
if (limit === 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Store cookie
|
||||
const c = recMessage.discoverResponse.cookie
|
||||
if (c && c.length) {
|
||||
const nsCookies = this._cookies.get(ns) || new Map()
|
||||
nsCookies.set(m.toString(), toString(c))
|
||||
this._cookies.set(ns, nsCookies)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Rendezvous
|
@@ -3,7 +3,6 @@
|
||||
|
||||
const { expect } = require('aegir/utils/chai')
|
||||
const sinon = require('sinon')
|
||||
const { CLOSED } = require('libp2p-interfaces/src/connection/status')
|
||||
|
||||
const delay = require('delay')
|
||||
const pWaitFor = require('p-wait-for')
|
||||
@@ -269,40 +268,5 @@ describe('libp2p.connections', () => {
|
||||
|
||||
await libp2p.stop()
|
||||
})
|
||||
|
||||
it('should be closed status once immediately stopping', async () => {
|
||||
const [libp2p] = await peerUtils.createPeer({
|
||||
config: {
|
||||
peerId: peerIds[0],
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/15003/ws']
|
||||
},
|
||||
modules: baseOptions.modules
|
||||
}
|
||||
})
|
||||
const [remoteLibp2p] = await peerUtils.createPeer({
|
||||
config: {
|
||||
peerId: peerIds[1],
|
||||
addresses: {
|
||||
listen: ['/ip4/127.0.0.1/tcp/15004/ws']
|
||||
},
|
||||
modules: baseOptions.modules
|
||||
}
|
||||
})
|
||||
|
||||
libp2p.peerStore.addressBook.set(remoteLibp2p.peerId, remoteLibp2p.multiaddrs)
|
||||
await libp2p.dial(remoteLibp2p.peerId)
|
||||
|
||||
const totalConns = Array.from(libp2p.connections.values())
|
||||
expect(totalConns.length).to.eql(1)
|
||||
const conns = totalConns[0]
|
||||
expect(conns.length).to.eql(1)
|
||||
const conn = conns[0]
|
||||
|
||||
await libp2p.stop()
|
||||
expect(conn.stat.status).to.eql(CLOSED)
|
||||
|
||||
await remoteLibp2p.stop()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
@@ -12,8 +12,6 @@ const CID = require('cids')
|
||||
const ipfsHttpClient = require('ipfs-http-client')
|
||||
const DelegatedContentRouter = require('libp2p-delegated-content-routing')
|
||||
const multiaddr = require('multiaddr')
|
||||
const drain = require('it-drain')
|
||||
const all = require('it-all')
|
||||
|
||||
const peerUtils = require('../utils/creators/peer')
|
||||
const { baseOptions, routingOptions } = require('./utils')
|
||||
@@ -80,14 +78,10 @@ describe('content-routing', () => {
|
||||
|
||||
it('should use the nodes dht to find providers', async () => {
|
||||
const deferred = pDefer()
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
sinon.stub(nodes[0]._dht, 'findProviders').callsFake(function * () {
|
||||
deferred.resolve()
|
||||
yield {
|
||||
id: providerPeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
yield
|
||||
})
|
||||
|
||||
await nodes[0].contentRouting.findProviders().next()
|
||||
@@ -144,14 +138,10 @@ describe('content-routing', () => {
|
||||
|
||||
it('should use the delegate router to find providers', async () => {
|
||||
const deferred = pDefer()
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
sinon.stub(delegate, 'findProviders').callsFake(function * () {
|
||||
deferred.resolve()
|
||||
yield {
|
||||
id: providerPeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
yield
|
||||
})
|
||||
|
||||
await node.contentRouting.findProviders().next()
|
||||
@@ -161,36 +151,25 @@ describe('content-routing', () => {
|
||||
|
||||
it('should be able to register as a provider', async () => {
|
||||
const cid = new CID('QmU621oD8AhHw6t25vVyfYKmL9VV3PTgc52FngEhTGACFB')
|
||||
const provider = 'QmZNgCqZCvTsi3B4Vt7gsSqpkqDpE7M2Y9TDmEhbDb4ceF'
|
||||
|
||||
const mockBlockApi = nock('http://0.0.0.0:60197')
|
||||
// mock the block/stat call
|
||||
.post('/api/v0/block/stat')
|
||||
const mockApi = nock('http://0.0.0.0:60197')
|
||||
// mock the refs call
|
||||
.post('/api/v0/refs')
|
||||
.query(true)
|
||||
.reply(200, '{"Key":"QmU621oD8AhHw6t25vVyfYKmL9VV3PTgc52FngEhTGACFB","Size":"2169"}', [
|
||||
'Content-Type', 'application/json',
|
||||
'X-Chunked-Output', '1'
|
||||
])
|
||||
const mockDhtApi = nock('http://0.0.0.0:60197')
|
||||
// mock the dht/provide call
|
||||
.post('/api/v0/dht/provide')
|
||||
.query(true)
|
||||
.reply(200, `{"Extra":"","ID":"QmWKqWXCtRXEeCQTo3FoZ7g4AfnGiauYYiczvNxFCHicbB","Responses":[{"Addrs":["/ip4/0.0.0.0/tcp/0"],"ID":"${provider}"}],"Type":4}\n`, [
|
||||
.reply(200, null, [
|
||||
'Content-Type', 'application/json',
|
||||
'X-Chunked-Output', '1'
|
||||
])
|
||||
|
||||
await node.contentRouting.provide(cid)
|
||||
|
||||
expect(mockBlockApi.isDone()).to.equal(true)
|
||||
expect(mockDhtApi.isDone()).to.equal(true)
|
||||
expect(mockApi.isDone()).to.equal(true)
|
||||
})
|
||||
|
||||
it('should handle errors when registering as a provider', async () => {
|
||||
const cid = new CID('QmU621oD8AhHw6t25vVyfYKmL9VV3PTgc52FngEhTGACFB')
|
||||
const mockApi = nock('http://0.0.0.0:60197')
|
||||
// mock the block/stat call
|
||||
.post('/api/v0/block/stat')
|
||||
// mock the refs call
|
||||
.post('/api/v0/refs')
|
||||
.query(true)
|
||||
.reply(502, 'Bad Gateway', ['Content-Type', 'application/json'])
|
||||
|
||||
@@ -272,110 +251,6 @@ describe('content-routing', () => {
|
||||
|
||||
afterEach(() => node.stop())
|
||||
|
||||
it('should store the multiaddrs of a peer', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const result = {
|
||||
id: providerPeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/49320')
|
||||
]
|
||||
}
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(function * () {})
|
||||
sinon.stub(delegate, 'findProviders').callsFake(function * () {
|
||||
yield result
|
||||
})
|
||||
|
||||
expect(node.peerStore.addressBook.get(providerPeerId)).to.not.be.ok()
|
||||
|
||||
await drain(node.contentRouting.findProviders('a cid'))
|
||||
|
||||
expect(node.peerStore.addressBook.get(providerPeerId)).to.deep.include({
|
||||
isCertified: false,
|
||||
multiaddr: result.multiaddrs[0]
|
||||
})
|
||||
})
|
||||
|
||||
it('should not wait for routing findProviders to finish before returning results', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const result = {
|
||||
id: providerPeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/49320')
|
||||
]
|
||||
}
|
||||
|
||||
const defer = pDefer()
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(async function * () { // eslint-disable-line require-yield
|
||||
await defer.promise
|
||||
})
|
||||
sinon.stub(delegate, 'findProviders').callsFake(async function * () {
|
||||
yield result
|
||||
|
||||
await defer.promise
|
||||
})
|
||||
|
||||
for await (const provider of node.contentRouting.findProviders('a cid')) {
|
||||
expect(provider.id).to.deep.equal(providerPeerId)
|
||||
defer.resolve()
|
||||
}
|
||||
})
|
||||
|
||||
it('should dedupe results', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const result = {
|
||||
id: providerPeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/49320')
|
||||
]
|
||||
}
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(async function * () {
|
||||
yield result
|
||||
})
|
||||
sinon.stub(delegate, 'findProviders').callsFake(async function * () {
|
||||
yield result
|
||||
})
|
||||
|
||||
const results = await all(node.contentRouting.findProviders('a cid'))
|
||||
|
||||
expect(results).to.be.an('array').with.lengthOf(1).that.deep.equals([result])
|
||||
})
|
||||
|
||||
it('should combine multiaddrs when different addresses are returned by different content routers', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const result1 = {
|
||||
id: providerPeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/49320')
|
||||
]
|
||||
}
|
||||
const result2 = {
|
||||
id: providerPeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/213.213.213.213/tcp/2344')
|
||||
]
|
||||
}
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(async function * () {
|
||||
yield result1
|
||||
})
|
||||
sinon.stub(delegate, 'findProviders').callsFake(async function * () {
|
||||
yield result2
|
||||
})
|
||||
|
||||
await drain(node.contentRouting.findProviders('a cid'))
|
||||
|
||||
expect(node.peerStore.addressBook.get(providerPeerId)).to.deep.include({
|
||||
isCertified: false,
|
||||
multiaddr: result1.multiaddrs[0]
|
||||
}).and.to.deep.include({
|
||||
isCertified: false,
|
||||
multiaddr: result2.multiaddrs[0]
|
||||
})
|
||||
})
|
||||
|
||||
it('should use both the dht and delegate router to provide', async () => {
|
||||
const dhtDeferred = pDefer()
|
||||
const delegatedDeferred = pDefer()
|
||||
@@ -396,18 +271,15 @@ describe('content-routing', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('should use the dht if the delegate fails to find providers', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = [{
|
||||
id: providerPeerId,
|
||||
multiaddrs: []
|
||||
}]
|
||||
it('should only use the dht if it finds providers', async () => {
|
||||
const results = [true]
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(function * () {
|
||||
yield results[0]
|
||||
})
|
||||
|
||||
sinon.stub(delegate, 'findProviders').callsFake(function * () { // eslint-disable-line require-yield
|
||||
throw new Error('the delegate should not have been called')
|
||||
})
|
||||
|
||||
const providers = []
|
||||
@@ -420,11 +292,7 @@ describe('content-routing', () => {
|
||||
})
|
||||
|
||||
it('should use the delegate if the dht fails to find providers', async () => {
|
||||
const [providerPeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = [{
|
||||
id: providerPeerId,
|
||||
multiaddrs: []
|
||||
}]
|
||||
const results = [true]
|
||||
|
||||
sinon.stub(node._dht, 'findProviders').callsFake(function * () {})
|
||||
|
||||
|
@@ -10,8 +10,6 @@ const delay = require('delay')
|
||||
const pDefer = require('p-defer')
|
||||
const pWaitFor = require('p-wait-for')
|
||||
const mergeOptions = require('merge-options')
|
||||
const drain = require('it-drain')
|
||||
const all = require('it-all')
|
||||
|
||||
const ipfsHttpClient = require('ipfs-http-client')
|
||||
const DelegatedPeerRouter = require('libp2p-delegated-peer-routing')
|
||||
@@ -84,14 +82,10 @@ describe('peer-routing', () => {
|
||||
|
||||
it('should use the nodes dht to get the closest peers', async () => {
|
||||
const deferred = pDefer()
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
sinon.stub(nodes[0]._dht, 'getClosestPeers').callsFake(function * () {
|
||||
deferred.resolve()
|
||||
yield {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
yield
|
||||
})
|
||||
|
||||
await nodes[0].peerRouting.getClosestPeers().next()
|
||||
@@ -134,14 +128,10 @@ describe('peer-routing', () => {
|
||||
|
||||
it('should use the delegate router to find peers', async () => {
|
||||
const deferred = pDefer()
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
deferred.resolve()
|
||||
return {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
return 'fake peer-id'
|
||||
})
|
||||
|
||||
await node.peerRouting.findPeer()
|
||||
@@ -150,14 +140,10 @@ describe('peer-routing', () => {
|
||||
|
||||
it('should use the delegate router to get the closest peers', async () => {
|
||||
const deferred = pDefer()
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
sinon.stub(delegate, 'getClosestPeers').callsFake(function * () {
|
||||
deferred.resolve()
|
||||
yield {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
yield
|
||||
})
|
||||
|
||||
await node.peerRouting.getClosestPeers().next()
|
||||
@@ -166,7 +152,7 @@ describe('peer-routing', () => {
|
||||
})
|
||||
|
||||
it('should be able to find a peer', async () => {
|
||||
const peerKey = PeerId.createFromB58String('QmTp9VkYvnHyrqKQuFPiuZkiX9gPcqj6x5LJ1rmWuSySnL')
|
||||
const peerKey = 'QmTp9VkYvnHyrqKQuFPiuZkiX9gPcqj6x5LJ1rmWuSySnL'
|
||||
const mockApi = nock('http://0.0.0.0:60197')
|
||||
.post('/api/v0/dht/findpeer')
|
||||
.query(true)
|
||||
@@ -291,93 +277,55 @@ describe('peer-routing', () => {
|
||||
|
||||
afterEach(() => node.stop())
|
||||
|
||||
it('should only use the dht if it finds the peer', async () => {
|
||||
const dhtDeferred = pDefer()
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(() => {
|
||||
dhtDeferred.resolve()
|
||||
return { id: node.peerId }
|
||||
})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
throw new Error('the delegate should not have been called')
|
||||
})
|
||||
|
||||
await node.peerRouting.findPeer('a peer id')
|
||||
await dhtDeferred.promise
|
||||
})
|
||||
|
||||
it('should use the delegate if the dht fails to find the peer', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
const results = [true]
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(() => {})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
return results
|
||||
})
|
||||
|
||||
const peer = await node.peerRouting.findPeer(remotePeerId)
|
||||
const peer = await node.peerRouting.findPeer('a peer id')
|
||||
expect(peer).to.eql(results)
|
||||
})
|
||||
|
||||
it('should not wait for the dht to return if the delegate does first', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
it('should only use the dht if it gets the closest peers', async () => {
|
||||
const results = [true]
|
||||
|
||||
sinon.stub(node._dht, 'getClosestPeers').callsFake(function * () {
|
||||
yield results[0]
|
||||
})
|
||||
|
||||
sinon.stub(delegate, 'getClosestPeers').callsFake(function * () { // eslint-disable-line require-yield
|
||||
throw new Error('the delegate should not have been called')
|
||||
})
|
||||
|
||||
const closest = []
|
||||
for await (const peer of node.peerRouting.getClosestPeers('a cid')) {
|
||||
closest.push(peer)
|
||||
}
|
||||
|
||||
const defer = pDefer()
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(async () => {
|
||||
await defer.promise
|
||||
})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
return results
|
||||
})
|
||||
|
||||
const peer = await node.peerRouting.findPeer(remotePeerId)
|
||||
expect(peer).to.eql(results)
|
||||
|
||||
defer.resolve()
|
||||
})
|
||||
|
||||
it('should not wait for the delegate to return if the dht does first', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = {
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}
|
||||
|
||||
const defer = pDefer()
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(() => {
|
||||
return results
|
||||
})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(async () => {
|
||||
await defer.promise
|
||||
})
|
||||
|
||||
const peer = await node.peerRouting.findPeer(remotePeerId)
|
||||
expect(peer).to.eql(results)
|
||||
|
||||
defer.resolve()
|
||||
})
|
||||
|
||||
it('should store the addresses of the found peer', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = {
|
||||
id: remotePeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/38982')
|
||||
]
|
||||
}
|
||||
|
||||
const spy = sinon.spy(node.peerStore.addressBook, 'add')
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(() => {
|
||||
return results
|
||||
})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {})
|
||||
|
||||
await node.peerRouting.findPeer(remotePeerId)
|
||||
|
||||
expect(spy.calledWith(results.id, results.multiaddrs)).to.be.true()
|
||||
expect(closest).to.have.length.above(0)
|
||||
expect(closest).to.eql(results)
|
||||
})
|
||||
|
||||
it('should use the delegate if the dht fails to get the closest peer', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = [{
|
||||
id: remotePeerId,
|
||||
multiaddrs: []
|
||||
}]
|
||||
const results = [true]
|
||||
|
||||
sinon.stub(node._dht, 'getClosestPeers').callsFake(function * () { })
|
||||
|
||||
@@ -385,55 +333,14 @@ describe('peer-routing', () => {
|
||||
yield results[0]
|
||||
})
|
||||
|
||||
const closest = await all(node.peerRouting.getClosestPeers('a cid'))
|
||||
const closest = []
|
||||
for await (const peer of node.peerRouting.getClosestPeers('a cid')) {
|
||||
closest.push(peer)
|
||||
}
|
||||
|
||||
expect(closest).to.have.length.above(0)
|
||||
expect(closest).to.eql(results)
|
||||
})
|
||||
|
||||
it('should store the addresses of the closest peer', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const result = {
|
||||
id: remotePeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/38982')
|
||||
]
|
||||
}
|
||||
|
||||
const spy = sinon.spy(node.peerStore.addressBook, 'add')
|
||||
|
||||
sinon.stub(node._dht, 'getClosestPeers').callsFake(function * () { })
|
||||
|
||||
sinon.stub(delegate, 'getClosestPeers').callsFake(function * () {
|
||||
yield result
|
||||
})
|
||||
|
||||
await drain(node.peerRouting.getClosestPeers('a cid'))
|
||||
|
||||
expect(spy.calledWith(result.id, result.multiaddrs)).to.be.true()
|
||||
})
|
||||
|
||||
it('should dedupe closest peers', async () => {
|
||||
const [remotePeerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
const results = [{
|
||||
id: remotePeerId,
|
||||
multiaddrs: [
|
||||
multiaddr('/ip4/123.123.123.123/tcp/38982')
|
||||
]
|
||||
}]
|
||||
|
||||
sinon.stub(node._dht, 'getClosestPeers').callsFake(function * () {
|
||||
yield * results
|
||||
})
|
||||
|
||||
sinon.stub(delegate, 'getClosestPeers').callsFake(function * () {
|
||||
yield * results
|
||||
})
|
||||
|
||||
const peers = await all(node.peerRouting.getClosestPeers('a cid'))
|
||||
|
||||
expect(peers).to.be.an('array').with.a.lengthOf(1).that.deep.equals(results)
|
||||
})
|
||||
})
|
||||
|
||||
describe('peer routing refresh manager service', () => {
|
||||
|
318
test/rendezvous/index.spec.js
Normal file
318
test/rendezvous/index.spec.js
Normal file
@@ -0,0 +1,318 @@
|
||||
'use strict'
|
||||
/* eslint-env mocha */
|
||||
|
||||
const { expect } = require('aegir/utils/chai')
|
||||
const sinon = require('sinon')
|
||||
const pWaitFor = require('p-wait-for')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
const { Message } = require('libp2p-rendezvous/src/proto')
|
||||
const RESPONSE_STATUS = Message.ResponseStatus
|
||||
|
||||
const Envelope = require('../../src/record/envelope')
|
||||
const PeerRecord = require('../../src/record/peer-record')
|
||||
const { codes: errCodes } = require('../../src/rendezvous/errors')
|
||||
|
||||
const {
|
||||
getSubsystemOptions,
|
||||
createRendezvousServer,
|
||||
createSignedPeerRecord
|
||||
} = require('./utils')
|
||||
|
||||
const {
|
||||
createPeer
|
||||
} = require('../utils/creators/peer')
|
||||
|
||||
const namespace = 'ns'
|
||||
|
||||
describe('rendezvous', () => {
|
||||
describe('no rendezvous server', () => {
|
||||
let clients
|
||||
|
||||
// Create and start Libp2p nodes
|
||||
beforeEach(async () => {
|
||||
clients = await createPeer({ number: 2, config: getSubsystemOptions([]) })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.map((c) => c.stop()))
|
||||
})
|
||||
|
||||
it('register throws error if no rendezvous servers', async () => {
|
||||
await expect(clients[0].rendezvous.register(namespace))
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
})
|
||||
|
||||
it('unregister throws error if no rendezvous servers', async () => {
|
||||
await expect(clients[0].rendezvous.unregister(namespace))
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
})
|
||||
|
||||
it('discover throws error if no rendezvous servers', async () => {
|
||||
try {
|
||||
for await (const _ of clients[0].rendezvous.discover()) { } // eslint-disable-line
|
||||
} catch (err) {
|
||||
expect(err).to.exist()
|
||||
expect(err.code).to.eql(errCodes.NO_CONNECTED_RENDEZVOUS_SERVERS)
|
||||
return
|
||||
}
|
||||
throw new Error('discover should throw error if no rendezvous servers')
|
||||
})
|
||||
})
|
||||
|
||||
describe('one rendezvous server', () => {
|
||||
let rendezvousServer
|
||||
let clients
|
||||
|
||||
// Create and start Libp2p
|
||||
beforeEach(async function () {
|
||||
this.timeout(10e3)
|
||||
|
||||
// Create Rendezvous Server
|
||||
rendezvousServer = await createRendezvousServer()
|
||||
await pWaitFor(() => rendezvousServer.multiaddrs.length > 0)
|
||||
const rendezvousServerMultiaddr = `${rendezvousServer.multiaddrs[0]}/p2p/${rendezvousServer.peerId.toB58String()}`
|
||||
|
||||
clients = await createPeer({ number: 2, config: getSubsystemOptions([rendezvousServerMultiaddr]) })
|
||||
})
|
||||
|
||||
afterEach(async function () {
|
||||
this.timeout(10e3)
|
||||
sinon.restore()
|
||||
await rendezvousServer.rendezvousDatastore.reset()
|
||||
await rendezvousServer.stop()
|
||||
|
||||
await Promise.all(clients.map((c) => c.stop()))
|
||||
})
|
||||
|
||||
it('register throws error if a namespace is not provided', async () => {
|
||||
await expect(clients[0].rendezvous.register())
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', errCodes.INVALID_NAMESPACE)
|
||||
})
|
||||
|
||||
it('register throws an error with an invalid namespace', async () => {
|
||||
const badNamespace = 'x'.repeat(300)
|
||||
|
||||
await expect(clients[0].rendezvous.register(badNamespace))
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', RESPONSE_STATUS.E_INVALID_NAMESPACE)
|
||||
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
|
||||
it('register throws an error with an invalid ttl', async () => {
|
||||
const badTtl = 5e10
|
||||
|
||||
await expect(clients[0].rendezvous.register(namespace, { ttl: badTtl }))
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', RESPONSE_STATUS.E_INVALID_TTL)
|
||||
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
|
||||
it('register throws an error with an invalid peerId', async () => {
|
||||
const badSignedPeerRecord = await createSignedPeerRecord(clients[1].peerId, [multiaddr('/ip4/127.0.0.1/tcp/100')])
|
||||
|
||||
const stub = sinon.stub(clients[0].peerStore.addressBook, 'getRawEnvelope')
|
||||
stub.onCall(0).returns(badSignedPeerRecord.marshal())
|
||||
|
||||
await expect(clients[0].rendezvous.register(namespace))
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', RESPONSE_STATUS.E_NOT_AUTHORIZED)
|
||||
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
|
||||
it('registers with an available rendezvous server node', async () => {
|
||||
const registers = []
|
||||
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
|
||||
await clients[0].rendezvous.register(namespace)
|
||||
|
||||
// Peer2 discovers Peer0 registered in Peer1
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) {
|
||||
registers.push(reg)
|
||||
}
|
||||
|
||||
expect(registers).to.have.lengthOf(1)
|
||||
expect(registers[0].ns).to.eql(namespace)
|
||||
})
|
||||
|
||||
it('unregister throws if a namespace is not provided', async () => {
|
||||
await expect(clients[0].rendezvous.unregister())
|
||||
.to.eventually.rejected()
|
||||
.and.have.property('code', errCodes.INVALID_NAMESPACE)
|
||||
})
|
||||
|
||||
it('unregisters with an available rendezvous server node', async () => {
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
|
||||
// Register
|
||||
await clients[0].rendezvous.register(namespace)
|
||||
|
||||
// Unregister
|
||||
await clients[0].rendezvous.unregister(namespace)
|
||||
|
||||
// other client does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
|
||||
it('unregister not fails if not registered', async () => {
|
||||
await clients[0].rendezvous.unregister(namespace)
|
||||
})
|
||||
|
||||
it('discover throws error if a namespace is invalid', async () => {
|
||||
const badNamespace = 'x'.repeat(300)
|
||||
|
||||
try {
|
||||
for await (const _ of clients[0].rendezvous.discover(badNamespace)) { } // eslint-disable-line
|
||||
} catch (err) {
|
||||
expect(err).to.exist()
|
||||
expect(err.code).to.eql(RESPONSE_STATUS.E_INVALID_NAMESPACE)
|
||||
return
|
||||
}
|
||||
|
||||
throw new Error('discover should throw error if a namespace is not provided')
|
||||
})
|
||||
|
||||
it('discover does not find any register if there is none', async () => {
|
||||
for await (const reg of clients[0].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
|
||||
it('discover finds registered peer for namespace', async () => {
|
||||
const registers = []
|
||||
|
||||
// Peer2 does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
|
||||
// Peer0 register itself on namespace (connected to Peer1)
|
||||
await clients[0].rendezvous.register(namespace)
|
||||
|
||||
// Peer2 discovers Peer0 registered in Peer1
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) {
|
||||
registers.push(reg)
|
||||
}
|
||||
|
||||
expect(registers).to.have.lengthOf(1)
|
||||
expect(registers[0].signedPeerRecord).to.exist()
|
||||
expect(registers[0].ns).to.eql(namespace)
|
||||
expect(registers[0].ttl).to.exist()
|
||||
|
||||
// Validate envelope
|
||||
const envelope = await Envelope.openAndCertify(registers[0].signedPeerRecord, PeerRecord.DOMAIN)
|
||||
const rec = PeerRecord.createFromProtobuf(envelope.payload)
|
||||
|
||||
expect(rec.multiaddrs).to.eql(clients[0].multiaddrs)
|
||||
})
|
||||
|
||||
it('discover finds registered peer for namespace once (cookie)', async () => {
|
||||
const registers = []
|
||||
|
||||
// Peer2 does not discovery any peer registered
|
||||
for await (const _ of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
|
||||
// Peer0 register itself on namespace (connected to Peer1)
|
||||
await clients[0].rendezvous.register(namespace)
|
||||
|
||||
// Peer2 discovers Peer0 registered in Peer1
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) {
|
||||
registers.push(reg)
|
||||
}
|
||||
|
||||
expect(registers).to.have.lengthOf(1)
|
||||
expect(registers[0].signedPeerRecord).to.exist()
|
||||
expect(registers[0].ns).to.eql(namespace)
|
||||
expect(registers[0].ttl).to.exist()
|
||||
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) {
|
||||
registers.push(reg)
|
||||
}
|
||||
|
||||
expect(registers).to.have.lengthOf(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('multiple rendezvous servers available', () => {
|
||||
let rendezvousServers = []
|
||||
let clients
|
||||
|
||||
// Create and start Libp2p
|
||||
beforeEach(async function () {
|
||||
this.timeout(10e3)
|
||||
|
||||
// Create Rendezvous Server
|
||||
rendezvousServers = await Promise.all([
|
||||
createRendezvousServer(),
|
||||
createRendezvousServer()
|
||||
])
|
||||
await pWaitFor(() => rendezvousServers[0].multiaddrs.length > 0 && rendezvousServers[1].multiaddrs.length > 0)
|
||||
const rendezvousServerMultiaddrs = rendezvousServers.map((rendezvousServer) => `${rendezvousServer.multiaddrs[0]}/p2p/${rendezvousServer.peerId.toB58String()}`)
|
||||
|
||||
clients = await createPeer({ number: 2, config: getSubsystemOptions(rendezvousServerMultiaddrs) })
|
||||
})
|
||||
|
||||
afterEach(async function () {
|
||||
this.timeout(10e3)
|
||||
await Promise.all(rendezvousServers.map((s) => s.rendezvousDatastore.reset()))
|
||||
await Promise.all(rendezvousServers.map((s) => s.stop()))
|
||||
|
||||
await Promise.all(clients.map((c) => c.stop()))
|
||||
})
|
||||
|
||||
it('discover find registered peer for namespace only when registered ', async () => {
|
||||
const registers = []
|
||||
|
||||
// Client 1 does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
|
||||
// Client 0 register itself on namespace (connected to Peer1)
|
||||
await clients[0].rendezvous.register(namespace)
|
||||
|
||||
// Client1 discovers Client0
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) {
|
||||
registers.push(reg)
|
||||
}
|
||||
|
||||
expect(registers[0].signedPeerRecord).to.exist()
|
||||
expect(registers[0].ns).to.eql(namespace)
|
||||
expect(registers[0].ttl).to.exist()
|
||||
|
||||
// Client0 unregister itself on namespace
|
||||
await clients[0].rendezvous.unregister(namespace)
|
||||
|
||||
// Peer2 does not discovery any peer registered
|
||||
for await (const reg of clients[1].rendezvous.discover(namespace)) { // eslint-disable-line
|
||||
throw new Error('no registers should exist')
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
60
test/rendezvous/utils.js
Normal file
60
test/rendezvous/utils.js
Normal file
@@ -0,0 +1,60 @@
|
||||
'use strict'
|
||||
|
||||
const mergeOptions = require('merge-options')
|
||||
|
||||
const RendezvousServer = require('libp2p-rendezvous')
|
||||
const Datastore = require('libp2p-rendezvous/src/datastores/memory')
|
||||
const PeerId = require('peer-id')
|
||||
|
||||
const Envelope = require('../../src/record/envelope')
|
||||
const PeerRecord = require('../../src/record/peer-record')
|
||||
|
||||
const { MULTIADDRS_WEBSOCKETS } = require('../fixtures/browser')
|
||||
const relayAddr = MULTIADDRS_WEBSOCKETS[0]
|
||||
const baseOptions = require('../utils/base-options.browser')
|
||||
|
||||
const getSubsystemOptions = (multiaddrs) => mergeOptions(baseOptions, {
|
||||
addresses: {
|
||||
listen: [`${relayAddr}/p2p-circuit`]
|
||||
},
|
||||
rendezvous: {
|
||||
enabled: true,
|
||||
rendezvousPoints: multiaddrs
|
||||
}
|
||||
})
|
||||
|
||||
async function createRendezvousServer ({ config = {}, started = true } = {}) {
|
||||
const datastore = new Datastore()
|
||||
|
||||
const peerId = await PeerId.create()
|
||||
const rendezvous = new RendezvousServer(mergeOptions(baseOptions, {
|
||||
addresses: {
|
||||
listen: [`${relayAddr}/p2p-circuit`]
|
||||
},
|
||||
peerId,
|
||||
...config
|
||||
}), { datastore })
|
||||
|
||||
if (started) {
|
||||
await rendezvous.start()
|
||||
}
|
||||
|
||||
return rendezvous
|
||||
}
|
||||
|
||||
async function createSignedPeerRecord (peerId, multiaddrs) {
|
||||
const pr = new PeerRecord({
|
||||
peerId,
|
||||
multiaddrs
|
||||
})
|
||||
|
||||
const envelope = await Envelope.seal(pr, peerId)
|
||||
|
||||
return envelope
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createRendezvousServer,
|
||||
getSubsystemOptions,
|
||||
createSignedPeerRecord
|
||||
}
|
Reference in New Issue
Block a user