smoldot 0.3.6 → 0.7.11

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 (74) hide show
  1. package/README.md +18 -21
  2. package/dist/cjs/base64.d.ts +22 -0
  3. package/dist/cjs/base64.js +104 -0
  4. package/dist/cjs/client.d.ts +287 -0
  5. package/dist/cjs/client.js +175 -0
  6. package/dist/cjs/index-browser.d.ts +11 -0
  7. package/dist/cjs/index-browser.js +465 -0
  8. package/dist/cjs/index-deno.d.ts +10 -0
  9. package/dist/cjs/index-deno.js +263 -0
  10. package/dist/cjs/index-nodejs.d.ts +10 -0
  11. package/dist/cjs/index-nodejs.js +174 -0
  12. package/dist/cjs/instance/autogen/wasm.d.ts +2 -0
  13. package/dist/cjs/instance/autogen/wasm.js +6 -0
  14. package/dist/cjs/instance/autogen/wasm0.d.ts +1 -0
  15. package/dist/cjs/instance/autogen/wasm0.js +4 -0
  16. package/dist/cjs/instance/autogen/wasm1.d.ts +1 -0
  17. package/dist/cjs/instance/autogen/wasm1.js +4 -0
  18. package/dist/cjs/instance/autogen/wasm2.d.ts +1 -0
  19. package/dist/cjs/instance/autogen/wasm2.js +4 -0
  20. package/dist/cjs/instance/bindings-smoldot-light.d.ts +154 -0
  21. package/dist/cjs/instance/bindings-smoldot-light.js +266 -0
  22. package/dist/cjs/instance/bindings-wasi.d.ts +23 -0
  23. package/dist/cjs/instance/bindings-wasi.js +142 -0
  24. package/dist/cjs/instance/bindings.d.ts +31 -0
  25. package/dist/cjs/instance/bindings.js +5 -0
  26. package/dist/cjs/instance/buffer.d.ts +10 -0
  27. package/dist/cjs/instance/buffer.js +53 -0
  28. package/dist/cjs/instance/instance.d.ts +45 -0
  29. package/dist/cjs/instance/instance.js +301 -0
  30. package/dist/cjs/instance/raw-instance.d.ts +65 -0
  31. package/dist/cjs/instance/raw-instance.js +72 -0
  32. package/dist/cjs/package.json +3 -0
  33. package/dist/mjs/base64.d.ts +22 -0
  34. package/dist/mjs/base64.js +97 -0
  35. package/dist/mjs/client.d.ts +287 -0
  36. package/dist/mjs/client.js +165 -0
  37. package/dist/mjs/index-browser.d.ts +11 -0
  38. package/dist/mjs/index-browser.js +455 -0
  39. package/dist/mjs/index-deno.d.ts +10 -0
  40. package/dist/mjs/index-deno.js +253 -0
  41. package/dist/mjs/index-nodejs.d.ts +10 -0
  42. package/dist/mjs/index-nodejs.js +164 -0
  43. package/dist/mjs/instance/autogen/wasm.d.ts +2 -0
  44. package/dist/mjs/instance/autogen/wasm.js +4 -0
  45. package/dist/mjs/instance/autogen/wasm0.d.ts +1 -0
  46. package/dist/mjs/instance/autogen/wasm0.js +1 -0
  47. package/dist/mjs/instance/autogen/wasm1.d.ts +1 -0
  48. package/dist/mjs/instance/autogen/wasm1.js +1 -0
  49. package/dist/mjs/instance/autogen/wasm2.d.ts +1 -0
  50. package/dist/mjs/instance/autogen/wasm2.js +1 -0
  51. package/dist/mjs/instance/bindings-smoldot-light.d.ts +154 -0
  52. package/dist/mjs/instance/bindings-smoldot-light.js +261 -0
  53. package/dist/mjs/instance/bindings-wasi.d.ts +23 -0
  54. package/{src → dist/mjs/instance}/bindings-wasi.js +47 -58
  55. package/dist/mjs/instance/bindings.d.ts +31 -0
  56. package/dist/mjs/instance/bindings.js +4 -0
  57. package/dist/mjs/instance/buffer.d.ts +10 -0
  58. package/dist/mjs/instance/buffer.js +46 -0
  59. package/dist/mjs/instance/instance.d.ts +45 -0
  60. package/dist/mjs/instance/instance.js +293 -0
  61. package/dist/mjs/instance/raw-instance.d.ts +65 -0
  62. package/dist/mjs/instance/raw-instance.js +67 -0
  63. package/dist/mjs/package.json +3 -0
  64. package/package.json +35 -19
  65. package/src/autogen/wasm.js +0 -1
  66. package/src/bindings-smoldot-js.js +0 -223
  67. package/src/compat-browser.js +0 -25
  68. package/src/compat-nodejs.js +0 -30
  69. package/src/health.js +0 -206
  70. package/src/index.d.ts +0 -68
  71. package/src/index.js +0 -192
  72. package/src/index.test-d.ts +0 -36
  73. package/src/tsconfig.json +0 -13
  74. package/src/worker.js +0 -151
