smoldot 2.0.1 → 2.0.3

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.
@@ -363,11 +363,16 @@ function start(options, wasmModule, platformBindings) {
363
363
  if (state.instance.status !== "ready")
364
364
  throw new Error(); // Internal error. Never supposed to happen.
365
365
  state.instance.instance.shutdownExecutor();
366
- state.instance = { status: "destroyed", error: new public_types_js_1.AlreadyDestroyedError() };
366
+ // Wait for the `executor-shutdown` event to be generated.
367
+ yield new Promise((resolve) => state.onExecutorShutdownOrWasmPanic = resolve);
368
+ // In case the instance crashes while we were waiting, we don't want to overwrite
369
+ // the error.
370
+ if (state.instance.status === "ready")
371
+ state.instance = { status: "destroyed", error: new public_types_js_1.AlreadyDestroyedError() };
367
372
  state.connections.forEach((connec) => connec.reset());
368
373
  state.connections.clear();
369
374
  for (const addChainResult of state.addChainResults) {
370
- addChainResult({ success: false, error: "Smoldot has crashed" });
375
+ addChainResult({ success: false, error: "Client.terminate() has been called" });
371
376
  }
372
377
  state.addChainResults = [];
373
378
  for (const chain of Array.from(state.chains.values())) {
@@ -377,8 +382,6 @@ function start(options, wasmModule, platformBindings) {
377
382
  chain.jsonRpcResponsesPromises = [];
378
383
  }
379
384
  state.chains.clear();
380
- // Wait for the `executor-shutdown` event to be generated.
381
- yield new Promise((resolve) => state.onExecutorShutdownOrWasmPanic = resolve);
382
385
  })
383
386
  };
384
387
  }
@@ -61,6 +61,30 @@ function startLocalInstance(config, wasmModule, eventCallback) {
61
61
  state.onShutdownExecutorOrWasmPanic = () => { };
62
62
  throw new Error();
63
63
  },
64
+ random_get: (ptr, len) => {
65
+ const instance = state.instance;
66
+ ptr >>>= 0;
67
+ len >>>= 0;
68
+ const baseBuffer = new Uint8Array(instance.exports.memory.buffer)
69
+ .subarray(ptr, ptr + len);
70
+ for (let iter = 0; iter < len; iter += 65536) {
71
+ // `baseBuffer.subarray` automatically saturates at the end of the buffer
72
+ config.getRandomValues(baseBuffer.subarray(iter, iter + 65536));
73
+ }
74
+ },
75
+ unix_timestamp_us: () => {
76
+ const value = Math.floor(Date.now());
77
+ if (value < 0)
78
+ throw new Error("UNIX timestamp inferior to 0");
79
+ return BigInt(value) * BigInt(1000);
80
+ },
81
+ monotonic_clock_us: () => {
82
+ const nowMs = config.performanceNow();
83
+ const nowMsInt = Math.floor(nowMs);
84
+ const now = BigInt(nowMsInt) * BigInt(1000) +
85
+ BigInt(Math.floor(((nowMs - nowMsInt) * 1000)));
86
+ return now;
87
+ },
64
88
  buffer_size: (bufferIndex) => {
65
89
  const buf = state.bufferIndices[bufferIndex];
66
90
  return buf.byteLength;
@@ -248,165 +272,12 @@ function startLocalInstance(config, wasmModule, eventCallback) {
248
272
  state.currentTask = null;
249
273
  }
250
274
  };
