@cap.js/widget 0.1.35 → 0.1.36

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/src/worker.js CHANGED
@@ -1,115 +1,184 @@
1
1
  (() => {
2
- const solveFallback = async ({ salt, target }) => {
3
- let nonce = 0;
4
- const batchSize = 50000;
5
- const encoder = new TextEncoder();
6
-
7
- const targetBytes = new Uint8Array(target.length / 2);
8
- for (let k = 0; k < targetBytes.length; k++) {
9
- targetBytes[k] = parseInt(target.substring(k * 2, k * 2 + 2), 16);
10
- }
11
- const targetBytesLength = targetBytes.length;
12
-
13
- while (true) {
14
- try {
15
- for (let i = 0; i < batchSize; i++) {
16
- const inputString = salt + nonce;
17
- const inputBytes = encoder.encode(inputString);
18
-
19
- const hashBuffer = await crypto.subtle.digest("SHA-256", inputBytes);
20
-
21
- const hashBytes = new Uint8Array(hashBuffer, 0, targetBytesLength);
22
-
23
- let matches = true;
24
- for (let k = 0; k < targetBytesLength; k++) {
25
- if (hashBytes[k] !== targetBytes[k]) {
26
- matches = false;
27
- break;
28
- }
29
- }
30
-
31
- if (matches) {
32
- self.postMessage({ nonce, found: true });
33
- return;
34
- }
35
-
36
- nonce++;
37
- }
38
- } catch (error) {
39
- console.error("[cap worker]", error);
40
- self.postMessage({
41
- found: false,
42
- error: error.message,
43
- });
44
- return;
45
- }
46
- }
47
- };
48
-
49
- if (
50
- typeof WebAssembly !== "object" ||
51
- typeof WebAssembly?.instantiate !== "function"
52
- ) {
53
- console.warn(
54
- "[cap worker] wasm not supported, falling back to alternative solver. this will be significantly slower.",
55
- );
56
-
57
- self.onmessage = async ({ data: { salt, target } }) => {
58
- return solveFallback({ salt, target });
59
- };
60
-
61
- return;
62
- }
63
-
64
- let wasmCacheUrl, solve_pow_function;
65
-
66
- self.onmessage = async ({ data: { salt, target, wasmUrl } }) => {
67
- let fb;
68
-
69
- if (wasmCacheUrl !== wasmUrl) {
70
- wasmCacheUrl = wasmUrl;
71
- await import(wasmUrl)
72
- .then((wasmModule) => {
73
- return wasmModule.default().then((instance) => {
74
- solve_pow_function = (
75
- instance?.exports ? instance.exports : wasmModule
76
- ).solve_pow;
77
- });
78
- })
79
- .catch((e) => {
80
- console.error("[cap worker] using fallback solver due to error:", e);
81
- fb = true;
82
-
83
- return solveFallback({ salt, target });
84
- });
85
-
86
- if (fb) return;
87
- }
88
-
89
- try {
90
- const startTime = performance.now();
91
- const nonce = solve_pow_function(salt, target);
92
- const endTime = performance.now();
93
-
94
- self.postMessage({
95
- nonce: Number(nonce),
96
- found: true,
97
- durationMs: (endTime - startTime).toFixed(2),
98
- });
99
- } catch (error) {
100
- console.error("[cap worker]", error);
101
-
102
- self.postMessage({
103
- found: false,
104
- error: error.message || String(error),
105
- });
106
- }
107
- };
108
-
109
- self.onerror = (error) => {
110
- self.postMessage({
111
- found: false,
112
- error,
113
- });
114
- };
2
+ const solveFallback = async ({ salt, target }) => {
3
+ let nonce = 0;
4
+ const batchSize = 50000;
5
+ const encoder = new TextEncoder();
6
+
7
+ const targetBytes = new Uint8Array(target.length / 2);
8
+ for (let k = 0; k < targetBytes.length; k++) {
9
+ targetBytes[k] = parseInt(target.substring(k * 2, k * 2 + 2), 16);
10
+ }
11
+ const targetBytesLength = targetBytes.length;
12
+
13
+ while (true) {
14
+ try {
15
+ for (let i = 0; i < batchSize; i++) {
16
+ const inputString = salt + nonce;
17
+ const inputBytes = encoder.encode(inputString);
18
+
19
+ const hashBuffer = await crypto.subtle.digest("SHA-256", inputBytes);
20
+
21
+ const hashBytes = new Uint8Array(hashBuffer, 0, targetBytesLength);
22
+
23
+ let matches = true;
24
+ for (let k = 0; k < targetBytesLength; k++) {
25
+ if (hashBytes[k] !== targetBytes[k]) {
26
+ matches = false;
27
+ break;
28
+ }
29
+ }
30
+
31
+ if (matches) {
32
+ self.postMessage({ nonce, found: true });
33
+ return;
34
+ }
35
+
36
+ nonce++;
37
+ }
38
+ } catch (error) {
39
+ console.error("[cap worker]", error);
40
+ self.postMessage({
41
+ found: false,
42
+ error: error.message,
43
+ });
44
+ return;
45
+ }
46
+ }
47
+ };
48
+
49
+ if (typeof WebAssembly !== "object" || typeof WebAssembly?.instantiate !== "function") {
50
+ console.warn(
51
+ "[cap worker] wasm not supported, falling back to alternative solver. this will be significantly slower.",
52
+ );
53
+
54
+ self.onmessage = async ({ data: { salt, target } }) => {
55
+ return solveFallback({ salt, target });
56
+ };
57
+
58
+ return;
59
+ }
60
+
61
+ let solve_pow_function = null;
62
+
63
+ const initFromModule = (wasmModule) => {
64
+ try {
65
+ let wasm;
66
+ let WASM_VECTOR_LEN = 0;
67
+ let cachedUint8ArrayMemory = null;
68
+
69
+ const getMemory = () => {
70
+ if (cachedUint8ArrayMemory === null || cachedUint8ArrayMemory.byteLength === 0) {
71
+ cachedUint8ArrayMemory = new Uint8Array(wasm.memory.buffer);
72
+ }
73
+ return cachedUint8ArrayMemory;
74
+ };
75
+
76
+ const encoder = new TextEncoder();
77
+
78
+ const passStringToWasm = (str, malloc, realloc) => {
79
+ if (realloc === undefined) {
80
+ const encoded = encoder.encode(str);
81
+ const ptr = malloc(encoded.length, 1) >>> 0;
82
+ getMemory()
83
+ .subarray(ptr, ptr + encoded.length)
84
+ .set(encoded);
85
+ WASM_VECTOR_LEN = encoded.length;
86
+ return ptr;
87
+ }
88
+
89
+ let len = str.length;
90
+ let ptr = malloc(len, 1) >>> 0;
91
+ const mem = getMemory();
92
+ let offset = 0;
93
+
94
+ for (; offset < len; offset++) {
95
+ const code = str.charCodeAt(offset);
96
+ if (code > 127) break;
97
+ mem[ptr + offset] = code;
98
+ }
99
+
100
+ if (offset !== len) {
101
+ if (offset !== 0) str = str.slice(offset);
102
+ ptr = realloc(ptr, len, (len = offset + str.length * 3), 1) >>> 0;
103
+ const subarray = getMemory().subarray(ptr + offset, ptr + len);
104
+ const { written } = encoder.encodeInto(str, subarray);
105
+ offset += written;
106
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
107
+ }
108
+
109
+ WASM_VECTOR_LEN = offset;
110
+ return ptr;
111
+ };
112
+
113
+ const imports = { wbg: {} };
114
+ imports.wbg.__wbindgen_init_externref_table = () => {
115
+ const table = wasm.__wbindgen_export_0;
116
+ const offset = table.grow(4);
117
+ table.set(0, undefined);
118
+ table.set(offset + 0, undefined);
119
+ table.set(offset + 1, null);
120
+ table.set(offset + 2, true);
121
+ table.set(offset + 3, false);
122
+ };
123
+
124
+ const instance = new WebAssembly.Instance(wasmModule, imports);
125
+ wasm = instance.exports;
126
+
127
+ if (wasm.__wbindgen_start) wasm.__wbindgen_start();
128
+
129
+ solve_pow_function = (salt, target) => {
130
+ const saltPtr = passStringToWasm(salt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
131
+ const saltLen = WASM_VECTOR_LEN;
132
+ const targetPtr = passStringToWasm(target, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
133
+ const targetLen = WASM_VECTOR_LEN;
134
+ return BigInt.asUintN(64, wasm.solve_pow(saltPtr, saltLen, targetPtr, targetLen));
135
+ };
136
+
137
+ return true;
138
+ } catch (e) {
139
+ console.error("[cap worker] failed to init wasm from module:", e);
140
+ return false;
141
+ }
142
+ };
143
+
144
+ self.onmessage = async ({ data: { salt, target, wasmModule } }) => {
145
+ if (wasmModule instanceof WebAssembly.Module && solve_pow_function === null) {
146
+ const ok = initFromModule(wasmModule);
147
+ if (!ok) {
148
+ console.warn("[cap worker] wasm init failed, falling back to JS solver.");
149
+ return solveFallback({ salt, target });
150
+ }
151
+ }
152
+
153
+ if (solve_pow_function === null) {
154
+ console.warn("[cap worker] no wasm module provided, falling back to JS solver.");
155
+ return solveFallback({ salt, target });
156
+ }
157
+
158
+ try {
159
+ const startTime = performance.now();
160
+ const nonce = solve_pow_function(salt, target);
161
+ const endTime = performance.now();
162
+
163
+ self.postMessage({
164
+ nonce: Number(nonce),
165
+ found: true,
166
+ durationMs: (endTime - startTime).toFixed(2),
167
+ });
168
+ } catch (error) {
169
+ console.error("[cap worker]", error);
170
+
171
+ self.postMessage({
172
+ found: false,
173
+ error: error.message || String(error),
174
+ });
175
+ }
176
+ };
177
+
178
+ self.onerror = (error) => {
179
+ self.postMessage({
180
+ found: false,
181
+ error,
182
+ });
183
+ };
115
184
  })();
@@ -359,26 +359,6 @@
359
359
  });