@@ -0,0 +1,455 @@
1
+ // Smoldot
2
+ // Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
3
+ // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
+ return new (P || (P = Promise))(function (resolve, reject) {
7
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11
+ });
12
+ };
13
+ // This program is free software: you can redistribute it and/or modify
14
+ // it under the terms of the GNU General Public License as published by
15
+ // the Free Software Foundation, either version 3 of the License, or
16
+ // (at your option) any later version.
17
+ // This program is distributed in the hope that it will be useful,
18
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
+ // GNU General Public License for more details.
21
+ // You should have received a copy of the GNU General Public License
22
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
23
+ /// <reference lib="dom" />
24
+ import { start as innerStart } from './client.js';
25
+ import { ConnectionError } from './instance/instance.js';
26
+ import { classicDecode, multibaseBase64Decode } from './base64.js';
27
+ import { inflate } from 'pako';
28
+ export { AddChainError, AlreadyDestroyedError, CrashError, JsonRpcDisabledError, MalformedJsonRpcError, QueueFullError } from './client.js';
29
+ /**
30
+ * Initializes a new client. This is a pre-requisite to connecting to a blockchain.
31
+ *
32
+ * Can never fail.
33
+ *
34
+ * @param options Configuration of the client. Defaults to `{}`.
35
+ */
36
+ export function start(options) {
37
+ options = options || {};
38
+ return innerStart(options, {
39
+ trustedBase64DecodeAndZlibInflate: (input) => {
40
+ return Promise.resolve(inflate(classicDecode(input)));
41
+ },
42
+ registerShouldPeriodicallyYield: (callback) => {
43
+ const wrappedCallback = () => callback(document.visibilityState === 'visible');
44
+ document.addEventListener('visibilitychange', wrappedCallback);
45
+ return [document.visibilityState === 'visible', () => { document.removeEventListener('visibilitychange', wrappedCallback); }];
46
+ },
47
+ performanceNow: () => {
48
+ return performance.now();
49
+ },
50
+ getRandomValues: (buffer) => {
51
+ const crypto = globalThis.crypto;
52
+ if (!crypto)
53
+ throw new Error('randomness not available');
54
+ crypto.getRandomValues(buffer);
55
+ },
56
+ connect: (config) => {
57
+ return connect(config, (options === null || options === void 0 ? void 0 : options.forbidWs) || false, (options === null || options === void 0 ? void 0 : options.forbidNonLocalWs) || false, (options === null || options === void 0 ? void 0 : options.forbidWss) || false, (options === null || options === void 0 ? void 0 : options.forbidWebRtc) || false);
58
+ }
59
+ });
60
+ }
61
+ /**
62
+ * Tries to open a new connection using the given configuration.
63
+ *
64
+ * @see Connection
65
+ * @throws {@link ConnectionError} If the multiaddress couldn't be parsed or contains an invalid protocol.
66
+ */
67
+ function connect(config, forbidWs, forbidNonLocalWs, forbidWss, forbidWebRTC) {
68
+ // Attempt to parse the multiaddress.
69
+ // TODO: remove support for `/wss` in a long time (https://github.com/paritytech/smoldot/issues/1940)
70
+ const wsParsed = config.address.match(/^\/(ip4|ip6|dns4|dns6|dns)\/(.*?)\/tcp\/(.*?)\/(ws|wss|tls\/ws)$/);
71
+ const webRTCParsed = config.address.match(/^\/(ip4|ip6)\/(.*?)\/udp\/(.*?)\/webrtc\/certhash\/(.*?)$/);
72
+ if (wsParsed != null) {
73
+ let connection;
74
+ const proto = (wsParsed[4] == 'ws') ? 'ws' : 'wss';
75
+ if ((proto == 'ws' && forbidWs) ||
76
+ (proto == 'ws' && wsParsed[2] != 'localhost' && wsParsed[2] != '127.0.0.1' && forbidNonLocalWs) ||
77
+ (proto == 'wss' && forbidWss)) {
78
+ throw new ConnectionError('Connection type not allowed');
79
+ }
80
+ const url = (wsParsed[1] == 'ip6') ?
81
+ (proto + "://[" + wsParsed[2] + "]:" + wsParsed[3]) :
82
+ (proto + "://" + wsParsed[2] + ":" + wsParsed[3]);
83
+ connection = new WebSocket(url);
84
+ connection.binaryType = 'arraybuffer';
85
+ connection.onopen = () => {
86
+ config.onOpen({ type: 'single-stream', handshake: 'multistream-select-noise-yamux' });
87
+ };
88
+ connection.onclose = (event) => {
89
+ const message = "Error code " + event.code + (!!event.reason ? (": " + event.reason) : "");
90
+ config.onConnectionReset(message);
91
+ };
92
+ connection.onmessage = (msg) => {
93
+ config.onMessage(new Uint8Array(msg.data));
94
+ };
95
+ return {
96
+ reset: () => {
97
+ connection.onopen = null;
98
+ connection.onclose = null;
99
+ connection.onmessage = null;
100
+ connection.onerror = null;
101
+ connection.close();
102
+ },
103
+ send: (data) => {
104
+ connection.send(data);
105
+ },
106
+ openOutSubstream: () => { throw new Error('Wrong connection type'); }
107
+ };
108
+ }
109
+ else if (webRTCParsed != null) {
110
+ const targetPort = webRTCParsed[3];
111
+ if (forbidWebRTC || targetPort === '0') {
112
+ throw new ConnectionError('Connection type not allowed');
113
+ }
114
+ const ipVersion = webRTCParsed[1] == 'ip4' ? '4' : '6';
115
+ const targetIp = webRTCParsed[2];
116
+ const remoteCertMultibase = webRTCParsed[4];
117
+ // The payload of `/certhash` is the hash of the self-generated certificate that the
118
+ // server presents.
119
+ // This function throws an exception if the certhash isn't correct. For this reason, this call
120
+ // is performed as part of the parsing of the multiaddr.
121
+ const remoteCertMultihash = multibaseBase64Decode(remoteCertMultibase);
122
+ const remoteCertSha256Hash = multihashToSha256(remoteCertMultihash);
123
+ // TODO: detect localhost for Firefox? https://bugzilla.mozilla.org/show_bug.cgi?id=1659672
124
+ // Note that `pc` can be the connection, but also null or undefined.
125
+ // `undefined` means "certificate generation in progress", while `null` means "opening must
126
+ // be cancelled".
127
+ // While it would be better to use for example a string instead of `null`, using `null` lets
128
+ // us use the `!` operator more easily and leads to more readable code.
129
+ let pc = undefined;
130
+ // Contains the data channels that are open and have been reported to smoldot.
131
+ const dataChannels = new Map();
132
+ // For various reasons explained below, we open a data channel in advance without reporting it
133
+ // to smoldot. This data channel is stored in this variable. Once it is reported to smoldot,
134
+ // it is inserted in `dataChannels`.
135
+ let handshakeDataChannel;
136
+ // Multihash-encoded DTLS certificate of the local node. Unknown as long as it hasn't been
137
+ // generated.
138
+ // TODO: could be merged with `pc` in one variable, and maybe even the other fields as well
139
+ let localTlsCertificateMultihash;
140
+ // Kills all the JavaScript objects (the connection and all its substreams), ensuring that no
141
+ // callback will be called again. Doesn't report anything to smoldot, as this should be done
142
+ // by the caller.
143
+ const killAllJs = () => {
144
+ // The `RTCPeerConnection` is created pretty quickly. It is however still possible for
145
+ // smoldot to cancel the opening, in which case `pc` will still be undefined.
146
+ if (!pc) {
147
+ console.assert(dataChannels.size === 0 && !handshakeDataChannel, "substreams exist while pc is undef");
148
+ pc = null;
149
+ return;
150
+ }
151
+ pc.onconnectionstatechange = null;
152
+ pc.onnegotiationneeded = null;
153
+ pc.ondatachannel = null;
154
+ for (const channel of Array.from(dataChannels.values())) {
155
+ channel.onopen = null;
156
+ channel.onerror = null;
157
+ channel.onclose = null;
158
+ channel.onmessage = null;
159
+ }
160
+ dataChannels.clear();
161
+ if (handshakeDataChannel) {
162
+ handshakeDataChannel.onopen = null;
163
+ handshakeDataChannel.onerror = null;
164
+ handshakeDataChannel.onclose = null;
165
+ handshakeDataChannel.onmessage = null;
166
+ }
167
+ handshakeDataChannel = undefined;
168
+ pc.close(); // Not necessarily necessary, but it doesn't hurt to do so.
169
+ };
170
+ // Function that configures a newly-opened channel and adds it to the map. Used for both
171
+ // inbound and outbound substreams.
172
+ const addChannel = (dataChannel, direction) => {
173
+ const dataChannelId = dataChannel.id;
174
+ dataChannel.binaryType = 'arraybuffer';
175
+ let isOpen = false;
176
+ dataChannel.onopen = () => {
177
+ console.assert(!isOpen, "substream opened twice");
178
+ isOpen = true;
179
+ if (direction === 'first-outbound') {
180
+ console.assert(dataChannels.size === 0, "dataChannels not empty when opening");
181
+ console.assert(handshakeDataChannel === dataChannel, "handshake substream mismatch");
182
+ config.onOpen({
183
+ type: 'multi-stream',
184
+ handshake: 'webrtc',
185
+ // `addChannel` can never be called before the local certificate is generated, so this
186
+ // value is always defined.
187
+ localTlsCertificateMultihash: localTlsCertificateMultihash,
188
+ remoteTlsCertificateMultihash: remoteCertMultihash
189
+ });
190
+ }
191
+ else {
192
+ console.assert(direction !== 'outbound' || !handshakeDataChannel, "handshakeDataChannel still defined");
193
+ config.onStreamOpened(dataChannelId, direction);
194
+ }
195
+ };
196
+ dataChannel.onerror = dataChannel.onclose = (_error) => {
197
+ // A couple of different things could be happening here.
198
+ if (handshakeDataChannel === dataChannel && !isOpen) {
199
+ // The handshake data channel that we have opened ahead of time failed to open. As this
200
+ // happens before we have reported the WebRTC connection as a whole as being open, we
201
+ // need to report that the connection has failed to open.
202
+ killAllJs();
203
+ // Note that the event doesn't give any additional reason for the failure.
204
+ config.onConnectionReset("handshake data channel failed to open");
205
+ }
206
+ else if (handshakeDataChannel === dataChannel) {
207
+ // The handshake data channel has been closed before we reported it to smoldot. This
208
+ // isn't really a problem. We just update the state and continue running. If smoldot
209
+ // requests a substream, another one will be opened. It could be a valid implementation
210
+ // to also just kill the entire connection, however doing so is a bit too intrusive and
211
+ // punches through abstraction layers.
212
+ handshakeDataChannel.onopen = null;
213
+ handshakeDataChannel.onerror = null;
214
+ handshakeDataChannel.onclose = null;
215
+ handshakeDataChannel.onmessage = null;
216
+ handshakeDataChannel = undefined;
217
+ }
218
+ else if (!isOpen) {
219
+ // Substream wasn't opened yet and thus has failed to open. The API has no mechanism to
220
+ // report substream openings failures. We could try opening it again, but given that
221
+ // it's unlikely to succeed, we simply opt to kill the entire connection.
222
+ killAllJs();
223
+ // Note that the event doesn't give any additional reason for the failure.
224
+ config.onConnectionReset("data channel failed to open");
225
+ }
226
+ else {
227
+ // Substream was open and is now closed. Normal situation.
228
+ config.onStreamReset(dataChannelId);
229
+ }
230
+ };
231
+ dataChannel.onmessage = (m) => {
232
+ // The `data` field is an `ArrayBuffer`.
233
+ config.onMessage(new Uint8Array(m.data), dataChannelId);
234
+ };
235
+ if (direction !== 'first-outbound')
236
+ dataChannels.set(dataChannelId, dataChannel);
237
+ else
238
+ handshakeDataChannel = dataChannel;
239
+ };
240
+ // It is possible for the browser to use multiple different certificates.
241
+ // In order for our local certificate to be deterministic, we need to generate it manually and
242
+ // set it explicitly as part of the configuration.
243
+ // According to <https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-generatecertificate>,
244
+ // browsers are guaranteed to support `{ name: "ECDSA", namedCurve: "P-256" }`.
245
+ RTCPeerConnection.generateCertificate({ name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" }).then((localCertificate) => __awaiter(this, void 0, void 0, function* () {
246
+ if (pc === null)
247
+ return;
248
+ // Create a new WebRTC connection.
249
+ pc = new RTCPeerConnection({ certificates: [localCertificate] });
250
+ // We need to build the multihash corresponding to the local certificate.
251
+ // While there exists a `RTCPeerConnection.getFingerprints` function, Firefox notably
252
+ // doesn't support it.
253
+ // See <https://developer.mozilla.org/en-US/docs/Web/API/RTCCertificate#browser_compatibility>
254
+ // An alternative to `getFingerprints` is to ask the browser to generate an SDP offer and
255
+ // extract from fingerprint from it. Because we explicitly provide a certificate, we have
256
+ // the guarantee that the list of certificates will always be the same whenever an SDP offer
257
+ // is generated by the browser. However, while this alternative does work on Firefox, it
258
+ // doesn't on Chrome, as the SDP offer is for some reason missing the fingerprints.
259
+ // Therefore, our strategy is to use `getFingerprints` when it is available (i.e. every
260
+ // browser except Firefox), and parse the SDP offer when it is not (i.e. Firefox). In the
261
+ // future, only `getFingerprints` would be used.
262
+ let localTlsCertificateHex;
263
+ if (localCertificate.getFingerprints) {
264
+ for (const { algorithm, value } of localCertificate.getFingerprints()) {
265
+ if (algorithm === 'sha-256') {
266
+ localTlsCertificateHex = value;
267
+ break;
268
+ }
269
+ }
270
+ }
271
+ else {
272
+ const localSdpOffer = yield pc.createOffer();
273
+ // Note that this regex is not strict. The browser isn't a malicious actor, and the
274
+ // objective of this regex is not to detect invalid input.
275
+ const localSdpOfferFingerprintMatch = localSdpOffer.sdp.match(/a(\s*)=(\s*)fingerprint:(\s*)(sha|SHA)-256(\s*)(([a-fA-F0-9]{2}(:)*){32})/);
276
+ if (localSdpOfferFingerprintMatch) {
277
+ localTlsCertificateHex = localSdpOfferFingerprintMatch[6];
278
+ }
279
+ }
280
+ if (localTlsCertificateHex === undefined) {
281
+ // Because we've already returned from the `connect` function at this point, we pretend
282
+ // that the connection has failed to open.
283
+ config.onConnectionReset('Failed to obtain the browser certificate fingerprint');
284
+ return;
285
+ }
286
+ localTlsCertificateMultihash = new Uint8Array(34);
287
+ localTlsCertificateMultihash.set([0x12, 32], 0);
288
+ localTlsCertificateMultihash.set(localTlsCertificateHex.split(':').map((s) => parseInt(s, 16)), 2);
289
+ // `onconnectionstatechange` is used to detect when the connection has closed or has failed
290
+ // to open.
291
+ // Note that smoldot will think that the connection is open even when it is still opening.
292
+ // Therefore we don't care about events concerning the fact that the connection is now fully
293
+ // open.
294
+ pc.onconnectionstatechange = (_event) => {
295
+ if (pc.connectionState == "closed" || pc.connectionState == "disconnected" || pc.connectionState == "failed") {
296
+ killAllJs();
297
+ config.onConnectionReset("WebRTC state transitioned to " + pc.connectionState);
298
+ }
299
+ };
300
+ pc.onnegotiationneeded = (_event) => __awaiter(this, void 0, void 0, function* () {
301
+ var _a;
302
+ // Create a new offer and set it as local description.
303
+ let sdpOffer = (yield pc.createOffer()).sdp;
304
+ // We check that the locally-generated SDP offer has a data channel with the UDP
305
+ // protocol. If that isn't the case, the connection will likely fail.
306
+ if (sdpOffer.match(/^m=application(\s+)(\d+)(\s+)UDP\/DTLS\/SCTP(\s+)webrtc-datachannel$/m) === null) {
307
+ console.error("Local offer doesn't contain UDP data channel. WebRTC connections will likely fail. Please report this issue.");
308
+ }
309
+ // According to the libp2p WebRTC spec, the ufrag and pwd are the same
310
+ // randomly-generated string on both sides, and must be prefixed with
311
+ // `libp2p-webrtc-v1:`. We modify the local description to ensure that.
312
+ // While we could randomly generate a new string, we just grab the one that the
313
+ // browser has generated, in order to make sure that it respects the constraints
314
+ // of the ICE protocol.
315
+ const browserGeneratedPwd = (_a = sdpOffer.match(/^a=ice-pwd:(.+)$/m)) === null || _a === void 0 ? void 0 : _a.at(1);
316
+ if (browserGeneratedPwd === undefined) {
317
+ console.error("Failed to set ufrag to pwd. WebRTC connections will likely fail. Please report this issue.");
318
+ }
319
+ const ufragPwd = "libp2p+webrtc+v1/" + browserGeneratedPwd;
320
+ sdpOffer = sdpOffer.replace(/^a=ice-ufrag.*$/m, 'a=ice-ufrag:' + ufragPwd);
321
+ sdpOffer = sdpOffer.replace(/^a=ice-pwd.*$/m, 'a=ice-pwd:' + ufragPwd);
322
+ yield pc.setLocalDescription({ type: 'offer', sdp: sdpOffer });
323
+ // Transform certificate hash into fingerprint (upper-hex; each byte separated by ":").
324
+ const fingerprint = Array.from(remoteCertSha256Hash).map((n) => ("0" + n.toString(16)).slice(-2).toUpperCase()).join(':');
325
+ // Note that the trailing line feed is important, as otherwise Chrome
326
+ // fails to parse the payload.
327
+ const remoteSdp =
328
+ // Version of the SDP protocol. Always 0. (RFC8866)
329
+ "v=0" + "\n" +
330
+ // Identifies the creator of the SDP document. We are allowed to use dummy values
331
+ // (`-` and `0.0.0.0`) to remain anonymous, which we do. Note that "IN" means
332
+ // "Internet" (and not "input"). (RFC8866)
333
+ "o=- 0 0 IN IP" + ipVersion + " " + targetIp + "\n" +
334
+ // Name for the session. We are allowed to pass a dummy `-`. (RFC8866)
335
+ "s=-" + "\n" +
336
+ // Start and end of the validity of the session. `0 0` means that the session never
337
+ // expires. (RFC8866)
338
+ "t=0 0" + "\n" +
339
+ // A lite implementation is only appropriate for devices that will
340
+ // always be connected to the public Internet and have a public
341
+ // IP address at which it can receive packets from any
342
+ // correspondent. ICE will not function when a lite implementation
343
+ // is placed behind a NAT (RFC8445).
344
+ "a=ice-lite" + "\n" +
345
+ // A `m=` line describes a request to establish a certain protocol.
346
+ // The protocol in this line (i.e. `TCP/DTLS/SCTP` or `UDP/DTLS/SCTP`) must always be
347
+ // the same as the one in the offer. We know that this is true because checked above.
348
+ // The `<fmt>` component must always be `webrtc-datachannel` for WebRTC.
349
+ // The rest of the SDP payload adds attributes to this specific media stream.
350
+ // RFCs: 8839, 8866, 8841
351
+ "m=application " + targetPort + " " + "UDP/DTLS/SCTP webrtc-datachannel" + "\n" +
352
+ // Indicates the IP address of the remote.
353
+ // Note that "IN" means "Internet" (and not "input").
354
+ "c=IN IP" + ipVersion + " " + targetIp + "\n" +
355
+ // Media ID - uniquely identifies this media stream (RFC9143).
356
+ "a=mid:0" + "\n" +
357
+ // Indicates that we are complying with RFC8839 (as oppposed to the legacy RFC5245).
358
+ "a=ice-options:ice2" + "\n" +
359
+ // ICE username and password, which are used for establishing and
360
+ // maintaining the ICE connection. (RFC8839)
361
+ // These values are set according to the libp2p WebRTC specification.
362
+ "a=ice-ufrag:" + ufragPwd + "\n" +
363
+ "a=ice-pwd:" + ufragPwd + "\n" +
364
+ // Fingerprint of the certificate that the server will use during the TLS
365
+ // handshake. (RFC8122)
366
+ // MUST be derived from the certificate used by the answerer (server).
367
+ "a=fingerprint:sha-256 " + fingerprint + "\n" +
368
+ // Indicates that the remote DTLS server will only listen for incoming
369
+ // connections. (RFC5763)
370
+ // The answerer (server) MUST not be located behind a NAT (RFC6135).
371
+ "a=setup:passive" + "\n" +
372
+ // The SCTP port (RFC8841)
373
+ // Note it's different from the "m=" line port value, which
374
+ // indicates the port of the underlying transport-layer protocol
375
+ // (UDP or TCP)
376
+ "a=sctp-port:5000" + "\n" +
377
+ // The maximum SCTP user message size (in bytes) (RFC8841)
378
+ "a=max-message-size:16384" + "\n" + // TODO: should this be part of the spec?
379
+ // A transport address for a candidate that can be used for connectivity
380
+ // checks (RFC8839).
381
+ "a=candidate:1 1 UDP 1 " + targetIp + " " + targetPort + " typ host" + "\n";
382
+ yield pc.setRemoteDescription({ type: "answer", sdp: remoteSdp });
383
+ });
384
+ pc.ondatachannel = ({ channel }) => {
385
+ // TODO: is the substream maybe already open? according to the Internet it seems that no but it's unclear
386
+ addChannel(channel, 'inbound');
387
+ };
388
+ // Creating a `RTCPeerConnection` doesn't actually do anything before `createDataChannel` is
389
+ // called. Smoldot's API, however, requires you to treat entire connections as open or
390
+ // closed. We know, according to the libp2p WebRTC specification, that every connection
391
+ // always starts with a substream where a handshake is performed. After we've reported that
392
+ // the connection is open, smoldot will open a substream in order to perform the handshake.
393
+ // Instead of following this API, we open this substream in advance, and will notify smoldot
394
+ // that the connection is open when the substream is open.
395
+ // Note that the label passed to `createDataChannel` is required to be empty as per the
396
+ // libp2p WebRTC specification.
397
+ addChannel(pc.createDataChannel("", { id: 0, negotiated: true }), 'first-outbound');
398
+ }));
399
+ return {
400
+ reset: (streamId) => {
401
+ // If `streamId` is undefined, then the whole connection must be destroyed.
402
+ if (streamId === undefined) {
403
+ killAllJs();
404
+ }
405
+ else {
406
+ const channel = dataChannels.get(streamId);
407
+ channel.onopen = null;
408
+ channel.onerror = null;
409
+ channel.onclose = null;
410
+ channel.onmessage = null;
411
+ channel.close();
412
+ dataChannels.delete(streamId);
413
+ }
414
+ },
415
+ send: (data, streamId) => {
416
+ dataChannels.get(streamId).send(data);
417
+ },
418
+ openOutSubstream: () => {
419
+ // `openOutSubstream` can only be called after we have called `config.onOpen`, therefore
420
+ // `pc` is guaranteed to be non-null.
421
+ // As explained above, we open a data channel ahead of time. If this data channel is still
422
+ // there, we report it.
423
+ if (handshakeDataChannel) {
424
+ // Do this asynchronously because calling callbacks within callbacks is error-prone.
425
+ (() => __awaiter(this, void 0, void 0, function* () {
426
+ // We need to check again if `handshakeDataChannel` is still defined, as the
427
+ // connection might have been closed.
428
+ if (handshakeDataChannel) {
429
+ config.onStreamOpened(handshakeDataChannel.id, 'outbound');
430
+ dataChannels.set(handshakeDataChannel.id, handshakeDataChannel);
431
+ handshakeDataChannel = undefined;
432
+ }
433
+ }))();
434
+ }
435
+ else {
436
+ // Note that the label passed to `createDataChannel` is required to be empty as per the
437
+ // libp2p WebRTC specification.
438
+ addChannel(pc.createDataChannel(""), 'outbound');
439
+ }
440
+ }
441
+ };
442
+ }
443
+ else {
444
+ throw new ConnectionError('Unrecognized multiaddr format');
445
+ }
446
+ }
447
+ /// Parses a multihash-multibase-encoded string into a SHA256 hash.
448
+ ///
449
+ /// Throws an exception if the multihash algorithm isn't SHA256.
450
+ const multihashToSha256 = (certMultihash) => {
451
+ if (certMultihash.length != 34 || certMultihash[0] != 0x12 || certMultihash[1] != 32) {
452
+ throw new Error('Certificate multihash is not SHA-256');
453
+ }
454
+ return new Uint8Array(certMultihash.slice(2));
455
+ };
@@ -0,0 +1,10 @@
1
+ import { Client, ClientOptions } from './client.js';
2
+ export { AddChainError, AddChainOptions, AlreadyDestroyedError, Chain, Client, ClientOptions, CrashError, MalformedJsonRpcError, QueueFullError, JsonRpcDisabledError, LogCallback } from './client.js';
3
+ /**
4
+ * Initializes a new client. This is a pre-requisite to connecting to a blockchain.
5
+ *
6
+ * Can never fail.
7
+ *
8
+ * @param options Configuration of the client. Defaults to `{}`.
9
+ */
10
+ export declare function start(options?: ClientOptions): Client;