Merge remote-tracking branch 'upstream/chore/add-typedefs' into chore/add-typedefs-peerstore-book-template

This commit is contained in:
Irakli Gozalishvili 2020-12-09 23:56:20 -08:00
commit d1caeb3882
No known key found for this signature in database
GPG Key ID: C80F9B292FB470DE
14 changed files with 101 additions and 49 deletions

View File

@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- run: yarn - run: yarn
- run: yarn lint - run: yarn lint
# - uses: gozala/typescript-error-reporter-action@v1.0.4 - uses: gozala/typescript-error-reporter-action@v1.0.8
- run: yarn build - run: yarn build
- run: yarn aegir dep-check - run: yarn aegir dep-check
- uses: ipfs/aegir/actions/bundle-size@master - uses: ipfs/aegir/actions/bundle-size@master

View File

@ -18,15 +18,18 @@ const { stop } = require('./stop')
const multicodec = require('./../multicodec') const multicodec = require('./../multicodec')
/** /**
* @typedef {import('../../types').CircuitRequest} Request
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('./stream-handler')<Request>} StreamHandlerT
* @typedef {import('../transport')} Transport
*/ */
/** /**
* @typedef {Object} HopRequest * @typedef {Object} HopRequest
* @property {Connection} connection * @property {Connection} connection
* @property {any} request * @property {Request} request
* @property {any} streamHandler * @property {StreamHandlerT} streamHandler
* @property {import('../transport')} circuit * @property {Transport} circuit
*/ */
/** /**
@ -110,7 +113,7 @@ async function handleHop ({
* *
* @param {object} options * @param {object} options
* @param {Connection} options.connection - Connection to the relay * @param {Connection} options.connection - Connection to the relay
* @param {CircuitPB} options.request * @param {Request} options.request
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
async function hop ({ async function hop ({
@ -168,8 +171,8 @@ async function canHop ({
* *
* @param {Object} options * @param {Object} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {StreamHandler} options.streamHandler * @param {StreamHandlerT} options.streamHandler
* @param {import('../transport')} options.circuit * @param {Transport} options.circuit
* @private * @private
*/ */
function handleCanHop ({ function handleCanHop ({

View File

@ -13,16 +13,18 @@ const { validateAddrs } = require('./utils')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
* @typedef {import('../../types').CircuitRequest} Request
* @typedef {import('./stream-handler')<Request>} StreamHandlerT
*/ */
/** /**
* Handles incoming STOP requests * Handles incoming STOP requests
* *
* @private * @private
* @param {object} options * @param {Object} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {CircuitPB} options.request - The CircuitRelay protobuf request (unencoded) * @param {Request} options.request - The CircuitRelay protobuf request (unencoded)
* @param {StreamHandler} options.streamHandler * @param {StreamHandlerT} options.streamHandler
* @returns {Promise<MuxedStream>|void} Resolves a duplex iterable * @returns {Promise<MuxedStream>|void} Resolves a duplex iterable
*/ */
module.exports.handleStop = function handleStop ({ module.exports.handleStop = function handleStop ({
@ -50,9 +52,9 @@ module.exports.handleStop = function handleStop ({
* Creates a STOP request * Creates a STOP request
* *
* @private * @private
* @param {object} options * @param {Object} options
* @param {Connection} options.connection * @param {Connection} options.connection
* @param {CircuitPB} options.request - The CircuitRelay protobuf request (unencoded) * @param {Request} options.request - The CircuitRelay protobuf request (unencoded)
* @returns {Promise<MuxedStream|void>} Resolves a duplex iterable * @returns {Promise<MuxedStream|void>} Resolves a duplex iterable
*/ */
module.exports.stop = async function stop ({ module.exports.stop = async function stop ({

View File

@ -9,13 +9,20 @@ 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')
/**
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
*/
/**
* @template T
*/
class StreamHandler { class StreamHandler {
/** /**
* Create a stream handler for connection * Create a stream handler for connection
* *
* @class * @class
* @param {object} options * @param {object} options
* @param {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} options.stream - A duplex iterable * @param {MuxedStream} options.stream - A duplex iterable
* @param {number} [options.maxLength = 4096] - max bytes length of message * @param {number} [options.maxLength = 4096] - max bytes length of message
*/ */
constructor ({ stream, maxLength = 4096 }) { constructor ({ stream, maxLength = 4096 }) {
@ -29,7 +36,7 @@ class StreamHandler {
* Read and decode message * Read and decode message
* *
* @async * @async
* @returns {Promise<CircuitPB>} * @returns {Promise<T|undefined>}
*/ */
async read () { async read () {
const msg = await this.decoder.next() const msg = await this.decoder.next()
@ -48,6 +55,7 @@ class StreamHandler {
* Encode and write array of buffers * Encode and write array of buffers
* *
* @param {CircuitPB} msg - An unencoded CircuitRelay protobuf message * @param {CircuitPB} msg - An unencoded CircuitRelay protobuf message
* @returns {void}
*/ */
write (msg) { write (msg) {
log('write message type %s', msg.type) log('write message type %s', msg.type)

View File

@ -8,7 +8,6 @@ const log = Object.assign(debug('libp2p:circuit'), {
const mafmt = require('mafmt') const mafmt = require('mafmt')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
const PeerId = require('peer-id') const PeerId = require('peer-id')
const withIs = require('class-is')
const { CircuitRelay: CircuitPB } = require('./protocol') const { CircuitRelay: CircuitPB } = require('./protocol')
const toConnection = require('libp2p-utils/src/stream-to-ma-conn') const toConnection = require('libp2p-utils/src/stream-to-ma-conn')
@ -19,9 +18,12 @@ const { handleCanHop, handleHop, hop } = require('./circuit/hop')
const { handleStop } = require('./circuit/stop') const { handleStop } = require('./circuit/stop')
const StreamHandler = require('./circuit/stream-handler') const StreamHandler = require('./circuit/stream-handler')
const transportSymbol = Symbol.for('@libp2p/js-libp2p-circuit/circuit')
/** /**
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
*/ */
class Circuit { class Circuit {
@ -45,6 +47,11 @@ class Circuit {
this._registrar.handle(multicodec, this._onProtocol.bind(this)) this._registrar.handle(multicodec, this._onProtocol.bind(this))
} }
/**
* @param {Object} props
* @param {Connection} props.connection
* @param {MuxedStream} props.stream
*/
async _onProtocol ({ connection, stream }) { async _onProtocol ({ connection, stream }) {
const streamHandler = new StreamHandler({ stream }) const streamHandler = new StreamHandler({ stream })
const request = await streamHandler.read() const request = await streamHandler.read()
@ -190,9 +197,20 @@ class Circuit {
return mafmt.Circuit.matches(ma) return mafmt.Circuit.matches(ma)
}) })
} }
get [Symbol.toStringTag] () {
return 'Circuit'
}
/**
* Checks if the given value is a Transport instance.
*
* @param {any} other
* @returns {other is Transport}
*/
static isTransport (other) {
return Boolean(other && other[transportSymbol])
}
} }
/** module.exports = Circuit
* @type {Circuit}
*/
module.exports = withIs(Circuit, { className: 'Circuit', symbolName: '@libp2p/js-libp2p-circuit/circuit' })

View File

@ -52,7 +52,6 @@ const defaultOptions = {
*/ */
/** /**
* @extends EventEmitter
* *
* @fires ConnectionManager#peer:connect Emitted when a new peer is connected. * @fires ConnectionManager#peer:connect Emitted when a new peer is connected.
* @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected. * @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected.

View File

@ -13,8 +13,6 @@ const debug = require('debug')('latency-monitor:VisibilityChangeEmitter')
/** /**
* Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter. * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.
* *
* @extends {EventEmitter}
*
* Warning: This does not work on all browsers, but should work on all modern browsers * Warning: This does not work on all browsers, but should work on all modern browsers
* *
* @example * @example

View File

@ -70,14 +70,14 @@ class ContentRouting {
* 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) {
if (!this.routers.length) { if (!this.routers.length) {
throw errCode(new Error('No content routers available'), 'NO_ROUTERS_AVAILABLE') throw errCode(new Error('No content routers available'), 'NO_ROUTERS_AVAILABLE')
} }
return Promise.all(this.routers.map((router) => router.provide(key))) await Promise.all(this.routers.map((router) => router.provide(key)))
} }
/** /**
@ -89,7 +89,7 @@ class ContentRouting {
* @param {number} [options.minPeers] - minimum number of peers required to successfully put * @param {number} [options.minPeers] - minimum number of peers required to successfully put
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async put (key, value, options) { // eslint-disable-line require-await put (key, value, options) {
if (!this.libp2p.isStarted() || !this.dht.isStarted) { if (!this.libp2p.isStarted() || !this.dht.isStarted) {
throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)
} }
@ -106,7 +106,7 @@ class ContentRouting {
* @param {number} [options.timeout] - optional timeout (default: 60000) * @param {number} [options.timeout] - optional timeout (default: 60000)
* @returns {Promise<GetData>} * @returns {Promise<GetData>}
*/ */
async get (key, options) { // eslint-disable-line require-await get (key, options) {
if (!this.libp2p.isStarted() || !this.dht.isStarted) { if (!this.libp2p.isStarted() || !this.dht.isStarted) {
throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)
} }

View File

@ -34,12 +34,14 @@ const {
* @property {PeerStore} peerStore * @property {PeerStore} peerStore
* @property {TransportManager} transportManager * @property {TransportManager} transportManager
* *
* @typedef {(addr:Multiaddr) => Promise<string[]>} Resolver
*
* @typedef {Object} DialerOptions * @typedef {Object} DialerOptions
* @param {(addresses: Address[]) => Address[]} [options.addressSorter = publicAddressesFirst] - Sort the known addresses of a peer before trying to dial. * @property {(addresses: Address[]) => Address[]} [options.addressSorter = publicAddressesFirst] - Sort the known addresses of a peer before trying to dial.
* @property {number} [concurrency = MAX_PARALLEL_DIALS] - Number of max concurrent dials. * @property {number} [concurrency = MAX_PARALLEL_DIALS] - Number of max concurrent dials.
* @property {number} [perPeerLimit = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer. * @property {number} [perPeerLimit = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer.
* @property {number} [timeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take. * @property {number} [timeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take.
* @property {Object} [resolvers = {}] - multiaddr resolvers to use when dialing * @property {Record<string, Resolver>} [resolvers = {}] - multiaddr resolvers to use when dialing
* *
* @typedef DialTarget * @typedef DialTarget
* @property {string} id * @property {string} id
@ -240,13 +242,13 @@ class Dialer {
return this._resolve(nm) return this._resolve(nm)
})) }))
return recursiveMultiaddrs.flat() const addrs = recursiveMultiaddrs.flat()
.reduce((/** @type {Multiaddr[]} */ array, /** @type {Multiaddr} */ newM) => { return addrs.reduce((array, newM) => {
if (!array.find(m => m.equals(newM))) { if (!array.find(m => m.equals(newM))) {
array.push(newM) array.push(newM)
} }
return array return array
}, []) // Unique addresses }, /** @type {Multiaddr[]} */([]))
} }
/** /**

View File

@ -37,6 +37,9 @@ const IDENTIFY_PROTOCOLS = IdentifyService.multicodecs
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
* @typedef {import('libp2p-interfaces/src/transport/types').TransportFactory} TransportFactory
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxerFactory} MuxerFactory
* @typedef {import('libp2p-interfaces/src/crypto/types').Crypto} Crypto
* @typedef {import('libp2p-interfaces/src/pubsub')} Pubsub * @typedef {import('libp2p-interfaces/src/pubsub')} Pubsub
*/ */
@ -54,14 +57,19 @@ const IDENTIFY_PROTOCOLS = IdentifyService.multicodecs
* @property {import('./circuit').AutoRelayOptions} autoRelay * @property {import('./circuit').AutoRelayOptions} autoRelay
* *
* @typedef {Object} Libp2pConfig * @typedef {Object} Libp2pConfig
* @property {any} [dht] dht module options * @property {Object} [dht] dht module options
* @property {PeerDiscoveryOptions} [peerDiscovery] * @property {PeerDiscoveryOptions} [peerDiscovery]
* @property {Pubsub} [pubsub] pubsub module options * @property {Pubsub} [pubsub] pubsub module options
* @property {RelayOptions} [relay] * @property {RelayOptions} [relay]
* @property {Object} [transport] transport options indexed by transport key * @property {Record<string, Object>} [transport] transport options indexed by transport key
*
* @typedef {Object} Libp2pModules
* @property {TransportFactory[]} transport
* @property {MuxerFactory[]} streamMuxer
* @property {Crypto[]} connEncryption
* *
* @typedef {Object} Libp2pOptions * @typedef {Object} Libp2pOptions
* @property {Object[]} modules libp2p modules to use * @property {Libp2pModules} modules libp2p modules to use
* @property {import('./address-manager').AddressManagerOptions} [addresses] * @property {import('./address-manager').AddressManagerOptions} [addresses]
* @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager] * @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager]
* @property {import('./dialer').DialerOptions} [dialer] * @property {import('./dialer').DialerOptions} [dialer]
@ -133,7 +141,6 @@ 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,
@ -342,6 +349,10 @@ class Libp2p extends EventEmitter {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async loadKeychain () { async loadKeychain () {
if (!this.keychain) {
return
}
try { try {
await this.keychain.findKeyByName('self') await this.keychain.findKeyByName('self')
} catch (err) { } catch (err) {
@ -373,7 +384,7 @@ class Libp2p extends EventEmitter {
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
dial (peer, options) { dial (peer, options) {
return this.dialProtocol(peer, undefined, options) return this.dialProtocol(peer, [], options)
} }
/** /**
@ -383,7 +394,7 @@ 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 {undefined|string[]|string} protocols * @param {null|string[]|string} protocols
* @param {object} [options] * @param {object} [options]
* @param {AbortSignal} [options.signal] * @param {AbortSignal} [options.signal]
* @returns {Promise<Connection|*>} * @returns {Promise<Connection|*>}
@ -399,7 +410,7 @@ class Libp2p extends EventEmitter {
} }
// If a protocol was provided, create a new stream // If a protocol was provided, create a new stream
if (protocols) { if (protocols && protocols.length) {
return connection.newStream(protocols) return connection.newStream(protocols)
} }

View File

@ -22,7 +22,7 @@ class CMS {
/** /**
* Creates a new instance with a keychain * Creates a new instance with a keychain
* *
* @param {Keychain} keychain - the available keys * @param {import('./index')} keychain - the available keys
*/ */
constructor (keychain) { constructor (keychain) {
if (!keychain) { if (!keychain) {
@ -39,7 +39,7 @@ class CMS {
* *
* @param {string} name - The local key name. * @param {string} name - The local key name.
* @param {Uint8Array} plain - The data to encrypt. * @param {Uint8Array} plain - The data to encrypt.
* @returns {undefined} * @returns {Promise<Uint8Array>}
*/ */
async encrypt (name, plain) { async encrypt (name, plain) {
if (!(plain instanceof Uint8Array)) { if (!(plain instanceof Uint8Array)) {
@ -69,7 +69,7 @@ class CMS {
* exists, an Error is returned with the property 'missingKeys'. It is array of key ids. * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.
* *
* @param {Uint8Array} cmsData - The CMS encrypted data to decrypt. * @param {Uint8Array} cmsData - The CMS encrypted data to decrypt.
* @returns {undefined} * @returns {Promise<Uint8Array>}
*/ */
async decrypt (cmsData) { async decrypt (cmsData) {
if (!(cmsData instanceof Uint8Array)) { if (!(cmsData instanceof Uint8Array)) {

View File

@ -207,7 +207,7 @@ class AddressBook extends Book {
log(`stored provided multiaddrs for ${id}`) log(`stored provided multiaddrs for ${id}`)
// Notify the existance of a new peer // Notify the existance of a new peer
if (!(entry && entry.addresses)) { if (!entry) {
this._ps.emit('peer', peerId) this._ps.emit('peer', peerId)
} }

View File

@ -33,7 +33,7 @@ async function ping (node, peer) {
const { stream } = await node.dialProtocol(peer, PROTOCOL) const { stream } = await node.dialProtocol(peer, PROTOCOL)
const start = new Date().getTime() const start = Date.now()
const data = crypto.randomBytes(PING_LENGTH) const data = crypto.randomBytes(PING_LENGTH)
const [result] = await pipe( const [result] = await pipe(

View File

@ -43,6 +43,17 @@ export type CAN_HOP = 4;
export type CircuitType = HOP | STOP | STATUS | CAN_HOP export type CircuitType = HOP | STOP | STATUS | CAN_HOP
export type CircuitPeer = {
id: Uint8Array
addrs: Uint8Array[]
}
export type CircuitRequest = {
type: CircuitType
dstPeer: CircuitPeer
srcPeer: CircuitPeer
}
export type CircuitMessageProto = { export type CircuitMessageProto = {
encode(value: any): Uint8Array encode(value: any): Uint8Array
decode(bytes: Uint8Array): any decode(bytes: Uint8Array): any