eth-crypto-ts 0.0.2 → 0.0.5

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/dist/index.js CHANGED
@@ -1,195 +1,3943 @@
1
- import { publicKeyConvert, ecdsaSign } from 'secp256k1';
2
- import { solidityPackedKeccak256, keccak256, concat, randomBytes, Wallet } from 'ethers';
3
- import { encrypt, decrypt } from 'eccrypto';
4
- import { privateToPublic, toBuffer } from 'ethereumjs-util';
5
-
6
- function removeLeading0x(str) {
7
- if (str.startsWith('0x'))
8
- return str.substring(2);
9
- else
10
- return str;
1
+ const SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';
2
+ const MIN_ENTROPY_SIZE = 128;
3
+
4
+ /**
5
+ * Hex, bytes and number utilities.
6
+ * @module
7
+ */
8
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
9
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
10
+ // This is OK: `abstract` directory does not use noble-hashes.
11
+ // User may opt-in into using different hashing library. This way, noble-hashes
12
+ // won't be included into their bundle.
13
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
14
+ const _1n$5 = /* @__PURE__ */ BigInt(1);
15
+ function isBytes$2(a) {
16
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
17
+ }
18
+ function abytes$3(item) {
19
+ if (!isBytes$2(item))
20
+ throw new Error('Uint8Array expected');
21
+ }
22
+ function abool(title, value) {
23
+ if (typeof value !== 'boolean')
24
+ throw new Error(title + ' boolean expected, got ' + value);
25
+ }
26
+ // Used in weierstrass, der
27
+ function numberToHexUnpadded(num) {
28
+ const hex = num.toString(16);
29
+ return hex.length & 1 ? '0' + hex : hex;
30
+ }
31
+ function hexToNumber(hex) {
32
+ if (typeof hex !== 'string')
33
+ throw new Error('hex string expected, got ' + typeof hex);
34
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
35
+ }
36
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
37
+ const hasHexBuiltin$1 =
38
+ // @ts-ignore
39
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
40
+ // Array where index 0xf0 (240) is mapped to string 'f0'
41
+ const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
42
+ /**
43
+ * Convert byte array to hex string. Uses built-in function, when available.
44
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
45
+ */
46
+ function bytesToHex$1(bytes) {
47
+ abytes$3(bytes);
48
+ // @ts-ignore
49
+ if (hasHexBuiltin$1)
50
+ return bytes.toHex();
51
+ // pre-caching improves the speed 6x
52
+ let hex = '';
53
+ for (let i = 0; i < bytes.length; i++) {
54
+ hex += hexes$1[bytes[i]];
55
+ }
56
+ return hex;
57
+ }
58
+ // We use optimized technique to convert hex string to byte array
59
+ const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
60
+ function asciiToBase16$1(ch) {
61
+ if (ch >= asciis$1._0 && ch <= asciis$1._9)
62
+ return ch - asciis$1._0; // '2' => 50-48
63
+ if (ch >= asciis$1.A && ch <= asciis$1.F)
64
+ return ch - (asciis$1.A - 10); // 'B' => 66-(65-10)
65
+ if (ch >= asciis$1.a && ch <= asciis$1.f)
66
+ return ch - (asciis$1.a - 10); // 'b' => 98-(97-10)
67
+ return;
68
+ }
69
+ /**
70
+ * Convert hex string to byte array. Uses built-in function, when available.
71
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
72
+ */
73
+ function hexToBytes$2(hex) {
74
+ if (typeof hex !== 'string')
75
+ throw new Error('hex string expected, got ' + typeof hex);
76
+ // @ts-ignore
77
+ if (hasHexBuiltin$1)
78
+ return Uint8Array.fromHex(hex);
79
+ const hl = hex.length;
80
+ const al = hl / 2;
81
+ if (hl % 2)
82
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
83
+ const array = new Uint8Array(al);
84
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
85
+ const n1 = asciiToBase16$1(hex.charCodeAt(hi));
86
+ const n2 = asciiToBase16$1(hex.charCodeAt(hi + 1));
87
+ if (n1 === undefined || n2 === undefined) {
88
+ const char = hex[hi] + hex[hi + 1];
89
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
90
+ }
91
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
92
+ }
93
+ return array;
94
+ }
95
+ // BE: Big Endian, LE: Little Endian
96
+ function bytesToNumberBE(bytes) {
97
+ return hexToNumber(bytesToHex$1(bytes));
98
+ }
99
+ function bytesToNumberLE(bytes) {
100
+ abytes$3(bytes);
101
+ return hexToNumber(bytesToHex$1(Uint8Array.from(bytes).reverse()));
102
+ }
103
+ function numberToBytesBE(n, len) {
104
+ return hexToBytes$2(n.toString(16).padStart(len * 2, '0'));
105
+ }
106
+ function numberToBytesLE(n, len) {
107
+ return numberToBytesBE(n, len).reverse();
108
+ }
109
+ /**
110
+ * Takes hex string or Uint8Array, converts to Uint8Array.
111
+ * Validates output length.
112
+ * Will throw error for other types.
113
+ * @param title descriptive title for an error e.g. 'private key'
114
+ * @param hex hex string or Uint8Array
115
+ * @param expectedLength optional, will compare to result array's length
116
+ * @returns
117
+ */
118
+ function ensureBytes(title, hex, expectedLength) {
119
+ let res;
120
+ if (typeof hex === 'string') {
121
+ try {
122
+ res = hexToBytes$2(hex);
123
+ }
124
+ catch (e) {
125
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
126
+ }
127
+ }
128
+ else if (isBytes$2(hex)) {
129
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
130
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
131
+ res = Uint8Array.from(hex);
132
+ }
133
+ else {
134
+ throw new Error(title + ' must be hex string or Uint8Array');
135
+ }
136
+ const len = res.length;
137
+ if (typeof expectedLength === 'number' && len !== expectedLength)
138
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
139
+ return res;
140
+ }
141
+ /**
142
+ * Copies several Uint8Arrays into one.
143
+ */
144
+ function concatBytes$1(...arrays) {
145
+ let sum = 0;
146
+ for (let i = 0; i < arrays.length; i++) {
147
+ const a = arrays[i];
148
+ abytes$3(a);
149
+ sum += a.length;
150
+ }
151
+ const res = new Uint8Array(sum);
152
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
153
+ const a = arrays[i];
154
+ res.set(a, pad);
155
+ pad += a.length;
156
+ }
157
+ return res;
158
+ }
159
+ // Is positive bigint
160
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
161
+ function inRange(n, min, max) {
162
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
163
+ }
164
+ /**
165
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
166
+ * @example
167
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
168
+ */
169
+ function aInRange(title, n, min, max) {
170
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
171
+ // consider P=256n, min=0n, max=P
172
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
173
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
174
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
175
+ if (!inRange(n, min, max))
176
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
177
+ }
178
+ // Bit operations
179
+ /**
180
+ * Calculates amount of bits in a bigint.
181
+ * Same as `n.toString(2).length`
182
+ * TODO: merge with nLength in modular
183
+ */
184
+ function bitLen(n) {
185
+ let len;
186
+ for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
187
+ ;
188
+ return len;
189
+ }
190
+ /**
191
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
192
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
193
+ */
194
+ const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
195
+ // DRBG
196
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
197
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
198
+ /**
199
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
200
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
201
+ * @example
202
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
203
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
204
+ */
205
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
206
+ if (typeof hashLen !== 'number' || hashLen < 2)
207
+ throw new Error('hashLen must be a number');
208
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
209
+ throw new Error('qByteLen must be a number');
210
+ if (typeof hmacFn !== 'function')
211
+ throw new Error('hmacFn must be a function');
212
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
213
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
214
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
215
+ let i = 0; // Iterations counter, will throw when over 1000
216
+ const reset = () => {
217
+ v.fill(1);
218
+ k.fill(0);
219
+ i = 0;
220
+ };
221
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
222
+ const reseed = (seed = u8n(0)) => {
223
+ // HMAC-DRBG reseed() function. Steps D-G
224
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
225
+ v = h(); // v = hmac(k || v)
226
+ if (seed.length === 0)
227
+ return;
228
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
229
+ v = h(); // v = hmac(k || v)
230
+ };
231
+ const gen = () => {
232
+ // HMAC-DRBG generate() function
233
+ if (i++ >= 1000)
234
+ throw new Error('drbg: tried 1000 values');
235
+ let len = 0;
236
+ const out = [];
237
+ while (len < qByteLen) {
238
+ v = h();
239
+ const sl = v.slice();
240
+ out.push(sl);
241
+ len += v.length;
242
+ }
243
+ return concatBytes$1(...out);
244
+ };
245
+ const genUntil = (seed, pred) => {
246
+ reset();
247
+ reseed(seed); // Steps D-G
248
+ let res = undefined; // Step H: grind until k is in [1..n-1]
249
+ while (!(res = pred(gen())))
250
+ reseed();
251
+ reset();
252
+ return res;
253
+ };
254
+ return genUntil;
255
+ }
256
+ // Validating curves and fields
257
+ const validatorFns = {
258
+ bigint: (val) => typeof val === 'bigint',
259
+ function: (val) => typeof val === 'function',
260
+ boolean: (val) => typeof val === 'boolean',
261
+ string: (val) => typeof val === 'string',
262
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes$2(val),
263
+ isSafeInteger: (val) => Number.isSafeInteger(val),
264
+ array: (val) => Array.isArray(val),
265
+ field: (val, object) => object.Fp.isValid(val),
266
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
267
+ };
268
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
269
+ function validateObject(object, validators, optValidators = {}) {
270
+ const checkField = (fieldName, type, isOptional) => {
271
+ const checkVal = validatorFns[type];
272
+ if (typeof checkVal !== 'function')
273
+ throw new Error('invalid validator function');
274
+ const val = object[fieldName];
275
+ if (isOptional && val === undefined)
276
+ return;
277
+ if (!checkVal(val, object)) {
278
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
279
+ }
280
+ };
281
+ for (const [fieldName, type] of Object.entries(validators))
282
+ checkField(fieldName, type, false);
283
+ for (const [fieldName, type] of Object.entries(optValidators))
284
+ checkField(fieldName, type, true);
285
+ return object;
286
+ }
287
+ /**
288
+ * Memoizes (caches) computation result.
289
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
290
+ */
291
+ function memoized(fn) {
292
+ const map = new WeakMap();
293
+ return (arg, ...args) => {
294
+ const val = map.get(arg);
295
+ if (val !== undefined)
296
+ return val;
297
+ const computed = fn(arg, ...args);
298
+ map.set(arg, computed);
299
+ return computed;
300
+ };
301
+ }
302
+
303
+ const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
304
+
305
+ /**
306
+ * Utilities for hex, bytes, CSPRNG.
307
+ * @module
308
+ */
309
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
310
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
311
+ // node.js versions earlier than v19 don't declare it in global scope.
312
+ // For node.js, package.json#exports field mapping rewrites import
313
+ // from `crypto` to `cryptoNode`, which imports native module.
314
+ // Makes the utils un-importable in browsers without a bundler.
315
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
316
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
317
+ function isBytes$1(a) {
318
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
319
+ }
320
+ /** Asserts something is positive integer. */
321
+ function anumber(n) {
322
+ if (!Number.isSafeInteger(n) || n < 0)
323
+ throw new Error('positive integer expected, got ' + n);
324
+ }
325
+ /** Asserts something is Uint8Array. */
326
+ function abytes$2(b, ...lengths) {
327
+ if (!isBytes$1(b))
328
+ throw new Error('Uint8Array expected');
329
+ if (lengths.length > 0 && !lengths.includes(b.length))
330
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
331
+ }
332
+ /** Asserts something is hash */
333
+ function ahash(h) {
334
+ if (typeof h !== 'function' || typeof h.create !== 'function')
335
+ throw new Error('Hash should be wrapped by utils.createHasher');
336
+ anumber(h.outputLen);
337
+ anumber(h.blockLen);
338
+ }
339
+ /** Asserts a hash instance has not been destroyed / finished */
340
+ function aexists(instance, checkFinished = true) {
341
+ if (instance.destroyed)
342
+ throw new Error('Hash instance has been destroyed');
343
+ if (checkFinished && instance.finished)
344
+ throw new Error('Hash#digest() has already been called');
345
+ }
346
+ /** Asserts output is properly-sized byte array */
347
+ function aoutput(out, instance) {
348
+ abytes$2(out);
349
+ const min = instance.outputLen;
350
+ if (out.length < min) {
351
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
352
+ }
353
+ }
354
+ /** Cast u8 / u16 / u32 to u32. */
355
+ function u32$1(arr) {
356
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
357
+ }
358
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
359
+ function clean$1(...arrays) {
360
+ for (let i = 0; i < arrays.length; i++) {
361
+ arrays[i].fill(0);
362
+ }
363
+ }
364
+ /** Create DataView of an array for easy byte-level manipulation. */
365
+ function createView(arr) {
366
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
367
+ }
368
+ /** The rotate right (circular right shift) operation for uint32 */
369
+ function rotr(word, shift) {
370
+ return (word << (32 - shift)) | (word >>> shift);
371
+ }
372
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
373
+ const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
374
+ /** The byte swap operation for uint32 */
375
+ function byteSwap(word) {
376
+ return (((word << 24) & 0xff000000) |
377
+ ((word << 8) & 0xff0000) |
378
+ ((word >>> 8) & 0xff00) |
379
+ ((word >>> 24) & 0xff));
380
+ }
381
+ /** In place byte swap for Uint32Array */
382
+ function byteSwap32(arr) {
383
+ for (let i = 0; i < arr.length; i++) {
384
+ arr[i] = byteSwap(arr[i]);
385
+ }
386
+ return arr;
387
+ }
388
+ const swap32IfBE = isLE$1
389
+ ? (u) => u
390
+ : byteSwap32;
391
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
392
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
393
+ // @ts-ignore
394
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
395
+ // Array where index 0xf0 (240) is mapped to string 'f0'
396
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
397
+ /**
398
+ * Convert byte array to hex string. Uses built-in function, when available.
399
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
400
+ */
401
+ function bytesToHex(bytes) {
402
+ abytes$2(bytes);
403
+ // @ts-ignore
404
+ if (hasHexBuiltin)
405
+ return bytes.toHex();
406
+ // pre-caching improves the speed 6x
407
+ let hex = '';
408
+ for (let i = 0; i < bytes.length; i++) {
409
+ hex += hexes[bytes[i]];
410
+ }
411
+ return hex;
412
+ }
413
+ // We use optimized technique to convert hex string to byte array
414
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
415
+ function asciiToBase16(ch) {
416
+ if (ch >= asciis._0 && ch <= asciis._9)
417
+ return ch - asciis._0; // '2' => 50-48
418
+ if (ch >= asciis.A && ch <= asciis.F)
419
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
420
+ if (ch >= asciis.a && ch <= asciis.f)
421
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
422
+ return;
423
+ }
424
+ /**
425
+ * Convert hex string to byte array. Uses built-in function, when available.
426
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
427
+ */
428
+ function hexToBytes$1(hex) {
429
+ if (typeof hex !== 'string')
430
+ throw new Error('hex string expected, got ' + typeof hex);
431
+ // @ts-ignore
432
+ if (hasHexBuiltin)
433
+ return Uint8Array.fromHex(hex);
434
+ const hl = hex.length;
435
+ const al = hl / 2;
436
+ if (hl % 2)
437
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
438
+ const array = new Uint8Array(al);
439
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
440
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
441
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
442
+ if (n1 === undefined || n2 === undefined) {
443
+ const char = hex[hi] + hex[hi + 1];
444
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
445
+ }
446
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
447
+ }
448
+ return array;
449
+ }
450
+ /**
451
+ * Converts string to bytes using UTF8 encoding.
452
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
453
+ */
454
+ function utf8ToBytes$1(str) {
455
+ if (typeof str !== 'string')
456
+ throw new Error('string expected');
457
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
458
+ }
459
+ /**
460
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
461
+ * Warning: when Uint8Array is passed, it would NOT get copied.
462
+ * Keep in mind for future mutable operations.
463
+ */
464
+ function toBytes(data) {
465
+ if (typeof data === 'string')
466
+ data = utf8ToBytes$1(data);
467
+ abytes$2(data);
468
+ return data;
469
+ }
470
+ /** Copies several Uint8Arrays into one. */
471
+ function concatBytes(...arrays) {
472
+ let sum = 0;
473
+ for (let i = 0; i < arrays.length; i++) {
474
+ const a = arrays[i];
475
+ abytes$2(a);
476
+ sum += a.length;
477
+ }
478
+ const res = new Uint8Array(sum);
479
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
480
+ const a = arrays[i];
481
+ res.set(a, pad);
482
+ pad += a.length;
483
+ }
484
+ return res;
485
+ }
486
+ /** For runtime check if class implements interface */
487
+ class Hash {
488
+ }
489
+ /** Wraps hash function, creating an interface on top of it */
490
+ function createHasher(hashCons) {
491
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
492
+ const tmp = hashCons();
493
+ hashC.outputLen = tmp.outputLen;
494
+ hashC.blockLen = tmp.blockLen;
495
+ hashC.create = () => hashCons();
496
+ return hashC;
497
+ }
498
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
499
+ function randomBytes(bytesLength = 32) {
500
+ if (crypto && typeof crypto.getRandomValues === 'function') {
501
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
502
+ }
503
+ // Legacy Node.js compatibility
504
+ if (crypto && typeof crypto.randomBytes === 'function') {
505
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
506
+ }
507
+ throw new Error('crypto.getRandomValues must be defined');
508
+ }
509
+
510
+ /**
511
+ * Internal assertion helpers.
512
+ * @module
513
+ * @deprecated
514
+ */
515
+ /** @deprecated Use import from `noble/hashes/utils` module */
516
+ const abytes$1 = abytes$2;
517
+
518
+ // buf.toString('utf8') -> bytesToUtf8(buf)
519
+ function bytesToUtf8(data) {
520
+ if (!(data instanceof Uint8Array)) {
521
+ throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
522
+ }
523
+ return new TextDecoder().decode(data);
524
+ }
525
+ function hexToBytes(data) {
526
+ const sliced = data.startsWith("0x") ? data.substring(2) : data;
527
+ return hexToBytes$1(sliced);
528
+ }
529
+ // Internal utils
530
+ function wrapHash(hash) {
531
+ return (msg) => {
532
+ abytes$1(msg);
533
+ return hash(msg);
534
+ };
535
+ }
536
+
537
+ /**
538
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
539
+ * @todo re-check https://issues.chromium.org/issues/42212588
540
+ * @module
541
+ */
542
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
543
+ const _32n = /* @__PURE__ */ BigInt(32);
544
+ function fromBig(n, le = false) {
545
+ if (le)
546
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
547
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
548
+ }
549
+ function split(lst, le = false) {
550
+ const len = lst.length;
551
+ let Ah = new Uint32Array(len);
552
+ let Al = new Uint32Array(len);
553
+ for (let i = 0; i < len; i++) {
554
+ const { h, l } = fromBig(lst[i], le);
555
+ [Ah[i], Al[i]] = [h, l];
556
+ }
557
+ return [Ah, Al];
558
+ }
559
+ // for Shift in [0, 32)
560
+ const shrSH = (h, _l, s) => h >>> s;
561
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
562
+ // Right rotate for Shift in [1, 32)
563
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
564
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
565
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
566
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
567
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
568
+ // Left rotate for Shift in [1, 32)
569
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
570
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
571
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
572
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
573
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
574
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
575
+ // simple take carry out of low bit sum by shift, we need to use division.
576
+ function add(Ah, Al, Bh, Bl) {
577
+ const l = (Al >>> 0) + (Bl >>> 0);
578
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
579
+ }
580
+ // Addition with more than 2 elements
581
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
582
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
583
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
584
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
585
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
586
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
587
+
588
+ /**
589
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
590
+ * Different from older hashes, the internal state is bigger than output size.
591
+ *
592
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
593
+ * [Website](https://keccak.team/keccak.html),
594
+ * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
595
+ *
596
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
597
+ * @module
598
+ */
599
+ // No __PURE__ annotations in sha3 header:
600
+ // EVERYTHING is in fact used on every export.
601
+ // Various per round constants calculations
602
+ const _0n$3 = BigInt(0);
603
+ const _1n$4 = BigInt(1);
604
+ const _2n$2 = BigInt(2);
605
+ const _7n = BigInt(7);
606
+ const _256n = BigInt(256);
607
+ const _0x71n = BigInt(0x71);
608
+ const SHA3_PI = [];
609
+ const SHA3_ROTL = [];
610
+ const _SHA3_IOTA = [];
611
+ for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) {
612
+ // Pi
613
+ [x, y] = [y, (2 * x + 3 * y) % 5];
614
+ SHA3_PI.push(2 * (5 * y + x));
615
+ // Rotational
616
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
617
+ // Iota
618
+ let t = _0n$3;
619
+ for (let j = 0; j < 7; j++) {
620
+ R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n;
621
+ if (R & _2n$2)
622
+ t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4);
623
+ }
624
+ _SHA3_IOTA.push(t);
625
+ }
626
+ const IOTAS = split(_SHA3_IOTA, true);
627
+ const SHA3_IOTA_H = IOTAS[0];
628
+ const SHA3_IOTA_L = IOTAS[1];
629
+ // Left rotation (without 0, 32, 64)
630
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
631
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
632
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
633
+ function keccakP(s, rounds = 24) {
634
+ const B = new Uint32Array(5 * 2);
635
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
636
+ for (let round = 24 - rounds; round < 24; round++) {
637
+ // Theta θ
638
+ for (let x = 0; x < 10; x++)
639
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
640
+ for (let x = 0; x < 10; x += 2) {
641
+ const idx1 = (x + 8) % 10;
642
+ const idx0 = (x + 2) % 10;
643
+ const B0 = B[idx0];
644
+ const B1 = B[idx0 + 1];
645
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
646
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
647
+ for (let y = 0; y < 50; y += 10) {
648
+ s[x + y] ^= Th;
649
+ s[x + y + 1] ^= Tl;
650
+ }
651
+ }
652
+ // Rho (ρ) and Pi (π)
653
+ let curH = s[2];
654
+ let curL = s[3];
655
+ for (let t = 0; t < 24; t++) {
656
+ const shift = SHA3_ROTL[t];
657
+ const Th = rotlH(curH, curL, shift);
658
+ const Tl = rotlL(curH, curL, shift);
659
+ const PI = SHA3_PI[t];
660
+ curH = s[PI];
661
+ curL = s[PI + 1];
662
+ s[PI] = Th;
663
+ s[PI + 1] = Tl;
664
+ }
665
+ // Chi (χ)
666
+ for (let y = 0; y < 50; y += 10) {
667
+ for (let x = 0; x < 10; x++)
668
+ B[x] = s[y + x];
669
+ for (let x = 0; x < 10; x++)
670
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
671
+ }
672
+ // Iota (ι)
673
+ s[0] ^= SHA3_IOTA_H[round];
674
+ s[1] ^= SHA3_IOTA_L[round];
675
+ }
676
+ clean$1(B);
11
677
  }
