diff --git a/package.json b/package.json index 3996c800c0..b7cd5777c4 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,15 @@ "description": "JavaScript implementation of libp2p, a modular peer to peer network stack", "leadMaintainer": "Jacob Heun ", "main": "src/index.js", + "types": "dist/src/index.d.ts", + "typesVersions": { + "*": { + "src/*": [ + "dist/src/*", + "dist/src/*/index" + ] + } + }, "files": [ "dist", "src" @@ -15,6 +24,7 @@ "test:node": "aegir test -t node -f \"./test/**/*.{node,spec}.js\"", "test:browser": "aegir test -t browser", "test:examples": "cd examples && npm run test:all", + "test:types": "aegir ts -p check", "release": "aegir release -t node -t browser", "release-minor": "aegir release --type minor -t node -t browser", "release-major": "aegir release --type major -t node -t browser", @@ -88,7 +98,7 @@ "devDependencies": { "@nodeutils/defaults-deep": "^1.1.0", "abortable-iterator": "^3.0.0", - "aegir": "^27.0.0", + "aegir": "^29.1.0", "chai-bytes": "^0.1.2", "chai-string": "^1.5.0", "delay": "^4.3.0", diff --git a/src/address-manager/index.js b/src/address-manager/index.js index d4811be72c..5c9874af33 100644 --- a/src/address-manager/index.js +++ b/src/address-manager/index.js @@ -1,9 +1,5 @@ 'use strict' -const debug = require('debug') -const log = debug('libp2p:addresses') -log.error = debug('libp2p:addresses:error') - const multiaddr = require('multiaddr') /** diff --git a/src/circuit/auto-relay.js b/src/circuit/auto-relay.js index 7cca188735..babf4ea75a 100644 --- a/src/circuit/auto-relay.js +++ b/src/circuit/auto-relay.js @@ -1,8 +1,9 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:auto-relay') -log.error = debug('libp2p:auto-relay:error') +const log = Object.assign(debug('libp2p:auto-relay'), { + error: debug('libp2p:auto-relay:err') +}) const uint8ArrayFromString = require('uint8arrays/from-string') const uint8ArrayToString = require('uint8arrays/to-string') diff --git a/src/circuit/circuit/hop.js b/src/circuit/circuit/hop.js index c653a7c9ae..7cd7ab2312 100644 --- a/src/circuit/circuit/hop.js +++ b/src/circuit/circuit/hop.js @@ -1,21 +1,26 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:circuit:hop') -log.error = debug('libp2p:circuit:hop:error') +const log = Object.assign(debug('libp2p:circuit:hop'), { + error: debug('libp2p:circuit:hop:err') +}) +const errCode = require('err-code') const PeerId = require('peer-id') const { validateAddrs } = require('./utils') const StreamHandler = require('./stream-handler') const { CircuitRelay: CircuitPB } = require('../protocol') -const pipe = require('it-pipe') -const errCode = require('err-code') +const { pipe } = require('it-pipe') const { codes: Errors } = require('../../errors') const { stop } = require('./stop') const multicodec = require('./../multicodec') +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + */ + module.exports.handleHop = async function handleHop ({ connection, request, diff --git a/src/circuit/circuit/stop.js b/src/circuit/circuit/stop.js index 77eaa1fcc2..f9447b722d 100644 --- a/src/circuit/circuit/stop.js +++ b/src/circuit/circuit/stop.js @@ -1,23 +1,28 @@ '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 multicodec = require('../multicodec') const StreamHandler = require('./stream-handler') const { validateAddrs } = require('./utils') -const debug = require('debug') -const log = debug('libp2p:circuit:stop') -log.error = debug('libp2p:circuit:stop:error') +/** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + */ /** * Handles incoming STOP requests * * @private - * @param {*} options + * @param {object} options * @param {Connection} options.connection * @param {*} options.request - The CircuitRelay protobuf request (unencoded) * @param {StreamHandler} options.streamHandler - * @returns {Promise<*>} Resolves a duplex iterable + * @returns {Promise<*>|void} Resolves a duplex iterable */ module.exports.handleStop = function handleStop ({ connection, @@ -44,7 +49,7 @@ module.exports.handleStop = function handleStop ({ * Creates a STOP request * * @private - * @param {*} options + * @param {object} options * @param {Connection} options.connection * @param {*} options.request - The CircuitRelay protobuf request (unencoded) * @returns {Promise<*>} Resolves a duplex iterable diff --git a/src/circuit/circuit/stream-handler.js b/src/circuit/circuit/stream-handler.js index 8b8ecf89bc..fe0adba722 100644 --- a/src/circuit/circuit/stream-handler.js +++ b/src/circuit/circuit/stream-handler.js @@ -1,13 +1,14 @@ '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 handshake = require('it-handshake') 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 { /** * Create a stream handler for connection @@ -27,7 +28,7 @@ class StreamHandler { * Read and decode message * * @async - * @returns {void} + * @returns {Promise} */ async read () { const msg = await this.decoder.next() diff --git a/src/circuit/circuit/utils.js b/src/circuit/circuit/utils.js index be7ab35a73..669c37adc3 100644 --- a/src/circuit/circuit/utils.js +++ b/src/circuit/circuit/utils.js @@ -3,6 +3,10 @@ const multiaddr = require('multiaddr') const { CircuitRelay } = require('../protocol') +/** + * @typedef {import('./stream-handler')} StreamHandler + */ + /** * Write a response * diff --git a/src/circuit/index.js b/src/circuit/index.js index 91cb685106..447d829ac5 100644 --- a/src/circuit/index.js +++ b/src/circuit/index.js @@ -1,8 +1,9 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:relay') -log.error = debug('libp2p:relay:error') +const log = Object.assign(debug('libp2p:relay'), { + error: debug('libp2p:relay:err') +}) const { setDelayedInterval, diff --git a/src/circuit/listener.js b/src/circuit/listener.js index 02e371fb8b..e591e43d11 100644 --- a/src/circuit/listener.js +++ b/src/circuit/listener.js @@ -1,14 +1,14 @@ 'use strict' -const EventEmitter = require('events') +const { EventEmitter } = require('events') const multiaddr = require('multiaddr') -const debug = require('debug') -const log = debug('libp2p:circuit:listener') -log.err = debug('libp2p:circuit:error:listener') +/** + * @typedef {import('multiaddr')} Multiaddr + */ /** - * @param {Libp2p} libp2p + * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { diff --git a/src/connection-manager/index.js b/src/connection-manager/index.js index 7b6ae5e414..8259e56ba5 100644 --- a/src/connection-manager/index.js +++ b/src/connection-manager/index.js @@ -1,8 +1,9 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:connection-manager') -log.error = debug('libp2p:connection-manager:error') +const log = Object.assign(debug('libp2p:connection-manager'), { + error: debug('libp2p:connection-manager:err') +}) const errcode = require('err-code') const mergeOptions = require('merge-options') @@ -14,7 +15,7 @@ const { EventEmitter } = require('events') const PeerId = require('peer-id') const { - ERR_INVALID_PARAMETERS + codes: { ERR_INVALID_PARAMETERS } } = require('../errors') const defaultOptions = { @@ -187,15 +188,17 @@ class ConnectionManager extends EventEmitter { * @private */ _checkMetrics () { - const movingAverages = this._libp2p.metrics.global.movingAverages - const received = movingAverages.dataReceived[this._options.movingAverageInterval].movingAverage() - this._checkMaxLimit('maxReceivedData', received) - const sent = movingAverages.dataSent[this._options.movingAverageInterval].movingAverage() - this._checkMaxLimit('maxSentData', sent) - const total = received + sent - this._checkMaxLimit('maxData', total) - log('metrics update', total) - this._timer = retimer(this._checkMetrics, this._options.pollInterval) + if (this._libp2p.metrics) { + const movingAverages = this._libp2p.metrics.global.movingAverages + const received = movingAverages.dataReceived[this._options.movingAverageInterval].movingAverage() + this._checkMaxLimit('maxReceivedData', received) + const sent = movingAverages.dataSent[this._options.movingAverageInterval].movingAverage() + this._checkMaxLimit('maxSentData', sent) + const total = received + sent + this._checkMaxLimit('maxData', total) + 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. * * @param {PeerId} peerId - * @returns {Connection} + * @returns {Connection|null} */ get (peerId) { const connections = this.getAll(peerId) diff --git a/src/content-routing.js b/src/content-routing.js index 75131ba1fa..185865d8ae 100644 --- a/src/content-routing.js +++ b/src/content-routing.js @@ -9,6 +9,7 @@ const pAny = require('p-any') /** * @typedef {import('peer-id')} PeerId * @typedef {import('multiaddr')} Multiaddr + * @typedef {import('cids')} CID */ /** @@ -63,7 +64,7 @@ module.exports = (node) => { * a provider of the given key. * * @param {CID} key - The CID key of the content to find - * @returns {Promise} + * @returns {Promise} */ async provide (key) { // eslint-disable-line require-await if (!routers.length) { diff --git a/src/dialer/dial-request.js b/src/dialer/dial-request.js index d91158ed49..f906c2ba81 100644 --- a/src/dialer/dial-request.js +++ b/src/dialer/dial-request.js @@ -1,15 +1,13 @@ 'use strict' +const errCode = require('err-code') const AbortController = require('abort-controller') 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 pAny = require('p-any') /** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('./')} Dialer * @typedef {import('multiaddr')} Multiaddr */ @@ -45,7 +43,7 @@ class DialRequest { * @async * @param {object} [options] * @param {AbortSignal} [options.signal] - An AbortController signal - * @returns {Connection} + * @returns {Promise} */ async run (options) { const tokens = this.dialer.getTokens(this.addrs.length) diff --git a/src/dialer/index.js b/src/dialer/index.js index 18be09c1a5..4233e2d977 100644 --- a/src/dialer/index.js +++ b/src/dialer/index.js @@ -1,12 +1,13 @@ '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 multiaddr = require('multiaddr') const TimeoutController = require('timeout-abort-controller') 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 { publicAddressesFirst } = require('libp2p-utils/src/address-sort') @@ -20,9 +21,11 @@ const { } = require('../constants') /** + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('multiaddr')} Multiaddr * @typedef {import('peer-id')} PeerId * @typedef {import('../peer-store')} PeerStore + * @typedef {import('../peer-store/address-book').Address} Address * @typedef {import('../transport-manager')} TransportManager * @typedef {import('./dial-request')} DialRequest */ @@ -172,7 +175,7 @@ class Dialer { * @param {AbortSignal} [options.signal] - An AbortController signal * @returns {PendingDial} */ - _createPendingDial (dialTarget, options) { + _createPendingDial (dialTarget, options = {}) { const dialAction = (addr, options) => { if (options.signal.aborted) throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED) return this.transportManager.dial(addr, options) diff --git a/src/get-peer.js b/src/get-peer.js index 29422334eb..35e2f26429 100644 --- a/src/get-peer.js +++ b/src/get-peer.js @@ -7,7 +7,6 @@ const errCode = require('err-code') const { codes } = require('./errors') /** - * @typedef {import('peer-id')} PeerId * @typedef {import('multiaddr')} Multiaddr */ @@ -16,7 +15,7 @@ const { codes } = require('./errors') * If a multiaddr is received, the addressBook is updated. * * @param {PeerId|multiaddr|string} peer - * @returns {{ id: PeerId, multiaddrs: Multiaddr[] }} + * @returns {{ id: PeerId, multiaddrs: Multiaddr[]|undefined }} */ function getPeer (peer) { if (typeof peer === 'string') { diff --git a/src/identify/index.js b/src/identify/index.js index 7b1617e139..fe8b91b0a4 100644 --- a/src/identify/index.js +++ b/src/identify/index.js @@ -1,13 +1,13 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:identify') -log.error = debug('libp2p:identify:error') - +const log = Object.assign(debug('libp2p:identify'), { + error: debug('libp2p:identify:err') +}) const errCode = require('err-code') const pb = require('it-protocol-buffers') const lp = require('it-length-prefixed') -const pipe = require('it-pipe') +const { pipe } = require('it-pipe') const { collect, take, consume } = require('streaming-iterables') const uint8ArrayFromString = require('uint8arrays/from-string') @@ -50,9 +50,7 @@ class IdentifyService { // When a new connection happens, trigger identify this.connectionManager.on('peer:connect', (connection) => { - const peerId = connection.remotePeer - - this.identify(connection, peerId).catch(log.error) + this.identify(connection).catch(log.error) }) // When self multiaddrs change, trigger identify-push @@ -74,7 +72,7 @@ class IdentifyService { * Send an Identify Push update to the list of connections * * @param {Connection[]} connections - * @returns {Promise} + * @returns {Promise} */ async push (connections) { const signedPeerRecord = await this.peerStore.addressBook.getRawEnvelope(this.peerId) @@ -205,7 +203,7 @@ class IdentifyService { * @param {string} options.protocol * @param {DuplexIterableStream} options.stream * @param {Connection} options.connection - * @returns {Promise} + * @returns {Promise|undefined} */ handleMessage ({ connection, stream, protocol }) { switch (protocol) { @@ -226,6 +224,7 @@ class IdentifyService { * @param {Object} options * @param {DuplexIterableStream} options.stream * @param {Connection} options.connection + * @returns {Promise} */ async _handleIdentify ({ connection, stream }) { let publicKey = new Uint8Array(0) @@ -265,6 +264,7 @@ class IdentifyService { * @param {object} options * @param {DuplexIterableStream} options.stream * @param {Connection} options.connection + * @returns {Promise} */ async _handlePush ({ connection, stream }) { let message diff --git a/src/index.js b/src/index.js index eca2206fa8..d9440adf1e 100644 --- a/src/index.js +++ b/src/index.js @@ -1,10 +1,11 @@ 'use strict' -const { EventEmitter } = require('events') 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 log = debug('libp2p') -log.error = debug('libp2p:error') const errCode = require('err-code') const PeerId = require('peer-id') @@ -36,6 +37,7 @@ const { /** * @typedef {import('multiaddr')} Multiaddr + * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection */ /** @@ -131,6 +133,7 @@ class Libp2p extends EventEmitter { const keychainOpts = Keychain.generateOptions() + /** @type {Keychain} */ this.keychain = new Keychain(this._options.keychain.datastore, { passPhrase: this._options.keychain.pass, ...keychainOpts, @@ -285,7 +288,7 @@ class Libp2p extends EventEmitter { * Stop the libp2p node by closing its listeners and open connections * * @async - * @returns {void} + * @returns {Promise} */ async stop () { log('libp2p is stopping') @@ -331,7 +334,7 @@ class Libp2p extends EventEmitter { * Imports the private key as 'self', if needed. * * @async - * @returns {void} + * @returns {Promise} */ async loadKeychain () { try { @@ -360,12 +363,12 @@ class Libp2p extends EventEmitter { * peer will be added to the nodes `peerStore` * * @param {PeerId|Multiaddr|string} peer - The peer to dial - * @param {object} options + * @param {object} [options] * @param {AbortSignal} [options.signal] * @returns {Promise} */ dial (peer, options) { - return this.dialProtocol(peer, null, options) + return this.dialProtocol(peer, undefined, options) } /** @@ -375,8 +378,8 @@ class Libp2p extends EventEmitter { * * @async * @param {PeerId|Multiaddr|string} peer - The peer to dial - * @param {string[]|string} protocols - * @param {object} options + * @param {undefined|string[]|string} protocols + * @param {object} [options] * @param {AbortSignal} [options.signal] * @returns {Promise} */ @@ -644,10 +647,10 @@ class Libp2p extends EventEmitter { * Like `new Libp2p(options)` except it will create a `PeerId` * instance if one is not provided in options. * - * @param {Libp2pOptions & CreateOptions} [options] - Libp2p configuration options - * @returns {Libp2p} + * @param {Libp2pOptions & CreateOptions} options - Libp2p configuration options + * @returns {Promise} */ -Libp2p.create = async function create (options = {}) { +Libp2p.create = async function create (options) { if (options.peerId) { return new Libp2p(options) } diff --git a/src/insecure/plaintext.js b/src/insecure/plaintext.js index 0e9f8dd992..92010798c1 100644 --- a/src/insecure/plaintext.js +++ b/src/insecure/plaintext.js @@ -1,11 +1,12 @@ 'use strict' +const debug = require('debug') +const log = Object.assign(debug('libp2p:plaintext'), { + error: debug('libp2p:plaintext:err') +}) const handshake = require('it-handshake') const lp = require('it-length-prefixed') 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 { Exchange, KeyType } = require('./proto') diff --git a/src/keychain/index.js b/src/keychain/index.js index c823eb3e46..10d402c669 100644 --- a/src/keychain/index.js +++ b/src/keychain/index.js @@ -101,7 +101,8 @@ class Keychain { * Creates a new instance of a key chain. * * @param {DS} store - where the key are. - * @param {object} options - ??? + * @param {object} options + * @class */ constructor (store, options) { if (!store) { diff --git a/src/peer-routing.js b/src/peer-routing.js index 841a3279c3..88a230196c 100644 --- a/src/peer-routing.js +++ b/src/peer-routing.js @@ -1,9 +1,10 @@ 'use strict' -const errCode = require('err-code') const debug = require('debug') -const log = debug('libp2p:peer-routing') -log.error = debug('libp2p:peer-routing:error') +const log = Object.assign(debug('libp2p:peer-routing'), { + error: debug('libp2p:peer-routing:err') +}) +const errCode = require('err-code') const all = require('it-all') const pAny = require('p-any') @@ -69,7 +70,6 @@ class PeerRouting { clearDelayedInterval(this._timeoutId) } -<<<<<<< HEAD /** * 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 (!result || Object.keys(result).length === 0) { 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 diff --git a/src/peer-store/address-book.js b/src/peer-store/address-book.js index bbfc30c8b9..5545997322 100644 --- a/src/peer-store/address-book.js +++ b/src/peer-store/address-book.js @@ -1,9 +1,10 @@ 'use strict' -const errcode = require('err-code') const debug = require('debug') -const log = debug('libp2p:peer-store:address-book') -log.error = debug('libp2p:peer-store:address-book:error') +const log = Object.assign(debug('libp2p:peer-store:address-book'), { + error: debug('libp2p:peer-store:address-book:err') +}) +const errcode = require('err-code') const multiaddr = require('multiaddr') const PeerId = require('peer-id') @@ -18,6 +19,7 @@ const Envelope = require('../record/envelope') /** * @typedef {import('multiaddr')} Multiaddr + * @typedef {import('./')} PeerStore */ /** @@ -75,7 +77,7 @@ class AddressBook extends Book { /** * Map known peers to their known Address Entries. * - * @type {Map} + * @type {Map} */ this.data = new Map() } @@ -110,7 +112,7 @@ class AddressBook extends Book { const peerId = peerRecord.peerId const id = peerId.toB58String() - const entry = this.data.get(id) || {} + const entry = this.data.get(id) || { record: undefined } const storedRecord = entry.record // 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. * * @param {PeerId} peerId - * @returns {Promise} + * @returns {Promise|undefined} */ getPeerRecord (peerId) { const raw = this.getRawEnvelope(peerId) diff --git a/src/peer-store/book.js b/src/peer-store/book.js index cbfafdd6b9..447483d9e2 100644 --- a/src/peer-store/book.js +++ b/src/peer-store/book.js @@ -9,12 +9,17 @@ const { const passthrough = data => data +/** + * @typedef {import('./')} PeerStore + */ + +/** + * @template T + */ class Book { /** * The Book is the skeleton for the PeerStore books. * - * @template T - * * @class * @param {Object} properties * @param {PeerStore} properties.peerStore - PeerStore instance. @@ -31,7 +36,7 @@ class Book { /** * Map known peers to their data. * - * @type {Map} */ this.data = new Map() } @@ -94,6 +99,7 @@ class Book { const rec = this.data.get(peerId.toB58String()) + // @ts-ignore return rec ? [...rec] : undefined } diff --git a/src/peer-store/index.js b/src/peer-store/index.js index 3713d7d4d0..07762b8cbc 100644 --- a/src/peer-store/index.js +++ b/src/peer-store/index.js @@ -1,9 +1,6 @@ 'use strict' 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 PeerId = require('peer-id') @@ -14,7 +11,7 @@ const MetadataBook = require('./metadata-book') const ProtoBook = require('./proto-book') const { - ERR_INVALID_PARAMETERS + codes: { ERR_INVALID_PARAMETERS } } = require('../errors') /** @@ -127,7 +124,7 @@ class PeerStore extends EventEmitter { * Get the stored information of a given peer. * * @param {PeerId} peerId - * @returns {Peer} + * @returns {Peer|undefined} */ get (peerId) { if (!PeerId.isPeerId(peerId)) { diff --git a/src/peer-store/key-book.js b/src/peer-store/key-book.js index 6a045ad58f..1c22db63ef 100644 --- a/src/peer-store/key-book.js +++ b/src/peer-store/key-book.js @@ -1,9 +1,10 @@ 'use strict' -const errcode = require('err-code') const debug = require('debug') -const log = debug('libp2p:peer-store:key-book') -log.error = debug('libp2p:peer-store:key-book:error') +const log = Object.assign(debug('libp2p:peer-store:key-book'), { + error: debug('libp2p:peer-store:key-book:err') +}) +const errcode = require('err-code') const PeerId = require('peer-id') @@ -13,6 +14,10 @@ const { codes: { ERR_INVALID_PARAMETERS } } = require('../errors') +/** + * @typedef {import('./')} PeerStore + */ + /** * @extends {Book} */ diff --git a/src/peer-store/metadata-book.js b/src/peer-store/metadata-book.js index 796c9ee8f9..7d24312cf8 100644 --- a/src/peer-store/metadata-book.js +++ b/src/peer-store/metadata-book.js @@ -1,9 +1,10 @@ 'use strict' -const errcode = require('err-code') const debug = require('debug') -const log = debug('libp2p:peer-store:proto-book') -log.error = debug('libp2p:peer-store:proto-book:error') +const log = Object.assign(debug('libp2p:peer-store:proto-book'), { + error: debug('libp2p:peer-store:proto-book:err') +}) +const errcode = require('err-code') const uint8ArrayEquals = require('uint8arrays/equals') const PeerId = require('peer-id') @@ -14,6 +15,10 @@ const { codes: { ERR_INVALID_PARAMETERS } } = require('../errors') +/** + * @typedef {import('./')} PeerStore + */ + /** * @extends {Book} * diff --git a/src/peer-store/persistent/index.js b/src/peer-store/persistent/index.js index f23c23e193..ceb77a650c 100644 --- a/src/peer-store/persistent/index.js +++ b/src/peer-store/persistent/index.js @@ -1,9 +1,9 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:persistent-peer-store') -log.error = debug('libp2p:persistent-peer-store:error') - +const log = Object.assign(debug('libp2p:persistent-peer-store'), { + error: debug('libp2p:persistent-peer-store:err') +}) const { Key } = require('interface-datastore') const multiaddr = require('multiaddr') const PeerId = require('peer-id') @@ -346,6 +346,7 @@ class PersistentPeerStore extends PeerStore { case 'addrs': decoded = Addresses.decode(value) + // @ts-ignore this.addressBook._setData( peerId, { @@ -363,6 +364,7 @@ class PersistentPeerStore extends PeerStore { case 'keys': decoded = await PeerId.createFromPubKey(value) + // @ts-ignore this.keyBook._setData( decoded, decoded, @@ -378,6 +380,7 @@ class PersistentPeerStore extends PeerStore { case 'protos': decoded = Protocols.decode(value) + // @ts-ignore this.protoBook._setData( peerId, new Set(decoded.protocols), diff --git a/src/peer-store/proto-book.js b/src/peer-store/proto-book.js index 60b9c503f9..18529d7369 100644 --- a/src/peer-store/proto-book.js +++ b/src/peer-store/proto-book.js @@ -1,10 +1,10 @@ 'use strict' -const errcode = require('err-code') const debug = require('debug') -const log = debug('libp2p:peer-store:proto-book') -log.error = debug('libp2p:peer-store:proto-book:error') - +const log = Object.assign(debug('libp2p:peer-store:proto-book'), { + error: debug('libp2p:peer-store:proto-book:err') +}) +const errcode = require('err-code') const PeerId = require('peer-id') const Book = require('./book') @@ -13,6 +13,10 @@ const { codes: { ERR_INVALID_PARAMETERS } } = require('../errors') +/** + * @typedef {import('./')} PeerStore + */ + /** * @extends {Book} * @@ -79,6 +83,7 @@ class ProtoBook extends Book { return this } + // @ts-ignore this._setData(peerId, newSet) log(`stored provided protocols for ${id}`) @@ -114,6 +119,7 @@ class ProtoBook extends Book { return this } + // @ts-ignore this._setData(peerId, newSet) log(`added provided protocols for ${id}`) @@ -152,6 +158,7 @@ class ProtoBook extends Book { return this } + // @ts-ignore this._setData(peerId, newSet) log(`removed provided protocols for ${id}`) } diff --git a/src/ping/index.js b/src/ping/index.js index 5ad54021cf..a242f9fb1a 100644 --- a/src/ping/index.js +++ b/src/ping/index.js @@ -1,14 +1,16 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p-ping') -log.error = debug('libp2p-ping:error') +const log = Object.assign(debug('libp2p:ping'), { + error: debug('libp2p:ping:err') +}) const errCode = require('err-code') const crypto = require('libp2p-crypto') -const pipe = require('it-pipe') +const { pipe } = require('it-pipe') const { toBuffer } = require('it-buffer') const { collect, take } = require('streaming-iterables') +const equals = require('uint8arrays/equals') const { PROTOCOL, PING_LENGTH } = require('./constants') @@ -26,11 +28,12 @@ const { PROTOCOL, PING_LENGTH } = require('./constants') * @returns {Promise} */ async function ping (node, peer) { + // @ts-ignore log('dialing %s to %s', PROTOCOL, peer.toB58String ? peer.toB58String() : peer) const { stream } = await node.dialProtocol(peer, PROTOCOL) - const start = new Date() + const start = new Date().getTime() const data = crypto.randomBytes(PING_LENGTH) const [result] = await pipe( @@ -42,7 +45,7 @@ async function ping (node, peer) { ) const end = Date.now() - if (!data.equals(result)) { + if (!equals(data, result)) { throw errCode(new Error('Received wrong ping ack'), 'ERR_WRONG_PING_ACK') } diff --git a/src/pnet/crypto.js b/src/pnet/crypto.js index ae824bfcfb..9cfcbc8e6f 100644 --- a/src/pnet/crypto.js +++ b/src/pnet/crypto.js @@ -1,16 +1,17 @@ 'use strict' 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 xsalsa20 = require('xsalsa20') const KEY_LENGTH = require('./key-generator').KEY_LENGTH const uint8ArrayFromString = require('uint8arrays/from-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 * diff --git a/src/pnet/index.js b/src/pnet/index.js index d2b97b2cb7..74c99947e0 100644 --- a/src/pnet/index.js +++ b/src/pnet/index.js @@ -1,12 +1,16 @@ '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 duplexPair = require('it-pair/duplex') const crypto = require('libp2p-crypto') const Errors = require('./errors') const { - ERR_INVALID_PARAMETERS + codes: { ERR_INVALID_PARAMETERS } } = require('../errors') const { createBoxStream, @@ -15,9 +19,6 @@ const { } = require('./crypto') const handshake = require('it-handshake') 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 @@ -44,7 +45,7 @@ class Protector { * created with. * * @param {Connection} connection - The connection to protect - * @returns {DuplexIterableStream} A protected duplex iterable + * @returns {Promise} A protected duplex iterable */ async protect (connection) { if (!connection) { diff --git a/src/pnet/key-generator.js b/src/pnet/key-generator.js index b3676dcccf..d88f23d83c 100644 --- a/src/pnet/key-generator.js +++ b/src/pnet/key-generator.js @@ -22,6 +22,8 @@ module.exports = generate module.exports.NONCE_LENGTH = 24 module.exports.KEY_LENGTH = KEY_LENGTH +// @ts-ignore if (require.main === module) { + // @ts-ignore generate(process.stdout) } diff --git a/src/pubsub-adapter.js b/src/pubsub-adapter.js index 4f2134fe6c..4c8aed8f2a 100644 --- a/src/pubsub-adapter.js +++ b/src/pubsub-adapter.js @@ -2,6 +2,7 @@ /** * @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. @@ -12,7 +13,7 @@ module.exports = (PubsubRouter, libp2p, options) => { * * @override * @param {string} topic - * @param {function(msg: InMessage)} [handler] + * @param {(msg: InMessage) => void} [handler] * @returns {void} */ subscribe (topic, handler) { @@ -26,7 +27,7 @@ module.exports = (PubsubRouter, libp2p, options) => { * * @override * @param {string} topic - * @param {function(msg: InMessage)} [handler] + * @param {(msg: InMessage) => void} [handler] * @returns {void} */ unsubscribe (topic, handler) { diff --git a/src/record/envelope/index.js b/src/record/envelope/index.js index cee2e26b96..88a702afc5 100644 --- a/src/record/envelope/index.js +++ b/src/record/envelope/index.js @@ -1,8 +1,5 @@ 'use strict' -const debug = require('debug') -const log = debug('libp2p:envelope') -log.error = debug('libp2p:envelope:error') const errCode = require('err-code') const uint8arraysConcat = require('uint8arrays/concat') const uint8arraysFromString = require('uint8arrays/from-string') @@ -15,7 +12,7 @@ const { codes } = require('../../errors') const Protobuf = require('./envelope.proto') /** - * @typedef {import('peer-id')} PeerId + * @typedef {import('libp2p-interfaces/src/record')} Record */ class Envelope { @@ -145,7 +142,7 @@ Envelope.createFromProtobuf = async (data) => { * @async * @param {Record} record * @param {PeerId} peerId - * @returns {Envelope} + * @returns {Promise} */ Envelope.seal = async (record, peerId) => { const domain = record.domain @@ -169,7 +166,7 @@ Envelope.seal = async (record, peerId) => { * * @param {Uint8Array} data * @param {string} domain - * @returns {Envelope} + * @returns {Promise} */ Envelope.openAndCertify = async (data, domain) => { const envelope = await Envelope.createFromProtobuf(data) diff --git a/src/registrar.js b/src/registrar.js index 4917aeb5b8..70998c5d1c 100644 --- a/src/registrar.js +++ b/src/registrar.js @@ -1,12 +1,13 @@ 'use strict' const debug = require('debug') +const log = Object.assign(debug('libp2p:peer-store'), { + error: debug('libp2p:peer-store:err') +}) const errcode = require('err-code') -const log = debug('libp2p:peer-store') -log.error = debug('libp2p:peer-store:error') const { - ERR_INVALID_PARAMETERS + codes: { ERR_INVALID_PARAMETERS } } = require('./errors') const Topology = require('libp2p-interfaces/src/topology') @@ -73,11 +74,12 @@ class Registrar { */ register (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) } // 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) diff --git a/src/transport-manager.js b/src/transport-manager.js index 06ab69b74b..d9aef5335c 100644 --- a/src/transport-manager.js +++ b/src/transport-manager.js @@ -1,11 +1,13 @@ 'use strict' +const debug = require('debug') +const log = Object.assign(debug('libp2p:transports'), { + error: debug('libp2p:transports:err') +}) + const pSettle = require('p-settle') const { codes } = require('./errors') 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') @@ -18,7 +20,7 @@ const { updateSelfPeerRecord } = require('./record/utils') * @property {import('./upgrader')} upgrader * * @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 { @@ -126,7 +128,7 @@ class TransportManager { /** * Returns all the transports instances. * - * @returns {Iterator} + * @returns {IterableIterator} */ getTransports () { return this._transports.values() @@ -166,7 +168,7 @@ class TransportManager { // For each supported multiaddr, create a listener for (const addr of supportedAddrs) { 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) // Track listen/close events diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000000..7f0ad3680c --- /dev/null +++ b/src/types.ts @@ -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 +} diff --git a/src/upgrader.js b/src/upgrader.js index 0a422b2e82..ca798deaa7 100644 --- a/src/upgrader.js +++ b/src/upgrader.js @@ -1,20 +1,22 @@ 'use strict' const debug = require('debug') -const log = debug('libp2p:upgrader') -log.error = debug('libp2p:upgrader:error') +const log = Object.assign(debug('libp2p:upgrader'), { + error: debug('libp2p:upgrader:err') +}) +const errCode = require('err-code') const Multistream = require('multistream-select') const { Connection } = require('libp2p-interfaces/src/connection') const ConnectionStatus = require('libp2p-interfaces/src/connection/status') const PeerId = require('peer-id') const pipe = require('it-pipe') -const errCode = require('err-code') const mutableProxy = require('mutable-proxy') const { codes } = require('./errors') /** * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection + * @typedef {import('multiaddr')} Multiaddr */ /** @@ -36,11 +38,11 @@ class Upgrader { /** * @param {object} options * @param {PeerId} options.localPeer - * @param {Metrics} options.metrics + * @param {import('./metrics')} [options.metrics] * @param {Map} options.cryptos * @param {Map} options.muxers - * @param {function(Connection)} options.onConnection - Called when a connection is upgraded - * @param {function(Connection)} options.onConnectionEnd + * @param {(Connection) => void} options.onConnection - Called when a connection is upgraded + * @param {(Connection) => void} options.onConnectionEnd */ constructor ({ localPeer, @@ -78,7 +80,7 @@ class Upgrader { if (this.metrics) { ({ 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 }) maConn = this.metrics.trackStream({ stream: maConn, remotePeer: proxyPeer }) } diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..5b9a618c43 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "./node_modules/aegir/src/config/tsconfig.aegir.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": [ + "src" + ] +} \ No newline at end of file