@btc-vision/bitcoin 7.0.0-alpha.3 → 7.0.0-alpha.4

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 (96) hide show
  1. package/README.md +139 -12
  2. package/browser/chunks/WorkerSigningPool.sequential-DHha7j0b.js +113 -0
  3. package/browser/env.d.ts +13 -0
  4. package/browser/env.d.ts.map +1 -0
  5. package/browser/index.d.ts +1 -1
  6. package/browser/index.d.ts.map +1 -1
  7. package/browser/index.js +872 -1105
  8. package/browser/io/index.d.ts +0 -1
  9. package/browser/io/index.d.ts.map +1 -1
  10. package/browser/types.d.ts.map +1 -1
  11. package/browser/workers/WorkerSigningPool.d.ts +6 -0
  12. package/browser/workers/WorkerSigningPool.d.ts.map +1 -1
  13. package/browser/workers/WorkerSigningPool.node.d.ts +6 -0
  14. package/browser/workers/WorkerSigningPool.node.d.ts.map +1 -1
  15. package/browser/workers/WorkerSigningPool.sequential.d.ts +69 -0
  16. package/browser/workers/WorkerSigningPool.sequential.d.ts.map +1 -0
  17. package/browser/workers/WorkerSigningPool.worklet.d.ts +64 -0
  18. package/browser/workers/WorkerSigningPool.worklet.d.ts.map +1 -0
  19. package/browser/workers/index.d.ts +2 -2
  20. package/browser/workers/index.d.ts.map +1 -1
  21. package/browser/workers/index.react-native.d.ts +28 -0
  22. package/browser/workers/index.react-native.d.ts.map +1 -0
  23. package/browser/workers/psbt-parallel.d.ts +2 -3
  24. package/browser/workers/psbt-parallel.d.ts.map +1 -1
  25. package/browser/workers/types.d.ts +12 -0
  26. package/browser/workers/types.d.ts.map +1 -1
  27. package/build/env.d.ts +13 -0
  28. package/build/env.d.ts.map +1 -0
  29. package/build/env.js +198 -0
  30. package/build/env.js.map +1 -0
  31. package/build/index.d.ts +2 -1
  32. package/build/index.d.ts.map +1 -1
  33. package/build/index.js +2 -1
  34. package/build/index.js.map +1 -1
  35. package/build/io/index.d.ts +0 -1
  36. package/build/io/index.d.ts.map +1 -1
  37. package/build/io/index.js +0 -2
  38. package/build/io/index.js.map +1 -1
  39. package/build/tsconfig.build.tsbuildinfo +1 -1
  40. package/build/types.d.ts.map +1 -1
  41. package/build/types.js +2 -16
  42. package/build/types.js.map +1 -1
  43. package/build/workers/WorkerSigningPool.d.ts +6 -0
  44. package/build/workers/WorkerSigningPool.d.ts.map +1 -1
  45. package/build/workers/WorkerSigningPool.js +8 -0
  46. package/build/workers/WorkerSigningPool.js.map +1 -1
  47. package/build/workers/WorkerSigningPool.node.d.ts +6 -0
  48. package/build/workers/WorkerSigningPool.node.d.ts.map +1 -1
  49. package/build/workers/WorkerSigningPool.node.js +9 -2
  50. package/build/workers/WorkerSigningPool.node.js.map +1 -1
  51. package/build/workers/WorkerSigningPool.sequential.d.ts +78 -0
  52. package/build/workers/WorkerSigningPool.sequential.d.ts.map +1 -0
  53. package/build/workers/WorkerSigningPool.sequential.js +160 -0
  54. package/build/workers/WorkerSigningPool.sequential.js.map +1 -0
  55. package/build/workers/WorkerSigningPool.worklet.d.ts +79 -0
  56. package/build/workers/WorkerSigningPool.worklet.d.ts.map +1 -0
  57. package/build/workers/WorkerSigningPool.worklet.js +388 -0
  58. package/build/workers/WorkerSigningPool.worklet.js.map +1 -0
  59. package/build/workers/index.d.ts +2 -2
  60. package/build/workers/index.d.ts.map +1 -1
  61. package/build/workers/index.js +9 -0
  62. package/build/workers/index.js.map +1 -1
  63. package/build/workers/index.react-native.d.ts +28 -0
  64. package/build/workers/index.react-native.d.ts.map +1 -0
  65. package/build/workers/index.react-native.js +67 -0
  66. package/build/workers/index.react-native.js.map +1 -0
  67. package/build/workers/psbt-parallel.d.ts +2 -3
  68. package/build/workers/psbt-parallel.d.ts.map +1 -1
  69. package/build/workers/psbt-parallel.js +4 -4
  70. package/build/workers/psbt-parallel.js.map +1 -1
  71. package/build/workers/types.d.ts +12 -0
  72. package/build/workers/types.d.ts.map +1 -1
  73. package/package.json +11 -1
  74. package/src/env.ts +237 -0
  75. package/src/index.ts +1 -2
  76. package/src/io/index.ts +0 -3
  77. package/src/types.ts +4 -27
  78. package/src/workers/WorkerSigningPool.node.ts +10 -2
  79. package/src/workers/WorkerSigningPool.sequential.ts +190 -0
  80. package/src/workers/WorkerSigningPool.ts +9 -0
  81. package/src/workers/WorkerSigningPool.worklet.ts +519 -0
  82. package/src/workers/index.react-native.ts +110 -0
  83. package/src/workers/index.ts +10 -1
  84. package/src/workers/psbt-parallel.ts +8 -8
  85. package/src/workers/types.ts +16 -0
  86. package/test/env.spec.ts +418 -0
  87. package/test/workers-pool.spec.ts +43 -0
  88. package/test/workers-sequential.spec.ts +669 -0
  89. package/test/workers-worklet.spec.ts +500 -0
  90. package/browser/io/MemoryPool.d.ts +0 -220
  91. package/browser/io/MemoryPool.d.ts.map +0 -1
  92. package/build/io/MemoryPool.d.ts +0 -220
  93. package/build/io/MemoryPool.d.ts.map +0 -1
  94. package/build/io/MemoryPool.js +0 -309
  95. package/build/io/MemoryPool.js.map +0 -1
  96. package/src/io/MemoryPool.ts +0 -343
