-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathlibp2p.ts
More file actions
196 lines (171 loc) · 7.27 KB
/
libp2p.ts
File metadata and controls
196 lines (171 loc) · 7.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import {
createDelegatedRoutingV1HttpApiClient,
DelegatedRoutingV1HttpApiClient,
} from '@helia/delegated-routing-v1-http-api-client'
import { createLibp2p } from 'libp2p'
import { identify } from '@libp2p/identify'
import { peerIdFromString } from '@libp2p/peer-id'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { bootstrap } from '@libp2p/bootstrap'
import { Multiaddr } from '@multiformats/multiaddr'
import { sha256 } from 'multiformats/hashes/sha2'
import type { Connection, Message, SignedMessage, PeerId, Libp2p } from '@libp2p/interface'
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
import { webSockets } from '@libp2p/websockets'
import { webTransport } from '@libp2p/webtransport'
import { webRTC, webRTCDirect } from '@libp2p/webrtc'
import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'
import { ping } from '@libp2p/ping'
import { BOOTSTRAP_PEER_IDS, CHAT_FILE_TOPIC, CHAT_TOPIC, PUBSUB_PEER_DISCOVERY } from './constants'
import first from 'it-first'
import { forComponent, enable } from './logger'
import { directMessage } from './direct-message'
import type { Libp2pType } from '@/context/ctx'
const log = forComponent('libp2p')
export async function startLibp2p(): Promise<Libp2pType> {
// enable verbose logging in browser console to view debug logs
enable('ui*,libp2p*,-libp2p:connection-manager*,-*:trace')
const delegatedClient = createDelegatedRoutingV1HttpApiClient('https://delegated-ipfs.dev')
const { bootstrapAddrs, relayListenAddrs } = await getBootstrapMultiaddrs(delegatedClient)
log('starting libp2p with bootstrapAddrs %o and relayListenAddrs: %o', bootstrapAddrs, relayListenAddrs)
let libp2p: Libp2pType
libp2p = await createLibp2p({
addresses: {
listen: [
// 👇 Listen for webRTC connection
'/webrtc',
...relayListenAddrs,
],
},
transports: [
webTransport(),
webSockets(),
webRTC(),
// 👇 Required to estalbish connections with peers supporting WebRTC-direct, e.g. the Rust-peer
webRTCDirect(),
// 👇 Required to create circuit relay reservations in order to hole punch browser-to-browser WebRTC connections
circuitRelayTransport(),
],
connectionEncrypters: [noise()],
streamMuxers: [yamux()],
connectionGater: {
denyDialMultiaddr: async () => false,
},
peerDiscovery: [
pubsubPeerDiscovery({
interval: 10_000,
topics: [PUBSUB_PEER_DISCOVERY],
listenOnly: false,
}),
bootstrap({
// The app-specific bootstrappers that use WebTransport and WebRTC-direct and have ephemeral multiadrrs
// that are resolved above using the delegated routing API
list: bootstrapAddrs
}),
],
services: {
pubsub: gossipsub({
allowPublishToZeroTopicPeers: true,
msgIdFn: msgIdFnStrictNoSign,
ignoreDuplicatePublishError: true,
}),
// Delegated routing helps us discover the ephemeral multiaddrs of the dedicated go and rust bootstrap peers
// This relies on the public delegated routing endpoint https://docs.ipfs.tech/concepts/public-utilities/#delegated-routing
delegatedRouting: () => delegatedClient,
identify: identify(),
// Custom protocol for direct messaging
directMessage: directMessage(),
ping: ping(),
},
})
if (!libp2p) {
throw new Error('Failed to create libp2p node')
}
libp2p.services.pubsub.subscribe(CHAT_TOPIC)
libp2p.services.pubsub.subscribe(CHAT_FILE_TOPIC)
libp2p.addEventListener('self:peer:update', ({ detail: { peer } }) => {
const multiaddrs = peer.addresses.map(({ multiaddr }) => multiaddr)
log(`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`)
})
// 👇 explicitly dial peers discovered via pubsub
libp2p.addEventListener('peer:discovery', (event) => {
const { multiaddrs, id } = event.detail
if (libp2p.getConnections(id)?.length > 0) {
log(`Already connected to peer %s. Will not try dialling`, id)
return
}
dialWebRTCMaddrs(libp2p, multiaddrs)
})
return libp2p
}
// message IDs are used to dedupe inbound messages
// every agent in network should use the same message id function
// messages could be perceived as duplicate if this isnt added (as opposed to rust peer which has unique message ids)
export async function msgIdFnStrictNoSign(msg: Message): Promise<Uint8Array> {
var enc = new TextEncoder()
const signedMessage = msg as SignedMessage
const encodedSeqNum = enc.encode(signedMessage.sequenceNumber.toString())
return await sha256.encode(encodedSeqNum)
}
// Function which dials one maddr at a time to avoid establishing multiple connections to the same peer
async function dialWebRTCMaddrs(libp2p: Libp2p, multiaddrs: Multiaddr[]): Promise<void> {
// Filter webrtc (browser-to-browser) multiaddrs
const webRTCMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('webrtc'))
log(`dialling WebRTC multiaddrs: %o`, webRTCMadrs)
for (const addr of webRTCMadrs) {
try {
log(`attempting to dial webrtc multiaddr: %o`, addr)
await libp2p.dial(addr)
return // if we succeed dialing the peer, no need to try another address
} catch (error) {
log.error(`failed to dial webrtc multiaddr: %o`, addr)
}
}
}
export const connectToMultiaddr = (libp2p: Libp2p) => async (multiaddr: Multiaddr) => {
log(`dialling: %a`, multiaddr)
try {
const conn = await libp2p.dial(multiaddr)
log('connected to %p on %a', conn.remotePeer, conn.remoteAddr)
return conn
} catch (e) {
console.error(e)
throw e
}
}
// Function which resolves PeerIDs of rust/go bootstrap nodes to multiaddrs dialable from the browser
// Returns both the dialable multiaddrs in addition to the relay
async function getBootstrapMultiaddrs(client: DelegatedRoutingV1HttpApiClient): Promise<BootstrapsMultiaddrs> {
const peers = await Promise.all(BOOTSTRAP_PEER_IDS.map((peerId) => first(client.getPeers(peerIdFromString(peerId)))))
const bootstrapAddrs = []
const relayListenAddrs = []
for (const p of peers) {
if (p && p.Addrs.length > 0) {
for (const maddr of p.Addrs) {
const protos = maddr.protoNames()
if ((protos.includes('webtransport') || protos.includes('webrtc-direct')) && protos.includes('certhash')) {
if (maddr.nodeAddress().address === '127.0.0.1') continue // skip loopback
bootstrapAddrs.push(maddr.toString())
relayListenAddrs.push(getRelayListenAddr(maddr, p.ID))
}
}
}
}
return { bootstrapAddrs, relayListenAddrs }
}
interface BootstrapsMultiaddrs {
// Multiaddrs that are dialable from the browser
bootstrapAddrs: string[]
// multiaddr string representing the circuit relay v2 listen addr
relayListenAddrs: string[]
}
// Constructs a multiaddr string representing the circuit relay v2 listen address for a relayed connection to the given peer.
const getRelayListenAddr = (maddr: Multiaddr, peer: PeerId): string =>
`${maddr.toString()}/p2p/${peer.toString()}/p2p-circuit`
export const getFormattedConnections = (connections: Connection[]) =>
connections.map((conn) => ({
peerId: conn.remotePeer,
protocols: [...new Set(conn.remoteAddr.protoNames())],
}))