@frequency-chain/ethereum-utils 1.17.0-rc5 → 1.17.0-rc6

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.
@@ -1,11 +1,11 @@
1
1
  import {Keyring}from'@polkadot/api';/** @internal Last-resort "this", if it gets here it probably would fail anyway */
2
- function evaluateThis(fn) {
2
+ function evaluateThis$3(fn) {
3
3
  return fn('return this');
4
4
  }
5
5
  /**
6
6
  * A cross-environment implementation for globalThis
7
7
  */
8
- const xglobal = (typeof globalThis !== 'undefined'
8
+ const xglobal$3 = (typeof globalThis !== 'undefined'
9
9
  ? globalThis
10
10
  : typeof global !== 'undefined'
11
11
  ? global
@@ -13,31 +13,19 @@ const xglobal = (typeof globalThis !== 'undefined'
13
13
  ? self
14
14
  : typeof window !== 'undefined'
15
15
  ? window
16
- : evaluateThis(Function));
16
+ : evaluateThis$3(Function));
17
17
  /**
18
18
  * Extracts a known global from the environment, applying a fallback if not found
19
19
  */
20
- function extractGlobal(name, fallback) {
20
+ function extractGlobal$2(name, fallback) {
21
21
  // Not quite sure why this is here - snuck in with TS 4.7.2 with no real idea
22
22
  // (as of now) as to why this looks like an "any" when we do cast it to a T
23
23
  //
24
24
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
25
- return typeof xglobal[name] === 'undefined'
25
+ return typeof xglobal$3[name] === 'undefined'
26
26
  ? fallback
27
- : xglobal[name];
28
- }let TextDecoder$1=class TextDecoder {
29
- __encoding;
30
- constructor(encoding) {
31
- this.__encoding = encoding;
32
- }
33
- decode(value) {
34
- let result = '';
35
- for (let i = 0, count = value.length; i < count; i++) {
36
- result += String.fromCharCode(value[i]);
37
- }
38
- return result;
39
- }
40
- };const TextDecoder = /*#__PURE__*/ extractGlobal('TextDecoder', TextDecoder$1);let TextEncoder$2=class TextEncoder {
27
+ : xglobal$3[name];
28
+ }let TextEncoder$4=class TextEncoder {
41
29
  encode(value) {
42
30
  const count = value.length;
43
31
  const u8a = new Uint8Array(count);
@@ -46,7 +34,7 @@ function extractGlobal(name, fallback) {
46
34
  }
47
35
  return u8a;
48
36
  }
49
- };const TextEncoder$1 = /*#__PURE__*/ extractGlobal('TextEncoder', TextEncoder$2);/**
37
+ };const TextEncoder$3 = /*#__PURE__*/ extractGlobal$2('TextEncoder', TextEncoder$4);/**
50
38
  * @name isFunction
51
39
  * @summary Tests for a `function`.
52
40
  * @description
@@ -75,19 +63,19 @@ function isFunction(value) {
75
63
  function invalidFallback() {
76
64
  return Number.NaN;
77
65
  }
78
- const BigInt$1 = /*#__PURE__*/ extractGlobal('BigInt', invalidFallback);const CHR$1 = '0123456789abcdef';
79
- const U8$1 = new Uint8Array(256);
80
- const U16$1 = new Uint8Array(256 * 256);
81
- for (let i = 0, count = CHR$1.length; i < count; i++) {
82
- U8$1[CHR$1[i].charCodeAt(0) | 0] = i | 0;
66
+ const BigInt$1 = /*#__PURE__*/ extractGlobal$2('BigInt', invalidFallback);const CHR$2 = '0123456789abcdef';
67
+ const U8$3 = new Uint8Array(256);
68
+ const U16$3 = new Uint8Array(256 * 256);
69
+ for (let i = 0, count = CHR$2.length; i < count; i++) {
70
+ U8$3[CHR$2[i].charCodeAt(0) | 0] = i | 0;
83
71
  if (i > 9) {
84
- U8$1[CHR$1[i].toUpperCase().charCodeAt(0) | 0] = i | 0;
72
+ U8$3[CHR$2[i].toUpperCase().charCodeAt(0) | 0] = i | 0;
85
73
  }
86
74
  }
87
75
  for (let i = 0; i < 256; i++) {
88
76
  const s = i << 8;
89
77
  for (let j = 0; j < 256; j++) {
90
- U16$1[s | j] = (U8$1[i] << 4) | U8$1[j];
78
+ U16$3[s | j] = (U8$3[i] << 4) | U8$3[j];
91
79
  }
92
80
  }
93
81
  /**
@@ -105,7 +93,7 @@ for (let i = 0; i < 256; i++) {
105
93
  * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
106
94
  * ```
107
95
  */
108
- function hexToU8a(value, bitLength = -1) {
96
+ function hexToU8a$1(value, bitLength = -1) {
109
97
  if (!value) {
110
98
  return new Uint8Array();
111
99
  }
@@ -125,7 +113,7 @@ function hexToU8a(value, bitLength = -1) {
125
113
  // HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
126
114
  // same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
127
115
  // also the faster operation by at least 2x with the character map above
128
- result[i] = U16$1[(value.charCodeAt(s) << 8) | value.charCodeAt(s + 1)];
116
+ result[i] = U16$3[(value.charCodeAt(s) << 8) | value.charCodeAt(s + 1)];
129
117
  }
130
118
  return result;
131
119
  }function getDefaultExportFromCjs (x) {
@@ -3560,9 +3548,9 @@ function isObject(value) {
3560
3548
  }const isToBigInt = /*#__PURE__*/ isOn('toBigInt');const isToBn = /*#__PURE__*/ isOn('toBn');/** true if the environment has proper BigInt support */
3561
3549
  const hasBigInt = typeof BigInt$1 === 'function' && typeof BigInt$1.asIntN === 'function';
3562
3550
  /** true if the environment has support for Buffer (typically Node.js) */
3563
- const hasBuffer = typeof xglobal.Buffer === 'function' && typeof xglobal.Buffer.isBuffer === 'function';
3551
+ const hasBuffer = typeof xglobal$3.Buffer === 'function' && typeof xglobal$3.Buffer.isBuffer === 'function';
3564
3552
  /** true if the environment has process available (typically Node.js) */
3565
- typeof xglobal.process === 'object';/**
3553
+ typeof xglobal$3.process === 'object';/**
3566
3554
  * @name isBuffer
3567
3555
  * @summary Tests for a `Buffer` object instance.
3568
3556
  * @description
@@ -3578,7 +3566,7 @@ typeof xglobal.process === 'object';/**
3578
3566
  */
3579
3567
  function isBuffer(value) {
3580
3568
  // we do check a function first, since it is slightly faster than isBuffer itself
3581
- return hasBuffer && !!value && isFunction(value.readDoubleLE) && xglobal.Buffer.isBuffer(value);
3569
+ return hasBuffer && !!value && isFunction(value.readDoubleLE) && xglobal$3.Buffer.isBuffer(value);
3582
3570
  }/**
3583
3571
  * @name isU8a
3584
3572
  * @summary Tests for a `Uint8Array` object instance.
@@ -3598,7 +3586,7 @@ function isU8a(value) {
3598
3586
  // slower than just checking the constrctor (direct instances)
3599
3587
  return (((value && value.constructor) === Uint8Array) ||
3600
3588
  value instanceof Uint8Array);
3601
- }const encoder = new TextEncoder$1();
3589
+ }const encoder$1 = new TextEncoder$3();
3602
3590
  /**
3603
3591
  * @name stringToU8a
3604
3592
  * @summary Creates a Uint8Array object from a utf-8 string.
@@ -3613,9 +3601,9 @@ function isU8a(value) {
3613
3601
  * stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f]
3614
3602
  * ```
3615
3603
  */
3616
- function stringToU8a(value) {
3604
+ function stringToU8a$1(value) {
3617
3605
  return value
3618
- ? encoder.encode(value.toString())
3606
+ ? encoder$1.encode(value.toString())
3619
3607
  : new Uint8Array();
3620
3608
  }/**
3621
3609
  * @name u8aToU8a
@@ -3641,10 +3629,10 @@ function u8aToU8a(value) {
3641
3629
  ? new Uint8Array(value)
3642
3630
  : value
3643
3631
  : isHex(value)
3644
- ? hexToU8a(value)
3632
+ ? hexToU8a$1(value)
3645
3633
  : Array.isArray(value)
3646
3634
  ? new Uint8Array(value)
3647
- : stringToU8a(value);
3635
+ : stringToU8a$1(value);
3648
3636
  }/**
3649
3637
  * @name u8aConcat
3650
3638
  * @summary Creates a concatenated Uint8Array from the inputs.
@@ -3690,26 +3678,26 @@ function u8aConcatStrict(u8as, length = 0) {
3690
3678
  offset += u8as[i].length;
3691
3679
  }
3692
3680
  return result;
3693
- }const U8 = new Array(256);
3694
- const U16 = new Array(256 * 256);
3681
+ }const U8$2 = new Array(256);
3682
+ const U16$2 = new Array(256 * 256);
3695
3683
  for (let n = 0; n < 256; n++) {
3696
- U8[n] = n.toString(16).padStart(2, '0');
3684
+ U8$2[n] = n.toString(16).padStart(2, '0');
3697
3685
  }
3698
3686
  for (let i = 0; i < 256; i++) {
3699
3687
  const s = i << 8;
3700
3688
  for (let j = 0; j < 256; j++) {
3701
- U16[s | j] = U8[i] + U8[j];
3689
+ U16$2[s | j] = U8$2[i] + U8$2[j];
3702
3690
  }
3703
3691
  }
3704
3692
  /** @internal */
3705
- function hex(value, result) {
3693
+ function hex$1(value, result) {
3706
3694
  const mod = (value.length % 2) | 0;
3707
3695
  const length = (value.length - mod) | 0;
3708
3696
  for (let i = 0; i < length; i += 2) {
3709
- result += U16[(value[i] << 8) | value[i + 1]];
3697
+ result += U16$2[(value[i] << 8) | value[i + 1]];
3710
3698
  }
3711
3699
  if (mod) {
3712
- result += U8[value[length] | 0];
3700
+ result += U8$2[value[length] | 0];
3713
3701
  }
3714
3702
  return result;
3715
3703
  }
@@ -3727,7 +3715,7 @@ function hex(value, result) {
3727
3715
  * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
3728
3716
  * ```
3729
3717
  */
3730
- function u8aToHex(value, bitLength = -1, isPrefixed = true) {
3718
+ function u8aToHex$1(value, bitLength = -1, isPrefixed = true) {
3731
3719
  // this is not 100% correct sinmce we support isPrefixed = false....
3732
3720
  const empty = isPrefixed
3733
3721
  ? '0x'
@@ -3738,29 +3726,10 @@ function u8aToHex(value, bitLength = -1, isPrefixed = true) {
3738
3726
  else if (bitLength > 0) {
3739
3727
  const length = Math.ceil(bitLength / 8);
3740
3728
  if (value.length > length) {
3741
- return `${hex(value.subarray(0, length / 2), empty)}…${hex(value.subarray(value.length - length / 2), '')}`;
3729
+ return `${hex$1(value.subarray(0, length / 2), empty)}…${hex$1(value.subarray(value.length - length / 2), '')}`;
3742
3730
  }
3743
3731
  }
3744
- return hex(value, empty);
3745
- }const decoder = new TextDecoder('utf-8');
3746
- /**
3747
- * @name u8aToString
3748
- * @summary Creates a utf-8 string from a Uint8Array object.
3749
- * @description
3750
- * `UInt8Array` input values return the actual decoded utf-8 string. `null` or `undefined` values returns an empty string.
3751
- * @example
3752
- * <BR>
3753
- *
3754
- * ```javascript
3755
- * import { u8aToString } from '@polkadot/util';
3756
- *
3757
- * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello
3758
- * ```
3759
- */
3760
- function u8aToString(value) {
3761
- return value
3762
- ? decoder.decode(value)
3763
- : '';
3732
+ return hex$1(value, empty);
3764
3733
  }/**
3765
3734
  * @name hexStripPrefix
3766
3735
  * @summary Strips any leading `0x` prefix.
@@ -3892,158 +3861,391 @@ function bnToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = DE
3892
3861
  : valueBn;
3893
3862
  output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
3894
3863
  return output;
3895
- }const crypto$3 = xglobal.crypto;
3896
- function getRandomValues(arr) {
3897
- return crypto$3.getRandomValues(arr);
3898
- }const DEFAULT_CRYPTO = { getRandomValues };
3899
- const DEFAULT_SELF = { crypto: DEFAULT_CRYPTO };
3864
+ }/** @internal Last-resort "this", if it gets here it probably would fail anyway */
3865
+ function evaluateThis$2(fn) {
3866
+ return fn('return this');
3867
+ }
3900
3868
  /**
3901
- * @name Wbg
3902
- * @description
3903
- * This defines the internal interfaces that wasm-bindgen used to communicate
3904
- * with the host layer. None of these functions are available to the user, rather
3905
- * they are called internally from the WASM code itself.
3906
- *
3907
- * The interfaces here are exposed in the imports on the created WASM interfaces.
3908
- *
3909
- * Internally the implementation does a thin layer into the supplied bridge.
3869
+ * A cross-environment implementation for globalThis
3910
3870
  */
3911
- class Wbg {
3912
- __internal__bridge;
3913
- constructor(bridge) {
3914
- this.__internal__bridge = bridge;
3915
- }
3916
- /** @internal */
3917
- abort = () => {
3918
- throw new Error('abort');
3919
- };
3920
- /** @internal */
3921
- __wbindgen_is_undefined = (idx) => {
3922
- return this.__internal__bridge.getObject(idx) === undefined;
3923
- };
3924
- /** @internal */
3925
- __wbindgen_throw = (ptr, len) => {
3926
- throw new Error(this.__internal__bridge.getString(ptr, len));
3927
- };
3928
- /** @internal */
3929
- __wbg_self_1b7a39e3a92c949c = () => {
3930
- return this.__internal__bridge.addObject(DEFAULT_SELF);
3931
- };
3932
- /** @internal */
3933
- __wbg_require_604837428532a733 = (ptr, len) => {
3934
- throw new Error(`Unable to require ${this.__internal__bridge.getString(ptr, len)}`);
3935
- };
3936
- /** @internal */
3937
- __wbg_crypto_968f1772287e2df0 = (_idx) => {
3938
- return this.__internal__bridge.addObject(DEFAULT_CRYPTO);
3939
- };
3940
- /** @internal */
3941
- __wbg_getRandomValues_a3d34b4fee3c2869 = (_idx) => {
3942
- return this.__internal__bridge.addObject(DEFAULT_CRYPTO.getRandomValues);
3943
- };
3944
- /** @internal */
3945
- __wbg_getRandomValues_f5e14ab7ac8e995d = (_arg0, ptr, len) => {
3946
- DEFAULT_CRYPTO.getRandomValues(this.__internal__bridge.getU8a(ptr, len));
3947
- };
3948
- /** @internal */
3949
- __wbg_randomFillSync_d5bd2d655fdf256a = (_idx, _ptr, _len) => {
3950
- throw new Error('randomFillsync is not available');
3951
- // getObject(idx).randomFillSync(getU8a(ptr, len));
3952
- };
3953
- /** @internal */
3954
- __wbindgen_object_drop_ref = (idx) => {
3955
- this.__internal__bridge.takeObject(idx);
3956
- };
3957
- }/**
3958
- * @name Bridge
3959
- * @description
3960
- * Creates a bridge between the JS and WASM environments.
3961
- *
3962
- * For any bridge it is passed an function which is then called internally at the
3963
- * time of initialization. This affectively implements the layer between WASM and
3964
- * the native environment, providing all the plumbing needed for the Wbg classes.
3871
+ const xglobal$2 = (typeof globalThis !== 'undefined'
3872
+ ? globalThis
3873
+ : typeof global !== 'undefined'
3874
+ ? global
3875
+ : typeof self !== 'undefined'
3876
+ ? self
3877
+ : typeof window !== 'undefined'
3878
+ ? window
3879
+ : evaluateThis$2(Function));
3880
+ /**
3881
+ * Extracts a known global from the environment, applying a fallback if not found
3965
3882
  */
3966
- class Bridge {
3967
- __internal__createWasm;
3968
- __internal__heap;
3969
- __internal__wbg;
3970
- __internal__cachegetInt32;
3971
- __internal__cachegetUint8;
3972
- __internal__heapNext;
3973
- __internal__wasm;
3974
- __internal__wasmError;
3975
- __internal__wasmPromise;
3976
- __internal__type;
3977
- constructor(createWasm) {
3978
- this.__internal__createWasm = createWasm;
3979
- this.__internal__cachegetInt32 = null;
3980
- this.__internal__cachegetUint8 = null;
3981
- this.__internal__heap = new Array(32)
3982
- .fill(undefined)
3983
- .concat(undefined, null, true, false);
3984
- this.__internal__heapNext = this.__internal__heap.length;
3985
- this.__internal__type = 'none';
3986
- this.__internal__wasm = null;
3987
- this.__internal__wasmError = null;
3988
- this.__internal__wasmPromise = null;
3989
- this.__internal__wbg = { ...new Wbg(this) };
3990
- }
3991
- /** @description Returns the init error */
3992
- get error() {
3993
- return this.__internal__wasmError;
3994
- }
3995
- /** @description Returns the init type */
3996
- get type() {
3997
- return this.__internal__type;
3998
- }
3999
- /** @description Returns the created wasm interface */
4000
- get wasm() {
4001
- return this.__internal__wasm;
3883
+ function extractGlobal$1(name, fallback) {
3884
+ // Not quite sure why this is here - snuck in with TS 4.7.2 with no real idea
3885
+ // (as of now) as to why this looks like an "any" when we do cast it to a T
3886
+ //
3887
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3888
+ return typeof xglobal$2[name] === 'undefined'
3889
+ ? fallback
3890
+ : xglobal$2[name];
3891
+ }let TextDecoder$1=class TextDecoder {
3892
+ __encoding;
3893
+ constructor(encoding) {
3894
+ this.__encoding = encoding;
4002
3895
  }
4003
- /** @description Performs the wasm initialization */
4004
- async init(createWasm) {
4005
- if (!this.__internal__wasmPromise || createWasm) {
4006
- this.__internal__wasmPromise = (createWasm || this.__internal__createWasm)(this.__internal__wbg);
3896
+ decode(value) {
3897
+ let result = '';
3898
+ for (let i = 0, count = value.length; i < count; i++) {
3899
+ result += String.fromCharCode(value[i]);
4007
3900
  }
4008
- const { error, type, wasm } = await this.__internal__wasmPromise;
4009
- this.__internal__type = type;
4010
- this.__internal__wasm = wasm;
4011
- this.__internal__wasmError = error;
4012
- return this.__internal__wasm;
4013
- }
4014
- /**
4015
- * @internal
4016
- * @description Gets an object from the heap
4017
- */
4018
- getObject(idx) {
4019
- return this.__internal__heap[idx];
3901
+ return result;
4020
3902
  }
4021
- /**
4022
- * @internal
4023
- * @description Removes an object from the heap
4024
- */
4025
- dropObject(idx) {
4026
- if (idx < 36) {
4027
- return;
3903
+ };const TextDecoder = /*#__PURE__*/ extractGlobal$1('TextDecoder', TextDecoder$1);/** @internal Last-resort "this", if it gets here it probably would fail anyway */
3904
+ function evaluateThis$1(fn) {
3905
+ return fn('return this');
3906
+ }
3907
+ /**
3908
+ * A cross-environment implementation for globalThis
3909
+ */
3910
+ const xglobal$1 = (typeof globalThis !== 'undefined'
3911
+ ? globalThis
3912
+ : typeof global !== 'undefined'
3913
+ ? global
3914
+ : typeof self !== 'undefined'
3915
+ ? self
3916
+ : typeof window !== 'undefined'
3917
+ ? window
3918
+ : evaluateThis$1(Function));
3919
+ /**
3920
+ * Extracts a known global from the environment, applying a fallback if not found
3921
+ */
3922
+ function extractGlobal(name, fallback) {
3923
+ // Not quite sure why this is here - snuck in with TS 4.7.2 with no real idea
3924
+ // (as of now) as to why this looks like an "any" when we do cast it to a T
3925
+ //
3926
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3927
+ return typeof xglobal$1[name] === 'undefined'
3928
+ ? fallback
3929
+ : xglobal$1[name];
3930
+ }let TextEncoder$2=class TextEncoder {
3931
+ encode(value) {
3932
+ const count = value.length;
3933
+ const u8a = new Uint8Array(count);
3934
+ for (let i = 0; i < count; i++) {
3935
+ u8a[i] = value.charCodeAt(i);
4028
3936
  }
4029
- this.__internal__heap[idx] = this.__internal__heapNext;
4030
- this.__internal__heapNext = idx;
3937
+ return u8a;
4031
3938
  }
4032
- /**
4033
- * @internal
4034
- * @description Retrieves and removes an object to the heap
4035
- */
4036
- takeObject(idx) {
4037
- const ret = this.getObject(idx);
4038
- this.dropObject(idx);
4039
- return ret;
3939
+ };const TextEncoder$1 = /*#__PURE__*/ extractGlobal('TextEncoder', TextEncoder$2);const CHR$1 = '0123456789abcdef';
3940
+ const U8$1 = new Uint8Array(256);
3941
+ const U16$1 = new Uint8Array(256 * 256);
3942
+ for (let i = 0, count = CHR$1.length; i < count; i++) {
3943
+ U8$1[CHR$1[i].charCodeAt(0) | 0] = i | 0;
3944
+ if (i > 9) {
3945
+ U8$1[CHR$1[i].toUpperCase().charCodeAt(0) | 0] = i | 0;
4040
3946
  }
4041
- /**
4042
- * @internal
4043
- * @description Adds an object to the heap
4044
- */
4045
- addObject(obj) {
4046
- if (this.__internal__heapNext === this.__internal__heap.length) {
3947
+ }
3948
+ for (let i = 0; i < 256; i++) {
3949
+ const s = i << 8;
3950
+ for (let j = 0; j < 256; j++) {
3951
+ U16$1[s | j] = (U8$1[i] << 4) | U8$1[j];
3952
+ }
3953
+ }
3954
+ /**
3955
+ * @name hexToU8a
3956
+ * @summary Creates a Uint8Array object from a hex string.
3957
+ * @description
3958
+ * `null` inputs returns an empty `Uint8Array` result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the `0x` prefix) throws an error.
3959
+ * @example
3960
+ * <BR>
3961
+ *
3962
+ * ```javascript
3963
+ * import { hexToU8a } from '@polkadot/util';
3964
+ *
3965
+ * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
3966
+ * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
3967
+ * ```
3968
+ */
3969
+ function hexToU8a(value, bitLength = -1) {
3970
+ if (!value) {
3971
+ return new Uint8Array();
3972
+ }
3973
+ let s = value.startsWith('0x')
3974
+ ? 2
3975
+ : 0;
3976
+ const decLength = Math.ceil((value.length - s) / 2);
3977
+ const endLength = Math.ceil(bitLength === -1
3978
+ ? decLength
3979
+ : bitLength / 8);
3980
+ const result = new Uint8Array(endLength);
3981
+ const offset = endLength > decLength
3982
+ ? endLength - decLength
3983
+ : 0;
3984
+ for (let i = offset; i < endLength; i++, s += 2) {
3985
+ // The big factor here is actually the string lookups. If we do
3986
+ // HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
3987
+ // same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
3988
+ // also the faster operation by at least 2x with the character map above
3989
+ result[i] = U16$1[(value.charCodeAt(s) << 8) | value.charCodeAt(s + 1)];
3990
+ }
3991
+ return result;
3992
+ }const encoder = new TextEncoder$1();
3993
+ /**
3994
+ * @name stringToU8a
3995
+ * @summary Creates a Uint8Array object from a utf-8 string.
3996
+ * @description
3997
+ * String input values return the actual encoded `UInt8Array`. `null` or `undefined` values returns an empty encoded array.
3998
+ * @example
3999
+ * <BR>
4000
+ *
4001
+ * ```javascript
4002
+ * import { stringToU8a } from '@polkadot/util';
4003
+ *
4004
+ * stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f]
4005
+ * ```
4006
+ */
4007
+ function stringToU8a(value) {
4008
+ return value
4009
+ ? encoder.encode(value.toString())
4010
+ : new Uint8Array();
4011
+ }const U8 = new Array(256);
4012
+ const U16 = new Array(256 * 256);
4013
+ for (let n = 0; n < 256; n++) {
4014
+ U8[n] = n.toString(16).padStart(2, '0');
4015
+ }
4016
+ for (let i = 0; i < 256; i++) {
4017
+ const s = i << 8;
4018
+ for (let j = 0; j < 256; j++) {
4019
+ U16[s | j] = U8[i] + U8[j];
4020
+ }
4021
+ }
4022
+ /** @internal */
4023
+ function hex(value, result) {
4024
+ const mod = (value.length % 2) | 0;
4025
+ const length = (value.length - mod) | 0;
4026
+ for (let i = 0; i < length; i += 2) {
4027
+ result += U16[(value[i] << 8) | value[i + 1]];
4028
+ }
4029
+ if (mod) {
4030
+ result += U8[value[length] | 0];
4031
+ }
4032
+ return result;
4033
+ }
4034
+ /**
4035
+ * @name u8aToHex
4036
+ * @summary Creates a hex string from a Uint8Array object.
4037
+ * @description
4038
+ * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string.
4039
+ * @example
4040
+ * <BR>
4041
+ *
4042
+ * ```javascript
4043
+ * import { u8aToHex } from '@polkadot/util';
4044
+ *
4045
+ * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
4046
+ * ```
4047
+ */
4048
+ function u8aToHex(value, bitLength = -1, isPrefixed = true) {
4049
+ // this is not 100% correct sinmce we support isPrefixed = false....
4050
+ const empty = isPrefixed
4051
+ ? '0x'
4052
+ : '';
4053
+ if (!value?.length) {
4054
+ return empty;
4055
+ }
4056
+ else if (bitLength > 0) {
4057
+ const length = Math.ceil(bitLength / 8);
4058
+ if (value.length > length) {
4059
+ return `${hex(value.subarray(0, length / 2), empty)}…${hex(value.subarray(value.length - length / 2), '')}`;
4060
+ }
4061
+ }
4062
+ return hex(value, empty);
4063
+ }const decoder = new TextDecoder('utf-8');
4064
+ /**
4065
+ * @name u8aToString
4066
+ * @summary Creates a utf-8 string from a Uint8Array object.
4067
+ * @description
4068
+ * `UInt8Array` input values return the actual decoded utf-8 string. `null` or `undefined` values returns an empty string.
4069
+ * @example
4070
+ * <BR>
4071
+ *
4072
+ * ```javascript
4073
+ * import { u8aToString } from '@polkadot/util';
4074
+ *
4075
+ * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello
4076
+ * ```
4077
+ */
4078
+ function u8aToString(value) {
4079
+ return value
4080
+ ? decoder.decode(value)
4081
+ : '';
4082
+ }/** @internal Last-resort "this", if it gets here it probably would fail anyway */
4083
+ function evaluateThis(fn) {
4084
+ return fn('return this');
4085
+ }
4086
+ /**
4087
+ * A cross-environment implementation for globalThis
4088
+ */
4089
+ const xglobal = (typeof globalThis !== 'undefined'
4090
+ ? globalThis
4091
+ : typeof global !== 'undefined'
4092
+ ? global
4093
+ : typeof self !== 'undefined'
4094
+ ? self
4095
+ : typeof window !== 'undefined'
4096
+ ? window
4097
+ : evaluateThis(Function));const crypto$3 = xglobal.crypto;
4098
+ function getRandomValues(arr) {
4099
+ return crypto$3.getRandomValues(arr);
4100
+ }const DEFAULT_CRYPTO = { getRandomValues };
4101
+ const DEFAULT_SELF = { crypto: DEFAULT_CRYPTO };
4102
+ /**
4103
+ * @name Wbg
4104
+ * @description
4105
+ * This defines the internal interfaces that wasm-bindgen used to communicate
4106
+ * with the host layer. None of these functions are available to the user, rather
4107
+ * they are called internally from the WASM code itself.
4108
+ *
4109
+ * The interfaces here are exposed in the imports on the created WASM interfaces.
4110
+ *
4111
+ * Internally the implementation does a thin layer into the supplied bridge.
4112
+ */
4113
+ class Wbg {
4114
+ __internal__bridge;
4115
+ constructor(bridge) {
4116
+ this.__internal__bridge = bridge;
4117
+ }
4118
+ /** @internal */
4119
+ abort = () => {
4120
+ throw new Error('abort');
4121
+ };
4122
+ /** @internal */
4123
+ __wbindgen_is_undefined = (idx) => {
4124
+ return this.__internal__bridge.getObject(idx) === undefined;
4125
+ };
4126
+ /** @internal */
4127
+ __wbindgen_throw = (ptr, len) => {
4128
+ throw new Error(this.__internal__bridge.getString(ptr, len));
4129
+ };
4130
+ /** @internal */
4131
+ __wbg_self_1b7a39e3a92c949c = () => {
4132
+ return this.__internal__bridge.addObject(DEFAULT_SELF);
4133
+ };
4134
+ /** @internal */
4135
+ __wbg_require_604837428532a733 = (ptr, len) => {
4136
+ throw new Error(`Unable to require ${this.__internal__bridge.getString(ptr, len)}`);
4137
+ };
4138
+ /** @internal */
4139
+ __wbg_crypto_968f1772287e2df0 = (_idx) => {
4140
+ return this.__internal__bridge.addObject(DEFAULT_CRYPTO);
4141
+ };
4142
+ /** @internal */
4143
+ __wbg_getRandomValues_a3d34b4fee3c2869 = (_idx) => {
4144
+ return this.__internal__bridge.addObject(DEFAULT_CRYPTO.getRandomValues);
4145
+ };
4146
+ /** @internal */
4147
+ __wbg_getRandomValues_f5e14ab7ac8e995d = (_arg0, ptr, len) => {
4148
+ DEFAULT_CRYPTO.getRandomValues(this.__internal__bridge.getU8a(ptr, len));
4149
+ };
4150
+ /** @internal */
4151
+ __wbg_randomFillSync_d5bd2d655fdf256a = (_idx, _ptr, _len) => {
4152
+ throw new Error('randomFillsync is not available');
4153
+ // getObject(idx).randomFillSync(getU8a(ptr, len));
4154
+ };
4155
+ /** @internal */
4156
+ __wbindgen_object_drop_ref = (idx) => {
4157
+ this.__internal__bridge.takeObject(idx);
4158
+ };
4159
+ }/**
4160
+ * @name Bridge
4161
+ * @description
4162
+ * Creates a bridge between the JS and WASM environments.
4163
+ *
4164
+ * For any bridge it is passed an function which is then called internally at the
4165
+ * time of initialization. This affectively implements the layer between WASM and
4166
+ * the native environment, providing all the plumbing needed for the Wbg classes.
4167
+ */
4168
+ class Bridge {
4169
+ __internal__createWasm;
4170
+ __internal__heap;
4171
+ __internal__wbg;
4172
+ __internal__cachegetInt32;
4173
+ __internal__cachegetUint8;
4174
+ __internal__heapNext;
4175
+ __internal__wasm;
4176
+ __internal__wasmError;
4177
+ __internal__wasmPromise;
4178
+ __internal__type;
4179
+ constructor(createWasm) {
4180
+ this.__internal__createWasm = createWasm;
4181
+ this.__internal__cachegetInt32 = null;
4182
+ this.__internal__cachegetUint8 = null;
4183
+ this.__internal__heap = new Array(32)
4184
+ .fill(undefined)
4185
+ .concat(undefined, null, true, false);
4186
+ this.__internal__heapNext = this.__internal__heap.length;
4187
+ this.__internal__type = 'none';
4188
+ this.__internal__wasm = null;
4189
+ this.__internal__wasmError = null;
4190
+ this.__internal__wasmPromise = null;
4191
+ this.__internal__wbg = { ...new Wbg(this) };
4192
+ }
4193
+ /** @description Returns the init error */
4194
+ get error() {
4195
+ return this.__internal__wasmError;
4196
+ }
4197
+ /** @description Returns the init type */
4198
+ get type() {
4199
+ return this.__internal__type;
4200
+ }
4201
+ /** @description Returns the created wasm interface */
4202
+ get wasm() {
4203
+ return this.__internal__wasm;
4204
+ }
4205
+ /** @description Performs the wasm initialization */
4206
+ async init(createWasm) {
4207
+ if (!this.__internal__wasmPromise || createWasm) {
4208
+ this.__internal__wasmPromise = (createWasm || this.__internal__createWasm)(this.__internal__wbg);
4209
+ }
4210
+ const { error, type, wasm } = await this.__internal__wasmPromise;
4211
+ this.__internal__type = type;
4212
+ this.__internal__wasm = wasm;
4213
+ this.__internal__wasmError = error;
4214
+ return this.__internal__wasm;
4215
+ }
4216
+ /**
4217
+ * @internal
4218
+ * @description Gets an object from the heap
4219
+ */
4220
+ getObject(idx) {
4221
+ return this.__internal__heap[idx];
4222
+ }
4223
+ /**
4224
+ * @internal
4225
+ * @description Removes an object from the heap
4226
+ */
4227
+ dropObject(idx) {
4228
+ if (idx < 36) {
4229
+ return;
4230
+ }
4231
+ this.__internal__heap[idx] = this.__internal__heapNext;
4232
+ this.__internal__heapNext = idx;
4233
+ }
4234
+ /**
4235
+ * @internal
4236
+ * @description Retrieves and removes an object to the heap
4237
+ */
4238
+ takeObject(idx) {
4239
+ const ret = this.getObject(idx);
4240
+ this.dropObject(idx);
4241
+ return ret;
4242
+ }
4243
+ /**
4244
+ * @internal
4245
+ * @description Adds an object to the heap
4246
+ */
4247
+ addObject(obj) {
4248
+ if (this.__internal__heapNext === this.__internal__heap.length) {
4047
4249
  this.__internal__heap.push(this.__internal__heap.length + 1);
4048
4250
  }
4049
4251
  const idx = this.__internal__heapNext;
@@ -4553,7 +4755,7 @@ const keccak512 = /*#__PURE__*/ withWasm((wasm, data) => {
4553
4755
  function isReady() {
4554
4756
  return !!bridge.wasm;
4555
4757
  }/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
4556
- function isBytes$2(a) {
4758
+ function isBytes$1(a) {
4557
4759
  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
4558
4760
  }
4559
4761
  function isArrayOf(isString, arr) {
@@ -4713,7 +4915,7 @@ function radix(num) {
4713
4915
  const _256 = 2 ** 8;
4714
4916
  return {
4715
4917
  encode: (bytes) => {
4716
- if (!isBytes$2(bytes))
4918
+ if (!isBytes$1(bytes))
4717
4919
  throw new Error('radix.encode input should be Uint8Array');
4718
4920
  return convertRadix(Array.from(bytes), _256, num);
4719
4921
  },
@@ -4815,7 +5017,7 @@ const base58Encode = /*#__PURE__*/ createEncode(config);const crypto$2 = typeof
4815
5017
  // Makes the utils un-importable in browsers without a bundler.
4816
5018
  // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
4817
5019
  /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
4818
- function isBytes$1(a) {
5020
+ function isBytes(a) {
4819
5021
  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
4820
5022
  }
4821
5023
  /** Asserts something is positive integer. */
@@ -4824,8 +5026,8 @@ function anumber(n) {
4824
5026
  throw new Error('positive integer expected, got ' + n);
4825
5027
  }
4826
5028
  /** Asserts something is Uint8Array. */
4827
- function abytes$1(b, ...lengths) {
4828
- if (!isBytes$1(b))
5029
+ function abytes(b, ...lengths) {
5030
+ if (!isBytes(b))
4829
5031
  throw new Error('Uint8Array expected');
4830
5032
  if (lengths.length > 0 && !lengths.includes(b.length))
4831
5033
  throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
@@ -4846,7 +5048,7 @@ function aexists(instance, checkFinished = true) {
4846
5048
  }
4847
5049
  /** Asserts output is properly-sized byte array */
4848
5050
  function aoutput(out, instance) {
4849
- abytes$1(out);
5051
+ abytes(out);
4850
5052
  const min = instance.outputLen;
4851
5053
  if (out.length < min) {
4852
5054
  throw new Error('digestInto() expects output buffer of length at least ' + min);
@@ -4893,6 +5095,65 @@ function byteSwap32(arr) {
4893
5095
  const swap32IfBE = isLE$1
4894
5096
  ? (u) => u
4895
5097
  : byteSwap32;
5098
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
5099
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
5100
+ // @ts-ignore
5101
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
5102
+ // Array where index 0xf0 (240) is mapped to string 'f0'
5103
+ const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
5104
+ /**
5105
+ * Convert byte array to hex string. Uses built-in function, when available.
5106
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
5107
+ */
5108
+ function bytesToHex$1(bytes) {
5109
+ abytes(bytes);
5110
+ // @ts-ignore
5111
+ if (hasHexBuiltin)
5112
+ return bytes.toHex();
5113
+ // pre-caching improves the speed 6x
5114
+ let hex = '';
5115
+ for (let i = 0; i < bytes.length; i++) {
5116
+ hex += hexes$1[bytes[i]];
5117
+ }
5118
+ return hex;
5119
+ }
5120
+ // We use optimized technique to convert hex string to byte array
5121
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
5122
+ function asciiToBase16(ch) {
5123
+ if (ch >= asciis._0 && ch <= asciis._9)
5124
+ return ch - asciis._0; // '2' => 50-48
5125
+ if (ch >= asciis.A && ch <= asciis.F)
5126
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
5127
+ if (ch >= asciis.a && ch <= asciis.f)
5128
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
5129
+ return;
5130
+ }
5131
+ /**
5132
+ * Convert hex string to byte array. Uses built-in function, when available.
5133
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
5134
+ */
5135
+ function hexToBytes$1(hex) {
5136
+ if (typeof hex !== 'string')
5137
+ throw new Error('hex string expected, got ' + typeof hex);
5138
+ // @ts-ignore
5139
+ if (hasHexBuiltin)
5140
+ return Uint8Array.fromHex(hex);
5141
+ const hl = hex.length;
5142
+ const al = hl / 2;
5143
+ if (hl % 2)
5144
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
5145
+ const array = new Uint8Array(al);
5146
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
5147
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
5148
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
5149
+ if (n1 === undefined || n2 === undefined) {
5150
+ const char = hex[hi] + hex[hi + 1];
5151
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
5152
+ }
5153
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
5154
+ }
5155
+ return array;
5156
+ }
4896
5157
  /**
4897
5158
  * Converts string to bytes using UTF8 encoding.
4898
5159
  * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
@@ -4910,15 +5171,15 @@ function utf8ToBytes$2(str) {
4910
5171
  function toBytes$1(data) {
4911
5172
  if (typeof data === 'string')
4912
5173
  data = utf8ToBytes$2(data);
4913
- abytes$1(data);
5174
+ abytes(data);
4914
5175
  return data;
4915
5176
  }
4916
5177
  /** Copies several Uint8Arrays into one. */
4917
- function concatBytes$3(...arrays) {
5178
+ function concatBytes$2(...arrays) {
4918
5179
  let sum = 0;
4919
5180
  for (let i = 0; i < arrays.length; i++) {
4920
5181
  const a = arrays[i];
4921
- abytes$1(a);
5182
+ abytes(a);
4922
5183
  sum += a.length;
4923
5184
  }
4924
5185
  const res = new Uint8Array(sum);
@@ -5032,7 +5293,7 @@ class HashMD extends Hash$1 {
5032
5293
  update(data) {
5033
5294
  aexists(this);
5034
5295
  data = toBytes$1(data);
5035
- abytes$1(data);
5296
+ abytes(data);
5036
5297
  const { view, buffer, blockLen } = this;
5037
5298
  const len = data.length;
5038
5299
  for (let pos = 0; pos < len;) {
@@ -5260,7 +5521,7 @@ class BLAKE2 extends Hash$1 {
5260
5521
  update(data) {
5261
5522
  aexists(this);
5262
5523
  data = toBytes$1(data);
5263
- abytes$1(data);
5524
+ abytes(data);
5264
5525
  // Main difference with other hashes: there is flag for last block,
5265
5526
  // so we cannot process current block before we know that there
5266
5527
  // is the next one. This significantly complicates logic and reduces ability
@@ -5506,7 +5767,7 @@ function blake2AsU8a(data, bitLength = 256, key, onlyJs) {
5506
5767
  : key
5507
5768
  ? blake2b(u8a, { dkLen: byteLength, key })
5508
5769
  : blake2b(u8a, { dkLen: byteLength });
5509
- }const SS58_PREFIX = stringToU8a('SS58PRE');
5770
+ }const SS58_PREFIX = stringToU8a$1('SS58PRE');
5510
5771
  function sshash(key) {
5511
5772
  return blake2AsU8a(u8aConcat(SS58_PREFIX, key), 512);
5512
5773
  }function checkAddressChecksum(decoded) {
@@ -7901,7 +8162,7 @@ let HMAC$1=class HMAC extends Hash$1 {
7901
8162
  }
7902
8163
  digestInto(out) {
7903
8164
  aexists(this);
7904
- abytes$1(out, this.outputLen);
8165
+ abytes(out, this.outputLen);
7905
8166
  this.finished = true;
7906
8167
  this.iHash.digestInto(out);
7907
8168
  this.oHash.update(out);
@@ -7951,19 +8212,8 @@ hmac$1.create = (hash, key) => new HMAC$1(hash, key);/**
7951
8212
  * @module
7952
8213
  */
7953
8214
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7954
- // 100 lines of code in the file are duplicated from noble-hashes (utils).
7955
- // This is OK: `abstract` directory does not use noble-hashes.
7956
- // User may opt-in into using different hashing library. This way, noble-hashes
7957
- // won't be included into their bundle.
7958
- const _0n$a = /* @__PURE__ */ BigInt(0);
8215
+ const _0n$9 = /* @__PURE__ */ BigInt(0);
7959
8216
  const _1n$b = /* @__PURE__ */ BigInt(1);
7960
- function isBytes(a) {
7961
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
7962
- }
7963
- function abytes(item) {
7964
- if (!isBytes(item))
7965
- throw new Error('Uint8Array expected');
7966
- }
7967
8217
  function abool(title, value) {
7968
8218
  if (typeof value !== 'boolean')
7969
8219
  throw new Error(title + ' boolean expected, got ' + value);
@@ -7976,66 +8226,7 @@ function numberToHexUnpadded$1(num) {
7976
8226
  function hexToNumber$1(hex) {
7977
8227
  if (typeof hex !== 'string')
7978
8228
  throw new Error('hex string expected, got ' + typeof hex);
7979
- return hex === '' ? _0n$a : BigInt('0x' + hex); // Big Endian
7980
- }
7981
- // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
7982
- const hasHexBuiltin =
7983
- // @ts-ignore
7984
- typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
7985
- // Array where index 0xf0 (240) is mapped to string 'f0'
7986
- const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
7987
- /**
7988
- * Convert byte array to hex string. Uses built-in function, when available.
7989
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
7990
- */
7991
- function bytesToHex$1(bytes) {
7992
- abytes(bytes);
7993
- // @ts-ignore
7994
- if (hasHexBuiltin)
7995
- return bytes.toHex();
7996
- // pre-caching improves the speed 6x
7997
- let hex = '';
7998
- for (let i = 0; i < bytes.length; i++) {
7999
- hex += hexes$1[bytes[i]];
8000
- }
8001
- return hex;
8002
- }
8003
- // We use optimized technique to convert hex string to byte array
8004
- const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
8005
- function asciiToBase16(ch) {
8006
- if (ch >= asciis._0 && ch <= asciis._9)
8007
- return ch - asciis._0; // '2' => 50-48
8008
- if (ch >= asciis.A && ch <= asciis.F)
8009
- return ch - (asciis.A - 10); // 'B' => 66-(65-10)
8010
- if (ch >= asciis.a && ch <= asciis.f)
8011
- return ch - (asciis.a - 10); // 'b' => 98-(97-10)
8012
- return;
8013
- }
8014
- /**
8015
- * Convert hex string to byte array. Uses built-in function, when available.
8016
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
8017
- */
8018
- function hexToBytes$1(hex) {
8019
- if (typeof hex !== 'string')
8020
- throw new Error('hex string expected, got ' + typeof hex);
8021
- // @ts-ignore
8022
- if (hasHexBuiltin)
8023
- return Uint8Array.fromHex(hex);
8024
- const hl = hex.length;
8025
- const al = hl / 2;
8026
- if (hl % 2)
8027
- throw new Error('hex string expected, got unpadded hex of length ' + hl);
8028
- const array = new Uint8Array(al);
8029
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
8030
- const n1 = asciiToBase16(hex.charCodeAt(hi));
8031
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
8032
- if (n1 === undefined || n2 === undefined) {
8033
- const char = hex[hi] + hex[hi + 1];
8034
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
8035
- }
8036
- array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
8037
- }
8038
- return array;
8229
+ return hex === '' ? _0n$9 : BigInt('0x' + hex); // Big Endian
8039
8230
  }
8040
8231
  // BE: Big Endian, LE: Little Endian
8041
8232
  function bytesToNumberBE$1(bytes) {
@@ -8084,25 +8275,16 @@ function ensureBytes$1(title, hex, expectedLength) {
8084
8275
  return res;
8085
8276
  }
8086
8277
  /**
8087
- * Copies several Uint8Arrays into one.
8278
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
8088
8279
  */
8089
- function concatBytes$2(...arrays) {
8090
- let sum = 0;
8091
- for (let i = 0; i < arrays.length; i++) {
8092
- const a = arrays[i];
8093
- abytes(a);
8094
- sum += a.length;
8095
- }
8096
- const res = new Uint8Array(sum);
8097
- for (let i = 0, pad = 0; i < arrays.length; i++) {
8098
- const a = arrays[i];
8099
- res.set(a, pad);
8100
- pad += a.length;
8101
- }
8102
- return res;
8103
- }
8280
+ // export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
8281
+ /**
8282
+ * Converts bytes to string using UTF8 encoding.
8283
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
8284
+ */
8285
+ // export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
8104
8286
  // Is positive bigint
8105
- const isPosBig = (n) => typeof n === 'bigint' && _0n$a <= n;
8287
+ const isPosBig = (n) => typeof n === 'bigint' && _0n$9 <= n;
8106
8288
  function inRange(n, min, max) {
8107
8289
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
8108
8290
  }
@@ -8128,7 +8310,7 @@ function aInRange(title, n, min, max) {
8128
8310
  */
8129
8311
  function bitLen$1(n) {
8130
8312
  let len;
8131
- for (len = 0; n > _0n$a; n >>= _1n$b, len += 1)
8313
+ for (len = 0; n > _0n$9; n >>= _1n$b, len += 1)
8132
8314
  ;
8133
8315
  return len;
8134
8316
  }
@@ -8137,9 +8319,6 @@ function bitLen$1(n) {
8137
8319
  * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
8138
8320
  */
8139
8321
  const bitMask$1 = (n) => (_1n$b << BigInt(n)) - _1n$b;
8140
- // DRBG
8141
- const u8n$1 = (len) => new Uint8Array(len); // creates Uint8Array
8142
- const u8fr$1 = (arr) => Uint8Array.from(arr); // another shortcut
8143
8322
  /**
8144
8323
  * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
8145
8324
  * @returns function that will call DRBG until 2nd arg returns something meaningful
@@ -8155,8 +8334,10 @@ function createHmacDrbg$1(hashLen, qByteLen, hmacFn) {
8155
8334
  if (typeof hmacFn !== 'function')
8156
8335
  throw new Error('hmacFn must be a function');
8157
8336
  // Step B, Step C: set hashLen to 8*ceil(hlen/8)
8158
- let v = u8n$1(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
8159
- let k = u8n$1(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
8337
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
8338
+ const u8of = (byte) => Uint8Array.of(byte); // another shortcut
8339
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
8340
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
8160
8341
  let i = 0; // Iterations counter, will throw when over 1000
8161
8342
  const reset = () => {
8162
8343
  v.fill(1);
@@ -8164,13 +8345,13 @@ function createHmacDrbg$1(hashLen, qByteLen, hmacFn) {
8164
8345
  i = 0;
8165
8346
  };
8166
8347
  const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
8167
- const reseed = (seed = u8n$1(0)) => {
8348
+ const reseed = (seed = u8n(0)) => {
8168
8349
  // HMAC-DRBG reseed() function. Steps D-G
8169
- k = h(u8fr$1([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
8350
+ k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
8170
8351
  v = h(); // v = hmac(k || v)
8171
8352
  if (seed.length === 0)
8172
8353
  return;
8173
- k = h(u8fr$1([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
8354
+ k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
8174
8355
  v = h(); // v = hmac(k || v)
8175
8356
  };
8176
8357
  const gen = () => {
@@ -8194,40 +8375,23 @@ function createHmacDrbg$1(hashLen, qByteLen, hmacFn) {
8194
8375
  while (!(res = pred(gen())))
8195
8376
  reseed();
8196
8377
  reset();
8197
- return res;
8198
- };
8199
- return genUntil;
8200
- }
8201
- // Validating curves and fields
8202
- const validatorFns$1 = {
8203
- bigint: (val) => typeof val === 'bigint',
8204
- function: (val) => typeof val === 'function',
8205
- boolean: (val) => typeof val === 'boolean',
8206
- string: (val) => typeof val === 'string',
8207
- stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),
8208
- isSafeInteger: (val) => Number.isSafeInteger(val),
8209
- array: (val) => Array.isArray(val),
8210
- field: (val, object) => object.Fp.isValid(val),
8211
- hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
8212
- };
8213
- // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
8214
- function validateObject$1(object, validators, optValidators = {}) {
8215
- const checkField = (fieldName, type, isOptional) => {
8216
- const checkVal = validatorFns$1[type];
8217
- if (typeof checkVal !== 'function')
8218
- throw new Error('invalid validator function');
8378
+ return res;
8379
+ };
8380
+ return genUntil;
8381
+ }
8382
+ function _validateObject(object, fields, optFields = {}) {
8383
+ if (!object || typeof object !== 'object')
8384
+ throw new Error('expected valid options object');
8385
+ function checkField(fieldName, expectedType, isOpt) {
8219
8386
  const val = object[fieldName];
8220
- if (isOptional && val === undefined)
8387
+ if (isOpt && val === undefined)
8221
8388
  return;
8222
- if (!checkVal(val, object)) {
8223
- throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
8224
- }
8225
- };
8226
- for (const [fieldName, type] of Object.entries(validators))
8227
- checkField(fieldName, type, false);
8228
- for (const [fieldName, type] of Object.entries(optValidators))
8229
- checkField(fieldName, type, true);
8230
- return object;
8389
+ const current = typeof val;
8390
+ if (current !== expectedType || val === null)
8391
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
8392
+ }
8393
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
8394
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
8231
8395
  }
8232
8396
  /**
8233
8397
  * Memoizes (caches) computation result.
@@ -8244,25 +8408,26 @@ function memoized(fn) {
8244
8408
  return computed;
8245
8409
  };
8246
8410
  }/**
8247
- * Utils for modular division and finite fields.
8248
- * A finite field over 11 is integer number operations `mod 11`.
8411
+ * Utils for modular division and fields.
8412
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
8249
8413
  * There is no division: it is replaced by modular multiplicative inverse.
8250
8414
  * @module
8251
8415
  */
8252
8416
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8253
8417
  // prettier-ignore
8254
- const _0n$9 = BigInt(0), _1n$a = BigInt(1), _2n$6 = /* @__PURE__ */ BigInt(2), _3n$3 = /* @__PURE__ */ BigInt(3);
8418
+ const _0n$8 = BigInt(0), _1n$a = BigInt(1), _2n$7 = /* @__PURE__ */ BigInt(2), _3n$3 = /* @__PURE__ */ BigInt(3);
8255
8419
  // prettier-ignore
8256
- const _4n$2 = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5), _8n$1 = /* @__PURE__ */ BigInt(8);
8420
+ const _4n$2 = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5);
8421
+ const _8n$1 = /* @__PURE__ */ BigInt(8);
8257
8422
  // Calculates a modulo b
8258
8423
  function mod$1(a, b) {
8259
8424
  const result = a % b;
8260
- return result >= _0n$9 ? result : b + result;
8425
+ return result >= _0n$8 ? result : b + result;
8261
8426
  }
8262
8427
  /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
8263
8428
  function pow2$1(x, power, modulo) {
8264
8429
  let res = x;
8265
- while (power-- > _0n$9) {
8430
+ while (power-- > _0n$8) {
8266
8431
  res *= res;
8267
8432
  res %= modulo;
8268
8433
  }
@@ -8273,16 +8438,16 @@ function pow2$1(x, power, modulo) {
8273
8438
  * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
8274
8439
  */
8275
8440
  function invert$1(number, modulo) {
8276
- if (number === _0n$9)
8441
+ if (number === _0n$8)
8277
8442
  throw new Error('invert: expected non-zero number');
8278
- if (modulo <= _0n$9)
8443
+ if (modulo <= _0n$8)
8279
8444
  throw new Error('invert: expected positive modulus, got ' + modulo);
8280
8445
  // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
8281
8446
  let a = mod$1(number, modulo);
8282
8447
  let b = modulo;
8283
8448
  // prettier-ignore
8284
- let x = _0n$9, u = _1n$a;
8285
- while (a !== _0n$9) {
8449
+ let x = _0n$8, u = _1n$a;
8450
+ while (a !== _0n$8) {
8286
8451
  // JIT applies optimization if those two lines follow each other
8287
8452
  const q = b / a;
8288
8453
  const r = b % a;
@@ -8309,10 +8474,10 @@ function sqrt3mod4(Fp, n) {
8309
8474
  }
8310
8475
  function sqrt5mod8(Fp, n) {
8311
8476
  const p5div8 = (Fp.ORDER - _5n$1) / _8n$1;
8312
- const n2 = Fp.mul(n, _2n$6);
8477
+ const n2 = Fp.mul(n, _2n$7);
8313
8478
  const v = Fp.pow(n2, p5div8);
8314
8479
  const nv = Fp.mul(n, v);
8315
- const i = Fp.mul(Fp.mul(nv, _2n$6), v);
8480
+ const i = Fp.mul(Fp.mul(nv, _2n$7), v);
8316
8481
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
8317
8482
  if (!Fp.eql(Fp.sqr(root), n))
8318
8483
  throw new Error('Cannot find square root');
@@ -8349,17 +8514,18 @@ function sqrt5mod8(Fp, n) {
8349
8514
  */
8350
8515
  function tonelliShanks$1(P) {
8351
8516
  // Initialization (precomputation).
8517
+ // Caching initialization could boost perf by 7%.
8352
8518
  if (P < BigInt(3))
8353
8519
  throw new Error('sqrt is not defined for small field');
8354
8520
  // Factor P - 1 = Q * 2^S, where Q is odd
8355
8521
  let Q = P - _1n$a;
8356
8522
  let S = 0;
8357
- while (Q % _2n$6 === _0n$9) {
8358
- Q /= _2n$6;
8523
+ while (Q % _2n$7 === _0n$8) {
8524
+ Q /= _2n$7;
8359
8525
  S++;
8360
8526
  }
8361
8527
  // Find the first quadratic non-residue Z >= 2
8362
- let Z = _2n$6;
8528
+ let Z = _2n$7;
8363
8529
  const _Fp = Field$1(P);
8364
8530
  while (FpLegendre(_Fp, Z) === 1) {
8365
8531
  // Basic primality test for P. After x iterations, chance of
@@ -8373,7 +8539,7 @@ function tonelliShanks$1(P) {
8373
8539
  // Slow-path
8374
8540
  // TODO: test on Fp2 and others
8375
8541
  let cc = _Fp.pow(Z, Q); // c = z^Q
8376
- const Q1div2 = (Q + _1n$a) / _2n$6;
8542
+ const Q1div2 = (Q + _1n$a) / _2n$7;
8377
8543
  return function tonelliSlow(Fp, n) {
8378
8544
  if (Fp.is0(n))
8379
8545
  return n;
@@ -8442,14 +8608,18 @@ function validateField$1(field) {
8442
8608
  const initial = {
8443
8609
  ORDER: 'bigint',
8444
8610
  MASK: 'bigint',
8445
- BYTES: 'isSafeInteger',
8446
- BITS: 'isSafeInteger',
8611
+ BYTES: 'number',
8612
+ BITS: 'number',
8447
8613
  };
8448
8614
  const opts = FIELD_FIELDS$1.reduce((map, val) => {
8449
8615
  map[val] = 'function';
8450
8616
  return map;
8451
8617
  }, initial);
8452
- return validateObject$1(field, opts);
8618
+ _validateObject(field, opts);
8619
+ // const max = 16384;
8620
+ // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
8621
+ // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
8622
+ return field;
8453
8623
  }
8454
8624
  // Generic field functions
8455
8625
  /**
@@ -8457,15 +8627,15 @@ function validateField$1(field) {
8457
8627
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
8458
8628
  */
8459
8629
  function FpPow$1(Fp, num, power) {
8460
- if (power < _0n$9)
8630
+ if (power < _0n$8)
8461
8631
  throw new Error('invalid exponent, negatives unsupported');
8462
- if (power === _0n$9)
8632
+ if (power === _0n$8)
8463
8633
  return Fp.ONE;
8464
8634
  if (power === _1n$a)
8465
8635
  return num;
8466
8636
  let p = Fp.ONE;
8467
8637
  let d = num;
8468
- while (power > _0n$9) {
8638
+ while (power > _0n$8) {
8469
8639
  if (power & _1n$a)
8470
8640
  p = Fp.mul(p, d);
8471
8641
  d = Fp.sqr(d);
@@ -8510,7 +8680,7 @@ function FpInvertBatch$1(Fp, nums, passZero = false) {
8510
8680
  function FpLegendre(Fp, n) {
8511
8681
  // We can use 3rd argument as optional cache of this value
8512
8682
  // but seems unneeded for now. The operation is very fast.
8513
- const p1mod2 = (Fp.ORDER - _1n$a) / _2n$6;
8683
+ const p1mod2 = (Fp.ORDER - _1n$a) / _2n$7;
8514
8684
  const powered = Fp.pow(n, p1mod2);
8515
8685
  const yes = Fp.eql(powered, Fp.ONE);
8516
8686
  const zero = Fp.eql(powered, Fp.ZERO);
@@ -8529,24 +8699,47 @@ function nLength$1(n, nBitLength) {
8529
8699
  return { nBitLength: _nBitLength, nByteLength };
8530
8700
  }
8531
8701
  /**
8532
- * Initializes a finite field over prime.
8533
- * Major performance optimizations:
8534
- * * a) denormalized operations like mulN instead of mul
8535
- * * b) same object shape: never add or remove keys
8536
- * * c) Object.freeze
8702
+ * Creates a finite field. Major performance optimizations:
8703
+ * * 1. Denormalized operations like mulN instead of mul.
8704
+ * * 2. Identical object shape: never add or remove keys.
8705
+ * * 3. `Object.freeze`.
8537
8706
  * Fragile: always run a benchmark on a change.
8538
8707
  * Security note: operations don't check 'isValid' for all elements for performance reasons,
8539
8708
  * it is caller responsibility to check this.
8540
8709
  * This is low-level code, please make sure you know what you're doing.
8541
- * @param ORDER prime positive bigint
8710
+ *
8711
+ * Note about field properties:
8712
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
8713
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
8714
+ *
8715
+ * @param ORDER field order, probably prime, or could be composite
8542
8716
  * @param bitLen how many bits the field consumes
8543
- * @param isLE (def: false) if encoding / decoding should be in little-endian
8717
+ * @param isLE (default: false) if encoding / decoding should be in little-endian
8544
8718
  * @param redef optional faster redefinitions of sqrt and other methods
8545
8719
  */
8546
- function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
8547
- if (ORDER <= _0n$9)
8720
+ function Field$1(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
8721
+ if (ORDER <= _0n$8)
8548
8722
  throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
8549
- const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen);
8723
+ let _nbitLength = undefined;
8724
+ let _sqrt = undefined;
8725
+ if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
8726
+ if (opts.sqrt || isLE)
8727
+ throw new Error('cannot specify opts in two arguments');
8728
+ const _opts = bitLenOrOpts;
8729
+ if (_opts.BITS)
8730
+ _nbitLength = _opts.BITS;
8731
+ if (_opts.sqrt)
8732
+ _sqrt = _opts.sqrt;
8733
+ if (typeof _opts.isLE === 'boolean')
8734
+ isLE = _opts.isLE;
8735
+ }
8736
+ else {
8737
+ if (typeof bitLenOrOpts === 'number')
8738
+ _nbitLength = bitLenOrOpts;
8739
+ if (opts.sqrt)
8740
+ _sqrt = opts.sqrt;
8741
+ }
8742
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, _nbitLength);
8550
8743
  if (BYTES > 2048)
8551
8744
  throw new Error('invalid field: expected ORDER of <= 2048 bytes');
8552
8745
  let sqrtP; // cached sqrtP
@@ -8556,15 +8749,17 @@ function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
8556
8749
  BITS,
8557
8750
  BYTES,
8558
8751
  MASK: bitMask$1(BITS),
8559
- ZERO: _0n$9,
8752
+ ZERO: _0n$8,
8560
8753
  ONE: _1n$a,
8561
8754
  create: (num) => mod$1(num, ORDER),
8562
8755
  isValid: (num) => {
8563
8756
  if (typeof num !== 'bigint')
8564
8757
  throw new Error('invalid field element: expected bigint, got ' + typeof num);
8565
- return _0n$9 <= num && num < ORDER; // 0 is valid element, but it's not invertible
8758
+ return _0n$8 <= num && num < ORDER; // 0 is valid element, but it's not invertible
8566
8759
  },
8567
- is0: (num) => num === _0n$9,
8760
+ is0: (num) => num === _0n$8,
8761
+ // is valid and invertible
8762
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
8568
8763
  isOdd: (num) => (num & _1n$a) === _1n$a,
8569
8764
  neg: (num) => mod$1(-num, ORDER),
8570
8765
  eql: (lhs, rhs) => lhs === rhs,
@@ -8580,7 +8775,7 @@ function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
8580
8775
  subN: (lhs, rhs) => lhs - rhs,
8581
8776
  mulN: (lhs, rhs) => lhs * rhs,
8582
8777
  inv: (num) => invert$1(num, ORDER),
8583
- sqrt: redef.sqrt ||
8778
+ sqrt: _sqrt ||
8584
8779
  ((n) => {
8585
8780
  if (!sqrtP)
8586
8781
  sqrtP = FpSqrt$1(ORDER);
@@ -8653,12 +8848,25 @@ function mapHashToField$1(key, fieldOrder, isLE = false) {
8653
8848
  * @module
8654
8849
  */
8655
8850
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8656
- const _0n$8 = BigInt(0);
8851
+ const _0n$7 = BigInt(0);
8657
8852
  const _1n$9 = BigInt(1);
8658
- function constTimeNegate(condition, item) {
8853
+ function negateCt(condition, item) {
8659
8854
  const neg = item.negate();
8660
8855
  return condition ? neg : item;
8661
8856
  }
8857
+ /**
8858
+ * Takes a bunch of Projective Points but executes only one
8859
+ * inversion on all of them. Inversion is very slow operation,
8860
+ * so this improves performance massively.
8861
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
8862
+ */
8863
+ function normalizeZ(c, property, points) {
8864
+ const getz = (p) => p.pz ;
8865
+ const toInv = FpInvertBatch$1(c.Fp, points.map(getz));
8866
+ // @ts-ignore
8867
+ const affined = points.map((p, i) => p.toAffine(toInv[i]));
8868
+ return affined.map(c.fromAffine);
8869
+ }
8662
8870
  function validateW(W, bits) {
8663
8871
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
8664
8872
  throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
@@ -8718,6 +8926,10 @@ const pointWindowSizes = new WeakMap();
8718
8926
  function getW(P) {
8719
8927
  return pointWindowSizes.get(P) || 1;
8720
8928
  }
8929
+ function assert0(n) {
8930
+ if (n !== _0n$7)
8931
+ throw new Error('invalid wNAF');
8932
+ }
8721
8933
  /**
8722
8934
  * Elliptic curve multiplication of Point by scalar. Fragile.
8723
8935
  * Scalars should always be less than curve order: this should be checked inside of a curve itself.
@@ -8734,14 +8946,14 @@ function getW(P) {
8734
8946
  */
8735
8947
  function wNAF$1(c, bits) {
8736
8948
  return {
8737
- constTimeNegate,
8949
+ constTimeNegate: negateCt,
8738
8950
  hasPrecomputes(elm) {
8739
8951
  return getW(elm) !== 1;
8740
8952
  },
8741
8953
  // non-const time multiplication ladder
8742
8954
  unsafeLadder(elm, n, p = c.ZERO) {
8743
8955
  let d = elm;
8744
- while (n > _0n$8) {
8956
+ while (n > _0n$7) {
8745
8957
  if (n & _1n$9)
8746
8958
  p = p.add(d);
8747
8959
  d = d.double();
@@ -8807,13 +9019,14 @@ function wNAF$1(c, bits) {
8807
9019
  if (isZero) {
8808
9020
  // bits are 0: add garbage to fake point
8809
9021
  // Important part for const-time getPublicKey: add random "noise" point to f.
8810
- f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
9022
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
8811
9023
  }
8812
9024
  else {
8813
9025
  // bits are 1: add to result point
8814
- p = p.add(constTimeNegate(isNeg, precomputes[offset]));
9026
+ p = p.add(negateCt(isNeg, precomputes[offset]));
8815
9027
  }
8816
9028
  }
9029
+ assert0(n);
8817
9030
  // Return both real and fake points: JIT won't eliminate f.
8818
9031
  // At this point there is a way to F be infinity-point even if p is not,
8819
9032
  // which makes it less const-time: around 1 bigint multiply.
@@ -8830,7 +9043,7 @@ function wNAF$1(c, bits) {
8830
9043
  wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
8831
9044
  const wo = calcWOpts(W, bits);
8832
9045
  for (let window = 0; window < wo.windows; window++) {
8833
- if (n === _0n$8)
9046
+ if (n === _0n$7)
8834
9047
  break; // Early-exit, skip 0 value
8835
9048
  const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
8836
9049
  n = nextN;
@@ -8844,6 +9057,7 @@ function wNAF$1(c, bits) {
8844
9057
  acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
8845
9058
  }
8846
9059
  }
9060
+ assert0(n);
8847
9061
  return acc;
8848
9062
  },
8849
9063
  getPrecomputes(W, P, transform) {
@@ -8851,8 +9065,12 @@ function wNAF$1(c, bits) {
8851
9065
  let comp = pointPrecomputes.get(P);
8852
9066
  if (!comp) {
8853
9067
  comp = this.precomputeWindow(P, W);
8854
- if (W !== 1)
8855
- pointPrecomputes.set(P, transform(comp));
9068
+ if (W !== 1) {
9069
+ // Doing transform outside of if brings 15% perf hit
9070
+ if (typeof transform === 'function')
9071
+ comp = transform(comp);
9072
+ pointPrecomputes.set(P, comp);
9073
+ }
8856
9074
  }
8857
9075
  return comp;
8858
9076
  },
@@ -8876,6 +9094,25 @@ function wNAF$1(c, bits) {
8876
9094
  },
8877
9095
  };
8878
9096
  }
9097
+ /**
9098
+ * Endomorphism-specific multiplication for Koblitz curves.
9099
+ * Cost: 128 dbl, 0-256 adds.
9100
+ */
9101
+ function mulEndoUnsafe(c, point, k1, k2) {
9102
+ let acc = point;
9103
+ let p1 = c.ZERO;
9104
+ let p2 = c.ZERO;
9105
+ while (k1 > _0n$7 || k2 > _0n$7) {
9106
+ if (k1 & _1n$9)
9107
+ p1 = p1.add(acc);
9108
+ if (k2 & _1n$9)
9109
+ p2 = p2.add(acc);
9110
+ acc = acc.double();
9111
+ k1 >>= _1n$9;
9112
+ k2 >>= _1n$9;
9113
+ }
9114
+ return { p1, p2 };
9115
+ }
8879
9116
  /**
8880
9117
  * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
8881
9118
  * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
@@ -8933,39 +9170,39 @@ function pippenger(c, fieldN, points, scalars) {
8933
9170
  }
8934
9171
  return sum;
8935
9172
  }
8936
- function validateBasic$1(curve) {
8937
- validateField$1(curve.Fp);
8938
- validateObject$1(curve, {
8939
- n: 'bigint',
8940
- h: 'bigint',
8941
- Gx: 'field',
8942
- Gy: 'field',
8943
- }, {
8944
- nBitLength: 'isSafeInteger',
8945
- nByteLength: 'isSafeInteger',
8946
- });
8947
- // Set defaults
8948
- return Object.freeze({
8949
- ...nLength$1(curve.n, curve.nBitLength),
8950
- ...curve,
8951
- ...{ p: curve.Fp.ORDER },
8952
- });
9173
+ function createField(order, field) {
9174
+ if (field) {
9175
+ if (field.ORDER !== order)
9176
+ throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
9177
+ validateField$1(field);
9178
+ return field;
9179
+ }
9180
+ else {
9181
+ return Field$1(order);
9182
+ }
9183
+ }
9184
+ /** Validates CURVE opts and creates fields */
9185
+ function _createCurveFields(type, CURVE, curveOpts = {}) {
9186
+ if (!CURVE || typeof CURVE !== 'object')
9187
+ throw new Error(`expected valid ${type} CURVE object`);
9188
+ for (const p of ['p', 'n', 'h']) {
9189
+ const val = CURVE[p];
9190
+ if (!(typeof val === 'bigint' && val > _0n$7))
9191
+ throw new Error(`CURVE.${p} must be positive bigint`);
9192
+ }
9193
+ const Fp = createField(CURVE.p, curveOpts.Fp);
9194
+ const Fn = createField(CURVE.n, curveOpts.Fn);
9195
+ const _b = 'b' ;
9196
+ const params = ['Gx', 'Gy', 'a', _b];
9197
+ for (const p of params) {
9198
+ // @ts-ignore
9199
+ if (!Fp.isValid(CURVE[p]))
9200
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
9201
+ }
9202
+ return { Fp, Fn };
8953
9203
  }/**
8954
9204
  * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
8955
9205
  *
8956
- * ### Parameters
8957
- *
8958
- * To initialize a weierstrass curve, one needs to pass following params:
8959
- *
8960
- * * a: formula param
8961
- * * b: formula param
8962
- * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field
8963
- * * n: order of prime subgroup a.k.a total amount of valid curve points
8964
- * * Gx: Base point (x, y) aka generator point. Gx = x coordinate
8965
- * * Gy: ...y coordinate
8966
- * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
8967
- * * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
8968
- *
8969
9206
  * ### Design rationale for types
8970
9207
  *
8971
9208
  * * Interaction between classes from different curves should fail:
@@ -8990,40 +9227,12 @@ function validateBasic$1(curve) {
8990
9227
  * @module
8991
9228
  */
8992
9229
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8993
- // prettier-ignore
8994
9230
  function validateSigVerOpts(opts) {
8995
9231
  if (opts.lowS !== undefined)
8996
9232
  abool('lowS', opts.lowS);
8997
9233
  if (opts.prehash !== undefined)
8998
9234
  abool('prehash', opts.prehash);
8999
9235
  }
9000
- function validatePointOpts$1(curve) {
9001
- const opts = validateBasic$1(curve);
9002
- validateObject$1(opts, {
9003
- a: 'field',
9004
- b: 'field',
9005
- }, {
9006
- allowInfinityPoint: 'boolean',
9007
- allowedPrivateKeyLengths: 'array',
9008
- clearCofactor: 'function',
9009
- fromBytes: 'function',
9010
- isTorsionFree: 'function',
9011
- toBytes: 'function',
9012
- wrapPrivateKey: 'boolean',
9013
- });
9014
- const { endo, Fp, a } = opts;
9015
- if (endo) {
9016
- if (!Fp.eql(a, Fp.ZERO)) {
9017
- throw new Error('invalid endo: CURVE.a must be 0');
9018
- }
9019
- if (typeof endo !== 'object' ||
9020
- typeof endo.beta !== 'bigint' ||
9021
- typeof endo.splitScalar !== 'function') {
9022
- throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
9023
- }
9024
- }
9025
- return Object.freeze({ ...opts });
9026
- }
9027
9236
  class DERErr extends Error {
9028
9237
  constructor(m = '') {
9029
9238
  super(m);
@@ -9100,7 +9309,7 @@ const DER$1 = {
9100
9309
  _int: {
9101
9310
  encode(num) {
9102
9311
  const { Err: E } = DER$1;
9103
- if (num < _0n$7)
9312
+ if (num < _0n$6)
9104
9313
  throw new E('integer: negative integers are not allowed');
9105
9314
  let hex = numberToHexUnpadded$1(num);
9106
9315
  // Pad with zero byte if negative flag is present
@@ -9140,40 +9349,139 @@ const DER$1 = {
9140
9349
  return tlv.encode(0x30, seq);
9141
9350
  },
9142
9351
  };
9143
- function numToSizedHex(num, size) {
9144
- return bytesToHex$1(numberToBytesBE$1(num, size));
9145
- }
9146
9352
  // Be friendly to bad ECMAScript parsers by not using bigint literals
9147
9353
  // prettier-ignore
9148
- const _0n$7 = BigInt(0), _1n$8 = BigInt(1); BigInt(2); const _3n$2 = BigInt(3), _4n$1 = BigInt(4);
9149
- function weierstrassPoints$1(opts) {
9150
- const CURVE = validatePointOpts$1(opts);
9151
- const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
9152
- const Fn = Field$1(CURVE.n, CURVE.nBitLength);
9153
- const toBytes = CURVE.toBytes ||
9154
- ((_c, point, _isCompressed) => {
9155
- const a = point.toAffine();
9156
- return concatBytes$2(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
9157
- });
9158
- const fromBytes = CURVE.fromBytes ||
9159
- ((bytes) => {
9160
- // const head = bytes[0];
9161
- const tail = bytes.subarray(1);
9162
- // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
9163
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
9164
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
9165
- return { x, y };
9166
- });
9354
+ const _0n$6 = BigInt(0), _1n$8 = BigInt(1), _2n$6 = BigInt(2), _3n$2 = BigInt(3), _4n$1 = BigInt(4);
9355
+ // TODO: remove
9356
+ function _legacyHelperEquat(Fp, a, b) {
9167
9357
  /**
9168
9358
  * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
9169
9359
  * @returns y²
9170
9360
  */
9171
9361
  function weierstrassEquation(x) {
9172
- const { a, b } = CURVE;
9173
9362
  const x2 = Fp.sqr(x); // x * x
9174
9363
  const x3 = Fp.mul(x2, x); // x² * x
9175
9364
  return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
9176
9365
  }
9366
+ return weierstrassEquation;
9367
+ }
9368
+ function _legacyHelperNormPriv(Fn, allowedPrivateKeyLengths, wrapPrivateKey) {
9369
+ const { BYTES: expected } = Fn;
9370
+ // Validates if priv key is valid and converts it to bigint.
9371
+ function normPrivateKeyToScalar(key) {
9372
+ let num;
9373
+ if (typeof key === 'bigint') {
9374
+ num = key;
9375
+ }
9376
+ else {
9377
+ let bytes = ensureBytes$1('private key', key);
9378
+ if (allowedPrivateKeyLengths) {
9379
+ if (!allowedPrivateKeyLengths.includes(bytes.length * 2))
9380
+ throw new Error('invalid private key');
9381
+ const padded = new Uint8Array(expected);
9382
+ padded.set(bytes, padded.length - bytes.length);
9383
+ bytes = padded;
9384
+ }
9385
+ try {
9386
+ num = Fn.fromBytes(bytes);
9387
+ }
9388
+ catch (error) {
9389
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
9390
+ }
9391
+ }
9392
+ if (wrapPrivateKey)
9393
+ num = Fn.create(num); // disabled by default, enabled for BLS
9394
+ if (!Fn.isValidNot0(num))
9395
+ throw new Error('invalid private key: out of range [1..N-1]');
9396
+ return num;
9397
+ }
9398
+ return normPrivateKeyToScalar;
9399
+ }
9400
+ function weierstrassN(CURVE, curveOpts = {}) {
9401
+ const { Fp, Fn } = _createCurveFields('weierstrass', CURVE, curveOpts);
9402
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
9403
+ _validateObject(curveOpts, {}, {
9404
+ allowInfinityPoint: 'boolean',
9405
+ clearCofactor: 'function',
9406
+ isTorsionFree: 'function',
9407
+ fromBytes: 'function',
9408
+ toBytes: 'function',
9409
+ endo: 'object',
9410
+ wrapPrivateKey: 'boolean',
9411
+ });
9412
+ const { endo } = curveOpts;
9413
+ if (endo) {
9414
+ // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
9415
+ if (!Fp.is0(CURVE.a) ||
9416
+ typeof endo.beta !== 'bigint' ||
9417
+ typeof endo.splitScalar !== 'function') {
9418
+ throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
9419
+ }
9420
+ }
9421
+ function assertCompressionIsSupported() {
9422
+ if (!Fp.isOdd)
9423
+ throw new Error('compression is not supported: Field does not have .isOdd()');
9424
+ }
9425
+ // Implements IEEE P1363 point encoding
9426
+ function pointToBytes(_c, point, isCompressed) {
9427
+ const { x, y } = point.toAffine();
9428
+ const bx = Fp.toBytes(x);
9429
+ abool('isCompressed', isCompressed);
9430
+ if (isCompressed) {
9431
+ assertCompressionIsSupported();
9432
+ const hasEvenY = !Fp.isOdd(y);
9433
+ return concatBytes$2(pprefix(hasEvenY), bx);
9434
+ }
9435
+ else {
9436
+ return concatBytes$2(Uint8Array.of(0x04), bx, Fp.toBytes(y));
9437
+ }
9438
+ }
9439
+ function pointFromBytes(bytes) {
9440
+ abytes(bytes);
9441
+ const L = Fp.BYTES;
9442
+ const LC = L + 1; // length compressed, e.g. 33 for 32-byte field
9443
+ const LU = 2 * L + 1; // length uncompressed, e.g. 65 for 32-byte field
9444
+ const length = bytes.length;
9445
+ const head = bytes[0];
9446
+ const tail = bytes.subarray(1);
9447
+ // No actual validation is done here: use .assertValidity()
9448
+ if (length === LC && (head === 0x02 || head === 0x03)) {
9449
+ const x = Fp.fromBytes(tail);
9450
+ if (!Fp.isValid(x))
9451
+ throw new Error('bad point: is not on curve, wrong x');
9452
+ const y2 = weierstrassEquation(x); // y² = x³ + ax + b
9453
+ let y;
9454
+ try {
9455
+ y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
9456
+ }
9457
+ catch (sqrtError) {
9458
+ const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
9459
+ throw new Error('bad point: is not on curve, sqrt error' + err);
9460
+ }
9461
+ assertCompressionIsSupported();
9462
+ const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
9463
+ const isHeadOdd = (head & 1) === 1; // ECDSA-specific
9464
+ if (isHeadOdd !== isYOdd)
9465
+ y = Fp.neg(y);
9466
+ return { x, y };
9467
+ }
9468
+ else if (length === LU && head === 0x04) {
9469
+ // TODO: more checks
9470
+ const x = Fp.fromBytes(tail.subarray(L * 0, L * 1));
9471
+ const y = Fp.fromBytes(tail.subarray(L * 1, L * 2));
9472
+ if (!isValidXY(x, y))
9473
+ throw new Error('bad point: is not on curve');
9474
+ return { x, y };
9475
+ }
9476
+ else {
9477
+ throw new Error(`bad point: got length ${length}, expected compressed=${LC} or uncompressed=${LU}`);
9478
+ }
9479
+ }
9480
+ const toBytes = curveOpts.toBytes || pointToBytes;
9481
+ const fromBytes = curveOpts.fromBytes || pointFromBytes;
9482
+ const weierstrassEquation = _legacyHelperEquat(Fp, CURVE.a, CURVE.b);
9483
+ // TODO: move top-level
9484
+ /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
9177
9485
  function isValidXY(x, y) {
9178
9486
  const left = Fp.sqr(y); // y²
9179
9487
  const right = weierstrassEquation(x); // x³ + ax + b
@@ -9189,36 +9497,11 @@ function weierstrassPoints$1(opts) {
9189
9497
  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
9190
9498
  if (Fp.is0(Fp.add(_4a3, _27b2)))
9191
9499
  throw new Error('bad curve params: a or b');
9192
- // Valid group elements reside in range 1..n-1
9193
- function isWithinCurveOrder(num) {
9194
- return inRange(num, _1n$8, CURVE.n);
9195
- }
9196
- // Validates if priv key is valid and converts it to bigint.
9197
- // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
9198
- function normPrivateKeyToScalar(key) {
9199
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
9200
- if (lengths && typeof key !== 'bigint') {
9201
- if (isBytes(key))
9202
- key = bytesToHex$1(key);
9203
- // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
9204
- if (typeof key !== 'string' || !lengths.includes(key.length))
9205
- throw new Error('invalid private key');
9206
- key = key.padStart(nByteLength * 2, '0');
9207
- }
9208
- let num;
9209
- try {
9210
- num =
9211
- typeof key === 'bigint'
9212
- ? key
9213
- : bytesToNumberBE$1(ensureBytes$1('private key', key, nByteLength));
9214
- }
9215
- catch (error) {
9216
- throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
9217
- }
9218
- if (wrapPrivateKey)
9219
- num = mod$1(num, N); // disabled by default, enabled for BLS
9220
- aInRange('private key', num, _1n$8, N); // num in range [1..N-1]
9221
- return num;
9500
+ /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
9501
+ function acoord(title, n, banZero = false) {
9502
+ if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
9503
+ throw new Error(`bad point coordinate ${title}`);
9504
+ return n;
9222
9505
  }
9223
9506
  function aprjpoint(other) {
9224
9507
  if (!(other instanceof Point))
@@ -9254,50 +9537,48 @@ function weierstrassPoints$1(opts) {
9254
9537
  // (0, 1, 0) aka ZERO is invalid in most contexts.
9255
9538
  // In BLS, ZERO can be serialized, so we allow it.
9256
9539
  // (0, 0, 0) is invalid representation of ZERO.
9257
- if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
9540
+ if (curveOpts.allowInfinityPoint && !Fp.is0(p.py))
9258
9541
  return;
9259
9542
  throw new Error('bad point: ZERO');
9260
9543
  }
9261
9544
  // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
9262
9545
  const { x, y } = p.toAffine();
9263
- // Check if x, y are valid field elements
9264
9546
  if (!Fp.isValid(x) || !Fp.isValid(y))
9265
- throw new Error('bad point: x or y not FE');
9547
+ throw new Error('bad point: x or y not field elements');
9266
9548
  if (!isValidXY(x, y))
9267
9549
  throw new Error('bad point: equation left != right');
9268
9550
  if (!p.isTorsionFree())
9269
9551
  throw new Error('bad point: not in prime-order subgroup');
9270
9552
  return true;
9271
9553
  });
9554
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
9555
+ k2p = new Point(Fp.mul(k2p.px, endoBeta), k2p.py, k2p.pz);
9556
+ k1p = negateCt(k1neg, k1p);
9557
+ k2p = negateCt(k2neg, k2p);
9558
+ return k1p.add(k2p);
9559
+ }
9272
9560
  /**
9273
- * Projective Point works in 3d / projective (homogeneous) coordinates: (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
9274
- * Default Point works in 2d / affine coordinates: (x, y)
9561
+ * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
9562
+ * Default Point works in 2d / affine coordinates: (x, y).
9275
9563
  * We're doing calculations in projective, because its operations don't require costly inversion.
9276
9564
  */
9277
9565
  class Point {
9566
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
9278
9567
  constructor(px, py, pz) {
9279
- if (px == null || !Fp.isValid(px))
9280
- throw new Error('x required');
9281
- if (py == null || !Fp.isValid(py) || Fp.is0(py))
9282
- throw new Error('y required');
9283
- if (pz == null || !Fp.isValid(pz))
9284
- throw new Error('z required');
9285
- this.px = px;
9286
- this.py = py;
9287
- this.pz = pz;
9568
+ this.px = acoord('x', px);
9569
+ this.py = acoord('y', py, true);
9570
+ this.pz = acoord('z', pz);
9288
9571
  Object.freeze(this);
9289
9572
  }
9290
- // Does not validate if the point is on-curve.
9291
- // Use fromHex instead, or call assertValidity() later.
9573
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
9292
9574
  static fromAffine(p) {
9293
9575
  const { x, y } = p || {};
9294
9576
  if (!p || !Fp.isValid(x) || !Fp.isValid(y))
9295
9577
  throw new Error('invalid affine point');
9296
9578
  if (p instanceof Point)
9297
9579
  throw new Error('projective point not allowed');
9298
- const is0 = (i) => Fp.eql(i, Fp.ZERO);
9299
- // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
9300
- if (is0(x) && is0(y))
9580
+ // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
9581
+ if (Fp.is0(x) && Fp.is0(y))
9301
9582
  return Point.ZERO;
9302
9583
  return new Point(x, y, Fp.ONE);
9303
9584
  }
@@ -9307,50 +9588,56 @@ function weierstrassPoints$1(opts) {
9307
9588
  get y() {
9308
9589
  return this.toAffine().y;
9309
9590
  }
9310
- /**
9311
- * Takes a bunch of Projective Points but executes only one
9312
- * inversion on all of them. Inversion is very slow operation,
9313
- * so this improves performance massively.
9314
- * Optimization: converts a list of projective points to a list of identical points with Z=1.
9315
- */
9316
9591
  static normalizeZ(points) {
9317
- const toInv = FpInvertBatch$1(Fp, points.map((p) => p.pz));
9318
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
9592
+ return normalizeZ(Point, 'pz', points);
9319
9593
  }
9320
- /**
9321
- * Converts hash string or Uint8Array to Point.
9322
- * @param hex short/long ECDSA hex
9323
- */
9594
+ static fromBytes(bytes) {
9595
+ abytes(bytes);
9596
+ return Point.fromHex(bytes);
9597
+ }
9598
+ /** Converts hash string or Uint8Array to Point. */
9324
9599
  static fromHex(hex) {
9325
9600
  const P = Point.fromAffine(fromBytes(ensureBytes$1('pointHex', hex)));
9326
9601
  P.assertValidity();
9327
9602
  return P;
9328
9603
  }
9329
- // Multiplies generator point by privateKey.
9604
+ /** Multiplies generator point by privateKey. */
9330
9605
  static fromPrivateKey(privateKey) {
9606
+ const normPrivateKeyToScalar = _legacyHelperNormPriv(Fn, curveOpts.allowedPrivateKeyLengths, curveOpts.wrapPrivateKey);
9331
9607
  return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
9332
9608
  }
9333
- // Multiscalar Multiplication
9609
+ /** Multiscalar Multiplication */
9334
9610
  static msm(points, scalars) {
9335
9611
  return pippenger(Point, Fn, points, scalars);
9336
9612
  }
9337
- // "Private method", don't use it directly
9338
- _setWindowSize(windowSize) {
9613
+ /**
9614
+ *
9615
+ * @param windowSize
9616
+ * @param isLazy true will defer table computation until the first multiplication
9617
+ * @returns
9618
+ */
9619
+ precompute(windowSize = 8, isLazy = true) {
9339
9620
  wnaf.setWindowSize(this, windowSize);
9621
+ if (!isLazy)
9622
+ this.multiply(_3n$2); // random number
9623
+ return this;
9340
9624
  }
9341
- // A point on curve is valid if it conforms to equation.
9625
+ /** "Private method", don't use it directly */
9626
+ _setWindowSize(windowSize) {
9627
+ this.precompute(windowSize);
9628
+ }
9629
+ // TODO: return `this`
9630
+ /** A point on curve is valid if it conforms to equation. */
9342
9631
  assertValidity() {
9343
9632
  assertValidMemo(this);
9344
9633
  }
9345
9634
  hasEvenY() {
9346
9635
  const { y } = this.toAffine();
9347
- if (Fp.isOdd)
9348
- return !Fp.isOdd(y);
9349
- throw new Error("Field doesn't support isOdd");
9636
+ if (!Fp.isOdd)
9637
+ throw new Error("Field doesn't support isOdd");
9638
+ return !Fp.isOdd(y);
9350
9639
  }
9351
- /**
9352
- * Compare one point to another.
9353
- */
9640
+ /** Compare one point to another. */
9354
9641
  equals(other) {
9355
9642
  aprjpoint(other);
9356
9643
  const { px: X1, py: Y1, pz: Z1 } = this;
@@ -9359,9 +9646,7 @@ function weierstrassPoints$1(opts) {
9359
9646
  const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
9360
9647
  return U1 && U2;
9361
9648
  }
9362
- /**
9363
- * Flips point to one corresponding to (x, -y) in Affine coordinates.
9364
- */
9649
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
9365
9650
  negate() {
9366
9651
  return new Point(this.px, Fp.neg(this.py), this.pz);
9367
9652
  }
@@ -9466,47 +9751,6 @@ function weierstrassPoints$1(opts) {
9466
9751
  is0() {
9467
9752
  return this.equals(Point.ZERO);
9468
9753
  }
9469
- wNAF(n) {
9470
- return wnaf.wNAFCached(this, n, Point.normalizeZ);
9471
- }
9472
- /**
9473
- * Non-constant-time multiplication. Uses double-and-add algorithm.
9474
- * It's faster, but should only be used when you don't care about
9475
- * an exposed private key e.g. sig verification, which works over *public* keys.
9476
- */
9477
- multiplyUnsafe(sc) {
9478
- const { endo, n: N } = CURVE;
9479
- aInRange('scalar', sc, _0n$7, N);
9480
- const I = Point.ZERO;
9481
- if (sc === _0n$7)
9482
- return I;
9483
- if (this.is0() || sc === _1n$8)
9484
- return this;
9485
- // Case a: no endomorphism. Case b: has precomputes.
9486
- if (!endo || wnaf.hasPrecomputes(this))
9487
- return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
9488
- // Case c: endomorphism
9489
- /** See docs for {@link EndomorphismOpts} */
9490
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
9491
- let k1p = I;
9492
- let k2p = I;
9493
- let d = this;
9494
- while (k1 > _0n$7 || k2 > _0n$7) {
9495
- if (k1 & _1n$8)
9496
- k1p = k1p.add(d);
9497
- if (k2 & _1n$8)
9498
- k2p = k2p.add(d);
9499
- d = d.double();
9500
- k1 >>= _1n$8;
9501
- k2 >>= _1n$8;
9502
- }
9503
- if (k1neg)
9504
- k1p = k1p.negate();
9505
- if (k2neg)
9506
- k2p = k2p.negate();
9507
- k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
9508
- return k1p.add(k2p);
9509
- }
9510
9754
  /**
9511
9755
  * Constant time multiplication.
9512
9756
  * Uses wNAF method. Windowed method may be 10% faster,
@@ -9517,22 +9761,21 @@ function weierstrassPoints$1(opts) {
9517
9761
  * @returns New point
9518
9762
  */
9519
9763
  multiply(scalar) {
9520
- const { endo, n: N } = CURVE;
9521
- aInRange('scalar', scalar, _1n$8, N);
9764
+ const { endo } = curveOpts;
9765
+ if (!Fn.isValidNot0(scalar))
9766
+ throw new Error('invalid scalar: out of range'); // 0 is invalid
9522
9767
  let point, fake; // Fake point is used to const-time mult
9768
+ const mul = (n) => wnaf.wNAFCached(this, n, Point.normalizeZ);
9523
9769
  /** See docs for {@link EndomorphismOpts} */
9524
9770
  if (endo) {
9525
9771
  const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
9526
- let { p: k1p, f: f1p } = this.wNAF(k1);
9527
- let { p: k2p, f: f2p } = this.wNAF(k2);
9528
- k1p = wnaf.constTimeNegate(k1neg, k1p);
9529
- k2p = wnaf.constTimeNegate(k2neg, k2p);
9530
- k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
9531
- point = k1p.add(k2p);
9532
- fake = f1p.add(f2p);
9772
+ const { p: k1p, f: k1f } = mul(k1);
9773
+ const { p: k2p, f: k2f } = mul(k2);
9774
+ fake = k1f.add(k2f);
9775
+ point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
9533
9776
  }
9534
9777
  else {
9535
- const { p, f } = this.wNAF(scalar);
9778
+ const { p, f } = mul(scalar);
9536
9779
  point = p;
9537
9780
  fake = f;
9538
9781
  }
@@ -9540,162 +9783,124 @@ function weierstrassPoints$1(opts) {
9540
9783
  return Point.normalizeZ([point, fake])[0];
9541
9784
  }
9542
9785
  /**
9543
- * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
9544
- * Not using Strauss-Shamir trick: precomputation tables are faster.
9545
- * The trick could be useful if both P and Q are not G (not in our case).
9546
- * @returns non-zero affine point
9786
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
9787
+ * It's faster, but should only be used when you don't care about
9788
+ * an exposed private key e.g. sig verification, which works over *public* keys.
9547
9789
  */
9548
- multiplyAndAddUnsafe(Q, a, b) {
9549
- const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
9550
- const mul = (P, a // Select faster multiply() method
9551
- ) => (a === _0n$7 || a === _1n$8 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
9552
- const sum = mul(this, a).add(mul(Q, b));
9790
+ multiplyUnsafe(sc) {
9791
+ const { endo } = curveOpts;
9792
+ const p = this;
9793
+ if (!Fn.isValid(sc))
9794
+ throw new Error('invalid scalar: out of range'); // 0 is valid
9795
+ if (sc === _0n$6 || p.is0())
9796
+ return Point.ZERO;
9797
+ if (sc === _1n$8)
9798
+ return p; // fast-path
9799
+ if (wnaf.hasPrecomputes(this))
9800
+ return this.multiply(sc);
9801
+ if (endo) {
9802
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
9803
+ // `wNAFCachedUnsafe` is 30% slower
9804
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
9805
+ return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
9806
+ }
9807
+ else {
9808
+ return wnaf.wNAFCachedUnsafe(p, sc);
9809
+ }
9810
+ }
9811
+ multiplyAndAddUnsafe(Q, a, b) {
9812
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
9553
9813
  return sum.is0() ? undefined : sum;
9554
9814
  }
9555
- // Converts Projective point to affine (x, y) coordinates.
9556
- // Can accept precomputed Z^-1 - for example, from invertBatch.
9557
- // (x, y, z) (x=x/z, y=y/z)
9558
- toAffine(iz) {
9559
- return toAffineMemo(this, iz);
9815
+ /**
9816
+ * Converts Projective point to affine (x, y) coordinates.
9817
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
9818
+ */
9819
+ toAffine(invertedZ) {
9820
+ return toAffineMemo(this, invertedZ);
9560
9821
  }
9822
+ /**
9823
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
9824
+ * Always torsion-free for cofactor=1 curves.
9825
+ */
9561
9826
  isTorsionFree() {
9562
- const { h: cofactor, isTorsionFree } = CURVE;
9827
+ const { isTorsionFree } = curveOpts;
9563
9828
  if (cofactor === _1n$8)
9564
- return true; // No subgroups, always torsion-free
9829
+ return true;
9565
9830
  if (isTorsionFree)
9566
9831
  return isTorsionFree(Point, this);
9567
- throw new Error('isTorsionFree() has not been declared for the elliptic curve');
9832
+ return wnaf.wNAFCachedUnsafe(this, CURVE_ORDER).is0();
9568
9833
  }
9569
9834
  clearCofactor() {
9570
- const { h: cofactor, clearCofactor } = CURVE;
9835
+ const { clearCofactor } = curveOpts;
9571
9836
  if (cofactor === _1n$8)
9572
9837
  return this; // Fast-path
9573
9838
  if (clearCofactor)
9574
9839
  return clearCofactor(Point, this);
9575
- return this.multiplyUnsafe(CURVE.h);
9840
+ return this.multiplyUnsafe(cofactor);
9576
9841
  }
9577
- toRawBytes(isCompressed = true) {
9842
+ toBytes(isCompressed = true) {
9578
9843
  abool('isCompressed', isCompressed);
9579
9844
  this.assertValidity();
9580
9845
  return toBytes(Point, this, isCompressed);
9581
9846
  }
9847
+ /** @deprecated use `toBytes` */
9848
+ toRawBytes(isCompressed = true) {
9849
+ return this.toBytes(isCompressed);
9850
+ }
9582
9851
  toHex(isCompressed = true) {
9583
- abool('isCompressed', isCompressed);
9584
- return bytesToHex$1(this.toRawBytes(isCompressed));
9852
+ return bytesToHex$1(this.toBytes(isCompressed));
9853
+ }
9854
+ toString() {
9855
+ return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
9585
9856
  }
9586
9857
  }
9587
9858
  // base / generator point
9588
9859
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
9589
9860
  // zero / infinity / identity point
9590
9861
  Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
9591
- const { endo, nBitLength } = CURVE;
9592
- const wnaf = wNAF$1(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
9593
- return {
9594
- CURVE,
9595
- ProjectivePoint: Point,
9596
- normPrivateKeyToScalar,
9597
- weierstrassEquation,
9598
- isWithinCurveOrder,
9599
- };
9600
- }
9601
- function validateOpts$1(curve) {
9602
- const opts = validateBasic$1(curve);
9603
- validateObject$1(opts, {
9604
- hash: 'hash',
9862
+ // fields
9863
+ Point.Fp = Fp;
9864
+ Point.Fn = Fn;
9865
+ const bits = Fn.BITS;
9866
+ const wnaf = wNAF$1(Point, curveOpts.endo ? Math.ceil(bits / 2) : bits);
9867
+ return Point;
9868
+ }
9869
+ // Points start with byte 0x02 when y is even; otherwise 0x03
9870
+ function pprefix(hasEvenY) {
9871
+ return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
9872
+ }
9873
+ function ecdsa(Point, ecdsaOpts, curveOpts = {}) {
9874
+ _validateObject(ecdsaOpts, { hash: 'function' }, {
9605
9875
  hmac: 'function',
9876
+ lowS: 'boolean',
9606
9877
  randomBytes: 'function',
9607
- }, {
9608
9878
  bits2int: 'function',
9609
9879
  bits2int_modN: 'function',
9610
- lowS: 'boolean',
9611
- });
9612
- return Object.freeze({ lowS: true, ...opts });
9613
- }
9614
- /**
9615
- * Creates short weierstrass curve and ECDSA signature methods for it.
9616
- * @example
9617
- * import { Field } from '@noble/curves/abstract/modular';
9618
- * // Before that, define BigInt-s: a, b, p, n, Gx, Gy
9619
- * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
9620
- */
9621
- function weierstrass$1(curveDef) {
9622
- const CURVE = validateOpts$1(curveDef);
9623
- const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
9624
- const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
9625
- const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
9626
- function modN(a) {
9627
- return mod$1(a, CURVE_ORDER);
9628
- }
9629
- function invN(a) {
9630
- return invert$1(a, CURVE_ORDER);
9631
- }
9632
- const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints$1({
9633
- ...CURVE,
9634
- toBytes(_c, point, isCompressed) {
9635
- const a = point.toAffine();
9636
- const x = Fp.toBytes(a.x);
9637
- const cat = concatBytes$2;
9638
- abool('isCompressed', isCompressed);
9639
- if (isCompressed) {
9640
- return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
9641
- }
9642
- else {
9643
- return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
9644
- }
9645
- },
9646
- fromBytes(bytes) {
9647
- const len = bytes.length;
9648
- const head = bytes[0];
9649
- const tail = bytes.subarray(1);
9650
- // this.assertValidity() is done inside of fromHex
9651
- if (len === compressedLen && (head === 0x02 || head === 0x03)) {
9652
- const x = bytesToNumberBE$1(tail);
9653
- if (!inRange(x, _1n$8, Fp.ORDER))
9654
- throw new Error('Point is not on curve');
9655
- const y2 = weierstrassEquation(x); // y² = x³ + ax + b
9656
- let y;
9657
- try {
9658
- y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
9659
- }
9660
- catch (sqrtError) {
9661
- const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
9662
- throw new Error('Point is not on curve' + suffix);
9663
- }
9664
- const isYOdd = (y & _1n$8) === _1n$8;
9665
- // ECDSA
9666
- const isHeadOdd = (head & 1) === 1;
9667
- if (isHeadOdd !== isYOdd)
9668
- y = Fp.neg(y);
9669
- return { x, y };
9670
- }
9671
- else if (len === uncompressedLen && head === 0x04) {
9672
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
9673
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
9674
- return { x, y };
9675
- }
9676
- else {
9677
- const cl = compressedLen;
9678
- const ul = uncompressedLen;
9679
- throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
9680
- }
9681
- },
9682
9880
  });
9881
+ const randomBytes_ = ecdsaOpts.randomBytes || randomBytes$3;
9882
+ const hmac_ = ecdsaOpts.hmac ||
9883
+ ((key, ...msgs) => hmac$1(ecdsaOpts.hash, key, concatBytes$2(...msgs)));
9884
+ const { Fp, Fn } = Point;
9885
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
9683
9886
  function isBiggerThanHalfOrder(number) {
9684
9887
  const HALF = CURVE_ORDER >> _1n$8;
9685
9888
  return number > HALF;
9686
9889
  }
9687
9890
  function normalizeS(s) {
9688
- return isBiggerThanHalfOrder(s) ? modN(-s) : s;
9891
+ return isBiggerThanHalfOrder(s) ? Fn.neg(s) : s;
9892
+ }
9893
+ function aValidRS(title, num) {
9894
+ if (!Fn.isValidNot0(num))
9895
+ throw new Error(`invalid signature ${title}: out of range 1..CURVE.n`);
9689
9896
  }
9690
- // slice bytes num
9691
- const slcNum = (b, from, to) => bytesToNumberBE$1(b.slice(from, to));
9692
9897
  /**
9693
9898
  * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
9694
9899
  */
9695
9900
  class Signature {
9696
9901
  constructor(r, s, recovery) {
9697
- aInRange('r', r, _1n$8, CURVE_ORDER); // r in [1..N]
9698
- aInRange('s', s, _1n$8, CURVE_ORDER); // s in [1..N]
9902
+ aValidRS('r', r); // r in [1..N-1]
9903
+ aValidRS('s', s); // s in [1..N-1]
9699
9904
  this.r = r;
9700
9905
  this.s = s;
9701
9906
  if (recovery != null)
@@ -9704,9 +9909,9 @@ function weierstrass$1(curveDef) {
9704
9909
  }
9705
9910
  // pair (bytes of r, bytes of s)
9706
9911
  static fromCompact(hex) {
9707
- const l = nByteLength;
9708
- hex = ensureBytes$1('compactSignature', hex, l * 2);
9709
- return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
9912
+ const L = Fn.BYTES;
9913
+ const b = ensureBytes$1('compactSignature', hex, L * 2);
9914
+ return new Signature(Fn.fromBytes(b.subarray(0, L)), Fn.fromBytes(b.subarray(L, L * 2)));
9710
9915
  }
9711
9916
  // DER encoded ECDSA signature
9712
9917
  // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
@@ -9722,22 +9927,36 @@ function weierstrass$1(curveDef) {
9722
9927
  addRecoveryBit(recovery) {
9723
9928
  return new Signature(this.r, this.s, recovery);
9724
9929
  }
9930
+ // ProjPointType<bigint>
9725
9931
  recoverPublicKey(msgHash) {
9932
+ const FIELD_ORDER = Fp.ORDER;
9726
9933
  const { r, s, recovery: rec } = this;
9727
- const h = bits2int_modN(ensureBytes$1('msgHash', msgHash)); // Truncate hash
9728
9934
  if (rec == null || ![0, 1, 2, 3].includes(rec))
9729
9935
  throw new Error('recovery id invalid');
9730
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
9731
- if (radj >= Fp.ORDER)
9936
+ // ECDSA recovery is hard for cofactor > 1 curves.
9937
+ // In sign, `r = q.x mod n`, and here we recover q.x from r.
9938
+ // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
9939
+ // However, for cofactor>1, r+n may not get q.x:
9940
+ // r+n*i would need to be done instead where i is unknown.
9941
+ // To easily get i, we either need to:
9942
+ // a. increase amount of valid recid values (4, 5...); OR
9943
+ // b. prohibit non-prime-order signatures (recid > 1).
9944
+ const hasCofactor = CURVE_ORDER * _2n$6 < FIELD_ORDER;
9945
+ if (hasCofactor && rec > 1)
9946
+ throw new Error('recovery id is ambiguous for h>1 curve');
9947
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
9948
+ if (!Fp.isValid(radj))
9732
9949
  throw new Error('recovery id 2 or 3 invalid');
9733
- const prefix = (rec & 1) === 0 ? '02' : '03';
9734
- const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
9735
- const ir = invN(radj); // r^-1
9736
- const u1 = modN(-h * ir); // -hr^-1
9737
- const u2 = modN(s * ir); // sr^-1
9738
- const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
9739
- if (!Q)
9740
- throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
9950
+ const x = Fp.toBytes(radj);
9951
+ const R = Point.fromHex(concatBytes$2(pprefix((rec & 1) === 0), x));
9952
+ const ir = Fn.inv(radj); // r^-1
9953
+ const h = bits2int_modN(ensureBytes$1('msgHash', msgHash)); // Truncate hash
9954
+ const u1 = Fn.create(-h * ir); // -hr^-1
9955
+ const u2 = Fn.create(s * ir); // sr^-1
9956
+ // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
9957
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
9958
+ if (Q.is0())
9959
+ throw new Error('point at infinify');
9741
9960
  Q.assertValidity();
9742
9961
  return Q;
9743
9962
  }
@@ -9746,24 +9965,31 @@ function weierstrass$1(curveDef) {
9746
9965
  return isBiggerThanHalfOrder(this.s);
9747
9966
  }
9748
9967
  normalizeS() {
9749
- return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
9968
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
9969
+ }
9970
+ toBytes(format) {
9971
+ if (format === 'compact')
9972
+ return concatBytes$2(Fn.toBytes(this.r), Fn.toBytes(this.s));
9973
+ if (format === 'der')
9974
+ return hexToBytes$1(DER$1.hexFromSig(this));
9975
+ throw new Error('invalid format');
9750
9976
  }
9751
9977
  // DER-encoded
9752
9978
  toDERRawBytes() {
9753
- return hexToBytes$1(this.toDERHex());
9979
+ return this.toBytes('der');
9754
9980
  }
9755
9981
  toDERHex() {
9756
- return DER$1.hexFromSig(this);
9982
+ return bytesToHex$1(this.toBytes('der'));
9757
9983
  }
9758
9984
  // padded bytes of r, then padded bytes of s
9759
9985
  toCompactRawBytes() {
9760
- return hexToBytes$1(this.toCompactHex());
9986
+ return this.toBytes('compact');
9761
9987
  }
9762
9988
  toCompactHex() {
9763
- const l = nByteLength;
9764
- return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
9989
+ return bytesToHex$1(this.toBytes('compact'));
9765
9990
  }
9766
9991
  }
9992
+ const normPrivateKeyToScalar = _legacyHelperNormPriv(Fn, curveOpts.allowedPrivateKeyLengths, curveOpts.wrapPrivateKey);
9767
9993
  const utils = {
9768
9994
  isValidPrivateKey(privateKey) {
9769
9995
  try {
@@ -9780,21 +10006,11 @@ function weierstrass$1(curveDef) {
9780
10006
  * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
9781
10007
  */
9782
10008
  randomPrivateKey: () => {
9783
- const length = getMinHashLength$1(CURVE.n);
9784
- return mapHashToField$1(CURVE.randomBytes(length), CURVE.n);
10009
+ const n = CURVE_ORDER;
10010
+ return mapHashToField$1(randomBytes_(getMinHashLength$1(n)), n);
9785
10011
  },
9786
- /**
9787
- * Creates precompute table for an arbitrary EC point. Makes point "cached".
9788
- * Allows to massively speed-up `point.multiply(scalar)`.
9789
- * @returns cached point
9790
- * @example
9791
- * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
9792
- * fast.multiply(privKey); // much faster ECDH now
9793
- */
9794
10012
  precompute(windowSize = 8, point = Point.BASE) {
9795
- point._setWindowSize(windowSize);
9796
- point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
9797
- return point;
10013
+ return point.precompute(windowSize, false);
9798
10014
  },
9799
10015
  };
9800
10016
  /**
@@ -9804,7 +10020,7 @@ function weierstrass$1(curveDef) {
9804
10020
  * @returns Public key, full when isCompressed=false; short when isCompressed=true
9805
10021
  */
9806
10022
  function getPublicKey(privateKey, isCompressed = true) {
9807
- return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
10023
+ return Point.fromPrivateKey(privateKey).toBytes(isCompressed);
9808
10024
  }
9809
10025
  /**
9810
10026
  * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
@@ -9815,15 +10031,15 @@ function weierstrass$1(curveDef) {
9815
10031
  if (item instanceof Point)
9816
10032
  return true;
9817
10033
  const arr = ensureBytes$1('key', item);
9818
- const len = arr.length;
9819
- const fpl = Fp.BYTES;
9820
- const compLen = fpl + 1; // e.g. 33 for 32
9821
- const uncompLen = 2 * fpl + 1; // e.g. 65 for 32
9822
- if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
10034
+ const length = arr.length;
10035
+ const L = Fp.BYTES;
10036
+ const LC = L + 1; // e.g. 33 for 32
10037
+ const LU = 2 * L + 1; // e.g. 65 for 32
10038
+ if (curveOpts.allowedPrivateKeyLengths || Fn.BYTES === LC) {
9823
10039
  return undefined;
9824
10040
  }
9825
10041
  else {
9826
- return len === compLen || len === uncompLen;
10042
+ return length === LC || length === LU;
9827
10043
  }
9828
10044
  }
9829
10045
  /**
@@ -9842,13 +10058,13 @@ function weierstrass$1(curveDef) {
9842
10058
  if (isProbPub(publicB) === false)
9843
10059
  throw new Error('second arg must be public key');
9844
10060
  const b = Point.fromHex(publicB); // check for being on-curve
9845
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
10061
+ return b.multiply(normPrivateKeyToScalar(privateA)).toBytes(isCompressed);
9846
10062
  }
9847
10063
  // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
9848
10064
  // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
9849
10065
  // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
9850
10066
  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
9851
- const bits2int = CURVE.bits2int ||
10067
+ const bits2int = ecdsaOpts.bits2int ||
9852
10068
  function (bytes) {
9853
10069
  // Our custom check "just in case", for protection against DoS
9854
10070
  if (bytes.length > 8192)
@@ -9856,22 +10072,22 @@ function weierstrass$1(curveDef) {
9856
10072
  // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
9857
10073
  // for some cases, since bytes.length * 8 is not actual bitLength.
9858
10074
  const num = bytesToNumberBE$1(bytes); // check for == u8 done here
9859
- const delta = bytes.length * 8 - nBitLength; // truncate to nBitLength leftmost bits
10075
+ const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
9860
10076
  return delta > 0 ? num >> BigInt(delta) : num;
9861
10077
  };
9862
- const bits2int_modN = CURVE.bits2int_modN ||
10078
+ const bits2int_modN = ecdsaOpts.bits2int_modN ||
9863
10079
  function (bytes) {
9864
- return modN(bits2int(bytes)); // can't use bytesToNumberBE here
10080
+ return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
9865
10081
  };
9866
10082
  // NOTE: pads output with zero as per spec
9867
- const ORDER_MASK = bitMask$1(nBitLength);
10083
+ const ORDER_MASK = bitMask$1(fnBits);
9868
10084
  /**
9869
10085
  * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
9870
10086
  */
9871
10087
  function int2octets(num) {
9872
- aInRange('num < 2^' + nBitLength, num, _0n$7, ORDER_MASK);
9873
- // works with order, can have different size than numToField!
9874
- return numberToBytesBE$1(num, nByteLength);
10088
+ // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
10089
+ aInRange('num < 2^' + fnBits, num, _0n$6, ORDER_MASK);
10090
+ return Fn.toBytes(num);
9875
10091
  }
9876
10092
  // Steps A, D of RFC6979 3.2
9877
10093
  // Creates RFC6979 seed; converts msg/privKey to numbers.
@@ -9881,7 +10097,7 @@ function weierstrass$1(curveDef) {
9881
10097
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
9882
10098
  if (['recovered', 'canonical'].some((k) => k in opts))
9883
10099
  throw new Error('sign() legacy options not supported');
9884
- const { hash, randomBytes } = CURVE;
10100
+ const { hash } = ecdsaOpts;
9885
10101
  let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
9886
10102
  if (lowS == null)
9887
10103
  lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
@@ -9890,7 +10106,7 @@ function weierstrass$1(curveDef) {
9890
10106
  if (prehash)
9891
10107
  msgHash = ensureBytes$1('prehashed msgHash', hash(msgHash));
9892
10108
  // We can't later call bits2octets, since nested bits2int is broken for curves
9893
- // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
10109
+ // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
9894
10110
  // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
9895
10111
  const h1int = bits2int_modN(msgHash);
9896
10112
  const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
@@ -9898,27 +10114,28 @@ function weierstrass$1(curveDef) {
9898
10114
  // extraEntropy. RFC6979 3.6: additional k' (optional).
9899
10115
  if (ent != null && ent !== false) {
9900
10116
  // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
9901
- const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
10117
+ const e = ent === true ? randomBytes_(Fp.BYTES) : ent; // generate random bytes OR pass as-is
9902
10118
  seedArgs.push(ensureBytes$1('extraEntropy', e)); // check for being bytes
9903
10119
  }
9904
10120
  const seed = concatBytes$2(...seedArgs); // Step D of RFC6979 3.2
9905
10121
  const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
9906
10122
  // Converts signature params into point w r/s, checks result for validity.
10123
+ // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
10124
+ // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
10125
+ // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
9907
10126
  function k2sig(kBytes) {
9908
10127
  // RFC 6979 Section 3.2, step 3: k = bits2int(T)
10128
+ // Important: all mod() calls here must be done over N
9909
10129
  const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
9910
- if (!isWithinCurveOrder(k))
9911
- return; // Important: all mod() calls here must be done over N
9912
- const ik = invN(k); // k^-1 mod n
10130
+ if (!Fn.isValidNot0(k))
10131
+ return; // Valid scalars (including k) must be in 1..N-1
10132
+ const ik = Fn.inv(k); // k^-1 mod n
9913
10133
  const q = Point.BASE.multiply(k).toAffine(); // q = Gk
9914
- const r = modN(q.x); // r = q.x mod n
9915
- if (r === _0n$7)
10134
+ const r = Fn.create(q.x); // r = q.x mod n
10135
+ if (r === _0n$6)
9916
10136
  return;
9917
- // Can use scalar blinding b^-1(bm + bdr) where b [1,q−1] according to
9918
- // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
9919
- // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
9920
- const s = modN(ik * modN(m + r * d)); // Not using blinding here
9921
- if (s === _0n$7)
10137
+ const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
10138
+ if (s === _0n$6)
9922
10139
  return;
9923
10140
  let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$8); // recovery bit (2 or 3, when q.x > n)
9924
10141
  let normS = s;
@@ -9930,8 +10147,8 @@ function weierstrass$1(curveDef) {
9930
10147
  }
9931
10148
  return { seed, k2sig };
9932
10149
  }
9933
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
9934
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
10150
+ const defaultSigOpts = { lowS: ecdsaOpts.lowS, prehash: false };
10151
+ const defaultVerOpts = { lowS: ecdsaOpts.lowS, prehash: false };
9935
10152
  /**
9936
10153
  * Signs message hash with a private key.
9937
10154
  * ```
@@ -9947,13 +10164,11 @@ function weierstrass$1(curveDef) {
9947
10164
  */
9948
10165
  function sign(msgHash, privKey, opts = defaultSigOpts) {
9949
10166
  const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
9950
- const C = CURVE;
9951
- const drbg = createHmacDrbg$1(C.hash.outputLen, C.nByteLength, C.hmac);
10167
+ const drbg = createHmacDrbg$1(ecdsaOpts.hash.outputLen, Fn.BYTES, hmac_);
9952
10168
  return drbg(seed, k2sig); // Steps B, C, D, E, F, G
9953
10169
  }
9954
10170
  // Enable precomputes. Slows down first publicKey computation by 20ms.
9955
- Point.BASE._setWindowSize(8);
9956
- // utils.precompute(8, ProjectivePoint.BASE)
10171
+ Point.BASE.precompute(8);
9957
10172
  /**
9958
10173
  * Verifies a signature against message hash and public key.
9959
10174
  * Rejects lowS signatures by default: to override,
@@ -9971,13 +10186,14 @@ function weierstrass$1(curveDef) {
9971
10186
  const sg = signature;
9972
10187
  msgHash = ensureBytes$1('msgHash', msgHash);
9973
10188
  publicKey = ensureBytes$1('publicKey', publicKey);
9974
- const { lowS, prehash, format } = opts;
9975
- // Verify opts, deduce signature format
10189
+ // Verify opts
9976
10190
  validateSigVerOpts(opts);
10191
+ const { lowS, prehash, format } = opts;
10192
+ // TODO: remove
9977
10193
  if ('strict' in opts)
9978
10194
  throw new Error('options.strict was renamed to lowS');
9979
- if (format !== undefined && format !== 'compact' && format !== 'der')
9980
- throw new Error('format must be compact or der');
10195
+ if (format !== undefined && !['compact', 'der', 'js'].includes(format))
10196
+ throw new Error('format must be "compact", "der" or "js"');
9981
10197
  const isHex = typeof sg === 'string' || isBytes(sg);
9982
10198
  const isObj = !isHex &&
9983
10199
  !format &&
@@ -9989,12 +10205,29 @@ function weierstrass$1(curveDef) {
9989
10205
  throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
9990
10206
  let _sig = undefined;
9991
10207
  let P;
10208
+ // deduce signature format
9992
10209
  try {
9993
- if (isObj)
9994
- _sig = new Signature(sg.r, sg.s);
10210
+ // if (format === 'js') {
10211
+ // if (sg != null && !isBytes(sg)) _sig = new Signature(sg.r, sg.s);
10212
+ // } else if (format === 'compact') {
10213
+ // _sig = Signature.fromCompact(sg);
10214
+ // } else if (format === 'der') {
10215
+ // _sig = Signature.fromDER(sg);
10216
+ // } else {
10217
+ // throw new Error('invalid format');
10218
+ // }
10219
+ if (isObj) {
10220
+ if (format === undefined || format === 'js') {
10221
+ _sig = new Signature(sg.r, sg.s);
10222
+ }
10223
+ else {
10224
+ throw new Error('invalid format');
10225
+ }
10226
+ }
9995
10227
  if (isHex) {
9996
- // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
9997
- // Since DER can also be 2*nByteLength bytes, we check for it first.
10228
+ // TODO: remove this malleable check
10229
+ // Signature can be represented in 2 ways: compact (2*Fn.BYTES) & DER (variable-length).
10230
+ // Since DER can also be 2*Fn.BYTES bytes, we check for it first.
9998
10231
  try {
9999
10232
  if (format !== 'compact')
10000
10233
  _sig = Signature.fromDER(sg);
@@ -10015,61 +10248,111 @@ function weierstrass$1(curveDef) {
10015
10248
  return false;
10016
10249
  if (lowS && _sig.hasHighS())
10017
10250
  return false;
10251
+ // todo: optional.hash => hash
10018
10252
  if (prehash)
10019
- msgHash = CURVE.hash(msgHash);
10253
+ msgHash = ecdsaOpts.hash(msgHash);
10020
10254
  const { r, s } = _sig;
10021
10255
  const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
10022
- const is = invN(s); // s^-1
10023
- const u1 = modN(h * is); // u1 = hs^-1 mod n
10024
- const u2 = modN(r * is); // u2 = rs^-1 mod n
10025
- const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
10026
- if (!R)
10256
+ const is = Fn.inv(s); // s^-1
10257
+ const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
10258
+ const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
10259
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
10260
+ if (R.is0())
10027
10261
  return false;
10028
- const v = modN(R.x);
10262
+ const v = Fn.create(R.x); // v = r.x mod n
10029
10263
  return v === r;
10030
10264
  }
10031
- return {
10032
- CURVE,
10265
+ // TODO: clarify API for cloning .clone({hash: sha512}) ? .createWith({hash: sha512})?
10266
+ // const clone = (hash: CHash): ECDSA => ecdsa(Point, { ...ecdsaOpts, ...getHash(hash) }, curveOpts);
10267
+ return Object.freeze({
10033
10268
  getPublicKey,
10034
10269
  getSharedSecret,
10035
10270
  sign,
10036
10271
  verify,
10037
- ProjectivePoint: Point,
10038
- Signature,
10039
10272
  utils,
10273
+ Point,
10274
+ Signature,
10275
+ });
10276
+ }
10277
+ function _weierstrass_legacy_opts_to_new(c) {
10278
+ const CURVE = {
10279
+ a: c.a,
10280
+ b: c.b,
10281
+ p: c.Fp.ORDER,
10282
+ n: c.n,
10283
+ h: c.h,
10284
+ Gx: c.Gx,
10285
+ Gy: c.Gy,
10286
+ };
10287
+ const Fp = c.Fp;
10288
+ const Fn = Field$1(CURVE.n, c.nBitLength);
10289
+ const curveOpts = {
10290
+ Fp,
10291
+ Fn,
10292
+ allowedPrivateKeyLengths: c.allowedPrivateKeyLengths,
10293
+ allowInfinityPoint: c.allowInfinityPoint,
10294
+ endo: c.endo,
10295
+ wrapPrivateKey: c.wrapPrivateKey,
10296
+ isTorsionFree: c.isTorsionFree,
10297
+ clearCofactor: c.clearCofactor,
10298
+ fromBytes: c.fromBytes,
10299
+ toBytes: c.toBytes,
10300
+ };
10301
+ return { CURVE, curveOpts };
10302
+ }
10303
+ function _ecdsa_legacy_opts_to_new(c) {
10304
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
10305
+ const ecdsaOpts = {
10306
+ hash: c.hash,
10307
+ hmac: c.hmac,
10308
+ randomBytes: c.randomBytes,
10309
+ lowS: c.lowS,
10310
+ bits2int: c.bits2int,
10311
+ bits2int_modN: c.bits2int_modN,
10040
10312
  };
10313
+ return { CURVE, curveOpts, ecdsaOpts };
10314
+ }
10315
+ function _ecdsa_new_output_to_legacy(c, ecdsa) {
10316
+ return Object.assign({}, ecdsa, {
10317
+ ProjectivePoint: ecdsa.Point,
10318
+ CURVE: c,
10319
+ });
10320
+ }
10321
+ // _ecdsa_legacy
10322
+ function weierstrass$1(c) {
10323
+ const { CURVE, curveOpts, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
10324
+ const Point = weierstrassN(CURVE, curveOpts);
10325
+ const signs = ecdsa(Point, ecdsaOpts, curveOpts);
10326
+ return _ecdsa_new_output_to_legacy(c, signs);
10041
10327
  }/**
10042
10328
  * Utilities for short weierstrass curves, combined with noble-hashes.
10043
10329
  * @module
10044
10330
  */
10045
10331
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
10046
- /** connects noble-curves to noble-hashes */
10047
- function getHash$1(hash) {
10048
- return {
10049
- hash,
10050
- hmac: (key, ...msgs) => hmac$1(hash, key, concatBytes$3(...msgs)),
10051
- randomBytes: randomBytes$3,
10052
- };
10053
- }
10054
10332
  function createCurve$1(curveDef, defHash) {
10055
- const create = (hash) => weierstrass$1({ ...curveDef, ...getHash$1(hash) });
10333
+ const create = (hash) => weierstrass$1({ ...curveDef, hash: hash });
10056
10334
  return { ...create(defHash), create };
10057
10335
  }/**
10058
- * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
10059
- *
10060
- * Seems to be rigid (not backdoored)
10061
- * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
10336
+ * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
10062
10337
  *
10063
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
10064
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
10065
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
10066
- * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
10338
+ * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
10339
+ * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
10067
10340
  * @module
10068
10341
  */
10069
10342
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
10070
- const secp256k1P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
10071
- const secp256k1N$1 = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
10072
- const _0n$6 = BigInt(0);
10343
+ // Seems like generator was produced from some seed:
10344
+ // `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
10345
+ // // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
10346
+ const secp256k1_CURVE = {
10347
+ p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
10348
+ n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
10349
+ h: BigInt(1),
10350
+ a: BigInt(0),
10351
+ b: BigInt(7),
10352
+ Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
10353
+ Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
10354
+ };
10355
+ BigInt(0);
10073
10356
  const _1n$7 = BigInt(1);
10074
10357
  const _2n$5 = BigInt(2);
10075
10358
  const divNearest$1 = (a, b) => (a + b / _2n$5) / b;
@@ -10078,7 +10361,7 @@ const divNearest$1 = (a, b) => (a + b / _2n$5) / b;
10078
10361
  * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
10079
10362
  */
10080
10363
  function sqrtMod$1(y) {
10081
- const P = secp256k1P$1;
10364
+ const P = secp256k1_CURVE.p;
10082
10365
  // prettier-ignore
10083
10366
  const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
10084
10367
  // prettier-ignore
@@ -10101,7 +10384,7 @@ function sqrtMod$1(y) {
10101
10384
  throw new Error('Cannot find square root');
10102
10385
  return root;
10103
10386
  }
10104
- const Fpk1 = Field$1(secp256k1P$1, undefined, undefined, { sqrt: sqrtMod$1 });
10387
+ const Fpk1 = Field$1(secp256k1_CURVE.p, undefined, undefined, { sqrt: sqrtMod$1 });
10105
10388
  /**
10106
10389
  * secp256k1 curve, ECDSA and ECDH methods.
10107
10390
  *
@@ -10118,19 +10401,14 @@ const Fpk1 = Field$1(secp256k1P$1, undefined, undefined, { sqrt: sqrtMod$1 });
10118
10401
  * ```
10119
10402
  */
10120
10403
  const secp256k1$1 = createCurve$1({
10121
- a: _0n$6,
10122
- b: BigInt(7),
10404
+ ...secp256k1_CURVE,
10123
10405
  Fp: Fpk1,
10124
- n: secp256k1N$1,
10125
- Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
10126
- Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
10127
- h: BigInt(1),
10128
10406
  lowS: true, // Allow only low-S signatures by default in sign() and verify()
10129
10407
  endo: {
10130
10408
  // Endomorphism, see above
10131
10409
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
10132
10410
  splitScalar: (k) => {
10133
- const n = secp256k1N$1;
10411
+ const n = secp256k1_CURVE.n;
10134
10412
  const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
10135
10413
  const b1 = -_1n$7 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
10136
10414
  const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
@@ -10295,7 +10573,7 @@ let Keccak$1=class Keccak extends Hash$1 {
10295
10573
  update(data) {
10296
10574
  aexists(this);
10297
10575
  data = toBytes$1(data);
10298
- abytes$1(data);
10576
+ abytes(data);
10299
10577
  const { blockLen, state } = this;
10300
10578
  const len = data.length;
10301
10579
  for (let pos = 0; pos < len;) {
@@ -10321,7 +10599,7 @@ let Keccak$1=class Keccak extends Hash$1 {
10321
10599
  }
10322
10600
  writeInto(out) {
10323
10601
  aexists(this, false);
10324
- abytes$1(out);
10602
+ abytes(out);
10325
10603
  this.finish();
10326
10604
  const bufferOut = this.state;
10327
10605
  const { blockLen } = this;
@@ -10420,8 +10698,8 @@ function ethereumEncode(addressOrPublic) {
10420
10698
  if (![20, 32, 33, 65].includes(u8aAddress.length)) {
10421
10699
  throw new Error(`Invalid address or publicKey provided, received ${u8aAddress.length} bytes input`);
10422
10700
  }
10423
- const address = u8aToHex(getH160(u8aAddress), -1, false);
10424
- const hash = u8aToHex(keccakAsU8a(address), -1, false);
10701
+ const address = u8aToHex$1(getH160(u8aAddress), -1, false);
10702
+ const hash = u8aToHex$1(keccakAsU8a(address), -1, false);
10425
10703
  let result = '';
10426
10704
  for (let i = 0; i < 40; i++) {
10427
10705
  result = `${result}${parseInt(hash[i], 16) > 7 ? address[i].toUpperCase() : address[i]}`;
@@ -10431,7 +10709,7 @@ function ethereumEncode(addressOrPublic) {
10431
10709
  /**
10432
10710
  * The current version of Ethers.
10433
10711
  */
10434
- const version = "6.14.3";/**
10712
+ const version = "6.14.4";/**
10435
10713
  * Property helper functions.
10436
10714
  *
10437
10715
  * @_subsection api/utils:Properties [about-properties]
@@ -10834,7 +11112,7 @@ function getBigInt(value, name) {
10834
11112
  case "bigint": return value;
10835
11113
  case "number":
10836
11114
  assertArgument(Number.isInteger(value), "underflow", name || "value", value);
10837
- assertArgument(value >= -9007199254740991 && value <= maxValue, "overflow", name || "value", value);
11115
+ assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
10838
11116
  return BigInt(value);
10839
11117
  case "string":
10840
11118
  try {
@@ -10886,11 +11164,11 @@ function toBigInt(value) {
10886
11164
  function getNumber(value, name) {
10887
11165
  switch (typeof (value)) {
10888
11166
  case "bigint":
10889
- assertArgument(value >= -9007199254740991 && value <= maxValue, "overflow", name || "value", value);
11167
+ assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
10890
11168
  return Number(value);
10891
11169
  case "number":
10892
11170
  assertArgument(Number.isInteger(value), "underflow", name || "value", value);
10893
- assertArgument(value >= -9007199254740991 && value <= maxValue, "overflow", name || "value", value);
11171
+ assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
10894
11172
  return value;
10895
11173
  case "string":
10896
11174
  try {
@@ -15422,8 +15700,8 @@ function formatAuthorizationList(value) {
15422
15700
  a.address,
15423
15701
  formatNumber(a.nonce, "nonce"),
15424
15702
  formatNumber(a.signature.yParity, "yParity"),
15425
- a.signature.r,
15426
- a.signature.s
15703
+ toBeArray(a.signature.r),
15704
+ toBeArray(a.signature.s)
15427
15705
  ];
15428
15706
  });
15429
15707
  }
@@ -16490,6 +16768,14 @@ function hashMessage(message) {
16490
16768
  toUtf8Bytes(String(message.length)),
16491
16769
  message
16492
16770
  ]));
16771
+ }
16772
+ /**
16773
+ * Return the address of the private key that produced
16774
+ * the signature %%sig%% during signing for %%message%%.
16775
+ */
16776
+ function verifyMessage(message, sig) {
16777
+ const digest = hashMessage(message);
16778
+ return recoverAddress(digest, sig);
16493
16779
  }//import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer";
16494
16780
  const padding = new Uint8Array(32);
16495
16781
  padding.fill(0);
@@ -18759,7 +19045,7 @@ class HDNodeWallet extends BaseWallet {
18759
19045
  // Base path
18760
19046
  let path = this.path;
18761
19047
  if (path) {
18762
- path += "/" + (index & 2147483647);
19048
+ path += "/" + (index & ~HardenedBit);
18763
19049
  if (index & HardenedBit) {
18764
19050
  path += "'";
18765
19051
  }
@@ -18961,7 +19247,7 @@ class HDNodeVoidWallet extends VoidSigner {
18961
19247
  // Base path
18962
19248
  let path = this.path;
18963
19249
  if (path) {
18964
- path += "/" + (index & 2147483647);
19250
+ path += "/" + (index & ~HardenedBit);
18965
19251
  if (index & HardenedBit) {
18966
19252
  path += "'";
18967
19253
  }
@@ -19358,6 +19644,22 @@ const ADD_KEY_DATA_DEFINITION = {
19358
19644
  },
19359
19645
  ],
19360
19646
  };
19647
+ const AUTHORIZED_KEY_DATA_DEFINITION = {
19648
+ AuthorizedKeyData: [
19649
+ {
19650
+ name: 'msaId',
19651
+ type: 'uint64',
19652
+ },
19653
+ {
19654
+ name: 'expiration',
19655
+ type: 'uint32',
19656
+ },
19657
+ {
19658
+ name: 'authorizedPublicKey',
19659
+ type: 'address',
19660
+ },
19661
+ ],
19662
+ };
19361
19663
  const CLAIM_HANDLE_PAYLOAD_DEFINITION = {
19362
19664
  ClaimHandlePayload: [
19363
19665
  {
@@ -19446,34 +19748,70 @@ const ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2 = {
19446
19748
  { name: 'data', type: 'bytes' },
19447
19749
  { name: 'index', type: 'uint16' },
19448
19750
  ],
19449
- };var signatureDefinitions=/*#__PURE__*/Object.freeze({__proto__:null,ADD_KEY_DATA_DEFINITION:ADD_KEY_DATA_DEFINITION,ADD_PROVIDER_DEFINITION:ADD_PROVIDER_DEFINITION,CLAIM_HANDLE_PAYLOAD_DEFINITION:CLAIM_HANDLE_PAYLOAD_DEFINITION,EIP712_DOMAIN_DEFAULT:EIP712_DOMAIN_DEFAULT,EIP712_DOMAIN_DEFINITION:EIP712_DOMAIN_DEFINITION,ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2:ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2:PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2:PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2,PASSKEY_PUBLIC_KEY_DEFINITION:PASSKEY_PUBLIC_KEY_DEFINITION});/**
19450
- * Signing EIP-712 compatible signature for payload
19751
+ };
19752
+ const SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION = {
19753
+ SiwfSignedRequestPayload: [
19754
+ {
19755
+ name: 'callback',
19756
+ type: 'string',
19757
+ },
19758
+ {
19759
+ name: 'permissions',
19760
+ type: 'uint16[]',
19761
+ },
19762
+ {
19763
+ name: 'userIdentifierAdminUrl',
19764
+ type: 'string',
19765
+ },
19766
+ ],
19767
+ };var signatureDefinitions=/*#__PURE__*/Object.freeze({__proto__:null,ADD_KEY_DATA_DEFINITION:ADD_KEY_DATA_DEFINITION,ADD_PROVIDER_DEFINITION:ADD_PROVIDER_DEFINITION,AUTHORIZED_KEY_DATA_DEFINITION:AUTHORIZED_KEY_DATA_DEFINITION,CLAIM_HANDLE_PAYLOAD_DEFINITION:CLAIM_HANDLE_PAYLOAD_DEFINITION,EIP712_DOMAIN_DEFAULT:EIP712_DOMAIN_DEFAULT,EIP712_DOMAIN_DEFINITION:EIP712_DOMAIN_DEFINITION,ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2:ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2:PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2:PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2,PASSKEY_PUBLIC_KEY_DEFINITION:PASSKEY_PUBLIC_KEY_DEFINITION,SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION:SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION});/**
19768
+ * Signing EIP-712 or ERC-191 compatible signature based on payload
19451
19769
  * @param secretKey
19452
19770
  * @param payload
19453
19771
  * @param chain
19454
19772
  */
19455
- async function signEip712(secretKey, payload, chain = 'Mainnet-Frequency') {
19456
- const types = getTypesFor(payload.type);
19773
+ async function sign(secretKey, payload, chain = 'Mainnet-Frequency') {
19774
+ const signatureType = getSignatureType(payload.type);
19457
19775
  const normalizedPayload = normalizePayload(payload);
19458
19776
  const wallet = new Wallet(secretKey);
19459
- // TODO: use correct chainID for different networks
19460
- // TODO: use correct contract address for different payloads
19461
- const signature = await wallet.signTypedData(EIP712_DOMAIN_DEFAULT, types, normalizedPayload);
19777
+ let signature;
19778
+ switch (signatureType) {
19779
+ case 'EIP-712':
19780
+ // TODO: use correct chainID for different networks
19781
+ // TODO: use correct contract address for different payloads
19782
+ signature = await wallet.signTypedData(EIP712_DOMAIN_DEFAULT, getTypesFor(payload.type), normalizedPayload);
19783
+ break;
19784
+ case 'EIP-191':
19785
+ signature = await wallet.signMessage(payload.message);
19786
+ break;
19787
+ default:
19788
+ throw new Error(`Unsupported signature type : ${signatureType}`);
19789
+ }
19462
19790
  return { Ecdsa: signature };
19463
19791
  }
19464
19792
  /**
19465
- * Verify EIP-712 signatures
19793
+ * Verify EIP-712 and ERC-191 signatures based on payload
19466
19794
  * @param ethereumAddress
19467
19795
  * @param signature
19468
19796
  * @param payload
19469
19797
  * @param chain
19470
19798
  */
19471
- function verifyEip712Signature(ethereumAddress, signature, payload, chain = 'Mainnet-Frequency') {
19472
- const types = getTypesFor(payload.type);
19799
+ function verifySignature(ethereumAddress, signature, payload, chain = 'Mainnet-Frequency') {
19800
+ const signatureType = getSignatureType(payload.type);
19473
19801
  const normalizedPayload = normalizePayload(payload);
19474
- // TODO: use correct chainID for different networks
19475
- // TODO: use correct contract address for different payloads
19476
- const recoveredAddress = verifyTypedData(EIP712_DOMAIN_DEFAULT, types, normalizedPayload, signature);
19802
+ let recoveredAddress;
19803
+ switch (signatureType) {
19804
+ case 'EIP-712':
19805
+ // TODO: use correct chainID for different networks
19806
+ // TODO: use correct contract address for different payloads
19807
+ recoveredAddress = verifyTypedData(EIP712_DOMAIN_DEFAULT, getTypesFor(payload.type), normalizedPayload, signature);
19808
+ break;
19809
+ case 'EIP-191':
19810
+ recoveredAddress = verifyMessage(payload.message, signature);
19811
+ break;
19812
+ default:
19813
+ throw new Error(`Unsupported signature type : ${signatureType}`);
19814
+ }
19477
19815
  return recoveredAddress.toLowerCase() === ethereumAddress.toLowerCase();
19478
19816
  }
19479
19817
  function normalizePayload(payload) {
@@ -19485,6 +19823,7 @@ function normalizePayload(payload) {
19485
19823
  case 'PasskeyPublicKey':
19486
19824
  case 'ClaimHandlePayload':
19487
19825
  case 'AddProvider':
19826
+ case 'SiwfLoginRequestPayload':
19488
19827
  break;
19489
19828
  case 'AddKeyData':
19490
19829
  // convert to 20 bytes ethereum address for signature
@@ -19493,6 +19832,18 @@ function normalizePayload(payload) {
19493
19832
  }
19494
19833
  clonedPayload.newPublicKey = clonedPayload.newPublicKey.toLowerCase();
19495
19834
  break;
19835
+ case 'AuthorizedKeyData':
19836
+ // convert to 20 bytes ethereum address for signature
19837
+ if (clonedPayload.authorizedPublicKey.length !== 42) {
19838
+ clonedPayload.authorizedPublicKey = reverseUnifiedAddressToEthereumAddress(payload.authorizedPublicKey);
19839
+ }
19840
+ clonedPayload.authorizedPublicKey = clonedPayload.authorizedPublicKey.toLowerCase();
19841
+ break;
19842
+ case 'SiwfSignedRequestPayload':
19843
+ if (clonedPayload.userIdentifierAdminUrl == null) {
19844
+ clonedPayload.userIdentifierAdminUrl = '';
19845
+ }
19846
+ break;
19496
19847
  default:
19497
19848
  throw new Error(`Unsupported payload type: ${JSON.stringify(payload)}`);
19498
19849
  }
@@ -19508,7 +19859,10 @@ function getTypesFor(payloadType) {
19508
19859
  PasskeyPublicKey: PASSKEY_PUBLIC_KEY_DEFINITION,
19509
19860
  ClaimHandlePayload: CLAIM_HANDLE_PAYLOAD_DEFINITION,
19510
19861
  AddKeyData: ADD_KEY_DATA_DEFINITION,
19862
+ AuthorizedKeyData: AUTHORIZED_KEY_DATA_DEFINITION,
19511
19863
  AddProvider: ADD_PROVIDER_DEFINITION,
19864
+ // offchain signatures
19865
+ SiwfSignedRequestPayload: SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION,
19512
19866
  };
19513
19867
  const definition = PAYLOAD_TYPE_DEFINITIONS[payloadType];
19514
19868
  if (!definition) {
@@ -19516,6 +19870,12 @@ function getTypesFor(payloadType) {
19516
19870
  }
19517
19871
  return definition;
19518
19872
  }
19873
+ function getSignatureType(payloadType) {
19874
+ if (payloadType === 'SiwfLoginRequestPayload') {
19875
+ return 'EIP-191';
19876
+ }
19877
+ return 'EIP-712';
19878
+ }
19519
19879
  /**
19520
19880
  * Build an AddKeyData payload for signature.
19521
19881
  *
@@ -19536,6 +19896,26 @@ function createAddKeyData(msaId, newPublicKey, expirationBlock) {
19536
19896
  newPublicKey: parsedNewPublicKey,
19537
19897
  };
19538
19898
  }
19899
+ /**
19900
+ * Build an AuthorizedKeyData payload for signature.
19901
+ *
19902
+ * @param msaId MSA ID (uint64) to add the key
19903
+ * @param authorizedPublicKey 32 bytes public key to authorize in hex or Uint8Array
19904
+ * @param expirationBlock Block number after which this payload is invalid
19905
+ */
19906
+ function createAuthorizedKeyData(msaId, newPublicKey, expirationBlock) {
19907
+ const parsedMsaId = typeof msaId === 'string' ? msaId : `${msaId}`;
19908
+ const parsedNewPublicKey = typeof newPublicKey === 'object' ? u8aToHex(newPublicKey) : newPublicKey;
19909
+ assert(isValidUint64String(parsedMsaId), 'msaId should be a valid uint64');
19910
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
19911
+ assert(isHexString(parsedNewPublicKey), 'newPublicKey should be valid hex');
19912
+ return {
19913
+ type: 'AuthorizedKeyData',
19914
+ msaId: parsedMsaId,
19915
+ expiration: expirationBlock,
19916
+ authorizedPublicKey: parsedNewPublicKey,
19917
+ };
19918
+ }
19539
19919
  /**
19540
19920
  * Build an AddProvider payload for signature.
19541
19921
  *
@@ -19660,6 +20040,35 @@ function createPaginatedUpsertSignaturePayloadV2(schemaId, pageId, targetHash, e
19660
20040
  payload: parsedPayload,
19661
20041
  };
19662
20042
  }
20043
+ /**
20044
+ * Build an SiwfSignedRequestPayload payload for signature.
20045
+ *
20046
+ * @param callback Callback URL for login
20047
+ * @param permissions One or more schema IDs (uint16) the provider may use
20048
+ * @param userIdentifierAdminUrl Only used for custom integration situations.
20049
+ */
20050
+ function createSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl) {
20051
+ permissions.forEach((schemaId) => {
20052
+ assert(isValidUint16(schemaId), 'permission should be a valid uint16');
20053
+ });
20054
+ return {
20055
+ type: 'SiwfSignedRequestPayload',
20056
+ callback: callback,
20057
+ permissions,
20058
+ userIdentifierAdminUrl,
20059
+ };
20060
+ }
20061
+ /**
20062
+ * Build an SiwfLoginRequestPayload payload for signature.
20063
+ *
20064
+ * @param message login message
20065
+ */
20066
+ function createSiwfLoginRequestPayload(message) {
20067
+ return {
20068
+ type: 'SiwfLoginRequestPayload',
20069
+ message,
20070
+ };
20071
+ }
19663
20072
  /**
19664
20073
  * Returns the EIP-712 browser request for a AddKeyData for signing.
19665
20074
  *
@@ -19673,6 +20082,19 @@ function getEip712BrowserRequestAddKeyData(msaId, newPublicKey, expirationBlock,
19673
20082
  const normalized = normalizePayload(message);
19674
20083
  return createEip712Payload(ADD_KEY_DATA_DEFINITION, message.type, domain, normalized);
19675
20084
  }
20085
+ /**
20086
+ * Returns the EIP-712 browser request for a AuthorizedKeyData for signing.
20087
+ *
20088
+ * @param msaId MSA ID (uint64) to add the key
20089
+ * @param authorizedPublicKey 32 bytes public key to add in hex or Uint8Array
20090
+ * @param expirationBlock Block number after which this payload is invalid
20091
+ * @param domain
20092
+ */
20093
+ function getEip712BrowserRequestAuthorizedKeyData(msaId, authorizedPublicKey, expirationBlock, domain = EIP712_DOMAIN_DEFAULT) {
20094
+ const message = createAuthorizedKeyData(msaId, authorizedPublicKey, expirationBlock);
20095
+ const normalized = normalizePayload(message);
20096
+ return createEip712Payload(AUTHORIZED_KEY_DATA_DEFINITION, message.type, domain, normalized);
20097
+ }
19676
20098
  /**
19677
20099
  * Returns the EIP-712 browser request for a AddProvider for signing.
19678
20100
  *
@@ -19752,6 +20174,19 @@ function getEip712BrowserRequestPasskeyPublicKey(publicKey, domain = EIP712_DOMA
19752
20174
  const normalized = normalizePayload(message);
19753
20175
  return createEip712Payload(PASSKEY_PUBLIC_KEY_DEFINITION, message.type, domain, normalized);
19754
20176
  }
20177
+ /**
20178
+ * Returns the EIP-712 browser request for a SiwfSignedRequestPayload for signing.
20179
+ *
20180
+ * @param callback Callback URL for login
20181
+ * @param permissions One or more schema IDs (uint16) the provider may use
20182
+ * @param userIdentifierAdminUrl Only used for custom integration situations.
20183
+ * @param domain
20184
+ */
20185
+ function getEip712BrowserRequestSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl, domain = EIP712_DOMAIN_DEFAULT) {
20186
+ const message = createSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl);
20187
+ const normalized = normalizePayload(message);
20188
+ return createEip712Payload(SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION, message.type, domain, normalized);
20189
+ }
19755
20190
  function createEip712Payload(typeDefinition, primaryType, domain, message) {
19756
20191
  return {
19757
20192
  types: {
@@ -19808,4 +20243,4 @@ function prefixEthereumTags(hexPayload) {
19808
20243
  const wrapped = `\x19Ethereum Signed Message:\n${hexPayload.length}${hexPayload}`;
19809
20244
  const buffer = Buffer.from(wrapped, 'utf-8');
19810
20245
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
19811
- }var signature=/*#__PURE__*/Object.freeze({__proto__:null,createAddKeyData:createAddKeyData,createAddProvider:createAddProvider,createClaimHandlePayload:createClaimHandlePayload,createItemizedAddAction:createItemizedAddAction,createItemizedDeleteAction:createItemizedDeleteAction,createItemizedSignaturePayloadV2:createItemizedSignaturePayloadV2,createPaginatedDeleteSignaturePayloadV2:createPaginatedDeleteSignaturePayloadV2,createPaginatedUpsertSignaturePayloadV2:createPaginatedUpsertSignaturePayloadV2,createPasskeyPublicKey:createPasskeyPublicKey,getEip712BrowserRequestAddKeyData:getEip712BrowserRequestAddKeyData,getEip712BrowserRequestAddProvider:getEip712BrowserRequestAddProvider,getEip712BrowserRequestClaimHandlePayload:getEip712BrowserRequestClaimHandlePayload,getEip712BrowserRequestItemizedSignaturePayloadV2:getEip712BrowserRequestItemizedSignaturePayloadV2,getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2:getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2,getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2:getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2,getEip712BrowserRequestPasskeyPublicKey:getEip712BrowserRequestPasskeyPublicKey,getEthereumMessageSigner:getEthereumMessageSigner,getEthereumRegularSigner:getEthereumRegularSigner,signEip712:signEip712,verifyEip712Signature:verifyEip712Signature});var index = { ...payloads, ...address, ...signatureDefinitions, ...signature };export{ADD_KEY_DATA_DEFINITION,ADD_PROVIDER_DEFINITION,CLAIM_HANDLE_PAYLOAD_DEFINITION,EIP712_DOMAIN_DEFAULT,EIP712_DOMAIN_DEFINITION,ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2,PASSKEY_PUBLIC_KEY_DEFINITION,createAddKeyData,createAddProvider,createClaimHandlePayload,createItemizedAddAction,createItemizedDeleteAction,createItemizedSignaturePayloadV2,createPaginatedDeleteSignaturePayloadV2,createPaginatedUpsertSignaturePayloadV2,createPasskeyPublicKey,createRandomKey,index as default,ethereumAddressToKeyringPair,getAccountId20MultiAddress,getEip712BrowserRequestAddKeyData,getEip712BrowserRequestAddProvider,getEip712BrowserRequestClaimHandlePayload,getEip712BrowserRequestItemizedSignaturePayloadV2,getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2,getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2,getEip712BrowserRequestPasskeyPublicKey,getEthereumMessageSigner,getEthereumRegularSigner,getKeyringPairFromSecp256k1PrivateKey,getSS58AccountFromEthereumAccount,getUnifiedAddress,getUnifiedPublicKey,reverseUnifiedAddressToEthereumAddress,signEip712,verifyEip712Signature};
20246
+ }var signature=/*#__PURE__*/Object.freeze({__proto__:null,createAddKeyData:createAddKeyData,createAddProvider:createAddProvider,createAuthorizedKeyData:createAuthorizedKeyData,createClaimHandlePayload:createClaimHandlePayload,createItemizedAddAction:createItemizedAddAction,createItemizedDeleteAction:createItemizedDeleteAction,createItemizedSignaturePayloadV2:createItemizedSignaturePayloadV2,createPaginatedDeleteSignaturePayloadV2:createPaginatedDeleteSignaturePayloadV2,createPaginatedUpsertSignaturePayloadV2:createPaginatedUpsertSignaturePayloadV2,createPasskeyPublicKey:createPasskeyPublicKey,createSiwfLoginRequestPayload:createSiwfLoginRequestPayload,createSiwfSignedRequestPayload:createSiwfSignedRequestPayload,getEip712BrowserRequestAddKeyData:getEip712BrowserRequestAddKeyData,getEip712BrowserRequestAddProvider:getEip712BrowserRequestAddProvider,getEip712BrowserRequestAuthorizedKeyData:getEip712BrowserRequestAuthorizedKeyData,getEip712BrowserRequestClaimHandlePayload:getEip712BrowserRequestClaimHandlePayload,getEip712BrowserRequestItemizedSignaturePayloadV2:getEip712BrowserRequestItemizedSignaturePayloadV2,getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2:getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2,getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2:getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2,getEip712BrowserRequestPasskeyPublicKey:getEip712BrowserRequestPasskeyPublicKey,getEip712BrowserRequestSiwfSignedRequestPayload:getEip712BrowserRequestSiwfSignedRequestPayload,getEthereumMessageSigner:getEthereumMessageSigner,getEthereumRegularSigner:getEthereumRegularSigner,sign:sign,verifySignature:verifySignature});var index = { ...payloads, ...address, ...signatureDefinitions, ...signature };export{ADD_KEY_DATA_DEFINITION,ADD_PROVIDER_DEFINITION,AUTHORIZED_KEY_DATA_DEFINITION,CLAIM_HANDLE_PAYLOAD_DEFINITION,EIP712_DOMAIN_DEFAULT,EIP712_DOMAIN_DEFINITION,ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2,PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2,PASSKEY_PUBLIC_KEY_DEFINITION,SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION,createAddKeyData,createAddProvider,createAuthorizedKeyData,createClaimHandlePayload,createItemizedAddAction,createItemizedDeleteAction,createItemizedSignaturePayloadV2,createPaginatedDeleteSignaturePayloadV2,createPaginatedUpsertSignaturePayloadV2,createPasskeyPublicKey,createRandomKey,createSiwfLoginRequestPayload,createSiwfSignedRequestPayload,index as default,ethereumAddressToKeyringPair,getAccountId20MultiAddress,getEip712BrowserRequestAddKeyData,getEip712BrowserRequestAddProvider,getEip712BrowserRequestAuthorizedKeyData,getEip712BrowserRequestClaimHandlePayload,getEip712BrowserRequestItemizedSignaturePayloadV2,getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2,getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2,getEip712BrowserRequestPasskeyPublicKey,getEip712BrowserRequestSiwfSignedRequestPayload,getEthereumMessageSigner,getEthereumRegularSigner,getKeyringPairFromSecp256k1PrivateKey,getSS58AccountFromEthereumAccount,getUnifiedAddress,getUnifiedPublicKey,reverseUnifiedAddressToEthereumAddress,sign,verifySignature};