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,36 +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.JsonRpcDisabledError = exports.QueueFullError = exports.MalformedJsonRpcError = 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
- const client_js_1 = require("./client.js");
27
- const instance_js_1 = require("./instance/instance.js");
28
- var client_js_2 = require("./client.js");
29
- Object.defineProperty(exports, "AddChainError", { enumerable: true, get: function () { return client_js_2.AddChainError; } });
30
- Object.defineProperty(exports, "AlreadyDestroyedError", { enumerable: true, get: function () { return client_js_2.AlreadyDestroyedError; } });
31
- Object.defineProperty(exports, "CrashError", { enumerable: true, get: function () { return client_js_2.CrashError; } });
32
- Object.defineProperty(exports, "MalformedJsonRpcError", { enumerable: true, get: function () { return client_js_2.MalformedJsonRpcError; } });
33
- Object.defineProperty(exports, "QueueFullError", { enumerable: true, get: function () { return client_js_2.QueueFullError; } });
34
- Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get: function () { return client_js_2.JsonRpcDisabledError; } });
7
+ const no_auto_bytecode_deno_js_1 = require("./no-auto-bytecode-deno.js");
8
+ const bytecode_deno_js_1 = require("./bytecode-deno.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, "MalformedJsonRpcError", { enumerable: true, get: function () { return public_types_js_1.MalformedJsonRpcError; } });
14
+ Object.defineProperty(exports, "QueueFullError", { enumerable: true, get: function () { return public_types_js_1.QueueFullError; } });
15
+ Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get: function () { return public_types_js_1.JsonRpcDisabledError; } });
35
16
  /**
36
17
  * Initializes a new client. This is a pre-requisite to connecting to a blockchain.
37
18
  *
@@ -41,250 +22,6 @@ Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get:
41
22
  */