251
- const wasiBindings = {
252
- // Need to fill the buffer described by `ptr` and `len` with random data.
253
- // This data will be used in order to generate secrets. Do not use a dummy implementation!
254
- random_get: (ptr, len) => {
255
- const instance = state.instance;
256
- ptr >>>= 0;
257
- len >>>= 0;
258
- const baseBuffer = new Uint8Array(instance.exports.memory.buffer)
259
- .subarray(ptr, ptr + len);
260
- for (let iter = 0; iter < len; iter += 65536) {
261
- // `baseBuffer.subarray` automatically saturates at the end of the buffer
262
- config.getRandomValues(baseBuffer.subarray(iter, iter + 65536));
263
- }
264
- return 0;
265
- },
266
- clock_time_get: (clockId, _precision, outPtr) => {
267
- // See <https://github.com/rust-lang/rust/blob/master/library/std/src/sys/wasi/time.rs>
268
- // and <docs.rs/wasi/> for help.
269
- const instance = state.instance;
270
- const mem = new Uint8Array(instance.exports.memory.buffer);
271
- outPtr >>>= 0;
272
- // We ignore the precision, as it can't be implemented anyway.
273
- switch (clockId) {
274
- case 0: {
275
- // Realtime clock.
276
- const now = BigInt(Math.floor(Date.now())) * BigInt(1000000);
277
- buffer.writeUInt64LE(mem, outPtr, now);
278
- // Success.
279
- return 0;
280
- }
281
- case 1: {
282
- // Monotonic clock.
283
- const nowMs = config.performanceNow();
284
- const nowMsInt = Math.floor(nowMs);
285
- const now = BigInt(nowMsInt) * BigInt(1000000) +
286
- BigInt(Math.floor(((nowMs - nowMsInt) * 1000000)));
287
- buffer.writeUInt64LE(mem, outPtr, now);
288
- // Success.
289
- return 0;
290
- }
291
- default:
292
- // Return an `EINVAL` error.
293
- return 28;
294
- }
295
- },
296
- // Writing to a file descriptor is used in order to write to stdout/stderr.
297
- fd_write: (fd, addr, num, outPtr) => {
298
- const instance = state.instance;
299
- outPtr >>>= 0;
300
- // Only stdout and stderr are open for writing.
301
- if (fd != 1 && fd != 2) {
302
- return 8;
303
- }
304
- const mem = new Uint8Array(instance.exports.memory.buffer);
305
- // `fd_write` passes a buffer containing itself a list of pointers and lengths to the
306
- // actual buffers. See writev(2).
307
- let toWrite = "";
308
- let totalLength = 0;
309
- for (let i = 0; i < num; i++) {
310
- const buf = buffer.readUInt32LE(mem, addr + 4 * i * 2);
311
- const bufLen = buffer.readUInt32LE(mem, addr + 4 * (i * 2 + 1));
312
- toWrite += buffer.utf8BytesToString(mem, buf, bufLen);
313
- totalLength += bufLen;
314
- }
315
- const flushBuffer = (string) => {
316
- // As documented in the documentation of `println!`, lines are always split by a
317
- // single `\n` in Rust.
318
- while (true) {
319
- const index = string.indexOf('\n');
320
- if (index != -1) {
321
- // Note that it is questionnable to use `console.log` from within a
322
- // library. However this simply reflects the usage of `println!` in the
323
- // Rust code. In other words, it is `println!` that shouldn't be used in
324
- // the first place. The harm of not showing text printed with `println!`
325
- // at all is greater than the harm possibly caused by accidentally leaving
326
- // a `println!` in the code.
327
- console.log(string.substring(0, index));
328
- string = string.substring(index + 1);
329
- }
330
- else {
331
- return string;
332
- }
333
- }
334
- };
335
- // Append the newly-written data to either `stdout_buffer` or `stderr_buffer`, and
336
- // print their content if necessary.
337
- if (fd == 1) {
338
- state.stdoutBuffer += toWrite;
339
- state.stdoutBuffer = flushBuffer(state.stdoutBuffer);
340
- }
341
- else if (fd == 2) {
342
- state.stderrBuffer += toWrite;
343
- state.stderrBuffer = flushBuffer(state.stderrBuffer);
344
- }
345
- // Need to write in `out_ptr` how much data was "written".
346
- buffer.writeUInt32LE(mem, outPtr, totalLength);
347
- return 0;
348
- },
349
- // It's unclear how to properly implement yielding, but a no-op works fine as well.
350
- sched_yield: () => {
351
- return 0;
352
- },
353
- // Used by Rust in catastrophic situations, such as a double panic.
354
- proc_exit: (retCode) => {
355
- state.instance = null;
356
- eventCallback({
357
- ty: "wasm-panic",
358
- message: `proc_exit called: ${retCode}`,
359
- currentTask: state.currentTask
360
- });
361
- state.onShutdownExecutorOrWasmPanic();
362
- state.onShutdownExecutorOrWasmPanic = () => { };
363
- throw new Error();
364
- },
365
- // Return the number of environment variables and the total size of all environment
366
- // variables. This is called in order to initialize buffers before `environ_get`.
367
- environ_sizes_get: (argcOut, argvBufSizeOut) => {
368
- const instance = state.instance;
369
- argcOut >>>= 0;
370
- argvBufSizeOut >>>= 0;
371
- let totalLen = 0;
372
- config.envVars.forEach(e => totalLen += new TextEncoder().encode(e).length + 1); // +1 for trailing \0
373
- const mem = new Uint8Array(instance.exports.memory.buffer);
374
- buffer.writeUInt32LE(mem, argcOut, config.envVars.length);
375
- buffer.writeUInt32LE(mem, argvBufSizeOut, totalLen);
376
- return 0;
377
- },
378
- // Write the environment variables to the given pointers.
379
- // `argv` is a pointer to a buffer that must be overwritten with a list of pointers to
380
- // environment variables, and `argvBuf` is a pointer to a buffer where to actually store
381
- // the environment variables.
382
- // The sizes of the buffers were determined by calling `environ_sizes_get`.
383
- environ_get: (argv, argvBuf) => {
384
- const instance = state.instance;
385
- argv >>>= 0;
386
- argvBuf >>>= 0;
387
- const mem = new Uint8Array(instance.exports.memory.buffer);
388
- let argvPos = 0;
389
- let argvBufPos = 0;
390
- config.envVars.forEach(envVar => {
391
- const encoded = new TextEncoder().encode(envVar);
392
- buffer.writeUInt32LE(mem, argv + argvPos, argvBuf + argvBufPos);
393
- argvPos += 4;
394
- mem.set(encoded, argvBuf + argvBufPos);
395
- argvBufPos += encoded.length;
396
- buffer.writeUInt8(mem, argvBuf + argvBufPos, 0);
397
- argvBufPos += 1;
398
- });
399
- return 0;
400
- },
401
- };
402
275
  // Start the Wasm virtual machine.
