nano-rspow-web 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,10 @@ If you are looking for the same functionality on the server side, see the [nano-
4
4
 
5
5
  Nano (XNO) proof-of-work generation for browsers using WebAssembly and WebGPU.
6
6
 
7
- Tries WebGPU first, then automatically falls back to single-threaded CPU WebAssembly if WebGPU is unavailable.
7
+ The high-level API runs all probing and generation in a dedicated Worker. If Worker creation is blocked,
8
+ or local work is not recommended for the device, it refuses local work so the application can use its
9
+ server route. A WebGPU failure falls back to CPU only after the Worker measures adequate CPU throughput.
10
+ Raw WASM generation exports reject calls from a browser Window as a second guard against UI-thread mining.
8
11
 
9
12
  ## Install
10
13
 
@@ -15,23 +18,25 @@ npm install nano-rspow-web
15
18
  ## Usage
16
19
 
17
20
  ```javascript
18
- import init, { generate_work, validate_work } from 'nano-rspow-web';
21
+ import { probeLocalPow, generateWork } from 'nano-rspow-web';
19
22
 
20
- // Initialize the WebAssembly module
21
- await init();
22
-
23
- // Generate work
24
23
  const hash = "718CC2121C3E641059BC1C2CFC45666C99E8AE922F7A807B7D07B62C995D79E2";
25
24
  const threshold = "fffffff800000000";
26
-
27
- const result = await generate_work(hash, threshold);
28
- console.log("Nonce:", result.nonce); // e.g., "8587f13863c049fd"
29
- console.log("Is GPU:", result.is_gpu); // true/false
30
-
31
- // Validate work
32
- const isValid = validate_work(hash, result.nonce, threshold); // true
25
+ const assessment = await probeLocalPow();
26
+ if (assessment.recommended) {
27
+ const result = await generateWork(hash, threshold, { timeoutMs: 10_000 });
28
+ console.log("Nonce:", result.nonce); // e.g., "8587f13863c049fd"
29
+ console.log("Backend:", result.backend);
30
+ } else {
31
+ // Ask the application server for work instead of mining on the page thread.
32
+ console.log("Local work unavailable:", assessment.reason);
33
+ }
33
34
  ```
34
35
 
36
+ `createPowEngine()` uses the same Worker-backed implementation for `ready()` and `generate()`. The
37
+ synchronous `validate()` operation is suitable for the page thread because it checks one nonce and does
38
+ not search. Applications should use `nanocurrency.validateWork` when they already depend on that API.
39
+
35
40
  The threshold argument is always caller supplied. For current Nano mainnet,
36
41
  use `fffffff800000000` for send/change blocks or `fffffe0000000000` for
37
42
  receive/open/epoch blocks. Pass the stricter value required by the publishing
@@ -39,7 +44,7 @@ node when it differs. See Nano's
39
44
  [Work Generation guide](https://docs.nano.org/integration-guides/work-generation/)
40
45
  for current network requirements.
41
46
 
42
- ## Benchmarking Dashboard
47
+ ## Benchmarking Dashboards
43
48
 
44
49
  <table>
45
50
  <tr>
@@ -54,9 +59,79 @@ for current network requirements.
54
59
  </tr>
55
60
  </table>
56
61
 
57
- An interactive benchmarking dashboard is included in `browser-demo/index.html` to measure WebGPU and CPU WebAssembly performance.
62
+ Try the browser-only dashboard without building anything:
63
+ **[https://casualsecurityinc.github.io/nano-rspow/](https://casualsecurityinc.github.io/nano-rspow/)**
64
+
65
+ ### Running them locally
66
+
67
+ Everything runs through `make` from the repository root. Run `make help` for the
68
+ full list.
69
+
70
+ **One-time setup, after cloning:**
71
+
72
+ ```bash
73
+ make web-prereqs
74
+ ```
75
+
76
+ That installs the `wasm32-unknown-unknown` Rust target, builds the
77
+ `nano-rspow-node` native addon and installs the dashboard's npm dependencies,
78
+ skipping whatever is already satisfied. It is safe to re-run. It needs `cargo`,
79
+ `npm` and `python3` on your `PATH`, plus the `wasm-bindgen` CLI, which it does
80
+ *not* install for you — that compiles for several minutes, so the script prints
81
+ the command instead and exits. Both dashboards need `wasm-bindgen`; the native
82
+ addon is the only prerequisite that only the head-to-head dashboard needs, so
83
+ `./scripts/setup-web-toolchain.sh --skip-addon` is enough for the browser-only
84
+ one.
85
+
86
+ Verify the toolchain without changing anything with
87
+ `./scripts/setup-web-toolchain.sh --check`.
58
88
 
59
- Try it out for yourself: **[https://casualsecurityinc.github.io/nano-rspow/](https://casualsecurityinc.github.io/nano-rspow/)**
89
+ `cargo benchmark-web` also builds and opens the browser-only dashboard. It is a
90
+ thin wrapper around the same `build-demo.py`, kept because the root README has
91
+ long pointed at it; prefer `make web-demo`, which is the same thing plus the
92
+ prerequisite tooling.
93
+
94
+ **Browser-only dashboard** — measures this package's WebGPU and WASM CPU
95
+ backends, nothing else. No server, no addon:
96
+
97
+ ```bash
98
+ make web-demo # builds and opens nano-rspow-web/browser-demo/index.html
99
+ make web-demo-build # same build, no browser launch
100
+ make web-demo-check # is the built page present, complete and current?
101
+ ```
102
+
103
+ `index.html` is a single self-contained file — the WebAssembly, the
104
+ wasm-bindgen glue and the WGSL shader are all inlined, so it works when opened
105
+ straight from disk over `file://`. It is **generated and not committed**,
106
+ because a 550 KB committed artifact eventually gets opened after the crate has
107
+ moved on and silently benchmarks an old WebAssembly module. If the file is
108
+ missing or older than its sources, `make web-demo-check` says so and tells you
109
+ to rebuild.
110
+
111
+ **Head-to-head dashboard** — compares this package against `nano-pow` and
112
+ against the `nano-rspow-node` addon and the Rust CLI work peer. It needs the
113
+ native addon, which is why it is a separate command:
114
+
115
+ ```bash
116
+ make web-compare-run # builds, then serves on http://localhost:8080/
117
+ ```
118
+
119
+ Overrides: `make web-compare-run PORT=8081`, or `WORK_PEER_PORT`,
120
+ `WORK_PEER_BACKEND=auto|cpu|gpu`, and `NANO_WORK_URL` to point at a work peer
121
+ you are already running. `make web-compare` builds into `dist/` without serving.
122
+ `make web-all` builds both, `make web-clean` removes the generated output.
123
+
124
+ ### What CI covers
125
+
126
+ CI builds and verifies the **browser-only** dashboard only, in the
127
+ `browser-demo` job of `.github/workflows/web-browser-tests.yml`. It runs the same
128
+ prerequisite script, the same `make web-demo-build`, and then
129
+ `scripts/check-browser-demo.sh` — the same check as `make web-demo-check` — so
130
+ CI and your machine cannot disagree about what a valid dashboard is.
131
+
132
+ The head-to-head dashboard is not built in CI because it requires the native
133
+ `nano-rspow-node` addon, which is a platform-specific native compile. It is a
134
+ local tool, and `make web-compare-run` is the supported way to run it.
60
135
 
61
136
 
62
137
 
@@ -64,6 +139,9 @@ Try it out for yourself: **[https://casualsecurityinc.github.io/nano-rspow/](htt
64
139
 
65
140
  ## API reference
66
141
 
142
+ Raw `generate_work*` exports are for use inside Workers and reject calls from a browser Window.
143
+ Use `probeLocalPow` and `generateWork` from page code.
144
+
67
145
  ### `init(moduleOrPath?)`
68
146
 
69
147
  Initializes the asynchronous WASM loader. Await this default export before calling the work functions. It accepts an optional WebAssembly module, bytes, `Response`, URL, request, or promise for one of those inputs.
@@ -78,6 +156,25 @@ Asynchronously generates Proof of Work for a 32-byte block hash at any hexadecim
78
156
  ### `generate_work_gpu(hash_hex: string, threshold_hex: string, cancel_token: WasmCancelToken): Promise<GenerateResult>`
79
157
  Forces WebGPU PoW generation at any hexadecimal threshold. Rejects if WebGPU is unavailable or if the cancellation token is triggered.
80
158
 
159
+ ### GPU resource lifetime and concurrency
160
+
161
+ One WebGPU generator is built per Worker and reused by its calls. Building one
162
+ requests an instance, adapter, device and queue, compiles the WGSL shader,
163
+ creates the compute pipeline and allocates the double-buffered slots, so
164
+ rebuilding it per call charged that whole cost to the caller once per block.
165
+ `recommendLocalPow` builds the same generator, which also warms the cache for
166
+ the first high-level `generateWork` call.
167
+
168
+ Two consequences for callers:
169
+
170
+ - **Generation is serialised.** The generator's ping-pong buffers are shared, so
171
+ overlapping calls would write the same slot and read back each other's
172
+ results, handing back work computed for a different block. Calls are
173
+ therefore queued and run one at a time, in the order they arrive. Concurrent
174
+ calls are safe but wait their turn; they are never rejected or interleaved.
175
+ - **A lost device is recovered automatically.** If the browser drops the
176
+ device, the cached generator is discarded and the next call builds a new one.
177
+
81
178
  ### `generate_work_cpu(hash_hex: string, threshold_hex: string): GenerateResult`
82
179
  Synchronously generates PoW at any hexadecimal threshold, forcing single-threaded CPU WebAssembly.
83
180
 
@@ -113,9 +210,25 @@ Returned by all generation functions.
113
210
 
114
211
  ## Browser compatibility
115
212
 
116
- Use a browser with WebGPU support to use the GPU path. Browsers without WebGPU use the synchronous single-threaded WebAssembly CPU fallback.
213
+ Use a browser with WebGPU support to use the GPU path. Without WebGPU, the high-level API permits CPU work only when its throughput probe passes. All searching runs inside a dedicated Worker.
117
214
 
118
215
 
119
216
 
120
217
  - **[nano-rspow-node](https://www.npmjs.com/package/nano-rspow-node)**: High-performance pre-compiled Node.js bindings for backend servers.
121
218
  - **[nano-rspow Workspace](https://github.com/CasualSecurityInc/nano-rspow)**: The monorepo source code containing both packages.
219
+
220
+ ## Cancellable local work
221
+
222
+ `probeLocalPow({ signal, timeoutMs, reprobe })` returns `{ recommended, backend, reason }`.
223
+ The default probe deadline is three seconds. Assessments last for the current page only.
224
+ WebGPU is recommended only after a real search passes CPU validation; CPU recommendation
225
+ retains the 15 MH/s threshold. Probe failure reports an unrecommended assessment.
226
+
227
+ `generateWork(root, threshold, { signal, timeoutMs })` returns `{ nonce, backend }`.
228
+ It rejects on local failure; applications own remote routing. Both APIs use a reusable
229
+ module Worker, preserving the warm GPU pipeline and serializing shared buffer access.
230
+ Cancelling or timing out a Worker request terminates that realm and rejects all queued
231
+ requests; callers may retry, which creates a fresh Worker. If Workers cannot be constructed, local work is disabled. Inside the Worker,
232
+ CPU work uses adaptive batches targeting eight milliseconds between event-loop yields.
233
+ No shared memory or isolation headers are required. Deadlines include initialization
234
+ and queue time. `createPowEngine` and low-level WASM exports remain available.
package/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { default } from './nano_rspow_web.js';
2
2
  export * from './nano_rspow_web.js';
3
- export { createPowEngine, recommendLocalPow } from './pow-engine.js';
3
+ export { createPowEngine, recommendLocalPow, probeLocalPow, generateWork } from './pow-engine.js';
package/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { default } from './nano_rspow_web.js'
2
2
  export * from './nano_rspow_web.js'
3
- export { createPowEngine, recommendLocalPow } from './pow-engine.js'
3
+ export { createPowEngine, recommendLocalPow, probeLocalPow, generateWork } from './pow-engine.js'
@@ -0,0 +1,43 @@
1
+ import init, { generate_work_gpu, generate_work_cpu_batch, validate_work, WasmCancelToken } from './nano_rspow_web.js'
2
+
3
+ let initialization
4
+ export function ready () {
5
+ initialization ??= init().catch(error => { initialization = undefined; throw error })
6
+ return initialization
7
+ }
8
+
9
+ export async function cpuWork (root, threshold, signal) {
10
+ let batch = 1000
11
+ for (;;) {
12
+ signal?.throwIfAborted()
13
+ const start = performance.now()
14
+ const nonce = generate_work_cpu_batch(root, threshold, batch)
15
+ if (nonce) return { nonce, backend: 'cpu' }
16
+ batch = Math.max(1, Math.min(250000, Math.floor(batch * 8 / Math.max(1, performance.now() - start))))
17
+ await new Promise(resolve => setTimeout(resolve, 0))
18
+ }
19
+ }
20
+
21
+ export async function gpuWork (root, threshold) {
22
+ const token = new WasmCancelToken()
23
+ try {
24
+ const result = await generate_work_gpu(root, threshold, token)
25
+ try { return { nonce: result.nonce, backend: 'webgpu' } } finally { result.free() }
26
+ } finally { token.cancel(); token.free() }
27
+ }
28
+
29
+ export function validate (root, nonce, threshold) {
30
+ if (!validate_work(root, nonce, threshold)) throw new Error('Invalid local proof-of-work')
31
+ }
32
+
33
+ export async function cpuProbe (signal) {
34
+ const root = '0'.repeat(64)
35
+ let hashes = 0
36
+ const start = performance.now()
37
+ do {
38
+ signal?.throwIfAborted()
39
+ generate_work_cpu_batch(root, 'ffffffffffffffff', 1000)
40
+ hashes += 1000
41
+ } while (performance.now() - start < 8)
42
+ return hashes / ((performance.now() - start) / 1000) >= 15000000
43
+ }
@@ -81,9 +81,9 @@ export interface InitOutput {
81
81
  readonly validate_work: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number, number];
82
82
  readonly wasmcanceltoken_cancel: (a: number) => void;
83
83
  readonly wasmcanceltoken_new: () => number;
84
- readonly wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue__core_f0fd674eaa06beef___result__Result_____wasm_bindgen_8b74beb86e9b2264___JsError___true_: (a: number, b: number, c: any) => [number, number];
85
- readonly wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
86
- readonly wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue______true_: (a: number, b: number, c: any) => void;
84
+ readonly wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue__core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_9ea18429a37eb43a___JsError___true_: (a: number, b: number, c: any) => [number, number];
85
+ readonly wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
86
+ readonly wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue______true_: (a: number, b: number, c: any) => void;
87
87
  readonly __wbindgen_malloc: (a: number, b: number) => number;
88
88
  readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
89
89
  readonly __wbindgen_exn_store: (a: number) => void;
package/nano_rspow_web.js CHANGED
@@ -212,6 +212,14 @@ function __wbg_get_imports() {
212
212
  const ret = arg0 === undefined;
213
213
  return ret;
214
214
  },
215
+ __wbg___wbindgen_string_get_d109740c0d18f4d7: function(arg0, arg1) {
216
+ const obj = arg1;
217
+ const ret = typeof(obj) === 'string' ? obj : undefined;
218
+ var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
219
+ var len1 = WASM_VECTOR_LEN;
220
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
221
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
222
+ },
215
223
  __wbg___wbindgen_throw_9c31b086c2b26051: function(arg0, arg1) {
216
224
  throw new Error(getStringFromWasm0(arg0, arg1));
217
225
  },
@@ -299,6 +307,10 @@ function __wbg_get_imports() {
299
307
  const ret = arg0.gpu;
300
308
  return ret;
301
309
  },
310
+ __wbg_has_ef192b1f278770eb: function() { return handleError(function (arg0, arg1) {
311
+ const ret = Reflect.has(arg0, arg1);
312
+ return ret;
313
+ }, arguments); },
302
314
  __wbg_instanceof_GpuAdapter_1297a3a5ce0db3ff: function(arg0) {
303
315
  let result;
304
316
  try {
@@ -309,6 +321,16 @@ function __wbg_get_imports() {
309
321
  const ret = result;
310
322
  return ret;
311
323
  },
324
+ __wbg_instanceof_GpuDeviceLostInfo_0e99a9595225a57d: function(arg0) {
325
+ let result;
326
+ try {
327
+ result = arg0 instanceof GPUDeviceLostInfo;
328
+ } catch (_) {
329
+ result = false;
330
+ }
331
+ const ret = result;
332
+ return ret;
333
+ },
312
334
  __wbg_label_9a8583e3a20fafc7: function(arg0, arg1) {
313
335
  const ret = arg1.label;
314
336
  const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
@@ -323,10 +345,21 @@ function __wbg_get_imports() {
323
345
  __wbg_log_eb752234eec406d1: function(arg0) {
324
346
  console.log(arg0);
325
347
  },
348
+ __wbg_lost_b787a12a0e44349f: function(arg0) {
349
+ const ret = arg0.lost;
350
+ return ret;
351
+ },
326
352
  __wbg_mapAsync_e3cfbd141919d03c: function(arg0, arg1, arg2, arg3) {
327
353
  const ret = arg0.mapAsync(arg1 >>> 0, arg2, arg3);
328
354
  return ret;
329
355
  },
356
+ __wbg_message_c717665d7f0d1da0: function(arg0, arg1) {
357
+ const ret = arg1.message;
358
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
359
+ const len1 = WASM_VECTOR_LEN;
360
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
361
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
362
+ },
330
363
  __wbg_navigator_3334c390f542c642: function(arg0) {
331
364
  const ret = arg0.navigator;
332
365
  return ret;
@@ -350,7 +383,7 @@ function __wbg_get_imports() {
350
383
  const a = state0.a;
351
384
  state0.a = 0;
352
385
  try {
353
- return wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined_______true_(a, state0.b, arg0, arg1);
386
+ return wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined_______true_(a, state0.b, arg0, arg1);
354
387
  } finally {
355
388
  state0.a = a;
356
389
  }
@@ -368,7 +401,7 @@ function __wbg_get_imports() {
368
401
  const a = state0.a;
369
402
  state0.a = 0;
370
403
  try {
371
- return wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined_______true_(a, state0.b, arg0, arg1);
404
+ return wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined_______true_(a, state0.b, arg0, arg1);
372
405
  } finally {
373
406
  state0.a = a;
374
407
  }
@@ -409,6 +442,10 @@ function __wbg_get_imports() {
409
442
  const ret = arg0.queue;
410
443
  return ret;
411
444
  },
445
+ __wbg_reason_170684b0bb329a56: function(arg0) {
446
+ const ret = arg0.reason;
447
+ return (__wbindgen_enum_GpuDeviceLostReason.indexOf(ret) + 1 || 3) - 1;
448
+ },
412
449
  __wbg_requestAdapter_0049683abd339828: function(arg0, arg1) {
413
450
  const ret = arg0.requestAdapter(arg1);
414
451
  return ret;
@@ -609,6 +646,10 @@ function __wbg_get_imports() {
609
646
  __wbg_submit_b3bbead76cbf7627: function(arg0, arg1) {
610
647
  arg0.submit(arg1);
611
648
  },
649
+ __wbg_then_7b57a40e3ee05615: function(arg0, arg1) {
650
+ const ret = arg0.then(arg1);
651
+ return ret;
652
+ },
612
653
  __wbg_then_837494e384b37459: function(arg0, arg1) {
613
654
  const ret = arg0.then(arg1);
614
655
  return ret;
@@ -628,13 +669,13 @@ function __wbg_get_imports() {
628
669
  arg0.writeBuffer(arg1, arg2, getArrayU8FromWasm0(arg3, arg4), arg5, arg6);
629
670
  }, arguments); },
630
671
  __wbindgen_cast_0000000000000001: function(arg0, arg1) {
631
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 103, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
632
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue__core_f0fd674eaa06beef___result__Result_____wasm_bindgen_8b74beb86e9b2264___JsError___true_);
672
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 124, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
673
+ const ret = makeMutClosure(arg0, arg1, wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue__core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_9ea18429a37eb43a___JsError___true_);
633
674
  return ret;
634
675
  },
635
676
  __wbindgen_cast_0000000000000002: function(arg0, arg1) {
636
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 69, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
637
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue______true_);
677
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 83, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
678
+ const ret = makeMutClosure(arg0, arg1, wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue______true_);
638
679
  return ret;
639
680
  },
640
681
  __wbindgen_cast_0000000000000003: function(arg0) {
@@ -668,25 +709,28 @@ function __wbg_get_imports() {
668
709
  };
669
710
  }
670
711
 
671
- function wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue______true_(arg0, arg1, arg2) {
672
- wasm.wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue______true_(arg0, arg1, arg2);
712
+ function wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue______true_(arg0, arg1, arg2) {
713
+ wasm.wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue______true_(arg0, arg1, arg2);
673
714
  }
674
715
 
675
- function wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue__core_f0fd674eaa06beef___result__Result_____wasm_bindgen_8b74beb86e9b2264___JsError___true_(arg0, arg1, arg2) {
676
- const ret = wasm.wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___wasm_bindgen_8b74beb86e9b2264___JsValue__core_f0fd674eaa06beef___result__Result_____wasm_bindgen_8b74beb86e9b2264___JsError___true_(arg0, arg1, arg2);
716
+ function wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue__core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_9ea18429a37eb43a___JsError___true_(arg0, arg1, arg2) {
717
+ const ret = wasm.wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___wasm_bindgen_9ea18429a37eb43a___JsValue__core_37ee0ce0c4cd57d5___result__Result_____wasm_bindgen_9ea18429a37eb43a___JsError___true_(arg0, arg1, arg2);
677
718
  if (ret[1]) {
678
719
  throw takeFromExternrefTable0(ret[0]);
679
720
  }
680
721
  }
681
722
 
682
- function wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined_______true_(arg0, arg1, arg2, arg3) {
683
- wasm.wasm_bindgen_8b74beb86e9b2264___convert__closures_____invoke___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined___js_sys_7c33e7a1356e6034___Function_fn_wasm_bindgen_8b74beb86e9b2264___JsValue_____wasm_bindgen_8b74beb86e9b2264___sys__Undefined_______true_(arg0, arg1, arg2, arg3);
723
+ function wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined_______true_(arg0, arg1, arg2, arg3) {
724
+ wasm.wasm_bindgen_9ea18429a37eb43a___convert__closures_____invoke___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined___js_sys_642fe99a051e5c51___Function_fn_wasm_bindgen_9ea18429a37eb43a___JsValue_____wasm_bindgen_9ea18429a37eb43a___sys__Undefined_______true_(arg0, arg1, arg2, arg3);
684
725
  }
685
726
 
686
727
 
687
728
  const __wbindgen_enum_GpuBufferBindingType = ["uniform", "storage", "read-only-storage"];
688
729
 
689
730
 
731
+ const __wbindgen_enum_GpuDeviceLostReason = ["unknown", "destroyed"];
732
+
733
+
690
734
  const __wbindgen_enum_GpuPowerPreference = ["low-power", "high-performance"];
691
735
 
692
736
 
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nano-rspow-web",
3
- "version": "0.17.1",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "description": "WebGPU-accelerated Nano (XNO) Proof of Work generation in the browser using WebAssembly",
6
6
  "keywords": [
@@ -30,11 +30,14 @@
30
30
  "pow-engine.js",
31
31
  "pow-engine.d.ts",
32
32
  "recommendation.js",
33
- "README.md"
33
+ "README.md",
34
+ "local-runtime.js",
35
+ "pow-worker.js"
34
36
  ],
35
37
  "scripts": {
36
38
  "build": "cargo build -p nano-rspow-web --target wasm32-unknown-unknown --release && wasm-bindgen --target web --out-dir . ../target/wasm32-unknown-unknown/release/nano_rspow_web.wasm",
37
- "test": "node --test recommendation.test.js"
39
+ "test": "node --test recommendation.test.js api.test.js",
40
+ "test:browser": "npm run build && node --test tests/browser/*.test.mjs"
38
41
  },
39
42
  "dependencies": {
40
43
  "@openrai/nano-pow-contract": "^0.1.0"
package/pow-engine.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import type { PowEngine } from '@openrai/nano-pow-contract';
2
-
3
- /** Create the nano-pow-contract adapter for the WebAssembly/WebGPU engine. */
2
+ export interface LocalPowOptions { signal?: AbortSignal; timeoutMs?: number }
3
+ export interface LocalPowAssessment {
4
+ recommended: boolean;
5
+ backend: 'webgpu' | 'cpu' | null;
6
+ reason: string;
7
+ }
8
+ export declare function probeLocalPow(options?: LocalPowOptions & { reprobe?: boolean }): Promise<LocalPowAssessment>;
9
+ export declare function generateWork(root: string, threshold: string, options?: LocalPowOptions): Promise<{ nonce: string; backend: 'webgpu' | 'cpu' }>;
4
10
  export declare function createPowEngine(): PowEngine;
5
-
6
- /**
7
- * Return whether this browser should prefer local PoW.
8
- *
9
- * The first call performs a capability and CPU-throughput evaluation. Later
10
- * calls return its cached result unless `reprobe` is `true`.
11
- */
12
11
  export declare function recommendLocalPow(reprobe?: boolean): Promise<boolean>;
package/pow-engine.js CHANGED
@@ -1,28 +1,123 @@
1
- import init, { generate_work, probe_local_pow, validate_work } from './nano_rspow_web.js'
2
- import { createLocalPowRecommendation } from './recommendation.js'
1
+ import init, { validate_work } from './nano_rspow_web.js'
3
2
 
4
- let initialization
3
+ let worker
4
+ let nextId = 0
5
+ const pending = new Map()
6
+ let assessment
7
+ let probing
8
+ let probeGeneration = 0
5
9
 
6
- function ready () {
7
- initialization ??= init()
8
- return initialization
10
+ function resetWorker (error) {
11
+ if (worker) {
12
+ worker.onmessage = null
13
+ worker.onerror = null
14
+ worker.terminate()
15
+ }
16
+ worker = undefined
17
+ assessment = undefined
18
+ for (const request of pending.values()) request.reject(error)
19
+ pending.clear()
20
+ }
21
+
22
+ function getWorker () {
23
+ if (worker) return worker
24
+ if (typeof Worker === 'undefined') return undefined
25
+ try {
26
+ const realm = new Worker(new URL('./pow-worker.js', import.meta.url), { type: 'module' })
27
+ worker = realm
28
+ worker.onmessage = ({ data }) => {
29
+ if (worker !== realm) return
30
+ const request = pending.get(data.id)
31
+ if (!request) return
32
+ pending.delete(data.id)
33
+ if (data.error) request.reject(new Error(data.error))
34
+ else request.resolve(data.result)
35
+ }
36
+ worker.onerror = () => {
37
+ if (worker === realm) resetWorker(new Error('Local PoW Worker failed'))
38
+ }
39
+ return worker
40
+ } catch { return undefined }
9
41
  }
10
42
 
11
- /**
12
- * Return whether this browser should prefer local PoW. The result is cached;
13
- * pass `true` to force a fresh browser capability and performance probe.
14
- */
15
- export const recommendLocalPow = createLocalPowRecommendation(async () => {
16
- await ready()
17
- return probe_local_pow()
18
- })
43
+ // Start the clock before queueing or initializing. Abandoning a Worker discards
44
+ // its entire WASM/GPU realm, so late readbacks cannot reuse shared buffers.
45
+ async function run (operation, root, threshold, { signal, timeoutMs } = {}) {
46
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) throw new RangeError('Invalid PoW timeout')
47
+ if (signal?.aborted) throw signal.reason ?? new DOMException('Aborted', 'AbortError')
48
+ let timer
49
+ let abort
50
+ const cancelled = new Promise((_, reject) => {
51
+ abort = () => {
52
+ const error = signal?.reason ?? new DOMException('Aborted', 'AbortError')
53
+ resetWorker(error)
54
+ reject(error)
55
+ }
56
+ signal?.addEventListener('abort', abort, { once: true })
57
+ if (timeoutMs !== undefined) timer = setTimeout(() => {
58
+ const error = new DOMException('Local PoW deadline exceeded', 'TimeoutError')
59
+ resetWorker(error)
60
+ reject(error)
61
+ }, timeoutMs)
62
+ })
63
+ try {
64
+ const activeWorker = getWorker()
65
+ if (!activeWorker) throw new Error('Dedicated Workers are unavailable; local proof-of-work is disabled')
66
+ const task = new Promise((resolve, reject) => {
67
+ const id = ++nextId
68
+ pending.set(id, { resolve, reject })
69
+ try {
70
+ activeWorker.postMessage({ id, operation, root, threshold })
71
+ } catch (error) {
72
+ resetWorker(error instanceof Error ? error : new Error(String(error)))
73
+ }
74
+ })
75
+ return await Promise.race([task, cancelled])
76
+ } finally {
77
+ clearTimeout(timer)
78
+ signal?.removeEventListener('abort', abort)
79
+ }
80
+ }
81
+
82
+ export async function ready () {
83
+ // The adapter's synchronous validate() needs a local WASM instance, too.
84
+ // Only validation runs here; all searching remains inside the Worker.
85
+ await Promise.all([init(), run('ready', undefined, undefined, { timeoutMs: 3000 })])
86
+ }
87
+
88
+ export async function probeLocalPow (options = {}) {
89
+ if (!options.reprobe && assessment) return assessment
90
+ // Each caller keeps its own cancellation/deadline; shared work is only used
91
+ // for ordinary probes without caller-specific cancellation options.
92
+ const share = !options.signal && options.timeoutMs === undefined
93
+ if (share && probing) return probing
94
+ const generation = ++probeGeneration
95
+ const promise = run('probe', undefined, undefined, { ...options, timeoutMs: options.timeoutMs ?? 3000 })
96
+ .then(result => {
97
+ if (generation === probeGeneration) assessment = result
98
+ return result
99
+ })
100
+ .catch(error => ({ recommended: false, backend: null, reason: error.name === 'TimeoutError' ? 'timeout' : String(error.message ?? error) }))
101
+ if (!share) return promise
102
+ probing = promise
103
+ try { return await promise } finally { probing = undefined }
104
+ }
105
+
106
+ export async function generateWork (root, threshold, options = {}) {
107
+ if (!/^[a-f\d]{64}$/i.test(root) || !/^[a-f\d]{16}$/i.test(threshold)) throw new TypeError('Invalid work root or threshold')
108
+ if (assessment && !assessment.recommended) throw new Error(`Local proof-of-work is unavailable: ${assessment.reason}`)
109
+ return await run('generate', root, threshold, options)
110
+ }
111
+
112
+ export async function recommendLocalPow (reprobe = false) {
113
+ return (await probeLocalPow({ reprobe })).recommended
114
+ }
19
115
 
20
- /** Create the nano-pow-contract adapter for the WebAssembly/WebGPU engine. */
21
116
  export function createPowEngine () {
22
117
  return {
23
118
  name: 'nano-rspow-web',
24
119
  ready,
25
- generate: async (root, threshold) => (await generate_work(root, threshold)).nonce,
120
+ generate: async (root, threshold) => (await generateWork(root, threshold)).nonce,
26
121
  validate: (root, work, threshold) => validate_work(root, work, threshold)
27
122
  }
28
123
  }
package/pow-worker.js ADDED
@@ -0,0 +1,58 @@
1
+ import { ready, gpuWork, cpuWork, cpuProbe, validate } from './local-runtime.js'
2
+ let selected
3
+ let queue = Promise.resolve()
4
+ self.onmessage = ({ data }) => {
5
+ queue = queue.then(async () => {
6
+ try {
7
+ await ready()
8
+ if (data.operation === 'ready') {
9
+ self.postMessage({ id: data.id, result: true })
10
+ return
11
+ }
12
+
13
+ if (data.operation === 'probe') {
14
+ try {
15
+ const root = '0'.repeat(64)
16
+ const threshold = 'ff00000000000000'
17
+ const result = await gpuWork(root, threshold)
18
+ validate(root, result.nonce, threshold)
19
+ selected = 'webgpu'
20
+ self.postMessage({ id: data.id, result: { recommended: true, backend: selected, reason: 'validated_gpu' } })
21
+ } catch {
22
+ const recommended = await cpuProbe()
23
+ selected = recommended ? 'cpu' : undefined
24
+ self.postMessage({ id: data.id, result: { recommended, backend: recommended ? 'cpu' : null, reason: recommended ? 'cpu_throughput' : 'slow_cpu' } })
25
+ }
26
+ return
27
+ }
28
+
29
+ if (selected === undefined) {
30
+ const root = '0'.repeat(64)
31
+ const threshold = 'ff00000000000000'
32
+ try {
33
+ const probe = await gpuWork(root, threshold)
34
+ validate(root, probe.nonce, threshold)
35
+ selected = 'webgpu'
36
+ } catch {
37
+ if (await cpuProbe()) selected = 'cpu'
38
+ }
39
+ }
40
+ if (selected === undefined) throw new Error('Local proof-of-work is not recommended on this device')
41
+
42
+ let result
43
+ if (selected === 'webgpu') {
44
+ try {
45
+ result = await gpuWork(data.root, data.threshold)
46
+ } catch (error) {
47
+ if (!await cpuProbe()) throw error
48
+ selected = 'cpu'
49
+ }
50
+ }
51
+ result ??= await cpuWork(data.root, data.threshold)
52
+ validate(data.root, result.nonce, data.threshold)
53
+ self.postMessage({ id: data.id, result })
54
+ } catch (error) {
55
+ self.postMessage({ id: data.id, error: String(error?.message ?? error) })
56
+ }
57
+ })
58
+ }
package/recommendation.js CHANGED
@@ -1,72 +1,19 @@
1
- const CACHE_KEY = 'nano-rspow-web.local-pow-recommendation.v1'
2
-
3
- function browserStorage () {
4
- try {
5
- return globalThis.localStorage ?? null
6
- } catch {
7
- return null
8
- }
9
- }
10
-
11
- /**
12
- * Cache an asynchronous local-PoW recommendation without exposing browser
13
- * storage details to consumers.
14
- *
15
- * @param {() => Promise<boolean>} probe runs the actual capability check
16
- * @param {{ storage?: Storage | null }} [options] testable browser storage override
17
- * @returns {(reprobe?: boolean) => Promise<boolean>} cached recommendation function
18
- */
19
- export function createLocalPowRecommendation (probe, { storage = browserStorage() } = {}) {
20
- let cacheRead = false
21
- let cachedRecommendation
22
- let activeProbe
1
+ /** Cache capability assessments only for the lifetime of the current page. */
2
+ export function createLocalPowRecommendation (probe) {
3
+ let cached
4
+ let active
23
5
  let generation = 0
24
-
25
- function readCache () {
26
- if (cacheRead) return
27
- cacheRead = true
28
-
29
- try {
30
- const value = storage?.getItem(CACHE_KEY)
31
- if (value === 'true') cachedRecommendation = true
32
- if (value === 'false') cachedRecommendation = false
33
- } catch {
34
- // Storage is optional: a private-browser or quota failure falls back to memory.
35
- }
36
- }
37
-
38
- function writeCache (recommendation) {
39
- try {
40
- storage?.setItem(CACHE_KEY, String(recommendation))
41
- } catch {
42
- // The in-memory result remains valid for this page session.
43
- }
44
- }
45
-
46
6
  return function recommendLocalPow (reprobe = false) {
47
- readCache()
48
-
49
- if (!reprobe && cachedRecommendation !== undefined) {
50
- return Promise.resolve(cachedRecommendation)
51
- }
52
-
53
- if (!reprobe && activeProbe) return activeProbe.promise
54
-
55
- const probeGeneration = ++generation
56
- const promise = Promise.resolve()
57
- .then(probe)
58
- .then(recommendation => {
59
- if (probeGeneration === generation) {
60
- cachedRecommendation = recommendation
61
- writeCache(recommendation)
62
- }
63
- return recommendation
64
- })
65
- .finally(() => {
66
- if (activeProbe?.generation === probeGeneration) activeProbe = undefined
67
- })
68
-
69
- activeProbe = { generation: probeGeneration, promise }
7
+ if (!reprobe && cached !== undefined) return Promise.resolve(cached)
8
+ if (!reprobe && active) return active.promise
9
+ const current = ++generation
10
+ const promise = Promise.resolve().then(probe).then(result => {
11
+ if (current === generation) cached = result
12
+ return result
13
+ }).finally(() => {
14
+ if (active?.generation === current) active = undefined
15
+ })
16
+ active = { generation: current, promise }
70
17
  return promise
71
18
  }
72
19
  }