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.esm.js CHANGED
@@ -1,5 +1,5 @@
1
- import * as algosdk from 'algosdk';
2
1
  import * as bip39 from 'bip39';
2
+ import { wordlists } from 'bip39';
3
3
  import { v4 } from 'uuid';
4
4
  import log from 'loglevel';
5
5
  import { AES, enc } from 'crypto-js';
@@ -384,6 +384,7 @@ var ErrorResponseCodes;
384
384
  ErrorResponseCodes["sdk_seed_phrase_not_found"] = "sdk_seed_phrase_not_found";
385
385
  ErrorResponseCodes["sdk_private_key_decryption_failed"] = "sdk_private_key_decryption_failed";
386
386
  ErrorResponseCodes["sdk_private_key_not_found"] = "sdk_private_key_not_found";
387
+ ErrorResponseCodes["sdk_device_key_missing_with_existing_data"] = "sdk_device_key_missing_with_existing_data";
387
388
  ErrorResponseCodes["sdk_refresh_token_missing"] = "sdk_refresh_token_missing";
388
389
  ErrorResponseCodes["sdk_missing_parameter"] = "sdk_missing_parameter";
389
390
  ErrorResponseCodes["sdk_invalid_parameter"] = "sdk_invalid_parameter";
@@ -572,7 +573,6 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
572
573
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
573
574
  */
574
575
  const defaultNetwork = 'testnet';
575
- const isTest = browser$1.env.NODE_ENV === 'test';
576
576
  const DEFAULT_ENTROPY_BYTES$1 = 32;
577
577
  const PBKDF2_ITERATIONS = 131072;
578
578
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -598,7 +598,7 @@ const env = {
598
598
  isNative: !isWeb,
599
599
  isWeb,
600
600
  };
601
- const currentPackageVersion = "3.5.2" ;
601
+ const currentPackageVersion = "3.7.0" ;
602
602
 
