wallaby-cash 3.5.2 → 3.7.0

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
@@ -2,7 +2,6 @@
2
2
 
3
3
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
4
4
 
5
- const algosdk = require('algosdk');
6
5
  const bip39 = require('bip39');
7
6
  const uuid = require('uuid');
8
7
  const log = require('loglevel');
@@ -31,7 +30,6 @@ n.default = e;
31
30
  return Object.freeze(n);
32
31
  }
33
32
 
34
- const algosdk__namespace = /*#__PURE__*/_interopNamespaceCompat(algosdk);
35
33
  const bip39__namespace = /*#__PURE__*/_interopNamespaceCompat(bip39);
36
34
  const log__default = /*#__PURE__*/_interopDefaultCompat(log);
37
35
  const WebAuthn__namespace = /*#__PURE__*/_interopNamespaceCompat(WebAuthn);
@@ -413,6 +411,7 @@ exports.ErrorResponseCodes = void 0;
413
411
  ErrorResponseCodes["sdk_seed_phrase_not_found"] = "sdk_seed_phrase_not_found";
414
412
  ErrorResponseCodes["sdk_private_key_decryption_failed"] = "sdk_private_key_decryption_failed";
415
413
  ErrorResponseCodes["sdk_private_key_not_found"] = "sdk_private_key_not_found";
414
+ ErrorResponseCodes["sdk_device_key_missing_with_existing_data"] = "sdk_device_key_missing_with_existing_data";
416
415
  ErrorResponseCodes["sdk_refresh_token_missing"] = "sdk_refresh_token_missing";
417
416
  ErrorResponseCodes["sdk_missing_parameter"] = "sdk_missing_parameter";
418
417
  ErrorResponseCodes["sdk_invalid_parameter"] = "sdk_invalid_parameter";
@@ -601,7 +600,6 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
601
600
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
602
601
  */
603
602
  const defaultNetwork = 'testnet';
604
- const isTest = browser$1.env.NODE_ENV === 'test';
605
603
  const DEFAULT_ENTROPY_BYTES$1 = 32;
606
604
  const PBKDF2_ITERATIONS = 131072;
607
605
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -627,7 +625,7 @@ const env = {
627
625
  isNative: !isWeb,
628
626
  isWeb,
629
627
  };
630
- const currentPackageVersion = "3.5.2" ;
628
+ const currentPackageVersion = "3.7.0" ;
631
629
 