12
- function addLeading0x(str) {
678
+ /** Keccak sponge function. */
679
+ class Keccak extends Hash {
680
+ // NOTE: we accept arguments in bytes instead of bits here.
681
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
682
+ super();
683
+ this.pos = 0;
684
+ this.posOut = 0;
685
+ this.finished = false;
686
+ this.destroyed = false;
687
+ this.enableXOF = false;
688
+ this.blockLen = blockLen;
689
+ this.suffix = suffix;
690
+ this.outputLen = outputLen;
691
+ this.enableXOF = enableXOF;
692
+ this.rounds = rounds;
693
+ // Can be passed from user as dkLen
694
+ anumber(outputLen);
695
+ // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
696
+ // 0 < blockLen < 200
697
+ if (!(0 < blockLen && blockLen < 200))
698
+ throw new Error('only keccak-f1600 function is supported');
699
+ this.state = new Uint8Array(200);
700
+ this.state32 = u32$1(this.state);
701
+ }
702
+ clone() {
703
+ return this._cloneInto();
704
+ }
705
+ keccak() {
706
+ swap32IfBE(this.state32);
707
+ keccakP(this.state32, this.rounds);
708
+ swap32IfBE(this.state32);
709
+ this.posOut = 0;
710
+ this.pos = 0;
711
+ }
712
+ update(data) {
713
+ aexists(this);
714
+ data = toBytes(data);
715
+ abytes$2(data);
716
+ const { blockLen, state } = this;
717
+ const len = data.length;
718
+ for (let pos = 0; pos < len;) {
719
+ const take = Math.min(blockLen - this.pos, len - pos);
720
+ for (let i = 0; i < take; i++)
721
+ state[this.pos++] ^= data[pos++];
722
+ if (this.pos === blockLen)
723
+ this.keccak();
724
+ }
725
+ return this;
726
+ }
727
+ finish() {
728
+ if (this.finished)
729
+ return;
730
+ this.finished = true;
731
+ const { state, suffix, pos, blockLen } = this;
732
+ // Do the padding
733
+ state[pos] ^= suffix;
734
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
735
+ this.keccak();
736
+ state[blockLen - 1] ^= 0x80;
737
+ this.keccak();
738
+ }
739
+ writeInto(out) {
740
+ aexists(this, false);
741
+ abytes$2(out);
742
+ this.finish();
743
+ const bufferOut = this.state;
744
+ const { blockLen } = this;
745
+ for (let pos = 0, len = out.length; pos < len;) {
746
+ if (this.posOut >= blockLen)
747
+ this.keccak();
748
+ const take = Math.min(blockLen - this.posOut, len - pos);
749
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
750
+ this.posOut += take;
751
+ pos += take;
752
+ }
753
+ return out;
754
+ }
755
+ xofInto(out) {
756
+ // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
757
+ if (!this.enableXOF)
758
+ throw new Error('XOF is not possible for this instance');
759
+ return this.writeInto(out);
760
+ }
761
+ xof(bytes) {
762
+ anumber(bytes);
763
+ return this.xofInto(new Uint8Array(bytes));
764
+ }
765
+ digestInto(out) {
766
+ aoutput(out, this);
767
+ if (this.finished)
768
+ throw new Error('digest() was already called');
769
+ this.writeInto(out);
770
+ this.destroy();
771
+ return out;
772
+ }
773
+ digest() {
774
+ return this.digestInto(new Uint8Array(this.outputLen));
775
+ }
776
+ destroy() {
777
+ this.destroyed = true;
778
+ clean$1(this.state);
779
+ }
780
+ _cloneInto(to) {
781
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
782
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
783
+ to.state32.set(this.state32);
784
+ to.pos = this.pos;
785
+ to.posOut = this.posOut;
786
+ to.finished = this.finished;
787
+ to.rounds = rounds;
788
+ // Suffix can change in cSHAKE
789
+ to.suffix = suffix;
790
+ to.outputLen = outputLen;
791
+ to.enableXOF = enableXOF;
792
+ to.destroyed = this.destroyed;
793
+ return to;
794
+ }
795
+ }
796
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
797
+ /** keccak-256 hash function. Different from SHA3-256. */
798
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
799
+
800
+ const keccak256$1 = (() => {
801
+ const k = wrapHash(keccak_256);
802
+ k.create = keccak_256.create;
803
+ return k;
804
+ })();
805
+
806
+ /**
807
+ * Returns a `Boolean` on whether or not the a `String` starts with '0x'
808
+ * @param str the string input value
809
+ * @return a boolean if it is or is not hex prefixed
810
+ * @throws if the str input is not a string
811
+ */
812
+ const isHexPrefixed = (str) => {
813
+ if (typeof str !== 'string') {
814
+ throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
815
+ }
816
+ return str[0] === '0' && str[1] === 'x';
817
+ };
818
+ /**
819
+ * Removes '0x' from a given `String` if present
820
+ * @param str the string value
821
+ * @returns the string without 0x prefix
822
+ */
823
+ const stripHexPrefix = (str) => {
824
+ if (typeof str !== 'string')
825
+ throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
826
+ return isHexPrefixed(str) ? str.slice(2) : str;
827
+ };
828
+ /**
829
+ * Is the string a hex string.
830
+ *
831
+ * @param value
832
+ * @param length
833
+ * @returns output the string is a hex string
834
+ */
835
+ const isHexString = (value, length) => {
836
+ if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
837
+ return false;
838
+ return true;
839
+ };
840
+ /**
841
+ * Adds '0x' to a given `String` if not present
842
+ * @param str the string input value
843
+ * @return the string with a 0x prefix
844
+ */
845
+ const addLeading0x = (str) => {
13
846
  if (!str.startsWith('0x'))
14
847
  return '0x' + str;
15
848
  else
16
849
  return str;
850
+ };
851
+ const decompress = (startsWith02Or03) => {
852
+ const testByteArray = hexToBytes(startsWith02Or03);
853
+ let startsWith04 = startsWith02Or03;
854
+ if (testByteArray.length === 64) {
855
+ startsWith04 = '04' + startsWith02Or03;
856
+ }
857
+ return startsWith04.substring(2);
858
+ };
859
+ /** Helper function to concat UInt8Arrays mimicking the behaviour of the
860
+ * Buffer.concat function in Node.js
861
+ */
862
+ const concatUint8Arrays = (uint8arrays) => {
863
+ const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
864
+ const result = new Uint8Array(totalLength);
865
+ let offset = 0;
866
+ uint8arrays.forEach((uint8array) => {
867
+ result.set(uint8array, offset);
868
+ offset += uint8array.byteLength;
869
+ });
870
+ return result;
871
+ };
872
+ /**
873
+ * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
874
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
875
+ */
876
+ const utf8ToBytes = (str) => {
877
+ if (typeof str !== 'string')
878
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
879
+ const bytes = [];
880
+ for (let i = 0; i < str.length; i++) {
881
+ const codePoint = str.codePointAt(i);
882
+ if (!codePoint) {
883
+ throw new Error('Invalid code point');
884
+ }
885
+ if (codePoint < 0x80) {
886
+ bytes.push(codePoint);
887
+ }
888
+ else if (codePoint < 0x800) {
889
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
890
+ }
891
+ else if (codePoint < 0x10000) {
892
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
893
+ }
894
+ else {
895
+ i++; // skip one iteration since we have a surrogate pair
896
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
897
+ }
898
+ }
899
+ return new Uint8Array(bytes);
900
+ };
901
+
902
+ const solidityPackedKeccak256 = (value) => {
903
+ const bytes = utf8ToBytes(value);
904
+ const hex = addLeading0x(bytesToHex(bytes));
905
+ const hash = keccak256$1(hexToBytes(hex));
906
+ return addLeading0x(bytesToHex(hash));
907
+ };
908
+ const keccak256 = (params) => {
909
+ return solidityPackedKeccak256(params);
910
+ };
911
+
912
+ /**
913
+ * Internal Merkle-Damgard hash utils.
914
+ * @module
915
+ */
916
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
917
+ function setBigUint64(view, byteOffset, value, isLE) {
918
+ if (typeof view.setBigUint64 === 'function')
919
+ return view.setBigUint64(byteOffset, value, isLE);
920
+ const _32n = BigInt(32);
921
+ const _u32_max = BigInt(0xffffffff);
922
+ const wh = Number((value >> _32n) & _u32_max);
923
+ const wl = Number(value & _u32_max);
924
+ const h = isLE ? 4 : 0;
925
+ const l = isLE ? 0 : 4;
926
+ view.setUint32(byteOffset + h, wh, isLE);
927
+ view.setUint32(byteOffset + l, wl, isLE);
928
+ }
929
+ /** Choice: a ? b : c */
930
+ function Chi(a, b, c) {
931
+ return (a & b) ^ (~a & c);
932
+ }
933
+ /** Majority function, true if any two inputs is true. */
934
+ function Maj(a, b, c) {
935
+ return (a & b) ^ (a & c) ^ (b & c);
936
+ }
937
+ /**
938
+ * Merkle-Damgard hash construction base class.
939
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
940
+ */
941
+ class HashMD extends Hash {
942
+ constructor(blockLen, outputLen, padOffset, isLE) {
943
+ super();
944
+ this.finished = false;
945
+ this.length = 0;
946
+ this.pos = 0;
947
+ this.destroyed = false;
948
+ this.blockLen = blockLen;
949
+ this.outputLen = outputLen;
950
+ this.padOffset = padOffset;
951
+ this.isLE = isLE;
952
+ this.buffer = new Uint8Array(blockLen);
953
+ this.view = createView(this.buffer);
954
+ }
955
+ update(data) {
956
+ aexists(this);
957
+ data = toBytes(data);
958
+ abytes$2(data);
959
+ const { view, buffer, blockLen } = this;
960
+ const len = data.length;
961
+ for (let pos = 0; pos < len;) {
962
+ const take = Math.min(blockLen - this.pos, len - pos);
963
+ // Fast path: we have at least one block in input, cast it to view and process
964
+ if (take === blockLen) {
965
+ const dataView = createView(data);
966
+ for (; blockLen <= len - pos; pos += blockLen)
967
+ this.process(dataView, pos);
968
+ continue;
969
+ }
970
+ buffer.set(data.subarray(pos, pos + take), this.pos);
971
+ this.pos += take;
972
+ pos += take;
973
+ if (this.pos === blockLen) {
974
+ this.process(view, 0);
975
+ this.pos = 0;
976
+ }
977
+ }
978
+ this.length += data.length;
979
+ this.roundClean();
980
+ return this;
981
+ }
982
+ digestInto(out) {
983
+ aexists(this);
984
+ aoutput(out, this);
985
+ this.finished = true;
986
+ // Padding
987
+ // We can avoid allocation of buffer for padding completely if it
988
+ // was previously not allocated here. But it won't change performance.
989
+ const { buffer, view, blockLen, isLE } = this;
990
+ let { pos } = this;
991
+ // append the bit '1' to the message
992
+ buffer[pos++] = 0b10000000;
993
+ clean$1(this.buffer.subarray(pos));
994
+ // we have less than padOffset left in buffer, so we cannot put length in
995
+ // current block, need process it and pad again
996
+ if (this.padOffset > blockLen - pos) {
997
+ this.process(view, 0);
998
+ pos = 0;
999
+ }
1000
+ // Pad until full block byte with zeros
1001
+ for (let i = pos; i < blockLen; i++)
1002
+ buffer[i] = 0;
1003
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
1004
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
1005
+ // So we just write lowest 64 bits of that value.
1006
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
1007
+ this.process(view, 0);
1008
+ const oview = createView(out);
1009
+ const len = this.outputLen;
1010
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
1011
+ if (len % 4)
1012
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
1013
+ const outLen = len / 4;
1014
+ const state = this.get();
1015
+ if (outLen > state.length)
1016
+ throw new Error('_sha2: outputLen bigger than state');
1017
+ for (let i = 0; i < outLen; i++)
1018
+ oview.setUint32(4 * i, state[i], isLE);
1019
+ }
1020
+ digest() {
1021
+ const { buffer, outputLen } = this;
1022
+ this.digestInto(buffer);
1023
+ const res = buffer.slice(0, outputLen);
1024
+ this.destroy();
1025
+ return res;
1026
+ }
1027
+ _cloneInto(to) {
1028
+ to || (to = new this.constructor());
1029
+ to.set(...this.get());
1030
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1031
+ to.destroyed = destroyed;
1032
+ to.finished = finished;
1033
+ to.length = length;
1034
+ to.pos = pos;
1035
+ if (length % blockLen)
1036
+ to.buffer.set(buffer);
1037
+ return to;
1038
+ }
1039
+ clone() {
1040
+ return this._cloneInto();
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
1045
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
1046
+ */
1047
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
1048
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1049
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
1050
+ ]);
1051
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
1052
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1053
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
1054
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
1055
+ ]);
1056
+
1057
+ /**
1058
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1059
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1060
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
1061
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1062
+ * @module
1063
+ */
1064
+ /**
1065
+ * Round constants:
1066
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
1067
+ */
1068
+ // prettier-ignore
1069
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1070
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1071
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1072
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1073
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1074
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1075
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1076
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1077
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1078
+ ]);
1079
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1080
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1081
+ class SHA256 extends HashMD {
1082
+ constructor(outputLen = 32) {
1083
+ super(64, outputLen, 8, false);
1084
+ // We cannot use array here since array allows indexing by variable
1085
+ // which means optimizer/compiler cannot use registers.
1086
+ this.A = SHA256_IV[0] | 0;
1087
+ this.B = SHA256_IV[1] | 0;
1088
+ this.C = SHA256_IV[2] | 0;
1089
+ this.D = SHA256_IV[3] | 0;
1090
+ this.E = SHA256_IV[4] | 0;
1091
+ this.F = SHA256_IV[5] | 0;
1092
+ this.G = SHA256_IV[6] | 0;
1093
+ this.H = SHA256_IV[7] | 0;
1094
+ }
1095
+ get() {
1096
+ const { A, B, C, D, E, F, G, H } = this;
1097
+ return [A, B, C, D, E, F, G, H];
1098
+ }
1099
+ // prettier-ignore
1100
+ set(A, B, C, D, E, F, G, H) {
1101
+ this.A = A | 0;
1102
+ this.B = B | 0;
1103
+ this.C = C | 0;
1104
+ this.D = D | 0;
1105
+ this.E = E | 0;
1106
+ this.F = F | 0;
1107
+ this.G = G | 0;
1108
+ this.H = H | 0;
1109
+ }
1110
+ process(view, offset) {
1111
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
1112
+ for (let i = 0; i < 16; i++, offset += 4)
1113
+ SHA256_W[i] = view.getUint32(offset, false);
1114
+ for (let i = 16; i < 64; i++) {
1115
+ const W15 = SHA256_W[i - 15];
1116
+ const W2 = SHA256_W[i - 2];
1117
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
1118
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
1119
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
1120
+ }
1121
+ // Compression function main loop, 64 rounds
1122
+ let { A, B, C, D, E, F, G, H } = this;
1123
+ for (let i = 0; i < 64; i++) {
1124
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1125
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1126
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1127
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
1128
+ H = G;
1129
+ G = F;
1130
+ F = E;
1131
+ E = (D + T1) | 0;
1132
+ D = C;
1133
+ C = B;
1134
+ B = A;
1135
+ A = (T1 + T2) | 0;
1136
+ }
1137
+ // Add the compressed chunk to the current hash value
1138
+ A = (A + this.A) | 0;
1139
+ B = (B + this.B) | 0;
1140
+ C = (C + this.C) | 0;
1141
+ D = (D + this.D) | 0;
1142
+ E = (E + this.E) | 0;
1143
+ F = (F + this.F) | 0;
1144
+ G = (G + this.G) | 0;
1145
+ H = (H + this.H) | 0;
1146
+ this.set(A, B, C, D, E, F, G, H);
1147
+ }
1148
+ roundClean() {
1149
+ clean$1(SHA256_W);
1150
+ }
1151
+ destroy() {
1152
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1153
+ clean$1(this.buffer);
1154
+ }
1155
+ }
1156
+ // SHA2-512 is slower than sha256 in js because u64 operations are slow.
1157
+ // Round contants
1158
+ // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
1159
+ // prettier-ignore
1160
+ const K512 = /* @__PURE__ */ (() => split([
1161
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
1162
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
1163
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
1164
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
1165
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
1166
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
1167
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
1168
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
1169
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
1170
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
1171
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
1172
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
1173
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
1174
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
1175
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
1176
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
1177
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
1178
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
1179
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
1180
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
1181
+ ].map(n => BigInt(n))))();
1182
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1183
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1184
+ // Reusable temporary buffers
1185
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1186
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1187
+ class SHA512 extends HashMD {
1188
+ constructor(outputLen = 64) {
1189
+ super(128, outputLen, 16, false);
1190
+ // We cannot use array here since array allows indexing by variable
1191
+ // which means optimizer/compiler cannot use registers.
1192
+ // h -- high 32 bits, l -- low 32 bits
1193
+ this.Ah = SHA512_IV[0] | 0;
1194
+ this.Al = SHA512_IV[1] | 0;
1195
+ this.Bh = SHA512_IV[2] | 0;
1196
+ this.Bl = SHA512_IV[3] | 0;
1197
+ this.Ch = SHA512_IV[4] | 0;
1198
+ this.Cl = SHA512_IV[5] | 0;
1199
+ this.Dh = SHA512_IV[6] | 0;
1200
+ this.Dl = SHA512_IV[7] | 0;
1201
+ this.Eh = SHA512_IV[8] | 0;
1202
+ this.El = SHA512_IV[9] | 0;
1203
+ this.Fh = SHA512_IV[10] | 0;
1204
+ this.Fl = SHA512_IV[11] | 0;
1205
+ this.Gh = SHA512_IV[12] | 0;
1206
+ this.Gl = SHA512_IV[13] | 0;
1207
+ this.Hh = SHA512_IV[14] | 0;
1208
+ this.Hl = SHA512_IV[15] | 0;
1209
+ }
1210
+ // prettier-ignore
1211
+ get() {
1212
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1213
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1214
+ }
1215
+ // prettier-ignore
1216
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1217
+ this.Ah = Ah | 0;
1218
+ this.Al = Al | 0;
1219
+ this.Bh = Bh | 0;
1220
+ this.Bl = Bl | 0;
1221
+ this.Ch = Ch | 0;
1222
+ this.Cl = Cl | 0;
1223
+ this.Dh = Dh | 0;
1224
+ this.Dl = Dl | 0;
1225
+ this.Eh = Eh | 0;
1226
+ this.El = El | 0;
1227
+ this.Fh = Fh | 0;
1228
+ this.Fl = Fl | 0;
1229
+ this.Gh = Gh | 0;
1230
+ this.Gl = Gl | 0;
1231
+ this.Hh = Hh | 0;
1232
+ this.Hl = Hl | 0;
1233
+ }
1234
+ process(view, offset) {
1235
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
1236
+ for (let i = 0; i < 16; i++, offset += 4) {
1237
+ SHA512_W_H[i] = view.getUint32(offset);
1238
+ SHA512_W_L[i] = view.getUint32((offset += 4));
1239
+ }
1240
+ for (let i = 16; i < 80; i++) {
1241
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
1242
+ const W15h = SHA512_W_H[i - 15] | 0;
1243
+ const W15l = SHA512_W_L[i - 15] | 0;
1244
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1245
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1246
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
1247
+ const W2h = SHA512_W_H[i - 2] | 0;
1248
+ const W2l = SHA512_W_L[i - 2] | 0;
1249
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1250
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1251
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
1252
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1253
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1254
+ SHA512_W_H[i] = SUMh | 0;
1255
+ SHA512_W_L[i] = SUMl | 0;
1256
+ }
1257
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1258
+ // Compression function main loop, 80 rounds
1259
+ for (let i = 0; i < 80; i++) {
1260
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
1261
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1262
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1263
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1264
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
1265
+ const CHIl = (El & Fl) ^ (~El & Gl);
1266
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
1267
+ // prettier-ignore
1268
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1269
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1270
+ const T1l = T1ll | 0;
1271
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
1272
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1273
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1274
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
1275
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
1276
+ Hh = Gh | 0;
1277
+ Hl = Gl | 0;
1278
+ Gh = Fh | 0;
1279
+ Gl = Fl | 0;
1280
+ Fh = Eh | 0;
1281
+ Fl = El | 0;
1282
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1283
+ Dh = Ch | 0;
1284
+ Dl = Cl | 0;
1285
+ Ch = Bh | 0;
1286
+ Cl = Bl | 0;
1287
+ Bh = Ah | 0;
1288
+ Bl = Al | 0;
1289
+ const All = add3L(T1l, sigma0l, MAJl);
1290
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1291
+ Al = All | 0;
1292
+ }
1293
+ // Add the compressed chunk to the current hash value
1294
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1295
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1296
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1297
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1298
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1299
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1300
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1301
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1302
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1303
+ }
1304
+ roundClean() {
1305
+ clean$1(SHA512_W_H, SHA512_W_L);
1306
+ }
1307
+ destroy() {
1308
+ clean$1(this.buffer);
1309
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1310
+ }
1311
+ }
1312
+ /**
1313
+ * SHA2-256 hash function from RFC 4634.
1314
+ *
1315
+ * It is the fastest JS hash, even faster than Blake3.
1316
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1317
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1318
+ */
1319
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
1320
+ /** SHA2-512 hash function from RFC 4634. */
1321
+ const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
1322
+
1323
+ /**
1324
+ * HMAC: RFC2104 message authentication code.
1325
+ * @module
1326
+ */
1327
+ class HMAC extends Hash {
1328
+ constructor(hash, _key) {
1329
+ super();
1330
+ this.finished = false;
1331
+ this.destroyed = false;
1332
+ ahash(hash);
1333
+ const key = toBytes(_key);
1334
+ this.iHash = hash.create();
1335
+ if (typeof this.iHash.update !== 'function')
1336
+ throw new Error('Expected instance of class which extends utils.Hash');
1337
+ this.blockLen = this.iHash.blockLen;
1338
+ this.outputLen = this.iHash.outputLen;
1339
+ const blockLen = this.blockLen;
1340
+ const pad = new Uint8Array(blockLen);
1341
+ // blockLen can be bigger than outputLen
1342
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1343
+ for (let i = 0; i < pad.length; i++)
1344
+ pad[i] ^= 0x36;
1345
+ this.iHash.update(pad);
1346
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
1347
+ this.oHash = hash.create();
1348
+ // Undo internal XOR && apply outer XOR
1349
+ for (let i = 0; i < pad.length; i++)
1350
+ pad[i] ^= 0x36 ^ 0x5c;
1351
+ this.oHash.update(pad);
1352
+ clean$1(pad);
1353
+ }
1354
+ update(buf) {
1355
+ aexists(this);
1356
+ this.iHash.update(buf);
1357
+ return this;
1358
+ }
1359
+ digestInto(out) {
1360
+ aexists(this);
1361
+ abytes$2(out, this.outputLen);
1362
+ this.finished = true;
1363
+ this.iHash.digestInto(out);
1364
+ this.oHash.update(out);
1365
+ this.oHash.digestInto(out);
1366
+ this.destroy();
1367
+ }
1368
+ digest() {
1369
+ const out = new Uint8Array(this.oHash.outputLen);
1370
+ this.digestInto(out);
1371
+ return out;
1372
+ }
1373
+ _cloneInto(to) {
1374
+ // Create new instance without calling constructor since key already in state and we don't know it.
1375
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1376
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1377
+ to = to;
1378
+ to.finished = finished;
1379
+ to.destroyed = destroyed;
1380
+ to.blockLen = blockLen;
1381
+ to.outputLen = outputLen;
1382
+ to.oHash = oHash._cloneInto(to.oHash);
1383
+ to.iHash = iHash._cloneInto(to.iHash);
1384
+ return to;
1385
+ }
1386
+ clone() {
1387
+ return this._cloneInto();
1388
+ }
1389
+ destroy() {
1390
+ this.destroyed = true;
1391
+ this.oHash.destroy();
1392
+ this.iHash.destroy();
1393
+ }
1394
+ }
1395
+ /**
1396
+ * HMAC: RFC2104 message authentication code.
1397
+ * @param hash - function that would be used e.g. sha256
1398
+ * @param key - message key
1399
+ * @param message - message data
1400
+ * @example
1401
+ * import { hmac } from '@noble/hashes/hmac';
1402
+ * import { sha256 } from '@noble/hashes/sha2';
1403
+ * const mac1 = hmac(sha256, 'key', 'message');
1404
+ */
1405
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1406
+ hmac.create = (hash, key) => new HMAC(hash, key);
1407
+
1408
+ /**
1409
+ * Utils for modular division and finite fields.
1410
+ * A finite field over 11 is integer number operations `mod 11`.
1411
+ * There is no division: it is replaced by modular multiplicative inverse.
1412
+ * @module
1413
+ */
1414
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1415
+ // prettier-ignore
1416
+ const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
1417
+ // prettier-ignore
1418
+ const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
1419
+ // Calculates a modulo b
1420
+ function mod(a, b) {
1421
+ const result = a % b;
1422
+ return result >= _0n$2 ? result : b + result;
17
1423
  }