42
23
  function start(options) {
43
24
  options = options || {};
44
- return (0, client_js_1.start)(options || {}, {
45
- trustedBase64DecodeAndZlibInflate: (input) => __awaiter(this, void 0, void 0, function* () {
46
- const buffer = trustedBase64Decode(input);
47
- // This code has been copy-pasted from the official streams draft specification.
48
- // At the moment, it is found here: https://wicg.github.io/compression/#example-deflate-compress
49
- const ds = new DecompressionStream('deflate');
50
- const writer = ds.writable.getWriter();
51
- writer.write(buffer);
52
- writer.close();
53
- const output = [];
54
- const reader = ds.readable.getReader();
55
- let totalSize = 0;
56
- while (true) {
57
- const { value, done } = yield reader.read();
58
- if (done)
59
- break;
60
- output.push(value);
61
- totalSize += value.byteLength;
62
- }
63
- const concatenated = new Uint8Array(totalSize);
64
- let offset = 0;
65
- for (const array of output) {
66
- concatenated.set(array, offset);
67
- offset += array.byteLength;
68
- }
69
- return concatenated;
70
- }),
71
- registerShouldPeriodicallyYield: (_callback) => {
72
- return [true, () => { }];
73
- },
74
- performanceNow: () => {
75
- return performance.now();
76
- },
77
- getRandomValues: (buffer) => {
78
- const crypto = globalThis.crypto;
79
- if (!crypto)
80
- throw new Error('randomness not available');
81
- crypto.getRandomValues(buffer);
82
- },
83
- connect: (config) => {
84
- return connect(config, (options === null || options === void 0 ? void 0 : options.forbidTcp) || false, (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);
85
- }
86
- });
25
+ return (0, no_auto_bytecode_deno_js_1.startWithBytecode)(Object.assign({ bytecode: (0, bytecode_deno_js_1.compileBytecode)() }, options));
87
26
  }
88
27
  exports.start = start;
89
- /**
90
- * Decodes a base64 string.
91
- *
92
- * The input is assumed to be correct.
93
- */
94
- function trustedBase64Decode(base64) {
95
- // This code is a bit sketchy due to the fact that we decode into a string, but it seems to
96
- // work.
97
- const binaryString = atob(base64);
98
- const size = binaryString.length;
99
- const bytes = new Uint8Array(size);
100
- for (let i = 0; i < size; i++) {
101
- bytes[i] = binaryString.charCodeAt(i);
102
- }
103
- return bytes;
104
- }
105
- /**
106
- * Tries to open a new connection using the given configuration.
107
- *
108
- * @see Connection
109
- * @throws {@link ConnectionError} If the multiaddress couldn't be parsed or contains an invalid protocol.
110
- */
111
- function connect(config, forbidTcp, forbidWs, forbidNonLocalWs, forbidWss) {
112
- // Attempt to parse the multiaddress.
113
- // TODO: remove support for `/wss` in a long time (https://github.com/paritytech/smoldot/issues/1940)
114
- const wsParsed = config.address.match(/^\/(ip4|ip6|dns4|dns6|dns)\/(.*?)\/tcp\/(.*?)\/(ws|wss|tls\/ws)$/);
115
- const tcpParsed = config.address.match(/^\/(ip4|ip6|dns4|dns6|dns)\/(.*?)\/tcp\/(.*?)$/);
116
- if (wsParsed != null) {
117
- const proto = (wsParsed[4] == 'ws') ? 'ws' : 'wss';
118
- if ((proto == 'ws' && forbidWs) ||
119
- (proto == 'ws' && wsParsed[2] != 'localhost' && wsParsed[2] != '127.0.0.1' && forbidNonLocalWs) ||
120
- (proto == 'wss' && forbidWss)) {
121
- throw new instance_js_1.ConnectionError('Connection type not allowed');
122
- }
123
- const url = (wsParsed[1] == 'ip6') ?
124
- (proto + "://[" + wsParsed[2] + "]:" + wsParsed[3]) :
125
- (proto + "://" + wsParsed[2] + ":" + wsParsed[3]);
126
- const socket = new WebSocket(url);
127
- socket.binaryType = 'arraybuffer';
128
- const bufferedAmountCheck = { quenedUnreportedBytes: 0, nextTimeout: 10 };
129
- const checkBufferedAmount = () => {
130
- if (socket.readyState != 1)
131
- return;
132
- // Note that we might expect `bufferedAmount` to always be <= the sum of the lengths
133
- // of all the data that has been sent, but that might not be the case. For this
134
- // reason, we use `bufferedAmount` as a hint rather than a correct value.
135
- const bufferedAmount = socket.bufferedAmount;
136
- let wasSent = bufferedAmountCheck.quenedUnreportedBytes - bufferedAmount;
137
- if (wasSent < 0)
138
- wasSent = 0;
139
- bufferedAmountCheck.quenedUnreportedBytes -= wasSent;
140
- if (bufferedAmountCheck.quenedUnreportedBytes != 0) {
141
- setTimeout(checkBufferedAmount, bufferedAmountCheck.nextTimeout);
142
- bufferedAmountCheck.nextTimeout *= 2;
143
- if (bufferedAmountCheck.nextTimeout > 500)
144
- bufferedAmountCheck.nextTimeout = 500;
145
- }
146
- // Note: it is important to call `onWritableBytes` at the very end, as it might
147
- // trigger a call to `send`.
148
- if (wasSent != 0)
149
- config.onWritableBytes(wasSent);
150
- };
151
- socket.onopen = () => {
152
- config.onOpen({ type: 'single-stream', handshake: 'multistream-select-noise-yamux', initialWritableBytes: 1024 * 1024, writeClosable: false });
153
- };
154
- socket.onclose = (event) => {
155
- const message = "Error code " + event.code + (!!event.reason ? (": " + event.reason) : "");
156
- config.onConnectionReset(message);
157
- };
158
- socket.onmessage = (msg) => {
159
- config.onMessage(new Uint8Array(msg.data));
160
- };
161
- return {
162
- reset: () => {
163
- // We can't set these fields to null because the TypeScript definitions don't
164
- // allow it, but we can set them to dummy values.
165
- socket.onopen = () => { };
166
- socket.onclose = () => { };
167
- socket.onmessage = () => { };
168
- socket.onerror = () => { };
169
- socket.close();
170
- },
171
- send: (data) => {
172
- // The WebSocket library that we use seems to spontaneously transition connections
173
- // to the "closed" state but not call the `onclosed` callback immediately. Calling
174
- // `send` on that object throws an exception. In order to avoid panicking smoldot,
175
- // we thus absorb any exception thrown here.
176
- // See also <https://github.com/paritytech/smoldot/issues/2937>.
177
- try {
178
- socket.send(data);
179
- if (bufferedAmountCheck.quenedUnreportedBytes == 0) {
180
- bufferedAmountCheck.nextTimeout = 10;
181
- setTimeout(checkBufferedAmount, 10);
182
- }
183
- bufferedAmountCheck.quenedUnreportedBytes += data.length;
184
- }
185
- catch (_error) { }
186
- },
187
- closeSend: () => { throw new Error('Wrong connection type'); },
188
- openOutSubstream: () => { throw new Error('Wrong connection type'); }
189
- };
190
- }
191
- else if (tcpParsed != null) {
192
- if (forbidTcp) {
193
- throw new instance_js_1.ConnectionError('TCP connections not available');
194
- }
195
- const socket = {
196
- destroyed: false,
197
- inner: Deno.connect({
198
- hostname: tcpParsed[2],
199
- port: parseInt(tcpParsed[3], 10),
200
- }).catch((error) => {
201
- socket.destroyed = true;
202
- config.onConnectionReset(error.toString());
203
- return null;
204
- })
205
- };
206
- socket.inner = socket.inner.then((established) => {
207
- // TODO: at the time of writing of this comment, `setNoDelay` is still unstable
208
- //established.setNoDelay();
209
- if (socket.destroyed)
210
- return established;
211
- config.onOpen({ type: 'single-stream', handshake: 'multistream-select-noise-yamux', initialWritableBytes: 1024 * 1024, writeClosable: true });
212
- // Spawns an asynchronous task that continuously reads from the socket.
213
- // Every time data is read, the task re-executes itself in order to continue reading.
214
- // The task ends automatically if an EOF or error is detected, which should also happen
215
- // if the user calls `close()`.
216
- const read = (readBuffer) => __awaiter(this, void 0, void 0, function* () {
217
- if (socket.destroyed || established === null)
218
- return;
219
- let outcome = null;
220
- try {
221
- outcome = yield established.read(readBuffer);
222
- }
223
- catch (error) {
224
- // The type of `error` is unclear, but we assume that it implements `Error`
225
- outcome = error.toString();
226
- }
227
- if (socket.destroyed)
228
- return;
229
- if (typeof outcome !== 'number' || outcome === null) {
230
- // The socket is reported closed, but `socket.destroyed` is still `false` (see
231
- // check above). As such, we must inform the inner layers.
232
- socket.destroyed = true;
233
- config.onConnectionReset(outcome === null ? "EOF when reading socket" : outcome);
234
- return;
235
- }
236
- console.assert(outcome !== 0); // `read` guarantees to return a non-zero value.
237
- config.onMessage(readBuffer.slice(0, outcome));
238
- return read(readBuffer);
239
- });
240
- read(new Uint8Array(1024));
241
- return established;
242
- });
243
- return {
244
- reset: () => {
245
- socket.destroyed = true;
246
- socket.inner.then((connec) => connec.close());
247
- },
248
- send: (data) => {
249
- let dataCopy = Uint8Array.from(data); // Deep copy of the data
250
- socket.inner = socket.inner.then((c) => __awaiter(this, void 0, void 0, function* () {
251
- while (dataCopy.length > 0) {
252
- if (socket.destroyed || c === null)
253
- return c;
254
- let outcome;
255
- try {
256
- outcome = yield c.write(dataCopy);
257
- config.onWritableBytes(dataCopy.length);
258
- }
259
- catch (error) {
260
- // The type of `error` is unclear, but we assume that it implements `Error`
261
- outcome = error.toString();
262
- }
263
- if (typeof outcome !== 'number') {
264
- // The socket is reported closed, but `socket.destroyed` is still
265
- // `false` (see check above). As such, we must inform the inner layers.
266
- socket.destroyed = true;
267
- config.onConnectionReset(outcome);
268
- return c;
269
- }
270
- // Note that, contrary to `read`, it is possible for `outcome` to be 0.
271
- // This happen if the write had to be interrupted, and the only thing
272
- // we have to do is try writing again.
273
- dataCopy = dataCopy.slice(outcome);
274
- }
275
- return c;
276
- }));
277
- },
278
- closeSend: () => {
279
- socket.inner = socket.inner.then((c) => __awaiter(this, void 0, void 0, function* () {
280
- yield (c === null || c === void 0 ? void 0 : c.closeWrite());
281
- return c;
282
- }));
283
- },
284
- openOutSubstream: () => { throw new Error('Wrong connection type'); }
285
- };
286
- }
287
- else {
288
- throw new instance_js_1.ConnectionError('Unrecognized multiaddr format');
289
- }
290
- }
@@ -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
  *
@@ -4,33 +4,15 @@
4
4
  // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.start = exports.JsonRpcDisabledError = exports.QueueFullError = exports.MalformedJsonRpcError = exports.CrashError = exports.AlreadyDestroyedError = exports.AddChainError = void 0;
7
- // This program is free software: you can redistribute it and/or modify
8
- // it under the terms of the GNU General Public License as published by
9
- // the Free Software Foundation, either version 3 of the License, or
10
- // (at your option) any later version.
11
- // This program is distributed in the hope that it will be useful,
12
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
13
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
- // GNU General Public License for more details.
15
- // You should have received a copy of the GNU General Public License
16
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
17
- // Note: if you modify these imports, please test both the ModuleJS and CommonJS generated
18
- // bindings. JavaScript being JavaScript, some libraries (such as `websocket`) have issues working
19
- // with both at the same time.
20
- const client_js_1 = require("./client.js");
21
- const instance_js_1 = require("./instance/instance.js");
22
- const ws_1 = require("ws");
23
- const pako_1 = require("pako");
24
- const node_perf_hooks_1 = require("node:perf_hooks");
25
- const node_net_1 = require("node:net");
26
- const node_crypto_1 = require("node:crypto");
27
- var client_js_2 = require("./client.js");
28
- Object.defineProperty(exports, "AddChainError", { enumerable: true, get: function () { return client_js_2.AddChainError; } });
29
- Object.defineProperty(exports, "AlreadyDestroyedError", { enumerable: true, get: function () { return client_js_2.AlreadyDestroyedError; } });
30
- Object.defineProperty(exports, "CrashError", { enumerable: true, get: function () { return client_js_2.CrashError; } });
31
- Object.defineProperty(exports, "MalformedJsonRpcError", { enumerable: true, get: function () { return client_js_2.MalformedJsonRpcError; } });
32
- Object.defineProperty(exports, "QueueFullError", { enumerable: true, get: function () { return client_js_2.QueueFullError; } });
33
- Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get: function () { return client_js_2.JsonRpcDisabledError; } });
7
+ const no_auto_bytecode_nodejs_js_1 = require("./no-auto-bytecode-nodejs.js");
8
+ const bytecode_nodejs_js_1 = require("./bytecode-nodejs.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, "MalformedJsonRpcError", { enumerable: true, get: function () { return public_types_js_1.MalformedJsonRpcError; } });
14
+ Object.defineProperty(exports, "QueueFullError", { enumerable: true, get: function () { return public_types_js_1.QueueFullError; } });
15
+ Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get: function () { return public_types_js_1.JsonRpcDisabledError; } });
34
16
  /**
35
17
  * Initializes a new client. This is a pre-requisite to connecting to a blockchain.
36
18
  *
@@ -40,186 +22,6 @@ Object.defineProperty(exports, "JsonRpcDisabledError", { enumerable: true, get:
40
22
  */
