@noble/curves 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/README.md +429 -281
  2. package/{lib/_shortw_utils.d.ts → _shortw_utils.d.ts} +1 -0
  3. package/_shortw_utils.d.ts.map +1 -0
  4. package/{lib/_shortw_utils.js → _shortw_utils.js} +2 -0
  5. package/_shortw_utils.js.map +1 -0
  6. package/{lib/abstract → abstract}/bls.d.ts +4 -9
  7. package/abstract/bls.d.ts.map +1 -0
  8. package/{lib/abstract → abstract}/bls.js +12 -25
  9. package/abstract/bls.js.map +1 -0
  10. package/{lib/abstract → abstract}/curve.d.ts +1 -0
  11. package/abstract/curve.d.ts.map +1 -0
  12. package/{lib/abstract → abstract}/curve.js +1 -0
  13. package/abstract/curve.js.map +1 -0
  14. package/{lib/abstract → abstract}/edwards.d.ts +1 -0
  15. package/abstract/edwards.d.ts.map +1 -0
  16. package/{lib/abstract → abstract}/edwards.js +9 -15
  17. package/abstract/edwards.js.map +1 -0
  18. package/{lib/abstract → abstract}/hash-to-curve.d.ts +5 -5
  19. package/abstract/hash-to-curve.d.ts.map +1 -0
  20. package/{lib/abstract → abstract}/hash-to-curve.js +41 -38
  21. package/abstract/hash-to-curve.js.map +1 -0
  22. package/{lib/abstract → abstract}/modular.d.ts +1 -0
  23. package/abstract/modular.d.ts.map +1 -0
  24. package/{lib/abstract → abstract}/modular.js +2 -1
  25. package/abstract/modular.js.map +1 -0
  26. package/{lib/abstract → abstract}/montgomery.d.ts +1 -0
  27. package/abstract/montgomery.d.ts.map +1 -0
  28. package/{lib/abstract → abstract}/montgomery.js +3 -2
  29. package/abstract/montgomery.js.map +1 -0
  30. package/{lib/abstract → abstract}/poseidon.d.ts +1 -0
  31. package/abstract/poseidon.d.ts.map +1 -0
  32. package/{lib/abstract → abstract}/poseidon.js +1 -0
  33. package/abstract/poseidon.js.map +1 -0
  34. package/{lib/abstract → abstract}/utils.d.ts +12 -1
  35. package/abstract/utils.d.ts.map +1 -0
  36. package/{lib/abstract → abstract}/utils.js +96 -10
  37. package/abstract/utils.js.map +1 -0
  38. package/{lib/abstract → abstract}/weierstrass.d.ts +4 -3
  39. package/abstract/weierstrass.d.ts.map +1 -0
  40. package/{lib/abstract → abstract}/weierstrass.js +45 -91
  41. package/abstract/weierstrass.js.map +1 -0
  42. package/{lib/bls12-381.d.ts → bls12-381.d.ts} +1 -0
  43. package/bls12-381.d.ts.map +1 -0
  44. package/{lib/bls12-381.js → bls12-381.js} +41 -7
  45. package/bls12-381.js.map +1 -0
  46. package/{lib/bn.d.ts → bn.d.ts} +1 -0
  47. package/bn.d.ts.map +1 -0
  48. package/{lib/bn.js → bn.js} +1 -0
  49. package/bn.js.map +1 -0
  50. package/{lib/ed25519.d.ts → ed25519.d.ts} +2 -1
  51. package/ed25519.d.ts.map +1 -0
  52. package/{lib/ed25519.js → ed25519.js} +4 -3
  53. package/ed25519.js.map +1 -0
  54. package/{lib/ed448.d.ts → ed448.d.ts} +2 -1
  55. package/ed448.d.ts.map +1 -0
  56. package/{lib/ed448.js → ed448.js} +2 -1
  57. package/ed448.js.map +1 -0
  58. package/{lib/esm → esm}/_shortw_utils.js +2 -0
  59. package/esm/_shortw_utils.js.map +1 -0
  60. package/{lib/esm → esm}/abstract/bls.js +13 -26
  61. package/esm/abstract/bls.js.map +1 -0
  62. package/{lib/esm → esm}/abstract/curve.js +1 -0
  63. package/esm/abstract/curve.js.map +1 -0
  64. package/{lib/esm → esm}/abstract/edwards.js +9 -15
  65. package/esm/abstract/edwards.js.map +1 -0
  66. package/{lib/esm → esm}/abstract/hash-to-curve.js +40 -36
  67. package/esm/abstract/hash-to-curve.js.map +1 -0
  68. package/{lib/esm → esm}/abstract/modular.js +2 -1
  69. package/esm/abstract/modular.js.map +1 -0
  70. package/{lib/esm → esm}/abstract/montgomery.js +3 -2
  71. package/esm/abstract/montgomery.js.map +1 -0
  72. package/{lib/esm → esm}/abstract/poseidon.js +1 -0
  73. package/esm/abstract/poseidon.js.map +1 -0
  74. package/{lib/esm → esm}/abstract/utils.js +93 -9
  75. package/esm/abstract/utils.js.map +1 -0
  76. package/{lib/esm → esm}/abstract/weierstrass.js +45 -91
  77. package/esm/abstract/weierstrass.js.map +1 -0
  78. package/{lib/esm → esm}/bls12-381.js +41 -7
  79. package/esm/bls12-381.js.map +1 -0
  80. package/{lib/esm → esm}/bn.js +1 -0
  81. package/esm/bn.js.map +1 -0
  82. package/{lib/esm → esm}/ed25519.js +5 -4
  83. package/esm/ed25519.js.map +1 -0
  84. package/{lib/esm → esm}/ed448.js +2 -1
  85. package/esm/ed448.js.map +1 -0
  86. package/{lib → esm}/index.js +1 -0
  87. package/esm/index.js.map +1 -0
  88. package/{lib/esm → esm}/jubjub.js +1 -0
  89. package/esm/jubjub.js.map +1 -0
  90. package/{lib/esm → esm}/p192.js +1 -0
  91. package/esm/p192.js.map +1 -0
  92. package/{lib/esm → esm}/p224.js +1 -0
  93. package/esm/p224.js.map +1 -0
  94. package/{lib/esm → esm}/p256.js +2 -1
  95. package/esm/p256.js.map +1 -0
  96. package/{lib/esm → esm}/p384.js +2 -1
  97. package/esm/p384.js.map +1 -0
  98. package/{lib/esm → esm}/p521.js +2 -1
  99. package/esm/p521.js.map +1 -0
  100. package/{lib/esm → esm}/package.json +0 -0
  101. package/{lib/esm → esm}/pasta.js +1 -0
  102. package/esm/pasta.js.map +1 -0
  103. package/{lib/esm → esm}/secp256k1.js +41 -50
  104. package/esm/secp256k1.js.map +1 -0
  105. package/{lib/esm → esm}/stark.js +1 -0
  106. package/esm/stark.js.map +1 -0
  107. package/index.d.ts +1 -0
  108. package/index.d.ts.map +1 -0
  109. package/index.js +3 -0
  110. package/index.js.map +1 -0
  111. package/{lib/jubjub.d.ts → jubjub.d.ts} +1 -0
  112. package/jubjub.d.ts.map +1 -0
  113. package/{lib/jubjub.js → jubjub.js} +1 -0
  114. package/jubjub.js.map +1 -0
  115. package/{lib/p192.d.ts → p192.d.ts} +1 -0
  116. package/p192.d.ts.map +1 -0
  117. package/{lib/p192.js → p192.js} +1 -0
  118. package/p192.js.map +1 -0
  119. package/{lib/p224.d.ts → p224.d.ts} +1 -0
  120. package/p224.d.ts.map +1 -0
  121. package/{lib/p224.js → p224.js} +1 -0
  122. package/p224.js.map +1 -0
  123. package/{lib/p256.d.ts → p256.d.ts} +2 -1
  124. package/p256.d.ts.map +1 -0
  125. package/{lib/p256.js → p256.js} +2 -1
  126. package/p256.js.map +1 -0
  127. package/{lib/p384.d.ts → p384.d.ts} +2 -1
  128. package/p384.d.ts.map +1 -0
  129. package/{lib/p384.js → p384.js} +2 -1
  130. package/p384.js.map +1 -0
  131. package/{lib/p521.d.ts → p521.d.ts} +2 -1
  132. package/p521.d.ts.map +1 -0
  133. package/{lib/p521.js → p521.js} +2 -1
  134. package/p521.js.map +1 -0
  135. package/package.json +84 -79
  136. package/{lib/pasta.d.ts → pasta.d.ts} +1 -0
  137. package/pasta.d.ts.map +1 -0
  138. package/{lib/pasta.js → pasta.js} +1 -0
  139. package/pasta.js.map +1 -0
  140. package/{lib/secp256k1.d.ts → secp256k1.d.ts} +15 -5
  141. package/secp256k1.d.ts.map +1 -0
  142. package/{lib/secp256k1.js → secp256k1.js} +38 -47
  143. package/secp256k1.js.map +1 -0
  144. package/src/_shortw_utils.ts +20 -0
  145. package/src/abstract/bls.ts +376 -0
  146. package/src/abstract/curve.ts +199 -0
  147. package/src/abstract/edwards.ts +479 -0
  148. package/src/abstract/hash-to-curve.ts +220 -0
  149. package/src/abstract/modular.ts +417 -0
  150. package/src/abstract/montgomery.ts +184 -0
  151. package/src/abstract/poseidon.ts +119 -0
  152. package/src/abstract/utils.ts +246 -0
  153. package/src/abstract/weierstrass.ts +1175 -0
  154. package/src/bls12-381.ts +1274 -0
  155. package/src/bn.ts +21 -0
  156. package/src/ed25519.ts +428 -0
  157. package/src/ed448.ts +241 -0
  158. package/{lib/esm/index.js → src/index.ts} +0 -1
  159. package/src/jubjub.ts +58 -0
  160. package/src/p192.ts +25 -0
  161. package/src/p224.ts +25 -0
  162. package/src/p256.ts +53 -0
  163. package/src/p384.ts +57 -0
  164. package/src/p521.ts +57 -0
  165. package/src/pasta.ts +31 -0
  166. package/src/secp256k1.ts +260 -0
  167. package/src/stark.ts +356 -0
  168. package/{lib/stark.d.ts → stark.d.ts} +1 -0
  169. package/stark.d.ts.map +1 -0
  170. package/{lib/stark.js → stark.js} +1 -0
  171. package/stark.js.map +1 -0
  172. package/lib/index.d.ts +0 -0
