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

fix: update multiaddr in webrtc connection to include webRTC #121

Merged
merged 1 commit into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/browser-to-browser/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
<input type="text" id="message" value="hello" />
<button id="send">Send</button>
</div>
<div id="connectionsWrapper">
<h3> Active Connections: </h3>
<ul id="connections"></ul>
</div>
<div id="connected_peer"></div>
<div id="output"></div>
</div>
Expand Down
19 changes: 19 additions & 0 deletions examples/browser-to-browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ await node.handle("/echo/1.0.0", ({ stream }) => {
)
})

function updateConnList() {
// Update connections list
const connListEls = node.getConnections()
.map((connection) => { return connection.remoteAddr.toString() })
.map((addr) => {
const el = document.createElement("li")
el.textContent = addr
return el
})
document.getElementById("connections").replaceChildren(...connListEls)
}

node.addEventListener("peer:connect", (event) => {
updateConnList()
})
node.addEventListener("peer:disconnect", (event) => {
updateConnList()
})

node.peerStore.addEventListener("change:multiaddrs", (event) => {
const { peerId } = event.detail

Expand Down
6 changes: 6 additions & 0 deletions examples/browser-to-browser/tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ play.describe('browser to browser example:', () => {
// Received message '${message}'
expect(connections).toContain(`Sending message '${message}'`)
expect(connections).toContain(`Received message '${message}'`)

const connListFromPage = await page.textContent('#connections')
const connListFromPageTwo = await pageTwo.textContent('#connections')
// Expect to see the webrtc multiaddr in the connections list
expect(connListFromPage).toContain('/webrtc/')
expect(connListFromPageTwo).toContain('/webrtc/')
})
})

Expand Down
44 changes: 27 additions & 17 deletions src/peer_transport/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { TransportManager, Upgrader } from '@libp2p/interface-transport'
import { multiaddr, Multiaddr, protocols } from '@multiformats/multiaddr'
import type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'
import type { PeerId } from '@libp2p/interface-peer-id'
import { peerIdFromString } from '@libp2p/peer-id'
import { WebRTCMultiaddrConnection } from '../maconn.js'
import type { Startable } from '@libp2p/interfaces/startable'
import { WebRTCPeerListener } from './listener.js'
Expand Down Expand Up @@ -75,15 +76,7 @@ export class WebRTCTransport implements Transport, Startable {
})
}

/*
* dial connects to a remote via the circuit relay or any other protocol
* and proceeds to upgrade to a webrtc connection.
* multiaddr of the form: <multiaddr>/webrtc/p2p/<destination-peer>
* For a circuit relay, this will be of the form
* <relay address>/p2p/<relay-peer>/p2p-circuit/webrtc/p2p/<destination-peer>
*/
async dial (ma: Multiaddr, options: DialOptions): Promise<Connection> {
log.trace('dialing address: ', ma)
private splitAddr (ma: Multiaddr): { baseAddr: Multiaddr, peerId: PeerId } {
const addrs = ma.toString().split(`${TRANSPORT}/`)
if (addrs.length !== 2) {
maschad marked this conversation as resolved.
Show resolved Hide resolved
throw new CodeError('invalid multiaddr', codes.ERR_INVALID_MULTIADDR)
Expand All @@ -97,11 +90,6 @@ export class WebRTCTransport implements Transport, Startable {
throw new CodeError('bad destination', codes.ERR_INVALID_MULTIADDR)
}

if (options.signal == null) {
const controller = new AbortController()
options.signal = controller.signal
}

const lastProtoInRemote = remoteAddr.protos().pop()
if (lastProtoInRemote === undefined) {
throw new CodeError('invalid multiaddr', codes.ERR_INVALID_MULTIADDR)
Expand All @@ -110,7 +98,26 @@ export class WebRTCTransport implements Transport, Startable {
remoteAddr = remoteAddr.encapsulate(`/p2p/${destinationIdString}`)
}

const connection = await this.components.transportManager.dial(remoteAddr)
return { baseAddr: remoteAddr, peerId: peerIdFromString(destinationIdString) }
}

/*
* dial connects to a remote via the circuit relay or any other protocol
* and proceeds to upgrade to a webrtc connection.
* multiaddr of the form: <multiaddr>/webrtc/p2p/<destination-peer>
* For a circuit relay, this will be of the form
* <relay address>/p2p/<relay-peer>/p2p-circuit/webrtc/p2p/<destination-peer>
*/
async dial (ma: Multiaddr, options: DialOptions): Promise<Connection> {
log.trace('dialing address: ', ma)
const { baseAddr, peerId } = this.splitAddr(ma)

if (options.signal == null) {
const controller = new AbortController()
options.signal = controller.signal
}

const connection = await this.components.transportManager.dial(baseAddr)

const rawStream = await connection.newStream([SIGNALING_PROTO_ID], options)

Expand All @@ -120,11 +127,12 @@ export class WebRTCTransport implements Transport, Startable {
rtcConfiguration: this.init.rtcConfiguration,
signal: options.signal
})
const webrtcMultiaddr = baseAddr.encapsulate(`${TRANSPORT}/p2p/${peerId.toString()}`)
const result = await options.upgrader.upgradeOutbound(
new WebRTCMultiaddrConnection({
peerConnection: pc,
timeline: { open: (new Date()).getTime() },
remoteAddr: connection.remoteAddr
remoteAddr: webrtcMultiaddr
}),
{
skipProtection: true,
Expand All @@ -150,10 +158,12 @@ export class WebRTCTransport implements Transport, Startable {
connection,
stream
})
const remotePeerId = connection.remoteAddr.getPeerId()
const webrtcMultiaddr = connection.remoteAddr.encapsulate(`${TRANSPORT}/p2p/${remotePeerId}`)
await this.components.upgrader.upgradeInbound(new WebRTCMultiaddrConnection({
peerConnection: pc,
timeline: { open: (new Date()).getTime() },
remoteAddr: connection.remoteAddr
remoteAddr: webrtcMultiaddr
}), {
skipEncryption: true,
skipProtection: true,
Expand Down