chore: add types checker script and more fixes on the jsdocs

This commit is contained in:
Vasco Santos
2020-11-26 19:16:35 +01:00
parent 7e05c4a43b
commit 28b9f8562c
37 changed files with 246 additions and 165 deletions

View File

@ -4,6 +4,15 @@
"description": "JavaScript implementation of libp2p, a modular peer to peer network stack", "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
"leadMaintainer": "Jacob Heun <jacobheun@gmail.com>", "leadMaintainer": "Jacob Heun <jacobheun@gmail.com>",
"main": "src/index.js", "main": "src/index.js",
"types": "dist/src/index.d.ts",
"typesVersions": {
"*": {
"src/*": [
"dist/src/*",
"dist/src/*/index"
]
}
},
"files": [ "files": [
"dist", "dist",
"src" "src"
@ -15,6 +24,7 @@
"test:node": "aegir test -t node -f \"./test/**/*.{node,spec}.js\"", "test:node": "aegir test -t node -f \"./test/**/*.{node,spec}.js\"",
"test:browser": "aegir test -t browser", "test:browser": "aegir test -t browser",
"test:examples": "cd examples && npm run test:all", "test:examples": "cd examples && npm run test:all",
"test:types": "aegir ts -p check",
"release": "aegir release -t node -t browser", "release": "aegir release -t node -t browser",
"release-minor": "aegir release --type minor -t node -t browser", "release-minor": "aegir release --type minor -t node -t browser",
"release-major": "aegir release --type major -t node -t browser", "release-major": "aegir release --type major -t node -t browser",
@ -88,7 +98,7 @@
"devDependencies": { "devDependencies": {
"@nodeutils/defaults-deep": "^1.1.0", "@nodeutils/defaults-deep": "^1.1.0",
"abortable-iterator": "^3.0.0", "abortable-iterator": "^3.0.0",
"aegir": "^27.0.0", "aegir": "^29.1.0",
"chai-bytes": "^0.1.2", "chai-bytes": "^0.1.2",
"chai-string": "^1.5.0", "chai-string": "^1.5.0",
"delay": "^4.3.0", "delay": "^4.3.0",

View File

@ -1,9 +1,5 @@
'use strict' 'use strict'
const debug = require('debug')
const log = debug('libp2p:addresses')
log.error = debug('libp2p:addresses:error')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
/** /**

View File

@ -1,8 +1,9 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:auto-relay') const log = Object.assign(debug('libp2p:auto-relay'), {
log.error = debug('libp2p:auto-relay:error') error: debug('libp2p:auto-relay:err')
})
const uint8ArrayFromString = require('uint8arrays/from-string') const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string') const uint8ArrayToString = require('uint8arrays/to-string')

View File

@ -1,21 +1,26 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:circuit:hop') const log = Object.assign(debug('libp2p:circuit:hop'), {
log.error = debug('libp2p:circuit:hop:error') error: debug('libp2p:circuit:hop:err')
})
const errCode = require('err-code')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const { validateAddrs } = require('./utils') const { validateAddrs } = require('./utils')
const StreamHandler = require('./stream-handler') const StreamHandler = require('./stream-handler')
const { CircuitRelay: CircuitPB } = require('../protocol') const { CircuitRelay: CircuitPB } = require('../protocol')
const pipe = require('it-pipe') const { pipe } = require('it-pipe')
const errCode = require('err-code')
const { codes: Errors } = require('../../errors') const { codes: Errors } = require('../../errors')
const { stop } = require('./stop') const { stop } = require('./stop')
const multicodec = require('./../multicodec') const multicodec = require('./../multicodec')
/**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
*/
module.exports.handleHop = async function handleHop ({ module.exports.handleHop = async function handleHop ({
connection, connection,
request, request,

View File

@ -1,23 +1,28 @@
'use strict' 'use strict'
const debug = require('debug')
const log = Object.assign(debug('libp2p:circuit:stop'), {
error: debug('libp2p:circuit:stop:err')
})
const { CircuitRelay: CircuitPB } = require('../protocol') const { CircuitRelay: CircuitPB } = require('../protocol')
const multicodec = require('../multicodec') const multicodec = require('../multicodec')
const StreamHandler = require('./stream-handler') const StreamHandler = require('./stream-handler')
const { validateAddrs } = require('./utils') const { validateAddrs } = require('./utils')
const debug = require('debug') /**
const log = debug('libp2p:circuit:stop') * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
log.error = debug('libp2p:circuit:stop:error') */
/** /**
* Handles incoming STOP requests * Handles incoming STOP requests
* *
* @private * @private
* @param {*} options * @param {object} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {*} options.request - The CircuitRelay protobuf request (unencoded) * @param {*} options.request - The CircuitRelay protobuf request (unencoded)
* @param {StreamHandler} options.streamHandler * @param {StreamHandler} options.streamHandler
* @returns {Promise<*>} Resolves a duplex iterable * @returns {Promise<*>|void} Resolves a duplex iterable
*/ */
module.exports.handleStop = function handleStop ({ module.exports.handleStop = function handleStop ({
connection, connection,
@ -44,7 +49,7 @@ module.exports.handleStop = function handleStop ({
* Creates a STOP request * Creates a STOP request
* *
* @private * @private
* @param {*} options * @param {object} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {*} options.request - The CircuitRelay protobuf request (unencoded) * @param {*} options.request - The CircuitRelay protobuf request (unencoded)
* @returns {Promise<*>} Resolves a duplex iterable * @returns {Promise<*>} Resolves a duplex iterable

View File

@ -1,13 +1,14 @@
'use strict' 'use strict'
const debug = require('debug')
const log = Object.assign(debug('libp2p:circuit:stream-handler'), {
error: debug('libp2p:circuit:stream-handler:err')
})
const lp = require('it-length-prefixed') const lp = require('it-length-prefixed')
const handshake = require('it-handshake') const handshake = require('it-handshake')
const { CircuitRelay: CircuitPB } = require('../protocol') const { CircuitRelay: CircuitPB } = require('../protocol')
const debug = require('debug')
const log = debug('libp2p:circuit:stream-handler')
log.error = debug('libp2p:circuit:stream-handler:error')
class StreamHandler { class StreamHandler {
/** /**
* Create a stream handler for connection * Create a stream handler for connection
@ -27,7 +28,7 @@ class StreamHandler {
* Read and decode message * Read and decode message
* *
* @async * @async
* @returns {void} * @returns {Promise<void>}
*/ */
async read () { async read () {
const msg = await this.decoder.next() const msg = await this.decoder.next()

View File

@ -3,6 +3,10 @@
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
const { CircuitRelay } = require('../protocol') const { CircuitRelay } = require('../protocol')
/**
* @typedef {import('./stream-handler')} StreamHandler
*/
/** /**
* Write a response * Write a response
* *

View File

@ -1,8 +1,9 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:relay') const log = Object.assign(debug('libp2p:relay'), {
log.error = debug('libp2p:relay:error') error: debug('libp2p:relay:err')
})
const { const {
setDelayedInterval, setDelayedInterval,

View File

@ -1,14 +1,14 @@
'use strict' 'use strict'
const EventEmitter = require('events') const { EventEmitter } = require('events')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
const debug = require('debug') /**
const log = debug('libp2p:circuit:listener') * @typedef {import('multiaddr')} Multiaddr
log.err = debug('libp2p:circuit:error:listener') */
/** /**
* @param {Libp2p} libp2p * @param {import('../')} libp2p
* @returns {Listener} a transport listener * @returns {Listener} a transport listener
*/ */
module.exports = (libp2p) => { module.exports = (libp2p) => {

View File

@ -1,8 +1,9 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:connection-manager') const log = Object.assign(debug('libp2p:connection-manager'), {
log.error = debug('libp2p:connection-manager:error') error: debug('libp2p:connection-manager:err')
})
const errcode = require('err-code') const errcode = require('err-code')
const mergeOptions = require('merge-options') const mergeOptions = require('merge-options')
@ -14,7 +15,7 @@ const { EventEmitter } = require('events')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const { const {
ERR_INVALID_PARAMETERS codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
const defaultOptions = { const defaultOptions = {
@ -187,15 +188,17 @@ class ConnectionManager extends EventEmitter {
* @private * @private
*/ */
_checkMetrics () { _checkMetrics () {
const movingAverages = this._libp2p.metrics.global.movingAverages if (this._libp2p.metrics) {
const received = movingAverages.dataReceived[this._options.movingAverageInterval].movingAverage() const movingAverages = this._libp2p.metrics.global.movingAverages
this._checkMaxLimit('maxReceivedData', received) const received = movingAverages.dataReceived[this._options.movingAverageInterval].movingAverage()
const sent = movingAverages.dataSent[this._options.movingAverageInterval].movingAverage() this._checkMaxLimit('maxReceivedData', received)
this._checkMaxLimit('maxSentData', sent) const sent = movingAverages.dataSent[this._options.movingAverageInterval].movingAverage()
const total = received + sent this._checkMaxLimit('maxSentData', sent)
this._checkMaxLimit('maxData', total) const total = received + sent
log('metrics update', total) this._checkMaxLimit('maxData', total)
this._timer = retimer(this._checkMetrics, this._options.pollInterval) log('metrics update', total)
this._timer = retimer(this._checkMetrics, this._options.pollInterval)
}
} }
/** /**
@ -249,7 +252,7 @@ class ConnectionManager extends EventEmitter {
* Get a connection with a peer. * Get a connection with a peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Connection} * @returns {Connection|null}
*/ */
get (peerId) { get (peerId) {
const connections = this.getAll(peerId) const connections = this.getAll(peerId)

View File

@ -9,6 +9,7 @@ const pAny = require('p-any')
/** /**
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('cids')} CID
*/ */
/** /**
@ -63,7 +64,7 @@ module.exports = (node) => {
* a provider of the given key. * a provider of the given key.
* *
* @param {CID} key - The CID key of the content to find * @param {CID} key - The CID key of the content to find
* @returns {Promise<void>} * @returns {Promise<void[]>}
*/ */
async provide (key) { // eslint-disable-line require-await async provide (key) { // eslint-disable-line require-await
if (!routers.length) { if (!routers.length) {

View File

@ -1,15 +1,13 @@
'use strict' 'use strict'
const errCode = require('err-code')
const AbortController = require('abort-controller') const AbortController = require('abort-controller')
const anySignal = require('any-signal') const anySignal = require('any-signal')
const debug = require('debug')
const errCode = require('err-code')
const log = debug('libp2p:dialer:request')
log.error = debug('libp2p:dialer:request:error')
const FIFO = require('p-fifo') const FIFO = require('p-fifo')
const pAny = require('p-any') const pAny = require('p-any')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('./')} Dialer * @typedef {import('./')} Dialer
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
*/ */
@ -45,7 +43,7 @@ class DialRequest {
* @async * @async
* @param {object} [options] * @param {object} [options]
* @param {AbortSignal} [options.signal] - An AbortController signal * @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {Connection} * @returns {Promise<Connection>}
*/ */
async run (options) { async run (options) {
const tokens = this.dialer.getTokens(this.addrs.length) const tokens = this.dialer.getTokens(this.addrs.length)

View File

@ -1,12 +1,13 @@
'use strict' 'use strict'
const multiaddr = require('multiaddr') const debug = require('debug')
const log = Object.assign(debug('libp2p:dialer'), {
error: debug('libp2p:dialer:err')
})
const errCode = require('err-code') const errCode = require('err-code')
const multiaddr = require('multiaddr')
const TimeoutController = require('timeout-abort-controller') const TimeoutController = require('timeout-abort-controller')
const anySignal = require('any-signal') const anySignal = require('any-signal')
const debug = require('debug')
const log = debug('libp2p:dialer')
log.error = debug('libp2p:dialer:error')
const { DialRequest } = require('./dial-request') const { DialRequest } = require('./dial-request')
const { publicAddressesFirst } = require('libp2p-utils/src/address-sort') const { publicAddressesFirst } = require('libp2p-utils/src/address-sort')
@ -20,9 +21,11 @@ const {
} = require('../constants') } = require('../constants')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('../peer-store')} PeerStore * @typedef {import('../peer-store')} PeerStore
* @typedef {import('../peer-store/address-book').Address} Address
* @typedef {import('../transport-manager')} TransportManager * @typedef {import('../transport-manager')} TransportManager
* @typedef {import('./dial-request')} DialRequest * @typedef {import('./dial-request')} DialRequest
*/ */
@ -172,7 +175,7 @@ class Dialer {
* @param {AbortSignal} [options.signal] - An AbortController signal * @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {PendingDial} * @returns {PendingDial}
*/ */
_createPendingDial (dialTarget, options) { _createPendingDial (dialTarget, options = {}) {
const dialAction = (addr, options) => { const dialAction = (addr, options) => {
if (options.signal.aborted) throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED) if (options.signal.aborted) throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)
return this.transportManager.dial(addr, options) return this.transportManager.dial(addr, options)

View File

@ -7,7 +7,6 @@ const errCode = require('err-code')
const { codes } = require('./errors') const { codes } = require('./errors')
/** /**
* @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
*/ */
@ -16,7 +15,7 @@ const { codes } = require('./errors')
* If a multiaddr is received, the addressBook is updated. * If a multiaddr is received, the addressBook is updated.
* *
* @param {PeerId|multiaddr|string} peer * @param {PeerId|multiaddr|string} peer
* @returns {{ id: PeerId, multiaddrs: Multiaddr[] }} * @returns {{ id: PeerId, multiaddrs: Multiaddr[]|undefined }}
*/ */
function getPeer (peer) { function getPeer (peer) {
if (typeof peer === 'string') { if (typeof peer === 'string') {

View File

@ -1,13 +1,13 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:identify') const log = Object.assign(debug('libp2p:identify'), {
log.error = debug('libp2p:identify:error') error: debug('libp2p:identify:err')
})
const errCode = require('err-code') const errCode = require('err-code')
const pb = require('it-protocol-buffers') const pb = require('it-protocol-buffers')
const lp = require('it-length-prefixed') const lp = require('it-length-prefixed')
const pipe = require('it-pipe') const { pipe } = require('it-pipe')
const { collect, take, consume } = require('streaming-iterables') const { collect, take, consume } = require('streaming-iterables')
const uint8ArrayFromString = require('uint8arrays/from-string') const uint8ArrayFromString = require('uint8arrays/from-string')
@ -50,9 +50,7 @@ class IdentifyService {
// When a new connection happens, trigger identify // When a new connection happens, trigger identify
this.connectionManager.on('peer:connect', (connection) => { this.connectionManager.on('peer:connect', (connection) => {
const peerId = connection.remotePeer this.identify(connection).catch(log.error)
this.identify(connection, peerId).catch(log.error)
}) })
// When self multiaddrs change, trigger identify-push // When self multiaddrs change, trigger identify-push
@ -74,7 +72,7 @@ class IdentifyService {
* Send an Identify Push update to the list of connections * Send an Identify Push update to the list of connections
* *
* @param {Connection[]} connections * @param {Connection[]} connections
* @returns {Promise<void>} * @returns {Promise<void[]>}
*/ */
async push (connections) { async push (connections) {
const signedPeerRecord = await this.peerStore.addressBook.getRawEnvelope(this.peerId) const signedPeerRecord = await this.peerStore.addressBook.getRawEnvelope(this.peerId)
@ -205,7 +203,7 @@ class IdentifyService {
* @param {string} options.protocol * @param {string} options.protocol
* @param {DuplexIterableStream} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
* @returns {Promise<void>} * @returns {Promise<void>|undefined}
*/ */
handleMessage ({ connection, stream, protocol }) { handleMessage ({ connection, stream, protocol }) {
switch (protocol) { switch (protocol) {
@ -226,6 +224,7 @@ class IdentifyService {
* @param {Object} options * @param {Object} options
* @param {DuplexIterableStream} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
* @returns {Promise<void>}
*/ */
async _handleIdentify ({ connection, stream }) { async _handleIdentify ({ connection, stream }) {
let publicKey = new Uint8Array(0) let publicKey = new Uint8Array(0)
@ -265,6 +264,7 @@ class IdentifyService {
* @param {object} options * @param {object} options
* @param {DuplexIterableStream} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
* @returns {Promise<void>}
*/ */
async _handlePush ({ connection, stream }) { async _handlePush ({ connection, stream }) {
let message let message

View File

@ -1,10 +1,11 @@
'use strict' 'use strict'
const { EventEmitter } = require('events')
const debug = require('debug') const debug = require('debug')
const log = Object.assign(debug('libp2p'), {
error: debug('libp2p:err')
})
const { EventEmitter } = require('events')
const globalThis = require('ipfs-utils/src/globalthis') const globalThis = require('ipfs-utils/src/globalthis')
const log = debug('libp2p')
log.error = debug('libp2p:error')
const errCode = require('err-code') const errCode = require('err-code')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -36,6 +37,7 @@ const {
/** /**
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
*/ */
/** /**
@ -131,6 +133,7 @@ class Libp2p extends EventEmitter {
const keychainOpts = Keychain.generateOptions() const keychainOpts = Keychain.generateOptions()
/** @type {Keychain} */
this.keychain = new Keychain(this._options.keychain.datastore, { this.keychain = new Keychain(this._options.keychain.datastore, {
passPhrase: this._options.keychain.pass, passPhrase: this._options.keychain.pass,
...keychainOpts, ...keychainOpts,
@ -285,7 +288,7 @@ class Libp2p extends EventEmitter {
* Stop the libp2p node by closing its listeners and open connections * Stop the libp2p node by closing its listeners and open connections
* *
* @async * @async
* @returns {void} * @returns {Promise<void>}
*/ */
async stop () { async stop () {
log('libp2p is stopping') log('libp2p is stopping')
@ -331,7 +334,7 @@ class Libp2p extends EventEmitter {
* Imports the private key as 'self', if needed. * Imports the private key as 'self', if needed.
* *
* @async * @async
* @returns {void} * @returns {Promise<void>}
*/ */
async loadKeychain () { async loadKeychain () {
try { try {
@ -360,12 +363,12 @@ class Libp2p extends EventEmitter {
* peer will be added to the nodes `peerStore` * peer will be added to the nodes `peerStore`
* *
* @param {PeerId|Multiaddr|string} peer - The peer to dial * @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {object} options * @param {object} [options]
* @param {AbortSignal} [options.signal] * @param {AbortSignal} [options.signal]
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
dial (peer, options) { dial (peer, options) {
return this.dialProtocol(peer, null, options) return this.dialProtocol(peer, undefined, options)
} }
/** /**
@ -375,8 +378,8 @@ class Libp2p extends EventEmitter {
* *
* @async * @async
* @param {PeerId|Multiaddr|string} peer - The peer to dial * @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {string[]|string} protocols * @param {undefined|string[]|string} protocols
* @param {object} options * @param {object} [options]
* @param {AbortSignal} [options.signal] * @param {AbortSignal} [options.signal]
* @returns {Promise<Connection|*>} * @returns {Promise<Connection|*>}
*/ */
@ -644,10 +647,10 @@ class Libp2p extends EventEmitter {
* Like `new Libp2p(options)` except it will create a `PeerId` * Like `new Libp2p(options)` except it will create a `PeerId`
* instance if one is not provided in options. * instance if one is not provided in options.
* *
* @param {Libp2pOptions & CreateOptions} [options] - Libp2p configuration options * @param {Libp2pOptions & CreateOptions} options - Libp2p configuration options
* @returns {Libp2p} * @returns {Promise<Libp2p>}
*/ */
Libp2p.create = async function create (options = {}) { Libp2p.create = async function create (options) {
if (options.peerId) { if (options.peerId) {
return new Libp2p(options) return new Libp2p(options)
} }

View File

@ -1,11 +1,12 @@
'use strict' 'use strict'
const debug = require('debug')
const log = Object.assign(debug('libp2p:plaintext'), {
error: debug('libp2p:plaintext:err')
})
const handshake = require('it-handshake') const handshake = require('it-handshake')
const lp = require('it-length-prefixed') const lp = require('it-length-prefixed')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const debug = require('debug')
const log = debug('libp2p:plaintext')
log.error = debug('libp2p:plaintext:error')
const { UnexpectedPeerError, InvalidCryptoExchangeError } = require('libp2p-interfaces/src/crypto/errors') const { UnexpectedPeerError, InvalidCryptoExchangeError } = require('libp2p-interfaces/src/crypto/errors')
const { Exchange, KeyType } = require('./proto') const { Exchange, KeyType } = require('./proto')

View File

@ -101,7 +101,8 @@ class Keychain {
* Creates a new instance of a key chain. * Creates a new instance of a key chain.
* *
* @param {DS} store - where the key are. * @param {DS} store - where the key are.
* @param {object} options - ??? * @param {object} options
* @class
*/ */
constructor (store, options) { constructor (store, options) {
if (!store) { if (!store) {

View File

@ -1,9 +1,10 @@
'use strict' 'use strict'
const errCode = require('err-code')
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:peer-routing') const log = Object.assign(debug('libp2p:peer-routing'), {
log.error = debug('libp2p:peer-routing:error') error: debug('libp2p:peer-routing:err')
})
const errCode = require('err-code')
const all = require('it-all') const all = require('it-all')
const pAny = require('p-any') const pAny = require('p-any')
@ -69,7 +70,6 @@ class PeerRouting {
clearDelayedInterval(this._timeoutId) clearDelayedInterval(this._timeoutId)
} }
<<<<<<< HEAD
/** /**
* Iterates over all peer routers in series to find the given peer. * Iterates over all peer routers in series to find the given peer.
* *
@ -89,20 +89,6 @@ class PeerRouting {
// If we don't have a result, we need to provide an error to keep trying // If we don't have a result, we need to provide an error to keep trying
if (!result || Object.keys(result).length === 0) { if (!result || Object.keys(result).length === 0) {
throw errCode(new Error('not found'), 'NOT_FOUND') throw errCode(new Error('not found'), 'NOT_FOUND')
=======
return {
/**
* Iterates over all peer routers in series to find the given peer.
*
* @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<{ id: PeerId, multiaddrs: Multiaddr[] }>}
*/
findPeer: async (id, options) => { // eslint-disable-line require-await
if (!routers.length) {
throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
>>>>>>> chore: address review
} }
return result return result

View File

@ -1,9 +1,10 @@
'use strict' 'use strict'
const errcode = require('err-code')
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:peer-store:address-book') const log = Object.assign(debug('libp2p:peer-store:address-book'), {
log.error = debug('libp2p:peer-store:address-book:error') error: debug('libp2p:peer-store:address-book:err')
})
const errcode = require('err-code')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -18,6 +19,7 @@ const Envelope = require('../record/envelope')
/** /**
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('./')} PeerStore
*/ */
/** /**
@ -75,7 +77,7 @@ class AddressBook extends Book {
/** /**
* Map known peers to their known Address Entries. * Map known peers to their known Address Entries.
* *
* @type {Map<string, Entry[]>} * @type {Map<string, Entry>}
*/ */
this.data = new Map() this.data = new Map()
} }
@ -110,7 +112,7 @@ class AddressBook extends Book {
const peerId = peerRecord.peerId const peerId = peerRecord.peerId
const id = peerId.toB58String() const id = peerId.toB58String()
const entry = this.data.get(id) || {} const entry = this.data.get(id) || { record: undefined }
const storedRecord = entry.record const storedRecord = entry.record
// ensure seq is greater than, or equal to, the last received // ensure seq is greater than, or equal to, the last received
@ -156,7 +158,7 @@ class AddressBook extends Book {
* Returns undefined if no record exists. * Returns undefined if no record exists.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Promise<Envelope|void>} * @returns {Promise<Envelope|void>|undefined}
*/ */
getPeerRecord (peerId) { getPeerRecord (peerId) {
const raw = this.getRawEnvelope(peerId) const raw = this.getRawEnvelope(peerId)

View File

@ -9,12 +9,17 @@ const {
const passthrough = data => data const passthrough = data => data
/**
* @typedef {import('./')} PeerStore
*/
/**
* @template T
*/
class Book { class Book {
/** /**
* The Book is the skeleton for the PeerStore books. * The Book is the skeleton for the PeerStore books.
* *
* @template T
*
* @class * @class
* @param {Object} properties * @param {Object} properties
* @param {PeerStore} properties.peerStore - PeerStore instance. * @param {PeerStore} properties.peerStore - PeerStore instance.
@ -31,7 +36,7 @@ class Book {
/** /**
* Map known peers to their data. * Map known peers to their data.
* *
* @type {Map<string, T[]} * @type {Map<string, T[]|T>}
*/ */
this.data = new Map() this.data = new Map()
} }
@ -94,6 +99,7 @@ class Book {
const rec = this.data.get(peerId.toB58String()) const rec = this.data.get(peerId.toB58String())
// @ts-ignore
return rec ? [...rec] : undefined return rec ? [...rec] : undefined
} }

View File

@ -1,9 +1,6 @@
'use strict' 'use strict'
const errcode = require('err-code') const errcode = require('err-code')
const debug = require('debug')
const log = debug('libp2p:peer-store')
log.error = debug('libp2p:peer-store:error')
const { EventEmitter } = require('events') const { EventEmitter } = require('events')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -14,7 +11,7 @@ const MetadataBook = require('./metadata-book')
const ProtoBook = require('./proto-book') const ProtoBook = require('./proto-book')
const { const {
ERR_INVALID_PARAMETERS codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
/** /**
@ -127,7 +124,7 @@ class PeerStore extends EventEmitter {
* Get the stored information of a given peer. * Get the stored information of a given peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Peer} * @returns {Peer|undefined}
*/ */
get (peerId) { get (peerId) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -1,9 +1,10 @@
'use strict' 'use strict'
const errcode = require('err-code')
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:peer-store:key-book') const log = Object.assign(debug('libp2p:peer-store:key-book'), {
log.error = debug('libp2p:peer-store:key-book:error') error: debug('libp2p:peer-store:key-book:err')
})
const errcode = require('err-code')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -13,6 +14,10 @@ const {
codes: { ERR_INVALID_PARAMETERS } codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
/**
* @typedef {import('./')} PeerStore
*/
/** /**
* @extends {Book} * @extends {Book}
*/ */

View File

@ -1,9 +1,10 @@
'use strict' 'use strict'
const errcode = require('err-code')
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:peer-store:proto-book') const log = Object.assign(debug('libp2p:peer-store:proto-book'), {
log.error = debug('libp2p:peer-store:proto-book:error') error: debug('libp2p:peer-store:proto-book:err')
})
const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals') const uint8ArrayEquals = require('uint8arrays/equals')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -14,6 +15,10 @@ const {
codes: { ERR_INVALID_PARAMETERS } codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
/**
* @typedef {import('./')} PeerStore
*/
/** /**
* @extends {Book} * @extends {Book}
* *

View File

@ -1,9 +1,9 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:persistent-peer-store') const log = Object.assign(debug('libp2p:persistent-peer-store'), {
log.error = debug('libp2p:persistent-peer-store:error') error: debug('libp2p:persistent-peer-store:err')
})
const { Key } = require('interface-datastore') const { Key } = require('interface-datastore')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
const PeerId = require('peer-id') const PeerId = require('peer-id')
@ -346,6 +346,7 @@ class PersistentPeerStore extends PeerStore {
case 'addrs': case 'addrs':
decoded = Addresses.decode(value) decoded = Addresses.decode(value)
// @ts-ignore
this.addressBook._setData( this.addressBook._setData(
peerId, peerId,
{ {
@ -363,6 +364,7 @@ class PersistentPeerStore extends PeerStore {
case 'keys': case 'keys':
decoded = await PeerId.createFromPubKey(value) decoded = await PeerId.createFromPubKey(value)
// @ts-ignore
this.keyBook._setData( this.keyBook._setData(
decoded, decoded,
decoded, decoded,
@ -378,6 +380,7 @@ class PersistentPeerStore extends PeerStore {
case 'protos': case 'protos':
decoded = Protocols.decode(value) decoded = Protocols.decode(value)
// @ts-ignore
this.protoBook._setData( this.protoBook._setData(
peerId, peerId,
new Set(decoded.protocols), new Set(decoded.protocols),

View File

@ -1,10 +1,10 @@
'use strict' 'use strict'
const errcode = require('err-code')
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:peer-store:proto-book') const log = Object.assign(debug('libp2p:peer-store:proto-book'), {
log.error = debug('libp2p:peer-store:proto-book:error') error: debug('libp2p:peer-store:proto-book:err')
})
const errcode = require('err-code')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const Book = require('./book') const Book = require('./book')
@ -13,6 +13,10 @@ const {
codes: { ERR_INVALID_PARAMETERS } codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
/**
* @typedef {import('./')} PeerStore
*/
/** /**
* @extends {Book} * @extends {Book}
* *
@ -79,6 +83,7 @@ class ProtoBook extends Book {
return this return this
} }
// @ts-ignore
this._setData(peerId, newSet) this._setData(peerId, newSet)
log(`stored provided protocols for ${id}`) log(`stored provided protocols for ${id}`)
@ -114,6 +119,7 @@ class ProtoBook extends Book {
return this return this
} }
// @ts-ignore
this._setData(peerId, newSet) this._setData(peerId, newSet)
log(`added provided protocols for ${id}`) log(`added provided protocols for ${id}`)
@ -152,6 +158,7 @@ class ProtoBook extends Book {
return this return this
} }
// @ts-ignore
this._setData(peerId, newSet) this._setData(peerId, newSet)
log(`removed provided protocols for ${id}`) log(`removed provided protocols for ${id}`)
} }

View File

@ -1,14 +1,16 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p-ping') const log = Object.assign(debug('libp2p:ping'), {
log.error = debug('libp2p-ping:error') error: debug('libp2p:ping:err')
})
const errCode = require('err-code') const errCode = require('err-code')
const crypto = require('libp2p-crypto') const crypto = require('libp2p-crypto')
const pipe = require('it-pipe') const { pipe } = require('it-pipe')
const { toBuffer } = require('it-buffer') const { toBuffer } = require('it-buffer')
const { collect, take } = require('streaming-iterables') const { collect, take } = require('streaming-iterables')
const equals = require('uint8arrays/equals')
const { PROTOCOL, PING_LENGTH } = require('./constants') const { PROTOCOL, PING_LENGTH } = require('./constants')
@ -26,11 +28,12 @@ const { PROTOCOL, PING_LENGTH } = require('./constants')
* @returns {Promise<number>} * @returns {Promise<number>}
*/ */
async function ping (node, peer) { async function ping (node, peer) {
// @ts-ignore
log('dialing %s to %s', PROTOCOL, peer.toB58String ? peer.toB58String() : peer) log('dialing %s to %s', PROTOCOL, peer.toB58String ? peer.toB58String() : peer)
const { stream } = await node.dialProtocol(peer, PROTOCOL) const { stream } = await node.dialProtocol(peer, PROTOCOL)
const start = new Date() const start = new Date().getTime()
const data = crypto.randomBytes(PING_LENGTH) const data = crypto.randomBytes(PING_LENGTH)
const [result] = await pipe( const [result] = await pipe(
@ -42,7 +45,7 @@ async function ping (node, peer) {
) )
const end = Date.now() const end = Date.now()
if (!data.equals(result)) { if (!equals(data, result)) {
throw errCode(new Error('Received wrong ping ack'), 'ERR_WRONG_PING_ACK') throw errCode(new Error('Received wrong ping ack'), 'ERR_WRONG_PING_ACK')
} }

View File

@ -1,16 +1,17 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = Object.assign(debug('libp2p:pnet'), {
trace: debug('libp2p:pnet:trace'),
error: debug('libp2p:pnet:err')
})
const Errors = require('./errors') const Errors = require('./errors')
const xsalsa20 = require('xsalsa20') const xsalsa20 = require('xsalsa20')
const KEY_LENGTH = require('./key-generator').KEY_LENGTH const KEY_LENGTH = require('./key-generator').KEY_LENGTH
const uint8ArrayFromString = require('uint8arrays/from-string') const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string') const uint8ArrayToString = require('uint8arrays/to-string')
const log = debug('libp2p:pnet')
log.trace = debug('libp2p:pnet:trace')
log.error = debug('libp2p:pnet:err')
/** /**
* Creates a stream iterable to encrypt messages in a private network * Creates a stream iterable to encrypt messages in a private network
* *

View File

@ -1,12 +1,16 @@
'use strict' 'use strict'
const pipe = require('it-pipe') const debug = require('debug')
const log = Object.assign(debug('libp2p:pnet'), {
error: debug('libp2p:pnet:err')
})
const { pipe } = require('it-pipe')
const errcode = require('err-code') const errcode = require('err-code')
const duplexPair = require('it-pair/duplex') const duplexPair = require('it-pair/duplex')
const crypto = require('libp2p-crypto') const crypto = require('libp2p-crypto')
const Errors = require('./errors') const Errors = require('./errors')
const { const {
ERR_INVALID_PARAMETERS codes: { ERR_INVALID_PARAMETERS }
} = require('../errors') } = require('../errors')
const { const {
createBoxStream, createBoxStream,
@ -15,9 +19,6 @@ const {
} = require('./crypto') } = require('./crypto')
const handshake = require('it-handshake') const handshake = require('it-handshake')
const { NONCE_LENGTH } = require('./key-generator') const { NONCE_LENGTH } = require('./key-generator')
const debug = require('debug')
const log = debug('libp2p:pnet')
log.error = debug('libp2p:pnet:err')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
@ -44,7 +45,7 @@ class Protector {
* created with. * created with.
* *
* @param {Connection} connection - The connection to protect * @param {Connection} connection - The connection to protect
* @returns {DuplexIterableStream} A protected duplex iterable * @returns {Promise<DuplexIterableStream>} A protected duplex iterable
*/ */
async protect (connection) { async protect (connection) {
if (!connection) { if (!connection) {

View File

@ -22,6 +22,8 @@ module.exports = generate
module.exports.NONCE_LENGTH = 24 module.exports.NONCE_LENGTH = 24
module.exports.KEY_LENGTH = KEY_LENGTH module.exports.KEY_LENGTH = KEY_LENGTH
// @ts-ignore
if (require.main === module) { if (require.main === module) {
// @ts-ignore
generate(process.stdout) generate(process.stdout)
} }

View File

@ -2,6 +2,7 @@
/** /**
* @typedef {import('libp2p-interfaces/src/pubsub').InMessage} InMessage * @typedef {import('libp2p-interfaces/src/pubsub').InMessage} InMessage
* @typedef {import('libp2p-interfaces/src/pubsub')} PubsubRouter
*/ */
// Pubsub adapter to keep API with handlers while not removed. // Pubsub adapter to keep API with handlers while not removed.
@ -12,7 +13,7 @@ module.exports = (PubsubRouter, libp2p, options) => {
* *
* @override * @override
* @param {string} topic * @param {string} topic
* @param {function(msg: InMessage)} [handler] * @param {(msg: InMessage) => void} [handler]
* @returns {void} * @returns {void}
*/ */
subscribe (topic, handler) { subscribe (topic, handler) {
@ -26,7 +27,7 @@ module.exports = (PubsubRouter, libp2p, options) => {
* *
* @override * @override
* @param {string} topic * @param {string} topic
* @param {function(msg: InMessage)} [handler] * @param {(msg: InMessage) => void} [handler]
* @returns {void} * @returns {void}
*/ */
unsubscribe (topic, handler) { unsubscribe (topic, handler) {

View File

@ -1,8 +1,5 @@
'use strict' 'use strict'
const debug = require('debug')
const log = debug('libp2p:envelope')
log.error = debug('libp2p:envelope:error')
const errCode = require('err-code') const errCode = require('err-code')
const uint8arraysConcat = require('uint8arrays/concat') const uint8arraysConcat = require('uint8arrays/concat')
const uint8arraysFromString = require('uint8arrays/from-string') const uint8arraysFromString = require('uint8arrays/from-string')
@ -15,7 +12,7 @@ const { codes } = require('../../errors')
const Protobuf = require('./envelope.proto') const Protobuf = require('./envelope.proto')
/** /**
* @typedef {import('peer-id')} PeerId * @typedef {import('libp2p-interfaces/src/record')} Record
*/ */
class Envelope { class Envelope {
@ -145,7 +142,7 @@ Envelope.createFromProtobuf = async (data) => {
* @async * @async
* @param {Record} record * @param {Record} record
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Envelope} * @returns {Promise<Envelope>}
*/ */
Envelope.seal = async (record, peerId) => { Envelope.seal = async (record, peerId) => {
const domain = record.domain const domain = record.domain
@ -169,7 +166,7 @@ Envelope.seal = async (record, peerId) => {
* *
* @param {Uint8Array} data * @param {Uint8Array} data
* @param {string} domain * @param {string} domain
* @returns {Envelope} * @returns {Promise<Envelope>}
*/ */
Envelope.openAndCertify = async (data, domain) => { Envelope.openAndCertify = async (data, domain) => {
const envelope = await Envelope.createFromProtobuf(data) const envelope = await Envelope.createFromProtobuf(data)

View File

@ -1,12 +1,13 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = Object.assign(debug('libp2p:peer-store'), {
error: debug('libp2p:peer-store:err')
})
const errcode = require('err-code') const errcode = require('err-code')
const log = debug('libp2p:peer-store')
log.error = debug('libp2p:peer-store:error')
const { const {
ERR_INVALID_PARAMETERS codes: { ERR_INVALID_PARAMETERS }
} = require('./errors') } = require('./errors')
const Topology = require('libp2p-interfaces/src/topology') const Topology = require('libp2p-interfaces/src/topology')
@ -73,11 +74,12 @@ class Registrar {
*/ */
register (topology) { register (topology) {
if (!Topology.isTopology(topology)) { if (!Topology.isTopology(topology)) {
log.error('topology must be an instance of interfaces/topology')
throw errcode(new Error('topology must be an instance of interfaces/topology'), ERR_INVALID_PARAMETERS) throw errcode(new Error('topology must be an instance of interfaces/topology'), ERR_INVALID_PARAMETERS)
} }
// Create topology // Create topology
const id = (parseInt(Math.random() * 1e9)).toString(36) + Date.now() const id = (Math.random() * 1e9).toString(36) + Date.now()
this.topologies.set(id, topology) this.topologies.set(id, topology)

View File

@ -1,11 +1,13 @@
'use strict' 'use strict'
const debug = require('debug')
const log = Object.assign(debug('libp2p:transports'), {
error: debug('libp2p:transports:err')
})
const pSettle = require('p-settle') const pSettle = require('p-settle')
const { codes } = require('./errors') const { codes } = require('./errors')
const errCode = require('err-code') const errCode = require('err-code')
const debug = require('debug')
const log = debug('libp2p:transports')
log.error = debug('libp2p:transports:error')
const { updateSelfPeerRecord } = require('./record/utils') const { updateSelfPeerRecord } = require('./record/utils')
@ -18,7 +20,7 @@ const { updateSelfPeerRecord } = require('./record/utils')
* @property {import('./upgrader')} upgrader * @property {import('./upgrader')} upgrader
* *
* @typedef {Object} TransportManagerOptions * @typedef {Object} TransportManagerOptions
* @property {boolean} [faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance. * @property {number} [faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance.
*/ */
class TransportManager { class TransportManager {
@ -126,7 +128,7 @@ class TransportManager {
/** /**
* Returns all the transports instances. * Returns all the transports instances.
* *
* @returns {Iterator<Transport>} * @returns {IterableIterator<Transport>}
*/ */
getTransports () { getTransports () {
return this._transports.values() return this._transports.values()
@ -166,7 +168,7 @@ class TransportManager {
// For each supported multiaddr, create a listener // For each supported multiaddr, create a listener
for (const addr of supportedAddrs) { for (const addr of supportedAddrs) {
log('creating listener for %s on %s', key, addr) log('creating listener for %s on %s', key, addr)
const listener = transport.createListener({}, this.onConnection) const listener = transport.createListener({})
this._listeners.get(key).push(listener) this._listeners.get(key).push(listener)
// Track listen/close events // Track listen/close events

18
src/types.ts Normal file
View File

@ -0,0 +1,18 @@
// Insecure Message types
export enum KeyType {
RSA = 0,
Ed25519 = 1,
Secp256k1 = 2,
ECDSA = 3
}
export type MessagePublicKey = {
Type: KeyType
Data: Uint8Array
}
export type MessageExchange = {
id: Uint8Array
pubKey: MessagePublicKey
}

View File

@ -1,20 +1,22 @@
'use strict' 'use strict'
const debug = require('debug') const debug = require('debug')
const log = debug('libp2p:upgrader') const log = Object.assign(debug('libp2p:upgrader'), {
log.error = debug('libp2p:upgrader:error') error: debug('libp2p:upgrader:err')
})
const errCode = require('err-code')
const Multistream = require('multistream-select') const Multistream = require('multistream-select')
const { Connection } = require('libp2p-interfaces/src/connection') const { Connection } = require('libp2p-interfaces/src/connection')
const ConnectionStatus = require('libp2p-interfaces/src/connection/status') const ConnectionStatus = require('libp2p-interfaces/src/connection/status')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const pipe = require('it-pipe') const pipe = require('it-pipe')
const errCode = require('err-code')
const mutableProxy = require('mutable-proxy') const mutableProxy = require('mutable-proxy')
const { codes } = require('./errors') const { codes } = require('./errors')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('multiaddr')} Multiaddr
*/ */
/** /**
@ -36,11 +38,11 @@ class Upgrader {
/** /**
* @param {object} options * @param {object} options
* @param {PeerId} options.localPeer * @param {PeerId} options.localPeer
* @param {Metrics} options.metrics * @param {import('./metrics')} [options.metrics]
* @param {Map<string, Crypto>} options.cryptos * @param {Map<string, Crypto>} options.cryptos
* @param {Map<string, Muxer>} options.muxers * @param {Map<string, Muxer>} options.muxers
* @param {function(Connection)} options.onConnection - Called when a connection is upgraded * @param {(Connection) => void} options.onConnection - Called when a connection is upgraded
* @param {function(Connection)} options.onConnectionEnd * @param {(Connection) => void} options.onConnectionEnd
*/ */
constructor ({ constructor ({
localPeer, localPeer,
@ -78,7 +80,7 @@ class Upgrader {
if (this.metrics) { if (this.metrics) {
({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy()) ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
const idString = (parseInt(Math.random() * 1e9)).toString(36) + Date.now() const idString = (Math.random() * 1e9).toString(36) + Date.now()
setPeer({ toB58String: () => idString }) setPeer({ toB58String: () => idString })
maConn = this.metrics.trackStream({ stream: maConn, remotePeer: proxyPeer }) maConn = this.metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
} }

9
tsconfig.json Normal file
View File

@ -0,0 +1,9 @@
{
"extends": "./node_modules/aegir/src/config/tsconfig.aegir.json",
"compilerOptions": {
"outDir": "dist"
},
"include": [
"src"
]
}