603
603
  /**
604
604
  * Storage keys adapter for Storage interface across different platforms.
@@ -611,77 +611,107 @@ const normalizeKey = (key) => key.replace(/:/g, '_');
611
611
 
612
612
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
613
613
 
614
- function number(n) {
615
- if (!Number.isSafeInteger(n) || n < 0)
616
- throw new Error(`positive integer expected, not ${n}`);
617
- }
618
- function bool(b) {
619
- if (typeof b !== 'boolean')
620
- throw new Error(`boolean expected, not ${b}`);
621
- }
622
- // copied from utils
614
+ /**
615
+ * Utilities for hex, bytes, CSPRNG.
616
+ * @module
617
+ */
618
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
619
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
620
+ // node.js versions earlier than v19 don't declare it in global scope.
621
+ // For node.js, package.json#exports field mapping rewrites import
622
+ // from `crypto` to `cryptoNode`, which imports native module.
623
+ // Makes the utils un-importable in browsers without a bundler.
624
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
625
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
623
626
  function isBytes$2(a) {
624
- return (a instanceof Uint8Array ||
625
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
627
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
626
628
  }
627
- function bytes$1(b, ...lengths) {
629
+ /** Asserts something is positive integer. */
630
+ function anumber(n) {
631
+ if (!Number.isSafeInteger(n) || n < 0)
632
+ throw new Error('positive integer expected, got ' + n);
633
+ }
634
+ /** Asserts something is Uint8Array. */
635
+ function abytes$3(b, ...lengths) {
628
636
  if (!isBytes$2(b))
629
637
  throw new Error('Uint8Array expected');
630
638
  if (lengths.length > 0 && !lengths.includes(b.length))
631
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
639
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
632
640
  }
633
- function hash$1(h) {
641
+ /** Asserts something is hash */
642
+ function ahash(h) {
634
643
  if (typeof h !== 'function' || typeof h.create !== 'function')
635
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
636
- number(h.outputLen);
637
- number(h.blockLen);
644
+ throw new Error('Hash should be wrapped by utils.createHasher');
645
+ anumber(h.outputLen);
646
+ anumber(h.blockLen);
638
647
  }
639
- function exists(instance, checkFinished = true) {
648
+ /** Asserts a hash instance has not been destroyed / finished */
649
+ function aexists(instance, checkFinished = true) {
640
650
  if (instance.destroyed)
641
651
  throw new Error('Hash instance has been destroyed');
642
652
  if (checkFinished && instance.finished)
643
653
  throw new Error('Hash#digest() has already been called');
644
654
  }
645
- function output$1(out, instance) {
646
- bytes$1(out);
655
+ /** Asserts output is properly-sized byte array */
656
+ function aoutput(out, instance) {
657
+ abytes$3(out);
647
658
  const min = instance.outputLen;
648
659
  if (out.length < min) {
649
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
660
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
650
661
  }
651
662
  }
652
- const assert = { number, bool, bytes: bytes$1, hash: hash$1, exists, output: output$1 };
653
-
654
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
655
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
656
- // node.js versions earlier than v19 don't declare it in global scope.
657
- // For node.js, package.json#exports field mapping rewrites import
658
- // from `crypto` to `cryptoNode`, which imports native module.
659
- // Makes the utils un-importable in browsers without a bundler.
660
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
661
- const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
662
- // Cast array to view
663
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
664
- // The rotate right (circular right shift) operation for uint32
665
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
666
- const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
667
- // The byte swap operation for uint32
668
- const byteSwap = (word) => ((word << 24) & 0xff000000) |
669
- ((word << 8) & 0xff0000) |
670
- ((word >>> 8) & 0xff00) |
671
- ((word >>> 24) & 0xff);
672
- // In place byte swap for Uint32Array
663
+ /** Cast u8 / u16 / u32 to u32. */
664
+ function u32$1(arr) {
665
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
666
+ }
667
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
668
+ function clean$1(...arrays) {
669
+ for (let i = 0; i < arrays.length; i++) {
670
+ arrays[i].fill(0);
671
+ }
672
+ }
673
+ /** Create DataView of an array for easy byte-level manipulation. */
674
+ function createView(arr) {
675
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
676
+ }
677
+ /** The rotate right (circular right shift) operation for uint32 */
678
+ function rotr(word, shift) {
679
+ return (word << (32 - shift)) | (word >>> shift);
680
+ }
681
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
682
+ const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
683
+ /** The byte swap operation for uint32 */
684
+ function byteSwap(word) {
685
+ return (((word << 24) & 0xff000000) |
686
+ ((word << 8) & 0xff0000) |
687
+ ((word >>> 8) & 0xff00) |
688
+ ((word >>> 24) & 0xff));
689
+ }
690
+ /** In place byte swap for Uint32Array */
673
691
  function byteSwap32(arr) {
674
692
  for (let i = 0; i < arr.length; i++) {
675
693
  arr[i] = byteSwap(arr[i]);
676
694
  }
695
+ return arr;
677
696
  }
697
+ const swap32IfBE = isLE$1
698
+ ? (u) => u
699
+ : byteSwap32;
700
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
701
+ const hasHexBuiltin$1 = /* @__PURE__ */ (() =>
702
+ // @ts-ignore
703
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
678
704
  // Array where index 0xf0 (240) is mapped to string 'f0'
679
705
  const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
680
706
  /**
707
+ * Convert byte array to hex string. Uses built-in function, when available.
681
708
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
682
709
  */
683
710
  function bytesToHex$1(bytes) {
684
- bytes$1(bytes);
711
+ abytes$3(bytes);
712
+ // @ts-ignore
713
+ if (hasHexBuiltin$1)
714
+ return bytes.toHex();
685
715
  // pre-caching improves the speed 6x
686
716
  let hex = '';
687
717
  for (let i = 0; i < bytes.length; i++) {
@@ -690,26 +720,30 @@ function bytesToHex$1(bytes) {
690
720
  return hex;
691
721
  }
692
722
  // We use optimized technique to convert hex string to byte array
693
- const asciis$1 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
694
- function asciiToBase16$1(char) {
695
- if (char >= asciis$1._0 && char <= asciis$1._9)
696
- return char - asciis$1._0;
697
- if (char >= asciis$1._A && char <= asciis$1._F)
698
- return char - (asciis$1._A - 10);
699
- if (char >= asciis$1._a && char <= asciis$1._f)
700
- return char - (asciis$1._a - 10);
723
+ const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
724
+ function asciiToBase16$1(ch) {
725
+ if (ch >= asciis$1._0 && ch <= asciis$1._9)
726
+ return ch - asciis$1._0; // '2' => 50-48
727
+ if (ch >= asciis$1.A && ch <= asciis$1.F)
728
+ return ch - (asciis$1.A - 10); // 'B' => 66-(65-10)
729
+ if (ch >= asciis$1.a && ch <= asciis$1.f)
730
+ return ch - (asciis$1.a - 10); // 'b' => 98-(97-10)
701
731
  return;
702
732
  }
703
733
  /**
734
+ * Convert hex string to byte array. Uses built-in function, when available.
704
735
  * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
705
736
  */
706
737
  function hexToBytes$2(hex) {
707
738
  if (typeof hex !== 'string')
708
739
  throw new Error('hex string expected, got ' + typeof hex);
740
+ // @ts-ignore
741
+ if (hasHexBuiltin$1)
742
+ return Uint8Array.fromHex(hex);
709
743
  const hl = hex.length;
710
744
  const al = hl / 2;
711
745
  if (hl % 2)
712
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
746
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
713
747
  const array = new Uint8Array(al);
714
748
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
715
749
  const n1 = asciiToBase16$1(hex.charCodeAt(hi));
@@ -718,16 +752,17 @@ function hexToBytes$2(hex) {
718
752
  const char = hex[hi] + hex[hi + 1];
719
753
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
720
754
  }
721
- array[ai] = n1 * 16 + n2;
755
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
722
756
  }
723
757
  return array;
724
758
  }
725
759
  /**
726
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
760
+ * Converts string to bytes using UTF8 encoding.
761
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
727
762
  */
728
763
  function utf8ToBytes$1(str) {
729
764
  if (typeof str !== 'string')
730
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
765
+ throw new Error('string expected');
731
766
  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
732
767
  }
733
768
  /**
@@ -738,17 +773,25 @@ function utf8ToBytes$1(str) {
738
773
  function toBytes(data) {
739
774
  if (typeof data === 'string')
740
775
  data = utf8ToBytes$1(data);
741
- bytes$1(data);
776
+ abytes$3(data);
742
777
  return data;
743
778
  }
744
779
  /**
745
- * Copies several Uint8Arrays into one.
780
+ * Helper for KDFs: consumes uint8array or string.
781
+ * When string is passed, does utf8 decoding, using TextDecoder.
746
782
  */
783
+ function kdfInputToBytes(data) {
784
+ if (typeof data === 'string')
785
+ data = utf8ToBytes$1(data);
786
+ abytes$3(data);
787
+ return data;
788
+ }
789
+ /** Copies several Uint8Arrays into one. */
747
790
  function concatBytes$1(...arrays) {
748
791
  let sum = 0;
749
792
  for (let i = 0; i < arrays.length; i++) {
750
793
  const a = arrays[i];
751
- bytes$1(a);
794
+ abytes$3(a);
752
795
  sum += a.length;
753
796
  }
754
797
  const res = new Uint8Array(sum);
@@ -759,21 +802,17 @@ function concatBytes$1(...arrays) {
759
802
  }
760
803
  return res;
761
804
  }
762
- // For runtime check if class implements interface
763
- class Hash {
764
- // Safe version that clones internal state
765
- clone() {
766
- return this._cloneInto();
767
- }
768
- }
769
- const toStr = {}.toString;
770
805
  function checkOpts(defaults, opts) {
771
- if (opts !== undefined && toStr.call(opts) !== '[object Object]')
772
- throw new Error('Options should be object or undefined');
806
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
807
+ throw new Error('options should be object or undefined');
773
808
  const merged = Object.assign(defaults, opts);
774
809
  return merged;
775
810
  }
776
- function wrapConstructor(hashCons) {
811
+ /** For runtime check if class implements interface */
812
+ class Hash {
813
+ }
814
+ /** Wraps hash function, creating an interface on top of it */
815
+ function createHasher(hashCons) {
777
816
  const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
778
817
  const tmp = hashCons();
779
818
  hashC.outputLen = tmp.outputLen;
@@ -781,16 +820,14 @@ function wrapConstructor(hashCons) {
781
820
  hashC.create = () => hashCons();
782
821
  return hashC;
783
822
  }
784
- /**
785
- * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
786
- */
823
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
787
824
  function randomBytes(bytesLength = 32) {
788
825
  if (crypto && typeof crypto.getRandomValues === 'function') {
789
826
  return crypto.getRandomValues(new Uint8Array(bytesLength));
790
827
  }
791
828
  // Legacy Node.js compatibility
792
829
  if (crypto && typeof crypto.randomBytes === 'function') {
793
- return crypto.randomBytes(bytesLength);
830
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
794
831
  }
795
832
  throw new Error('crypto.getRandomValues must be defined');
796
833
  }
@@ -799,168 +836,476 @@ function getRandomBytesSync(bytes) {
799
836
  return randomBytes(bytes);
800
837
  }
801
838
 
802
- const assertBool = assert.bool;
803
- const assertBytes = assert.bytes;
804
- // buf.toString('utf8') -> bytesToUtf8(buf)
805
- function bytesToUtf8(data) {
806
- if (!(data instanceof Uint8Array)) {
807
- throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
808
- }
809
- return new TextDecoder().decode(data);
839
+ /**
840
+ * Hex, bytes and number utilities.
841
+ * @module
842
+ */
843
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
844
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
845
+ // This is OK: `abstract` directory does not use noble-hashes.
846
+ // User may opt-in into using different hashing library. This way, noble-hashes
847
+ // won't be included into their bundle.
848
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
849
+ const _1n$5 = /* @__PURE__ */ BigInt(1);
850
+ function isBytes$1(a) {
851
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
810
852
  }
811
- function hexToBytes$1(data) {
812
- const sliced = data.startsWith("0x") ? data.substring(2) : data;
813
- return hexToBytes$2(sliced);
853
+ function abytes$2(item) {
854
+ if (!isBytes$1(item))
855
+ throw new Error('Uint8Array expected');
814
856
  }
815
- // Internal utils
816
- function wrapHash(hash) {
817
- return (msg) => {
818
- assert.bytes(msg);
819
- return hash(msg);
820
- };
857
+ function abool(title, value) {
858
+ if (typeof value !== 'boolean')
859
+ throw new Error(title + ' boolean expected, got ' + value);
821
860
  }
822
-
861
+ // Used in weierstrass, der
862
+ function numberToHexUnpadded(num) {
863
+ const hex = num.toString(16);
864
+ return hex.length & 1 ? '0' + hex : hex;
865
+ }
866
+ function hexToNumber(hex) {
867
+ if (typeof hex !== 'string')
868
+ throw new Error('hex string expected, got ' + typeof hex);
869
+ return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
870
+ }
871
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
872
+ const hasHexBuiltin =
873
+ // @ts-ignore
874
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
875
+ // Array where index 0xf0 (240) is mapped to string 'f0'
876
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
823
877
  /**
824
- * Returns a `Boolean` on whether or not the a `String` starts with '0x'
825
- * @param str the string input value
826
- * @return a boolean if it is or is not hex prefixed
827
- * @throws if the str input is not a string
878
+ * Convert byte array to hex string. Uses built-in function, when available.
879
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
828
880
  */
829
- const isHexPrefixed = (str) => {
830
- if (typeof str !== 'string') {
831
- throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
881
+ function bytesToHex(bytes) {
882
+ abytes$2(bytes);
883
+ // @ts-ignore
884
+ if (hasHexBuiltin)
885
+ return bytes.toHex();
886
+ // pre-caching improves the speed 6x
887
+ let hex = '';
888
+ for (let i = 0; i < bytes.length; i++) {
889
+ hex += hexes[bytes[i]];
832
890
  }
833
- return str[0] === '0' && str[1] === 'x';
834
- };
835
- /**
836
- * Removes '0x' from a given `String` if present
837
- * @param str the string value
838
- * @returns the string without 0x prefix
839
- */
840
- const stripHexPrefix = (str) => {
841
- if (typeof str !== 'string')
842
- throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
843
- return isHexPrefixed(str) ? str.slice(2) : str;
844
- };
845
- /**
846
- * Is the string a hex string.
847
- *
848
- * @param value
849
- * @param length
850
- * @returns output the string is a hex string
851
- */
852
- const isHexString = (value, length) => {
853
- if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
854
- return false;
855
- return true;
856
- };
891
+ return hex;
892
+ }
893
+ // We use optimized technique to convert hex string to byte array
894
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
895
+ function asciiToBase16(ch) {
896
+ if (ch >= asciis._0 && ch <= asciis._9)
897
+ return ch - asciis._0; // '2' => 50-48
898
+ if (ch >= asciis.A && ch <= asciis.F)
899
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
900
+ if (ch >= asciis.a && ch <= asciis.f)
901
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
902
+ return;
903
+ }
857
904
  /**
858
- * Adds '0x' to a given `String` if not present
859
- * @param str the string input value
860
- * @return the string with a 0x prefix
905
+ * Convert hex string to byte array. Uses built-in function, when available.
906
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
861
907
  */
862
- const addLeading0x = (str) => {
863
- if (!str.startsWith('0x'))
864
- return '0x' + str;
865
- else
866
- return str;
867
- };
868
- const decompress = (startsWith02Or03) => {
869
- const testByteArray = hexToBytes$1(startsWith02Or03);
870
- let startsWith04 = startsWith02Or03;
871
- if (testByteArray.length === 64) {
872
- startsWith04 = '04' + startsWith02Or03;
908
+ function hexToBytes$1(hex) {
909
+ if (typeof hex !== 'string')
910
+ throw new Error('hex string expected, got ' + typeof hex);
911
+ // @ts-ignore
912
+ if (hasHexBuiltin)
913
+ return Uint8Array.fromHex(hex);
914
+ const hl = hex.length;
915
+ const al = hl / 2;
916
+ if (hl % 2)
917
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
918
+ const array = new Uint8Array(al);
919
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
920
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
921
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
922
+ if (n1 === undefined || n2 === undefined) {
923
+ const char = hex[hi] + hex[hi + 1];
924
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
925
+ }
926
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
873
927
  }
874
- return startsWith04.substring(2);
875
- };
876
- /** Helper function to concat UInt8Arrays mimicking the behaviour of the
877
- * Buffer.concat function in Node.js
878
- */
879
- const concatUint8Arrays = (uint8arrays) => {
880
- const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
881
- const result = new Uint8Array(totalLength);
882
- let offset = 0;
883
- uint8arrays.forEach((uint8array) => {
884
- result.set(uint8array, offset);
885
- offset += uint8array.byteLength;
886
- });
887
- return result;
888
- };
928
+ return array;
929
+ }
930
+ // BE: Big Endian, LE: Little Endian
931
+ function bytesToNumberBE(bytes) {
932
+ return hexToNumber(bytesToHex(bytes));
933
+ }
934
+ function bytesToNumberLE(bytes) {
935
+ abytes$2(bytes);
936
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
937
+ }
938
+ function numberToBytesBE(n, len) {
939
+ return hexToBytes$1(n.toString(16).padStart(len * 2, '0'));
940
+ }
941
+ function numberToBytesLE(n, len) {
942
+ return numberToBytesBE(n, len).reverse();
943
+ }
889
944
  /**
890
- * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
891
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
945
+ * Takes hex string or Uint8Array, converts to Uint8Array.
946
+ * Validates output length.
947
+ * Will throw error for other types.
948
+ * @param title descriptive title for an error e.g. 'private key'
949
+ * @param hex hex string or Uint8Array
950
+ * @param expectedLength optional, will compare to result array's length
951
+ * @returns
892
952
  */
893
- const utf8ToBytes = (str) => {
894
- if (typeof str !== 'string')
895
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
896
- const bytes = [];
897
- for (let i = 0; i < str.length; i++) {
898
- const codePoint = str.codePointAt(i);
899
- if (!codePoint) {
900
- throw new Error('Invalid code point');
901
- }
902
- if (codePoint < 0x80) {
903
- bytes.push(codePoint);
904
- }
905
- else if (codePoint < 0x800) {
906
- bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
907
- }
908
- else if (codePoint < 0x10000) {
909
- bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
953
+ function ensureBytes(title, hex, expectedLength) {
954
+ let res;
955
+ if (typeof hex === 'string') {
956
+ try {
957
+ res = hexToBytes$1(hex);
910
958
  }
911
- else {
912
- i++; // skip one iteration since we have a surrogate pair
913
- bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
959
+ catch (e) {
960
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
914
961
  }
915
962
  }
916
- return new Uint8Array(bytes);
917
- };
918
-
919
- /**
920
- * Polyfill for Safari 14
921
- */
922
- function setBigUint64(view, byteOffset, value, isLE) {
923
- if (typeof view.setBigUint64 === 'function')
924
- return view.setBigUint64(byteOffset, value, isLE);
925
- const _32n = BigInt(32);
926
- const _u32_max = BigInt(0xffffffff);
927
- const wh = Number((value >> _32n) & _u32_max);
928
- const wl = Number(value & _u32_max);
929
- const h = isLE ? 4 : 0;
930
- const l = isLE ? 0 : 4;
931
- view.setUint32(byteOffset + h, wh, isLE);
932
- view.setUint32(byteOffset + l, wl, isLE);
963
+ else if (isBytes$1(hex)) {
964
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
965
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
966
+ res = Uint8Array.from(hex);
967
+ }
968
+ else {
969
+ throw new Error(title + ' must be hex string or Uint8Array');
970
+ }
971
+ const len = res.length;
972
+ if (typeof expectedLength === 'number' && len !== expectedLength)
973
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
974
+ return res;
933
975
  }
934
976
  /**
935
- * Choice: a ? b : c
936
- */
937
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
938
- /**
939
- * Majority function, true if any two inputs is true
940
- */
941
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
942
- /**
943
- * Merkle-Damgard hash construction base class.
944
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
977
+ * Copies several Uint8Arrays into one.
945
978
  */
946
- class HashMD extends Hash {
947
- constructor(blockLen, outputLen, padOffset, isLE) {
948
- super();
949
- this.blockLen = blockLen;
950
- this.outputLen = outputLen;
951
- this.padOffset = padOffset;
952
- this.isLE = isLE;
953
- this.finished = false;
979
+ function concatBytes(...arrays) {
980
+ let sum = 0;
981
+ for (let i = 0; i < arrays.length; i++) {
982
+ const a = arrays[i];
983
+ abytes$2(a);
984
+ sum += a.length;
985
+ }
986
+ const res = new Uint8Array(sum);
987
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
988
+ const a = arrays[i];
989
+ res.set(a, pad);
990
+ pad += a.length;
991
+ }
992
+ return res;
993
+ }
994
+ // Is positive bigint
995
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
996
+ function inRange(n, min, max) {
997
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
998
+ }
999
+ /**
1000
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
1001
+ * @example
1002
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
1003
+ */
1004
+ function aInRange(title, n, min, max) {
1005
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
1006
+ // consider P=256n, min=0n, max=P
1007
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
1008
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
1009
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
1010
+ if (!inRange(n, min, max))
1011
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
1012
+ }
1013
+ // Bit operations
1014
+ /**
1015
+ * Calculates amount of bits in a bigint.
1016
+ * Same as `n.toString(2).length`
1017
+ * TODO: merge with nLength in modular
1018
+ */
1019
+ function bitLen(n) {
1020
+ let len;
1021
+ for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
1022
+ ;
1023
+ return len;
1024
+ }
1025
+ /**
1026
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1027
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1028
+ */
1029
+ const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
1030
+ // DRBG
1031
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
1032
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
1033
+ /**
1034
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1035
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
1036
+ * @example
1037
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
1038
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
1039
+ */
1040
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1041
+ if (typeof hashLen !== 'number' || hashLen < 2)
1042
+ throw new Error('hashLen must be a number');
1043
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
1044
+ throw new Error('qByteLen must be a number');
1045
+ if (typeof hmacFn !== 'function')
1046
+ throw new Error('hmacFn must be a function');
1047
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
1048
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1049
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
1050
+ let i = 0; // Iterations counter, will throw when over 1000
1051
+ const reset = () => {
1052
+ v.fill(1);
1053
+ k.fill(0);
1054
+ i = 0;
1055
+ };
1056
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
1057
+ const reseed = (seed = u8n(0)) => {
1058
+ // HMAC-DRBG reseed() function. Steps D-G
1059
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
1060
+ v = h(); // v = hmac(k || v)
1061
+ if (seed.length === 0)
1062
+ return;
1063
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
1064
+ v = h(); // v = hmac(k || v)
1065
+ };
1066
+ const gen = () => {
1067
+ // HMAC-DRBG generate() function
1068
+ if (i++ >= 1000)
1069
+ throw new Error('drbg: tried 1000 values');
1070
+ let len = 0;
1071
+ const out = [];
1072
+ while (len < qByteLen) {
1073
+ v = h();
1074
+ const sl = v.slice();
1075
+ out.push(sl);
1076
+ len += v.length;
1077
+ }
1078
+ return concatBytes(...out);
1079
+ };
1080
+ const genUntil = (seed, pred) => {
1081
+ reset();
1082
+ reseed(seed); // Steps D-G
1083
+ let res = undefined; // Step H: grind until k is in [1..n-1]
1084
+ while (!(res = pred(gen())))
1085
+ reseed();
1086
+ reset();
1087
+ return res;
1088
+ };
1089
+ return genUntil;
1090
+ }
1091
+ // Validating curves and fields
1092
+ const validatorFns = {
1093
+ bigint: (val) => typeof val === 'bigint',
1094
+ function: (val) => typeof val === 'function',
1095
+ boolean: (val) => typeof val === 'boolean',
1096
+ string: (val) => typeof val === 'string',
1097
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
1098
+ isSafeInteger: (val) => Number.isSafeInteger(val),
1099
+ array: (val) => Array.isArray(val),
1100
+ field: (val, object) => object.Fp.isValid(val),
1101
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1102
+ };
1103
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1104
+ function validateObject(object, validators, optValidators = {}) {
1105
+ const checkField = (fieldName, type, isOptional) => {
1106
+ const checkVal = validatorFns[type];
1107
+ if (typeof checkVal !== 'function')
1108
+ throw new Error('invalid validator function');
1109
+ const val = object[fieldName];
1110
+ if (isOptional && val === undefined)
1111
+ return;
1112
+ if (!checkVal(val, object)) {
1113
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
1114
+ }
1115
+ };
1116
+ for (const [fieldName, type] of Object.entries(validators))
1117
+ checkField(fieldName, type, false);
1118
+ for (const [fieldName, type] of Object.entries(optValidators))
1119
+ checkField(fieldName, type, true);
1120
+ return object;
1121
+ }
1122
+ /**
1123
+ * Memoizes (caches) computation result.
1124
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1125
+ */
1126
+ function memoized(fn) {
1127
+ const map = new WeakMap();
1128
+ return (arg, ...args) => {
1129
+ const val = map.get(arg);
1130
+ if (val !== undefined)
1131
+ return val;
1132
+ const computed = fn(arg, ...args);
1133
+ map.set(arg, computed);
1134
+ return computed;
1135
+ };
1136
+ }
1137
+
1138
+ /**
1139
+ * Internal assertion helpers.
1140
+ * @module
1141
+ * @deprecated
1142
+ */
1143
+ /** @deprecated Use import from `noble/hashes/utils` module */
1144
+ const abytes$1 = abytes$3;
1145
+
1146
+ // buf.toString('utf8') -> bytesToUtf8(buf)
1147
+ function bytesToUtf8(data) {
1148
+ if (!(data instanceof Uint8Array)) {
1149
+ throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
1150
+ }
1151
+ return new TextDecoder().decode(data);
1152
+ }
1153
+ function hexToBytes(data) {
1154
+ const sliced = data.startsWith("0x") ? data.substring(2) : data;
1155
+ return hexToBytes$2(sliced);
1156
+ }
1157
+ // Internal utils
1158
+ function wrapHash(hash) {
1159
+ return (msg) => {
1160
+ abytes$1(msg);
1161
+ return hash(msg);
1162
+ };
1163
+ }
1164
+
1165
+ /**
1166
+ * Returns a `Boolean` on whether or not the a `String` starts with '0x'
1167
+ * @param str the string input value
1168
+ * @return a boolean if it is or is not hex prefixed
1169
+ * @throws if the str input is not a string
1170
+ */
1171
+ const isHexPrefixed = (str) => {
1172
+ if (typeof str !== 'string') {
1173
+ throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
1174
+ }
1175
+ return str[0] === '0' && str[1] === 'x';
1176
+ };
1177
+ /**
1178
+ * Removes '0x' from a given `String` if present
1179
+ * @param str the string value
1180
+ * @returns the string without 0x prefix
1181
+ */
1182
+ const stripHexPrefix = (str) => {
1183
+ if (typeof str !== 'string')
1184
+ throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
1185
+ return isHexPrefixed(str) ? str.slice(2) : str;
1186
+ };
1187
+ /**
1188
+ * Is the string a hex string.
1189
+ *
1190
+ * @param value
1191
+ * @param length
1192
+ * @returns output the string is a hex string
1193
+ */
1194
+ const isHexString = (value, length) => {
1195
+ if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
1196
+ return false;
1197
+ return true;
1198
+ };
1199
+ /**
1200
+ * Adds '0x' to a given `String` if not present
1201
+ * @param str the string input value
1202
+ * @return the string with a 0x prefix
1203
+ */
1204
+ const addLeading0x = (str) => {
1205
+ if (!str.startsWith('0x'))
1206
+ return '0x' + str;
1207
+ else
1208
+ return str;
1209
+ };
1210
+ const decompress = (startsWith02Or03) => {
1211
+ const testByteArray = hexToBytes(startsWith02Or03);
1212
+ let startsWith04 = startsWith02Or03;
1213
+ if (testByteArray.length === 64) {
1214
+ startsWith04 = '04' + startsWith02Or03;
1215
+ }
1216
+ return startsWith04.substring(2);
1217
+ };
1218
+ /** Helper function to concat UInt8Arrays mimicking the behaviour of the
1219
+ * Buffer.concat function in Node.js
1220
+ */
1221
+ const concatUint8Arrays = (uint8arrays) => {
1222
+ const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
1223
+ const result = new Uint8Array(totalLength);
1224
+ let offset = 0;
1225
+ uint8arrays.forEach((uint8array) => {
1226
+ result.set(uint8array, offset);
1227
+ offset += uint8array.byteLength;
1228
+ });
1229
+ return result;
1230
+ };
1231
+ /**
1232
+ * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
1233
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
1234
+ */
1235
+ const utf8ToBytes = (str) => {
1236
+ if (typeof str !== 'string')
1237
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
1238
+ const bytes = [];
1239
+ for (let i = 0; i < str.length; i++) {
1240
+ const codePoint = str.codePointAt(i);
1241
+ if (!codePoint) {
1242
+ throw new Error('Invalid code point');
1243
+ }
1244
+ if (codePoint < 0x80) {
1245
+ bytes.push(codePoint);
1246
+ }
1247
+ else if (codePoint < 0x800) {
1248
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
1249
+ }
1250
+ else if (codePoint < 0x10000) {
1251
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1252
+ }
1253
+ else {
1254
+ i++; // skip one iteration since we have a surrogate pair
1255
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1256
+ }
1257
+ }
1258
+ return new Uint8Array(bytes);
1259
+ };
1260
+
1261
+ /**
1262
+ * Internal Merkle-Damgard hash utils.
1263
+ * @module
1264
+ */
1265
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
1266
+ function setBigUint64(view, byteOffset, value, isLE) {
1267
+ if (typeof view.setBigUint64 === 'function')
1268
+ return view.setBigUint64(byteOffset, value, isLE);
1269
+ const _32n = BigInt(32);
1270
+ const _u32_max = BigInt(0xffffffff);
1271
+ const wh = Number((value >> _32n) & _u32_max);
1272
+ const wl = Number(value & _u32_max);
1273
+ const h = isLE ? 4 : 0;
1274
+ const l = isLE ? 0 : 4;
1275
+ view.setUint32(byteOffset + h, wh, isLE);
1276
+ view.setUint32(byteOffset + l, wl, isLE);
1277
+ }
1278
+ /** Choice: a ? b : c */
1279
+ function Chi(a, b, c) {
1280
+ return (a & b) ^ (~a & c);
1281
+ }
1282
+ /** Majority function, true if any two inputs is true. */
1283
+ function Maj(a, b, c) {
1284
+ return (a & b) ^ (a & c) ^ (b & c);
1285
+ }
1286
+ /**
1287
+ * Merkle-Damgard hash construction base class.
1288
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1289
+ */
1290
+ class HashMD extends Hash {
1291
+ constructor(blockLen, outputLen, padOffset, isLE) {
1292
+ super();
1293
+ this.finished = false;
954
1294
  this.length = 0;
955
1295
  this.pos = 0;
956
1296
  this.destroyed = false;
1297
+ this.blockLen = blockLen;
1298
+ this.outputLen = outputLen;
1299
+ this.padOffset = padOffset;
1300
+ this.isLE = isLE;
957
1301
  this.buffer = new Uint8Array(blockLen);
958
1302
  this.view = createView(this.buffer);
959
1303
  }
960
1304
  update(data) {
961
- exists(this);
962
- const { view, buffer, blockLen } = this;
1305
+ aexists(this);
963
1306
  data = toBytes(data);
1307
+ abytes$3(data);
1308
+ const { view, buffer, blockLen } = this;
964
1309
  const len = data.length;
965
1310
  for (let pos = 0; pos < len;) {
966
1311
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -984,8 +1329,8 @@ class HashMD extends Hash {
984
1329
  return this;
985
1330
  }
986
1331
  digestInto(out) {
987
- exists(this);
988
- output$1(out, this);
1332
+ aexists(this);
1333
+ aoutput(out, this);
989
1334
  this.finished = true;
990
1335
  // Padding
991
1336
  // We can avoid allocation of buffer for padding completely if it
@@ -994,7 +1339,7 @@ class HashMD extends Hash {
994
1339
  let { pos } = this;
995
1340
  // append the bit '1' to the message
996
1341
  buffer[pos++] = 0b10000000;
997
- this.buffer.subarray(pos).fill(0);
1342
+ clean$1(this.buffer.subarray(pos));
998
1343
  // we have less than padOffset left in buffer, so we cannot put length in
999
1344
  // current block, need process it and pad again
1000
1345
  if (this.padOffset > blockLen - pos) {
@@ -1032,22 +1377,96 @@ class HashMD extends Hash {
1032
1377
  to || (to = new this.constructor());
1033
1378
  to.set(...this.get());
1034
1379
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
1380
+ to.destroyed = destroyed;
1381
+ to.finished = finished;
1035
1382
  to.length = length;
1036
1383
  to.pos = pos;
1037
- to.finished = finished;
1038
- to.destroyed = destroyed;
1039
1384
  if (length % blockLen)
1040
1385
  to.buffer.set(buffer);
1041
1386
  return to;
1042
1387
  }
1388
+ clone() {
1389
+ return this._cloneInto();
1390
+ }
1391
+ }
1392
+ /**
1393
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
1394
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
1395
+ */
1396
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
1397
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1398
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
1399
+ ]);
1400
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
1401
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1402
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
1403
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
1404
+ ]);
1405
+
1406
+ /**
1407
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
1408
+ * @todo re-check https://issues.chromium.org/issues/42212588
1409
+ * @module
1410
+ */
1411
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1412
+ const _32n = /* @__PURE__ */ BigInt(32);
1413
+ function fromBig(n, le = false) {
1414
+ if (le)
1415
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
1416
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1417
+ }
1418
+ function split(lst, le = false) {
1419
+ const len = lst.length;
1420
+ let Ah = new Uint32Array(len);
1421
+ let Al = new Uint32Array(len);
1422
+ for (let i = 0; i < len; i++) {
1423
+ const { h, l } = fromBig(lst[i], le);
1424
+ [Ah[i], Al[i]] = [h, l];
1425
+ }
1426
+ return [Ah, Al];
1427
+ }
1428
+ // for Shift in [0, 32)
1429
+ const shrSH = (h, _l, s) => h >>> s;
1430
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1431
+ // Right rotate for Shift in [1, 32)
1432
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
1433
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
1434
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
1435
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
1436
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
1437
+ // Left rotate for Shift in [1, 32)
1438
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
1439
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
1440
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
1441
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
1442
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
1443
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
1444
+ // simple take carry out of low bit sum by shift, we need to use division.
1445
+ function add(Ah, Al, Bh, Bl) {
1446
+ const l = (Al >>> 0) + (Bl >>> 0);
1447
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
1043
1448
  }
1449
+ // Addition with more than 2 elements
1450
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1451
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
1452
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1453
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
1454
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1455
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
1044
1456
 
1045
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
1046
- // BTC network is doing 2^67 hashes/sec as per early 2023.
1047
- // Round constants:
1048
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
1457
+ /**
1458
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1459
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1460
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
1461
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1462
+ * @module
1463
+ */
1464
+ /**
1465
+ * Round constants:
1466
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
1467
+ */
1049
1468
  // prettier-ignore
1050
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
1469
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1051
1470
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1052
1471
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1053
1472
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -1057,18 +1476,11 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
1057
1476
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1058
1477
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1059
1478
  ]);
1060
- // Initial state:
1061
- // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
1062
- // prettier-ignore
1063
- const SHA256_IV = /* @__PURE__ */ new Uint32Array([
1064
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
1065
- ]);
1066
- // Temporary buffer, not used to store anything between runs
1067
- // Named this way because it matches specification.
1479
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1068
1480
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1069
1481
  class SHA256 extends HashMD {
1070
- constructor() {
1071
- super(64, 32, 8, false);
1482
+ constructor(outputLen = 32) {
1483
+ super(64, outputLen, 8, false);
1072
1484
  // We cannot use array here since array allows indexing by variable
1073
1485
  // which means optimizer/compiler cannot use registers.
1074
1486
  this.A = SHA256_IV[0] | 0;
@@ -1134,441 +1546,313 @@ class SHA256 extends HashMD {
1134
1546
  this.set(A, B, C, D, E, F, G, H);
1135
1547
  }
1136
1548
  roundClean() {
1137
- SHA256_W.fill(0);
1549
+ clean$1(SHA256_W);
1138
1550
  }
1139
1551
  destroy() {
1140
1552
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
1141
- this.buffer.fill(0);
1553
+ clean$1(this.buffer);
1142
1554
  }
1143
1555
  }
1144
- /**
1145
- * SHA2-256 hash function
1146
- * @param message - data that would be hashed
1147
- */
1148
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1149
-
1150
- // HMAC (RFC 2104)
1151
- class HMAC extends Hash {
1152
- constructor(hash, _key) {
1153
- super();
1154
- this.finished = false;
1155
- this.destroyed = false;
1156
- hash$1(hash);
1157
- const key = toBytes(_key);
1158
- this.iHash = hash.create();
1159
- if (typeof this.iHash.update !== 'function')
1160
- throw new Error('Expected instance of class which extends utils.Hash');
1161
- this.blockLen = this.iHash.blockLen;
1162
- this.outputLen = this.iHash.outputLen;
1163
- const blockLen = this.blockLen;
1164
- const pad = new Uint8Array(blockLen);
1165
- // blockLen can be bigger than outputLen
1166
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1167
- for (let i = 0; i < pad.length; i++)
1168
- pad[i] ^= 0x36;
1169
- this.iHash.update(pad);
1170
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
1171
- this.oHash = hash.create();
1172
- // Undo internal XOR && apply outer XOR
1173
- for (let i = 0; i < pad.length; i++)
1174
- pad[i] ^= 0x36 ^ 0x5c;
1175
- this.oHash.update(pad);
1176
- pad.fill(0);
1177
- }
1178
- update(buf) {
1179
- exists(this);
1180
- this.iHash.update(buf);
1181
- return this;
1182
- }
1183
- digestInto(out) {
1184
- exists(this);
1185
- bytes$1(out, this.outputLen);
1186
- this.finished = true;
1187
- this.iHash.digestInto(out);
1188
- this.oHash.update(out);
1189
- this.oHash.digestInto(out);
1190
- this.destroy();
1191
- }
1192
- digest() {
1193
- const out = new Uint8Array(this.oHash.outputLen);
1194
- this.digestInto(out);
1195
- return out;
1196
- }
1197
- _cloneInto(to) {
1198
- // Create new instance without calling constructor since key already in state and we don't know it.
1199
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
1200
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1201
- to = to;
1202
- to.finished = finished;
1203
- to.destroyed = destroyed;
1204
- to.blockLen = blockLen;
1205
- to.outputLen = outputLen;
1206
- to.oHash = oHash._cloneInto(to.oHash);
1207
- to.iHash = iHash._cloneInto(to.iHash);
1208
- return to;
1209
- }
1210
- destroy() {
1211
- this.destroyed = true;
1212
- this.oHash.destroy();
1213
- this.iHash.destroy();
1556
+ // SHA2-512 is slower than sha256 in js because u64 operations are slow.
1557
+ // Round contants
1558
+ // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
1559
+ // prettier-ignore
1560
+ const K512 = /* @__PURE__ */ (() => split([
1561
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
1562
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
1563
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
1564
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
1565
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
1566
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
1567
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
1568
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
1569
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
1570
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
1571
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
1572
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
1573
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
1574
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
1575
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
1576
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
1577
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
1578
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
1579
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
1580
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
1581
+ ].map(n => BigInt(n))))();
1582
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1583
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1584
+ // Reusable temporary buffers
1585
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1586
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1587
+ class SHA512 extends HashMD {
1588
+ constructor(outputLen = 64) {
1589
+ super(128, outputLen, 16, false);
1590
+ // We cannot use array here since array allows indexing by variable
1591
+ // which means optimizer/compiler cannot use registers.
1592
+ // h -- high 32 bits, l -- low 32 bits
1593
+ this.Ah = SHA512_IV[0] | 0;
1594
+ this.Al = SHA512_IV[1] | 0;
1595
+ this.Bh = SHA512_IV[2] | 0;
1596
+ this.Bl = SHA512_IV[3] | 0;
1597
+ this.Ch = SHA512_IV[4] | 0;
1598
+ this.Cl = SHA512_IV[5] | 0;
1599
+ this.Dh = SHA512_IV[6] | 0;
1600
+ this.Dl = SHA512_IV[7] | 0;
1601
+ this.Eh = SHA512_IV[8] | 0;
1602
+ this.El = SHA512_IV[9] | 0;
1603
+ this.Fh = SHA512_IV[10] | 0;
1604
+ this.Fl = SHA512_IV[11] | 0;
1605
+ this.Gh = SHA512_IV[12] | 0;
1606
+ this.Gl = SHA512_IV[13] | 0;
1607
+ this.Hh = SHA512_IV[14] | 0;
1608
+ this.Hl = SHA512_IV[15] | 0;
1214
1609
  }
1215
- }
1216
- /**
1217
- * HMAC: RFC2104 message authentication code.
1218
- * @param hash - function that would be used e.g. sha256
1219
- * @param key - message key
1220
- * @param message - message data
1221
- * @example
1222
- * import { hmac } from '@noble/hashes/hmac';
1223
- * import { sha256 } from '@noble/hashes/sha2';
1224
- * const mac1 = hmac(sha256, 'key', 'message');
1225
- */
1226
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1227
- hmac.create = (hash, key) => new HMAC(hash, key);
1228
-
1229
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1230
- // 100 lines of code in the file are duplicated from noble-hashes (utils).
1231
- // This is OK: `abstract` directory does not use noble-hashes.
1232
- // User may opt-in into using different hashing library. This way, noble-hashes
1233
- // won't be included into their bundle.
1234
- const _0n$4 = /* @__PURE__ */ BigInt(0);
1235
- const _1n$5 = /* @__PURE__ */ BigInt(1);
1236
- const _2n$3 = /* @__PURE__ */ BigInt(2);
1237
- function isBytes$1(a) {
1238
- return (a instanceof Uint8Array ||
1239
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
1240
- }
1241
- function abytes(item) {
1242
- if (!isBytes$1(item))
1243
- throw new Error('Uint8Array expected');
1244
- }
1245
- function abool(title, value) {
1246
- if (typeof value !== 'boolean')
1247
- throw new Error(`${title} must be valid boolean, got "${value}".`);
1248
- }
1249
- // Array where index 0xf0 (240) is mapped to string 'f0'
1250
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
1251
- /**
1252
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
1253
- */
1254
- function bytesToHex(bytes) {
1255
- abytes(bytes);
1256
- // pre-caching improves the speed 6x
1257
- let hex = '';
1258
- for (let i = 0; i < bytes.length; i++) {
1259
- hex += hexes[bytes[i]];
1610
+ // prettier-ignore
1611
+ get() {
1612
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1613
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1260
1614
  }
1261
- return hex;
1262
- }
1263
- function numberToHexUnpadded(num) {
1264
- const hex = num.toString(16);
1265
- return hex.length & 1 ? `0${hex}` : hex;
1266
- }
1267
- function hexToNumber(hex) {
1268
- if (typeof hex !== 'string')
1269
- throw new Error('hex string expected, got ' + typeof hex);
1270
- // Big Endian
1271
- return BigInt(hex === '' ? '0' : `0x${hex}`);
1272
- }
1273
- // We use optimized technique to convert hex string to byte array
1274
- const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
1275
- function asciiToBase16(char) {
1276
- if (char >= asciis._0 && char <= asciis._9)
1277
- return char - asciis._0;
1278
- if (char >= asciis._A && char <= asciis._F)
1279
- return char - (asciis._A - 10);
1280
- if (char >= asciis._a && char <= asciis._f)
1281
- return char - (asciis._a - 10);
1282
- return;
1283
- }
1284
- /**
1285
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
1286
- */
1287
- function hexToBytes(hex) {
1288
- if (typeof hex !== 'string')
1289
- throw new Error('hex string expected, got ' + typeof hex);
1290
- const hl = hex.length;
1291
- const al = hl / 2;
1292
- if (hl % 2)
1293
- throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
1294
- const array = new Uint8Array(al);
1295
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1296
- const n1 = asciiToBase16(hex.charCodeAt(hi));
1297
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1298
- if (n1 === undefined || n2 === undefined) {
1299
- const char = hex[hi] + hex[hi + 1];
1300
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1301
- }
1302
- array[ai] = n1 * 16 + n2;
1615
+ // prettier-ignore
1616
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1617
+ this.Ah = Ah | 0;
1618
+ this.Al = Al | 0;
1619
+ this.Bh = Bh | 0;
1620
+ this.Bl = Bl | 0;
1621
+ this.Ch = Ch | 0;
1622
+ this.Cl = Cl | 0;
1623
+ this.Dh = Dh | 0;
1624
+ this.Dl = Dl | 0;
1625
+ this.Eh = Eh | 0;
1626
+ this.El = El | 0;
1627
+ this.Fh = Fh | 0;
1628
+ this.Fl = Fl | 0;
1629
+ this.Gh = Gh | 0;
1630
+ this.Gl = Gl | 0;
1631
+ this.Hh = Hh | 0;
1632
+ this.Hl = Hl | 0;
1303
1633
  }
1304
- return array;
1305
- }
1306
- // BE: Big Endian, LE: Little Endian
1307
- function bytesToNumberBE(bytes) {
1308
- return hexToNumber(bytesToHex(bytes));
1309
- }
1310
- function bytesToNumberLE(bytes) {
1311
- abytes(bytes);
1312
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
1313
- }
1314
- function numberToBytesBE(n, len) {
1315
- return hexToBytes(n.toString(16).padStart(len * 2, '0'));
1316
- }
1317
- function numberToBytesLE(n, len) {
1318
- return numberToBytesBE(n, len).reverse();
1319
- }
1320
- /**
1321
- * Takes hex string or Uint8Array, converts to Uint8Array.
1322
- * Validates output length.
1323
- * Will throw error for other types.
1324
- * @param title descriptive title for an error e.g. 'private key'
1325
- * @param hex hex string or Uint8Array
1326
- * @param expectedLength optional, will compare to result array's length
1327
- * @returns
1328
- */
1329
- function ensureBytes(title, hex, expectedLength) {
1330
- let res;
1331
- if (typeof hex === 'string') {
1332
- try {
1333
- res = hexToBytes(hex);
1634
+ process(view, offset) {
1635
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
1636
+ for (let i = 0; i < 16; i++, offset += 4) {
1637
+ SHA512_W_H[i] = view.getUint32(offset);
1638
+ SHA512_W_L[i] = view.getUint32((offset += 4));
1334
1639
  }
1335
- catch (e) {
1336
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
1640
+ for (let i = 16; i < 80; i++) {
1641
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
1642
+ const W15h = SHA512_W_H[i - 15] | 0;
1643
+ const W15l = SHA512_W_L[i - 15] | 0;
1644
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1645
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1646
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
1647
+ const W2h = SHA512_W_H[i - 2] | 0;
1648
+ const W2l = SHA512_W_L[i - 2] | 0;
1649
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1650
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1651
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
1652
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1653
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1654
+ SHA512_W_H[i] = SUMh | 0;
1655
+ SHA512_W_L[i] = SUMl | 0;
1656
+ }
1657
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1658
+ // Compression function main loop, 80 rounds
1659
+ for (let i = 0; i < 80; i++) {
1660
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
1661
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1662
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1663
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1664
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
1665
+ const CHIl = (El & Fl) ^ (~El & Gl);
1666
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
1667
+ // prettier-ignore
1668
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1669
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1670
+ const T1l = T1ll | 0;
1671
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
1672
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1673
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1674
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
1675
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
1676
+ Hh = Gh | 0;
1677
+ Hl = Gl | 0;
1678
+ Gh = Fh | 0;
1679
+ Gl = Fl | 0;
1680
+ Fh = Eh | 0;
1681
+ Fl = El | 0;
1682
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1683
+ Dh = Ch | 0;
1684
+ Dl = Cl | 0;
1685
+ Ch = Bh | 0;
1686
+ Cl = Bl | 0;
1687
+ Bh = Ah | 0;
1688
+ Bl = Al | 0;
1689
+ const All = add3L(T1l, sigma0l, MAJl);
1690
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1691
+ Al = All | 0;
1337
1692
  }
1693
+ // Add the compressed chunk to the current hash value
1694
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1695
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1696
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1697
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1698
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1699
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1700
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1701
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1702
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1338
1703
  }
1339
- else if (isBytes$1(hex)) {
1340
- // Uint8Array.from() instead of hash.slice() because node.js Buffer
1341
- // is instance of Uint8Array, and its slice() creates **mutable** copy
1342
- res = Uint8Array.from(hex);
1704
+ roundClean() {
1705
+ clean$1(SHA512_W_H, SHA512_W_L);
1343
1706
  }
1344
- else {
1345
- throw new Error(`${title} must be hex string or Uint8Array`);
1707
+ destroy() {
1708
+ clean$1(this.buffer);
1709
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1346
1710
  }
1347
- const len = res.length;
1348
- if (typeof expectedLength === 'number' && len !== expectedLength)
1349
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
1350
- return res;
1351
1711
  }
1352
- /**
1353
- * Copies several Uint8Arrays into one.
1354
- */
1355
- function concatBytes(...arrays) {
1356
- let sum = 0;
1357
- for (let i = 0; i < arrays.length; i++) {
1358
- const a = arrays[i];
1359
- abytes(a);
1360
- sum += a.length;
1361
- }
1362
- const res = new Uint8Array(sum);
1363
- for (let i = 0, pad = 0; i < arrays.length; i++) {
1364
- const a = arrays[i];
1365
- res.set(a, pad);
1366
- pad += a.length;
1712
+ /** SHA512/256 IV */
1713
+ const T256_IV = /* @__PURE__ */ Uint32Array.from([
1714
+ 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
1715
+ 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
1716
+ ]);
1717
+ class SHA512_256 extends SHA512 {
1718
+ constructor() {
1719
+ super(32);
1720
+ this.Ah = T256_IV[0] | 0;
1721
+ this.Al = T256_IV[1] | 0;
1722
+ this.Bh = T256_IV[2] | 0;
1723
+ this.Bl = T256_IV[3] | 0;
1724
+ this.Ch = T256_IV[4] | 0;
1725
+ this.Cl = T256_IV[5] | 0;
1726
+ this.Dh = T256_IV[6] | 0;
1727
+ this.Dl = T256_IV[7] | 0;
1728
+ this.Eh = T256_IV[8] | 0;
1729
+ this.El = T256_IV[9] | 0;
1730
+ this.Fh = T256_IV[10] | 0;
1731
+ this.Fl = T256_IV[11] | 0;
1732
+ this.Gh = T256_IV[12] | 0;
1733
+ this.Gl = T256_IV[13] | 0;
1734
+ this.Hh = T256_IV[14] | 0;
1735
+ this.Hl = T256_IV[15] | 0;
1367
1736
  }
1368
- return res;
1369
- }
1370
- // Is positive bigint
1371
- const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
1372
- function inRange(n, min, max) {
1373
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1374
- }
1375
- /**
1376
- * Asserts min <= n < max. NOTE: It's < max and not <= max.
1377
- * @example
1378
- * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
1379
- */
1380
- function aInRange(title, n, min, max) {
1381
- // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
1382
- // consider P=256n, min=0n, max=P
1383
- // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
1384
- // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
1385
- // - our way is the cleanest: `inRange('x', x, 0n, P)
1386
- if (!inRange(n, min, max))
1387
- throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
1388
1737
  }
1389
- // Bit operations
1390
1738
  /**
1391
- * Calculates amount of bits in a bigint.
1392
- * Same as `n.toString(2).length`
1739
+ * SHA2-256 hash function from RFC 4634.
1740
+ *
1741
+ * It is the fastest JS hash, even faster than Blake3.
1742
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1743
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1393
1744
  */
1394
- function bitLen(n) {
1395
- let len;
1396
- for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
1397
- ;
1398
- return len;
1399
- }
1745
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
1746
+ /** SHA2-512 hash function from RFC 4634. */
1747
+ const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
1400
1748
  /**
1401
- * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1402
- * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1749
+ * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
1750
+ * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
1403
1751
  */
1404
- const bitMask = (n) => (_2n$3 << BigInt(n - 1)) - _1n$5;
1405
- // DRBG
1406
- const u8n = (data) => new Uint8Array(data); // creates Uint8Array
1407
- const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
1752
+ const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
1753
+
1408
1754
  /**
1409
- * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1410
- * @returns function that will call DRBG until 2nd arg returns something meaningful
1411
- * @example
1412
- * const drbg = createHmacDRBG<Key>(32, 32, hmac);
1413
- * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
1755
+ * HMAC: RFC2104 message authentication code.
1756
+ * @module
1414
1757
  */
1415
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1416
- if (typeof hashLen !== 'number' || hashLen < 2)
1417
- throw new Error('hashLen must be a number');
1418
- if (typeof qByteLen !== 'number' || qByteLen < 2)
1419
- throw new Error('qByteLen must be a number');
1420
- if (typeof hmacFn !== 'function')
1421
- throw new Error('hmacFn must be a function');
1422
- // Step B, Step C: set hashLen to 8*ceil(hlen/8)
1423
- let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1424
- let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
1425
- let i = 0; // Iterations counter, will throw when over 1000
1426
- const reset = () => {
1427
- v.fill(1);
1428
- k.fill(0);
1429
- i = 0;
1430
- };
1431
- const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
1432
- const reseed = (seed = u8n()) => {
1433
- // HMAC-DRBG reseed() function. Steps D-G
1434
- k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
1435
- v = h(); // v = hmac(k || v)
1436
- if (seed.length === 0)
1437
- return;
1438
- k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
1439
- v = h(); // v = hmac(k || v)
1440
- };
1441
- const gen = () => {
1442
- // HMAC-DRBG generate() function
1443
- if (i++ >= 1000)
1444
- throw new Error('drbg: tried 1000 values');
1445
- let len = 0;
1446
- const out = [];
1447
- while (len < qByteLen) {
1448
- v = h();
1449
- const sl = v.slice();
1450
- out.push(sl);
1451
- len += v.length;
1452
- }
1453
- return concatBytes(...out);
1454
- };
1455
- const genUntil = (seed, pred) => {
1456
- reset();
1457
- reseed(seed); // Steps D-G
1458
- let res = undefined; // Step H: grind until k is in [1..n-1]
1459
- while (!(res = pred(gen())))
1460
- reseed();
1461
- reset();
1462
- return res;
1463
- };
1464
- return genUntil;
1465
- }
1466
- // Validating curves and fields
1467
- const validatorFns = {
1468
- bigint: (val) => typeof val === 'bigint',
1469
- function: (val) => typeof val === 'function',
1470
- boolean: (val) => typeof val === 'boolean',
1471
- string: (val) => typeof val === 'string',
1472
- stringOrUint8Array: (val) => typeof val === 'string' || isBytes$1(val),
1473
- isSafeInteger: (val) => Number.isSafeInteger(val),
1474
- array: (val) => Array.isArray(val),
1475
- field: (val, object) => object.Fp.isValid(val),
1476
- hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1477
- };
1478
- // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1479
- function validateObject(object, validators, optValidators = {}) {
1480
- const checkField = (fieldName, type, isOptional) => {
1481
- const checkVal = validatorFns[type];
1482
- if (typeof checkVal !== 'function')
1483
- throw new Error(`Invalid validator "${type}", expected function`);
1484
- const val = object[fieldName];
1485
- if (isOptional && val === undefined)
1486
- return;
1487
- if (!checkVal(val, object)) {
1488
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
1489
- }
1490
- };
1491
- for (const [fieldName, type] of Object.entries(validators))
1492
- checkField(fieldName, type, false);
1493
- for (const [fieldName, type] of Object.entries(optValidators))
1494
- checkField(fieldName, type, true);
1495
- return object;
1758
+ class HMAC extends Hash {
1759
+ constructor(hash, _key) {
1760
+ super();
1761
+ this.finished = false;
1762
+ this.destroyed = false;
1763
+ ahash(hash);
1764
+ const key = toBytes(_key);
1765
+ this.iHash = hash.create();
1766
+ if (typeof this.iHash.update !== 'function')
1767
+ throw new Error('Expected instance of class which extends utils.Hash');
1768
+ this.blockLen = this.iHash.blockLen;
1769
+ this.outputLen = this.iHash.outputLen;
1770
+ const blockLen = this.blockLen;
1771
+ const pad = new Uint8Array(blockLen);
1772
+ // blockLen can be bigger than outputLen
1773
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1774
+ for (let i = 0; i < pad.length; i++)
1775
+ pad[i] ^= 0x36;
1776
+ this.iHash.update(pad);
1777
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
1778
+ this.oHash = hash.create();
1779
+ // Undo internal XOR && apply outer XOR
1780
+ for (let i = 0; i < pad.length; i++)
1781
+ pad[i] ^= 0x36 ^ 0x5c;
1782
+ this.oHash.update(pad);
1783
+ clean$1(pad);
1784
+ }
1785
+ update(buf) {
1786
+ aexists(this);
1787
+ this.iHash.update(buf);
1788
+ return this;
1789
+ }
1790
+ digestInto(out) {
1791
+ aexists(this);
1792
+ abytes$3(out, this.outputLen);
1793
+ this.finished = true;
1794
+ this.iHash.digestInto(out);
1795
+ this.oHash.update(out);
1796
+ this.oHash.digestInto(out);
1797
+ this.destroy();
1798
+ }
1799
+ digest() {
1800
+ const out = new Uint8Array(this.oHash.outputLen);
1801
+ this.digestInto(out);
1802
+ return out;
1803
+ }
1804
+ _cloneInto(to) {
1805
+ // Create new instance without calling constructor since key already in state and we don't know it.
1806
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1807
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1808
+ to = to;
1809
+ to.finished = finished;
1810
+ to.destroyed = destroyed;
1811
+ to.blockLen = blockLen;
1812
+ to.outputLen = outputLen;
1813
+ to.oHash = oHash._cloneInto(to.oHash);
1814
+ to.iHash = iHash._cloneInto(to.iHash);
1815
+ return to;
1816
+ }
1817
+ clone() {
1818
+ return this._cloneInto();
1819
+ }
1820
+ destroy() {
1821
+ this.destroyed = true;
1822
+ this.oHash.destroy();
1823
+ this.iHash.destroy();
1824
+ }
1496
1825
  }
1497
1826
  /**
1498
- * Memoizes (caches) computation result.
1499
- * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1827
+ * HMAC: RFC2104 message authentication code.
1828
+ * @param hash - function that would be used e.g. sha256
1829
+ * @param key - message key
1830
+ * @param message - message data
1831
+ * @example
1832
+ * import { hmac } from '@noble/hashes/hmac';
1833
+ * import { sha256 } from '@noble/hashes/sha2';
1834
+ * const mac1 = hmac(sha256, 'key', 'message');
1500
1835
  */
1501
- function memoized(fn) {
1502
- const map = new WeakMap();
1503
- return (arg, ...args) => {
1504
- const val = map.get(arg);
1505
- if (val !== undefined)
1506
- return val;
1507
- const computed = fn(arg, ...args);
1508
- map.set(arg, computed);
1509
- return computed;
1510
- };
1511
- }
1512
-
1513
- const ut = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
1514
- __proto__: null,
1515
- aInRange,
1516
- abool,
1517
- abytes,
1518
- bitLen,
1519
- bitMask,
1520
- bytesToHex,
1521
- bytesToNumberBE,
1522
- bytesToNumberLE,
1523
- concatBytes,
1524
- createHmacDrbg,
1525
- ensureBytes,
1526
- hexToBytes,
1527
- hexToNumber,
1528
- inRange,
1529
- isBytes: isBytes$1,
1530
- memoized,
1531
- numberToBytesBE,
1532
- numberToBytesLE,
1533
- numberToHexUnpadded,
1534
- validateObject
1535
- }, Symbol.toStringTag, { value: 'Module' }));
1836
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1837
+ hmac.create = (hash, key) => new HMAC(hash, key);
1536
1838
 
1839
+ /**
1840
+ * Utils for modular division and finite fields.
1841
+ * A finite field over 11 is integer number operations `mod 11`.
1842
+ * There is no division: it is replaced by modular multiplicative inverse.
1843
+ * @module
1844
+ */
1537
1845
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1538
- // Utilities for modular arithmetics and finite fields
1539
1846
  // prettier-ignore
1540
- const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = BigInt(2), _3n$1 = BigInt(3);
1847
+ const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
1541
1848
  // prettier-ignore
1542
- const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
1543
- // prettier-ignore
1544
- BigInt(9); BigInt(16);
1849
+ const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
1545
1850
  // Calculates a modulo b
1546
1851
  function mod(a, b) {
1547
1852
  const result = a % b;
1548
1853
  return result >= _0n$3 ? result : b + result;
1549
1854
  }
1550
- /**
1551
- * Efficiently raise num to power and do modular division.
1552
- * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1553
- * @example
1554
- * pow(2n, 6n, 11n) // 64n % 11n == 9n
1555
- */
1556
- // TODO: use field version && remove
1557
- function pow(num, power, modulo) {
1558
- if (modulo <= _0n$3 || power < _0n$3)
1559
- throw new Error('Expected power/modulo > 0');
1560
- if (modulo === _1n$4)
1561
- return _0n$3;
1562
- let res = _1n$4;
1563
- while (power > _0n$3) {
1564
- if (power & _1n$4)
1565
- res = (res * num) % modulo;
1566
- num = (num * num) % modulo;
1567
- power >>= _1n$4;
1568
- }
1569
- return res;
1570
- }
1571
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
1855
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
1572
1856
  function pow2(x, power, modulo) {
1573
1857
  let res = x;
1574
1858
  while (power-- > _0n$3) {
@@ -1577,12 +1861,15 @@ function pow2(x, power, modulo) {
1577
1861
  }
1578
1862
  return res;
1579
1863
  }
1580
- // Inverses number over modulo
1864
+ /**
1865
+ * Inverses number over modulo.
1866
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
1867
+ */
1581
1868
  function invert(number, modulo) {
1582
- if (number === _0n$3 || modulo <= _0n$3) {
1583
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
1584
- }
1585
- // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
1869
+ if (number === _0n$3)
1870
+ throw new Error('invert: expected non-zero number');
1871
+ if (modulo <= _0n$3)
1872
+ throw new Error('invert: expected positive modulus, got ' + modulo);
1586
1873
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
1587
1874
  let a = mod(number, modulo);
1588
1875
  let b = modulo;
@@ -1605,25 +1892,26 @@ function invert(number, modulo) {
1605
1892
  * Tonelli-Shanks square root search algorithm.
1606
1893
  * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
1607
1894
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
1608
- * Will start an infinite loop if field order P is not prime.
1609
1895
  * @param P field order
1610
1896
  * @returns function that takes field Fp (created from P) and number n
1611
1897
  */
1612
1898
  function tonelliShanks(P) {
1613
- // Legendre constant: used to calculate Legendre symbol (a | p),
1614
- // which denotes the value of a^((p-1)/2) (mod p).
1615
- // (a | p) ≡ 1 if a is a square (mod p)
1616
- // (a | p) ≡ -1 if a is not a square (mod p)
1617
- // (a | p) ≡ 0 if a ≡ 0 (mod p)
1618
- const legendreC = (P - _1n$4) / _2n$2;
1619
- let Q, S, Z;
1899
+ // Do expensive precomputation step
1620
1900
  // Step 1: By factoring out powers of 2 from p - 1,
1621
- // find q and s such that p - 1 = q*(2^s) with q odd
1622
- for (Q = P - _1n$4, S = 0; Q % _2n$2 === _0n$3; Q /= _2n$2, S++)
1623
- ;
1901
+ // find q and s such that p-1 == q*(2^s) with q odd
1902
+ let Q = P - _1n$4;
1903
+ let S = 0;
1904
+ while (Q % _2n$2 === _0n$3) {
1905
+ Q /= _2n$2;
1906
+ S++;
1907
+ }
1624
1908
  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
1625
- for (Z = _2n$2; Z < P && pow(Z, legendreC, P) !== P - _1n$4; Z++)
1626
- ;
1909
+ let Z = _2n$2;
1910
+ const _Fp = Field(P);
1911
+ while (Z < P && FpIsSquare(_Fp, Z)) {
1912
+ if (Z++ > 1000)
1913
+ throw new Error('Cannot find square root: probably non-prime P');
1914
+ }
1627
1915
  // Fast-path
1628
1916
  if (S === 1) {
1629
1917
  const p1div4 = (P + _1n$4) / _4n;
@@ -1638,16 +1926,18 @@ function tonelliShanks(P) {
1638
1926
  const Q1div2 = (Q + _1n$4) / _2n$2;
1639
1927
  return function tonelliSlow(Fp, n) {
1640
1928
  // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
1641
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
1929
+ if (!FpIsSquare(Fp, n))
1642
1930
  throw new Error('Cannot find square root');
1643
1931
  let r = S;
1644
- // TODO: will fail at Fp2/etc
1932
+ // TODO: test on Fp2 and others
1645
1933
  let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
1646
1934
  let x = Fp.pow(n, Q1div2); // first guess at the square root
1647
1935
  let b = Fp.pow(n, Q); // first guess at the fudge factor
1648
1936
  while (!Fp.eql(b, Fp.ONE)) {
1937
+ // (4. If t = 0, return r = 0)
1938
+ // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
1649
1939
  if (Fp.eql(b, Fp.ZERO))
1650
- return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
1940
+ return Fp.ZERO;
1651
1941
  // Find m such b^(2^m)==1
1652
1942
  let m = 1;
1653
1943
  for (let t2 = Fp.sqr(b); m < r; m++) {
@@ -1655,7 +1945,8 @@ function tonelliShanks(P) {
1655
1945
  break;
1656
1946
  t2 = Fp.sqr(t2); // t2 *= t2
1657
1947
  }
1658
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
1948
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
1949
+ // otherwise there will be overflow.
1659
1950
  const ge = Fp.pow(g, _1n$4 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
1660
1951
  g = Fp.sqr(ge); // g = ge * ge
1661
1952
  x = Fp.mul(x, ge); // x *= ge
@@ -1665,9 +1956,18 @@ function tonelliShanks(P) {
1665
1956
  return x;
1666
1957
  };
1667
1958
  }
1959
+ /**
1960
+ * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
1961
+ *
1962
+ * 1. P ≡ 3 (mod 4)
1963
+ * 2. P ≡ 5 (mod 8)
1964
+ * 3. P ≡ 9 (mod 16)
1965
+ * 4. Tonelli-Shanks algorithm
1966
+ *
1967
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
1968
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1969
+ */
1668
1970
  function FpSqrt(P) {
1669
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
1670
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
1671
1971
  // P ≡ 3 (mod 4)
1672
1972
  // √n = n^((P+1)/4)
1673
1973
  if (P % _4n === _3n$1) {
@@ -1675,8 +1975,8 @@ function FpSqrt(P) {
1675
1975
  // const ORDER =
1676
1976
  // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
1677
1977
  // const NUM = 72057594037927816n;
1678
- const p1div4 = (P + _1n$4) / _4n;
1679
1978
  return function sqrt3mod4(Fp, n) {
1979
+ const p1div4 = (P + _1n$4) / _4n;
1680
1980
  const root = Fp.pow(n, p1div4);
1681
1981
  // Throw if root**2 != n
1682
1982
  if (!Fp.eql(Fp.sqr(root), n))
@@ -1686,9 +1986,9 @@ function FpSqrt(P) {
1686
1986
  }
1687
1987
  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
1688
1988
  if (P % _8n === _5n) {
1689
- const c1 = (P - _5n) / _8n;
1690
1989
  return function sqrt5mod8(Fp, n) {
1691
1990
  const n2 = Fp.mul(n, _2n$2);
1991
+ const c1 = (P - _5n) / _8n;
1692
1992
  const v = Fp.pow(n2, c1);
1693
1993
  const nv = Fp.mul(n, v);
1694
1994
  const i = Fp.mul(Fp.mul(nv, _2n$2), v);
@@ -1725,66 +2025,92 @@ function validateField(field) {
1725
2025
  * Same as `pow` but for Fp: non-constant-time.
1726
2026
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
1727
2027
  */
1728
- function FpPow(f, num, power) {
1729
- // Should have same speed as pow for bigints
1730
- // TODO: benchmark!
2028
+ function FpPow(Fp, num, power) {
1731
2029
  if (power < _0n$3)
1732
- throw new Error('Expected power > 0');
2030
+ throw new Error('invalid exponent, negatives unsupported');
1733
2031
  if (power === _0n$3)
1734
- return f.ONE;
2032
+ return Fp.ONE;
1735
2033
  if (power === _1n$4)
1736
2034
  return num;
1737
- let p = f.ONE;
2035
+ // @ts-ignore
2036
+ let p = Fp.ONE;
1738
2037
  let d = num;
1739
2038
  while (power > _0n$3) {
1740
2039
  if (power & _1n$4)
1741
- p = f.mul(p, d);
1742
- d = f.sqr(d);
2040
+ p = Fp.mul(p, d);
2041
+ d = Fp.sqr(d);
1743
2042
  power >>= _1n$4;
1744
2043
  }
1745
2044
  return p;
1746
2045
  }
1747
2046
  /**
1748
2047
  * Efficiently invert an array of Field elements.
1749
- * `inv(0)` will return `undefined` here: make sure to throw an error.
2048
+ * Exception-free. Will return `undefined` for 0 elements.
2049
+ * @param passZero map 0 to 0 (instead of undefined)
1750
2050
  */
1751
- function FpInvertBatch(f, nums) {
1752
- const tmp = new Array(nums.length);
2051
+ function FpInvertBatch(Fp, nums, passZero = false) {
2052
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
1753
2053
  // Walk from first to last, multiply them by each other MOD p
1754
- const lastMultiplied = nums.reduce((acc, num, i) => {
1755
- if (f.is0(num))
2054
+ const multipliedAcc = nums.reduce((acc, num, i) => {
2055
+ if (Fp.is0(num))
1756
2056
  return acc;
1757
- tmp[i] = acc;
1758
- return f.mul(acc, num);
1759
- }, f.ONE);
2057
+ inverted[i] = acc;
2058
+ return Fp.mul(acc, num);
2059
+ }, Fp.ONE);
1760
2060
  // Invert last element
1761
- const inverted = f.inv(lastMultiplied);
2061
+ const invertedAcc = Fp.inv(multipliedAcc);
1762
2062
  // Walk from last to first, multiply them by inverted each other MOD p
1763
2063
  nums.reduceRight((acc, num, i) => {
1764
- if (f.is0(num))
2064
+ if (Fp.is0(num))
1765
2065
  return acc;
1766
- tmp[i] = f.mul(acc, tmp[i]);
1767
- return f.mul(acc, num);
1768
- }, inverted);
1769
- return tmp;
2066
+ inverted[i] = Fp.mul(acc, inverted[i]);
2067
+ return Fp.mul(acc, num);
2068
+ }, invertedAcc);
2069
+ return inverted;
2070
+ }
2071
+ /**
2072
+ * Legendre symbol.
2073
+ * Legendre constant is used to calculate Legendre symbol (a | p)
2074
+ * which denotes the value of a^((p-1)/2) (mod p)..
2075
+ *
2076
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
2077
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
2078
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
2079
+ */
2080
+ function FpLegendre(Fp, n) {
2081
+ const legc = (Fp.ORDER - _1n$4) / _2n$2;
2082
+ const powered = Fp.pow(n, legc);
2083
+ const yes = Fp.eql(powered, Fp.ONE);
2084
+ const zero = Fp.eql(powered, Fp.ZERO);
2085
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
2086
+ if (!yes && !zero && !no)
2087
+ throw new Error('Cannot find square root: probably non-prime P');
2088
+ return yes ? 1 : zero ? 0 : -1;
2089
+ }
2090
+ // This function returns True whenever the value x is a square in the field F.
2091
+ function FpIsSquare(Fp, n) {
2092
+ const l = FpLegendre(Fp, n);
2093
+ return l === 0 || l === 1;
1770
2094
  }
1771
2095
  // CURVE.n lengths
1772
2096
  function nLength(n, nBitLength) {
1773
2097
  // Bit size, byte size of CURVE.n
2098
+ if (nBitLength !== undefined)
2099
+ anumber(nBitLength);
1774
2100
  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
1775
2101
  const nByteLength = Math.ceil(_nBitLength / 8);
1776
2102
  return { nBitLength: _nBitLength, nByteLength };
1777
2103
  }
1778
2104
  /**
1779
- * Initializes a finite field over prime. **Non-primes are not supported.**
1780
- * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
2105
+ * Initializes a finite field over prime.
1781
2106
  * Major performance optimizations:
1782
2107
  * * a) denormalized operations like mulN instead of mul
1783
2108
  * * b) same object shape: never add or remove keys
1784
2109
  * * c) Object.freeze
1785
- * NOTE: operations don't check 'isValid' for all elements for performance reasons,
2110
+ * Fragile: always run a benchmark on a change.
2111
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
1786
2112
  * it is caller responsibility to check this.
1787
- * This is low-level code, please make sure you know what you doing.
2113
+ * This is low-level code, please make sure you know what you're doing.
1788
2114
  * @param ORDER prime positive bigint
1789
2115
  * @param bitLen how many bits the field consumes
1790
2116
  * @param isLE (def: false) if encoding / decoding should be in little-endian
@@ -1792,13 +2118,14 @@ function nLength(n, nBitLength) {
1792
2118
  */
1793
2119
  function Field(ORDER, bitLen, isLE = false, redef = {}) {
1794
2120
  if (ORDER <= _0n$3)
1795
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
2121
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
1796
2122
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
1797
2123
  if (BYTES > 2048)
1798
- throw new Error('Field lengths over 2048 bytes are not supported');
1799
- const sqrtP = FpSqrt(ORDER);
2124
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
2125
+ let sqrtP; // cached sqrtP
1800
2126
  const f = Object.freeze({
1801
2127
  ORDER,
2128
+ isLE,
1802
2129
  BITS,
1803
2130
  BYTES,
1804
2131
  MASK: bitMask(BITS),
@@ -1807,7 +2134,7 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1807
2134
  create: (num) => mod(num, ORDER),
1808
2135
  isValid: (num) => {
1809
2136
  if (typeof num !== 'bigint')
1810
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
2137
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
1811
2138
  return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1812
2139
  },
1813
2140
  is0: (num) => num === _0n$3,
@@ -1826,17 +2153,23 @@ function Field(ORDER, bitLen, isLE = false, redef = {}) {
1826
2153
  subN: (lhs, rhs) => lhs - rhs,
1827
2154
  mulN: (lhs, rhs) => lhs * rhs,
1828
2155
  inv: (num) => invert(num, ORDER),
1829
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
1830
- invertBatch: (lst) => FpInvertBatch(f, lst),
1831
- // TODO: do we really need constant cmov?
1832
- // We don't have const-time bigints anyway, so probably will be not very useful
1833
- cmov: (a, b, c) => (c ? b : a),
2156
+ sqrt: redef.sqrt ||
2157
+ ((n) => {
2158
+ if (!sqrtP)
2159
+ sqrtP = FpSqrt(ORDER);
2160
+ return sqrtP(f, n);
2161
+ }),
1834
2162
  toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
1835
2163
  fromBytes: (bytes) => {
1836
2164
  if (bytes.length !== BYTES)
1837
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
2165
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
1838
2166
  return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1839
2167
  },
2168
+ // TODO: we don't need it here, move out to separate fn
2169
+ invertBatch: (lst) => FpInvertBatch(f, lst),
2170
+ // We can't move this out because Fp6, Fp12 implement it
2171
+ // and it's unclear what to return in there.
2172
+ cmov: (a, b, c) => (c ? b : a),
1840
2173
  });
1841
2174
  return Object.freeze(f);
1842
2175
  }
@@ -1882,52 +2215,106 @@ function mapHashToField(key, fieldOrder, isLE = false) {
1882
2215
  const minLen = getMinHashLength(fieldOrder);
1883
2216
  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
1884
2217
  if (len < 16 || len < minLen || len > 1024)
1885
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
1886
- const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
2218
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
2219
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1887
2220
  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
1888
2221
  const reduced = mod(num, fieldOrder - _1n$4) + _1n$4;
1889
2222
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1890
2223
  }
1891
2224
 
2225
+ /**
2226
+ * Methods for elliptic curve multiplication by scalars.
2227
+ * Contains wNAF, pippenger
2228
+ * @module
2229
+ */
1892
2230
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1893
- // Abelian group utilities
1894
2231
  const _0n$2 = BigInt(0);
1895
2232
  const _1n$3 = BigInt(1);
2233
+ function constTimeNegate(condition, item) {
2234
+ const neg = item.negate();
2235
+ return condition ? neg : item;
2236
+ }
2237
+ function validateW(W, bits) {
2238
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
2239
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
2240
+ }
2241
+ function calcWOpts(W, scalarBits) {
2242
+ validateW(W, scalarBits);
2243
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
2244
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
2245
+ const maxNumber = 2 ** W; // W=8 256
2246
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
2247
+ const shiftBy = BigInt(W); // W=8 8
2248
+ return { windows, windowSize, mask, maxNumber, shiftBy };
2249
+ }
2250
+ function calcOffsets(n, window, wOpts) {
2251
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
2252
+ let wbits = Number(n & mask); // extract W bits.
2253
+ let nextN = n >> shiftBy; // shift number by W bits.
2254
+ // What actually happens here:
2255
+ // const highestBit = Number(mask ^ (mask >> 1n));
2256
+ // let wbits2 = wbits - 1; // skip zero
2257
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
2258
+ // split if bits > max: +224 => 256-32
2259
+ if (wbits > windowSize) {
2260
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
2261
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
2262
+ nextN += _1n$3; // +256 (carry)
2263
+ }
2264
+ const offsetStart = window * windowSize;
2265
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
2266
+ const isZero = wbits === 0; // is current window slice a 0?
2267
+ const isNeg = wbits < 0; // is current window slice negative?
2268
+ const isNegF = window % 2 !== 0; // fake random statement for noise
2269
+ const offsetF = offsetStart; // fake offset for noise
2270
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
2271
+ }
2272
+ function validateMSMPoints(points, c) {
2273
+ if (!Array.isArray(points))
2274
+ throw new Error('array expected');
2275
+ points.forEach((p, i) => {
2276
+ if (!(p instanceof c))
2277
+ throw new Error('invalid point at index ' + i);
2278
+ });
2279
+ }
2280
+ function validateMSMScalars(scalars, field) {
2281
+ if (!Array.isArray(scalars))
2282
+ throw new Error('array of scalars expected');
2283
+ scalars.forEach((s, i) => {
2284
+ if (!field.isValid(s))
2285
+ throw new Error('invalid scalar at index ' + i);
2286
+ });
2287
+ }
1896
2288
  // Since points in different groups cannot be equal (different object constructor),
1897
- // we can have single place to store precomputes
2289
+ // we can have single place to store precomputes.
2290
+ // Allows to make points frozen / immutable.
1898
2291
  const pointPrecomputes = new WeakMap();
1899
- const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)
1900
- // Elliptic curve multiplication of Point by scalar. Fragile.
1901
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
1902
- // Creates precomputation tables for fast multiplication:
1903
- // - private scalar is split by fixed size windows of W bits
1904
- // - every window point is collected from window's table & added to accumulator
1905
- // - since windows are different, same point inside tables won't be accessed more than once per calc
1906
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1907
- // - +1 window is neccessary for wNAF
1908
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1909
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
1910
- // windows to be in different memory locations
2292
+ const pointWindowSizes = new WeakMap();
2293
+ function getW(P) {
2294
+ return pointWindowSizes.get(P) || 1;
2295
+ }
2296
+ /**
2297
+ * Elliptic curve multiplication of Point by scalar. Fragile.
2298
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
2299
+ * Creates precomputation tables for fast multiplication:
2300
+ * - private scalar is split by fixed size windows of W bits
2301
+ * - every window point is collected from window's table & added to accumulator
2302
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
2303
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
2304
+ * - +1 window is neccessary for wNAF
2305
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
2306
+ *
2307
+ * @todo Research returning 2d JS array of windows, instead of a single window.
2308
+ * This would allow windows to be in different memory locations
2309
+ */
1911
2310
  function wNAF(c, bits) {
1912
- const constTimeNegate = (condition, item) => {
1913
- const neg = item.negate();
1914
- return condition ? neg : item;
1915
- };
1916
- const validateW = (W) => {
1917
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1918
- throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
1919
- };
1920
- const opts = (W) => {
1921
- validateW(W);
1922
- const windows = Math.ceil(bits / W) + 1; // +1, because
1923
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
1924
- return { windows, windowSize };
1925
- };
1926
2311
  return {
1927
2312
  constTimeNegate,
2313
+ hasPrecomputes(elm) {
2314
+ return getW(elm) !== 1;
2315
+ },
1928
2316
  // non-const time multiplication ladder
1929
- unsafeLadder(elm, n) {
1930
- let p = c.ZERO;
2317
+ unsafeLadder(elm, n, p = c.ZERO) {
1931
2318
  let d = elm;
1932
2319
  while (n > _0n$2) {
1933
2320
  if (n & _1n$3)
@@ -1945,17 +2332,19 @@ function wNAF(c, bits) {
1945
2332
  * - 𝑊 is the window size
1946
2333
  * - 𝑛 is the bitlength of the curve order.
1947
2334
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
2335
+ * @param elm Point instance
2336
+ * @param W window size
1948
2337
  * @returns precomputed point tables flattened to a single array
1949
2338
  */
1950
2339
  precomputeWindow(elm, W) {
1951
- const { windows, windowSize } = opts(W);
2340
+ const { windows, windowSize } = calcWOpts(W, bits);
1952
2341
  const points = [];
1953
2342
  let p = elm;
1954
2343
  let base = p;
1955
2344
  for (let window = 0; window < windows; window++) {
1956
2345
  base = p;
1957
2346
  points.push(base);
1958
- // =1, because we skip zero
2347
+ // i=1, bc we skip 0
1959
2348
  for (let i = 1; i < windowSize; i++) {
1960
2349
  base = base.add(p);
1961
2350
  points.push(base);
@@ -1972,54 +2361,67 @@ function wNAF(c, bits) {
1972
2361
  * @returns real and fake (for const-time) points
1973
2362
  */
1974
2363
  wNAF(W, precomputes, n) {
1975
- // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
1976
- // But need to carefully remove other checks before wNAF. ORDER == bits here
1977
- const { windows, windowSize } = opts(W);
2364
+ // Smaller version:
2365
+ // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
2366
+ // TODO: check the scalar is less than group order?
2367
+ // wNAF behavior is undefined otherwise. But have to carefully remove
2368
+ // other checks before wNAF. ORDER == bits here.
2369
+ // Accumulators
1978
2370
  let p = c.ZERO;
1979
2371
  let f = c.BASE;
1980
- const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
1981
- const maxNumber = 2 ** W;
1982
- const shiftBy = BigInt(W);
1983
- for (let window = 0; window < windows; window++) {
1984
- const offset = window * windowSize;
1985
- // Extract W bits.
1986
- let wbits = Number(n & mask);
1987
- // Shift number by W bits.
1988
- n >>= shiftBy;
1989
- // If the bits are bigger than max size, we'll split those.
1990
- // +224 => 256 - 32
1991
- if (wbits > windowSize) {
1992
- wbits -= maxNumber;
1993
- n += _1n$3;
1994
- }
1995
- // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1996
- // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1997
- // there is negate now: it is possible that negated element from low value
1998
- // would be the same as high element, which will create carry into next window.
1999
- // It's not obvious how this can fail, but still worth investigating later.
2000
- // Check if we're onto Zero point.
2001
- // Add random point inside current window to f.
2002
- const offset1 = offset;
2003
- const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
2004
- const cond1 = window % 2 !== 0;
2005
- const cond2 = wbits < 0;
2006
- if (wbits === 0) {
2007
- // The most important part for const-time getPublicKey
2008
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
2372
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
2373
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
2374
+ // there is negate now: it is possible that negated element from low value
2375
+ // would be the same as high element, which will create carry into next window.
2376
+ // It's not obvious how this can fail, but still worth investigating later.
2377
+ const wo = calcWOpts(W, bits);
2378
+ for (let window = 0; window < wo.windows; window++) {
2379
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
2380
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
2381
+ n = nextN;
2382
+ if (isZero) {
2383
+ // bits are 0: add garbage to fake point
2384
+ // Important part for const-time getPublicKey: add random "noise" point to f.
2385
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
2009
2386
  }
2010
2387
  else {
2011
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
2388
+ // bits are 1: add to result point
2389
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
2012
2390
  }
2013
2391
  }
2014
- // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
2015
- // Even if the variable is still unused, there are some checks which will
2016
- // throw an exception, so compiler needs to prove they won't happen, which is hard.
2392
+ // Return both real and fake points: JIT won't eliminate f.
2017
2393
  // At this point there is a way to F be infinity-point even if p is not,
2018
2394
  // which makes it less const-time: around 1 bigint multiply.
2019
2395
  return { p, f };
2020
2396
  },
2021
- wNAFCached(P, n, transform) {
2022
- const W = pointWindowSizes.get(P) || 1;
2397
+ /**
2398
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
2399
+ * @param W window size
2400
+ * @param precomputes precomputed tables
2401
+ * @param n scalar (we don't check here, but should be less than curve order)
2402
+ * @param acc accumulator point to add result of multiplication
2403
+ * @returns point
2404
+ */
2405
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
2406
+ const wo = calcWOpts(W, bits);
2407
+ for (let window = 0; window < wo.windows; window++) {
2408
+ if (n === _0n$2)
2409
+ break; // Early-exit, skip 0 value
2410
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
2411
+ n = nextN;
2412
+ if (isZero) {
2413
+ // Window bits are 0: skip processing.
2414
+ // Move to next window.
2415
+ continue;
2416
+ }
2417
+ else {
2418
+ const item = precomputes[offset];
2419
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
2420
+ }
2421
+ }
2422
+ return acc;
2423
+ },
2424
+ getPrecomputes(W, P, transform) {
2023
2425
  // Calculate precomputes on a first run, reuse them after
2024
2426
  let comp = pointPrecomputes.get(P);
2025
2427
  if (!comp) {
@@ -2027,62 +2429,66 @@ function wNAF(c, bits) {
2027
2429
  if (W !== 1)
2028
2430
  pointPrecomputes.set(P, transform(comp));
2029
2431
  }
2030
- return this.wNAF(W, comp, n);
2432
+ return comp;
2433
+ },
2434
+ wNAFCached(P, n, transform) {
2435
+ const W = getW(P);
2436
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
2437
+ },
2438
+ wNAFCachedUnsafe(P, n, transform, prev) {
2439
+ const W = getW(P);
2440
+ if (W === 1)
2441
+ return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
2442
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
2031
2443
  },
2032
2444
  // We calculate precomputes for elliptic curve point multiplication
2033
2445
  // using windowed method. This specifies window size and
2034
2446
  // stores precomputed values. Usually only base point would be precomputed.
2035
2447
  setWindowSize(P, W) {
2036
- validateW(W);
2448
+ validateW(W, bits);
2037
2449
  pointWindowSizes.set(P, W);
2038
2450
  pointPrecomputes.delete(P);
2039
2451
  },
2040
2452
  };
2041
2453
  }
2042
2454
  /**
2043
- * Pippenger algorithm for multi-scalar multiplication (MSM).
2044
- * MSM is basically (Pa + Qb + Rc + ...).
2045
- * 30x faster vs naive addition on L=4096, 10x faster with precomputes.
2455
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
2456
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
2046
2457
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
2047
2458
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
2048
2459
  * @param c Curve Point constructor
2049
- * @param field field over CURVE.N - important that it's not over CURVE.P
2460
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
2050
2461
  * @param points array of L curve points
2051
2462
  * @param scalars array of L scalars (aka private keys / bigints)
2052
2463
  */
2053
- function pippenger(c, field, points, scalars) {
2464
+ function pippenger(c, fieldN, points, scalars) {
2054
2465
  // If we split scalars by some window (let's say 8 bits), every chunk will only
2055
2466
  // take 256 buckets even if there are 4096 scalars, also re-uses double.
2056
2467
  // TODO:
2057
2468
  // - https://eprint.iacr.org/2024/750.pdf
2058
2469
  // - https://tches.iacr.org/index.php/TCHES/article/view/10287
2059
2470
  // 0 is accepted in scalars
2060
- if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
2471
+ validateMSMPoints(points, c);
2472
+ validateMSMScalars(scalars, fieldN);
2473
+ if (points.length !== scalars.length)
2061
2474
  throw new Error('arrays of points and scalars must have equal length');
2062
- scalars.forEach((s, i) => {
2063
- if (!field.isValid(s))
2064
- throw new Error(`wrong scalar at index ${i}`);
2065
- });
2066
- points.forEach((p, i) => {
2067
- if (!(p instanceof c))
2068
- throw new Error(`wrong point at index ${i}`);
2069
- });
2475
+ const zero = c.ZERO;
2070
2476
  const wbits = bitLen(BigInt(points.length));
2071
2477
  const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
2072
- const MASK = (1 << windowSize) - 1;
2073
- const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
2074
- const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
2075
- let sum = c.ZERO;
2478
+ const MASK = bitMask(windowSize);
2479
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
2480
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
2481
+ let sum = zero;
2076
2482
  for (let i = lastBits; i >= 0; i -= windowSize) {
2077
- buckets.fill(c.ZERO);
2483
+ buckets.fill(zero);
2078
2484
  for (let j = 0; j < scalars.length; j++) {
2079
2485
  const scalar = scalars[j];
2080
- const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
2486
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
2081
2487
  buckets[wbits] = buckets[wbits].add(points[j]);
2082
2488
  }
2083
- let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
2489
+ let resI = zero; // not using this will do small speed-up, but will lose ct
2084
2490
  // Skip first bucket, because it is zero
2085
- for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
2491
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
2086
2492
  sumI = sumI.add(buckets[j]);
2087
2493
  resI = resI.add(sumI);
2088
2494
  }
@@ -2112,8 +2518,47 @@ function validateBasic(curve) {
2112
2518
  });
2113
2519
  }
2114
2520
 
2521
+ /**
2522
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
2523
+ *
2524
+ * ### Parameters
2525
+ *
2526
+ * To initialize a weierstrass curve, one needs to pass following params:
2527
+ *
2528
+ * * a: formula param
2529
+ * * b: formula param
2530
+ * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
2531
+ * * n: Curve prime subgroup order, total count of valid points in the field
2532
+ * * Gx: Base point (x, y) aka generator point x coordinate
2533
+ * * Gy: ...y coordinate
2534
+ * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
2535
+ * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
2536
+ *
2537
+ * ### Design rationale for types
2538
+ *
2539
+ * * Interaction between classes from different curves should fail:
2540
+ * `k256.Point.BASE.add(p256.Point.BASE)`
2541
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
2542
+ * * Different calls of `curve()` would return different classes -
2543
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
2544
+ * it won't affect others
2545
+ *
2546
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
2547
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
2548
+ * unique type for every function call.
2549
+ *
2550
+ * We can use generic types via some param, like curve opts, but that would:
2551
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
2552
+ * which is hard to debug.
2553
+ * 2. Params can be generic and we can't enforce them to be constant value:
2554
+ * if somebody creates curve from non-constant params,
2555
+ * it would be allowed to interact with other curves with non-constant params
2556
+ *
2557
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
2558
+ * @module
2559
+ */
2115
2560
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2116
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
2561
+ // prettier-ignore
2117
2562
  function validateSigVerOpts(opts) {
2118
2563
  if (opts.lowS !== undefined)
2119
2564
  abool('lowS', opts.lowS);
@@ -2137,17 +2582,21 @@ function validatePointOpts(curve) {
2137
2582
  const { endo, Fp, a } = opts;
2138
2583
  if (endo) {
2139
2584
  if (!Fp.eql(a, Fp.ZERO)) {
2140
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
2585
+ throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
2141
2586
  }
2142
2587
  if (typeof endo !== 'object' ||
2143
2588
  typeof endo.beta !== 'bigint' ||
2144
2589
  typeof endo.splitScalar !== 'function') {
2145
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
2590
+ throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
2146
2591
  }
2147
2592
  }
2148
2593
  return Object.freeze({ ...opts });
2149
2594
  }
2150
- const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
2595
+ class DERErr extends Error {
2596
+ constructor(m = '') {
2597
+ super(m);
2598
+ }
2599
+ }
2151
2600
  /**
2152
2601
  * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
2153
2602
  *
@@ -2157,11 +2606,7 @@ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
2157
2606
  */
2158
2607
  const DER = {
2159
2608
  // asn.1 DER encoding utils
2160
- Err: class DERErr extends Error {
2161
- constructor(m = '') {
2162
- super(m);
2163
- }
2164
- },
2609
+ Err: DERErr,
2165
2610
  // Basic building block is TLV (Tag-Length-Value)
2166
2611
  _tlv: {
2167
2612
  encode: (tag, data) => {
@@ -2176,7 +2621,8 @@ const DER = {
2176
2621
  throw new E('tlv.encode: long form length too big');
2177
2622
  // length of length with long form flag
2178
2623
  const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
2179
- return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
2624
+ const t = numberToHexUnpadded(tag);
2625
+ return t + lenLen + len + data;
2180
2626
  },
2181
2627
  // v - value, l - left bytes (unparsed)
2182
2628
  decode(tag, data) {
@@ -2229,35 +2675,36 @@ const DER = {
2229
2675
  if (Number.parseInt(hex[0], 16) & 0b1000)
2230
2676
  hex = '00' + hex;
2231
2677
  if (hex.length & 1)
2232
- throw new E('unexpected assertion');
2678
+ throw new E('unexpected DER parsing assertion: unpadded hex');
2233
2679
  return hex;
2234
2680
  },
2235
2681
  decode(data) {
2236
2682
  const { Err: E } = DER;
2237
2683
  if (data[0] & 128)
2238
- throw new E('Invalid signature integer: negative');
2684
+ throw new E('invalid signature integer: negative');
2239
2685
  if (data[0] === 0x00 && !(data[1] & 128))
2240
- throw new E('Invalid signature integer: unnecessary leading zero');
2241
- return b2n(data);
2686
+ throw new E('invalid signature integer: unnecessary leading zero');
2687
+ return bytesToNumberBE(data);
2242
2688
  },
2243
2689
  },
2244
2690
  toSig(hex) {
2245
2691
  // parse DER signature
2246
2692
  const { Err: E, _int: int, _tlv: tlv } = DER;
2247
- const data = typeof hex === 'string' ? h2b(hex) : hex;
2248
- abytes(data);
2693
+ const data = ensureBytes('signature', hex);
2249
2694
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
2250
2695
  if (seqLeftBytes.length)
2251
- throw new E('Invalid signature: left bytes after parsing');
2696
+ throw new E('invalid signature: left bytes after parsing');
2252
2697
  const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
2253
2698
  const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
2254
2699
  if (sLeftBytes.length)
2255
- throw new E('Invalid signature: left bytes after parsing');
2700
+ throw new E('invalid signature: left bytes after parsing');
2256
2701
  return { r: int.decode(rBytes), s: int.decode(sBytes) };
2257
2702
  },
2258
2703
  hexFromSig(sig) {
2259
2704
  const { _tlv: tlv, _int: int } = DER;
2260
- const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
2705
+ const rs = tlv.encode(0x02, int.encode(sig.r));
2706
+ const ss = tlv.encode(0x02, int.encode(sig.s));
2707
+ const seq = rs + ss;
2261
2708
  return tlv.encode(0x30, seq);
2262
2709
  },
2263
2710
  };
@@ -2283,7 +2730,7 @@ function weierstrassPoints(opts) {
2283
2730
  return { x, y };
2284
2731
  });
2285
2732
  /**
2286
- * y² = x³ + ax + b: Short weierstrass curve formula
2733
+ * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
2287
2734
  * @returns y²
2288
2735
  */
2289
2736
  function weierstrassEquation(x) {
@@ -2311,7 +2758,7 @@ function weierstrassPoints(opts) {
2311
2758
  key = bytesToHex(key);
2312
2759
  // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
2313
2760
  if (typeof key !== 'string' || !lengths.includes(key.length))
2314
- throw new Error('Invalid key');
2761
+ throw new Error('invalid private key');
2315
2762
  key = key.padStart(nByteLength * 2, '0');
2316
2763
  }
2317
2764
  let num;
@@ -2322,14 +2769,14 @@ function weierstrassPoints(opts) {
2322
2769
  : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
2323
2770
  }
2324
2771
  catch (error) {
2325
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
2772
+ throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
2326
2773
  }
2327
2774
  if (wrapPrivateKey)
2328
2775
  num = mod(num, N); // disabled by default, enabled for BLS
2329
2776
  aInRange('private key', num, _1n$2, N); // num in range [1..N-1]
2330
2777
  return num;
2331
2778
  }
2332
- function assertPrjPoint(other) {
2779
+ function aprjpoint(other) {
2333
2780
  if (!(other instanceof Point))
2334
2781
  throw new Error('ProjectivePoint expected');
2335
2782
  }
@@ -2362,7 +2809,7 @@ function weierstrassPoints(opts) {
2362
2809
  if (p.is0()) {
2363
2810
  // (0, 1, 0) aka ZERO is invalid in most contexts.
2364
2811
  // In BLS, ZERO can be serialized, so we allow it.
2365
- // (0, 0, 0) is wrong representation of ZERO and is always invalid.
2812
+ // (0, 0, 0) is invalid representation of ZERO.
2366
2813
  if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
2367
2814
  return;
2368
2815
  throw new Error('bad point: ZERO');
@@ -2387,15 +2834,15 @@ function weierstrassPoints(opts) {
2387
2834
  */
2388
2835
  class Point {
2389
2836
  constructor(px, py, pz) {
2390
- this.px = px;
2391
- this.py = py;
2392
- this.pz = pz;
2393
2837
  if (px == null || !Fp.isValid(px))
2394
2838
  throw new Error('x required');
2395
- if (py == null || !Fp.isValid(py))
2839
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
2396
2840
  throw new Error('y required');
2397
2841
  if (pz == null || !Fp.isValid(pz))
2398
2842
  throw new Error('z required');
2843
+ this.px = px;
2844
+ this.py = py;
2845
+ this.pz = pz;
2399
2846
  Object.freeze(this);
2400
2847
  }
2401
2848
  // Does not validate if the point is on-curve.
@@ -2425,7 +2872,7 @@ function weierstrassPoints(opts) {
2425
2872
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
2426
2873
  */
2427
2874
  static normalizeZ(points) {
2428
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
2875
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
2429
2876
  return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
2430
2877
  }
2431
2878
  /**
@@ -2463,7 +2910,7 @@ function weierstrassPoints(opts) {
2463
2910
  * Compare one point to another.
2464
2911
  */
2465
2912
  equals(other) {
2466
- assertPrjPoint(other);
2913
+ aprjpoint(other);
2467
2914
  const { px: X1, py: Y1, pz: Z1 } = this;
2468
2915
  const { px: X2, py: Y2, pz: Z2 } = other;
2469
2916
  const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
@@ -2523,7 +2970,7 @@ function weierstrassPoints(opts) {
2523
2970
  // https://eprint.iacr.org/2015/1060, algorithm 1
2524
2971
  // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2525
2972
  add(other) {
2526
- assertPrjPoint(other);
2973
+ aprjpoint(other);
2527
2974
  const { px: X1, py: Y1, pz: Z1 } = this;
2528
2975
  const { px: X2, py: Y2, pz: Z2 } = other;
2529
2976
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
@@ -2586,16 +3033,17 @@ function weierstrassPoints(opts) {
2586
3033
  * an exposed private key e.g. sig verification, which works over *public* keys.
2587
3034
  */
2588
3035
  multiplyUnsafe(sc) {
2589
- aInRange('scalar', sc, _0n$1, CURVE.n);
3036
+ const { endo, n: N } = CURVE;
3037
+ aInRange('scalar', sc, _0n$1, N);
2590
3038
  const I = Point.ZERO;
2591
3039
  if (sc === _0n$1)
2592
3040
  return I;
2593
- if (sc === _1n$2)
3041
+ if (this.is0() || sc === _1n$2)
2594
3042
  return this;
2595
- const { endo } = CURVE;
2596
- if (!endo)
2597
- return wnaf.unsafeLadder(this, sc);
2598
- // Apply endomorphism
3043
+ // Case a: no endomorphism. Case b: has precomputes.
3044
+ if (!endo || wnaf.hasPrecomputes(this))
3045
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
3046
+ // Case c: endomorphism
2599
3047
  let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
2600
3048
  let k1p = I;
2601
3049
  let k2p = I;
@@ -2693,10 +3141,9 @@ function weierstrassPoints(opts) {
2693
3141
  }
2694
3142
  }
2695
3143
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2696
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
3144
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
2697
3145
  const _bits = CURVE.nBitLength;
2698
3146
  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
2699
- // Validate if generator point is on curve
2700
3147
  return {
2701
3148
  CURVE,
2702
3149
  ProjectivePoint: Point,
@@ -2781,11 +3228,13 @@ function weierstrass(curveDef) {
2781
3228
  return { x, y };
2782
3229
  }
2783
3230
  else {
2784
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
3231
+ const cl = compressedLen;
3232
+ const ul = uncompressedLen;
3233
+ throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
2785
3234
  }
2786
3235
  },
2787
3236
  });
2788
- const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
3237
+ const numToNByteHex = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
2789
3238
  function isBiggerThanHalfOrder(number) {
2790
3239
  const HALF = CURVE_ORDER >> _1n$2;
2791
3240
  return number > HALF;
@@ -2800,10 +3249,13 @@ function weierstrass(curveDef) {
2800
3249
  */
2801
3250
  class Signature {
2802
3251
  constructor(r, s, recovery) {
3252
+ aInRange('r', r, _1n$2, CURVE_ORDER); // r in [1..N]
3253
+ aInRange('s', s, _1n$2, CURVE_ORDER); // s in [1..N]
2803
3254
  this.r = r;
2804
3255
  this.s = s;
2805
- this.recovery = recovery;
2806
- this.assertValidity();
3256
+ if (recovery != null)
3257
+ this.recovery = recovery;
3258
+ Object.freeze(this);
2807
3259
  }
2808
3260
  // pair (bytes of r, bytes of s)
2809
3261
  static fromCompact(hex) {
@@ -2817,10 +3269,11 @@ function weierstrass(curveDef) {
2817
3269
  const { r, s } = DER.toSig(ensureBytes('DER', hex));
2818
3270
  return new Signature(r, s);
2819
3271
  }
2820
- assertValidity() {
2821
- aInRange('r', this.r, _1n$2, CURVE_ORDER); // r in [1..N]
2822
- aInRange('s', this.s, _1n$2, CURVE_ORDER); // s in [1..N]
2823
- }
3272
+ /**
3273
+ * @todo remove
3274
+ * @deprecated
3275
+ */
3276
+ assertValidity() { }
2824
3277
  addRecoveryBit(recovery) {
2825
3278
  return new Signature(this.r, this.s, recovery);
2826
3279
  }
@@ -2833,7 +3286,7 @@ function weierstrass(curveDef) {
2833
3286
  if (radj >= Fp.ORDER)
2834
3287
  throw new Error('recovery id 2 or 3 invalid');
2835
3288
  const prefix = (rec & 1) === 0 ? '02' : '03';
2836
- const R = Point.fromHex(prefix + numToNByteStr(radj));
3289
+ const R = Point.fromHex(prefix + numToNByteHex(radj));
2837
3290
  const ir = invN(radj); // r^-1
2838
3291
  const u1 = modN(-h * ir); // -hr^-1
2839
3292
  const u2 = modN(s * ir); // sr^-1
@@ -2852,17 +3305,17 @@ function weierstrass(curveDef) {
2852
3305
  }
2853
3306
  // DER-encoded
2854
3307
  toDERRawBytes() {
2855
- return hexToBytes(this.toDERHex());
3308
+ return hexToBytes$1(this.toDERHex());
2856
3309
  }
2857
3310
  toDERHex() {
2858
- return DER.hexFromSig({ r: this.r, s: this.s });
3311
+ return DER.hexFromSig(this);
2859
3312
  }
2860
3313
  // padded bytes of r, then padded bytes of s
2861
3314
  toCompactRawBytes() {
2862
- return hexToBytes(this.toCompactHex());
3315
+ return hexToBytes$1(this.toCompactHex());
2863
3316
  }
2864
3317
  toCompactHex() {
2865
- return numToNByteStr(this.r) + numToNByteStr(this.s);
3318
+ return numToNByteHex(this.r) + numToNByteHex(this.s);
2866
3319
  }
2867
3320
  }
2868
3321
  const utils = {
@@ -2946,6 +3399,9 @@ function weierstrass(curveDef) {
2946
3399
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
2947
3400
  const bits2int = CURVE.bits2int ||
2948
3401
  function (bytes) {
3402
+ // Our custom check "just in case"
3403
+ if (bytes.length > 8192)
3404
+ throw new Error('input is too large');
2949
3405
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
2950
3406
  // for some cases, since bytes.length * 8 is not actual bitLength.
2951
3407
  const num = bytesToNumberBE(bytes); // check for == u8 done here
@@ -2962,15 +3418,15 @@ function weierstrass(curveDef) {
2962
3418
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
2963
3419
  */
2964
3420
  function int2octets(num) {
2965
- aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$1, ORDER_MASK);
3421
+ aInRange('num < 2^' + CURVE.nBitLength, num, _0n$1, ORDER_MASK);
2966
3422
  // works with order, can have different size than numToField!
2967
3423
  return numberToBytesBE(num, CURVE.nByteLength);
2968
3424
  }
2969
3425
  // Steps A, D of RFC6979 3.2
2970
3426
  // Creates RFC6979 seed; converts msg/privKey to numbers.
2971
3427
  // Used only in sign, not in verify.
2972
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
2973
- // Also it can be bigger for P224 + SHA256
3428
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
3429
+ // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
2974
3430
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
2975
3431
  if (['recovered', 'canonical'].some((k) => k in opts))
2976
3432
  throw new Error('sign() legacy options not supported');
@@ -3064,39 +3520,48 @@ function weierstrass(curveDef) {
3064
3520
  const sg = signature;
3065
3521
  msgHash = ensureBytes('msgHash', msgHash);
3066
3522
  publicKey = ensureBytes('publicKey', publicKey);
3523
+ const { lowS, prehash, format } = opts;
3524
+ // Verify opts, deduce signature format
3525
+ validateSigVerOpts(opts);
3067
3526
  if ('strict' in opts)
3068
3527
  throw new Error('options.strict was renamed to lowS');
3069
- validateSigVerOpts(opts);
3070
- const { lowS, prehash } = opts;
3528
+ if (format !== undefined && format !== 'compact' && format !== 'der')
3529
+ throw new Error('format must be compact or der');
3530
+ const isHex = typeof sg === 'string' || isBytes$1(sg);
3531
+ const isObj = !isHex &&
3532
+ !format &&
3533
+ typeof sg === 'object' &&
3534
+ sg !== null &&
3535
+ typeof sg.r === 'bigint' &&
3536
+ typeof sg.s === 'bigint';
3537
+ if (!isHex && !isObj)
3538
+ throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
3071
3539
  let _sig = undefined;
3072
3540
  let P;
3073
3541
  try {
3074
- if (typeof sg === 'string' || isBytes$1(sg)) {
3542
+ if (isObj)
3543
+ _sig = new Signature(sg.r, sg.s);
3544
+ if (isHex) {
3075
3545
  // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
3076
3546
  // Since DER can also be 2*nByteLength bytes, we check for it first.
3077
3547
  try {
3078
- _sig = Signature.fromDER(sg);
3548
+ if (format !== 'compact')
3549
+ _sig = Signature.fromDER(sg);
3079
3550
  }
3080
3551
  catch (derError) {
3081
3552
  if (!(derError instanceof DER.Err))
3082
3553
  throw derError;
3083
- _sig = Signature.fromCompact(sg);
3084
3554
  }
3085
- }
3086
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
3087
- const { r, s } = sg;
3088
- _sig = new Signature(r, s);
3089
- }
3090
- else {
3091
- throw new Error('PARSE');
3555
+ if (!_sig && format !== 'der')
3556
+ _sig = Signature.fromCompact(sg);
3092
3557
  }
3093
3558
  P = Point.fromHex(publicKey);
3094
3559
  }
3095
3560
  catch (error) {
3096
- if (error.message === 'PARSE')
3097
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
3098
3561
  return false;
3099
3562
  }
3563
+ if (!_sig)
3564
+ return false;
3100
3565
  if (lowS && _sig.hasHighS())
3101
3566
  return false;
3102
3567
  if (prehash)
@@ -3124,8 +3589,12 @@ function weierstrass(curveDef) {
3124
3589
  };
3125
3590
  }
3126
3591
 
3592
+ /**
3593
+ * Utilities for short weierstrass curves, combined with noble-hashes.
3594
+ * @module
3595
+ */
3127
3596
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3128
- // connects noble-curves to noble-hashes
3597
+ /** connects noble-curves to noble-hashes */
3129
3598
  function getHash(hash) {
3130
3599
  return {
3131
3600
  hash,
@@ -3135,9 +3604,21 @@ function getHash(hash) {
3135
3604
  }
3136
3605
  function createCurve(curveDef, defHash) {
3137
3606
  const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
3138
- return Object.freeze({ ...create(defHash), create });
3607
+ return { ...create(defHash), create };
3139
3608
  }
3140
3609
 
3610
+ /**
3611
+ * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
3612
+ *
3613
+ * Seems to be rigid (not backdoored)
3614
+ * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
3615
+ *
3616
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3617
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3618
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3619
+ * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
3620
+ * @module
3621
+ */
3141
3622
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3142
3623
  const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
3143
3624
  const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
@@ -3168,145 +3649,103 @@ function sqrtMod(y) {
3168
3649
  const t1 = (pow2(b223, _23n, P) * b22) % P;
3169
3650
  const t2 = (pow2(t1, _6n, P) * b2) % P;
3170
3651
  const root = pow2(t2, _2n$1, P);
3171
- if (!Fp.eql(Fp.sqr(root), y))
3652
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3172
3653
  throw new Error('Cannot find square root');
3173
3654
  return root;
3174
3655
  }
3175
- const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3656
+ const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
3176
3657
  /**
3177
- * secp256k1 short weierstrass curve and ECDSA signatures over it.
3658
+ * secp256k1 curve, ECDSA and ECDH methods.
3659
+ *
3660
+ * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
3661
+ *
3662
+ * @example
3663
+ * ```js
3664
+ * import { secp256k1 } from '@noble/curves/secp256k1';
3665
+ * const priv = secp256k1.utils.randomPrivateKey();
3666
+ * const pub = secp256k1.getPublicKey(priv);
3667
+ * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
3668
+ * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
3669
+ * const isValid = secp256k1.verify(sig, msg, pub) === true;
3670
+ * ```
3178
3671
  */
3179
3672
  const secp256k1 = createCurve({
3180
- a: BigInt(0), // equation params: a, b
3181
- b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
3182
- Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
3183
- n: secp256k1N, // Curve order, total count of valid points in the field
3184
- // Base point (x, y) aka generator point
3673
+ a: BigInt(0),
3674
+ b: BigInt(7),
3675
+ Fp: Fpk1,
3676
+ n: secp256k1N,
3185
3677
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
3186
3678
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
3187
- h: BigInt(1), // Cofactor
3679
+ h: BigInt(1),
3188
3680
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
3189
- /**
3190
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
3191
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
3192
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
3193
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
3194
- */
3195
3681
  endo: {
3682
+ // Endomorphism, see above
3196
3683
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
3197
3684
  splitScalar: (k) => {
3198
- const n = secp256k1N;
3199
- const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
3200
- const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
3201
- const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
3202
- const b2 = a1;
3203
- const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
3204
- const c1 = divNearest(b2 * k, n);
3205
- const c2 = divNearest(-b1 * k, n);
3206
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
3207
- let k2 = mod(-c1 * b1 - c2 * b2, n);
3208
- const k1neg = k1 > POW_2_128;
3209
- const k2neg = k2 > POW_2_128;
3210
- if (k1neg)
3211
- k1 = n - k1;
3212
- if (k2neg)
3213
- k2 = n - k2;
3214
- if (k1 > POW_2_128 || k2 > POW_2_128) {
3215
- throw new Error('splitScalar: Endomorphism failed, k=' + k);
3216
- }
3217
- return { k1neg, k1, k2neg, k2 };
3218
- },
3219
- },
3220
- }, sha256);
3221
- // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3222
- // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3223
- BigInt(0);
3224
- secp256k1.ProjectivePoint;
3225
-
3226
- /**
3227
- * Generate publicKey from the privateKey.
3228
- * This creates the uncompressed publicKey,
3229
- * where 04 has stripped from left
3230
- * @returns {string}
3231
- */
3232
- const publicKeyByPrivateKey = (privateKey) => {
3233
- const key = stripHexPrefix(privateKey);
3234
- const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
3235
- const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
3236
- return decompress(bytesToHex$1(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
3237
- };
3238
-
3239
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
3240
- const _32n = /* @__PURE__ */ BigInt(32);
3241
- // We are not using BigUint64Array, because they are extremely slow as per 2022
3242
- function fromBig(n, le = false) {
3243
- if (le)
3244
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
3245
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
3246
- }
3247
- function split(lst, le = false) {
3248
- let Ah = new Uint32Array(lst.length);
3249
- let Al = new Uint32Array(lst.length);
3250
- for (let i = 0; i < lst.length; i++) {
3251
- const { h, l } = fromBig(lst[i], le);
3252
- [Ah[i], Al[i]] = [h, l];
3253
- }
3254
- return [Ah, Al];
3255
- }
3256
- const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
3257
- // for Shift in [0, 32)
3258
- const shrSH = (h, _l, s) => h >>> s;
3259
- const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
3260
- // Right rotate for Shift in [1, 32)
3261
- const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
3262
- const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
3263
- // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
3264
- const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
3265
- const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
3266
- // Right rotate for shift===32 (just swaps l&h)
3267
- const rotr32H = (_h, l) => l;
3268
- const rotr32L = (h, _l) => h;
3269
- // Left rotate for Shift in [1, 32)
3270
- const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
3271
- const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
3272
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
3273
- const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
3274
- const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
3275
- // JS uses 32-bit signed integers for bitwise operations which means we cannot
3276
- // simple take carry out of low bit sum by shift, we need to use division.
3277
- function add(Ah, Al, Bh, Bl) {
3278
- const l = (Al >>> 0) + (Bl >>> 0);
3279
- return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
3280
- }
3281
- // Addition with more than 2 elements
3282
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
3283
- const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
3284
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
3285
- const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
3286
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
3287
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
3288
- // prettier-ignore
3289
- const u64 = {
3290
- fromBig, split, toBig,
3291
- shrSH, shrSL,
3292
- rotrSH, rotrSL, rotrBH, rotrBL,
3293
- rotr32H, rotr32L,
3294
- rotlSH, rotlSL, rotlBH, rotlBL,
3295
- add, add3L, add3H, add4L, add4H, add5H, add5L,
3685
+ const n = secp256k1N;
3686
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
3687
+ const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
3688
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
3689
+ const b2 = a1;
3690
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
3691
+ const c1 = divNearest(b2 * k, n);
3692
+ const c2 = divNearest(-b1 * k, n);
3693
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
3694
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
3695
+ const k1neg = k1 > POW_2_128;
3696
+ const k2neg = k2 > POW_2_128;
3697
+ if (k1neg)
3698
+ k1 = n - k1;
3699
+ if (k2neg)
3700
+ k2 = n - k2;
3701
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
3702
+ throw new Error('splitScalar: Endomorphism failed, k=' + k);
3703
+ }
3704
+ return { k1neg, k1, k2neg, k2 };
3705
+ },
3706
+ },
3707
+ }, sha256);
3708
+ // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
3709
+ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
3710
+ BigInt(0);
3711
+ secp256k1.ProjectivePoint;
3712
+
3713
+ /**
3714
+ * Generate publicKey from the privateKey.
3715
+ * This creates the uncompressed publicKey,
3716
+ * where 04 has stripped from left
3717
+ * @returns {string}
3718
+ */
3719
+ const publicKeyByPrivateKey = (privateKey) => {
3720
+ const key = stripHexPrefix(privateKey);
3721
+ const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
3722
+ const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
3723
+ return decompress(bytesToHex$1(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
3296
3724
  };
3297
3725
 
3298
- // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
3299
- // It's called a sponge function.
3726
+ /**
3727
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
3728
+ * Different from older hashes, the internal state is bigger than output size.
3729
+ *
3730
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
3731
+ * [Website](https://keccak.team/keccak.html),
3732
+ * [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).
3733
+ *
3734
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
3735
+ * @module
3736
+ */
3737
+ // No __PURE__ annotations in sha3 header:
3738
+ // EVERYTHING is in fact used on every export.
3300
3739
  // Various per round constants calculations
3740
+ const _0n = BigInt(0);
3741
+ const _1n = BigInt(1);
3742
+ const _2n = BigInt(2);
3743
+ const _7n = BigInt(7);
3744
+ const _256n = BigInt(256);
3745
+ const _0x71n = BigInt(0x71);
3301
3746
  const SHA3_PI = [];
3302
3747
  const SHA3_ROTL = [];
3303
3748
  const _SHA3_IOTA = [];
3304
- const _0n = /* @__PURE__ */ BigInt(0);
3305
- const _1n = /* @__PURE__ */ BigInt(1);
3306
- const _2n = /* @__PURE__ */ BigInt(2);
3307
- const _7n = /* @__PURE__ */ BigInt(7);
3308
- const _256n = /* @__PURE__ */ BigInt(256);
3309
- const _0x71n = /* @__PURE__ */ BigInt(0x71);
3310
3749
  for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
3311
3750
  // Pi
3312
3751
  [x, y] = [y, (2 * x + 3 * y) % 5];
@@ -3322,11 +3761,13 @@ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
3322
3761
  }
3323
3762
  _SHA3_IOTA.push(t);
3324
3763
  }
3325
- const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);
3764
+ const IOTAS = split(_SHA3_IOTA, true);
3765
+ const SHA3_IOTA_H = IOTAS[0];
3766
+ const SHA3_IOTA_L = IOTAS[1];
3326
3767
  // Left rotation (without 0, 32, 64)
3327
3768
  const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
3328
3769
  const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
3329
- // Same as keccakf1600, but allows to skip some rounds
3770
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
3330
3771
  function keccakP(s, rounds = 24) {
3331
3772
  const B = new Uint32Array(5 * 2);
3332
3773
  // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
@@ -3370,42 +3811,47 @@ function keccakP(s, rounds = 24) {
3370
3811
  s[0] ^= SHA3_IOTA_H[round];
3371
3812
  s[1] ^= SHA3_IOTA_L[round];
3372
3813
  }
3373
- B.fill(0);
3814
+ clean$1(B);
3374
3815
  }
3816
+ /** Keccak sponge function. */
3375
3817
  class Keccak extends Hash {
3376
3818
  // NOTE: we accept arguments in bytes instead of bits here.
3377
3819
  constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
3378
3820
  super();
3821
+ this.pos = 0;
3822
+ this.posOut = 0;
3823
+ this.finished = false;
3824
+ this.destroyed = false;
3825
+ this.enableXOF = false;
3379
3826
  this.blockLen = blockLen;
3380
3827
  this.suffix = suffix;
3381
3828
  this.outputLen = outputLen;
3382
3829
  this.enableXOF = enableXOF;
3383
3830
  this.rounds = rounds;
3384
- this.pos = 0;
3385
- this.posOut = 0;
3386
- this.finished = false;
3387
- this.destroyed = false;
3388
3831
  // Can be passed from user as dkLen
3389
- number(outputLen);
3832
+ anumber(outputLen);
3390
3833
  // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
3391
- if (0 >= this.blockLen || this.blockLen >= 200)
3392
- throw new Error('Sha3 supports only keccak-f1600 function');
3834
+ // 0 < blockLen < 200
3835
+ if (!(0 < blockLen && blockLen < 200))
3836
+ throw new Error('only keccak-f1600 function is supported');
3393
3837
  this.state = new Uint8Array(200);
3394
3838
  this.state32 = u32$1(this.state);
3395
3839
  }
3840
+ clone() {
3841
+ return this._cloneInto();
3842
+ }
3396
3843
  keccak() {
3397
- if (!isLE$1)
3398
- byteSwap32(this.state32);
3844
+ swap32IfBE(this.state32);
3399
3845
  keccakP(this.state32, this.rounds);
3400
- if (!isLE$1)
3401
- byteSwap32(this.state32);
3846
+ swap32IfBE(this.state32);
3402
3847
  this.posOut = 0;
3403
3848
  this.pos = 0;
3404
3849
  }
3405
3850
  update(data) {
3406
- exists(this);
3407
- const { blockLen, state } = this;
3851
+ aexists(this);
3408
3852
  data = toBytes(data);
3853
+ abytes$3(data);
3854
+ const { blockLen, state } = this;
3409
3855
  const len = data.length;
3410
3856
  for (let pos = 0; pos < len;) {
3411
3857
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -3429,8 +3875,8 @@ class Keccak extends Hash {
3429
3875
  this.keccak();
3430
3876
  }
3431
3877
  writeInto(out) {
3432
- exists(this, false);
3433
- bytes$1(out);
3878
+ aexists(this, false);
3879
+ abytes$3(out);
3434
3880
  this.finish();
3435
3881
  const bufferOut = this.state;
3436
3882
  const { blockLen } = this;
@@ -3451,11 +3897,11 @@ class Keccak extends Hash {
3451
3897
  return this.writeInto(out);
3452
3898
  }
3453
3899
  xof(bytes) {
3454
- number(bytes);
3900
+ anumber(bytes);
3455
3901
  return this.xofInto(new Uint8Array(bytes));
3456
3902
  }
3457
3903
  digestInto(out) {
3458
- output$1(out, this);
3904
+ aoutput(out, this);
3459
3905
  if (this.finished)
3460
3906
  throw new Error('digest() was already called');
3461
3907
  this.writeInto(out);
@@ -3467,7 +3913,7 @@ class Keccak extends Hash {
3467
3913
  }
3468
3914
  destroy() {
3469
3915
  this.destroyed = true;
3470
- this.state.fill(0);
3916
+ clean$1(this.state);
3471
3917
  }
3472
3918
  _cloneInto(to) {
3473
3919
  const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
@@ -3485,12 +3931,9 @@ class Keccak extends Hash {
3485
3931
  return to;
3486
3932
  }
3487
3933
  }
3488
- const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));
3489
- /**
3490
- * keccak-256 hash function. Different from SHA3-256.
3491
- * @param message - that would be hashed
3492
- */
3493
- const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);
3934
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
3935
+ /** keccak-256 hash function. Different from SHA3-256. */
3936
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
3494
3937
 
3495
3938
  const keccak256$1 = (() => {
3496
3939
  const k = wrapHash(keccak_256);
@@ -3543,162 +3986,6 @@ const createIdentity = (entropy) => {
3543
3986
  return identity;
3544
3987
  };
3545
3988
 
3546
- // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
3547
- // prettier-ignore
3548
- const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
3549
- '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
3550
- '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
3551
- '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
3552
- '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
3553
- '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
3554
- '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
3555
- '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
3556
- '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
3557
- '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
3558
- '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
3559
- '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
3560
- '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
3561
- '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
3562
- '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
3563
- '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
3564
- '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
3565
- '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
3566
- '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
3567
- '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
3568
- '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
3569
- ].map(n => BigInt(n))))();
3570
- // Temporary buffer, not used to store anything between runs
3571
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
3572
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
3573
- class SHA512 extends HashMD {
3574
- constructor() {
3575
- super(128, 64, 16, false);
3576
- // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
3577
- // Also looks cleaner and easier to verify with spec.
3578
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
3579
- // h -- high 32 bits, l -- low 32 bits
3580
- this.Ah = 0x6a09e667 | 0;
3581
- this.Al = 0xf3bcc908 | 0;
3582
- this.Bh = 0xbb67ae85 | 0;
3583
- this.Bl = 0x84caa73b | 0;
3584
- this.Ch = 0x3c6ef372 | 0;
3585
- this.Cl = 0xfe94f82b | 0;
3586
- this.Dh = 0xa54ff53a | 0;
3587
- this.Dl = 0x5f1d36f1 | 0;
3588
- this.Eh = 0x510e527f | 0;
3589
- this.El = 0xade682d1 | 0;
3590
- this.Fh = 0x9b05688c | 0;
3591
- this.Fl = 0x2b3e6c1f | 0;
3592
- this.Gh = 0x1f83d9ab | 0;
3593
- this.Gl = 0xfb41bd6b | 0;
3594
- this.Hh = 0x5be0cd19 | 0;
3595
- this.Hl = 0x137e2179 | 0;
3596
- }
3597
- // prettier-ignore
3598
- get() {
3599
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3600
- return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
3601
- }
3602
- // prettier-ignore
3603
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
3604
- this.Ah = Ah | 0;
3605
- this.Al = Al | 0;
3606
- this.Bh = Bh | 0;
3607
- this.Bl = Bl | 0;
3608
- this.Ch = Ch | 0;
3609
- this.Cl = Cl | 0;
3610
- this.Dh = Dh | 0;
3611
- this.Dl = Dl | 0;
3612
- this.Eh = Eh | 0;
3613
- this.El = El | 0;
3614
- this.Fh = Fh | 0;
3615
- this.Fl = Fl | 0;
3616
- this.Gh = Gh | 0;
3617
- this.Gl = Gl | 0;
3618
- this.Hh = Hh | 0;
3619
- this.Hl = Hl | 0;
3620
- }
3621
- process(view, offset) {
3622
- // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
3623
- for (let i = 0; i < 16; i++, offset += 4) {
3624
- SHA512_W_H[i] = view.getUint32(offset);
3625
- SHA512_W_L[i] = view.getUint32((offset += 4));
3626
- }
3627
- for (let i = 16; i < 80; i++) {
3628
- // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
3629
- const W15h = SHA512_W_H[i - 15] | 0;
3630
- const W15l = SHA512_W_L[i - 15] | 0;
3631
- const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
3632
- const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
3633
- // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
3634
- const W2h = SHA512_W_H[i - 2] | 0;
3635
- const W2l = SHA512_W_L[i - 2] | 0;
3636
- const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
3637
- const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
3638
- // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
3639
- const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
3640
- const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
3641
- SHA512_W_H[i] = SUMh | 0;
3642
- SHA512_W_L[i] = SUMl | 0;
3643
- }
3644
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
3645
- // Compression function main loop, 80 rounds
3646
- for (let i = 0; i < 80; i++) {
3647
- // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
3648
- const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
3649
- const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
3650
- //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3651
- const CHIh = (Eh & Fh) ^ (~Eh & Gh);
3652
- const CHIl = (El & Fl) ^ (~El & Gl);
3653
- // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
3654
- // prettier-ignore
3655
- const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
3656
- const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
3657
- const T1l = T1ll | 0;
3658
- // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
3659
- const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
3660
- const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
3661
- const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
3662
- const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
3663
- Hh = Gh | 0;
3664
- Hl = Gl | 0;
3665
- Gh = Fh | 0;
3666
- Gl = Fl | 0;
3667
- Fh = Eh | 0;
3668
- Fl = El | 0;
3669
- ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
3670
- Dh = Ch | 0;
3671
- Dl = Cl | 0;
3672
- Ch = Bh | 0;
3673
- Cl = Bl | 0;
3674
- Bh = Ah | 0;
3675
- Bl = Al | 0;
3676
- const All = u64.add3L(T1l, sigma0l, MAJl);
3677
- Ah = u64.add3H(All, T1h, sigma0h, MAJh);
3678
- Al = All | 0;
3679
- }
3680
- // Add the compressed chunk to the current hash value
3681
- ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
3682
- ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
3683
- ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
3684
- ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
3685
- ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
3686
- ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
3687
- ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
3688
- ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
3689
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
3690
- }
3691
- roundClean() {
3692
- SHA512_W_H.fill(0);
3693
- SHA512_W_L.fill(0);
3694
- }
3695
- destroy() {
3696
- this.buffer.fill(0);
3697
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
3698
- }
3699
- }
3700
- const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
3701
-
3702
3989
  /**
3703
3990
  * signs the given message
3704
3991
  * @param {string} privateKey
@@ -3709,7 +3996,7 @@ const sign = (privateKey, hash) => {
3709
3996
  const hashWith0x = addLeading0x(hash);
3710
3997
  if (hashWith0x.length !== 66 || !isHexString(hashWith0x))
3711
3998
  throw new Error('Can only sign hashes, given: ' + hash);
3712
- const sigObj = secp256k1.sign(hexToBytes$1(stripHexPrefix(hash)), hexToBytes$1(stripHexPrefix(privateKey)));
3999
+ const sigObj = secp256k1.sign(hexToBytes(stripHexPrefix(hash)), hexToBytes(stripHexPrefix(privateKey)));
3713
4000
  const recoveryId = sigObj.recovery === 1 ? '1c' : '1b';
3714
4001
  const newSignature = '0x' + sigObj.toCompactHex() + recoveryId;
3715
4002
  return newSignature;
@@ -3721,33 +4008,129 @@ const hmacSha256Sign = (key, msg) => {
3721
4008
 
3722
4009
  const sha512 = wrapHash(sha512$1);
3723
4010
 
4011
+ /**
4012
+ * Utilities for hex, bytes, CSPRNG.
4013
+ * @module
4014
+ */
4015
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
4016
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
3724
4017
  function isBytes(a) {
3725
- return (a instanceof Uint8Array ||
3726
- (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
4018
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
3727
4019
  }
3728
- function bytes(b, ...lengths) {
4020
+ /** Asserts something is Uint8Array. */
4021
+ function abytes(b, ...lengths) {
3729
4022
  if (!isBytes(b))
3730
4023
  throw new Error('Uint8Array expected');
3731
4024
  if (lengths.length > 0 && !lengths.includes(b.length))
3732
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
4025
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
3733
4026
  }
3734
-
3735
- /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3736
- // Cast array to different type
3737
- const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3738
- const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3739
- // big-endian hardware is rare. Just in case someone still decides to run ciphers:
3740
- // early-throw an error because we don't support BE yet.
3741
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
3742
- if (!isLE)
3743
- throw new Error('Non little-endian hardware is not supported');
4027
+ /** Cast u8 / u16 / u32 to u8. */
4028
+ function u8(arr) {
4029
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
4030
+ }
4031
+ /** Cast u8 / u16 / u32 to u32. */
4032
+ function u32(arr) {
4033
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
4034
+ }
4035
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
4036
+ function clean(...arrays) {
4037
+ for (let i = 0; i < arrays.length; i++) {
4038
+ arrays[i].fill(0);
4039
+ }
4040
+ }
4041
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
4042
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
3744
4043
  /**
4044
+ * Checks if two U8A use same underlying buffer and overlaps.
4045
+ * This is invalid and can corrupt data.
4046
+ */
4047
+ function overlapBytes(a, b) {
4048
+ return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
4049
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
4050
+ b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
4051
+ );
4052
+ }
4053
+ /**
4054
+ * If input and output overlap and input starts before output, we will overwrite end of input before
4055
+ * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
4056
+ */
4057
+ function complexOverlapBytes(input, output) {
4058
+ // This is very cursed. It works somehow, but I'm completely unsure,
4059
+ // reasoning about overlapping aligned windows is very hard.
4060
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
4061
+ throw new Error('complex overlap of input and output is not supported');
4062
+ }
4063
+ /**
4064
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
3745
4065
  * @__NO_SIDE_EFFECTS__
3746
4066
  */
3747
- const wrapCipher = (params, c) => {
3748
- Object.assign(c, params);
3749
- return c;
4067
+ const wrapCipher = (params, constructor) => {
4068
+ function wrappedCipher(key, ...args) {
4069
+ // Validate key
4070
+ abytes(key);
4071
+ // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
4072
+ if (!isLE)
4073
+ throw new Error('Non little-endian hardware is not yet supported');
4074
+ // Validate nonce if nonceLength is present
4075
+ if (params.nonceLength !== undefined) {
4076
+ const nonce = args[0];
4077
+ if (!nonce)
4078
+ throw new Error('nonce / iv required');
4079
+ if (params.varSizeNonce)
4080
+ abytes(nonce);
4081
+ else
4082
+ abytes(nonce, params.nonceLength);
4083
+ }
4084
+ // Validate AAD if tagLength present
4085
+ const tagl = params.tagLength;
4086
+ if (tagl && args[1] !== undefined) {
4087
+ abytes(args[1]);
4088
+ }
4089
+ const cipher = constructor(key, ...args);
4090
+ const checkOutput = (fnLength, output) => {
4091
+ if (output !== undefined) {
4092
+ if (fnLength !== 2)
4093
+ throw new Error('cipher output not supported');
4094
+ abytes(output);
4095
+ }
4096
+ };
4097
+ // Create wrapped cipher with validation and single-use encryption
4098
+ let called = false;
4099
+ const wrCipher = {
4100
+ encrypt(data, output) {
4101
+ if (called)
4102
+ throw new Error('cannot encrypt() twice with same key + nonce');
4103
+ called = true;
4104
+ abytes(data);
4105
+ checkOutput(cipher.encrypt.length, output);
4106
+ return cipher.encrypt(data, output);
4107
+ },
4108
+ decrypt(data, output) {
4109
+ abytes(data);
4110
+ if (tagl && data.length < tagl)
4111
+ throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
4112
+ checkOutput(cipher.decrypt.length, output);
4113
+ return cipher.decrypt(data, output);
4114
+ },
4115
+ };
4116
+ return wrCipher;
4117
+ }
4118
+ Object.assign(wrappedCipher, params);
4119
+ return wrappedCipher;
3750
4120
  };
4121
+ /**
4122
+ * By default, returns u8a of length.
4123
+ * When out is available, it checks it for validity and uses it.
4124
+ */
4125
+ function getOutput(expectedLength, out, onlyAligned = true) {
4126
+ if (out === undefined)
4127
+ return new Uint8Array(expectedLength);
4128
+ if (out.length !== expectedLength)
4129
+ throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
4130
+ if (onlyAligned && !isAligned32(out))
4131
+ throw new Error('invalid output, must be aligned');
4132
+ return out;
4133
+ }
3751
4134
  // Is byte array aligned to 4 byte offset (u32)?
3752
4135
  function isAligned32(bytes) {
3753
4136
  return bytes.byteOffset % 4 === 0;
@@ -3756,26 +4139,23 @@ function isAligned32(bytes) {
3756
4139
  function copyBytes(bytes) {
3757
4140
  return Uint8Array.from(bytes);
3758
4141
  }
3759
- function clean(...arrays) {
3760
- for (let i = 0; i < arrays.length; i++) {
3761
- arrays[i].fill(0);
3762
- }
3763
- }
3764
-
3765
- // prettier-ignore
3766
- /*
3767
- AES (Advanced Encryption Standard) aka Rijndael block cipher.
3768
4142
 
3769
- Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
3770
- 1. **S-box**, table substitution
3771
- 2. **Shift rows**, cyclic shift left of all rows of data array
3772
- 3. **Mix columns**, multiplying every column by fixed polynomial
3773
- 4. **Add round key**, round_key xor i-th column of array
3774
-
3775
- Resources:
3776
- - FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf
3777
- - Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf
3778
- */
4143
+ /**
4144
+ * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
4145
+ * a.k.a. Advanced Encryption Standard
4146
+ * is a variant of Rijndael block cipher, standardized by NIST in 2001.
4147
+ * We provide the fastest available pure JS implementation.
4148
+ *
4149
+ * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
4150
+ * 1. **S-box**, table substitution
4151
+ * 2. **Shift rows**, cyclic shift left of all rows of data array
4152
+ * 3. **Mix columns**, multiplying every column by fixed polynomial
4153
+ * 4. **Add round key**, round_key xor i-th column of array
4154
+ *
4155
+ * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
4156
+ * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
4157
+ * @module
4158
+ */
3779
4159
  const BLOCK_SIZE = 16;
3780
4160
  const BLOCK_SIZE32 = 4;
3781
4161
  const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
@@ -3845,11 +4225,12 @@ const xPowers = /* @__PURE__ */ (() => {
3845
4225
  p[i] = x;
3846
4226
  return p;
3847
4227
  })();
4228
+ /** Key expansion used in CTR. */
3848
4229
  function expandKeyLE(key) {
3849
- bytes(key);
4230
+ abytes(key);
3850
4231
  const len = key.length;
3851
4232
  if (![16, 24, 32].includes(len))
3852
- throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);
4233
+ throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
3853
4234
  const { sbox2 } = tableEncoding;
3854
4235
  const toClean = [];
3855
4236
  if (!isAligned32(key))
@@ -3939,22 +4320,13 @@ function decrypt$2(xk, s0, s1, s2, s3) {
3939
4320
  const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
3940
4321
  return { s0: t0, s1: t1, s2: t2, s3: t3 };
3941
4322
  }
3942
- function getDst(len, dst) {
3943
- if (dst === undefined)
3944
- return new Uint8Array(len);
3945
- bytes(dst);
3946
- if (dst.length < len)
3947
- throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);
3948
- if (!isAligned32(dst))
3949
- throw new Error('unaligned dst');
3950
- return dst;
3951
- }
3952
4323
  // TODO: investigate merging with ctr32
3953
4324
  function ctrCounter(xk, nonce, src, dst) {
3954
- bytes(nonce, BLOCK_SIZE);
3955
- bytes(src);
4325
+ abytes(nonce, BLOCK_SIZE);
4326
+ abytes(src);
3956
4327
  const srcLen = src.length;
3957
- dst = getDst(srcLen, dst);
4328
+ dst = getOutput(srcLen, dst);
4329
+ complexOverlapBytes(src, dst);
3958
4330
  const ctr = nonce;
3959
4331
  const c32 = u32(ctr);
3960
4332
  // Fill block (empty, ctr=0)
@@ -3992,13 +4364,11 @@ function ctrCounter(xk, nonce, src, dst) {
3992
4364
  * CTR: counter mode. Creates stream cipher.
3993
4365
  * Requires good IV. Parallelizable. OK, but no MAC.
3994
4366
  */
3995
- const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {
3996
- bytes(key);
3997
- bytes(nonce, BLOCK_SIZE);
4367
+ const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
3998
4368
  function processCtr(buf, dst) {
3999
- bytes(buf);
4369
+ abytes(buf);
4000
4370
  if (dst !== undefined) {
4001
- bytes(dst);
4371
+ abytes(dst);
4002
4372
  if (!isAligned32(dst))
4003
4373
  throw new Error('unaligned destination');
4004
4374
  }
@@ -4017,13 +4387,13 @@ const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, non
4017
4387
  };
4018
4388
  });
4019
4389
  function validateBlockDecrypt(data) {
4020
- bytes(data);
4390
+ abytes(data);
4021
4391
  if (data.length % BLOCK_SIZE !== 0) {
4022
- throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);
4392
+ throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
4023
4393
  }
4024
4394
  }
4025
4395
  function validateBlockEncrypt(plaintext, pcks5, dst) {
4026
- bytes(plaintext);
4396
+ abytes(plaintext);
4027
4397
  let outLen = plaintext.length;
4028
4398
  const remaining = outLen % BLOCK_SIZE;
4029
4399
  if (!pcks5 && remaining !== 0)
@@ -4037,9 +4407,10 @@ function validateBlockEncrypt(plaintext, pcks5, dst) {
4037
4407
  left = BLOCK_SIZE; // if no bytes left, create empty padding block
4038
4408
  outLen = outLen + left;
4039
4409
  }
4040
- const out = getDst(outLen, dst);
4041
- const o = u32(out);
4042
- return { b, o, out };
4410
+ dst = getOutput(outLen, dst);
4411
+ complexOverlapBytes(plaintext, dst);
4412
+ const o = u32(dst);
4413
+ return { b, o, out: dst };
4043
4414
  }
4044
4415
  function validatePCKS(data, pcks5) {
4045
4416
  if (!pcks5)
@@ -4069,9 +4440,7 @@ function padPCKS(left) {
4069
4440
  * CBC: Cipher-Block-Chaining. Key is previous round’s block.
4070
4441
  * Fragile: needs proper padding. Unauthenticated: needs MAC.
4071
4442
  */
4072
- const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {
4073
- bytes(key);
4074
- bytes(iv, 16);
4443
+ const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
4075
4444
  const pcks5 = !opts.disablePadding;
4076
4445
  return {
4077
4446
  encrypt(plaintext, dst) {
@@ -4107,11 +4476,12 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
4107
4476
  if (!isAligned32(_iv))
4108
4477
  toClean.push((_iv = copyBytes(_iv)));
4109
4478
  const n32 = u32(_iv);
4110
- const out = getDst(ciphertext.length, dst);
4479
+ dst = getOutput(ciphertext.length, dst);
4111
4480
  if (!isAligned32(ciphertext))
4112
4481
  toClean.push((ciphertext = copyBytes(ciphertext)));
4482
+ complexOverlapBytes(ciphertext, dst);
4113
4483
  const b = u32(ciphertext);
4114
- const o = u32(out);
4484
+ const o = u32(dst);
4115
4485
  // prettier-ignore
4116
4486
  let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4117
4487
  for (let i = 0; i + 4 <= b.length;) {
@@ -4122,18 +4492,18 @@ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv,
4122
4492
  (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
4123
4493
  }
4124
4494
  clean(...toClean);
4125
- return validatePCKS(out, pcks5);
4495
+ return validatePCKS(dst, pcks5);
4126
4496
  },
4127
4497
  };
4128
4498
  });
4129
- new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
4130
4499
 
4131
4500
  function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
4132
4501
  if (!mode.startsWith("aes-")) {
4133
4502
  throw new Error("AES: unsupported mode");
4134
4503
  }
4135
4504
  const len = key.length;
4136
- if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) {
4505
+ if ((mode.startsWith("aes-128") && len !== 16) ||
4506
+ (mode.startsWith("aes-256") && len !== 32)) {
4137
4507
  throw new Error("AES: wrong key length");
4138
4508
  }
4139
4509
  if (iv.length !== 16) {
@@ -4164,12 +4534,12 @@ function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnable
4164
4534
  * @returns {Encrypted} The encrypted message.
4165
4535
  */
4166
4536
  const encrypt = (publicKeyTo, msg, options) => {
4167
- const ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes$1(options.ephemPrivateKey) : getRandomBytesSync(32);
4537
+ const ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes(options.ephemPrivateKey) : getRandomBytesSync(32);
4168
4538
  const iv = getRandomBytesSync(16);
4169
4539
  const compressedPub = secp256k1.getPublicKey(ephemPrivateKey); // defaults to compressed format
4170
4540
  const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
4171
4541
  const ephemPublicKey = point.toRawBytes(false); // Get uncompressed SEC1 format pub
4172
- const sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes$1(publicKeyTo), true).slice(1);
4542
+ const sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes(publicKeyTo), true).slice(1);
4173
4543
  const hash = sha512(sharedSecret);
4174
4544
  const encryptionKey = hash.subarray(0, 32);
4175
4545
  const macKey = hash.subarray(32);
@@ -4193,7 +4563,7 @@ const encrypt = (publicKeyTo, msg, options) => {
4193
4563
  const decrypt = (privateKey, opts) => {
4194
4564
  let sharedSecret;
4195
4565
  try {
4196
- sharedSecret = secp256k1.getSharedSecret(hexToBytes$1(privateKey), opts.ephemPublicKey, true).slice(1);
4566
+ sharedSecret = secp256k1.getSharedSecret(hexToBytes(privateKey), opts.ephemPublicKey, true).slice(1);
4197
4567
  }
4198
4568
  catch (e) {
4199
4569
  throw new Error(`Invalid MAC: data integrity check failed: ${e}`);
@@ -4201,10 +4571,10 @@ const decrypt = (privateKey, opts) => {
4201
4571
  const hash = sha512(sharedSecret);
4202
4572
  const encryptionKey = hash.subarray(0, 32);
4203
4573
  const macKey = hash.subarray(32);
4204
- const ciphertext = hexToBytes$1(opts.ciphertext);
4205
- const iv = hexToBytes$1(opts.iv);
4206
- const ephemPublicKey = hexToBytes$1(opts.ephemPublicKey);
4207
- const receivedMac = hexToBytes$1(opts.mac);
4574
+ const ciphertext = hexToBytes(opts.ciphertext);
4575
+ const iv = hexToBytes(opts.iv);
4576
+ const ephemPublicKey = hexToBytes(opts.ephemPublicKey);
4577
+ const receivedMac = hexToBytes(opts.mac);
4208
4578
  // Recompute MAC
4209
4579
  const dataToMac = concatUint8Arrays([iv, ephemPublicKey, ciphertext]);
4210
4580
  const expectedMac = hmacSha256Sign(macKey, dataToMac);
@@ -4247,7 +4617,7 @@ const decryptWithPrivateKey = (privateKey, encrypted) => {
4247
4617
  const solidityPackedKeccak256 = (value) => {
4248
4618
  const bytes = utf8ToBytes(value);
4249
4619
  const hex = addLeading0x(bytesToHex$1(bytes));
4250
- const hash = keccak256$1(hexToBytes$1(hex));
4620
+ const hash = keccak256$1(hexToBytes(hex));
4251
4621
  return addLeading0x(bytesToHex$1(hash));
4252
4622
  };
4253
4623
  const keccak256 = (params) => {
@@ -4262,19 +4632,19 @@ function output(out = (len) => new Uint8Array(len), length, value) {
4262
4632
  if (typeof out === "function") {
4263
4633
  out = out(length);
4264
4634
  }
4265
- assertBytes(out, length);
4635
+ abytes$1(out, length);
4266
4636
  if (value) {
4267
4637
  out.set(value);
4268
4638
  }
4269
4639
  return out;
4270
4640
  }
4271
4641
  function getSignature(signature) {
4272
- assertBytes(signature, 64);
4642
+ abytes$1(signature, 64);
4273
4643
  return secp256k1.Signature.fromCompact(signature);
4274
4644
  }
4275
4645
  function ecdsaRecover(signature, recid, msgHash, compressed = true, out) {
4276
- assertBytes(msgHash, 32);
4277
- assertBool(compressed);
4646
+ abytes$1(msgHash, 32);
4647
+ abool("compressed", compressed);
4278
4648
  const sign = getSignature(signature);
4279
4649
  const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash);
4280
4650
  return output(out, compressed ? 33 : 65, point.toRawBytes(compressed));
@@ -4292,7 +4662,7 @@ const recoverPublicKey = (signature, hash) => {
4292
4662
  const sigOnly = noHex.substring(0, noHex.length - 2); // all but last 2 chars
4293
4663
  const vValue = noHex.slice(-2); // last 2 chars
4294
4664
  const recoveryNumber = vValue === '1c' ? 1 : 0;
4295
- let pubKey = bytesToHex$1(ecdsaRecover(hexToBytes$1(sigOnly), recoveryNumber, hexToBytes$1(stripHexPrefix(hash)), false));
4665
+ let pubKey = bytesToHex$1(ecdsaRecover(hexToBytes(sigOnly), recoveryNumber, hexToBytes(stripHexPrefix(hash)), false));
4296
4666
  // remove trailing '04'
4297
4667
  pubKey = pubKey.slice(2);
4298
4668
  return pubKey;
@@ -4321,18 +4691,22 @@ function isJsonString(str) {
4321
4691
  }
4322
4692
  }
4323
4693
 
4694
+ /**
4695
+ * PBKDF (RFC 2898). Can be used to create a key from password and salt.
4696
+ * @module
4697
+ */
4324
4698
  // Common prologue and epilogue for sync/async functions
4325
4699
  function pbkdf2Init(hash, _password, _salt, _opts) {
4326
- hash$1(hash);
4700
+ ahash(hash);
4327
4701
  const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
4328
4702
  const { c, dkLen, asyncTick } = opts;
4329
- number(c);
4330
- number(dkLen);
4331
- number(asyncTick);
4703
+ anumber(c);
4704
+ anumber(dkLen);
4705
+ anumber(asyncTick);
4332
4706
  if (c < 1)
4333
- throw new Error('PBKDF2: iterations (c) should be >= 1');
4334
- const password = toBytes(_password);
4335
- const salt = toBytes(_salt);
4707
+ throw new Error('iterations (c) should be >= 1');
4708
+ const password = kdfInputToBytes(_password);
4709
+ const salt = kdfInputToBytes(_salt);
4336
4710
  // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
4337
4711
  const DK = new Uint8Array(dkLen);
4338
4712
  // U1 = PRF(Password, Salt + INT_32_BE(i))
@@ -4345,7 +4719,7 @@ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
4345
4719
  PRFSalt.destroy();
4346
4720
  if (prfW)
4347
4721
  prfW.destroy();
4348
- u.fill(0);
4722
+ clean$1(u);
4349
4723
  return DK;
4350
4724
  }
4351
4725
  /**
@@ -4354,6 +4728,8 @@ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
4354
4728
  * @param password - password from which a derived key is generated
4355
4729
  * @param salt - cryptographic salt
4356
4730
  * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
4731
+ * @example
4732
+ * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
4357
4733
  */
4358
4734
  function pbkdf2(hash, password, salt, opts) {
4359
4735
  const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
@@ -4384,8 +4760,8 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4384
4760
  if (!["sha256", "sha512"].includes(digest)) {
4385
4761
  throw new Error("Only sha256 and sha512 are supported");
4386
4762
  }
4387
- assertBytes(password);
4388
- assertBytes(salt);
4763
+ abytes$1(password);
4764
+ abytes$1(salt);
4389
4765
  return pbkdf2(sha256 , password, salt, {
4390
4766
  c: iterations,
4391
4767
  dkLen: keylen
@@ -5405,11 +5781,11 @@ class StorageService {
5405
5781
  * @param jwt - The JWT string to check. If null, the function will return true.
5406
5782
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5407
5783
  */
5408
- function jwtHasExpired(jwt) {
5784
+ function jwtHasExpired(jwt, now = Date.now) {
5409
5785
  if (!jwt) {
5410
5786
  return true;
5411
5787
  }
5412
- return millisecondsToJWTTimeout(jwt) <= 0;
5788
+ return millisecondsToJWTTimeout(jwt, now) <= 0;
5413
5789
  }
5414
5790
  function jwtHasSameUser(jwt, userId) {
5415
5791
  if (!jwt || !userId) {
@@ -5429,11 +5805,11 @@ function userIsMfaVerified(jwt) {
5429
5805
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5430
5806
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5431
5807
  */
5432
- function isJwtNearExpiry(jwt, thresholdSeconds) {
5808
+ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5433
5809
  if (!jwt) {
5434
5810
  return false;
5435
5811
  }
5436
- return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5812
+ return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5437
5813
  }
5438
5814
  /**
5439
5815
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5441,11 +5817,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds) {
5441
5817
  * @param jwt - The JWT string to decode and check.
5442
5818
  * @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.
5443
5819
  */
5444
- function millisecondsToJWTTimeout(jwt) {
5820
+ function millisecondsToJWTTimeout(jwt, now = Date.now) {
5445
5821
  const jwtDecoded = jwtDecode(jwt);
5446
5822
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5447
5823
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5448
- const timeNowMilliseconds = Date.now();
5824
+ const timeNowMilliseconds = now();
5449
5825
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5450
5826
  }
5451
5827
 
@@ -7112,8 +7488,8 @@ const refreshDedupeManager = new DedupeManagerService();
7112
7488
  // actually contend. Global lock keys (no per-user scoping); add scoping only if multiple users share one process.
7113
7489
  const sharedLockManager = new LockManagerService();
7114
7490
  class Base {
7115
- constructor(config) {
7116
- var _a, _b;
7491
+ constructor(config, ports = {}) {
7492
+ var _a, _b, _c, _d, _e;
7117
7493
  const sanitizedConfig = sanitizeConfig(config);
7118
7494
  this.apiKey = sanitizedConfig.apiKey;
7119
7495
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -7124,7 +7500,9 @@ class Base {
7124
7500
  env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
7125
7501
  env.isWeb = !env.isNative;
7126
7502
  }
7127
- this.cipher = new Cipher();
7503
+ this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
7504
+ this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
7505
+ this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
7128
7506
  this.lockManager = sharedLockManager;
7129
7507
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
7130
7508
  this.request = this.request.bind(this);
@@ -7138,6 +7516,7 @@ class Base {
7138
7516
  secure: true, // Enable security worker for all requests by default
7139
7517
  },
7140
7518
  securityWorker: this.securityWorker.bind(this),
7519
+ customFetch: this.transport,
7141
7520
  });
7142
7521
  /**
7143
7522
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -7150,39 +7529,48 @@ class Base {
7150
7529
  return await originalRequest(params);
7151
7530
  }
7152
7531
  catch (error) {
7153
- // Reactive 401 handling for the generated client: refresh once and retry
7532
+ // Reactive 401 handling for the generated client: refresh once and retry.
7533
+ // The retry recurses and surfaces its own final error, so the intermediate
7534
+ // 401 must not be routed through toWallabyError (would double-fire onError).
7154
7535
  if (!retried && shouldAttemptTokenRefresh(error)) {
7155
7536
  await this._performTokenRefresh();
7156
7537
  // securityWorker will re-fetch the new access token on retry
7157
7538
  return attemptRequest(true);
7158
7539
  }
7159
- // Transform the generated API error format into WallabyError
7540
+ // Transform the generated API error format into WallabyError.
7541
+ // `error.error` is the parsed response body (no statusCode); the HTTP
7542
+ // status lives on the HttpResponse itself (`error.status`).
7160
7543
  if (error === null || error === void 0 ? void 0 : error.error) {
7161
7544
  const apiError = error.error;
7162
- throw new WallabyError({
7545
+ throw this.toWallabyError({
7163
7546
  message: apiError.message || 'API request failed',
7164
- statusCode: apiError.statusCode || 500,
7547
+ statusCode: apiError.statusCode || error.status || 500,
7165
7548
  errorCode: apiError.errorCode,
7166
7549
  data: apiError,
7167
7550
  });
7168
7551
  }
7169
- // Re-throw if already a WallabyError
7552
+ // Already a WallabyError (e.g. a pre-send guard from securityWorker) — propagate as-is.
7170
7553
  if (error instanceof WallabyError) {
7171
7554
  throw error;
7172
7555
  }
7173
- // Wrap any other errors
7174
- throw new WallabyError({
7175
- message: error.message || 'Unknown error occurred',
7176
- statusCode: error.statusCode || 500,
7177
- errorCode: error.errorCode,
7178
- data: error,
7556
+ // No HTTP response reached us: treat as a network failure, mirroring the
7557
+ // custom request() path so both transports surface the same shape.
7558
+ throw this.toWallabyError({
7559
+ message: error.message || 'Network request failed',
7560
+ statusCode: 0,
7561
+ errorCode: 'NETWORK_ERROR',
7562
+ data: {
7563
+ code: error.code || error.name,
7564
+ originalError: error,
7565
+ },
7566
+ cause: error.cause,
7179
7567
  });
7180
7568
  }
7181
7569
  };
7182
7570
  return attemptRequest(false);
7183
7571
  };
7184
7572
  this.api = new Api(httpClient);
7185
- 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));
7573
+ 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));
7186
7574
  }
7187
7575
  set setClientAuthToken(token) {
7188
7576
  this._initializeClientAuthToken(token);
@@ -7268,17 +7656,16 @@ class Base {
7268
7656
  * All concurrent callers share the same in-flight promise via the module-level
7269
7657
  * `refreshDedupeManager` so only one network request is issued per user/environment scope.
7270
7658
  */
7271
- async _performTokenRefresh() {
7659
+ async _performTokenRefresh(opts) {
7272
7660
  const refreshDedupeKey = `refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;
7273
7661
  await refreshDedupeManager.withDedupe(refreshDedupeKey, async () => {
7662
+ var _a;
7274
7663
  const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
7275
7664
  if (!refreshToken) {
7276
7665
  return;
7277
7666
  }
7278
7667
  try {
7279
- const response = await this.request(AuthRoutes.refreshAccessToken, {
7280
- payload: { refreshToken },
7281
- });
7668
+ 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);
7282
7669
  await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
7283
7670
  await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
7284
7671
  }
@@ -7291,20 +7678,48 @@ class Base {
7291
7678
  }
7292
7679
  });
7293
7680
  }
7681
+ /**
7682
+ * Single chokepoint for surfacing transport failures. Every WallabyError raised
7683
+ * by a transport path is built here so `options.onError` fires exactly once per
7684
+ * logical failure. Retry paths must decide to retry BEFORE calling this so a
7685
+ * retried request does not double-fire.
7686
+ */
7687
+ toWallabyError(payload) {
7688
+ var _a, _b;
7689
+ const error = new WallabyError(payload);
7690
+ try {
7691
+ (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
7692
+ }
7693
+ catch (onErrorException) {
7694
+ // A throwing consumer callback must not replace the WallabyError being surfaced.
7695
+ logger.error('SDK::Base::toWallabyError::onError handler threw', { error: onErrorException });
7696
+ }
7697
+ return error;
7698
+ }
7294
7699
  /**
7295
7700
  * Main request method for making API calls to the Wallaby API.
7296
7701
  * @param route - Route configuration object containing the endpoint path and HTTP method
7297
7702
  * @param options - Optional request options including payload and query parameters
7298
7703
  * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
7704
+ * @param silent - Internal flag; when true the resulting WallabyError does NOT fire
7705
+ * `options.onError`. Used for best-effort refreshes whose failure is
7706
+ * swallowed by the caller (e.g. proactive refresh in securityWorker),
7707
+ * so an internal request never surfaces a consumer-facing error.
7299
7708
  * @returns Promise resolving to the typed response data
7300
7709
  * @throws Error if the API returns an error response or network failure occurs
7301
7710
  */
7302
- async request(route, options, retried = false) {
7711
+ async request(route, options, retried = false, silent = false) {
7303
7712
  var _a;
7713
+ // `silent` suppresses onError for swallowed internal refreshes. Note: refresh
7714
+ // requests dedupe by user/env/network, so under concurrent mixed-path refreshes
7715
+ // the winning call's `silent` value applies to all sharers — a narrow edge that
7716
+ // does not affect the retry no-double-fire guarantee. A fully race-free fix would
7717
+ // require idempotent (per-error) firing.
7718
+ const emitError = (payload) => silent ? new WallabyError(payload) : this.toWallabyError(payload);
7304
7719
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7305
7720
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7306
7721
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7307
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7722
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7308
7723
  await this._performTokenRefresh();
7309
7724
  }
7310
7725
  }
@@ -7328,7 +7743,7 @@ class Base {
7328
7743
  fetchOptions.body = JSON.stringify(options.payload);
7329
7744
  }
7330
7745
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7331
- const response = await fetch(fullUrl, fetchOptions);
7746
+ const response = await this.transport(fullUrl, fetchOptions);
7332
7747
  const contentType = response.headers.get('content-type');
7333
7748
  let data;
7334
7749
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7351,7 +7766,16 @@ class Base {
7351
7766
  });
7352
7767
  // Handle error responses (status >= 400)
7353
7768
  if (!response.ok) {
7354
- throw new WallabyError({
7769
+ // Reactive token refresh: on a refreshable 401, refresh once and retry the
7770
+ // original request. Decided here (before constructing the WallabyError) so the
7771
+ // retried attempt surfaces the single onError; the intermediate 401 never fires.
7772
+ if (!retried &&
7773
+ route !== AuthRoutes.refreshAccessToken &&
7774
+ shouldAttemptTokenRefresh({ status: response.status, errorCode: data === null || data === void 0 ? void 0 : data.errorCode })) {
7775
+ await this._performTokenRefresh();
7776
+ return this.request(route, options, true);
7777
+ }
7778
+ throw emitError({
7355
7779
  message: (data === null || data === void 0 ? void 0 : data.message) || response.statusText || 'Request failed',
7356
7780
  statusCode: response.status,
7357
7781
  errorCode: data === null || data === void 0 ? void 0 : data.errorCode,
@@ -7361,36 +7785,33 @@ class Base {
7361
7785
  return data;
7362
7786
  }
7363
7787
  catch (error) {
7364
- // Reactive token refresh: on 401, refresh once and retry the original request
7365
- if (!retried && route !== AuthRoutes.refreshAccessToken && shouldAttemptTokenRefresh(error)) {
7366
- await this._performTokenRefresh();
7367
- return this.request(route, options, true);
7788
+ // Already surfaced through toWallabyError (the !response.ok branch above), or a
7789
+ // pre-send guard error from before the fetch — propagate without re-firing onError.
7790
+ if (error instanceof WallabyError) {
7791
+ throw error;
7368
7792
  }
7369
7793
  if (error === null || error === void 0 ? void 0 : error.error) {
7370
7794
  logger.error('SDK::Base::handleApiCall::API Error', { error });
7371
7795
  const apiError = error.error;
7372
- throw new WallabyError({
7796
+ throw emitError({
7373
7797
  message: apiError.message || 'API request failed',
7374
7798
  statusCode: apiError.statusCode || 500,
7375
7799
  errorCode: apiError.errorCode,
7376
7800
  data: apiError,
7377
7801
  });
7378
7802
  }
7379
- if (error instanceof WallabyError) {
7380
- throw error;
7381
- }
7382
7803
  // Handle network errors, fetch failures, etc.
7383
7804
  logger.error(`SDK::Base::${route.method}::NetworkError`, {
7384
7805
  message: error.message,
7385
7806
  name: error.name,
7386
7807
  error,
7387
7808
  });
7388
- throw new WallabyError({
7809
+ throw emitError({
7389
7810
  message: error.message || 'Network request failed',
7390
7811
  statusCode: 0,
7391
7812
  errorCode: 'NETWORK_ERROR',
7392
7813
  data: {
7393
- code: error.name,
7814
+ code: error.code || error.name,
7394
7815
  originalError: error,
7395
7816
  },
7396
7817
  cause: error.cause,
@@ -7399,7 +7820,7 @@ class Base {
7399
7820
  }
7400
7821
  async _getRequestHeaders() {
7401
7822
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7402
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7823
+ if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7403
7824
  throw new WallabyError({
7404
7825
  message: 'Auth token has expired',
7405
7826
  statusCode: 401,
@@ -7418,11 +7839,13 @@ class Base {
7418
7839
  return headers;
7419
7840
  }
7420
7841
  async securityWorker(securityData) {
7421
- // Proactive token refresh before building headers for the generated client
7842
+ // Proactive token refresh before building headers for the generated client.
7843
+ // Best-effort and swallowed below, so it must NOT surface onError — otherwise a
7844
+ // failed internal refresh would fire even when the actual request later succeeds.
7422
7845
  try {
7423
7846
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7424
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7425
- await this._performTokenRefresh();
7847
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7848
+ await this._performTokenRefresh({ silent: true });
7426
7849
  }
7427
7850
  }
7428
7851
  catch (_a) {
@@ -7802,8 +8225,8 @@ function decodeBase64URL(base64url) {
7802
8225
  }
7803
8226
 
7804
8227
  class PasskeyService {
7805
- constructor(userId, storageService, request) {
7806
- this.cipher = new Cipher();
8228
+ constructor(userId, storageService, request, cipher = new Cipher()) {
8229
+ this.cipher = cipher;
7807
8230
  this.localStorageService = storageService;
7808
8231
  this.userId = userId;
7809
8232
  this.request = request;
@@ -8333,10 +8756,10 @@ function WithLock(lockKey) {
8333
8756
  }
8334
8757
 
8335
8758
  class AuthService extends Base {
8336
- constructor(config) {
8337
- super(config);
8759
+ constructor(config, ports = {}) {
8760
+ super(config, ports);
8338
8761
  this.getUserSalt = this.getUserSalt.bind(this);
8339
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8762
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8340
8763
  }
8341
8764
  /**
8342
8765
  * @description
@@ -8575,6 +8998,18 @@ class AuthService extends Base {
8575
8998
  throw error;
8576
8999
  }
8577
9000
  }
9001
+ /**
9002
+ * @private
9003
+ * @description Whether this device already has a stored `ClientAuthPublicKey`, which is written
9004
+ * atomically alongside the device private key in every provisioning path. Its presence is proof
9005
+ * the device was already provisioned: if it exists while the private key reads as missing we are
9006
+ * looking at a partial read-miss / corruption — creating a new identity would orphan shares still
9007
+ * wrapped to the old key. A device with no stored public key is instead treated as genuinely fresh.
9008
+ * @returns {Promise<boolean>} true when a device public key is stored and a missing key means data loss.
9009
+ */
9010
+ async hasStoredDevicePublicKey() {
9011
+ return !!(await this.localStorageService.fetch(LocalStorageItems.ClientAuthPublicKey));
9012
+ }
8578
9013
  /**
8579
9014
  *
8580
9015
  * @private
@@ -8622,8 +9057,19 @@ class AuthService extends Base {
8622
9057
  decryptedClientAuthPrivKey = await this.localStorageService.getDecryptedV1PrivateKey(input.password);
8623
9058
  }
8624
9059
  }
9060
+ else if (await this.hasStoredDevicePublicKey()) {
9061
+ // Private key reads as missing but the paired public key is still here: this is a partial
9062
+ // read-miss, not a fresh device. Fabricating a new identity would orphan wallet shares still
9063
+ // wrapped to the old key, so fail hard instead.
9064
+ logger.error('SDK::AuthService::handleSignInWithPassword::error', 'Device key missing but wallet data exists');
9065
+ throw new WallabyError({
9066
+ 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.',
9067
+ statusCode: 500,
9068
+ errorCode: ErrorResponseCodes.sdk_device_key_missing_with_existing_data,
9069
+ });
9070
+ }
8625
9071
  else {
8626
- logger.info('Device private key could not be retrieved, creating a new key pair');
9072
+ logger.info('No device data found, treating as a fresh device and creating a new key pair');
8627
9073
  const newIdentity = createIdentity();
8628
9074
  decryptedClientAuthPrivKey = newIdentity.privateKey;
8629
9075
  }
@@ -8661,13 +9107,26 @@ class AuthService extends Base {
8661
9107
  try {
8662
9108
  const passkeyCredential = await this.localStorageService.fetch(LocalStorageItems.PasskeyCredential);
8663
9109
  const encryptedDevicePrivateKey = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
8664
- let devicePublicKey = await this.localStorageService.fetch(LocalStorageItems.ClientAuthPublicKey);
9110
+ const devicePublicKey = await this.localStorageService.fetch(LocalStorageItems.ClientAuthPublicKey);
8665
9111
  let deviceKeyPair;
8666
9112
  // This logic needs to change and depend on data from server.
8667
9113
  if (!passkeyCredential) {
9114
+ // Passkey credential reads as missing but the device already holds a key pair: this is a
9115
+ // partial read-miss, not a fresh device. Registering a new passkey/identity would orphan
9116
+ // wallet shares still wrapped to the existing key, so fail hard instead.
9117
+ if (devicePublicKey || encryptedDevicePrivateKey) {
9118
+ logger.error('SDK::AuthService::handleSignInWithPasskey::error', 'Passkey credential missing but device data exists');
9119
+ throw new WallabyError({
9120
+ 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.',
9121
+ statusCode: 500,
9122
+ errorCode: ErrorResponseCodes.sdk_device_key_missing_with_existing_data,
9123
+ });
9124
+ }
8668
9125
  deviceKeyPair = createIdentity();
8669
- devicePublicKey = deviceKeyPair.publicKey;
8670
- await this.localStorageService.save(LocalStorageItems.ClientAuthPublicKey, devicePublicKey);
9126
+ // Don't persist ClientAuthPublicKey ahead of registration: addNewPasskey() writes it
9127
+ // atomically with the encrypted private key and passkey credential on success. Writing it
9128
+ // early would leave an orphaned public key if registration fails, which the guard above
9129
+ // would then misread as a partial read-miss and permanently brick this fresh device.
8671
9130
  authentication = await this.passkeyService.addNewPasskey({
8672
9131
  deviceKeyPair,
8673
9132
  getSignature: this.getSignature.bind(this),
@@ -8909,9 +9368,9 @@ function assertBackupSharePayloadShape(encrypted) {
8909
9368
  }
8910
9369
  }
8911
9370
  class WalletHandlersService extends Base {
8912
- constructor(config) {
8913
- super(config);
8914
- this.authService = new AuthService(config);
9371
+ constructor(config, ports = {}) {
9372
+ super(config, ports);
9373
+ this.authService = new AuthService(config, ports);
8915
9374
  this.userId = config.userId;
8916
9375
  }
8917
9376
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -9216,13 +9675,51 @@ class WalletHandlersService extends Base {
9216
9675
  }
9217
9676
  }
9218
9677
 
9678
+ const SEED_LENGTH_BYTES = 32;
9679
+ const CHECKSUM_BYTES = 2;
9680
+ /** Pack bytes into 11-bit groups, least-significant bits first (Algorand's encoding). */
9681
+ function toUint11Array(bytes) {
9682
+ const out = [];
9683
+ let acc = 0;
9684
+ let accBits = 0;
9685
+ for (const byte of bytes) {
9686
+ acc |= byte << accBits;
9687
+ accBits += 8;
9688
+ if (accBits >= 11) {
9689
+ out.push(acc & 0x7ff);
9690
+ acc >>>= 11;
9691
+ accBits -= 11;
9692
+ }
9693
+ }
9694
+ if (accBits > 0)
9695
+ out.push(acc & 0x7ff);
9696
+ return out;
9697
+ }
9698
+ /**
9699
+ * Convert a 32-byte seed to Algorand's fixed 25-word mnemonic: 24 data words
9700
+ * (256 bits packed into 11-bit BIP39-English word indices) plus a checksum word
9701
+ * derived from the first two bytes of the seed's SHA-512/256 hash.
9702
+ *
9703
+ * Word-for-word compatible with algosdk's `mnemonicFromSeed`; parity is
9704
+ * verified against algosdk (devDependency) in `algorand-mnemonic.spec.ts`.
9705
+ */
9706
+ function algorandMnemonicFromSeed(seed) {
9707
+ if (seed.length !== SEED_LENGTH_BYTES) {
9708
+ throw new Error(`Algorand seed must be ${SEED_LENGTH_BYTES} bytes, got ${seed.length}`);
9709
+ }
9710
+ const english = wordlists.english;
9711
+ const words = toUint11Array(seed).map((index) => english[index]);
9712
+ const checksumIndex = toUint11Array(sha512_256(seed).subarray(0, CHECKSUM_BYTES))[0];
9713
+ return [...words, english[checksumIndex]].join(' ');
9714
+ }
9715
+
9219
9716
  class WalletService extends Base {
9220
- constructor(config) {
9221
- super(config);
9222
- this.authService = new AuthService(config);
9223
- this.handlers = new WalletHandlersService(config);
9717
+ constructor(config, ports = {}) {
9718
+ super(config, ports);
9719
+ this.authService = new AuthService(config, ports);
9720
+ this.handlers = new WalletHandlersService(config, ports);
9224
9721
  this.userId = config.userId;
9225
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9722
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9226
9723
  }
9227
9724
  /**
9228
9725
  * Reads the persisted sliding-window rate-limit state for a counter key.
@@ -9826,7 +10323,7 @@ class WalletService extends Base {
9826
10323
  try {
9827
10324
  const seedBuffer = bip39.mnemonicToSeedSync(bip39Mnemonic);
9828
10325
  const seed = seedBuffer.slice(0, 32);
9829
- const convertedSeedPhrase = algosdk.mnemonicFromSeed(seed);
10326
+ const convertedSeedPhrase = algorandMnemonicFromSeed(seed);
9830
10327
  return convertedSeedPhrase;
9831
10328
  }
9832
10329
  catch (error) {
@@ -10754,10 +11251,10 @@ __decorate([
10754
11251
  ], WalletService.prototype, "convertToPasskey", null);
10755
11252
 
10756
11253
  class WalletDataService extends Base {
10757
- constructor(config) {
10758
- super(config);
11254
+ constructor(config, ports = {}) {
11255
+ super(config, ports);
10759
11256
  this.userId = config.userId;
10760
- this.walletService = new WalletService(config);
11257
+ this.walletService = new WalletService(config, ports);
10761
11258
  }
10762
11259
  /**
10763
11260
  * @description Validates the wallet address info for a given blockchain.
@@ -11078,8 +11575,8 @@ class WalletDataService extends Base {
11078
11575
  }
11079
11576
 
11080
11577
  class Utils extends Base {
11081
- constructor(config) {
11082
- super(config);
11578
+ constructor(config, ports = {}) {
11579
+ super(config, ports);
11083
11580
  /**
11084
11581
  *
11085
11582
  * Decrypts user private key
@@ -11112,7 +11609,7 @@ class Utils extends Base {
11112
11609
  return undefined;
11113
11610
  }
11114
11611
  };
11115
- this.auth = new AuthService(config);
11612
+ this.auth = new AuthService(config, ports);
11116
11613
  }
11117
11614
  /**
11118
11615
  *
@@ -11219,16 +11716,16 @@ class HttpApi extends Base {
11219
11716
  * @param config - The Wallaby configuration object
11220
11717
  * @public
11221
11718
  */
11222
- constructor(config) {
11223
- super(config);
11719
+ constructor(config, ports = {}) {
11720
+ super(config, ports);
11224
11721
  }
11225
11722
  }
11226
11723
 
11227
11724
  class Swap extends Base {
11228
- constructor(config) {
11229
- super(config);
11230
- this.authService = new AuthService(config);
11231
- this.walletService = new WalletService(config);
11725
+ constructor(config, ports = {}) {
11726
+ super(config, ports);
11727
+ this.authService = new AuthService(config, ports);
11728
+ this.walletService = new WalletService(config, ports);
11232
11729
  }
11233
11730
  /**
11234
11731
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11502,8 +11999,8 @@ const extractSuiAssetSymbol = (objectId) => {
11502
11999
  };
11503
12000
 
11504
12001
  class System extends Base {
11505
- constructor(config) {
11506
- super(config);
12002
+ constructor(config, ports = {}) {
12003
+ super(config, ports);
11507
12004
  }
11508
12005
  /**
11509
12006
  * @public
@@ -11700,10 +12197,10 @@ class System extends Base {
11700
12197
  }
11701
12198
 
11702
12199
  class Transactions extends Base {
11703
- constructor(config) {
11704
- super(config);
11705
- this.authService = new AuthService(config);
11706
- this.walletService = new WalletService(config);
12200
+ constructor(config, ports = {}) {
12201
+ super(config, ports);
12202
+ this.authService = new AuthService(config, ports);
12203
+ this.walletService = new WalletService(config, ports);
11707
12204
  this.userId = config.userId;
11708
12205
  }
11709
12206
  /**
@@ -12144,15 +12641,15 @@ class Wallaby {
12144
12641
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
12145
12642
  * @public
12146
12643
  */
12147
- constructor(config) {
12148
- this.wallet = new WalletService(config);
12149
- this.walletData = new WalletDataService(config);
12150
- this.utils = new Utils(config);
12151
- this.auth = new AuthService(config);
12152
- this.system = new System(config);
12153
- this.transactions = new Transactions(config);
12154
- this.swap = new Swap(config);
12155
- this.httpApi = new HttpApi(config);
12644
+ constructor(config, ports = {}) {
12645
+ this.wallet = new WalletService(config, ports);
12646
+ this.walletData = new WalletDataService(config, ports);
12647
+ this.utils = new Utils(config, ports);
12648
+ this.auth = new AuthService(config, ports);
12649
+ this.system = new System(config, ports);
12650
+ this.transactions = new Transactions(config, ports);
12651
+ this.swap = new Swap(config, ports);
12652
+ this.httpApi = new HttpApi(config, ports);
12156
12653
  }
12157
12654
  get version() {
12158
12655
  return currentPackageVersion;