libp2p 0.42.2-f6f73a21 → 0.43.0

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 (277) hide show
  1. package/README.md +1 -1
  2. package/dist/index.min.js +28 -28
  3. package/dist/src/address-manager/index.d.ts +1 -10
  4. package/dist/src/address-manager/index.d.ts.map +1 -1
  5. package/dist/src/address-manager/index.js +46 -29
  6. package/dist/src/address-manager/index.js.map +1 -1
  7. package/dist/src/autonat/constants.d.ts +4 -0
  8. package/dist/src/autonat/constants.d.ts.map +1 -0
  9. package/dist/src/autonat/constants.js +4 -0
  10. package/dist/src/autonat/constants.js.map +1 -0
  11. package/dist/src/autonat/index.d.ts +64 -0
  12. package/dist/src/autonat/index.d.ts.map +1 -0
  13. package/dist/src/autonat/index.js +417 -0
  14. package/dist/src/autonat/index.js.map +1 -0
  15. package/dist/src/autonat/pb/index.d.ts +57 -0
  16. package/dist/src/autonat/pb/index.d.ts.map +1 -0
  17. package/dist/src/autonat/pb/index.js +250 -0
  18. package/dist/src/autonat/pb/index.js.map +1 -0
  19. package/dist/src/circuit/constants.d.ts +31 -6
  20. package/dist/src/circuit/constants.d.ts.map +1 -1
  21. package/dist/src/circuit/constants.js +37 -7
  22. package/dist/src/circuit/constants.js.map +1 -1
  23. package/dist/src/circuit/index.d.ts +16 -61
  24. package/dist/src/circuit/index.d.ts.map +1 -1
  25. package/dist/src/circuit/index.js +2 -68
  26. package/dist/src/circuit/index.js.map +1 -1
  27. package/dist/src/circuit/pb/index.d.ts +83 -43
  28. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  29. package/dist/src/circuit/pb/index.js +363 -127
  30. package/dist/src/circuit/pb/index.js.map +1 -1
  31. package/dist/src/circuit/server/advert-service.d.ts +43 -0
  32. package/dist/src/circuit/server/advert-service.d.ts.map +1 -0
  33. package/dist/src/circuit/server/advert-service.js +69 -0
  34. package/dist/src/circuit/server/advert-service.js.map +1 -0
  35. package/dist/src/circuit/server/index.d.ts +60 -0
  36. package/dist/src/circuit/server/index.d.ts.map +1 -0
  37. package/dist/src/circuit/server/index.js +287 -0
  38. package/dist/src/circuit/server/index.js.map +1 -0
  39. package/dist/src/circuit/server/reservation-store.d.ts +49 -0
  40. package/dist/src/circuit/server/reservation-store.d.ts.map +1 -0
  41. package/dist/src/circuit/server/reservation-store.js +57 -0
  42. package/dist/src/circuit/server/reservation-store.js.map +1 -0
  43. package/dist/src/circuit/server/reservation-voucher.d.ts +18 -0
  44. package/dist/src/circuit/server/reservation-voucher.d.ts.map +1 -0
  45. package/dist/src/circuit/server/reservation-voucher.js +33 -0
  46. package/dist/src/circuit/server/reservation-voucher.js.map +1 -0
  47. package/dist/src/circuit/transport/discovery.d.ts +45 -0
  48. package/dist/src/circuit/transport/discovery.d.ts.map +1 -0
  49. package/dist/src/circuit/transport/discovery.js +82 -0
  50. package/dist/src/circuit/transport/discovery.js.map +1 -0
  51. package/dist/src/circuit/transport/index.d.ts +33 -0
  52. package/dist/src/circuit/transport/index.d.ts.map +1 -0
  53. package/dist/src/circuit/transport/index.js +225 -0
  54. package/dist/src/circuit/transport/index.js.map +1 -0
  55. package/dist/src/circuit/transport/listener.d.ts +9 -0
  56. package/dist/src/circuit/transport/listener.d.ts.map +1 -0
  57. package/dist/src/circuit/transport/listener.js +76 -0
  58. package/dist/src/circuit/transport/listener.js.map +1 -0
  59. package/dist/src/circuit/transport/reservation-store.d.ts +60 -0
  60. package/dist/src/circuit/transport/reservation-store.d.ts.map +1 -0
  61. package/dist/src/circuit/transport/reservation-store.js +165 -0
  62. package/dist/src/circuit/transport/reservation-store.js.map +1 -0
  63. package/dist/src/circuit/utils.d.ts +7 -0
  64. package/dist/src/circuit/utils.d.ts.map +1 -1
  65. package/dist/src/circuit/utils.js +87 -0
  66. package/dist/src/circuit/utils.js.map +1 -1
  67. package/dist/src/components.d.ts +2 -1
  68. package/dist/src/components.d.ts.map +1 -1
  69. package/dist/src/components.js +13 -13
  70. package/dist/src/components.js.map +1 -1
  71. package/dist/src/config.d.ts.map +1 -1
  72. package/dist/src/config.js +21 -25
  73. package/dist/src/config.js.map +1 -1
  74. package/dist/src/connection/index.d.ts +2 -2
  75. package/dist/src/connection/index.d.ts.map +1 -1
  76. package/dist/src/connection/index.js +4 -4
  77. package/dist/src/connection/index.js.map +1 -1
  78. package/dist/src/connection-manager/auto-dialler.d.ts +0 -4
  79. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  80. package/dist/src/connection-manager/auto-dialler.js +0 -9
  81. package/dist/src/connection-manager/auto-dialler.js.map +1 -1
  82. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  83. package/dist/src/connection-manager/dialer/dial-request.js +13 -6
  84. package/dist/src/connection-manager/dialer/dial-request.js.map +1 -1
  85. package/dist/src/connection-manager/dialer/index.d.ts +2 -1
  86. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  87. package/dist/src/connection-manager/dialer/index.js +9 -9
  88. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  89. package/dist/src/connection-manager/index.d.ts +0 -4
  90. package/dist/src/connection-manager/index.d.ts.map +1 -1
  91. package/dist/src/connection-manager/index.js +5 -5
  92. package/dist/src/connection-manager/index.js.map +1 -1
  93. package/dist/src/connection-manager/latency-monitor.d.ts.map +1 -1
  94. package/dist/src/connection-manager/latency-monitor.js +1 -1
  95. package/dist/src/connection-manager/latency-monitor.js.map +1 -1
  96. package/dist/src/connection-manager/visibility-change-emitter.d.ts.map +1 -1
  97. package/dist/src/content-routing/index.d.ts +6 -4
  98. package/dist/src/content-routing/index.d.ts.map +1 -1
  99. package/dist/src/content-routing/index.js +9 -9
  100. package/dist/src/content-routing/index.js.map +1 -1
  101. package/dist/src/content-routing/utils.d.ts +3 -3
  102. package/dist/src/content-routing/utils.d.ts.map +1 -1
  103. package/dist/src/content-routing/utils.js +2 -2
  104. package/dist/src/content-routing/utils.js.map +1 -1
  105. package/dist/src/dht/dht-content-routing.d.ts +2 -1
  106. package/dist/src/dht/dht-content-routing.d.ts.map +1 -1
  107. package/dist/src/dht/dht-content-routing.js +2 -2
  108. package/dist/src/dht/dht-content-routing.js.map +1 -1
  109. package/dist/src/dht/dht-peer-routing.d.ts +3 -2
  110. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  111. package/dist/src/dht/dht-peer-routing.js +2 -2
  112. package/dist/src/dht/dht-peer-routing.js.map +1 -1
  113. package/dist/src/dht/dummy-dht.d.ts +1 -1
  114. package/dist/src/dht/dummy-dht.d.ts.map +1 -1
  115. package/dist/src/dht/dummy-dht.js +12 -12
  116. package/dist/src/dht/dummy-dht.js.map +1 -1
  117. package/dist/src/errors.d.ts +2 -1
  118. package/dist/src/errors.d.ts.map +1 -1
  119. package/dist/src/errors.js +1 -0
  120. package/dist/src/errors.js.map +1 -1
  121. package/dist/src/fetch/index.d.ts.map +1 -1
  122. package/dist/src/fetch/index.js +6 -6
  123. package/dist/src/fetch/index.js.map +1 -1
  124. package/dist/src/fetch/pb/proto.d.ts +3 -3
  125. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  126. package/dist/src/fetch/pb/proto.js +4 -3
  127. package/dist/src/fetch/pb/proto.js.map +1 -1
  128. package/dist/src/get-peer.js +2 -2
  129. package/dist/src/get-peer.js.map +1 -1
  130. package/dist/src/identify/index.d.ts +3 -1
  131. package/dist/src/identify/index.d.ts.map +1 -1
  132. package/dist/src/identify/index.js +19 -14
  133. package/dist/src/identify/index.js.map +1 -1
  134. package/dist/src/identify/pb/message.d.ts +2 -2
  135. package/dist/src/identify/pb/message.d.ts.map +1 -1
  136. package/dist/src/identify/pb/message.js +1 -0
  137. package/dist/src/identify/pb/message.js.map +1 -1
  138. package/dist/src/index.d.ts +13 -7
  139. package/dist/src/index.d.ts.map +1 -1
  140. package/dist/src/index.js.map +1 -1
  141. package/dist/src/insecure/index.d.ts.map +1 -1
  142. package/dist/src/insecure/index.js.map +1 -1
  143. package/dist/src/insecure/pb/proto.d.ts +3 -3
  144. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  145. package/dist/src/insecure/pb/proto.js +4 -5
  146. package/dist/src/insecure/pb/proto.js.map +1 -1
  147. package/dist/src/libp2p.d.ts +6 -2
  148. package/dist/src/libp2p.d.ts.map +1 -1
  149. package/dist/src/libp2p.js +24 -26
  150. package/dist/src/libp2p.js.map +1 -1
  151. package/dist/src/nat-manager.d.ts.map +1 -1
  152. package/dist/src/nat-manager.js +5 -3
  153. package/dist/src/nat-manager.js.map +1 -1
  154. package/dist/src/peer-record-updater.d.ts.map +1 -1
  155. package/dist/src/peer-routing.d.ts.map +1 -1
  156. package/dist/src/peer-routing.js +5 -5
  157. package/dist/src/peer-routing.js.map +1 -1
  158. package/dist/src/ping/index.d.ts.map +1 -1
  159. package/dist/src/ping/index.js +2 -2
  160. package/dist/src/ping/index.js.map +1 -1
  161. package/dist/src/pnet/crypto.d.ts +1 -1
  162. package/dist/src/pnet/crypto.d.ts.map +1 -1
  163. package/dist/src/pnet/crypto.js +1 -1
  164. package/dist/src/pnet/crypto.js.map +1 -1
  165. package/dist/src/pnet/index.js +3 -3
  166. package/dist/src/pnet/index.js.map +1 -1
  167. package/dist/src/pnet/key-generator.d.ts.map +1 -1
  168. package/dist/src/pubsub/dummy-pubsub.js +9 -9
  169. package/dist/src/pubsub/dummy-pubsub.js.map +1 -1
  170. package/dist/src/registrar.d.ts.map +1 -1
  171. package/dist/src/registrar.js +4 -4
  172. package/dist/src/registrar.js.map +1 -1
  173. package/dist/src/transport-manager.d.ts.map +1 -1
  174. package/dist/src/transport-manager.js +8 -9
  175. package/dist/src/transport-manager.js.map +1 -1
  176. package/dist/src/upgrader.d.ts +2 -1
  177. package/dist/src/upgrader.d.ts.map +1 -1
  178. package/dist/src/upgrader.js +38 -33
  179. package/dist/src/upgrader.js.map +1 -1
  180. package/dist/typedoc-urls.json +41 -0
  181. package/package.json +35 -30
  182. package/src/address-manager/index.ts +62 -35
  183. package/src/autonat/constants.ts +4 -0
  184. package/src/autonat/index.ts +567 -0
  185. package/src/autonat/pb/index.proto +35 -0
  186. package/src/autonat/pb/index.ts +320 -0
  187. package/src/circuit/constants.ts +48 -7
  188. package/src/circuit/index.ts +17 -129
  189. package/src/circuit/pb/index.proto +57 -32
  190. package/src/circuit/pb/index.ts +448 -138
  191. package/src/circuit/server/advert-service.ts +108 -0
  192. package/src/circuit/server/index.ts +421 -0
  193. package/src/circuit/server/reservation-store.ts +111 -0
  194. package/src/circuit/server/reservation-voucher.ts +51 -0
  195. package/src/circuit/transport/discovery.ts +127 -0
  196. package/src/circuit/transport/index.ts +325 -0
  197. package/src/circuit/transport/listener.ts +99 -0
  198. package/src/circuit/transport/reservation-store.ts +249 -0
  199. package/src/circuit/utils.ts +108 -0
  200. package/src/components.ts +22 -21
  201. package/src/config.ts +21 -25
  202. package/src/connection/index.ts +10 -10
  203. package/src/connection-manager/auto-dialler.ts +4 -20
  204. package/src/connection-manager/dialer/dial-request.ts +13 -6
  205. package/src/connection-manager/dialer/index.ts +16 -15
  206. package/src/connection-manager/index.ts +18 -23
  207. package/src/connection-manager/latency-monitor.ts +9 -9
  208. package/src/connection-manager/visibility-change-emitter.ts +4 -4
  209. package/src/content-routing/index.ts +18 -16
  210. package/src/content-routing/utils.ts +5 -5
  211. package/src/dht/dht-content-routing.ts +5 -4
  212. package/src/dht/dht-peer-routing.ts +5 -4
  213. package/src/dht/dummy-dht.ts +13 -13
  214. package/src/errors.ts +2 -1
  215. package/src/fetch/index.ts +13 -13
  216. package/src/fetch/pb/proto.ts +8 -7
  217. package/src/get-peer.ts +3 -3
  218. package/src/identify/index.ts +29 -24
  219. package/src/identify/pb/message.ts +3 -2
  220. package/src/index.ts +14 -7
  221. package/src/insecure/index.ts +2 -1
  222. package/src/insecure/pb/proto.ts +8 -9
  223. package/src/libp2p.ts +38 -37
  224. package/src/nat-manager.ts +11 -9
  225. package/src/peer-record-updater.ts +4 -4
  226. package/src/peer-routing.ts +9 -9
  227. package/src/ping/index.ts +6 -6
  228. package/src/pnet/crypto.ts +3 -3
  229. package/src/pnet/index.ts +3 -3
  230. package/src/pnet/key-generator.ts +1 -1
  231. package/src/pubsub/dummy-pubsub.ts +9 -9
  232. package/src/registrar.ts +12 -12
  233. package/src/transport-manager.ts +17 -18
  234. package/src/upgrader.ts +43 -42
  235. package/src/version.ts +1 -1
  236. package/dist/src/circuit/auto-relay.d.ts +0 -46
  237. package/dist/src/circuit/auto-relay.d.ts.map +0 -1
  238. package/dist/src/circuit/auto-relay.js +0 -220
  239. package/dist/src/circuit/auto-relay.js.map +0 -1
  240. package/dist/src/circuit/circuit/hop.d.ts +0 -42
  241. package/dist/src/circuit/circuit/hop.d.ts.map +0 -1
  242. package/dist/src/circuit/circuit/hop.js +0 -142
  243. package/dist/src/circuit/circuit/hop.js.map +0 -1
  244. package/dist/src/circuit/circuit/stop.d.ts +0 -24
  245. package/dist/src/circuit/circuit/stop.d.ts.map +0 -1
  246. package/dist/src/circuit/circuit/stop.js +0 -51
  247. package/dist/src/circuit/circuit/stop.js.map +0 -1
  248. package/dist/src/circuit/circuit/stream-handler.d.ts +0 -40
  249. package/dist/src/circuit/circuit/stream-handler.d.ts.map +0 -1
  250. package/dist/src/circuit/circuit/stream-handler.js +0 -59
  251. package/dist/src/circuit/circuit/stream-handler.js.map +0 -1
  252. package/dist/src/circuit/circuit/utils.d.ts +0 -7
  253. package/dist/src/circuit/circuit/utils.d.ts.map +0 -1
  254. package/dist/src/circuit/circuit/utils.js +0 -43
  255. package/dist/src/circuit/circuit/utils.js.map +0 -1
  256. package/dist/src/circuit/listener.d.ts +0 -9
  257. package/dist/src/circuit/listener.d.ts.map +0 -1
  258. package/dist/src/circuit/listener.js +0 -62
  259. package/dist/src/circuit/listener.js.map +0 -1
  260. package/dist/src/circuit/multicodec.d.ts +0 -2
  261. package/dist/src/circuit/multicodec.d.ts.map +0 -1
  262. package/dist/src/circuit/multicodec.js +0 -2
  263. package/dist/src/circuit/multicodec.js.map +0 -1
  264. package/dist/src/circuit/transport.d.ts +0 -51
  265. package/dist/src/circuit/transport.d.ts.map +0 -1
  266. package/dist/src/circuit/transport.js +0 -223
  267. package/dist/src/circuit/transport.js.map +0 -1
  268. package/src/circuit/IMPLEMENTATION_NOTES.md +0 -128
  269. package/src/circuit/README.md +0 -111
  270. package/src/circuit/auto-relay.ts +0 -292
  271. package/src/circuit/circuit/hop.ts +0 -220
  272. package/src/circuit/circuit/stop.ts +0 -83
  273. package/src/circuit/circuit/stream-handler.ts +0 -87
  274. package/src/circuit/circuit/utils.ts +0 -44
  275. package/src/circuit/listener.ts +0 -83
  276. package/src/circuit/multicodec.ts +0 -2
  277. package/src/circuit/transport.ts +0 -278
