Skip to content
This repository has been archived by the owner on Apr 24, 2023. It is now read-only.

Commit

Permalink
fix: update interfaces
Browse files Browse the repository at this point in the history
Updates to latest code from libp2p/js-libp2p-interfaces#180
  • Loading branch information
achingbrain committed Mar 17, 2022
1 parent c60ae51 commit 19bdc4e
Show file tree
Hide file tree
Showing 15 changed files with 173 additions and 127 deletions.
2 changes: 1 addition & 1 deletion packages/webrtc-star-protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
"build": "tsc"
},
"dependencies": {
"@multiformats/multiaddr": "^10.1.2",
"@multiformats/multiaddr": "^10.1.7",
"socket.io-client": "^4.1.2"
},
"devDependencies": {
Expand Down
8 changes: 4 additions & 4 deletions packages/webrtc-star-signalling-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,16 @@
"dep-check": "aegir dep-check dist/src/**/*.js dist/test/**/*.js",
"build": "tsc",
"pretest": "npm run build",
"test": "aegir test -f ./dist/test/**/*.js",
"test": "aegir test -f \"./dist/test/**/*.js\"",
"test:node": "npm run test -- -t node --cov",
"start": "node src/sig-server/bin.js"
},
"dependencies": {
"@hapi/hapi": "^20.0.0",
"@hapi/inert": "^6.0.3",
"@libp2p/logger": "^1.0.2",
"@libp2p/webrtc-star-protocol": "^0.0.0",
"@multiformats/multiaddr": "^10.1.2",
"@libp2p/logger": "^1.1.2",
"@libp2p/webrtc-star-protocol": "^1.0.0",
"@multiformats/multiaddr": "^10.1.7",
"menoetius": "0.0.3",
"minimist": "^1.2.5",
"prom-client": "^14.0.0",
Expand Down
18 changes: 9 additions & 9 deletions packages/webrtc-star-transport/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,20 +125,20 @@
"dep-check": "aegir dep-check dist/src/**/*.js dist/test/**/*.js",
"build": "tsc",
"pretest": "npm run build",
"test": "aegir test -f ./dist/test/*.spec.js",
"test": "aegir test -f \"./dist/test/**/*.spec.js\"",
"test:chrome": "npm run test -- -t browser -f ./dist/test/browser.js ",
"test:firefox": "npm run test -- -t browser -- --browser firefox -f ./dist/test/browser.js",
"test:dns": "WEBRTC_STAR_REMOTE_SIGNAL_DNS=1 aegir test -t browser",
"test:ip": "WEBRTC_STAR_REMOTE_SIGNAL_IP=1 aegir test -t browser"
},
"dependencies": {
"@libp2p/interfaces": "^1.3.2",
"@libp2p/logger": "^1.0.2",
"@libp2p/peer-id": "^1.0.4",
"@libp2p/utils": "^1.0.5",
"@libp2p/webrtc-star-protocol": "^0.0.0",
"@libp2p/interfaces": "^1.3.15",
"@libp2p/logger": "^1.1.2",
"@libp2p/peer-id": "^1.1.8",
"@libp2p/utils": "^1.0.9",
"@libp2p/webrtc-star-protocol": "^1.0.0",
"@multiformats/mafmt": "^11.0.2",
"@multiformats/multiaddr": "^10.1.2",
"@multiformats/multiaddr": "^10.1.7",
"abortable-iterator": "^4.0.2",
"delay": "^5.0.0",
"err-code": "^3.0.1",
Expand All @@ -151,8 +151,8 @@
"socket.io-client": "^4.1.2"
},
"devDependencies": {
"@libp2p/interface-compliance-tests": "^1.0.6",
"@libp2p/webrtc-star-signalling-server": "^0.1.2",
"@libp2p/interface-compliance-tests": "^1.1.17",
"@libp2p/webrtc-star-signalling-server": "^1.0.0",
"@mapbox/node-pre-gyp": "^1.0.5",
"aegir": "^36.1.3",
"electron-webrtc": "~0.3.0",
Expand Down
57 changes: 28 additions & 29 deletions packages/webrtc-star-transport/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,24 @@ import { cleanMultiaddr, cleanUrlSIO } from './utils.js'
import { WebRTCInitiator } from './peer/initiator.js'
import randomBytes from 'iso-random-stream/src/random.js'
import { toString as uint8ArrayToString } from 'uint8arrays'
import { EventEmitter, CustomEvent } from '@libp2p/interfaces'
import { EventEmitter, CustomEvent, Startable } from '@libp2p/interfaces'
import { peerIdFromString } from '@libp2p/peer-id'
import type { PeerId } from '@libp2p/interfaces/peer-id'
import { symbol } from '@libp2p/interfaces/transport'
import type { WRTC } from './peer/interface.js'
import type { Connection } from '@libp2p/interfaces/connection'
import type { Transport, Upgrader, ListenerOptions, MultiaddrConnection, Listener } from '@libp2p/interfaces/transport'
import type { Transport, MultiaddrConnection, Listener, DialOptions, CreateListenerOptions } from '@libp2p/interfaces/transport'
import type { PeerDiscovery, PeerDiscoveryEvents } from '@libp2p/interfaces/peer-discovery'
import type { AbortOptions } from '@libp2p/interfaces'
import type { WebRTCInitiatorOptions } from './peer/initiator.js'
import type { WebRTCReceiver, WebRTCReceiverOptions } from './peer/receiver.js'
import type { WebRTCStarSocket, HandshakeSignal } from '@libp2p/webrtc-star-protocol'
import { Components, Initializable } from '@libp2p/interfaces/components'

const webrtcSupport = 'RTCPeerConnection' in globalThis
const log = logger('libp2p:webrtc-star')

const noop = () => {}

class WebRTCStarDiscovery extends EventEmitter<PeerDiscoveryEvents> implements PeerDiscovery {
class WebRTCStarDiscovery extends EventEmitter<PeerDiscoveryEvents> implements PeerDiscovery, Startable {
public tag = 'webRTCStar'
private started = false

Expand All @@ -53,16 +53,14 @@ class WebRTCStarDiscovery extends EventEmitter<PeerDiscoveryEvents> implements P
}

export interface WebRTCStarOptions {
upgrader: Upgrader
peerId: PeerId
wrtc?: WRTC
}

export interface WebRTCStarDialOptions extends AbortOptions {
export interface WebRTCStarDialOptions extends DialOptions {
channelOptions?: WebRTCInitiatorOptions
}

export interface WebRTCStarListenerOptions extends ListenerOptions, WebRTCInitiatorOptions {
export interface WebRTCStarListenerOptions extends CreateListenerOptions, WebRTCInitiatorOptions {
channelOptions?: WebRTCReceiverOptions
}

Expand All @@ -85,23 +83,14 @@ export interface SignalServer extends EventEmitter<SignalServerServerEvents> {
/**
* @class WebRTCStar
*/
export class WebRTCStar implements Transport<WebRTCStarDialOptions, WebRTCStarListenerOptions> {
export class WebRTCStar implements Transport, Initializable {
public wrtc?: WRTC
public discovery: PeerDiscovery
public discovery: PeerDiscovery & Startable
public sigServers: Map<string, SignalServer>
private components: Components = new Components()

private readonly upgrader: Upgrader
private readonly peerId: PeerId

constructor (options: WebRTCStarOptions) {
if (options.upgrader == null) {
throw new Error('An upgrader must be provided. See https://github.com/libp2p/interface-transport#upgrader.')
}

this.upgrader = options.upgrader
this.peerId = options.peerId

if (options.wrtc != null) {
constructor (options?: WebRTCStarOptions) {
if (options?.wrtc != null) {
this.wrtc = options.wrtc
}

Expand All @@ -113,12 +102,23 @@ export class WebRTCStar implements Transport<WebRTCStarDialOptions, WebRTCStarLi
this.peerDiscovered = this.peerDiscovered.bind(this)
}

async dial (ma: Multiaddr, options?: WebRTCStarDialOptions) {
options = options ?? {}
get [symbol] (): true {
return true
}

get [Symbol.toStringTag] () {
return this.constructor.name
}

init (components: Components) {
this.components = components
}

async dial (ma: Multiaddr, options: WebRTCStarDialOptions) {
const rawConn = await this._connect(ma, options)
const maConn = toMultiaddrConnection(rawConn, { remoteAddr: ma, signal: options.signal })
log('new outbound connection %s', maConn.remoteAddr)
const conn = await this.upgrader.upgradeOutbound(maConn)
const conn = await options.upgrader.upgradeOutbound(maConn)
log('outbound connection %s upgraded', maConn.remoteAddr)
return conn
}
Expand Down Expand Up @@ -222,19 +222,18 @@ export class WebRTCStar implements Transport<WebRTCStarDialOptions, WebRTCStarLi
* anytime a new incoming Connection has been successfully upgraded via
* `upgrader.upgradeInbound`.
*/
createListener (options?: WebRTCStarListenerOptions): Listener {
createListener (options: WebRTCStarListenerOptions): Listener {
if (!webrtcSupport && this.wrtc == null) {
throw errcode(new Error('no WebRTC support'), 'ERR_NO_WEBRTC_SUPPORT')
}

options = options ?? {}
options.channelOptions = options.channelOptions ?? {}

if (this.wrtc != null) {
options.channelOptions.wrtc = this.wrtc
}

return createListener(this.upgrader, options.handler ?? noop, this.peerId, this, options)
return createListener(options.upgrader, options.handler ?? noop, this.components.getPeerId(), this, options)
}

/**
Expand Down
5 changes: 2 additions & 3 deletions packages/webrtc-star-transport/src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { WebRTCReceiver } from './peer/receiver.js'
import { toMultiaddrConnection } from './socket-to-conn.js'
import { cleanUrlSIO } from './utils.js'
import { CODE_P2P } from './constants.js'
import { base58btc } from 'multiformats/bases/base58'
import type { PeerId } from '@libp2p/interfaces/peer-id'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { Upgrader, ConnectionHandler, Listener, MultiaddrConnection, ListenerEvents } from '@libp2p/interfaces/transport'
Expand Down Expand Up @@ -227,7 +226,7 @@ class WebRTCListener extends EventEmitter<ListenerEvents> implements Listener {

let signallingAddr: Multiaddr
if (!ma.protoCodes().includes(CODE_P2P)) {
signallingAddr = ma.encapsulate(`/p2p/${this.peerId.toString(base58btc)}`)
signallingAddr = ma.encapsulate(`/p2p/${this.peerId.toString()}`)
} else {
signallingAddr = ma
}
Expand Down Expand Up @@ -258,7 +257,7 @@ class WebRTCListener extends EventEmitter<ListenerEvents> implements Listener {

if (conn.remoteAddr == null) {
try {
conn.remoteAddr = ma.decapsulateCode(CODE_P2P).encapsulate(`/p2p/${conn.remotePeer.toString(base58btc)}`)
conn.remoteAddr = ma.decapsulateCode(CODE_P2P).encapsulate(`/p2p/${conn.remotePeer.toString()}`)
} catch (err) {
log.error('could not determine remote address', err)
}
Expand Down
21 changes: 4 additions & 17 deletions packages/webrtc-star-transport/test/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,18 @@

import { WebRTCStar } from '../src/index.js'
import { createEd25519PeerId } from '@libp2p/peer-id-factory'
import { mockRegistrar, mockUpgrader } from '@libp2p/interface-compliance-tests/mocks'
import dialTests from './transport/dial.js'
import listenTests from './transport/listen.js'
import discoveryTests from './transport/discovery.js'
import filterTests from './transport/filter.js'
import { pipe } from 'it-pipe'
import { Components } from '@libp2p/interfaces/components'

describe('browser RTC', () => {
const create = async () => {
const protocol = '/echo/1.0.0'
const registrar = mockRegistrar()
void registrar.handle(protocol, (evt) => {
void pipe(
evt.detail.stream,
evt.detail.stream
)
})
const upgrader = mockUpgrader({
registrar
})
const ws = new WebRTCStar()
ws.init(new Components({ peerId: await createEd25519PeerId() }))

return new WebRTCStar({
peerId: await createEd25519PeerId(),
upgrader
})
return ws
}

dialTests(create)
Expand Down
32 changes: 19 additions & 13 deletions packages/webrtc-star-transport/test/compliance.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,16 @@ import { Multiaddr } from '@multiformats/multiaddr'
import testsTransport from '@libp2p/interface-compliance-tests/transport'
import testsDiscovery from '@libp2p/interface-compliance-tests/peer-discovery'
import { WebRTCStar } from '../src/index.js'
import { mockUpgrader } from '@libp2p/interface-compliance-tests/mocks'
import pWaitFor from 'p-wait-for'
import { peerIdFromString } from '@libp2p/peer-id'
import { Components } from '@libp2p/interfaces/components'

describe('interface-transport compliance', function () {
testsTransport({
async setup (args) {
if (args == null) {
throw new Error('No args')
}

const { upgrader } = args
async setup () {
const peerId = peerIdFromString('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')
const ws = new WebRTCStar({ upgrader, wrtc, peerId })
const ws = new WebRTCStar({ wrtc })
ws.init(new Components({ peerId }))

const base = (id: string) => {
return `/ip4/127.0.0.1/tcp/15555/ws/p2p-webrtc-star/p2p/${id}`
Expand All @@ -47,19 +43,28 @@ describe('interface-transport compliance', function () {
})

describe('interface-discovery compliance', () => {
let intervalId: NodeJS.Timer
let intervalId: ReturnType<typeof setInterval>
let running: boolean = false

testsDiscovery({
async setup () {
const peerId = peerIdFromString('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2d')
const ws = new WebRTCStar({ upgrader: mockUpgrader(), wrtc, peerId })
const ws = new WebRTCStar({ wrtc })
ws.init(new Components({ peerId }))
const maStr = '/ip4/127.0.0.1/tcp/15555/ws/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2d'

// only discover peers while discovery is running
void pWaitFor(() => ws.discovery.isStarted())
const discovery = ws.discovery
running = true

// only discover peers while the test is running and after discovery has been started
void pWaitFor(() => !running || discovery.isStarted())
.then(() => {
if (!running) {
return
}

intervalId = setInterval(() => {
if (ws.discovery.isStarted()) {
if (discovery.isStarted()) {
ws.peerDiscovered(maStr)
}
}, 1000)
Expand All @@ -72,6 +77,7 @@ describe('interface-discovery compliance', () => {
return ws.discovery
},
async teardown () {
running = false
clearInterval(intervalId)
}
})
Expand Down
16 changes: 9 additions & 7 deletions packages/webrtc-star-transport/test/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import wrtc from 'wrtc'
// @ts-expect-error no types
import electronWebRTC from 'electron-webrtc'
import { createEd25519PeerId } from '@libp2p/peer-id-factory'
import { mockUpgrader } from '@libp2p/interface-compliance-tests/mocks'
import { WebRTCStar } from '../src/index.js'
import dialTests from './transport/dial.js'
import listenTests from './transport/listen.js'
Expand All @@ -14,15 +13,17 @@ import filterTests from './transport/filter.js'
import multipleSignalServersTests from './transport/multiple-signal-servers.js'
import trackTests from './transport/track.js'
import reconnectTests from './transport/reconnect.node.js'
import { Components } from '@libp2p/interfaces/components'

describe('transport: with wrtc', () => {
const create = async () => {
const peerId = await createEd25519PeerId()
return new WebRTCStar({
peerId,
upgrader: mockUpgrader(),
const ws = new WebRTCStar({
wrtc
})
ws.init(new Components({ peerId }))

return ws
}

dialTests(create)
Expand All @@ -38,11 +39,12 @@ describe('transport: with wrtc', () => {
describe.skip('transport: with electron-webrtc', () => {
const create = async () => {
const peerId = await createEd25519PeerId()
return new WebRTCStar({
peerId,
upgrader: mockUpgrader(),
const ws = new WebRTCStar({
wrtc: electronWebRTC()
})
ws.init(new Components({ peerId }))

return ws
}

dialTests(create)
Expand Down
Loading

0 comments on commit 19bdc4e

Please sign in to comment.