18
- function uint8ArrayToHex(arr) {
19
- return Buffer.from(arr).toString('hex');
20
- }
21
- function hexToUnit8Array(str) {
22
- return new Uint8Array(Buffer.from(str, 'hex'));
23
- }
24
-
25
- function compress(startsWith04) {
26
- // add trailing 04 if not done before
27
- const testBuffer = Buffer.from(startsWith04, 'hex');
28
- if (testBuffer.length === 64)
29
- startsWith04 = '04' + startsWith04;
30
- return uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith04), true));
31
- }
32
-
33
- function decompress(startsWith02Or03) {
34
- // if already decompressed an not has trailing 04
35
- const testBuffer = Buffer.from(startsWith02Or03, 'hex');
36
- if (testBuffer.length === 64)
37
- startsWith02Or03 = '04' + startsWith02Or03;
38
- let decompressed = uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith02Or03), false));
39
- // remove trailing 04
40
- decompressed = decompressed.substring(2);
41
- return decompressed;
42
- }
43
-
44
- class Cipher {
45
- constructor() { }
46
- stringify(encrypted) {
47
- if (typeof encrypted === 'string')
48
- return encrypted;
49
- // use compressed key because it's smaller
50
- const compressedKey = compress(encrypted.ephemPublicKey);
51
- const ret = Buffer.concat([
52
- Buffer.from(encrypted.iv, 'hex'), // 16bit
53
- Buffer.from(compressedKey, 'hex'), // 33bit
54
- Buffer.from(encrypted.mac, 'hex'), // 32bit
55
- Buffer.from(encrypted.ciphertext, 'hex'), // var bit
56
- ]);
57
- return ret.toString('hex');
58
- }
59
- parse(str) {
60
- if (typeof str !== 'string')
61
- return str;
62
- const buf = Buffer.from(str, 'hex');
63
- const ret = {
64
- iv: buf.toString('hex', 0, 16),
65
- ephemPublicKey: buf.toString('hex', 16, 49),
66
- mac: buf.toString('hex', 49, 81),
67
- ciphertext: buf.toString('hex', 81, buf.length),
1424
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
1425
+ function pow2(x, power, modulo) {
1426
+ let res = x;
1427
+ while (power-- > _0n$2) {
1428
+ res *= res;
1429
+ res %= modulo;
1430
+ }
1431
+ return res;
1432
+ }
1433
+ /**
1434
+ * Inverses number over modulo.
1435
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
1436
+ */
1437
+ function invert(number, modulo) {
1438
+ if (number === _0n$2)
1439
+ throw new Error('invert: expected non-zero number');
1440
+ if (modulo <= _0n$2)
1441
+ throw new Error('invert: expected positive modulus, got ' + modulo);
1442
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
1443
+ let a = mod(number, modulo);
1444
+ let b = modulo;
1445
+ // prettier-ignore
1446
+ let x = _0n$2, u = _1n$3;
1447
+ while (a !== _0n$2) {
1448
+ // JIT applies optimization if those two lines follow each other
1449
+ const q = b / a;
1450
+ const r = b % a;
1451
+ const m = x - u * q;
1452
+ // prettier-ignore
1453
+ b = a, a = r, x = u, u = m;
1454
+ }
1455
+ const gcd = b;
1456
+ if (gcd !== _1n$3)
1457
+ throw new Error('invert: does not exist');
1458
+ return mod(x, modulo);
1459
+ }
1460
+ /**
1461
+ * Tonelli-Shanks square root search algorithm.
1462
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
1463
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
1464
+ * @param P field order
1465
+ * @returns function that takes field Fp (created from P) and number n
1466
+ */
1467
+ function tonelliShanks(P) {
1468
+ // Do expensive precomputation step
1469
+ // Step 1: By factoring out powers of 2 from p - 1,
1470
+ // find q and s such that p-1 == q*(2^s) with q odd
1471
+ let Q = P - _1n$3;
1472
+ let S = 0;
1473
+ while (Q % _2n$1 === _0n$2) {
1474
+ Q /= _2n$1;
1475
+ S++;
1476
+ }
1477
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
1478
+ let Z = _2n$1;
1479
+ const _Fp = Field(P);
1480
+ while (Z < P && FpIsSquare(_Fp, Z)) {
1481
+ if (Z++ > 1000)
1482
+ throw new Error('Cannot find square root: probably non-prime P');
1483
+ }
1484
+ // Fast-path
1485
+ if (S === 1) {
1486
+ const p1div4 = (P + _1n$3) / _4n;
1487
+ return function tonelliFast(Fp, n) {
1488
+ const root = Fp.pow(n, p1div4);
1489
+ if (!Fp.eql(Fp.sqr(root), n))
1490
+ throw new Error('Cannot find square root');
1491
+ return root;
68
1492
  };
69
- // decompress publicKey
70
- ret.ephemPublicKey = '04' + decompress(ret.ephemPublicKey);
71
- return ret;
72
1493
  }
1494
+ // Slow-path
1495
+ const Q1div2 = (Q + _1n$3) / _2n$1;
1496
+ return function tonelliSlow(Fp, n) {
1497
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
1498
+ if (!FpIsSquare(Fp, n))
1499
+ throw new Error('Cannot find square root');
1500
+ let r = S;
1501
+ // TODO: test on Fp2 and others
1502
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
1503
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
1504
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
1505
+ while (!Fp.eql(b, Fp.ONE)) {
1506
+ // (4. If t = 0, return r = 0)
1507
+ // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
1508
+ if (Fp.eql(b, Fp.ZERO))
1509
+ return Fp.ZERO;
1510
+ // Find m such b^(2^m)==1
1511
+ let m = 1;
1512
+ for (let t2 = Fp.sqr(b); m < r; m++) {
1513
+ if (Fp.eql(t2, Fp.ONE))
1514
+ break;
1515
+ t2 = Fp.sqr(t2); // t2 *= t2
1516
+ }
1517
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
1518
+ // otherwise there will be overflow.
1519
+ const ge = Fp.pow(g, _1n$3 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
1520
+ g = Fp.sqr(ge); // g = ge * ge
1521
+ x = Fp.mul(x, ge); // x *= ge
1522
+ b = Fp.mul(b, g); // b *= g
1523
+ r = m;
1524
+ }
1525
+ return x;
1526
+ };
1527
+ }
1528
+ /**
1529
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
1530
+ *
1531
+ * 1. P ≡ 3 (mod 4)
1532
+ * 2. P ≡ 5 (mod 8)
1533
+ * 3. P ≡ 9 (mod 16)
1534
+ * 4. Tonelli-Shanks algorithm
1535
+ *
1536
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
1537
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1538
+ */
1539
+ function FpSqrt(P) {
1540
+ // P ≡ 3 (mod 4)
1541
+ // √n = n^((P+1)/4)
1542
+ if (P % _4n === _3n$1) {
1543
+ // Not all roots possible!
1544
+ // const ORDER =
1545
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
1546
+ // const NUM = 72057594037927816n;
1547
+ return function sqrt3mod4(Fp, n) {
1548
+ const p1div4 = (P + _1n$3) / _4n;
1549
+ const root = Fp.pow(n, p1div4);
1550
+ // Throw if root**2 != n
1551
+ if (!Fp.eql(Fp.sqr(root), n))
1552
+ throw new Error('Cannot find square root');
1553
+ return root;
1554
+ };
1555
+ }
1556
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
1557
+ if (P % _8n === _5n) {
1558
+ return function sqrt5mod8(Fp, n) {
1559
+ const n2 = Fp.mul(n, _2n$1);
1560
+ const c1 = (P - _5n) / _8n;
1561
+ const v = Fp.pow(n2, c1);
1562
+ const nv = Fp.mul(n, v);
1563
+ const i = Fp.mul(Fp.mul(nv, _2n$1), v);
1564
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
1565
+ if (!Fp.eql(Fp.sqr(root), n))
1566
+ throw new Error('Cannot find square root');
1567
+ return root;
1568
+ };
1569
+ }
1570
+ // Other cases: Tonelli-Shanks algorithm
1571
+ return tonelliShanks(P);
1572
+ }
1573
+ // prettier-ignore
1574
+ const FIELD_FIELDS = [
1575
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
1576
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
1577
+ 'addN', 'subN', 'mulN', 'sqrN'
1578
+ ];
1579
+ function validateField(field) {
1580
+ const initial = {
1581
+ ORDER: 'bigint',
1582
+ MASK: 'bigint',
1583
+ BYTES: 'isSafeInteger',
1584
+ BITS: 'isSafeInteger',
1585
+ };
1586
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1587
+ map[val] = 'function';
1588
+ return map;
1589
+ }, initial);
1590
+ return validateObject(field, opts);
1591
+ }
1592
+ // Generic field functions
1593
+ /**
1594
+ * Same as `pow` but for Fp: non-constant-time.
1595
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1596
+ */
1597
+ function FpPow(Fp, num, power) {
1598
+ if (power < _0n$2)
1599
+ throw new Error('invalid exponent, negatives unsupported');
1600
+ if (power === _0n$2)
1601
+ return Fp.ONE;
1602
+ if (power === _1n$3)
1603
+ return num;
1604
+ // @ts-ignore
1605
+ let p = Fp.ONE;
1606
+ let d = num;
1607
+ while (power > _0n$2) {
1608
+ if (power & _1n$3)
1609
+ p = Fp.mul(p, d);
1610
+ d = Fp.sqr(d);
1611
+ power >>= _1n$3;
1612
+ }
1613
+ return p;
1614
+ }
1615
+ /**
1616
+ * Efficiently invert an array of Field elements.
1617
+ * Exception-free. Will return `undefined` for 0 elements.
1618
+ * @param passZero map 0 to 0 (instead of undefined)
1619
+ */
1620
+ function FpInvertBatch(Fp, nums, passZero = false) {
1621
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
1622
+ // Walk from first to last, multiply them by each other MOD p
1623
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1624
+ if (Fp.is0(num))
1625
+ return acc;
1626
+ inverted[i] = acc;
1627
+ return Fp.mul(acc, num);
1628
+ }, Fp.ONE);
1629
+ // Invert last element
1630
+ const invertedAcc = Fp.inv(multipliedAcc);
1631
+ // Walk from last to first, multiply them by inverted each other MOD p
1632
+ nums.reduceRight((acc, num, i) => {
1633
+ if (Fp.is0(num))
1634
+ return acc;
1635
+ inverted[i] = Fp.mul(acc, inverted[i]);
1636
+ return Fp.mul(acc, num);
1637
+ }, invertedAcc);
1638
+ return inverted;
1639
+ }
1640
+ /**
1641
+ * Legendre symbol.
1642
+ * Legendre constant is used to calculate Legendre symbol (a | p)
1643
+ * which denotes the value of a^((p-1)/2) (mod p)..
1644
+ *
1645
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
1646
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
1647
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
1648
+ */
1649
+ function FpLegendre(Fp, n) {
1650
+ const legc = (Fp.ORDER - _1n$3) / _2n$1;
1651
+ const powered = Fp.pow(n, legc);
1652
+ const yes = Fp.eql(powered, Fp.ONE);
1653
+ const zero = Fp.eql(powered, Fp.ZERO);
1654
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1655
+ if (!yes && !zero && !no)
1656
+ throw new Error('Cannot find square root: probably non-prime P');
1657
+ return yes ? 1 : zero ? 0 : -1;
1658
+ }
1659
+ // This function returns True whenever the value x is a square in the field F.
1660
+ function FpIsSquare(Fp, n) {
1661
+ const l = FpLegendre(Fp, n);
1662
+ return l === 0 || l === 1;
1663
+ }
1664
+ // CURVE.n lengths
1665
+ function nLength(n, nBitLength) {
1666
+ // Bit size, byte size of CURVE.n
1667
+ if (nBitLength !== undefined)
1668
+ anumber(nBitLength);
1669
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
1670
+ const nByteLength = Math.ceil(_nBitLength / 8);
1671
+ return { nBitLength: _nBitLength, nByteLength };
1672
+ }
1673
+ /**
1674
+ * Initializes a finite field over prime.
1675
+ * Major performance optimizations:
1676
+ * * a) denormalized operations like mulN instead of mul
1677
+ * * b) same object shape: never add or remove keys
1678
+ * * c) Object.freeze
1679
+ * Fragile: always run a benchmark on a change.
1680
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
1681
+ * it is caller responsibility to check this.
1682
+ * This is low-level code, please make sure you know what you're doing.
1683
+ * @param ORDER prime positive bigint
1684
+ * @param bitLen how many bits the field consumes
1685
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
1686
+ * @param redef optional faster redefinitions of sqrt and other methods
1687
+ */
1688
+ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1689
+ if (ORDER <= _0n$2)
1690
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
1691
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
1692
+ if (BYTES > 2048)
1693
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
1694
+ let sqrtP; // cached sqrtP
1695
+ const f = Object.freeze({
1696
+ ORDER,
1697
+ isLE,
1698
+ BITS,
1699
+ BYTES,
1700
+ MASK: bitMask(BITS),
1701
+ ZERO: _0n$2,
1702
+ ONE: _1n$3,
1703
+ create: (num) => mod(num, ORDER),
1704
+ isValid: (num) => {
1705
+ if (typeof num !== 'bigint')
1706
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
1707
+ return _0n$2 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1708
+ },
1709
+ is0: (num) => num === _0n$2,
1710
+ isOdd: (num) => (num & _1n$3) === _1n$3,
1711
+ neg: (num) => mod(-num, ORDER),
1712
+ eql: (lhs, rhs) => lhs === rhs,
1713
+ sqr: (num) => mod(num * num, ORDER),
1714
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1715
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1716
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1717
+ pow: (num, power) => FpPow(f, num, power),
1718
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1719
+ // Same as above, but doesn't normalize
1720
+ sqrN: (num) => num * num,
1721
+ addN: (lhs, rhs) => lhs + rhs,
1722
+ subN: (lhs, rhs) => lhs - rhs,
1723
+ mulN: (lhs, rhs) => lhs * rhs,
1724
+ inv: (num) => invert(num, ORDER),
1725
+ sqrt: redef.sqrt ||
1726
+ ((n) => {
1727
+ if (!sqrtP)
1728
+ sqrtP = FpSqrt(ORDER);
1729
+ return sqrtP(f, n);
1730
+ }),
1731
+ toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
1732
+ fromBytes: (bytes) => {
1733
+ if (bytes.length !== BYTES)
1734
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
1735
+ return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1736
+ },
1737
+ // TODO: we don't need it here, move out to separate fn
1738
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1739
+ // We can't move this out because Fp6, Fp12 implement it
1740
+ // and it's unclear what to return in there.
1741
+ cmov: (a, b, c) => (c ? b : a),
1742
+ });
1743
+ return Object.freeze(f);
1744
+ }
1745
+ /**
1746
+ * Returns total number of bytes consumed by the field element.
1747
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
1748
+ * @param fieldOrder number of field elements, usually CURVE.n
1749
+ * @returns byte length of field
1750
+ */
1751
+ function getFieldBytesLength(fieldOrder) {
1752
+ if (typeof fieldOrder !== 'bigint')
1753
+ throw new Error('field order must be bigint');
1754
+ const bitLength = fieldOrder.toString(2).length;
1755
+ return Math.ceil(bitLength / 8);
1756
+ }
1757
+ /**
1758
+ * Returns minimal amount of bytes that can be safely reduced
1759
+ * by field order.
1760
+ * Should be 2^-128 for 128-bit curve such as P256.
1761
+ * @param fieldOrder number of field elements, usually CURVE.n
1762
+ * @returns byte length of target hash
1763
+ */
1764
+ function getMinHashLength(fieldOrder) {
1765
+ const length = getFieldBytesLength(fieldOrder);
1766
+ return length + Math.ceil(length / 2);
1767
+ }
1768
+ /**
1769
+ * "Constant-time" private key generation utility.
1770
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
1771
+ * and convert them into private scalar, with the modulo bias being negligible.
1772
+ * Needs at least 48 bytes of input for 32-byte private key.
1773
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
1774
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
1775
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
1776
+ * @param hash hash output from SHA3 or a similar function
1777
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
1778
+ * @param isLE interpret hash bytes as LE num
1779
+ * @returns valid private scalar
1780
+ */
1781
+ function mapHashToField(key, fieldOrder, isLE = false) {
1782
+ const len = key.length;
1783
+ const fieldLen = getFieldBytesLength(fieldOrder);
1784
+ const minLen = getMinHashLength(fieldOrder);
1785
+ // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
1786
+ if (len < 16 || len < minLen || len > 1024)
1787
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
1788
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1789
+ // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
1790
+ const reduced = mod(num, fieldOrder - _1n$3) + _1n$3;
1791
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
73
1792
  }
