libp2p 0.42.2-45fc415b → 0.42.2-5e63ee2d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/dist/index.min.js +28 -28
  2. package/dist/src/address-manager/index.d.ts +1 -10
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/address-manager/index.js +46 -29
  5. package/dist/src/address-manager/index.js.map +1 -1
  6. package/dist/src/autonat/constants.d.ts +4 -0
  7. package/dist/src/autonat/constants.d.ts.map +1 -0
  8. package/dist/src/autonat/constants.js +4 -0
  9. package/dist/src/autonat/constants.js.map +1 -0
  10. package/dist/src/autonat/index.d.ts +64 -0
  11. package/dist/src/autonat/index.d.ts.map +1 -0
  12. package/dist/src/autonat/index.js +417 -0
  13. package/dist/src/autonat/index.js.map +1 -0
  14. package/dist/src/autonat/pb/index.d.ts +57 -0
  15. package/dist/src/autonat/pb/index.d.ts.map +1 -0
  16. package/dist/src/autonat/pb/index.js +250 -0
  17. package/dist/src/autonat/pb/index.js.map +1 -0
  18. package/dist/src/circuit/constants.d.ts +31 -6
  19. package/dist/src/circuit/constants.d.ts.map +1 -1
  20. package/dist/src/circuit/constants.js +37 -7
  21. package/dist/src/circuit/constants.js.map +1 -1
  22. package/dist/src/circuit/index.d.ts +16 -61
  23. package/dist/src/circuit/index.d.ts.map +1 -1
  24. package/dist/src/circuit/index.js +2 -68
  25. package/dist/src/circuit/index.js.map +1 -1
  26. package/dist/src/circuit/pb/index.d.ts +83 -43
  27. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  28. package/dist/src/circuit/pb/index.js +363 -127
  29. package/dist/src/circuit/pb/index.js.map +1 -1
  30. package/dist/src/circuit/server/advert-service.d.ts +43 -0
  31. package/dist/src/circuit/server/advert-service.d.ts.map +1 -0
  32. package/dist/src/circuit/server/advert-service.js +69 -0
  33. package/dist/src/circuit/server/advert-service.js.map +1 -0
  34. package/dist/src/circuit/server/index.d.ts +60 -0
  35. package/dist/src/circuit/server/index.d.ts.map +1 -0
  36. package/dist/src/circuit/server/index.js +287 -0
  37. package/dist/src/circuit/server/index.js.map +1 -0
  38. package/dist/src/circuit/server/reservation-store.d.ts +49 -0
  39. package/dist/src/circuit/server/reservation-store.d.ts.map +1 -0
  40. package/dist/src/circuit/server/reservation-store.js +57 -0
  41. package/dist/src/circuit/server/reservation-store.js.map +1 -0
  42. package/dist/src/circuit/server/reservation-voucher.d.ts +18 -0
  43. package/dist/src/circuit/server/reservation-voucher.d.ts.map +1 -0
  44. package/dist/src/circuit/server/reservation-voucher.js +33 -0
  45. package/dist/src/circuit/server/reservation-voucher.js.map +1 -0
  46. package/dist/src/circuit/transport/discovery.d.ts +45 -0
  47. package/dist/src/circuit/transport/discovery.d.ts.map +1 -0
  48. package/dist/src/circuit/transport/discovery.js +82 -0
  49. package/dist/src/circuit/transport/discovery.js.map +1 -0
  50. package/dist/src/circuit/transport/index.d.ts +33 -0
  51. package/dist/src/circuit/transport/index.d.ts.map +1 -0
  52. package/dist/src/circuit/transport/index.js +225 -0
  53. package/dist/src/circuit/transport/index.js.map +1 -0
  54. package/dist/src/circuit/transport/listener.d.ts +9 -0
  55. package/dist/src/circuit/transport/listener.d.ts.map +1 -0
  56. package/dist/src/circuit/transport/listener.js +76 -0
  57. package/dist/src/circuit/transport/listener.js.map +1 -0
  58. package/dist/src/circuit/transport/reservation-store.d.ts +60 -0
  59. package/dist/src/circuit/transport/reservation-store.d.ts.map +1 -0
  60. package/dist/src/circuit/transport/reservation-store.js +165 -0
  61. package/dist/src/circuit/transport/reservation-store.js.map +1 -0
  62. package/dist/src/circuit/utils.d.ts +7 -0
  63. package/dist/src/circuit/utils.d.ts.map +1 -1
  64. package/dist/src/circuit/utils.js +87 -0
  65. package/dist/src/circuit/utils.js.map +1 -1
  66. package/dist/src/components.d.ts +2 -1
  67. package/dist/src/components.d.ts.map +1 -1
  68. package/dist/src/components.js.map +1 -1
  69. package/dist/src/config.d.ts.map +1 -1
  70. package/dist/src/config.js +17 -21
  71. package/dist/src/config.js.map +1 -1
  72. package/dist/src/connection/index.d.ts +2 -2
  73. package/dist/src/connection/index.d.ts.map +1 -1
  74. package/dist/src/connection/index.js +1 -1
  75. package/dist/src/connection/index.js.map +1 -1
  76. package/dist/src/connection-manager/auto-dialler.d.ts +0 -4
  77. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  78. package/dist/src/connection-manager/auto-dialler.js +0 -9
  79. package/dist/src/connection-manager/auto-dialler.js.map +1 -1
  80. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  81. package/dist/src/connection-manager/dialer/dial-request.js +8 -1
  82. package/dist/src/connection-manager/dialer/dial-request.js.map +1 -1
  83. package/dist/src/connection-manager/dialer/index.d.ts +2 -1
  84. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  85. package/dist/src/connection-manager/dialer/index.js +3 -3
  86. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  87. package/dist/src/connection-manager/index.d.ts +0 -4
  88. package/dist/src/connection-manager/index.d.ts.map +1 -1
  89. package/dist/src/connection-manager/index.js +1 -1
  90. package/dist/src/connection-manager/index.js.map +1 -1
  91. package/dist/src/connection-manager/latency-monitor.d.ts.map +1 -1
  92. package/dist/src/connection-manager/latency-monitor.js +1 -1
  93. package/dist/src/connection-manager/latency-monitor.js.map +1 -1
  94. package/dist/src/connection-manager/visibility-change-emitter.d.ts.map +1 -1
  95. package/dist/src/content-routing/index.d.ts +6 -4
  96. package/dist/src/content-routing/index.d.ts.map +1 -1
  97. package/dist/src/content-routing/index.js +1 -1
  98. package/dist/src/content-routing/index.js.map +1 -1
  99. package/dist/src/content-routing/utils.d.ts +3 -3
  100. package/dist/src/content-routing/utils.d.ts.map +1 -1
  101. package/dist/src/dht/dht-content-routing.d.ts +2 -1
  102. package/dist/src/dht/dht-content-routing.d.ts.map +1 -1
  103. package/dist/src/dht/dht-content-routing.js.map +1 -1
  104. package/dist/src/dht/dht-peer-routing.d.ts +3 -2
  105. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  106. package/dist/src/dht/dht-peer-routing.js.map +1 -1
  107. package/dist/src/dht/dummy-dht.d.ts +1 -1
  108. package/dist/src/dht/dummy-dht.d.ts.map +1 -1
  109. package/dist/src/errors.d.ts +2 -1
  110. package/dist/src/errors.d.ts.map +1 -1
  111. package/dist/src/errors.js +1 -0
  112. package/dist/src/errors.js.map +1 -1
  113. package/dist/src/fetch/index.d.ts.map +1 -1
  114. package/dist/src/fetch/pb/proto.d.ts +3 -3
  115. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  116. package/dist/src/fetch/pb/proto.js +4 -3
  117. package/dist/src/fetch/pb/proto.js.map +1 -1
  118. package/dist/src/identify/index.d.ts +3 -1
  119. package/dist/src/identify/index.d.ts.map +1 -1
  120. package/dist/src/identify/index.js +12 -7
  121. package/dist/src/identify/index.js.map +1 -1
  122. package/dist/src/identify/pb/message.d.ts +2 -2
  123. package/dist/src/identify/pb/message.d.ts.map +1 -1
  124. package/dist/src/identify/pb/message.js +1 -0
  125. package/dist/src/identify/pb/message.js.map +1 -1
  126. package/dist/src/index.d.ts +13 -7
  127. package/dist/src/index.d.ts.map +1 -1
  128. package/dist/src/index.js.map +1 -1
  129. package/dist/src/insecure/index.d.ts.map +1 -1
  130. package/dist/src/insecure/index.js.map +1 -1
  131. package/dist/src/insecure/pb/proto.d.ts +3 -3
  132. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  133. package/dist/src/insecure/pb/proto.js +4 -5
  134. package/dist/src/insecure/pb/proto.js.map +1 -1
  135. package/dist/src/libp2p.d.ts +6 -2
  136. package/dist/src/libp2p.d.ts.map +1 -1
  137. package/dist/src/libp2p.js +19 -21
  138. package/dist/src/libp2p.js.map +1 -1
  139. package/dist/src/nat-manager.d.ts.map +1 -1
  140. package/dist/src/nat-manager.js +3 -1
  141. package/dist/src/nat-manager.js.map +1 -1
  142. package/dist/src/peer-record-updater.d.ts.map +1 -1
  143. package/dist/src/peer-routing.d.ts.map +1 -1
  144. package/dist/src/ping/index.d.ts.map +1 -1
  145. package/dist/src/pnet/crypto.d.ts +1 -1
  146. package/dist/src/pnet/crypto.d.ts.map +1 -1
  147. package/dist/src/pnet/crypto.js +1 -1
  148. package/dist/src/pnet/crypto.js.map +1 -1
  149. package/dist/src/pnet/key-generator.d.ts.map +1 -1
  150. package/dist/src/registrar.d.ts.map +1 -1
  151. package/dist/src/transport-manager.d.ts.map +1 -1
  152. package/dist/src/transport-manager.js +3 -4
  153. package/dist/src/transport-manager.js.map +1 -1
  154. package/dist/src/upgrader.d.ts +2 -1
  155. package/dist/src/upgrader.d.ts.map +1 -1
  156. package/dist/src/upgrader.js +19 -14
  157. package/dist/src/upgrader.js.map +1 -1
  158. package/package.json +32 -26
  159. package/src/address-manager/index.ts +62 -35
  160. package/src/autonat/constants.ts +4 -0
  161. package/src/autonat/index.ts +567 -0
  162. package/src/autonat/pb/index.proto +35 -0
  163. package/src/autonat/pb/index.ts +320 -0
  164. package/src/circuit/constants.ts +48 -7
  165. package/src/circuit/index.ts +17 -129
  166. package/src/circuit/pb/index.proto +57 -32
  167. package/src/circuit/pb/index.ts +448 -138
  168. package/src/circuit/server/advert-service.ts +108 -0
  169. package/src/circuit/server/index.ts +421 -0
  170. package/src/circuit/server/reservation-store.ts +111 -0
  171. package/src/circuit/server/reservation-voucher.ts +51 -0
  172. package/src/circuit/transport/discovery.ts +127 -0
  173. package/src/circuit/transport/index.ts +325 -0
  174. package/src/circuit/transport/listener.ts +99 -0
  175. package/src/circuit/transport/reservation-store.ts +249 -0
  176. package/src/circuit/utils.ts +108 -0
  177. package/src/components.ts +9 -8
  178. package/src/config.ts +17 -21
  179. package/src/connection/index.ts +7 -7
  180. package/src/connection-manager/auto-dialler.ts +4 -20
  181. package/src/connection-manager/dialer/dial-request.ts +8 -1
  182. package/src/connection-manager/dialer/index.ts +10 -9
  183. package/src/connection-manager/index.ts +14 -19
  184. package/src/connection-manager/latency-monitor.ts +9 -9
  185. package/src/connection-manager/visibility-change-emitter.ts +4 -4
  186. package/src/content-routing/index.ts +10 -8
  187. package/src/content-routing/utils.ts +3 -3
  188. package/src/dht/dht-content-routing.ts +3 -2
  189. package/src/dht/dht-peer-routing.ts +3 -2
  190. package/src/dht/dummy-dht.ts +1 -1
  191. package/src/errors.ts +2 -1
  192. package/src/fetch/index.ts +7 -7
  193. package/src/fetch/pb/proto.ts +8 -7
  194. package/src/identify/index.ts +22 -17
  195. package/src/identify/pb/message.ts +3 -2
  196. package/src/index.ts +14 -7
  197. package/src/insecure/index.ts +2 -1
  198. package/src/insecure/pb/proto.ts +8 -9
  199. package/src/libp2p.ts +33 -32
  200. package/src/nat-manager.ts +9 -7
  201. package/src/peer-record-updater.ts +4 -4
  202. package/src/peer-routing.ts +4 -4
  203. package/src/ping/index.ts +4 -4
  204. package/src/pnet/crypto.ts +3 -3
  205. package/src/pnet/key-generator.ts +1 -1
  206. package/src/registrar.ts +8 -8
  207. package/src/transport-manager.ts +12 -13
  208. package/src/upgrader.ts +24 -23
  209. package/src/version.ts +1 -1
  210. package/dist/src/circuit/auto-relay.d.ts +0 -46
  211. package/dist/src/circuit/auto-relay.d.ts.map +0 -1
  212. package/dist/src/circuit/auto-relay.js +0 -220
  213. package/dist/src/circuit/auto-relay.js.map +0 -1
  214. package/dist/src/circuit/circuit/hop.d.ts +0 -42
  215. package/dist/src/circuit/circuit/hop.d.ts.map +0 -1
  216. package/dist/src/circuit/circuit/hop.js +0 -142
  217. package/dist/src/circuit/circuit/hop.js.map +0 -1
  218. package/dist/src/circuit/circuit/stop.d.ts +0 -24
  219. package/dist/src/circuit/circuit/stop.d.ts.map +0 -1
  220. package/dist/src/circuit/circuit/stop.js +0 -51
  221. package/dist/src/circuit/circuit/stop.js.map +0 -1
  222. package/dist/src/circuit/circuit/stream-handler.d.ts +0 -40
  223. package/dist/src/circuit/circuit/stream-handler.d.ts.map +0 -1
  224. package/dist/src/circuit/circuit/stream-handler.js +0 -59
  225. package/dist/src/circuit/circuit/stream-handler.js.map +0 -1
  226. package/dist/src/circuit/circuit/utils.d.ts +0 -7
  227. package/dist/src/circuit/circuit/utils.d.ts.map +0 -1
  228. package/dist/src/circuit/circuit/utils.js +0 -43
  229. package/dist/src/circuit/circuit/utils.js.map +0 -1
  230. package/dist/src/circuit/listener.d.ts +0 -9
  231. package/dist/src/circuit/listener.d.ts.map +0 -1
  232. package/dist/src/circuit/listener.js +0 -62
  233. package/dist/src/circuit/listener.js.map +0 -1
  234. package/dist/src/circuit/multicodec.d.ts +0 -2
  235. package/dist/src/circuit/multicodec.d.ts.map +0 -1
  236. package/dist/src/circuit/multicodec.js +0 -2
  237. package/dist/src/circuit/multicodec.js.map +0 -1
  238. package/dist/src/circuit/transport.d.ts +0 -51
  239. package/dist/src/circuit/transport.d.ts.map +0 -1
  240. package/dist/src/circuit/transport.js +0 -223
  241. package/dist/src/circuit/transport.js.map +0 -1
  242. package/src/circuit/IMPLEMENTATION_NOTES.md +0 -128
  243. package/src/circuit/README.md +0 -111
  244. package/src/circuit/auto-relay.ts +0 -292
  245. package/src/circuit/circuit/hop.ts +0 -220
  246. package/src/circuit/circuit/stop.ts +0 -83
  247. package/src/circuit/circuit/stream-handler.ts +0 -87
  248. package/src/circuit/circuit/utils.ts +0 -44
  249. package/src/circuit/listener.ts +0 -83
  250. package/src/circuit/multicodec.ts +0 -2
  251. package/src/circuit/transport.ts +0 -278