@@ -1,111 +0,0 @@
1
- # js-libp2p-circuit
2
-
3
- > Node.js implementation of the Circuit module that libp2p uses, which implements the [interface-connection](https://github.com/libp2p/js-libp2p-interfaces/tree/master/src/connection) interface for dial/listen.
4
-
5
- **Note**: git history prior to merging into js-libp2p can be found in the original repository, https://github.com/libp2p/js-libp2p-circuit.
6
-
7
- `libp2p-circuit` implements the circuit-relay mechanism that allows nodes that don't speak the same protocol to communicate using a third _relay_ node. You can read more about this in its [spec](https://github.com/libp2p/specs/tree/master/relay).
8
-
9
- ## Table of Contents
10
-
11
- - [js-libp2p-circuit](#js-libp2p-circuit)
12
- - [Table of Contents](#table-of-contents)
13
- - [Why?](#why)
14
- - [libp2p-circuit and IPFS](#libp2p-circuit-and-ipfs)
15
- - [Usage](#usage)
16
- - [API](#api)
17
- - [Implementation rational](#implementation-rational)
18
-
19
- ### Why?
20
-
21
- `circuit-relaying` uses additional nodes in order to transfer traffic between two otherwise unreachable nodes. This allows nodes that don't speak the same protocols or are running in limited environments, e.g. browsers and IoT devices, to communicate, which would otherwise be impossible given the fact that for example browsers don't have any socket support and as such cannot be directly dialed.
22
-
23
- The use of circuit-relaying is not limited to routing traffic between browser nodes, other uses include:
24
- - routing traffic between private nets and circumventing NAT layers
25
- - route mangling for better privacy (matreshka/shallot dialing).
26
-
27
- It's also possible to use it for clients that implement exotic transports such as devices that only have bluetooth radios to be reachable over bluetooth enabled relays and become full p2p nodes.
28
-
29
- ### libp2p-circuit and IPFS
30
-
31
- Prior to `libp2p-circuit` there was a rift in the IPFS network, were IPFS nodes could only access content from nodes that speak the same protocol, for example TCP only nodes could only dial to other TCP only nodes, same for any other protocol combination. In practice, this limitation was most visible in JS-IPFS browser nodes, since they can only dial out but not be dialed in over WebRTC or WebSockets, hence any content that the browser node held was not reachable by the rest of the network even through it was announced on the DHT. Non browser IPFS nodes would usually speak more than one protocol such as TCP, WebSockets and/or WebRTC, this made the problem less severe outside of the browser. `libp2p-circuit` solves this problem completely, as long as there are `relay nodes` capable of routing traffic between those nodes their content should be available to the rest of the IPFS network.
32
-
33
- ## Usage
34
-
35
- Libp2p circuit configuration can be seen at [Setup with Relay](../../doc/CONFIGURATION.md#setup-with-relay).
36
-
37
- Once you have a circuit relay node running, you can configure other nodes to use it as a relay as follows:
38
-
39
- ```js
40
- import { multiaddr } from '@multiformats/multiaddr'
41
- import Libp2p from 'libp2p'
42
- import { tcp } from '@libp2p/tcp'
43
- import { mplex } from '@libp2p/mplex'
44
- import { noise } from '@chainsafe/libp2p-noise'
45
-
46
- const relayAddr = ...
47
-
48
- const node = await createLibp2p({
49
- addresses: {
50
- listen: [multiaddr(`${relayAddr}/p2p-circuit`)]
51
- },
52
- transports: [
53
- tcp()
54
- ],
55
- streamMuxers: [
56
- mplex()
57
- ],
58
- connectionEncryption: [
59
- noise()
60
- ]
61
- },
62
- config: {
63
- relay: { // Circuit Relay options (this config is part of libp2p core configurations)
64
- enabled: true // Allows you to dial and accept relayed connections. Does not make you a relay.
65
- }
66
- }
67
- })
68
- ```
69
-
70
- ## API
71
-
72
- [![](https://raw.githubusercontent.com/libp2p/interface-transport/master/img/badge.png)](https://github.com/libp2p/interface-transport)
73
-
74
- `libp2p-circuit` accepts Circuit addresses for both IPFS and non IPFS encapsulated addresses, i.e:
75
-
76
- `/p2p-circuit/ip4/127.0.0.1/tcp/4001/p2p/QmHash`
77
-
78
- Both for dialing and listening.
79
-
80
- ### Implementation rational
81
-
82
- This module is not a transport, however it implements `interface-transport` interface in order to allow circuit to be plugged with `libp2p`. The rational behind it is that, `libp2p-circuit` has a dial and listen flow, which fits nicely with other transports, moreover, it requires the _raw_ connection to be encrypted and muxed just as a regular transport's connection does. All in all, `interface-transport` ended up being the correct level of abstraction for circuit, as well as allowed us to reuse existing integration points in `libp2p` and `libp2p` without adding any ad-hoc logic. All parts of `interface-transport` are used, including `.getAddr` which returns a list of `/p2p-circuit` addresses that circuit is currently listening.
83
-
84
- ```
85
- libp2p libp2p-circuit (transport)
86
- +-------------------------------------------------+ +--------------------------+
87
- | +---------------------------------+ | | |
88
- | | | | | +------------------+ |
89
- | | | | circuit-relay listens for the HOP | | | |
90
- | | libp2p <------------------------------------------------| circuit-relay | |
91
- | | | | message to handle incomming relay | | | |
92
- | | | | requests from other nodes | +------------------+ |
93
- | +---------------------------------+ | | |
94
- | ^ ^ ^ ^ ^ ^ | | +------------------+ |
95
- | | | | | | | | | | +-------------+ | |
96
- | | | | | | | | dialer uses libp2p to dial | | | | | |
97
- | | | | +----------------------------------------------------------------------> dialer | | |
98
- | | | transports | | to a circuit-relay node using the | | | | | |
99
- | | | | | | | HOP message | | +-------------+ | |
100
- | | | | | | | | | | |
101
- | v v | v v | | | | |
102
- |+------------------|----------------------------+| | | +-------------+ | |
103
- || | | | | || | | | | | |
104
- ||libp2p-tcp |libp2p-ws | .... |libp2p-circuit || listener handles STOP messages from| | | listener | | |
105
- || | +--------------------------------------------------------------------------> | | |
106
- || | | |plugs in just || circuit-relay nodes | | +-------------+ | |
107
- || | | |as any other || | | | |
108
- || | | |transport || | +------------------+ |
109
- |+-----------------------------------------------+| | |
110
- +-------------------------------------------------+ +--------------------------+
111
- ```
@@ -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
- }