403
276
  // The Rust code defines a list of imports that must be fulfilled by the environment. The second
404
277
  // parameter provides their implementations.
405
278
  const result = yield WebAssembly.instantiate(wasmModule, {
406
279
  // The functions with the "smoldot" prefix are specific to smoldot.
407
280
  "smoldot": smoldotJsBindings,
408
- // As the Rust code is compiled for wasi, some more wasi-specific imports exist.
409
- "wasi_snapshot_preview1": wasiBindings,
410
281
  });
411
282
  state.instance = result;
412
283
  // Smoldot requires an initial call to the `init` function in order to do its internal
@@ -142,12 +142,20 @@ export interface Chain {
142
142
  * The JSON-RPC callback will no longer be called. This is the case immediately after this
143
143
  * function is called. Any on-going JSON-RPC request is instantaneously aborted.
144
144
  *
145
- * Trying to use the chain again will lead to an exception being thrown.
145
+ * Trying to use the chain again will lead to a {@link AlreadyDestroyedError} exception
146
+ * being thrown.
146
147
  *
147
- * If this chain is a relay chain, then all parachains that use it will continue to work. Smoldot
148
- * automatically keeps alive all relay chains that have an active parachains. There is no need
149
- * to track parachains and relay chains, or to destroy them in the correct order, as this is
150
- * handled automatically internally.
148
+ * While the chain instantaneously disappears from the public API as soon as this function is
149
+ * called, its shutdown process actually happens asynchronously in the background. This means
150
+ * for example that networking connections to the chain will remain open for a little bit even
151
+ * after this function returns.
152
+ *
153
+ * If the chain is a relay chain, and that there exists {@link Chain} instances corresponding
154
+ * to parachains that are using this relay chain, then these parachains will continue to work
155
+ * and the relay chain will actually remain connected in the background.
156
+ * Smoldot automatically keeps alive all relay chains that have an active parachains. There
157
+ * is no need to track parachains and relay chains, or to destroy them in the correct order,
158
+ * as this is handled automatically internally.
151
159
  *
152
160
  * @throws {@link AlreadyDestroyedError} If the chain has already been removed or the client has been terminated.
153
161
  * @throws {@link CrashError} If the background client has crashed.