360
360
  });
361
361
 
362
- // ====================================================
363
-
364
- // this is a now unused library which an old version of
365
- // cap depended on. to avoid breaking things as much as
366
- // possible, we've kept it here.
367
-
368
- try {
369
- // lets us know how many people are actually using this
370
- // so we can know when it's safe to deprecate.
371
-
372
- // server source code:
373
- // https://gist.github.com/tiagozip/ffb39489f5af91e6e45f94f1bfa14ab2
374
- fetch(
375
- `https://api.tiagorangel.com/cap-legacy-widget?h=${self.location?.hostname || "unknown"}`,
376
- {
377
- mode: "no-cors",
378
- },
379
- ).catch(() => {});
380
- } catch {}
381
-
382
362
  console.warn(
383
363
  `[cap]
384
364
  %cYou're using a deprecated version of Cap's widget that still relies on this file.
@@ -387,9 +367,4 @@ It may continue to work for now, but could break at any time since this dependen
387
367
 
388
368
  Please update Cap to fix this.`,
389
369
  "font-size:15px;background-image:url('https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fpreview.colorkit.co%2Fcolor%2FEEEEEE.png%3Ftype%3Darticle-preview-logo%26size%3Dsocial%26colorname%3DSuper%2520Silver&f=1&nofb=1&ipt=49845e9195461b7c779182793c2ebf7834102eaf5561c15fa2cbb55494b77a9b');background-size:10px",
390
- );
391
-
392
- console.log(
393
- `%cTo help us understand how many people are using this legacy version and when it's safe to deprecate it, we've sent a small, privacy-friendly beacon to our servers. All related code, including the telemetry server, is open source.\n\nYou might have gotten a CSP error before this, it should be safe to ignore. Server source code: https://gist.github.com/tiagozip/ffb39489f5af91e6e45f94f1bfa14ab2`,
394
- "font-size:11px;color:#b7b7b7",
395
- );
370
+ );