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:
Vasco Santos
2020-04-14 14:05:30 +02:00
committed by Jacob Heun
parent ed6d5bb4b4
commit 12e48adafa
45 changed files with 608 additions and 695 deletions

View File

@ -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({

View File

@ -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,

View File

@ -4,6 +4,9 @@ const mergeOptions = require('merge-options')
const Constants = require('./constants')
const DefaultConfig = {
addresses: {
listen: []
},
connectionManager: {
minPeers: 25
},

View File

@ -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)

View File

@ -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
}
},

View File

@ -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

View File

@ -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
View 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

View File

@ -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
}

View File

@ -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())
})

View File

@ -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)
}

View File

@ -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) {

View File

@ -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

View File

@ -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]: []
})

View File

@ -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)) {

View File

@ -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
})

View File

@ -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 {
/**

View File

@ -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')