@pezkuwi/wasm-crypto 7.5.12 → 7.5.15
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/Cargo.toml +50 -0
- package/Xargo.toml +2 -0
- package/build/README.md +29 -0
- package/build/bundle-pezkuwi-wasm-crypto.js +2092 -0
- package/build/bundle.d.ts +40 -0
- package/build/bundle.js +505 -0
- package/build/cjs/bundle.d.ts +40 -0
- package/build/cjs/bundle.js +544 -0
- package/{index.d.ts → build/cjs/index.d.ts} +0 -1
- package/build/cjs/index.js +4 -0
- package/build/cjs/init.js +21 -0
- package/build/cjs/initNone.js +20 -0
- package/build/cjs/initOnlyAsm.js +20 -0
- package/build/cjs/initOnlyWasm.js +20 -0
- package/build/cjs/initWasmAsm.js +20 -0
- package/build/cjs/packageInfo.js +4 -0
- package/build/index.d.ts +1 -0
- package/build/index.js +1 -0
- package/build/init.d.ts +16 -0
- package/build/init.js +17 -0
- package/build/initNone.d.ts +10 -0
- package/build/initNone.js +17 -0
- package/build/initOnlyAsm.d.ts +10 -0
- package/build/initOnlyAsm.js +17 -0
- package/build/initOnlyWasm.d.ts +10 -0
- package/build/initOnlyWasm.js +17 -0
- package/build/initWasmAsm.d.ts +10 -0
- package/build/initWasmAsm.js +17 -0
- package/build/package.json +208 -0
- package/build/packageDetect.d.ts +1 -0
- package/build/packageDetect.js +8 -0
- package/build/packageInfo.d.ts +6 -0
- package/build/packageInfo.js +1 -0
- package/build-deno/README.md +25 -0
- package/build-deno/bundle.ts +597 -0
- package/build-deno/index.ts +2 -0
- package/build-deno/init.ts +23 -0
- package/build-deno/initNone.ts +21 -0
- package/build-deno/initOnlyAsm.ts +21 -0
- package/build-deno/initOnlyWasm.ts +21 -0
- package/build-deno/initWasmAsm.ts +21 -0
- package/build-deno/mod.ts +2 -0
- package/build-deno/packageDetect.ts +12 -0
- package/build-deno/packageInfo.ts +3 -0
- package/build-deno/rs/.editorconfig +10 -0
- package/build-tsc/bundle.d.ts +40 -0
- package/{cjs → build-tsc}/index.d.ts +0 -1
- package/build-tsc-cjs/bundle.js +544 -0
- package/{cjs → build-tsc-cjs}/index.js +0 -1
- package/build-tsc-cjs/packageDetect.js +10 -0
- package/{cjs → build-tsc-cjs}/packageInfo.js +1 -1
- package/build-tsc-esm/bundle.js +505 -0
- package/{index.js → build-tsc-esm/index.js} +0 -1
- package/{packageInfo.js → build-tsc-esm/packageInfo.js} +1 -1
- package/package.json +89 -87
- package/src/bundle.ts +613 -0
- package/src/index.ts +5 -0
- package/src/init.ts +25 -0
- package/src/initNone.ts +23 -0
- package/src/initOnlyAsm.ts +23 -0
- package/src/initOnlyWasm.ts +23 -0
- package/src/initWasmAsm.ts +23 -0
- package/src/lib.rs +24 -0
- package/src/mod.ts +4 -0
- package/src/packageDetect.ts +16 -0
- package/src/packageInfo.ts +6 -0
- package/src/rs/.editorconfig +10 -0
- package/src/rs/bip39.rs +139 -0
- package/src/rs/ed25519.rs +142 -0
- package/src/rs/hashing.rs +322 -0
- package/src/rs/secp256k1.rs +150 -0
- package/src/rs/sr25519.rs +331 -0
- package/src/rs/vrf.rs +144 -0
- package/test/all/bip39.js +86 -0
- package/test/all/ed25519.js +84 -0
- package/test/all/hashing.js +138 -0
- package/test/all/index.js +126 -0
- package/test/all/secp256k1.js +105 -0
- package/test/all/sr25519.js +211 -0
- package/test/all/vrf.js +74 -0
- package/test/asm.js +10 -0
- package/test/deno.ts +38 -0
- package/test/jest.spec.ts +25 -0
- package/test/loader-build.js +39 -0
- package/test/wasm.js +8 -0
- package/tsconfig.build.json +19 -0
- package/tsconfig.build.tsbuildinfo +1 -0
- package/tsconfig.spec.json +16 -0
- package/tsconfig.spec.tsbuildinfo +1 -0
- package/bundle-pezkuwi-wasm-crypto.js +0 -777
- package/bundle.d.ts +0 -37
- package/bundle.js +0 -165
- package/cjs/bundle.d.ts +0 -37
- package/cjs/bundle.js +0 -171
- /package/{LICENSE → build/LICENSE} +0 -0
- /package/{init.d.ts → build/cjs/init.d.ts} +0 -0
- /package/{initNone.d.ts → build/cjs/initNone.d.ts} +0 -0
- /package/{initOnlyAsm.d.ts → build/cjs/initOnlyAsm.d.ts} +0 -0
- /package/{initOnlyWasm.d.ts → build/cjs/initOnlyWasm.d.ts} +0 -0
- /package/{initWasmAsm.d.ts → build/cjs/initWasmAsm.d.ts} +0 -0
- /package/{cjs → build/cjs}/package.json +0 -0
- /package/{packageDetect.d.ts → build/cjs/packageDetect.d.ts} +0 -0
- /package/{cjs → build/cjs}/packageDetect.js +0 -0
- /package/{packageInfo.d.ts → build/cjs/packageInfo.d.ts} +0 -0
- /package/{cjs → build-tsc}/init.d.ts +0 -0
- /package/{cjs → build-tsc}/initNone.d.ts +0 -0
- /package/{cjs → build-tsc}/initOnlyAsm.d.ts +0 -0
- /package/{cjs → build-tsc}/initOnlyWasm.d.ts +0 -0
- /package/{cjs → build-tsc}/initWasmAsm.d.ts +0 -0
- /package/{cjs → build-tsc}/packageDetect.d.ts +0 -0
- /package/{cjs → build-tsc}/packageInfo.d.ts +0 -0
- /package/{cjs → build-tsc-cjs}/init.js +0 -0
- /package/{cjs → build-tsc-cjs}/initNone.js +0 -0
- /package/{cjs → build-tsc-cjs}/initOnlyAsm.js +0 -0
- /package/{cjs → build-tsc-cjs}/initOnlyWasm.js +0 -0
- /package/{cjs → build-tsc-cjs}/initWasmAsm.js +0 -0
- /package/{init.js → build-tsc-esm/init.js} +0 -0
- /package/{initNone.js → build-tsc-esm/initNone.js} +0 -0
- /package/{initOnlyAsm.js → build-tsc-esm/initOnlyAsm.js} +0 -0
- /package/{initOnlyWasm.js → build-tsc-esm/initOnlyWasm.js} +0 -0
- /package/{initWasmAsm.js → build-tsc-esm/initWasmAsm.js} +0 -0
- /package/{packageDetect.js → build-tsc-esm/packageDetect.js} +0 -0
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
import { wasmBytes } from '@pezkuwi/wasm-crypto-wasm';
|
|
2
|
+
export { packageInfo } from './packageInfo.js';
|
|
3
|
+
let wasm = null;
|
|
4
|
+
let cachedUint8ArrayMemory = null;
|
|
5
|
+
let cachedTextDecoder = null;
|
|
6
|
+
let _isReady = false;
|
|
7
|
+
let initPromise = null;
|
|
8
|
+
let WASM_VECTOR_LEN = 0;
|
|
9
|
+
function getUint8ArrayMemory() {
|
|
10
|
+
if (cachedUint8ArrayMemory === null || cachedUint8ArrayMemory.byteLength === 0) {
|
|
11
|
+
cachedUint8ArrayMemory = new Uint8Array(wasm['memory'].buffer);
|
|
12
|
+
}
|
|
13
|
+
return cachedUint8ArrayMemory;
|
|
14
|
+
}
|
|
15
|
+
function getStringFromWasm(ptr, len) {
|
|
16
|
+
if (!cachedTextDecoder) {
|
|
17
|
+
cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
|
18
|
+
cachedTextDecoder.decode();
|
|
19
|
+
}
|
|
20
|
+
ptr = ptr >>> 0;
|
|
21
|
+
return cachedTextDecoder.decode(getUint8ArrayMemory().subarray(ptr, ptr + len));
|
|
22
|
+
}
|
|
23
|
+
function getArrayU8FromWasm(ptr, len) {
|
|
24
|
+
ptr = ptr >>> 0;
|
|
25
|
+
return getUint8ArrayMemory().subarray(ptr / 1, ptr / 1 + len);
|
|
26
|
+
}
|
|
27
|
+
function passArray8ToWasm(arg, malloc) {
|
|
28
|
+
const ptr = malloc(arg.length * 1, 1) >>> 0;
|
|
29
|
+
getUint8ArrayMemory().set(arg, ptr / 1);
|
|
30
|
+
WASM_VECTOR_LEN = arg.length;
|
|
31
|
+
return ptr;
|
|
32
|
+
}
|
|
33
|
+
function addToExternrefTable(obj) {
|
|
34
|
+
const idx = wasm['__externref_table_alloc']();
|
|
35
|
+
wasm['__wbindgen_externrefs'].set(idx, obj);
|
|
36
|
+
return idx;
|
|
37
|
+
}
|
|
38
|
+
function takeFromExternrefTable(idx) {
|
|
39
|
+
const value = wasm['__wbindgen_externrefs'].get(idx);
|
|
40
|
+
wasm['__externref_table_dealloc'](idx);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function isLikeNone(x) {
|
|
44
|
+
return x === undefined || x === null;
|
|
45
|
+
}
|
|
46
|
+
function handleError(f, args) {
|
|
47
|
+
try {
|
|
48
|
+
return f.apply(null, args);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
const idx = addToExternrefTable(e);
|
|
52
|
+
wasm['__wbindgen_exn_store'](idx);
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function createImports() {
|
|
57
|
+
const import0 = {
|
|
58
|
+
__proto__: null,
|
|
59
|
+
__wbg___wbindgen_is_function_0095a73b8b156f76: function (arg0) {
|
|
60
|
+
return typeof (arg0) === 'function';
|
|
61
|
+
},
|
|
62
|
+
__wbg___wbindgen_is_object_5ae8e5880f2c1fbd: function (arg0) {
|
|
63
|
+
const val = arg0;
|
|
64
|
+
return typeof (val) === 'object' && val !== null;
|
|
65
|
+
},
|
|
66
|
+
__wbg___wbindgen_is_string_cd444516edc5b180: function (arg0) {
|
|
67
|
+
return typeof (arg0) === 'string';
|
|
68
|
+
},
|
|
69
|
+
__wbg___wbindgen_is_undefined_9e4d92534c42d778: function (arg0) {
|
|
70
|
+
return arg0 === undefined;
|
|
71
|
+
},
|
|
72
|
+
__wbg___wbindgen_throw_be289d5034ed271b: function (arg0, arg1) {
|
|
73
|
+
throw new Error(getStringFromWasm(arg0, arg1));
|
|
74
|
+
},
|
|
75
|
+
__wbg_call_389efe28435a9388: function () {
|
|
76
|
+
return handleError(function (arg0, arg1) {
|
|
77
|
+
return arg0.call(arg1);
|
|
78
|
+
}, arguments);
|
|
79
|
+
},
|
|
80
|
+
__wbg_call_4708e0c13bdc8e95: function () {
|
|
81
|
+
return handleError(function (arg0, arg1, arg2) {
|
|
82
|
+
return arg0.call(arg1, arg2);
|
|
83
|
+
}, arguments);
|
|
84
|
+
},
|
|
85
|
+
__wbg_crypto_86f2631e91b51511: function (arg0) {
|
|
86
|
+
return arg0.crypto;
|
|
87
|
+
},
|
|
88
|
+
__wbg_getRandomValues_b3f15fcbfabb0f8b: function () {
|
|
89
|
+
return handleError(function (arg0, arg1) {
|
|
90
|
+
arg0.getRandomValues(arg1);
|
|
91
|
+
}, arguments);
|
|
92
|
+
},
|
|
93
|
+
__wbg_length_32ed9a279acd054c: function (arg0) {
|
|
94
|
+
return arg0.length;
|
|
95
|
+
},
|
|
96
|
+
__wbg_msCrypto_d562bbe83e0d4b91: function (arg0) {
|
|
97
|
+
return arg0.msCrypto;
|
|
98
|
+
},
|
|
99
|
+
__wbg_new_no_args_1c7c842f08d00ebb: function (arg0, arg1) {
|
|
100
|
+
return new Function(getStringFromWasm(arg0, arg1));
|
|
101
|
+
},
|
|
102
|
+
__wbg_new_with_length_a2c39cbe88fd8ff1: function (arg0) {
|
|
103
|
+
return new Uint8Array(arg0 >>> 0);
|
|
104
|
+
},
|
|
105
|
+
__wbg_node_e1f24f89a7336c2e: function (arg0) {
|
|
106
|
+
return arg0.node;
|
|
107
|
+
},
|
|
108
|
+
__wbg_process_3975fd6c72f520aa: function (arg0) {
|
|
109
|
+
return arg0.process;
|
|
110
|
+
},
|
|
111
|
+
__wbg_prototypesetcall_bdcdcc5842e4d77d: function (arg0, arg1, arg2) {
|
|
112
|
+
Uint8Array.prototype.set.call(getArrayU8FromWasm(arg0, arg1), arg2);
|
|
113
|
+
},
|
|
114
|
+
__wbg_randomFillSync_f8c153b79f285817: function () {
|
|
115
|
+
return handleError(function (arg0, arg1) {
|
|
116
|
+
arg0.randomFillSync(arg1);
|
|
117
|
+
}, arguments);
|
|
118
|
+
},
|
|
119
|
+
__wbg_require_b74f47fc2d022fd6: function () {
|
|
120
|
+
return handleError(function () {
|
|
121
|
+
return typeof module !== 'undefined' ? module.require : undefined;
|
|
122
|
+
}, arguments);
|
|
123
|
+
},
|
|
124
|
+
__wbg_static_accessor_GLOBAL_12837167ad935116: function () {
|
|
125
|
+
const ret = typeof global === 'undefined' ? null : global;
|
|
126
|
+
return isLikeNone(ret) ? 0 : addToExternrefTable(ret);
|
|
127
|
+
},
|
|
128
|
+
__wbg_static_accessor_GLOBAL_THIS_e628e89ab3b1c95f: function () {
|
|
129
|
+
const ret = typeof globalThis === 'undefined' ? null : globalThis;
|
|
130
|
+
return isLikeNone(ret) ? 0 : addToExternrefTable(ret);
|
|
131
|
+
},
|
|
132
|
+
__wbg_static_accessor_SELF_a621d3dfbb60d0ce: function () {
|
|
133
|
+
const ret = typeof self === 'undefined' ? null : self;
|
|
134
|
+
return isLikeNone(ret) ? 0 : addToExternrefTable(ret);
|
|
135
|
+
},
|
|
136
|
+
__wbg_static_accessor_WINDOW_f8727f0cf888e0bd: function () {
|
|
137
|
+
const ret = typeof window === 'undefined' ? null : window;
|
|
138
|
+
return isLikeNone(ret) ? 0 : addToExternrefTable(ret);
|
|
139
|
+
},
|
|
140
|
+
__wbg_subarray_a96e1fef17ed23cb: function (arg0, arg1, arg2) {
|
|
141
|
+
return arg0.subarray(arg1 >>> 0, arg2 >>> 0);
|
|
142
|
+
},
|
|
143
|
+
__wbg_versions_4e31226f5e8dc909: function (arg0) {
|
|
144
|
+
return arg0.versions;
|
|
145
|
+
},
|
|
146
|
+
__wbindgen_cast_0000000000000001: function (arg0, arg1) {
|
|
147
|
+
return getArrayU8FromWasm(arg0, arg1);
|
|
148
|
+
},
|
|
149
|
+
__wbindgen_cast_0000000000000002: function (arg0, arg1) {
|
|
150
|
+
return getStringFromWasm(arg0, arg1);
|
|
151
|
+
},
|
|
152
|
+
__wbindgen_init_externref_table: function () {
|
|
153
|
+
const table = wasm['__wbindgen_externrefs'];
|
|
154
|
+
const offset = table.grow(4);
|
|
155
|
+
table.set(0, undefined);
|
|
156
|
+
table.set(offset + 0, undefined);
|
|
157
|
+
table.set(offset + 1, null);
|
|
158
|
+
table.set(offset + 2, true);
|
|
159
|
+
table.set(offset + 3, false);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
return {
|
|
163
|
+
__proto__: null,
|
|
164
|
+
'./pezkuwi_wasm_crypto_bg.js': import0,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
async function initWasm() {
|
|
168
|
+
if (_isReady)
|
|
169
|
+
return true;
|
|
170
|
+
try {
|
|
171
|
+
// wasmBytes is already decompressed by @pezkuwi/wasm-crypto-wasm
|
|
172
|
+
const imports = createImports();
|
|
173
|
+
const result = await WebAssembly.instantiate(wasmBytes, imports);
|
|
174
|
+
wasm = result.instance.exports;
|
|
175
|
+
// Initialize the module
|
|
176
|
+
if (typeof wasm['__wbindgen_start'] === 'function') {
|
|
177
|
+
wasm['__wbindgen_start']();
|
|
178
|
+
}
|
|
179
|
+
_isReady = true;
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
console.error('FATAL: Unable to initialize @pezkuwi/wasm-crypto:', error.message);
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export const bridge = {
|
|
188
|
+
wasm: null,
|
|
189
|
+
type: 'wasm'
|
|
190
|
+
};
|
|
191
|
+
export function isReady() {
|
|
192
|
+
return _isReady;
|
|
193
|
+
}
|
|
194
|
+
export async function waitReady() {
|
|
195
|
+
if (!initPromise) {
|
|
196
|
+
initPromise = initWasm();
|
|
197
|
+
}
|
|
198
|
+
return initPromise;
|
|
199
|
+
}
|
|
200
|
+
export function getSigningContext() {
|
|
201
|
+
if (!wasm)
|
|
202
|
+
throw new Error('WASM not initialized');
|
|
203
|
+
const ret = wasm['get_signing_context']();
|
|
204
|
+
const str = getStringFromWasm(ret[0], ret[1]);
|
|
205
|
+
wasm['__wbindgen_free'](ret[0], ret[1], 1);
|
|
206
|
+
return str;
|
|
207
|
+
}
|
|
208
|
+
export function sr25519KeypairFromSeed(seed) {
|
|
209
|
+
if (!wasm)
|
|
210
|
+
throw new Error('WASM not initialized');
|
|
211
|
+
const ptr0 = passArray8ToWasm(seed, wasm['__wbindgen_malloc']);
|
|
212
|
+
const len0 = WASM_VECTOR_LEN;
|
|
213
|
+
const ret = wasm['sr25519_keypair_from_seed'](ptr0, len0);
|
|
214
|
+
if (ret[3]) {
|
|
215
|
+
throw takeFromExternrefTable(ret[2]);
|
|
216
|
+
}
|
|
217
|
+
const v2 = getArrayU8FromWasm(ret[0], ret[1]).slice();
|
|
218
|
+
wasm['__wbindgen_free'](ret[0], ret[1] * 1, 1);
|
|
219
|
+
return v2;
|
|
220
|
+
}
|
|
221
|
+
export function sr25519Sign(publicKey, secretKey, message) {
|
|
222
|
+
if (!wasm)
|
|
223
|
+
throw new Error('WASM not initialized');
|
|
224
|
+
const ptr0 = passArray8ToWasm(publicKey, wasm['__wbindgen_malloc']);
|
|
225
|
+
const len0 = WASM_VECTOR_LEN;
|
|
226
|
+
const ptr1 = passArray8ToWasm(secretKey, wasm['__wbindgen_malloc']);
|
|
227
|
+
const len1 = WASM_VECTOR_LEN;
|
|
228
|
+
const ptr2 = passArray8ToWasm(message, wasm['__wbindgen_malloc']);
|
|
229
|
+
const len2 = WASM_VECTOR_LEN;
|
|
230
|
+
const ret = wasm['sr25519_sign'](ptr0, len0, ptr1, len1, ptr2, len2);
|
|
231
|
+
if (ret[3]) {
|
|
232
|
+
throw takeFromExternrefTable(ret[2]);
|
|
233
|
+
}
|
|
234
|
+
const v4 = getArrayU8FromWasm(ret[0], ret[1]).slice();
|
|
235
|
+
wasm['__wbindgen_free'](ret[0], ret[1] * 1, 1);
|
|
236
|
+
return v4;
|
|
237
|
+
}
|
|
238
|
+
export function sr25519Verify(signature, message, publicKey) {
|
|
239
|
+
if (!wasm)
|
|
240
|
+
throw new Error('WASM not initialized');
|
|
241
|
+
const ptr0 = passArray8ToWasm(signature, wasm['__wbindgen_malloc']);
|
|
242
|
+
const len0 = WASM_VECTOR_LEN;
|
|
243
|
+
const ptr1 = passArray8ToWasm(message, wasm['__wbindgen_malloc']);
|
|
244
|
+
const len1 = WASM_VECTOR_LEN;
|
|
245
|
+
const ptr2 = passArray8ToWasm(publicKey, wasm['__wbindgen_malloc']);
|
|
246
|
+
const len2 = WASM_VECTOR_LEN;
|
|
247
|
+
const ret = wasm['sr25519_verify'](ptr0, len0, ptr1, len1, ptr2, len2);
|
|
248
|
+
return ret !== 0;
|
|
249
|
+
}
|
|
250
|
+
import { sha256 as nobleSha256 } from '@noble/hashes/sha256';
|
|
251
|
+
import { sha512 as nobleSha512 } from '@noble/hashes/sha512';
|
|
252
|
+
import { pbkdf2 as noblePbkdf2 } from '@noble/hashes/pbkdf2';
|
|
253
|
+
import { blake2b as nobleBlake2b } from '@noble/hashes/blake2b';
|
|
254
|
+
import { hmac } from '@noble/hashes/hmac';
|
|
255
|
+
import { keccak_256, keccak_512 } from '@noble/hashes/sha3';
|
|
256
|
+
function normalizeString(str) {
|
|
257
|
+
return (str || '').normalize('NFKD');
|
|
258
|
+
}
|
|
259
|
+
export function bip39Validate(phrase) {
|
|
260
|
+
try {
|
|
261
|
+
const words = normalizeString(phrase).split(' ');
|
|
262
|
+
return [12, 15, 18, 21, 24].includes(words.length);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const BIP39_WORDLIST = 'abandon|ability|able|about|above|absent|absorb|abstract|absurd|abuse|access|accident|account|accuse|achieve|acid|acoustic|acquire|across|act|action|actor|actress|actual|adapt|add|addict|address|adjust|admit|adult|advance|advice|aerobic|affair|afford|afraid|again|age|agent|agree|ahead|aim|air|airport|aisle|alarm|album|alcohol|alert|alien|all|alley|allow|almost|alone|alpha|already|also|alter|always|amateur|amazing|among|amount|amused|analyst|anchor|ancient|anger|angle|angry|animal|ankle|announce|annual|another|answer|antenna|antique|anxiety|any|apart|apology|appear|apple|approve|april|arch|arctic|area|arena|argue|arm|armed|armor|army|around|arrange|arrest|arrive|arrow|art|artefact|artist|artwork|ask|aspect|assault|asset|assist|assume|asthma|athlete|atom|attack|attend|attitude|attract|auction|audit|august|aunt|author|auto|autumn|average|avocado|avoid|awake|aware|away|awesome|awful|awkward|axis|baby|bachelor|bacon|badge|bag|balance|balcony|ball|bamboo|banana|banner|bar|barely|bargain|barrel|base|basic|basket|battle|beach|bean|beauty|because|become|beef|before|begin|behave|behind|believe|below|belt|bench|benefit|best|betray|better|between|beyond|bicycle|bid|bike|bind|biology|bird|birth|bitter|black|blade|blame|blanket|blast|bleak|bless|blind|blood|blossom|blouse|blue|blur|blush|board|boat|body|boil|bomb|bone|bonus|book|boost|border|boring|borrow|boss|bottom|bounce|box|boy|bracket|brain|brand|brass|brave|bread|breeze|brick|bridge|brief|bright|bring|brisk|broccoli|broken|bronze|broom|brother|brown|brush|bubble|buddy|budget|buffalo|build|bulb|bulk|bullet|bundle|bunker|burden|burger|burst|bus|business|busy|butter|buyer|buzz|cabbage|cabin|cable|cactus|cage|cake|call|calm|camera|camp|can|canal|cancel|candy|cannon|canoe|canvas|canyon|capable|capital|captain|car|carbon|card|cargo|carpet|carry|cart|case|cash|casino|castle|casual|cat|catalog|catch|category|cattle|caught|cause|caution|cave|ceiling|celery|cement|census|century|cereal|certain|chair|chalk|champion|change|chaos|chapter|charge|chase|chat|cheap|check|cheese|chef|cherry|chest|chicken|chief|child|chimney|choice|choose|chronic|chuckle|chunk|churn|cigar|cinnamon|circle|citizen|city|civil|claim|clap|clarify|claw|clay|clean|clerk|clever|click|client|cliff|climb|clinic|clip|clock|clog|close|cloth|cloud|clown|club|clump|cluster|clutch|coach|coast|coconut|code|coffee|coil|coin|collect|color|column|combine|come|comfort|comic|common|company|concert|conduct|confirm|congress|connect|consider|control|convince|cook|cool|copper|copy|coral|core|corn|correct|cost|cotton|couch|country|couple|course|cousin|cover|coyote|crack|cradle|craft|cram|crane|crash|crater|crawl|crazy|cream|credit|creek|crew|cricket|crime|crisp|critic|crop|cross|crouch|crowd|crucial|cruel|cruise|crumble|crunch|crush|cry|crystal|cube|culture|cup|cupboard|curious|current|curtain|curve|cushion|custom|cute|cycle|dad|damage|damp|dance|danger|daring|dash|daughter|dawn|day|deal|debate|debris|decade|december|decide|decline|decorate|decrease|deer|defense|define|defy|degree|delay|deliver|demand|demise|denial|dentist|deny|depart|depend|deposit|depth|deputy|derive|describe|desert|design|desk|despair|destroy|detail|detect|develop|device|devote|diagram|dial|diamond|diary|dice|diesel|diet|differ|digital|dignity|dilemma|dinner|dinosaur|direct|dirt|disagree|discover|disease|dish|dismiss|disorder|display|distance|divert|divide|divorce|dizzy|doctor|document|dog|doll|dolphin|domain|donate|donkey|donor|door|dose|double|dove|draft|dragon|drama|drastic|draw|dream|dress|drift|drill|drink|drip|drive|drop|drum|dry|duck|dumb|dune|during|dust|dutch|duty|dwarf|dynamic|eager|eagle|early|earn|earth|easily|east|easy|echo|ecology|economy|edge|edit|educate|effort|egg|eight|either|elbow|elder|electric|elegant|element|elephant|elevator|elite|else|embark|embody|embrace|emerge|emotion|employ|empower|empty|enable|enact|end|endless|endorse|enemy|energy|enforce|engage|engine|enhance|enjoy|enlist|enough|enrich|enroll|ensure|enter|entire|entry|envelope|episode|equal|equip|era|erase|erode|erosion|error|erupt|escape|essay|essence|estate|eternal|ethics|evidence|evil|evoke|evolve|exact|example|excess|exchange|excite|exclude|excuse|execute|exercise|exhaust|exhibit|exile|exist|exit|exotic|expand|expect|expire|explain|expose|express|extend|extra|eye|eyebrow|fabric|face|faculty|fade|faint|faith|fall|false|fame|family|famous|fan|fancy|fantasy|farm|fashion|fat|fatal|father|fatigue|fault|favorite|feature|february|federal|fee|feed|feel|female|fence|festival|fetch|fever|few|fiber|fiction|field|figure|file|film|filter|final|find|fine|finger|finish|fire|firm|first|fiscal|fish|fit|fitness|fix|flag|flame|flash|flat|flavor|flee|flight|flip|float|flock|floor|flower|fluid|flush|fly|foam|focus|fog|foil|fold|follow|food|foot|force|forest|forget|fork|fortune|forum|forward|fossil|foster|found|fox|fragile|frame|frequent|fresh|friend|fringe|frog|front|frost|frown|frozen|fruit|fuel|fun|funny|furnace|fury|future|gadget|gain|galaxy|gallery|game|gap|garage|garbage|garden|garlic|garment|gas|gasp|gate|gather|gauge|gaze|general|genius|genre|gentle|genuine|gesture|ghost|giant|gift|giggle|ginger|giraffe|girl|give|glad|glance|glare|glass|glide|glimpse|globe|gloom|glory|glove|glow|glue|goat|goddess|gold|good|goose|gorilla|gospel|gossip|govern|gown|grab|grace|grain|grant|grape|grass|gravity|great|green|grid|grief|grit|grocery|group|grow|grunt|guard|guess|guide|guilt|guitar|gun|gym|habit|hair|half|hammer|hamster|hand|happy|harbor|hard|harsh|harvest|hat|have|hawk|hazard|head|health|heart|heavy|hedgehog|height|hello|helmet|help|hen|hero|hidden|high|hill|hint|hip|hire|history|hobby|hockey|hold|hole|holiday|hollow|home|honey|hood|hope|horn|horror|horse|hospital|host|hotel|hour|hover|hub|huge|human|humble|humor|hundred|hungry|hunt|hurdle|hurry|hurt|husband|hybrid|ice|icon|idea|identify|idle|ignore|ill|illegal|illness|image|imitate|immense|immune|impact|impose|improve|impulse|inch|include|income|increase|index|indicate|indoor|industry|infant|inflict|inform|inhale|inherit|initial|inject|injury|inmate|inner|innocent|input|inquiry|insane|insect|inside|inspire|install|intact|interest|into|invest|invite|involve|iron|island|isolate|issue|item|ivory|jacket|jaguar|jar|jazz|jealous|jeans|jelly|jewel|job|join|joke|journey|joy|judge|juice|jump|jungle|junior|junk|just|kangaroo|keen|keep|ketchup|key|kick|kid|kidney|kind|kingdom|kiss|kit|kitchen|kite|kitten|kiwi|knee|knife|knock|know|lab|label|labor|ladder|lady|lake|lamp|language|laptop|large|later|latin|laugh|laundry|lava|law|lawn|lawsuit|layer|lazy|leader|leaf|learn|leave|lecture|left|leg|legal|legend|leisure|lemon|lend|length|lens|leopard|lesson|letter|level|liar|liberty|library|license|life|lift|light|like|limb|limit|link|lion|liquid|list|little|live|lizard|load|loan|lobster|local|lock|logic|lonely|long|loop|lottery|loud|lounge|love|loyal|lucky|luggage|lumber|lunar|lunch|luxury|lyrics|machine|mad|magic|magnet|maid|mail|main|major|make|mammal|man|manage|mandate|mango|mansion|manual|maple|marble|march|margin|marine|market|marriage|mask|mass|master|match|material|math|matrix|matter|maximum|maze|meadow|mean|measure|meat|mechanic|medal|media|melody|melt|member|memory|mention|menu|mercy|merge|merit|merry|mesh|message|metal|method|middle|midnight|milk|million|mimic|mind|minimum|minor|minute|miracle|mirror|misery|miss|mistake|mix|mixed|mixture|mobile|model|modify|mom|moment|monitor|monkey|monster|month|moon|moral|more|morning|mosquito|mother|motion|motor|mountain|mouse|move|movie|much|muffin|mule|multiply|muscle|museum|mushroom|music|must|mutual|myself|mystery|myth|naive|name|napkin|narrow|nasty|nation|nature|near|neck|need|negative|neglect|neither|nephew|nerve|nest|net|network|neutral|never|news|next|nice|night|noble|noise|nominee|noodle|normal|north|nose|notable|note|nothing|notice|novel|now|nuclear|number|nurse|nut|oak|obey|object|oblige|obscure|observe|obtain|obvious|occur|ocean|october|odor|off|offer|office|often|oil|okay|old|olive|olympic|omit|once|one|onion|online|only|open|opera|opinion|oppose|option|orange|orbit|orchard|order|ordinary|organ|orient|original|orphan|ostrich|other|outdoor|outer|output|outside|oval|oven|over|own|owner|oxygen|oyster|ozone|pact|paddle|page|pair|palace|palm|panda|panel|panic|panther|paper|parade|parent|park|parrot|party|pass|patch|path|patient|patrol|pattern|pause|pave|payment|peace|peanut|pear|peasant|pelican|pen|penalty|pencil|people|pepper|perfect|permit|person|pet|phone|photo|phrase|physical|piano|picnic|picture|piece|pig|pigeon|pill|pilot|pink|pioneer|pipe|pistol|pitch|pizza|place|planet|plastic|plate|play|please|pledge|pluck|plug|plunge|poem|poet|point|polar|pole|police|pond|pony|pool|popular|portion|position|possible|post|potato|pottery|poverty|powder|power|practice|praise|predict|prefer|prepare|present|pretty|prevent|price|pride|primary|print|priority|prison|private|prize|problem|process|produce|profit|program|project|promote|proof|property|prosper|protect|proud|provide|public|pudding|pull|pulp|pulse|pumpkin|punch|pupil|puppy|purchase|purity|purpose|purse|push|put|puzzle|pyramid|quality|quantum|quarter|question|quick|quit|quiz|quote|rabbit|raccoon|race|rack|radar|radio|rail|rain|raise|rally|ramp|ranch|random|range|rapid|rare|rate|rather|raven|raw|razor|ready|real|reason|rebel|rebuild|recall|receive|recipe|record|recycle|reduce|reflect|reform|refuse|region|regret|regular|reject|relax|release|relief|rely|remain|remember|remind|remove|render|renew|rent|reopen|repair|repeat|replace|report|require|rescue|resemble|resist|resource|response|result|retire|retreat|return|reunion|reveal|review|reward|rhythm|rib|ribbon|rice|rich|ride|ridge|rifle|right|rigid|ring|riot|ripple|risk|ritual|rival|river|road|roast|robot|robust|rocket|romance|roof|rookie|room|rose|rotate|rough|round|route|royal|rubber|rude|rug|rule|run|runway|rural|sad|saddle|sadness|safe|sail|salad|salmon|salon|salt|salute|same|sample|sand|satisfy|satoshi|sauce|sausage|save|say|scale|scan|scare|scatter|scene|scheme|school|science|scissors|scorpion|scout|scrap|screen|script|scrub|sea|search|season|seat|second|secret|section|security|seed|seek|segment|select|sell|seminar|senior|sense|sentence|series|service|session|settle|setup|seven|shadow|shaft|shallow|share|shed|shell|sheriff|shield|shift|shine|ship|shiver|shock|shoe|shoot|shop|short|shoulder|shove|shrimp|shrug|shuffle|shy|sibling|sick|side|siege|sight|sign|silent|silk|silly|silver|similar|simple|since|sing|siren|sister|situate|six|size|skate|sketch|ski|skill|skin|skirt|skull|slab|slam|sleep|slender|slice|slide|slight|slim|slogan|slot|slow|slush|small|smart|smile|smoke|smooth|snack|snake|snap|sniff|snow|soap|soccer|social|sock|soda|soft|solar|soldier|solid|solution|solve|someone|song|soon|sorry|sort|soul|sound|soup|source|south|space|spare|spatial|spawn|speak|special|speed|spell|spend|sphere|spice|spider|spike|spin|spirit|split|spoil|sponsor|spoon|sport|spot|spray|spread|spring|spy|square|squeeze|squirrel|stable|stadium|staff|stage|stairs|stamp|stand|start|state|stay|steak|steel|stem|step|stereo|stick|still|sting|stock|stomach|stone|stool|story|stove|strategy|street|strike|strong|struggle|student|stuff|stumble|style|subject|submit|subway|success|such|sudden|suffer|sugar|suggest|suit|summer|sun|sunny|sunset|super|supply|supreme|sure|surface|surge|surprise|surround|survey|suspect|sustain|swallow|swamp|swap|swarm|swear|sweet|swift|swim|swing|switch|sword|symbol|symptom|syrup|system|table|tackle|tag|tail|talent|talk|tank|tape|target|task|taste|tattoo|taxi|teach|team|tell|ten|tenant|tennis|tent|term|test|text|thank|that|theme|then|theory|there|they|thing|this|thought|three|thrive|throw|thumb|thunder|ticket|tide|tiger|tilt|timber|time|tiny|tip|tired|tissue|title|toast|tobacco|today|toddler|toe|together|toilet|token|tomato|tomorrow|tone|tongue|tonight|tool|tooth|top|topic|topple|torch|tornado|tortoise|toss|total|tourist|toward|tower|town|toy|track|trade|traffic|tragic|train|transfer|trap|trash|travel|tray|treat|tree|trend|trial|tribe|trick|trigger|trim|trip|trophy|trouble|truck|true|truly|trumpet|trust|truth|try|tube|tuition|tumble|tuna|tunnel|turkey|turn|turtle|twelve|twenty|twice|twin|twist|two|type|typical|ugly|umbrella|unable|unaware|uncle|uncover|under|undo|unfair|unfold|unhappy|uniform|unique|unit|universe|unknown|unlock|until|unusual|unveil|update|upgrade|uphold|upon|upper|upset|urban|urge|usage|use|used|useful|useless|usual|utility|vacant|vacuum|vague|valid|valley|valve|van|vanish|vapor|various|vast|vault|vehicle|velvet|vendor|venture|venue|verb|verify|version|very|vessel|veteran|viable|vibrant|vicious|victory|video|view|village|vintage|violin|virtual|virus|visa|visit|visual|vital|vivid|vocal|voice|void|volcano|volume|vote|voyage|wage|wagon|wait|walk|wall|walnut|want|warfare|warm|warrior|wash|wasp|waste|water|wave|way|wealth|weapon|wear|weasel|weather|web|wedding|weekend|weird|welcome|west|wet|whale|what|wheat|wheel|when|where|whip|whisper|wide|width|wife|wild|will|win|window|wine|wing|wink|winner|winter|wire|wisdom|wise|wish|witness|wolf|woman|wonder|wood|wool|word|work|world|worry|worth|wrap|wreck|wrestle|wrist|write|wrong|yard|year|yellow|you|young|youth|zebra|zero|zone|zoo'.split('|');
|
|
269
|
+
function binaryToByte(bin) {
|
|
270
|
+
return parseInt(bin, 2);
|
|
271
|
+
}
|
|
272
|
+
function bytesToBinary(bytes) {
|
|
273
|
+
return bytes.map((x) => x.toString(2).padStart(8, '0')).join('');
|
|
274
|
+
}
|
|
275
|
+
function deriveChecksumBits(entropyBuffer) {
|
|
276
|
+
const hash = nobleSha256(entropyBuffer);
|
|
277
|
+
return bytesToBinary(Array.from(hash)).slice(0, (entropyBuffer.length * 8) / 32);
|
|
278
|
+
}
|
|
279
|
+
export function bip39Generate(_words) {
|
|
280
|
+
throw new Error('bip39Generate: use @pezkuwi/util-crypto mnemonicGenerate instead');
|
|
281
|
+
}
|
|
282
|
+
export function bip39ToEntropy(phrase) {
|
|
283
|
+
const words = normalizeString(phrase).split(' ');
|
|
284
|
+
if (words.length % 3 !== 0) {
|
|
285
|
+
throw new Error('Invalid mnemonic');
|
|
286
|
+
}
|
|
287
|
+
// convert word indices to 11 bit binary strings
|
|
288
|
+
const bits = words
|
|
289
|
+
.map((word) => {
|
|
290
|
+
const index = BIP39_WORDLIST.indexOf(word);
|
|
291
|
+
if (index === -1) {
|
|
292
|
+
throw new Error('Invalid mnemonic');
|
|
293
|
+
}
|
|
294
|
+
return index.toString(2).padStart(11, '0');
|
|
295
|
+
})
|
|
296
|
+
.join('');
|
|
297
|
+
// split the binary string into ENT/CS
|
|
298
|
+
const dividerIndex = Math.floor(bits.length / 33) * 32;
|
|
299
|
+
const entropyBits = bits.slice(0, dividerIndex);
|
|
300
|
+
const checksumBits = bits.slice(dividerIndex);
|
|
301
|
+
// calculate the checksum and compare
|
|
302
|
+
const matched = entropyBits.match(/(.{1,8})/g);
|
|
303
|
+
const entropyBytes = matched?.map(binaryToByte);
|
|
304
|
+
if (!entropyBytes || (entropyBytes.length % 4 !== 0) || (entropyBytes.length < 16) || (entropyBytes.length > 32)) {
|
|
305
|
+
throw new Error('Invalid entropy');
|
|
306
|
+
}
|
|
307
|
+
const entropy = new Uint8Array(entropyBytes);
|
|
308
|
+
if (deriveChecksumBits(entropy) !== checksumBits) {
|
|
309
|
+
throw new Error('Invalid mnemonic checksum');
|
|
310
|
+
}
|
|
311
|
+
return entropy;
|
|
312
|
+
}
|
|
313
|
+
export function bip39ToMiniSecret(phrase, password) {
|
|
314
|
+
// Substrate uses entropy-based derivation (not BIP39's mnemonic string PBKDF2)
|
|
315
|
+
const entropy = bip39ToEntropy(phrase);
|
|
316
|
+
const salt = new TextEncoder().encode(`mnemonic${normalizeString(password)}`);
|
|
317
|
+
// PBKDF2 on the entropy, not the mnemonic string
|
|
318
|
+
return noblePbkdf2(nobleSha512, entropy, salt, { c: 2048, dkLen: 64 }).slice(0, 32);
|
|
319
|
+
}
|
|
320
|
+
export function bip39ToSeed(phrase, password) {
|
|
321
|
+
const salt = new TextEncoder().encode(`mnemonic${normalizeString(password)}`);
|
|
322
|
+
const input = new TextEncoder().encode(normalizeString(phrase));
|
|
323
|
+
return noblePbkdf2(nobleSha256, input, salt, { c: 2048, dkLen: 64 });
|
|
324
|
+
}
|
|
325
|
+
export function ed25519KeypairFromSeed(_seed) {
|
|
326
|
+
throw new Error('ed25519KeypairFromSeed not yet implemented');
|
|
327
|
+
}
|
|
328
|
+
export function ed25519Sign(_publicKey, _secretKey, _message) {
|
|
329
|
+
throw new Error('ed25519Sign not yet implemented');
|
|
330
|
+
}
|
|
331
|
+
export function ed25519Verify(_signature, _message, _publicKey) {
|
|
332
|
+
throw new Error('ed25519Verify not yet implemented');
|
|
333
|
+
}
|
|
334
|
+
export function sr25519Agree(_publicKey, _secretKey) {
|
|
335
|
+
throw new Error('sr25519Agree not yet implemented');
|
|
336
|
+
}
|
|
337
|
+
export function sr25519DeriveKeypairHard(_pair, _cc) {
|
|
338
|
+
throw new Error('sr25519DeriveKeypairHard not yet implemented');
|
|
339
|
+
}
|
|
340
|
+
export function sr25519DeriveKeypairSoft(_pair, _cc) {
|
|
341
|
+
throw new Error('sr25519DeriveKeypairSoft not yet implemented');
|
|
342
|
+
}
|
|
343
|
+
export function sr25519DerivePublicSoft(_publicKey, _cc) {
|
|
344
|
+
throw new Error('sr25519DerivePublicSoft not yet implemented');
|
|
345
|
+
}
|
|
346
|
+
export function vrfSign(_secretKey, _context, _message, _extra) {
|
|
347
|
+
throw new Error('vrfSign not yet implemented');
|
|
348
|
+
}
|
|
349
|
+
export function vrfVerify(_publicKey, _context, _message, _extra, _outAndProof) {
|
|
350
|
+
throw new Error('vrfVerify not yet implemented');
|
|
351
|
+
}
|
|
352
|
+
export function secp256k1FromSeed(_seed) {
|
|
353
|
+
throw new Error('secp256k1FromSeed not yet implemented');
|
|
354
|
+
}
|
|
355
|
+
export function secp256k1Compress(_publicKey) {
|
|
356
|
+
throw new Error('secp256k1Compress not yet implemented');
|
|
357
|
+
}
|
|
358
|
+
export function secp256k1Expand(_publicKey) {
|
|
359
|
+
throw new Error('secp256k1Expand not yet implemented');
|
|
360
|
+
}
|
|
361
|
+
export function secp256k1Recover(_msgHash, _signature, _recoveryId) {
|
|
362
|
+
throw new Error('secp256k1Recover not yet implemented');
|
|
363
|
+
}
|
|
364
|
+
export function secp256k1Sign(_msgHash, _secretKey) {
|
|
365
|
+
throw new Error('secp256k1Sign not yet implemented');
|
|
366
|
+
}
|
|
367
|
+
export function blake2b(data, key, size) {
|
|
368
|
+
// size is already in bytes (passed by util-crypto's blake2AsU8a)
|
|
369
|
+
if (key && key.length > 0) {
|
|
370
|
+
return nobleBlake2b(data, { dkLen: size, key });
|
|
371
|
+
}
|
|
372
|
+
return nobleBlake2b(data, { dkLen: size });
|
|
373
|
+
}
|
|
374
|
+
export function hmacSha256(key, data) {
|
|
375
|
+
return hmac(nobleSha256, key, data);
|
|
376
|
+
}
|
|
377
|
+
export function hmacSha512(key, data) {
|
|
378
|
+
return hmac(nobleSha512, key, data);
|
|
379
|
+
}
|
|
380
|
+
export function keccak256(data) {
|
|
381
|
+
return keccak_256(data);
|
|
382
|
+
}
|
|
383
|
+
export function keccak512(data) {
|
|
384
|
+
return keccak_512(data);
|
|
385
|
+
}
|
|
386
|
+
export function pbkdf2(data, salt, rounds) {
|
|
387
|
+
return noblePbkdf2(nobleSha512, data, salt, { c: rounds, dkLen: 64 });
|
|
388
|
+
}
|
|
389
|
+
export function scrypt(_password, _salt, _log2n, _r, _p) {
|
|
390
|
+
// scrypt is rarely used - defer to @noble/hashes/scrypt if needed
|
|
391
|
+
throw new Error('scrypt not yet implemented - use @pezkuwi/util-crypto scryptSync instead');
|
|
392
|
+
}
|
|
393
|
+
export function sha256(data) {
|
|
394
|
+
return nobleSha256(data);
|
|
395
|
+
}
|
|
396
|
+
export function sha512(data) {
|
|
397
|
+
return nobleSha512(data);
|
|
398
|
+
}
|
|
399
|
+
const P64_1 = BigInt('11400714785074694791');
|
|
400
|
+
const P64_2 = BigInt('14029467366897019727');
|
|
401
|
+
const P64_3 = BigInt('1609587929392839161');
|
|
402
|
+
const P64_4 = BigInt('9650029242287828579');
|
|
403
|
+
const P64_5 = BigInt('2870177450012600261');
|
|
404
|
+
const U64 = BigInt('0xffffffffffffffff');
|
|
405
|
+
const _0n = BigInt(0);
|
|
406
|
+
const _1n = BigInt(1);
|
|
407
|
+
const _7n = BigInt(7);
|
|
408
|
+
const _11n = BigInt(11);
|
|
409
|
+
const _12n = BigInt(12);
|
|
410
|
+
const _16n = BigInt(16);
|
|
411
|
+
const _18n = BigInt(18);
|
|
412
|
+
const _23n = BigInt(23);
|
|
413
|
+
const _27n = BigInt(27);
|
|
414
|
+
const _29n = BigInt(29);
|
|
415
|
+
const _31n = BigInt(31);
|
|
416
|
+
const _32n = BigInt(32);
|
|
417
|
+
const _33n = BigInt(33);
|
|
418
|
+
const _64n = BigInt(64);
|
|
419
|
+
const _256n = BigInt(256);
|
|
420
|
+
function rotl(a, b) {
|
|
421
|
+
const c = a & U64;
|
|
422
|
+
return ((c << b) | (c >> (_64n - b))) & U64;
|
|
423
|
+
}
|
|
424
|
+
function fromU8a(u8a, p, count) {
|
|
425
|
+
const bigints = new Array(count);
|
|
426
|
+
let offset = 0;
|
|
427
|
+
for (let i = 0; i < count; i++, offset += 2) {
|
|
428
|
+
bigints[i] = BigInt(u8a[p + offset] | (u8a[p + 1 + offset] << 8));
|
|
429
|
+
}
|
|
430
|
+
let result = _0n;
|
|
431
|
+
for (let i = count - 1; i >= 0; i--) {
|
|
432
|
+
result = (result << _16n) + bigints[i];
|
|
433
|
+
}
|
|
434
|
+
return result;
|
|
435
|
+
}
|
|
436
|
+
function xxhashInit(seed, input) {
|
|
437
|
+
const state = {
|
|
438
|
+
seed,
|
|
439
|
+
u8a: new Uint8Array(32),
|
|
440
|
+
u8asize: 0,
|
|
441
|
+
v1: seed + P64_1 + P64_2,
|
|
442
|
+
v2: seed + P64_2,
|
|
443
|
+
v3: seed,
|
|
444
|
+
v4: seed - P64_1
|
|
445
|
+
};
|
|
446
|
+
if (input.length < 32) {
|
|
447
|
+
state.u8a.set(input);
|
|
448
|
+
state.u8asize = input.length;
|
|
449
|
+
return state;
|
|
450
|
+
}
|
|
451
|
+
const limit = input.length - 32;
|
|
452
|
+
let p = 0;
|
|
453
|
+
if (limit >= 0) {
|
|
454
|
+
const adjustV = (v) => P64_1 * rotl(v + P64_2 * fromU8a(input, p, 4), _31n);
|
|
455
|
+
do {
|
|
456
|
+
state.v1 = adjustV(state.v1);
|
|
457
|
+
p += 8;
|
|
458
|
+
state.v2 = adjustV(state.v2);
|
|
459
|
+
p += 8;
|
|
460
|
+
state.v3 = adjustV(state.v3);
|
|
461
|
+
p += 8;
|
|
462
|
+
state.v4 = adjustV(state.v4);
|
|
463
|
+
p += 8;
|
|
464
|
+
} while (p <= limit);
|
|
465
|
+
}
|
|
466
|
+
if (p < input.length) {
|
|
467
|
+
state.u8a.set(input.subarray(p, input.length));
|
|
468
|
+
state.u8asize = input.length - p;
|
|
469
|
+
}
|
|
470
|
+
return state;
|
|
471
|
+
}
|
|
472
|
+
function xxhash64(input, initSeed) {
|
|
473
|
+
const { seed, u8a, u8asize, v1, v2, v3, v4 } = xxhashInit(BigInt(initSeed), input);
|
|
474
|
+
let p = 0;
|
|
475
|
+
let h64 = U64 & (BigInt(input.length) + (input.length >= 32
|
|
476
|
+
? (((((((((rotl(v1, _1n) + rotl(v2, _7n) + rotl(v3, _12n) + rotl(v4, _18n)) ^ (P64_1 * rotl(v1 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v2 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v3 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v4 * P64_2, _31n))) * P64_1 + P64_4)
|
|
477
|
+
: (seed + P64_5)));
|
|
478
|
+
while (p <= (u8asize - 8)) {
|
|
479
|
+
h64 = U64 & (P64_4 + P64_1 * rotl(h64 ^ (P64_1 * rotl(P64_2 * fromU8a(u8a, p, 4), _31n)), _27n));
|
|
480
|
+
p += 8;
|
|
481
|
+
}
|
|
482
|
+
if ((p + 4) <= u8asize) {
|
|
483
|
+
h64 = U64 & (P64_3 + P64_2 * rotl(h64 ^ (P64_1 * fromU8a(u8a, p, 2)), _23n));
|
|
484
|
+
p += 4;
|
|
485
|
+
}
|
|
486
|
+
while (p < u8asize) {
|
|
487
|
+
h64 = U64 & (P64_1 * rotl(h64 ^ (P64_5 * BigInt(u8a[p++])), _11n));
|
|
488
|
+
}
|
|
489
|
+
h64 = U64 & (P64_2 * (h64 ^ (h64 >> _33n)));
|
|
490
|
+
h64 = U64 & (P64_3 * (h64 ^ (h64 >> _29n)));
|
|
491
|
+
h64 = U64 & (h64 ^ (h64 >> _32n));
|
|
492
|
+
const result = new Uint8Array(8);
|
|
493
|
+
for (let i = 7; i >= 0; i--) {
|
|
494
|
+
result[i] = Number(h64 % _256n);
|
|
495
|
+
h64 = h64 / _256n;
|
|
496
|
+
}
|
|
497
|
+
return result;
|
|
498
|
+
}
|
|
499
|
+
export function twox(data, rounds) {
|
|
500
|
+
const result = new Uint8Array(rounds * 8);
|
|
501
|
+
for (let seed = 0; seed < rounds; seed++) {
|
|
502
|
+
result.set(xxhash64(data, seed).reverse(), seed * 8);
|
|
503
|
+
}
|
|
504
|
+
return result;
|
|
505
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const packageInfo = { name: '@pezkuwi/wasm-crypto', path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '7.5.
|
|
1
|
+
export const packageInfo = { name: '@pezkuwi/wasm-crypto', path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '7.5.15' };
|