wallaby-cash 1.7.25 → 1.7.27

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.cjs.js CHANGED
@@ -112,77 +112,107 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
112
112
 
113
113
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
114
114
 
115
- function number(n) {
116
- if (!Number.isSafeInteger(n) || n < 0)
117
- throw new Error(`positive integer expected, not ${n}`);
118
- }
119
- function bool(b) {
120
- if (typeof b !== 'boolean')
121
- throw new Error(`boolean expected, not ${b}`);
122
- }
123
- // copied from utils
115
+ /**
116
+ * Utilities for hex, bytes, CSPRNG.
117
+ * @module
118
+ */
119
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
120
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
121
+ // node.js versions earlier than v19 don't declare it in global scope.
122
+ // For node.js, package.json#exports field mapping rewrites import
123
+ // from `crypto` to `cryptoNode`, which imports native module.
124
+ // Makes the utils un-importable in browsers without a bundler.
125
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
126
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
124
127
  function isBytes$2(a) {
125
- return (a instanceof Uint8Array ||
126
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
128
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
127
129
  }
128
- function bytes$1(b, ...lengths) {
130
+ /** Asserts something is positive integer. */
131
+ function anumber(n) {
132
+ if (!Number.isSafeInteger(n) || n < 0)
133
+ throw new Error('positive integer expected, got ' + n);
134
+ }
135
+ /** Asserts something is Uint8Array. */
136
+ function abytes$3(b, ...lengths) {
129
137
  if (!isBytes$2(b))
130
138
  throw new Error('Uint8Array expected');
131
139
  if (lengths.length > 0 && !lengths.includes(b.length))
132
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
140
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
133
141
  }
134
- function hash$1(h) {
142
+ /** Asserts something is hash */
143
+ function ahash(h) {
135
144
  if (typeof h !== 'function' || typeof h.create !== 'function')
136
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
137
- number(h.outputLen);
138
- number(h.blockLen);
145
+ throw new Error('Hash should be wrapped by utils.createHasher');
146
+ anumber(h.outputLen);
147
+ anumber(h.blockLen);
139
148
  }
140
- function exists(instance, checkFinished = true) {
149
+ /** Asserts a hash instance has not been destroyed / finished */
150
+ function aexists(instance, checkFinished = true) {
141
151
  if (instance.destroyed)
142
152
  throw new Error('Hash instance has been destroyed');
143
153
  if (checkFinished && instance.finished)
144
154
  throw new Error('Hash#digest() has already been called');
145
155
  }
146
- function output$1(out, instance) {
147
- bytes$1(out);
156
+ /** Asserts output is properly-sized byte array */
157
+ function aoutput(out, instance) {
158
+ abytes$3(out);
148
159
  const min = instance.outputLen;
149
160
  if (out.length < min) {
150
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
161
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
151
162
  }
152
163
  }
153
- const assert = { number, bool, bytes: bytes$1, hash: hash$1, exists, output: output$1 };
154
-
155
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
156
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
157
- // node.js versions earlier than v19 don't declare it in global scope.
158
- // For node.js, package.json#exports field mapping rewrites import
159
- // from `crypto` to `cryptoNode`, which imports native module.
160
- // Makes the utils un-importable in browsers without a bundler.
161
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
162
- const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
163
- // Cast array to view
164
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
165
- // The rotate right (circular right shift) operation for uint32
166
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
167
- const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
168
- // The byte swap operation for uint32
169
- const byteSwap = (word) => ((word << 24) & 0xff000000) |
170
- ((word << 8) & 0xff0000) |
171
- ((word >>> 8) & 0xff00) |
172
- ((word >>> 24) & 0xff);
173
- // In place byte swap for Uint32Array
164
+ /** Cast u8 / u16 / u32 to u32. */
165
+ function u32$1(arr) {
166
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
167
+ }
168
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
169
+ function clean$1(...arrays) {
170
+ for (let i = 0; i < arrays.length; i++) {
171
+ arrays[i].fill(0);
172
+ }
173
+ }
174
+ /** Create DataView of an array for easy byte-level manipulation. */
175
+ function createView(arr) {
176
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
177
+ }
178
+ /** The rotate right (circular right shift) operation for uint32 */
179
+ function rotr(word, shift) {
180
+ return (word << (32 - shift)) | (word >>> shift);
181
+ }
182
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
183
+ const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
184
+ /** The byte swap operation for uint32 */
185
+ function byteSwap(word) {
186
+ return (((word << 24) & 0xff000000) |
187
+ ((word << 8) & 0xff0000) |
188
+ ((word >>> 8) & 0xff00) |
189
+ ((word >>> 24) & 0xff));
190
+ }
191
+ /** In place byte swap for Uint32Array */
174
192
  function byteSwap32(arr) {
175
193
  for (let i = 0; i < arr.length; i++) {
176
194
  arr[i] = byteSwap(arr[i]);
177
195
  }
196
+ return arr;
178
197
  }
198
+ const swap32IfBE = isLE$1
199
+ ? (u) => u
200
+ : byteSwap32;
201
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
202
+ const hasHexBuiltin$1 = /* @__PURE__ */ (() =>
203
+ // @ts-ignore
204
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
179
205
  // Array where index 0xf0 (240) is mapped to string 'f0'
180
206
  const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
181
207
  /**
208
+ * Convert byte array to hex string. Uses built-in function, when available.
182
209
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
183
210
  */
184
211
  function bytesToHex$1(bytes) {
185
- bytes$1(bytes);
212
+ abytes$3(bytes);
213
+ // @ts-ignore
214
+ if (hasHexBuiltin$1)
215
+ return bytes.toHex();
186
216
  // pre-caching improves the speed 6x
187
217
  let hex = '';
188
218
  for (let i = 0; i < bytes.length; i++) {
@@ -191,26 +221,30 @@ function bytesToHex$1(bytes) {
191
221
  return hex;
192
222
  }
193
223
  // We use optimized technique to convert hex string to byte array
194
- const asciis$1 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
195
- function asciiToBase16$1(char) {
196
- if (char >= asciis$1._0 && char <= asciis$1._9)
197
- return char - asciis$1._0;
198
- if (char >= asciis$1._A && char <= asciis$1._F)
199
- return char - (asciis$1._A - 10);
200
- if (char >= asciis$1._a && char <= asciis$1._f)
201
- return char - (asciis$1._a - 10);
224
+ const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
225
+ function asciiToBase16$1(ch) {
226
+ if (ch >= asciis$1._0 && ch <= asciis$1._9)
227
+ return ch - asciis$1._0; // '2' => 50-48
228
+ if (ch >= asciis$1.A && ch <= asciis$1.F)
229
+ return ch - (asciis$1.A - 10); // 'B' => 66-(65-10)
230
+ if (ch >= asciis$1.a && ch <= asciis$1.f)
231
+ return ch - (asciis$1.a - 10); // 'b' => 98-(97-10)
202
232
  return;
203
233
  }
204
234
  /**
235
+ * Convert hex string to byte array. Uses built-in function, when available.
205
236
  * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
206
237
  */
207
238
  function hexToBytes$2(hex) {
208
239
  if (typeof hex !== 'string')
209
240
  throw new Error('hex string expected, got ' + typeof hex);
241
+ // @ts-ignore
242
+ if (hasHexBuiltin$1)
243
+ return Uint8Array.fromHex(hex);
210
244
  const hl = hex.length;
211
245
  const al = hl / 2;
212
246
  if (hl % 2)
213
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
247
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
214
248
  const array = new Uint8Array(al);
215
249
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
216
250
  const n1 = asciiToBase16$1(hex.charCodeAt(hi));
@@ -219,16 +253,17 @@ function hexToBytes$2(hex) {
219
253
  const char = hex[hi] + hex[hi + 1];
220
254
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
221
255
  }
222
- array[ai] = n1 * 16 + n2;
256
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
223
257
  }
224
258
  return array;
225
259
  }
226
260
  /**
227
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
261
+ * Converts string to bytes using UTF8 encoding.
262
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
228
263
  */
229
- function utf8ToBytes$2(str) {
264
+ function utf8ToBytes$1(str) {
230
265
  if (typeof str !== 'string')
231
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
266
+ throw new Error('string expected');
232
267
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
233
268
  }
234
269
  /**
@@ -238,18 +273,16 @@ function utf8ToBytes$2(str) {
238
273
  */
239
274
  function toBytes(data) {
240
275
  if (typeof data === 'string')
241
- data = utf8ToBytes$2(data);
242
- bytes$1(data);
276
+ data = utf8ToBytes$1(data);
277
+ abytes$3(data);
243
278
  return data;
244
279
  }
245
- /**
246
- * Copies several Uint8Arrays into one.
247
- */
280
+ /** Copies several Uint8Arrays into one. */
248
281
  function concatBytes$1(...arrays) {
249
282
  let sum = 0;
250
283
  for (let i = 0; i < arrays.length; i++) {
251
284
  const a = arrays[i];
252
- bytes$1(a);
285
+ abytes$3(a);
253
286
  sum += a.length;
254
287
  }
255
288
  const res = new Uint8Array(sum);
@@ -260,14 +293,11 @@ function concatBytes$1(...arrays) {
260
293
  }
261
294
  return res;
262
295
  }
263
- // For runtime check if class implements interface
296
+ /** For runtime check if class implements interface */
264
297
  class Hash {
265
- // Safe version that clones internal state
266
- clone() {
267
- return this._cloneInto();
268
- }
269
298
  }
270
- function wrapConstructor(hashCons) {
299
+ /** Wraps hash function, creating an interface on top of it */
300
+ function createHasher(hashCons) {
271
301
  const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
272
302
  const tmp = hashCons();
273
303
  hashC.outputLen = tmp.outputLen;
@@ -275,16 +305,14 @@ function wrapConstructor(hashCons) {
275
305
  hashC.create = () => hashCons();
276
306
  return hashC;
277
307
  }
278
- /**
279
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
280
- */
308
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
281
309
  function randomBytes(bytesLength = 32) {
282
310
  if (crypto && typeof crypto.getRandomValues === 'function') {
283
311
  return crypto.getRandomValues(new Uint8Array(bytesLength));
284
312
  }
285
313
  // Legacy Node.js compatibility
286
314
  if (crypto && typeof crypto.randomBytes === 'function') {
287
- return crypto.randomBytes(bytesLength);
315
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
288
316
  }
289
317
  throw new Error('crypto.getRandomValues must be defined');
290
318
  }
@@ -293,156 +321,464 @@ function getRandomBytesSync(bytes) {
293
321
  return randomBytes(bytes);
294
322
  }
295
323
 
296
- const assertBool = assert.bool;
297
- const assertBytes = assert.bytes;
298
- // buf.toString('utf8') -> bytesToUtf8(buf)
299
- function bytesToUtf8(data) {
300
- if (!(data instanceof Uint8Array)) {
301
- throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
302
- }
303
- return new TextDecoder().decode(data);
324
+ /**
325
+ * Hex, bytes and number utilities.
326
+ * @module
327
+ */
328
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
329
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
330
+ // This is OK: `abstract` directory does not use noble-hashes.
331
+ // User may opt-in into using different hashing library. This way, noble-hashes
332
+ // won't be included into their bundle.
333
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
334
+ const _1n$5 = /* @__PURE__ */ BigInt(1);
335
+ function isBytes$1(a) {
336
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
304
337
  }
305
- function hexToBytes$1(data) {
306
- const sliced = data.startsWith("0x") ? data.substring(2) : data;
307
- return hexToBytes$2(sliced);
338
+ function abytes$2(item) {
339
+ if (!isBytes$1(item))
340
+ throw new Error('Uint8Array expected');
308
341
  }
309
- // Internal utils
310
- function wrapHash(hash) {
311
- return (msg) => {
312
- assert.bytes(msg);
313
- return hash(msg);
314
- };
342
+ function abool(title, value) {
343
+ if (typeof value !== 'boolean')
344
+ throw new Error(title + ' boolean expected, got ' + value);
315
345
  }
316
-
346
+ // Used in weierstrass, der
347
+ function numberToHexUnpadded(num) {
348
+ const hex = num.toString(16);
349
+ return hex.length & 1 ? '0' + hex : hex;
350
+ }
351
+ function hexToNumber(hex) {
352
+ if (typeof hex !== 'string')
353
+ throw new Error('hex string expected, got ' + typeof hex);
354
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
355
+ }
356
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
357
+ const hasHexBuiltin =
358
+ // @ts-ignore
359
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
360
+ // Array where index 0xf0 (240) is mapped to string 'f0'
361
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
317
362
  /**
318
- * Returns a `Boolean` on whether or not the a `String` starts with '0x'
319
- * @param str the string input value
320
- * @return a boolean if it is or is not hex prefixed
321
- * @throws if the str input is not a string
363
+ * Convert byte array to hex string. Uses built-in function, when available.
364
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
322
365
  */
323
- var isHexPrefixed = function (str) {
324
- if (typeof str !== 'string') {
325
- throw new Error("[isHexPrefixed] input must be type 'string', received type ".concat(typeof str));
366
+ function bytesToHex(bytes) {
367
+ abytes$2(bytes);
368
+ // @ts-ignore
369
+ if (hasHexBuiltin)
370
+ return bytes.toHex();
371
+ // pre-caching improves the speed 6x
372
+ let hex = '';
373
+ for (let i = 0; i < bytes.length; i++) {
374
+ hex += hexes[bytes[i]];
326
375
  }
327
- return str[0] === '0' && str[1] === 'x';
328
- };
329
- /**
330
- * Removes '0x' from a given `String` if present
331
- * @param str the string value
332
- * @returns the string without 0x prefix
333
- */
334
- var stripHexPrefix = function (str) {
335
- if (typeof str !== 'string')
336
- throw new Error("[stripHexPrefix] input must be type 'string', received ".concat(typeof str));
337
- return isHexPrefixed(str) ? str.slice(2) : str;
338
- };
376
+ return hex;
377
+ }
378
+ // We use optimized technique to convert hex string to byte array
379
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
380
+ function asciiToBase16(ch) {
381
+ if (ch >= asciis._0 && ch <= asciis._9)
382
+ return ch - asciis._0; // '2' => 50-48
383
+ if (ch >= asciis.A && ch <= asciis.F)
384
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
385
+ if (ch >= asciis.a && ch <= asciis.f)
386
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
387
+ return;
388
+ }
339
389
  /**
340
- * Adds '0x' to a given `String` if not present
341
- * @param str the string input value
342
- * @return the string with a 0x prefix
390
+ * Convert hex string to byte array. Uses built-in function, when available.
391
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
343
392
  */
344
- var addLeading0x = function (str) {
345
- if (!str.startsWith('0x'))
346
- return '0x' + str;
347
- else
348
- return str;
349
- };
350
- var decompress = function (startsWith02Or03) {
351
- var testByteArray = hexToBytes$1(startsWith02Or03);
352
- var startsWith04 = startsWith02Or03;
353
- if (testByteArray.length === 64) {
354
- startsWith04 = '04' + startsWith02Or03;
393
+ function hexToBytes$1(hex) {
394
+ if (typeof hex !== 'string')
395
+ throw new Error('hex string expected, got ' + typeof hex);
396
+ // @ts-ignore
397
+ if (hasHexBuiltin)
398
+ return Uint8Array.fromHex(hex);
399
+ const hl = hex.length;
400
+ const al = hl / 2;
401
+ if (hl % 2)
402
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
403
+ const array = new Uint8Array(al);
404
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
405
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
406
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
407
+ if (n1 === undefined || n2 === undefined) {
408
+ const char = hex[hi] + hex[hi + 1];
409
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
410
+ }
411
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
355
412
  }
356
- return startsWith04.substring(2);
357
- };
358
- /** Helper function to concat UInt8Arrays mimicking the behaviour of the
359
- * Buffer.concat function in Node.js
360
- */
361
- var concatUint8Arrays = function (uint8arrays) {
362
- var totalLength = uint8arrays.reduce(function (total, uint8array) { return total + uint8array.byteLength; }, 0);
363
- var result = new Uint8Array(totalLength);
364
- var offset = 0;
365
- uint8arrays.forEach(function (uint8array) {
366
- result.set(uint8array, offset);
367
- offset += uint8array.byteLength;
368
- });
369
- return result;
370
- };
413
+ return array;
414
+ }
415
+ // BE: Big Endian, LE: Little Endian
416
+ function bytesToNumberBE(bytes) {
417
+ return hexToNumber(bytesToHex(bytes));
418
+ }
419
+ function bytesToNumberLE(bytes) {
420
+ abytes$2(bytes);
421
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
422
+ }
423
+ function numberToBytesBE(n, len) {
424
+ return hexToBytes$1(n.toString(16).padStart(len * 2, '0'));
425
+ }
426
+ function numberToBytesLE(n, len) {
427
+ return numberToBytesBE(n, len).reverse();
428
+ }
371
429
  /**
372
- * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
373
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
430
+ * Takes hex string or Uint8Array, converts to Uint8Array.
431
+ * Validates output length.
432
+ * Will throw error for other types.
433
+ * @param title descriptive title for an error e.g. 'private key'
434
+ * @param hex hex string or Uint8Array
435
+ * @param expectedLength optional, will compare to result array's length
436
+ * @returns
374
437
  */
375
- var utf8ToBytes$1 = function (str) {
376
- if (typeof str !== 'string')
377
- throw new Error("utf8ToBytes expected string, got ".concat(typeof str));
378
- var bytes = [];
379
- for (var i = 0; i < str.length; i++) {
380
- var codePoint = str.codePointAt(i);
381
- if (!codePoint) {
382
- throw new Error('Invalid code point');
383
- }
384
- if (codePoint < 0x80) {
385
- bytes.push(codePoint);
386
- }
387
- else if (codePoint < 0x800) {
388
- bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
389
- }
390
- else if (codePoint < 0x10000) {
391
- bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
438
+ function ensureBytes(title, hex, expectedLength) {
439
+ let res;
440
+ if (typeof hex === 'string') {
441
+ try {
442
+ res = hexToBytes$1(hex);
392
443
  }
393
- else {
394
- i++; // skip one iteration since we have a surrogate pair
395
- bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
444
+ catch (e) {
445
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
396
446
  }
397
447
  }
398
- return new Uint8Array(bytes);
399
- };
400
-
448
+ else if (isBytes$1(hex)) {
449
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
450
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
451
+ res = Uint8Array.from(hex);
452
+ }
453
+ else {
454
+ throw new Error(title + ' must be hex string or Uint8Array');
455
+ }
456
+ const len = res.length;
457
+ if (typeof expectedLength === 'number' && len !== expectedLength)
458
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
459
+ return res;
460
+ }
401
461
  /**
402
- * Polyfill for Safari 14
462
+ * Copies several Uint8Arrays into one.
403
463
  */
404
- function setBigUint64(view, byteOffset, value, isLE) {
405
- if (typeof view.setBigUint64 === 'function')
406
- return view.setBigUint64(byteOffset, value, isLE);
407
- const _32n = BigInt(32);
408
- const _u32_max = BigInt(0xffffffff);
409
- const wh = Number((value >> _32n) & _u32_max);
410
- const wl = Number(value & _u32_max);
411
- const h = isLE ? 4 : 0;
412
- const l = isLE ? 0 : 4;
413
- view.setUint32(byteOffset + h, wh, isLE);
414
- view.setUint32(byteOffset + l, wl, isLE);
464
+ function concatBytes(...arrays) {
465
+ let sum = 0;
466
+ for (let i = 0; i < arrays.length; i++) {
467
+ const a = arrays[i];
468
+ abytes$2(a);
469
+ sum += a.length;
470
+ }
471
+ const res = new Uint8Array(sum);
472
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
473
+ const a = arrays[i];
474
+ res.set(a, pad);
475
+ pad += a.length;
476
+ }
477
+ return res;
478
+ }
479
+ // Is positive bigint
480
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
481
+ function inRange(n, min, max) {
482
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
415
483
  }
416
484
  /**
417
- * Choice: a ? b : c
485
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
486
+ * @example
487
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
418
488
  */
419
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
489
+ function aInRange(title, n, min, max) {
490
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
491
+ // consider P=256n, min=0n, max=P
492
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
493
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
494
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
495
+ if (!inRange(n, min, max))
496
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
497
+ }
498
+ // Bit operations
420
499
  /**
421
- * Majority function, true if any two inputs is true
500
+ * Calculates amount of bits in a bigint.
501
+ * Same as `n.toString(2).length`
502
+ * TODO: merge with nLength in modular
422
503
  */
423
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
424
- /**
425
- * Merkle-Damgard hash construction base class.
426
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
504
+ function bitLen(n) {
505
+ let len;
506
+ for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
507
+ ;
508
+ return len;
509
+ }
510
+ /**
511
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
512
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
513
+ */
514
+ const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
515
+ // DRBG
516
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
517
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
518
+ /**
519
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
520
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
521
+ * @example
522
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
523
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
524
+ */
525
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
526
+ if (typeof hashLen !== 'number' || hashLen < 2)
527
+ throw new Error('hashLen must be a number');
528
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
529
+ throw new Error('qByteLen must be a number');
530
+ if (typeof hmacFn !== 'function')
531
+ throw new Error('hmacFn must be a function');
532
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
533
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
534
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
535
+ let i = 0; // Iterations counter, will throw when over 1000
536
+ const reset = () => {
537
+ v.fill(1);
538
+ k.fill(0);
539
+ i = 0;
540
+ };
541
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
542
+ const reseed = (seed = u8n(0)) => {
543
+ // HMAC-DRBG reseed() function. Steps D-G
544
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
545
+ v = h(); // v = hmac(k || v)
546
+ if (seed.length === 0)
547
+ return;
548
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
549
+ v = h(); // v = hmac(k || v)
550
+ };
551
+ const gen = () => {
552
+ // HMAC-DRBG generate() function
553
+ if (i++ >= 1000)
554
+ throw new Error('drbg: tried 1000 values');
555
+ let len = 0;
556
+ const out = [];
557
+ while (len < qByteLen) {
558
+ v = h();
559
+ const sl = v.slice();
560
+ out.push(sl);
561
+ len += v.length;
562
+ }
563
+ return concatBytes(...out);
564
+ };
565
+ const genUntil = (seed, pred) => {
566
+ reset();
567
+ reseed(seed); // Steps D-G
568
+ let res = undefined; // Step H: grind until k is in [1..n-1]
569
+ while (!(res = pred(gen())))
570
+ reseed();
571
+ reset();
572
+ return res;
573
+ };
574
+ return genUntil;
575
+ }
576
+ // Validating curves and fields
577
+ const validatorFns = {
578
+ bigint: (val) => typeof val === 'bigint',
579
+ function: (val) => typeof val === 'function',
580
+ boolean: (val) => typeof val === 'boolean',
581
+ string: (val) => typeof val === 'string',
582
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
583
+ isSafeInteger: (val) => Number.isSafeInteger(val),
584
+ array: (val) => Array.isArray(val),
585
+ field: (val, object) => object.Fp.isValid(val),
586
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
587
+ };
588
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
589
+ function validateObject(object, validators, optValidators = {}) {
590
+ const checkField = (fieldName, type, isOptional) => {
591
+ const checkVal = validatorFns[type];
592
+ if (typeof checkVal !== 'function')
593
+ throw new Error('invalid validator function');
594
+ const val = object[fieldName];
595
+ if (isOptional && val === undefined)
596
+ return;
597
+ if (!checkVal(val, object)) {
598
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
599
+ }
600
+ };
601
+ for (const [fieldName, type] of Object.entries(validators))
602
+ checkField(fieldName, type, false);
603
+ for (const [fieldName, type] of Object.entries(optValidators))
604
+ checkField(fieldName, type, true);
605
+ return object;
606
+ }
607
+ /**
608
+ * Memoizes (caches) computation result.
609
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
610
+ */
611
+ function memoized(fn) {
612
+ const map = new WeakMap();
613
+ return (arg, ...args) => {
614
+ const val = map.get(arg);
615
+ if (val !== undefined)
616
+ return val;
617
+ const computed = fn(arg, ...args);
618
+ map.set(arg, computed);
619
+ return computed;
620
+ };
621
+ }
622
+
623
+ /**
624
+ * Internal assertion helpers.
625
+ * @module
626
+ * @deprecated
627
+ */
628
+ /** @deprecated Use import from `noble/hashes/utils` module */
629
+ const abytes$1 = abytes$3;
630
+
631
+ // buf.toString('utf8') -> bytesToUtf8(buf)
632
+ function bytesToUtf8(data) {
633
+ if (!(data instanceof Uint8Array)) {
634
+ throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
635
+ }
636
+ return new TextDecoder().decode(data);
637
+ }
638
+ function hexToBytes(data) {
639
+ const sliced = data.startsWith("0x") ? data.substring(2) : data;
640
+ return hexToBytes$2(sliced);
641
+ }
642
+ // Internal utils
643
+ function wrapHash(hash) {
644
+ return (msg) => {
645
+ abytes$1(msg);
646
+ return hash(msg);
647
+ };
648
+ }
649
+
650
+ /**
651
+ * Returns a `Boolean` on whether or not the a `String` starts with '0x'
652
+ * @param str the string input value
653
+ * @return a boolean if it is or is not hex prefixed
654
+ * @throws if the str input is not a string
655
+ */
656
+ var isHexPrefixed = function (str) {
657
+ if (typeof str !== 'string') {
658
+ throw new Error("[isHexPrefixed] input must be type 'string', received type ".concat(typeof str));
659
+ }
660
+ return str[0] === '0' && str[1] === 'x';
661
+ };
662
+ /**
663
+ * Removes '0x' from a given `String` if present
664
+ * @param str the string value
665
+ * @returns the string without 0x prefix
666
+ */
667
+ var stripHexPrefix = function (str) {
668
+ if (typeof str !== 'string')
669
+ throw new Error("[stripHexPrefix] input must be type 'string', received ".concat(typeof str));
670
+ return isHexPrefixed(str) ? str.slice(2) : str;
671
+ };
672
+ /**
673
+ * Adds '0x' to a given `String` if not present
674
+ * @param str the string input value
675
+ * @return the string with a 0x prefix
676
+ */
677
+ var addLeading0x = function (str) {
678
+ if (!str.startsWith('0x'))
679
+ return '0x' + str;
680
+ else
681
+ return str;
682
+ };
683
+ var decompress = function (startsWith02Or03) {
684
+ var testByteArray = hexToBytes(startsWith02Or03);
685
+ var startsWith04 = startsWith02Or03;
686
+ if (testByteArray.length === 64) {
687
+ startsWith04 = '04' + startsWith02Or03;
688
+ }
689
+ return startsWith04.substring(2);
690
+ };
691
+ /** Helper function to concat UInt8Arrays mimicking the behaviour of the
692
+ * Buffer.concat function in Node.js
693
+ */
694
+ var concatUint8Arrays = function (uint8arrays) {
695
+ var totalLength = uint8arrays.reduce(function (total, uint8array) { return total + uint8array.byteLength; }, 0);
696
+ var result = new Uint8Array(totalLength);
697
+ var offset = 0;
698
+ uint8arrays.forEach(function (uint8array) {
699
+ result.set(uint8array, offset);
700
+ offset += uint8array.byteLength;
701
+ });
702
+ return result;
703
+ };
704
+ /**
705
+ * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
706
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
707
+ */
708
+ var utf8ToBytes = function (str) {
709
+ if (typeof str !== 'string')
710
+ throw new Error("utf8ToBytes expected string, got ".concat(typeof str));
711
+ var bytes = [];
712
+ for (var i = 0; i < str.length; i++) {
713
+ var codePoint = str.codePointAt(i);
714
+ if (!codePoint) {
715
+ throw new Error('Invalid code point');
716
+ }
717
+ if (codePoint < 0x80) {
718
+ bytes.push(codePoint);
719
+ }
720
+ else if (codePoint < 0x800) {
721
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
722
+ }
723
+ else if (codePoint < 0x10000) {
724
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
725
+ }
726
+ else {
727
+ i++; // skip one iteration since we have a surrogate pair
728
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
729
+ }
730
+ }
731
+ return new Uint8Array(bytes);
732
+ };
733
+
734
+ /**
735
+ * Internal Merkle-Damgard hash utils.
736
+ * @module
737
+ */
738
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
739
+ function setBigUint64(view, byteOffset, value, isLE) {
740
+ if (typeof view.setBigUint64 === 'function')
741
+ return view.setBigUint64(byteOffset, value, isLE);
742
+ const _32n = BigInt(32);
743
+ const _u32_max = BigInt(0xffffffff);
744
+ const wh = Number((value >> _32n) & _u32_max);
745
+ const wl = Number(value & _u32_max);
746
+ const h = isLE ? 4 : 0;
747
+ const l = isLE ? 0 : 4;
748
+ view.setUint32(byteOffset + h, wh, isLE);
749
+ view.setUint32(byteOffset + l, wl, isLE);
750
+ }
751
+ /** Choice: a ? b : c */
752
+ function Chi(a, b, c) {
753
+ return (a & b) ^ (~a & c);
754
+ }
755
+ /** Majority function, true if any two inputs is true. */
756
+ function Maj(a, b, c) {
757
+ return (a & b) ^ (a & c) ^ (b & c);
758
+ }
759
+ /**
760
+ * Merkle-Damgard hash construction base class.
761
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
427
762
  */
428
763
  class HashMD extends Hash {
429
764
  constructor(blockLen, outputLen, padOffset, isLE) {
430
765
  super();
431
- this.blockLen = blockLen;
432
- this.outputLen = outputLen;
433
- this.padOffset = padOffset;
434
- this.isLE = isLE;
435
766
  this.finished = false;
436
767
  this.length = 0;
437
768
  this.pos = 0;
438
769
  this.destroyed = false;
770
+ this.blockLen = blockLen;
771
+ this.outputLen = outputLen;
772
+ this.padOffset = padOffset;
773
+ this.isLE = isLE;
439
774
  this.buffer = new Uint8Array(blockLen);
440
775
  this.view = createView(this.buffer);
441
776
  }
442
777
  update(data) {
443
- exists(this);
444
- const { view, buffer, blockLen } = this;
778
+ aexists(this);
445
779
  data = toBytes(data);
780
+ abytes$3(data);
781
+ const { view, buffer, blockLen } = this;
446
782
  const len = data.length;
447
783
  for (let pos = 0; pos < len;) {
448
784
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -466,8 +802,8 @@ class HashMD extends Hash {
466
802
  return this;
467
803
  }
468
804
  digestInto(out) {
469
- exists(this);
470
- output$1(out, this);
805
+ aexists(this);
806
+ aoutput(out, this);
471
807
  this.finished = true;
472
808
  // Padding
473
809
  // We can avoid allocation of buffer for padding completely if it
@@ -476,7 +812,7 @@ class HashMD extends Hash {
476
812
  let { pos } = this;
477
813
  // append the bit '1' to the message
478
814
  buffer[pos++] = 0b10000000;
479
- this.buffer.subarray(pos).fill(0);
815
+ clean$1(this.buffer.subarray(pos));
480
816
  // we have less than padOffset left in buffer, so we cannot put length in
481
817
  // current block, need process it and pad again
482
818
  if (this.padOffset > blockLen - pos) {
@@ -514,22 +850,96 @@ class HashMD extends Hash {
514
850
  to || (to = new this.constructor());
515
851
  to.set(...this.get());
516
852
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
853
+ to.destroyed = destroyed;
854
+ to.finished = finished;
517
855
  to.length = length;
518
856
  to.pos = pos;
519
- to.finished = finished;
520
- to.destroyed = destroyed;
521
857
  if (length % blockLen)
522
858
  to.buffer.set(buffer);
523
859
  return to;
524
860
  }
861
+ clone() {
862
+ return this._cloneInto();
863
+ }
525
864
  }
865
+ /**
866
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
867
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
868
+ */
869
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
870
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
871
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
872
+ ]);
873
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
874
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
875
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
876
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
877
+ ]);
526
878
 
527
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
528
- // BTC network is doing 2^67 hashes/sec as per early 2023.
529
- // Round constants:
530
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
879
+ /**
880
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
881
+ * @todo re-check https://issues.chromium.org/issues/42212588
882
+ * @module
883
+ */
884
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
885
+ const _32n = /* @__PURE__ */ BigInt(32);
886
+ function fromBig(n, le = false) {
887
+ if (le)
888
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
889
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
890
+ }
891
+ function split(lst, le = false) {
892
+ const len = lst.length;
893
+ let Ah = new Uint32Array(len);
894
+ let Al = new Uint32Array(len);
895
+ for (let i = 0; i < len; i++) {
896
+ const { h, l } = fromBig(lst[i], le);
897
+ [Ah[i], Al[i]] = [h, l];
898
+ }
899
+ return [Ah, Al];
900
+ }
901
+ // for Shift in [0, 32)
902
+ const shrSH = (h, _l, s) => h >>> s;
903
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
904
+ // Right rotate for Shift in [1, 32)
905
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
906
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
907
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
908
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
909
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
910
+ // Left rotate for Shift in [1, 32)
911
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
912
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
913
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
914
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
915
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
916
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
917
+ // simple take carry out of low bit sum by shift, we need to use division.
918
+ function add(Ah, Al, Bh, Bl) {
919
+ const l = (Al >>> 0) + (Bl >>> 0);
920
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
921
+ }
922
+ // Addition with more than 2 elements
923
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
924
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
925
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
926
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
927
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
928
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
929
+
930
+ /**
931
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
932
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
933
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
934
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
935
+ * @module
936
+ */
937
+ /**
938
+ * Round constants:
939
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
940
+ */
531
941
  // prettier-ignore
532
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
942
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
533
943
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
534
944
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
535
945
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -539,18 +949,11 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
539
949
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
540
950
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
541
951
  ]);
542
- // Initial state:
543
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
544
- // prettier-ignore
545
- const SHA256_IV = /* @__PURE__ */ new Uint32Array([
546
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
547
- ]);
548
- // Temporary buffer, not used to store anything between runs
549
- // Named this way because it matches specification.
952
+ /** Reusable temporary buffer. "W" comes straight from spec. */
550
953
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
551
954
  class SHA256 extends HashMD {
552
- constructor() {
553
- super(64, 32, 8, false);
955
+ constructor(outputLen = 32) {
956
+ super(64, outputLen, 8, false);
554
957
  // We cannot use array here since array allows indexing by variable
555
958
  // which means optimizer/compiler cannot use registers.
556
959
  this.A = SHA256_IV[0] | 0;
@@ -616,26 +1019,190 @@ class SHA256 extends HashMD {
616
1019
  this.set(A, B, C, D, E, F, G, H);
617
1020
  }
618
1021
  roundClean() {
619
- SHA256_W.fill(0);
1022
+ clean$1(SHA256_W);
620
1023
  }
621
1024
  destroy() {
622
1025
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
623
- this.buffer.fill(0);
1026
+ clean$1(this.buffer);
1027
+ }
1028
+ }
1029
+ // SHA2-512 is slower than sha256 in js because u64 operations are slow.
1030
+ // Round contants
1031
+ // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
1032
+ // prettier-ignore
1033
+ const K512 = /* @__PURE__ */ (() => split([
1034
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
1035
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
1036
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
1037
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
1038
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
1039
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
1040
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
1041
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
1042
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
1043
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
1044
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
1045
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
1046
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
1047
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
1048
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
1049
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
1050
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
1051
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
1052
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
1053
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
1054
+ ].map(n => BigInt(n))))();
1055
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1056
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1057
+ // Reusable temporary buffers
1058
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1059
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1060
+ class SHA512 extends HashMD {
1061
+ constructor(outputLen = 64) {
1062
+ super(128, outputLen, 16, false);
1063
+ // We cannot use array here since array allows indexing by variable
1064
+ // which means optimizer/compiler cannot use registers.
1065
+ // h -- high 32 bits, l -- low 32 bits
1066
+ this.Ah = SHA512_IV[0] | 0;
1067
+ this.Al = SHA512_IV[1] | 0;
1068
+ this.Bh = SHA512_IV[2] | 0;
1069
+ this.Bl = SHA512_IV[3] | 0;
1070
+ this.Ch = SHA512_IV[4] | 0;
1071
+ this.Cl = SHA512_IV[5] | 0;
1072
+ this.Dh = SHA512_IV[6] | 0;
1073
+ this.Dl = SHA512_IV[7] | 0;
1074
+ this.Eh = SHA512_IV[8] | 0;
1075
+ this.El = SHA512_IV[9] | 0;
1076
+ this.Fh = SHA512_IV[10] | 0;
1077
+ this.Fl = SHA512_IV[11] | 0;
1078
+ this.Gh = SHA512_IV[12] | 0;
1079
+ this.Gl = SHA512_IV[13] | 0;
1080
+ this.Hh = SHA512_IV[14] | 0;
1081
+ this.Hl = SHA512_IV[15] | 0;
1082
+ }
1083
+ // prettier-ignore
1084
+ get() {
1085
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1086
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1087
+ }
1088
+ // prettier-ignore
1089
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1090
+ this.Ah = Ah | 0;
1091
+ this.Al = Al | 0;
1092
+ this.Bh = Bh | 0;
1093
+ this.Bl = Bl | 0;
1094
+ this.Ch = Ch | 0;
1095
+ this.Cl = Cl | 0;
1096
+ this.Dh = Dh | 0;
1097
+ this.Dl = Dl | 0;
1098
+ this.Eh = Eh | 0;
1099
+ this.El = El | 0;
1100
+ this.Fh = Fh | 0;
1101
+ this.Fl = Fl | 0;
1102
+ this.Gh = Gh | 0;
1103
+ this.Gl = Gl | 0;
1104
+ this.Hh = Hh | 0;
1105
+ this.Hl = Hl | 0;
1106
+ }
1107
+ process(view, offset) {
1108
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
1109
+ for (let i = 0; i < 16; i++, offset += 4) {
1110
+ SHA512_W_H[i] = view.getUint32(offset);
1111
+ SHA512_W_L[i] = view.getUint32((offset += 4));
1112
+ }
1113
+ for (let i = 16; i < 80; i++) {
1114
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
1115
+ const W15h = SHA512_W_H[i - 15] | 0;
1116
+ const W15l = SHA512_W_L[i - 15] | 0;
1117
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1118
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1119
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
1120
+ const W2h = SHA512_W_H[i - 2] | 0;
1121
+ const W2l = SHA512_W_L[i - 2] | 0;
1122
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1123
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1124
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
1125
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1126
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1127
+ SHA512_W_H[i] = SUMh | 0;
1128
+ SHA512_W_L[i] = SUMl | 0;
1129
+ }
1130
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1131
+ // Compression function main loop, 80 rounds
1132
+ for (let i = 0; i < 80; i++) {
1133
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
1134
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1135
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1136
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1137
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
1138
+ const CHIl = (El & Fl) ^ (~El & Gl);
1139
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
1140
+ // prettier-ignore
1141
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1142
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1143
+ const T1l = T1ll | 0;
1144
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
1145
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1146
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1147
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
1148
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
1149
+ Hh = Gh | 0;
1150
+ Hl = Gl | 0;
1151
+ Gh = Fh | 0;
1152
+ Gl = Fl | 0;
1153
+ Fh = Eh | 0;
1154
+ Fl = El | 0;
1155
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1156
+ Dh = Ch | 0;
1157
+ Dl = Cl | 0;
1158
+ Ch = Bh | 0;
1159
+ Cl = Bl | 0;
1160
+ Bh = Ah | 0;
1161
+ Bl = Al | 0;
1162
+ const All = add3L(T1l, sigma0l, MAJl);
1163
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1164
+ Al = All | 0;
1165
+ }
1166
+ // Add the compressed chunk to the current hash value
1167
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1168
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1169
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1170
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1171
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1172
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1173
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1174
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1175
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1176
+ }
1177
+ roundClean() {
1178
+ clean$1(SHA512_W_H, SHA512_W_L);
1179
+ }
1180
+ destroy() {
1181
+ clean$1(this.buffer);
1182
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
624
1183
  }
625
1184
  }
626
1185
  /**
627
- * SHA2-256 hash function
628
- * @param message - data that would be hashed
1186
+ * SHA2-256 hash function from RFC 4634.
1187
+ *
1188
+ * It is the fastest JS hash, even faster than Blake3.
1189
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1190
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
629
1191
  */
630
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1192
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
1193
+ /** SHA2-512 hash function from RFC 4634. */
1194
+ const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
631
1195
 
632
- // HMAC (RFC 2104)
1196
+ /**
1197
+ * HMAC: RFC2104 message authentication code.
1198
+ * @module
1199
+ */
633
1200
  class HMAC extends Hash {
634
1201
  constructor(hash, _key) {
635
1202
  super();
636
1203
  this.finished = false;
637
1204
  this.destroyed = false;
638
- hash$1(hash);
1205
+ ahash(hash);
639
1206
  const key = toBytes(_key);
640
1207
  this.iHash = hash.create();
641
1208
  if (typeof this.iHash.update !== 'function')
@@ -652,460 +1219,82 @@ class HMAC extends Hash {
652
1219
  // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
653
1220
  this.oHash = hash.create();
654
1221
  // Undo internal XOR && apply outer XOR
655
- for (let i = 0; i < pad.length; i++)
656
- pad[i] ^= 0x36 ^ 0x5c;
657
- this.oHash.update(pad);
658
- pad.fill(0);
659
- }
660
- update(buf) {
661
- exists(this);
662
- this.iHash.update(buf);
663
- return this;
664
- }
665
- digestInto(out) {
666
- exists(this);
667
- bytes$1(out, this.outputLen);
668
- this.finished = true;
669
- this.iHash.digestInto(out);
670
- this.oHash.update(out);
671
- this.oHash.digestInto(out);
672
- this.destroy();
673
- }
674
- digest() {
675
- const out = new Uint8Array(this.oHash.outputLen);
676
- this.digestInto(out);
677
- return out;
678
- }
679
- _cloneInto(to) {
680
- // Create new instance without calling constructor since key already in state and we don't know it.
681
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
682
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
683
- to = to;
684
- to.finished = finished;
685
- to.destroyed = destroyed;
686
- to.blockLen = blockLen;
687
- to.outputLen = outputLen;
688
- to.oHash = oHash._cloneInto(to.oHash);
689
- to.iHash = iHash._cloneInto(to.iHash);
690
- return to;
691
- }
692
- destroy() {
693
- this.destroyed = true;
694
- this.oHash.destroy();
695
- this.iHash.destroy();
696
- }
697
- }
698
- /**
699
- * HMAC: RFC2104 message authentication code.
700
- * @param hash - function that would be used e.g. sha256
701
- * @param key - message key
702
- * @param message - message data
703
- * @example
704
- * import { hmac } from '@noble/hashes/hmac';
705
- * import { sha256 } from '@noble/hashes/sha2';
706
- * const mac1 = hmac(sha256, 'key', 'message');
707
- */
708
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
709
- hmac.create = (hash, key) => new HMAC(hash, key);
710
-
711
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
712
- // 100 lines of code in the file are duplicated from noble-hashes (utils).
713
- // This is OK: `abstract` directory does not use noble-hashes.
714
- // User may opt-in into using different hashing library. This way, noble-hashes
715
- // won't be included into their bundle.
716
- const _0n$4 = /* @__PURE__ */ BigInt(0);
717
- const _1n$5 = /* @__PURE__ */ BigInt(1);
718
- const _2n$3 = /* @__PURE__ */ BigInt(2);
719
- function isBytes$1(a) {
720
- return (a instanceof Uint8Array ||
721
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
722
- }
723
- function abytes(item) {
724
- if (!isBytes$1(item))
725
- throw new Error('Uint8Array expected');
726
- }
727
- function abool(title, value) {
728
- if (typeof value !== 'boolean')
729
- throw new Error(`${title} must be valid boolean, got "${value}".`);
730
- }
731
- // Array where index 0xf0 (240) is mapped to string 'f0'
732
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
733
- /**
734
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
735
- */
736
- function bytesToHex(bytes) {
737
- abytes(bytes);
738
- // pre-caching improves the speed 6x
739
- let hex = '';
740
- for (let i = 0; i < bytes.length; i++) {
741
- hex += hexes[bytes[i]];
742
- }
743
- return hex;
744
- }
745
- function numberToHexUnpadded(num) {
746
- const hex = num.toString(16);
747
- return hex.length & 1 ? `0${hex}` : hex;
748
- }
749
- function hexToNumber(hex) {
750
- if (typeof hex !== 'string')
751
- throw new Error('hex string expected, got ' + typeof hex);
752
- // Big Endian
753
- return BigInt(hex === '' ? '0' : `0x${hex}`);
754
- }
755
- // We use optimized technique to convert hex string to byte array
756
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
757
- function asciiToBase16(char) {
758
- if (char >= asciis._0 && char <= asciis._9)
759
- return char - asciis._0;
760
- if (char >= asciis._A && char <= asciis._F)
761
- return char - (asciis._A - 10);
762
- if (char >= asciis._a && char <= asciis._f)
763
- return char - (asciis._a - 10);
764
- return;
765
- }
766
- /**
767
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
768
- */
769
- function hexToBytes(hex) {
770
- if (typeof hex !== 'string')
771
- throw new Error('hex string expected, got ' + typeof hex);
772
- const hl = hex.length;
773
- const al = hl / 2;
774
- if (hl % 2)
775
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
776
- const array = new Uint8Array(al);
777
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
778
- const n1 = asciiToBase16(hex.charCodeAt(hi));
779
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
780
- if (n1 === undefined || n2 === undefined) {
781
- const char = hex[hi] + hex[hi + 1];
782
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
783
- }
784
- array[ai] = n1 * 16 + n2;
785
- }
786
- return array;
787
- }
788
- // BE: Big Endian, LE: Little Endian
789
- function bytesToNumberBE(bytes) {
790
- return hexToNumber(bytesToHex(bytes));
791
- }
792
- function bytesToNumberLE(bytes) {
793
- abytes(bytes);
794
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
795
- }
796
- function numberToBytesBE(n, len) {
797
- return hexToBytes(n.toString(16).padStart(len * 2, '0'));
798
- }
799
- function numberToBytesLE(n, len) {
800
- return numberToBytesBE(n, len).reverse();
801
- }
802
- // Unpadded, rarely used
803
- function numberToVarBytesBE(n) {
804
- return hexToBytes(numberToHexUnpadded(n));
805
- }
806
- /**
807
- * Takes hex string or Uint8Array, converts to Uint8Array.
808
- * Validates output length.
809
- * Will throw error for other types.
810
- * @param title descriptive title for an error e.g. 'private key'
811
- * @param hex hex string or Uint8Array
812
- * @param expectedLength optional, will compare to result array's length
813
- * @returns
814
- */
815
- function ensureBytes(title, hex, expectedLength) {
816
- let res;
817
- if (typeof hex === 'string') {
818
- try {
819
- res = hexToBytes(hex);
820
- }
821
- catch (e) {
822
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
823
- }
824
- }
825
- else if (isBytes$1(hex)) {
826
- // Uint8Array.from() instead of hash.slice() because node.js Buffer
827
- // is instance of Uint8Array, and its slice() creates **mutable** copy
828
- res = Uint8Array.from(hex);
829
- }
830
- else {
831
- throw new Error(`${title} must be hex string or Uint8Array`);
832
- }
833
- const len = res.length;
834
- if (typeof expectedLength === 'number' && len !== expectedLength)
835
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
836
- return res;
837
- }
838
- /**
839
- * Copies several Uint8Arrays into one.
840
- */
841
- function concatBytes(...arrays) {
842
- let sum = 0;
843
- for (let i = 0; i < arrays.length; i++) {
844
- const a = arrays[i];
845
- abytes(a);
846
- sum += a.length;
847
- }
848
- const res = new Uint8Array(sum);
849
- for (let i = 0, pad = 0; i < arrays.length; i++) {
850
- const a = arrays[i];
851
- res.set(a, pad);
852
- pad += a.length;
853
- }
854
- return res;
855
- }
856
- // Compares 2 u8a-s in kinda constant time
857
- function equalBytes(a, b) {
858
- if (a.length !== b.length)
859
- return false;
860
- let diff = 0;
861
- for (let i = 0; i < a.length; i++)
862
- diff |= a[i] ^ b[i];
863
- return diff === 0;
864
- }
865
- /**
866
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
867
- */
868
- function utf8ToBytes(str) {
869
- if (typeof str !== 'string')
870
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
871
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
872
- }
873
- // Is positive bigint
874
- const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
875
- function inRange(n, min, max) {
876
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
877
- }
878
- /**
879
- * Asserts min <= n < max. NOTE: It's < max and not <= max.
880
- * @example
881
- * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
882
- */
883
- function aInRange(title, n, min, max) {
884
- // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
885
- // consider P=256n, min=0n, max=P
886
- // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
887
- // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
888
- // - our way is the cleanest: `inRange('x', x, 0n, P)
889
- if (!inRange(n, min, max))
890
- throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
891
- }
892
- // Bit operations
893
- /**
894
- * Calculates amount of bits in a bigint.
895
- * Same as `n.toString(2).length`
896
- */
897
- function bitLen(n) {
898
- let len;
899
- for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
900
- ;
901
- return len;
902
- }
903
- /**
904
- * Gets single bit at position.
905
- * NOTE: first bit position is 0 (same as arrays)
906
- * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
907
- */
908
- function bitGet(n, pos) {
909
- return (n >> BigInt(pos)) & _1n$5;
910
- }
911
- /**
912
- * Sets single bit at position.
913
- */
914
- function bitSet(n, pos, value) {
915
- return n | ((value ? _1n$5 : _0n$4) << BigInt(pos));
916
- }
917
- /**
918
- * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
919
- * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
920
- */
921
- const bitMask = (n) => (_2n$3 << BigInt(n - 1)) - _1n$5;
922
- // DRBG
923
- const u8n = (data) => new Uint8Array(data); // creates Uint8Array
924
- const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
925
- /**
926
- * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
927
- * @returns function that will call DRBG until 2nd arg returns something meaningful
928
- * @example
929
- * const drbg = createHmacDRBG<Key>(32, 32, hmac);
930
- * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
931
- */
932
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
933
- if (typeof hashLen !== 'number' || hashLen < 2)
934
- throw new Error('hashLen must be a number');
935
- if (typeof qByteLen !== 'number' || qByteLen < 2)
936
- throw new Error('qByteLen must be a number');
937
- if (typeof hmacFn !== 'function')
938
- throw new Error('hmacFn must be a function');
939
- // Step B, Step C: set hashLen to 8*ceil(hlen/8)
940
- let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
941
- let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
942
- let i = 0; // Iterations counter, will throw when over 1000
943
- const reset = () => {
944
- v.fill(1);
945
- k.fill(0);
946
- i = 0;
947
- };
948
- const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
949
- const reseed = (seed = u8n()) => {
950
- // HMAC-DRBG reseed() function. Steps D-G
951
- k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
952
- v = h(); // v = hmac(k || v)
953
- if (seed.length === 0)
954
- return;
955
- k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
956
- v = h(); // v = hmac(k || v)
957
- };
958
- const gen = () => {
959
- // HMAC-DRBG generate() function
960
- if (i++ >= 1000)
961
- throw new Error('drbg: tried 1000 values');
962
- let len = 0;
963
- const out = [];
964
- while (len < qByteLen) {
965
- v = h();
966
- const sl = v.slice();
967
- out.push(sl);
968
- len += v.length;
969
- }
970
- return concatBytes(...out);
971
- };
972
- const genUntil = (seed, pred) => {
973
- reset();
974
- reseed(seed); // Steps D-G
975
- let res = undefined; // Step H: grind until k is in [1..n-1]
976
- while (!(res = pred(gen())))
977
- reseed();
978
- reset();
979
- return res;
980
- };
981
- return genUntil;
982
- }
983
- // Validating curves and fields
984
- const validatorFns = {
985
- bigint: (val) => typeof val === 'bigint',
986
- function: (val) => typeof val === 'function',
987
- boolean: (val) => typeof val === 'boolean',
988
- string: (val) => typeof val === 'string',
989
- stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
990
- isSafeInteger: (val) => Number.isSafeInteger(val),
991
- array: (val) => Array.isArray(val),
992
- field: (val, object) => object.Fp.isValid(val),
993
- hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
994
- };
995
- // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
996
- function validateObject(object, validators, optValidators = {}) {
997
- const checkField = (fieldName, type, isOptional) => {
998
- const checkVal = validatorFns[type];
999
- if (typeof checkVal !== 'function')
1000
- throw new Error(`Invalid validator "${type}", expected function`);
1001
- const val = object[fieldName];
1002
- if (isOptional && val === undefined)
1003
- return;
1004
- if (!checkVal(val, object)) {
1005
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
1006
- }
1007
- };
1008
- for (const [fieldName, type] of Object.entries(validators))
1009
- checkField(fieldName, type, false);
1010
- for (const [fieldName, type] of Object.entries(optValidators))
1011
- checkField(fieldName, type, true);
1012
- return object;
1222
+ for (let i = 0; i < pad.length; i++)
1223
+ pad[i] ^= 0x36 ^ 0x5c;
1224
+ this.oHash.update(pad);
1225
+ clean$1(pad);
1226
+ }
1227
+ update(buf) {
1228
+ aexists(this);
1229
+ this.iHash.update(buf);
1230
+ return this;
1231
+ }
1232
+ digestInto(out) {
1233
+ aexists(this);
1234
+ abytes$3(out, this.outputLen);
1235
+ this.finished = true;
1236
+ this.iHash.digestInto(out);
1237
+ this.oHash.update(out);
1238
+ this.oHash.digestInto(out);
1239
+ this.destroy();
1240
+ }
1241
+ digest() {
1242
+ const out = new Uint8Array(this.oHash.outputLen);
1243
+ this.digestInto(out);
1244
+ return out;
1245
+ }
1246
+ _cloneInto(to) {
1247
+ // Create new instance without calling constructor since key already in state and we don't know it.
1248
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1249
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1250
+ to = to;
1251
+ to.finished = finished;
1252
+ to.destroyed = destroyed;
1253
+ to.blockLen = blockLen;
1254
+ to.outputLen = outputLen;
1255
+ to.oHash = oHash._cloneInto(to.oHash);
1256
+ to.iHash = iHash._cloneInto(to.iHash);
1257
+ return to;
1258
+ }
1259
+ clone() {
1260
+ return this._cloneInto();
1261
+ }
1262
+ destroy() {
1263
+ this.destroyed = true;
1264
+ this.oHash.destroy();
1265
+ this.iHash.destroy();
1266
+ }
1013
1267
  }
1014
- // validate type tests
1015
- // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
1016
- // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
1017
- // // Should fail type-check
1018
- // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
1019
- // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
1020
- // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
1021
- // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
1022
1268
  /**
1023
- * throws not implemented error
1269
+ * HMAC: RFC2104 message authentication code.
1270
+ * @param hash - function that would be used e.g. sha256
1271
+ * @param key - message key
1272
+ * @param message - message data
1273
+ * @example
1274
+ * import { hmac } from '@noble/hashes/hmac';
1275
+ * import { sha256 } from '@noble/hashes/sha2';
1276
+ * const mac1 = hmac(sha256, 'key', 'message');
1024
1277
  */
1025
- const notImplemented = () => {
1026
- throw new Error('not implemented');
1027
- };
1278
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1279
+ hmac.create = (hash, key) => new HMAC(hash, key);
1280
+
1028
1281
  /**
1029
- * Memoizes (caches) computation result.
1030
- * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1282
+ * Utils for modular division and finite fields.
1283
+ * A finite field over 11 is integer number operations `mod 11`.
1284
+ * There is no division: it is replaced by modular multiplicative inverse.
1285
+ * @module
1031
1286
  */
1032
- function memoized(fn) {
1033
- const map = new WeakMap();
1034
- return (arg, ...args) => {
1035
- const val = map.get(arg);
1036
- if (val !== undefined)
1037
- return val;
1038
- const computed = fn(arg, ...args);
1039
- map.set(arg, computed);
1040
- return computed;
1041
- };
1042
- }
1043
-
1044
- const ut = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
1045
- __proto__: null,
1046
- aInRange,
1047
- abool,
1048
- abytes,
1049
- bitGet,
1050
- bitLen,
1051
- bitMask,
1052
- bitSet,
1053
- bytesToHex,
1054
- bytesToNumberBE,
1055
- bytesToNumberLE,
1056
- concatBytes,
1057
- createHmacDrbg,
1058
- ensureBytes,
1059
- equalBytes,
1060
- hexToBytes,
1061
- hexToNumber,
1062
- inRange,
1063
- isBytes: isBytes$1,
1064
- memoized,
1065
- notImplemented,
1066
- numberToBytesBE,
1067
- numberToBytesLE,
1068
- numberToHexUnpadded,
1069
- numberToVarBytesBE,
1070
- utf8ToBytes,
1071
- validateObject
1072
- }, Symbol.toStringTag, { value: 'Module' }));
1073
-
1074
1287
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1075
- // Utilities for modular arithmetics and finite fields
1076
1288
  // prettier-ignore
1077
- const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = BigInt(2), _3n$1 = BigInt(3);
1289
+ const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
1078
1290
  // prettier-ignore
1079
- const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
1080
- // prettier-ignore
1081
- BigInt(9); BigInt(16);
1291
+ const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
1082
1292
  // Calculates a modulo b
1083
1293
  function mod(a, b) {
1084
1294
  const result = a % b;
1085
1295
  return result >= _0n$3 ? result : b + result;
1086
1296
  }
1087
- /**
1088
- * Efficiently raise num to power and do modular division.
1089
- * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1090
- * @example
1091
- * pow(2n, 6n, 11n) // 64n % 11n == 9n
1092
- */
1093
- // TODO: use field version && remove
1094
- function pow(num, power, modulo) {
1095
- if (modulo <= _0n$3 || power < _0n$3)
1096
- throw new Error('Expected power/modulo > 0');
1097
- if (modulo === _1n$4)
1098
- return _0n$3;
1099
- let res = _1n$4;
1100
- while (power > _0n$3) {
1101
- if (power & _1n$4)
1102
- res = (res * num) % modulo;
1103
- num = (num * num) % modulo;
1104
- power >>= _1n$4;
1105
- }
1106
- return res;
1107
- }
1108
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
1297
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
1109
1298
  function pow2(x, power, modulo) {
1110
1299
  let res = x;
1111
1300
  while (power-- > _0n$3) {
@@ -1114,12 +1303,15 @@ function pow2(x, power, modulo) {
1114
1303
  }
1115
1304
  return res;
1116
1305
  }
1117
- // Inverses number over modulo
1306
+ /**
1307
+ * Inverses number over modulo.
1308
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
1309
+ */
1118
1310
  function invert(number, modulo) {
1119
- if (number === _0n$3 || modulo <= _0n$3) {
1120
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
1121
- }
1122
- // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
1311
+ if (number === _0n$3)
1312
+ throw new Error('invert: expected non-zero number');
1313
+ if (modulo <= _0n$3)
1314
+ throw new Error('invert: expected positive modulus, got ' + modulo);
1123
1315
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
1124
1316
  let a = mod(number, modulo);
1125
1317
  let b = modulo;
@@ -1142,25 +1334,26 @@ function invert(number, modulo) {
1142
1334
  * Tonelli-Shanks square root search algorithm.
1143
1335
  * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
1144
1336
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
1145
- * Will start an infinite loop if field order P is not prime.
1146
1337
  * @param P field order
1147
1338
  * @returns function that takes field Fp (created from P) and number n
1148
1339
  */
1149
1340
  function tonelliShanks(P) {
1150
- // Legendre constant: used to calculate Legendre symbol (a | p),
1151
- // which denotes the value of a^((p-1)/2) (mod p).
1152
- // (a | p) ≡ 1 if a is a square (mod p)
1153
- // (a | p) ≡ -1 if a is not a square (mod p)
1154
- // (a | p) ≡ 0 if a ≡ 0 (mod p)
1155
- const legendreC = (P - _1n$4) / _2n$2;
1156
- let Q, S, Z;
1341
+ // Do expensive precomputation step
1157
1342
  // Step 1: By factoring out powers of 2 from p - 1,
1158
- // find q and s such that p - 1 = q*(2^s) with q odd
1159
- for (Q = P - _1n$4, S = 0; Q % _2n$2 === _0n$3; Q /= _2n$2, S++)
1160
- ;
1343
+ // find q and s such that p-1 == q*(2^s) with q odd
1344
+ let Q = P - _1n$4;
1345
+ let S = 0;
1346
+ while (Q % _2n$2 === _0n$3) {
1347
+ Q /= _2n$2;
1348
+ S++;
1349
+ }
1161
1350
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
1162
- for (Z = _2n$2; Z < P && pow(Z, legendreC, P) !== P - _1n$4; Z++)
1163
- ;
1351
+ let Z = _2n$2;
1352
+ const _Fp = Field(P);
1353
+ while (Z < P && FpIsSquare(_Fp, Z)) {
1354
+ if (Z++ > 1000)
1355
+ throw new Error('Cannot find square root: probably non-prime P');
1356
+ }
1164
1357
  // Fast-path
1165
1358
  if (S === 1) {
1166
1359
  const p1div4 = (P + _1n$4) / _4n;
@@ -1175,16 +1368,18 @@ function tonelliShanks(P) {
1175
1368
  const Q1div2 = (Q + _1n$4) / _2n$2;
1176
1369
  return function tonelliSlow(Fp, n) {
1177
1370
  // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
1178
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
1371
+ if (!FpIsSquare(Fp, n))
1179
1372
  throw new Error('Cannot find square root');
1180
1373
  let r = S;
1181
- // TODO: will fail at Fp2/etc
1374
+ // TODO: test on Fp2 and others
1182
1375
  let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
1183
1376
  let x = Fp.pow(n, Q1div2); // first guess at the square root
1184
1377
  let b = Fp.pow(n, Q); // first guess at the fudge factor
1185
1378
  while (!Fp.eql(b, Fp.ONE)) {
1379
+ // (4. If t = 0, return r = 0)
1380
+ // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
1186
1381
  if (Fp.eql(b, Fp.ZERO))
1187
- return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
1382
+ return Fp.ZERO;
1188
1383
  // Find m such b^(2^m)==1
1189
1384
  let m = 1;
1190
1385
  for (let t2 = Fp.sqr(b); m < r; m++) {
@@ -1192,7 +1387,8 @@ function tonelliShanks(P) {
1192
1387
  break;
1193
1388
  t2 = Fp.sqr(t2); // t2 *= t2
1194
1389
  }
1195
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
1390
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
1391
+ // otherwise there will be overflow.
1196
1392
  const ge = Fp.pow(g, _1n$4 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
1197
1393
  g = Fp.sqr(ge); // g = ge * ge
1198
1394
  x = Fp.mul(x, ge); // x *= ge
@@ -1202,9 +1398,18 @@ function tonelliShanks(P) {
1202
1398
  return x;
1203
1399
  };
1204
1400
  }
1401
+ /**
1402
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
1403
+ *
1404
+ * 1. P ≡ 3 (mod 4)
1405
+ * 2. P ≡ 5 (mod 8)
1406
+ * 3. P ≡ 9 (mod 16)
1407
+ * 4. Tonelli-Shanks algorithm
1408
+ *
1409
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
1410
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1411
+ */
1205
1412
  function FpSqrt(P) {
1206
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
1207
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1208
1413
  // P ≡ 3 (mod 4)
1209
1414
  // √n = n^((P+1)/4)
1210
1415
  if (P % _4n === _3n$1) {
@@ -1212,8 +1417,8 @@ function FpSqrt(P) {
1212
1417
  // const ORDER =
1213
1418
  // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
1214
1419
  // const NUM = 72057594037927816n;
1215
- const p1div4 = (P + _1n$4) / _4n;
1216
1420
  return function sqrt3mod4(Fp, n) {
1421
+ const p1div4 = (P + _1n$4) / _4n;
1217
1422
  const root = Fp.pow(n, p1div4);
1218
1423
  // Throw if root**2 != n
1219
1424
  if (!Fp.eql(Fp.sqr(root), n))
@@ -1223,9 +1428,9 @@ function FpSqrt(P) {
1223
1428
  }
1224
1429
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
1225
1430
  if (P % _8n === _5n) {
1226
- const c1 = (P - _5n) / _8n;
1227
1431
  return function sqrt5mod8(Fp, n) {
1228
1432
  const n2 = Fp.mul(n, _2n$2);
1433
+ const c1 = (P - _5n) / _8n;
1229
1434
  const v = Fp.pow(n2, c1);
1230
1435
  const nv = Fp.mul(n, v);
1231
1436
  const i = Fp.mul(Fp.mul(nv, _2n$2), v);
@@ -1262,66 +1467,92 @@ function validateField(field) {
1262
1467
  * Same as `pow` but for Fp: non-constant-time.
1263
1468
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1264
1469
  */
1265
- function FpPow(f, num, power) {
1266
- // Should have same speed as pow for bigints
1267
- // TODO: benchmark!
1470
+ function FpPow(Fp, num, power) {
1268
1471
  if (power < _0n$3)
1269
- throw new Error('Expected power > 0');
1472
+ throw new Error('invalid exponent, negatives unsupported');
1270
1473
  if (power === _0n$3)
1271
- return f.ONE;
1474
+ return Fp.ONE;
1272
1475
  if (power === _1n$4)
1273
1476
  return num;
1274
- let p = f.ONE;
1477
+ // @ts-ignore
1478
+ let p = Fp.ONE;
1275
1479
  let d = num;
1276
1480
  while (power > _0n$3) {
1277
1481
  if (power & _1n$4)
1278
- p = f.mul(p, d);
1279
- d = f.sqr(d);
1482
+ p = Fp.mul(p, d);
1483
+ d = Fp.sqr(d);
1280
1484
  power >>= _1n$4;
1281
1485
  }
1282
1486
  return p;
1283
1487
  }
1284
1488
  /**
1285
1489
  * Efficiently invert an array of Field elements.
1286
- * `inv(0)` will return `undefined` here: make sure to throw an error.
1490
+ * Exception-free. Will return `undefined` for 0 elements.
1491
+ * @param passZero map 0 to 0 (instead of undefined)
1287
1492
  */
1288
- function FpInvertBatch(f, nums) {
1289
- const tmp = new Array(nums.length);
1493
+ function FpInvertBatch(Fp, nums, passZero = false) {
1494
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
1290
1495
  // Walk from first to last, multiply them by each other MOD p
1291
- const lastMultiplied = nums.reduce((acc, num, i) => {
1292
- if (f.is0(num))
1496
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1497
+ if (Fp.is0(num))
1293
1498
  return acc;
1294
- tmp[i] = acc;
1295
- return f.mul(acc, num);
1296
- }, f.ONE);
1499
+ inverted[i] = acc;
1500
+ return Fp.mul(acc, num);
1501
+ }, Fp.ONE);
1297
1502
  // Invert last element
1298
- const inverted = f.inv(lastMultiplied);
1503
+ const invertedAcc = Fp.inv(multipliedAcc);
1299
1504
  // Walk from last to first, multiply them by inverted each other MOD p
1300
1505
  nums.reduceRight((acc, num, i) => {
1301
- if (f.is0(num))
1506
+ if (Fp.is0(num))
1302
1507
  return acc;
1303
- tmp[i] = f.mul(acc, tmp[i]);
1304
- return f.mul(acc, num);
1305
- }, inverted);
1306
- return tmp;
1508
+ inverted[i] = Fp.mul(acc, inverted[i]);
1509
+ return Fp.mul(acc, num);
1510
+ }, invertedAcc);
1511
+ return inverted;
1512
+ }
1513
+ /**
1514
+ * Legendre symbol.
1515
+ * Legendre constant is used to calculate Legendre symbol (a | p)
1516
+ * which denotes the value of a^((p-1)/2) (mod p)..
1517
+ *
1518
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
1519
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
1520
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
1521
+ */
1522
+ function FpLegendre(Fp, n) {
1523
+ const legc = (Fp.ORDER - _1n$4) / _2n$2;
1524
+ const powered = Fp.pow(n, legc);
1525
+ const yes = Fp.eql(powered, Fp.ONE);
1526
+ const zero = Fp.eql(powered, Fp.ZERO);
1527
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1528
+ if (!yes && !zero && !no)
1529
+ throw new Error('Cannot find square root: probably non-prime P');
1530
+ return yes ? 1 : zero ? 0 : -1;
1531
+ }
1532
+ // This function returns True whenever the value x is a square in the field F.
1533
+ function FpIsSquare(Fp, n) {
1534
+ const l = FpLegendre(Fp, n);
1535
+ return l === 0 || l === 1;
1307
1536
  }
1308
1537
  // CURVE.n lengths
1309
1538
  function nLength(n, nBitLength) {
1310
1539
  // Bit size, byte size of CURVE.n
1540
+ if (nBitLength !== undefined)
1541
+ anumber(nBitLength);
1311
1542
  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
1312
1543
  const nByteLength = Math.ceil(_nBitLength / 8);
1313
1544
  return { nBitLength: _nBitLength, nByteLength };
1314
1545
  }
1315
1546
  /**
1316
- * Initializes a finite field over prime. **Non-primes are not supported.**
1317
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
1547
+ * Initializes a finite field over prime.
1318
1548
  * Major performance optimizations:
1319
1549
  * * a) denormalized operations like mulN instead of mul
1320
1550
  * * b) same object shape: never add or remove keys
1321
1551
  * * c) Object.freeze
1322
- * NOTE: operations don't check 'isValid' for all elements for performance reasons,
1552
+ * Fragile: always run a benchmark on a change.
1553
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
1323
1554
  * it is caller responsibility to check this.
1324
- * This is low-level code, please make sure you know what you doing.
1555
+ * This is low-level code, please make sure you know what you're doing.
1325
1556
  * @param ORDER prime positive bigint
1326
1557
  * @param bitLen how many bits the field consumes
1327
1558
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -1329,13 +1560,14 @@ function nLength(n, nBitLength) {
1329
1560
  */
1330
1561
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
1331
1562
  if (ORDER <= _0n$3)
1332
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
1563
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
1333
1564
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
1334
1565
  if (BYTES > 2048)
1335
- throw new Error('Field lengths over 2048 bytes are not supported');
1336
- const sqrtP = FpSqrt(ORDER);
1566
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
1567
+ let sqrtP; // cached sqrtP
1337
1568
  const f = Object.freeze({
1338
1569
  ORDER,
1570
+ isLE,
1339
1571
  BITS,
1340
1572
  BYTES,
1341
1573
  MASK: bitMask(BITS),
@@ -1344,7 +1576,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1344
1576
  create: (num) => mod(num, ORDER),
1345
1577
  isValid: (num) => {
1346
1578
  if (typeof num !== 'bigint')
1347
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
1579
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
1348
1580
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1349
1581
  },
1350
1582
  is0: (num) => num === _0n$3,
@@ -1363,17 +1595,23 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1363
1595
  subN: (lhs, rhs) => lhs - rhs,
1364
1596
  mulN: (lhs, rhs) => lhs * rhs,
1365
1597
  inv: (num) => invert(num, ORDER),
1366
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
1367
- invertBatch: (lst) => FpInvertBatch(f, lst),
1368
- // TODO: do we really need constant cmov?
1369
- // We don't have const-time bigints anyway, so probably will be not very useful
1370
- cmov: (a, b, c) => (c ? b : a),
1598
+ sqrt: redef.sqrt ||
1599
+ ((n) => {
1600
+ if (!sqrtP)
1601
+ sqrtP = FpSqrt(ORDER);
1602
+ return sqrtP(f, n);
1603
+ }),
1371
1604
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
1372
1605
  fromBytes: (bytes) => {
1373
1606
  if (bytes.length !== BYTES)
1374
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
1607
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
1375
1608
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1376
1609
  },
1610
+ // TODO: we don't need it here, move out to separate fn
1611
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1612
+ // We can't move this out because Fp6, Fp12 implement it
1613
+ // and it's unclear what to return in there.
1614
+ cmov: (a, b, c) => (c ? b : a),
1377
1615
  });
1378
1616
  return Object.freeze(f);
1379
1617
  }
@@ -1419,52 +1657,106 @@ function mapHashToField(key, fieldOrder, isLE = false) {
1419
1657
  const minLen = getMinHashLength(fieldOrder);
1420
1658
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
1421
1659
  if (len < 16 || len < minLen || len > 1024)
1422
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
1423
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
1660
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
1661
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1424
1662
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
1425
1663
  const reduced = mod(num, fieldOrder - _1n$4) + _1n$4;
1426
1664
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1427
1665
  }
1428
1666
 
1667
+ /**
1668
+ * Methods for elliptic curve multiplication by scalars.
1669
+ * Contains wNAF, pippenger
1670
+ * @module
1671
+ */
1429
1672
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1430
- // Abelian group utilities
1431
1673
  const _0n$2 = BigInt(0);
1432
1674
  const _1n$3 = BigInt(1);
1675
+ function constTimeNegate(condition, item) {
1676
+ const neg = item.negate();
1677
+ return condition ? neg : item;
1678
+ }
1679
+ function validateW(W, bits) {
1680
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1681
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
1682
+ }
1683
+ function calcWOpts(W, scalarBits) {
1684
+ validateW(W, scalarBits);
1685
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
1686
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
1687
+ const maxNumber = 2 ** W; // W=8 256
1688
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
1689
+ const shiftBy = BigInt(W); // W=8 8
1690
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1691
+ }
1692
+ function calcOffsets(n, window, wOpts) {
1693
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1694
+ let wbits = Number(n & mask); // extract W bits.
1695
+ let nextN = n >> shiftBy; // shift number by W bits.
1696
+ // What actually happens here:
1697
+ // const highestBit = Number(mask ^ (mask >> 1n));
1698
+ // let wbits2 = wbits - 1; // skip zero
1699
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
1700
+ // split if bits > max: +224 => 256-32
1701
+ if (wbits > windowSize) {
1702
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
1703
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
1704
+ nextN += _1n$3; // +256 (carry)
1705
+ }
1706
+ const offsetStart = window * windowSize;
1707
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
1708
+ const isZero = wbits === 0; // is current window slice a 0?
1709
+ const isNeg = wbits < 0; // is current window slice negative?
1710
+ const isNegF = window % 2 !== 0; // fake random statement for noise
1711
+ const offsetF = offsetStart; // fake offset for noise
1712
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1713
+ }
1714
+ function validateMSMPoints(points, c) {
1715
+ if (!Array.isArray(points))
1716
+ throw new Error('array expected');
1717
+ points.forEach((p, i) => {
1718
+ if (!(p instanceof c))
1719
+ throw new Error('invalid point at index ' + i);
1720
+ });
1721
+ }
1722
+ function validateMSMScalars(scalars, field) {
1723
+ if (!Array.isArray(scalars))
1724
+ throw new Error('array of scalars expected');
1725
+ scalars.forEach((s, i) => {
1726
+ if (!field.isValid(s))
1727
+ throw new Error('invalid scalar at index ' + i);
1728
+ });
1729
+ }
1433
1730
  // Since points in different groups cannot be equal (different object constructor),
1434
- // we can have single place to store precomputes
1731
+ // we can have single place to store precomputes.
1732
+ // Allows to make points frozen / immutable.
1435
1733
  const pointPrecomputes = new WeakMap();
1436
- const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
1437
- // Elliptic curve multiplication of Point by scalar. Fragile.
1438
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
1439
- // Creates precomputation tables for fast multiplication:
1440
- // - private scalar is split by fixed size windows of W bits
1441
- // - every window point is collected from window's table & added to accumulator
1442
- // - since windows are different, same point inside tables won't be accessed more than once per calc
1443
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1444
- // - +1 window is neccessary for wNAF
1445
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1446
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
1447
- // windows to be in different memory locations
1734
+ const pointWindowSizes = new WeakMap();
1735
+ function getW(P) {
1736
+ return pointWindowSizes.get(P) || 1;
1737
+ }
1738
+ /**
1739
+ * Elliptic curve multiplication of Point by scalar. Fragile.
1740
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
1741
+ * Creates precomputation tables for fast multiplication:
1742
+ * - private scalar is split by fixed size windows of W bits
1743
+ * - every window point is collected from window's table & added to accumulator
1744
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
1745
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1746
+ * - +1 window is neccessary for wNAF
1747
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1748
+ *
1749
+ * @todo Research returning 2d JS array of windows, instead of a single window.
1750
+ * This would allow windows to be in different memory locations
1751
+ */
1448
1752
  function wNAF(c, bits) {
1449
- const constTimeNegate = (condition, item) => {
1450
- const neg = item.negate();
1451
- return condition ? neg : item;
1452
- };
1453
- const validateW = (W) => {
1454
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1455
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
1456
- };
1457
- const opts = (W) => {
1458
- validateW(W);
1459
- const windows = Math.ceil(bits / W) + 1; // +1, because
1460
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
1461
- return { windows, windowSize };
1462
- };
1463
1753
  return {
1464
1754
  constTimeNegate,
1755
+ hasPrecomputes(elm) {
1756
+ return getW(elm) !== 1;
1757
+ },
1465
1758
  // non-const time multiplication ladder
1466
- unsafeLadder(elm, n) {
1467
- let p = c.ZERO;
1759
+ unsafeLadder(elm, n, p = c.ZERO) {
1468
1760
  let d = elm;
1469
1761
  while (n > _0n$2) {
1470
1762
  if (n & _1n$3)
@@ -1482,17 +1774,19 @@ function wNAF(c, bits) {
1482
1774
  * - 𝑊 is the window size
1483
1775
  * - 𝑛 is the bitlength of the curve order.
1484
1776
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1777
+ * @param elm Point instance
1778
+ * @param W window size
1485
1779
  * @returns precomputed point tables flattened to a single array
1486
1780
  */
1487
1781
  precomputeWindow(elm, W) {
1488
- const { windows, windowSize } = opts(W);
1782
+ const { windows, windowSize } = calcWOpts(W, bits);
1489
1783
  const points = [];
1490
1784
  let p = elm;
1491
1785
  let base = p;
1492
1786
  for (let window = 0; window < windows; window++) {
1493
1787
  base = p;
1494
1788
  points.push(base);
1495
- // =1, because we skip zero
1789
+ // i=1, bc we skip 0
1496
1790
  for (let i = 1; i < windowSize; i++) {
1497
1791
  base = base.add(p);
1498
1792
  points.push(base);
@@ -1509,54 +1803,67 @@ function wNAF(c, bits) {
1509
1803
  * @returns real and fake (for const-time) points
1510
1804
  */
1511
1805
  wNAF(W, precomputes, n) {
1512
- // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
1513
- // But need to carefully remove other checks before wNAF. ORDER == bits here
1514
- const { windows, windowSize } = opts(W);
1806
+ // Smaller version:
1807
+ // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1808
+ // TODO: check the scalar is less than group order?
1809
+ // wNAF behavior is undefined otherwise. But have to carefully remove
1810
+ // other checks before wNAF. ORDER == bits here.
1811
+ // Accumulators
1515
1812
  let p = c.ZERO;
1516
1813
  let f = c.BASE;
1517
- const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
1518
- const maxNumber = 2 ** W;
1519
- const shiftBy = BigInt(W);
1520
- for (let window = 0; window < windows; window++) {
1521
- const offset = window * windowSize;
1522
- // Extract W bits.
1523
- let wbits = Number(n & mask);
1524
- // Shift number by W bits.
1525
- n >>= shiftBy;
1526
- // If the bits are bigger than max size, we'll split those.
1527
- // +224 => 256 - 32
1528
- if (wbits > windowSize) {
1529
- wbits -= maxNumber;
1530
- n += _1n$3;
1531
- }
1532
- // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1533
- // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1534
- // there is negate now: it is possible that negated element from low value
1535
- // would be the same as high element, which will create carry into next window.
1536
- // It's not obvious how this can fail, but still worth investigating later.
1537
- // Check if we're onto Zero point.
1538
- // Add random point inside current window to f.
1539
- const offset1 = offset;
1540
- const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
1541
- const cond1 = window % 2 !== 0;
1542
- const cond2 = wbits < 0;
1543
- if (wbits === 0) {
1544
- // The most important part for const-time getPublicKey
1545
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1814
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1815
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1816
+ // there is negate now: it is possible that negated element from low value
1817
+ // would be the same as high element, which will create carry into next window.
1818
+ // It's not obvious how this can fail, but still worth investigating later.
1819
+ const wo = calcWOpts(W, bits);
1820
+ for (let window = 0; window < wo.windows; window++) {
1821
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
1822
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1823
+ n = nextN;
1824
+ if (isZero) {
1825
+ // bits are 0: add garbage to fake point
1826
+ // Important part for const-time getPublicKey: add random "noise" point to f.
1827
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
1546
1828
  }
1547
1829
  else {
1548
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1830
+ // bits are 1: add to result point
1831
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
1549
1832
  }
1550
1833
  }
1551
- // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
1552
- // Even if the variable is still unused, there are some checks which will
1553
- // throw an exception, so compiler needs to prove they won't happen, which is hard.
1834
+ // Return both real and fake points: JIT won't eliminate f.
1554
1835
  // At this point there is a way to F be infinity-point even if p is not,
1555
1836
  // which makes it less const-time: around 1 bigint multiply.
1556
1837
  return { p, f };
1557
1838
  },
1558
- wNAFCached(P, n, transform) {
1559
- const W = pointWindowSizes.get(P) || 1;
1839
+ /**
1840
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1841
+ * @param W window size
1842
+ * @param precomputes precomputed tables
1843
+ * @param n scalar (we don't check here, but should be less than curve order)
1844
+ * @param acc accumulator point to add result of multiplication
1845
+ * @returns point
1846
+ */
1847
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1848
+ const wo = calcWOpts(W, bits);
1849
+ for (let window = 0; window < wo.windows; window++) {
1850
+ if (n === _0n$2)
1851
+ break; // Early-exit, skip 0 value
1852
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1853
+ n = nextN;
1854
+ if (isZero) {
1855
+ // Window bits are 0: skip processing.
1856
+ // Move to next window.
1857
+ continue;
1858
+ }
1859
+ else {
1860
+ const item = precomputes[offset];
1861
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
1862
+ }
1863
+ }
1864
+ return acc;
1865
+ },
1866
+ getPrecomputes(W, P, transform) {
1560
1867
  // Calculate precomputes on a first run, reuse them after
1561
1868
  let comp = pointPrecomputes.get(P);
1562
1869
  if (!comp) {
@@ -1564,62 +1871,66 @@ function wNAF(c, bits) {
1564
1871
  if (W !== 1)
1565
1872
  pointPrecomputes.set(P, transform(comp));
1566
1873
  }
1567
- return this.wNAF(W, comp, n);
1874
+ return comp;
1875
+ },
1876
+ wNAFCached(P, n, transform) {
1877
+ const W = getW(P);
1878
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
1879
+ },
1880
+ wNAFCachedUnsafe(P, n, transform, prev) {
1881
+ const W = getW(P);
1882
+ if (W === 1)
1883
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
1884
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
1568
1885
  },
1569
1886
  // We calculate precomputes for elliptic curve point multiplication
1570
1887
  // using windowed method. This specifies window size and
1571
1888
  // stores precomputed values. Usually only base point would be precomputed.
1572
1889
  setWindowSize(P, W) {
1573
- validateW(W);
1890
+ validateW(W, bits);
1574
1891
  pointWindowSizes.set(P, W);
1575
1892
  pointPrecomputes.delete(P);
1576
1893
  },
1577
1894
  };
1578
1895
  }
1579
1896
  /**
1580
- * Pippenger algorithm for multi-scalar multiplication (MSM).
1581
- * MSM is basically (Pa + Qb + Rc + ...).
1582
- * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
1897
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
1898
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
1583
1899
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
1584
1900
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
1585
1901
  * @param c Curve Point constructor
1586
- * @param field field over CURVE.N - important that it's not over CURVE.P
1902
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
1587
1903
  * @param points array of L curve points
1588
1904
  * @param scalars array of L scalars (aka private keys / bigints)
1589
1905
  */
1590
- function pippenger(c, field, points, scalars) {
1906
+ function pippenger(c, fieldN, points, scalars) {
1591
1907
  // If we split scalars by some window (let's say 8 bits), every chunk will only
1592
1908
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
1593
1909
  // TODO:
1594
1910
  // - https://eprint.iacr.org/2024/750.pdf
1595
1911
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
1596
1912
  // 0 is accepted in scalars
1597
- if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
1913
+ validateMSMPoints(points, c);
1914
+ validateMSMScalars(scalars, fieldN);
1915
+ if (points.length !== scalars.length)
1598
1916
  throw new Error('arrays of points and scalars must have equal length');
1599
- scalars.forEach((s, i) => {
1600
- if (!field.isValid(s))
1601
- throw new Error(`wrong scalar at index ${i}`);
1602
- });
1603
- points.forEach((p, i) => {
1604
- if (!(p instanceof c))
1605
- throw new Error(`wrong point at index ${i}`);
1606
- });
1917
+ const zero = c.ZERO;
1607
1918
  const wbits = bitLen(BigInt(points.length));
1608
1919
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
1609
- const MASK = (1 << windowSize) - 1;
1610
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
1611
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
1612
- let sum = c.ZERO;
1920
+ const MASK = bitMask(windowSize);
1921
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
1922
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1923
+ let sum = zero;
1613
1924
  for (let i = lastBits; i >= 0; i -= windowSize) {
1614
- buckets.fill(c.ZERO);
1925
+ buckets.fill(zero);
1615
1926
  for (let j = 0; j < scalars.length; j++) {
1616
1927
  const scalar = scalars[j];
1617
- const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
1928
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
1618
1929
  buckets[wbits] = buckets[wbits].add(points[j]);
1619
1930
  }
1620
- let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
1931
+ let resI = zero; // not using this will do small speed-up, but will lose ct
1621
1932
  // Skip first bucket, because it is zero
1622
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
1933
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1623
1934
  sumI = sumI.add(buckets[j]);
1624
1935
  resI = resI.add(sumI);
1625
1936
  }
@@ -1649,8 +1960,47 @@ function validateBasic(curve) {
1649
1960
  });
1650
1961
  }
1651
1962
 
1963
+ /**
1964
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
1965
+ *
1966
+ * ### Parameters
1967
+ *
1968
+ * To initialize a weierstrass curve, one needs to pass following params:
1969
+ *
1970
+ * * a: formula param
1971
+ * * b: formula param
1972
+ * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
1973
+ * * n: Curve prime subgroup order, total count of valid points in the field
1974
+ * * Gx: Base point (x, y) aka generator point x coordinate
1975
+ * * Gy: ...y coordinate
1976
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
1977
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
1978
+ *
1979
+ * ### Design rationale for types
1980
+ *
1981
+ * * Interaction between classes from different curves should fail:
1982
+ * `k256.Point.BASE.add(p256.Point.BASE)`
1983
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
1984
+ * * Different calls of `curve()` would return different classes -
1985
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
1986
+ * it won't affect others
1987
+ *
1988
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
1989
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
1990
+ * unique type for every function call.
1991
+ *
1992
+ * We can use generic types via some param, like curve opts, but that would:
1993
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
1994
+ * which is hard to debug.
1995
+ * 2. Params can be generic and we can't enforce them to be constant value:
1996
+ * if somebody creates curve from non-constant params,
1997
+ * it would be allowed to interact with other curves with non-constant params
1998
+ *
1999
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
2000
+ * @module
2001
+ */
1652
2002
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1653
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
2003
+ // prettier-ignore
1654
2004
  function validateSigVerOpts(opts) {
1655
2005
  if (opts.lowS !== undefined)
1656
2006
  abool('lowS', opts.lowS);
@@ -1674,17 +2024,21 @@ function validatePointOpts(curve) {
1674
2024
  const { endo, Fp, a } = opts;
1675
2025
  if (endo) {
1676
2026
  if (!Fp.eql(a, Fp.ZERO)) {
1677
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
2027
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
1678
2028
  }
1679
2029
  if (typeof endo !== 'object' ||
1680
2030
  typeof endo.beta !== 'bigint' ||
1681
2031
  typeof endo.splitScalar !== 'function') {
1682
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
2032
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
1683
2033
  }
1684
2034
  }
1685
2035
  return Object.freeze({ ...opts });
1686
2036
  }
1687
- const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
2037
+ class DERErr extends Error {
2038
+ constructor(m = '') {
2039
+ super(m);
2040
+ }
2041
+ }
1688
2042
  /**
1689
2043
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
1690
2044
  *
@@ -1694,11 +2048,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
1694
2048
  */
1695
2049
  const DER = {
1696
2050
  // asn.1 DER encoding utils
1697
- Err: class DERErr extends Error {
1698
- constructor(m = '') {
1699
- super(m);
1700
- }
1701
- },
2051
+ Err: DERErr,
1702
2052
  // Basic building block is TLV (Tag-Length-Value)
1703
2053
  _tlv: {
1704
2054
  encode: (tag, data) => {
@@ -1713,7 +2063,8 @@ const DER = {
1713
2063
  throw new E('tlv.encode: long form length too big');
1714
2064
  // length of length with long form flag
1715
2065
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
1716
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
2066
+ const t = numberToHexUnpadded(tag);
2067
+ return t + lenLen + len + data;
1717
2068
  },
1718
2069
  // v - value, l - left bytes (unparsed)
1719
2070
  decode(tag, data) {
@@ -1766,35 +2117,36 @@ const DER = {
1766
2117
  if (Number.parseInt(hex[0], 16) & 0b1000)
1767
2118
  hex = '00' + hex;
1768
2119
  if (hex.length & 1)
1769
- throw new E('unexpected assertion');
2120
+ throw new E('unexpected DER parsing assertion: unpadded hex');
1770
2121
  return hex;
1771
2122
  },
1772
2123
  decode(data) {
1773
2124
  const { Err: E } = DER;
1774
2125
  if (data[0] & 128)
1775
- throw new E('Invalid signature integer: negative');
2126
+ throw new E('invalid signature integer: negative');
1776
2127
  if (data[0] === 0x00 && !(data[1] & 128))
1777
- throw new E('Invalid signature integer: unnecessary leading zero');
1778
- return b2n(data);
2128
+ throw new E('invalid signature integer: unnecessary leading zero');
2129
+ return bytesToNumberBE(data);
1779
2130
  },
1780
2131
  },
1781
2132
  toSig(hex) {
1782
2133
  // parse DER signature
1783
2134
  const { Err: E, _int: int, _tlv: tlv } = DER;
1784
- const data = typeof hex === 'string' ? h2b(hex) : hex;
1785
- abytes(data);
2135
+ const data = ensureBytes('signature', hex);
1786
2136
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
1787
2137
  if (seqLeftBytes.length)
1788
- throw new E('Invalid signature: left bytes after parsing');
2138
+ throw new E('invalid signature: left bytes after parsing');
1789
2139
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
1790
2140
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
1791
2141
  if (sLeftBytes.length)
1792
- throw new E('Invalid signature: left bytes after parsing');
2142
+ throw new E('invalid signature: left bytes after parsing');
1793
2143
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
1794
2144
  },
1795
2145
  hexFromSig(sig) {
1796
2146
  const { _tlv: tlv, _int: int } = DER;
1797
- const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
2147
+ const rs = tlv.encode(0x02, int.encode(sig.r));
2148
+ const ss = tlv.encode(0x02, int.encode(sig.s));
2149
+ const seq = rs + ss;
1798
2150
  return tlv.encode(0x30, seq);
1799
2151
  },
1800
2152
  };
@@ -1820,7 +2172,7 @@ function weierstrassPoints(opts) {
1820
2172
  return { x, y };
1821
2173
  });
1822
2174
  /**
1823
- * y² = x³ + ax + b: Short weierstrass curve formula
2175
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
1824
2176
  * @returns y²
1825
2177
  */
1826
2178
  function weierstrassEquation(x) {
@@ -1848,7 +2200,7 @@ function weierstrassPoints(opts) {
1848
2200
  key = bytesToHex(key);
1849
2201
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
1850
2202
  if (typeof key !== 'string' || !lengths.includes(key.length))
1851
- throw new Error('Invalid key');
2203
+ throw new Error('invalid private key');
1852
2204
  key = key.padStart(nByteLength * 2, '0');
1853
2205
  }
1854
2206
  let num;
@@ -1859,14 +2211,14 @@ function weierstrassPoints(opts) {
1859
2211
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
1860
2212
  }
1861
2213
  catch (error) {
1862
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
2214
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
1863
2215
  }
1864
2216
  if (wrapPrivateKey)
1865
2217
  num = mod(num, N); // disabled by default, enabled for BLS
1866
2218
  aInRange('private key', num, _1n$2, N); // num in range [1..N-1]
1867
2219
  return num;
1868
2220
  }
1869
- function assertPrjPoint(other) {
2221
+ function aprjpoint(other) {
1870
2222
  if (!(other instanceof Point))
1871
2223
  throw new Error('ProjectivePoint expected');
1872
2224
  }
@@ -1899,7 +2251,7 @@ function weierstrassPoints(opts) {
1899
2251
  if (p.is0()) {
1900
2252
  // (0, 1, 0) aka ZERO is invalid in most contexts.
1901
2253
  // In BLS, ZERO can be serialized, so we allow it.
1902
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
2254
+ // (0, 0, 0) is invalid representation of ZERO.
1903
2255
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
1904
2256
  return;
1905
2257
  throw new Error('bad point: ZERO');
@@ -1924,15 +2276,15 @@ function weierstrassPoints(opts) {
1924
2276
  */
1925
2277
  class Point {
1926
2278
  constructor(px, py, pz) {
1927
- this.px = px;
1928
- this.py = py;
1929
- this.pz = pz;
1930
2279
  if (px == null || !Fp.isValid(px))
1931
2280
  throw new Error('x required');
1932
- if (py == null || !Fp.isValid(py))
2281
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
1933
2282
  throw new Error('y required');
1934
2283
  if (pz == null || !Fp.isValid(pz))
1935
2284
  throw new Error('z required');
2285
+ this.px = px;
2286
+ this.py = py;
2287
+ this.pz = pz;
1936
2288
  Object.freeze(this);
1937
2289
  }
1938
2290
  // Does not validate if the point is on-curve.
@@ -1962,7 +2314,7 @@ function weierstrassPoints(opts) {
1962
2314
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
1963
2315
  */
1964
2316
  static normalizeZ(points) {
1965
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
2317
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
1966
2318
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1967
2319
  }
1968
2320
  /**
@@ -2000,7 +2352,7 @@ function weierstrassPoints(opts) {
2000
2352
  * Compare one point to another.
2001
2353
  */
2002
2354
  equals(other) {
2003
- assertPrjPoint(other);
2355
+ aprjpoint(other);
2004
2356
  const { px: X1, py: Y1, pz: Z1 } = this;
2005
2357
  const { px: X2, py: Y2, pz: Z2 } = other;
2006
2358
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
@@ -2060,7 +2412,7 @@ function weierstrassPoints(opts) {
2060
2412
  // https://eprint.iacr.org/2015/1060, algorithm 1
2061
2413
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2062
2414
  add(other) {
2063
- assertPrjPoint(other);
2415
+ aprjpoint(other);
2064
2416
  const { px: X1, py: Y1, pz: Z1 } = this;
2065
2417
  const { px: X2, py: Y2, pz: Z2 } = other;
2066
2418
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
@@ -2123,16 +2475,17 @@ function weierstrassPoints(opts) {
2123
2475
  * an exposed private key e.g. sig verification, which works over *public* keys.
2124
2476
  */
2125
2477
  multiplyUnsafe(sc) {
2126
- aInRange('scalar', sc, _0n$1, CURVE.n);
2478
+ const { endo, n: N } = CURVE;
2479
+ aInRange('scalar', sc, _0n$1, N);
2127
2480
  const I = Point.ZERO;
2128
2481
  if (sc === _0n$1)
2129
2482
  return I;
2130
- if (sc === _1n$2)
2483
+ if (this.is0() || sc === _1n$2)
2131
2484
  return this;
2132
- const { endo } = CURVE;
2133
- if (!endo)
2134
- return wnaf.unsafeLadder(this, sc);
2135
- // Apply endomorphism
2485
+ // Case a: no endomorphism. Case b: has precomputes.
2486
+ if (!endo || wnaf.hasPrecomputes(this))
2487
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
2488
+ // Case c: endomorphism
2136
2489
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
2137
2490
  let k1p = I;
2138
2491
  let k2p = I;
@@ -2230,10 +2583,9 @@ function weierstrassPoints(opts) {
2230
2583
  }
2231
2584
  }
2232
2585
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2233
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2586
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
2234
2587
  const _bits = CURVE.nBitLength;
2235
2588
  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
2236
- // Validate if generator point is on curve
2237
2589
  return {
2238
2590
  CURVE,
2239
2591
  ProjectivePoint: Point,
@@ -2318,11 +2670,13 @@ function weierstrass(curveDef) {
2318
2670
  return { x, y };
2319
2671
  }
2320
2672
  else {
2321
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
2673
+ const cl = compressedLen;
2674
+ const ul = uncompressedLen;
2675
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
2322
2676
  }
2323
2677
  },
2324
2678
  });
2325
- const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
2679
+ const numToNByteHex = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
2326
2680
  function isBiggerThanHalfOrder(number) {
2327
2681
  const HALF = CURVE_ORDER >> _1n$2;
2328
2682
  return number > HALF;
@@ -2337,10 +2691,13 @@ function weierstrass(curveDef) {
2337
2691
  */
2338
2692
  class Signature {
2339
2693
  constructor(r, s, recovery) {
2694
+ aInRange('r', r, _1n$2, CURVE_ORDER); // r in [1..N]
2695
+ aInRange('s', s, _1n$2, CURVE_ORDER); // s in [1..N]
2340
2696
  this.r = r;
2341
2697
  this.s = s;
2342
- this.recovery = recovery;
2343
- this.assertValidity();
2698
+ if (recovery != null)
2699
+ this.recovery = recovery;
2700
+ Object.freeze(this);
2344
2701
  }
2345
2702
  // pair (bytes of r, bytes of s)
2346
2703
  static fromCompact(hex) {
@@ -2354,10 +2711,11 @@ function weierstrass(curveDef) {
2354
2711
  const { r, s } = DER.toSig(ensureBytes('DER', hex));
2355
2712
  return new Signature(r, s);
2356
2713
  }
2357
- assertValidity() {
2358
- aInRange('r', this.r, _1n$2, CURVE_ORDER); // r in [1..N]
2359
- aInRange('s', this.s, _1n$2, CURVE_ORDER); // s in [1..N]
2360
- }
2714
+ /**
2715
+ * @todo remove
2716
+ * @deprecated
2717
+ */
2718
+ assertValidity() { }
2361
2719
  addRecoveryBit(recovery) {
2362
2720
  return new Signature(this.r, this.s, recovery);
2363
2721
  }
@@ -2370,7 +2728,7 @@ function weierstrass(curveDef) {
2370
2728
  if (radj >= Fp.ORDER)
2371
2729
  throw new Error('recovery id 2 or 3 invalid');
2372
2730
  const prefix = (rec & 1) === 0 ? '02' : '03';
2373
- const R = Point.fromHex(prefix + numToNByteStr(radj));
2731
+ const R = Point.fromHex(prefix + numToNByteHex(radj));
2374
2732
  const ir = invN(radj); // r^-1
2375
2733
  const u1 = modN(-h * ir); // -hr^-1
2376
2734
  const u2 = modN(s * ir); // sr^-1
@@ -2389,17 +2747,17 @@ function weierstrass(curveDef) {
2389
2747
  }
2390
2748
  // DER-encoded
2391
2749
  toDERRawBytes() {
2392
- return hexToBytes(this.toDERHex());
2750
+ return hexToBytes$1(this.toDERHex());
2393
2751
  }
2394
2752
  toDERHex() {
2395
- return DER.hexFromSig({ r: this.r, s: this.s });
2753
+ return DER.hexFromSig(this);
2396
2754
  }
2397
2755
  // padded bytes of r, then padded bytes of s
2398
2756
  toCompactRawBytes() {
2399
- return hexToBytes(this.toCompactHex());
2757
+ return hexToBytes$1(this.toCompactHex());
2400
2758
  }
2401
2759
  toCompactHex() {
2402
- return numToNByteStr(this.r) + numToNByteStr(this.s);
2760
+ return numToNByteHex(this.r) + numToNByteHex(this.s);
2403
2761
  }
2404
2762
  }
2405
2763
  const utils = {
@@ -2483,6 +2841,9 @@ function weierstrass(curveDef) {
2483
2841
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
2484
2842
  const bits2int = CURVE.bits2int ||
2485
2843
  function (bytes) {
2844
+ // Our custom check "just in case"
2845
+ if (bytes.length > 8192)
2846
+ throw new Error('input is too large');
2486
2847
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
2487
2848
  // for some cases, since bytes.length * 8 is not actual bitLength.
2488
2849
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -2499,15 +2860,15 @@ function weierstrass(curveDef) {
2499
2860
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
2500
2861
  */
2501
2862
  function int2octets(num) {
2502
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$1, ORDER_MASK);
2863
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n$1, ORDER_MASK);
2503
2864
  // works with order, can have different size than numToField!
2504
2865
  return numberToBytesBE(num, CURVE.nByteLength);
2505
2866
  }
2506
2867
  // Steps A, D of RFC6979 3.2
2507
2868
  // Creates RFC6979 seed; converts msg/privKey to numbers.
2508
2869
  // Used only in sign, not in verify.
2509
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
2510
- // Also it can be bigger for P224 + SHA256
2870
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
2871
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
2511
2872
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
2512
2873
  if (['recovered', 'canonical'].some((k) => k in opts))
2513
2874
  throw new Error('sign() legacy options not supported');
@@ -2601,39 +2962,48 @@ function weierstrass(curveDef) {
2601
2962
  const sg = signature;
2602
2963
  msgHash = ensureBytes('msgHash', msgHash);
2603
2964
  publicKey = ensureBytes('publicKey', publicKey);
2965
+ const { lowS, prehash, format } = opts;
2966
+ // Verify opts, deduce signature format
2967
+ validateSigVerOpts(opts);
2604
2968
  if ('strict' in opts)
2605
2969
  throw new Error('options.strict was renamed to lowS');
2606
- validateSigVerOpts(opts);
2607
- const { lowS, prehash } = opts;
2970
+ if (format !== undefined && format !== 'compact' && format !== 'der')
2971
+ throw new Error('format must be compact or der');
2972
+ const isHex = typeof sg === 'string' || isBytes$1(sg);
2973
+ const isObj = !isHex &&
2974
+ !format &&
2975
+ typeof sg === 'object' &&
2976
+ sg !== null &&
2977
+ typeof sg.r === 'bigint' &&
2978
+ typeof sg.s === 'bigint';
2979
+ if (!isHex && !isObj)
2980
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
2608
2981
  let _sig = undefined;
2609
2982
  let P;
2610
2983
  try {
2611
- if (typeof sg === 'string' || isBytes$1(sg)) {
2984
+ if (isObj)
2985
+ _sig = new Signature(sg.r, sg.s);
2986
+ if (isHex) {
2612
2987
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
2613
2988
  // Since DER can also be 2*nByteLength bytes, we check for it first.
2614
2989
  try {
2615
- _sig = Signature.fromDER(sg);
2990
+ if (format !== 'compact')
2991
+ _sig = Signature.fromDER(sg);
2616
2992
  }
2617
2993
  catch (derError) {
2618
2994
  if (!(derError instanceof DER.Err))
2619
2995
  throw derError;
2620
- _sig = Signature.fromCompact(sg);
2621
2996
  }
2622
- }
2623
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
2624
- const { r, s } = sg;
2625
- _sig = new Signature(r, s);
2626
- }
2627
- else {
2628
- throw new Error('PARSE');
2997
+ if (!_sig && format !== 'der')
2998
+ _sig = Signature.fromCompact(sg);
2629
2999
  }
2630
3000
  P = Point.fromHex(publicKey);
2631
3001
  }
2632
3002
  catch (error) {
2633
- if (error.message === 'PARSE')
2634
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
2635
3003
  return false;
2636
3004
  }
3005
+ if (!_sig)
3006
+ return false;
2637
3007
  if (lowS && _sig.hasHighS())
2638
3008
  return false;
2639
3009
  if (prehash)
@@ -2661,8 +3031,12 @@ function weierstrass(curveDef) {
2661
3031
  };
2662
3032
  }
2663
3033
 
3034
+ /**
3035
+ * Utilities for short weierstrass curves, combined with noble-hashes.
3036
+ * @module
3037
+ */
2664
3038
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2665
- // connects noble-curves to noble-hashes
3039
+ /** connects noble-curves to noble-hashes */
2666
3040
  function getHash(hash) {
2667
3041
  return {
2668
3042
  hash,
@@ -2672,9 +3046,21 @@ function getHash(hash) {
2672
3046
  }
2673
3047
  function createCurve(curveDef, defHash) {
2674
3048
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
2675
- return Object.freeze({ ...create(defHash), create });
3049
+ return { ...create(defHash), create };
2676
3050
  }
2677
3051
 
3052
+ /**
3053
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
3054
+ *
3055
+ * Seems to be rigid (not backdoored)
3056
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
3057
+ *
3058
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3059
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3060
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3061
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
3062
+ * @module
3063
+ */
2678
3064
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2679
3065
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
2680
3066
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -2705,31 +3091,37 @@ function sqrtMod(y) {
2705
3091
  const t1 = (pow2(b223, _23n, P) * b22) % P;
2706
3092
  const t2 = (pow2(t1, _6n, P) * b2) % P;
2707
3093
  const root = pow2(t2, _2n$1, P);
2708
- if (!Fp.eql(Fp.sqr(root), y))
3094
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
2709
3095
  throw new Error('Cannot find square root');
2710
3096
  return root;
2711
3097
  }
2712
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3098
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
2713
3099
  /**
2714
- * secp256k1 short weierstrass curve and ECDSA signatures over it.
3100
+ * secp256k1 curve, ECDSA and ECDH methods.
3101
+ *
3102
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
3103
+ *
3104
+ * @example
3105
+ * ```js
3106
+ * import { secp256k1 } from '@noble/curves/secp256k1';
3107
+ * const priv = secp256k1.utils.randomPrivateKey();
3108
+ * const pub = secp256k1.getPublicKey(priv);
3109
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
3110
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
3111
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
3112
+ * ```
2715
3113
  */
2716
3114
  const secp256k1 = createCurve({
2717
- a: BigInt(0), // equation params: a, b
2718
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
2719
- Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
2720
- n: secp256k1N, // Curve order, total count of valid points in the field
2721
- // Base point (x, y) aka generator point
3115
+ a: BigInt(0),
3116
+ b: BigInt(7),
3117
+ Fp: Fpk1,
3118
+ n: secp256k1N,
2722
3119
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
2723
3120
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
2724
- h: BigInt(1), // Cofactor
3121
+ h: BigInt(1),
2725
3122
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
2726
- /**
2727
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
2728
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
2729
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
2730
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
2731
- */
2732
3123
  endo: {
3124
+ // Endomorphism, see above
2733
3125
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2734
3126
  splitScalar: (k) => {
2735
3127
  const n = secp256k1N;
@@ -2753,97 +3145,49 @@ const secp256k1 = createCurve({
2753
3145
  }
2754
3146
  return { k1neg, k1, k2neg, k2 };
2755
3147
  },
2756
- },
2757
- }, sha256);
2758
- // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
2759
- // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
2760
- BigInt(0);
2761
- secp256k1.ProjectivePoint;
2762
-
2763
- /**
2764
- * Generate publicKey from the privateKey.
2765
- * This creates the uncompressed publicKey,
2766
- * where 04 has stripped from left
2767
- * @returns {string}
2768
- */
2769
- var publicKeyByPrivateKey = function (privateKey) {
2770
- var key = stripHexPrefix(privateKey);
2771
- var publicKey = secp256k1.getPublicKey(key, false);
2772
- var hex = bytesToHex$1(publicKey);
2773
- return decompress(hex);
2774
- };
2775
-
2776
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2777
- const _32n = /* @__PURE__ */ BigInt(32);
2778
- // We are not using BigUint64Array, because they are extremely slow as per 2022
2779
- function fromBig(n, le = false) {
2780
- if (le)
2781
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
2782
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
2783
- }
2784
- function split(lst, le = false) {
2785
- let Ah = new Uint32Array(lst.length);
2786
- let Al = new Uint32Array(lst.length);
2787
- for (let i = 0; i < lst.length; i++) {
2788
- const { h, l } = fromBig(lst[i], le);
2789
- [Ah[i], Al[i]] = [h, l];
2790
- }
2791
- return [Ah, Al];
2792
- }
2793
- const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
2794
- // for Shift in [0, 32)
2795
- const shrSH = (h, _l, s) => h >>> s;
2796
- const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
2797
- // Right rotate for Shift in [1, 32)
2798
- const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
2799
- const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
2800
- // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
2801
- const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
2802
- const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
2803
- // Right rotate for shift===32 (just swaps l&h)
2804
- const rotr32H = (_h, l) => l;
2805
- const rotr32L = (h, _l) => h;
2806
- // Left rotate for Shift in [1, 32)
2807
- const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
2808
- const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
2809
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
2810
- const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
2811
- const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
2812
- // JS uses 32-bit signed integers for bitwise operations which means we cannot
2813
- // simple take carry out of low bit sum by shift, we need to use division.
2814
- function add(Ah, Al, Bh, Bl) {
2815
- const l = (Al >>> 0) + (Bl >>> 0);
2816
- return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
2817
- }
2818
- // Addition with more than 2 elements
2819
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
2820
- const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
2821
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
2822
- const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
2823
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
2824
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
2825
- // prettier-ignore
2826
- const u64 = {
2827
- fromBig, split, toBig,
2828
- shrSH, shrSL,
2829
- rotrSH, rotrSL, rotrBH, rotrBL,
2830
- rotr32H, rotr32L,
2831
- rotlSH, rotlSL, rotlBH, rotlBL,
2832
- add, add3L, add3H, add4L, add4H, add5H, add5L,
3148
+ },
3149
+ }, sha256);
3150
+ // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3151
+ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3152
+ BigInt(0);
3153
+ secp256k1.ProjectivePoint;
3154
+
3155
+ /**
3156
+ * Generate publicKey from the privateKey.
3157
+ * This creates the uncompressed publicKey,
3158
+ * where 04 has stripped from left
3159
+ * @returns {string}
3160
+ */
3161
+ var publicKeyByPrivateKey = function (privateKey) {
3162
+ var key = stripHexPrefix(privateKey);
3163
+ var publicKey = secp256k1.getPublicKey(key, false);
3164
+ var hex = bytesToHex$1(publicKey);
3165
+ return decompress(hex);
2833
3166
  };
2834
3167
 
2835
- // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
2836
- // It's called a sponge function.
3168
+ /**
3169
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
3170
+ * Different from older hashes, the internal state is bigger than output size.
3171
+ *
3172
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
3173
+ * [Website](https://keccak.team/keccak.html),
3174
+ * [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).
3175
+ *
3176
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
3177
+ * @module
3178
+ */
3179
+ // No __PURE__ annotations in sha3 header:
3180
+ // EVERYTHING is in fact used on every export.
2837
3181
  // Various per round constants calculations
3182
+ const _0n = BigInt(0);
3183
+ const _1n = BigInt(1);
3184
+ const _2n = BigInt(2);
3185
+ const _7n = BigInt(7);
3186
+ const _256n = BigInt(256);
3187
+ const _0x71n = BigInt(0x71);
2838
3188
  const SHA3_PI = [];
2839
3189
  const SHA3_ROTL = [];
2840
3190
  const _SHA3_IOTA = [];
2841
- const _0n = /* @__PURE__ */ BigInt(0);
2842
- const _1n = /* @__PURE__ */ BigInt(1);
2843
- const _2n = /* @__PURE__ */ BigInt(2);
2844
- const _7n = /* @__PURE__ */ BigInt(7);
2845
- const _256n = /* @__PURE__ */ BigInt(256);
2846
- const _0x71n = /* @__PURE__ */ BigInt(0x71);
2847
3191
  for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2848
3192
  // Pi
2849
3193
  [x, y] = [y, (2 * x + 3 * y) % 5];
@@ -2859,11 +3203,13 @@ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2859
3203
  }
2860
3204
  _SHA3_IOTA.push(t);
2861
3205
  }
2862
- const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);
3206
+ const IOTAS = split(_SHA3_IOTA, true);
3207
+ const SHA3_IOTA_H = IOTAS[0];
3208
+ const SHA3_IOTA_L = IOTAS[1];
2863
3209
  // Left rotation (without 0, 32, 64)
2864
3210
  const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
2865
3211
  const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
2866
- // Same as keccakf1600, but allows to skip some rounds
3212
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
2867
3213
  function keccakP(s, rounds = 24) {
2868
3214
  const B = new Uint32Array(5 * 2);
2869
3215
  // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
@@ -2907,42 +3253,47 @@ function keccakP(s, rounds = 24) {
2907
3253
  s[0] ^= SHA3_IOTA_H[round];
2908
3254
  s[1] ^= SHA3_IOTA_L[round];
2909
3255
  }
2910
- B.fill(0);
3256
+ clean$1(B);
2911
3257
  }
3258
+ /** Keccak sponge function. */
2912
3259
  class Keccak extends Hash {
2913
3260
  // NOTE: we accept arguments in bytes instead of bits here.
2914
3261
  constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2915
3262
  super();
3263
+ this.pos = 0;
3264
+ this.posOut = 0;
3265
+ this.finished = false;
3266
+ this.destroyed = false;
3267
+ this.enableXOF = false;
2916
3268
  this.blockLen = blockLen;
2917
3269
  this.suffix = suffix;
2918
3270
  this.outputLen = outputLen;
2919
3271
  this.enableXOF = enableXOF;
2920
3272
  this.rounds = rounds;
2921
- this.pos = 0;
2922
- this.posOut = 0;
2923
- this.finished = false;
2924
- this.destroyed = false;
2925
3273
  // Can be passed from user as dkLen
2926
- number(outputLen);
3274
+ anumber(outputLen);
2927
3275
  // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
2928
- if (0 >= this.blockLen || this.blockLen >= 200)
2929
- throw new Error('Sha3 supports only keccak-f1600 function');
3276
+ // 0 < blockLen < 200
3277
+ if (!(0 < blockLen && blockLen < 200))
3278
+ throw new Error('only keccak-f1600 function is supported');
2930
3279
  this.state = new Uint8Array(200);
2931
3280
  this.state32 = u32$1(this.state);
2932
3281
  }
3282
+ clone() {
3283
+ return this._cloneInto();
3284
+ }
2933
3285
  keccak() {
2934
- if (!isLE$1)
2935
- byteSwap32(this.state32);
3286
+ swap32IfBE(this.state32);
2936
3287
  keccakP(this.state32, this.rounds);
2937
- if (!isLE$1)
2938
- byteSwap32(this.state32);
3288
+ swap32IfBE(this.state32);
2939
3289
  this.posOut = 0;
2940
3290
  this.pos = 0;
2941
3291
  }
2942
3292
  update(data) {
2943
- exists(this);
2944
- const { blockLen, state } = this;
3293
+ aexists(this);
2945
3294
  data = toBytes(data);
3295
+ abytes$3(data);
3296
+ const { blockLen, state } = this;
2946
3297
  const len = data.length;
2947
3298
  for (let pos = 0; pos < len;) {
2948
3299
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -2966,8 +3317,8 @@ class Keccak extends Hash {
2966
3317
  this.keccak();
2967
3318
  }
2968
3319
  writeInto(out) {
2969
- exists(this, false);
2970
- bytes$1(out);
3320
+ aexists(this, false);
3321
+ abytes$3(out);
2971
3322
  this.finish();
2972
3323
  const bufferOut = this.state;
2973
3324
  const { blockLen } = this;
@@ -2988,11 +3339,11 @@ class Keccak extends Hash {
2988
3339
  return this.writeInto(out);
2989
3340
  }
2990
3341
  xof(bytes) {
2991
- number(bytes);
3342
+ anumber(bytes);
2992
3343
  return this.xofInto(new Uint8Array(bytes));
2993
3344
  }
2994
3345
  digestInto(out) {
2995
- output$1(out, this);
3346
+ aoutput(out, this);
2996
3347
  if (this.finished)
2997
3348
  throw new Error('digest() was already called');
2998
3349
  this.writeInto(out);
@@ -3004,7 +3355,7 @@ class Keccak extends Hash {
3004
3355
  }
3005
3356
  destroy() {
3006
3357
  this.destroyed = true;
3007
- this.state.fill(0);
3358
+ clean$1(this.state);
3008
3359
  }
3009
3360
  _cloneInto(to) {
3010
3361
  const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
@@ -3022,12 +3373,9 @@ class Keccak extends Hash {
3022
3373
  return to;
3023
3374
  }
3024
3375
  }
3025
- const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));
3026
- /**
3027
- * keccak-256 hash function. Different from SHA3-256.
3028
- * @param message - that would be hashed
3029
- */
3030
- const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);
3376
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
3377
+ /** keccak-256 hash function. Different from SHA3-256. */
3378
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
3031
3379
 
3032
3380
  const keccak256$1 = (() => {
3033
3381
  const k = wrapHash(keccak_256);
@@ -3071,162 +3419,6 @@ var createIdentity = function (entropy) {
3071
3419
  return identity;
3072
3420
  };
3073
3421
 
3074
- // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
3075
- // prettier-ignore
3076
- const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
3077
- '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
3078
- '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
3079
- '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
3080
- '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
3081
- '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
3082
- '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
3083
- '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
3084
- '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
3085
- '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
3086
- '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
3087
- '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
3088
- '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
3089
- '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
3090
- '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
3091
- '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
3092
- '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
3093
- '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
3094
- '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
3095
- '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
3096
- '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
3097
- ].map(n => BigInt(n))))();
3098
- // Temporary buffer, not used to store anything between runs
3099
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
3100
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
3101
- class SHA512 extends HashMD {
3102
- constructor() {
3103
- super(128, 64, 16, false);
3104
- // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
3105
- // Also looks cleaner and easier to verify with spec.
3106
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
3107
- // h -- high 32 bits, l -- low 32 bits
3108
- this.Ah = 0x6a09e667 | 0;
3109
- this.Al = 0xf3bcc908 | 0;
3110
- this.Bh = 0xbb67ae85 | 0;
3111
- this.Bl = 0x84caa73b | 0;
3112
- this.Ch = 0x3c6ef372 | 0;
3113
- this.Cl = 0xfe94f82b | 0;
3114
- this.Dh = 0xa54ff53a | 0;
3115
- this.Dl = 0x5f1d36f1 | 0;
3116
- this.Eh = 0x510e527f | 0;
3117
- this.El = 0xade682d1 | 0;
3118
- this.Fh = 0x9b05688c | 0;
3119
- this.Fl = 0x2b3e6c1f | 0;
3120
- this.Gh = 0x1f83d9ab | 0;
3121
- this.Gl = 0xfb41bd6b | 0;
3122
- this.Hh = 0x5be0cd19 | 0;
3123
- this.Hl = 0x137e2179 | 0;
3124
- }
3125
- // prettier-ignore
3126
- get() {
3127
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3128
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
3129
- }
3130
- // prettier-ignore
3131
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
3132
- this.Ah = Ah | 0;
3133
- this.Al = Al | 0;
3134
- this.Bh = Bh | 0;
3135
- this.Bl = Bl | 0;
3136
- this.Ch = Ch | 0;
3137
- this.Cl = Cl | 0;
3138
- this.Dh = Dh | 0;
3139
- this.Dl = Dl | 0;
3140
- this.Eh = Eh | 0;
3141
- this.El = El | 0;
3142
- this.Fh = Fh | 0;
3143
- this.Fl = Fl | 0;
3144
- this.Gh = Gh | 0;
3145
- this.Gl = Gl | 0;
3146
- this.Hh = Hh | 0;
3147
- this.Hl = Hl | 0;
3148
- }
3149
- process(view, offset) {
3150
- // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
3151
- for (let i = 0; i < 16; i++, offset += 4) {
3152
- SHA512_W_H[i] = view.getUint32(offset);
3153
- SHA512_W_L[i] = view.getUint32((offset += 4));
3154
- }
3155
- for (let i = 16; i < 80; i++) {
3156
- // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
3157
- const W15h = SHA512_W_H[i - 15] | 0;
3158
- const W15l = SHA512_W_L[i - 15] | 0;
3159
- const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
3160
- const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
3161
- // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
3162
- const W2h = SHA512_W_H[i - 2] | 0;
3163
- const W2l = SHA512_W_L[i - 2] | 0;
3164
- const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
3165
- const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
3166
- // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
3167
- const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
3168
- const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
3169
- SHA512_W_H[i] = SUMh | 0;
3170
- SHA512_W_L[i] = SUMl | 0;
3171
- }
3172
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3173
- // Compression function main loop, 80 rounds
3174
- for (let i = 0; i < 80; i++) {
3175
- // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
3176
- const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
3177
- const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
3178
- //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3179
- const CHIh = (Eh & Fh) ^ (~Eh & Gh);
3180
- const CHIl = (El & Fl) ^ (~El & Gl);
3181
- // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
3182
- // prettier-ignore
3183
- const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
3184
- const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
3185
- const T1l = T1ll | 0;
3186
- // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
3187
- const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
3188
- const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
3189
- const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
3190
- const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
3191
- Hh = Gh | 0;
3192
- Hl = Gl | 0;
3193
- Gh = Fh | 0;
3194
- Gl = Fl | 0;
3195
- Fh = Eh | 0;
3196
- Fl = El | 0;
3197
- ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
3198
- Dh = Ch | 0;
3199
- Dl = Cl | 0;
3200
- Ch = Bh | 0;
3201
- Cl = Bl | 0;
3202
- Bh = Ah | 0;
3203
- Bl = Al | 0;
3204
- const All = u64.add3L(T1l, sigma0l, MAJl);
3205
- Ah = u64.add3H(All, T1h, sigma0h, MAJh);
3206
- Al = All | 0;
3207
- }
3208
- // Add the compressed chunk to the current hash value
3209
- ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
3210
- ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
3211
- ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
3212
- ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
3213
- ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
3214
- ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
3215
- ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
3216
- ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
3217
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
3218
- }
3219
- roundClean() {
3220
- SHA512_W_H.fill(0);
3221
- SHA512_W_L.fill(0);
3222
- }
3223
- destroy() {
3224
- this.buffer.fill(0);
3225
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
3226
- }
3227
- }
3228
- const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
3229
-
3230
3422
  /**
3231
3423
  * signs the given message
3232
3424
  * @param {string} privateKey
@@ -3237,7 +3429,7 @@ var sign = function (privateKey, hash) {
3237
3429
  var hashWith0x = addLeading0x(hash);
3238
3430
  if (hashWith0x.length !== 66)
3239
3431
  throw new Error('Can only sign hashes, given: ' + hash);
3240
- var sigObj = secp256k1.sign(hexToBytes$1(stripHexPrefix(hash)), hexToBytes$1(stripHexPrefix(privateKey)));
3432
+ var sigObj = secp256k1.sign(hexToBytes(stripHexPrefix(hash)), hexToBytes(stripHexPrefix(privateKey)));
3241
3433
  var recoveryId = sigObj.recovery === 1 ? '1c' : '1b';
3242
3434
  var newSignature = '0x' + sigObj.toCompactHex() + recoveryId;
3243
3435
  return newSignature;
@@ -3249,33 +3441,129 @@ var hmacSha256Sign = function (key, msg) {
3249
3441
 
3250
3442
  const sha512 = wrapHash(sha512$1);
3251
3443
 
3444
+ /**
3445
+ * Utilities for hex, bytes, CSPRNG.
3446
+ * @module
3447
+ */
3448
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3449
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
3252
3450
  function isBytes(a) {
3253
- return (a instanceof Uint8Array ||
3254
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
3451
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3255
3452
  }
3256
- function bytes(b, ...lengths) {
3453
+ /** Asserts something is Uint8Array. */
3454
+ function abytes(b, ...lengths) {
3257
3455
  if (!isBytes(b))
3258
3456
  throw new Error('Uint8Array expected');
3259
3457
  if (lengths.length > 0 && !lengths.includes(b.length))
3260
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
3458
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3459
+ }
3460
+ /** Cast u8 / u16 / u32 to u8. */
3461
+ function u8(arr) {
3462
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3463
+ }
3464
+ /** Cast u8 / u16 / u32 to u32. */
3465
+ function u32(arr) {
3466
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3467
+ }
3468
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
3469
+ function clean(...arrays) {
3470
+ for (let i = 0; i < arrays.length; i++) {
3471
+ arrays[i].fill(0);
3472
+ }
3473
+ }
3474
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
3475
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
3476
+ /**
3477
+ * Checks if two U8A use same underlying buffer and overlaps.
3478
+ * This is invalid and can corrupt data.
3479
+ */
3480
+ function overlapBytes(a, b) {
3481
+ return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
3482
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
3483
+ b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
3484
+ );
3485
+ }
3486
+ /**
3487
+ * If input and output overlap and input starts before output, we will overwrite end of input before
3488
+ * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
3489
+ */
3490
+ function complexOverlapBytes(input, output) {
3491
+ // This is very cursed. It works somehow, but I'm completely unsure,
3492
+ // reasoning about overlapping aligned windows is very hard.
3493
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
3494
+ throw new Error('complex overlap of input and output is not supported');
3261
3495
  }
3262
-
3263
- /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3264
- // Cast array to different type
3265
- const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3266
- const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3267
- // big-endian hardware is rare. Just in case someone still decides to run ciphers:
3268
- // early-throw an error because we don't support BE yet.
3269
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3270
- if (!isLE)
3271
- throw new Error('Non little-endian hardware is not supported');
3272
3496
  /**
3497
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
3273
3498
  * @__NO_SIDE_EFFECTS__
3274
3499
  */
3275
- const wrapCipher = (params, c) => {
3276
- Object.assign(c, params);
3277
- return c;
3500
+ const wrapCipher = (params, constructor) => {
3501
+ function wrappedCipher(key, ...args) {
3502
+ // Validate key
3503
+ abytes(key);
3504
+ // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
3505
+ if (!isLE)
3506
+ throw new Error('Non little-endian hardware is not yet supported');
3507
+ // Validate nonce if nonceLength is present
3508
+ if (params.nonceLength !== undefined) {
3509
+ const nonce = args[0];
3510
+ if (!nonce)
3511
+ throw new Error('nonce / iv required');
3512
+ if (params.varSizeNonce)
3513
+ abytes(nonce);
3514
+ else
3515
+ abytes(nonce, params.nonceLength);
3516
+ }
3517
+ // Validate AAD if tagLength present
3518
+ const tagl = params.tagLength;
3519
+ if (tagl && args[1] !== undefined) {
3520
+ abytes(args[1]);
3521
+ }
3522
+ const cipher = constructor(key, ...args);
3523
+ const checkOutput = (fnLength, output) => {
3524
+ if (output !== undefined) {
3525
+ if (fnLength !== 2)
3526
+ throw new Error('cipher output not supported');
3527
+ abytes(output);
3528
+ }
3529
+ };
3530
+ // Create wrapped cipher with validation and single-use encryption
3531
+ let called = false;
3532
+ const wrCipher = {
3533
+ encrypt(data, output) {
3534
+ if (called)
3535
+ throw new Error('cannot encrypt() twice with same key + nonce');
3536
+ called = true;
3537
+ abytes(data);
3538
+ checkOutput(cipher.encrypt.length, output);
3539
+ return cipher.encrypt(data, output);
3540
+ },
3541
+ decrypt(data, output) {
3542
+ abytes(data);
3543
+ if (tagl && data.length < tagl)
3544
+ throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
3545
+ checkOutput(cipher.decrypt.length, output);
3546
+ return cipher.decrypt(data, output);
3547
+ },
3548
+ };
3549
+ return wrCipher;
3550
+ }
3551
+ Object.assign(wrappedCipher, params);
3552
+ return wrappedCipher;
3278
3553
  };
3554
+ /**
3555
+ * By default, returns u8a of length.
3556
+ * When out is available, it checks it for validity and uses it.
3557
+ */
3558
+ function getOutput(expectedLength, out, onlyAligned = true) {
3559
+ if (out === undefined)
3560
+ return new Uint8Array(expectedLength);
3561
+ if (out.length !== expectedLength)
3562
+ throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
3563
+ if (onlyAligned && !isAligned32(out))
3564
+ throw new Error('invalid output, must be aligned');
3565
+ return out;
3566
+ }
3279
3567
  // Is byte array aligned to 4 byte offset (u32)?
3280
3568
  function isAligned32(bytes) {
3281
3569
  return bytes.byteOffset % 4 === 0;
@@ -3284,26 +3572,23 @@ function isAligned32(bytes) {
3284
3572
  function copyBytes(bytes) {
3285
3573
  return Uint8Array.from(bytes);
3286
3574
  }
3287
- function clean(...arrays) {
3288
- for (let i = 0; i < arrays.length; i++) {
3289
- arrays[i].fill(0);
3290
- }
3291
- }
3292
-
3293
- // prettier-ignore
3294
- /*
3295
- AES (Advanced Encryption Standard) aka Rijndael block cipher.
3296
-
3297
- Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
3298
- 1. **S-box**, table substitution
3299
- 2. **Shift rows**, cyclic shift left of all rows of data array
3300
- 3. **Mix columns**, multiplying every column by fixed polynomial
3301
- 4. **Add round key**, round_key xor i-th column of array
3302
3575
 
3303
- Resources:
3304
- - FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf
3305
- - Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf
3306
- */
3576
+ /**
3577
+ * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
3578
+ * a.k.a. Advanced Encryption Standard
3579
+ * is a variant of Rijndael block cipher, standardized by NIST in 2001.
3580
+ * We provide the fastest available pure JS implementation.
3581
+ *
3582
+ * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
3583
+ * 1. **S-box**, table substitution
3584
+ * 2. **Shift rows**, cyclic shift left of all rows of data array
3585
+ * 3. **Mix columns**, multiplying every column by fixed polynomial
3586
+ * 4. **Add round key**, round_key xor i-th column of array
3587
+ *
3588
+ * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
3589
+ * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
3590
+ * @module
3591
+ */
3307
3592
  const BLOCK_SIZE = 16;
3308
3593
  const BLOCK_SIZE32 = 4;
3309
3594
  const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
@@ -3373,11 +3658,12 @@ const xPowers = /* @__PURE__ */ (() => {
3373
3658
  p[i] = x;
3374
3659
  return p;
3375
3660
  })();
3661
+ /** Key expansion used in CTR. */
3376
3662
  function expandKeyLE(key) {
3377
- bytes(key);
3663
+ abytes(key);
3378
3664
  const len = key.length;
3379
3665
  if (![16, 24, 32].includes(len))
3380
- throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);
3666
+ throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
3381
3667
  const { sbox2 } = tableEncoding;
3382
3668
  const toClean = [];
3383
3669
  if (!isAligned32(key))
@@ -3467,22 +3753,13 @@ function decrypt$2(xk, s0, s1, s2, s3) {
3467
3753
  const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
3468
3754
  return { s0: t0, s1: t1, s2: t2, s3: t3 };
3469
3755
  }
3470
- function getDst(len, dst) {
3471
- if (dst === undefined)
3472
- return new Uint8Array(len);
3473
- bytes(dst);
3474
- if (dst.length < len)
3475
- throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);
3476
- if (!isAligned32(dst))
3477
- throw new Error('unaligned dst');
3478
- return dst;
3479
- }
3480
3756
  // TODO: investigate merging with ctr32
3481
3757
  function ctrCounter(xk, nonce, src, dst) {
3482
- bytes(nonce, BLOCK_SIZE);
3483
- bytes(src);
3758
+ abytes(nonce, BLOCK_SIZE);
3759
+ abytes(src);
3484
3760
  const srcLen = src.length;
3485
- dst = getDst(srcLen, dst);
3761
+ dst = getOutput(srcLen, dst);
3762
+ complexOverlapBytes(src, dst);
3486
3763
  const ctr = nonce;
3487
3764
  const c32 = u32(ctr);
3488
3765
  // Fill block (empty, ctr=0)
@@ -3520,13 +3797,11 @@ function ctrCounter(xk, nonce, src, dst) {
3520
3797
  * CTR: counter mode. Creates stream cipher.
3521
3798
  * Requires good IV. Parallelizable. OK, but no MAC.
3522
3799
  */
3523
- const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {
3524
- bytes(key);
3525
- bytes(nonce, BLOCK_SIZE);
3800
+ const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
3526
3801
  function processCtr(buf, dst) {
3527
- bytes(buf);
3802
+ abytes(buf);
3528
3803
  if (dst !== undefined) {
3529
- bytes(dst);
3804
+ abytes(dst);
3530
3805
  if (!isAligned32(dst))
3531
3806
  throw new Error('unaligned destination');
3532
3807
  }
@@ -3545,13 +3820,13 @@ const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, non
3545
3820
  };
3546
3821
  });
3547
3822
  function validateBlockDecrypt(data) {
3548
- bytes(data);
3823
+ abytes(data);
3549
3824
  if (data.length % BLOCK_SIZE !== 0) {
3550
- throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);
3825
+ throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
3551
3826
  }
3552
3827
  }
3553
3828
  function validateBlockEncrypt(plaintext, pcks5, dst) {
3554
- bytes(plaintext);
3829
+ abytes(plaintext);
3555
3830
  let outLen = plaintext.length;
3556
3831
  const remaining = outLen % BLOCK_SIZE;
3557
3832
  if (!pcks5 && remaining !== 0)
@@ -3565,9 +3840,10 @@ function validateBlockEncrypt(plaintext, pcks5, dst) {
3565
3840
  left = BLOCK_SIZE; // if no bytes left, create empty padding block
3566
3841
  outLen = outLen + left;
3567
3842
  }
3568
- const out = getDst(outLen, dst);
3569
- const o = u32(out);
3570
- return { b, o, out };
3843
+ dst = getOutput(outLen, dst);
3844
+ complexOverlapBytes(plaintext, dst);
3845
+ const o = u32(dst);
3846
+ return { b, o, out: dst };
3571
3847
  }
3572
3848
  function validatePCKS(data, pcks5) {
3573
3849
  if (!pcks5)
@@ -3597,9 +3873,7 @@ function padPCKS(left) {
3597
3873
  * CBC: Cipher-Block-Chaining. Key is previous round’s block.
3598
3874
  * Fragile: needs proper padding. Unauthenticated: needs MAC.
3599
3875
  */
3600
- const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {
3601
- bytes(key);
3602
- bytes(iv, 16);
3876
+ const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
3603
3877
  const pcks5 = !opts.disablePadding;
3604
3878
  return {
3605
3879
  encrypt(plaintext, dst) {
@@ -3635,11 +3909,12 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
3635
3909
  if (!isAligned32(_iv))
3636
3910
  toClean.push((_iv = copyBytes(_iv)));
3637
3911
  const n32 = u32(_iv);
3638
- const out = getDst(ciphertext.length, dst);
3912
+ dst = getOutput(ciphertext.length, dst);
3639
3913
  if (!isAligned32(ciphertext))
3640
3914
  toClean.push((ciphertext = copyBytes(ciphertext)));
3915
+ complexOverlapBytes(ciphertext, dst);
3641
3916
  const b = u32(ciphertext);
3642
- const o = u32(out);
3917
+ const o = u32(dst);
3643
3918
  // prettier-ignore
3644
3919
  let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
3645
3920
  for (let i = 0; i + 4 <= b.length;) {
@@ -3650,18 +3925,18 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
3650
3925
  (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
3651
3926
  }
3652
3927
  clean(...toClean);
3653
- return validatePCKS(out, pcks5);
3928
+ return validatePCKS(dst, pcks5);
3654
3929
  },
3655
3930
  };
3656
3931
  });
3657
- new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
3658
3932
 
3659
3933
  function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
3660
3934
  if (!mode.startsWith("aes-")) {
3661
3935
  throw new Error("AES: unsupported mode");
3662
3936
  }
3663
3937
  const len = key.length;
3664
- if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) {
3938
+ if ((mode.startsWith("aes-128") && len !== 16) ||
3939
+ (mode.startsWith("aes-256") && len !== 32)) {
3665
3940
  throw new Error("AES: wrong key length");
3666
3941
  }
3667
3942
  if (iv.length !== 16) {
@@ -3692,14 +3967,14 @@ function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnable
3692
3967
  * @returns {Encrypted} The encrypted message.
3693
3968
  */
3694
3969
  var encrypt = function (publicKeyTo, msg, options) {
3695
- var ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes$1(options.ephemPrivateKey) : getRandomBytesSync(32);
3696
- var iv = (options === null || options === void 0 ? void 0 : options.iv) ? hexToBytes$1(options.iv) : getRandomBytesSync(16);
3970
+ var ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes(options.ephemPrivateKey) : getRandomBytesSync(32);
3971
+ var iv = (options === null || options === void 0 ? void 0 : options.iv) ? hexToBytes(options.iv) : getRandomBytesSync(16);
3697
3972
  var ephemPublicKey = secp256k1.getPublicKey(ephemPrivateKey, false);
3698
- var sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes$1(publicKeyTo), true).slice(1);
3973
+ var sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes(publicKeyTo), true).slice(1);
3699
3974
  var hash = sha512(sharedSecret);
3700
3975
  var encryptionKey = hash.subarray(0, 32);
3701
3976
  var macKey = hash.subarray(32);
3702
- var message = utf8ToBytes$1(msg);
3977
+ var message = utf8ToBytes(msg);
3703
3978
  var data = encrypt$1(message, encryptionKey, iv, 'aes-256-cbc');
3704
3979
  var dataToMac = concatUint8Arrays([iv, ephemPublicKey, data]);
3705
3980
  var mac = hmacSha256Sign(macKey, dataToMac);
@@ -3717,11 +3992,11 @@ var encrypt = function (publicKeyTo, msg, options) {
3717
3992
  * @returns {string} The decrypted message.
3718
3993
  */
3719
3994
  var decrypt = function (privateKey, opts) {
3720
- var sharedSecret = secp256k1.getSharedSecret(hexToBytes$1(privateKey), opts.ephemPublicKey, true).slice(1);
3995
+ var sharedSecret = secp256k1.getSharedSecret(hexToBytes(privateKey), opts.ephemPublicKey, true).slice(1);
3721
3996
  var hash = sha512(sharedSecret);
3722
3997
  var encryptionKey = hash.subarray(0, 32);
3723
- var ciphertext = hexToBytes$1(opts.ciphertext);
3724
- var iv = hexToBytes$1(opts.iv);
3998
+ var ciphertext = hexToBytes(opts.ciphertext);
3999
+ var iv = hexToBytes(opts.iv);
3725
4000
  var decrypted = decrypt$1(ciphertext, encryptionKey, iv, 'aes-256-cbc');
3726
4001
  return bytesToUtf8(decrypted);
3727
4002
  };
@@ -3741,9 +4016,9 @@ var decryptWithPrivateKey = function (privateKey, encrypted) {
3741
4016
  };
3742
4017
 
3743
4018
  var solidityPackedKeccak256 = function (value) {
3744
- var bytes = utf8ToBytes$1(value);
4019
+ var bytes = utf8ToBytes(value);
3745
4020
  var hex = addLeading0x(bytesToHex$1(bytes));
3746
- var hash = keccak256$1(hexToBytes$1(hex));
4021
+ var hash = keccak256$1(hexToBytes(hex));
3747
4022
  return addLeading0x(bytesToHex$1(hash));
3748
4023
  };
3749
4024
  var keccak256 = function (params) {
@@ -3758,19 +4033,19 @@ function output(out = (len) => new Uint8Array(len), length, value) {
3758
4033
  if (typeof out === "function") {
3759
4034
  out = out(length);
3760
4035
  }
3761
- assertBytes(out, length);
4036
+ abytes$1(out, length);
3762
4037
  if (value) {
3763
4038
  out.set(value);
3764
4039
  }
3765
4040
  return out;
3766
4041
  }
3767
4042
  function getSignature(signature) {
3768
- assertBytes(signature, 64);
4043
+ abytes$1(signature, 64);
3769
4044
  return secp256k1.Signature.fromCompact(signature);
3770
4045
  }
3771
4046
  function ecdsaRecover(signature, recid, msgHash, compressed = true, out) {
3772
- assertBytes(msgHash, 32);
3773
- assertBool(compressed);
4047
+ abytes$1(msgHash, 32);
4048
+ abool("compressed", compressed);
3774
4049
  const sign = getSignature(signature);
3775
4050
  const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash);
3776
4051
  return output(out, compressed ? 33 : 65, point.toRawBytes(compressed));
@@ -3788,7 +4063,7 @@ var recoverPublicKey = function (signature, hash) {
3788
4063
  var sigOnly = noHex.substring(0, noHex.length - 2); // all but last 2 chars
3789
4064
  var vValue = noHex.slice(-2); // last 2 chars
3790
4065
  var recoveryNumber = vValue === '1c' ? 1 : 0;
3791
- var pubKey = bytesToHex$1(ecdsaRecover(hexToBytes$1(sigOnly), recoveryNumber, hexToBytes$1(stripHexPrefix(hash)), false));
4066
+ var pubKey = bytesToHex$1(ecdsaRecover(hexToBytes(sigOnly), recoveryNumber, hexToBytes(stripHexPrefix(hash)), false));
3792
4067
  // remove trailing '04'
3793
4068
  pubKey = pubKey.slice(2);
3794
4069
  return pubKey;
@@ -3913,227 +4188,19 @@ const global$1 = (typeof global !== "undefined" ? global :
3913
4188
  typeof self !== "undefined" ? self :
3914
4189
  typeof window !== "undefined" ? window : {});
3915
4190
 
3916
- // shim for using process in browser
3917
- // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
3918
-
3919
- function defaultSetTimout() {
3920
- throw new Error('setTimeout has not been defined');
3921
- }
3922
- function defaultClearTimeout () {
3923
- throw new Error('clearTimeout has not been defined');
3924
- }
3925
- var cachedSetTimeout = defaultSetTimout;
3926
- var cachedClearTimeout = defaultClearTimeout;
3927
- if (typeof global$1.setTimeout === 'function') {
3928
- cachedSetTimeout = setTimeout;
3929
- }
3930
- if (typeof global$1.clearTimeout === 'function') {
3931
- cachedClearTimeout = clearTimeout;
3932
- }
3933
-
3934
- function runTimeout(fun) {
3935
- if (cachedSetTimeout === setTimeout) {
3936
- //normal enviroments in sane situations
3937
- return setTimeout(fun, 0);
3938
- }
3939
- // if setTimeout wasn't available but was latter defined
3940
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3941
- cachedSetTimeout = setTimeout;
3942
- return setTimeout(fun, 0);
3943
- }
3944
- try {
3945
- // when when somebody has screwed with setTimeout but no I.E. maddness
3946
- return cachedSetTimeout(fun, 0);
3947
- } catch(e){
3948
- try {
3949
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3950
- return cachedSetTimeout.call(null, fun, 0);
3951
- } catch(e){
3952
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
3953
- return cachedSetTimeout.call(this, fun, 0);
3954
- }
3955
- }
3956
-
3957
-
3958
- }
3959
- function runClearTimeout(marker) {
3960
- if (cachedClearTimeout === clearTimeout) {
3961
- //normal enviroments in sane situations
3962
- return clearTimeout(marker);
3963
- }
3964
- // if clearTimeout wasn't available but was latter defined
3965
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3966
- cachedClearTimeout = clearTimeout;
3967
- return clearTimeout(marker);
3968
- }
3969
- try {
3970
- // when when somebody has screwed with setTimeout but no I.E. maddness
3971
- return cachedClearTimeout(marker);
3972
- } catch (e){
3973
- try {
3974
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3975
- return cachedClearTimeout.call(null, marker);
3976
- } catch (e){
3977
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
3978
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3979
- return cachedClearTimeout.call(this, marker);
3980
- }
3981
- }
3982
-
3983
-
3984
-
3985
- }
3986
- var queue = [];
3987
- var draining = false;
3988
- var currentQueue;
3989
- var queueIndex = -1;
3990
-
3991
- function cleanUpNextTick() {
3992
- if (!draining || !currentQueue) {
3993
- return;
3994
- }
3995
- draining = false;
3996
- if (currentQueue.length) {
3997
- queue = currentQueue.concat(queue);
3998
- } else {
3999
- queueIndex = -1;
4000
- }
4001
- if (queue.length) {
4002
- drainQueue();
4003
- }
4004
- }
4005
-
4006
- function drainQueue() {
4007
- if (draining) {
4008
- return;
4009
- }
4010
- var timeout = runTimeout(cleanUpNextTick);
4011
- draining = true;
4012
-
4013
- var len = queue.length;
4014
- while(len) {
4015
- currentQueue = queue;
4016
- queue = [];
4017
- while (++queueIndex < len) {
4018
- if (currentQueue) {
4019
- currentQueue[queueIndex].run();
4020
- }
4021
- }
4022
- queueIndex = -1;
4023
- len = queue.length;
4024
- }
4025
- currentQueue = null;
4026
- draining = false;
4027
- runClearTimeout(timeout);
4028
- }
4029
- function nextTick(fun) {
4030
- var args = new Array(arguments.length - 1);
4031
- if (arguments.length > 1) {
4032
- for (var i = 1; i < arguments.length; i++) {
4033
- args[i - 1] = arguments[i];
4034
- }
4035
- }
4036
- queue.push(new Item(fun, args));
4037
- if (queue.length === 1 && !draining) {
4038
- runTimeout(drainQueue);
4039
- }
4040
- }
4041
- // v8 likes predictible objects
4042
- function Item(fun, array) {
4043
- this.fun = fun;
4044
- this.array = array;
4045
- }
4046
- Item.prototype.run = function () {
4047
- this.fun.apply(null, this.array);
4048
- };
4049
- var title = 'browser';
4050
- var platform = 'browser';
4051
- var browser = true;
4052
4191
  var env = {};
4053
- var argv = [];
4054
- var version = ''; // empty string to avoid regexp issues
4055
- var versions = {};
4056
- var release = {};
4057
- var config = {};
4058
-
4059
- function noop() {}
4060
-
4061
- var on = noop;
4062
- var addListener = noop;
4063
- var once = noop;
4064
- var off = noop;
4065
- var removeListener = noop;
4066
- var removeAllListeners = noop;
4067
- var emit = noop;
4068
-
4069
- function binding(name) {
4070
- throw new Error('process.binding is not supported');
4071
- }
4072
-
4073
- function cwd () { return '/' }
4074
- function chdir (dir) {
4075
- throw new Error('process.chdir is not supported');
4076
- }function umask() { return 0; }
4077
4192
 
4078
4193
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
4079
4194
  var performance = global$1.performance || {};
4080
- var performanceNow =
4081
- performance.now ||
4195
+ performance.now ||
4082
4196
  performance.mozNow ||
4083
4197
  performance.msNow ||
4084
4198
  performance.oNow ||
4085
4199
  performance.webkitNow ||
4086
4200
  function(){ return (new Date()).getTime() };
4087
4201
 
4088
- // generate timestamp or delta
4089
- // see http://nodejs.org/api/process.html#process_process_hrtime
4090
- function hrtime(previousTimestamp){
4091
- var clocktime = performanceNow.call(performance)*1e-3;
4092
- var seconds = Math.floor(clocktime);
4093
- var nanoseconds = Math.floor((clocktime%1)*1e9);
4094
- if (previousTimestamp) {
4095
- seconds = seconds - previousTimestamp[0];
4096
- nanoseconds = nanoseconds - previousTimestamp[1];
4097
- if (nanoseconds<0) {
4098
- seconds--;
4099
- nanoseconds += 1e9;
4100
- }
4101
- }
4102
- return [seconds,nanoseconds]
4103
- }
4104
-
4105
- var startTime = new Date();
4106
- function uptime() {
4107
- var currentTime = new Date();
4108
- var dif = currentTime - startTime;
4109
- return dif / 1000;
4110
- }
4111
-
4112
4202
  var browser$1 = {
4113
- nextTick: nextTick,
4114
- title: title,
4115
- browser: browser,
4116
- env: env,
4117
- argv: argv,
4118
- version: version,
4119
- versions: versions,
4120
- on: on,
4121
- addListener: addListener,
4122
- once: once,
4123
- off: off,
4124
- removeListener: removeListener,
4125
- removeAllListeners: removeAllListeners,
4126
- emit: emit,
4127
- binding: binding,
4128
- cwd: cwd,
4129
- chdir: chdir,
4130
- umask: umask,
4131
- hrtime: hrtime,
4132
- platform: platform,
4133
- release: release,
4134
- config: config,
4135
- uptime: uptime
4136
- };
4203
+ env: env};
4137
4204
 
4138
4205
  if (browser$1.env.NODE_ENV === 'production') {
4139
4206
  log__default.default.setLevel('silent');
@@ -4750,11 +4817,11 @@ var Base = /** @class */ (function () {
4750
4817
  Base.prototype.request = function (route, options) {
4751
4818
  return __awaiter(this, void 0, void 0, function () {
4752
4819
  var url, headers, http, _a, result, error_1, result, error_2, result, error_3, result, error_4, error_5;
4753
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
4754
- return __generator(this, function (_m) {
4755
- switch (_m.label) {
4820
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
4821
+ return __generator(this, function (_q) {
4822
+ switch (_q.label) {
4756
4823
  case 0:
4757
- _m.trys.push([0, 16, , 17]);
4824
+ _q.trys.push([0, 16, , 17]);
4758
4825
  url = void 0;
4759
4826
  if (typeof route.fullPath !== 'string') {
4760
4827
  url = route.fullPath(options === null || options === void 0 ? void 0 : options.payload);
@@ -4767,7 +4834,7 @@ var Base = /** @class */ (function () {
4767
4834
  }
4768
4835
  return [4 /*yield*/, this.getRequestHeaders(route.requiresAccessToken)];
4769
4836
  case 1:
4770
- headers = _m.sent();
4837
+ headers = _q.sent();
4771
4838
  if ((_b = this.options) === null || _b === void 0 ? void 0 : _b.headers) {
4772
4839
  headers = __assign(__assign({}, headers), this.options.headers);
4773
4840
  }
@@ -4777,10 +4844,12 @@ var Base = /** @class */ (function () {
4777
4844
  headers: headers,
4778
4845
  });
4779
4846
  http.interceptors.response.use(function (response) { return response; }, function (error) {
4780
- var _a, _b, _c;
4847
+ var _a, _b, _c, _d, _e;
4781
4848
  if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) {
4782
4849
  logger.info('SDK::Base::Interceptor::error.response.data', (_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.data);
4783
- return Promise.reject((_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data);
4850
+ if (((_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data.errorCode) && ((_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data.errorCode) !== exports.ErrorResponseCodes.user_already_exists) {
4851
+ return Promise.reject((_e = error === null || error === void 0 ? void 0 : error.response) === null || _e === void 0 ? void 0 : _e.data);
4852
+ }
4784
4853
  }
4785
4854
  logger.error('SDK::Base::Interceptor::error', error);
4786
4855
  return Promise.reject(error);
@@ -4794,63 +4863,66 @@ var Base = /** @class */ (function () {
4794
4863
  }
4795
4864
  return [3 /*break*/, 14];
4796
4865
  case 2:
4797
- _m.trys.push([2, 4, , 5]);
4866
+ _q.trys.push([2, 4, , 5]);
4798
4867
  return [4 /*yield*/, http.get(url)];
4799
4868
  case 3:
4800
- result = _m.sent();
4869
+ result = _q.sent();
4801
4870
  logger.info('SDK::Base::RequestMethod.Get::result', result);
4802
4871
  return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4803
4872
  case 4:
4804
- error_1 = _m.sent();
4873
+ error_1 = _q.sent();
4805
4874
  if (error_1 instanceof axios.AxiosError) {
4806
- logger.error('SDK::Base::RequestMethod.Get::error', (_c = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _c === void 0 ? void 0 : _c.data);
4875
+ logger.error('SDK::Base::RequestMethod.Get::AxiosError', (_c = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _c === void 0 ? void 0 : _c.data);
4807
4876
  return [2 /*return*/, Promise.reject((_d = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _d === void 0 ? void 0 : _d.data)];
4808
4877
  }
4809
4878
  return [2 /*return*/, Promise.reject(error_1 === null || error_1 === void 0 ? void 0 : error_1.message)];
4810
4879
  case 5:
4811
- _m.trys.push([5, 7, , 8]);
4880
+ _q.trys.push([5, 7, , 8]);
4812
4881
  return [4 /*yield*/, http.post(url, JSON.stringify(options === null || options === void 0 ? void 0 : options.payload))];
4813
4882
  case 6:
4814
- result = _m.sent();
4883
+ result = _q.sent();
4815
4884
  logger.info('SDK::Base::RequestMethod.Post::result', result);
4816
4885
  return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4817
4886
  case 7:
4818
- error_2 = _m.sent();
4887
+ error_2 = _q.sent();
4819
4888
  if (error_2 instanceof axios.AxiosError) {
4820
- logger.error('SDK::Base::RequestMethod.Post::error', (_e = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _e === void 0 ? void 0 : _e.data);
4821
- return [2 /*return*/, Promise.reject((_f = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _f === void 0 ? void 0 : _f.data)];
4889
+ logger.error('SDK::Base::RequestMethod.Post::AxiosError', (_e = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _e === void 0 ? void 0 : _e.data);
4890
+ if (((_f = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _f === void 0 ? void 0 : _f.data.errorCode) && ((_g = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _g === void 0 ? void 0 : _g.data.errorCode) === exports.ErrorResponseCodes.user_already_exists) {
4891
+ return [2 /*return*/, (_h = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _h === void 0 ? void 0 : _h.data];
4892
+ }
4893
+ return [2 /*return*/, Promise.reject((_j = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _j === void 0 ? void 0 : _j.data)];
4822
4894
  }
4823
4895
  return [2 /*return*/, Promise.reject(error_2 === null || error_2 === void 0 ? void 0 : error_2.message)];
4824
4896
  case 8:
4825
- _m.trys.push([8, 10, , 11]);
4826
- return [4 /*yield*/, http.put(url, (_g = JSON.stringify(options === null || options === void 0 ? void 0 : options.payload)) !== null && _g !== void 0 ? _g : null)];
4897
+ _q.trys.push([8, 10, , 11]);
4898
+ return [4 /*yield*/, http.put(url, (_k = JSON.stringify(options === null || options === void 0 ? void 0 : options.payload)) !== null && _k !== void 0 ? _k : null)];
4827
4899
  case 9:
4828
- result = _m.sent();
4900
+ result = _q.sent();
4829
4901
  return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4830
4902
  case 10:
4831
- error_3 = _m.sent();
4903
+ error_3 = _q.sent();
4832
4904
  if (error_3 instanceof axios.AxiosError) {
4833
- logger.error('SDK::Base::RequestMethod.Put::error', (_h = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _h === void 0 ? void 0 : _h.data);
4834
- return [2 /*return*/, Promise.reject((_j = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _j === void 0 ? void 0 : _j.data)];
4905
+ logger.error('SDK::Base::RequestMethod.Put::error', (_l = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _l === void 0 ? void 0 : _l.data);
4906
+ return [2 /*return*/, Promise.reject((_m = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _m === void 0 ? void 0 : _m.data)];
4835
4907
  }
4836
4908
  return [2 /*return*/, Promise.reject(error_3 === null || error_3 === void 0 ? void 0 : error_3.message)];
4837
4909
  case 11:
4838
- _m.trys.push([11, 13, , 14]);
4910
+ _q.trys.push([11, 13, , 14]);
4839
4911
  return [4 /*yield*/, http.delete(url)];
4840
4912
  case 12:
4841
- result = _m.sent();
4913
+ result = _q.sent();
4842
4914
  return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4843
4915
  case 13:
4844
- error_4 = _m.sent();
4916
+ error_4 = _q.sent();
4845
4917
  if (error_4 instanceof axios.AxiosError) {
4846
- logger.error('SDK::Base::RequestMethod.Put::error', (_k = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _k === void 0 ? void 0 : _k.data);
4847
- return [2 /*return*/, Promise.reject((_l = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _l === void 0 ? void 0 : _l.data)];
4918
+ logger.error('SDK::Base::RequestMethod.Put::AxiosError', (_o = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _o === void 0 ? void 0 : _o.data);
4919
+ return [2 /*return*/, Promise.reject((_p = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _p === void 0 ? void 0 : _p.data)];
4848
4920
  }
4849
4921
  return [2 /*return*/, Promise.reject(error_4 === null || error_4 === void 0 ? void 0 : error_4.message)];
4850
4922
  case 14: throw new Error('Request method is not supported');
4851
4923
  case 15: return [3 /*break*/, 17];
4852
4924
  case 16:
4853
- error_5 = _m.sent();
4925
+ error_5 = _q.sent();
4854
4926
  logger.error('SDK::Base::request::error', error_5);
4855
4927
  return [2 /*return*/, Promise.reject(error_5)];
4856
4928
  case 17: return [2 /*return*/];
@@ -5003,10 +5075,7 @@ var AuthRoutes = {
5003
5075
  requiresAccessToken: true,
5004
5076
  },
5005
5077
  wallabyAuthPublicKey: {
5006
- fullPath: '/auth/wallaby-auth-pubkey',
5007
- method: exports.RequestMethod.Get,
5008
- requiresAccessToken: true,
5009
- },
5078
+ method: exports.RequestMethod.Get},
5010
5079
  getUserSalt: {
5011
5080
  fullPath: '/users/salt',
5012
5081
  method: exports.RequestMethod.Get,
@@ -5179,7 +5248,7 @@ var Auth = /** @class */ (function (_super) {
5179
5248
  return __generator(this, function (_e) {
5180
5249
  switch (_e.label) {
5181
5250
  case 0:
5182
- _e.trys.push([0, 7, , 8]);
5251
+ _e.trys.push([0, 10, , 11]);
5183
5252
  return [4 /*yield*/, this.signatureMessage({ password: password })];
5184
5253
  case 1:
5185
5254
  signatureMessage = _e.sent();
@@ -5190,32 +5259,35 @@ var Auth = /** @class */ (function (_super) {
5190
5259
  })];
5191
5260
  case 2:
5192
5261
  response = _e.sent();
5193
- if (!response || response.error) {
5194
- throw new Error();
5195
- }
5262
+ if (!(!response || response.error || response.errorCode)) return [3 /*break*/, 5];
5263
+ if (!(response.errorCode === exports.ErrorResponseCodes.user_already_exists)) return [3 /*break*/, 4];
5264
+ return [4 /*yield*/, this.handleSignUpError(response, password)];
5265
+ case 3: return [2 /*return*/, _e.sent()];
5266
+ case 4: throw new Error();
5267
+ case 5:
5196
5268
  accessToken = response.accessToken, user = response.user;
5197
5269
  this.storageService.setAccessToken(accessToken);
5198
5270
  this.storageService.setWallabyAuthPubKey(user.wallabyAuthPubKey);
5199
5271
  this.storageService.setEncryptedPrivateKey(decryptedClientAuthPrivKey, password);
5200
5272
  return [4 /*yield*/, this.device];
5201
- case 3:
5273
+ case 6:
5202
5274
  (_e.sent()).authTokens.accessToken = accessToken;
5203
5275
  return [4 /*yield*/, this.device];
5204
- case 4:
5276
+ case 7:
5205
5277
  (_e.sent()).credentials.wallabyPublicKey = user.wallabyAuthPubKey;
5206
5278
  return [4 /*yield*/, this.device];
5207
- case 5:
5279
+ case 8:
5208
5280
  _c = (_e.sent());
5209
5281
  _d = [{}];
5210
5282
  return [4 /*yield*/, this.device];
5211
- case 6:
5283
+ case 9:
5212
5284
  _c.user = __assign.apply(void 0, [__assign.apply(void 0, _d.concat([(_e.sent()).user])), user]);
5213
5285
  return [2 /*return*/, response];
5214
- case 7:
5286
+ case 10:
5215
5287
  error_2 = _e.sent();
5216
5288
  logger.error('SDK::Auth::singUp::error', error_2);
5217
5289
  return [2 /*return*/, Promise.reject(error_2)];
5218
- case 8: return [2 /*return*/];
5290
+ case 11: return [2 /*return*/];
5219
5291
  }
5220
5292
  });
5221
5293
  });
@@ -5377,7 +5449,7 @@ var Auth = /** @class */ (function (_super) {
5377
5449
  return __generator(this, function (_b) {
5378
5450
  switch (_b.label) {
5379
5451
  case 0:
5380
- userAlreadyExists = (error === null || error === void 0 ? void 0 : error.errorCode) === exports.ErrorResponseCodes.user_already_exists || ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.match(/User already exists/i));
5452
+ userAlreadyExists = (error === null || error === void 0 ? void 0 : error.errorCode) === exports.ErrorResponseCodes.user_already_exists || ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.toLowerCase().match(/user already exists/i));
5381
5453
  if (!userAlreadyExists) return [3 /*break*/, 5];
5382
5454
  _b.label = 1;
5383
5455
  case 1:
@@ -5733,7 +5805,7 @@ var Wallet = /** @class */ (function (_super) {
5733
5805
  return [2 /*return*/, __assign(__assign({}, response), { decryptedSeedPhrase: decryptedSeedPhrase, decryptedMnemonicSeedPhrase: decryptedMnemonicSeedPhrase })];
5734
5806
  case 10:
5735
5807
  error_6 = _c.sent();
5736
- logger.error('SDK::Wallet::create::error', error_6);
5808
+ logger.error('SDK::Wallet::createWithNewAccount::error', error_6);
5737
5809
  return [2 /*return*/, Promise.reject(error_6)];
5738
5810
  case 11: return [2 /*return*/];
5739
5811
  }
@@ -5796,7 +5868,7 @@ var Wallet = /** @class */ (function (_super) {
5796
5868
  return [2 /*return*/, response];
5797
5869
  case 6:
5798
5870
  error_7 = _c.sent();
5799
- logger.error('SDK::Wallet::create::error', error_7);
5871
+ logger.error('SDK::Wallet::import::error', error_7);
5800
5872
  return [2 /*return*/, Promise.reject(error_7)];
5801
5873
  case 7: return [2 /*return*/];
5802
5874
  }