diff --git a/doc/migrations/v0.46-v1.0.0.md b/doc/migrations/v0.46-v1.0.0.md index 82132e798f..e6b04bddee 100644 --- a/doc/migrations/v0.46-v1.0.0.md +++ b/doc/migrations/v0.46-v1.0.0.md @@ -7,6 +7,7 @@ A migration guide for refactoring your application code from libp2p `v0.46` to ` - [AutoNAT](#autonat) - [KeyChain](#keychain) +- [Pnet](#pnet) - [Metrics](#metrics) ## AutoNAT @@ -54,6 +55,22 @@ const libp2p = await createLibp2p({ const keychain: Keychain = libp2p.services.keychain ``` +## Pnet + +The pnet module is now published in its own package. + +**Before** + +```ts +import { preSharedKey, generateKey } from 'libp2p/pnet' +``` + +**After** + +```ts +import { preSharedKey, generateKey } from '@libp2p/pnet' +``` + ## Metrics The following metrics were renamed: diff --git a/packages/interface-compliance-tests/src/pubsub/api.ts b/packages/interface-compliance-tests/src/pubsub/api.ts index a879c46473..4c81f4f595 100644 --- a/packages/interface-compliance-tests/src/pubsub/api.ts +++ b/packages/interface-compliance-tests/src/pubsub/api.ts @@ -48,7 +48,6 @@ export default (common: TestSetup): void => { await start(...Object.values(components)) - expect(pubsub.isStarted()).to.equal(true) expect(components.registrar.register).to.have.property('callCount', 1) }) @@ -62,7 +61,6 @@ export default (common: TestSetup): void => { await start(...Object.values(components)) await stop(...Object.values(components)) - expect(pubsub.isStarted()).to.equal(false) expect(components.registrar.unregister).to.have.property('callCount', 1) }) diff --git a/packages/interface/src/startable.ts b/packages/interface/src/startable.ts index 8393abc489..7923b1d557 100644 --- a/packages/interface/src/startable.ts +++ b/packages/interface/src/startable.ts @@ -2,8 +2,6 @@ * Implemented by components that have a lifecycle */ export interface Startable { - isStarted(): boolean - /** * If implemented, this method will be invoked before the start method. * diff --git a/packages/libp2p/package.json b/packages/libp2p/package.json index 146f1b8e39..277917656e 100644 --- a/packages/libp2p/package.json +++ b/packages/libp2p/package.json @@ -72,10 +72,6 @@ "types": "./dist/src/ping/index.d.ts", "import": "./dist/src/ping/index.js" }, - "./pnet": { - "types": "./dist/src/pnet/index.d.ts", - "import": "./dist/src/pnet/index.js" - }, "./upnp-nat": { "types": "./dist/src/upnp-nat/index.d.ts", "import": "./dist/src/upnp-nat/index.js" @@ -156,8 +152,7 @@ "rate-limiter-flexible": "^3.0.0", "uint8arraylist": "^2.4.3", "uint8arrays": "^4.0.6", - "wherearewe": "^2.0.1", - "xsalsa20": "^1.1.0" + "wherearewe": "^2.0.1" }, "devDependencies": { "@chainsafe/libp2p-gossipsub": "^10.0.0", @@ -174,7 +169,6 @@ "@libp2p/mplex": "^9.0.12", "@libp2p/tcp": "^8.0.13", "@libp2p/websockets": "^7.0.13", - "@types/xsalsa20": "^1.1.0", "aegir": "^41.0.2", "execa": "^8.0.1", "go-libp2p": "^1.1.1", diff --git a/packages/libp2p/src/pnet/README.md b/packages/libp2p/src/pnet/README.md deleted file mode 100644 index 94d03c0362..0000000000 --- a/packages/libp2p/src/pnet/README.md +++ /dev/null @@ -1,68 +0,0 @@ -js-libp2p-pnet -================== - -> Connection protection management for libp2p leveraging PSK encryption via XSalsa20. - -**Note**: git history prior to merging into js-libp2p can be found in the original repository, https://github.com/libp2p/js-libp2p-pnet. - -## Table of Contents - -- [Usage](#usage) -- [Private Shared Keys](#private-shared-keys) -- [PSK Generation](#psk-generation) - - [From a module using libp2p](#from-a-module-using-libp2p) - - [Programmatically](#programmatically) - -## Usage - -```js -import { createLibp2p } from 'libp2p' -import { preSharedKey, generateKey } from 'libp2p/pnet' - -// Create a Uint8Array and write the swarm key to it -const swarmKey = new Uint8Array(95) -generateKey(swarmKey) - -const node = await createLibp2p({ - // ...other options - connectionProtector: preSharedKey({ - psk: swarmKey - }) -}) -``` - -## Private Shared Keys - -Private Shared Keys are expected to be in the following format: - -``` -/key/swarm/psk/1.0.0/ -/base16/ -dffb7e3135399a8b1612b2aaca1c36a3a8ac2cd0cca51ceeb2ced87d308cac6d -``` - -## PSK Generation - -A utility method has been created to generate a key for your private network. You can -use one of the methods below to generate your key. - -#### From a module using libp2p - -If you have a module locally that depends on libp2p, you can run the following from -that project, assuming the node_modules are installed. - -```console -node -e "import('libp2p/pnet').then(({ generateKey }) => generateKey(process.stdout))" > swarm.key -``` - -#### Programmatically - -```js -import fs from 'fs' -import { generateKey } from 'libp2p/pnet' - -const swarmKey = new Uint8Array(95) -generateKey(swarmKey) - -fs.writeFileSync('swarm.key', swarmKey) -``` diff --git a/packages/libp2p/test/connection-manager/direct.node.ts b/packages/libp2p/test/connection-manager/direct.node.ts index 4b225596da..a345a5c8d1 100644 --- a/packages/libp2p/test/connection-manager/direct.node.ts +++ b/packages/libp2p/test/connection-manager/direct.node.ts @@ -32,14 +32,11 @@ import { DefaultConnectionManager } from '../../src/connection-manager/index.js' import { codes as ErrorCodes } from '../../src/errors.js' import { plaintext } from '../../src/insecure/index.js' import { createLibp2pNode, type Libp2pNode } from '../../src/libp2p.js' -import { preSharedKey } from '../../src/pnet/index.js' import { DefaultTransportManager } from '../../src/transport-manager.js' -import swarmKey from '../fixtures/swarm.key.js' import type { PeerId } from '@libp2p/interface/peer-id' import type { TransportManager } from '@libp2p/interface-internal/transport-manager' import type { Multiaddr } from '@multiformats/multiaddr' -const swarmKeyBuffer = uint8ArrayFromString(swarmKey) const listenAddr = multiaddr('/ip4/127.0.0.1/tcp/0') const unsupportedAddr = multiaddr('/ip4/127.0.0.1/tcp/9999/ws/p2p/QmckxVrJw1Yo8LqvmDJNUmdAsKtSbiKWmrXJFyKmUraBoN') @@ -496,9 +493,11 @@ describe('libp2p.dialer (direct, TCP)', () => { }) it('should use the protectors when provided for connecting', async () => { - const protector: ConnectionProtector = preSharedKey({ - psk: swarmKeyBuffer - })() + const protector: ConnectionProtector = { + async protect (connection) { + return connection + } + } libp2p = await createLibp2pNode({ peerId, @@ -517,8 +516,6 @@ describe('libp2p.dialer (direct, TCP)', () => { const protectorProtectSpy = Sinon.spy(protector, 'protect') - remoteLibp2p.components.connectionProtector = preSharedKey({ psk: swarmKeyBuffer })() - await libp2p.start() const connection = await libp2p.dial(remoteAddr) diff --git a/packages/libp2p/test/core/start.spec.ts b/packages/libp2p/test/core/start.spec.ts deleted file mode 100644 index a8c5b44855..0000000000 --- a/packages/libp2p/test/core/start.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* eslint-env mocha */ - -import { webSockets } from '@libp2p/websockets' -import { expect } from 'aegir/chai' -import { createLibp2p, type Libp2p } from '../../src/index.js' -import { plaintext } from '../../src/insecure/index.js' - -describe('start', () => { - let libp2p: Libp2p - - afterEach(async () => { - if (libp2p != null) { - await libp2p.stop() - } - }) - - it('it should start by default', async () => { - libp2p = await createLibp2p({ - transports: [ - webSockets() - ], - connectionEncryption: [ - plaintext() - ] - }) - - expect(libp2p.isStarted()).to.be.true() - }) - - it('it should allow overriding', async () => { - libp2p = await createLibp2p({ - start: false, - transports: [ - webSockets() - ], - connectionEncryption: [ - plaintext() - ] - }) - - expect(libp2p.isStarted()).to.be.false() - - await libp2p.start() - - expect(libp2p.isStarted()).to.be.true() - }) -}) diff --git a/packages/libp2p/test/fixtures/swarm.key.ts b/packages/libp2p/test/fixtures/swarm.key.ts deleted file mode 100644 index ee524766d1..0000000000 --- a/packages/libp2p/test/fixtures/swarm.key.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default '/key/swarm/psk/1.0.0/\n' + - '/base16/\n' + - '411f0a244cbbc25ecbb2b070d00a1832516ded521eb3ee3aa13189efe2e2b9a2' diff --git a/packages/libp2p/test/identify/service.spec.ts b/packages/libp2p/test/identify/service.spec.ts index 64e7303e2d..5181b8cdfc 100644 --- a/packages/libp2p/test/identify/service.spec.ts +++ b/packages/libp2p/test/identify/service.spec.ts @@ -153,7 +153,6 @@ describe('identify', () => { // Wait for identify to finish await identityServiceIdentifySpy.firstCall.returnValue - sinon.stub(libp2p, 'isStarted').returns(true) // Cause supported protocols to change await libp2p.handle('/echo/2.0.0', () => {}) @@ -251,7 +250,6 @@ describe('identify', () => { // Wait for identify to finish await identityServiceIdentifySpy.firstCall.returnValue - sinon.stub(libp2p, 'isStarted').returns(true) await libp2p.peerStore.merge(libp2p.peerId, { multiaddrs: [multiaddr('/ip4/180.0.0.1/tcp/15001/ws')] diff --git a/packages/libp2p/test/transports/transport-manager.spec.ts b/packages/libp2p/test/transports/transport-manager.spec.ts index c71a124a92..075364aea9 100644 --- a/packages/libp2p/test/transports/transport-manager.spec.ts +++ b/packages/libp2p/test/transports/transport-manager.spec.ts @@ -124,7 +124,6 @@ describe('libp2p.transportManager (dial only)', () => { start: false }) - expect(libp2p.isStarted()).to.be.false() await expect(libp2p.start()).to.eventually.be.rejected .with.property('code', ErrorCodes.ERR_NO_VALID_ADDRESSES) }) @@ -147,7 +146,6 @@ describe('libp2p.transportManager (dial only)', () => { start: false }) - expect(libp2p.isStarted()).to.be.false() await expect(libp2p.start()).to.eventually.be.undefined() }) @@ -169,7 +167,6 @@ describe('libp2p.transportManager (dial only)', () => { start: false }) - expect(libp2p.isStarted()).to.be.false() await expect(libp2p.start()).to.eventually.be.undefined() }) }) diff --git a/packages/libp2p/test/upgrading/upgrader.spec.ts b/packages/libp2p/test/upgrading/upgrader.spec.ts index 6f83c08ecd..0c2267d73b 100644 --- a/packages/libp2p/test/upgrading/upgrader.spec.ts +++ b/packages/libp2p/test/upgrading/upgrader.spec.ts @@ -26,10 +26,8 @@ import { type Components, defaultComponents } from '../../src/components.js' import { codes } from '../../src/errors.js' import { createLibp2p } from '../../src/index.js' import { plaintext } from '../../src/insecure/index.js' -import { preSharedKey } from '../../src/pnet/index.js' import { DEFAULT_MAX_OUTBOUND_STREAMS } from '../../src/registrar.js' import { DefaultUpgrader } from '../../src/upgrader.js' -import swarmKey from '../fixtures/swarm.key.js' import type { Libp2p } from '@libp2p/interface' import type { Connection, ConnectionProtector, Stream } from '@libp2p/interface/connection' import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface/connection-encrypter' @@ -206,9 +204,12 @@ describe('Upgrader', () => { it('should use a private connection protector when provided', async () => { const { inbound, outbound } = mockMultiaddrConnPair({ addrs, remotePeer }) - const protector = preSharedKey({ - psk: uint8ArrayFromString(swarmKey) - })() + const protector: ConnectionProtector = { + async protect (connection) { + return connection + } + } + const protectorProtectSpy = sinon.spy(protector, 'protect') localComponents.connectionProtector = protector @@ -615,6 +616,12 @@ describe('libp2p.upgrader', () => { it('should create an Upgrader', async () => { const deferred = pDefer() + const protector: ConnectionProtector = { + async protect (connection) { + return connection + } + } + libp2p = await createLibp2p({ peerId: peers[0], transports: [ @@ -627,9 +634,7 @@ describe('libp2p.upgrader', () => { connectionEncryption: [ plaintext() ], - connectionProtector: preSharedKey({ - psk: uint8ArrayFromString(swarmKey) - }), + connectionProtector: () => protector, services: { test: (components: any) => { deferred.resolve(components) diff --git a/packages/libp2p/typedoc.json b/packages/libp2p/typedoc.json index 5629b3c79d..dde288fe84 100644 --- a/packages/libp2p/typedoc.json +++ b/packages/libp2p/typedoc.json @@ -6,7 +6,6 @@ "./src/identify/index.ts", "./src/insecure/index.ts", "./src/ping/index.ts", - "./src/pnet/index.ts", "./src/upnp-nat/index.ts" ] } diff --git a/packages/peer-discovery-mdns/src/index.ts b/packages/peer-discovery-mdns/src/index.ts index ed37439b57..6f78e6f7e2 100644 --- a/packages/peer-discovery-mdns/src/index.ts +++ b/packages/peer-discovery-mdns/src/index.ts @@ -76,186 +76,9 @@ * ``` */ -import { CustomEvent, TypedEventEmitter } from '@libp2p/interface/events' -import { peerDiscovery } from '@libp2p/interface/peer-discovery' -import { logger } from '@libp2p/logger' -import multicastDNS from 'multicast-dns' -import * as query from './query.js' -import { stringGen } from './utils.js' -import type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface/peer-discovery' -import type { PeerInfo } from '@libp2p/interface/peer-info' -import type { Startable } from '@libp2p/interface/src/startable.js' -import type { AddressManager } from '@libp2p/interface-internal/address-manager' - -const log = logger('libp2p:mdns') - -export interface MulticastDNSInit { - /** - * (true/false) announce our presence through mDNS, default `true` - */ - broadcast?: boolean - - /** - * query interval, default 10 \* 1000 (10 seconds) - */ - interval?: number - - /** - * name of the service announce , default '_p2p._udp.local\` - */ - serviceTag?: string - /** - * Peer name to announce (should not be peeer id), default random string - */ - peerName?: string - - /** - * UDP port to broadcast to - */ - port?: number - - /** - * UDP IP to broadcast to - */ - ip?: string -} - -export interface MulticastDNSComponents { - addressManager: AddressManager -} - -class MulticastDNS extends TypedEventEmitter implements PeerDiscovery, Startable { - public mdns?: multicastDNS.MulticastDNS - - private readonly broadcast: boolean - private readonly interval: number - private readonly serviceTag: string - private readonly peerName: string - private readonly port: number - private readonly ip: string - private _queryInterval: ReturnType | null - private readonly components: MulticastDNSComponents - - constructor (components: MulticastDNSComponents, init: MulticastDNSInit = {}) { - super() - - this.broadcast = init.broadcast !== false - this.interval = init.interval ?? (1e3 * 10) - this.serviceTag = init.serviceTag ?? '_p2p._udp.local' - this.ip = init.ip ?? '224.0.0.251' - this.peerName = init.peerName ?? stringGen(63) - // 63 is dns label limit - if (this.peerName.length >= 64) { - throw new Error('Peer name should be less than 64 chars long') - } - this.port = init.port ?? 5353 - this.components = components - this._queryInterval = null - this._onMdnsQuery = this._onMdnsQuery.bind(this) - this._onMdnsResponse = this._onMdnsResponse.bind(this) - this._onMdnsWarning = this._onMdnsWarning.bind(this) - this._onMdnsError = this._onMdnsError.bind(this) - } - - readonly [peerDiscovery] = this - - readonly [Symbol.toStringTag] = '@libp2p/mdns' - - isStarted (): boolean { - return Boolean(this.mdns) - } - - /** - * Start sending queries to the LAN. - * - * @returns {void} - */ - async start (): Promise { - if (this.mdns != null) { - return - } - - this.mdns = multicastDNS({ port: this.port, ip: this.ip }) - this.mdns.on('query', this._onMdnsQuery) - this.mdns.on('response', this._onMdnsResponse) - this.mdns.on('warning', this._onMdnsWarning) - this.mdns.on('error', this._onMdnsError) - - this._queryInterval = query.queryLAN(this.mdns, this.serviceTag, this.interval) - } - - _onMdnsQuery (event: multicastDNS.QueryPacket): void { - if (this.mdns == null) { - return - } - - log.trace('received incoming mDNS query') - query.gotQuery( - event, - this.mdns, - this.peerName, - this.components.addressManager.getAddresses(), - this.serviceTag, - this.broadcast) - } - - _onMdnsResponse (event: multicastDNS.ResponsePacket): void { - log.trace('received mDNS query response') - - try { - const foundPeer = query.gotResponse(event, this.peerName, this.serviceTag) - - if (foundPeer != null) { - log('discovered peer in mDNS query response %p', foundPeer.id) - - this.dispatchEvent(new CustomEvent('peer', { - detail: foundPeer - })) - } - } catch (err) { - log.error('Error processing peer response', err) - } - } - - _onMdnsWarning (err: Error): void { - log.error('mdns warning', err) - } - - _onMdnsError (err: Error): void { - log.error('mdns error', err) - } - - /** - * Stop sending queries to the LAN. - * - * @returns {Promise} - */ - async stop (): Promise { - if (this.mdns == null) { - return - } - - this.mdns.removeListener('query', this._onMdnsQuery) - this.mdns.removeListener('response', this._onMdnsResponse) - this.mdns.removeListener('warning', this._onMdnsWarning) - this.mdns.removeListener('error', this._onMdnsError) - - if (this._queryInterval != null) { - clearInterval(this._queryInterval) - this._queryInterval = null - } - - await new Promise((resolve) => { - if (this.mdns != null) { - this.mdns.destroy(resolve) - } else { - resolve() - } - }) - - this.mdns = undefined - } -} +import { MulticastDNS } from './mdns.js' +import type { MulticastDNSInit, MulticastDNSComponents } from './mdns.js' +import type { PeerDiscovery } from '@libp2p/interface/peer-discovery' export function mdns (init: MulticastDNSInit = {}): (components: MulticastDNSComponents) => PeerDiscovery { return (components: MulticastDNSComponents) => new MulticastDNS(components, init) diff --git a/packages/peer-discovery-mdns/src/mdns.ts b/packages/peer-discovery-mdns/src/mdns.ts new file mode 100644 index 0000000000..cdcd802a46 --- /dev/null +++ b/packages/peer-discovery-mdns/src/mdns.ts @@ -0,0 +1,158 @@ +import { CustomEvent, EventEmitter } from '@libp2p/interface/events' +import { peerDiscovery } from '@libp2p/interface/peer-discovery' +import { logger } from '@libp2p/logger' +import multicastDNS from 'multicast-dns' +import * as query from './query.js' +import { stringGen } from './utils.js' +import type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interface/peer-discovery' +import type { PeerInfo } from '@libp2p/interface/peer-info' +import type { Startable } from '@libp2p/interface/src/startable.js' +import type { AddressManager } from '@libp2p/interface-internal/address-manager' + +const log = logger('libp2p:mdns') + +export interface MulticastDNSInit { + broadcast?: boolean + interval?: number + serviceTag?: string + peerName?: string + port?: number + ip?: string +} + +export interface MulticastDNSComponents { + addressManager: AddressManager +} + +export class MulticastDNS extends EventEmitter implements PeerDiscovery, Startable { + public mdns?: multicastDNS.MulticastDNS + + private readonly broadcast: boolean + private readonly interval: number + private readonly serviceTag: string + private readonly peerName: string + private readonly port: number + private readonly ip: string + private _queryInterval: ReturnType | null + private readonly components: MulticastDNSComponents + + constructor (components: MulticastDNSComponents, init: MulticastDNSInit = {}) { + super() + + this.broadcast = init.broadcast !== false + this.interval = init.interval ?? (1e3 * 10) + this.serviceTag = init.serviceTag ?? '_p2p._udp.local' + this.ip = init.ip ?? '224.0.0.251' + this.peerName = init.peerName ?? stringGen(63) + // 63 is dns label limit + if (this.peerName.length >= 64) { + throw new Error('Peer name should be less than 64 chars long') + } + this.port = init.port ?? 5353 + this.components = components + this._queryInterval = null + this._onMdnsQuery = this._onMdnsQuery.bind(this) + this._onMdnsResponse = this._onMdnsResponse.bind(this) + this._onMdnsWarning = this._onMdnsWarning.bind(this) + this._onMdnsError = this._onMdnsError.bind(this) + } + + readonly [peerDiscovery] = this + + readonly [Symbol.toStringTag] = '@libp2p/mdns' + + isStarted (): boolean { + return Boolean(this.mdns) + } + + /** + * Start sending queries to the LAN. + * + * @returns {void} + */ + async start (): Promise { + if (this.mdns != null) { + return + } + + this.mdns = multicastDNS({ port: this.port, ip: this.ip }) + this.mdns.on('query', this._onMdnsQuery) + this.mdns.on('response', this._onMdnsResponse) + this.mdns.on('warning', this._onMdnsWarning) + this.mdns.on('error', this._onMdnsError) + + this._queryInterval = query.queryLAN(this.mdns, this.serviceTag, this.interval) + } + + _onMdnsQuery (event: multicastDNS.QueryPacket): void { + if (this.mdns == null) { + return + } + + log.trace('received incoming mDNS query') + query.gotQuery( + event, + this.mdns, + this.peerName, + this.components.addressManager.getAddresses(), + this.serviceTag, + this.broadcast) + } + + _onMdnsResponse (event: multicastDNS.ResponsePacket): void { + log.trace('received mDNS query response') + + try { + const foundPeer = query.gotResponse(event, this.peerName, this.serviceTag) + + if (foundPeer != null) { + log('discovered peer in mDNS query response %p', foundPeer.id) + + this.dispatchEvent(new CustomEvent('peer', { + detail: foundPeer + })) + } + } catch (err) { + log.error('Error processing peer response', err) + } + } + + _onMdnsWarning (err: Error): void { + log.error('mdns warning', err) + } + + _onMdnsError (err: Error): void { + log.error('mdns error', err) + } + + /** + * Stop sending queries to the LAN. + * + * @returns {Promise} + */ + async stop (): Promise { + if (this.mdns == null) { + return + } + + this.mdns.removeListener('query', this._onMdnsQuery) + this.mdns.removeListener('response', this._onMdnsResponse) + this.mdns.removeListener('warning', this._onMdnsWarning) + this.mdns.removeListener('error', this._onMdnsError) + + if (this._queryInterval != null) { + clearInterval(this._queryInterval) + this._queryInterval = null + } + + await new Promise((resolve) => { + if (this.mdns != null) { + this.mdns.destroy(resolve) + } else { + resolve() + } + }) + + this.mdns = undefined + } +} diff --git a/packages/peer-discovery-mdns/test/compliance.spec.ts b/packages/peer-discovery-mdns/test/compliance.spec.ts index b24d590d91..d5975b654c 100644 --- a/packages/peer-discovery-mdns/test/compliance.spec.ts +++ b/packages/peer-discovery-mdns/test/compliance.spec.ts @@ -1,16 +1,14 @@ /* eslint-env mocha */ import { CustomEvent } from '@libp2p/interface/events' -import { isStartable } from '@libp2p/interface/startable' import tests from '@libp2p/interface-compliance-tests/peer-discovery' import { createEd25519PeerId } from '@libp2p/peer-id-factory' import { multiaddr } from '@multiformats/multiaddr' import { stubInterface } from 'ts-sinon' -import { mdns } from '../src/index.js' -import type { PeerDiscovery } from '@libp2p/interface/peer-discovery' +import { MulticastDNS } from '../src/mdns.js' import type { AddressManager } from '@libp2p/interface-internal/address-manager' -let discovery: PeerDiscovery +let discovery: MulticastDNS describe('compliance tests', () => { let intervalId: ReturnType @@ -25,18 +23,18 @@ describe('compliance tests', () => { multiaddr(`/ip4/127.0.0.1/tcp/13921/p2p/${peerId1.toString()}`) ]) - discovery = mdns({ + discovery = new MulticastDNS({ + addressManager + }, { broadcast: false, port: 50001 - })({ - addressManager }) // Trigger discovery const maStr = '/ip4/127.0.0.1/tcp/15555/ws/p2p-webrtc-star' intervalId = setInterval(() => { - if (isStartable(discovery) && !discovery.isStarted()) { + if (!discovery.isStarted()) { return } diff --git a/packages/peer-discovery-mdns/test/multicast-dns.spec.ts b/packages/peer-discovery-mdns/test/multicast-dns.spec.ts index 9955002dd7..1ac9b75056 100644 --- a/packages/peer-discovery-mdns/test/multicast-dns.spec.ts +++ b/packages/peer-discovery-mdns/test/multicast-dns.spec.ts @@ -6,7 +6,8 @@ import { multiaddr } from '@multiformats/multiaddr' import { expect } from 'aegir/chai' import pWaitFor from 'p-wait-for' import { stubInterface } from 'ts-sinon' -import { mdns, type MulticastDNSComponents } from './../src/index.js' +import { mdns } from './../src/index.js' +import type { MulticastDNSComponents } from './../src/mdns.js' import type { PeerId } from '@libp2p/interface/peer-id' import type { PeerInfo } from '@libp2p/interface/peer-info' import type { AddressManager } from '@libp2p/interface-internal/address-manager' diff --git a/packages/pnet/LICENSE b/packages/pnet/LICENSE new file mode 100644 index 0000000000..20ce483c86 --- /dev/null +++ b/packages/pnet/LICENSE @@ -0,0 +1,4 @@ +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 diff --git a/packages/pnet/LICENSE-APACHE b/packages/pnet/LICENSE-APACHE new file mode 100644 index 0000000000..14478a3b60 --- /dev/null +++ b/packages/pnet/LICENSE-APACHE @@ -0,0 +1,5 @@ +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/packages/pnet/LICENSE-MIT b/packages/pnet/LICENSE-MIT new file mode 100644 index 0000000000..72dc60d84b --- /dev/null +++ b/packages/pnet/LICENSE-MIT @@ -0,0 +1,19 @@ +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/packages/pnet/README.md b/packages/pnet/README.md new file mode 100644 index 0000000000..3b12436c22 --- /dev/null +++ b/packages/pnet/README.md @@ -0,0 +1,89 @@ +> Connection protection management for libp2p leveraging PSK encryption via XSalsa20. + +[![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/) +[![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io) +[![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p) +[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=master\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amaster) + +> Implementation of Connection protection management via a shared secret + +# About + +Connection protection management for libp2p leveraging PSK encryption via XSalsa20. + +## Example + +```typescript +import { createLibp2p } from 'libp2p' +import { preSharedKey, generateKey } from '@libp2p/pnet' + +// Create a Uint8Array and write the swarm key to it +const swarmKey = new Uint8Array(95) +generateKey(swarmKey) + +const node = await createLibp2p({ + // ...other options + connectionProtector: preSharedKey({ + psk: swarmKey + }) +}) +``` + +## Private Shared Keys + +Private Shared Keys are expected to be in the following format: + +``` +/key/swarm/psk/1.0.0/ +/base16/ +dffb7e3135399a8b1612b2aaca1c36a3a8ac2cd0cca51ceeb2ced87d308cac6d +``` + +## PSK Generation + +A utility method has been created to generate a key for your private network. You can use one of the methods below to generate your key. + +### From a module using libp2p + +If you have a module locally that depends on libp2p, you can run the following from that project, assuming the node\_modules are installed. + +```console +node -e "import('@libp2p/pnet').then(({ generateKey }) => generateKey(process.stdout))" > swarm.key +``` + +### Programmatically + +```js +import fs from 'fs' +import { generateKey } from '@libp2p/pnet' + +const swarmKey = new Uint8Array(95) +generateKey(swarmKey) + +fs.writeFileSync('swarm.key', swarmKey) +``` + +# Install + +```console +$ npm i @libp2p/pnet +``` + +## Browser ` +``` + +# License + +Licensed under either of + +- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / ) +- MIT ([LICENSE-MIT](LICENSE-MIT) / ) + +# Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. diff --git a/packages/pnet/package.json b/packages/pnet/package.json new file mode 100644 index 0000000000..a568b2e111 --- /dev/null +++ b/packages/pnet/package.json @@ -0,0 +1,67 @@ +{ + "name": "@libp2p/pnet", + "version": "1.0.0", + "description": "Implementation of Connection protection management via a shared secret", + "license": "Apache-2.0 OR MIT", + "homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/pnet#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/libp2p/js-libp2p.git" + }, + "bugs": { + "url": "https://github.com/libp2p/js-libp2p/issues" + }, + "type": "module", + "types": "./dist/src/index.d.ts", + "files": [ + "src", + "dist", + "!dist/test", + "!**/*.tsbuildinfo" + ], + "exports": { + ".": { + "types": "./dist/src/index.d.ts", + "import": "./dist/src/index.js" + } + }, + "eslintConfig": { + "extends": "ipfs", + "parserOptions": { + "project": true, + "sourceType": "module" + } + }, + "scripts": { + "build": "aegir build", + "test": "aegir test", + "clean": "aegir clean", + "lint": "aegir lint", + "test:chrome": "aegir test -t browser --cov", + "test:chrome-webworker": "aegir test -t webworker", + "test:firefox": "aegir test -t browser -- --browser firefox", + "test:firefox-webworker": "aegir test -t webworker -- --browser firefox", + "test:node": "aegir test -t node --cov", + "dep-check": "aegir dep-check" + }, + "dependencies": { + "@libp2p/crypto": "^2.0.5", + "@libp2p/interface": "^0.1.3", + "@libp2p/logger": "^3.0.2", + "it-handshake": "^4.1.3", + "it-map": "^3.0.3", + "it-pair": "^2.0.6", + "it-pipe": "^3.0.1", + "it-stream-types": "^2.0.1", + "uint8arrays": "^4.0.6", + "xsalsa20": "^1.1.0" + }, + "devDependencies": { + "@libp2p/interface-compliance-tests": "^4.1.1", + "@libp2p/peer-id-factory": "^3.0.5", + "@multiformats/multiaddr": "^12.1.5", + "@types/xsalsa20": "^1.1.0", + "aegir": "^41.0.2", + "it-all": "^3.0.1" + } +} diff --git a/packages/libp2p/src/pnet/crypto.ts b/packages/pnet/src/crypto.ts similarity index 100% rename from packages/libp2p/src/pnet/crypto.ts rename to packages/pnet/src/crypto.ts diff --git a/packages/libp2p/src/pnet/errors.ts b/packages/pnet/src/errors.ts similarity index 83% rename from packages/libp2p/src/pnet/errors.ts rename to packages/pnet/src/errors.ts index b09f68a2a1..a8288ac045 100644 --- a/packages/libp2p/src/pnet/errors.ts +++ b/packages/pnet/src/errors.ts @@ -3,3 +3,4 @@ export const INVALID_PSK = 'Your private shared key is invalid' export const NO_LOCAL_ID = 'No local private key provided' export const NO_HANDSHAKE_CONNECTION = 'No connection for the handshake provided' export const STREAM_ENDED = 'Stream ended prematurely' +export const ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS' diff --git a/packages/libp2p/src/pnet/index.ts b/packages/pnet/src/index.ts similarity index 72% rename from packages/libp2p/src/pnet/index.ts rename to packages/pnet/src/index.ts index 3433710512..c072e47de8 100644 --- a/packages/libp2p/src/pnet/index.ts +++ b/packages/pnet/src/index.ts @@ -7,7 +7,7 @@ * * ```typescript * import { createLibp2p } from 'libp2p' - * import { preSharedKey, generateKey } from 'libp2p/pnet' + * import { preSharedKey, generateKey } from '@libp2p/pnet' * * // Create a Uint8Array and write the swarm key to it * const swarmKey = new Uint8Array(95) @@ -20,6 +20,40 @@ * }) * }) * ``` + * + * ## Private Shared Keys + * + * Private Shared Keys are expected to be in the following format: + * + * ``` + * /key/swarm/psk/1.0.0/ + * /base16/ + * dffb7e3135399a8b1612b2aaca1c36a3a8ac2cd0cca51ceeb2ced87d308cac6d + * ``` + * + * ## PSK Generation + * + * A utility method has been created to generate a key for your private network. You can use one of the methods below to generate your key. + * + * ### From a module using libp2p + * + * If you have a module locally that depends on libp2p, you can run the following from that project, assuming the node_modules are installed. + * + * ```console + * node -e "import('@libp2p/pnet').then(({ generateKey }) => generateKey(process.stdout))" > swarm.key + * ``` + * + * ### Programmatically + * + * ```js + * import fs from 'fs' + * import { generateKey } from '@libp2p/pnet' + * + * const swarmKey = new Uint8Array(95) + * generateKey(swarmKey) + * + * fs.writeFileSync('swarm.key', swarmKey) + * ``` */ import { randomBytes } from '@libp2p/crypto' @@ -29,7 +63,6 @@ import { handshake } from 'it-handshake' import map from 'it-map' import { duplexPair } from 'it-pair/duplex' import { pipe } from 'it-pipe' -import { codes } from '../errors.js' import { createBoxStream, createUnboxStream, @@ -81,7 +114,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { } if (connection == null) { - throw new CodeError(Errors.NO_HANDSHAKE_CONNECTION, codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.NO_HANDSHAKE_CONNECTION, Errors.ERR_INVALID_PARAMETERS) } // Exchange nonces @@ -94,7 +127,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { const result = await shake.reader.next(NONCE_LENGTH) if (result.value == null) { - throw new CodeError(Errors.STREAM_ENDED, codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.STREAM_ENDED, Errors.ERR_INVALID_PARAMETERS) } const remoteNonce = result.value.slice() diff --git a/packages/libp2p/src/pnet/key-generator.ts b/packages/pnet/src/key-generator.ts similarity index 100% rename from packages/libp2p/src/pnet/key-generator.ts rename to packages/pnet/src/key-generator.ts diff --git a/packages/libp2p/test/pnet/index.spec.ts b/packages/pnet/test/index.spec.ts similarity index 96% rename from packages/libp2p/test/pnet/index.spec.ts rename to packages/pnet/test/index.spec.ts index 20812893a0..e713e16d51 100644 --- a/packages/libp2p/test/pnet/index.spec.ts +++ b/packages/pnet/test/index.spec.ts @@ -6,8 +6,8 @@ import { expect } from 'aegir/chai' import all from 'it-all' import { pipe } from 'it-pipe' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' -import { INVALID_PSK } from '../../src/pnet/errors.js' -import { preSharedKey, generateKey } from '../../src/pnet/index.js' +import { INVALID_PSK } from '../src/errors.js' +import { preSharedKey, generateKey } from '../src/index.js' const swarmKeyBuffer = new Uint8Array(95) const wrongSwarmKeyBuffer = new Uint8Array(95) diff --git a/packages/pnet/tsconfig.json b/packages/pnet/tsconfig.json new file mode 100644 index 0000000000..1e17899ddc --- /dev/null +++ b/packages/pnet/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "aegir/src/config/tsconfig.aegir.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": [ + "src", + "test" + ], + "references": [ + { + "path": "../crypto" + }, + { + "path": "../interface" + }, + { + "path": "../interface-compliance-tests" + }, + { + "path": "../logger" + }, + { + "path": "../peer-id-factory" + } + ] +} diff --git a/packages/pnet/typedoc.json b/packages/pnet/typedoc.json new file mode 100644 index 0000000000..f599dc728d --- /dev/null +++ b/packages/pnet/typedoc.json @@ -0,0 +1,5 @@ +{ + "entryPoints": [ + "./src/index.ts" + ] +}