74
1793
 
75
- class Hash {
76
- constructor() { }
77
- keccak256(params) {
78
- const types = [];
79
- const values = [];
80
- if (!Array.isArray(params)) {
81
- types.push('string');
82
- values.push(params);
1794
+ /**
1795
+ * Methods for elliptic curve multiplication by scalars.
1796
+ * Contains wNAF, pippenger
1797
+ * @module
1798
+ */
1799
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1800
+ const _0n$1 = BigInt(0);
1801
+ const _1n$2 = BigInt(1);
1802
+ function constTimeNegate(condition, item) {
1803
+ const neg = item.negate();
1804
+ return condition ? neg : item;
1805
+ }
1806
+ function validateW(W, bits) {
1807
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1808
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
1809
+ }
1810
+ function calcWOpts(W, scalarBits) {
1811
+ validateW(W, scalarBits);
1812
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
1813
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
1814
+ const maxNumber = 2 ** W; // W=8 256
1815
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
1816
+ const shiftBy = BigInt(W); // W=8 8
1817
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1818
+ }
1819
+ function calcOffsets(n, window, wOpts) {
1820
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1821
+ let wbits = Number(n & mask); // extract W bits.
1822
+ let nextN = n >> shiftBy; // shift number by W bits.
1823
+ // What actually happens here:
1824
+ // const highestBit = Number(mask ^ (mask >> 1n));
1825
+ // let wbits2 = wbits - 1; // skip zero
1826
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
1827
+ // split if bits > max: +224 => 256-32
1828
+ if (wbits > windowSize) {
1829
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
1830
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
1831
+ nextN += _1n$2; // +256 (carry)
1832
+ }
1833
+ const offsetStart = window * windowSize;
1834
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
1835
+ const isZero = wbits === 0; // is current window slice a 0?
1836
+ const isNeg = wbits < 0; // is current window slice negative?
1837
+ const isNegF = window % 2 !== 0; // fake random statement for noise
1838
+ const offsetF = offsetStart; // fake offset for noise
1839
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1840
+ }
1841
+ function validateMSMPoints(points, c) {
1842
+ if (!Array.isArray(points))
1843
+ throw new Error('array expected');
1844
+ points.forEach((p, i) => {
1845
+ if (!(p instanceof c))
1846
+ throw new Error('invalid point at index ' + i);
1847
+ });
1848
+ }
1849
+ function validateMSMScalars(scalars, field) {
1850
+ if (!Array.isArray(scalars))
1851
+ throw new Error('array of scalars expected');
1852
+ scalars.forEach((s, i) => {
1853
+ if (!field.isValid(s))
1854
+ throw new Error('invalid scalar at index ' + i);
1855
+ });
1856
+ }
1857
+ // Since points in different groups cannot be equal (different object constructor),
1858
+ // we can have single place to store precomputes.
1859
+ // Allows to make points frozen / immutable.
1860
+ const pointPrecomputes = new WeakMap();
1861
+ const pointWindowSizes = new WeakMap();
1862
+ function getW(P) {
1863
+ return pointWindowSizes.get(P) || 1;
1864
+ }
1865
+ /**
1866
+ * Elliptic curve multiplication of Point by scalar. Fragile.
1867
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
1868
+ * Creates precomputation tables for fast multiplication:
1869
+ * - private scalar is split by fixed size windows of W bits
1870
+ * - every window point is collected from window's table & added to accumulator
1871
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
1872
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1873
+ * - +1 window is neccessary for wNAF
1874
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1875
+ *
1876
+ * @todo Research returning 2d JS array of windows, instead of a single window.
1877
+ * This would allow windows to be in different memory locations
1878
+ */
1879
+ function wNAF(c, bits) {
1880
+ return {
1881
+ constTimeNegate,
1882
+ hasPrecomputes(elm) {
1883
+ return getW(elm) !== 1;
1884
+ },
1885
+ // non-const time multiplication ladder
1886
+ unsafeLadder(elm, n, p = c.ZERO) {
1887
+ let d = elm;
1888
+ while (n > _0n$1) {
1889
+ if (n & _1n$2)
1890
+ p = p.add(d);
1891
+ d = d.double();
1892
+ n >>= _1n$2;
1893
+ }
1894
+ return p;
1895
+ },
1896
+ /**
1897
+ * Creates a wNAF precomputation window. Used for caching.
1898
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1899
+ * Number of precomputed points depends on the curve size:
1900
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1901
+ * - 𝑊 is the window size
1902
+ * - 𝑛 is the bitlength of the curve order.
1903
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1904
+ * @param elm Point instance
1905
+ * @param W window size
1906
+ * @returns precomputed point tables flattened to a single array
1907
+ */
1908
+ precomputeWindow(elm, W) {
1909
+ const { windows, windowSize } = calcWOpts(W, bits);
1910
+ const points = [];
1911
+ let p = elm;
1912
+ let base = p;
1913
+ for (let window = 0; window < windows; window++) {
1914
+ base = p;
1915
+ points.push(base);
1916
+ // i=1, bc we skip 0
1917
+ for (let i = 1; i < windowSize; i++) {
1918
+ base = base.add(p);
1919
+ points.push(base);
1920
+ }
1921
+ p = base.double();
1922
+ }
1923
+ return points;
1924
+ },
1925
+ /**
1926
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1927
+ * @param W window size
1928
+ * @param precomputes precomputed tables
1929
+ * @param n scalar (we don't check here, but should be less than curve order)
1930
+ * @returns real and fake (for const-time) points
1931
+ */
1932
+ wNAF(W, precomputes, n) {
1933
+ // Smaller version:
1934
+ // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1935
+ // TODO: check the scalar is less than group order?
1936
+ // wNAF behavior is undefined otherwise. But have to carefully remove
1937
+ // other checks before wNAF. ORDER == bits here.
1938
+ // Accumulators
1939
+ let p = c.ZERO;
1940
+ let f = c.BASE;
1941
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1942
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1943
+ // there is negate now: it is possible that negated element from low value
1944
+ // would be the same as high element, which will create carry into next window.
1945
+ // It's not obvious how this can fail, but still worth investigating later.
1946
+ const wo = calcWOpts(W, bits);
1947
+ for (let window = 0; window < wo.windows; window++) {
1948
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
1949
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1950
+ n = nextN;
1951
+ if (isZero) {
1952
+ // bits are 0: add garbage to fake point
1953
+ // Important part for const-time getPublicKey: add random "noise" point to f.
1954
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
1955
+ }
1956
+ else {
1957
+ // bits are 1: add to result point
1958
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
1959
+ }
1960
+ }
1961
+ // Return both real and fake points: JIT won't eliminate f.
1962
+ // At this point there is a way to F be infinity-point even if p is not,
1963
+ // which makes it less const-time: around 1 bigint multiply.
1964
+ return { p, f };
1965
+ },
1966
+ /**
1967
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1968
+ * @param W window size
1969
+ * @param precomputes precomputed tables
1970
+ * @param n scalar (we don't check here, but should be less than curve order)
1971
+ * @param acc accumulator point to add result of multiplication
1972
+ * @returns point
1973
+ */
1974
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1975
+ const wo = calcWOpts(W, bits);
1976
+ for (let window = 0; window < wo.windows; window++) {
1977
+ if (n === _0n$1)
1978
+ break; // Early-exit, skip 0 value
1979
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1980
+ n = nextN;
1981
+ if (isZero) {
1982
+ // Window bits are 0: skip processing.
1983
+ // Move to next window.
1984
+ continue;
1985
+ }
1986
+ else {
1987
+ const item = precomputes[offset];
1988
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
1989
+ }
1990
+ }
1991
+ return acc;
1992
+ },
1993
+ getPrecomputes(W, P, transform) {
1994
+ // Calculate precomputes on a first run, reuse them after
1995
+ let comp = pointPrecomputes.get(P);
1996
+ if (!comp) {
1997
+ comp = this.precomputeWindow(P, W);
1998
+ if (W !== 1)
1999
+ pointPrecomputes.set(P, transform(comp));
2000
+ }
2001
+ return comp;
2002
+ },
2003
+ wNAFCached(P, n, transform) {
2004
+ const W = getW(P);
2005
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
2006
+ },
2007
+ wNAFCachedUnsafe(P, n, transform, prev) {
2008
+ const W = getW(P);
2009
+ if (W === 1)
2010
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
2011
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
2012
+ },
2013
+ // We calculate precomputes for elliptic curve point multiplication
2014
+ // using windowed method. This specifies window size and
2015
+ // stores precomputed values. Usually only base point would be precomputed.
2016
+ setWindowSize(P, W) {
2017
+ validateW(W, bits);
2018
+ pointWindowSizes.set(P, W);
2019
+ pointPrecomputes.delete(P);
2020
+ },
2021
+ };
2022
+ }
2023
+ /**
2024
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
2025
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
2026
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
2027
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
2028
+ * @param c Curve Point constructor
2029
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
2030
+ * @param points array of L curve points
2031
+ * @param scalars array of L scalars (aka private keys / bigints)
2032
+ */
2033
+ function pippenger(c, fieldN, points, scalars) {
2034
+ // If we split scalars by some window (let's say 8 bits), every chunk will only
2035
+ // take 256 buckets even if there are 4096 scalars, also re-uses double.
2036
+ // TODO:
2037
+ // - https://eprint.iacr.org/2024/750.pdf
2038
+ // - https://tches.iacr.org/index.php/TCHES/article/view/10287
2039
+ // 0 is accepted in scalars
2040
+ validateMSMPoints(points, c);
2041
+ validateMSMScalars(scalars, fieldN);
2042
+ if (points.length !== scalars.length)
2043
+ throw new Error('arrays of points and scalars must have equal length');
2044
+ const zero = c.ZERO;
2045
+ const wbits = bitLen(BigInt(points.length));
2046
+ const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
2047
+ const MASK = bitMask(windowSize);
2048
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
2049
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
2050
+ let sum = zero;
2051
+ for (let i = lastBits; i >= 0; i -= windowSize) {
2052
+ buckets.fill(zero);
2053
+ for (let j = 0; j < scalars.length; j++) {
2054
+ const scalar = scalars[j];
2055
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
2056
+ buckets[wbits] = buckets[wbits].add(points[j]);
83
2057
  }
84
- else {
85
- params.forEach((p) => {
86
- types.push(p.type);
87
- values.push(p.value);
88
- });
2058
+ let resI = zero; // not using this will do small speed-up, but will lose ct
2059
+ // Skip first bucket, because it is zero
2060
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
2061
+ sumI = sumI.add(buckets[j]);
2062
+ resI = resI.add(sumI);
89
2063
  }
90
- return solidityPackedKeccak256(types, values);
2064
+ sum = sum.add(resI);
2065
+ if (i !== 0)
2066
+ for (let j = 0; j < windowSize; j++)
2067
+ sum = sum.double();
91
2068
  }
2069
+ return sum;
2070
+ }
2071
+ function validateBasic(curve) {
2072
+ validateField(curve.Fp);
2073
+ validateObject(curve, {
2074
+ n: 'bigint',
2075
+ h: 'bigint',
2076
+ Gx: 'field',
2077
+ Gy: 'field',
2078
+ }, {
2079
+ nBitLength: 'isSafeInteger',
2080
+ nByteLength: 'isSafeInteger',
2081
+ });
2082
+ // Set defaults
2083
+ return Object.freeze({
2084
+ ...nLength(curve.n, curve.nBitLength),
2085
+ ...curve,
2086
+ ...{ p: curve.Fp.ORDER },
2087
+ });
92
2088
  }
93
2089
 
2090
+ /**
2091
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
2092
+ *
2093
+ * ### Parameters
2094
+ *
2095
+ * To initialize a weierstrass curve, one needs to pass following params:
2096
+ *
2097
+ * * a: formula param
2098
+ * * b: formula param
2099
+ * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
2100
+ * * n: Curve prime subgroup order, total count of valid points in the field
2101
+ * * Gx: Base point (x, y) aka generator point x coordinate
2102
+ * * Gy: ...y coordinate
2103
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
2104
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
2105
+ *
2106
+ * ### Design rationale for types
2107
+ *
2108
+ * * Interaction between classes from different curves should fail:
2109
+ * `k256.Point.BASE.add(p256.Point.BASE)`
2110
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
2111
+ * * Different calls of `curve()` would return different classes -
2112
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
2113
+ * it won't affect others
2114
+ *
2115
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
2116
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
2117
+ * unique type for every function call.
2118
+ *
2119
+ * We can use generic types via some param, like curve opts, but that would:
2120
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
2121
+ * which is hard to debug.
2122
+ * 2. Params can be generic and we can't enforce them to be constant value:
2123
+ * if somebody creates curve from non-constant params,
2124
+ * it would be allowed to interact with other curves with non-constant params
2125
+ *
2126
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
2127
+ * @module
2128
+ */
2129
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2130
+ // prettier-ignore
2131
+ function validateSigVerOpts(opts) {
2132
+ if (opts.lowS !== undefined)
2133
+ abool('lowS', opts.lowS);
2134
+ if (opts.prehash !== undefined)
2135
+ abool('prehash', opts.prehash);
2136
+ }
2137
+ function validatePointOpts(curve) {
2138
+ const opts = validateBasic(curve);
2139
+ validateObject(opts, {
2140
+ a: 'field',
2141
+ b: 'field',
2142
+ }, {
2143
+ allowedPrivateKeyLengths: 'array',
2144
+ wrapPrivateKey: 'boolean',
2145
+ isTorsionFree: 'function',
2146
+ clearCofactor: 'function',
2147
+ allowInfinityPoint: 'boolean',
2148
+ fromBytes: 'function',
2149
+ toBytes: 'function',
2150
+ });
2151
+ const { endo, Fp, a } = opts;
2152
+ if (endo) {
2153
+ if (!Fp.eql(a, Fp.ZERO)) {
2154
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
2155
+ }
2156
+ if (typeof endo !== 'object' ||
2157
+ typeof endo.beta !== 'bigint' ||
2158
+ typeof endo.splitScalar !== 'function') {
2159
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
2160
+ }
2161
+ }
2162
+ return Object.freeze({ ...opts });
2163
+ }
2164
+ class DERErr extends Error {
2165
+ constructor(m = '') {
2166
+ super(m);
2167
+ }
2168
+ }
2169
+ /**
2170
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
2171
+ *
2172
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
2173
+ *
2174
+ * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
2175
+ */
2176
+ const DER = {
2177
+ // asn.1 DER encoding utils
2178
+ Err: DERErr,
2179
+ // Basic building block is TLV (Tag-Length-Value)
2180
+ _tlv: {
2181
+ encode: (tag, data) => {
2182
+ const { Err: E } = DER;
2183
+ if (tag < 0 || tag > 256)
2184
+ throw new E('tlv.encode: wrong tag');
2185
+ if (data.length & 1)
2186
+ throw new E('tlv.encode: unpadded data');
2187
+ const dataLen = data.length / 2;
2188
+ const len = numberToHexUnpadded(dataLen);
2189
+ if ((len.length / 2) & 128)
2190
+ throw new E('tlv.encode: long form length too big');
2191
+ // length of length with long form flag
2192
+ const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
2193
+ const t = numberToHexUnpadded(tag);
2194
+ return t + lenLen + len + data;
2195
+ },
2196
+ // v - value, l - left bytes (unparsed)
2197
+ decode(tag, data) {
2198
+ const { Err: E } = DER;
2199
+ let pos = 0;
2200
+ if (tag < 0 || tag > 256)
2201
+ throw new E('tlv.encode: wrong tag');
2202
+ if (data.length < 2 || data[pos++] !== tag)
2203
+ throw new E('tlv.decode: wrong tlv');
2204
+ const first = data[pos++];
2205
+ const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
2206
+ let length = 0;
2207
+ if (!isLong)
2208
+ length = first;
2209
+ else {
2210
+ // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
2211
+ const lenLen = first & 127;
2212
+ if (!lenLen)
2213
+ throw new E('tlv.decode(long): indefinite length not supported');
2214
+ if (lenLen > 4)
2215
+ throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
2216
+ const lengthBytes = data.subarray(pos, pos + lenLen);
2217
+ if (lengthBytes.length !== lenLen)
2218
+ throw new E('tlv.decode: length bytes not complete');
2219
+ if (lengthBytes[0] === 0)
2220
+ throw new E('tlv.decode(long): zero leftmost byte');
2221
+ for (const b of lengthBytes)
2222
+ length = (length << 8) | b;
2223
+ pos += lenLen;
2224
+ if (length < 128)
2225
+ throw new E('tlv.decode(long): not minimal encoding');
2226
+ }
2227
+ const v = data.subarray(pos, pos + length);
2228
+ if (v.length !== length)
2229
+ throw new E('tlv.decode: wrong value length');
2230
+ return { v, l: data.subarray(pos + length) };
2231
+ },
2232
+ },
2233
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2234
+ // since we always use positive integers here. It must always be empty:
2235
+ // - add zero byte if exists
2236
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2237
+ _int: {
2238
+ encode(num) {
2239
+ const { Err: E } = DER;
2240
+ if (num < _0n)
2241
+ throw new E('integer: negative integers are not allowed');
2242
+ let hex = numberToHexUnpadded(num);
2243
+ // Pad with zero byte if negative flag is present
2244
+ if (Number.parseInt(hex[0], 16) & 0b1000)
2245
+ hex = '00' + hex;
2246
+ if (hex.length & 1)
2247
+ throw new E('unexpected DER parsing assertion: unpadded hex');
2248
+ return hex;
2249
+ },
2250
+ decode(data) {
2251
+ const { Err: E } = DER;
2252
+ if (data[0] & 128)
2253
+ throw new E('invalid signature integer: negative');
2254
+ if (data[0] === 0x00 && !(data[1] & 128))
2255
+ throw new E('invalid signature integer: unnecessary leading zero');
2256
+ return bytesToNumberBE(data);
2257
+ },
2258
+ },
2259
+ toSig(hex) {
2260
+ // parse DER signature
2261
+ const { Err: E, _int: int, _tlv: tlv } = DER;
2262
+ const data = ensureBytes('signature', hex);
2263
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
2264
+ if (seqLeftBytes.length)
2265
+ throw new E('invalid signature: left bytes after parsing');
2266
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
2267
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
2268
+ if (sLeftBytes.length)
2269
+ throw new E('invalid signature: left bytes after parsing');
2270
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
2271
+ },
2272
+ hexFromSig(sig) {
2273
+ const { _tlv: tlv, _int: int } = DER;
2274
+ const rs = tlv.encode(0x02, int.encode(sig.r));
2275
+ const ss = tlv.encode(0x02, int.encode(sig.s));
2276
+ const seq = rs + ss;
2277
+ return tlv.encode(0x30, seq);
2278
+ },
2279
+ };
2280
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
2281
+ // prettier-ignore
2282
+ const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigInt(4);
2283
+ function weierstrassPoints(opts) {
2284
+ const CURVE = validatePointOpts(opts);
2285
+ const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
2286
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
2287
+ const toBytes = CURVE.toBytes ||
2288
+ ((_c, point, _isCompressed) => {
2289
+ const a = point.toAffine();
2290
+ return concatBytes$1(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
2291
+ });
2292
+ const fromBytes = CURVE.fromBytes ||
2293
+ ((bytes) => {
2294
+ // const head = bytes[0];
2295
+ const tail = bytes.subarray(1);
2296
+ // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
2297
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
2298
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
2299
+ return { x, y };
2300
+ });
2301
+ /**
2302
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
2303
+ * @returns y²
2304
+ */
2305
+ function weierstrassEquation(x) {
2306
+ const { a, b } = CURVE;
2307
+ const x2 = Fp.sqr(x); // x * x
2308
+ const x3 = Fp.mul(x2, x); // x2 * x
2309
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
2310
+ }
2311
+ // Validate whether the passed curve params are valid.
2312
+ // We check if curve equation works for generator point.
2313
+ // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
2314
+ // ProjectivePoint class has not been initialized yet.
2315
+ if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
2316
+ throw new Error('bad generator point: equation left != right');
2317
+ // Valid group elements reside in range 1..n-1
2318
+ function isWithinCurveOrder(num) {
2319
+ return inRange(num, _1n$1, CURVE.n);
2320
+ }
2321
+ // Validates if priv key is valid and converts it to bigint.
2322
+ // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
2323
+ function normPrivateKeyToScalar(key) {
2324
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
2325
+ if (lengths && typeof key !== 'bigint') {
2326
+ if (isBytes$2(key))
2327
+ key = bytesToHex$1(key);
2328
+ // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
2329
+ if (typeof key !== 'string' || !lengths.includes(key.length))
2330
+ throw new Error('invalid private key');
2331
+ key = key.padStart(nByteLength * 2, '0');
2332
+ }
2333
+ let num;
2334
+ try {
2335
+ num =
2336
+ typeof key === 'bigint'
2337
+ ? key
2338
+ : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
2339
+ }
2340
+ catch (error) {
2341
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
2342
+ }
2343
+ if (wrapPrivateKey)
2344
+ num = mod(num, N); // disabled by default, enabled for BLS
2345
+ aInRange('private key', num, _1n$1, N); // num in range [1..N-1]
2346
+ return num;
2347
+ }
2348
+ function aprjpoint(other) {
2349
+ if (!(other instanceof Point))
2350
+ throw new Error('ProjectivePoint expected');
2351
+ }
2352
+ // Memoized toAffine / validity check. They are heavy. Points are immutable.
2353
+ // Converts Projective point to affine (x, y) coordinates.
2354
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2355
+ // (x, y, z) ∋ (x=x/z, y=y/z)
2356
+ const toAffineMemo = memoized((p, iz) => {
2357
+ const { px: x, py: y, pz: z } = p;
2358
+ // Fast-path for normalized points
2359
+ if (Fp.eql(z, Fp.ONE))
2360
+ return { x, y };
2361
+ const is0 = p.is0();
2362
+ // If invZ was 0, we return zero point. However we still want to execute
2363
+ // all operations, so we replace invZ with a random number, 1.
2364
+ if (iz == null)
2365
+ iz = is0 ? Fp.ONE : Fp.inv(z);
2366
+ const ax = Fp.mul(x, iz);
2367
+ const ay = Fp.mul(y, iz);
2368
+ const zz = Fp.mul(z, iz);
2369
+ if (is0)
2370
+ return { x: Fp.ZERO, y: Fp.ZERO };
2371
+ if (!Fp.eql(zz, Fp.ONE))
2372
+ throw new Error('invZ was invalid');
2373
+ return { x: ax, y: ay };
2374
+ });
2375
+ // NOTE: on exception this will crash 'cached' and no value will be set.
2376
+ // Otherwise true will be return
2377
+ const assertValidMemo = memoized((p) => {
2378
+ if (p.is0()) {
2379
+ // (0, 1, 0) aka ZERO is invalid in most contexts.
2380
+ // In BLS, ZERO can be serialized, so we allow it.
2381
+ // (0, 0, 0) is invalid representation of ZERO.
2382
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
2383
+ return;
2384
+ throw new Error('bad point: ZERO');
2385
+ }
2386
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
2387
+ const { x, y } = p.toAffine();
2388
+ // Check if x, y are valid field elements
2389
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2390
+ throw new Error('bad point: x or y not FE');
2391
+ const left = Fp.sqr(y); // y²
2392
+ const right = weierstrassEquation(x); // x³ + ax + b
2393
+ if (!Fp.eql(left, right))
2394
+ throw new Error('bad point: equation left != right');
2395
+ if (!p.isTorsionFree())
2396
+ throw new Error('bad point: not in prime-order subgroup');
2397
+ return true;
2398
+ });
2399
+ /**
2400
+ * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
2401
+ * Default Point works in 2d / affine coordinates: (x, y)
2402
+ * We're doing calculations in projective, because its operations don't require costly inversion.
2403
+ */
2404
+ class Point {
2405
+ constructor(px, py, pz) {
2406
+ if (px == null || !Fp.isValid(px))
2407
+ throw new Error('x required');
2408
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
2409
+ throw new Error('y required');
2410
+ if (pz == null || !Fp.isValid(pz))
2411
+ throw new Error('z required');
2412
+ this.px = px;
2413
+ this.py = py;
2414
+ this.pz = pz;
2415
+ Object.freeze(this);
2416
+ }
2417
+ // Does not validate if the point is on-curve.
2418
+ // Use fromHex instead, or call assertValidity() later.
2419
+ static fromAffine(p) {
2420
+ const { x, y } = p || {};
2421
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2422
+ throw new Error('invalid affine point');
2423
+ if (p instanceof Point)
2424
+ throw new Error('projective point not allowed');
2425
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
2426
+ // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
2427
+ if (is0(x) && is0(y))
2428
+ return Point.ZERO;
2429
+ return new Point(x, y, Fp.ONE);
2430
+ }
2431
+ get x() {
2432
+ return this.toAffine().x;
2433
+ }
2434
+ get y() {
2435
+ return this.toAffine().y;
2436
+ }
2437
+ /**
2438
+ * Takes a bunch of Projective Points but executes only one
2439
+ * inversion on all of them. Inversion is very slow operation,
2440
+ * so this improves performance massively.
2441
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
2442
+ */
2443
+ static normalizeZ(points) {
2444
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
2445
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
2446
+ }
2447
+ /**
2448
+ * Converts hash string or Uint8Array to Point.
2449
+ * @param hex short/long ECDSA hex
2450
+ */
2451
+ static fromHex(hex) {
2452
+ const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));
2453
+ P.assertValidity();
2454
+ return P;
2455
+ }
2456
+ // Multiplies generator point by privateKey.
2457
+ static fromPrivateKey(privateKey) {
2458
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
2459
+ }
2460
+ // Multiscalar Multiplication
2461
+ static msm(points, scalars) {
2462
+ return pippenger(Point, Fn, points, scalars);
2463
+ }
2464
+ // "Private method", don't use it directly
2465
+ _setWindowSize(windowSize) {
2466
+ wnaf.setWindowSize(this, windowSize);
2467
+ }
2468
+ // A point on curve is valid if it conforms to equation.
2469
+ assertValidity() {
2470
+ assertValidMemo(this);
2471
+ }
2472
+ hasEvenY() {
2473
+ const { y } = this.toAffine();
2474
+ if (Fp.isOdd)
2475
+ return !Fp.isOdd(y);
2476
+ throw new Error("Field doesn't support isOdd");
2477
+ }
2478
+ /**
2479
+ * Compare one point to another.
2480
+ */
2481
+ equals(other) {
2482
+ aprjpoint(other);
2483
+ const { px: X1, py: Y1, pz: Z1 } = this;
2484
+ const { px: X2, py: Y2, pz: Z2 } = other;
2485
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2486
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2487
+ return U1 && U2;
2488
+ }
2489
+ /**
2490
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
2491
+ */
2492
+ negate() {
2493
+ return new Point(this.px, Fp.neg(this.py), this.pz);
2494
+ }
2495
+ // Renes-Costello-Batina exception-free doubling formula.
2496
+ // There is 30% faster Jacobian formula, but it is not complete.
2497
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2498
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2499
+ double() {
2500
+ const { a, b } = CURVE;
2501
+ const b3 = Fp.mul(b, _3n);
2502
+ const { px: X1, py: Y1, pz: Z1 } = this;
2503
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
2504
+ let t0 = Fp.mul(X1, X1); // step 1
2505
+ let t1 = Fp.mul(Y1, Y1);
2506
+ let t2 = Fp.mul(Z1, Z1);
2507
+ let t3 = Fp.mul(X1, Y1);
2508
+ t3 = Fp.add(t3, t3); // step 5
2509
+ Z3 = Fp.mul(X1, Z1);
2510
+ Z3 = Fp.add(Z3, Z3);
2511
+ X3 = Fp.mul(a, Z3);
2512
+ Y3 = Fp.mul(b3, t2);
2513
+ Y3 = Fp.add(X3, Y3); // step 10
2514
+ X3 = Fp.sub(t1, Y3);
2515
+ Y3 = Fp.add(t1, Y3);
2516
+ Y3 = Fp.mul(X3, Y3);
2517
+ X3 = Fp.mul(t3, X3);
2518
+ Z3 = Fp.mul(b3, Z3); // step 15
2519
+ t2 = Fp.mul(a, t2);
2520
+ t3 = Fp.sub(t0, t2);
2521
+ t3 = Fp.mul(a, t3);
2522
+ t3 = Fp.add(t3, Z3);
2523
+ Z3 = Fp.add(t0, t0); // step 20
2524
+ t0 = Fp.add(Z3, t0);
2525
+ t0 = Fp.add(t0, t2);
2526
+ t0 = Fp.mul(t0, t3);
2527
+ Y3 = Fp.add(Y3, t0);
2528
+ t2 = Fp.mul(Y1, Z1); // step 25
2529
+ t2 = Fp.add(t2, t2);
2530
+ t0 = Fp.mul(t2, t3);
2531
+ X3 = Fp.sub(X3, t0);
2532
+ Z3 = Fp.mul(t2, t1);
2533
+ Z3 = Fp.add(Z3, Z3); // step 30
2534
+ Z3 = Fp.add(Z3, Z3);
2535
+ return new Point(X3, Y3, Z3);
2536
+ }
2537
+ // Renes-Costello-Batina exception-free addition formula.
2538
+ // There is 30% faster Jacobian formula, but it is not complete.
2539
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2540
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2541
+ add(other) {
2542
+ aprjpoint(other);
2543
+ const { px: X1, py: Y1, pz: Z1 } = this;
2544
+ const { px: X2, py: Y2, pz: Z2 } = other;
2545
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
2546
+ const a = CURVE.a;
2547
+ const b3 = Fp.mul(CURVE.b, _3n);
2548
+ let t0 = Fp.mul(X1, X2); // step 1
2549
+ let t1 = Fp.mul(Y1, Y2);
2550
+ let t2 = Fp.mul(Z1, Z2);
2551
+ let t3 = Fp.add(X1, Y1);
2552
+ let t4 = Fp.add(X2, Y2); // step 5
2553
+ t3 = Fp.mul(t3, t4);
2554
+ t4 = Fp.add(t0, t1);
2555
+ t3 = Fp.sub(t3, t4);
2556
+ t4 = Fp.add(X1, Z1);
2557
+ let t5 = Fp.add(X2, Z2); // step 10
2558
+ t4 = Fp.mul(t4, t5);
2559
+ t5 = Fp.add(t0, t2);
2560
+ t4 = Fp.sub(t4, t5);
2561
+ t5 = Fp.add(Y1, Z1);
2562
+ X3 = Fp.add(Y2, Z2); // step 15
2563
+ t5 = Fp.mul(t5, X3);
2564
+ X3 = Fp.add(t1, t2);
2565
+ t5 = Fp.sub(t5, X3);
2566
+ Z3 = Fp.mul(a, t4);
2567
+ X3 = Fp.mul(b3, t2); // step 20
2568
+ Z3 = Fp.add(X3, Z3);
2569
+ X3 = Fp.sub(t1, Z3);
2570
+ Z3 = Fp.add(t1, Z3);
2571
+ Y3 = Fp.mul(X3, Z3);
2572
+ t1 = Fp.add(t0, t0); // step 25
2573
+ t1 = Fp.add(t1, t0);
2574
+ t2 = Fp.mul(a, t2);
2575
+ t4 = Fp.mul(b3, t4);
2576
+ t1 = Fp.add(t1, t2);
2577
+ t2 = Fp.sub(t0, t2); // step 30
2578
+ t2 = Fp.mul(a, t2);
2579
+ t4 = Fp.add(t4, t2);
2580
+ t0 = Fp.mul(t1, t4);
2581
+ Y3 = Fp.add(Y3, t0);
2582
+ t0 = Fp.mul(t5, t4); // step 35
2583
+ X3 = Fp.mul(t3, X3);
2584
+ X3 = Fp.sub(X3, t0);
2585
+ t0 = Fp.mul(t3, t1);
2586
+ Z3 = Fp.mul(t5, Z3);
2587
+ Z3 = Fp.add(Z3, t0); // step 40
2588
+ return new Point(X3, Y3, Z3);
2589
+ }
2590
+ subtract(other) {
2591
+ return this.add(other.negate());
2592
+ }
2593
+ is0() {
2594
+ return this.equals(Point.ZERO);
2595
+ }
2596
+ wNAF(n) {
2597
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
2598
+ }
2599
+ /**
2600
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2601
+ * It's faster, but should only be used when you don't care about
2602
+ * an exposed private key e.g. sig verification, which works over *public* keys.
2603
+ */
2604
+ multiplyUnsafe(sc) {
2605
+ const { endo, n: N } = CURVE;
2606
+ aInRange('scalar', sc, _0n, N);
2607
+ const I = Point.ZERO;
2608
+ if (sc === _0n)
2609
+ return I;
2610
+ if (this.is0() || sc === _1n$1)
2611
+ return this;
2612
+ // Case a: no endomorphism. Case b: has precomputes.
2613
+ if (!endo || wnaf.hasPrecomputes(this))
2614
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
2615
+ // Case c: endomorphism
2616
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
2617
+ let k1p = I;
2618
+ let k2p = I;
2619
+ let d = this;
2620
+ while (k1 > _0n || k2 > _0n) {
2621
+ if (k1 & _1n$1)
2622
+ k1p = k1p.add(d);
2623
+ if (k2 & _1n$1)
2624
+ k2p = k2p.add(d);
2625
+ d = d.double();
2626
+ k1 >>= _1n$1;
2627
+ k2 >>= _1n$1;
2628
+ }
2629
+ if (k1neg)
2630
+ k1p = k1p.negate();
2631
+ if (k2neg)
2632
+ k2p = k2p.negate();
2633
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
2634
+ return k1p.add(k2p);
2635
+ }
2636
+ /**
2637
+ * Constant time multiplication.
2638
+ * Uses wNAF method. Windowed method may be 10% faster,
2639
+ * but takes 2x longer to generate and consumes 2x memory.
2640
+ * Uses precomputes when available.
2641
+ * Uses endomorphism for Koblitz curves.
2642
+ * @param scalar by which the point would be multiplied
2643
+ * @returns New point
2644
+ */
2645
+ multiply(scalar) {
2646
+ const { endo, n: N } = CURVE;
2647
+ aInRange('scalar', scalar, _1n$1, N);
2648
+ let point, fake; // Fake point is used to const-time mult
2649
+ if (endo) {
2650
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
2651
+ let { p: k1p, f: f1p } = this.wNAF(k1);
2652
+ let { p: k2p, f: f2p } = this.wNAF(k2);
2653
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
2654
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
2655
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
2656
+ point = k1p.add(k2p);
2657
+ fake = f1p.add(f2p);
2658
+ }
2659
+ else {
2660
+ const { p, f } = this.wNAF(scalar);
2661
+ point = p;
2662
+ fake = f;
2663
+ }
2664
+ // Normalize `z` for both points, but return only real one
2665
+ return Point.normalizeZ([point, fake])[0];
2666
+ }
2667
+ /**
2668
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
2669
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
2670
+ * The trick could be useful if both P and Q are not G (not in our case).
2671
+ * @returns non-zero affine point
2672
+ */
2673
+ multiplyAndAddUnsafe(Q, a, b) {
2674
+ const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
2675
+ const mul = (P, a // Select faster multiply() method
2676
+ ) => (a === _0n || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
2677
+ const sum = mul(this, a).add(mul(Q, b));
2678
+ return sum.is0() ? undefined : sum;
2679
+ }
2680
+ // Converts Projective point to affine (x, y) coordinates.
2681
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2682
+ // (x, y, z) ∋ (x=x/z, y=y/z)
2683
+ toAffine(iz) {
2684
+ return toAffineMemo(this, iz);
2685
+ }
2686
+ isTorsionFree() {
2687
+ const { h: cofactor, isTorsionFree } = CURVE;
2688
+ if (cofactor === _1n$1)
2689
+ return true; // No subgroups, always torsion-free
2690
+ if (isTorsionFree)
2691
+ return isTorsionFree(Point, this);
2692
+ throw new Error('isTorsionFree() has not been declared for the elliptic curve');
2693
+ }
2694
+ clearCofactor() {
2695
+ const { h: cofactor, clearCofactor } = CURVE;
2696
+ if (cofactor === _1n$1)
2697
+ return this; // Fast-path
2698
+ if (clearCofactor)
2699
+ return clearCofactor(Point, this);
2700
+ return this.multiplyUnsafe(CURVE.h);
2701
+ }
2702
+ toRawBytes(isCompressed = true) {
2703
+ abool('isCompressed', isCompressed);
2704
+ this.assertValidity();
2705
+ return toBytes(Point, this, isCompressed);
2706
+ }
2707
+ toHex(isCompressed = true) {
2708
+ abool('isCompressed', isCompressed);
2709
+ return bytesToHex$1(this.toRawBytes(isCompressed));
2710
+ }
2711
+ }
2712
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2713
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
2714
+ const _bits = CURVE.nBitLength;
2715
+ const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
2716
+ return {
2717
+ CURVE,
2718
+ ProjectivePoint: Point,
2719
+ normPrivateKeyToScalar,
2720
+ weierstrassEquation,
2721
+ isWithinCurveOrder,
2722
+ };
2723
+ }
2724
+ function validateOpts(curve) {
2725
+ const opts = validateBasic(curve);
2726
+ validateObject(opts, {
2727
+ hash: 'hash',
2728
+ hmac: 'function',
2729
+ randomBytes: 'function',
2730
+ }, {
2731
+ bits2int: 'function',
2732
+ bits2int_modN: 'function',
2733
+ lowS: 'boolean',
2734
+ });
2735
+ return Object.freeze({ lowS: true, ...opts });
2736
+ }
2737
+ /**
2738
+ * Creates short weierstrass curve and ECDSA signature methods for it.
2739
+ * @example
2740
+ * import { Field } from '@noble/curves/abstract/modular';
2741
+ * // Before that, define BigInt-s: a, b, p, n, Gx, Gy
2742
+ * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
2743
+ */
2744
+ function weierstrass(curveDef) {
2745
+ const CURVE = validateOpts(curveDef);
2746
+ const { Fp, n: CURVE_ORDER } = CURVE;
2747
+ const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
2748
+ const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
2749
+ function modN(a) {
2750
+ return mod(a, CURVE_ORDER);
2751
+ }
2752
+ function invN(a) {
2753
+ return invert(a, CURVE_ORDER);
2754
+ }
2755
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
2756
+ ...CURVE,
2757
+ toBytes(_c, point, isCompressed) {
2758
+ const a = point.toAffine();
2759
+ const x = Fp.toBytes(a.x);
2760
+ const cat = concatBytes$1;
2761
+ abool('isCompressed', isCompressed);
2762
+ if (isCompressed) {
2763
+ return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
2764
+ }
2765
+ else {
2766
+ return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
2767
+ }
2768
+ },
2769
+ fromBytes(bytes) {
2770
+ const len = bytes.length;
2771
+ const head = bytes[0];
2772
+ const tail = bytes.subarray(1);
2773
+ // this.assertValidity() is done inside of fromHex
2774
+ if (len === compressedLen && (head === 0x02 || head === 0x03)) {
2775
+ const x = bytesToNumberBE(tail);
2776
+ if (!inRange(x, _1n$1, Fp.ORDER))
2777
+ throw new Error('Point is not on curve');
2778
+ const y2 = weierstrassEquation(x); // y² = x³ + ax + b
2779
+ let y;
2780
+ try {
2781
+ y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
2782
+ }
2783
+ catch (sqrtError) {
2784
+ const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
2785
+ throw new Error('Point is not on curve' + suffix);
2786
+ }
2787
+ const isYOdd = (y & _1n$1) === _1n$1;
2788
+ // ECDSA
2789
+ const isHeadOdd = (head & 1) === 1;
2790
+ if (isHeadOdd !== isYOdd)
2791
+ y = Fp.neg(y);
2792
+ return { x, y };
2793
+ }
2794
+ else if (len === uncompressedLen && head === 0x04) {
2795
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
2796
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
2797
+ return { x, y };
2798
+ }
2799
+ else {
2800
+ const cl = compressedLen;
2801
+ const ul = uncompressedLen;
2802
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
2803
+ }
2804
+ },
2805
+ });
2806
+ const numToNByteHex = (num) => bytesToHex$1(numberToBytesBE(num, CURVE.nByteLength));
2807
+ function isBiggerThanHalfOrder(number) {
2808
+ const HALF = CURVE_ORDER >> _1n$1;
2809
+ return number > HALF;
2810
+ }
2811
+ function normalizeS(s) {
2812
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
2813
+ }
2814
+ // slice bytes num
2815
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
2816
+ /**
2817
+ * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
2818
+ */
2819
+ class Signature {
2820
+ constructor(r, s, recovery) {
2821
+ aInRange('r', r, _1n$1, CURVE_ORDER); // r in [1..N]
2822
+ aInRange('s', s, _1n$1, CURVE_ORDER); // s in [1..N]
2823
+ this.r = r;
2824
+ this.s = s;
2825
+ if (recovery != null)
2826
+ this.recovery = recovery;
2827
+ Object.freeze(this);
2828
+ }
2829
+ // pair (bytes of r, bytes of s)
2830
+ static fromCompact(hex) {
2831
+ const l = CURVE.nByteLength;
2832
+ hex = ensureBytes('compactSignature', hex, l * 2);
2833
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
2834
+ }
2835
+ // DER encoded ECDSA signature
2836
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
2837
+ static fromDER(hex) {
2838
+ const { r, s } = DER.toSig(ensureBytes('DER', hex));
2839
+ return new Signature(r, s);
2840
+ }
2841
+ /**
2842
+ * @todo remove
2843
+ * @deprecated
2844
+ */
2845
+ assertValidity() { }
2846
+ addRecoveryBit(recovery) {
2847
+ return new Signature(this.r, this.s, recovery);
2848
+ }
2849
+ recoverPublicKey(msgHash) {
2850
+ const { r, s, recovery: rec } = this;
2851
+ const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
2852
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
2853
+ throw new Error('recovery id invalid');
2854
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
2855
+ if (radj >= Fp.ORDER)
2856
+ throw new Error('recovery id 2 or 3 invalid');
2857
+ const prefix = (rec & 1) === 0 ? '02' : '03';
2858
+ const R = Point.fromHex(prefix + numToNByteHex(radj));
2859
+ const ir = invN(radj); // r^-1
2860
+ const u1 = modN(-h * ir); // -hr^-1
2861
+ const u2 = modN(s * ir); // sr^-1
2862
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
2863
+ if (!Q)
2864
+ throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
2865
+ Q.assertValidity();
2866
+ return Q;
2867
+ }
2868
+ // Signatures should be low-s, to prevent malleability.
2869
+ hasHighS() {
2870
+ return isBiggerThanHalfOrder(this.s);
2871
+ }
2872
+ normalizeS() {
2873
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
2874
+ }
2875
+ // DER-encoded
2876
+ toDERRawBytes() {
2877
+ return hexToBytes$2(this.toDERHex());
2878
+ }
2879
+ toDERHex() {
2880
+ return DER.hexFromSig(this);
2881
+ }
2882
+ // padded bytes of r, then padded bytes of s
2883
+ toCompactRawBytes() {
2884
+ return hexToBytes$2(this.toCompactHex());
2885
+ }
2886
+ toCompactHex() {
2887
+ return numToNByteHex(this.r) + numToNByteHex(this.s);
2888
+ }
2889
+ }
2890
+ const utils = {
2891
+ isValidPrivateKey(privateKey) {
2892
+ try {
2893
+ normPrivateKeyToScalar(privateKey);
2894
+ return true;
2895
+ }
2896
+ catch (error) {
2897
+ return false;
2898
+ }
2899
+ },
2900
+ normPrivateKeyToScalar: normPrivateKeyToScalar,
2901
+ /**
2902
+ * Produces cryptographically secure private key from random of size
2903
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
2904
+ */
2905
+ randomPrivateKey: () => {
2906
+ const length = getMinHashLength(CURVE.n);
2907
+ return mapHashToField(CURVE.randomBytes(length), CURVE.n);
2908
+ },
2909
+ /**
2910
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
2911
+ * Allows to massively speed-up `point.multiply(scalar)`.
2912
+ * @returns cached point
2913
+ * @example
2914
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
2915
+ * fast.multiply(privKey); // much faster ECDH now
2916
+ */
2917
+ precompute(windowSize = 8, point = Point.BASE) {
2918
+ point._setWindowSize(windowSize);
2919
+ point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
2920
+ return point;
2921
+ },
2922
+ };
2923
+ /**
2924
+ * Computes public key for a private key. Checks for validity of the private key.
2925
+ * @param privateKey private key
2926
+ * @param isCompressed whether to return compact (default), or full key
2927
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
2928
+ */
2929
+ function getPublicKey(privateKey, isCompressed = true) {
2930
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
2931
+ }
2932
+ /**
2933
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
2934
+ */
2935
+ function isProbPub(item) {
2936
+ const arr = isBytes$2(item);
2937
+ const str = typeof item === 'string';
2938
+ const len = (arr || str) && item.length;
2939
+ if (arr)
2940
+ return len === compressedLen || len === uncompressedLen;
2941
+ if (str)
2942
+ return len === 2 * compressedLen || len === 2 * uncompressedLen;
2943
+ if (item instanceof Point)
2944
+ return true;
2945
+ return false;
2946
+ }
2947
+ /**
2948
+ * ECDH (Elliptic Curve Diffie Hellman).
2949
+ * Computes shared public key from private key and public key.
2950
+ * Checks: 1) private key validity 2) shared key is on-curve.
2951
+ * Does NOT hash the result.
2952
+ * @param privateA private key
2953
+ * @param publicB different public key
2954
+ * @param isCompressed whether to return compact (default), or full key
2955
+ * @returns shared public key
2956
+ */
2957
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
2958
+ if (isProbPub(privateA))
2959
+ throw new Error('first arg must be private key');
2960
+ if (!isProbPub(publicB))
2961
+ throw new Error('second arg must be public key');
2962
+ const b = Point.fromHex(publicB); // check for being on-curve
2963
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
2964
+ }
2965
+ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
2966
+ // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
2967
+ // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
2968
+ // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
2969
+ const bits2int = CURVE.bits2int ||
2970
+ function (bytes) {
2971
+ // Our custom check "just in case"
2972
+ if (bytes.length > 8192)
2973
+ throw new Error('input is too large');
2974
+ // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
2975
+ // for some cases, since bytes.length * 8 is not actual bitLength.
2976
+ const num = bytesToNumberBE(bytes); // check for == u8 done here
2977
+ const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
2978
+ return delta > 0 ? num >> BigInt(delta) : num;
2979
+ };
2980
+ const bits2int_modN = CURVE.bits2int_modN ||
2981
+ function (bytes) {
2982
+ return modN(bits2int(bytes)); // can't use bytesToNumberBE here
2983
+ };
2984
+ // NOTE: pads output with zero as per spec
2985
+ const ORDER_MASK = bitMask(CURVE.nBitLength);
2986
+ /**
2987
+ * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
2988
+ */
2989
+ function int2octets(num) {
2990
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
2991
+ // works with order, can have different size than numToField!
2992
+ return numberToBytesBE(num, CURVE.nByteLength);
2993
+ }
2994
+ // Steps A, D of RFC6979 3.2
2995
+ // Creates RFC6979 seed; converts msg/privKey to numbers.
2996
+ // Used only in sign, not in verify.
2997
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
2998
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
2999
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
3000
+ if (['recovered', 'canonical'].some((k) => k in opts))
3001
+ throw new Error('sign() legacy options not supported');
3002
+ const { hash, randomBytes } = CURVE;
3003
+ let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
3004
+ if (lowS == null)
3005
+ lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
3006
+ msgHash = ensureBytes('msgHash', msgHash);
3007
+ validateSigVerOpts(opts);
3008
+ if (prehash)
3009
+ msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
3010
+ // We can't later call bits2octets, since nested bits2int is broken for curves
3011
+ // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
3012
+ // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
3013
+ const h1int = bits2int_modN(msgHash);
3014
+ const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
3015
+ const seedArgs = [int2octets(d), int2octets(h1int)];
3016
+ // extraEntropy. RFC6979 3.6: additional k' (optional).
3017
+ if (ent != null && ent !== false) {
3018
+ // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
3019
+ const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
3020
+ seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
3021
+ }
3022
+ const seed = concatBytes$1(...seedArgs); // Step D of RFC6979 3.2
3023
+ const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
3024
+ // Converts signature params into point w r/s, checks result for validity.
3025
+ function k2sig(kBytes) {
3026
+ // RFC 6979 Section 3.2, step 3: k = bits2int(T)
3027
+ const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
3028
+ if (!isWithinCurveOrder(k))
3029
+ return; // Important: all mod() calls here must be done over N
3030
+ const ik = invN(k); // k^-1 mod n
3031
+ const q = Point.BASE.multiply(k).toAffine(); // q = Gk
3032
+ const r = modN(q.x); // r = q.x mod n
3033
+ if (r === _0n)
3034
+ return;
3035
+ // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
3036
+ // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
3037
+ // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
3038
+ const s = modN(ik * modN(m + r * d)); // Not using blinding here
3039
+ if (s === _0n)
3040
+ return;
3041
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); // recovery bit (2 or 3, when q.x > n)
3042
+ let normS = s;
3043
+ if (lowS && isBiggerThanHalfOrder(s)) {
3044
+ normS = normalizeS(s); // if lowS was passed, ensure s is always
3045
+ recovery ^= 1; // // in the bottom half of N
3046
+ }
3047
+ return new Signature(r, normS, recovery); // use normS, not s
3048
+ }
3049
+ return { seed, k2sig };
3050
+ }
3051
+ const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
3052
+ const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
3053
+ /**
3054
+ * Signs message hash with a private key.
3055
+ * ```
3056
+ * sign(m, d, k) where
3057
+ * (x, y) = G × k
3058
+ * r = x mod n
3059
+ * s = (m + dr)/k mod n
3060
+ * ```
3061
+ * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
3062
+ * @param privKey private key
3063
+ * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
3064
+ * @returns signature with recovery param
3065
+ */
3066
+ function sign(msgHash, privKey, opts = defaultSigOpts) {
3067
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
3068
+ const C = CURVE;
3069
+ const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
3070
+ return drbg(seed, k2sig); // Steps B, C, D, E, F, G
3071
+ }
3072
+ // Enable precomputes. Slows down first publicKey computation by 20ms.
3073
+ Point.BASE._setWindowSize(8);
3074
+ // utils.precompute(8, ProjectivePoint.BASE)
3075
+ /**
3076
+ * Verifies a signature against message hash and public key.
3077
+ * Rejects lowS signatures by default: to override,
3078
+ * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
3079
+ *
3080
+ * ```
3081
+ * verify(r, s, h, P) where
3082
+ * U1 = hs^-1 mod n
3083
+ * U2 = rs^-1 mod n
3084
+ * R = U1⋅G - U2⋅P
3085
+ * mod(R.x, n) == r
3086
+ * ```
3087
+ */
3088
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
3089
+ const sg = signature;
3090
+ msgHash = ensureBytes('msgHash', msgHash);
3091
+ publicKey = ensureBytes('publicKey', publicKey);
3092
+ const { lowS, prehash, format } = opts;
3093
+ // Verify opts, deduce signature format
3094
+ validateSigVerOpts(opts);
3095
+ if ('strict' in opts)
3096
+ throw new Error('options.strict was renamed to lowS');
3097
+ if (format !== undefined && format !== 'compact' && format !== 'der')
3098
+ throw new Error('format must be compact or der');
3099
+ const isHex = typeof sg === 'string' || isBytes$2(sg);
3100
+ const isObj = !isHex &&
3101
+ !format &&
3102
+ typeof sg === 'object' &&
3103
+ sg !== null &&
3104
+ typeof sg.r === 'bigint' &&
3105
+ typeof sg.s === 'bigint';
3106
+ if (!isHex && !isObj)
3107
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
3108
+ let _sig = undefined;
3109
+ let P;
3110
+ try {
3111
+ if (isObj)
3112
+ _sig = new Signature(sg.r, sg.s);
3113
+ if (isHex) {
3114
+ // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
3115
+ // Since DER can also be 2*nByteLength bytes, we check for it first.
3116
+ try {
3117
+ if (format !== 'compact')
3118
+ _sig = Signature.fromDER(sg);
3119
+ }
3120
+ catch (derError) {
3121
+ if (!(derError instanceof DER.Err))
3122
+ throw derError;
3123
+ }
3124
+ if (!_sig && format !== 'der')
3125
+ _sig = Signature.fromCompact(sg);
3126
+ }
3127
+ P = Point.fromHex(publicKey);
3128
+ }
3129
+ catch (error) {
3130
+ return false;
3131
+ }
3132
+ if (!_sig)
3133
+ return false;
3134
+ if (lowS && _sig.hasHighS())
3135
+ return false;
3136
+ if (prehash)
3137
+ msgHash = CURVE.hash(msgHash);
3138
+ const { r, s } = _sig;
3139
+ const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
3140
+ const is = invN(s); // s^-1
3141
+ const u1 = modN(h * is); // u1 = hs^-1 mod n
3142
+ const u2 = modN(r * is); // u2 = rs^-1 mod n
3143
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
3144
+ if (!R)
3145
+ return false;
3146
+ const v = modN(R.x);
3147
+ return v === r;
3148
+ }
3149
+ return {
3150
+ CURVE,
3151
+ getPublicKey,
3152
+ getSharedSecret,
3153
+ sign,
3154
+ verify,
3155
+ ProjectivePoint: Point,
3156
+ Signature,
3157
+ utils,
3158
+ };
3159
+ }
3160
+
3161
+ /**
3162
+ * Utilities for short weierstrass curves, combined with noble-hashes.
3163
+ * @module
3164
+ */
3165
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3166
+ /** connects noble-curves to noble-hashes */
3167
+ function getHash(hash) {
3168
+ return {
3169
+ hash,
3170
+ hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
3171
+ randomBytes,
3172
+ };
3173
+ }
3174
+ function createCurve(curveDef, defHash) {
3175
+ const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
3176
+ return { ...create(defHash), create };
3177
+ }
3178
+
3179
+ /**
3180
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
3181
+ *
3182
+ * Seems to be rigid (not backdoored)
3183
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
3184
+ *
3185
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3186
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3187
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3188
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
3189
+ * @module
3190
+ */
3191
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3192
+ const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
3193
+ const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
3194
+ const _1n = BigInt(1);
3195
+ const _2n = BigInt(2);
3196
+ const divNearest = (a, b) => (a + b / _2n) / b;
3197
+ /**
3198
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
3199
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
3200
+ */
3201
+ function sqrtMod(y) {
3202
+ const P = secp256k1P;
3203
+ // prettier-ignore
3204
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
3205
+ // prettier-ignore
3206
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
3207
+ const b2 = (y * y * y) % P; // x^3, 11
3208
+ const b3 = (b2 * b2 * y) % P; // x^7
3209
+ const b6 = (pow2(b3, _3n, P) * b3) % P;
3210
+ const b9 = (pow2(b6, _3n, P) * b3) % P;
3211
+ const b11 = (pow2(b9, _2n, P) * b2) % P;
3212
+ const b22 = (pow2(b11, _11n, P) * b11) % P;
3213
+ const b44 = (pow2(b22, _22n, P) * b22) % P;
3214
+ const b88 = (pow2(b44, _44n, P) * b44) % P;
3215
+ const b176 = (pow2(b88, _88n, P) * b88) % P;
3216
+ const b220 = (pow2(b176, _44n, P) * b44) % P;
3217
+ const b223 = (pow2(b220, _3n, P) * b3) % P;
3218
+ const t1 = (pow2(b223, _23n, P) * b22) % P;
3219
+ const t2 = (pow2(t1, _6n, P) * b2) % P;
3220
+ const root = pow2(t2, _2n, P);
3221
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3222
+ throw new Error('Cannot find square root');
3223
+ return root;
3224
+ }
3225
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3226
+ /**
3227
+ * secp256k1 curve, ECDSA and ECDH methods.
3228
+ *
3229
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
3230
+ *
3231
+ * @example
3232
+ * ```js
3233
+ * import { secp256k1 } from '@noble/curves/secp256k1';
3234
+ * const priv = secp256k1.utils.randomPrivateKey();
3235
+ * const pub = secp256k1.getPublicKey(priv);
3236
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
3237
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
3238
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
3239
+ * ```
3240
+ */
3241
+ const secp256k1 = createCurve({
3242
+ a: BigInt(0),
3243
+ b: BigInt(7),
3244
+ Fp: Fpk1,
3245
+ n: secp256k1N,
3246
+ Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
3247
+ Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
3248
+ h: BigInt(1),
3249
+ lowS: true, // Allow only low-S signatures by default in sign() and verify()
3250
+ endo: {
3251
+ // Endomorphism, see above
3252
+ beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
3253
+ splitScalar: (k) => {
3254
+ const n = secp256k1N;
3255
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
3256
+ const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
3257
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
3258
+ const b2 = a1;
3259
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
3260
+ const c1 = divNearest(b2 * k, n);
3261
+ const c2 = divNearest(-b1 * k, n);
3262
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
3263
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
3264
+ const k1neg = k1 > POW_2_128;
3265
+ const k2neg = k2 > POW_2_128;
3266
+ if (k1neg)
3267
+ k1 = n - k1;
3268
+ if (k2neg)
3269
+ k2 = n - k2;
3270
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
3271
+ throw new Error('splitScalar: Endomorphism failed, k=' + k);
3272
+ }
3273
+ return { k1neg, k1, k2neg, k2 };
3274
+ },
3275
+ },
3276
+ }, sha256);
3277
+ // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3278
+ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3279
+ BigInt(0);
3280
+ secp256k1.ProjectivePoint;
3281
+
94
3282
  /**
95
3283
  * signs the given message
96
- * we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
97
3284
  * @param {string} privateKey
98
3285
  * @param {string} hash
99
3286
  * @return {string} hexString
100
3287
  */
