Skip to content

Commit

Permalink
chore: config typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
vasco-santos committed Mar 26, 2021
1 parent b894452 commit 141f2b3
Show file tree
Hide file tree
Showing 12 changed files with 141 additions and 77 deletions.
2 changes: 1 addition & 1 deletion doc/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ const TCP = require('libp2p-tcp')
const MPLEX = require('libp2p-mplex')
const { NOISE } = require('libp2p-noise')

const { FaultTolerance } = require('libp2p/src/transport-manager')}
const { FaultTolerance } = require('libp2p/src/transport-manager')

const node = await Libp2p.create({
modules: {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"src"
],
"scripts": {
"prepare": "aegir build --no-bundle",
"lint": "aegir lint",
"build": "aegir build",
"test": "npm run test:node && npm run test:browser",
Expand Down Expand Up @@ -81,7 +82,7 @@
"it-protocol-buffers": "^0.2.0",
"it-take": "1.0.0",
"libp2p-crypto": "^0.19.0",
"libp2p-interfaces": "^0.8.1",
"libp2p-interfaces": "libp2p/js-libp2p-interfaces#chore/update-types",
"libp2p-utils": "^0.2.2",
"mafmt": "^8.0.0",
"merge-options": "^3.0.4",
Expand Down
22 changes: 11 additions & 11 deletions src/dialer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ const {
*
* @typedef {Object} DialerOptions
* @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} [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} [maxParallelDials = MAX_PARALLEL_DIALS] - Number of max concurrent dials.
* @property {number} [maxDialsPerPeer = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer.
* @property {number} [dialTimeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take.
* @property {Record<string, Resolver>} [resolvers = {}] - multiaddr resolvers to use when dialing
*
* @typedef DialTarget
Expand All @@ -63,18 +63,18 @@ class Dialer {
transportManager,
peerStore,
addressSorter = publicAddressesFirst,
concurrency = MAX_PARALLEL_DIALS,
timeout = DIAL_TIMEOUT,
perPeerLimit = MAX_PER_PEER_DIALS,
maxParallelDials = MAX_PARALLEL_DIALS,
dialTimeout = DIAL_TIMEOUT,
maxDialsPerPeer = MAX_PER_PEER_DIALS,
resolvers = {}
}) {
this.transportManager = transportManager
this.peerStore = peerStore
this.addressSorter = addressSorter
this.concurrency = concurrency
this.timeout = timeout
this.perPeerLimit = perPeerLimit
this.tokens = [...new Array(concurrency)].map((_, index) => index)
this.maxParallelDials = maxParallelDials
this.timeout = dialTimeout
this.maxDialsPerPeer = maxDialsPerPeer
this.tokens = [...new Array(maxParallelDials)].map((_, index) => index)
this._pendingDials = new Map()

for (const [key, value] of Object.entries(resolvers)) {
Expand Down Expand Up @@ -208,7 +208,7 @@ class Dialer {
}

getTokens (num) {
const total = Math.min(num, this.perPeerLimit, this.tokens.length)
const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)
const tokens = this.tokens.splice(0, total)
log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)
return tokens
Expand Down
5 changes: 5 additions & 0 deletions src/identify/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ const { codes } = require('../errors')
* @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
*/

/**
* @typedef {Object} HostProperties
* @property {string} agentVersion
*/

class IdentifyService {
/**
* @class
Expand Down
61 changes: 45 additions & 16 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,41 +43,75 @@ const { updateSelfPeerRecord } = require('./record/utils')
* @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/content-routing/types').ContentRouting} ContentRoutingFactory
* @typedef {import('libp2p-interfaces/src/peer-discovery/types').PeerDiscovery} PeerDiscoveryFactory
* @typedef {import('libp2p-interfaces/src/peer-routing/types').PeerRouting} PeerRoutingFactory
* @typedef {import('libp2p-interfaces/src/crypto/types').Crypto} Crypto
* @typedef {import('libp2p-interfaces/src/pubsub')} Pubsub
* @typedef {import('libp2p-interfaces/src/pubsub').PubsubOptions} PubsubOptions
* @typedef {import('interface-datastore').Datastore} Datastore
*/

/**
* @typedef {Object} RandomWalkOptions
* @property {boolean} [enabled = false]
* @property {number} [queriesPerPeriod = 1]
* @property {number} [interval = 300e3]
* @property {number} [timeout = 10e3]
*
* @typedef {Object} DhtOptions
* @property {boolean} [enabled = false]
* @property {number} [kBucketSize = 20]
* @property {RandomWalkOptions} [randomWalk]
*
* @typedef {Object} KeychainOptions
* @property {Datastore} [datastore]
*
* @typedef {Object} PeerStoreOptions
* @property {boolean} persistence
*
* @typedef {Object} RelayOptions
* @typedef {Object} PubsubLocalOptions
* @property {boolean} enabled
*
* @typedef {Object} MetricsOptions
* @property {boolean} enabled
* @property {import('./circuit').RelayAdvertiseOptions} advertise
* @property {import('./circuit').HopOptions} hop
* @property {import('./circuit').AutoRelayOptions} autoRelay
*
* @typedef {Object} RelayOptions
* @property {boolean} [enabled = true]
* @property {import('./circuit').RelayAdvertiseOptions} [advertise]
* @property {import('./circuit').HopOptions} [hop]
* @property {import('./circuit').AutoRelayOptions} [autoRelay]
*
* @typedef {Object} Libp2pConfig
* @property {Object} [dht] dht module options
* @property {Object} [peerDiscovery]
* @property {Pubsub} [pubsub] pubsub module options
* @property {DhtOptions} [dht] dht module options
* @property {import('./nat-manager').NatManagerOptions} [nat]
* @property {Record<string, Object|boolean>} [peerDiscovery]
* @property {PubsubLocalOptions & PubsubOptions} [pubsub] pubsub module options
* @property {RelayOptions} [relay]
* @property {Record<string, Object>} [transport] transport options indexed by transport key
*
* @typedef {Object} Libp2pModules
* @property {TransportFactory[]} transport
* @property {MuxerFactory[]} streamMuxer
* @property {Crypto[]} connEncryption
* @property {PeerDiscoveryFactory[]} [peerDiscovery]
* @property {PeerRoutingFactory[]} [peerRouting]
* @property {ContentRoutingFactory[]} [contentRouting]
* @property {Object} [dht]
* @property {Pubsub} [pubsub]
*
* @typedef {Object} Libp2pOptions
* @property {Libp2pModules} modules libp2p modules to use
* @property {import('./address-manager').AddressManagerOptions} [addresses]
* @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager]
* @property {Datastore} [datastore]
* @property {import('./dialer').DialerOptions} [dialer]
* @property {import('./metrics').MetricsOptions} [metrics]
* @property {Object} [keychain]
* @property {import('./transport-manager').TransportManagerOptions} [transportManager]
* @property {import('./identify/index').HostProperties} [host] libp2p host
* @property {KeychainOptions & import('./keychain/index').KeychainOptions} [keychain]
* @property {MetricsOptions & import('./metrics').MetricsOptions} [metrics]
* @property {import('./peer-routing').PeerRoutingOptions} [peerRouting]
* @property {PeerStoreOptions & import('./peer-store/persistent').PersistentPeerStoreOptions} [peerStore]
* @property {import('./transport-manager').TransportManagerOptions} [transportManager]
* @property {Libp2pConfig} [config]
*
* @typedef {Object} constructorOptions
Expand Down Expand Up @@ -175,7 +209,6 @@ class Libp2p extends EventEmitter {
const keychainOpts = Keychain.generateOptions()

this.keychain = new Keychain(this._options.keychain.datastore, {
passPhrase: this._options.keychain.pass,
...keychainOpts,
...this._options.keychain
})
Expand Down Expand Up @@ -227,11 +260,7 @@ class Libp2p extends EventEmitter {
this.dialer = new Dialer({
transportManager: this.transportManager,
peerStore: this.peerStore,
concurrency: this._options.dialer.maxParallelDials,
perPeerLimit: this._options.dialer.maxDialsPerPeer,
timeout: this._options.dialer.dialTimeout,
resolvers: this._options.dialer.resolvers,
addressSorter: this._options.dialer.addressSorter
...this._options.dialer
})

this._modules.transport.forEach((Transport) => {
Expand Down
38 changes: 25 additions & 13 deletions src/keychain/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ require('node-forge/lib/sha512')
* @typedef {import('interface-datastore').Datastore} Datastore
*/

/**
* @typedef {Object} DekOptions
* @property {string} hash
* @property {string} salt
* @property {number} iterationCount
* @property {number} keyLength
*
* @typedef {Object} KeychainOptions
* @property {string} pass
* @property {DekOptions} [dek]
*/

/**
* Information about a key.
*
* @typedef {Object} KeyInfo
* @property {string} id - The universally unique key id.
* @property {string} name - The local key name.
*/

const keyPrefix = '/pkcs8/'
const infoPrefix = '/info/'
const privates = new WeakMap()
Expand Down Expand Up @@ -85,14 +105,6 @@ function DsInfoName (name) {
return new Key(infoPrefix + name)
}

/**
* Information about a key.
*
* @typedef {Object} KeyInfo
* @property {string} id - The universally unique key id.
* @property {string} name - The local key name.
*/

/**
* Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.
*
Expand All @@ -106,7 +118,7 @@ class Keychain {
* Creates a new instance of a key chain.
*
* @param {Datastore} store - where the key are.
* @param {object} options
* @param {KeychainOptions} options
* @class
*/
constructor (store, options) {
Expand All @@ -118,8 +130,8 @@ class Keychain {
this.opts = mergeOptions(defaultOptions, options)

// Enforce NIST SP 800-132
if (this.opts.passPhrase && this.opts.passPhrase.length < 20) {
throw new Error('passPhrase must be least 20 characters')
if (this.opts.pass && this.opts.pass.length < 20) {
throw new Error('pass must be least 20 characters')
}
if (this.opts.dek.keyLength < NIST.minKeyLength) {
throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)
Expand All @@ -131,8 +143,8 @@ class Keychain {
throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)
}

const dek = this.opts.passPhrase ? crypto.pbkdf2(
this.opts.passPhrase,
const dek = this.opts.pass ? crypto.pbkdf2(
this.opts.pass,
this.opts.dek.salt,
this.opts.dek.iterationCount,
this.opts.dek.keyLength,
Expand Down
34 changes: 20 additions & 14 deletions src/nat-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,39 @@ const {
} = require('./errors')
const isLoopback = require('libp2p-utils/src/multiaddr/is-loopback')

const DEFAULT_TTL = 7200

/**
* @typedef {import('peer-id')} PeerId
* @typedef {import('./transport-manager')} TransportManager
* @typedef {import('./address-manager')} AddressManager
*/

/**
* @typedef {Object} NatManagerProperties
* @property {PeerId} peerId - The peer ID of the current node
* @property {TransportManager} transportManager - A transport manager
* @property {AddressManager} addressManager - An address manager
*
* @typedef {Object} NatManagerOptions
* @property {boolean} enabled - Whether to enable the NAT manager
* @property {string} [externalIp] - Pass a value to use instead of auto-detection
* @property {string} [description] - A string value to use for the port mapping description on the gateway
* @property {number} [ttl = DEFAULT_TTL] - How long UPnP port mappings should last for in seconds (minimum 1200)
* @property {boolean} [keepAlive] - Whether to automatically refresh UPnP port mappings when their TTL is reached
* @property {string} [gateway] - Pass a value to use instead of auto-detection
* @property {object} [pmp] - PMP options
* @property {boolean} [pmp.enabled] - Whether to enable PMP as well as UPnP
*/

function highPort (min = 1024, max = 65535) {
return Math.floor(Math.random() * (max - min + 1) + min)
}

const DEFAULT_TTL = 7200

class NatManager {
/**
* @class
* @param {object} options
* @param {PeerId} options.peerId - The peer ID of the current node
* @param {TransportManager} options.transportManager - A transport manager
* @param {AddressManager} options.addressManager - An address manager
* @param {boolean} options.enabled - Whether to enable the NAT manager
* @param {string} [options.externalIp] - Pass a value to use instead of auto-detection
* @param {string} [options.description] - A string value to use for the port mapping description on the gateway
* @param {number} [options.ttl] - How long UPnP port mappings should last for in seconds (minimum 1200)
* @param {boolean} [options.keepAlive] - Whether to automatically refresh UPnP port mappings when their TTL is reached
* @param {string} [options.gateway] - Pass a value to use instead of auto-detection
* @param {object} [options.pmp] - PMP options
* @param {boolean} [options.pmp.enabled] - Whether to enable PMP as well as UPnP
* @param {NatManagerProperties & NatManagerOptions} options
*/
constructor ({ peerId, addressManager, transportManager, ...options }) {
this._peerId = peerId
Expand Down
11 changes: 11 additions & 0 deletions src/peer-routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ const PeerId = require('peer-id')
/**
* @typedef {import('multiaddr')} Multiaddr
*/

/**
* @typedef {Object} RefreshManagerOptions
* @property {boolean} [enabled = true] - Whether to enable the Refresh manager
* @property {number} [bootDelay = 6e5] - Boot delay to start the Refresh Manager (in ms)
* @property {number} [interval = 10e3] - Interval between each Refresh Manager run (in ms)
*
* @typedef {Object} PeerRoutingOptions
* @property {RefreshManagerOptions} [refreshManager]
*/

class PeerRouting {
/**
* @class
Expand Down
2 changes: 1 addition & 1 deletion src/peer-store/persistent/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const Protocols = require('./pb/proto-book.proto')
/**
* @typedef {Object} PersistentPeerStoreProperties
* @property {PeerId} peerId
* @property {any} datastore
* @property {import('interface-datastore').Datastore} datastore
*
* @typedef {Object} PersistentPeerStoreOptions
* @property {number} [threshold = 5] - Number of dirty peers allowed before commit data.
Expand Down
4 changes: 2 additions & 2 deletions test/dialing/direct.node.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ describe('Dialing (direct, TCP)', () => {
const dialer = new Dialer({
transportManager: localTM,
peerStore,
timeout: 50
dialTimeout: 50
})
sinon.stub(localTM, 'dial').callsFake(async (addr, options) => {
expect(options.signal).to.exist()
Expand All @@ -171,7 +171,7 @@ describe('Dialing (direct, TCP)', () => {
]
const dialer = new Dialer({
transportManager: localTM,
concurrency: 2,
maxParallelDials: 2,
peerStore: {
addressBook: {
add: () => {},
Expand Down
Loading

0 comments on commit 141f2b3

Please sign in to comment.