From fad3074b843cae69289c6da94f3797d59879ec1c Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Wed, 13 Mar 2024 14:17:59 +0100 Subject: [PATCH] docs: update webrtc readme to show difference between transports (#2441) Documents the difference between WebRTC and WebRTC Direct. --- packages/transport-webrtc/README.md | 159 ++++++++++++++++++++++++- packages/transport-webrtc/src/index.ts | 159 ++++++++++++++++++++++++- 2 files changed, 308 insertions(+), 10 deletions(-) diff --git a/packages/transport-webrtc/README.md b/packages/transport-webrtc/README.md index 0872cd7327..3f6703d550 100644 --- a/packages/transport-webrtc/README.md +++ b/packages/transport-webrtc/README.md @@ -26,20 +26,168 @@ repo and examine the changes made. A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebRTC datachannels](https://webrtc.org/). -## Example +[WebRTC](https://www.w3.org/TR/webrtc/) is a specification that allows real-time communication between nodes - it's commonly used in browser video conferencing applications but it also provides a reliable data transport mechanism called [data channels](https://www.w3.org/TR/webrtc/#peer-to-peer-data-api) which libp2p uses to facilitate [protocol streams](https://docs.libp2p.io/concepts/multiplex/overview/) between peers. + +There are two transports exposed by this module, [webRTC](https://github.com/libp2p/specs/blob/master/webrtc/webrtc.md) and [webRTCDirect](https://github.com/libp2p/specs/blob/master/webrtc/webrtc-direct.md). + +## WebRTC vs WebRTC Direct + +The connection establishment phase of WebRTC involves a handshake using [SDP](https://en.wikipedia.org/wiki/Session_Description_Protocol) during which two peers will exchange information such as open ports, network addresses and required capabilities. + +A third party is usually necessary to carry out this handshake, forwarding messages between the two peers until they can make a direct connection between themselves. + +The WebRTC transport uses libp2p [Circuit Relay](https://docs.libp2p.io/concepts/nat/circuit-relay/)s to forward SDP messages. Once a direct connection is formed the relay plays no further part in the exchange. + +WebRTC Direct uses a technique known as [SDP munging](https://webrtchacks.com/not-a-guide-to-sdp-munging/) to skip the handshake step, instead encoding enough information in the connection request that the responder can derive what would have been in the handshake messages and so requires no third parties to establish a connection. + +A WebRTC Direct multiaddr also includes a certhash of the target peer - this is used to allow opening a connection to the remote, which would otherwise be denied due to use of a self-signed certificate. + +In both cases, once the connection is established a [Noise handshake](https://noiseprotocol.org/noise.html) is carried out to ensure that the remote peer has the private key that corresponds to the public key that makes up their PeerId, giving you both encryption and authentication. + +## Support + +WebRTC is supported in both Node.js and browsers. + +At the time of writing, WebRTC Direct is dial-only in browsers and not supported in Node.js at all. + +Support in Node.js is possible but PRs will need to be opened to [libdatachannel](https://github.com/paullouisageneau/libdatachannel) and the appropriate APIs exposed in [node-datachannel](https://github.com/murat-dogan/node-datachannel). + +For both WebRTC and WebRTC Direct, support is arriving soon in go-libp2p but they are unsupported in rust-libp2p. + +See the WebRTC section of for more information. + +## Example - WebRTC + +WebRTC requires use of a relay to connect two nodes. The listener first discovers a relay server and makes a reservation, then the dialer can connect via the relayed address. + +```TypeScript +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { echo } from '@libp2p/echo' +import { circuitRelayTransport, circuitRelayServer } from '@libp2p/circuit-relay-v2' +import { identify } from '@libp2p/identify' +import { webRTC } from '@libp2p/webrtc' +import { webSockets } from '@libp2p/websockets' +import * as filters from '@libp2p/websockets/filters' +import { WebRTC } from '@multiformats/multiaddr-matcher' +import delay from 'delay' +import { pipe } from 'it-pipe' +import { createLibp2p } from 'libp2p' +import type { Multiaddr } from '@multiformats/multiaddr' + +// the relay server listens on a transport dialable by the listener and the +// dialer, and has a relay service configured +const relay = await createLibp2p({ + addresses: { + listen: ['/ip4/127.0.0.1/tcp/0/ws'] + }, + transports: [ + webSockets({filter: filters.all}) + ], + connectionEncryption: [noise()], + streamMuxers: [yamux()], + services: { + identify: identify(), + relay: circuitRelayServer() + } +}) + +// the listener has a WebSocket transport to dial the relay, a Circuit Relay +// transport to make a reservation, and a WebRTC transport to accept incoming +// WebRTC connections +const listener = await createLibp2p({ + addresses: { + listen: ['/webrtc'] + }, + transports: [ + webSockets({filter: filters.all}), + webRTC(), + circuitRelayTransport({ + discoverRelays: 1 + }) + ], + connectionEncryption: [noise()], + streamMuxers: [yamux()], + services: { + identify: identify(), + echo: echo() + } +}) + +// the listener dials the relay (or discovers a public relay via some other +// method) +await listener.dial(relay.getMultiaddrs(), { + signal: AbortSignal.timeout(5000) +}) + +let webRTCMultiaddr: Multiaddr | undefined + +// wait for the listener to make a reservation on the relay +while (true) { + webRTCMultiaddr = listener.getMultiaddrs().find(ma => WebRTC.matches(ma)) + + if (webRTCMultiaddr != null) { + break + } + + // try again later + await delay(1000) +} + +// the listener has Circuit Relay, WebSocket and WebRTC transports to dial +// the listener via the relay, complete the SDP handshake and establish a +// direct WebRTC connection +const dialer = await createLibp2p({ + transports: [ + webSockets({filter: filters.all}), + webRTC(), + circuitRelayTransport() + ], + connectionEncryption: [noise()], + streamMuxers: [yamux()], + services: { + identify: identify(), + echo: echo() + } +}) + +// dial the listener and open an echo protocol stream +const stream = await dialer.dialProtocol(webRTCMultiaddr, dialer.services.echo.protocol, { + signal: AbortSignal.timeout(5000) +}) + +// we can now stop the relay +await relay.stop() + +// send/receive some data from the remote peer via a direct connection +await pipe( + [new TextEncoder().encode('hello world')], + stream, + async source => { + for await (const buf of source) { + console.info(new TextDecoder().decode(buf.subarray())) + } + } +) +``` + +## Example - WebRTC Direct + +At the time of writing WebRTC Direct is dial-only in browsers and unsupported in Node.js. + +The only implementation that supports a WebRTC Direct listener is go-libp2p and it's not yet enabled by default. ```TypeScript import { createLibp2p } from 'libp2p' import { noise } from '@chainsafe/libp2p-noise' import { multiaddr } from '@multiformats/multiaddr' -import first from 'it-first' import { pipe } from 'it-pipe' import { fromString, toString } from 'uint8arrays' -import { webRTC } from '@libp2p/webrtc' +import { webRTCDirect } from '@libp2p/webrtc' const node = await createLibp2p({ transports: [ - webRTC() + webRTCDirect() ], connectionEncryption: [ noise() @@ -48,7 +196,8 @@ const node = await createLibp2p({ await node.start() -const ma = multiaddr('/ip4/0.0.0.0/udp/56093/webrtc/certhash/uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ') +// this multiaddr corresponds to a remote node running a WebRTC Direct listener +const ma = multiaddr('/ip4/0.0.0.0/udp/56093/webrtc-direct/certhash/uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ') const stream = await node.dialProtocol(ma, '/my-protocol/1.0.0', { signal: AbortSignal.timeout(10_000) }) diff --git a/packages/transport-webrtc/src/index.ts b/packages/transport-webrtc/src/index.ts index 2898a51217..a21ae0a9a3 100644 --- a/packages/transport-webrtc/src/index.ts +++ b/packages/transport-webrtc/src/index.ts @@ -3,20 +3,168 @@ * * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebRTC datachannels](https://webrtc.org/). * - * @example + * [WebRTC](https://www.w3.org/TR/webrtc/) is a specification that allows real-time communication between nodes - it's commonly used in browser video conferencing applications but it also provides a reliable data transport mechanism called [data channels](https://www.w3.org/TR/webrtc/#peer-to-peer-data-api) which libp2p uses to facilitate [protocol streams](https://docs.libp2p.io/concepts/multiplex/overview/) between peers. + * + * There are two transports exposed by this module, [webRTC](https://github.com/libp2p/specs/blob/master/webrtc/webrtc.md) and [webRTCDirect](https://github.com/libp2p/specs/blob/master/webrtc/webrtc-direct.md). + * + * ## WebRTC vs WebRTC Direct + * + * The connection establishment phase of WebRTC involves a handshake using [SDP](https://en.wikipedia.org/wiki/Session_Description_Protocol) during which two peers will exchange information such as open ports, network addresses and required capabilities. + * + * A third party is usually necessary to carry out this handshake, forwarding messages between the two peers until they can make a direct connection between themselves. + * + * The WebRTC transport uses libp2p [Circuit Relay](https://docs.libp2p.io/concepts/nat/circuit-relay/)s to forward SDP messages. Once a direct connection is formed the relay plays no further part in the exchange. + * + * WebRTC Direct uses a technique known as [SDP munging](https://webrtchacks.com/not-a-guide-to-sdp-munging/) to skip the handshake step, instead encoding enough information in the connection request that the responder can derive what would have been in the handshake messages and so requires no third parties to establish a connection. + * + * A WebRTC Direct multiaddr also includes a certhash of the target peer - this is used to allow opening a connection to the remote, which would otherwise be denied due to use of a self-signed certificate. + * + * In both cases, once the connection is established a [Noise handshake](https://noiseprotocol.org/noise.html) is carried out to ensure that the remote peer has the private key that corresponds to the public key that makes up their PeerId, giving you both encryption and authentication. + * + * ## Support + * + * WebRTC is supported in both Node.js and browsers. + * + * At the time of writing, WebRTC Direct is dial-only in browsers and not supported in Node.js at all. + * + * Support in Node.js is possible but PRs will need to be opened to [libdatachannel](https://github.com/paullouisageneau/libdatachannel) and the appropriate APIs exposed in [node-datachannel](https://github.com/murat-dogan/node-datachannel). + * + * For both WebRTC and WebRTC Direct, support is arriving soon in go-libp2p but they are unsupported in rust-libp2p. + * + * See the WebRTC section of https://connectivity.libp2p.io for more information. + * + * @example WebRTC + * + * WebRTC requires use of a relay to connect two nodes. The listener first discovers a relay server and makes a reservation, then the dialer can connect via the relayed address. + * + * ```TypeScript + * import { noise } from '@chainsafe/libp2p-noise' + * import { yamux } from '@chainsafe/libp2p-yamux' + * import { echo } from '@libp2p/echo' + * import { circuitRelayTransport, circuitRelayServer } from '@libp2p/circuit-relay-v2' + * import { identify } from '@libp2p/identify' + * import { webRTC } from '@libp2p/webrtc' + * import { webSockets } from '@libp2p/websockets' + * import * as filters from '@libp2p/websockets/filters' + * import { WebRTC } from '@multiformats/multiaddr-matcher' + * import delay from 'delay' + * import { pipe } from 'it-pipe' + * import { createLibp2p } from 'libp2p' + * import type { Multiaddr } from '@multiformats/multiaddr' + * + * // the relay server listens on a transport dialable by the listener and the + * // dialer, and has a relay service configured + * const relay = await createLibp2p({ + * addresses: { + * listen: ['/ip4/127.0.0.1/tcp/0/ws'] + * }, + * transports: [ + * webSockets({filter: filters.all}) + * ], + * connectionEncryption: [noise()], + * streamMuxers: [yamux()], + * services: { + * identify: identify(), + * relay: circuitRelayServer() + * } + * }) + * + * // the listener has a WebSocket transport to dial the relay, a Circuit Relay + * // transport to make a reservation, and a WebRTC transport to accept incoming + * // WebRTC connections + * const listener = await createLibp2p({ + * addresses: { + * listen: ['/webrtc'] + * }, + * transports: [ + * webSockets({filter: filters.all}), + * webRTC(), + * circuitRelayTransport({ + * discoverRelays: 1 + * }) + * ], + * connectionEncryption: [noise()], + * streamMuxers: [yamux()], + * services: { + * identify: identify(), + * echo: echo() + * } + * }) + * + * // the listener dials the relay (or discovers a public relay via some other + * // method) + * await listener.dial(relay.getMultiaddrs(), { + * signal: AbortSignal.timeout(5000) + * }) + * + * let webRTCMultiaddr: Multiaddr | undefined + * + * // wait for the listener to make a reservation on the relay + * while (true) { + * webRTCMultiaddr = listener.getMultiaddrs().find(ma => WebRTC.matches(ma)) + * + * if (webRTCMultiaddr != null) { + * break + * } + * + * // try again later + * await delay(1000) + * } + * + * // the listener has Circuit Relay, WebSocket and WebRTC transports to dial + * // the listener via the relay, complete the SDP handshake and establish a + * // direct WebRTC connection + * const dialer = await createLibp2p({ + * transports: [ + * webSockets({filter: filters.all}), + * webRTC(), + * circuitRelayTransport() + * ], + * connectionEncryption: [noise()], + * streamMuxers: [yamux()], + * services: { + * identify: identify(), + * echo: echo() + * } + * }) + * + * // dial the listener and open an echo protocol stream + * const stream = await dialer.dialProtocol(webRTCMultiaddr, dialer.services.echo.protocol, { + * signal: AbortSignal.timeout(5000) + * }) + * + * // we can now stop the relay + * await relay.stop() + * + * // send/receive some data from the remote peer via a direct connection + * await pipe( + * [new TextEncoder().encode('hello world')], + * stream, + * async source => { + * for await (const buf of source) { + * console.info(new TextDecoder().decode(buf.subarray())) + * } + * } + * ) + * ``` + * + * @example WebRTC Direct + * + * At the time of writing WebRTC Direct is dial-only in browsers and unsupported in Node.js. + * + * The only implementation that supports a WebRTC Direct listener is go-libp2p and it's not yet enabled by default. * * ```TypeScript * import { createLibp2p } from 'libp2p' * import { noise } from '@chainsafe/libp2p-noise' * import { multiaddr } from '@multiformats/multiaddr' - * import first from 'it-first' * import { pipe } from 'it-pipe' * import { fromString, toString } from 'uint8arrays' - * import { webRTC } from '@libp2p/webrtc' + * import { webRTCDirect } from '@libp2p/webrtc' * * const node = await createLibp2p({ * transports: [ - * webRTC() + * webRTCDirect() * ], * connectionEncryption: [ * noise() @@ -25,7 +173,8 @@ * * await node.start() * - * const ma = multiaddr('/ip4/0.0.0.0/udp/56093/webrtc/certhash/uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ') + * // this multiaddr corresponds to a remote node running a WebRTC Direct listener + * const ma = multiaddr('/ip4/0.0.0.0/udp/56093/webrtc-direct/certhash/uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ') * const stream = await node.dialProtocol(ma, '/my-protocol/1.0.0', { * signal: AbortSignal.timeout(10_000) * })