smoldot 1.0.3 → 1.0.5

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