@@ -1,292 +0,0 @@
1
- import { logger } from '@libp2p/logger'
2
- import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
3
- import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
4
- import { RELAY_CODEC } from './multicodec.js'
5
- import { canHop } from './circuit/hop.js'
6
- import { namespaceToCid } from './utils.js'
7
- import {
8
- CIRCUIT_PROTO_CODE,
9
- HOP_METADATA_KEY,
10
- HOP_METADATA_VALUE,
11
- RELAY_RENDEZVOUS_NS
12
- } from './constants.js'
13
- import type { PeerId } from '@libp2p/interface-peer-id'
14
- import type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'
15
- import type { Connection } from '@libp2p/interface-connection'
16
- import sort from 'it-sort'
17
- import all from 'it-all'
18
- import { pipe } from 'it-pipe'
19
- import { publicAddressesFirst } from '@libp2p/utils/address-sort'
20
- import type { RelayComponents } from './index.js'
21
-
22
- const log = logger('libp2p:auto-relay')
23
-
24
- const noop = () => {}
25
-
26
- export interface AutoRelayInit {
27
- addressSorter?: AddressSorter
28
- maxListeners?: number
29
- onError?: (error: Error, msg?: string) => void
30
- }
31
-
32
- export class AutoRelay {
33
- private readonly components: RelayComponents
34
- private readonly addressSorter: AddressSorter
35
- private readonly maxListeners: number
36
- private readonly listenRelays: Set<string>
37
- private readonly onError: (error: Error, msg?: string) => void
38
-
39
- constructor (components: RelayComponents, init: AutoRelayInit) {
40
- this.components = components
41
- this.addressSorter = init.addressSorter ?? publicAddressesFirst
42
- this.maxListeners = init.maxListeners ?? 1
43
- this.listenRelays = new Set()
44
- this.onError = init.onError ?? noop
45
-
46
- this._onProtocolChange = this._onProtocolChange.bind(this)
47
- this._onPeerDisconnected = this._onPeerDisconnected.bind(this)
48
-
49
- this.components.peerStore.addEventListener('change:protocols', (evt) => {
50
- void this._onProtocolChange(evt).catch(err => {
51
- log.error(err)
52
- })
53
- })
54
- this.components.connectionManager.addEventListener('peer:disconnect', this._onPeerDisconnected)
55
- }
56
-
57
- /**
58
- * Check if a peer supports the relay protocol.
59
- * If the protocol is not supported, check if it was supported before and remove it as a listen relay.
60
- * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if
61
- * inside the threshold.
62
- */
63
- async _onProtocolChange (evt: CustomEvent<PeerProtocolsChangeData>) {
64
- const {
65
- peerId,
66
- protocols
67
- } = evt.detail
68
- const id = peerId.toString()
69
-
70
- // Check if it has the protocol
71
- const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)
72
-
73
- // If no protocol, check if we were keeping the peer before as a listenRelay
74
- if (hasProtocol == null) {
75
- if (this.listenRelays.has(id)) {
76
- await this._removeListenRelay(id)
77
- }
78
-
79
- return
80
- }
81
-
82
- if (this.listenRelays.has(id)) {
83
- return
84
- }
85
-
86
- // If protocol, check if can hop, store info in the metadataBook and listen on it
87
- try {
88
- const connections = this.components.connectionManager.getConnections(peerId)
89
-
90
- if (connections.length === 0) {
91
- return
92
- }
93
-
94
- const connection = connections[0]
95
-
96
- // Do not hop on a relayed connection
97
- if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {
98
- log(`relayed connection to ${id} will not be used to hop on`)
99
- return
100
- }
101
-
102
- const supportsHop = await canHop({ connection })
103
-
104
- if (supportsHop) {
105
- await this.components.peerStore.metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))
106
- await this._addListenRelay(connection, id)
107
- }
108
- } catch (err: any) {
109
- this.onError(err)
110
- }
111
- }
112
-
113
- /**
114
- * Peer disconnects
115
- */
116
- _onPeerDisconnected (evt: CustomEvent<Connection>) {
117
- const connection = evt.detail
118
- const peerId = connection.remotePeer
119
- const id = peerId.toString()
120
-
121
- // Not listening on this relay
122
- if (!this.listenRelays.has(id)) {
123
- return
124
- }
125
-
126
- this._removeListenRelay(id).catch(err => {
127
- log.error(err)
128
- })
129
- }
130
-
131
- /**
132
- * Attempt to listen on the given relay connection
133
- */
134
- async _addListenRelay (connection: Connection, id: string): Promise<void> {
135
- try {
136
- // Check if already listening on enough relays
137
- if (this.listenRelays.size >= this.maxListeners) {
138
- return
139
- }
140
-
141
- // Get peer known addresses and sort them with public addresses first
142
- const remoteAddrs = await pipe(
143
- await this.components.peerStore.addressBook.get(connection.remotePeer),
144
- (source) => sort(source, this.addressSorter),
145
- async (source) => await all(source)
146
- )
147
-
148
- // Attempt to listen on relay
149
- const result = await Promise.all(
150
- remoteAddrs.map(async addr => {
151
- try {
152
- let multiaddr = addr.multiaddr
153
-
154
- if (multiaddr.getPeerId() == null) {
155
- multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)
156
- }
157
-
158
- multiaddr = multiaddr.encapsulate('/p2p-circuit')
159
-
160
- // Announce multiaddrs will update on listen success by TransportManager event being triggered
161
- await this.components.transportManager.listen([multiaddr])
162
- return true
163
- } catch (err: any) {
164
- log.error('error listening on circuit address', err)
165
- this.onError(err)
166
- }
167
-
168
- return false
169
- })
170
- )
171
-
172
- if (result.includes(true)) {
173
- this.listenRelays.add(id)
174
- }
175
- } catch (err: any) {
176
- this.onError(err)
177
- this.listenRelays.delete(id)
178
- }
179
- }
180
-
181
- /**
182
- * Remove listen relay
183
- */
184
- async _removeListenRelay (id: string) {
185
- if (this.listenRelays.delete(id)) {
186
- // TODO: this should be responsibility of the connMgr
187
- await this._listenOnAvailableHopRelays([id])
188
- }
189
- }
190
-
191
- /**
192
- * Try to listen on available hop relay connections.
193
- * The following order will happen while we do not have enough relays.
194
- * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.
195
- * 2. Dial and try to listen on the peers we know that support hop but are not connected.
196
- * 3. Search the network.
197
- */
198
- async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {
199
- // TODO: The peer redial issue on disconnect should be handled by connection gating
200
- // Check if already listening on enough relays
201
- if (this.listenRelays.size >= this.maxListeners) {
202
- return
203
- }
204
-
205
- const knownHopsToDial = []
206
- const peers = await this.components.peerStore.all()
207
-
208
- // Check if we have known hop peers to use and attempt to listen on the already connected
209
- for (const { id, metadata } of peers) {
210
- const idStr = id.toString()
211
-
212
- // Continue to next if listening on this or peer to ignore
213
- if (this.listenRelays.has(idStr)) {
214
- continue
215
- }
216
-
217
- if (peersToIgnore.includes(idStr)) {
218
- continue
219
- }
220
-
221
- const supportsHop = metadata.get(HOP_METADATA_KEY)
222
-
223
- // Continue to next if it does not support Hop
224
- if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {
225
- continue
226
- }
227
-
228
- const connections = this.components.connectionManager.getConnections(id)
229
-
230
- // If not connected, store for possible later use.
231
- if (connections.length === 0) {
232
- knownHopsToDial.push(id)
233
- continue
234
- }
235
-
236
- await this._addListenRelay(connections[0], idStr)
237
-
238
- // Check if already listening on enough relays
239
- if (this.listenRelays.size >= this.maxListeners) {
240
- return
241
- }
242
- }
243
-
244
- // Try to listen on known peers that are not connected
245
- for (const peerId of knownHopsToDial) {
246
- await this._tryToListenOnRelay(peerId)
247
-
248
- // Check if already listening on enough relays
249
- if (this.listenRelays.size >= this.maxListeners) {
250
- return
251
- }
252
- }
253
-
254
- // Try to find relays to hop on the network
255
- try {
256
- const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)
257
- for await (const provider of this.components.contentRouting.findProviders(cid)) {
258
- if (provider.multiaddrs.length === 0) {
259
- continue
260
- }
261
-
262
- const peerId = provider.id
263
-
264
- if (peerId.equals(this.components.peerId)) {
265
- // Skip the provider if it's us as dialing will fail
266
- continue
267
- }
268
-
269
- await this.components.peerStore.addressBook.add(peerId, provider.multiaddrs)
270
-
271
- await this._tryToListenOnRelay(peerId)
272
-
273
- // Check if already listening on enough relays
274
- if (this.listenRelays.size >= this.maxListeners) {
275
- return
276
- }
277
- }
278
- } catch (err: any) {
279
- this.onError(err)
280
- }
281
- }
282
-
283
- async _tryToListenOnRelay (peerId: PeerId) {
284
- try {
285
- const connection = await this.components.connectionManager.openConnection(peerId)
286
- await this._addListenRelay(connection, peerId.toString())
287
- } catch (err: any) {
288
- log.error('Could not use %p as relay', peerId, err)
289
- this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)
290
- }
291
- }
292
- }
@@ -1,220 +0,0 @@
1
- import { logger } from '@libp2p/logger'
2
- import errCode from 'err-code'
3
- import { validateAddrs } from './utils.js'
4
- import { StreamHandler } from './stream-handler.js'
5
- import { CircuitRelay as CircuitPB } from '../pb/index.js'
6
- import { pipe } from 'it-pipe'
7
- import { codes as Errors } from '../../errors.js'
8
- import { stop } from './stop.js'
9
- import { RELAY_CODEC } from '../multicodec.js'
10
- import type { Connection } from '@libp2p/interface-connection'
11
- import { peerIdFromBytes } from '@libp2p/peer-id'
12
- import type { Duplex } from 'it-stream-types'
13
- import type { Circuit } from '../transport.js'
14
- import type { ConnectionManager } from '@libp2p/interface-connection-manager'
15
- import type { AbortOptions } from '@libp2p/interfaces'
16
- import type { Uint8ArrayList } from 'uint8arraylist'
17
-
18
- const log = logger('libp2p:circuit:hop')
19
-
20
- export interface HopRequest {
21
- connection: Connection
22
- request: CircuitPB
23
- streamHandler: StreamHandler
24
- circuit: Circuit
25
- connectionManager: ConnectionManager
26
- }
27
-
28
- export async function handleHop (hopRequest: HopRequest): Promise<void> {
29
- const {
30
- connection,
31
- request,
32
- streamHandler,
33
- circuit,
34
- connectionManager
35
- } = hopRequest
36
-
37
- // Ensure hop is enabled
38
- if (!circuit.hopEnabled()) {
39
- log('HOP request received but we are not acting as a relay')
40
- return streamHandler.end({
41
- type: CircuitPB.Type.STATUS,
42
- code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY
43
- })
44
- }
45
-
46
- // Validate the HOP request has the required input
47
- try {
48
- validateAddrs(request, streamHandler)
49
- } catch (err: any) {
50
- log.error('invalid hop request via peer %p %o', connection.remotePeer, err)
51
-
52
- return
53
- }
54
-
55
- if (request.dstPeer == null) {
56
- log('HOP request received but we do not receive a dstPeer')
57
- return
58
- }
59
-
60
- // Get the connection to the destination (stop) peer
61
- const destinationPeer = peerIdFromBytes(request.dstPeer.id)
62
-
63
- const destinationConnections = connectionManager.getConnections(destinationPeer)
64
- if (destinationConnections.length === 0 && !circuit.hopActive()) {
65
- log('HOP request received but we are not connected to the destination peer')
66
- return streamHandler.end({
67
- type: CircuitPB.Type.STATUS,
68
- code: CircuitPB.Status.HOP_NO_CONN_TO_DST
69
- })
70
- }
71
-
72
- // TODO: Handle being an active relay
73
- if (destinationConnections.length === 0) {
74
- log('did not have connection to remote peer')
75
- return streamHandler.end({
76
- type: CircuitPB.Type.STATUS,
77
- code: CircuitPB.Status.HOP_NO_CONN_TO_DST
78
- })
79
- }
80
-
81
- // Handle the incoming HOP request by performing a STOP request
82
- const stopRequest = {
83
- type: CircuitPB.Type.STOP,
84
- dstPeer: request.dstPeer,
85
- srcPeer: request.srcPeer
86
- }
87
-
88
- let destinationStream: Duplex<Uint8ArrayList>
89
- try {
90
- log('performing STOP request')
91
- const result = await stop({
92
- connection: destinationConnections[0],
93
- request: stopRequest
94
- })
95
-
96
- if (result == null) {
97
- throw new Error('Could not stop')
98
- }
99
-
100
- destinationStream = result
101
- } catch (err: any) {
102
- log.error(err)
103
-
104
- return
105
- }
106
-
107
- log('hop request from %p is valid', connection.remotePeer)
108
- streamHandler.write({
109
- type: CircuitPB.Type.STATUS,
110
- code: CircuitPB.Status.SUCCESS
111
- })
112
- const sourceStream = streamHandler.rest()
113
-
114
- log('creating related connections')
115
- // Short circuit the two streams to create the relayed connection
116
- return await pipe(
117
- sourceStream,
118
- destinationStream,
119
- sourceStream
120
- )
121
- }
122
-
123
- export interface HopConfig extends AbortOptions {
124
- connection: Connection
125
- request: CircuitPB
126
- }
127
-
128
- /**
129
- * Performs a HOP request to a relay peer, to request a connection to another
130
- * peer. A new, virtual, connection will be created between the two via the relay.
131
- */
132
- export async function hop (options: HopConfig): Promise<Duplex<Uint8ArrayList, Uint8ArrayList | Uint8Array>> {
133
- const {
134
- connection,
135
- request,
136
- signal
137
- } = options
138
-
139
- // Create a new stream to the relay
140
- const stream = await connection.newStream(RELAY_CODEC, {
141
- signal
142
- })
143
- // Send the HOP request
144
- const streamHandler = new StreamHandler({ stream })
145
- streamHandler.write(request)
146
-
147
- const response = await streamHandler.read()
148
-
149
- if (response == null) {
150
- throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)
151
- }
152
-
153
- if (response.code === CircuitPB.Status.SUCCESS) {
154
- log('hop request was successful')
155
-
156
- return streamHandler.rest()
157
- }
158
-
159
- log('hop request failed with code %d, closing stream', response.code)
160
- streamHandler.close()
161
-
162
- throw errCode(new Error(`HOP request failed with code "${response.code ?? 'unknown'}"`), Errors.ERR_HOP_REQUEST_FAILED)
163
- }
164
-
165
- export interface CanHopOptions extends AbortOptions {
166
- connection: Connection
167
- }
168
-
169
- /**
170
- * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities
171
- */
172
- export async function canHop (options: CanHopOptions) {
173
- const {
174
- connection,
175
- signal
176
- } = options
177
-
178
- // Create a new stream to the relay
179
- const stream = await connection.newStream(RELAY_CODEC, {
180
- signal
181
- })
182
-
183
- // Send the HOP request
184
- const streamHandler = new StreamHandler({ stream })
185
- streamHandler.write({
186
- type: CircuitPB.Type.CAN_HOP
187
- })
188
-
189
- const response = await streamHandler.read()
190
- await streamHandler.close()
191
-
192
- if (response == null || response.code !== CircuitPB.Status.SUCCESS) {
193
- return false
194
- }
195
-
196
- return true
197
- }
198
-
199
- export interface HandleCanHopOptions {
200
- connection: Connection
201
- streamHandler: StreamHandler
202
- circuit: Circuit
203
- }
204
-
205
- /**
206
- * Creates an unencoded CAN_HOP response based on the Circuits configuration
207
- */
208
- export function handleCanHop (options: HandleCanHopOptions) {
209
- const {
210
- connection,
211
- streamHandler,
212
- circuit
213
- } = options
214
- const canHop = circuit.hopEnabled()
215
- log('can hop (%s) request from %p', canHop, connection.remotePeer)
216
- streamHandler.end({
217
- type: CircuitPB.Type.STATUS,
218
- code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY
219
- })
220
- }
@@ -1,83 +0,0 @@
1
- import { logger } from '@libp2p/logger'
2
- import { CircuitRelay as CircuitPB } from '../pb/index.js'
3
- import { RELAY_CODEC } from '../multicodec.js'
4
- import { StreamHandler } from './stream-handler.js'
5
- import { validateAddrs } from './utils.js'
6
- import type { Connection } from '@libp2p/interface-connection'
7
- import type { Duplex } from 'it-stream-types'
8
- import type { AbortOptions } from '@libp2p/interfaces'
9
- import type { Uint8ArrayList } from 'uint8arraylist'
10
-
11
- const log = logger('libp2p:circuit:stop')
12
-
13
- export interface HandleStopOptions {
14
- connection: Connection
15
- request: CircuitPB
16
- streamHandler: StreamHandler
17
- }
18
-
19
- /**
20
- * Handles incoming STOP requests
21
- */
22
- export function handleStop (options: HandleStopOptions): Duplex<Uint8ArrayList, Uint8ArrayList | Uint8Array> | undefined {
23
- const {
24
- connection,
25
- request,
26
- streamHandler
27
- } = options
28
-
29
- // Validate the STOP request has the required input
30
- try {
31
- validateAddrs(request, streamHandler)
32
- } catch (err: any) {
33
- log.error('invalid stop request via peer %p %o', connection.remotePeer, err)
34
- return
35
- }
36
-
37
- // The request is valid
38
- log('stop request is valid')
39
- streamHandler.write({
40
- type: CircuitPB.Type.STATUS,
41
- code: CircuitPB.Status.SUCCESS
42
- })
43
-
44
- return streamHandler.rest()
45
- }
46
-
47
- export interface StopOptions extends AbortOptions {
48
- connection: Connection
49
- request: CircuitPB
50
- }
51
-
52
- /**
53
- * Creates a STOP request
54
- */
55
- export async function stop (options: StopOptions) {
56
- const {
57
- connection,
58
- request,
59
- signal
60
- } = options
61
-
62
- const stream = await connection.newStream(RELAY_CODEC, {
63
- signal
64
- })
65
- log('starting stop request to %p', connection.remotePeer)
66
- const streamHandler = new StreamHandler({ stream })
67
-
68
- streamHandler.write(request)
69
- const response = await streamHandler.read()
70
-
71
- if (response == null) {
72
- streamHandler.close()
73
- return
74
- }
75
-
76
- if (response.code === CircuitPB.Status.SUCCESS) {
77
- log('stop request to %p was successful', connection.remotePeer)
78
- return streamHandler.rest()
79
- }
80
-
81
- log('stop request failed with code %d', response.code)
82
- streamHandler.close()
83
- }
@@ -1,87 +0,0 @@
1
- import { logger } from '@libp2p/logger'
2
- import * as lp from 'it-length-prefixed'
3
- import { Handshake, handshake } from 'it-handshake'
4
- import { CircuitRelay } from '../pb/index.js'
5
- import type { Stream } from '@libp2p/interface-connection'
6
- import type { Source } from 'it-stream-types'
7
- import type { Uint8ArrayList } from 'uint8arraylist'
8
-
9
- const log = logger('libp2p:circuit:stream-handler')
10
-
11
- export interface StreamHandlerOptions {
12
- /**
13
- * A duplex iterable
14
- */
15
- stream: Stream
16
-
17
- /**
18
- * max bytes length of message
19
- */
20
- maxLength?: number
21
- }
22
-
23
- export class StreamHandler {
24
- private readonly stream: Stream
25
- private readonly shake: Handshake<Uint8ArrayList | Uint8Array>
26
- private readonly decoder: Source<Uint8ArrayList>
27
-
28
- constructor (options: StreamHandlerOptions) {
29
- const { stream, maxLength = 4096 } = options
30
-
31
- this.stream = stream
32
- this.shake = handshake(this.stream)
33
- this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })
34
- }
35
-
36
- /**
37
- * Read and decode message
38
- */
39
- async read () {
40
- // @ts-expect-error FIXME is a source, needs to be a generator
41
- const msg = await this.decoder.next()
42
-
43
- if (msg.value != null) {
44
- const value = CircuitRelay.decode(msg.value)
45
- log('read message type', value.type)
46
- return value
47
- }
48
-
49
- log('read received no value, closing stream')
50
- // End the stream, we didn't get data
51
- this.close()
52
- }
53
-
54
- /**
55
- * Encode and write array of buffers
56
- */
57
- write (msg: CircuitRelay) {
58
- log('write message type %s', msg.type)
59
- this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))
60
- }
61
-
62
- /**
63
- * Return the handshake rest stream and invalidate handler
64
- */
65
- rest () {
66
- this.shake.rest()
67
- return this.shake.stream
68
- }
69
-
70
- /**
71
- * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message
72
- */
73
- end (msg: CircuitRelay) {
74
- this.write(msg)
75
- this.close()
76
- }
77
-
78
- /**
79
- * Close the stream
80
- */
81
- close () {
82
- log('closing the stream')
83
- void this.rest().sink([]).catch(err => {
84
- log.error(err)
85
- })
86
- }
87
- }