632
630
  /**
633
631
  * Storage keys adapter for Storage interface across different platforms.
@@ -640,77 +638,107 @@ const normalizeKey = (key) => key.replace(/:/g, '_');
640
638
 
641
639
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
642
640
 
643
- function number(n) {
644
- if (!Number.isSafeInteger(n) || n < 0)
645
- throw new Error(`positive integer expected, not ${n}`);
646
- }
647
- function bool(b) {
648
- if (typeof b !== 'boolean')
649
- throw new Error(`boolean expected, not ${b}`);
650
- }
651
- // copied from utils
641
+ /**
642
+ * Utilities for hex, bytes, CSPRNG.
643
+ * @module
644
+ */
645
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
646
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
647
+ // node.js versions earlier than v19 don't declare it in global scope.
648
+ // For node.js, package.json#exports field mapping rewrites import
649
+ // from `crypto` to `cryptoNode`, which imports native module.
650
+ // Makes the utils un-importable in browsers without a bundler.
651
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
652
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
652
653
  function isBytes$2(a) {
653
- return (a instanceof Uint8Array ||
654
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
654
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
655
655
  }
656
- function bytes$1(b, ...lengths) {
656
+ /** Asserts something is positive integer. */
657
+ function anumber(n) {
658
+ if (!Number.isSafeInteger(n) || n < 0)
659
+ throw new Error('positive integer expected, got ' + n);
660
+ }
661
+ /** Asserts something is Uint8Array. */
662
+ function abytes$3(b, ...lengths) {
657
663
  if (!isBytes$2(b))
658
664
  throw new Error('Uint8Array expected');
659
665
  if (lengths.length > 0 && !lengths.includes(b.length))
660
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
666
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
661
667
  }
662
- function hash$1(h) {
668
+ /** Asserts something is hash */
669
+ function ahash(h) {
663
670
  if (typeof h !== 'function' || typeof h.create !== 'function')
664
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
665
- number(h.outputLen);
666
- number(h.blockLen);
671
+ throw new Error('Hash should be wrapped by utils.createHasher');
672
+ anumber(h.outputLen);
673
+ anumber(h.blockLen);
667
674
  }
668
- function exists(instance, checkFinished = true) {
675
+ /** Asserts a hash instance has not been destroyed / finished */
676
+ function aexists(instance, checkFinished = true) {
669
677
  if (instance.destroyed)
670
678
  throw new Error('Hash instance has been destroyed');
671
679
  if (checkFinished && instance.finished)
672
680
  throw new Error('Hash#digest() has already been called');
673
681
  }
674
- function output$1(out, instance) {
675
- bytes$1(out);
682
+ /** Asserts output is properly-sized byte array */
683
+ function aoutput(out, instance) {
684
+ abytes$3(out);
676
685
  const min = instance.outputLen;
677
686
  if (out.length < min) {
678
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
687
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
679
688
  }
680
689
  }
681
- const assert = { number, bool, bytes: bytes$1, hash: hash$1, exists, output: output$1 };
682
-
683
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
684
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
685
- // node.js versions earlier than v19 don't declare it in global scope.
686
- // For node.js, package.json#exports field mapping rewrites import
687
- // from `crypto` to `cryptoNode`, which imports native module.
688
- // Makes the utils un-importable in browsers without a bundler.
689
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
690
- const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
691
- // Cast array to view
692
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
693
- // The rotate right (circular right shift) operation for uint32
694
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
695
- const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
696
- // The byte swap operation for uint32
697
- const byteSwap = (word) => ((word << 24) & 0xff000000) |
698
- ((word << 8) & 0xff0000) |
699
- ((word >>> 8) & 0xff00) |
700
- ((word >>> 24) & 0xff);
701
- // In place byte swap for Uint32Array
690
+ /** Cast u8 / u16 / u32 to u32. */
691
+ function u32$1(arr) {
692
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
693
+ }
694
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
695
+ function clean$1(...arrays) {
696
+ for (let i = 0; i < arrays.length; i++) {
697
+ arrays[i].fill(0);
698
+ }
699
+ }
700
+ /** Create DataView of an array for easy byte-level manipulation. */
701
+ function createView(arr) {
702
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
703
+ }
704
+ /** The rotate right (circular right shift) operation for uint32 */
705
+ function rotr(word, shift) {
706
+ return (word << (32 - shift)) | (word >>> shift);
707
+ }
708
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
709
+ const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
710
+ /** The byte swap operation for uint32 */
711
+ function byteSwap(word) {
712
+ return (((word << 24) & 0xff000000) |
713
+ ((word << 8) & 0xff0000) |
714
+ ((word >>> 8) & 0xff00) |
715
+ ((word >>> 24) & 0xff));
716
+ }
717
+ /** In place byte swap for Uint32Array */
702
718
  function byteSwap32(arr) {
703
719
  for (let i = 0; i < arr.length; i++) {
704
720
  arr[i] = byteSwap(arr[i]);
705
721
  }
722
+ return arr;
706
723
  }
724
+ const swap32IfBE = isLE$1
725
+ ? (u) => u
726
+ : byteSwap32;
727
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
728
+ const hasHexBuiltin$1 = /* @__PURE__ */ (() =>
729
+ // @ts-ignore
730
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
707
731
  // Array where index 0xf0 (240) is mapped to string 'f0'
708
732
  const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
709
733
  /**
734
+ * Convert byte array to hex string. Uses built-in function, when available.
710
735
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
711
736
  */
712
737
  function bytesToHex$1(bytes) {
713
- bytes$1(bytes);
738
+ abytes$3(bytes);
739
+ // @ts-ignore
740
+ if (hasHexBuiltin$1)
741
+ return bytes.toHex();
714
742
  // pre-caching improves the speed 6x
715
743
  let hex = '';
716
744
  for (let i = 0; i < bytes.length; i++) {
@@ -719,26 +747,30 @@ function bytesToHex$1(bytes) {
719
747
  return hex;
720
748
  }
721
749
  // We use optimized technique to convert hex string to byte array
722
- const asciis$1 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
723
- function asciiToBase16$1(char) {
724
- if (char >= asciis$1._0 && char <= asciis$1._9)
725
- return char - asciis$1._0;
726
- if (char >= asciis$1._A && char <= asciis$1._F)
727
- return char - (asciis$1._A - 10);
728
- if (char >= asciis$1._a && char <= asciis$1._f)
729
- return char - (asciis$1._a - 10);
750
+ const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
751
+ function asciiToBase16$1(ch) {
752
+ if (ch >= asciis$1._0 && ch <= asciis$1._9)
753
+ return ch - asciis$1._0; // '2' => 50-48
754
+ if (ch >= asciis$1.A && ch <= asciis$1.F)
755
+ return ch - (asciis$1.A - 10); // 'B' => 66-(65-10)
756
+ if (ch >= asciis$1.a && ch <= asciis$1.f)
757
+ return ch - (asciis$1.a - 10); // 'b' => 98-(97-10)
730
758
  return;
731
759
  }
732
760
  /**
761
+ * Convert hex string to byte array. Uses built-in function, when available.
733
762
  * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
734
763
  */
735
764
  function hexToBytes$2(hex) {
736
765
  if (typeof hex !== 'string')
737
766
  throw new Error('hex string expected, got ' + typeof hex);
767
+ // @ts-ignore
768
+ if (hasHexBuiltin$1)
769
+ return Uint8Array.fromHex(hex);
738
770
  const hl = hex.length;
739
771
  const al = hl / 2;
740
772
  if (hl % 2)
741
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
773
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
742
774
  const array = new Uint8Array(al);
743
775
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
744
776
  const n1 = asciiToBase16$1(hex.charCodeAt(hi));
@@ -747,16 +779,17 @@ function hexToBytes$2(hex) {
747
779
  const char = hex[hi] + hex[hi + 1];
748
780
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
749
781
  }
750
- array[ai] = n1 * 16 + n2;
782
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
751
783
  }
752
784
  return array;
753
785
  }
754
786
  /**
755
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
787
+ * Converts string to bytes using UTF8 encoding.
788
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
756
789
  */
757
790
  function utf8ToBytes$1(str) {
758
791
  if (typeof str !== 'string')
759
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
792
+ throw new Error('string expected');
760
793
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
761
794
  }
762
795
  /**
@@ -767,17 +800,25 @@ function utf8ToBytes$1(str) {
767
800
  function toBytes(data) {
768
801
  if (typeof data === 'string')
769
802
  data = utf8ToBytes$1(data);
770
- bytes$1(data);
803
+ abytes$3(data);
771
804
  return data;
772
805
  }
773
806
  /**
774
- * Copies several Uint8Arrays into one.
807
+ * Helper for KDFs: consumes uint8array or string.
808
+ * When string is passed, does utf8 decoding, using TextDecoder.
775
809
  */
810
+ function kdfInputToBytes(data) {
811
+ if (typeof data === 'string')
812
+ data = utf8ToBytes$1(data);
813
+ abytes$3(data);
814
+ return data;
815
+ }
816
+ /** Copies several Uint8Arrays into one. */
776
817
  function concatBytes$1(...arrays) {
777
818
  let sum = 0;
778
819
  for (let i = 0; i < arrays.length; i++) {
779
820
  const a = arrays[i];
780
- bytes$1(a);
821
+ abytes$3(a);
781
822
  sum += a.length;
782
823
  }
783
824
  const res = new Uint8Array(sum);
@@ -788,21 +829,17 @@ function concatBytes$1(...arrays) {
788
829
  }
789
830
  return res;
790
831
  }
791
- // For runtime check if class implements interface
792
- class Hash {
793
- // Safe version that clones internal state
794
- clone() {
795
- return this._cloneInto();
796
- }
797
- }
798
- const toStr = {}.toString;
799
832
  function checkOpts(defaults, opts) {
800
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
801
- throw new Error('Options should be object or undefined');
833
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
834
+ throw new Error('options should be object or undefined');
802
835
  const merged = Object.assign(defaults, opts);
803
836
  return merged;
804
837
  }
805
- function wrapConstructor(hashCons) {
838
+ /** For runtime check if class implements interface */
839
+ class Hash {
840
+ }
841
+ /** Wraps hash function, creating an interface on top of it */
842
+ function createHasher(hashCons) {
806
843
  const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
807
844
  const tmp = hashCons();
808
845
  hashC.outputLen = tmp.outputLen;
@@ -810,16 +847,14 @@ function wrapConstructor(hashCons) {
810
847
  hashC.create = () => hashCons();
811
848
  return hashC;
812
849
  }
813
- /**
814
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
815
- */
850
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
816
851
  function randomBytes(bytesLength = 32) {
817
852
  if (crypto && typeof crypto.getRandomValues === 'function') {
818
853
  return crypto.getRandomValues(new Uint8Array(bytesLength));
819
854
  }
820
855
  // Legacy Node.js compatibility
821
856
  if (crypto && typeof crypto.randomBytes === 'function') {
822
- return crypto.randomBytes(bytesLength);
857
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
823
858
  }
824
859
  throw new Error('crypto.getRandomValues must be defined');
825
860
  }
@@ -828,168 +863,476 @@ function getRandomBytesSync(bytes) {
828
863
  return randomBytes(bytes);
829
864
  }
830
865
 
831
- const assertBool = assert.bool;
832
- const assertBytes = assert.bytes;
833
- // buf.toString('utf8') -> bytesToUtf8(buf)
834
- function bytesToUtf8(data) {
835
- if (!(data instanceof Uint8Array)) {
836
- throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
837
- }
838
- return new TextDecoder().decode(data);
866
+ /**
867
+ * Hex, bytes and number utilities.
868
+ * @module
869
+ */
870
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
871
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
872
+ // This is OK: `abstract` directory does not use noble-hashes.
873
+ // User may opt-in into using different hashing library. This way, noble-hashes
874
+ // won't be included into their bundle.
875
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
876
+ const _1n$5 = /* @__PURE__ */ BigInt(1);
877
+ function isBytes$1(a) {
878
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
839
879
  }
840
- function hexToBytes$1(data) {
841
- const sliced = data.startsWith("0x") ? data.substring(2) : data;
842
- return hexToBytes$2(sliced);
880
+ function abytes$2(item) {
881
+ if (!isBytes$1(item))
882
+ throw new Error('Uint8Array expected');
843
883
  }
844
- // Internal utils
845
- function wrapHash(hash) {
846
- return (msg) => {
847
- assert.bytes(msg);
848
- return hash(msg);
849
- };
884
+ function abool(title, value) {
885
+ if (typeof value !== 'boolean')
886
+ throw new Error(title + ' boolean expected, got ' + value);
850
887
  }
851
-
888
+ // Used in weierstrass, der
889
+ function numberToHexUnpadded(num) {
890
+ const hex = num.toString(16);
891
+ return hex.length & 1 ? '0' + hex : hex;
892
+ }
893
+ function hexToNumber(hex) {
894
+ if (typeof hex !== 'string')
895
+ throw new Error('hex string expected, got ' + typeof hex);
896
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
897
+ }
898
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
899
+ const hasHexBuiltin =
900
+ // @ts-ignore
901
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
902
+ // Array where index 0xf0 (240) is mapped to string 'f0'
903
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
852
904
  /**
853
- * Returns a `Boolean` on whether or not the a `String` starts with '0x'
854
- * @param str the string input value
855
- * @return a boolean if it is or is not hex prefixed
856
- * @throws if the str input is not a string
905
+ * Convert byte array to hex string. Uses built-in function, when available.
906
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
857
907
  */
858
- const isHexPrefixed = (str) => {
859
- if (typeof str !== 'string') {
860
- throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
908
+ function bytesToHex(bytes) {
909
+ abytes$2(bytes);
910
+ // @ts-ignore
911
+ if (hasHexBuiltin)
912
+ return bytes.toHex();
913
+ // pre-caching improves the speed 6x
914
+ let hex = '';
915
+ for (let i = 0; i < bytes.length; i++) {
916
+ hex += hexes[bytes[i]];
861
917
  }
862
- return str[0] === '0' && str[1] === 'x';
863
- };
864
- /**
865
- * Removes '0x' from a given `String` if present
866
- * @param str the string value
867
- * @returns the string without 0x prefix
868
- */
869
- const stripHexPrefix = (str) => {
870
- if (typeof str !== 'string')
871
- throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
872
- return isHexPrefixed(str) ? str.slice(2) : str;
873
- };
874
- /**
875
- * Is the string a hex string.
876
- *
877
- * @param value
878
- * @param length
879
- * @returns output the string is a hex string
880
- */
881
- const isHexString = (value, length) => {
882
- if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
883
- return false;
884
- return true;
885
- };
918
+ return hex;
919
+ }
920
+ // We use optimized technique to convert hex string to byte array
921
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
922
+ function asciiToBase16(ch) {
923
+ if (ch >= asciis._0 && ch <= asciis._9)
924
+ return ch - asciis._0; // '2' => 50-48
925
+ if (ch >= asciis.A && ch <= asciis.F)
926
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
927
+ if (ch >= asciis.a && ch <= asciis.f)
928
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
929
+ return;
930
+ }
886
931
  /**
887
- * Adds '0x' to a given `String` if not present
888
- * @param str the string input value
889
- * @return the string with a 0x prefix
932
+ * Convert hex string to byte array. Uses built-in function, when available.
933
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
890
934
  */
891
- const addLeading0x = (str) => {
892
- if (!str.startsWith('0x'))
893
- return '0x' + str;
894
- else
895
- return str;
896
- };
897
- const decompress = (startsWith02Or03) => {
898
- const testByteArray = hexToBytes$1(startsWith02Or03);
899
- let startsWith04 = startsWith02Or03;
900
- if (testByteArray.length === 64) {
901
- startsWith04 = '04' + startsWith02Or03;
935
+ function hexToBytes$1(hex) {
936
+ if (typeof hex !== 'string')
937
+ throw new Error('hex string expected, got ' + typeof hex);
938
+ // @ts-ignore
939
+ if (hasHexBuiltin)
940
+ return Uint8Array.fromHex(hex);
941
+ const hl = hex.length;
942
+ const al = hl / 2;
943
+ if (hl % 2)
944
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
945
+ const array = new Uint8Array(al);
946
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
947
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
948
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
949
+ if (n1 === undefined || n2 === undefined) {
950
+ const char = hex[hi] + hex[hi + 1];
951
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
952
+ }
953
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
902
954
  }
903
- return startsWith04.substring(2);
904
- };
905
- /** Helper function to concat UInt8Arrays mimicking the behaviour of the
906
- * Buffer.concat function in Node.js
907
- */
908
- const concatUint8Arrays = (uint8arrays) => {
909
- const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
910
- const result = new Uint8Array(totalLength);
911
- let offset = 0;
912
- uint8arrays.forEach((uint8array) => {
913
- result.set(uint8array, offset);
914
- offset += uint8array.byteLength;
915
- });
916
- return result;
917
- };
955
+ return array;
956
+ }
957
+ // BE: Big Endian, LE: Little Endian
958
+ function bytesToNumberBE(bytes) {
959
+ return hexToNumber(bytesToHex(bytes));
960
+ }
961
+ function bytesToNumberLE(bytes) {
962
+ abytes$2(bytes);
963
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
964
+ }
965
+ function numberToBytesBE(n, len) {
966
+ return hexToBytes$1(n.toString(16).padStart(len * 2, '0'));
967
+ }
968
+ function numberToBytesLE(n, len) {
969
+ return numberToBytesBE(n, len).reverse();
970
+ }
918
971
  /**
919
- * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
920
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
972
+ * Takes hex string or Uint8Array, converts to Uint8Array.
973
+ * Validates output length.
974
+ * Will throw error for other types.
975
+ * @param title descriptive title for an error e.g. 'private key'
976
+ * @param hex hex string or Uint8Array
977
+ * @param expectedLength optional, will compare to result array's length
978
+ * @returns
921
979
  */
922
- const utf8ToBytes = (str) => {
923
- if (typeof str !== 'string')
924
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
925
- const bytes = [];
926
- for (let i = 0; i < str.length; i++) {
927
- const codePoint = str.codePointAt(i);
928
- if (!codePoint) {
929
- throw new Error('Invalid code point');
930
- }
931
- if (codePoint < 0x80) {
932
- bytes.push(codePoint);
933
- }
934
- else if (codePoint < 0x800) {
935
- bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
936
- }
937
- else if (codePoint < 0x10000) {
938
- bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
980
+ function ensureBytes(title, hex, expectedLength) {
981
+ let res;
982
+ if (typeof hex === 'string') {
983
+ try {
984
+ res = hexToBytes$1(hex);
939
985
  }
940
- else {
941
- i++; // skip one iteration since we have a surrogate pair
942
- bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
986
+ catch (e) {
987
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
943
988
  }
944
989
  }
945
- return new Uint8Array(bytes);
946
- };
947
-
948
- /**
949
- * Polyfill for Safari 14
950
- */
951
- function setBigUint64(view, byteOffset, value, isLE) {
952
- if (typeof view.setBigUint64 === 'function')
953
- return view.setBigUint64(byteOffset, value, isLE);
954
- const _32n = BigInt(32);
955
- const _u32_max = BigInt(0xffffffff);
956
- const wh = Number((value >> _32n) & _u32_max);
957
- const wl = Number(value & _u32_max);
958
- const h = isLE ? 4 : 0;
959
- const l = isLE ? 0 : 4;
960
- view.setUint32(byteOffset + h, wh, isLE);
961
- view.setUint32(byteOffset + l, wl, isLE);
990
+ else if (isBytes$1(hex)) {
991
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
992
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
993
+ res = Uint8Array.from(hex);
994
+ }
995
+ else {
996
+ throw new Error(title + ' must be hex string or Uint8Array');
997
+ }
998
+ const len = res.length;
999
+ if (typeof expectedLength === 'number' && len !== expectedLength)
1000
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
1001
+ return res;
962
1002
  }
963
1003
  /**
964
- * Choice: a ? b : c
965
- */
966
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
967
- /**
968
- * Majority function, true if any two inputs is true
969
- */
970
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
971
- /**
972
- * Merkle-Damgard hash construction base class.
973
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1004
+ * Copies several Uint8Arrays into one.
974
1005
  */
975
- class HashMD extends Hash {
976
- constructor(blockLen, outputLen, padOffset, isLE) {
977
- super();
978
- this.blockLen = blockLen;
979
- this.outputLen = outputLen;
980
- this.padOffset = padOffset;
981
- this.isLE = isLE;
982
- this.finished = false;
1006
+ function concatBytes(...arrays) {
1007
+ let sum = 0;
1008
+ for (let i = 0; i < arrays.length; i++) {
1009
+ const a = arrays[i];
1010
+ abytes$2(a);
1011
+ sum += a.length;
1012
+ }
1013
+ const res = new Uint8Array(sum);
1014
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1015
+ const a = arrays[i];
1016
+ res.set(a, pad);
1017
+ pad += a.length;
1018
+ }
1019
+ return res;
1020
+ }
1021
+ // Is positive bigint
1022
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
1023
+ function inRange(n, min, max) {
1024
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1025
+ }
1026
+ /**
1027
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
1028
+ * @example
1029
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
1030
+ */
1031
+ function aInRange(title, n, min, max) {
1032
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
1033
+ // consider P=256n, min=0n, max=P
1034
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
1035
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
1036
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
1037
+ if (!inRange(n, min, max))
1038
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
1039
+ }
1040
+ // Bit operations
1041
+ /**
1042
+ * Calculates amount of bits in a bigint.
1043
+ * Same as `n.toString(2).length`
1044
+ * TODO: merge with nLength in modular
1045
+ */
1046
+ function bitLen(n) {
1047
+ let len;
1048
+ for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
1049
+ ;
1050
+ return len;
1051
+ }
1052
+ /**
1053
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1054
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1055
+ */
1056
+ const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
1057
+ // DRBG
1058
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
1059
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
1060
+ /**
1061
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1062
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
1063
+ * @example
1064
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
1065
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
1066
+ */
1067
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1068
+ if (typeof hashLen !== 'number' || hashLen < 2)
1069
+ throw new Error('hashLen must be a number');
1070
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
1071
+ throw new Error('qByteLen must be a number');
1072
+ if (typeof hmacFn !== 'function')
1073
+ throw new Error('hmacFn must be a function');
1074
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
1075
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1076
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
1077
+ let i = 0; // Iterations counter, will throw when over 1000
1078
+ const reset = () => {
1079
+ v.fill(1);
1080
+ k.fill(0);
1081
+ i = 0;
1082
+ };
1083
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
1084
+ const reseed = (seed = u8n(0)) => {
1085
+ // HMAC-DRBG reseed() function. Steps D-G
1086
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
1087
+ v = h(); // v = hmac(k || v)
1088
+ if (seed.length === 0)
1089
+ return;
1090
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
1091
+ v = h(); // v = hmac(k || v)
1092
+ };
1093
+ const gen = () => {
1094
+ // HMAC-DRBG generate() function
1095
+ if (i++ >= 1000)
1096
+ throw new Error('drbg: tried 1000 values');
1097
+ let len = 0;
1098
+ const out = [];
1099
+ while (len < qByteLen) {
1100
+ v = h();
1101
+ const sl = v.slice();
1102
+ out.push(sl);
1103
+ len += v.length;
1104
+ }
1105
+ return concatBytes(...out);
1106
+ };
1107
+ const genUntil = (seed, pred) => {
1108
+ reset();
1109
+ reseed(seed); // Steps D-G
1110
+ let res = undefined; // Step H: grind until k is in [1..n-1]
1111
+ while (!(res = pred(gen())))
1112
+ reseed();
1113
+ reset();
1114
+ return res;
1115
+ };
1116
+ return genUntil;
1117
+ }
1118
+ // Validating curves and fields
1119
+ const validatorFns = {
1120
+ bigint: (val) => typeof val === 'bigint',
1121
+ function: (val) => typeof val === 'function',
1122
+ boolean: (val) => typeof val === 'boolean',
1123
+ string: (val) => typeof val === 'string',
1124
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
1125
+ isSafeInteger: (val) => Number.isSafeInteger(val),
1126
+ array: (val) => Array.isArray(val),
1127
+ field: (val, object) => object.Fp.isValid(val),
1128
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1129
+ };
1130
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1131
+ function validateObject(object, validators, optValidators = {}) {
1132
+ const checkField = (fieldName, type, isOptional) => {
1133
+ const checkVal = validatorFns[type];
1134
+ if (typeof checkVal !== 'function')
1135
+ throw new Error('invalid validator function');
1136
+ const val = object[fieldName];
1137
+ if (isOptional && val === undefined)
1138
+ return;
1139
+ if (!checkVal(val, object)) {
1140
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
1141
+ }
1142
+ };
1143
+ for (const [fieldName, type] of Object.entries(validators))
1144
+ checkField(fieldName, type, false);
1145
+ for (const [fieldName, type] of Object.entries(optValidators))
1146
+ checkField(fieldName, type, true);
1147
+ return object;
1148
+ }
1149
+ /**
1150
+ * Memoizes (caches) computation result.
1151
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1152
+ */
1153
+ function memoized(fn) {
1154
+ const map = new WeakMap();
1155
+ return (arg, ...args) => {
1156
+ const val = map.get(arg);
1157
+ if (val !== undefined)
1158
+ return val;
1159
+ const computed = fn(arg, ...args);
1160
+ map.set(arg, computed);
1161
+ return computed;
1162
+ };
1163
+ }
1164
+
1165
+ /**
1166
+ * Internal assertion helpers.
1167
+ * @module
1168
+ * @deprecated
1169
+ */
1170
+ /** @deprecated Use import from `noble/hashes/utils` module */
1171
+ const abytes$1 = abytes$3;
1172
+
1173
+ // buf.toString('utf8') -> bytesToUtf8(buf)
1174
+ function bytesToUtf8(data) {
1175
+ if (!(data instanceof Uint8Array)) {
1176
+ throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
1177
+ }
1178
+ return new TextDecoder().decode(data);
1179
+ }
1180
+ function hexToBytes(data) {
1181
+ const sliced = data.startsWith("0x") ? data.substring(2) : data;
1182
+ return hexToBytes$2(sliced);
1183
+ }
1184
+ // Internal utils
1185
+ function wrapHash(hash) {
1186
+ return (msg) => {
1187
+ abytes$1(msg);
1188
+ return hash(msg);
1189
+ };
1190
+ }
1191
+
1192
+ /**
1193
+ * Returns a `Boolean` on whether or not the a `String` starts with '0x'
1194
+ * @param str the string input value
1195
+ * @return a boolean if it is or is not hex prefixed
1196
+ * @throws if the str input is not a string
1197
+ */
1198
+ const isHexPrefixed = (str) => {
1199
+ if (typeof str !== 'string') {
1200
+ throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
1201
+ }
1202
+ return str[0] === '0' && str[1] === 'x';
1203
+ };
1204
+ /**
1205
+ * Removes '0x' from a given `String` if present
1206
+ * @param str the string value
1207
+ * @returns the string without 0x prefix
1208
+ */
1209
+ const stripHexPrefix = (str) => {
1210
+ if (typeof str !== 'string')
1211
+ throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
1212
+ return isHexPrefixed(str) ? str.slice(2) : str;
1213
+ };
1214
+ /**
1215
+ * Is the string a hex string.
1216
+ *
1217
+ * @param value
1218
+ * @param length
1219
+ * @returns output the string is a hex string
1220
+ */
1221
+ const isHexString = (value, length) => {
1222
+ if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
1223
+ return false;
1224
+ return true;
1225
+ };
1226
+ /**
1227
+ * Adds '0x' to a given `String` if not present
1228
+ * @param str the string input value
1229
+ * @return the string with a 0x prefix
1230
+ */
1231
+ const addLeading0x = (str) => {
1232
+ if (!str.startsWith('0x'))
1233
+ return '0x' + str;
1234
+ else
1235
+ return str;
1236
+ };
1237
+ const decompress = (startsWith02Or03) => {
1238
+ const testByteArray = hexToBytes(startsWith02Or03);
1239
+ let startsWith04 = startsWith02Or03;
1240
+ if (testByteArray.length === 64) {
1241
+ startsWith04 = '04' + startsWith02Or03;
1242
+ }
1243
+ return startsWith04.substring(2);
1244
+ };
1245
+ /** Helper function to concat UInt8Arrays mimicking the behaviour of the
1246
+ * Buffer.concat function in Node.js
1247
+ */
1248
+ const concatUint8Arrays = (uint8arrays) => {
1249
+ const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
1250
+ const result = new Uint8Array(totalLength);
1251
+ let offset = 0;
1252
+ uint8arrays.forEach((uint8array) => {
1253
+ result.set(uint8array, offset);
1254
+ offset += uint8array.byteLength;
1255
+ });
1256
+ return result;
1257
+ };
1258
+ /**
1259
+ * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
1260
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
1261
+ */
1262
+ const utf8ToBytes = (str) => {
1263
+ if (typeof str !== 'string')
1264
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
1265
+ const bytes = [];
1266
+ for (let i = 0; i < str.length; i++) {
1267
+ const codePoint = str.codePointAt(i);
1268
+ if (!codePoint) {
1269
+ throw new Error('Invalid code point');
1270
+ }
1271
+ if (codePoint < 0x80) {
1272
+ bytes.push(codePoint);
1273
+ }
1274
+ else if (codePoint < 0x800) {
1275
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
1276
+ }
1277
+ else if (codePoint < 0x10000) {
1278
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1279
+ }
1280
+ else {
1281
+ i++; // skip one iteration since we have a surrogate pair
1282
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1283
+ }
1284
+ }
1285
+ return new Uint8Array(bytes);
1286
+ };
1287
+
1288
+ /**
1289
+ * Internal Merkle-Damgard hash utils.
1290
+ * @module
1291
+ */
1292
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
1293
+ function setBigUint64(view, byteOffset, value, isLE) {
1294
+ if (typeof view.setBigUint64 === 'function')
1295
+ return view.setBigUint64(byteOffset, value, isLE);
1296
+ const _32n = BigInt(32);
1297
+ const _u32_max = BigInt(0xffffffff);
1298
+ const wh = Number((value >> _32n) & _u32_max);
1299
+ const wl = Number(value & _u32_max);
1300
+ const h = isLE ? 4 : 0;
1301
+ const l = isLE ? 0 : 4;
1302
+ view.setUint32(byteOffset + h, wh, isLE);
1303
+ view.setUint32(byteOffset + l, wl, isLE);
1304
+ }
1305
+ /** Choice: a ? b : c */
1306
+ function Chi(a, b, c) {
1307
+ return (a & b) ^ (~a & c);
1308
+ }
1309
+ /** Majority function, true if any two inputs is true. */
1310
+ function Maj(a, b, c) {
1311
+ return (a & b) ^ (a & c) ^ (b & c);
1312
+ }
1313
+ /**
1314
+ * Merkle-Damgard hash construction base class.
1315
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1316
+ */
1317
+ class HashMD extends Hash {
1318
+ constructor(blockLen, outputLen, padOffset, isLE) {
1319
+ super();
1320
+ this.finished = false;
983
1321
  this.length = 0;
984
1322
  this.pos = 0;
985
1323
  this.destroyed = false;
1324
+ this.blockLen = blockLen;
1325
+ this.outputLen = outputLen;
1326
+ this.padOffset = padOffset;
1327
+ this.isLE = isLE;
986
1328
  this.buffer = new Uint8Array(blockLen);
987
1329
  this.view = createView(this.buffer);
988
1330
  }
989
1331
  update(data) {
990
- exists(this);
991
- const { view, buffer, blockLen } = this;
1332
+ aexists(this);
992
1333
  data = toBytes(data);
1334
+ abytes$3(data);
1335
+ const { view, buffer, blockLen } = this;
993
1336
  const len = data.length;
994
1337
  for (let pos = 0; pos < len;) {
995
1338
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -1013,8 +1356,8 @@ class HashMD extends Hash {
1013
1356
  return this;
1014
1357
  }
1015
1358
  digestInto(out) {
1016
- exists(this);
1017
- output$1(out, this);
1359
+ aexists(this);
1360
+ aoutput(out, this);
1018
1361
  this.finished = true;
1019
1362
  // Padding
1020
1363
  // We can avoid allocation of buffer for padding completely if it
@@ -1023,7 +1366,7 @@ class HashMD extends Hash {
1023
1366
  let { pos } = this;
1024
1367
  // append the bit '1' to the message
1025
1368
  buffer[pos++] = 0b10000000;
1026
- this.buffer.subarray(pos).fill(0);
1369
+ clean$1(this.buffer.subarray(pos));
1027
1370
  // we have less than padOffset left in buffer, so we cannot put length in
1028
1371
  // current block, need process it and pad again
1029
1372
  if (this.padOffset > blockLen - pos) {
@@ -1061,22 +1404,96 @@ class HashMD extends Hash {
1061
1404
  to || (to = new this.constructor());
1062
1405
  to.set(...this.get());
1063
1406
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
1407
+ to.destroyed = destroyed;
1408
+ to.finished = finished;
1064
1409
  to.length = length;
1065
1410
  to.pos = pos;
1066
- to.finished = finished;
1067
- to.destroyed = destroyed;
1068
1411
  if (length % blockLen)
1069
1412
  to.buffer.set(buffer);
1070
1413
  return to;
1071
1414
  }
1415
+ clone() {
1416
+ return this._cloneInto();
1417
+ }
1418
+ }
1419
+ /**
1420
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
1421
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
1422
+ */
1423
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
1424
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1425
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
1426
+ ]);
1427
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
1428
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1429
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
1430
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
1431
+ ]);
1432
+
1433
+ /**
1434
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
1435
+ * @todo re-check https://issues.chromium.org/issues/42212588
1436
+ * @module
1437
+ */
1438
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1439
+ const _32n = /* @__PURE__ */ BigInt(32);
1440
+ function fromBig(n, le = false) {
1441
+ if (le)
1442
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
1443
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1444
+ }
1445
+ function split(lst, le = false) {
1446
+ const len = lst.length;
1447
+ let Ah = new Uint32Array(len);
1448
+ let Al = new Uint32Array(len);
1449
+ for (let i = 0; i < len; i++) {
1450
+ const { h, l } = fromBig(lst[i], le);
1451
+ [Ah[i], Al[i]] = [h, l];
1452
+ }
1453
+ return [Ah, Al];
1454
+ }
1455
+ // for Shift in [0, 32)
1456
+ const shrSH = (h, _l, s) => h >>> s;
1457
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1458
+ // Right rotate for Shift in [1, 32)
1459
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
1460
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1461
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
1462
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
1463
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
1464
+ // Left rotate for Shift in [1, 32)
1465
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
1466
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
1467
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
1468
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
1469
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
1470
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
1471
+ // simple take carry out of low bit sum by shift, we need to use division.
1472
+ function add(Ah, Al, Bh, Bl) {
1473
+ const l = (Al >>> 0) + (Bl >>> 0);
1474
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
1072
1475
  }
1476
+ // Addition with more than 2 elements
1477
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1478
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
1479
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1480
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
1481
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1482
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
1073
1483
 
1074
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
1075
- // BTC network is doing 2^67 hashes/sec as per early 2023.
1076
- // Round constants:
1077
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
1484
+ /**
1485
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1486
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1487
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
1488
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1489
+ * @module
1490
+ */
1491
+ /**
1492
+ * Round constants:
1493
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
1494
+ */
1078
1495
  // prettier-ignore
1079
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
1496
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1080
1497
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1081
1498
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1082
1499
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -1086,18 +1503,11 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
1086
1503
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1087
1504
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1088
1505
  ]);
1089
- // Initial state:
1090
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
1091
- // prettier-ignore
1092
- const SHA256_IV = /* @__PURE__ */ new Uint32Array([
1093
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
1094
- ]);
1095
- // Temporary buffer, not used to store anything between runs
1096
- // Named this way because it matches specification.
1506
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1097
1507
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1098
1508
  class SHA256 extends HashMD {
1099
- constructor() {
1100
- super(64, 32, 8, false);
1509
+ constructor(outputLen = 32) {
1510
+ super(64, outputLen, 8, false);
1101
1511
  // We cannot use array here since array allows indexing by variable
1102
1512
  // which means optimizer/compiler cannot use registers.
1103
1513
  this.A = SHA256_IV[0] | 0;
@@ -1163,441 +1573,313 @@ class SHA256 extends HashMD {
1163
1573
  this.set(A, B, C, D, E, F, G, H);
1164
1574
  }
1165
1575
  roundClean() {
1166
- SHA256_W.fill(0);
1576
+ clean$1(SHA256_W);
1167
1577
  }
1168
1578
  destroy() {
1169
1579
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
1170
- this.buffer.fill(0);
1580
+ clean$1(this.buffer);
1171
1581
  }
1172
1582
  }
1173
- /**
1174
- * SHA2-256 hash function
1175
- * @param message - data that would be hashed
1176
- */
1177
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1178
-
1179
- // HMAC (RFC 2104)
1180
- class HMAC extends Hash {
1181
- constructor(hash, _key) {
1182
- super();
1183
- this.finished = false;
1184
- this.destroyed = false;
1185
- hash$1(hash);
1186
- const key = toBytes(_key);
1187
- this.iHash = hash.create();
1188
- if (typeof this.iHash.update !== 'function')
1189
- throw new Error('Expected instance of class which extends utils.Hash');
1190
- this.blockLen = this.iHash.blockLen;
1191
- this.outputLen = this.iHash.outputLen;
1192
- const blockLen = this.blockLen;
1193
- const pad = new Uint8Array(blockLen);
1194
- // blockLen can be bigger than outputLen
1195
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1196
- for (let i = 0; i < pad.length; i++)
1197
- pad[i] ^= 0x36;
1198
- this.iHash.update(pad);
1199
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
1200
- this.oHash = hash.create();
1201
- // Undo internal XOR && apply outer XOR
1202
- for (let i = 0; i < pad.length; i++)
1203
- pad[i] ^= 0x36 ^ 0x5c;
1204
- this.oHash.update(pad);
1205
- pad.fill(0);
1206
- }
1207
- update(buf) {
1208
- exists(this);
1209
- this.iHash.update(buf);
1210
- return this;
1211
- }
1212
- digestInto(out) {
1213
- exists(this);
1214
- bytes$1(out, this.outputLen);
1215
- this.finished = true;
1216
- this.iHash.digestInto(out);
1217
- this.oHash.update(out);
1218
- this.oHash.digestInto(out);
1219
- this.destroy();
1220
- }
1221
- digest() {
1222
- const out = new Uint8Array(this.oHash.outputLen);
1223
- this.digestInto(out);
1224
- return out;
1225
- }
1226
- _cloneInto(to) {
1227
- // Create new instance without calling constructor since key already in state and we don't know it.
1228
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
1229
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1230
- to = to;
1231
- to.finished = finished;
1232
- to.destroyed = destroyed;
1233
- to.blockLen = blockLen;
1234
- to.outputLen = outputLen;
1235
- to.oHash = oHash._cloneInto(to.oHash);
1236
- to.iHash = iHash._cloneInto(to.iHash);
1237
- return to;
1238
- }
1239
- destroy() {
1240
- this.destroyed = true;
1241
- this.oHash.destroy();
1242
- this.iHash.destroy();
1583
+ // SHA2-512 is slower than sha256 in js because u64 operations are slow.
1584
+ // Round contants
1585
+ // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
1586
+ // prettier-ignore
1587
+ const K512 = /* @__PURE__ */ (() => split([
1588
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
1589
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
1590
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
1591
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
1592
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
1593
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
1594
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
1595
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
1596
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
1597
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
1598
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
1599
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
1600
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
1601
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
1602
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
1603
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
1604
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
1605
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
1606
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
1607
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
1608
+ ].map(n => BigInt(n))))();
1609
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1610
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1611
+ // Reusable temporary buffers
1612
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1613
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1614
+ class SHA512 extends HashMD {
1615
+ constructor(outputLen = 64) {
1616
+ super(128, outputLen, 16, false);
1617
+ // We cannot use array here since array allows indexing by variable
1618
+ // which means optimizer/compiler cannot use registers.
1619
+ // h -- high 32 bits, l -- low 32 bits
1620
+ this.Ah = SHA512_IV[0] | 0;
1621
+ this.Al = SHA512_IV[1] | 0;
1622
+ this.Bh = SHA512_IV[2] | 0;
1623
+ this.Bl = SHA512_IV[3] | 0;
1624
+ this.Ch = SHA512_IV[4] | 0;
1625
+ this.Cl = SHA512_IV[5] | 0;
1626
+ this.Dh = SHA512_IV[6] | 0;
1627
+ this.Dl = SHA512_IV[7] | 0;
1628
+ this.Eh = SHA512_IV[8] | 0;
1629
+ this.El = SHA512_IV[9] | 0;
1630
+ this.Fh = SHA512_IV[10] | 0;
1631
+ this.Fl = SHA512_IV[11] | 0;
1632
+ this.Gh = SHA512_IV[12] | 0;
1633
+ this.Gl = SHA512_IV[13] | 0;
1634
+ this.Hh = SHA512_IV[14] | 0;
1635
+ this.Hl = SHA512_IV[15] | 0;
1243
1636
  }
1244
- }
1245
- /**
1246
- * HMAC: RFC2104 message authentication code.
1247
- * @param hash - function that would be used e.g. sha256
1248
- * @param key - message key
1249
- * @param message - message data
1250
- * @example
1251
- * import { hmac } from '@noble/hashes/hmac';
1252
- * import { sha256 } from '@noble/hashes/sha2';
1253
- * const mac1 = hmac(sha256, 'key', 'message');
1254
- */
1255
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1256
- hmac.create = (hash, key) => new HMAC(hash, key);
1257
-
1258
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1259
- // 100 lines of code in the file are duplicated from noble-hashes (utils).
1260
- // This is OK: `abstract` directory does not use noble-hashes.
1261
- // User may opt-in into using different hashing library. This way, noble-hashes
1262
- // won't be included into their bundle.
1263
- const _0n$4 = /* @__PURE__ */ BigInt(0);
1264
- const _1n$5 = /* @__PURE__ */ BigInt(1);
1265
- const _2n$3 = /* @__PURE__ */ BigInt(2);
1266
- function isBytes$1(a) {
1267
- return (a instanceof Uint8Array ||
1268
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
1269
- }
1270
- function abytes(item) {
1271
- if (!isBytes$1(item))
1272
- throw new Error('Uint8Array expected');
1273
- }
1274
- function abool(title, value) {
1275
- if (typeof value !== 'boolean')
1276
- throw new Error(`${title} must be valid boolean, got "${value}".`);
1277
- }
1278
- // Array where index 0xf0 (240) is mapped to string 'f0'
1279
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
1280
- /**
1281
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
1282
- */
1283
- function bytesToHex(bytes) {
1284
- abytes(bytes);
1285
- // pre-caching improves the speed 6x
1286
- let hex = '';
1287
- for (let i = 0; i < bytes.length; i++) {
1288
- hex += hexes[bytes[i]];
1637
+ // prettier-ignore
1638
+ get() {
1639
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1640
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1289
1641
  }
1290
- return hex;
1291
- }
1292
- function numberToHexUnpadded(num) {
1293
- const hex = num.toString(16);
1294
- return hex.length & 1 ? `0${hex}` : hex;
1295
- }
1296
- function hexToNumber(hex) {
1297
- if (typeof hex !== 'string')
1298
- throw new Error('hex string expected, got ' + typeof hex);
1299
- // Big Endian
1300
- return BigInt(hex === '' ? '0' : `0x${hex}`);
1301
- }
1302
- // We use optimized technique to convert hex string to byte array
1303
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
1304
- function asciiToBase16(char) {
1305
- if (char >= asciis._0 && char <= asciis._9)
1306
- return char - asciis._0;
1307
- if (char >= asciis._A && char <= asciis._F)
1308
- return char - (asciis._A - 10);
1309
- if (char >= asciis._a && char <= asciis._f)
1310
- return char - (asciis._a - 10);
1311
- return;
1312
- }
1313
- /**
1314
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
1315
- */
1316
- function hexToBytes(hex) {
1317
- if (typeof hex !== 'string')
1318
- throw new Error('hex string expected, got ' + typeof hex);
1319
- const hl = hex.length;
1320
- const al = hl / 2;
1321
- if (hl % 2)
1322
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
1323
- const array = new Uint8Array(al);
1324
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1325
- const n1 = asciiToBase16(hex.charCodeAt(hi));
1326
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1327
- if (n1 === undefined || n2 === undefined) {
1328
- const char = hex[hi] + hex[hi + 1];
1329
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1330
- }
1331
- array[ai] = n1 * 16 + n2;
1642
+ // prettier-ignore
1643
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1644
+ this.Ah = Ah | 0;
1645
+ this.Al = Al | 0;
1646
+ this.Bh = Bh | 0;
1647
+ this.Bl = Bl | 0;
1648
+ this.Ch = Ch | 0;
1649
+ this.Cl = Cl | 0;
1650
+ this.Dh = Dh | 0;
1651
+ this.Dl = Dl | 0;
1652
+ this.Eh = Eh | 0;
1653
+ this.El = El | 0;
1654
+ this.Fh = Fh | 0;
1655
+ this.Fl = Fl | 0;
1656
+ this.Gh = Gh | 0;
1657
+ this.Gl = Gl | 0;
1658
+ this.Hh = Hh | 0;
1659
+ this.Hl = Hl | 0;
1332
1660
  }
1333
- return array;
1334
- }
1335
- // BE: Big Endian, LE: Little Endian
1336
- function bytesToNumberBE(bytes) {
1337
- return hexToNumber(bytesToHex(bytes));
1338
- }
1339
- function bytesToNumberLE(bytes) {
1340
- abytes(bytes);
1341
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
1342
- }
1343
- function numberToBytesBE(n, len) {
1344
- return hexToBytes(n.toString(16).padStart(len * 2, '0'));
1345
- }
1346
- function numberToBytesLE(n, len) {
1347
- return numberToBytesBE(n, len).reverse();
1348
- }
1349
- /**
1350
- * Takes hex string or Uint8Array, converts to Uint8Array.
1351
- * Validates output length.
1352
- * Will throw error for other types.
1353
- * @param title descriptive title for an error e.g. 'private key'
1354
- * @param hex hex string or Uint8Array
1355
- * @param expectedLength optional, will compare to result array's length
1356
- * @returns
1357
- */
1358
- function ensureBytes(title, hex, expectedLength) {
1359
- let res;
1360
- if (typeof hex === 'string') {
1361
- try {
1362
- res = hexToBytes(hex);
1661
+ process(view, offset) {
1662
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
1663
+ for (let i = 0; i < 16; i++, offset += 4) {
1664
+ SHA512_W_H[i] = view.getUint32(offset);
1665
+ SHA512_W_L[i] = view.getUint32((offset += 4));
1363
1666
  }
1364
- catch (e) {
1365
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
1667
+ for (let i = 16; i < 80; i++) {
1668
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
1669
+ const W15h = SHA512_W_H[i - 15] | 0;
1670
+ const W15l = SHA512_W_L[i - 15] | 0;
1671
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1672
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1673
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
1674
+ const W2h = SHA512_W_H[i - 2] | 0;
1675
+ const W2l = SHA512_W_L[i - 2] | 0;
1676
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1677
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1678
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
1679
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1680
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1681
+ SHA512_W_H[i] = SUMh | 0;
1682
+ SHA512_W_L[i] = SUMl | 0;
1683
+ }
1684
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1685
+ // Compression function main loop, 80 rounds
1686
+ for (let i = 0; i < 80; i++) {
1687
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
1688
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1689
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1690
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1691
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
1692
+ const CHIl = (El & Fl) ^ (~El & Gl);
1693
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
1694
+ // prettier-ignore
1695
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1696
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1697
+ const T1l = T1ll | 0;
1698
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
1699
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1700
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1701
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
1702
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
1703
+ Hh = Gh | 0;
1704
+ Hl = Gl | 0;
1705
+ Gh = Fh | 0;
1706
+ Gl = Fl | 0;
1707
+ Fh = Eh | 0;
1708
+ Fl = El | 0;
1709
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1710
+ Dh = Ch | 0;
1711
+ Dl = Cl | 0;
1712
+ Ch = Bh | 0;
1713
+ Cl = Bl | 0;
1714
+ Bh = Ah | 0;
1715
+ Bl = Al | 0;
1716
+ const All = add3L(T1l, sigma0l, MAJl);
1717
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1718
+ Al = All | 0;
1366
1719
  }
1720
+ // Add the compressed chunk to the current hash value
1721
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1722
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1723
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1724
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1725
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1726
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1727
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1728
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1729
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1367
1730
  }
1368
- else if (isBytes$1(hex)) {
1369
- // Uint8Array.from() instead of hash.slice() because node.js Buffer
1370
- // is instance of Uint8Array, and its slice() creates **mutable** copy
1371
- res = Uint8Array.from(hex);
1731
+ roundClean() {
1732
+ clean$1(SHA512_W_H, SHA512_W_L);
1372
1733
  }
1373
- else {
1374
- throw new Error(`${title} must be hex string or Uint8Array`);
1734
+ destroy() {
1735
+ clean$1(this.buffer);
1736
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1375
1737
  }
1376
- const len = res.length;
1377
- if (typeof expectedLength === 'number' && len !== expectedLength)
1378
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
1379
- return res;
1380
1738
  }
1381
- /**
1382
- * Copies several Uint8Arrays into one.
1383
- */
1384
- function concatBytes(...arrays) {
1385
- let sum = 0;
1386
- for (let i = 0; i < arrays.length; i++) {
1387
- const a = arrays[i];
1388
- abytes(a);
1389
- sum += a.length;
1390
- }
1391
- const res = new Uint8Array(sum);
1392
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1393
- const a = arrays[i];
1394
- res.set(a, pad);
1395
- pad += a.length;
1739
+ /** SHA512/256 IV */
1740
+ const T256_IV = /* @__PURE__ */ Uint32Array.from([
1741
+ 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
1742
+ 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
1743
+ ]);
1744
+ class SHA512_256 extends SHA512 {
1745
+ constructor() {
1746
+ super(32);
1747
+ this.Ah = T256_IV[0] | 0;
1748
+ this.Al = T256_IV[1] | 0;
1749
+ this.Bh = T256_IV[2] | 0;
1750
+ this.Bl = T256_IV[3] | 0;
1751
+ this.Ch = T256_IV[4] | 0;
1752
+ this.Cl = T256_IV[5] | 0;
1753
+ this.Dh = T256_IV[6] | 0;
1754
+ this.Dl = T256_IV[7] | 0;
1755
+ this.Eh = T256_IV[8] | 0;
1756
+ this.El = T256_IV[9] | 0;
1757
+ this.Fh = T256_IV[10] | 0;
1758
+ this.Fl = T256_IV[11] | 0;
1759
+ this.Gh = T256_IV[12] | 0;
1760
+ this.Gl = T256_IV[13] | 0;
1761
+ this.Hh = T256_IV[14] | 0;
1762
+ this.Hl = T256_IV[15] | 0;
1396
1763
  }
1397
- return res;
1398
- }
1399
- // Is positive bigint
1400
- const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
1401
- function inRange(n, min, max) {
1402
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1403
- }
1404
- /**
1405
- * Asserts min <= n < max. NOTE: It's < max and not <= max.
1406
- * @example
1407
- * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
1408
- */
1409
- function aInRange(title, n, min, max) {
1410
- // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
1411
- // consider P=256n, min=0n, max=P
1412
- // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
1413
- // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
1414
- // - our way is the cleanest: `inRange('x', x, 0n, P)
1415
- if (!inRange(n, min, max))
1416
- throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
1417
1764
  }
1418
- // Bit operations
1419
1765
  /**
1420
- * Calculates amount of bits in a bigint.
1421
- * Same as `n.toString(2).length`
1766
+ * SHA2-256 hash function from RFC 4634.
1767
+ *
1768
+ * It is the fastest JS hash, even faster than Blake3.
1769
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1770
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1422
1771
  */
1423
- function bitLen(n) {
1424
- let len;
1425
- for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
1426
- ;
1427
- return len;
1428
- }
1772
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
1773
+ /** SHA2-512 hash function from RFC 4634. */
1774
+ const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
1429
1775
  /**
1430
- * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1431
- * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1776
+ * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
1777
+ * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
1432
1778
  */
1433
- const bitMask = (n) => (_2n$3 << BigInt(n - 1)) - _1n$5;
1434
- // DRBG
1435
- const u8n = (data) => new Uint8Array(data); // creates Uint8Array
1436
- const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
1779
+ const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
1780
+
1437
1781
  /**
1438
- * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1439
- * @returns function that will call DRBG until 2nd arg returns something meaningful
1440
- * @example
1441
- * const drbg = createHmacDRBG<Key>(32, 32, hmac);
1442
- * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
1782
+ * HMAC: RFC2104 message authentication code.
1783
+ * @module
1443
1784
  */
1444
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1445
- if (typeof hashLen !== 'number' || hashLen < 2)
1446
- throw new Error('hashLen must be a number');
1447
- if (typeof qByteLen !== 'number' || qByteLen < 2)
1448
- throw new Error('qByteLen must be a number');
1449
- if (typeof hmacFn !== 'function')
1450
- throw new Error('hmacFn must be a function');
1451
- // Step B, Step C: set hashLen to 8*ceil(hlen/8)
1452
- let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1453
- let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
1454
- let i = 0; // Iterations counter, will throw when over 1000
1455
- const reset = () => {
1456
- v.fill(1);
1457
- k.fill(0);
1458
- i = 0;
1459
- };
1460
- const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
1461
- const reseed = (seed = u8n()) => {
1462
- // HMAC-DRBG reseed() function. Steps D-G
1463
- k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
1464
- v = h(); // v = hmac(k || v)
1465
- if (seed.length === 0)
1466
- return;
1467
- k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
1468
- v = h(); // v = hmac(k || v)
1469
- };
1470
- const gen = () => {
1471
- // HMAC-DRBG generate() function
1472
- if (i++ >= 1000)
1473
- throw new Error('drbg: tried 1000 values');
1474
- let len = 0;
1475
- const out = [];
1476
- while (len < qByteLen) {
1477
- v = h();
1478
- const sl = v.slice();
1479
- out.push(sl);
1480
- len += v.length;
1481
- }
1482
- return concatBytes(...out);
1483
- };
1484
- const genUntil = (seed, pred) => {
1485
- reset();
1486
- reseed(seed); // Steps D-G
1487
- let res = undefined; // Step H: grind until k is in [1..n-1]
1488
- while (!(res = pred(gen())))
1489
- reseed();
1490
- reset();
1491
- return res;
1492
- };
1493
- return genUntil;
1494
- }
1495
- // Validating curves and fields
1496
- const validatorFns = {
1497
- bigint: (val) => typeof val === 'bigint',
1498
- function: (val) => typeof val === 'function',
1499
- boolean: (val) => typeof val === 'boolean',
1500
- string: (val) => typeof val === 'string',
1501
- stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
1502
- isSafeInteger: (val) => Number.isSafeInteger(val),
1503
- array: (val) => Array.isArray(val),
1504
- field: (val, object) => object.Fp.isValid(val),
1505
- hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1506
- };
1507
- // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1508
- function validateObject(object, validators, optValidators = {}) {
1509
- const checkField = (fieldName, type, isOptional) => {
1510
- const checkVal = validatorFns[type];
1511
- if (typeof checkVal !== 'function')
1512
- throw new Error(`Invalid validator "${type}", expected function`);
1513
- const val = object[fieldName];
1514
- if (isOptional && val === undefined)
1515
- return;
1516
- if (!checkVal(val, object)) {
1517
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
1518
- }
1519
- };
1520
- for (const [fieldName, type] of Object.entries(validators))
1521
- checkField(fieldName, type, false);
1522
- for (const [fieldName, type] of Object.entries(optValidators))
1523
- checkField(fieldName, type, true);
1524
- return object;
1785
+ class HMAC extends Hash {
1786
+ constructor(hash, _key) {
1787
+ super();
1788
+ this.finished = false;
1789
+ this.destroyed = false;
1790
+ ahash(hash);
1791
+ const key = toBytes(_key);
1792
+ this.iHash = hash.create();
1793
+ if (typeof this.iHash.update !== 'function')
1794
+ throw new Error('Expected instance of class which extends utils.Hash');
1795
+ this.blockLen = this.iHash.blockLen;
1796
+ this.outputLen = this.iHash.outputLen;
1797
+ const blockLen = this.blockLen;
1798
+ const pad = new Uint8Array(blockLen);
1799
+ // blockLen can be bigger than outputLen
1800
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1801
+ for (let i = 0; i < pad.length; i++)
1802
+ pad[i] ^= 0x36;
1803
+ this.iHash.update(pad);
1804
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
1805
+ this.oHash = hash.create();
1806
+ // Undo internal XOR && apply outer XOR
1807
+ for (let i = 0; i < pad.length; i++)
1808
+ pad[i] ^= 0x36 ^ 0x5c;
1809
+ this.oHash.update(pad);
1810
+ clean$1(pad);
1811
+ }
1812
+ update(buf) {
1813
+ aexists(this);
1814
+ this.iHash.update(buf);
1815
+ return this;
1816
+ }
1817
+ digestInto(out) {
1818
+ aexists(this);
1819
+ abytes$3(out, this.outputLen);
1820
+ this.finished = true;
1821
+ this.iHash.digestInto(out);
1822
+ this.oHash.update(out);
1823
+ this.oHash.digestInto(out);
1824
+ this.destroy();
1825
+ }
1826
+ digest() {
1827
+ const out = new Uint8Array(this.oHash.outputLen);
1828
+ this.digestInto(out);
1829
+ return out;
1830
+ }
1831
+ _cloneInto(to) {
1832
+ // Create new instance without calling constructor since key already in state and we don't know it.
1833
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1834
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1835
+ to = to;
1836
+ to.finished = finished;
1837
+ to.destroyed = destroyed;
1838
+ to.blockLen = blockLen;
1839
+ to.outputLen = outputLen;
1840
+ to.oHash = oHash._cloneInto(to.oHash);
1841
+ to.iHash = iHash._cloneInto(to.iHash);
1842
+ return to;
1843
+ }
1844
+ clone() {
1845
+ return this._cloneInto();
1846
+ }
1847
+ destroy() {
1848
+ this.destroyed = true;
1849
+ this.oHash.destroy();
1850
+ this.iHash.destroy();
1851
+ }
1525
1852
  }
1526
1853
  /**
1527
- * Memoizes (caches) computation result.
1528
- * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1854
+ * HMAC: RFC2104 message authentication code.
1855
+ * @param hash - function that would be used e.g. sha256
1856
+ * @param key - message key
1857
+ * @param message - message data
1858
+ * @example
1859
+ * import { hmac } from '@noble/hashes/hmac';
1860
+ * import { sha256 } from '@noble/hashes/sha2';
1861
+ * const mac1 = hmac(sha256, 'key', 'message');
1529
1862
  */
1530
- function memoized(fn) {
1531
- const map = new WeakMap();
1532
- return (arg, ...args) => {
1533
- const val = map.get(arg);
1534
- if (val !== undefined)
1535
- return val;
1536
- const computed = fn(arg, ...args);
1537
- map.set(arg, computed);
1538
- return computed;
1539
- };
1540
- }
1541
-
1542
- const ut = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
1543
- __proto__: null,
1544
- aInRange,
1545
- abool,
1546
- abytes,
1547
- bitLen,
1548
- bitMask,
1549
- bytesToHex,
1550
- bytesToNumberBE,
1551
- bytesToNumberLE,
1552
- concatBytes,
1553
- createHmacDrbg,
1554
- ensureBytes,
1555
- hexToBytes,
1556
- hexToNumber,
1557
- inRange,
1558
- isBytes: isBytes$1,
1559
- memoized,
1560
- numberToBytesBE,
1561
- numberToBytesLE,
1562
- numberToHexUnpadded,
1563
- validateObject
1564
- }, Symbol.toStringTag, { value: 'Module' }));
1863
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1864
+ hmac.create = (hash, key) => new HMAC(hash, key);
1565
1865
 
1866
+ /**
1867
+ * Utils for modular division and finite fields.
1868
+ * A finite field over 11 is integer number operations `mod 11`.
1869
+ * There is no division: it is replaced by modular multiplicative inverse.
1870
+ * @module
1871
+ */
1566
1872
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1567
- // Utilities for modular arithmetics and finite fields
1568
1873
  // prettier-ignore
1569
- const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = BigInt(2), _3n$1 = BigInt(3);
1874
+ const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
1570
1875
  // prettier-ignore
1571
- const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
1572
- // prettier-ignore
1573
- BigInt(9); BigInt(16);
1876
+ const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
1574
1877
  // Calculates a modulo b
1575
1878
  function mod(a, b) {
1576
1879
  const result = a % b;
1577
1880
  return result >= _0n$3 ? result : b + result;
1578
1881
  }
1579
- /**
1580
- * Efficiently raise num to power and do modular division.
1581
- * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1582
- * @example
1583
- * pow(2n, 6n, 11n) // 64n % 11n == 9n
1584
- */
1585
- // TODO: use field version && remove
1586
- function pow(num, power, modulo) {
1587
- if (modulo <= _0n$3 || power < _0n$3)
1588
- throw new Error('Expected power/modulo > 0');
1589
- if (modulo === _1n$4)
1590
- return _0n$3;
1591
- let res = _1n$4;
1592
- while (power > _0n$3) {
1593
- if (power & _1n$4)
1594
- res = (res * num) % modulo;
1595
- num = (num * num) % modulo;
1596
- power >>= _1n$4;
1597
- }
1598
- return res;
1599
- }
1600
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
1882
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
1601
1883
  function pow2(x, power, modulo) {
1602
1884
  let res = x;
1603
1885
  while (power-- > _0n$3) {
@@ -1606,12 +1888,15 @@ function pow2(x, power, modulo) {
1606
1888
  }
1607
1889
  return res;
1608
1890
  }
1609
- // Inverses number over modulo
1891
+ /**
1892
+ * Inverses number over modulo.
1893
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
1894
+ */
1610
1895
  function invert(number, modulo) {
1611
- if (number === _0n$3 || modulo <= _0n$3) {
1612
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
1613
- }
1614
- // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
1896
+ if (number === _0n$3)
1897
+ throw new Error('invert: expected non-zero number');
1898
+ if (modulo <= _0n$3)
1899
+ throw new Error('invert: expected positive modulus, got ' + modulo);
1615
1900
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
1616
1901
  let a = mod(number, modulo);
1617
1902
  let b = modulo;
@@ -1634,25 +1919,26 @@ function invert(number, modulo) {
1634
1919
  * Tonelli-Shanks square root search algorithm.
1635
1920
  * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
1636
1921
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
1637
- * Will start an infinite loop if field order P is not prime.
1638
1922
  * @param P field order
1639
1923
  * @returns function that takes field Fp (created from P) and number n
1640
1924
  */
1641
1925
  function tonelliShanks(P) {
1642
- // Legendre constant: used to calculate Legendre symbol (a | p),
1643
- // which denotes the value of a^((p-1)/2) (mod p).
1644
- // (a | p) ≡ 1 if a is a square (mod p)
1645
- // (a | p) ≡ -1 if a is not a square (mod p)
1646
- // (a | p) ≡ 0 if a ≡ 0 (mod p)
1647
- const legendreC = (P - _1n$4) / _2n$2;
1648
- let Q, S, Z;
1926
+ // Do expensive precomputation step
1649
1927
  // Step 1: By factoring out powers of 2 from p - 1,
1650
- // find q and s such that p - 1 = q*(2^s) with q odd
1651
- for (Q = P - _1n$4, S = 0; Q % _2n$2 === _0n$3; Q /= _2n$2, S++)
1652
- ;
1928
+ // find q and s such that p-1 == q*(2^s) with q odd
1929
+ let Q = P - _1n$4;
1930
+ let S = 0;
1931
+ while (Q % _2n$2 === _0n$3) {
1932
+ Q /= _2n$2;
1933
+ S++;
1934
+ }
1653
1935
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
1654
- for (Z = _2n$2; Z < P && pow(Z, legendreC, P) !== P - _1n$4; Z++)
1655
- ;
1936
+ let Z = _2n$2;
1937
+ const _Fp = Field(P);
1938
+ while (Z < P && FpIsSquare(_Fp, Z)) {
1939
+ if (Z++ > 1000)
1940
+ throw new Error('Cannot find square root: probably non-prime P');
1941
+ }
1656
1942
  // Fast-path
1657
1943
  if (S === 1) {
1658
1944
  const p1div4 = (P + _1n$4) / _4n;
@@ -1667,16 +1953,18 @@ function tonelliShanks(P) {
1667
1953
  const Q1div2 = (Q + _1n$4) / _2n$2;
1668
1954
  return function tonelliSlow(Fp, n) {
1669
1955
  // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
1670
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
1956
+ if (!FpIsSquare(Fp, n))
1671
1957
  throw new Error('Cannot find square root');
1672
1958
  let r = S;
1673
- // TODO: will fail at Fp2/etc
1959
+ // TODO: test on Fp2 and others
1674
1960
  let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
1675
1961
  let x = Fp.pow(n, Q1div2); // first guess at the square root
1676
1962
  let b = Fp.pow(n, Q); // first guess at the fudge factor
1677
1963
  while (!Fp.eql(b, Fp.ONE)) {
1964
+ // (4. If t = 0, return r = 0)
1965
+ // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
1678
1966
  if (Fp.eql(b, Fp.ZERO))
1679
- return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
1967
+ return Fp.ZERO;
1680
1968
  // Find m such b^(2^m)==1
1681
1969
  let m = 1;
1682
1970
  for (let t2 = Fp.sqr(b); m < r; m++) {
@@ -1684,7 +1972,8 @@ function tonelliShanks(P) {
1684
1972
  break;
1685
1973
  t2 = Fp.sqr(t2); // t2 *= t2
1686
1974
  }
1687
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
1975
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
1976
+ // otherwise there will be overflow.
1688
1977
  const ge = Fp.pow(g, _1n$4 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
1689
1978
  g = Fp.sqr(ge); // g = ge * ge
1690
1979
  x = Fp.mul(x, ge); // x *= ge
@@ -1694,9 +1983,18 @@ function tonelliShanks(P) {
1694
1983
  return x;
1695
1984
  };
1696
1985
  }
1986
+ /**
1987
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
1988
+ *
1989
+ * 1. P ≡ 3 (mod 4)
1990
+ * 2. P ≡ 5 (mod 8)
1991
+ * 3. P ≡ 9 (mod 16)
1992
+ * 4. Tonelli-Shanks algorithm
1993
+ *
1994
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
1995
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1996
+ */
1697
1997
  function FpSqrt(P) {
1698
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
1699
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1700
1998
  // P ≡ 3 (mod 4)
1701
1999
  // √n = n^((P+1)/4)
1702
2000
  if (P % _4n === _3n$1) {
@@ -1704,8 +2002,8 @@ function FpSqrt(P) {
1704
2002
  // const ORDER =
1705
2003
  // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
1706
2004
  // const NUM = 72057594037927816n;
1707
- const p1div4 = (P + _1n$4) / _4n;
1708
2005
  return function sqrt3mod4(Fp, n) {
2006
+ const p1div4 = (P + _1n$4) / _4n;
1709
2007
  const root = Fp.pow(n, p1div4);
1710
2008
  // Throw if root**2 != n
1711
2009
  if (!Fp.eql(Fp.sqr(root), n))
@@ -1715,9 +2013,9 @@ function FpSqrt(P) {
1715
2013
  }
1716
2014
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
1717
2015
  if (P % _8n === _5n) {
1718
- const c1 = (P - _5n) / _8n;
1719
2016
  return function sqrt5mod8(Fp, n) {
1720
2017
  const n2 = Fp.mul(n, _2n$2);
2018
+ const c1 = (P - _5n) / _8n;
1721
2019
  const v = Fp.pow(n2, c1);
1722
2020
  const nv = Fp.mul(n, v);
1723
2021
  const i = Fp.mul(Fp.mul(nv, _2n$2), v);
@@ -1754,66 +2052,92 @@ function validateField(field) {
1754
2052
  * Same as `pow` but for Fp: non-constant-time.
1755
2053
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1756
2054
  */
1757
- function FpPow(f, num, power) {
1758
- // Should have same speed as pow for bigints
1759
- // TODO: benchmark!
2055
+ function FpPow(Fp, num, power) {
1760
2056
  if (power < _0n$3)
1761
- throw new Error('Expected power > 0');
2057
+ throw new Error('invalid exponent, negatives unsupported');
1762
2058
  if (power === _0n$3)
1763
- return f.ONE;
2059
+ return Fp.ONE;
1764
2060
  if (power === _1n$4)
1765
2061
  return num;
1766
- let p = f.ONE;
2062
+ // @ts-ignore
2063
+ let p = Fp.ONE;
1767
2064
  let d = num;
1768
2065
  while (power > _0n$3) {
1769
2066
  if (power & _1n$4)
1770
- p = f.mul(p, d);
1771
- d = f.sqr(d);
2067
+ p = Fp.mul(p, d);
2068
+ d = Fp.sqr(d);
1772
2069
  power >>= _1n$4;
1773
2070
  }
1774
2071
  return p;
1775
2072
  }
1776
2073
  /**
1777
2074
  * Efficiently invert an array of Field elements.
1778
- * `inv(0)` will return `undefined` here: make sure to throw an error.
2075
+ * Exception-free. Will return `undefined` for 0 elements.
2076
+ * @param passZero map 0 to 0 (instead of undefined)
1779
2077
  */
1780
- function FpInvertBatch(f, nums) {
1781
- const tmp = new Array(nums.length);
2078
+ function FpInvertBatch(Fp, nums, passZero = false) {
2079
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
1782
2080
  // Walk from first to last, multiply them by each other MOD p
1783
- const lastMultiplied = nums.reduce((acc, num, i) => {
1784
- if (f.is0(num))
2081
+ const multipliedAcc = nums.reduce((acc, num, i) => {
2082
+ if (Fp.is0(num))
1785
2083
  return acc;
1786
- tmp[i] = acc;
1787
- return f.mul(acc, num);
1788
- }, f.ONE);
2084
+ inverted[i] = acc;
2085
+ return Fp.mul(acc, num);
2086
+ }, Fp.ONE);
1789
2087
  // Invert last element
1790
- const inverted = f.inv(lastMultiplied);
2088
+ const invertedAcc = Fp.inv(multipliedAcc);
1791
2089
  // Walk from last to first, multiply them by inverted each other MOD p
1792
2090
  nums.reduceRight((acc, num, i) => {
1793
- if (f.is0(num))
2091
+ if (Fp.is0(num))
1794
2092
  return acc;
1795
- tmp[i] = f.mul(acc, tmp[i]);
1796
- return f.mul(acc, num);
1797
- }, inverted);
1798
- return tmp;
2093
+ inverted[i] = Fp.mul(acc, inverted[i]);
2094
+ return Fp.mul(acc, num);
2095
+ }, invertedAcc);
2096
+ return inverted;
2097
+ }
2098
+ /**
2099
+ * Legendre symbol.
2100
+ * Legendre constant is used to calculate Legendre symbol (a | p)
2101
+ * which denotes the value of a^((p-1)/2) (mod p)..
2102
+ *
2103
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
2104
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
2105
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
2106
+ */
2107
+ function FpLegendre(Fp, n) {
2108
+ const legc = (Fp.ORDER - _1n$4) / _2n$2;
2109
+ const powered = Fp.pow(n, legc);
2110
+ const yes = Fp.eql(powered, Fp.ONE);
2111
+ const zero = Fp.eql(powered, Fp.ZERO);
2112
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
2113
+ if (!yes && !zero && !no)
2114
+ throw new Error('Cannot find square root: probably non-prime P');
2115
+ return yes ? 1 : zero ? 0 : -1;
2116
+ }
2117
+ // This function returns True whenever the value x is a square in the field F.
2118
+ function FpIsSquare(Fp, n) {
2119
+ const l = FpLegendre(Fp, n);
2120
+ return l === 0 || l === 1;
1799
2121
  }
1800
2122
  // CURVE.n lengths
1801
2123
  function nLength(n, nBitLength) {
1802
2124
  // Bit size, byte size of CURVE.n
2125
+ if (nBitLength !== undefined)
2126
+ anumber(nBitLength);
1803
2127
  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
1804
2128
  const nByteLength = Math.ceil(_nBitLength / 8);
1805
2129
  return { nBitLength: _nBitLength, nByteLength };
1806
2130
  }
1807
2131
  /**
1808
- * Initializes a finite field over prime. **Non-primes are not supported.**
1809
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
2132
+ * Initializes a finite field over prime.
1810
2133
  * Major performance optimizations:
1811
2134
  * * a) denormalized operations like mulN instead of mul
1812
2135
  * * b) same object shape: never add or remove keys
1813
2136
  * * c) Object.freeze
1814
- * NOTE: operations don't check 'isValid' for all elements for performance reasons,
2137
+ * Fragile: always run a benchmark on a change.
2138
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
1815
2139
  * it is caller responsibility to check this.
1816
- * This is low-level code, please make sure you know what you doing.
2140
+ * This is low-level code, please make sure you know what you're doing.
1817
2141
  * @param ORDER prime positive bigint
1818
2142
  * @param bitLen how many bits the field consumes
1819
2143
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -1821,13 +2145,14 @@ function nLength(n, nBitLength) {
1821
2145
  */
1822
2146
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
1823
2147
  if (ORDER <= _0n$3)
1824
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
2148
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
1825
2149
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
1826
2150
  if (BYTES > 2048)
1827
- throw new Error('Field lengths over 2048 bytes are not supported');
1828
- const sqrtP = FpSqrt(ORDER);
2151
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
2152
+ let sqrtP; // cached sqrtP
1829
2153
  const f = Object.freeze({
1830
2154
  ORDER,
2155
+ isLE,
1831
2156
  BITS,
1832
2157
  BYTES,
1833
2158
  MASK: bitMask(BITS),
@@ -1836,7 +2161,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1836
2161
  create: (num) => mod(num, ORDER),
1837
2162
  isValid: (num) => {
1838
2163
  if (typeof num !== 'bigint')
1839
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
2164
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
1840
2165
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1841
2166
  },
1842
2167
  is0: (num) => num === _0n$3,
@@ -1855,17 +2180,23 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1855
2180
  subN: (lhs, rhs) => lhs - rhs,
1856
2181
  mulN: (lhs, rhs) => lhs * rhs,
1857
2182
  inv: (num) => invert(num, ORDER),
1858
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
1859
- invertBatch: (lst) => FpInvertBatch(f, lst),
1860
- // TODO: do we really need constant cmov?
1861
- // We don't have const-time bigints anyway, so probably will be not very useful
1862
- cmov: (a, b, c) => (c ? b : a),
2183
+ sqrt: redef.sqrt ||
2184
+ ((n) => {
2185
+ if (!sqrtP)
2186
+ sqrtP = FpSqrt(ORDER);
2187
+ return sqrtP(f, n);
2188
+ }),
1863
2189
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
1864
2190
  fromBytes: (bytes) => {
1865
2191
  if (bytes.length !== BYTES)
1866
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
2192
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
1867
2193
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1868
2194
  },
2195
+ // TODO: we don't need it here, move out to separate fn
2196
+ invertBatch: (lst) => FpInvertBatch(f, lst),
2197
+ // We can't move this out because Fp6, Fp12 implement it
2198
+ // and it's unclear what to return in there.
2199
+ cmov: (a, b, c) => (c ? b : a),
1869
2200
  });
1870
2201
  return Object.freeze(f);
1871
2202
  }
@@ -1911,52 +2242,106 @@ function mapHashToField(key, fieldOrder, isLE = false) {
1911
2242
  const minLen = getMinHashLength(fieldOrder);
1912
2243
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
1913
2244
  if (len < 16 || len < minLen || len > 1024)
1914
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
1915
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
2245
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
2246
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1916
2247
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
1917
2248
  const reduced = mod(num, fieldOrder - _1n$4) + _1n$4;
1918
2249
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1919
2250
  }
1920
2251
 
2252
+ /**
2253
+ * Methods for elliptic curve multiplication by scalars.
2254
+ * Contains wNAF, pippenger
2255
+ * @module
2256
+ */
1921
2257
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1922
- // Abelian group utilities
1923
2258
  const _0n$2 = BigInt(0);
1924
2259
  const _1n$3 = BigInt(1);
2260
+ function constTimeNegate(condition, item) {
2261
+ const neg = item.negate();
2262
+ return condition ? neg : item;
2263
+ }
2264
+ function validateW(W, bits) {
2265
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
2266
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
2267
+ }
2268
+ function calcWOpts(W, scalarBits) {
2269
+ validateW(W, scalarBits);
2270
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
2271
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
2272
+ const maxNumber = 2 ** W; // W=8 256
2273
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
2274
+ const shiftBy = BigInt(W); // W=8 8
2275
+ return { windows, windowSize, mask, maxNumber, shiftBy };
2276
+ }
2277
+ function calcOffsets(n, window, wOpts) {
2278
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
2279
+ let wbits = Number(n & mask); // extract W bits.
2280
+ let nextN = n >> shiftBy; // shift number by W bits.
2281
+ // What actually happens here:
2282
+ // const highestBit = Number(mask ^ (mask >> 1n));
2283
+ // let wbits2 = wbits - 1; // skip zero
2284
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
2285
+ // split if bits > max: +224 => 256-32
2286
+ if (wbits > windowSize) {
2287
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
2288
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
2289
+ nextN += _1n$3; // +256 (carry)
2290
+ }
2291
+ const offsetStart = window * windowSize;
2292
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
2293
+ const isZero = wbits === 0; // is current window slice a 0?
2294
+ const isNeg = wbits < 0; // is current window slice negative?
2295
+ const isNegF = window % 2 !== 0; // fake random statement for noise
2296
+ const offsetF = offsetStart; // fake offset for noise
2297
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
2298
+ }
2299
+ function validateMSMPoints(points, c) {
2300
+ if (!Array.isArray(points))
2301
+ throw new Error('array expected');
2302
+ points.forEach((p, i) => {
2303
+ if (!(p instanceof c))
2304
+ throw new Error('invalid point at index ' + i);
2305
+ });
2306
+ }
2307
+ function validateMSMScalars(scalars, field) {
2308
+ if (!Array.isArray(scalars))
2309
+ throw new Error('array of scalars expected');
2310
+ scalars.forEach((s, i) => {
2311
+ if (!field.isValid(s))
2312
+ throw new Error('invalid scalar at index ' + i);
2313
+ });
2314
+ }
1925
2315
  // Since points in different groups cannot be equal (different object constructor),
1926
- // we can have single place to store precomputes
2316
+ // we can have single place to store precomputes.
2317
+ // Allows to make points frozen / immutable.
1927
2318
  const pointPrecomputes = new WeakMap();
1928
- const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
1929
- // Elliptic curve multiplication of Point by scalar. Fragile.
1930
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
1931
- // Creates precomputation tables for fast multiplication:
1932
- // - private scalar is split by fixed size windows of W bits
1933
- // - every window point is collected from window's table & added to accumulator
1934
- // - since windows are different, same point inside tables won't be accessed more than once per calc
1935
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1936
- // - +1 window is neccessary for wNAF
1937
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1938
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
1939
- // windows to be in different memory locations
2319
+ const pointWindowSizes = new WeakMap();
2320
+ function getW(P) {
2321
+ return pointWindowSizes.get(P) || 1;
2322
+ }
2323
+ /**
2324
+ * Elliptic curve multiplication of Point by scalar. Fragile.
2325
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
2326
+ * Creates precomputation tables for fast multiplication:
2327
+ * - private scalar is split by fixed size windows of W bits
2328
+ * - every window point is collected from window's table & added to accumulator
2329
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
2330
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
2331
+ * - +1 window is neccessary for wNAF
2332
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
2333
+ *
2334
+ * @todo Research returning 2d JS array of windows, instead of a single window.
2335
+ * This would allow windows to be in different memory locations
2336
+ */
1940
2337
  function wNAF(c, bits) {
1941
- const constTimeNegate = (condition, item) => {
1942
- const neg = item.negate();
1943
- return condition ? neg : item;
1944
- };
1945
- const validateW = (W) => {
1946
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1947
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
1948
- };
1949
- const opts = (W) => {
1950
- validateW(W);
1951
- const windows = Math.ceil(bits / W) + 1; // +1, because
1952
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
1953
- return { windows, windowSize };
1954
- };
1955
2338
  return {
1956
2339
  constTimeNegate,
2340
+ hasPrecomputes(elm) {
2341
+ return getW(elm) !== 1;
2342
+ },
1957
2343
  // non-const time multiplication ladder
1958
- unsafeLadder(elm, n) {
1959
- let p = c.ZERO;
2344
+ unsafeLadder(elm, n, p = c.ZERO) {
1960
2345
  let d = elm;
1961
2346
  while (n > _0n$2) {
1962
2347
  if (n & _1n$3)
@@ -1974,17 +2359,19 @@ function wNAF(c, bits) {
1974
2359
  * - 𝑊 is the window size
1975
2360
  * - 𝑛 is the bitlength of the curve order.
1976
2361
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
2362
+ * @param elm Point instance
2363
+ * @param W window size
1977
2364
  * @returns precomputed point tables flattened to a single array
1978
2365
  */
1979
2366
  precomputeWindow(elm, W) {
1980
- const { windows, windowSize } = opts(W);
2367
+ const { windows, windowSize } = calcWOpts(W, bits);
1981
2368
  const points = [];
1982
2369
  let p = elm;
1983
2370
  let base = p;
1984
2371
  for (let window = 0; window < windows; window++) {
1985
2372
  base = p;
1986
2373
  points.push(base);
1987
- // =1, because we skip zero
2374
+ // i=1, bc we skip 0
1988
2375
  for (let i = 1; i < windowSize; i++) {
1989
2376
  base = base.add(p);
1990
2377
  points.push(base);
@@ -2001,54 +2388,67 @@ function wNAF(c, bits) {
2001
2388
  * @returns real and fake (for const-time) points
2002
2389
  */
2003
2390
  wNAF(W, precomputes, n) {
2004
- // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
2005
- // But need to carefully remove other checks before wNAF. ORDER == bits here
2006
- const { windows, windowSize } = opts(W);
2391
+ // Smaller version:
2392
+ // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
2393
+ // TODO: check the scalar is less than group order?
2394
+ // wNAF behavior is undefined otherwise. But have to carefully remove
2395
+ // other checks before wNAF. ORDER == bits here.
2396
+ // Accumulators
2007
2397
  let p = c.ZERO;
2008
2398
  let f = c.BASE;
2009
- const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
2010
- const maxNumber = 2 ** W;
2011
- const shiftBy = BigInt(W);
2012
- for (let window = 0; window < windows; window++) {
2013
- const offset = window * windowSize;
2014
- // Extract W bits.
2015
- let wbits = Number(n & mask);
2016
- // Shift number by W bits.
2017
- n >>= shiftBy;
2018
- // If the bits are bigger than max size, we'll split those.
2019
- // +224 => 256 - 32
2020
- if (wbits > windowSize) {
2021
- wbits -= maxNumber;
2022
- n += _1n$3;
2023
- }
2024
- // This code was first written with assumption that 'f' and 'p' will never be infinity point:
2025
- // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
2026
- // there is negate now: it is possible that negated element from low value
2027
- // would be the same as high element, which will create carry into next window.
2028
- // It's not obvious how this can fail, but still worth investigating later.
2029
- // Check if we're onto Zero point.
2030
- // Add random point inside current window to f.
2031
- const offset1 = offset;
2032
- const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
2033
- const cond1 = window % 2 !== 0;
2034
- const cond2 = wbits < 0;
2035
- if (wbits === 0) {
2036
- // The most important part for const-time getPublicKey
2037
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
2399
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
2400
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
2401
+ // there is negate now: it is possible that negated element from low value
2402
+ // would be the same as high element, which will create carry into next window.
2403
+ // It's not obvious how this can fail, but still worth investigating later.
2404
+ const wo = calcWOpts(W, bits);
2405
+ for (let window = 0; window < wo.windows; window++) {
2406
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
2407
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
2408
+ n = nextN;
2409
+ if (isZero) {
2410
+ // bits are 0: add garbage to fake point
2411
+ // Important part for const-time getPublicKey: add random "noise" point to f.
2412
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
2038
2413
  }
2039
2414
  else {
2040
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
2415
+ // bits are 1: add to result point
2416
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
2041
2417
  }
2042
2418
  }
2043
- // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
2044
- // Even if the variable is still unused, there are some checks which will
2045
- // throw an exception, so compiler needs to prove they won't happen, which is hard.
2419
+ // Return both real and fake points: JIT won't eliminate f.
2046
2420
  // At this point there is a way to F be infinity-point even if p is not,
2047
2421
  // which makes it less const-time: around 1 bigint multiply.
2048
2422
  return { p, f };
2049
2423
  },
2050
- wNAFCached(P, n, transform) {
2051
- const W = pointWindowSizes.get(P) || 1;
2424
+ /**
2425
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
2426
+ * @param W window size
2427
+ * @param precomputes precomputed tables
2428
+ * @param n scalar (we don't check here, but should be less than curve order)
2429
+ * @param acc accumulator point to add result of multiplication
2430
+ * @returns point
2431
+ */
2432
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
2433
+ const wo = calcWOpts(W, bits);
2434
+ for (let window = 0; window < wo.windows; window++) {
2435
+ if (n === _0n$2)
2436
+ break; // Early-exit, skip 0 value
2437
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
2438
+ n = nextN;
2439
+ if (isZero) {
2440
+ // Window bits are 0: skip processing.
2441
+ // Move to next window.
2442
+ continue;
2443
+ }
2444
+ else {
2445
+ const item = precomputes[offset];
2446
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
2447
+ }
2448
+ }
2449
+ return acc;
2450
+ },
2451
+ getPrecomputes(W, P, transform) {
2052
2452
  // Calculate precomputes on a first run, reuse them after
2053
2453
  let comp = pointPrecomputes.get(P);
2054
2454
  if (!comp) {
@@ -2056,62 +2456,66 @@ function wNAF(c, bits) {
2056
2456
  if (W !== 1)
2057
2457
  pointPrecomputes.set(P, transform(comp));
2058
2458
  }
2059
- return this.wNAF(W, comp, n);
2459
+ return comp;
2460
+ },
2461
+ wNAFCached(P, n, transform) {
2462
+ const W = getW(P);
2463
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
2464
+ },
2465
+ wNAFCachedUnsafe(P, n, transform, prev) {
2466
+ const W = getW(P);
2467
+ if (W === 1)
2468
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
2469
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
2060
2470
  },
2061
2471
  // We calculate precomputes for elliptic curve point multiplication
2062
2472
  // using windowed method. This specifies window size and
2063
2473
  // stores precomputed values. Usually only base point would be precomputed.
2064
2474
  setWindowSize(P, W) {
2065
- validateW(W);
2475
+ validateW(W, bits);
2066
2476
  pointWindowSizes.set(P, W);
2067
2477
  pointPrecomputes.delete(P);
2068
2478
  },
2069
2479
  };
2070
2480
  }
2071
2481
  /**
2072
- * Pippenger algorithm for multi-scalar multiplication (MSM).
2073
- * MSM is basically (Pa + Qb + Rc + ...).
2074
- * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
2482
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
2483
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
2075
2484
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
2076
2485
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
2077
2486
  * @param c Curve Point constructor
2078
- * @param field field over CURVE.N - important that it's not over CURVE.P
2487
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
2079
2488
  * @param points array of L curve points
2080
2489
  * @param scalars array of L scalars (aka private keys / bigints)
2081
2490
  */
2082
- function pippenger(c, field, points, scalars) {
2491
+ function pippenger(c, fieldN, points, scalars) {
2083
2492
  // If we split scalars by some window (let's say 8 bits), every chunk will only
2084
2493
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
2085
2494
  // TODO:
2086
2495
  // - https://eprint.iacr.org/2024/750.pdf
2087
2496
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
2088
2497
  // 0 is accepted in scalars
2089
- if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
2498
+ validateMSMPoints(points, c);
2499
+ validateMSMScalars(scalars, fieldN);
2500
+ if (points.length !== scalars.length)
2090
2501
  throw new Error('arrays of points and scalars must have equal length');
2091
- scalars.forEach((s, i) => {
2092
- if (!field.isValid(s))
2093
- throw new Error(`wrong scalar at index ${i}`);
2094
- });
2095
- points.forEach((p, i) => {
2096
- if (!(p instanceof c))
2097
- throw new Error(`wrong point at index ${i}`);
2098
- });
2502
+ const zero = c.ZERO;
2099
2503
  const wbits = bitLen(BigInt(points.length));
2100
2504
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
2101
- const MASK = (1 << windowSize) - 1;
2102
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
2103
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
2104
- let sum = c.ZERO;
2505
+ const MASK = bitMask(windowSize);
2506
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
2507
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
2508
+ let sum = zero;
2105
2509
  for (let i = lastBits; i >= 0; i -= windowSize) {
2106
- buckets.fill(c.ZERO);
2510
+ buckets.fill(zero);
2107
2511
  for (let j = 0; j < scalars.length; j++) {
2108
2512
  const scalar = scalars[j];
2109
- const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
2513
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
2110
2514
  buckets[wbits] = buckets[wbits].add(points[j]);
2111
2515
  }
2112
- let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
2516
+ let resI = zero; // not using this will do small speed-up, but will lose ct
2113
2517
  // Skip first bucket, because it is zero
2114
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
2518
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
2115
2519
  sumI = sumI.add(buckets[j]);
2116
2520
  resI = resI.add(sumI);
2117
2521
  }
@@ -2141,8 +2545,47 @@ function validateBasic(curve) {
2141
2545
  });
2142
2546
  }
2143
2547
 
2548
+ /**
2549
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
2550
+ *
2551
+ * ### Parameters
2552
+ *
2553
+ * To initialize a weierstrass curve, one needs to pass following params:
2554
+ *
2555
+ * * a: formula param
2556
+ * * b: formula param
2557
+ * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
2558
+ * * n: Curve prime subgroup order, total count of valid points in the field
2559
+ * * Gx: Base point (x, y) aka generator point x coordinate
2560
+ * * Gy: ...y coordinate
2561
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
2562
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
2563
+ *
2564
+ * ### Design rationale for types
2565
+ *
2566
+ * * Interaction between classes from different curves should fail:
2567
+ * `k256.Point.BASE.add(p256.Point.BASE)`
2568
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
2569
+ * * Different calls of `curve()` would return different classes -
2570
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
2571
+ * it won't affect others
2572
+ *
2573
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
2574
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
2575
+ * unique type for every function call.
2576
+ *
2577
+ * We can use generic types via some param, like curve opts, but that would:
2578
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
2579
+ * which is hard to debug.
2580
+ * 2. Params can be generic and we can't enforce them to be constant value:
2581
+ * if somebody creates curve from non-constant params,
2582
+ * it would be allowed to interact with other curves with non-constant params
2583
+ *
2584
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
2585
+ * @module
2586
+ */
2144
2587
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2145
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
2588
+ // prettier-ignore
2146
2589
  function validateSigVerOpts(opts) {
2147
2590
  if (opts.lowS !== undefined)
2148
2591
  abool('lowS', opts.lowS);
@@ -2166,17 +2609,21 @@ function validatePointOpts(curve) {
2166
2609
  const { endo, Fp, a } = opts;
2167
2610
  if (endo) {
2168
2611
  if (!Fp.eql(a, Fp.ZERO)) {
2169
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
2612
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
2170
2613
  }
2171
2614
  if (typeof endo !== 'object' ||
2172
2615
  typeof endo.beta !== 'bigint' ||
2173
2616
  typeof endo.splitScalar !== 'function') {
2174
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
2617
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
2175
2618
  }
2176
2619
  }
2177
2620
  return Object.freeze({ ...opts });
2178
2621
  }
2179
- const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
2622
+ class DERErr extends Error {
2623
+ constructor(m = '') {
2624
+ super(m);
2625
+ }
2626
+ }
2180
2627
  /**
2181
2628
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
2182
2629
  *
@@ -2186,11 +2633,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
2186
2633
  */
2187
2634
  const DER = {
2188
2635
  // asn.1 DER encoding utils
2189
- Err: class DERErr extends Error {
2190
- constructor(m = '') {
2191
- super(m);
2192
- }
2193
- },
2636
+ Err: DERErr,
2194
2637
  // Basic building block is TLV (Tag-Length-Value)
2195
2638
  _tlv: {
2196
2639
  encode: (tag, data) => {
@@ -2205,7 +2648,8 @@ const DER = {
2205
2648
  throw new E('tlv.encode: long form length too big');
2206
2649
  // length of length with long form flag
2207
2650
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
2208
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
2651
+ const t = numberToHexUnpadded(tag);
2652
+ return t + lenLen + len + data;
2209
2653
  },
2210
2654
  // v - value, l - left bytes (unparsed)
2211
2655
  decode(tag, data) {
@@ -2258,35 +2702,36 @@ const DER = {
2258
2702
  if (Number.parseInt(hex[0], 16) & 0b1000)
2259
2703
  hex = '00' + hex;
2260
2704
  if (hex.length & 1)
2261
- throw new E('unexpected assertion');
2705
+ throw new E('unexpected DER parsing assertion: unpadded hex');
2262
2706
  return hex;
2263
2707
  },
2264
2708
  decode(data) {
2265
2709
  const { Err: E } = DER;
2266
2710
  if (data[0] & 128)
2267
- throw new E('Invalid signature integer: negative');
2711
+ throw new E('invalid signature integer: negative');
2268
2712
  if (data[0] === 0x00 && !(data[1] & 128))
2269
- throw new E('Invalid signature integer: unnecessary leading zero');
2270
- return b2n(data);
2713
+ throw new E('invalid signature integer: unnecessary leading zero');
2714
+ return bytesToNumberBE(data);
2271
2715
  },
2272
2716
  },
2273
2717
  toSig(hex) {
2274
2718
  // parse DER signature
2275
2719
  const { Err: E, _int: int, _tlv: tlv } = DER;
2276
- const data = typeof hex === 'string' ? h2b(hex) : hex;
2277
- abytes(data);
2720
+ const data = ensureBytes('signature', hex);
2278
2721
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
2279
2722
  if (seqLeftBytes.length)
2280
- throw new E('Invalid signature: left bytes after parsing');
2723
+ throw new E('invalid signature: left bytes after parsing');
2281
2724
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
2282
2725
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
2283
2726
  if (sLeftBytes.length)
2284
- throw new E('Invalid signature: left bytes after parsing');
2727
+ throw new E('invalid signature: left bytes after parsing');
2285
2728
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
2286
2729
  },
2287
2730
  hexFromSig(sig) {
2288
2731
  const { _tlv: tlv, _int: int } = DER;
2289
- const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
2732
+ const rs = tlv.encode(0x02, int.encode(sig.r));
2733
+ const ss = tlv.encode(0x02, int.encode(sig.s));
2734
+ const seq = rs + ss;
2290
2735
  return tlv.encode(0x30, seq);
2291
2736
  },
2292
2737
  };
@@ -2312,7 +2757,7 @@ function weierstrassPoints(opts) {
2312
2757
  return { x, y };
2313
2758
  });
2314
2759
  /**
2315
- * y² = x³ + ax + b: Short weierstrass curve formula
2760
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
2316
2761
  * @returns y²
2317
2762
  */
2318
2763
  function weierstrassEquation(x) {
@@ -2340,7 +2785,7 @@ function weierstrassPoints(opts) {
2340
2785
  key = bytesToHex(key);
2341
2786
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
2342
2787
  if (typeof key !== 'string' || !lengths.includes(key.length))
2343
- throw new Error('Invalid key');
2788
+ throw new Error('invalid private key');
2344
2789
  key = key.padStart(nByteLength * 2, '0');
2345
2790
  }
2346
2791
  let num;
@@ -2351,14 +2796,14 @@ function weierstrassPoints(opts) {
2351
2796
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
2352
2797
  }
2353
2798
  catch (error) {
2354
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
2799
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
2355
2800
  }
2356
2801
  if (wrapPrivateKey)
2357
2802
  num = mod(num, N); // disabled by default, enabled for BLS
2358
2803
  aInRange('private key', num, _1n$2, N); // num in range [1..N-1]
2359
2804
  return num;
2360
2805
  }
2361
- function assertPrjPoint(other) {
2806
+ function aprjpoint(other) {
2362
2807
  if (!(other instanceof Point))
2363
2808
  throw new Error('ProjectivePoint expected');
2364
2809
  }
@@ -2391,7 +2836,7 @@ function weierstrassPoints(opts) {
2391
2836
  if (p.is0()) {
2392
2837
  // (0, 1, 0) aka ZERO is invalid in most contexts.
2393
2838
  // In BLS, ZERO can be serialized, so we allow it.
2394
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
2839
+ // (0, 0, 0) is invalid representation of ZERO.
2395
2840
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
2396
2841
  return;
2397
2842
  throw new Error('bad point: ZERO');
@@ -2416,15 +2861,15 @@ function weierstrassPoints(opts) {
2416
2861
  */
2417
2862
  class Point {
2418
2863
  constructor(px, py, pz) {
2419
- this.px = px;
2420
- this.py = py;
2421
- this.pz = pz;
2422
2864
  if (px == null || !Fp.isValid(px))
2423
2865
  throw new Error('x required');
2424
- if (py == null || !Fp.isValid(py))
2866
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
2425
2867
  throw new Error('y required');
2426
2868
  if (pz == null || !Fp.isValid(pz))
2427
2869
  throw new Error('z required');
2870
+ this.px = px;
2871
+ this.py = py;
2872
+ this.pz = pz;
2428
2873
  Object.freeze(this);
2429
2874
  }
2430
2875
  // Does not validate if the point is on-curve.
@@ -2454,7 +2899,7 @@ function weierstrassPoints(opts) {
2454
2899
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
2455
2900
  */
2456
2901
  static normalizeZ(points) {
2457
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
2902
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
2458
2903
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
2459
2904
  }
2460
2905
  /**
@@ -2492,7 +2937,7 @@ function weierstrassPoints(opts) {
2492
2937
  * Compare one point to another.
2493
2938
  */
2494
2939
  equals(other) {
2495
- assertPrjPoint(other);
2940
+ aprjpoint(other);
2496
2941
  const { px: X1, py: Y1, pz: Z1 } = this;
2497
2942
  const { px: X2, py: Y2, pz: Z2 } = other;
2498
2943
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
@@ -2552,7 +2997,7 @@ function weierstrassPoints(opts) {
2552
2997
  // https://eprint.iacr.org/2015/1060, algorithm 1
2553
2998
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2554
2999
  add(other) {
2555
- assertPrjPoint(other);
3000
+ aprjpoint(other);
2556
3001
  const { px: X1, py: Y1, pz: Z1 } = this;
2557
3002
  const { px: X2, py: Y2, pz: Z2 } = other;
2558
3003
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
@@ -2615,16 +3060,17 @@ function weierstrassPoints(opts) {
2615
3060
  * an exposed private key e.g. sig verification, which works over *public* keys.
2616
3061
  */
2617
3062
  multiplyUnsafe(sc) {
2618
- aInRange('scalar', sc, _0n$1, CURVE.n);
3063
+ const { endo, n: N } = CURVE;
3064
+ aInRange('scalar', sc, _0n$1, N);
2619
3065
  const I = Point.ZERO;
2620
3066
  if (sc === _0n$1)
2621
3067
  return I;
2622
- if (sc === _1n$2)
3068
+ if (this.is0() || sc === _1n$2)
2623
3069
  return this;
2624
- const { endo } = CURVE;
2625
- if (!endo)
2626
- return wnaf.unsafeLadder(this, sc);
2627
- // Apply endomorphism
3070
+ // Case a: no endomorphism. Case b: has precomputes.
3071
+ if (!endo || wnaf.hasPrecomputes(this))
3072
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
3073
+ // Case c: endomorphism
2628
3074
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
2629
3075
  let k1p = I;
2630
3076
  let k2p = I;
@@ -2722,10 +3168,9 @@ function weierstrassPoints(opts) {
2722
3168
  }
2723
3169
  }
2724
3170
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2725
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
3171
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
2726
3172
  const _bits = CURVE.nBitLength;
2727
3173
  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
2728
- // Validate if generator point is on curve
2729
3174
  return {
2730
3175
  CURVE,
2731
3176
  ProjectivePoint: Point,
@@ -2810,11 +3255,13 @@ function weierstrass(curveDef) {
2810
3255
  return { x, y };
2811
3256
  }
2812
3257
  else {
2813
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
3258
+ const cl = compressedLen;
3259
+ const ul = uncompressedLen;
3260
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
2814
3261
  }
2815
3262
  },
2816
3263
  });
2817
- const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
3264
+ const numToNByteHex = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
2818
3265
  function isBiggerThanHalfOrder(number) {
2819
3266
  const HALF = CURVE_ORDER >> _1n$2;
2820
3267
  return number > HALF;
@@ -2829,10 +3276,13 @@ function weierstrass(curveDef) {
2829
3276
  */
2830
3277
  class Signature {
2831
3278
  constructor(r, s, recovery) {
3279
+ aInRange('r', r, _1n$2, CURVE_ORDER); // r in [1..N]
3280
+ aInRange('s', s, _1n$2, CURVE_ORDER); // s in [1..N]
2832
3281
  this.r = r;
2833
3282
  this.s = s;
2834
- this.recovery = recovery;
2835
- this.assertValidity();
3283
+ if (recovery != null)
3284
+ this.recovery = recovery;
3285
+ Object.freeze(this);
2836
3286
  }
2837
3287
  // pair (bytes of r, bytes of s)
2838
3288
  static fromCompact(hex) {
@@ -2846,10 +3296,11 @@ function weierstrass(curveDef) {
2846
3296
  const { r, s } = DER.toSig(ensureBytes('DER', hex));
2847
3297
  return new Signature(r, s);
2848
3298
  }
2849
- assertValidity() {
2850
- aInRange('r', this.r, _1n$2, CURVE_ORDER); // r in [1..N]
2851
- aInRange('s', this.s, _1n$2, CURVE_ORDER); // s in [1..N]
2852
- }
3299
+ /**
3300
+ * @todo remove
3301
+ * @deprecated
3302
+ */
3303
+ assertValidity() { }
2853
3304
  addRecoveryBit(recovery) {
2854
3305
  return new Signature(this.r, this.s, recovery);
2855
3306
  }
@@ -2862,7 +3313,7 @@ function weierstrass(curveDef) {
2862
3313
  if (radj >= Fp.ORDER)
2863
3314
  throw new Error('recovery id 2 or 3 invalid');
2864
3315
  const prefix = (rec & 1) === 0 ? '02' : '03';
2865
- const R = Point.fromHex(prefix + numToNByteStr(radj));
3316
+ const R = Point.fromHex(prefix + numToNByteHex(radj));
2866
3317
  const ir = invN(radj); // r^-1
2867
3318
  const u1 = modN(-h * ir); // -hr^-1
2868
3319
  const u2 = modN(s * ir); // sr^-1
@@ -2881,17 +3332,17 @@ function weierstrass(curveDef) {
2881
3332
  }
2882
3333
  // DER-encoded
2883
3334
  toDERRawBytes() {
2884
- return hexToBytes(this.toDERHex());
3335
+ return hexToBytes$1(this.toDERHex());
2885
3336
  }
2886
3337
  toDERHex() {
2887
- return DER.hexFromSig({ r: this.r, s: this.s });
3338
+ return DER.hexFromSig(this);
2888
3339
  }
2889
3340
  // padded bytes of r, then padded bytes of s
2890
3341
  toCompactRawBytes() {
2891
- return hexToBytes(this.toCompactHex());
3342
+ return hexToBytes$1(this.toCompactHex());
2892
3343
  }
2893
3344
  toCompactHex() {
2894
- return numToNByteStr(this.r) + numToNByteStr(this.s);
3345
+ return numToNByteHex(this.r) + numToNByteHex(this.s);
2895
3346
  }
2896
3347
  }
2897
3348
  const utils = {
@@ -2975,6 +3426,9 @@ function weierstrass(curveDef) {
2975
3426
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
2976
3427
  const bits2int = CURVE.bits2int ||
2977
3428
  function (bytes) {
3429
+ // Our custom check "just in case"
3430
+ if (bytes.length > 8192)
3431
+ throw new Error('input is too large');
2978
3432
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
2979
3433
  // for some cases, since bytes.length * 8 is not actual bitLength.
2980
3434
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -2991,15 +3445,15 @@ function weierstrass(curveDef) {
2991
3445
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
2992
3446
  */
2993
3447
  function int2octets(num) {
2994
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$1, ORDER_MASK);
3448
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n$1, ORDER_MASK);
2995
3449
  // works with order, can have different size than numToField!
2996
3450
  return numberToBytesBE(num, CURVE.nByteLength);
2997
3451
  }
2998
3452
  // Steps A, D of RFC6979 3.2
2999
3453
  // Creates RFC6979 seed; converts msg/privKey to numbers.
3000
3454
  // Used only in sign, not in verify.
3001
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
3002
- // Also it can be bigger for P224 + SHA256
3455
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
3456
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
3003
3457
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
3004
3458
  if (['recovered', 'canonical'].some((k) => k in opts))
3005
3459
  throw new Error('sign() legacy options not supported');
@@ -3093,39 +3547,48 @@ function weierstrass(curveDef) {
3093
3547
  const sg = signature;
3094
3548
  msgHash = ensureBytes('msgHash', msgHash);
3095
3549
  publicKey = ensureBytes('publicKey', publicKey);
3550
+ const { lowS, prehash, format } = opts;
3551
+ // Verify opts, deduce signature format
3552
+ validateSigVerOpts(opts);
3096
3553
  if ('strict' in opts)
3097
3554
  throw new Error('options.strict was renamed to lowS');
3098
- validateSigVerOpts(opts);
3099
- const { lowS, prehash } = opts;
3555
+ if (format !== undefined && format !== 'compact' && format !== 'der')
3556
+ throw new Error('format must be compact or der');
3557
+ const isHex = typeof sg === 'string' || isBytes$1(sg);
3558
+ const isObj = !isHex &&
3559
+ !format &&
3560
+ typeof sg === 'object' &&
3561
+ sg !== null &&
3562
+ typeof sg.r === 'bigint' &&
3563
+ typeof sg.s === 'bigint';
3564
+ if (!isHex && !isObj)
3565
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
3100
3566
  let _sig = undefined;
3101
3567
  let P;
3102
3568
  try {
3103
- if (typeof sg === 'string' || isBytes$1(sg)) {
3569
+ if (isObj)
3570
+ _sig = new Signature(sg.r, sg.s);
3571
+ if (isHex) {
3104
3572
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
3105
3573
  // Since DER can also be 2*nByteLength bytes, we check for it first.
3106
3574
  try {
3107
- _sig = Signature.fromDER(sg);
3575
+ if (format !== 'compact')
3576
+ _sig = Signature.fromDER(sg);
3108
3577
  }
3109
3578
  catch (derError) {
3110
3579
  if (!(derError instanceof DER.Err))
3111
3580
  throw derError;
3112
- _sig = Signature.fromCompact(sg);
3113
3581
  }
3114
- }
3115
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
3116
- const { r, s } = sg;
3117
- _sig = new Signature(r, s);
3118
- }
3119
- else {
3120
- throw new Error('PARSE');
3582
+ if (!_sig && format !== 'der')
3583
+ _sig = Signature.fromCompact(sg);
3121
3584
  }
3122
3585
  P = Point.fromHex(publicKey);
3123
3586
  }
3124
3587
  catch (error) {
3125
- if (error.message === 'PARSE')
3126
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
3127
3588
  return false;
3128
3589
  }
3590
+ if (!_sig)
3591
+ return false;
3129
3592
  if (lowS && _sig.hasHighS())
3130
3593
  return false;
3131
3594
  if (prehash)
@@ -3153,8 +3616,12 @@ function weierstrass(curveDef) {
3153
3616
  };
3154
3617
  }
3155
3618
 
3619
+ /**
3620
+ * Utilities for short weierstrass curves, combined with noble-hashes.
3621
+ * @module
3622
+ */
3156
3623
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3157
- // connects noble-curves to noble-hashes
3624
+ /** connects noble-curves to noble-hashes */
3158
3625
  function getHash(hash) {
3159
3626
  return {
3160
3627
  hash,
@@ -3164,9 +3631,21 @@ function getHash(hash) {
3164
3631
  }
3165
3632
  function createCurve(curveDef, defHash) {
3166
3633
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
3167
- return Object.freeze({ ...create(defHash), create });
3634
+ return { ...create(defHash), create };
3168
3635
  }
3169
3636
 
3637
+ /**
3638
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
3639
+ *
3640
+ * Seems to be rigid (not backdoored)
3641
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
3642
+ *
3643
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3644
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3645
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3646
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
3647
+ * @module
3648
+ */
3170
3649
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3171
3650
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
3172
3651
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -3197,145 +3676,103 @@ function sqrtMod(y) {
3197
3676
  const t1 = (pow2(b223, _23n, P) * b22) % P;
3198
3677
  const t2 = (pow2(t1, _6n, P) * b2) % P;
3199
3678
  const root = pow2(t2, _2n$1, P);
3200
- if (!Fp.eql(Fp.sqr(root), y))
3679
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3201
3680
  throw new Error('Cannot find square root');
3202
3681
  return root;
3203
3682
  }
3204
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3683
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3205
3684
  /**
3206
- * secp256k1 short weierstrass curve and ECDSA signatures over it.
3685
+ * secp256k1 curve, ECDSA and ECDH methods.
3686
+ *
3687
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
3688
+ *
3689
+ * @example
3690
+ * ```js
3691
+ * import { secp256k1 } from '@noble/curves/secp256k1';
3692
+ * const priv = secp256k1.utils.randomPrivateKey();
3693
+ * const pub = secp256k1.getPublicKey(priv);
3694
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
3695
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
3696
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
3697
+ * ```
3207
3698
  */
3208
3699
  const secp256k1 = createCurve({
3209
- a: BigInt(0), // equation params: a, b
3210
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
3211
- Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
3212
- n: secp256k1N, // Curve order, total count of valid points in the field
3213
- // Base point (x, y) aka generator point
3700
+ a: BigInt(0),
3701
+ b: BigInt(7),
3702
+ Fp: Fpk1,
3703
+ n: secp256k1N,
3214
3704
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
3215
3705
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
3216
- h: BigInt(1), // Cofactor
3706
+ h: BigInt(1),
3217
3707
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
3218
- /**
3219
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3220
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3221
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3222
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
3223
- */
3224
3708
  endo: {
3709
+ // Endomorphism, see above
3225
3710
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
3226
3711
  splitScalar: (k) => {
3227
- const n = secp256k1N;
3228
- const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
3229
- const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
3230
- const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
3231
- const b2 = a1;
3232
- const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
3233
- const c1 = divNearest(b2 * k, n);
3234
- const c2 = divNearest(-b1 * k, n);
3235
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
3236
- let k2 = mod(-c1 * b1 - c2 * b2, n);
3237
- const k1neg = k1 > POW_2_128;
3238
- const k2neg = k2 > POW_2_128;
3239
- if (k1neg)
3240
- k1 = n - k1;
3241
- if (k2neg)
3242
- k2 = n - k2;
3243
- if (k1 > POW_2_128 || k2 > POW_2_128) {
3244
- throw new Error('splitScalar: Endomorphism failed, k=' + k);
3245
- }
3246
- return { k1neg, k1, k2neg, k2 };
3247
- },
3248
- },
3249
- }, sha256);
3250
- // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3251
- // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3252
- BigInt(0);
3253
- secp256k1.ProjectivePoint;
3254
-
3255
- /**
3256
- * Generate publicKey from the privateKey.
3257
- * This creates the uncompressed publicKey,
3258
- * where 04 has stripped from left
3259
- * @returns {string}
3260
- */
3261
- const publicKeyByPrivateKey = (privateKey) => {
3262
- const key = stripHexPrefix(privateKey);
3263
- const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
3264
- const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
3265
- return decompress(bytesToHex$1(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
3266
- };
3267
-
3268
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
3269
- const _32n = /* @__PURE__ */ BigInt(32);
3270
- // We are not using BigUint64Array, because they are extremely slow as per 2022
3271
- function fromBig(n, le = false) {
3272
- if (le)
3273
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
3274
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
3275
- }
3276
- function split(lst, le = false) {
3277
- let Ah = new Uint32Array(lst.length);
3278
- let Al = new Uint32Array(lst.length);
3279
- for (let i = 0; i < lst.length; i++) {
3280
- const { h, l } = fromBig(lst[i], le);
3281
- [Ah[i], Al[i]] = [h, l];
3282
- }
3283
- return [Ah, Al];
3284
- }
3285
- const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
3286
- // for Shift in [0, 32)
3287
- const shrSH = (h, _l, s) => h >>> s;
3288
- const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
3289
- // Right rotate for Shift in [1, 32)
3290
- const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
3291
- const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
3292
- // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
3293
- const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
3294
- const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
3295
- // Right rotate for shift===32 (just swaps l&h)
3296
- const rotr32H = (_h, l) => l;
3297
- const rotr32L = (h, _l) => h;
3298
- // Left rotate for Shift in [1, 32)
3299
- const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
3300
- const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
3301
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
3302
- const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
3303
- const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
3304
- // JS uses 32-bit signed integers for bitwise operations which means we cannot
3305
- // simple take carry out of low bit sum by shift, we need to use division.
3306
- function add(Ah, Al, Bh, Bl) {
3307
- const l = (Al >>> 0) + (Bl >>> 0);
3308
- return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
3309
- }
3310
- // Addition with more than 2 elements
3311
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
3312
- const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
3313
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
3314
- const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
3315
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
3316
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
3317
- // prettier-ignore
3318
- const u64 = {
3319
- fromBig, split, toBig,
3320
- shrSH, shrSL,
3321
- rotrSH, rotrSL, rotrBH, rotrBL,
3322
- rotr32H, rotr32L,
3323
- rotlSH, rotlSL, rotlBH, rotlBL,
3324
- add, add3L, add3H, add4L, add4H, add5H, add5L,
3712
+ const n = secp256k1N;
3713
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
3714
+ const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
3715
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
3716
+ const b2 = a1;
3717
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
3718
+ const c1 = divNearest(b2 * k, n);
3719
+ const c2 = divNearest(-b1 * k, n);
3720
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
3721
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
3722
+ const k1neg = k1 > POW_2_128;
3723
+ const k2neg = k2 > POW_2_128;
3724
+ if (k1neg)
3725
+ k1 = n - k1;
3726
+ if (k2neg)
3727
+ k2 = n - k2;
3728
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
3729
+ throw new Error('splitScalar: Endomorphism failed, k=' + k);
3730
+ }
3731
+ return { k1neg, k1, k2neg, k2 };
3732
+ },
3733
+ },
3734
+ }, sha256);
3735
+ // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3736
+ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3737
+ BigInt(0);
3738
+ secp256k1.ProjectivePoint;
3739
+
3740
+ /**
3741
+ * Generate publicKey from the privateKey.
3742
+ * This creates the uncompressed publicKey,
3743
+ * where 04 has stripped from left
3744
+ * @returns {string}
3745
+ */
3746
+ const publicKeyByPrivateKey = (privateKey) => {
3747
+ const key = stripHexPrefix(privateKey);
3748
+ const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
3749
+ const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
3750
+ return decompress(bytesToHex$1(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
3325
3751
  };
3326
3752
 
3327
- // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
3328
- // It's called a sponge function.
3753
+ /**
3754
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
3755
+ * Different from older hashes, the internal state is bigger than output size.
3756
+ *
3757
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
3758
+ * [Website](https://keccak.team/keccak.html),
3759
+ * [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).
3760
+ *
3761
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
3762
+ * @module
3763
+ */
3764
+ // No __PURE__ annotations in sha3 header:
3765
+ // EVERYTHING is in fact used on every export.
3329
3766
  // Various per round constants calculations
3767
+ const _0n = BigInt(0);
3768
+ const _1n = BigInt(1);
3769
+ const _2n = BigInt(2);
3770
+ const _7n = BigInt(7);
3771
+ const _256n = BigInt(256);
3772
+ const _0x71n = BigInt(0x71);
3330
3773
  const SHA3_PI = [];
3331
3774
  const SHA3_ROTL = [];
3332
3775
  const _SHA3_IOTA = [];
3333
- const _0n = /* @__PURE__ */ BigInt(0);
3334
- const _1n = /* @__PURE__ */ BigInt(1);
3335
- const _2n = /* @__PURE__ */ BigInt(2);
3336
- const _7n = /* @__PURE__ */ BigInt(7);
3337
- const _256n = /* @__PURE__ */ BigInt(256);
3338
- const _0x71n = /* @__PURE__ */ BigInt(0x71);
3339
3776
  for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
3340
3777
  // Pi
3341
3778
  [x, y] = [y, (2 * x + 3 * y) % 5];
@@ -3351,11 +3788,13 @@ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
3351
3788
  }
3352
3789
  _SHA3_IOTA.push(t);
3353
3790
  }
3354
- const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);
3791
+ const IOTAS = split(_SHA3_IOTA, true);
3792
+ const SHA3_IOTA_H = IOTAS[0];
3793
+ const SHA3_IOTA_L = IOTAS[1];
3355
3794
  // Left rotation (without 0, 32, 64)
3356
3795
  const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
3357
3796
  const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
3358
- // Same as keccakf1600, but allows to skip some rounds
3797
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
3359
3798
  function keccakP(s, rounds = 24) {
3360
3799
  const B = new Uint32Array(5 * 2);
3361
3800
  // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
@@ -3399,42 +3838,47 @@ function keccakP(s, rounds = 24) {
3399
3838
  s[0] ^= SHA3_IOTA_H[round];
3400
3839
  s[1] ^= SHA3_IOTA_L[round];
3401
3840
  }
3402
- B.fill(0);
3841
+ clean$1(B);
3403
3842
  }
3843
+ /** Keccak sponge function. */
3404
3844
  class Keccak extends Hash {
3405
3845
  // NOTE: we accept arguments in bytes instead of bits here.
3406
3846
  constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
3407
3847
  super();
3848
+ this.pos = 0;
3849
+ this.posOut = 0;
3850
+ this.finished = false;
3851
+ this.destroyed = false;
3852
+ this.enableXOF = false;
3408
3853
  this.blockLen = blockLen;
3409
3854
  this.suffix = suffix;
3410
3855
  this.outputLen = outputLen;
3411
3856
  this.enableXOF = enableXOF;
3412
3857
  this.rounds = rounds;
3413
- this.pos = 0;
3414
- this.posOut = 0;
3415
- this.finished = false;
3416
- this.destroyed = false;
3417
3858
  // Can be passed from user as dkLen
3418
- number(outputLen);
3859
+ anumber(outputLen);
3419
3860
  // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
3420
- if (0 >= this.blockLen || this.blockLen >= 200)
3421
- throw new Error('Sha3 supports only keccak-f1600 function');
3861
+ // 0 < blockLen < 200
3862
+ if (!(0 < blockLen && blockLen < 200))
3863
+ throw new Error('only keccak-f1600 function is supported');
3422
3864
  this.state = new Uint8Array(200);
3423
3865
  this.state32 = u32$1(this.state);
3424
3866
  }
3867
+ clone() {
3868
+ return this._cloneInto();
3869
+ }
3425
3870
  keccak() {
3426
- if (!isLE$1)
3427
- byteSwap32(this.state32);
3871
+ swap32IfBE(this.state32);
3428
3872
  keccakP(this.state32, this.rounds);
3429
- if (!isLE$1)
3430
- byteSwap32(this.state32);
3873
+ swap32IfBE(this.state32);
3431
3874
  this.posOut = 0;
3432
3875
  this.pos = 0;
3433
3876
  }
3434
3877
  update(data) {
3435
- exists(this);
3436
- const { blockLen, state } = this;
3878
+ aexists(this);
3437
3879
  data = toBytes(data);
3880
+ abytes$3(data);
3881
+ const { blockLen, state } = this;
3438
3882
  const len = data.length;
3439
3883
  for (let pos = 0; pos < len;) {
3440
3884
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -3458,8 +3902,8 @@ class Keccak extends Hash {
3458
3902
  this.keccak();
3459
3903
  }
3460
3904
  writeInto(out) {
3461
- exists(this, false);
3462
- bytes$1(out);
3905
+ aexists(this, false);
3906
+ abytes$3(out);
3463
3907
  this.finish();
3464
3908
  const bufferOut = this.state;
3465
3909
  const { blockLen } = this;
@@ -3480,11 +3924,11 @@ class Keccak extends Hash {
3480
3924
  return this.writeInto(out);
3481
3925
  }
3482
3926
  xof(bytes) {
3483
- number(bytes);
3927
+ anumber(bytes);
3484
3928
  return this.xofInto(new Uint8Array(bytes));
3485
3929
  }
3486
3930
  digestInto(out) {
3487
- output$1(out, this);
3931
+ aoutput(out, this);
3488
3932
  if (this.finished)
3489
3933
  throw new Error('digest() was already called');
3490
3934
  this.writeInto(out);
@@ -3496,7 +3940,7 @@ class Keccak extends Hash {
3496
3940
  }
3497
3941
  destroy() {
3498
3942
  this.destroyed = true;
3499
- this.state.fill(0);
3943
+ clean$1(this.state);
3500
3944
  }
3501
3945
  _cloneInto(to) {
3502
3946
  const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
@@ -3514,12 +3958,9 @@ class Keccak extends Hash {
3514
3958
  return to;
3515
3959
  }
3516
3960
  }
3517
- const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));
3518
- /**
3519
- * keccak-256 hash function. Different from SHA3-256.
3520
- * @param message - that would be hashed
3521
- */
3522
- const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);
3961
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
3962
+ /** keccak-256 hash function. Different from SHA3-256. */
3963
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
3523
3964
 
3524
3965
  const keccak256$1 = (() => {
3525
3966
  const k = wrapHash(keccak_256);
@@ -3572,162 +4013,6 @@ const createIdentity = (entropy) => {
3572
4013
  return identity;
3573
4014
  };
3574
4015
 
3575
- // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
3576
- // prettier-ignore
3577
- const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
3578
- '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
3579
- '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
3580
- '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
3581
- '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
3582
- '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
3583
- '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
3584
- '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
3585
- '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
3586
- '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
3587
- '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
3588
- '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
3589
- '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
3590
- '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
3591
- '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
3592
- '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
3593
- '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
3594
- '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
3595
- '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
3596
- '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
3597
- '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
3598
- ].map(n => BigInt(n))))();
3599
- // Temporary buffer, not used to store anything between runs
3600
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
3601
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
3602
- class SHA512 extends HashMD {
3603
- constructor() {
3604
- super(128, 64, 16, false);
3605
- // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
3606
- // Also looks cleaner and easier to verify with spec.
3607
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
3608
- // h -- high 32 bits, l -- low 32 bits
3609
- this.Ah = 0x6a09e667 | 0;
3610
- this.Al = 0xf3bcc908 | 0;
3611
- this.Bh = 0xbb67ae85 | 0;
3612
- this.Bl = 0x84caa73b | 0;
3613
- this.Ch = 0x3c6ef372 | 0;
3614
- this.Cl = 0xfe94f82b | 0;
3615
- this.Dh = 0xa54ff53a | 0;
3616
- this.Dl = 0x5f1d36f1 | 0;
3617
- this.Eh = 0x510e527f | 0;
3618
- this.El = 0xade682d1 | 0;
3619
- this.Fh = 0x9b05688c | 0;
3620
- this.Fl = 0x2b3e6c1f | 0;
3621
- this.Gh = 0x1f83d9ab | 0;
3622
- this.Gl = 0xfb41bd6b | 0;
3623
- this.Hh = 0x5be0cd19 | 0;
3624
- this.Hl = 0x137e2179 | 0;
3625
- }
3626
- // prettier-ignore
3627
- get() {
3628
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3629
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
3630
- }
3631
- // prettier-ignore
3632
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
3633
- this.Ah = Ah | 0;
3634
- this.Al = Al | 0;
3635
- this.Bh = Bh | 0;
3636
- this.Bl = Bl | 0;
3637
- this.Ch = Ch | 0;
3638
- this.Cl = Cl | 0;
3639
- this.Dh = Dh | 0;
3640
- this.Dl = Dl | 0;
3641
- this.Eh = Eh | 0;
3642
- this.El = El | 0;
3643
- this.Fh = Fh | 0;
3644
- this.Fl = Fl | 0;
3645
- this.Gh = Gh | 0;
3646
- this.Gl = Gl | 0;
3647
- this.Hh = Hh | 0;
3648
- this.Hl = Hl | 0;
3649
- }
3650
- process(view, offset) {
3651
- // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
3652
- for (let i = 0; i < 16; i++, offset += 4) {
3653
- SHA512_W_H[i] = view.getUint32(offset);
3654
- SHA512_W_L[i] = view.getUint32((offset += 4));
3655
- }
3656
- for (let i = 16; i < 80; i++) {
3657
- // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
3658
- const W15h = SHA512_W_H[i - 15] | 0;
3659
- const W15l = SHA512_W_L[i - 15] | 0;
3660
- const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
3661
- const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
3662
- // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
3663
- const W2h = SHA512_W_H[i - 2] | 0;
3664
- const W2l = SHA512_W_L[i - 2] | 0;
3665
- const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
3666
- const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
3667
- // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
3668
- const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
3669
- const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
3670
- SHA512_W_H[i] = SUMh | 0;
3671
- SHA512_W_L[i] = SUMl | 0;
3672
- }
3673
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3674
- // Compression function main loop, 80 rounds
3675
- for (let i = 0; i < 80; i++) {
3676
- // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
3677
- const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
3678
- const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
3679
- //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3680
- const CHIh = (Eh & Fh) ^ (~Eh & Gh);
3681
- const CHIl = (El & Fl) ^ (~El & Gl);
3682
- // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
3683
- // prettier-ignore
3684
- const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
3685
- const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
3686
- const T1l = T1ll | 0;
3687
- // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
3688
- const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
3689
- const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
3690
- const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
3691
- const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
3692
- Hh = Gh | 0;
3693
- Hl = Gl | 0;
3694
- Gh = Fh | 0;
3695
- Gl = Fl | 0;
3696
- Fh = Eh | 0;
3697
- Fl = El | 0;
3698
- ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
3699
- Dh = Ch | 0;
3700
- Dl = Cl | 0;
3701
- Ch = Bh | 0;
3702
- Cl = Bl | 0;
3703
- Bh = Ah | 0;
3704
- Bl = Al | 0;
3705
- const All = u64.add3L(T1l, sigma0l, MAJl);
3706
- Ah = u64.add3H(All, T1h, sigma0h, MAJh);
3707
- Al = All | 0;
3708
- }
3709
- // Add the compressed chunk to the current hash value
3710
- ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
3711
- ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
3712
- ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
3713
- ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
3714
- ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
3715
- ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
3716
- ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
3717
- ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
3718
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
3719
- }
3720
- roundClean() {
3721
- SHA512_W_H.fill(0);
3722
- SHA512_W_L.fill(0);
3723
- }
3724
- destroy() {
3725
- this.buffer.fill(0);
3726
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
3727
- }
3728
- }
3729
- const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
3730
-
3731
4016
  /**
3732
4017
  * signs the given message
3733
4018
  * @param {string} privateKey
@@ -3738,7 +4023,7 @@ const sign = (privateKey, hash) => {
3738
4023
  const hashWith0x = addLeading0x(hash);
3739
4024
  if (hashWith0x.length !== 66 || !isHexString(hashWith0x))
3740
4025
  throw new Error('Can only sign hashes, given: ' + hash);
3741
- const sigObj = secp256k1.sign(hexToBytes$1(stripHexPrefix(hash)), hexToBytes$1(stripHexPrefix(privateKey)));
4026
+ const sigObj = secp256k1.sign(hexToBytes(stripHexPrefix(hash)), hexToBytes(stripHexPrefix(privateKey)));
3742
4027
  const recoveryId = sigObj.recovery === 1 ? '1c' : '1b';
3743
4028
  const newSignature = '0x' + sigObj.toCompactHex() + recoveryId;
3744
4029
  return newSignature;
@@ -3750,33 +4035,129 @@ const hmacSha256Sign = (key, msg) => {
3750
4035
 
3751
4036
  const sha512 = wrapHash(sha512$1);
3752
4037
 
4038
+ /**
4039
+ * Utilities for hex, bytes, CSPRNG.
4040
+ * @module
4041
+ */
4042
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
4043
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
3753
4044
  function isBytes(a) {
3754
- return (a instanceof Uint8Array ||
3755
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
4045
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3756
4046
  }
3757
- function bytes(b, ...lengths) {
4047
+ /** Asserts something is Uint8Array. */
4048
+ function abytes(b, ...lengths) {
3758
4049
  if (!isBytes(b))
3759
4050
  throw new Error('Uint8Array expected');
3760
4051
  if (lengths.length > 0 && !lengths.includes(b.length))
3761
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
4052
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3762
4053
  }
3763
-
3764
- /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3765
- // Cast array to different type
3766
- const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3767
- const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3768
- // big-endian hardware is rare. Just in case someone still decides to run ciphers:
3769
- // early-throw an error because we don't support BE yet.
3770
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3771
- if (!isLE)
3772
- throw new Error('Non little-endian hardware is not supported');
4054
+ /** Cast u8 / u16 / u32 to u8. */
4055
+ function u8(arr) {
4056
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
4057
+ }
4058
+ /** Cast u8 / u16 / u32 to u32. */
4059
+ function u32(arr) {
4060
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
4061
+ }
4062
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
4063
+ function clean(...arrays) {
4064
+ for (let i = 0; i < arrays.length; i++) {
4065
+ arrays[i].fill(0);
4066
+ }
4067
+ }
4068
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
4069
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
3773
4070
  /**
4071
+ * Checks if two U8A use same underlying buffer and overlaps.
4072
+ * This is invalid and can corrupt data.
4073
+ */
4074
+ function overlapBytes(a, b) {
4075
+ return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
4076
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
4077
+ b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
4078
+ );
4079
+ }
4080
+ /**
4081
+ * If input and output overlap and input starts before output, we will overwrite end of input before
4082
+ * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
4083
+ */
4084
+ function complexOverlapBytes(input, output) {
4085
+ // This is very cursed. It works somehow, but I'm completely unsure,
4086
+ // reasoning about overlapping aligned windows is very hard.
4087
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
4088
+ throw new Error('complex overlap of input and output is not supported');
4089
+ }
4090
+ /**
4091
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
3774
4092
  * @__NO_SIDE_EFFECTS__
3775
4093
  */
3776
- const wrapCipher = (params, c) => {
3777
- Object.assign(c, params);
3778
- return c;
4094
+ const wrapCipher = (params, constructor) => {
4095
+ function wrappedCipher(key, ...args) {
4096
+ // Validate key
4097
+ abytes(key);
4098
+ // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
4099
+ if (!isLE)
4100
+ throw new Error('Non little-endian hardware is not yet supported');
4101
+ // Validate nonce if nonceLength is present
4102
+ if (params.nonceLength !== undefined) {
4103
+ const nonce = args[0];
4104
+ if (!nonce)
4105
+ throw new Error('nonce / iv required');
4106
+ if (params.varSizeNonce)
4107
+ abytes(nonce);
4108
+ else
4109
+ abytes(nonce, params.nonceLength);
4110
+ }
4111
+ // Validate AAD if tagLength present
4112
+ const tagl = params.tagLength;
4113
+ if (tagl && args[1] !== undefined) {
4114
+ abytes(args[1]);
4115
+ }
4116
+ const cipher = constructor(key, ...args);
4117
+ const checkOutput = (fnLength, output) => {
4118
+ if (output !== undefined) {
4119
+ if (fnLength !== 2)
4120
+ throw new Error('cipher output not supported');
4121
+ abytes(output);
4122
+ }
4123
+ };
4124
+ // Create wrapped cipher with validation and single-use encryption
4125
+ let called = false;
4126
+ const wrCipher = {
4127
+ encrypt(data, output) {
4128
+ if (called)
4129
+ throw new Error('cannot encrypt() twice with same key + nonce');
4130
+ called = true;
4131
+ abytes(data);
4132
+ checkOutput(cipher.encrypt.length, output);
4133
+ return cipher.encrypt(data, output);
4134
+ },
4135
+ decrypt(data, output) {
4136
+ abytes(data);
4137
+ if (tagl && data.length < tagl)
4138
+ throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
4139
+ checkOutput(cipher.decrypt.length, output);
4140
+ return cipher.decrypt(data, output);
4141
+ },
4142
+ };
4143
+ return wrCipher;
4144
+ }
4145
+ Object.assign(wrappedCipher, params);
4146
+ return wrappedCipher;
3779
4147
  };
4148
+ /**
4149
+ * By default, returns u8a of length.
4150
+ * When out is available, it checks it for validity and uses it.
4151
+ */
4152
+ function getOutput(expectedLength, out, onlyAligned = true) {
4153
+ if (out === undefined)
4154
+ return new Uint8Array(expectedLength);
4155
+ if (out.length !== expectedLength)
4156
+ throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
4157
+ if (onlyAligned && !isAligned32(out))
4158
+ throw new Error('invalid output, must be aligned');
4159
+ return out;
4160
+ }
3780
4161
  // Is byte array aligned to 4 byte offset (u32)?
3781
4162
  function isAligned32(bytes) {
3782
4163
  return bytes.byteOffset % 4 === 0;
@@ -3785,26 +4166,23 @@ function isAligned32(bytes) {
3785
4166
  function copyBytes(bytes) {
3786
4167
  return Uint8Array.from(bytes);
3787
4168
  }
3788
- function clean(...arrays) {
3789
- for (let i = 0; i < arrays.length; i++) {
3790
- arrays[i].fill(0);
3791
- }
3792
- }
3793
-
3794
- // prettier-ignore
3795
- /*
3796
- AES (Advanced Encryption Standard) aka Rijndael block cipher.
3797
4169
 
3798
- Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
3799
- 1. **S-box**, table substitution
3800
- 2. **Shift rows**, cyclic shift left of all rows of data array
3801
- 3. **Mix columns**, multiplying every column by fixed polynomial
3802
- 4. **Add round key**, round_key xor i-th column of array
3803
-
3804
- Resources:
3805
- - FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf
3806
- - Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf
3807
- */
4170
+ /**
4171
+ * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
4172
+ * a.k.a. Advanced Encryption Standard
4173
+ * is a variant of Rijndael block cipher, standardized by NIST in 2001.
4174
+ * We provide the fastest available pure JS implementation.
4175
+ *
4176
+ * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
4177
+ * 1. **S-box**, table substitution
4178
+ * 2. **Shift rows**, cyclic shift left of all rows of data array
4179
+ * 3. **Mix columns**, multiplying every column by fixed polynomial
4180
+ * 4. **Add round key**, round_key xor i-th column of array
4181
+ *
4182
+ * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
4183
+ * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
4184
+ * @module
4185
+ */
3808
4186
  const BLOCK_SIZE = 16;
3809
4187
  const BLOCK_SIZE32 = 4;
3810
4188
  const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
@@ -3874,11 +4252,12 @@ const xPowers = /* @__PURE__ */ (() => {
3874
4252
  p[i] = x;
3875
4253
  return p;
3876
4254
  })();
4255
+ /** Key expansion used in CTR. */
3877
4256
  function expandKeyLE(key) {
3878
- bytes(key);
4257
+ abytes(key);
3879
4258
  const len = key.length;
3880
4259
  if (![16, 24, 32].includes(len))
3881
- throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);
4260
+ throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
3882
4261
  const { sbox2 } = tableEncoding;
3883
4262
  const toClean = [];
3884
4263
  if (!isAligned32(key))
@@ -3968,22 +4347,13 @@ function decrypt$2(xk, s0, s1, s2, s3) {
3968
4347
  const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
3969
4348
  return { s0: t0, s1: t1, s2: t2, s3: t3 };
3970
4349
  }
3971
- function getDst(len, dst) {
3972
- if (dst === undefined)
3973
- return new Uint8Array(len);
3974
- bytes(dst);
3975
- if (dst.length < len)
3976
- throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);
3977
- if (!isAligned32(dst))
3978
- throw new Error('unaligned dst');
3979
- return dst;
3980
- }
3981
4350
  // TODO: investigate merging with ctr32
3982
4351
  function ctrCounter(xk, nonce, src, dst) {
3983
- bytes(nonce, BLOCK_SIZE);
3984
- bytes(src);
4352
+ abytes(nonce, BLOCK_SIZE);
4353
+ abytes(src);
3985
4354
  const srcLen = src.length;
3986
- dst = getDst(srcLen, dst);
4355
+ dst = getOutput(srcLen, dst);
4356
+ complexOverlapBytes(src, dst);
3987
4357
  const ctr = nonce;
3988
4358
  const c32 = u32(ctr);
3989
4359
  // Fill block (empty, ctr=0)
@@ -4021,13 +4391,11 @@ function ctrCounter(xk, nonce, src, dst) {
4021
4391
  * CTR: counter mode. Creates stream cipher.
4022
4392
  * Requires good IV. Parallelizable. OK, but no MAC.
4023
4393
  */
4024
- const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {
4025
- bytes(key);
4026
- bytes(nonce, BLOCK_SIZE);
4394
+ const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
4027
4395
  function processCtr(buf, dst) {
4028
- bytes(buf);
4396
+ abytes(buf);
4029
4397
  if (dst !== undefined) {
4030
- bytes(dst);
4398
+ abytes(dst);
4031
4399
  if (!isAligned32(dst))
4032
4400
  throw new Error('unaligned destination');
4033
4401
  }
@@ -4046,13 +4414,13 @@ const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, non
4046
4414
  };
4047
4415
  });
4048
4416
  function validateBlockDecrypt(data) {
4049
- bytes(data);
4417
+ abytes(data);
4050
4418
  if (data.length % BLOCK_SIZE !== 0) {
4051
- throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);
4419
+ throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
4052
4420
  }
4053
4421
  }
4054
4422
  function validateBlockEncrypt(plaintext, pcks5, dst) {
4055
- bytes(plaintext);
4423
+ abytes(plaintext);
4056
4424
  let outLen = plaintext.length;
4057
4425
  const remaining = outLen % BLOCK_SIZE;
4058
4426
  if (!pcks5 && remaining !== 0)
@@ -4066,9 +4434,10 @@ function validateBlockEncrypt(plaintext, pcks5, dst) {
4066
4434
  left = BLOCK_SIZE; // if no bytes left, create empty padding block
4067
4435
  outLen = outLen + left;
4068
4436
  }
4069
- const out = getDst(outLen, dst);
4070
- const o = u32(out);
4071
- return { b, o, out };
4437
+ dst = getOutput(outLen, dst);
4438
+ complexOverlapBytes(plaintext, dst);
4439
+ const o = u32(dst);
4440
+ return { b, o, out: dst };
4072
4441
  }
4073
4442
  function validatePCKS(data, pcks5) {
4074
4443
  if (!pcks5)
@@ -4098,9 +4467,7 @@ function padPCKS(left) {
4098
4467
  * CBC: Cipher-Block-Chaining. Key is previous round’s block.
4099
4468
  * Fragile: needs proper padding. Unauthenticated: needs MAC.
4100
4469
  */
4101
- const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {
4102
- bytes(key);
4103
- bytes(iv, 16);
4470
+ const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
4104
4471
  const pcks5 = !opts.disablePadding;
4105
4472
  return {
4106
4473
  encrypt(plaintext, dst) {
@@ -4136,11 +4503,12 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
4136
4503
  if (!isAligned32(_iv))
4137
4504
  toClean.push((_iv = copyBytes(_iv)));
4138
4505
  const n32 = u32(_iv);
4139
- const out = getDst(ciphertext.length, dst);
4506
+ dst = getOutput(ciphertext.length, dst);
4140
4507
  if (!isAligned32(ciphertext))
4141
4508
  toClean.push((ciphertext = copyBytes(ciphertext)));
4509
+ complexOverlapBytes(ciphertext, dst);
4142
4510
  const b = u32(ciphertext);
4143
- const o = u32(out);
4511
+ const o = u32(dst);
4144
4512
  // prettier-ignore
4145
4513
  let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4146
4514
  for (let i = 0; i + 4 <= b.length;) {
@@ -4151,18 +4519,18 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
4151
4519
  (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
4152
4520
  }
4153
4521
  clean(...toClean);
4154
- return validatePCKS(out, pcks5);
4522
+ return validatePCKS(dst, pcks5);
4155
4523
  },
4156
4524
  };
4157
4525
  });
4158
- new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
4159
4526
 
4160
4527
  function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
4161
4528
  if (!mode.startsWith("aes-")) {
4162
4529
  throw new Error("AES: unsupported mode");
4163
4530
  }
4164
4531
  const len = key.length;
4165
- if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) {
4532
+ if ((mode.startsWith("aes-128") && len !== 16) ||
4533
+ (mode.startsWith("aes-256") && len !== 32)) {
4166
4534
  throw new Error("AES: wrong key length");
4167
4535
  }
4168
4536
  if (iv.length !== 16) {
@@ -4193,12 +4561,12 @@ function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnable
4193
4561
  * @returns {Encrypted} The encrypted message.
4194
4562
  */
4195
4563
  const encrypt = (publicKeyTo, msg, options) => {
4196
- const ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes$1(options.ephemPrivateKey) : getRandomBytesSync(32);
4564
+ const ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes(options.ephemPrivateKey) : getRandomBytesSync(32);
4197
4565
  const iv = getRandomBytesSync(16);
4198
4566
  const compressedPub = secp256k1.getPublicKey(ephemPrivateKey); // defaults to compressed format
4199
4567
  const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
4200
4568
  const ephemPublicKey = point.toRawBytes(false); // Get uncompressed SEC1 format pub
4201
- const sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes$1(publicKeyTo), true).slice(1);
4569
+ const sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes(publicKeyTo), true).slice(1);
4202
4570
  const hash = sha512(sharedSecret);
4203
4571
  const encryptionKey = hash.subarray(0, 32);
4204
4572
  const macKey = hash.subarray(32);
@@ -4222,7 +4590,7 @@ const encrypt = (publicKeyTo, msg, options) => {
4222
4590
  const decrypt = (privateKey, opts) => {
4223
4591
  let sharedSecret;
4224
4592
  try {
4225
- sharedSecret = secp256k1.getSharedSecret(hexToBytes$1(privateKey), opts.ephemPublicKey, true).slice(1);
4593
+ sharedSecret = secp256k1.getSharedSecret(hexToBytes(privateKey), opts.ephemPublicKey, true).slice(1);
4226
4594
  }
4227
4595
  catch (e) {
4228
4596
  throw new Error(`Invalid MAC: data integrity check failed: ${e}`);
@@ -4230,10 +4598,10 @@ const decrypt = (privateKey, opts) => {
4230
4598
  const hash = sha512(sharedSecret);
4231
4599
  const encryptionKey = hash.subarray(0, 32);
4232
4600
  const macKey = hash.subarray(32);
4233
- const ciphertext = hexToBytes$1(opts.ciphertext);
4234
- const iv = hexToBytes$1(opts.iv);
4235
- const ephemPublicKey = hexToBytes$1(opts.ephemPublicKey);
4236
- const receivedMac = hexToBytes$1(opts.mac);
4601
+ const ciphertext = hexToBytes(opts.ciphertext);
4602
+ const iv = hexToBytes(opts.iv);
4603
+ const ephemPublicKey = hexToBytes(opts.ephemPublicKey);
4604
+ const receivedMac = hexToBytes(opts.mac);
4237
4605
  // Recompute MAC
4238
4606
  const dataToMac = concatUint8Arrays([iv, ephemPublicKey, ciphertext]);
4239
4607
  const expectedMac = hmacSha256Sign(macKey, dataToMac);
@@ -4276,7 +4644,7 @@ const decryptWithPrivateKey = (privateKey, encrypted) => {
4276
4644
  const solidityPackedKeccak256 = (value) => {
4277
4645
  const bytes = utf8ToBytes(value);
4278
4646
  const hex = addLeading0x(bytesToHex$1(bytes));
4279
- const hash = keccak256$1(hexToBytes$1(hex));
4647
+ const hash = keccak256$1(hexToBytes(hex));
4280
4648
  return addLeading0x(bytesToHex$1(hash));
4281
4649
  };
4282
4650
  const keccak256 = (params) => {
@@ -4291,19 +4659,19 @@ function output(out = (len) => new Uint8Array(len), length, value) {
4291
4659
  if (typeof out === "function") {
4292
4660
  out = out(length);
4293
4661
  }
4294
- assertBytes(out, length);
4662
+ abytes$1(out, length);
4295
4663
  if (value) {
4296
4664
  out.set(value);
4297
4665
  }
4298
4666
  return out;
4299
4667
  }
4300
4668
  function getSignature(signature) {
4301
- assertBytes(signature, 64);
4669
+ abytes$1(signature, 64);
4302
4670
  return secp256k1.Signature.fromCompact(signature);
4303
4671
  }
4304
4672
  function ecdsaRecover(signature, recid, msgHash, compressed = true, out) {
4305
- assertBytes(msgHash, 32);
4306
- assertBool(compressed);
4673
+ abytes$1(msgHash, 32);
4674
+ abool("compressed", compressed);
4307
4675
  const sign = getSignature(signature);
4308
4676
  const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash);
4309
4677
  return output(out, compressed ? 33 : 65, point.toRawBytes(compressed));
@@ -4321,7 +4689,7 @@ const recoverPublicKey = (signature, hash) => {
4321
4689
  const sigOnly = noHex.substring(0, noHex.length - 2); // all but last 2 chars
4322
4690
  const vValue = noHex.slice(-2); // last 2 chars
4323
4691
  const recoveryNumber = vValue === '1c' ? 1 : 0;
4324
- let pubKey = bytesToHex$1(ecdsaRecover(hexToBytes$1(sigOnly), recoveryNumber, hexToBytes$1(stripHexPrefix(hash)), false));
4692
+ let pubKey = bytesToHex$1(ecdsaRecover(hexToBytes(sigOnly), recoveryNumber, hexToBytes(stripHexPrefix(hash)), false));
4325
4693
  // remove trailing '04'
4326
4694
  pubKey = pubKey.slice(2);
4327
4695
  return pubKey;
@@ -4350,18 +4718,22 @@ function isJsonString(str) {
4350
4718
  }
4351
4719
  }
4352
4720
 
4721
+ /**
4722
+ * PBKDF (RFC 2898). Can be used to create a key from password and salt.
4723
+ * @module
4724
+ */
4353
4725
  // Common prologue and epilogue for sync/async functions
4354
4726
  function pbkdf2Init(hash, _password, _salt, _opts) {
4355
- hash$1(hash);
4727
+ ahash(hash);
4356
4728
  const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
4357
4729
  const { c, dkLen, asyncTick } = opts;
4358
- number(c);
4359
- number(dkLen);
4360
- number(asyncTick);
4730
+ anumber(c);
4731
+ anumber(dkLen);
4732
+ anumber(asyncTick);
4361
4733
  if (c < 1)
4362
- throw new Error('PBKDF2: iterations (c) should be >= 1');
4363
- const password = toBytes(_password);
4364
- const salt = toBytes(_salt);
4734
+ throw new Error('iterations (c) should be >= 1');
4735
+ const password = kdfInputToBytes(_password);
4736
+ const salt = kdfInputToBytes(_salt);
4365
4737
  // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
4366
4738
  const DK = new Uint8Array(dkLen);
4367
4739
  // U1 = PRF(Password, Salt + INT_32_BE(i))
@@ -4374,7 +4746,7 @@ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
4374
4746
  PRFSalt.destroy();
4375
4747
  if (prfW)
4376
4748
  prfW.destroy();
4377
- u.fill(0);
4749
+ clean$1(u);
4378
4750
  return DK;
4379
4751
  }
4380
4752
  /**
@@ -4383,6 +4755,8 @@ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
4383
4755
  * @param password - password from which a derived key is generated
4384
4756
  * @param salt - cryptographic salt
4385
4757
  * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
4758
+ * @example
4759
+ * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
4386
4760
  */
4387
4761
  function pbkdf2(hash, password, salt, opts) {
4388
4762
  const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
@@ -4413,8 +4787,8 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4413
4787
  if (!["sha256", "sha512"].includes(digest)) {
4414
4788
  throw new Error("Only sha256 and sha512 are supported");
4415
4789
  }
4416
- assertBytes(password);
4417
- assertBytes(salt);
4790
+ abytes$1(password);
4791
+ abytes$1(salt);
4418
4792
  return pbkdf2(sha256 , password, salt, {
4419
4793
  c: iterations,
4420
4794
  dkLen: keylen
@@ -5434,11 +5808,11 @@ class StorageService {
5434
5808
  * @param jwt - The JWT string to check. If null, the function will return true.
5435
5809
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5436
5810
  */
5437
- function jwtHasExpired(jwt) {
5811
+ function jwtHasExpired(jwt, now = Date.now) {
5438
5812
  if (!jwt) {
5439
5813
  return true;
5440
5814
  }
5441
- return millisecondsToJWTTimeout(jwt) <= 0;
5815
+ return millisecondsToJWTTimeout(jwt, now) <= 0;
5442
5816
  }
5443
5817
  function jwtHasSameUser(jwt, userId) {
5444
5818
  if (!jwt || !userId) {
@@ -5458,11 +5832,11 @@ function userIsMfaVerified(jwt) {
5458
5832
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5459
5833
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5460
5834
  */
5461
- function isJwtNearExpiry(jwt, thresholdSeconds) {
5835
+ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5462
5836
  if (!jwt) {
5463
5837
  return false;
5464
5838
  }
5465
- return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5839
+ return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5466
5840
  }
5467
5841
  /**
5468
5842
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5470,11 +5844,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds) {
5470
5844
  * @param jwt - The JWT string to decode and check.
5471
5845
  * @returns The number of milliseconds until the JWT expires. If the JWT has already expired, the returned value will be less than or equal to 0.
5472
5846
  */
5473
- function millisecondsToJWTTimeout(jwt) {
5847
+ function millisecondsToJWTTimeout(jwt, now = Date.now) {
5474
5848
  const jwtDecoded = jwtDecode.jwtDecode(jwt);
5475
5849
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5476
5850
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5477
- const timeNowMilliseconds = Date.now();
5851
+ const timeNowMilliseconds = now();
5478
5852
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5479
5853
  }
5480
5854
 
@@ -7141,8 +7515,8 @@ const refreshDedupeManager = new DedupeManagerService();
7141
7515
  // actually contend. Global lock keys (no per-user scoping); add scoping only if multiple users share one process.
7142
7516
  const sharedLockManager = new LockManagerService();
7143
7517
  class Base {
7144
- constructor(config) {
7145
- var _a, _b;
7518
+ constructor(config, ports = {}) {
7519
+ var _a, _b, _c, _d, _e;
7146
7520
  const sanitizedConfig = sanitizeConfig(config);
7147
7521
  this.apiKey = sanitizedConfig.apiKey;
7148
7522
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -7153,7 +7527,9 @@ class Base {
7153
7527
  env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
7154
7528
  env.isWeb = !env.isNative;
7155
7529
  }
7156
- this.cipher = new Cipher();
7530
+ this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
7531
+ this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
7532
+ this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
7157
7533
  this.lockManager = sharedLockManager;
7158
7534
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
7159
7535
  this.request = this.request.bind(this);
@@ -7167,6 +7543,7 @@ class Base {
7167
7543
  secure: true, // Enable security worker for all requests by default
7168
7544
  },
7169
7545
  securityWorker: this.securityWorker.bind(this),
7546
+ customFetch: this.transport,
7170
7547
  });
7171
7548
  /**
7172
7549
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -7179,39 +7556,48 @@ class Base {
7179
7556
  return await originalRequest(params);
7180
7557
  }
7181
7558
  catch (error) {
7182
- // Reactive 401 handling for the generated client: refresh once and retry
7559
+ // Reactive 401 handling for the generated client: refresh once and retry.
7560
+ // The retry recurses and surfaces its own final error, so the intermediate
7561
+ // 401 must not be routed through toWallabyError (would double-fire onError).
7183
7562
  if (!retried && shouldAttemptTokenRefresh(error)) {
7184
7563
  await this._performTokenRefresh();
7185
7564
  // securityWorker will re-fetch the new access token on retry
7186
7565
  return attemptRequest(true);
7187
7566
  }
7188
- // Transform the generated API error format into WallabyError
7567
+ // Transform the generated API error format into WallabyError.
7568
+ // `error.error` is the parsed response body (no statusCode); the HTTP
7569
+ // status lives on the HttpResponse itself (`error.status`).
7189
7570
  if (error === null || error === void 0 ? void 0 : error.error) {
7190
7571
  const apiError = error.error;
7191
- throw new WallabyError({
7572
+ throw this.toWallabyError({
7192
7573
  message: apiError.message || 'API request failed',
7193
- statusCode: apiError.statusCode || 500,
7574
+ statusCode: apiError.statusCode || error.status || 500,
7194
7575
  errorCode: apiError.errorCode,
7195
7576
  data: apiError,
7196
7577
  });
7197
7578
  }
7198
- // Re-throw if already a WallabyError
7579
+ // Already a WallabyError (e.g. a pre-send guard from securityWorker) — propagate as-is.
7199
7580
  if (error instanceof WallabyError) {
7200
7581
  throw error;
7201
7582
  }
7202
- // Wrap any other errors
7203
- throw new WallabyError({
7204
- message: error.message || 'Unknown error occurred',
7205
- statusCode: error.statusCode || 500,
7206
- errorCode: error.errorCode,
7207
- data: error,
7583
+ // No HTTP response reached us: treat as a network failure, mirroring the
7584
+ // custom request() path so both transports surface the same shape.
7585
+ throw this.toWallabyError({
7586
+ message: error.message || 'Network request failed',
7587
+ statusCode: 0,
7588
+ errorCode: 'NETWORK_ERROR',
7589
+ data: {
7590
+ code: error.code || error.name,
7591
+ originalError: error,
7592
+ },
7593
+ cause: error.cause,
7208
7594
  });
7209
7595
  }
7210
7596
  };
7211
7597
  return attemptRequest(false);
7212
7598
  };
7213
7599
  this.api = new Api(httpClient);
7214
- this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_b = this.options) === null || _b === void 0 ? void 0 : _b.headers));
7600
+ this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_e = this.options) === null || _e === void 0 ? void 0 : _e.headers));
7215
7601
  }
7216
7602
  set setClientAuthToken(token) {
7217
7603
  this._initializeClientAuthToken(token);
@@ -7297,17 +7683,16 @@ class Base {
7297
7683
  * All concurrent callers share the same in-flight promise via the module-level
7298
7684
  * `refreshDedupeManager` so only one network request is issued per user/environment scope.
7299
7685
  */
7300
- async _performTokenRefresh() {
7686
+ async _performTokenRefresh(opts) {
7301
7687
  const refreshDedupeKey = `refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;
7302
7688
  await refreshDedupeManager.withDedupe(refreshDedupeKey, async () => {
7689
+ var _a;
7303
7690
  const refreshToken = await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);
7304
7691
  if (!refreshToken) {
7305
7692
  return;
7306
7693
  }
7307
7694
  try {
7308
- const response = await this.request(AuthRoutes.refreshAccessToken, {
7309
- payload: { refreshToken },
7310
- });
7695
+ const response = await this.request(AuthRoutes.refreshAccessToken, { payload: { refreshToken } }, false, (_a = opts === null || opts === void 0 ? void 0 : opts.silent) !== null && _a !== void 0 ? _a : false);
7311
7696
  await this.localStorageService.save(exports.LocalStorageItems.AccessToken, response.accessToken);
7312
7697
  await this.localStorageService.save(exports.LocalStorageItems.RefreshToken, response.refreshToken);
7313
7698
  }
@@ -7320,20 +7705,48 @@ class Base {
7320
7705
  }
7321
7706
  });
7322
7707
  }
7708
+ /**
7709
+ * Single chokepoint for surfacing transport failures. Every WallabyError raised
7710
+ * by a transport path is built here so `options.onError` fires exactly once per
7711
+ * logical failure. Retry paths must decide to retry BEFORE calling this so a
7712
+ * retried request does not double-fire.
7713
+ */
7714
+ toWallabyError(payload) {
7715
+ var _a, _b;
7716
+ const error = new WallabyError(payload);
7717
+ try {
7718
+ (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
7719
+ }
7720
+ catch (onErrorException) {
7721
+ // A throwing consumer callback must not replace the WallabyError being surfaced.
7722
+ logger.error('SDK::Base::toWallabyError::onError handler threw', { error: onErrorException });
7723
+ }
7724
+ return error;
7725
+ }
7323
7726
  /**
7324
7727
  * Main request method for making API calls to the Wallaby API.
7325
7728
  * @param route - Route configuration object containing the endpoint path and HTTP method
7326
7729
  * @param options - Optional request options including payload and query parameters
7327
7730
  * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
7731
+ * @param silent - Internal flag; when true the resulting WallabyError does NOT fire
7732
+ * `options.onError`. Used for best-effort refreshes whose failure is
7733
+ * swallowed by the caller (e.g. proactive refresh in securityWorker),
7734
+ * so an internal request never surfaces a consumer-facing error.
7328
7735
  * @returns Promise resolving to the typed response data
7329
7736
  * @throws Error if the API returns an error response or network failure occurs
7330
7737
  */
7331
- async request(route, options, retried = false) {
7738
+ async request(route, options, retried = false, silent = false) {
7332
7739
  var _a;
7740
+ // `silent` suppresses onError for swallowed internal refreshes. Note: refresh
7741
+ // requests dedupe by user/env/network, so under concurrent mixed-path refreshes
7742
+ // the winning call's `silent` value applies to all sharers — a narrow edge that
7743
+ // does not affect the retry no-double-fire guarantee. A fully race-free fix would
7744
+ // require idempotent (per-error) firing.
7745
+ const emitError = (payload) => silent ? new WallabyError(payload) : this.toWallabyError(payload);
7333
7746
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7334
7747
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7335
7748
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7336
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7749
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7337
7750
  await this._performTokenRefresh();
7338
7751
  }
7339
7752
  }
@@ -7357,7 +7770,7 @@ class Base {
7357
7770
  fetchOptions.body = JSON.stringify(options.payload);
7358
7771
  }
7359
7772
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7360
- const response = await fetch(fullUrl, fetchOptions);
7773
+ const response = await this.transport(fullUrl, fetchOptions);
7361
7774
  const contentType = response.headers.get('content-type');
7362
7775
  let data;
7363
7776
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7380,7 +7793,16 @@ class Base {
7380
7793
  });
7381
7794
  // Handle error responses (status >= 400)
7382
7795
  if (!response.ok) {
7383
- throw new WallabyError({
7796
+ // Reactive token refresh: on a refreshable 401, refresh once and retry the
7797
+ // original request. Decided here (before constructing the WallabyError) so the
7798
+ // retried attempt surfaces the single onError; the intermediate 401 never fires.
7799
+ if (!retried &&
7800
+ route !== AuthRoutes.refreshAccessToken &&
7801
+ shouldAttemptTokenRefresh({ status: response.status, errorCode: data === null || data === void 0 ? void 0 : data.errorCode })) {
7802
+ await this._performTokenRefresh();
7803
+ return this.request(route, options, true);
7804
+ }
7805
+ throw emitError({
7384
7806
  message: (data === null || data === void 0 ? void 0 : data.message) || response.statusText || 'Request failed',
7385
7807
  statusCode: response.status,
7386
7808
  errorCode: data === null || data === void 0 ? void 0 : data.errorCode,
@@ -7390,36 +7812,33 @@ class Base {
7390
7812
  return data;
7391
7813
  }
7392
7814
  catch (error) {
7393
- // Reactive token refresh: on 401, refresh once and retry the original request
7394
- if (!retried && route !== AuthRoutes.refreshAccessToken && shouldAttemptTokenRefresh(error)) {
7395
- await this._performTokenRefresh();
7396
- return this.request(route, options, true);
7815
+ // Already surfaced through toWallabyError (the !response.ok branch above), or a
7816
+ // pre-send guard error from before the fetch — propagate without re-firing onError.
7817
+ if (error instanceof WallabyError) {
7818
+ throw error;
7397
7819
  }
7398
7820
  if (error === null || error === void 0 ? void 0 : error.error) {
7399
7821
  logger.error('SDK::Base::handleApiCall::API Error', { error });
7400
7822
  const apiError = error.error;
7401
- throw new WallabyError({
7823
+ throw emitError({
7402
7824
  message: apiError.message || 'API request failed',
7403
7825
  statusCode: apiError.statusCode || 500,
7404
7826
  errorCode: apiError.errorCode,
7405
7827
  data: apiError,
7406
7828
  });
7407
7829
  }
7408
- if (error instanceof WallabyError) {
7409
- throw error;
7410
- }
7411
7830
  // Handle network errors, fetch failures, etc.
7412
7831
  logger.error(`SDK::Base::${route.method}::NetworkError`, {
7413
7832
  message: error.message,
7414
7833
  name: error.name,
7415
7834
  error,
7416
7835
  });
7417
- throw new WallabyError({
7836
+ throw emitError({
7418
7837
  message: error.message || 'Network request failed',
7419
7838
  statusCode: 0,
7420
7839
  errorCode: 'NETWORK_ERROR',
7421
7840
  data: {
7422
- code: error.name,
7841
+ code: error.code || error.name,
7423
7842
  originalError: error,
7424
7843
  },
7425
7844
  cause: error.cause,
@@ -7428,7 +7847,7 @@ class Base {
7428
7847
  }
7429
7848
  async _getRequestHeaders() {
7430
7849
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7431
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7850
+ if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7432
7851
  throw new WallabyError({
7433
7852
  message: 'Auth token has expired',
7434
7853
  statusCode: 401,
@@ -7447,11 +7866,13 @@ class Base {
7447
7866
  return headers;
7448
7867
  }
7449
7868
  async securityWorker(securityData) {
7450
- // Proactive token refresh before building headers for the generated client
7869
+ // Proactive token refresh before building headers for the generated client.
7870
+ // Best-effort and swallowed below, so it must NOT surface onError — otherwise a
7871
+ // failed internal refresh would fire even when the actual request later succeeds.
7451
7872
  try {
7452
7873
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7453
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7454
- await this._performTokenRefresh();
7874
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7875
+ await this._performTokenRefresh({ silent: true });
7455
7876
  }
7456
7877
  }
7457
7878
  catch (_a) {
@@ -7831,8 +8252,8 @@ function decodeBase64URL(base64url) {
7831
8252
  }
7832
8253
 
7833
8254
  class PasskeyService {
7834
- constructor(userId, storageService, request) {
7835
- this.cipher = new Cipher();
8255
+ constructor(userId, storageService, request, cipher = new Cipher()) {
8256
+ this.cipher = cipher;
7836
8257
  this.localStorageService = storageService;
7837
8258
  this.userId = userId;
7838
8259
  this.request = request;
@@ -8362,10 +8783,10 @@ function WithLock(lockKey) {
8362
8783
  }
8363
8784
 
8364
8785
  class AuthService extends Base {
8365
- constructor(config) {
8366
- super(config);
8786
+ constructor(config, ports = {}) {
8787
+ super(config, ports);
8367
8788
  this.getUserSalt = this.getUserSalt.bind(this);
8368
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8789
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8369
8790
  }
8370
8791
  /**
8371
8792
  * @description
@@ -8604,6 +9025,18 @@ class AuthService extends Base {
8604
9025
  throw error;
8605
9026
  }
8606
9027
  }
9028
+ /**
9029
+ * @private
9030
+ * @description Whether this device already has a stored `ClientAuthPublicKey`, which is written
9031
+ * atomically alongside the device private key in every provisioning path. Its presence is proof
9032
+ * the device was already provisioned: if it exists while the private key reads as missing we are
9033
+ * looking at a partial read-miss / corruption — creating a new identity would orphan shares still
9034
+ * wrapped to the old key. A device with no stored public key is instead treated as genuinely fresh.
9035
+ * @returns {Promise<boolean>} true when a device public key is stored and a missing key means data loss.
9036
+ */
9037
+ async hasStoredDevicePublicKey() {
9038
+ return !!(await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey));
9039
+ }
8607
9040
  /**
8608
9041
  *
8609
9042
  * @private
@@ -8651,8 +9084,19 @@ class AuthService extends Base {
8651
9084
  decryptedClientAuthPrivKey = await this.localStorageService.getDecryptedV1PrivateKey(input.password);
8652
9085
  }
8653
9086
  }
9087
+ else if (await this.hasStoredDevicePublicKey()) {
9088
+ // Private key reads as missing but the paired public key is still here: this is a partial
9089
+ // read-miss, not a fresh device. Fabricating a new identity would orphan wallet shares still
9090
+ // wrapped to the old key, so fail hard instead.
9091
+ logger.error('SDK::AuthService::handleSignInWithPassword::error', 'Device key missing but wallet data exists');
9092
+ throw new WallabyError({
9093
+ message: 'Device key could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.',
9094
+ statusCode: 500,
9095
+ errorCode: exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data,
9096
+ });
9097
+ }
8654
9098
  else {
8655
- logger.info('Device private key could not be retrieved, creating a new key pair');
9099
+ logger.info('No device data found, treating as a fresh device and creating a new key pair');
8656
9100
  const newIdentity = createIdentity();
8657
9101
  decryptedClientAuthPrivKey = newIdentity.privateKey;
8658
9102
  }
@@ -8690,13 +9134,26 @@ class AuthService extends Base {
8690
9134
  try {
8691
9135
  const passkeyCredential = await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential);
8692
9136
  const encryptedDevicePrivateKey = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);
8693
- let devicePublicKey = await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey);
9137
+ const devicePublicKey = await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey);
8694
9138
  let deviceKeyPair;
8695
9139
  // This logic needs to change and depend on data from server.
8696
9140
  if (!passkeyCredential) {
9141
+ // Passkey credential reads as missing but the device already holds a key pair: this is a
9142
+ // partial read-miss, not a fresh device. Registering a new passkey/identity would orphan
9143
+ // wallet shares still wrapped to the existing key, so fail hard instead.
9144
+ if (devicePublicKey || encryptedDevicePrivateKey) {
9145
+ logger.error('SDK::AuthService::handleSignInWithPasskey::error', 'Passkey credential missing but device data exists');
9146
+ throw new WallabyError({
9147
+ message: 'Passkey credential could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.',
9148
+ statusCode: 500,
9149
+ errorCode: exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data,
9150
+ });
9151
+ }
8697
9152
  deviceKeyPair = createIdentity();
8698
- devicePublicKey = deviceKeyPair.publicKey;
8699
- await this.localStorageService.save(exports.LocalStorageItems.ClientAuthPublicKey, devicePublicKey);
9153
+ // Don't persist ClientAuthPublicKey ahead of registration: addNewPasskey() writes it
9154
+ // atomically with the encrypted private key and passkey credential on success. Writing it
9155
+ // early would leave an orphaned public key if registration fails, which the guard above
9156
+ // would then misread as a partial read-miss and permanently brick this fresh device.
8700
9157
  authentication = await this.passkeyService.addNewPasskey({
8701
9158
  deviceKeyPair,
8702
9159
  getSignature: this.getSignature.bind(this),
@@ -8938,9 +9395,9 @@ function assertBackupSharePayloadShape(encrypted) {
8938
9395
  }
8939
9396
  }
8940
9397
  class WalletHandlersService extends Base {
8941
- constructor(config) {
8942
- super(config);
8943
- this.authService = new AuthService(config);
9398
+ constructor(config, ports = {}) {
9399
+ super(config, ports);
9400
+ this.authService = new AuthService(config, ports);
8944
9401
  this.userId = config.userId;
8945
9402
  }
8946
9403
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -9245,13 +9702,51 @@ class WalletHandlersService extends Base {
9245
9702
  }
9246
9703
  }
9247
9704
 
9705
+ const SEED_LENGTH_BYTES = 32;
9706
+ const CHECKSUM_BYTES = 2;
9707
+ /** Pack bytes into 11-bit groups, least-significant bits first (Algorand's encoding). */
9708
+ function toUint11Array(bytes) {
9709
+ const out = [];
9710
+ let acc = 0;
9711
+ let accBits = 0;
9712
+ for (const byte of bytes) {
9713
+ acc |= byte << accBits;
9714
+ accBits += 8;
9715
+ if (accBits >= 11) {
9716
+ out.push(acc & 0x7ff);
9717
+ acc >>>= 11;
9718
+ accBits -= 11;
9719
+ }
9720
+ }
9721
+ if (accBits > 0)
9722
+ out.push(acc & 0x7ff);
9723
+ return out;
9724
+ }
9725
+ /**
9726
+ * Convert a 32-byte seed to Algorand's fixed 25-word mnemonic: 24 data words
9727
+ * (256 bits packed into 11-bit BIP39-English word indices) plus a checksum word
9728
+ * derived from the first two bytes of the seed's SHA-512/256 hash.
9729
+ *
9730
+ * Word-for-word compatible with algosdk's `mnemonicFromSeed`; parity is
9731
+ * verified against algosdk (devDependency) in `algorand-mnemonic.spec.ts`.
9732
+ */
9733
+ function algorandMnemonicFromSeed(seed) {
9734
+ if (seed.length !== SEED_LENGTH_BYTES) {
9735
+ throw new Error(`Algorand seed must be ${SEED_LENGTH_BYTES} bytes, got ${seed.length}`);
9736
+ }
9737
+ const english = bip39.wordlists.english;
9738
+ const words = toUint11Array(seed).map((index) => english[index]);
9739
+ const checksumIndex = toUint11Array(sha512_256(seed).subarray(0, CHECKSUM_BYTES))[0];
9740
+ return [...words, english[checksumIndex]].join(' ');
9741
+ }
9742
+
9248
9743
  class WalletService extends Base {
9249
- constructor(config) {
9250
- super(config);
9251
- this.authService = new AuthService(config);
9252
- this.handlers = new WalletHandlersService(config);
9744
+ constructor(config, ports = {}) {
9745
+ super(config, ports);
9746
+ this.authService = new AuthService(config, ports);
9747
+ this.handlers = new WalletHandlersService(config, ports);
9253
9748
  this.userId = config.userId;
9254
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9749
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9255
9750
  }
9256
9751
  /**
9257
9752
  * Reads the persisted sliding-window rate-limit state for a counter key.
@@ -9855,7 +10350,7 @@ class WalletService extends Base {
9855
10350
  try {
9856
10351
  const seedBuffer = bip39__namespace.mnemonicToSeedSync(bip39Mnemonic);
9857
10352
  const seed = seedBuffer.slice(0, 32);
9858
- const convertedSeedPhrase = algosdk__namespace.mnemonicFromSeed(seed);
10353
+ const convertedSeedPhrase = algorandMnemonicFromSeed(seed);
9859
10354
  return convertedSeedPhrase;
9860
10355
  }
9861
10356
  catch (error) {
@@ -10783,10 +11278,10 @@ __decorate([
10783
11278
  ], WalletService.prototype, "convertToPasskey", null);
10784
11279
 
10785
11280
  class WalletDataService extends Base {
10786
- constructor(config) {
10787
- super(config);
11281
+ constructor(config, ports = {}) {
11282
+ super(config, ports);
10788
11283
  this.userId = config.userId;
10789
- this.walletService = new WalletService(config);
11284
+ this.walletService = new WalletService(config, ports);
10790
11285
  }
10791
11286
  /**
10792
11287
  * @description Validates the wallet address info for a given blockchain.
@@ -11107,8 +11602,8 @@ class WalletDataService extends Base {
11107
11602
  }
11108
11603
 
11109
11604
  class Utils extends Base {
11110
- constructor(config) {
11111
- super(config);
11605
+ constructor(config, ports = {}) {
11606
+ super(config, ports);
11112
11607
  /**
11113
11608
  *
11114
11609
  * Decrypts user private key
@@ -11141,7 +11636,7 @@ class Utils extends Base {
11141
11636
  return undefined;
11142
11637
  }
11143
11638
  };
11144
- this.auth = new AuthService(config);
11639
+ this.auth = new AuthService(config, ports);
11145
11640
  }
11146
11641
  /**
11147
11642
  *
@@ -11248,16 +11743,16 @@ class HttpApi extends Base {
11248
11743
  * @param config - The Wallaby configuration object
11249
11744
  * @public
11250
11745
  */
11251
- constructor(config) {
11252
- super(config);
11746
+ constructor(config, ports = {}) {
11747
+ super(config, ports);
11253
11748
  }
11254
11749
  }
11255
11750
 
11256
11751
  class Swap extends Base {
11257
- constructor(config) {
11258
- super(config);
11259
- this.authService = new AuthService(config);
11260
- this.walletService = new WalletService(config);
11752
+ constructor(config, ports = {}) {
11753
+ super(config, ports);
11754
+ this.authService = new AuthService(config, ports);
11755
+ this.walletService = new WalletService(config, ports);
11261
11756
  }
11262
11757
  /**
11263
11758
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11531,8 +12026,8 @@ const extractSuiAssetSymbol = (objectId) => {
11531
12026
  };
11532
12027
 
11533
12028
  class System extends Base {
11534
- constructor(config) {
11535
- super(config);
12029
+ constructor(config, ports = {}) {
12030
+ super(config, ports);
11536
12031
  }
11537
12032
  /**
11538
12033
  * @public
@@ -11729,10 +12224,10 @@ class System extends Base {
11729
12224
  }
11730
12225
 
11731
12226
  class Transactions extends Base {
11732
- constructor(config) {
11733
- super(config);
11734
- this.authService = new AuthService(config);
11735
- this.walletService = new WalletService(config);
12227
+ constructor(config, ports = {}) {
12228
+ super(config, ports);
12229
+ this.authService = new AuthService(config, ports);
12230
+ this.walletService = new WalletService(config, ports);
11736
12231
  this.userId = config.userId;
11737
12232
  }
11738
12233
  /**
@@ -12173,15 +12668,15 @@ class Wallaby {
12173
12668
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
12174
12669
  * @public
12175
12670
  */
12176
- constructor(config) {
12177
- this.wallet = new WalletService(config);
12178
- this.walletData = new WalletDataService(config);
12179
- this.utils = new Utils(config);
12180
- this.auth = new AuthService(config);
12181
- this.system = new System(config);
12182
- this.transactions = new Transactions(config);
12183
- this.swap = new Swap(config);
12184
- this.httpApi = new HttpApi(config);
12671
+ constructor(config, ports = {}) {
12672
+ this.wallet = new WalletService(config, ports);
12673
+ this.walletData = new WalletDataService(config, ports);
12674
+ this.utils = new Utils(config, ports);
12675
+ this.auth = new AuthService(config, ports);
12676
+ this.system = new System(config, ports);
12677
+ this.transactions = new Transactions(config, ports);
12678
+ this.swap = new Swap(config, ports);
12679
+ this.httpApi = new HttpApi(config, ports);
12185
12680
  }
12186
12681
  get version() {
12187
12682
  return currentPackageVersion;