41
23
  function start(options) {
42
24
  options = options || {};
43
- return (0, client_js_1.start)(options || {}, {
44
- trustedBase64DecodeAndZlibInflate: (input) => {
45
- return Promise.resolve((0, pako_1.inflate)(Buffer.from(input, 'base64')));
46
- },
47
- registerShouldPeriodicallyYield: (_callback) => {
48
- return [true, () => { }];
49
- },
50
- performanceNow: () => {
51
- return node_perf_hooks_1.performance.now();
52
- },
53
- getRandomValues: (buffer) => {
54
- if (buffer.length >= 1024 * 1024)
55
- throw new Error('getRandomValues buffer too large');
56
- (0, node_crypto_1.randomFillSync)(buffer);
57
- },
58
- connect: (config) => {
59
- return connect(config, (options === null || options === void 0 ? void 0 : options.forbidTcp) || false, (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);
60
- }
61
- });
25
+ return (0, no_auto_bytecode_nodejs_js_1.startWithBytecode)(Object.assign({ bytecode: (0, bytecode_nodejs_js_1.compileBytecode)() }, options));
62
26
  }
63
27
  exports.start = start;
64
- /**
65
- * Tries to open a new connection using the given configuration.
66
- *
67
- * @see Connection
68
- * @throws {@link ConnectionError} If the multiaddress couldn't be parsed or contains an invalid protocol.
69
- */
70
- function connect(config, forbidTcp, forbidWs, forbidNonLocalWs, forbidWss) {
71
- // Attempt to parse the multiaddress.
72
- // TODO: remove support for `/wss` in a long time (https://github.com/paritytech/smoldot/issues/1940)
73
- const wsParsed = config.address.match(/^\/(ip4|ip6|dns4|dns6|dns)\/(.*?)\/tcp\/(.*?)\/(ws|wss|tls\/ws)$/);
74
- const tcpParsed = config.address.match(/^\/(ip4|ip6|dns4|dns6|dns)\/(.*?)\/tcp\/(.*?)$/);
75
- if (wsParsed != null) {
76
- const proto = (wsParsed[4] == 'ws') ? 'ws' : 'wss';
77
- if ((proto == 'ws' && forbidWs) ||
78
- (proto == 'ws' && wsParsed[2] != 'localhost' && wsParsed[2] != '127.0.0.1' && forbidNonLocalWs) ||
79
- (proto == 'wss' && forbidWss)) {
80
- throw new instance_js_1.ConnectionError('Connection type not allowed');
81
- }
82
- const url = (wsParsed[1] == 'ip6') ?
83
- (proto + "://[" + wsParsed[2] + "]:" + wsParsed[3]) :
84
- (proto + "://" + wsParsed[2] + ":" + wsParsed[3]);
85
- const socket = new ws_1.WebSocket(url);
86
- socket.binaryType = 'arraybuffer';
87
- const bufferedAmountCheck = { quenedUnreportedBytes: 0, nextTimeout: 10 };
88
- const checkBufferedAmount = () => {
89
- if (socket.readyState != 1)
90
- return;
91
- // Note that we might expect `bufferedAmount` to always be <= the sum of the lengths
92
- // of all the data that has been sent, but that seems to not be the case. It is
93
- // unclear whether this is intended or a bug, but is is likely that `bufferedAmount`
94
- // also includes WebSocket headers. For this reason, we use `bufferedAmount` as a hint
95
- // rather than a correct value.
96
- const bufferedAmount = socket.bufferedAmount;
97
- let wasSent = bufferedAmountCheck.quenedUnreportedBytes - bufferedAmount;
98
- if (wasSent < 0)
99
- wasSent = 0;
100
- bufferedAmountCheck.quenedUnreportedBytes -= wasSent;
101
- if (bufferedAmountCheck.quenedUnreportedBytes != 0) {
102
- setTimeout(checkBufferedAmount, bufferedAmountCheck.nextTimeout);
103
- bufferedAmountCheck.nextTimeout *= 2;
104
- if (bufferedAmountCheck.nextTimeout > 500)
105
- bufferedAmountCheck.nextTimeout = 500;
106
- }
107
- // Note: it is important to call `onWritableBytes` at the very end, as it might
108
- // trigger a call to `send`.
109
- if (wasSent != 0)
110
- config.onWritableBytes(wasSent);
111
- };
112
- socket.onopen = () => {
113
- config.onOpen({ type: 'single-stream', handshake: 'multistream-select-noise-yamux', initialWritableBytes: 1024 * 1024, writeClosable: false });
114
- };
115
- socket.onclose = (event) => {
116
- const message = "Error code " + event.code + (!!event.reason ? (": " + event.reason) : "");
117
- config.onConnectionReset(message);
118
- socket.onopen = () => { };
119
- socket.onclose = () => { };
120
- socket.onmessage = () => { };
121
- socket.onerror = () => { };
122
- };
123
- socket.onerror = (event) => {
124
- config.onConnectionReset(event.message);
125
- socket.onopen = () => { };
126
- socket.onclose = () => { };
127
- socket.onmessage = () => { };
128
- socket.onerror = () => { };
129
- };
130
- socket.onmessage = (msg) => {
131
- config.onMessage(new Uint8Array(msg.data));
132
- };
133
- return {
134
- reset: () => {
135
- // We can't set these fields to null because the TypeScript definitions don't
136
- // allow it, but we can set them to dummy values.
137
- socket.onopen = () => { };
138
- socket.onclose = () => { };
139
- socket.onmessage = () => { };
140
- socket.onerror = () => { };
141
- socket.close();
142
- },
143
- send: (data) => {
144
- socket.send(data);
145
- if (bufferedAmountCheck.quenedUnreportedBytes == 0) {
146
- bufferedAmountCheck.nextTimeout = 10;
147
- setTimeout(checkBufferedAmount, 10);
148
- }
149
- bufferedAmountCheck.quenedUnreportedBytes += data.length;
150
- },
151
- closeSend: () => { throw new Error('Wrong connection type'); },
152
- openOutSubstream: () => { throw new Error('Wrong connection type'); }
153
- };
154
- }
155
- else if (tcpParsed != null) {
156
- // `net` module will be missing when we're not in NodeJS.
157
- if (forbidTcp) {
158
- throw new instance_js_1.ConnectionError('TCP connections not available');
159
- }
160
- const socket = (0, node_net_1.createConnection)({
161
- host: tcpParsed[2],
162
- port: parseInt(tcpParsed[3], 10),
163
- });
164
- // Number of bytes queued using `socket.write` and where `write` has returned false.
165
- const drainingBytes = { num: 0 };
166
- socket.setNoDelay();
167
- socket.on('connect', () => {
168
- if (socket.destroyed)
169
- return;
170
- config.onOpen({
171
- type: 'single-stream', handshake: 'multistream-select-noise-yamux',
172
- initialWritableBytes: socket.writableHighWaterMark, writeClosable: true
173
- });
174
- });
175
- socket.on('close', (hasError) => {
176
- if (socket.destroyed)
177
- return;
178
- // NodeJS doesn't provide a reason why the closing happened, but only
179
- // whether it was caused by an error.
180
- const message = hasError ? "Error" : "Closed gracefully";
181
- config.onConnectionReset(message);
182
- });
183
- socket.on('error', () => { });
184
- socket.on('data', (message) => {
185
- if (socket.destroyed)
186
- return;
187
- config.onMessage(new Uint8Array(message.buffer));
188
- });
189
- socket.on('drain', () => {
190
- // The bytes queued using `socket.write` and where `write` has returned false have now
191
- // been sent. Notify the API that it can write more data.
192
- if (socket.destroyed)
193
- return;
194
- const val = drainingBytes.num;
195
- drainingBytes.num = 0;
196
- config.onWritableBytes(val);
197
- });
198
- return {
199
- reset: () => {
200
- socket.destroy();
201
- },
202
- send: (data) => {
203
- const dataLen = data.length;
204
- const allWritten = socket.write(data);
205
- if (allWritten) {
206
- setImmediate(() => {
207
- if (!socket.writable)
208
- return;
209
- config.onWritableBytes(dataLen);
210
- });
211
- }
212
- else {
213
- drainingBytes.num += dataLen;
214
- }
215
- },
216
- closeSend: () => {
217
- socket.end();
218
- },
219
- openOutSubstream: () => { throw new Error('Wrong connection type'); }
220
- };
221
- }
222
- else {
223
- throw new instance_js_1.ConnectionError('Unrecognized multiaddr format');
224
- }
225
- }