101
- function sign(privateKey, hash) {
102
- hash = addLeading0x(hash);
103
- if (hash.length !== 66)
104
- throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
105
- const sigObj = ecdsaSign(new Uint8Array(Buffer.from(removeLeading0x(hash), 'hex')), new Uint8Array(Buffer.from(removeLeading0x(privateKey), 'hex')));
106
- const recoveryId = sigObj.recid === 1 ? '1c' : '1b';
107
- const newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
3288
+ const sign = (privateKey, hash) => {
3289
+ const hashWith0x = addLeading0x(hash);
3290
+ if (hashWith0x.length !== 66 || !isHexString(hashWith0x))
3291
+ throw new Error('Can only sign hashes, given: ' + hash);
3292
+ const sigObj = secp256k1.sign(hexToBytes(stripHexPrefix(hash)), hexToBytes(stripHexPrefix(privateKey)));
3293
+ const recoveryId = sigObj.recovery === 1 ? '1c' : '1b';
3294
+ const newSignature = '0x' + sigObj.toCompactHex() + recoveryId;
108
3295
  return newSignature;
3296
+ };
3297
+ const hmacSha256Sign = (key, msg) => {
3298
+ const result = hmac(sha256, key, msg);
3299
+ return result;
3300
+ };
3301
+
3302
+ const sha512 = wrapHash(sha512$1);
3303
+
3304
+ function getRandomBytesSync(bytes) {
3305
+ return randomBytes(bytes);
109
3306
  }
110
3307
 
111
- function encryptWithPublicKey(publicKey, message, options) {
112
- // ensure its an uncompressed publicKey
113
- publicKey = decompress(publicKey);
114
- // re-add the compression-flag
115
- const pubString = '04' + publicKey;
116
- return encrypt(Buffer.from(pubString, 'hex'), Buffer.from(message), options ? options : {}).then((encryptedBuffers) => {
117
- const encrypted = {
118
- iv: encryptedBuffers.iv.toString('hex'),
119
- ephemPublicKey: encryptedBuffers.ephemPublicKey.toString('hex'),
120
- ciphertext: encryptedBuffers.ciphertext.toString('hex'),
121
- mac: encryptedBuffers.mac.toString('hex'),
3308
+ /**
3309
+ * Utilities for hex, bytes, CSPRNG.
3310
+ * @module
3311
+ */
3312
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3313
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
3314
+ function isBytes(a) {
3315
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3316
+ }
3317
+ /** Asserts something is Uint8Array. */
3318
+ function abytes(b, ...lengths) {
3319
+ if (!isBytes(b))
3320
+ throw new Error('Uint8Array expected');
3321
+ if (lengths.length > 0 && !lengths.includes(b.length))
3322
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3323
+ }
3324
+ /** Cast u8 / u16 / u32 to u8. */
3325
+ function u8(arr) {
3326
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3327
+ }
3328
+ /** Cast u8 / u16 / u32 to u32. */
3329
+ function u32(arr) {
3330
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3331
+ }
3332
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
3333
+ function clean(...arrays) {
3334
+ for (let i = 0; i < arrays.length; i++) {
3335
+ arrays[i].fill(0);
3336
+ }
3337
+ }
3338
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
3339
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
3340
+ /**
3341
+ * Checks if two U8A use same underlying buffer and overlaps.
3342
+ * This is invalid and can corrupt data.
3343
+ */
3344
+ function overlapBytes(a, b) {
3345
+ return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
3346
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
3347
+ b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
3348
+ );
3349
+ }
3350
+ /**
3351
+ * If input and output overlap and input starts before output, we will overwrite end of input before
3352
+ * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
3353
+ */
3354
+ function complexOverlapBytes(input, output) {
3355
+ // This is very cursed. It works somehow, but I'm completely unsure,
3356
+ // reasoning about overlapping aligned windows is very hard.
3357
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
3358
+ throw new Error('complex overlap of input and output is not supported');
3359
+ }
3360
+ /**
3361
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
3362
+ * @__NO_SIDE_EFFECTS__
3363
+ */
3364
+ const wrapCipher = (params, constructor) => {
3365
+ function wrappedCipher(key, ...args) {
3366
+ // Validate key
3367
+ abytes(key);
3368
+ // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
3369
+ if (!isLE)
3370
+ throw new Error('Non little-endian hardware is not yet supported');
3371
+ // Validate nonce if nonceLength is present
3372
+ if (params.nonceLength !== undefined) {
3373
+ const nonce = args[0];
3374
+ if (!nonce)
3375
+ throw new Error('nonce / iv required');
3376
+ if (params.varSizeNonce)
3377
+ abytes(nonce);
3378
+ else
3379
+ abytes(nonce, params.nonceLength);
3380
+ }
3381
+ // Validate AAD if tagLength present
3382
+ const tagl = params.tagLength;
3383
+ if (tagl && args[1] !== undefined) {
3384
+ abytes(args[1]);
3385
+ }
3386
+ const cipher = constructor(key, ...args);
3387
+ const checkOutput = (fnLength, output) => {
3388
+ if (output !== undefined) {
3389
+ if (fnLength !== 2)
3390
+ throw new Error('cipher output not supported');
3391
+ abytes(output);
3392
+ }
122
3393
  };
123
- return encrypted;
124
- });
3394
+ // Create wrapped cipher with validation and single-use encryption
3395
+ let called = false;
3396
+ const wrCipher = {
3397
+ encrypt(data, output) {
3398
+ if (called)
3399
+ throw new Error('cannot encrypt() twice with same key + nonce');
3400
+ called = true;
3401
+ abytes(data);
3402
+ checkOutput(cipher.encrypt.length, output);
3403
+ return cipher.encrypt(data, output);
3404
+ },
3405
+ decrypt(data, output) {
3406
+ abytes(data);
3407
+ if (tagl && data.length < tagl)
3408
+ throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
3409
+ checkOutput(cipher.decrypt.length, output);
3410
+ return cipher.decrypt(data, output);
3411
+ },
3412
+ };
3413
+ return wrCipher;
3414
+ }
3415
+ Object.assign(wrappedCipher, params);
3416
+ return wrappedCipher;
3417
+ };
3418
+ /**
3419
+ * By default, returns u8a of length.
3420
+ * When out is available, it checks it for validity and uses it.
3421
+ */
3422
+ function getOutput(expectedLength, out, onlyAligned = true) {
3423
+ if (out === undefined)
3424
+ return new Uint8Array(expectedLength);
3425
+ if (out.length !== expectedLength)
3426
+ throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
3427
+ if (onlyAligned && !isAligned32(out))
3428
+ throw new Error('invalid output, must be aligned');
3429
+ return out;
3430
+ }
3431
+ // Is byte array aligned to 4 byte offset (u32)?
3432
+ function isAligned32(bytes) {
3433
+ return bytes.byteOffset % 4 === 0;
3434
+ }
3435
+ // copy bytes to new u8a (aligned). Because Buffer.slice is broken.
3436
+ function copyBytes(bytes) {
3437
+ return Uint8Array.from(bytes);
125
3438
  }
126
3439
 
127
- function decryptWithPrivateKey(privateKey, encrypted) {
128
- const cipher = new Cipher();
129
- // ensuring the encrypted data is in the correct format.
130
- encrypted = cipher.parse(encrypted);
131
- // remove trailing '0x' from privateKey
132
- const twoStripped = removeLeading0x(privateKey);
133
- const encryptedBuffer = {
134
- iv: Buffer.from(encrypted.iv, 'hex'),
135
- ephemPublicKey: Buffer.from(encrypted.ephemPublicKey, 'hex'),
136
- ciphertext: Buffer.from(encrypted.ciphertext, 'hex'),
137
- mac: Buffer.from(encrypted.mac, 'hex'),
3440
+ /**
3441
+ * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
3442
+ * a.k.a. Advanced Encryption Standard
3443
+ * is a variant of Rijndael block cipher, standardized by NIST in 2001.
3444
+ * We provide the fastest available pure JS implementation.
3445
+ *
3446
+ * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
3447
+ * 1. **S-box**, table substitution
3448
+ * 2. **Shift rows**, cyclic shift left of all rows of data array
3449
+ * 3. **Mix columns**, multiplying every column by fixed polynomial
3450
+ * 4. **Add round key**, round_key xor i-th column of array
3451
+ *
3452
+ * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
3453
+ * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
3454
+ * @module
3455
+ */
3456
+ const BLOCK_SIZE = 16;
3457
+ const BLOCK_SIZE32 = 4;
3458
+ const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
3459
+ // TODO: remove multiplication, binary ops only
3460
+ function mul2(n) {
3461
+ return (n << 1) ^ (POLY & -(n >> 7));
3462
+ }
3463
+ function mul(a, b) {
3464
+ let res = 0;
3465
+ for (; b > 0; b >>= 1) {
3466
+ // Montgomery ladder
3467
+ res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
3468
+ a = mul2(a); // a = 2*a
3469
+ }
3470
+ return res;
3471
+ }
3472
+ // AES S-box is generated using finite field inversion,
3473
+ // an affine transform, and xor of a constant 0x63.
3474
+ const sbox = /* @__PURE__ */ (() => {
3475
+ const t = new Uint8Array(256);
3476
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
3477
+ t[i] = x;
3478
+ const box = new Uint8Array(256);
3479
+ box[0] = 0x63; // first elm
3480
+ for (let i = 0; i < 255; i++) {
3481
+ let x = t[255 - i];
3482
+ x |= x << 8;
3483
+ box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
3484
+ }
3485
+ clean(t);
3486
+ return box;
3487
+ })();
3488
+ // Inverted S-box
3489
+ const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
3490
+ // Rotate u32 by 8
3491
+ const rotr32_8 = (n) => (n << 24) | (n >>> 8);
3492
+ const rotl32_8 = (n) => (n << 8) | (n >>> 24);
3493
+ // T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
3494
+ // - LE instead of BE
3495
+ // - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
3496
+ // so index is u16, instead of u8. This speeds up things, unexpectedly
3497
+ function genTtable(sbox, fn) {
3498
+ if (sbox.length !== 256)
3499
+ throw new Error('Wrong sbox length');
3500
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
3501
+ const T1 = T0.map(rotl32_8);
3502
+ const T2 = T1.map(rotl32_8);
3503
+ const T3 = T2.map(rotl32_8);
3504
+ const T01 = new Uint32Array(256 * 256);
3505
+ const T23 = new Uint32Array(256 * 256);
3506
+ const sbox2 = new Uint16Array(256 * 256);
3507
+ for (let i = 0; i < 256; i++) {
3508
+ for (let j = 0; j < 256; j++) {
3509
+ const idx = i * 256 + j;
3510
+ T01[idx] = T0[i] ^ T1[j];
3511
+ T23[idx] = T2[i] ^ T3[j];
3512
+ sbox2[idx] = (sbox[i] << 8) | sbox[j];
3513
+ }
3514
+ }
3515
+ return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
3516
+ }
3517
+ const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
3518
+ const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
3519
+ const xPowers = /* @__PURE__ */ (() => {
3520
+ const p = new Uint8Array(16);
3521
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
3522
+ p[i] = x;
3523
+ return p;
3524
+ })();
3525
+ /** Key expansion used in CTR. */
3526
+ function expandKeyLE(key) {
3527
+ abytes(key);
3528
+ const len = key.length;
3529
+ if (![16, 24, 32].includes(len))
3530
+ throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
3531
+ const { sbox2 } = tableEncoding;
3532
+ const toClean = [];
3533
+ if (!isAligned32(key))
3534
+ toClean.push((key = copyBytes(key)));
3535
+ const k32 = u32(key);
3536
+ const Nk = k32.length;
3537
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
3538
+ const xk = new Uint32Array(len + 28); // expanded key
3539
+ xk.set(k32);
3540
+ // 4.3.1 Key expansion
3541
+ for (let i = Nk; i < xk.length; i++) {
3542
+ let t = xk[i - 1];
3543
+ if (i % Nk === 0)
3544
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
3545
+ else if (Nk > 6 && i % Nk === 4)
3546
+ t = subByte(t);
3547
+ xk[i] = xk[i - Nk] ^ t;
3548
+ }
3549
+ clean(...toClean);
3550
+ return xk;
3551
+ }
3552
+ function expandKeyDecLE(key) {
3553
+ const encKey = expandKeyLE(key);
3554
+ const xk = encKey.slice();
3555
+ const Nk = encKey.length;
3556
+ const { sbox2 } = tableEncoding;
3557
+ const { T0, T1, T2, T3 } = tableDecoding;
3558
+ // Inverse key by chunks of 4 (rounds)
3559
+ for (let i = 0; i < Nk; i += 4) {
3560
+ for (let j = 0; j < 4; j++)
3561
+ xk[i + j] = encKey[Nk - i - 4 + j];
3562
+ }
3563
+ clean(encKey);
3564
+ // apply InvMixColumn except first & last round
3565
+ for (let i = 4; i < Nk - 4; i++) {
3566
+ const x = xk[i];
3567
+ const w = applySbox(sbox2, x, x, x, x);
3568
+ xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
3569
+ }
3570
+ return xk;
3571
+ }
3572
+ // Apply tables
3573
+ function apply0123(T01, T23, s0, s1, s2, s3) {
3574
+ return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
3575
+ T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
3576
+ }
3577
+ function applySbox(sbox2, s0, s1, s2, s3) {
3578
+ return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
3579
+ (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
3580
+ }
3581
+ function encrypt(xk, s0, s1, s2, s3) {
3582
+ const { sbox2, T01, T23 } = tableEncoding;
3583
+ let k = 0;
3584
+ (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
3585
+ const rounds = xk.length / 4 - 2;
3586
+ for (let i = 0; i < rounds; i++) {
3587
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
3588
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
3589
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
3590
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
3591
+ (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
3592
+ }
3593
+ // last round (without mixcolumns, so using SBOX2 table)
3594
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
3595
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
3596
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
3597
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
3598
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
3599
+ }
3600
+ // Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
3601
+ function decrypt$2(xk, s0, s1, s2, s3) {
3602
+ const { sbox2, T01, T23 } = tableDecoding;
3603
+ let k = 0;
3604
+ (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
3605
+ const rounds = xk.length / 4 - 2;
3606
+ for (let i = 0; i < rounds; i++) {
3607
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
3608
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
3609
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
3610
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
3611
+ (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
3612
+ }
3613
+ // Last round
3614
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
3615
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
3616
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
3617
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
3618
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
3619
+ }
3620
+ // TODO: investigate merging with ctr32
3621
+ function ctrCounter(xk, nonce, src, dst) {
3622
+ abytes(nonce, BLOCK_SIZE);
3623
+ abytes(src);
3624
+ const srcLen = src.length;
3625
+ dst = getOutput(srcLen, dst);
3626
+ complexOverlapBytes(src, dst);
3627
+ const ctr = nonce;
3628
+ const c32 = u32(ctr);
3629
+ // Fill block (empty, ctr=0)
3630
+ let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
3631
+ const src32 = u32(src);
3632
+ const dst32 = u32(dst);
3633
+ // process blocks
3634
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
3635
+ dst32[i + 0] = src32[i + 0] ^ s0;
3636
+ dst32[i + 1] = src32[i + 1] ^ s1;
3637
+ dst32[i + 2] = src32[i + 2] ^ s2;
3638
+ dst32[i + 3] = src32[i + 3] ^ s3;
3639
+ // Full 128 bit counter with wrap around
3640
+ let carry = 1;
3641
+ for (let i = ctr.length - 1; i >= 0; i--) {
3642
+ carry = (carry + (ctr[i] & 0xff)) | 0;
3643
+ ctr[i] = carry & 0xff;
3644
+ carry >>>= 8;
3645
+ }
3646
+ ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
3647
+ }
3648
+ // leftovers (less than block)
3649
+ // It's possible to handle > u32 fast, but is it worth it?
3650
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
3651
+ if (start < srcLen) {
3652
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
3653
+ const buf = u8(b32);
3654
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
3655
+ dst[i] = src[i] ^ buf[pos];
3656
+ clean(b32);
3657
+ }
3658
+ return dst;
3659
+ }
3660
+ /**
3661
+ * CTR: counter mode. Creates stream cipher.
3662
+ * Requires good IV. Parallelizable. OK, but no MAC.
3663
+ */
3664
+ const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
3665
+ function processCtr(buf, dst) {
3666
+ abytes(buf);
3667
+ if (dst !== undefined) {
3668
+ abytes(dst);
3669
+ if (!isAligned32(dst))
3670
+ throw new Error('unaligned destination');
3671
+ }
3672
+ const xk = expandKeyLE(key);
3673
+ const n = copyBytes(nonce); // align + avoid changing
3674
+ const toClean = [xk, n];
3675
+ if (!isAligned32(buf))
3676
+ toClean.push((buf = copyBytes(buf)));
3677
+ const out = ctrCounter(xk, n, buf, dst);
3678
+ clean(...toClean);
3679
+ return out;
3680
+ }
3681
+ return {
3682
+ encrypt: (plaintext, dst) => processCtr(plaintext, dst),
3683
+ decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
138
3684
  };
139
- return decrypt(Buffer.from(twoStripped, 'hex'), encryptedBuffer).then((decryptedBuffer) => decryptedBuffer.toString());
3685
+ });
3686
+ function validateBlockDecrypt(data) {
3687
+ abytes(data);
3688
+ if (data.length % BLOCK_SIZE !== 0) {
3689
+ throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
3690
+ }
3691
+ }
3692
+ function validateBlockEncrypt(plaintext, pcks5, dst) {
3693
+ abytes(plaintext);
3694
+ let outLen = plaintext.length;
3695
+ const remaining = outLen % BLOCK_SIZE;
3696
+ if (!pcks5 && remaining !== 0)
3697
+ throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
3698
+ if (!isAligned32(plaintext))
3699
+ plaintext = copyBytes(plaintext);
3700
+ const b = u32(plaintext);
3701
+ if (pcks5) {
3702
+ let left = BLOCK_SIZE - remaining;
3703
+ if (!left)
3704
+ left = BLOCK_SIZE; // if no bytes left, create empty padding block
3705
+ outLen = outLen + left;
3706
+ }
3707
+ dst = getOutput(outLen, dst);
3708
+ complexOverlapBytes(plaintext, dst);
3709
+ const o = u32(dst);
3710
+ return { b, o, out: dst };
140
3711
  }
3712
+ function validatePCKS(data, pcks5) {
3713
+ if (!pcks5)
3714
+ return data;
3715
+ const len = data.length;
3716
+ if (!len)
3717
+ throw new Error('aes/pcks5: empty ciphertext not allowed');
3718
+ const lastByte = data[len - 1];
3719
+ if (lastByte <= 0 || lastByte > 16)
3720
+ throw new Error('aes/pcks5: wrong padding');
3721
+ const out = data.subarray(0, -lastByte);
3722
+ for (let i = 0; i < lastByte; i++)
3723
+ if (data[len - i - 1] !== lastByte)
3724
+ throw new Error('aes/pcks5: wrong padding');
3725
+ return out;
3726
+ }
3727
+ function padPCKS(left) {
3728
+ const tmp = new Uint8Array(16);
3729
+ const tmp32 = u32(tmp);
3730
+ tmp.set(left);
3731
+ const paddingByte = BLOCK_SIZE - left.length;
3732
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
3733
+ tmp[i] = paddingByte;
3734
+ return tmp32;
3735
+ }
3736
+ /**
3737
+ * CBC: Cipher-Block-Chaining. Key is previous round’s block.
3738
+ * Fragile: needs proper padding. Unauthenticated: needs MAC.
3739
+ */
3740
+ const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
3741
+ const pcks5 = !opts.disablePadding;
3742
+ return {
3743
+ encrypt(plaintext, dst) {
3744
+ const xk = expandKeyLE(key);
3745
+ const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
3746
+ let _iv = iv;
3747
+ const toClean = [xk];
3748
+ if (!isAligned32(_iv))
3749
+ toClean.push((_iv = copyBytes(_iv)));
3750
+ const n32 = u32(_iv);
3751
+ // prettier-ignore
3752
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
3753
+ let i = 0;
3754
+ for (; i + 4 <= b.length;) {
3755
+ (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
3756
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
3757
+ (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
3758
+ }
3759
+ if (pcks5) {
3760
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
3761
+ (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
3762
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
3763
+ (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
3764
+ }
3765
+ clean(...toClean);
3766
+ return _out;
3767
+ },
3768
+ decrypt(ciphertext, dst) {
3769
+ validateBlockDecrypt(ciphertext);
3770
+ const xk = expandKeyDecLE(key);
3771
+ let _iv = iv;
3772
+ const toClean = [xk];
3773
+ if (!isAligned32(_iv))
3774
+ toClean.push((_iv = copyBytes(_iv)));
3775
+ const n32 = u32(_iv);
3776
+ dst = getOutput(ciphertext.length, dst);
3777
+ if (!isAligned32(ciphertext))
3778
+ toClean.push((ciphertext = copyBytes(ciphertext)));
3779
+ complexOverlapBytes(ciphertext, dst);
3780
+ const b = u32(ciphertext);
3781
+ const o = u32(dst);
3782
+ // prettier-ignore
3783
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
3784
+ for (let i = 0; i + 4 <= b.length;) {
3785
+ // prettier-ignore
3786
+ const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
3787
+ (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
3788
+ const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$2(xk, s0, s1, s2, s3);
3789
+ (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
3790
+ }
3791
+ clean(...toClean);
3792
+ return validatePCKS(dst, pcks5);
3793
+ },
3794
+ };
3795
+ });
3796
+
3797
+ function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
3798
+ if (!mode.startsWith("aes-")) {
3799
+ throw new Error("AES: unsupported mode");
3800
+ }
3801
+ const len = key.length;
3802
+ if ((mode.startsWith("aes-128") && len !== 16) ||
3803
+ (mode.startsWith("aes-256") && len !== 32)) {
3804
+ throw new Error("AES: wrong key length");
3805
+ }
3806
+ if (iv.length !== 16) {
3807
+ throw new Error("AES: wrong IV length");
3808
+ }
3809
+ if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) {
3810
+ return cbc(key, iv, { disablePadding: !pkcs7PaddingEnabled });
3811
+ }
3812
+ if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) {
3813
+ return ctr(key, iv);
3814
+ }
3815
+ throw new Error("AES: unsupported mode");
3816
+ }
3817
+ function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
3818
+ return getCipher(key, iv, mode, pkcs7PaddingEnabled).decrypt(ciphertext);
3819
+ }
3820
+
3821
+ /**
3822
+ * Decrypts an encrypted message using the recipient's private key.
3823
+ * @param {string} privateKey - The recipient's private key.
3824
+ * @param {Encrypted} opts - The encrypted message.
3825
+ * @returns {string} The decrypted message.
3826
+ */
3827
+ const decrypt = (privateKey, opts) => {
3828
+ let sharedSecret;
3829
+ try {
3830
+ sharedSecret = secp256k1.getSharedSecret(hexToBytes(privateKey), opts.ephemPublicKey, true).slice(1);
3831
+ }
3832
+ catch (e) {
3833
+ throw new Error(`Invalid MAC: data integrity check failed: ${e}`);
3834
+ }
3835
+ const hash = sha512(sharedSecret);
3836
+ const encryptionKey = hash.subarray(0, 32);
3837
+ const macKey = hash.subarray(32);
3838
+ const ciphertext = hexToBytes(opts.ciphertext);
3839
+ const iv = hexToBytes(opts.iv);
3840
+ const ephemPublicKey = hexToBytes(opts.ephemPublicKey);
3841
+ const receivedMac = hexToBytes(opts.mac);
3842
+ // Recompute MAC
3843
+ const dataToMac = concatUint8Arrays([iv, ephemPublicKey, ciphertext]);
3844
+ const expectedMac = hmacSha256Sign(macKey, dataToMac);
3845
+ if (!constantTimeEqual(expectedMac, receivedMac)) {
3846
+ throw new Error('Invalid MAC: data integrity check failed');
3847
+ }
3848
+ const decrypted = decrypt$1(ciphertext, encryptionKey, iv, 'aes-256-cbc');
3849
+ return bytesToUtf8(decrypted);
3850
+ };
3851
+ /**
3852
+ * Compares two Uint8Arrays in constant time to prevent timing attacks.
3853
+ * @param {Uint8Array} a - The first array.
3854
+ * @param {Uint8Array} b - The second array.
3855
+ * @returns {boolean} True if the arrays are equal, false otherwise.
3856
+ */
3857
+ function constantTimeEqual(a, b) {
3858
+ if (a.length !== b.length)
3859
+ return false;
3860
+ let result = 0;
3861
+ for (let i = 0; i < a.length; i++) {
3862
+ result |= a[i] ^ b[i];
3863
+ }
3864
+ return result === 0;
3865
+ }
3866
+
3867
+ const decryptWithPrivateKey = (privateKey, encrypted) => {
3868
+ // remove '0x' from privateKey
3869
+ const twoStripped = stripHexPrefix(privateKey);
3870
+ return decrypt(twoStripped, encrypted);
3871
+ };
141
3872
 
142
3873
  /**
143
3874
  * Generate publicKey from the privateKey.
144
3875
  * This creates the uncompressed publicKey,
145
3876
  * where 04 has stripped from left
146
- * @param {string} privateKey
147
3877
  * @returns {string}
148
3878
  */
149
- function publicKeyByPrivateKey(privateKey) {
150
- privateKey = addLeading0x(privateKey);
151
- const publicKeyBuffer = privateToPublic(toBuffer(privateKey));
152
- return publicKeyBuffer.toString('hex');
153
- }
154
-
155
- const MIN_ENTROPY_SIZE = 128;
3879
+ const publicKeyByPrivateKey = (privateKey) => {
3880
+ const key = stripHexPrefix(privateKey);
3881
+ const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
3882
+ const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
3883
+ return decompress(bytesToHex(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
3884
+ };
156
3885
 
3886
+ const DEFAULT_ENTROPY_BYTES = 32;
3887
+ const MINIMUM_SHANNON_ENTROPY = 4;
157
3888
  /**
158
- * create a privateKey from the given entropy or a new one
159
- * @param {Buffer} entropy
160
- * @return {string}
3889
+ * creates a new private key
3890
+ * @param { Uint8Array } entropy - optional entropy to create the private key
3891
+ * @returns a new private key
161
3892
  */
162
- function createPrivateKey(entropy) {
3893
+ const createPrivateKey = (entropy) => {
163
3894
  if (entropy) {
164
- if (!Buffer.isBuffer(entropy))
165
- throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
166
- if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE)
167
- throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
168
- const outerHex = keccak256(entropy);
169
- return outerHex;
3895
+ if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3896
+ throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3897
+ }
3898
+ // Check byte diversity
3899
+ const uniqueBytes = new Set(entropy);
3900
+ if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3901
+ throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3902
+ }
3903
+ // Estimate Shannon entropy
3904
+ const byteCounts = new Uint32Array(256);
3905
+ entropy.forEach((b) => byteCounts[b]++);
3906
+ const total = entropy.length;
3907
+ let shannonEntropy = 0;
3908
+ for (let i = 0; i < 256; i++) {
3909
+ if (byteCounts[i] > 0) {
3910
+ const p = byteCounts[i] / total;
3911
+ shannonEntropy -= p * Math.log2(p);
3912
+ }
3913
+ }
3914
+ if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3915
+ throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3916
+ }
3917
+ const outerHex = keccak256$1(entropy);
3918
+ return addLeading0x(bytesToHex(outerHex));
170
3919
  }
171
3920
  else {
172
- const innerHex = keccak256(concat([randomBytes(32), randomBytes(32)]));
173
- const middleHex = concat([concat([randomBytes(32), innerHex]), randomBytes(32)]);
174
- const outerHex = keccak256(middleHex);
175
- return outerHex;
3921
+ const innerHex = keccak256$1(concatUint8Arrays([getRandomBytesSync(32), getRandomBytesSync(32)]));
3922
+ const middleHex = concatUint8Arrays([concatUint8Arrays([getRandomBytesSync(32), innerHex]), getRandomBytesSync(32)]);
3923
+ const outerHex = keccak256$1(middleHex);
3924
+ return addLeading0x(bytesToHex(outerHex));
176
3925
  }
177
- }
3926
+ };
178
3927
  /**
179
- * creates a new object with
180
- * private-, public-Key and address
181
- * @param {Buffer?} entropy if provided, will use that as single random-source
3928
+ * creates a new identity
3929
+ * @param { Uint8Array } entropy - optional entropy to create the private key
3930
+ * @returns a new pair of private and public key
182
3931
  */
183
- function createIdentity(entropy) {
3932
+ const createIdentity = (entropy) => {
184
3933
  const privateKey = createPrivateKey(entropy);
185
- const wallet = new Wallet(privateKey);
3934
+ const walletPublicKey = publicKeyByPrivateKey(privateKey);
186
3935
  const identity = {
187
3936
  privateKey: privateKey,
188
- publicKey: publicKeyByPrivateKey(privateKey),
189
- address: wallet.address,
3937
+ publicKey: stripHexPrefix(walletPublicKey),
190
3938
  };
191
3939
  return identity;
192
- }
3940
+ };
193
3941
 
194
- export { Cipher, Hash, addLeading0x, compress, createIdentity, createPrivateKey, decompress, decryptWithPrivateKey, encryptWithPublicKey, hexToUnit8Array, publicKeyByPrivateKey, removeLeading0x, sign, uint8ArrayToHex };
3942
+ export { DEFAULT_ENTROPY_BYTES, MINIMUM_SHANNON_ENTROPY, MIN_ENTROPY_SIZE, SIGN_PREFIX, createIdentity, createPrivateKey, decryptWithPrivateKey, hmacSha256Sign, keccak256, publicKeyByPrivateKey, sign };
195
3943
  //# sourceMappingURL=index.js.map