mirror of
https://github.com/fluencelabs/js-libp2p
synced 2025-04-24 18:12:14 +00:00
chore: remove peer-info usage
BREAKING CHANGE: all API methods with peer-info parameters or return values were changed. You can check the API.md document, in order to check the new values to use
This commit is contained in:
parent
ed6d5bb4b4
commit
12e48adafa
@ -4,7 +4,6 @@ const Libp2p = require('./src')
|
||||
const { MULTIADDRS_WEBSOCKETS } = require('./test/fixtures/browser')
|
||||
const Peers = require('./test/fixtures/peers')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const WebSockets = require('libp2p-websockets')
|
||||
const Muxer = require('libp2p-mplex')
|
||||
const Crypto = require('libp2p-secio')
|
||||
@ -14,11 +13,12 @@ let libp2p
|
||||
const before = async () => {
|
||||
// Use the last peer
|
||||
const peerId = await PeerId.createFromJSON(Peers[Peers.length - 1])
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
peerInfo.multiaddrs.add(MULTIADDRS_WEBSOCKETS[0])
|
||||
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
addresses: {
|
||||
listen: [MULTIADDRS_WEBSOCKETS[0]]
|
||||
},
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [WebSockets],
|
||||
streamMuxer: [Muxer],
|
||||
|
61
doc/API.md
61
doc/API.md
@ -60,12 +60,13 @@ Creates an instance of Libp2p.
|
||||
|------|------|-------------|
|
||||
| options | `object` | libp2p options |
|
||||
| options.modules | `Array<object>` | libp2p modules to use |
|
||||
| [options.addresses] | `{ listen: Array<Multiaddr> }` | Addresses to use for transport listening and to announce to the network |
|
||||
| [options.config] | `object` | libp2p modules configuration and core configuration |
|
||||
| [options.connectionManager] | `object` | libp2p Connection Manager configuration |
|
||||
| [options.datastore] | `object` | must implement [ipfs/interface-datastore](https://github.com/ipfs/interface-datastore) (in memory datastore will be used if not provided) |
|
||||
| [options.dialer] | `object` | libp2p Dialer configuration
|
||||
| [options.metrics] | `object` | libp2p Metrics configuration
|
||||
| [options.peerInfo] | [`PeerInfo`][peer-info] | peerInfo instance (it will be created if not provided) |
|
||||
| [options.peerId] | [`PeerId`][peer-id] | peerId instance (it will be created if not provided) |
|
||||
|
||||
For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
|
||||
|
||||
@ -87,7 +88,7 @@ const options = {}
|
||||
const libp2p = await Libp2p.create(options)
|
||||
```
|
||||
|
||||
Note: The [`PeerInfo`][peer-info] option is not required and will be generated if it is not provided.
|
||||
Note: The [`PeerId`][peer-id] option is not required and will be generated if it is not provided.
|
||||
|
||||
<details><summary>Alternative</summary>
|
||||
As an alternative, it is possible to create a Libp2p instance with the constructor:
|
||||
@ -106,7 +107,7 @@ const libp2p = new Libp2p(options)
|
||||
|
||||
Required keys in the `options` object:
|
||||
|
||||
- `peerInfo`: instance of [`PeerInfo`][peer-info] that contains the [`PeerId`][peer-id], Keys and [multiaddrs][multiaddr] of the libp2p Node (optional when using `.create`).
|
||||
- `peerId`: instance of [`PeerId`][peer-id] that contains the peer Keys (optional when using `.create`).
|
||||
- `modules.transport`: An array that must include at least 1 compliant transport. See [modules that implement the transport interface](https://github.com/libp2p/js-interfaces/tree/master/src/transport#modules-that-implement-the-interface).
|
||||
|
||||
</details>
|
||||
@ -163,6 +164,10 @@ const libp2p = await Libp2p.create(options)
|
||||
await libp2p.stop()
|
||||
```
|
||||
|
||||
### addresses
|
||||
|
||||
TODO with `address-manager`.
|
||||
|
||||
### connections
|
||||
|
||||
A Getter that returns a Map of the current Connections libp2p has to other peers.
|
||||
@ -194,10 +199,12 @@ for (const [peerId, connections] of libp2p.connections) {
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| peer | [`PeerInfo`][peer-info]\|[`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | The peer to dial. If a [`Multiaddr`][multiaddr] or its string is provided, it **must** include the peer id |
|
||||
| peer | [`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | The peer to dial. |
|
||||
| [options] | `object` | dial options |
|
||||
| [options.signal] | [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) | An `AbortSignal` instance obtained from an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) that can be used to abort the connection before it completes |
|
||||
|
||||
**Note:** If a [`Multiaddr`][multiaddr] or its string is provided, it **must** include the peer id. Moreover, if a [`PeerId`][peer-id] is given, the peer will need to have known multiaddrs for it in the PeerStore.
|
||||
|
||||
#### Returns
|
||||
|
||||
| Type | Description |
|
||||
@ -208,7 +215,7 @@ for (const [peerId, connections] of libp2p.connections) {
|
||||
|
||||
```js
|
||||
// ...
|
||||
const conn = await libp2p.dial(remotePeerInfo)
|
||||
const conn = await libp2p.dial(remotePeerId)
|
||||
|
||||
// create a new stream within the connection
|
||||
const { stream, protocol } = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])
|
||||
@ -229,11 +236,13 @@ Dials to another peer in the network and selects a protocol to communicate with
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| peer | [`PeerInfo`][peer-info]\|[`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | The peer to dial. If a [`Multiaddr`][multiaddr] or its string is provided, it **must** include the peer id |
|
||||
| peer | [`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | The peer to dial. |
|
||||
| protocols | `string|Array<string>` | A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made. (e.g '/ipfs/bitswap/1.1.0') |
|
||||
| [options] | `object` | dial options |
|
||||
| [options.signal] | [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) | An `AbortSignal` instance obtained from an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) that can be used to abort the connection before it completes |
|
||||
|
||||
**Note:** If a [`Multiaddr`][multiaddr] or its string is provided, it **must** include the peer id. Moreover, if a [`PeerId`][peer-id] is given, the peer will need to have known multiaddrs for it in the PeerStore.
|
||||
|
||||
#### Returns
|
||||
|
||||
| Type | Description |
|
||||
@ -246,7 +255,7 @@ Dials to another peer in the network and selects a protocol to communicate with
|
||||
// ...
|
||||
const pipe = require('it-pipe')
|
||||
|
||||
const { stream, protocol } = await libp2p.dialProtocol(remotePeerInfo, protocols)
|
||||
const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)
|
||||
|
||||
// Use this new stream like any other duplex stream
|
||||
pipe([1, 2, 3], stream, consume)
|
||||
@ -262,7 +271,7 @@ Attempts to gracefully close an open connection to the given peer. If the connec
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| peer | [`PeerInfo`][peer-info]\|[`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | peer to hang up |
|
||||
| peer | [`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | peer to hang up |
|
||||
|
||||
#### Returns
|
||||
|
||||
@ -274,7 +283,7 @@ Attempts to gracefully close an open connection to the given peer. If the connec
|
||||
|
||||
```js
|
||||
// ...
|
||||
await libp2p.hangUp(remotePeerInfo)
|
||||
await libp2p.hangUp(remotePeerId)
|
||||
```
|
||||
|
||||
### handle
|
||||
@ -333,7 +342,7 @@ Pings a given peer and get the operation's latency.
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| peer | [`PeerInfo`][peer-info]\|[`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | peer to ping |
|
||||
| peer | [`PeerId`][peer-id]\|[`Multiaddr`][multiaddr]\|`string` | peer to ping |
|
||||
|
||||
#### Returns
|
||||
|
||||
@ -366,13 +375,13 @@ Iterates over all peer routers in series to find the given peer. If the DHT is e
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `Promise<PeerInfo>` | Peer info of a known peer |
|
||||
| `Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>` | Peer data of a known peer |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
// ...
|
||||
const peerInfo = await libp2p.peerRouting.findPeer(peerId, options)
|
||||
const peerData = await libp2p.peerRouting.findPeer(peerId, options)
|
||||
```
|
||||
|
||||
### contentRouting.findProviders
|
||||
@ -395,14 +404,14 @@ Once a content router succeeds, the iteration will stop. If the DHT is enabled,
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `AsyncIterator<PeerInfo>` | Async iterator for [`PeerInfo`][peer-info] |
|
||||
| `AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }` | Async iterator for peer data |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
// Iterate over the providers found for the given cid
|
||||
for await (const provider of libp2p.contentRouting.findProviders(cid)) {
|
||||
console.log(provider)
|
||||
console.log(provider.id, provider.addrs)
|
||||
}
|
||||
```
|
||||
|
||||
@ -809,7 +818,7 @@ peerStore.delete(peerId2)
|
||||
|
||||
### peerStore.get
|
||||
|
||||
Get the stored information of a given peer.
|
||||
Get the stored information of a given peer, namely its [`PeerId`][peer-id], known [`MultiaddrInfos`][multiaddr-info] and supported protocols.
|
||||
|
||||
`peerStore.get(peerId)`
|
||||
|
||||
@ -823,9 +832,7 @@ Get the stored information of a given peer.
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| [`PeerInfo`][peer-info] | Peer information of the provided peer |
|
||||
|
||||
TODO: change when `peer-info` is deprecated to new pointer
|
||||
| `{ id: PeerId, multiaddrInfos: Array<MultiaddrInfo>, protocols: Array<string> }` | Peer information of the provided peer |
|
||||
|
||||
#### Example
|
||||
|
||||
@ -836,6 +843,7 @@ peerStore.addressBook.set(peerId, multiaddrs)
|
||||
peerStore.protoBook.set(peerId, protocols)
|
||||
peerStore.get(peerId)
|
||||
// {
|
||||
// id: {},
|
||||
// MultiaddrInfos: [...],
|
||||
// protocols: [...]
|
||||
// }
|
||||
@ -851,15 +859,13 @@ Get all the stored information of every peer.
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `Map<string, PeerInfo>` | Peer information of every peer |
|
||||
|
||||
TODO: change when `peer-info` is deprecated to new pointer (breaking change)
|
||||
| `Map<string, { id: PeerId, multiaddrInfos: Array<MultiaddrInfo>, protocols: Array<string> }>` | Peer data of every peer known |
|
||||
|
||||
#### Example
|
||||
|
||||
```js
|
||||
for (let [peerIdString, peerInfo] of peerStore.peers.entries()) {
|
||||
// peerInfo instance
|
||||
for (let [peerIdString, peerData] of peerStore.peers.entries()) {
|
||||
// peerData
|
||||
}
|
||||
```
|
||||
|
||||
@ -1070,7 +1076,7 @@ Returns the [`Stats`](#stats) object for a given [`PeerId`][peer-id] if it is be
|
||||
#### Example
|
||||
|
||||
```js
|
||||
const peerStats = libp2p.metrics.forPeer(peerInfo)
|
||||
const peerStats = libp2p.metrics.forPeer(peerId)
|
||||
console.log(peerStats.toJSON())
|
||||
```
|
||||
|
||||
@ -1118,7 +1124,7 @@ Once you have a libp2p instance, you can listen to several events it emits, so t
|
||||
If `autoDial` option is `true`, applications should **not** attempt to connect to the peer
|
||||
unless they are performing a specific action. See [peer discovery and auto dial](./PEER_DISCOVERY.md) for more information.
|
||||
|
||||
- `peer`: instance of [`PeerInfo`][peer-info]
|
||||
- `peer`: instance of [`PeerId`][peer-id]
|
||||
|
||||
#### A new connection to a peer has been opened
|
||||
|
||||
@ -1126,7 +1132,7 @@ This event will be triggered anytime a new Connection is established to another
|
||||
|
||||
`libp2p.on('peer:connect', (peer) => {})`
|
||||
|
||||
- `peer`: instance of [`PeerInfo`][peer-info]
|
||||
- `peer`: instance of [`PeerId`][peer-id]
|
||||
|
||||
#### An existing connection to a peer has been closed
|
||||
|
||||
@ -1134,7 +1140,7 @@ This event will be triggered anytime we are disconnected from another peer, rega
|
||||
|
||||
`libp2p.on('peer:disconnect', (peer) => {})`
|
||||
|
||||
- `peer`: instance of [`PeerInfo`][peer-info]
|
||||
- `peer`: instance of [`PeerId`][peer-id]
|
||||
|
||||
### libp2p.peerStore
|
||||
|
||||
@ -1183,4 +1189,3 @@ This event will be triggered anytime we are disconnected from another peer, rega
|
||||
[connection]: https://github.com/libp2p/js-interfaces/tree/master/src/connection
|
||||
[multiaddr]: https://github.com/multiformats/js-multiaddr
|
||||
[peer-id]: https://github.com/libp2p/js-peer-id
|
||||
[peer-info]: https://github.com/libp2p/js-peer-info
|
||||
|
20
package.json
20
package.json
@ -58,7 +58,7 @@
|
||||
"it-pipe": "^1.1.0",
|
||||
"it-protocol-buffers": "^0.2.0",
|
||||
"libp2p-crypto": "^0.17.6",
|
||||
"libp2p-interfaces": "^0.2.8",
|
||||
"libp2p-interfaces": "^0.3.0",
|
||||
"libp2p-utils": "^0.1.2",
|
||||
"mafmt": "^7.0.0",
|
||||
"merge-options": "^2.0.0",
|
||||
@ -70,7 +70,6 @@
|
||||
"p-fifo": "^1.0.0",
|
||||
"p-settle": "^4.0.1",
|
||||
"peer-id": "^0.13.11",
|
||||
"peer-info": "^0.17.0",
|
||||
"protons": "^1.0.1",
|
||||
"retimer": "^2.0.0",
|
||||
"streaming-iterables": "^4.1.0",
|
||||
@ -87,20 +86,21 @@
|
||||
"delay": "^4.3.0",
|
||||
"dirty-chai": "^2.0.1",
|
||||
"interop-libp2p": "libp2p/interop#chore/update-libp2p-daemon-with-peerstore",
|
||||
"ipfs-http-client": "^44.0.0",
|
||||
"it-concat": "^1.0.0",
|
||||
"it-pair": "^1.0.0",
|
||||
"it-pushable": "^1.4.0",
|
||||
"libp2p-bootstrap": "^0.10.3",
|
||||
"libp2p-delegated-content-routing": "^0.4.5",
|
||||
"libp2p-delegated-peer-routing": "^0.4.3",
|
||||
"libp2p-floodsub": "^0.20.0",
|
||||
"libp2p-gossipsub": "^0.2.6",
|
||||
"libp2p-kad-dht": "^0.19.0-pre.0",
|
||||
"libp2p-mdns": "^0.13.0",
|
||||
"libp2p-bootstrap": "^0.11.0",
|
||||
"libp2p-delegated-content-routing": "^0.5.0",
|
||||
"libp2p-delegated-peer-routing": "^0.5.0",
|
||||
"libp2p-floodsub": "^0.21.0",
|
||||
"libp2p-gossipsub": "^0.4.0",
|
||||
"libp2p-kad-dht": "^0.19.0",
|
||||
"libp2p-mdns": "^0.14.0",
|
||||
"libp2p-mplex": "^0.9.5",
|
||||
"libp2p-secio": "^0.12.4",
|
||||
"libp2p-tcp": "^0.14.1",
|
||||
"libp2p-webrtc-star": "^0.17.9",
|
||||
"libp2p-webrtc-star": "^0.18.0",
|
||||
"libp2p-websockets": "^0.13.1",
|
||||
"nock": "^12.0.3",
|
||||
"p-defer": "^3.0.0",
|
||||
|
@ -1,7 +1,9 @@
|
||||
'use strict'
|
||||
|
||||
const debug = require('debug')
|
||||
const PeerInfo = require('peer-info')
|
||||
const log = debug('libp2p:circuit:hop')
|
||||
log.error = debug('libp2p:circuit:hop:error')
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const { validateAddrs } = require('./utils')
|
||||
const StreamHandler = require('./stream-handler')
|
||||
@ -14,9 +16,6 @@ const { stop } = require('./stop')
|
||||
|
||||
const multicodec = require('./../multicodec')
|
||||
|
||||
const log = debug('libp2p:circuit:hop')
|
||||
log.error = debug('libp2p:circuit:hop:error')
|
||||
|
||||
module.exports.handleHop = async function handleHop ({
|
||||
connection,
|
||||
request,
|
||||
@ -42,7 +41,7 @@ module.exports.handleHop = async function handleHop ({
|
||||
// Get the connection to the destination (stop) peer
|
||||
const destinationPeer = new PeerId(request.dstPeer.id)
|
||||
|
||||
const destinationConnection = circuit._registrar.getConnection(new PeerInfo(destinationPeer))
|
||||
const destinationConnection = circuit._registrar.getConnection(destinationPeer)
|
||||
if (!destinationConnection && !circuit._options.hop.active) {
|
||||
log('HOP request received but we are not connected to the destination peer')
|
||||
return streamHandler.end({
|
||||
|
@ -3,7 +3,6 @@
|
||||
const mafmt = require('mafmt')
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const withIs = require('class-is')
|
||||
const { CircuitRelay: CircuitPB } = require('./protocol')
|
||||
|
||||
@ -32,7 +31,8 @@ class Circuit {
|
||||
this._registrar = libp2p.registrar
|
||||
this._upgrader = upgrader
|
||||
this._options = libp2p._config.relay
|
||||
this.peerInfo = libp2p.peerInfo
|
||||
this.addresses = libp2p.addresses
|
||||
this.peerId = libp2p.peerId
|
||||
this._registrar.handle(multicodec, this._onProtocol.bind(this))
|
||||
}
|
||||
|
||||
@ -107,7 +107,7 @@ class Circuit {
|
||||
const destinationPeer = PeerId.createFromCID(destinationAddr.getPeerId())
|
||||
|
||||
let disconnectOnFailure = false
|
||||
let relayConnection = this._registrar.getConnection(new PeerInfo(relayPeer))
|
||||
let relayConnection = this._registrar.getConnection(relayPeer)
|
||||
if (!relayConnection) {
|
||||
relayConnection = await this._dialer.connectToPeer(relayAddr, options)
|
||||
disconnectOnFailure = true
|
||||
@ -120,8 +120,8 @@ class Circuit {
|
||||
request: {
|
||||
type: CircuitPB.Type.HOP,
|
||||
srcPeer: {
|
||||
id: this.peerInfo.id.toBytes(),
|
||||
addrs: this.peerInfo.multiaddrs.toArray().map(addr => addr.buffer)
|
||||
id: this.peerId.toBytes(),
|
||||
addrs: this.addresses.listen.map(addr => addr.buffer)
|
||||
},
|
||||
dstPeer: {
|
||||
id: destinationPeer.toBytes(),
|
||||
@ -130,7 +130,7 @@ class Circuit {
|
||||
}
|
||||
})
|
||||
|
||||
const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.peerInfo.id.toB58String()}`)
|
||||
const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.peerId.toB58String()}`)
|
||||
const maConn = toConnection({
|
||||
stream: virtualConnection,
|
||||
remoteAddr: ma,
|
||||
|
@ -4,6 +4,9 @@ const mergeOptions = require('merge-options')
|
||||
const Constants = require('./constants')
|
||||
|
||||
const DefaultConfig = {
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
connectionManager: {
|
||||
minPeers: 25
|
||||
},
|
||||
|
@ -40,7 +40,7 @@ class ConnectionManager {
|
||||
constructor (libp2p, options) {
|
||||
this._libp2p = libp2p
|
||||
this._registrar = libp2p.registrar
|
||||
this._peerId = libp2p.peerInfo.id.toB58String()
|
||||
this._peerId = libp2p.peerId.toB58String()
|
||||
this._options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, options)
|
||||
if (this._options.maxConnections < this._options.minConnections) {
|
||||
throw errcode(new Error('Connection Manager maxConnections must be greater than minConnections'), ERR_INVALID_PARAMETERS)
|
||||
|
@ -24,7 +24,7 @@ module.exports = (node) => {
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.timeout] How long the query should run
|
||||
* @param {number} [options.maxNumProviders] - maximum number of providers to find
|
||||
* @returns {AsyncIterable<PeerInfo>}
|
||||
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
|
||||
*/
|
||||
async * findProviders (key, options) {
|
||||
if (!routers.length) {
|
||||
@ -42,8 +42,8 @@ module.exports = (node) => {
|
||||
})
|
||||
)
|
||||
|
||||
for (const pInfo of result) {
|
||||
yield pInfo
|
||||
for (const peerData of result) {
|
||||
yield peerData
|
||||
}
|
||||
},
|
||||
|
||||
|
@ -4,11 +4,12 @@ const multiaddr = require('multiaddr')
|
||||
const errCode = require('err-code')
|
||||
const TimeoutController = require('timeout-abort-controller')
|
||||
const anySignal = require('any-signal')
|
||||
const PeerId = require('peer-id')
|
||||
const debug = require('debug')
|
||||
const log = debug('libp2p:dialer')
|
||||
log.error = debug('libp2p:dialer:error')
|
||||
|
||||
const { DialRequest } = require('./dial-request')
|
||||
const getPeerId = require('../get-peer-id')
|
||||
|
||||
const { codes } = require('../errors')
|
||||
const {
|
||||
@ -57,18 +58,19 @@ class Dialer {
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to a given `PeerId` or `Multiaddr` by dialing all of its known addresses.
|
||||
* Connects to a given `peer` by dialing all of its known addresses.
|
||||
* The dial to the first address that is successfully able to upgrade a connection
|
||||
* will be used.
|
||||
*
|
||||
* @param {PeerId|Multiaddr} peerId The peer to dial
|
||||
* @param {PeerId|Multiaddr|string} peer The peer to dial
|
||||
* @param {object} [options]
|
||||
* @param {AbortSignal} [options.signal] An AbortController signal
|
||||
* @returns {Promise<Connection>}
|
||||
*/
|
||||
async connectToPeer (peerId, options = {}) {
|
||||
const dialTarget = this._createDialTarget(peerId)
|
||||
if (dialTarget.addrs.length === 0) {
|
||||
async connectToPeer (peer, options = {}) {
|
||||
const dialTarget = this._createDialTarget(peer)
|
||||
|
||||
if (!dialTarget.addrs.length) {
|
||||
throw errCode(new Error('The dial request has no addresses'), codes.ERR_NO_VALID_ADDRESSES)
|
||||
}
|
||||
const pendingDial = this._pendingDials.get(dialTarget.id) || this._createPendingDial(dialTarget, options)
|
||||
@ -98,24 +100,24 @@ class Dialer {
|
||||
/**
|
||||
* Creates a DialTarget. The DialTarget is used to create and track
|
||||
* the DialRequest to a given peer.
|
||||
* If a multiaddr is received it should be the first address attempted.
|
||||
* @private
|
||||
* @param {PeerId|Multiaddr} peer A PeerId or Multiaddr
|
||||
* @param {PeerId|Multiaddr|string} peer A PeerId or Multiaddr
|
||||
* @returns {DialTarget}
|
||||
*/
|
||||
_createDialTarget (peer) {
|
||||
const dialable = Dialer.getDialable(peer)
|
||||
if (multiaddr.isMultiaddr(dialable)) {
|
||||
return {
|
||||
id: dialable.toString(),
|
||||
addrs: [dialable]
|
||||
}
|
||||
const peerId = getPeerId(peer, this.peerStore)
|
||||
let addrs = this.peerStore.addressBook.getMultiaddrsForPeer(peerId)
|
||||
|
||||
// If received a multiaddr to dial, it should be the first to use
|
||||
// But, if we know other multiaddrs for the peer, we should try them too.
|
||||
if (multiaddr.isMultiaddr(peer)) {
|
||||
addrs = addrs.filter((addr) => !peer.equals(addr))
|
||||
addrs.unshift(peer)
|
||||
}
|
||||
|
||||
dialable.multiaddrs && this.peerStore.addressBook.add(dialable.id, Array.from(dialable.multiaddrs))
|
||||
const addrs = this.peerStore.addressBook.getMultiaddrsForPeer(dialable.id)
|
||||
|
||||
return {
|
||||
id: dialable.id.toB58String(),
|
||||
id: peerId.toB58String(),
|
||||
addrs
|
||||
}
|
||||
}
|
||||
@ -180,44 +182,6 @@ class Dialer {
|
||||
log('token %d released', token)
|
||||
this.tokens.push(token)
|
||||
}
|
||||
|
||||
/**
|
||||
* PeerInfo object
|
||||
* @typedef {Object} peerInfo
|
||||
* @property {Multiaddr} multiaddr peer multiaddr.
|
||||
* @property {PeerId} id peer id.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Converts the given `peer` into a `PeerInfo` or `Multiaddr`.
|
||||
* @static
|
||||
* @param {PeerId|Multiaddr|string} peer
|
||||
* @returns {peerInfo|Multiaddr}
|
||||
*/
|
||||
static getDialable (peer) {
|
||||
if (typeof peer === 'string') {
|
||||
peer = multiaddr(peer)
|
||||
}
|
||||
|
||||
let addrs
|
||||
if (multiaddr.isMultiaddr(peer)) {
|
||||
addrs = new Set([peer]) // TODO: after peer-info removal, a Set should not be needed
|
||||
try {
|
||||
peer = PeerId.createFromCID(peer.getPeerId())
|
||||
} catch (err) {
|
||||
throw errCode(new Error('The multiaddr did not contain a valid peer id'), codes.ERR_INVALID_PEER)
|
||||
}
|
||||
}
|
||||
|
||||
if (PeerId.isPeerId(peer)) {
|
||||
peer = {
|
||||
id: peer,
|
||||
multiaddrs: addrs
|
||||
}
|
||||
}
|
||||
|
||||
return peer
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Dialer
|
||||
|
@ -26,5 +26,6 @@ exports.codes = {
|
||||
ERR_TIMEOUT: 'ERR_TIMEOUT',
|
||||
ERR_TRANSPORT_UNAVAILABLE: 'ERR_TRANSPORT_UNAVAILABLE',
|
||||
ERR_TRANSPORT_DIAL_FAILED: 'ERR_TRANSPORT_DIAL_FAILED',
|
||||
ERR_UNSUPPORTED_PROTOCOL: 'ERR_UNSUPPORTED_PROTOCOL'
|
||||
ERR_UNSUPPORTED_PROTOCOL: 'ERR_UNSUPPORTED_PROTOCOL',
|
||||
ERR_INVALID_MULTIADDR: 'ERR_INVALID_MULTIADDR'
|
||||
}
|
||||
|
41
src/get-peer-id.js
Normal file
41
src/get-peer-id.js
Normal file
@ -0,0 +1,41 @@
|
||||
'use strict'
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const multiaddr = require('multiaddr')
|
||||
const errCode = require('err-code')
|
||||
|
||||
const { codes } = require('./errors')
|
||||
|
||||
/**
|
||||
* Converts the given `peer` to a `PeerId` instance.
|
||||
* If a multiaddr is received, the addressBook is updated.
|
||||
* @param {PeerId|Multiaddr|string} peer
|
||||
* @param {PeerStore} peerStore
|
||||
* @returns {PeerId}
|
||||
*/
|
||||
function getPeerId (peer, peerStore) {
|
||||
if (typeof peer === 'string') {
|
||||
peer = multiaddr(peer)
|
||||
}
|
||||
|
||||
let addr
|
||||
if (multiaddr.isMultiaddr(peer)) {
|
||||
addr = peer
|
||||
try {
|
||||
peer = PeerId.createFromB58String(peer.getPeerId())
|
||||
} catch (err) {
|
||||
throw errCode(
|
||||
new Error(`${peer} is not a valid peer type`),
|
||||
codes.ERR_INVALID_MULTIADDR
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (addr && peerStore) {
|
||||
peerStore.addressBook.add(peer, [addr])
|
||||
}
|
||||
|
||||
return peer
|
||||
}
|
||||
|
||||
module.exports = getPeerId
|
@ -1,78 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const multiaddr = require('multiaddr')
|
||||
const errCode = require('err-code')
|
||||
|
||||
/**
|
||||
* Converts the given `peer` to a `PeerInfo` instance.
|
||||
* The `PeerStore` will be checked for the resulting peer, and
|
||||
* the peer will be updated in the `PeerStore`.
|
||||
*
|
||||
* @param {PeerInfo|PeerId|Multiaddr|string} peer
|
||||
* @param {PeerStore} peerStore
|
||||
* @returns {PeerInfo}
|
||||
*/
|
||||
function getPeerInfo (peer, peerStore) {
|
||||
if (typeof peer === 'string') {
|
||||
peer = multiaddr(peer)
|
||||
}
|
||||
|
||||
let addr
|
||||
if (multiaddr.isMultiaddr(peer)) {
|
||||
addr = peer
|
||||
try {
|
||||
peer = PeerId.createFromB58String(peer.getPeerId())
|
||||
} catch (err) {
|
||||
throw errCode(
|
||||
new Error(`${peer} is not a valid peer type`),
|
||||
'ERR_INVALID_MULTIADDR'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (PeerId.isPeerId(peer)) {
|
||||
peer = new PeerInfo(peer)
|
||||
}
|
||||
|
||||
addr && peer.multiaddrs.add(addr)
|
||||
|
||||
if (peerStore) {
|
||||
peerStore.addressBook.add(peer.id, peer.multiaddrs.toArray())
|
||||
peerStore.protoBook.add(peer.id, Array.from(peer.protocols))
|
||||
}
|
||||
|
||||
return peer
|
||||
}
|
||||
|
||||
/**
|
||||
* If `getPeerInfo` does not return a peer with multiaddrs,
|
||||
* the `libp2p` PeerRouter will be used to attempt to find the peer.
|
||||
*
|
||||
* @async
|
||||
* @param {PeerInfo|PeerId|Multiaddr|string} peer
|
||||
* @param {Libp2p} libp2p
|
||||
* @returns {Promise<PeerInfo>}
|
||||
*/
|
||||
function getPeerInfoRemote (peer, libp2p) {
|
||||
let peerInfo
|
||||
|
||||
try {
|
||||
peerInfo = getPeerInfo(peer, libp2p.peerStore)
|
||||
} catch (err) {
|
||||
throw errCode(err, 'ERR_INVALID_PEER_TYPE')
|
||||
}
|
||||
|
||||
// If we don't have an address for the peer, attempt to find it
|
||||
if (peerInfo.multiaddrs.size < 1) {
|
||||
return libp2p.peerRouting.findPeer(peerInfo.id)
|
||||
}
|
||||
|
||||
return peerInfo
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getPeerInfoRemote,
|
||||
getPeerInfo
|
||||
}
|
@ -48,7 +48,8 @@ class IdentifyService {
|
||||
* @param {object} options
|
||||
* @param {Registrar} options.registrar
|
||||
* @param {Map<string, handler>} options.protocols A reference to the protocols we support
|
||||
* @param {PeerInfo} options.peerInfo The peer running the identify service
|
||||
* @param {PeerId} options.peerId The peer running the identify service
|
||||
* @param {{ listen: Array<Multiaddr>}} options.addresses The peer aaddresses
|
||||
*/
|
||||
constructor (options) {
|
||||
/**
|
||||
@ -56,9 +57,11 @@ class IdentifyService {
|
||||
*/
|
||||
this.registrar = options.registrar
|
||||
/**
|
||||
* @property {PeerInfo}
|
||||
* @property {PeerId}
|
||||
*/
|
||||
this.peerInfo = options.peerInfo
|
||||
this.peerId = options.peerId
|
||||
|
||||
this.addresses = options.addresses || {}
|
||||
|
||||
this._protocols = options.protocols
|
||||
|
||||
@ -77,7 +80,7 @@ class IdentifyService {
|
||||
|
||||
await pipe(
|
||||
[{
|
||||
listenAddrs: this.peerInfo.multiaddrs.toArray().map((ma) => ma.buffer),
|
||||
listenAddrs: this.addresses.listen.map((ma) => ma.buffer),
|
||||
protocols: Array.from(this._protocols.keys())
|
||||
}],
|
||||
pb.encode(Message),
|
||||
@ -101,7 +104,7 @@ class IdentifyService {
|
||||
const connections = []
|
||||
let connection
|
||||
for (const peer of peerStore.peers.values()) {
|
||||
if (peer.protocols.has(MULTICODEC_IDENTIFY_PUSH) && (connection = this.registrar.getConnection(peer))) {
|
||||
if (peer.protocols.includes(MULTICODEC_IDENTIFY_PUSH) && (connection = this.registrar.getConnection(peer.id))) {
|
||||
connections.push(connection)
|
||||
}
|
||||
}
|
||||
@ -194,15 +197,15 @@ class IdentifyService {
|
||||
*/
|
||||
_handleIdentify ({ connection, stream }) {
|
||||
let publicKey = Buffer.alloc(0)
|
||||
if (this.peerInfo.id.pubKey) {
|
||||
publicKey = this.peerInfo.id.pubKey.bytes
|
||||
if (this.peerId.pubKey) {
|
||||
publicKey = this.peerId.pubKey.bytes
|
||||
}
|
||||
|
||||
const message = Message.encode({
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
agentVersion: AGENT_VERSION,
|
||||
publicKey,
|
||||
listenAddrs: this.peerInfo.multiaddrs.toArray().map((ma) => ma.buffer),
|
||||
listenAddrs: this.addresses.listen.map((ma) => ma.buffer),
|
||||
observedAddr: connection.remoteAddr.buffer,
|
||||
protocols: Array.from(this._protocols.keys())
|
||||
})
|
||||
|
137
src/index.js
137
src/index.js
@ -6,12 +6,12 @@ const globalThis = require('ipfs-utils/src/globalthis')
|
||||
const log = debug('libp2p')
|
||||
log.error = debug('libp2p:error')
|
||||
|
||||
const PeerInfo = require('peer-info')
|
||||
const PeerId = require('peer-id')
|
||||
|
||||
const peerRouting = require('./peer-routing')
|
||||
const contentRouting = require('./content-routing')
|
||||
const pubsub = require('./pubsub')
|
||||
const { getPeerInfo } = require('./get-peer-info')
|
||||
const getPeerId = require('./get-peer-id')
|
||||
const { validate: validateConfig } = require('./config')
|
||||
const { codes } = require('./errors')
|
||||
|
||||
@ -43,9 +43,12 @@ class Libp2p extends EventEmitter {
|
||||
this._options = validateConfig(_options)
|
||||
|
||||
this.datastore = this._options.datastore
|
||||
this.peerInfo = this._options.peerInfo
|
||||
this.peerId = this._options.peerId
|
||||
this.peerStore = new PeerStore()
|
||||
|
||||
// Addresses {listen, announce, noAnnounce}
|
||||
this.addresses = this._options.addresses
|
||||
|
||||
this._modules = this._options.modules
|
||||
this._config = this._options.config
|
||||
this._transport = [] // Transport instances/references
|
||||
@ -57,29 +60,31 @@ class Libp2p extends EventEmitter {
|
||||
|
||||
// Setup the Upgrader
|
||||
this.upgrader = new Upgrader({
|
||||
localPeer: this.peerInfo.id,
|
||||
localPeer: this.peerId,
|
||||
metrics: this.metrics,
|
||||
onConnection: (connection) => {
|
||||
const peerInfo = new PeerInfo(connection.remotePeer)
|
||||
this.registrar.onConnect(peerInfo, connection)
|
||||
const peerId = connection.remotePeer
|
||||
|
||||
this.registrar.onConnect(peerId, connection)
|
||||
this.connectionManager.onConnect(connection)
|
||||
this.emit('peer:connect', peerInfo)
|
||||
this.emit('peer:connect', peerId)
|
||||
|
||||
// Run identify for every connection
|
||||
if (this.identifyService) {
|
||||
this.identifyService.identify(connection, connection.remotePeer)
|
||||
this.identifyService.identify(connection, peerId)
|
||||
.catch(log.error)
|
||||
}
|
||||
},
|
||||
onConnectionEnd: (connection) => {
|
||||
const peerInfo = Dialer.getDialable(connection.remotePeer)
|
||||
this.registrar.onDisconnect(peerInfo, connection)
|
||||
const peerId = connection.remotePeer
|
||||
|
||||
this.registrar.onDisconnect(peerId, connection)
|
||||
this.connectionManager.onDisconnect(connection)
|
||||
|
||||
// If there are no connections to the peer, disconnect
|
||||
if (!this.registrar.getConnection(peerInfo)) {
|
||||
this.emit('peer:disconnect', peerInfo)
|
||||
this.metrics && this.metrics.onPeerDisconnected(peerInfo.id)
|
||||
if (!this.registrar.getConnection(peerId)) {
|
||||
this.emit('peer:disconnect', peerId)
|
||||
this.metrics && this.metrics.onPeerDisconnected(peerId)
|
||||
}
|
||||
}
|
||||
})
|
||||
@ -134,7 +139,8 @@ class Libp2p extends EventEmitter {
|
||||
// Add the identify service since we can multiplex
|
||||
this.identifyService = new IdentifyService({
|
||||
registrar: this.registrar,
|
||||
peerInfo: this.peerInfo,
|
||||
peerId: this.peerId,
|
||||
addresses: this.addresses,
|
||||
protocols: this.upgrader.protocols
|
||||
})
|
||||
this.handle(Object.values(IDENTIFY_PROTOCOLS), this.identifyService.handleMessage)
|
||||
@ -152,7 +158,7 @@ class Libp2p extends EventEmitter {
|
||||
const DHT = this._modules.dht
|
||||
this._dht = new DHT({
|
||||
dialer: this.dialer,
|
||||
peerInfo: this.peerInfo,
|
||||
peerId: this.peerId,
|
||||
peerStore: this.peerStore,
|
||||
registrar: this.registrar,
|
||||
datastore: this.datastore,
|
||||
@ -264,10 +270,9 @@ class Libp2p extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Dials to the provided peer. If successful, the `PeerInfo` of the
|
||||
* Dials to the provided peer. If successful, the known `PeerData` of the
|
||||
* peer will be added to the nodes `peerStore`
|
||||
*
|
||||
* @param {PeerInfo|PeerId|Multiaddr|string} peer The peer to dial
|
||||
* @param {PeerId|Multiaddr|string} peer The peer to dial
|
||||
* @param {object} options
|
||||
* @param {AbortSignal} [options.signal]
|
||||
* @returns {Promise<Connection>}
|
||||
@ -278,30 +283,21 @@ class Libp2p extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Dials to the provided peer and handshakes with the given protocol.
|
||||
* If successful, the `PeerInfo` of the peer will be added to the nodes `peerStore`,
|
||||
* and the `Connection` will be sent in the callback
|
||||
*
|
||||
* If successful, the known `PeerData` of the peer will be added to the nodes `peerStore`,
|
||||
* and the `Connection` will be returned
|
||||
* @async
|
||||
* @param {PeerInfo|PeerId|Multiaddr|string} peer The peer to dial
|
||||
* @param {PeerId|Multiaddr|string} peer The peer to dial
|
||||
* @param {string[]|string} protocols
|
||||
* @param {object} options
|
||||
* @param {AbortSignal} [options.signal]
|
||||
* @returns {Promise<Connection|*>}
|
||||
*/
|
||||
async dialProtocol (peer, protocols, options) {
|
||||
const dialable = Dialer.getDialable(peer)
|
||||
let connection
|
||||
if (PeerInfo.isPeerInfo(dialable)) {
|
||||
// TODO Inconsistency from: getDialable adds a set, while regular peerInfo uses a Multiaddr set
|
||||
// This should be handled on `peer-info` removal
|
||||
const multiaddrs = dialable.multiaddrs.toArray ? dialable.multiaddrs.toArray() : Array.from(dialable.multiaddrs)
|
||||
this.peerStore.addressBook.add(dialable.id, multiaddrs)
|
||||
|
||||
connection = this.registrar.getConnection(dialable)
|
||||
}
|
||||
const peerId = getPeerId(peer, this.peerStore)
|
||||
let connection = this.registrar.getConnection(peerId)
|
||||
|
||||
if (!connection) {
|
||||
connection = await this.dialer.connectToPeer(dialable, options)
|
||||
connection = await this.dialer.connectToPeer(peer, options)
|
||||
}
|
||||
|
||||
// If a protocol was provided, create a new stream
|
||||
@ -314,14 +310,13 @@ class Libp2p extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Disconnects all connections to the given `peer`
|
||||
*
|
||||
* @param {PeerInfo|PeerId|multiaddr|string} peer the peer to close connections to
|
||||
* @param {PeerId|multiaddr|string} peer the peer to close connections to
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async hangUp (peer) {
|
||||
const peerInfo = getPeerInfo(peer, this.peerStore)
|
||||
const peerId = getPeerId(peer)
|
||||
|
||||
const connections = this.registrar.connections.get(peerInfo.id.toB58String())
|
||||
const connections = this.registrar.connections.get(peerId.toB58String())
|
||||
|
||||
if (!connections) {
|
||||
return
|
||||
@ -335,14 +330,14 @@ class Libp2p extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pings the given peer
|
||||
* @param {PeerInfo|PeerId|Multiaddr|string} peer The peer to ping
|
||||
* Pings the given peer in order to obtain the operation latency.
|
||||
* @param {PeerId|Multiaddr|string} peer The peer to ping
|
||||
* @returns {Promise<number>}
|
||||
*/
|
||||
async ping (peer) {
|
||||
const peerInfo = await getPeerInfo(peer, this.peerStore)
|
||||
ping (peer) {
|
||||
const peerId = getPeerId(peer)
|
||||
|
||||
return ping(this, peerInfo.id)
|
||||
return ping(this, peerId)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -380,17 +375,14 @@ class Libp2p extends EventEmitter {
|
||||
}
|
||||
|
||||
async _onStarting () {
|
||||
// Listen on the addresses supplied in the peerInfo
|
||||
const multiaddrs = this.peerInfo.multiaddrs.toArray()
|
||||
// Listen on the addresses provided
|
||||
const multiaddrs = this.addresses.listen
|
||||
|
||||
await this.transportManager.listen(multiaddrs)
|
||||
|
||||
// The addresses may change once the listener starts
|
||||
// eg /ip4/0.0.0.0/tcp/0 => /ip4/192.168.1.0/tcp/58751
|
||||
this.peerInfo.multiaddrs.clear()
|
||||
for (const ma of this.transportManager.getAddrs()) {
|
||||
this.peerInfo.multiaddrs.add(ma)
|
||||
}
|
||||
this.addresses.listen = this.transportManager.getAddrs()
|
||||
|
||||
if (this._config.pubsub.enabled) {
|
||||
this.pubsub && this.pubsub.start()
|
||||
@ -418,18 +410,18 @@ class Libp2p extends EventEmitter {
|
||||
|
||||
this.connectionManager.start()
|
||||
|
||||
this.peerStore.on('peer', peerInfo => {
|
||||
this.emit('peer:discovery', peerInfo)
|
||||
this._maybeConnect(peerInfo)
|
||||
this.peerStore.on('peer', peerId => {
|
||||
this.emit('peer:discovery', peerId)
|
||||
this._maybeConnect(peerId)
|
||||
})
|
||||
|
||||
// Peer discovery
|
||||
await this._setupPeerDiscovery()
|
||||
|
||||
// Once we start, emit and dial any peers we may have already discovered
|
||||
for (const peerInfo of this.peerStore.peers.values()) {
|
||||
this.emit('peer:discovery', peerInfo)
|
||||
this._maybeConnect(peerInfo)
|
||||
for (const peerData of this.peerStore.peers.values()) {
|
||||
this.emit('peer:discovery', peerData.id)
|
||||
this._maybeConnect(peerData.id)
|
||||
}
|
||||
}
|
||||
|
||||
@ -437,34 +429,33 @@ class Libp2p extends EventEmitter {
|
||||
* Called whenever peer discovery services emit `peer` events.
|
||||
* Known peers may be emitted.
|
||||
* @private
|
||||
* @param {PeerInfo} peerInfo
|
||||
* @param {PeerDara} peerData
|
||||
*/
|
||||
_onDiscoveryPeer (peerInfo) {
|
||||
if (peerInfo.id.toB58String() === this.peerInfo.id.toB58String()) {
|
||||
_onDiscoveryPeer (peerData) {
|
||||
if (peerData.id.toB58String() === this.peerId.toB58String()) {
|
||||
log.error(new Error(codes.ERR_DISCOVERED_SELF))
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: once we deprecate peer-info, we should only set if we have data
|
||||
this.peerStore.addressBook.add(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
this.peerStore.protoBook.set(peerInfo.id, Array.from(peerInfo.protocols))
|
||||
peerData.multiaddrs && this.peerStore.addressBook.add(peerData.id, peerData.multiaddrs)
|
||||
peerData.protocols && this.peerStore.protoBook.set(peerData.id, peerData.protocols)
|
||||
}
|
||||
|
||||
/**
|
||||
* Will dial to the given `peerInfo` if the current number of
|
||||
* Will dial to the given `peerId` if the current number of
|
||||
* connected peers is less than the configured `ConnectionManager`
|
||||
* minPeers.
|
||||
* @private
|
||||
* @param {PeerInfo} peerInfo
|
||||
* @param {PeerId} peerId
|
||||
*/
|
||||
async _maybeConnect (peerInfo) {
|
||||
async _maybeConnect (peerId) {
|
||||
// If auto dialing is on and we have no connection to the peer, check if we should dial
|
||||
if (this._config.peerDiscovery.autoDial === true && !this.registrar.getConnection(peerInfo)) {
|
||||
if (this._config.peerDiscovery.autoDial === true && !this.registrar.getConnection(peerId)) {
|
||||
const minPeers = this._options.connectionManager.minPeers || 0
|
||||
if (minPeers > this.connectionManager._connections.size) {
|
||||
log('connecting to discovered peer %s', peerInfo.id.toB58String())
|
||||
log('connecting to discovered peer %s', peerId.toB58String())
|
||||
try {
|
||||
await this.dialer.connectToPeer(peerInfo)
|
||||
await this.dialer.connectToPeer(peerId)
|
||||
} catch (err) {
|
||||
log.error('could not connect to discovered peer', err)
|
||||
}
|
||||
@ -495,7 +486,11 @@ class Libp2p extends EventEmitter {
|
||||
let discoveryService
|
||||
|
||||
if (typeof DiscoveryService === 'function') {
|
||||
discoveryService = new DiscoveryService(Object.assign({}, config, { peerInfo: this.peerInfo, libp2p: this }))
|
||||
discoveryService = new DiscoveryService(Object.assign({}, config, {
|
||||
peerId: this.peerId,
|
||||
multiaddrs: this.addresses.listen,
|
||||
libp2p: this
|
||||
}))
|
||||
} else {
|
||||
discoveryService = DiscoveryService
|
||||
}
|
||||
@ -522,19 +517,19 @@ class Libp2p extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `new Libp2p(options)` except it will create a `PeerInfo`
|
||||
* Like `new Libp2p(options)` except it will create a `PeerId`
|
||||
* instance if one is not provided in options.
|
||||
* @param {object} options Libp2p configuration options
|
||||
* @returns {Libp2p}
|
||||
*/
|
||||
Libp2p.create = async function create (options = {}) {
|
||||
if (options.peerInfo) {
|
||||
if (options.peerId) {
|
||||
return new Libp2p(options)
|
||||
}
|
||||
|
||||
const peerInfo = await PeerInfo.create()
|
||||
const peerId = await PeerId.create()
|
||||
|
||||
options.peerInfo = peerInfo
|
||||
options.peerId = peerId
|
||||
return new Libp2p(options)
|
||||
}
|
||||
|
||||
|
@ -18,7 +18,7 @@ module.exports = (node) => {
|
||||
* @param {String} id The id of the peer to find
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.timeout] How long the query should run
|
||||
* @returns {Promise<PeerInfo>}
|
||||
* @returns {Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>}
|
||||
*/
|
||||
findPeer: async (id, options) => { // eslint-disable-line require-await
|
||||
if (!routers.length) {
|
||||
|
@ -7,7 +7,6 @@ log.error = debug('libp2p:peer-store:address-book:error')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
const Book = require('./book')
|
||||
|
||||
@ -83,19 +82,13 @@ class AddressBook extends Book {
|
||||
this._setPeerId(peerId)
|
||||
log(`stored provided multiaddrs for ${id}`)
|
||||
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
multiaddrInfos.forEach((mi) => peerInfo.multiaddrs.add(mi.multiaddr))
|
||||
|
||||
// Notify the existance of a new peer
|
||||
if (!rec) {
|
||||
// this._ps.emit('peer', peerId)
|
||||
this._ps.emit('peer', peerInfo)
|
||||
this._ps.emit('peer', peerId)
|
||||
}
|
||||
|
||||
this._ps.emit('change:multiaddrs', {
|
||||
peerId,
|
||||
peerInfo,
|
||||
multiaddrs: multiaddrInfos.map((mi) => mi.multiaddr)
|
||||
})
|
||||
|
||||
@ -139,20 +132,14 @@ class AddressBook extends Book {
|
||||
|
||||
log(`added provided multiaddrs for ${id}`)
|
||||
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
multiaddrInfos.forEach((mi) => peerInfo.multiaddrs.add(mi.multiaddr))
|
||||
|
||||
this._ps.emit('change:multiaddrs', {
|
||||
peerId,
|
||||
peerInfo,
|
||||
multiaddrs: multiaddrInfos.map((mi) => mi.multiaddr)
|
||||
})
|
||||
|
||||
// Notify the existance of a new peer
|
||||
if (!rec) {
|
||||
// this._ps.emit('peer', peerId)
|
||||
this._ps.emit('peer', peerInfo)
|
||||
this._ps.emit('peer', peerId)
|
||||
}
|
||||
|
||||
return this
|
||||
|
@ -2,7 +2,6 @@
|
||||
|
||||
const errcode = require('err-code')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
const {
|
||||
ERR_INVALID_PARAMETERS
|
||||
@ -71,12 +70,8 @@ class Book {
|
||||
return false
|
||||
}
|
||||
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
|
||||
this._ps.emit(this.eventName, {
|
||||
peerId,
|
||||
peerInfo,
|
||||
[this.eventProperty]: []
|
||||
})
|
||||
|
||||
|
@ -6,9 +6,7 @@ const log = debug('libp2p:peer-store')
|
||||
log.error = debug('libp2p:peer-store:error')
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
const AddressBook = require('./address-book')
|
||||
const ProtoBook = require('./proto-book')
|
||||
@ -25,8 +23,9 @@ const {
|
||||
*/
|
||||
class PeerStore extends EventEmitter {
|
||||
/**
|
||||
* PeerInfo object
|
||||
* @typedef {Object} peerInfo
|
||||
* PeerData object
|
||||
* @typedef {Object} PeerData
|
||||
* @property {PeerId} id peer's peer-id instance.
|
||||
* @property {Array<multiaddrInfo>} multiaddrsInfos peer's information of the multiaddrs.
|
||||
* @property {Array<string>} protocols peer's supported protocols.
|
||||
*/
|
||||
@ -54,49 +53,35 @@ class PeerStore extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Get all the stored information of every peer.
|
||||
* @returns {Map<string, peerInfo>}
|
||||
* @returns {Map<string, PeerData>}
|
||||
*/
|
||||
get peers () {
|
||||
const peerInfos = new Map()
|
||||
const peersData = new Map()
|
||||
|
||||
// AddressBook
|
||||
for (const [idStr, multiaddrInfos] of this.addressBook.data.entries()) {
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(PeerId.createFromCID(idStr))
|
||||
|
||||
multiaddrInfos.forEach((mi) => peerInfo.multiaddrs.add((mi.multiaddr)))
|
||||
|
||||
const protocols = this.protoBook.data.get(idStr) || []
|
||||
protocols.forEach((p) => peerInfo.protocols.add(p))
|
||||
|
||||
peerInfos.set(idStr, peerInfo)
|
||||
// TODO
|
||||
// peerInfos.set(idStr, {
|
||||
// id: PeerId.createFromCID(idStr),
|
||||
// multiaddrInfos,
|
||||
// protocols: this.protoBook.data.get(idStr) || []
|
||||
// })
|
||||
const id = PeerId.createFromCID(idStr)
|
||||
peersData.set(idStr, {
|
||||
id,
|
||||
multiaddrInfos,
|
||||
protocols: this.protoBook.get(id) || []
|
||||
})
|
||||
}
|
||||
|
||||
// ProtoBook
|
||||
for (const [idStr, protocols] of this.protoBook.data.entries()) {
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = peerInfos.get(idStr)
|
||||
const pData = peersData.get(idStr)
|
||||
|
||||
if (!peerInfo) {
|
||||
const peerInfo = new PeerInfo(PeerId.createFromCID(idStr))
|
||||
|
||||
protocols.forEach((p) => peerInfo.protocols.add(p))
|
||||
peerInfos.set(idStr, peerInfo)
|
||||
// peerInfos.set(idStr, {
|
||||
// id: PeerId.createFromCID(idStr),
|
||||
// multiaddrInfos: [],
|
||||
// protocols: protocols
|
||||
// })
|
||||
if (!pData) {
|
||||
peersData.set(idStr, {
|
||||
id: PeerId.createFromCID(idStr),
|
||||
multiaddrInfos: [],
|
||||
protocols: Array.from(protocols)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return peerInfos
|
||||
return peersData
|
||||
}
|
||||
|
||||
/**
|
||||
@ -113,7 +98,7 @@ class PeerStore extends EventEmitter {
|
||||
/**
|
||||
* Get the stored information of a given peer.
|
||||
* @param {PeerId} peerId
|
||||
* @returns {peerInfo}
|
||||
* @returns {PeerData}
|
||||
*/
|
||||
get (peerId) {
|
||||
if (!PeerId.isPeerId(peerId)) {
|
||||
|
@ -6,7 +6,6 @@ const log = debug('libp2p:peer-store:proto-book')
|
||||
log.error = debug('libp2p:peer-store:proto-book:error')
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
const Book = require('./book')
|
||||
|
||||
@ -74,13 +73,8 @@ class ProtoBook extends Book {
|
||||
this._setPeerId(peerId)
|
||||
log(`stored provided protocols for ${id}`)
|
||||
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
protocols.forEach((p) => peerInfo.protocols.add(p))
|
||||
|
||||
this._ps.emit('change:protocols', {
|
||||
peerId,
|
||||
peerInfo,
|
||||
protocols
|
||||
})
|
||||
|
||||
@ -122,13 +116,8 @@ class ProtoBook extends Book {
|
||||
this._setPeerId(peerId)
|
||||
log(`added provided protocols for ${id}`)
|
||||
|
||||
// TODO: Remove peerInfo and its usage on peer-info deprecate
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
protocols.forEach((p) => peerInfo.protocols.add(p))
|
||||
|
||||
this._ps.emit('change:protocols', {
|
||||
peerId,
|
||||
peerInfo,
|
||||
protocols
|
||||
})
|
||||
|
||||
|
@ -5,7 +5,7 @@ const errCode = require('err-code')
|
||||
const { messages, codes } = require('./errors')
|
||||
|
||||
module.exports = (node, Pubsub, config) => {
|
||||
const pubsub = new Pubsub(node.peerInfo, node.registrar, config)
|
||||
const pubsub = new Pubsub(node.peerId, node.registrar, config)
|
||||
|
||||
return {
|
||||
/**
|
||||
|
@ -5,6 +5,8 @@ const errcode = require('err-code')
|
||||
const log = debug('libp2p:peer-store')
|
||||
log.error = debug('libp2p:peer-store:error')
|
||||
|
||||
const PeerId = require('peer-id')
|
||||
|
||||
const {
|
||||
ERR_INVALID_PARAMETERS
|
||||
} = require('./errors')
|
||||
@ -69,22 +71,20 @@ class Registrar {
|
||||
/**
|
||||
* Add a new connected peer to the record
|
||||
* TODO: this should live in the ConnectionManager
|
||||
* @param {PeerInfo} peerInfo
|
||||
* @param {PeerId} peerId
|
||||
* @param {Connection} conn
|
||||
* @returns {void}
|
||||
*/
|
||||
onConnect (peerInfo, conn) {
|
||||
// TODO: This is not a `peer-info` instance anymore, but an object with the data.
|
||||
// This can be modified to `peer-id` though, once `peer-info` is deprecated.
|
||||
// if (!PeerInfo.isPeerInfo(peerInfo)) {
|
||||
// throw errcode(new Error('peerInfo must be an instance of peer-info'), ERR_INVALID_PARAMETERS)
|
||||
// }
|
||||
onConnect (peerId, conn) {
|
||||
if (!PeerId.isPeerId(peerId)) {
|
||||
throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
|
||||
}
|
||||
|
||||
if (!Connection.isConnection(conn)) {
|
||||
throw errcode(new Error('conn must be an instance of interface-connection'), ERR_INVALID_PARAMETERS)
|
||||
}
|
||||
|
||||
const id = peerInfo.id.toB58String()
|
||||
const id = peerId.toB58String()
|
||||
const storedConn = this.connections.get(id)
|
||||
|
||||
if (storedConn) {
|
||||
@ -97,19 +97,17 @@ class Registrar {
|
||||
/**
|
||||
* Remove a disconnected peer from the record
|
||||
* TODO: this should live in the ConnectionManager
|
||||
* @param {PeerInfo} peerInfo
|
||||
* @param {PeerId} peerId
|
||||
* @param {Connection} connection
|
||||
* @param {Error} [error]
|
||||
* @returns {void}
|
||||
*/
|
||||
onDisconnect (peerInfo, connection, error) {
|
||||
// TODO: This is not a `peer-info` instance anymore, but an object with the data.
|
||||
// This can be modified to `peer-id` though, once `peer-info` is deprecated.
|
||||
// if (!PeerInfo.isPeerInfo(peerInfo)) {
|
||||
// throw errcode(new Error('peerInfo must be an instance of peer-info'), ERR_INVALID_PARAMETERS)
|
||||
// }
|
||||
onDisconnect (peerId, connection, error) {
|
||||
if (!PeerId.isPeerId(peerId)) {
|
||||
throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
|
||||
}
|
||||
|
||||
const id = peerInfo.id.toB58String()
|
||||
const id = peerId.toB58String()
|
||||
let storedConn = this.connections.get(id)
|
||||
|
||||
if (storedConn && storedConn.length > 1) {
|
||||
@ -117,26 +115,24 @@ class Registrar {
|
||||
this.connections.set(id, storedConn)
|
||||
} else if (storedConn) {
|
||||
for (const [, topology] of this.topologies) {
|
||||
topology.disconnect(peerInfo, error)
|
||||
topology.disconnect(peerId, error)
|
||||
}
|
||||
|
||||
this.connections.delete(peerInfo.id.toB58String())
|
||||
this.connections.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a connection with a peer.
|
||||
* @param {PeerInfo} peerInfo
|
||||
* @param {PeerId} peerId
|
||||
* @returns {Connection}
|
||||
*/
|
||||
getConnection (peerInfo) {
|
||||
// TODO: This is not a `peer-info` instance anymore, but an object with the data.
|
||||
// This can be modified to `peer-id` though, once `peer-info` is deprecated.
|
||||
// if (!PeerInfo.isPeerInfo(peerInfo)) {
|
||||
// throw errcode(new Error('peerInfo must be an instance of peer-info'), ERR_INVALID_PARAMETERS)
|
||||
// }
|
||||
getConnection (peerId) {
|
||||
if (!PeerId.isPeerId(peerId)) {
|
||||
throw errcode(new Error('peerId must be an instance of peer-id'), ERR_INVALID_PARAMETERS)
|
||||
}
|
||||
|
||||
const connections = this.connections.get(peerInfo.id.toB58String())
|
||||
const connections = this.connections.get(peerId.toB58String())
|
||||
// Return the first, open connection
|
||||
if (connections) {
|
||||
return connections.find(connection => connection.stat.status === 'open')
|
||||
|
@ -56,7 +56,7 @@ describe('content-routing', () => {
|
||||
|
||||
// Ring dial
|
||||
await Promise.all(
|
||||
nodes.map((peer, i) => peer.dial(nodes[(i + 1) % number].peerInfo))
|
||||
nodes.map((peer, i) => peer.dial(nodes[(i + 1) % number].peerId))
|
||||
)
|
||||
})
|
||||
|
||||
@ -96,9 +96,9 @@ describe('content-routing', () => {
|
||||
let delegate
|
||||
|
||||
beforeEach(async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo({ fixture: false })
|
||||
const [peerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
delegate = new DelegatedContentRouter(peerInfo.id, {
|
||||
delegate = new DelegatedContentRouter(peerId, {
|
||||
host: '0.0.0.0',
|
||||
protocol: 'http',
|
||||
port: 60197
|
||||
@ -227,9 +227,9 @@ describe('content-routing', () => {
|
||||
let delegate
|
||||
|
||||
beforeEach(async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo({ fixture: false })
|
||||
const [peerId] = await peerUtils.createPeerId({ fixture: false })
|
||||
|
||||
delegate = new DelegatedContentRouter(peerInfo.id, {
|
||||
delegate = new DelegatedContentRouter(peerId, {
|
||||
host: '0.0.0.0',
|
||||
protocol: 'http',
|
||||
port: 60197
|
||||
|
@ -32,11 +32,13 @@ describe('DHT subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should start and stop by default once libp2p starts', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo(1)
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId(1)
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
})
|
||||
|
||||
libp2p = await create(customOptions)
|
||||
@ -50,11 +52,13 @@ describe('DHT subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should not start if disabled once libp2p starts', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo(1)
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId(1)
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
config: {
|
||||
dht: {
|
||||
enabled: false
|
||||
@ -70,11 +74,13 @@ describe('DHT subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should allow a manual start', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo(1)
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId(1)
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
config: {
|
||||
dht: {
|
||||
enabled: false
|
||||
|
@ -18,25 +18,28 @@ const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/8000')
|
||||
const remoteListenAddr = multiaddr('/ip4/127.0.0.1/tcp/8001')
|
||||
|
||||
describe('DHT subsystem operates correctly', () => {
|
||||
let peerInfo, remotePeerInfo
|
||||
let peerId, remotePeerId
|
||||
let libp2p, remoteLibp2p
|
||||
let remAddr
|
||||
|
||||
beforeEach(async () => {
|
||||
[peerInfo, remotePeerInfo] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
remotePeerInfo.multiaddrs.add(remoteListenAddr)
|
||||
[peerId, remotePeerId] = await peerUtils.createPeerId({ number: 2 })
|
||||
})
|
||||
|
||||
describe('dht started before connect', () => {
|
||||
beforeEach(async () => {
|
||||
libp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
remoteLibp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo: remotePeerInfo
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [remoteListenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
await Promise.all([
|
||||
@ -44,8 +47,8 @@ describe('DHT subsystem operates correctly', () => {
|
||||
remoteLibp2p.start()
|
||||
])
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerInfo.id, [remoteListenAddr])
|
||||
remAddr = libp2p.peerStore.addressBook.getMultiaddrsForPeer(remotePeerInfo.id)[0]
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, [remoteListenAddr])
|
||||
remAddr = libp2p.peerStore.addressBook.getMultiaddrsForPeer(remotePeerId)[0]
|
||||
})
|
||||
|
||||
afterEach(() => Promise.all([
|
||||
@ -84,11 +87,17 @@ describe('DHT subsystem operates correctly', () => {
|
||||
describe('dht started after connect', () => {
|
||||
beforeEach(async () => {
|
||||
libp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
remoteLibp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo: remotePeerInfo,
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [remoteListenAddr]
|
||||
},
|
||||
config: {
|
||||
dht: {
|
||||
enabled: false
|
||||
@ -99,8 +108,8 @@ describe('DHT subsystem operates correctly', () => {
|
||||
await libp2p.start()
|
||||
await remoteLibp2p.start()
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerInfo.id, [remoteListenAddr])
|
||||
remAddr = libp2p.peerStore.addressBook.getMultiaddrsForPeer(remotePeerInfo.id)[0]
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, [remoteListenAddr])
|
||||
remAddr = libp2p.peerStore.addressBook.getMultiaddrsForPeer(remotePeerId)[0]
|
||||
})
|
||||
|
||||
afterEach(() => Promise.all([
|
||||
|
@ -14,12 +14,11 @@ const peerUtils = require('../utils/creators/peer')
|
||||
const listenAddr = multiaddr('/ip4/0.0.0.0/tcp/0')
|
||||
|
||||
describe('Listening', () => {
|
||||
let peerInfo
|
||||
let peerId
|
||||
let libp2p
|
||||
|
||||
before(async () => {
|
||||
[peerInfo] = await peerUtils.createPeerInfo()
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
[peerId] = await peerUtils.createPeerId()
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
@ -28,7 +27,10 @@ describe('Listening', () => {
|
||||
|
||||
it('should replace wildcard host and port with actual host and port on startup', async () => {
|
||||
libp2p = await create({
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
transport: [Transport]
|
||||
}
|
||||
@ -36,7 +38,7 @@ describe('Listening', () => {
|
||||
|
||||
await libp2p.start()
|
||||
|
||||
const addrs = libp2p.peerInfo.multiaddrs.toArray()
|
||||
const addrs = libp2p.addresses.listen
|
||||
|
||||
// Should get something like:
|
||||
// /ip4/127.0.0.1/tcp/50866
|
||||
|
@ -20,16 +20,19 @@ describe('ping', () => {
|
||||
number: 2,
|
||||
config: baseOptions
|
||||
})
|
||||
|
||||
nodes[0].peerStore.addressBook.set(nodes[1].peerId, nodes[1].addresses.listen)
|
||||
nodes[1].peerStore.addressBook.set(nodes[0].peerId, nodes[0].addresses.listen)
|
||||
})
|
||||
|
||||
it('ping once from peer0 to peer1', async () => {
|
||||
const latency = await nodes[0].ping(nodes[1].peerInfo)
|
||||
const latency = await nodes[0].ping(nodes[1].peerId)
|
||||
|
||||
expect(latency).to.be.a('Number')
|
||||
})
|
||||
|
||||
it('ping several times for getting an average', async () => {
|
||||
const latencies = await pTimes(5, () => nodes[1].ping(nodes[0].peerInfo))
|
||||
const latencies = await pTimes(5, () => nodes[1].ping(nodes[0].peerId))
|
||||
|
||||
const averageLatency = latencies.reduce((p, c) => p + c, 0) / latencies.length
|
||||
expect(averageLatency).to.be.a('Number')
|
||||
@ -66,7 +69,7 @@ describe('ping', () => {
|
||||
)
|
||||
})
|
||||
|
||||
const latency = await nodes[0].ping(nodes[1].peerInfo)
|
||||
const latency = await nodes[0].ping(nodes[1].peerId)
|
||||
|
||||
expect(latency).to.be.a('Number')
|
||||
})
|
||||
|
@ -12,7 +12,6 @@ const Muxer = require('libp2p-mplex')
|
||||
const Crypto = require('libp2p-secio')
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const delay = require('delay')
|
||||
const pDefer = require('p-defer')
|
||||
const pSettle = require('p-settle')
|
||||
@ -32,7 +31,7 @@ const swarmKeyBuffer = Buffer.from(require('../fixtures/swarm.key'))
|
||||
const mockUpgrader = require('../utils/mockUpgrader')
|
||||
const createMockConnection = require('../utils/mockConnection')
|
||||
const Peers = require('../fixtures/peers')
|
||||
const { createPeerInfo } = require('../utils/creators/peer')
|
||||
const { createPeerId } = require('../utils/creators/peer')
|
||||
|
||||
const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
const unsupportedAddr = multiaddr('/ip4/127.0.0.1/tcp/9999/ws/p2p/QmckxVrJw1Yo8LqvmDJNUmdAsKtSbiKWmrXJFyKmUraBoN')
|
||||
@ -81,9 +80,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should be able to connect to a remote node via its stringified multiaddr', async () => {
|
||||
const dialer = new Dialer({ transportManager: localTM, peerStore })
|
||||
|
||||
const dialable = Dialer.getDialable(remoteAddr.toString())
|
||||
const connection = await dialer.connectToPeer(dialable)
|
||||
const connection = await dialer.connectToPeer(remoteAddr.toString())
|
||||
expect(connection).to.exist()
|
||||
await connection.close()
|
||||
})
|
||||
@ -96,24 +93,6 @@ describe('Dialing (direct, TCP)', () => {
|
||||
.and.to.have.nested.property('._errors[0].code', ErrorCodes.ERR_TRANSPORT_UNAVAILABLE)
|
||||
})
|
||||
|
||||
it('should be able to connect to a given peer info', async () => {
|
||||
const dialer = new Dialer({
|
||||
transportManager: localTM,
|
||||
peerStore: {
|
||||
addressBook: {
|
||||
add: () => {},
|
||||
getMultiaddrsForPeer: () => [remoteAddr]
|
||||
}
|
||||
}
|
||||
})
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
|
||||
const connection = await dialer.connectToPeer(peerInfo)
|
||||
expect(connection).to.exist()
|
||||
await connection.close()
|
||||
})
|
||||
|
||||
it('should be able to connect to a given peer id', async () => {
|
||||
const peerStore = new PeerStore()
|
||||
const dialer = new Dialer({
|
||||
@ -122,11 +101,9 @@ describe('Dialing (direct, TCP)', () => {
|
||||
})
|
||||
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
peerInfo.multiaddrs.add(remoteAddr)
|
||||
peerStore.addressBook.set(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
peerStore.addressBook.set(peerId, [remoteAddr])
|
||||
|
||||
const connection = await dialer.connectToPeer(peerInfo)
|
||||
const connection = await dialer.connectToPeer(peerId)
|
||||
expect(connection).to.exist()
|
||||
await connection.close()
|
||||
})
|
||||
@ -142,9 +119,8 @@ describe('Dialing (direct, TCP)', () => {
|
||||
}
|
||||
})
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
const peerInfo = new PeerInfo(peerId)
|
||||
|
||||
await expect(dialer.connectToPeer(peerInfo))
|
||||
await expect(dialer.connectToPeer(peerId))
|
||||
.to.eventually.be.rejectedWith(AggregateError)
|
||||
.and.to.have.nested.property('._errors[0].code', ErrorCodes.ERR_TRANSPORT_UNAVAILABLE)
|
||||
})
|
||||
@ -191,10 +167,10 @@ describe('Dialing (direct, TCP)', () => {
|
||||
const deferredDial = pDefer()
|
||||
sinon.stub(localTM, 'dial').callsFake(() => deferredDial.promise)
|
||||
|
||||
const [peerInfo] = await createPeerInfo()
|
||||
const [peerId] = await createPeerId()
|
||||
|
||||
// Perform 3 multiaddr dials
|
||||
dialer.connectToPeer(peerInfo)
|
||||
dialer.connectToPeer(peerId)
|
||||
|
||||
// Let the call stack run
|
||||
await delay(0)
|
||||
@ -213,30 +189,28 @@ describe('Dialing (direct, TCP)', () => {
|
||||
})
|
||||
|
||||
describe('libp2p.dialer', () => {
|
||||
let peerInfo
|
||||
let remotePeerInfo
|
||||
let peerId, remotePeerId
|
||||
let libp2p
|
||||
let remoteLibp2p
|
||||
let remoteAddr
|
||||
|
||||
before(async () => {
|
||||
const [peerId, remotePeerId] = await Promise.all([
|
||||
[peerId, remotePeerId] = await Promise.all([
|
||||
PeerId.createFromJSON(Peers[0]),
|
||||
PeerId.createFromJSON(Peers[1])
|
||||
])
|
||||
|
||||
peerInfo = new PeerInfo(peerId)
|
||||
remotePeerInfo = new PeerInfo(remotePeerId)
|
||||
|
||||
remoteLibp2p = new Libp2p({
|
||||
peerInfo: remotePeerInfo,
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
connEncryption: [Crypto]
|
||||
}
|
||||
})
|
||||
remoteLibp2p.peerInfo.multiaddrs.add(listenAddr)
|
||||
remoteLibp2p.handle('/echo/1.0.0', ({ stream }) => pipe(stream, stream))
|
||||
|
||||
await remoteLibp2p.start()
|
||||
@ -253,7 +227,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should fail if no peer id is provided', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -266,7 +240,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
try {
|
||||
await libp2p.dial(remoteLibp2p.transportManager.getAddrs()[0])
|
||||
} catch (err) {
|
||||
expect(err).to.have.property('code', ErrorCodes.ERR_INVALID_PEER)
|
||||
expect(err).to.have.property('code', ErrorCodes.ERR_INVALID_MULTIADDR)
|
||||
return
|
||||
}
|
||||
|
||||
@ -275,7 +249,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should use the dialer for connecting to a multiaddr', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -296,7 +270,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should use the dialer for connecting to a peer', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -305,8 +279,9 @@ describe('Dialing (direct, TCP)', () => {
|
||||
})
|
||||
|
||||
sinon.spy(libp2p.dialer, 'connectToPeer')
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
|
||||
const connection = await libp2p.dial(remotePeerInfo)
|
||||
const connection = await libp2p.dial(remotePeerId)
|
||||
expect(connection).to.exist()
|
||||
const { stream, protocol } = await connection.newStream('/echo/1.0.0')
|
||||
expect(stream).to.exist()
|
||||
@ -317,7 +292,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should be able to use hangup to close connections', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -334,7 +309,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should be able to use hangup by address string to close connections', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -352,7 +327,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
it('should use the protectors when provided for connecting', async () => {
|
||||
const protector = new Protector(swarmKeyBuffer)
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -375,7 +350,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should coalesce parallel dials to the same peer (id in multiaddr)', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -384,9 +359,11 @@ describe('Dialing (direct, TCP)', () => {
|
||||
})
|
||||
const dials = 10
|
||||
|
||||
const fullAddress = remoteAddr.encapsulate(`/p2p/${remoteLibp2p.peerInfo.id.toB58String()}`)
|
||||
const fullAddress = remoteAddr.encapsulate(`/p2p/${remoteLibp2p.peerId.toB58String()}`)
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
const dialResults = await Promise.all([...new Array(dials)].map((_, index) => {
|
||||
if (index % 2 === 0) return libp2p.dial(remoteLibp2p.peerInfo)
|
||||
if (index % 2 === 0) return libp2p.dial(remoteLibp2p.peerId)
|
||||
return libp2p.dial(fullAddress)
|
||||
}))
|
||||
|
||||
@ -403,7 +380,7 @@ describe('Dialing (direct, TCP)', () => {
|
||||
|
||||
it('should coalesce parallel dials to the same error on failure', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -414,8 +391,9 @@ describe('Dialing (direct, TCP)', () => {
|
||||
const error = new Error('Boom')
|
||||
sinon.stub(libp2p.transportManager, 'dial').callsFake(() => Promise.reject(error))
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
const dialResults = await pSettle([...new Array(dials)].map((_, index) => {
|
||||
if (index % 2 === 0) return libp2p.dial(remoteLibp2p.peerInfo)
|
||||
if (index % 2 === 0) return libp2p.dial(remoteLibp2p.peerId)
|
||||
return libp2p.dial(remoteAddr)
|
||||
}))
|
||||
|
||||
|
@ -14,7 +14,6 @@ const Muxer = require('libp2p-mplex')
|
||||
const Crypto = require('libp2p-secio')
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const AggregateError = require('aggregate-error')
|
||||
const { AbortError } = require('libp2p-interfaces/src/transport/errors')
|
||||
|
||||
@ -267,13 +266,12 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
})
|
||||
|
||||
describe('libp2p.dialer', () => {
|
||||
let peerInfo
|
||||
let peerId
|
||||
let libp2p
|
||||
let remoteLibp2p
|
||||
|
||||
before(async () => {
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
peerInfo = new PeerInfo(peerId)
|
||||
peerId = await PeerId.createFromJSON(Peers[0])
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -288,7 +286,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should create a dialer', () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -306,7 +304,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should be able to override dialer options', async () => {
|
||||
const config = {
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -328,7 +326,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should use the dialer for connecting', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -351,7 +349,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should run identify automatically after connecting', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -380,7 +378,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should be able to use hangup to close connections', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -410,7 +408,7 @@ describe('Dialing (direct, WebSockets)', () => {
|
||||
|
||||
it('should abort pending dials on stop', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
|
@ -6,7 +6,6 @@ const chai = require('chai')
|
||||
chai.use(require('dirty-chai'))
|
||||
chai.use(require('chai-as-promised'))
|
||||
const { expect } = chai
|
||||
const sinon = require('sinon')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
const { collect } = require('streaming-iterables')
|
||||
@ -14,25 +13,30 @@ const pipe = require('it-pipe')
|
||||
const AggregateError = require('aggregate-error')
|
||||
const PeerId = require('peer-id')
|
||||
|
||||
const { createPeerInfo } = require('../utils/creators/peer')
|
||||
const { createPeerId } = require('../utils/creators/peer')
|
||||
const baseOptions = require('../utils/base-options')
|
||||
const Libp2p = require('../../src')
|
||||
const { codes: Errors } = require('../../src/errors')
|
||||
|
||||
const listenAddr = multiaddr('/ip4/0.0.0.0/tcp/0')
|
||||
|
||||
describe('Dialing (via relay, TCP)', () => {
|
||||
let srcLibp2p
|
||||
let relayLibp2p
|
||||
let dstLibp2p
|
||||
|
||||
before(async () => {
|
||||
const peerInfos = await createPeerInfo({ number: 3 })
|
||||
const peerIds = await createPeerId({ number: 3 })
|
||||
// Create 3 nodes, and turn HOP on for the relay
|
||||
;[srcLibp2p, relayLibp2p, dstLibp2p] = peerInfos.map((peerInfo, index) => {
|
||||
;[srcLibp2p, relayLibp2p, dstLibp2p] = peerIds.map((peerId, index) => {
|
||||
const opts = baseOptions
|
||||
index === 1 && (opts.config.relay.hop.enabled = true)
|
||||
return new Libp2p({
|
||||
...opts,
|
||||
peerInfo
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
peerId
|
||||
})
|
||||
})
|
||||
|
||||
@ -41,12 +45,7 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
// Start each node
|
||||
return Promise.all([srcLibp2p, relayLibp2p, dstLibp2p].map(libp2p => {
|
||||
// Reset multiaddrs and start
|
||||
libp2p.peerInfo.multiaddrs.clear()
|
||||
libp2p.peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
||||
return libp2p.start()
|
||||
}))
|
||||
return Promise.all([srcLibp2p, relayLibp2p, dstLibp2p].map(libp2p => libp2p.start()))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@ -63,11 +62,11 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
|
||||
it('should be able to connect to a peer over a relay with active connections', async () => {
|
||||
const relayAddr = relayLibp2p.transportManager.getAddrs()[0]
|
||||
const relayIdString = relayLibp2p.peerInfo.id.toB58String()
|
||||
const relayIdString = relayLibp2p.peerId.toB58String()
|
||||
|
||||
const dialAddr = relayAddr
|
||||
.encapsulate(`/p2p/${relayIdString}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerInfo.id.toB58String()}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerId.toB58String()}`)
|
||||
|
||||
const tcpAddrs = dstLibp2p.transportManager.getAddrs()
|
||||
await dstLibp2p.transportManager.listen([multiaddr(`/p2p-circuit${relayAddr}/p2p/${relayIdString}`)])
|
||||
@ -75,14 +74,14 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
|
||||
const connection = await srcLibp2p.dial(dialAddr)
|
||||
expect(connection).to.exist()
|
||||
expect(connection.remotePeer.toBytes()).to.eql(dstLibp2p.peerInfo.id.toBytes())
|
||||
expect(connection.localPeer.toBytes()).to.eql(srcLibp2p.peerInfo.id.toBytes())
|
||||
expect(connection.remotePeer.toBytes()).to.eql(dstLibp2p.peerId.toBytes())
|
||||
expect(connection.localPeer.toBytes()).to.eql(srcLibp2p.peerId.toBytes())
|
||||
expect(connection.remoteAddr).to.eql(dialAddr)
|
||||
expect(connection.localAddr).to.eql(
|
||||
relayAddr // the relay address
|
||||
.encapsulate(`/p2p/${relayIdString}`) // with its peer id
|
||||
.encapsulate('/p2p-circuit') // the local peer is connected over the relay
|
||||
.encapsulate(`/p2p/${srcLibp2p.peerInfo.id.toB58String()}`) // and the local peer id
|
||||
.encapsulate(`/p2p/${srcLibp2p.peerId.toB58String()}`) // and the local peer id
|
||||
)
|
||||
|
||||
const { stream: echoStream } = await connection.newStream('/echo/1.0.0')
|
||||
@ -98,11 +97,11 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
|
||||
it('should fail to connect to a peer over a relay with inactive connections', async () => {
|
||||
const relayAddr = relayLibp2p.transportManager.getAddrs()[0]
|
||||
const relayIdString = relayLibp2p.peerInfo.id.toB58String()
|
||||
const relayIdString = relayLibp2p.peerId.toB58String()
|
||||
|
||||
const dialAddr = relayAddr
|
||||
.encapsulate(`/p2p/${relayIdString}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerInfo.id.toB58String()}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerId.toB58String()}`)
|
||||
|
||||
await expect(srcLibp2p.dial(dialAddr))
|
||||
.to.eventually.be.rejectedWith(AggregateError)
|
||||
@ -111,27 +110,27 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
|
||||
it('should not stay connected to a relay when not already connected and HOP fails', async () => {
|
||||
const relayAddr = relayLibp2p.transportManager.getAddrs()[0]
|
||||
const relayIdString = relayLibp2p.peerInfo.id.toB58String()
|
||||
const relayIdString = relayLibp2p.peerId.toB58String()
|
||||
|
||||
const dialAddr = relayAddr
|
||||
.encapsulate(`/p2p/${relayIdString}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerInfo.id.toB58String()}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerId.toB58String()}`)
|
||||
|
||||
await expect(srcLibp2p.dial(dialAddr))
|
||||
.to.eventually.be.rejectedWith(AggregateError)
|
||||
.and.to.have.nested.property('._errors[0].code', Errors.ERR_HOP_REQUEST_FAILED)
|
||||
|
||||
// We should not be connected to the relay, because we weren't before the dial
|
||||
const srcToRelayConn = srcLibp2p.registrar.getConnection(relayLibp2p.peerInfo)
|
||||
const srcToRelayConn = srcLibp2p.registrar.getConnection(relayLibp2p.peerId)
|
||||
expect(srcToRelayConn).to.not.exist()
|
||||
})
|
||||
|
||||
it('dialer should stay connected to an already connected relay on hop failure', async () => {
|
||||
const relayIdString = relayLibp2p.peerInfo.id.toB58String()
|
||||
const relayIdString = relayLibp2p.peerId.toB58String()
|
||||
const relayAddr = relayLibp2p.transportManager.getAddrs()[0].encapsulate(`/p2p/${relayIdString}`)
|
||||
|
||||
const dialAddr = relayAddr
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerInfo.id.toB58String()}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerId.toB58String()}`)
|
||||
|
||||
await srcLibp2p.dial(relayAddr)
|
||||
|
||||
@ -139,17 +138,17 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
.to.eventually.be.rejectedWith(AggregateError)
|
||||
.and.to.have.nested.property('._errors[0].code', Errors.ERR_HOP_REQUEST_FAILED)
|
||||
|
||||
const srcToRelayConn = srcLibp2p.registrar.getConnection(relayLibp2p.peerInfo)
|
||||
const srcToRelayConn = srcLibp2p.registrar.getConnection(relayLibp2p.peerId)
|
||||
expect(srcToRelayConn).to.exist()
|
||||
expect(srcToRelayConn.stat.status).to.equal('open')
|
||||
})
|
||||
|
||||
it('destination peer should stay connected to an already connected relay on hop failure', async () => {
|
||||
const relayIdString = relayLibp2p.peerInfo.id.toB58String()
|
||||
const relayIdString = relayLibp2p.peerId.toB58String()
|
||||
const relayAddr = relayLibp2p.transportManager.getAddrs()[0].encapsulate(`/p2p/${relayIdString}`)
|
||||
|
||||
const dialAddr = relayAddr
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerInfo.id.toB58String()}`)
|
||||
.encapsulate(`/p2p-circuit/p2p/${dstLibp2p.peerId.toB58String()}`)
|
||||
|
||||
// Connect the destination peer and the relay
|
||||
const tcpAddrs = dstLibp2p.transportManager.getAddrs()
|
||||
@ -157,15 +156,15 @@ describe('Dialing (via relay, TCP)', () => {
|
||||
expect(dstLibp2p.transportManager.getAddrs()).to.have.deep.members([...tcpAddrs, dialAddr.decapsulate('p2p')])
|
||||
|
||||
// Tamper with the our multiaddrs for the circuit message
|
||||
sinon.stub(srcLibp2p.peerInfo.multiaddrs, 'toArray').returns([{
|
||||
srcLibp2p.addresses.listen = [{
|
||||
buffer: Buffer.from('an invalid multiaddr')
|
||||
}])
|
||||
}]
|
||||
|
||||
await expect(srcLibp2p.dial(dialAddr))
|
||||
.to.eventually.be.rejectedWith(AggregateError)
|
||||
.and.to.have.nested.property('._errors[0].code', Errors.ERR_HOP_REQUEST_FAILED)
|
||||
|
||||
const dstToRelayConn = dstLibp2p.registrar.getConnection(relayLibp2p.peerInfo)
|
||||
const dstToRelayConn = dstLibp2p.registrar.getConnection(relayLibp2p.peerId)
|
||||
expect(dstToRelayConn).to.exist()
|
||||
expect(dstToRelayConn.stat.status).to.equal('open')
|
||||
})
|
||||
|
@ -9,7 +9,6 @@ const sinon = require('sinon')
|
||||
|
||||
const delay = require('delay')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const duplexPair = require('it-pair/duplex')
|
||||
const multiaddr = require('multiaddr')
|
||||
const pWaitFor = require('p-wait-for')
|
||||
@ -35,7 +34,7 @@ describe('Identify', () => {
|
||||
[localPeer, remotePeer] = (await Promise.all([
|
||||
PeerId.createFromJSON(Peers[0]),
|
||||
PeerId.createFromJSON(Peers[1])
|
||||
])).map(id => new PeerInfo(id))
|
||||
]))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@ -44,7 +43,10 @@ describe('Identify', () => {
|
||||
|
||||
it('should be able to identify another peer', async () => {
|
||||
const localIdentify = new IdentifyService({
|
||||
peerInfo: localPeer,
|
||||
peerId: localPeer,
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
protocols,
|
||||
registrar: {
|
||||
peerStore: {
|
||||
@ -58,12 +60,15 @@ describe('Identify', () => {
|
||||
}
|
||||
})
|
||||
const remoteIdentify = new IdentifyService({
|
||||
peerInfo: remotePeer,
|
||||
peerId: remotePeer,
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
protocols
|
||||
})
|
||||
|
||||
const observedAddr = multiaddr('/ip4/127.0.0.1/tcp/1234')
|
||||
const localConnectionMock = { newStream: () => {}, remotePeer: remotePeer.id }
|
||||
const localConnectionMock = { newStream: () => {}, remotePeer }
|
||||
const remoteConnectionMock = { remoteAddr: observedAddr }
|
||||
|
||||
const [local, remote] = duplexPair()
|
||||
@ -86,12 +91,15 @@ describe('Identify', () => {
|
||||
expect(localIdentify.registrar.peerStore.protoBook.set.callCount).to.equal(1)
|
||||
// Validate the remote peer gets updated in the peer store
|
||||
const call = localIdentify.registrar.peerStore.addressBook.set.firstCall
|
||||
expect(call.args[0].id.bytes).to.equal(remotePeer.id.bytes)
|
||||
expect(call.args[0].id.bytes).to.equal(remotePeer.bytes)
|
||||
})
|
||||
|
||||
it('should throw if identified peer is the wrong peer', async () => {
|
||||
const localIdentify = new IdentifyService({
|
||||
peerInfo: localPeer,
|
||||
peerId: localPeer,
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
protocols,
|
||||
registrar: {
|
||||
peerStore: {
|
||||
@ -105,12 +113,15 @@ describe('Identify', () => {
|
||||
}
|
||||
})
|
||||
const remoteIdentify = new IdentifyService({
|
||||
peerInfo: remotePeer,
|
||||
peerId: remotePeer,
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
protocols
|
||||
})
|
||||
|
||||
const observedAddr = multiaddr('/ip4/127.0.0.1/tcp/1234')
|
||||
const localConnectionMock = { newStream: () => {}, remotePeer: localPeer.id }
|
||||
const localConnectionMock = { newStream: () => {}, remotePeer: localPeer }
|
||||
const remoteConnectionMock = { remoteAddr: observedAddr }
|
||||
|
||||
const [local, remote] = duplexPair()
|
||||
@ -118,7 +129,7 @@ describe('Identify', () => {
|
||||
|
||||
// Run identify
|
||||
const identifyPromise = Promise.all([
|
||||
localIdentify.identify(localConnectionMock, localPeer.id),
|
||||
localIdentify.identify(localConnectionMock, localPeer),
|
||||
remoteIdentify.handleMessage({
|
||||
connection: remoteConnectionMock,
|
||||
stream: remote,
|
||||
@ -133,8 +144,12 @@ describe('Identify', () => {
|
||||
|
||||
describe('push', () => {
|
||||
it('should be able to push identify updates to another peer', async () => {
|
||||
const listeningAddr = multiaddr('/ip4/127.0.0.1/tcp/1234')
|
||||
const localIdentify = new IdentifyService({
|
||||
peerInfo: localPeer,
|
||||
peerId: localPeer,
|
||||
addresses: {
|
||||
listen: [listeningAddr]
|
||||
},
|
||||
registrar: { getConnection: () => {} },
|
||||
protocols: new Map([
|
||||
[multicodecs.IDENTIFY],
|
||||
@ -143,7 +158,10 @@ describe('Identify', () => {
|
||||
])
|
||||
})
|
||||
const remoteIdentify = new IdentifyService({
|
||||
peerInfo: remotePeer,
|
||||
peerId: remotePeer,
|
||||
addresses: {
|
||||
listen: []
|
||||
},
|
||||
registrar: {
|
||||
peerStore: {
|
||||
addressBook: {
|
||||
@ -158,13 +176,8 @@ describe('Identify', () => {
|
||||
|
||||
// Setup peer protocols and multiaddrs
|
||||
const localProtocols = new Set([multicodecs.IDENTIFY, multicodecs.IDENTIFY_PUSH, '/echo/1.0.0'])
|
||||
const listeningAddr = multiaddr('/ip4/127.0.0.1/tcp/1234')
|
||||
sinon.stub(localPeer.multiaddrs, 'toArray').returns([listeningAddr])
|
||||
sinon.stub(localPeer, 'protocols').value(localProtocols)
|
||||
sinon.stub(remotePeer, 'protocols').value(new Set([multicodecs.IDENTIFY, multicodecs.IDENTIFY_PUSH]))
|
||||
|
||||
const localConnectionMock = { newStream: () => {} }
|
||||
const remoteConnectionMock = { remotePeer: localPeer.id }
|
||||
const remoteConnectionMock = { remotePeer: localPeer }
|
||||
|
||||
const [local, remote] = duplexPair()
|
||||
sinon.stub(localConnectionMock, 'newStream').returns({ stream: local, protocol: multicodecs.IDENTIFY_PUSH })
|
||||
@ -185,22 +198,21 @@ describe('Identify', () => {
|
||||
expect(remoteIdentify.registrar.peerStore.addressBook.set.callCount).to.equal(1)
|
||||
expect(remoteIdentify.registrar.peerStore.protoBook.set.callCount).to.equal(1)
|
||||
const [peerId, multiaddrs] = remoteIdentify.registrar.peerStore.addressBook.set.firstCall.args
|
||||
expect(peerId.bytes).to.eql(localPeer.id.bytes)
|
||||
expect(peerId.bytes).to.eql(localPeer.bytes)
|
||||
expect(multiaddrs).to.eql([listeningAddr])
|
||||
const [peerId2, protocols] = remoteIdentify.registrar.peerStore.protoBook.set.firstCall.args
|
||||
expect(peerId2.bytes).to.eql(localPeer.id.bytes)
|
||||
expect(peerId2.bytes).to.eql(localPeer.bytes)
|
||||
expect(protocols).to.eql(Array.from(localProtocols))
|
||||
})
|
||||
})
|
||||
|
||||
describe('libp2p.dialer.identifyService', () => {
|
||||
let peerInfo
|
||||
let peerId
|
||||
let libp2p
|
||||
let remoteLibp2p
|
||||
|
||||
before(async () => {
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
peerInfo = new PeerInfo(peerId)
|
||||
peerId = await PeerId.createFromJSON(Peers[0])
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -216,7 +228,7 @@ describe('Identify', () => {
|
||||
it('should run identify automatically after connecting', async () => {
|
||||
libp2p = new Libp2p({
|
||||
...baseOptions,
|
||||
peerInfo
|
||||
peerId
|
||||
})
|
||||
|
||||
sinon.spy(libp2p.identifyService, 'identify')
|
||||
@ -239,7 +251,7 @@ describe('Identify', () => {
|
||||
it('should push protocol updates to an already connected peer', async () => {
|
||||
libp2p = new Libp2p({
|
||||
...baseOptions,
|
||||
peerInfo
|
||||
peerId
|
||||
})
|
||||
|
||||
sinon.spy(libp2p.identifyService, 'identify')
|
||||
|
@ -74,7 +74,7 @@ describe('libp2p.metrics', () => {
|
||||
|
||||
remoteLibp2p.handle('/echo/1.0.0', ({ stream }) => pipe(stream, stream))
|
||||
|
||||
const connection = await libp2p.dial(remoteLibp2p.peerInfo)
|
||||
const connection = await libp2p.dial(remoteLibp2p.peerId)
|
||||
const { stream } = await connection.newStream('/echo/1.0.0')
|
||||
|
||||
const bytes = randomBytes(512)
|
||||
@ -109,6 +109,11 @@ describe('libp2p.metrics', () => {
|
||||
enabled: true,
|
||||
computeThrottleMaxQueueSize: 1, // compute after every message
|
||||
movingAverageIntervals: [10]
|
||||
},
|
||||
config: {
|
||||
peerDiscovery: {
|
||||
autoDial: false
|
||||
}
|
||||
}
|
||||
}
|
||||
let remoteLibp2p
|
||||
@ -116,7 +121,7 @@ describe('libp2p.metrics', () => {
|
||||
|
||||
remoteLibp2p.handle('/echo/1.0.0', ({ stream }) => pipe(stream, stream))
|
||||
|
||||
const connection = await libp2p.dial(remoteLibp2p.peerInfo)
|
||||
const connection = await libp2p.dial(remoteLibp2p.peerId)
|
||||
const { stream } = await connection.newStream('/echo/1.0.0')
|
||||
|
||||
const bytes = randomBytes(512)
|
||||
|
@ -16,18 +16,16 @@ const multiaddr = require('multiaddr')
|
||||
|
||||
const Libp2p = require('../../src')
|
||||
const baseOptions = require('../utils/base-options')
|
||||
const { createPeerInfo } = require('../utils/creators/peer')
|
||||
const { createPeerId } = require('../utils/creators/peer')
|
||||
|
||||
const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
|
||||
describe('peer discovery scenarios', () => {
|
||||
let peerInfo, remotePeerInfo1, remotePeerInfo2
|
||||
let peerId, remotePeerId1, remotePeerId2
|
||||
let libp2p
|
||||
|
||||
before(async () => {
|
||||
[peerInfo, remotePeerInfo1, remotePeerInfo2] = await createPeerInfo({ number: 3 })
|
||||
|
||||
peerInfo.multiaddrs.add(multiaddr('/ip4/127.0.0.1/tcp/0'))
|
||||
remotePeerInfo1.multiaddrs.add(multiaddr('/ip4/127.0.0.1/tcp/0'))
|
||||
remotePeerInfo2.multiaddrs.add(multiaddr('/ip4/127.0.0.1/tcp/0'))
|
||||
[peerId, remotePeerId1, remotePeerId2] = await createPeerId({ number: 3 })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -53,12 +51,15 @@ describe('peer discovery scenarios', () => {
|
||||
const deferred = defer()
|
||||
|
||||
const bootstrappers = [
|
||||
...remotePeerInfo1.multiaddrs.toArray().map((ma) => `${ma}/p2p/${remotePeerInfo1.id.toB58String()}`),
|
||||
...remotePeerInfo2.multiaddrs.toArray().map((ma) => `${ma}/p2p/${remotePeerInfo2.id.toB58String()}`)
|
||||
`${listenAddr}/p2p/${remotePeerId1.toB58String()}`,
|
||||
`${listenAddr}/p2p/${remotePeerId2.toB58String()}`
|
||||
]
|
||||
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
peerDiscovery: [Bootstrap]
|
||||
},
|
||||
@ -74,12 +75,12 @@ describe('peer discovery scenarios', () => {
|
||||
}))
|
||||
|
||||
const expectedPeers = new Set([
|
||||
remotePeerInfo1.id.toB58String(),
|
||||
remotePeerInfo2.id.toB58String()
|
||||
remotePeerId1.toB58String(),
|
||||
remotePeerId2.toB58String()
|
||||
])
|
||||
|
||||
libp2p.on('peer:discovery', (peerInfo) => {
|
||||
expectedPeers.delete(peerInfo.id.toB58String())
|
||||
libp2p.on('peer:discovery', (peerId) => {
|
||||
expectedPeers.delete(peerId.toB58String())
|
||||
if (expectedPeers.size === 0) {
|
||||
libp2p.removeAllListeners('peer:discovery')
|
||||
deferred.resolve()
|
||||
@ -94,8 +95,11 @@ describe('peer discovery scenarios', () => {
|
||||
it('MulticastDNS should discover all peers on the local network', async () => {
|
||||
const deferred = defer()
|
||||
|
||||
const getConfig = (peerInfo) => mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
const getConfig = (peerId) => mergeOptions(baseOptions, {
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
peerDiscovery: [MulticastDNS]
|
||||
},
|
||||
@ -112,17 +116,17 @@ describe('peer discovery scenarios', () => {
|
||||
}
|
||||
})
|
||||
|
||||
libp2p = new Libp2p(getConfig(peerInfo))
|
||||
const remoteLibp2p1 = new Libp2p(getConfig(remotePeerInfo1))
|
||||
const remoteLibp2p2 = new Libp2p(getConfig(remotePeerInfo2))
|
||||
libp2p = new Libp2p(getConfig(peerId))
|
||||
const remoteLibp2p1 = new Libp2p(getConfig(remotePeerId1))
|
||||
const remoteLibp2p2 = new Libp2p(getConfig(remotePeerId2))
|
||||
|
||||
const expectedPeers = new Set([
|
||||
remotePeerInfo1.id.toB58String(),
|
||||
remotePeerInfo2.id.toB58String()
|
||||
remotePeerId1.toB58String(),
|
||||
remotePeerId2.toB58String()
|
||||
])
|
||||
|
||||
libp2p.on('peer:discovery', (peerInfo) => {
|
||||
expectedPeers.delete(peerInfo.id.toB58String())
|
||||
libp2p.on('peer:discovery', (peerId) => {
|
||||
expectedPeers.delete(peerId.toB58String())
|
||||
if (expectedPeers.size === 0) {
|
||||
libp2p.removeAllListeners('peer:discovery')
|
||||
deferred.resolve()
|
||||
@ -144,8 +148,11 @@ describe('peer discovery scenarios', () => {
|
||||
it('kad-dht should discover other peers', async () => {
|
||||
const deferred = defer()
|
||||
|
||||
const getConfig = (peerInfo) => mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
const getConfig = (peerId) => mergeOptions(baseOptions, {
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
dht: KadDht
|
||||
},
|
||||
@ -165,16 +172,16 @@ describe('peer discovery scenarios', () => {
|
||||
}
|
||||
})
|
||||
|
||||
const localConfig = getConfig(peerInfo)
|
||||
const localConfig = getConfig(peerId)
|
||||
// Only run random walk on our local node
|
||||
localConfig.config.dht.randomWalk.enabled = true
|
||||
libp2p = new Libp2p(localConfig)
|
||||
|
||||
const remoteLibp2p1 = new Libp2p(getConfig(remotePeerInfo1))
|
||||
const remoteLibp2p2 = new Libp2p(getConfig(remotePeerInfo2))
|
||||
const remoteLibp2p1 = new Libp2p(getConfig(remotePeerId1))
|
||||
const remoteLibp2p2 = new Libp2p(getConfig(remotePeerId2))
|
||||
|
||||
libp2p.on('peer:discovery', (peerInfo) => {
|
||||
if (peerInfo.id.toB58String() === remotePeerInfo2.id.toB58String()) {
|
||||
libp2p.on('peer:discovery', (peerId) => {
|
||||
if (peerId.toB58String() === remotePeerId1.toB58String()) {
|
||||
libp2p.removeAllListeners('peer:discovery')
|
||||
deferred.resolve()
|
||||
}
|
||||
@ -186,12 +193,15 @@ describe('peer discovery scenarios', () => {
|
||||
remoteLibp2p2.start()
|
||||
])
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId1, remoteLibp2p1.addresses.listen)
|
||||
remoteLibp2p2.peerStore.addressBook.set(remotePeerId1, remoteLibp2p1.addresses.listen)
|
||||
|
||||
// Topology:
|
||||
// A -> B
|
||||
// C -> B
|
||||
await Promise.all([
|
||||
libp2p.dial(remotePeerInfo1),
|
||||
remoteLibp2p2.dial(remotePeerInfo1)
|
||||
libp2p.dial(remotePeerId1),
|
||||
remoteLibp2p2.dial(remotePeerId1)
|
||||
])
|
||||
|
||||
await deferred.promise
|
||||
|
@ -9,20 +9,21 @@ const sinon = require('sinon')
|
||||
const defer = require('p-defer')
|
||||
const mergeOptions = require('merge-options')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
const WebRTCStar = require('libp2p-webrtc-star')
|
||||
|
||||
const Libp2p = require('../../src')
|
||||
const baseOptions = require('../utils/base-options.browser')
|
||||
const { createPeerInfo } = require('../utils/creators/peer')
|
||||
const { createPeerId } = require('../utils/creators/peer')
|
||||
|
||||
describe('peer discovery', () => {
|
||||
describe('basic functions', () => {
|
||||
let peerInfo
|
||||
let remotePeerInfo
|
||||
let peerId
|
||||
let remotePeerId
|
||||
let libp2p
|
||||
|
||||
before(async () => {
|
||||
[peerInfo, remotePeerInfo] = await createPeerInfo({ number: 2 })
|
||||
[peerId, remotePeerId] = await createPeerId({ number: 2 })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -33,14 +34,14 @@ describe('peer discovery', () => {
|
||||
it('should dial know peers on startup', async () => {
|
||||
libp2p = new Libp2p({
|
||||
...baseOptions,
|
||||
peerInfo
|
||||
peerId
|
||||
})
|
||||
libp2p.peerStore.addressBook.set(remotePeerInfo.id, remotePeerInfo.multiaddrs.toArray())
|
||||
libp2p.peerStore.protoBook.set(remotePeerInfo.id, Array.from(remotePeerInfo.protocols))
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, [multiaddr('/ip4/165.1.1.1/tcp/80')])
|
||||
|
||||
const deferred = defer()
|
||||
sinon.stub(libp2p.dialer, 'connectToPeer').callsFake((remotePeerInfo) => {
|
||||
expect(remotePeerInfo).to.equal(remotePeerInfo)
|
||||
sinon.stub(libp2p.dialer, 'connectToPeer').callsFake((remotePeerId) => {
|
||||
expect(remotePeerId).to.equal(remotePeerId)
|
||||
deferred.resolve()
|
||||
})
|
||||
const spy = sinon.spy()
|
||||
@ -50,7 +51,7 @@ describe('peer discovery', () => {
|
||||
await deferred.promise
|
||||
|
||||
expect(spy.calledOnce).to.eql(true)
|
||||
expect(spy.getCall(0).args[0].id.toString()).to.eql(remotePeerInfo.id.toString())
|
||||
expect(spy.getCall(0).args[0].toString()).to.eql(remotePeerId.toString())
|
||||
})
|
||||
|
||||
it('should stop discovery on libp2p start/stop', async () => {
|
||||
@ -65,7 +66,7 @@ describe('peer discovery', () => {
|
||||
const stopSpy = sinon.spy(mockDiscovery, 'stop')
|
||||
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
peerDiscovery: [mockDiscovery]
|
||||
}
|
||||
@ -81,15 +82,15 @@ describe('peer discovery', () => {
|
||||
})
|
||||
|
||||
describe('discovery modules from transports', () => {
|
||||
let peerInfo, libp2p
|
||||
let peerId, libp2p
|
||||
|
||||
before(async () => {
|
||||
[peerInfo] = await createPeerInfo()
|
||||
[peerId] = await createPeerId()
|
||||
})
|
||||
|
||||
it('should add discovery module if present in transports and enabled', async () => {
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [WebRTCStar]
|
||||
},
|
||||
@ -110,7 +111,7 @@ describe('peer discovery', () => {
|
||||
|
||||
it('should not add discovery module if present in transports but disabled', async () => {
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [WebRTCStar]
|
||||
},
|
||||
|
@ -44,7 +44,7 @@ describe('peer-routing', () => {
|
||||
|
||||
// Ring dial
|
||||
await Promise.all(
|
||||
nodes.map((peer, i) => peer.dial(nodes[(i + 1) % number].peerInfo))
|
||||
nodes.map((peer, i) => peer.dial(nodes[(i + 1) % number].peerId))
|
||||
)
|
||||
})
|
||||
|
||||
@ -59,7 +59,7 @@ describe('peer-routing', () => {
|
||||
|
||||
sinon.stub(nodes[0]._dht, 'findPeer').callsFake(() => {
|
||||
deferred.resolve()
|
||||
return nodes[1].peerInfo
|
||||
return nodes[1].peerId
|
||||
})
|
||||
|
||||
nodes[0].peerRouting.findPeer()
|
||||
@ -104,7 +104,7 @@ describe('peer-routing', () => {
|
||||
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
deferred.resolve()
|
||||
return 'fake peer-info'
|
||||
return 'fake peer-id'
|
||||
})
|
||||
|
||||
await node.peerRouting.findPeer()
|
||||
@ -121,9 +121,9 @@ describe('peer-routing', () => {
|
||||
'X-Chunked-Output', '1'
|
||||
])
|
||||
|
||||
const peerInfo = await node.peerRouting.findPeer(peerKey)
|
||||
const peerData = await node.peerRouting.findPeer(peerKey)
|
||||
|
||||
expect(peerInfo.id.toB58String()).to.equal(peerKey)
|
||||
expect(peerData.id).to.equal(peerKey)
|
||||
expect(mockApi.isDone()).to.equal(true)
|
||||
})
|
||||
|
||||
@ -188,7 +188,7 @@ describe('peer-routing', () => {
|
||||
|
||||
sinon.stub(node._dht, 'findPeer').callsFake(() => {
|
||||
dhtDeferred.resolve()
|
||||
return node.peerInfo
|
||||
return { id: node.peerId }
|
||||
})
|
||||
sinon.stub(delegate, 'findPeer').callsFake(() => {
|
||||
throw new Error('the delegate should not have been called')
|
||||
|
@ -123,7 +123,7 @@ describe('peer-store', () => {
|
||||
const peerSupporting2 = []
|
||||
|
||||
for (const [, peerInfo] of peerStore.peers.entries()) {
|
||||
if (peerInfo.protocols.has(proto2)) {
|
||||
if (peerInfo.protocols.includes(proto2)) {
|
||||
peerSupporting2.push(peerInfo)
|
||||
}
|
||||
}
|
||||
@ -137,7 +137,9 @@ describe('peer-store', () => {
|
||||
const peerListenint4 = []
|
||||
|
||||
for (const [, peerInfo] of peerStore.peers.entries()) {
|
||||
if (peerInfo.multiaddrs.has(addr4)) {
|
||||
const multiaddrs = peerInfo.multiaddrInfos.map((mi) => mi.multiaddr)
|
||||
|
||||
if (multiaddrs.includes(addr4)) {
|
||||
peerListenint4.push(peerInfo)
|
||||
}
|
||||
}
|
||||
|
@ -32,11 +32,13 @@ describe('Pubsub subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should start and stop by default once libp2p starts', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo()
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId()
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
})
|
||||
|
||||
libp2p = await create(customOptions)
|
||||
@ -50,11 +52,13 @@ describe('Pubsub subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should not start if disabled once libp2p starts', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo()
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId()
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
config: {
|
||||
pubsub: {
|
||||
enabled: false
|
||||
@ -70,11 +74,13 @@ describe('Pubsub subsystem is configurable', () => {
|
||||
})
|
||||
|
||||
it('should allow a manual start', async () => {
|
||||
const [peerInfo] = await peerUtils.createPeerInfo()
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
const [peerId] = await peerUtils.createPeerId()
|
||||
|
||||
const customOptions = mergeOptions(subsystemOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
config: {
|
||||
pubsub: {
|
||||
enabled: false
|
||||
|
@ -24,14 +24,11 @@ const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
const remoteListenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
|
||||
describe('Pubsub subsystem is able to use different implementations', () => {
|
||||
let peerInfo, remotePeerInfo
|
||||
let peerId, remotePeerId
|
||||
let libp2p, remoteLibp2p
|
||||
|
||||
beforeEach(async () => {
|
||||
[peerInfo, remotePeerInfo] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
remotePeerInfo.multiaddrs.add(remoteListenAddr)
|
||||
[peerId, remotePeerId] = await peerUtils.createPeerId({ number: 2 })
|
||||
})
|
||||
|
||||
afterEach(() => Promise.all([
|
||||
@ -53,14 +50,20 @@ describe('Pubsub subsystem is able to use different implementations', () => {
|
||||
const data = 'hey!'
|
||||
|
||||
libp2p = await create(mergeOptions(baseOptions, {
|
||||
peerInfo,
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
},
|
||||
modules: {
|
||||
pubsub: pubsub
|
||||
}
|
||||
}))
|
||||
|
||||
remoteLibp2p = await create(mergeOptions(baseOptions, {
|
||||
peerInfo: remotePeerInfo,
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [remoteListenAddr]
|
||||
},
|
||||
modules: {
|
||||
pubsub: pubsub
|
||||
}
|
||||
@ -71,9 +74,10 @@ describe('Pubsub subsystem is able to use different implementations', () => {
|
||||
remoteLibp2p.start()
|
||||
])
|
||||
|
||||
const libp2pId = libp2p.peerInfo.id.toB58String()
|
||||
const libp2pId = libp2p.peerId.toB58String()
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
|
||||
const connection = await libp2p.dialProtocol(remotePeerInfo, multicodec)
|
||||
const connection = await libp2p.dialProtocol(remotePeerId, multicodec)
|
||||
expect(connection).to.exist()
|
||||
|
||||
libp2p.pubsub.subscribe(topic, (msg) => {
|
||||
|
@ -19,30 +19,35 @@ const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
const remoteListenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
|
||||
describe('Pubsub subsystem operates correctly', () => {
|
||||
let peerInfo, remotePeerInfo
|
||||
let peerId, remotePeerId
|
||||
let libp2p, remoteLibp2p
|
||||
|
||||
beforeEach(async () => {
|
||||
[peerInfo, remotePeerInfo] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
|
||||
peerInfo.multiaddrs.add(listenAddr)
|
||||
remotePeerInfo.multiaddrs.add(remoteListenAddr)
|
||||
[peerId, remotePeerId] = await peerUtils.createPeerId({ number: 2 })
|
||||
})
|
||||
|
||||
describe('pubsub started before connect', () => {
|
||||
beforeEach(async () => {
|
||||
libp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
remoteLibp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo: remotePeerInfo
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [remoteListenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
await Promise.all([
|
||||
libp2p.start(),
|
||||
remoteLibp2p.start()
|
||||
])
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
})
|
||||
|
||||
afterEach(() => Promise.all([
|
||||
@ -55,7 +60,7 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
})
|
||||
|
||||
it('should get notified of connected peers on dial', async () => {
|
||||
const connection = await libp2p.dialProtocol(remotePeerInfo, subsystemMulticodecs)
|
||||
const connection = await libp2p.dialProtocol(remotePeerId, subsystemMulticodecs)
|
||||
|
||||
expect(connection).to.exist()
|
||||
|
||||
@ -69,9 +74,9 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
const defer = pDefer()
|
||||
const topic = 'test-topic'
|
||||
const data = 'hey!'
|
||||
const libp2pId = libp2p.peerInfo.id.toB58String()
|
||||
const libp2pId = libp2p.peerId.toB58String()
|
||||
|
||||
await libp2p.dialProtocol(remotePeerInfo, subsystemMulticodecs)
|
||||
await libp2p.dialProtocol(remotePeerId, subsystemMulticodecs)
|
||||
|
||||
let subscribedTopics = libp2p.pubsub.getTopics()
|
||||
expect(subscribedTopics).to.not.include(topic)
|
||||
@ -98,11 +103,17 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
describe('pubsub started after connect', () => {
|
||||
beforeEach(async () => {
|
||||
libp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo
|
||||
peerId,
|
||||
addresses: {
|
||||
listen: [listenAddr]
|
||||
}
|
||||
}))
|
||||
|
||||
remoteLibp2p = await create(mergeOptions(subsystemOptions, {
|
||||
peerInfo: remotePeerInfo,
|
||||
peerId: remotePeerId,
|
||||
addresses: {
|
||||
listen: [remoteListenAddr]
|
||||
},
|
||||
config: {
|
||||
pubsub: {
|
||||
enabled: false
|
||||
@ -112,6 +123,8 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
|
||||
await libp2p.start()
|
||||
await remoteLibp2p.start()
|
||||
|
||||
libp2p.peerStore.addressBook.set(remotePeerId, remoteLibp2p.addresses.listen)
|
||||
})
|
||||
|
||||
afterEach(() => Promise.all([
|
||||
@ -124,7 +137,7 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
})
|
||||
|
||||
it('should get notified of connected peers after starting', async () => {
|
||||
const connection = await libp2p.dial(remotePeerInfo)
|
||||
const connection = await libp2p.dial(remotePeerId)
|
||||
|
||||
expect(connection).to.exist()
|
||||
expect(libp2p.pubsub._pubsub.peers.size).to.be.eql(0)
|
||||
@ -141,11 +154,11 @@ describe('Pubsub subsystem operates correctly', () => {
|
||||
it('should receive pubsub messages', async function () {
|
||||
this.timeout(10e3)
|
||||
const defer = pDefer()
|
||||
const libp2pId = libp2p.peerInfo.id.toB58String()
|
||||
const libp2pId = libp2p.peerId.toB58String()
|
||||
const topic = 'test-topic'
|
||||
const data = 'hey!'
|
||||
|
||||
await libp2p.dial(remotePeerInfo)
|
||||
await libp2p.dial(remotePeerId)
|
||||
|
||||
remoteLibp2p.pubsub.start()
|
||||
|
||||
|
@ -16,20 +16,20 @@ const peerUtils = require('../utils/creators/peer')
|
||||
const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
|
||||
describe('registrar on dial', () => {
|
||||
let peerInfo
|
||||
let remotePeerInfo
|
||||
let peerId
|
||||
let remotePeerId
|
||||
let libp2p
|
||||
let remoteLibp2p
|
||||
let remoteAddr
|
||||
|
||||
before(async () => {
|
||||
[peerInfo, remotePeerInfo] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
[peerId, remotePeerId] = await peerUtils.createPeerId({ number: 2 })
|
||||
remoteLibp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo: remotePeerInfo
|
||||
peerId: remotePeerId
|
||||
}))
|
||||
|
||||
await remoteLibp2p.transportManager.listen([listenAddr])
|
||||
remoteAddr = remoteLibp2p.transportManager.getAddrs()[0].encapsulate(`/p2p/${remotePeerInfo.id.toB58String()}`)
|
||||
remoteAddr = remoteLibp2p.transportManager.getAddrs()[0].encapsulate(`/p2p/${remotePeerId.toB58String()}`)
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
@ -40,7 +40,7 @@ describe('registrar on dial', () => {
|
||||
|
||||
it('should inform registrar of a new connection', async () => {
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo
|
||||
peerId
|
||||
}))
|
||||
|
||||
sinon.spy(remoteLibp2p.registrar, 'onConnect')
|
||||
@ -48,16 +48,16 @@ describe('registrar on dial', () => {
|
||||
await libp2p.dial(remoteAddr)
|
||||
expect(remoteLibp2p.registrar.onConnect.callCount).to.equal(1)
|
||||
|
||||
const libp2pConn = libp2p.registrar.getConnection(remotePeerInfo)
|
||||
const libp2pConn = libp2p.registrar.getConnection(remotePeerId)
|
||||
expect(libp2pConn).to.exist()
|
||||
|
||||
const remoteConn = remoteLibp2p.registrar.getConnection(peerInfo)
|
||||
const remoteConn = remoteLibp2p.registrar.getConnection(peerId)
|
||||
expect(remoteConn).to.exist()
|
||||
})
|
||||
|
||||
it('should be closed on libp2p stop', async () => {
|
||||
libp2p = new Libp2p(mergeOptions(baseOptions, {
|
||||
peerInfo
|
||||
peerId
|
||||
}))
|
||||
|
||||
await libp2p.dial(remoteAddr)
|
||||
|
@ -6,7 +6,6 @@ chai.use(require('dirty-chai'))
|
||||
const { expect } = chai
|
||||
const pDefer = require('p-defer')
|
||||
|
||||
const PeerInfo = require('peer-info')
|
||||
const Topology = require('libp2p-interfaces/src/topology/multicodec-topology')
|
||||
const PeerStore = require('../../src/peer-store')
|
||||
const Registrar = require('../../src/registrar')
|
||||
@ -83,29 +82,25 @@ describe('registrar', () => {
|
||||
|
||||
// Setup connections before registrar
|
||||
const conn = await createMockConnection()
|
||||
const remotePeerInfo = await PeerInfo.create(conn.remotePeer)
|
||||
const remotePeerId = conn.remotePeer
|
||||
|
||||
// Add protocol to peer
|
||||
remotePeerInfo.protocols.add(multicodec)
|
||||
// Add connected peer with protocol to peerStore and registrar
|
||||
peerStore.protoBook.add(remotePeerId, [multicodec])
|
||||
|
||||
// Add connected peer to peerStore and registrar
|
||||
peerStore.addressBook.set(remotePeerInfo.id, remotePeerInfo.multiaddrs.toArray())
|
||||
peerStore.protoBook.set(remotePeerInfo.id, Array.from(remotePeerInfo.protocols))
|
||||
|
||||
registrar.onConnect(remotePeerInfo, conn)
|
||||
registrar.onConnect(remotePeerId, conn)
|
||||
expect(registrar.connections.size).to.eql(1)
|
||||
|
||||
const topologyProps = new Topology({
|
||||
multicodecs: multicodec,
|
||||
handlers: {
|
||||
onConnect: (peerInfo, connection) => {
|
||||
expect(peerInfo.id.toB58String()).to.eql(remotePeerInfo.id.toB58String())
|
||||
onConnect: (peerId, connection) => {
|
||||
expect(peerId.toB58String()).to.eql(remotePeerId.toB58String())
|
||||
expect(connection.id).to.eql(conn.id)
|
||||
|
||||
onConnectDefer.resolve()
|
||||
},
|
||||
onDisconnect: (peerInfo) => {
|
||||
expect(peerInfo.id.toB58String()).to.eql(remotePeerInfo.id.toB58String())
|
||||
onDisconnect: (peerId) => {
|
||||
expect(peerId.toB58String()).to.eql(remotePeerId.toB58String())
|
||||
|
||||
onDisconnectDefer.resolve()
|
||||
}
|
||||
@ -119,7 +114,7 @@ describe('registrar', () => {
|
||||
// Topology created
|
||||
expect(topology).to.exist()
|
||||
|
||||
registrar.onDisconnect(remotePeerInfo)
|
||||
registrar.onDisconnect(remotePeerId)
|
||||
expect(registrar.connections.size).to.eql(0)
|
||||
|
||||
// Wait for handlers to be called
|
||||
@ -155,26 +150,19 @@ describe('registrar', () => {
|
||||
|
||||
// Setup connections before registrar
|
||||
const conn = await createMockConnection()
|
||||
const peerInfo = await PeerInfo.create(conn.remotePeer)
|
||||
const remotePeerId = conn.remotePeer
|
||||
|
||||
// Add connected peer to peerStore and registrar
|
||||
peerStore.addressBook.set(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
peerStore.protoBook.set(peerInfo.id, Array.from(peerInfo.protocols))
|
||||
|
||||
registrar.onConnect(peerInfo, conn)
|
||||
peerStore.protoBook.set(remotePeerId, [])
|
||||
registrar.onConnect(remotePeerId, conn)
|
||||
|
||||
// Add protocol to peer and update it
|
||||
peerInfo.protocols.add(multicodec)
|
||||
peerStore.addressBook.add(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
peerStore.protoBook.add(peerInfo.id, Array.from(peerInfo.protocols))
|
||||
peerStore.protoBook.add(remotePeerId, [multicodec])
|
||||
|
||||
await onConnectDefer.promise
|
||||
|
||||
// Remove protocol to peer and update it
|
||||
peerInfo.protocols.delete(multicodec)
|
||||
|
||||
peerStore.addressBook.set(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
peerStore.protoBook.set(peerInfo.id, Array.from(peerInfo.protocols))
|
||||
peerStore.protoBook.set(remotePeerId, [])
|
||||
|
||||
await onDisconnectDefer.promise
|
||||
})
|
||||
@ -196,23 +184,21 @@ describe('registrar', () => {
|
||||
registrar.register(topologyProps)
|
||||
|
||||
// Setup connections before registrar
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerId({ number: 2 })
|
||||
|
||||
const conn1 = await createMockConnection({ localPeer: localPeer.id, remotePeer: remotePeer.id })
|
||||
const conn2 = await createMockConnection({ localPeer: localPeer.id, remotePeer: remotePeer.id })
|
||||
const peerInfo = await PeerInfo.create(remotePeer.id)
|
||||
const id = peerInfo.id.toB58String()
|
||||
const conn1 = await createMockConnection({ localPeer, remotePeer })
|
||||
const conn2 = await createMockConnection({ localPeer, remotePeer })
|
||||
|
||||
const id = remotePeer.toB58String()
|
||||
|
||||
// Add connection to registrar
|
||||
peerStore.addressBook.set(peerInfo.id, peerInfo.multiaddrs.toArray())
|
||||
peerStore.protoBook.set(peerInfo.id, Array.from(peerInfo.protocols))
|
||||
registrar.onConnect(peerInfo, conn1)
|
||||
registrar.onConnect(peerInfo, conn2)
|
||||
registrar.onConnect(remotePeer, conn1)
|
||||
registrar.onConnect(remotePeer, conn2)
|
||||
|
||||
expect(registrar.connections.get(id).length).to.eql(2)
|
||||
|
||||
conn2._stat.status = 'closed'
|
||||
registrar.onDisconnect(peerInfo, conn2)
|
||||
registrar.onDisconnect(remotePeer, conn2)
|
||||
|
||||
const peerConnections = registrar.connections.get(id)
|
||||
expect(peerConnections.length).to.eql(1)
|
||||
|
@ -11,13 +11,13 @@ module.exports.createMockConnection = async (properties = {}) => {
|
||||
const localAddr = multiaddr('/ip4/127.0.0.1/tcp/8080')
|
||||
const remoteAddr = multiaddr('/ip4/127.0.0.1/tcp/8081')
|
||||
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerId({ number: 2 })
|
||||
const openStreams = []
|
||||
let streamId = 0
|
||||
|
||||
return new Connection({
|
||||
localPeer: localPeer.id,
|
||||
remotePeer: remotePeer.id,
|
||||
localPeer: localPeer,
|
||||
remotePeer: remotePeer,
|
||||
localAddr,
|
||||
remoteAddr,
|
||||
stat: {
|
||||
|
@ -16,7 +16,6 @@ const { codes: ErrorCodes } = require('../../src/errors')
|
||||
const Libp2p = require('../../src')
|
||||
const Peers = require('../fixtures/peers')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
describe('Transport Manager (WebSockets)', () => {
|
||||
let tm
|
||||
@ -88,12 +87,11 @@ describe('Transport Manager (WebSockets)', () => {
|
||||
})
|
||||
|
||||
describe('libp2p.transportManager', () => {
|
||||
let peerInfo
|
||||
let peerId
|
||||
let libp2p
|
||||
|
||||
before(async () => {
|
||||
const peerId = await PeerId.createFromJSON(Peers[0])
|
||||
peerInfo = new PeerInfo(peerId)
|
||||
peerId = await PeerId.createFromJSON(Peers[0])
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -104,7 +102,7 @@ describe('libp2p.transportManager', () => {
|
||||
|
||||
it('should create a TransportManager', () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport]
|
||||
}
|
||||
@ -122,7 +120,7 @@ describe('libp2p.transportManager', () => {
|
||||
another: 'value'
|
||||
}
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [spy]
|
||||
},
|
||||
@ -146,7 +144,7 @@ describe('libp2p.transportManager', () => {
|
||||
|
||||
it('starting and stopping libp2p should start and stop TransportManager', async () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo,
|
||||
peerId,
|
||||
modules: {
|
||||
transport: [Transport]
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ const sinon = require('sinon')
|
||||
const Muxer = require('libp2p-mplex')
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
const pipe = require('it-pipe')
|
||||
const { collect } = require('streaming-iterables')
|
||||
const pSettle = require('p-settle')
|
||||
@ -348,11 +347,10 @@ describe('libp2p.upgrader', () => {
|
||||
let libp2p
|
||||
|
||||
before(async () => {
|
||||
const ids = await Promise.all([
|
||||
peers = await Promise.all([
|
||||
PeerId.createFromJSON(Peers[0]),
|
||||
PeerId.createFromJSON(Peers[1])
|
||||
])
|
||||
peers = ids.map(peerId => new PeerInfo(peerId))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@ -364,7 +362,7 @@ describe('libp2p.upgrader', () => {
|
||||
it('should create an Upgrader', () => {
|
||||
const protector = new Protector(swarmKeyBuffer)
|
||||
libp2p = new Libp2p({
|
||||
peerInfo: peers[0],
|
||||
peerId: peers[0],
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -383,7 +381,7 @@ describe('libp2p.upgrader', () => {
|
||||
|
||||
it('should be able to register and unregister a handler', () => {
|
||||
libp2p = new Libp2p({
|
||||
peerInfo: peers[0],
|
||||
peerId: peers[0],
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -406,7 +404,7 @@ describe('libp2p.upgrader', () => {
|
||||
it('should emit connect and disconnect events', async () => {
|
||||
const remotePeer = peers[1]
|
||||
libp2p = new Libp2p({
|
||||
peerInfo: peers[0],
|
||||
peerId: peers[0],
|
||||
modules: {
|
||||
transport: [Transport],
|
||||
streamMuxer: [Muxer],
|
||||
@ -415,12 +413,12 @@ describe('libp2p.upgrader', () => {
|
||||
})
|
||||
|
||||
const remoteUpgrader = new Upgrader({
|
||||
localPeer: remotePeer.id,
|
||||
localPeer: remotePeer,
|
||||
muxers: new Map([[Muxer.multicodec, Muxer]]),
|
||||
cryptos: new Map([[Crypto.protocol, Crypto]])
|
||||
})
|
||||
|
||||
const { inbound, outbound } = mockMultiaddrConnPair({ addrs, remotePeer: remotePeer.id })
|
||||
const { inbound, outbound } = mockMultiaddrConnPair({ addrs, remotePeer })
|
||||
|
||||
// Spy on emit for easy verification
|
||||
sinon.spy(libp2p, 'emit')
|
||||
@ -431,15 +429,16 @@ describe('libp2p.upgrader', () => {
|
||||
remoteUpgrader.upgradeInbound(inbound)
|
||||
])
|
||||
expect(libp2p.emit.callCount).to.equal(1)
|
||||
let [event, peerInfo] = libp2p.emit.getCall(0).args
|
||||
|
||||
let [event, peerId] = libp2p.emit.getCall(0).args
|
||||
expect(event).to.equal('peer:connect')
|
||||
expect(peerInfo.id.isEqual(remotePeer.id)).to.equal(true)
|
||||
expect(peerId.isEqual(remotePeer)).to.equal(true)
|
||||
|
||||
// Close and check the disconnect event
|
||||
await Promise.all(connections.map(conn => conn.close()))
|
||||
expect(libp2p.emit.callCount).to.equal(2)
|
||||
;([event, peerInfo] = libp2p.emit.getCall(1).args)
|
||||
;([event, peerId] = libp2p.emit.getCall(1).args)
|
||||
expect(event).to.equal('peer:disconnect')
|
||||
expect(peerInfo.id.isEqual(remotePeer.id)).to.equal(true)
|
||||
expect(peerId.isEqual(remotePeer)).to.equal(true)
|
||||
})
|
||||
})
|
||||
|
@ -4,7 +4,6 @@ const pTimes = require('p-times')
|
||||
|
||||
const multiaddr = require('multiaddr')
|
||||
const PeerId = require('peer-id')
|
||||
const PeerInfo = require('peer-info')
|
||||
|
||||
const Libp2p = require('../../../src')
|
||||
const Peers = require('../../fixtures/peers')
|
||||
@ -19,37 +18,36 @@ const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0')
|
||||
* @param {number} [properties.number] number of peers (default: 1).
|
||||
* @param {boolean} [properties.fixture] use fixture for peer-id generation (default: true)
|
||||
* @param {boolean} [properties.started] nodes should start (default: true)
|
||||
* @param {boolean} [properties.populateAddressBooks] nodes addressBooks should be populated with other peers (default: true)
|
||||
* @return {Promise<Array<Libp2p>>}
|
||||
*/
|
||||
async function createPeer ({ number = 1, fixture = true, started = true, config = defaultOptions } = {}) {
|
||||
const peerInfos = await createPeerInfo({ number, fixture })
|
||||
async function createPeer ({ number = 1, fixture = true, started = true, populateAddressBooks = true, config = defaultOptions } = {}) {
|
||||
const peerIds = await createPeerId({ number, fixture })
|
||||
|
||||
const addresses = started ? { listen: [listenAddr] } : {}
|
||||
const peers = await pTimes(number, (i) => Libp2p.create({
|
||||
peerInfo: peerInfos[i],
|
||||
peerId: peerIds[i],
|
||||
addresses,
|
||||
...config
|
||||
}))
|
||||
|
||||
if (started) {
|
||||
await Promise.all(peers.map((p) => {
|
||||
p.peerInfo.multiaddrs.add(listenAddr)
|
||||
return p.start()
|
||||
}))
|
||||
await Promise.all(peers.map((p) => p.start()))
|
||||
|
||||
populateAddressBooks && _populateAddressBooks(peers)
|
||||
}
|
||||
|
||||
return peers
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Peer-ids.
|
||||
* @param {Object} [properties]
|
||||
* @param {number} [properties.number] number of peers (default: 1).
|
||||
* @param {boolean} [properties.fixture] use fixture for peer-id generation (default: true)
|
||||
* @return {Promise<Array<PeerInfo>>}
|
||||
*/
|
||||
async function createPeerInfo ({ number = 1, fixture = true } = {}) {
|
||||
const peerIds = await createPeerId({ number, fixture })
|
||||
|
||||
return pTimes(number, (i) => PeerInfo.create(peerIds[i]))
|
||||
function _populateAddressBooks (peers) {
|
||||
for (let i = 0; i < peers.length; i++) {
|
||||
for (let j = 0; j < peers.length; j++) {
|
||||
if (i !== j) {
|
||||
peers[i].peerStore.addressBook.set(peers[j].peerId, peers[j].addresses.listen)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -67,5 +65,4 @@ function createPeerId ({ number = 1, fixture = true } = {}) {
|
||||
}
|
||||
|
||||
module.exports.createPeer = createPeer
|
||||
module.exports.createPeerInfo = createPeerInfo
|
||||
module.exports.createPeerId = createPeerId
|
||||
|
@ -16,13 +16,13 @@ module.exports = async (properties = {}) => {
|
||||
const localAddr = multiaddr('/ip4/127.0.0.1/tcp/8080')
|
||||
const remoteAddr = multiaddr('/ip4/127.0.0.1/tcp/8081')
|
||||
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerInfo({ number: 2 })
|
||||
const [localPeer, remotePeer] = await peerUtils.createPeerId({ number: 2 })
|
||||
const openStreams = []
|
||||
let streamId = 0
|
||||
|
||||
return new Connection({
|
||||
localPeer: localPeer.id,
|
||||
remotePeer: remotePeer.id,
|
||||
localPeer: localPeer,
|
||||
remotePeer: remotePeer,
|
||||
localAddr,
|
||||
remoteAddr,
|
||||
stat: {
|
||||
|
Loading…
x
Reference in New Issue
Block a user