nano-rspow-web 0.17.2 → 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
@@ -134,6 +139,9 @@ local tool, and `make web-compare-run` is the supported way to run it.
134
139
 
135
140
  ## API reference
136
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
+
137
145
  ### `init(moduleOrPath?)`
138
146
 
139
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.
@@ -150,12 +158,12 @@ Forces WebGPU PoW generation at any hexadecimal threshold. Rejects if WebGPU is
150
158
 
151
159
  ### GPU resource lifetime and concurrency
152
160
 
153
- One WebGPU generator is built per page and reused by every call. Building one
161
+ One WebGPU generator is built per Worker and reused by its calls. Building one
154
162
  requests an instance, adapter, device and queue, compiles the WGSL shader,
155
163
  creates the compute pipeline and allocates the double-buffered slots, so
156
164
  rebuilding it per call charged that whole cost to the caller once per block.
157
165
  `recommendLocalPow` builds the same generator, which also warms the cache for
158
- the first `generate_work` call.
166
+ the first high-level `generateWork` call.
159
167
 
160
168
  Two consequences for callers:
161
169
 
@@ -202,9 +210,25 @@ Returned by all generation functions.
202
210
 
203
211
  ## Browser compatibility
204
212
 
205
- 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.
206
214
 
207
215
 
208
216
 
209
217
  - **[nano-rspow-node](https://www.npmjs.com/package/nano-rspow-node)**: High-performance pre-compiled Node.js bindings for backend servers.
210
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_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___JsValue__core_ed718c3d60ebd546___result__Result_____wasm_bindgen_eea6accdcfb85281___JsError___true_: (a: number, b: number, c: any) => [number, number];
85
- readonly wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
86
- readonly wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___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 {
@@ -371,7 +383,7 @@ function __wbg_get_imports() {
371
383
  const a = state0.a;
372
384
  state0.a = 0;
373
385
  try {
374
- return wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___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);
375
387
  } finally {
376
388
  state0.a = a;
377
389
  }
@@ -389,7 +401,7 @@ function __wbg_get_imports() {
389
401
  const a = state0.a;
390
402
  state0.a = 0;
391
403
  try {
392
- return wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___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);
393
405
  } finally {
394
406
  state0.a = a;
395
407
  }
@@ -657,13 +669,13 @@ function __wbg_get_imports() {
657
669
  arg0.writeBuffer(arg1, arg2, getArrayU8FromWasm0(arg3, arg4), arg5, arg6);
658
670
  }, arguments); },
659
671
  __wbindgen_cast_0000000000000001: function(arg0, arg1) {
660
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 111, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
661
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___JsValue__core_ed718c3d60ebd546___result__Result_____wasm_bindgen_eea6accdcfb85281___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_);
662
674
  return ret;
663
675
  },
664
676
  __wbindgen_cast_0000000000000002: function(arg0, arg1) {
665
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 77, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
666
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___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_);
667
679
  return ret;
668
680
  },
669
681
  __wbindgen_cast_0000000000000003: function(arg0) {
@@ -697,19 +709,19 @@ function __wbg_get_imports() {
697
709
  };
698
710
  }
699
711
 
700
- function wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___JsValue______true_(arg0, arg1, arg2) {
701
- wasm.wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___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);
702
714
  }
703
715
 
704
- function wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___JsValue__core_ed718c3d60ebd546___result__Result_____wasm_bindgen_eea6accdcfb85281___JsError___true_(arg0, arg1, arg2) {
705
- const ret = wasm.wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___wasm_bindgen_eea6accdcfb85281___JsValue__core_ed718c3d60ebd546___result__Result_____wasm_bindgen_eea6accdcfb85281___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);
706
718
  if (ret[1]) {
707
719
  throw takeFromExternrefTable0(ret[0]);
708
720
  }
709
721
  }
710
722
 
711
- function wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined_______true_(arg0, arg1, arg2, arg3) {
712
- wasm.wasm_bindgen_eea6accdcfb85281___convert__closures_____invoke___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___sys__Undefined___js_sys_8383356d580dd162___Function_fn_wasm_bindgen_eea6accdcfb85281___JsValue_____wasm_bindgen_eea6accdcfb85281___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);
713
725
  }
714
726
 
715
727
 
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nano-rspow-web",
3
- "version": "0.17.2",
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,13 @@
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",
38
40
  "test:browser": "npm run build && node --test tests/browser/*.test.mjs"
39
41
  },
40
42
  "dependencies": {
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
  }