@@ -0,0 +1,519 @@
1
+ /**
2
+ * Worklet-based parallel signing pool for React Native.
3
+ *
4
+ * Uses `react-native-worklets` (Software Mansion v0.7+) to run signing
5
+ * operations in parallel across multiple worklet runtimes.
6
+ * Each runtime gets its own ECC module instance via eval of the bundled
7
+ * @noble/secp256k1 IIFE string.
8
+ *
9
+ * SECURITY ARCHITECTURE:
10
+ * - Private keys are cloned per-runtime (structuredClone semantics)
11
+ * - Keys are zeroed inside worklet AND in main thread finally block
12
+ * - Tainted runtimes (timeout) are replaced, not reused
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+
17
+ import type {
18
+ ParallelSignerKeyPair,
19
+ ParallelSigningResult,
20
+ SigningResultMessage,
21
+ SigningTask,
22
+ WorkerPoolConfig,
23
+ } from './types.js';
24
+ import { SignatureType } from './types.js';
25
+
26
+ /**
27
+ * Minimal interface for react-native-worklets runtime.
28
+ * Keeps us decoupled from the actual module types.
29
+ */
30
+ interface WorkletRuntime {
31
+ readonly name: string;
32
+ }
33
+
34
+ /**
35
+ * Minimal interface for the react-native-worklets module.
36
+ */
37
+ interface WorkletsModule {
38
+ createWorkletRuntime(name: string): WorkletRuntime;
39
+ runOnRuntime<T>(runtime: WorkletRuntime, fn: () => T): Promise<T>;
40
+ }
41
+
42
+ /**
43
+ * Default configuration for the worklet pool.
44
+ */
45
+ const DEFAULT_CONFIG: Required<WorkerPoolConfig> = {
46
+ workerCount: 4,
47
+ taskTimeoutMs: 30000,
48
+ maxKeyHoldTimeMs: 5000,
49
+ verifySignatures: true,
50
+ preserveWorkers: false,
51
+ };
52
+
53
+ /**
54
+ * Internal runtime wrapper for pool management.
55
+ */
56
+ interface PooledRuntime {
57
+ readonly id: number;
58
+ runtime: WorkletRuntime;
59
+ tainted: boolean;
60
+ }
61
+
62
+ /**
63
+ * Worklet-based parallel signing pool for React Native.
64
+ *
65
+ * Mirrors the API of WorkerSigningPool (browser) but uses
66
+ * `react-native-worklets` runtimes instead of Web Workers.
67
+ * `runOnRuntime()` returns a Promise directly — no postMessage protocol.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * import { WorkletSigningPool } from '@btc-vision/bitcoin/workers';
72
+ *
73
+ * const pool = WorkletSigningPool.getInstance();
74
+ * pool.preserveWorkers();
75
+ *
76
+ * const result = await pool.signBatch(tasks, keyPair);
77
+ * await pool.shutdown();
78
+ * ```
79
+ */
80
+ export class WorkletSigningPool {
81
+ static #instance: WorkletSigningPool | null = null;
82
+
83
+ readonly #config: Required<WorkerPoolConfig>;
84
+ readonly #runtimes: PooledRuntime[] = [];
85
+
86
+ #workletsModule: WorkletsModule | null = null;
87
+ #eccBundleCode: string | null = null;
88
+ #preserveWorkers: boolean = false;
89
+ #nextRuntimeId: number = 0;
90
+ #initialized: boolean = false;
91
+ #shuttingDown: boolean = false;
92
+
93
+ /**
94
+ * Whether Uint8Array survives worklet boundary.
95
+ * Detected during initialize(); if false, we encode as number[].
96
+ */
97
+ #uint8ArraySupported: boolean = true;
98
+
99
+ private constructor(config: WorkerPoolConfig = {}) {
100
+ this.#config = { ...DEFAULT_CONFIG, ...config };
101
+ this.#preserveWorkers = this.#config.preserveWorkers;
102
+ }
103
+
104
+ /** Number of active runtimes. */
105
+ public get workerCount(): number {
106
+ return this.#runtimes.length;
107
+ }
108
+
109
+ /** Idle runtimes (all non-tainted). */
110
+ public get idleWorkerCount(): number {
111
+ return this.#runtimes.filter((r) => !r.tainted).length;
112
+ }
113
+
114
+ /** Busy runtimes — always 0 outside of signBatch. */
115
+ public get busyWorkerCount(): number {
116
+ return 0;
117
+ }
118
+
119
+ /** Whether runtimes are preserved between batches. */
120
+ public get isPreservingWorkers(): boolean {
121
+ return this.#preserveWorkers;
122
+ }
123
+
124
+ /**
125
+ * Gets the singleton pool instance.
126
+ *
127
+ * @param config - Optional configuration (only used on first call)
128
+ */
129
+ public static getInstance(config?: WorkerPoolConfig): WorkletSigningPool {
130
+ if (!WorkletSigningPool.#instance) {
131
+ WorkletSigningPool.#instance = new WorkletSigningPool(config);
132
+ }
133
+ return WorkletSigningPool.#instance;
134
+ }
135
+
136
+ /** Resets the singleton instance (for testing). */
137
+ public static resetInstance(): void {
138
+ if (WorkletSigningPool.#instance) {
139
+ WorkletSigningPool.#instance.shutdown().catch(() => {});
140
+ WorkletSigningPool.#instance = null;
141
+ }
142
+ }
143
+
144
+ /** Enable runtime preservation between signing batches. */
145
+ public preserveWorkers(): void {
146
+ this.#preserveWorkers = true;
147
+ }
148
+
149
+ /** Disable runtime preservation. */
150
+ public releaseWorkers(): void {
151
+ this.#preserveWorkers = false;
152
+ }
153
+
154
+ /**
155
+ * Initializes the worklet pool.
156
+ *
157
+ * Dynamically imports `react-native-worklets`, creates N runtimes,
158
+ * and injects the ECC bundle into each via eval.
159
+ *
160
+ * @throws If `react-native-worklets` is not installed or eval fails
161
+ */
162
+ public async initialize(): Promise<void> {
163
+ if (this.#initialized) {
164
+ return;
165
+ }
166
+
167
+ if (this.#shuttingDown) {
168
+ throw new Error('Cannot initialize pool while shutting down');
169
+ }
170
+
171
+ // Lazy dynamic import — module loads even without the dep
172
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
173
+ const worklets: WorkletsModule = await import('react-native-worklets' as string);
174
+ this.#workletsModule = worklets;
175
+
176
+ // Load ECC bundle
177
+ const { ECC_BUNDLE } = await import('./ecc-bundle.js');
178
+ this.#eccBundleCode = ECC_BUNDLE;
179
+
180
+ // Create runtimes and inject ECC
181
+ for (let i = 0; i < this.#config.workerCount; i++) {
182
+ await this.#createRuntime();
183
+ }
184
+
185
+ // Feature-detect Uint8Array support across worklet boundary
186
+ const firstRuntime = this.#runtimes[0];
187
+ if (firstRuntime) {
188
+ try {
189
+ const result = await this.#workletsModule.runOnRuntime(
190
+ firstRuntime.runtime,
191
+ () => {
192
+ const arr = new Uint8Array([1, 2, 3]);
193
+ return arr instanceof Uint8Array;
194
+ },
195
+ );
196
+ this.#uint8ArraySupported = result;
197
+ } catch {
198
+ this.#uint8ArraySupported = false;
199
+ }
200
+ }
201
+
202
+ this.#initialized = true;
203
+ }
204
+
205
+ /**
206
+ * Signs a batch of tasks in parallel across worklet runtimes.
207
+ *
208
+ * SECURITY: Private keys are cloned per-runtime and zeroed both
209
+ * inside the worklet and in the main thread finally block.
210
+ */
211
+ public async signBatch(
212
+ tasks: readonly SigningTask[],
213
+ keyPair: ParallelSignerKeyPair,
214
+ ): Promise<ParallelSigningResult> {
215
+ const startTime = performance.now();
216
+
217
+ if (!this.#initialized) {
218
+ await this.initialize();
219
+ }
220
+
221
+ if (tasks.length === 0) {
222
+ return {
223
+ success: true,
224
+ signatures: new Map(),
225
+ errors: new Map(),
226
+ durationMs: performance.now() - startTime,
227
+ };
228
+ }
229
+
230
+ // Distribute tasks round-robin
231
+ const runtimeCount = Math.min(this.#runtimes.length, tasks.length);
232
+ const taskBatches: SigningTask[][] = Array.from({ length: runtimeCount }, () => []);
233
+
234
+ for (let i = 0; i < tasks.length; i++) {
235
+ const batch = taskBatches[i % runtimeCount];
236
+ const task = tasks[i];
237
+ if (batch && task) {
238
+ batch.push(task);
239
+ }
240
+ }
241
+
242
+ const privateKey = keyPair.getPrivateKey();
243
+
244
+ try {
245
+ const batchResults = await Promise.allSettled(
246
+ taskBatches.map((batch, index) =>
247
+ this.#signBatchOnRuntime(
248
+ batch,
249
+ privateKey,
250
+ keyPair.publicKey,
251
+ index,
252
+ ),
253
+ ),
254
+ );
255
+
256
+ const signatures = new Map<number, SigningResultMessage>();
257
+ const errors = new Map<number, string>();
258
+
259
+ for (let i = 0; i < batchResults.length; i++) {
260
+ const result = batchResults[i];
261
+ if (!result) continue;
262
+
263
+ if (result.status === 'fulfilled') {
264
+ for (const sig of result.value.signatures) {
265
+ signatures.set(sig.inputIndex, sig);
266
+ }
267
+ for (const [idx, errMsg] of result.value.errors) {
268
+ errors.set(idx, errMsg);
269
+ }
270
+ } else {
271
+ const reason = result.reason as { message?: string } | undefined;
272
+ const errorMsg = reason?.message ?? 'Worklet batch signing failed';
273
+ const failedBatch = taskBatches[i];
274
+ if (failedBatch) {
275
+ for (const task of failedBatch) {
276
+ errors.set(task.inputIndex, errorMsg);
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ // Cleanup runtimes if not preserving
283
+ if (!this.#preserveWorkers) {
284
+ await this.shutdown();
285
+ }
286
+
287
+ return {
288
+ success: errors.size === 0,
289
+ signatures,
290
+ errors,
291
+ durationMs: performance.now() - startTime,
292
+ };
293
+ } finally {
294
+ // SECURITY: Zero the key in main thread
295
+ privateKey.fill(0);
296
+ }
297
+ }
298
+
299
+ /** Shuts down all runtimes. */
300
+ // eslint-disable-next-line @typescript-eslint/require-await
301
+ public async shutdown(): Promise<void> {
302
+ if (this.#shuttingDown) {
303
+ return;
304
+ }
305
+
306
+ this.#shuttingDown = true;
307
+
308
+ // Worklet runtimes don't have a destroy() — clear references for GC
309
+ this.#runtimes.length = 0;
310
+ this.#workletsModule = null;
311
+ this.#eccBundleCode = null;
312
+ this.#initialized = false;
313
+ this.#shuttingDown = false;
314
+ }
315
+
316
+ /** Enables `await using pool = ...` syntax. */
317
+ public async [Symbol.asyncDispose](): Promise<void> {
318
+ await this.shutdown();
319
+ }
320
+
321
+ /**
322
+ * Creates a new worklet runtime and injects the ECC bundle.
323
+ */
324
+ async #createRuntime(): Promise<PooledRuntime> {
325
+ if (!this.#workletsModule || !this.#eccBundleCode) {
326
+ throw new Error('Worklets module or ECC bundle not loaded');
327
+ }
328
+
329
+ const id = this.#nextRuntimeId++;
330
+ const runtime = this.#workletsModule.createWorkletRuntime(`signing-runtime-${id}`);
331
+
332
+ // Inject ECC bundle into the worklet runtime.
333
+ // The bundle declares `var nobleBundle = (()=>{...})()` with "use strict",
334
+ // so a plain eval won't leak it to globalThis. We use `new Function` to
335
+ // execute the bundle and then explicitly assign the result.
336
+ const bundleCode = this.#eccBundleCode;
337
+ await this.#workletsModule.runOnRuntime(runtime, () => {
338
+ 'worklet';
339
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
340
+ const fn = new Function(bundleCode + '; return nobleBundle;') as () => unknown;
341
+ (globalThis as Record<string, unknown>)['nobleBundle'] = fn();
342
+ });
343
+
344
+ const pooled: PooledRuntime = { id, runtime, tainted: false };
345
+ this.#runtimes.push(pooled);
346
+ return pooled;
347
+ }
348
+
349
+ /**
350
+ * Replaces a tainted runtime with a fresh one.
351
+ */
352
+ async #replaceRuntime(pooled: PooledRuntime): Promise<void> {
353
+ const idx = this.#runtimes.indexOf(pooled);
354
+ if (idx >= 0) {
355
+ this.#runtimes.splice(idx, 1);
356
+ }
357
+
358
+ try {
359
+ await this.#createRuntime();
360
+ } catch {
361
+ // If replacement fails, pool continues with fewer runtimes
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Signs a batch of tasks on a specific runtime.
367
+ */
368
+ async #signBatchOnRuntime(
369
+ tasks: readonly SigningTask[],
370
+ privateKey: Uint8Array,
371
+ publicKey: Uint8Array,
372
+ runtimeIndex: number,
373
+ ): Promise<{
374
+ signatures: SigningResultMessage[];
375
+ errors: Map<number, string>;
376
+ }> {
377
+ if (tasks.length === 0) {
378
+ return { signatures: [], errors: new Map() };
379
+ }
380
+
381
+ const pooled = this.#runtimes[runtimeIndex];
382
+ if (!pooled || pooled.tainted) {
383
+ throw new Error(`Runtime ${runtimeIndex} unavailable or tainted`);
384
+ }
385
+
386
+ if (!this.#workletsModule) {
387
+ throw new Error('Worklets module not loaded');
388
+ }
389
+
390
+ // Prepare data for worklet transfer
391
+ const useArrayEncoding = !this.#uint8ArraySupported;
392
+ const keyData: number[] | Uint8Array = useArrayEncoding
393
+ ? Array.from(privateKey)
394
+ : new Uint8Array(privateKey);
395
+
396
+ const taskData = tasks.map((t) => ({
397
+ taskId: t.taskId,
398
+ inputIndex: t.inputIndex,
399
+ hash: useArrayEncoding ? Array.from(t.hash) : new Uint8Array(t.hash),
400
+ signatureType: t.signatureType,
401
+ lowR: t.lowR,
402
+ sighashType: t.sighashType,
403
+ leafHash: t.leafHash
404
+ ? (useArrayEncoding ? Array.from(t.leafHash) : new Uint8Array(t.leafHash))
405
+ : undefined,
406
+ }));
407
+
408
+ const pubKeyData: number[] | Uint8Array = useArrayEncoding
409
+ ? Array.from(publicKey)
410
+ : new Uint8Array(publicKey);
411
+
412
+ // Dispatch to worklet runtime with timeout
413
+ const signingPromise = this.#workletsModule.runOnRuntime(
414
+ pooled.runtime,
415
+ () => {
416
+ 'worklet';
417
+ // Inside the worklet runtime, nobleBundle is available from init eval
418
+ // The bundled secp.sign() returns a compact 64-byte Uint8Array directly
419
+ // (not a Signature object). secp.schnorr.sign() also returns Uint8Array.
420
+ const eccModule = (globalThis as Record<string, unknown>)['nobleBundle'] as {
421
+ secp: {
422
+ sign(
423
+ hash: Uint8Array,
424
+ key: Uint8Array,
425
+ opts?: { lowS: boolean; prehash: boolean },
426
+ ): Uint8Array;
427
+ schnorr: {
428
+ sign(hash: Uint8Array, key: Uint8Array): Uint8Array;
429
+ };
430
+ };
431
+ };
432
+
433
+ const toU8 = (data: number[] | Uint8Array): Uint8Array =>
434
+ data instanceof Uint8Array ? data : new Uint8Array(data);
435
+
436
+ const privKey = toU8(keyData);
437
+ const results: Array<{
438
+ type: 'result';
439
+ taskId: string;
440
+ signature: number[];
441
+ inputIndex: number;
442
+ publicKey: number[];
443
+ signatureType: number;
444
+ leafHash?: number[];
445
+ }> = [];
446
+ const errors: Array<{ inputIndex: number; error: string }> = [];
447
+
448
+ try {
449
+ for (const task of taskData) {
450
+ try {
451
+ const hash = toU8(task.hash);
452
+ let signature: Uint8Array;
453
+
454
+ if (task.signatureType === 1) {
455
+ signature = eccModule.secp.schnorr.sign(hash, privKey);
456
+ } else {
457
+ // prehash: false — input is already a 32-byte hash
458
+ signature = eccModule.secp.sign(hash, privKey, {
459
+ lowS: true,
460
+ prehash: false,
461
+ });
462
+ }
463
+
464
+ const entry: (typeof results)[number] = {
465
+ type: 'result' as const,
466
+ taskId: task.taskId,
467
+ signature: Array.from(signature),
468
+ inputIndex: task.inputIndex,
469
+ publicKey: Array.from(toU8(pubKeyData)),
470
+ signatureType: task.signatureType,
471
+ };
472
+ if (task.leafHash) {
473
+ entry.leafHash = Array.from(toU8(task.leafHash));
474
+ }
475
+ results.push(entry);
476
+ } catch (err: unknown) {
477
+ const msg = err instanceof Error ? err.message : 'Signing failed';
478
+ errors.push({ inputIndex: task.inputIndex, error: msg });
479
+ }
480
+ }
481
+ } finally {
482
+ // SECURITY: Zero key inside worklet
483
+ privKey.fill(0);
484
+ }
485
+
486
+ return { results, errors };
487
+ },
488
+ );
489
+
490
+ // Timeout guard
491
+ const timeoutPromise = new Promise<never>((_resolve, reject) => {
492
+ setTimeout(() => {
493
+ pooled.tainted = true;
494
+ this.#replaceRuntime(pooled).catch(() => {});
495
+ reject(new Error(`Worklet signing timeout for ${tasks.length} tasks`));
496
+ }, this.#config.maxKeyHoldTimeMs);
497
+ });
498
+
499
+ const raw = await Promise.race([signingPromise, timeoutPromise]);
500
+
501
+ // Convert results back to proper types
502
+ const signatures: SigningResultMessage[] = raw.results.map((r) => ({
503
+ type: 'result' as const,
504
+ taskId: r.taskId,
505
+ signature: new Uint8Array(r.signature),
506
+ inputIndex: r.inputIndex,
507
+ publicKey: new Uint8Array(r.publicKey),
508
+ signatureType: r.signatureType as SignatureType,
509
+ leafHash: r.leafHash ? new Uint8Array(r.leafHash) : undefined,
510
+ }));
511
+
512
+ const errors = new Map<number, string>();
513
+ for (const e of raw.errors) {
514
+ errors.set(e.inputIndex, e.error);
515
+ }
516
+
517
+ return { signatures, errors };
518
+ }
519
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * React Native entry point for the workers module.
3
+ *
4
+ * Provides the same public API as the browser/Node.js workers module
5
+ * but uses WorkletSigningPool (parallel via react-native-worklets)
6
+ * when available, falling back to SequentialSigningPool (main-thread).
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+
11
+ // Type exports (same as main index.ts)
12
+ export {
13
+ SignatureType,
14
+ type SigningTaskMessage,
15
+ type BatchSigningMessage,
16
+ type BatchSigningTask,
17
+ type BatchSigningResultMessage,
18
+ type BatchSigningTaskResult,
19
+ type BatchSigningTaskError,
20
+ type WorkerInitMessage,
21
+ type WorkerShutdownMessage,
22
+ type WorkerMessage,
23
+ type SigningResultMessage,
24
+ type SigningErrorMessage,
25
+ type WorkerReadyMessage,
26
+ type WorkerShutdownAckMessage,
27
+ type WorkerResponse,
28
+ isSigningError,
29
+ isSigningResult,
30
+ isBatchResult,
31
+ isWorkerReady,
32
+ type WorkerEccLib,
33
+ type WorkerPoolConfig,
34
+ type SigningTask,
35
+ type ParallelSignerKeyPair,
36
+ type ParallelSigningResult,
37
+ type SigningPoolLike,
38
+ WorkerState,
39
+ type PooledWorker,
40
+ } from './types.js';
41
+
42
+ // Sequential pool (React Native fallback)
43
+ export { SequentialSigningPool } from './WorkerSigningPool.sequential.js';
44
+
45
+ // Worklet pool (React Native parallel signing)
46
+ export { WorkletSigningPool } from './WorkerSigningPool.worklet.js';
47
+
48
+ // Alias for API compatibility — consumers using `WorkerSigningPool` get the sequential pool
49
+ export { SequentialSigningPool as WorkerSigningPool } from './WorkerSigningPool.sequential.js';
50
+
51
+ // PSBT parallel signing integration (works with any SigningPoolLike)
52
+ export {
53
+ signPsbtParallel,
54
+ prepareSigningTasks,
55
+ applySignaturesToPsbt,
56
+ type ParallelSignOptions,
57
+ type PsbtParallelKeyPair,
58
+ } from './psbt-parallel.js';
59
+
60
+ /**
61
+ * Detects the runtime environment.
62
+ *
63
+ * @returns Always 'react-native' in this entry point.
64
+ */
65
+ export function detectRuntime(): 'node' | 'browser' | 'react-native' | 'unknown' {
66
+ return 'react-native';
67
+ }
68
+
69
+ /**
70
+ * Cached result of the worklets availability check.
71
+ * `null` = not yet checked, `true` = available, `false` = unavailable.
72
+ */
73
+ let workletsAvailable: boolean | null = null;
74
+
75
+ /**
76
+ * Creates a signing pool appropriate for the React Native runtime.
77
+ *
78
+ * Tries to use WorkletSigningPool (parallel via react-native-worklets).
79
+ * Falls back to SequentialSigningPool if worklets are not installed.
80
+ */
81
+ export async function createSigningPool(
82
+ config?: import('./types.js').WorkerPoolConfig,
83
+ ): Promise<import('./types.js').SigningPoolLike> {
84
+ // Check worklets availability (cached after first probe)
85
+ if (workletsAvailable === null) {
86
+ try {
87
+ await import('react-native-worklets' as string);
88
+ workletsAvailable = true;
89
+ } catch {
90
+ workletsAvailable = false;
91
+ }
92
+ }
93
+
94
+ if (workletsAvailable) {
95
+ try {
96
+ const { WorkletSigningPool } = await import('./WorkerSigningPool.worklet.js');
97
+ const pool = WorkletSigningPool.getInstance(config);
98
+ await pool.initialize();
99
+ return pool;
100
+ } catch {
101
+ // Initialization failed (e.g. eval blocked) — fall through
102
+ workletsAvailable = false;
103
+ }
104
+ }
105
+
106
+ const { SequentialSigningPool } = await import('./WorkerSigningPool.sequential.js');
107
+ const pool = SequentialSigningPool.getInstance(config);
108
+ await pool.initialize();
109
+ return pool;
110
+ }
@@ -74,6 +74,7 @@ export {
74
74
  type SigningTask,
75
75
  type ParallelSignerKeyPair,
76
76
  type ParallelSigningResult,
77
+ type SigningPoolLike,
77
78
  WorkerState,
78
79
  type PooledWorker,
79
80
  } from './types.js';
@@ -101,7 +102,10 @@ export {
101
102
  *
102
103
  * @returns 'node' for Node.js, 'browser' for browsers, 'unknown' otherwise
103
104
  */
104
- export function detectRuntime(): 'node' | 'browser' | 'unknown' {
105
+ export function detectRuntime(): 'node' | 'browser' | 'react-native' | 'unknown' {
106
+ if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
107
+ return 'react-native';
108
+ }
105
109
  if (typeof process !== 'undefined' && process.versions?.node) {
106
110
  return 'node';
107
111
  }
@@ -157,6 +161,11 @@ export async function createSigningPool(config?: WorkerPoolConfig): Promise<{
157
161
  const pool = WorkerSigningPool.getInstance(config);
158
162
  await pool.initialize();
159
163
  return pool;
164
+ } else if (runtime === 'react-native') {
165
+ const { SequentialSigningPool } = await import('./WorkerSigningPool.sequential.js');
166
+ const pool = SequentialSigningPool.getInstance(config);
167
+ await pool.initialize();
168
+ return pool;
160
169
  } else {
161
170
  throw new Error('Unsupported runtime for worker signing pool');
162
171
  }