@@ -0,0 +1,119 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ // Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info
3
+ import { Field, FpPow, validateField } from './modular.js';
4
+ // We don't provide any constants, since different implementations use different constants.
5
+ // For reference constants see './test/poseidon.test.js'.
6
+ export type PoseidonOpts = {
7
+ Fp: Field<bigint>;
8
+ t: number;
9
+ roundsFull: number;
10
+ roundsPartial: number;
11
+ sboxPower?: number;
12
+ reversePartialPowIdx?: boolean; // Hack for stark
13
+ mds: bigint[][];
14
+ roundConstants: bigint[][];
15
+ };
16
+
17
+ export function validateOpts(opts: PoseidonOpts) {
18
+ const { Fp } = opts;
19
+ validateField(Fp);
20
+ for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) {
21
+ if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
22
+ throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`);
23
+ }
24
+ if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean')
25
+ throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`);
26
+ // Default is 5, but by some reasons stark uses 3
27
+ let sboxPower = opts.sboxPower;
28
+ if (sboxPower === undefined) sboxPower = 5;
29
+ if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower))
30
+ throw new Error(`Poseidon wrong sboxPower=${sboxPower}`);
31
+
32
+ const _sboxPower = BigInt(sboxPower);
33
+ let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower);
34
+ // Unwrapped sbox power for common cases (195->142μs)
35
+ if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n);
36
+ else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
37
+
38
+ if (opts.roundsFull % 2 !== 0)
39
+ throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`);
40
+ const rounds = opts.roundsFull + opts.roundsPartial;
41
+
42
+ if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds)
43
+ throw new Error('Poseidon: wrong round constants');
44
+ const roundConstants = opts.roundConstants.map((rc) => {
45
+ if (!Array.isArray(rc) || rc.length !== opts.t)
46
+ throw new Error(`Poseidon wrong round constants: ${rc}`);
47
+ return rc.map((i) => {
48
+ if (typeof i !== 'bigint' || !Fp.isValid(i))
49
+ throw new Error(`Poseidon wrong round constant=${i}`);
50
+ return Fp.create(i);
51
+ });
52
+ });
53
+ // MDS is TxT matrix
54
+ if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t)
55
+ throw new Error('Poseidon: wrong MDS matrix');
56
+ const mds = opts.mds.map((mdsRow) => {
57
+ if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t)
58
+ throw new Error(`Poseidon MDS matrix row: ${mdsRow}`);
59
+ return mdsRow.map((i) => {
60
+ if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`);
61
+ return Fp.create(i);
62
+ });
63
+ });
64
+ return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds });
65
+ }
66
+
67
+ export function splitConstants(rc: bigint[], t: number) {
68
+ if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t');
69
+ if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc');
70
+ const res = [];
71
+ let tmp = [];
72
+ for (let i = 0; i < rc.length; i++) {
73
+ tmp.push(rc[i]);
74
+ if (tmp.length === t) {
75
+ res.push(tmp);
76
+ tmp = [];
77
+ }
78
+ }
79
+ return res;
80
+ }
81
+
82
+ export function poseidon(opts: PoseidonOpts) {
83
+ const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts);
84
+ const halfRoundsFull = Math.floor(opts.roundsFull / 2);
85
+ const partialIdx = reversePartialPowIdx ? t - 1 : 0;
86
+ const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => {
87
+ values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j]));
88
+
89
+ if (isFull) values = values.map((i) => sboxFn(i));
90
+ else values[partialIdx] = sboxFn(values[partialIdx]);
91
+ // Matrix multiplication
92
+ values = opts.mds.map((i) =>
93
+ i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)
94
+ );
95
+ return values;
96
+ };
97
+ const poseidonHash = function poseidonHash(values: bigint[]) {
98
+ if (!Array.isArray(values) || values.length !== t)
99
+ throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`);
100
+ values = values.map((i) => {
101
+ if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`);
102
+ return Fp.create(i);
103
+ });
104
+ let round = 0;
105
+ // Apply r_f/2 full rounds.
106
+ for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++);
107
+ // Apply r_p partial rounds.
108
+ for (let i = 0; i < opts.roundsPartial; i++) values = poseidonRound(values, false, round++);
109
+ // Apply r_f/2 full rounds.
110
+ for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++);
111
+
112
+ if (round !== rounds)
113
+ throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`);
114
+ return values;
115
+ };
116
+ // For verification in tests
117
+ poseidonHash.roundConstants = opts.roundConstants;
118
+ return poseidonHash;
119
+ }
@@ -0,0 +1,246 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ const _0n = BigInt(0);
3
+ const _1n = BigInt(1);
4
+ const _2n = BigInt(2);
5
+ const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;
6
+
7
+ // We accept hex strings besides Uint8Array for simplicity
8
+ export type Hex = Uint8Array | string;
9
+ // Very few implementations accept numbers, we do it to ease learning curve
10
+ export type PrivKey = Hex | bigint;
11
+ export type CHash = {
12
+ (message: Uint8Array | string): Uint8Array;
13
+ blockLen: number;
14
+ outputLen: number;
15
+ create(opts?: { dkLen?: number }): any; // For shake
16
+ };
17
+ export type FHash = (message: Uint8Array | string) => Uint8Array;
18
+
19
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
20
+ export function bytesToHex(bytes: Uint8Array): string {
21
+ if (!u8a(bytes)) throw new Error('Uint8Array expected');
22
+ // pre-caching improves the speed 6x
23
+ let hex = '';
24
+ for (let i = 0; i < bytes.length; i++) {
25
+ hex += hexes[bytes[i]];
26
+ }
27
+ return hex;
28
+ }
29
+
30
+ export function numberToHexUnpadded(num: number | bigint): string {
31
+ const hex = num.toString(16);
32
+ return hex.length & 1 ? `0${hex}` : hex;
33
+ }
34
+
35
+ export function hexToNumber(hex: string): bigint {
36
+ if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
37
+ // Big Endian
38
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
39
+ }
40
+
41
+ // Caching slows it down 2-3x
42
+ export function hexToBytes(hex: string): Uint8Array {
43
+ if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
44
+ if (hex.length % 2) throw new Error('hex string is invalid: unpadded ' + hex.length);
45
+ const array = new Uint8Array(hex.length / 2);
46
+ for (let i = 0; i < array.length; i++) {
47
+ const j = i * 2;
48
+ const hexByte = hex.slice(j, j + 2);
49
+ const byte = Number.parseInt(hexByte, 16);
50
+ if (Number.isNaN(byte) || byte < 0) throw new Error('invalid byte sequence');
51
+ array[i] = byte;
52
+ }
53
+ return array;
54
+ }
55
+
56
+ // Big Endian
57
+ export function bytesToNumberBE(bytes: Uint8Array): bigint {
58
+ return hexToNumber(bytesToHex(bytes));
59
+ }
60
+ export function bytesToNumberLE(bytes: Uint8Array): bigint {
61
+ if (!u8a(bytes)) throw new Error('Uint8Array expected');
62
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
63
+ }
64
+
65
+ export const numberToBytesBE = (n: bigint, len: number) =>
66
+ hexToBytes(n.toString(16).padStart(len * 2, '0'));
67
+ export const numberToBytesLE = (n: bigint, len: number) => numberToBytesBE(n, len).reverse();
68
+ // Returns variable number bytes (minimal bigint encoding?)
69
+ export const numberToVarBytesBE = (n: bigint) => hexToBytes(numberToHexUnpadded(n));
70
+
71
+ export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {
72
+ let res: Uint8Array;
73
+ if (typeof hex === 'string') {
74
+ try {
75
+ res = hexToBytes(hex);
76
+ } catch (e) {
77
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
78
+ }
79
+ } else if (u8a(hex)) {
80
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
81
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
82
+ res = Uint8Array.from(hex);
83
+ } else {
84
+ throw new Error(`${title} must be hex string or Uint8Array`);
85
+ }
86
+ const len = res.length;
87
+ if (typeof expectedLength === 'number' && len !== expectedLength)
88
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
89
+ return res;
90
+ }
91
+
92
+ // Copies several Uint8Arrays into one.
93
+ export function concatBytes(...arrs: Uint8Array[]): Uint8Array {
94
+ const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));
95
+ let pad = 0; // walk through each item, ensure they have proper type
96
+ arrs.forEach((a) => {
97
+ if (!u8a(a)) throw new Error('Uint8Array expected');
98
+ r.set(a, pad);
99
+ pad += a.length;
100
+ });
101
+ return r;
102
+ }
103
+
104
+ export function equalBytes(b1: Uint8Array, b2: Uint8Array) {
105
+ // We don't care about timing attacks here
106
+ if (b1.length !== b2.length) return false;
107
+ for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;
108
+ return true;
109
+ }
110
+
111
+ // Global symbols in both browsers and Node.js since v11
112
+ // See https://github.com/microsoft/TypeScript/issues/31535
113
+ declare const TextEncoder: any;
114
+ export function utf8ToBytes(str: string): Uint8Array {
115
+ if (typeof str !== 'string') {
116
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
117
+ }
118
+ return new TextEncoder().encode(str);
119
+ }
120
+
121
+ // Bit operations
122
+
123
+ // Amount of bits inside bigint (Same as n.toString(2).length)
124
+ export function bitLen(n: bigint) {
125
+ let len;
126
+ for (len = 0; n > 0n; n >>= _1n, len += 1);
127
+ return len;
128
+ }
129
+ // Gets single bit at position. NOTE: first bit position is 0 (same as arrays)
130
+ // Same as !!+Array.from(n.toString(2)).reverse()[pos]
131
+ export const bitGet = (n: bigint, pos: number) => (n >> BigInt(pos)) & 1n;
132
+ // Sets single bit at position
133
+ export const bitSet = (n: bigint, pos: number, value: boolean) =>
134
+ n | ((value ? _1n : _0n) << BigInt(pos));
135
+ // Return mask for N bits (Same as BigInt(`0b${Array(i).fill('1').join('')}`))
136
+ // Not using ** operator with bigints for old engines.
137
+ export const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;
138
+
139
+ // DRBG
140
+
141
+ const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array
142
+ const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut
143
+ type Pred<T> = (v: Uint8Array) => T | undefined;
144
+ /**
145
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
146
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
147
+ * @example
148
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
149
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
150
+ */
151
+ export function createHmacDrbg<T>(
152
+ hashLen: number,
153
+ qByteLen: number,
154
+ hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array
155
+ ): (seed: Uint8Array, predicate: Pred<T>) => T {
156
+ if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');
157
+ if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');
158
+ if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');
159
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
160
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
161
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
162
+ let i = 0; // Iterations counter, will throw when over 1000
163
+ const reset = () => {
164
+ v.fill(1);
165
+ k.fill(0);
166
+ i = 0;
167
+ };
168
+ const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
169
+ const reseed = (seed = u8n()) => {
170
+ // HMAC-DRBG reseed() function. Steps D-G
171
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
172
+ v = h(); // v = hmac(k || v)
173
+ if (seed.length === 0) return;
174
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
175
+ v = h(); // v = hmac(k || v)
176
+ };
177
+ const gen = () => {
178
+ // HMAC-DRBG generate() function
179
+ if (i++ >= 1000) throw new Error('drbg: tried 1000 values');
180
+ let len = 0;
181
+ const out: Uint8Array[] = [];
182
+ while (len < qByteLen) {
183
+ v = h();
184
+ const sl = v.slice();
185
+ out.push(sl);
186
+ len += v.length;
187
+ }
188
+ return concatBytes(...out);
189
+ };
190
+ const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {
191
+ reset();
192
+ reseed(seed); // Steps D-G
193
+ let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]
194
+ while (!(res = pred(gen()))) reseed();
195
+ reset();
196
+ return res;
197
+ };
198
+ return genUntil;
199
+ }
200
+
201
+ // Validating curves and fields
202
+
203
+ const validatorFns = {
204
+ bigint: (val: any) => typeof val === 'bigint',
205
+ function: (val: any) => typeof val === 'function',
206
+ boolean: (val: any) => typeof val === 'boolean',
207
+ string: (val: any) => typeof val === 'string',
208
+ isSafeInteger: (val: any) => Number.isSafeInteger(val),
209
+ array: (val: any) => Array.isArray(val),
210
+ field: (val: any, object: any) => (object as any).Fp.isValid(val),
211
+ hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
212
+ } as const;
213
+ type Validator = keyof typeof validatorFns;
214
+ type ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };
215
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
216
+
217
+ export function validateObject<T extends Record<string, any>>(
218
+ object: T,
219
+ validators: ValMap<T>,
220
+ optValidators: ValMap<T> = {}
221
+ ) {
222
+ const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {
223
+ const checkVal = validatorFns[type];
224
+ if (typeof checkVal !== 'function')
225
+ throw new Error(`Invalid validator "${type}", expected function`);
226
+
227
+ const val = object[fieldName as keyof typeof object];
228
+ if (isOptional && val === undefined) return;
229
+ if (!checkVal(val, object)) {
230
+ throw new Error(
231
+ `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`
232
+ );
233
+ }
234
+ };
235
+ for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);
236
+ for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);
237
+ return object;
238
+ }
239
+ // validate type tests
240
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
241
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
242
+ // // Should fail type-check
243
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
244
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
245
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
246
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });