@leofcoin/chain 1.10.9 → 1.10.11

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 (44) hide show
  1. package/exports/beacon-envelope.js +68 -0
  2. package/exports/beacon-epoch.js +117 -0
  3. package/exports/beacon-lifecycle.js +155 -0
  4. package/exports/beacon-round.js +77 -0
  5. package/exports/beacon-wire.js +98 -0
  6. package/exports/beacon.js +141 -0
  7. package/exports/browser/beacon-envelope.js +163 -0
  8. package/exports/browser/beacon-epoch.js +116 -0
  9. package/exports/browser/beacon-lifecycle.js +154 -0
  10. package/exports/browser/beacon-round.js +76 -0
  11. package/exports/browser/beacon-wire.js +99 -0
  12. package/exports/browser/beacon.js +1706 -0
  13. package/exports/browser/{browser-D-r0O9Qn-BZDYY6cg.js → browser-CWeoyGUw-BabtHowB.js} +4 -2
  14. package/exports/browser/{browser-_hiyXwPp-DYI1tyUr.js → browser-DvU1xNFS-sdlKNCJc.js} +4 -2
  15. package/exports/browser/chain.js +174 -5008
  16. package/exports/browser/{client-BVhUamQG-D-D1e_x8.js → client-B-jyclOB-CsNYfj4Z.js} +6 -4
  17. package/exports/browser/constants-Cv0p224A.js +130 -0
  18. package/exports/browser/hkdf-DhdhLAAv.js +147 -0
  19. package/exports/browser/{index-BD0Anx7_-Dg4_tCeN.js → index-Bxr5Iztg-C6xBk0rK.js} +4 -2
  20. package/exports/browser/index-CvKt4UDE.js +464 -0
  21. package/exports/browser/index-D7FUx7Dd.js +4996 -0
  22. package/exports/browser/{messages-UKnuelZ7-DJT-98q-.js → messages-FMRAS8QX-CvlZBzy5.js} +4 -2
  23. package/exports/browser/{node-browser-DlzZ5CP_.js → node-browser-xlqSBOaN.js} +12 -5
  24. package/exports/browser/node-browser.js +4 -2
  25. package/exports/browser/{constants-gMYZLHKp.js → proposal.proto-BcUgd885.js} +61 -620
  26. package/exports/browser/quorum-S_qdgiAY.js +8 -0
  27. package/exports/browser/weierstrass-C-jX_jly.js +2156 -0
  28. package/exports/browser/workers/block-worker.js +1 -1
  29. package/exports/browser/workers/machine-worker.js +7142 -72
  30. package/exports/browser/workers/{worker-CZqErLI7-BxofVJAn.js → worker-DMCj1e6z-CTYVa2yX.js} +30 -1
  31. package/exports/chain.js +158 -75
  32. package/exports/{constants-D6gWzJZg.js → constants-CMYKv-Rt.js} +1 -1
  33. package/exports/node.js +1 -1
  34. package/exports/quorum-S_qdgiAY.js +8 -0
  35. package/exports/workers/block-worker.js +1 -1
  36. package/exports/workers/machine-worker.js +7142 -72
  37. package/exports/workers/{worker-CZqErLI7-BxofVJAn.js → worker-DMCj1e6z-CTYVa2yX.js} +30 -1
  38. package/package.json +29 -2
  39. package/types/beacon-envelope.d.ts +27 -0
  40. package/types/beacon-epoch.d.ts +28 -0
  41. package/types/beacon-lifecycle.d.ts +40 -0
  42. package/types/beacon-round.d.ts +18 -0
  43. package/types/beacon-wire.d.ts +31 -0
  44. package/types/beacon.d.ts +24 -0
@@ -0,0 +1,2156 @@
1
+ function number(n) {
2
+ if (!Number.isSafeInteger(n) || n < 0)
3
+ throw new Error(`Wrong positive integer: ${n}`);
4
+ }
5
+ function bytes(b, ...lengths) {
6
+ if (!(b instanceof Uint8Array))
7
+ throw new Error('Expected Uint8Array');
8
+ if (lengths.length > 0 && !lengths.includes(b.length))
9
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
10
+ }
11
+ function hash(hash) {
12
+ if (typeof hash !== 'function' || typeof hash.create !== 'function')
13
+ throw new Error('Hash should be wrapped by utils.wrapConstructor');
14
+ number(hash.outputLen);
15
+ number(hash.blockLen);
16
+ }
17
+ function exists(instance, checkFinished = true) {
18
+ if (instance.destroyed)
19
+ throw new Error('Hash instance has been destroyed');
20
+ if (checkFinished && instance.finished)
21
+ throw new Error('Hash#digest() has already been called');
22
+ }
23
+ function output(out, instance) {
24
+ bytes(out);
25
+ const min = instance.outputLen;
26
+ if (out.length < min) {
27
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
28
+ }
29
+ }
30
+
31
+ const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
32
+
33
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
34
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
35
+ // node.js versions earlier than v19 don't declare it in global scope.
36
+ // For node.js, package.json#exports field mapping rewrites import
37
+ // from `crypto` to `cryptoNode`, which imports native module.
38
+ // Makes the utils un-importable in browsers without a bundler.
39
+ // Once node.js 18 is deprecated, we can just drop the import.
40
+ const u8a$1 = (a) => a instanceof Uint8Array;
41
+ // Cast array to view
42
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
43
+ // The rotate right (circular right shift) operation for uint32
44
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
45
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
46
+ // early-throw an error because we don't support BE yet.
47
+ const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
48
+ if (!isLE)
49
+ throw new Error('Non little-endian hardware is not supported');
50
+ /**
51
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
52
+ */
53
+ function utf8ToBytes$1(str) {
54
+ if (typeof str !== 'string')
55
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
56
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
57
+ }
58
+ /**
59
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
60
+ * Warning: when Uint8Array is passed, it would NOT get copied.
61
+ * Keep in mind for future mutable operations.
62
+ */
63
+ function toBytes(data) {
64
+ if (typeof data === 'string')
65
+ data = utf8ToBytes$1(data);
66
+ if (!u8a$1(data))
67
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
68
+ return data;
69
+ }
70
+ /**
71
+ * Copies several Uint8Arrays into one.
72
+ */
73
+ function concatBytes$1(...arrays) {
74
+ const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
75
+ let pad = 0; // walk through each item, ensure they have proper type
76
+ arrays.forEach((a) => {
77
+ if (!u8a$1(a))
78
+ throw new Error('Uint8Array expected');
79
+ r.set(a, pad);
80
+ pad += a.length;
81
+ });
82
+ return r;
83
+ }
84
+ // For runtime check if class implements interface
85
+ class Hash {
86
+ // Safe version that clones internal state
87
+ clone() {
88
+ return this._cloneInto();
89
+ }
90
+ }
91
+ function wrapConstructor(hashCons) {
92
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
93
+ const tmp = hashCons();
94
+ hashC.outputLen = tmp.outputLen;
95
+ hashC.blockLen = tmp.blockLen;
96
+ hashC.create = () => hashCons();
97
+ return hashC;
98
+ }
99
+ /**
100
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
101
+ */
102
+ function randomBytes(bytesLength = 32) {
103
+ if (crypto && typeof crypto.getRandomValues === 'function') {
104
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
105
+ }
106
+ throw new Error('crypto.getRandomValues must be defined');
107
+ }
108
+
109
+ // Polyfill for Safari 14
110
+ function setBigUint64(view, byteOffset, value, isLE) {
111
+ if (typeof view.setBigUint64 === 'function')
112
+ return view.setBigUint64(byteOffset, value, isLE);
113
+ const _32n = BigInt(32);
114
+ const _u32_max = BigInt(0xffffffff);
115
+ const wh = Number((value >> _32n) & _u32_max);
116
+ const wl = Number(value & _u32_max);
117
+ const h = isLE ? 4 : 0;
118
+ const l = isLE ? 0 : 4;
119
+ view.setUint32(byteOffset + h, wh, isLE);
120
+ view.setUint32(byteOffset + l, wl, isLE);
121
+ }
122
+ // Base SHA2 class (RFC 6234)
123
+ class SHA2 extends Hash {
124
+ constructor(blockLen, outputLen, padOffset, isLE) {
125
+ super();
126
+ this.blockLen = blockLen;
127
+ this.outputLen = outputLen;
128
+ this.padOffset = padOffset;
129
+ this.isLE = isLE;
130
+ this.finished = false;
131
+ this.length = 0;
132
+ this.pos = 0;
133
+ this.destroyed = false;
134
+ this.buffer = new Uint8Array(blockLen);
135
+ this.view = createView(this.buffer);
136
+ }
137
+ update(data) {
138
+ exists(this);
139
+ const { view, buffer, blockLen } = this;
140
+ data = toBytes(data);
141
+ const len = data.length;
142
+ for (let pos = 0; pos < len;) {
143
+ const take = Math.min(blockLen - this.pos, len - pos);
144
+ // Fast path: we have at least one block in input, cast it to view and process
145
+ if (take === blockLen) {
146
+ const dataView = createView(data);
147
+ for (; blockLen <= len - pos; pos += blockLen)
148
+ this.process(dataView, pos);
149
+ continue;
150
+ }
151
+ buffer.set(data.subarray(pos, pos + take), this.pos);
152
+ this.pos += take;
153
+ pos += take;
154
+ if (this.pos === blockLen) {
155
+ this.process(view, 0);
156
+ this.pos = 0;
157
+ }
158
+ }
159
+ this.length += data.length;
160
+ this.roundClean();
161
+ return this;
162
+ }
163
+ digestInto(out) {
164
+ exists(this);
165
+ output(out, this);
166
+ this.finished = true;
167
+ // Padding
168
+ // We can avoid allocation of buffer for padding completely if it
169
+ // was previously not allocated here. But it won't change performance.
170
+ const { buffer, view, blockLen, isLE } = this;
171
+ let { pos } = this;
172
+ // append the bit '1' to the message
173
+ buffer[pos++] = 0b10000000;
174
+ this.buffer.subarray(pos).fill(0);
175
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
176
+ if (this.padOffset > blockLen - pos) {
177
+ this.process(view, 0);
178
+ pos = 0;
179
+ }
180
+ // Pad until full block byte with zeros
181
+ for (let i = pos; i < blockLen; i++)
182
+ buffer[i] = 0;
183
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
184
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
185
+ // So we just write lowest 64 bits of that value.
186
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
187
+ this.process(view, 0);
188
+ const oview = createView(out);
189
+ const len = this.outputLen;
190
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
191
+ if (len % 4)
192
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
193
+ const outLen = len / 4;
194
+ const state = this.get();
195
+ if (outLen > state.length)
196
+ throw new Error('_sha2: outputLen bigger than state');
197
+ for (let i = 0; i < outLen; i++)
198
+ oview.setUint32(4 * i, state[i], isLE);
199
+ }
200
+ digest() {
201
+ const { buffer, outputLen } = this;
202
+ this.digestInto(buffer);
203
+ const res = buffer.slice(0, outputLen);
204
+ this.destroy();
205
+ return res;
206
+ }
207
+ _cloneInto(to) {
208
+ to || (to = new this.constructor());
209
+ to.set(...this.get());
210
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
211
+ to.length = length;
212
+ to.pos = pos;
213
+ to.finished = finished;
214
+ to.destroyed = destroyed;
215
+ if (length % blockLen)
216
+ to.buffer.set(buffer);
217
+ return to;
218
+ }
219
+ }
220
+
221
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
222
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
223
+ // Choice: a ? b : c
224
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
225
+ // Majority function, true if any two inpust is true
226
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
227
+ // Round constants:
228
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
229
+ // prettier-ignore
230
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
231
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
232
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
233
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
234
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
235
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
236
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
237
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
238
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
239
+ ]);
240
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
241
+ // prettier-ignore
242
+ const IV = /* @__PURE__ */ new Uint32Array([
243
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
244
+ ]);
245
+ // Temporary buffer, not used to store anything between runs
246
+ // Named this way because it matches specification.
247
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
248
+ class SHA256 extends SHA2 {
249
+ constructor() {
250
+ super(64, 32, 8, false);
251
+ // We cannot use array here since array allows indexing by variable
252
+ // which means optimizer/compiler cannot use registers.
253
+ this.A = IV[0] | 0;
254
+ this.B = IV[1] | 0;
255
+ this.C = IV[2] | 0;
256
+ this.D = IV[3] | 0;
257
+ this.E = IV[4] | 0;
258
+ this.F = IV[5] | 0;
259
+ this.G = IV[6] | 0;
260
+ this.H = IV[7] | 0;
261
+ }
262
+ get() {
263
+ const { A, B, C, D, E, F, G, H } = this;
264
+ return [A, B, C, D, E, F, G, H];
265
+ }
266
+ // prettier-ignore
267
+ set(A, B, C, D, E, F, G, H) {
268
+ this.A = A | 0;
269
+ this.B = B | 0;
270
+ this.C = C | 0;
271
+ this.D = D | 0;
272
+ this.E = E | 0;
273
+ this.F = F | 0;
274
+ this.G = G | 0;
275
+ this.H = H | 0;
276
+ }
277
+ process(view, offset) {
278
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
279
+ for (let i = 0; i < 16; i++, offset += 4)
280
+ SHA256_W[i] = view.getUint32(offset, false);
281
+ for (let i = 16; i < 64; i++) {
282
+ const W15 = SHA256_W[i - 15];
283
+ const W2 = SHA256_W[i - 2];
284
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
285
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
286
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
287
+ }
288
+ // Compression function main loop, 64 rounds
289
+ let { A, B, C, D, E, F, G, H } = this;
290
+ for (let i = 0; i < 64; i++) {
291
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
292
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
293
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
294
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
295
+ H = G;
296
+ G = F;
297
+ F = E;
298
+ E = (D + T1) | 0;
299
+ D = C;
300
+ C = B;
301
+ B = A;
302
+ A = (T1 + T2) | 0;
303
+ }
304
+ // Add the compressed chunk to the current hash value
305
+ A = (A + this.A) | 0;
306
+ B = (B + this.B) | 0;
307
+ C = (C + this.C) | 0;
308
+ D = (D + this.D) | 0;
309
+ E = (E + this.E) | 0;
310
+ F = (F + this.F) | 0;
311
+ G = (G + this.G) | 0;
312
+ H = (H + this.H) | 0;
313
+ this.set(A, B, C, D, E, F, G, H);
314
+ }
315
+ roundClean() {
316
+ SHA256_W.fill(0);
317
+ }
318
+ destroy() {
319
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
320
+ this.buffer.fill(0);
321
+ }
322
+ }
323
+ /**
324
+ * SHA2-256 hash function
325
+ * @param message - data that would be hashed
326
+ */
327
+ const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
328
+
329
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
330
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
331
+ // This is OK: `abstract` directory does not use noble-hashes.
332
+ // User may opt-in into using different hashing library. This way, noble-hashes
333
+ // won't be included into their bundle.
334
+ const _0n$3 = BigInt(0);
335
+ const _1n$3 = BigInt(1);
336
+ const _2n$2 = BigInt(2);
337
+ const u8a = (a) => a instanceof Uint8Array;
338
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
339
+ /**
340
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
341
+ */
342
+ function bytesToHex(bytes) {
343
+ if (!u8a(bytes))
344
+ throw new Error('Uint8Array expected');
345
+ // pre-caching improves the speed 6x
346
+ let hex = '';
347
+ for (let i = 0; i < bytes.length; i++) {
348
+ hex += hexes[bytes[i]];
349
+ }
350
+ return hex;
351
+ }
352
+ function hexToNumber(hex) {
353
+ if (typeof hex !== 'string')
354
+ throw new Error('hex string expected, got ' + typeof hex);
355
+ // Big Endian
356
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
357
+ }
358
+ /**
359
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
360
+ */
361
+ function hexToBytes(hex) {
362
+ if (typeof hex !== 'string')
363
+ throw new Error('hex string expected, got ' + typeof hex);
364
+ const len = hex.length;
365
+ if (len % 2)
366
+ throw new Error('padded hex string expected, got unpadded hex of length ' + len);
367
+ const array = new Uint8Array(len / 2);
368
+ for (let i = 0; i < array.length; i++) {
369
+ const j = i * 2;
370
+ const hexByte = hex.slice(j, j + 2);
371
+ const byte = Number.parseInt(hexByte, 16);
372
+ if (Number.isNaN(byte) || byte < 0)
373
+ throw new Error('Invalid byte sequence');
374
+ array[i] = byte;
375
+ }
376
+ return array;
377
+ }
378
+ // BE: Big Endian, LE: Little Endian
379
+ function bytesToNumberBE(bytes) {
380
+ return hexToNumber(bytesToHex(bytes));
381
+ }
382
+ function bytesToNumberLE(bytes) {
383
+ if (!u8a(bytes))
384
+ throw new Error('Uint8Array expected');
385
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
386
+ }
387
+ function numberToBytesBE(n, len) {
388
+ return hexToBytes(n.toString(16).padStart(len * 2, '0'));
389
+ }
390
+ function numberToBytesLE(n, len) {
391
+ return numberToBytesBE(n, len).reverse();
392
+ }
393
+ /**
394
+ * Takes hex string or Uint8Array, converts to Uint8Array.
395
+ * Validates output length.
396
+ * Will throw error for other types.
397
+ * @param title descriptive title for an error e.g. 'private key'
398
+ * @param hex hex string or Uint8Array
399
+ * @param expectedLength optional, will compare to result array's length
400
+ * @returns
401
+ */
402
+ function ensureBytes(title, hex, expectedLength) {
403
+ let res;
404
+ if (typeof hex === 'string') {
405
+ try {
406
+ res = hexToBytes(hex);
407
+ }
408
+ catch (e) {
409
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
410
+ }
411
+ }
412
+ else if (u8a(hex)) {
413
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
414
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
415
+ res = Uint8Array.from(hex);
416
+ }
417
+ else {
418
+ throw new Error(`${title} must be hex string or Uint8Array`);
419
+ }
420
+ const len = res.length;
421
+ if (typeof expectedLength === 'number' && len !== expectedLength)
422
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
423
+ return res;
424
+ }
425
+ /**
426
+ * Copies several Uint8Arrays into one.
427
+ */
428
+ function concatBytes(...arrays) {
429
+ const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
430
+ let pad = 0; // walk through each item, ensure they have proper type
431
+ arrays.forEach((a) => {
432
+ if (!u8a(a))
433
+ throw new Error('Uint8Array expected');
434
+ r.set(a, pad);
435
+ pad += a.length;
436
+ });
437
+ return r;
438
+ }
439
+ /**
440
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
441
+ */
442
+ function utf8ToBytes(str) {
443
+ if (typeof str !== 'string')
444
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
445
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
446
+ }
447
+ // Bit operations
448
+ /**
449
+ * Calculates amount of bits in a bigint.
450
+ * Same as `n.toString(2).length`
451
+ */
452
+ function bitLen(n) {
453
+ let len;
454
+ for (len = 0; n > _0n$3; n >>= _1n$3, len += 1)
455
+ ;
456
+ return len;
457
+ }
458
+ /**
459
+ * Gets single bit at position.
460
+ * NOTE: first bit position is 0 (same as arrays)
461
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
462
+ */
463
+ function bitGet(n, pos) {
464
+ return (n >> BigInt(pos)) & _1n$3;
465
+ }
466
+ /**
467
+ * Sets single bit at position.
468
+ */
469
+ const bitSet = (n, pos, value) => {
470
+ return n | ((value ? _1n$3 : _0n$3) << BigInt(pos));
471
+ };
472
+ /**
473
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
474
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
475
+ */
476
+ const bitMask = (n) => (_2n$2 << BigInt(n - 1)) - _1n$3;
477
+ // DRBG
478
+ const u8n = (data) => new Uint8Array(data); // creates Uint8Array
479
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
480
+ /**
481
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
482
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
483
+ * @example
484
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
485
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
486
+ */
487
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
488
+ if (typeof hashLen !== 'number' || hashLen < 2)
489
+ throw new Error('hashLen must be a number');
490
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
491
+ throw new Error('qByteLen must be a number');
492
+ if (typeof hmacFn !== 'function')
493
+ throw new Error('hmacFn must be a function');
494
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
495
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
496
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
497
+ let i = 0; // Iterations counter, will throw when over 1000
498
+ const reset = () => {
499
+ v.fill(1);
500
+ k.fill(0);
501
+ i = 0;
502
+ };
503
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
504
+ const reseed = (seed = u8n()) => {
505
+ // HMAC-DRBG reseed() function. Steps D-G
506
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
507
+ v = h(); // v = hmac(k || v)
508
+ if (seed.length === 0)
509
+ return;
510
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
511
+ v = h(); // v = hmac(k || v)
512
+ };
513
+ const gen = () => {
514
+ // HMAC-DRBG generate() function
515
+ if (i++ >= 1000)
516
+ throw new Error('drbg: tried 1000 values');
517
+ let len = 0;
518
+ const out = [];
519
+ while (len < qByteLen) {
520
+ v = h();
521
+ const sl = v.slice();
522
+ out.push(sl);
523
+ len += v.length;
524
+ }
525
+ return concatBytes(...out);
526
+ };
527
+ const genUntil = (seed, pred) => {
528
+ reset();
529
+ reseed(seed); // Steps D-G
530
+ let res = undefined; // Step H: grind until k is in [1..n-1]
531
+ while (!(res = pred(gen())))
532
+ reseed();
533
+ reset();
534
+ return res;
535
+ };
536
+ return genUntil;
537
+ }
538
+ // Validating curves and fields
539
+ const validatorFns = {
540
+ bigint: (val) => typeof val === 'bigint',
541
+ function: (val) => typeof val === 'function',
542
+ boolean: (val) => typeof val === 'boolean',
543
+ string: (val) => typeof val === 'string',
544
+ stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,
545
+ isSafeInteger: (val) => Number.isSafeInteger(val),
546
+ array: (val) => Array.isArray(val),
547
+ field: (val, object) => object.Fp.isValid(val),
548
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
549
+ };
550
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
551
+ function validateObject(object, validators, optValidators = {}) {
552
+ const checkField = (fieldName, type, isOptional) => {
553
+ const checkVal = validatorFns[type];
554
+ if (typeof checkVal !== 'function')
555
+ throw new Error(`Invalid validator "${type}", expected function`);
556
+ const val = object[fieldName];
557
+ if (isOptional && val === undefined)
558
+ return;
559
+ if (!checkVal(val, object)) {
560
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
561
+ }
562
+ };
563
+ for (const [fieldName, type] of Object.entries(validators))
564
+ checkField(fieldName, type, false);
565
+ for (const [fieldName, type] of Object.entries(optValidators))
566
+ checkField(fieldName, type, true);
567
+ return object;
568
+ }
569
+ // validate type tests
570
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
571
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
572
+ // // Should fail type-check
573
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
574
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
575
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
576
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
577
+
578
+ var ut = /*#__PURE__*/Object.freeze({
579
+ __proto__: null,
580
+ bitGet: bitGet,
581
+ bitLen: bitLen,
582
+ bitMask: bitMask,
583
+ bitSet: bitSet,
584
+ bytesToHex: bytesToHex,
585
+ bytesToNumberBE: bytesToNumberBE,
586
+ bytesToNumberLE: bytesToNumberLE,
587
+ concatBytes: concatBytes,
588
+ createHmacDrbg: createHmacDrbg,
589
+ ensureBytes: ensureBytes,
590
+ hexToBytes: hexToBytes,
591
+ hexToNumber: hexToNumber,
592
+ numberToBytesBE: numberToBytesBE,
593
+ numberToBytesLE: numberToBytesLE,
594
+ utf8ToBytes: utf8ToBytes,
595
+ validateObject: validateObject
596
+ });
597
+
598
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
599
+ // Utilities for modular arithmetics and finite fields
600
+ // prettier-ignore
601
+ const _0n$2 = BigInt(0), _1n$2 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3);
602
+ // prettier-ignore
603
+ const _4n$1 = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
604
+ // prettier-ignore
605
+ BigInt(9); BigInt(16);
606
+ // Calculates a modulo b
607
+ function mod(a, b) {
608
+ const result = a % b;
609
+ return result >= _0n$2 ? result : b + result;
610
+ }
611
+ /**
612
+ * Efficiently raise num to power and do modular division.
613
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
614
+ * @example
615
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
616
+ */
617
+ // TODO: use field version && remove
618
+ function pow(num, power, modulo) {
619
+ if (modulo <= _0n$2 || power < _0n$2)
620
+ throw new Error('Expected power/modulo > 0');
621
+ if (modulo === _1n$2)
622
+ return _0n$2;
623
+ let res = _1n$2;
624
+ while (power > _0n$2) {
625
+ if (power & _1n$2)
626
+ res = (res * num) % modulo;
627
+ num = (num * num) % modulo;
628
+ power >>= _1n$2;
629
+ }
630
+ return res;
631
+ }
632
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
633
+ function pow2(x, power, modulo) {
634
+ let res = x;
635
+ while (power-- > _0n$2) {
636
+ res *= res;
637
+ res %= modulo;
638
+ }
639
+ return res;
640
+ }
641
+ // Inverses number over modulo
642
+ function invert(number, modulo) {
643
+ if (number === _0n$2 || modulo <= _0n$2) {
644
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
645
+ }
646
+ // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
647
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
648
+ let a = mod(number, modulo);
649
+ let b = modulo;
650
+ // prettier-ignore
651
+ let x = _0n$2, u = _1n$2;
652
+ while (a !== _0n$2) {
653
+ // JIT applies optimization if those two lines follow each other
654
+ const q = b / a;
655
+ const r = b % a;
656
+ const m = x - u * q;
657
+ // prettier-ignore
658
+ b = a, a = r, x = u, u = m;
659
+ }
660
+ const gcd = b;
661
+ if (gcd !== _1n$2)
662
+ throw new Error('invert: does not exist');
663
+ return mod(x, modulo);
664
+ }
665
+ /**
666
+ * Tonelli-Shanks square root search algorithm.
667
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
668
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
669
+ * Will start an infinite loop if field order P is not prime.
670
+ * @param P field order
671
+ * @returns function that takes field Fp (created from P) and number n
672
+ */
673
+ function tonelliShanks(P) {
674
+ // Legendre constant: used to calculate Legendre symbol (a | p),
675
+ // which denotes the value of a^((p-1)/2) (mod p).
676
+ // (a | p) ≡ 1 if a is a square (mod p)
677
+ // (a | p) ≡ -1 if a is not a square (mod p)
678
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
679
+ const legendreC = (P - _1n$2) / _2n$1;
680
+ let Q, S, Z;
681
+ // Step 1: By factoring out powers of 2 from p - 1,
682
+ // find q and s such that p - 1 = q*(2^s) with q odd
683
+ for (Q = P - _1n$2, S = 0; Q % _2n$1 === _0n$2; Q /= _2n$1, S++)
684
+ ;
685
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
686
+ for (Z = _2n$1; Z < P && pow(Z, legendreC, P) !== P - _1n$2; Z++)
687
+ ;
688
+ // Fast-path
689
+ if (S === 1) {
690
+ const p1div4 = (P + _1n$2) / _4n$1;
691
+ return function tonelliFast(Fp, n) {
692
+ const root = Fp.pow(n, p1div4);
693
+ if (!Fp.eql(Fp.sqr(root), n))
694
+ throw new Error('Cannot find square root');
695
+ return root;
696
+ };
697
+ }
698
+ // Slow-path
699
+ const Q1div2 = (Q + _1n$2) / _2n$1;
700
+ return function tonelliSlow(Fp, n) {
701
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
702
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
703
+ throw new Error('Cannot find square root');
704
+ let r = S;
705
+ // TODO: will fail at Fp2/etc
706
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
707
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
708
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
709
+ while (!Fp.eql(b, Fp.ONE)) {
710
+ if (Fp.eql(b, Fp.ZERO))
711
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
712
+ // Find m such b^(2^m)==1
713
+ let m = 1;
714
+ for (let t2 = Fp.sqr(b); m < r; m++) {
715
+ if (Fp.eql(t2, Fp.ONE))
716
+ break;
717
+ t2 = Fp.sqr(t2); // t2 *= t2
718
+ }
719
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
720
+ const ge = Fp.pow(g, _1n$2 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
721
+ g = Fp.sqr(ge); // g = ge * ge
722
+ x = Fp.mul(x, ge); // x *= ge
723
+ b = Fp.mul(b, g); // b *= g
724
+ r = m;
725
+ }
726
+ return x;
727
+ };
728
+ }
729
+ function FpSqrt(P) {
730
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
731
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
732
+ // P ≡ 3 (mod 4)
733
+ // √n = n^((P+1)/4)
734
+ if (P % _4n$1 === _3n$1) {
735
+ // Not all roots possible!
736
+ // const ORDER =
737
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
738
+ // const NUM = 72057594037927816n;
739
+ const p1div4 = (P + _1n$2) / _4n$1;
740
+ return function sqrt3mod4(Fp, n) {
741
+ const root = Fp.pow(n, p1div4);
742
+ // Throw if root**2 != n
743
+ if (!Fp.eql(Fp.sqr(root), n))
744
+ throw new Error('Cannot find square root');
745
+ return root;
746
+ };
747
+ }
748
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
749
+ if (P % _8n === _5n) {
750
+ const c1 = (P - _5n) / _8n;
751
+ return function sqrt5mod8(Fp, n) {
752
+ const n2 = Fp.mul(n, _2n$1);
753
+ const v = Fp.pow(n2, c1);
754
+ const nv = Fp.mul(n, v);
755
+ const i = Fp.mul(Fp.mul(nv, _2n$1), v);
756
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
757
+ if (!Fp.eql(Fp.sqr(root), n))
758
+ throw new Error('Cannot find square root');
759
+ return root;
760
+ };
761
+ }
762
+ // Other cases: Tonelli-Shanks algorithm
763
+ return tonelliShanks(P);
764
+ }
765
+ // prettier-ignore
766
+ const FIELD_FIELDS = [
767
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
768
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
769
+ 'addN', 'subN', 'mulN', 'sqrN'
770
+ ];
771
+ function validateField(field) {
772
+ const initial = {
773
+ ORDER: 'bigint',
774
+ MASK: 'bigint',
775
+ BYTES: 'isSafeInteger',
776
+ BITS: 'isSafeInteger',
777
+ };
778
+ const opts = FIELD_FIELDS.reduce((map, val) => {
779
+ map[val] = 'function';
780
+ return map;
781
+ }, initial);
782
+ return validateObject(field, opts);
783
+ }
784
+ // Generic field functions
785
+ /**
786
+ * Same as `pow` but for Fp: non-constant-time.
787
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
788
+ */
789
+ function FpPow(f, num, power) {
790
+ // Should have same speed as pow for bigints
791
+ // TODO: benchmark!
792
+ if (power < _0n$2)
793
+ throw new Error('Expected power > 0');
794
+ if (power === _0n$2)
795
+ return f.ONE;
796
+ if (power === _1n$2)
797
+ return num;
798
+ let p = f.ONE;
799
+ let d = num;
800
+ while (power > _0n$2) {
801
+ if (power & _1n$2)
802
+ p = f.mul(p, d);
803
+ d = f.sqr(d);
804
+ power >>= _1n$2;
805
+ }
806
+ return p;
807
+ }
808
+ /**
809
+ * Efficiently invert an array of Field elements.
810
+ * `inv(0)` will return `undefined` here: make sure to throw an error.
811
+ */
812
+ function FpInvertBatch(f, nums) {
813
+ const tmp = new Array(nums.length);
814
+ // Walk from first to last, multiply them by each other MOD p
815
+ const lastMultiplied = nums.reduce((acc, num, i) => {
816
+ if (f.is0(num))
817
+ return acc;
818
+ tmp[i] = acc;
819
+ return f.mul(acc, num);
820
+ }, f.ONE);
821
+ // Invert last element
822
+ const inverted = f.inv(lastMultiplied);
823
+ // Walk from last to first, multiply them by inverted each other MOD p
824
+ nums.reduceRight((acc, num, i) => {
825
+ if (f.is0(num))
826
+ return acc;
827
+ tmp[i] = f.mul(acc, tmp[i]);
828
+ return f.mul(acc, num);
829
+ }, inverted);
830
+ return tmp;
831
+ }
832
+ // CURVE.n lengths
833
+ function nLength(n, nBitLength) {
834
+ // Bit size, byte size of CURVE.n
835
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
836
+ const nByteLength = Math.ceil(_nBitLength / 8);
837
+ return { nBitLength: _nBitLength, nByteLength };
838
+ }
839
+ /**
840
+ * Initializes a finite field over prime. **Non-primes are not supported.**
841
+ * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
842
+ * Major performance optimizations:
843
+ * * a) denormalized operations like mulN instead of mul
844
+ * * b) same object shape: never add or remove keys
845
+ * * c) Object.freeze
846
+ * @param ORDER prime positive bigint
847
+ * @param bitLen how many bits the field consumes
848
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
849
+ * @param redef optional faster redefinitions of sqrt and other methods
850
+ */
851
+ function Field(ORDER, bitLen, isLE = false, redef = {}) {
852
+ if (ORDER <= _0n$2)
853
+ throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
854
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
855
+ if (BYTES > 2048)
856
+ throw new Error('Field lengths over 2048 bytes are not supported');
857
+ const sqrtP = FpSqrt(ORDER);
858
+ const f = Object.freeze({
859
+ ORDER,
860
+ BITS,
861
+ BYTES,
862
+ MASK: bitMask(BITS),
863
+ ZERO: _0n$2,
864
+ ONE: _1n$2,
865
+ create: (num) => mod(num, ORDER),
866
+ isValid: (num) => {
867
+ if (typeof num !== 'bigint')
868
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
869
+ return _0n$2 <= num && num < ORDER; // 0 is valid element, but it's not invertible
870
+ },
871
+ is0: (num) => num === _0n$2,
872
+ isOdd: (num) => (num & _1n$2) === _1n$2,
873
+ neg: (num) => mod(-num, ORDER),
874
+ eql: (lhs, rhs) => lhs === rhs,
875
+ sqr: (num) => mod(num * num, ORDER),
876
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
877
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
878
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
879
+ pow: (num, power) => FpPow(f, num, power),
880
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
881
+ // Same as above, but doesn't normalize
882
+ sqrN: (num) => num * num,
883
+ addN: (lhs, rhs) => lhs + rhs,
884
+ subN: (lhs, rhs) => lhs - rhs,
885
+ mulN: (lhs, rhs) => lhs * rhs,
886
+ inv: (num) => invert(num, ORDER),
887
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
888
+ invertBatch: (lst) => FpInvertBatch(f, lst),
889
+ // TODO: do we really need constant cmov?
890
+ // We don't have const-time bigints anyway, so probably will be not very useful
891
+ cmov: (a, b, c) => (c ? b : a),
892
+ toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
893
+ fromBytes: (bytes) => {
894
+ if (bytes.length !== BYTES)
895
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
896
+ return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
897
+ },
898
+ });
899
+ return Object.freeze(f);
900
+ }
901
+ /**
902
+ * Returns total number of bytes consumed by the field element.
903
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
904
+ * @param fieldOrder number of field elements, usually CURVE.n
905
+ * @returns byte length of field
906
+ */
907
+ function getFieldBytesLength(fieldOrder) {
908
+ if (typeof fieldOrder !== 'bigint')
909
+ throw new Error('field order must be bigint');
910
+ const bitLength = fieldOrder.toString(2).length;
911
+ return Math.ceil(bitLength / 8);
912
+ }
913
+ /**
914
+ * Returns minimal amount of bytes that can be safely reduced
915
+ * by field order.
916
+ * Should be 2^-128 for 128-bit curve such as P256.
917
+ * @param fieldOrder number of field elements, usually CURVE.n
918
+ * @returns byte length of target hash
919
+ */
920
+ function getMinHashLength(fieldOrder) {
921
+ const length = getFieldBytesLength(fieldOrder);
922
+ return length + Math.ceil(length / 2);
923
+ }
924
+ /**
925
+ * "Constant-time" private key generation utility.
926
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
927
+ * and convert them into private scalar, with the modulo bias being negligible.
928
+ * Needs at least 48 bytes of input for 32-byte private key.
929
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
930
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
931
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
932
+ * @param hash hash output from SHA3 or a similar function
933
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
934
+ * @param isLE interpret hash bytes as LE num
935
+ * @returns valid private scalar
936
+ */
937
+ function mapHashToField(key, fieldOrder, isLE = false) {
938
+ const len = key.length;
939
+ const fieldLen = getFieldBytesLength(fieldOrder);
940
+ const minLen = getMinHashLength(fieldOrder);
941
+ // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
942
+ if (len < 16 || len < minLen || len > 1024)
943
+ throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
944
+ const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
945
+ // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
946
+ const reduced = mod(num, fieldOrder - _1n$2) + _1n$2;
947
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
948
+ }
949
+
950
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
951
+ // Abelian group utilities
952
+ const _0n$1 = BigInt(0);
953
+ const _1n$1 = BigInt(1);
954
+ // Elliptic curve multiplication of Point by scalar. Fragile.
955
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
956
+ // Creates precomputation tables for fast multiplication:
957
+ // - private scalar is split by fixed size windows of W bits
958
+ // - every window point is collected from window's table & added to accumulator
959
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
960
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
961
+ // - +1 window is neccessary for wNAF
962
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
963
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
964
+ // windows to be in different memory locations
965
+ function wNAF(c, bits) {
966
+ const constTimeNegate = (condition, item) => {
967
+ const neg = item.negate();
968
+ return condition ? neg : item;
969
+ };
970
+ const opts = (W) => {
971
+ const windows = Math.ceil(bits / W) + 1; // +1, because
972
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
973
+ return { windows, windowSize };
974
+ };
975
+ return {
976
+ constTimeNegate,
977
+ // non-const time multiplication ladder
978
+ unsafeLadder(elm, n) {
979
+ let p = c.ZERO;
980
+ let d = elm;
981
+ while (n > _0n$1) {
982
+ if (n & _1n$1)
983
+ p = p.add(d);
984
+ d = d.double();
985
+ n >>= _1n$1;
986
+ }
987
+ return p;
988
+ },
989
+ /**
990
+ * Creates a wNAF precomputation window. Used for caching.
991
+ * Default window size is set by `utils.precompute()` and is equal to 8.
992
+ * Number of precomputed points depends on the curve size:
993
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
994
+ * - 𝑊 is the window size
995
+ * - 𝑛 is the bitlength of the curve order.
996
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
997
+ * @returns precomputed point tables flattened to a single array
998
+ */
999
+ precomputeWindow(elm, W) {
1000
+ const { windows, windowSize } = opts(W);
1001
+ const points = [];
1002
+ let p = elm;
1003
+ let base = p;
1004
+ for (let window = 0; window < windows; window++) {
1005
+ base = p;
1006
+ points.push(base);
1007
+ // =1, because we skip zero
1008
+ for (let i = 1; i < windowSize; i++) {
1009
+ base = base.add(p);
1010
+ points.push(base);
1011
+ }
1012
+ p = base.double();
1013
+ }
1014
+ return points;
1015
+ },
1016
+ /**
1017
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1018
+ * @param W window size
1019
+ * @param precomputes precomputed tables
1020
+ * @param n scalar (we don't check here, but should be less than curve order)
1021
+ * @returns real and fake (for const-time) points
1022
+ */
1023
+ wNAF(W, precomputes, n) {
1024
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
1025
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
1026
+ const { windows, windowSize } = opts(W);
1027
+ let p = c.ZERO;
1028
+ let f = c.BASE;
1029
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
1030
+ const maxNumber = 2 ** W;
1031
+ const shiftBy = BigInt(W);
1032
+ for (let window = 0; window < windows; window++) {
1033
+ const offset = window * windowSize;
1034
+ // Extract W bits.
1035
+ let wbits = Number(n & mask);
1036
+ // Shift number by W bits.
1037
+ n >>= shiftBy;
1038
+ // If the bits are bigger than max size, we'll split those.
1039
+ // +224 => 256 - 32
1040
+ if (wbits > windowSize) {
1041
+ wbits -= maxNumber;
1042
+ n += _1n$1;
1043
+ }
1044
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1045
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1046
+ // there is negate now: it is possible that negated element from low value
1047
+ // would be the same as high element, which will create carry into next window.
1048
+ // It's not obvious how this can fail, but still worth investigating later.
1049
+ // Check if we're onto Zero point.
1050
+ // Add random point inside current window to f.
1051
+ const offset1 = offset;
1052
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
1053
+ const cond1 = window % 2 !== 0;
1054
+ const cond2 = wbits < 0;
1055
+ if (wbits === 0) {
1056
+ // The most important part for const-time getPublicKey
1057
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1058
+ }
1059
+ else {
1060
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1061
+ }
1062
+ }
1063
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
1064
+ // Even if the variable is still unused, there are some checks which will
1065
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
1066
+ // At this point there is a way to F be infinity-point even if p is not,
1067
+ // which makes it less const-time: around 1 bigint multiply.
1068
+ return { p, f };
1069
+ },
1070
+ wNAFCached(P, precomputesMap, n, transform) {
1071
+ // @ts-ignore
1072
+ const W = P._WINDOW_SIZE || 1;
1073
+ // Calculate precomputes on a first run, reuse them after
1074
+ let comp = precomputesMap.get(P);
1075
+ if (!comp) {
1076
+ comp = this.precomputeWindow(P, W);
1077
+ if (W !== 1) {
1078
+ precomputesMap.set(P, transform(comp));
1079
+ }
1080
+ }
1081
+ return this.wNAF(W, comp, n);
1082
+ },
1083
+ };
1084
+ }
1085
+ function validateBasic(curve) {
1086
+ validateField(curve.Fp);
1087
+ validateObject(curve, {
1088
+ n: 'bigint',
1089
+ h: 'bigint',
1090
+ Gx: 'field',
1091
+ Gy: 'field',
1092
+ }, {
1093
+ nBitLength: 'isSafeInteger',
1094
+ nByteLength: 'isSafeInteger',
1095
+ });
1096
+ // Set defaults
1097
+ return Object.freeze({
1098
+ ...nLength(curve.n, curve.nBitLength),
1099
+ ...curve,
1100
+ ...{ p: curve.Fp.ORDER },
1101
+ });
1102
+ }
1103
+
1104
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1105
+ // Short Weierstrass curve. The formula is: y² = x³ + ax + b
1106
+ function validatePointOpts(curve) {
1107
+ const opts = validateBasic(curve);
1108
+ validateObject(opts, {
1109
+ a: 'field',
1110
+ b: 'field',
1111
+ }, {
1112
+ allowedPrivateKeyLengths: 'array',
1113
+ wrapPrivateKey: 'boolean',
1114
+ isTorsionFree: 'function',
1115
+ clearCofactor: 'function',
1116
+ allowInfinityPoint: 'boolean',
1117
+ fromBytes: 'function',
1118
+ toBytes: 'function',
1119
+ });
1120
+ const { endo, Fp, a } = opts;
1121
+ if (endo) {
1122
+ if (!Fp.eql(a, Fp.ZERO)) {
1123
+ throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
1124
+ }
1125
+ if (typeof endo !== 'object' ||
1126
+ typeof endo.beta !== 'bigint' ||
1127
+ typeof endo.splitScalar !== 'function') {
1128
+ throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
1129
+ }
1130
+ }
1131
+ return Object.freeze({ ...opts });
1132
+ }
1133
+ // ASN.1 DER encoding utilities
1134
+ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
1135
+ const DER = {
1136
+ // asn.1 DER encoding utils
1137
+ Err: class DERErr extends Error {
1138
+ constructor(m = '') {
1139
+ super(m);
1140
+ }
1141
+ },
1142
+ _parseInt(data) {
1143
+ const { Err: E } = DER;
1144
+ if (data.length < 2 || data[0] !== 0x02)
1145
+ throw new E('Invalid signature integer tag');
1146
+ const len = data[1];
1147
+ const res = data.subarray(2, len + 2);
1148
+ if (!len || res.length !== len)
1149
+ throw new E('Invalid signature integer: wrong length');
1150
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
1151
+ // since we always use positive integers here. It must always be empty:
1152
+ // - add zero byte if exists
1153
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
1154
+ if (res[0] & 0b10000000)
1155
+ throw new E('Invalid signature integer: negative');
1156
+ if (res[0] === 0x00 && !(res[1] & 0b10000000))
1157
+ throw new E('Invalid signature integer: unnecessary leading zero');
1158
+ return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
1159
+ },
1160
+ toSig(hex) {
1161
+ // parse DER signature
1162
+ const { Err: E } = DER;
1163
+ const data = typeof hex === 'string' ? h2b(hex) : hex;
1164
+ if (!(data instanceof Uint8Array))
1165
+ throw new Error('ui8a expected');
1166
+ let l = data.length;
1167
+ if (l < 2 || data[0] != 0x30)
1168
+ throw new E('Invalid signature tag');
1169
+ if (data[1] !== l - 2)
1170
+ throw new E('Invalid signature: incorrect length');
1171
+ const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
1172
+ const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
1173
+ if (rBytesLeft.length)
1174
+ throw new E('Invalid signature: left bytes after parsing');
1175
+ return { r, s };
1176
+ },
1177
+ hexFromSig(sig) {
1178
+ // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
1179
+ const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
1180
+ const h = (num) => {
1181
+ const hex = num.toString(16);
1182
+ return hex.length & 1 ? `0${hex}` : hex;
1183
+ };
1184
+ const s = slice(h(sig.s));
1185
+ const r = slice(h(sig.r));
1186
+ const shl = s.length / 2;
1187
+ const rhl = r.length / 2;
1188
+ const sl = h(shl);
1189
+ const rl = h(rhl);
1190
+ return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
1191
+ },
1192
+ };
1193
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
1194
+ // prettier-ignore
1195
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
1196
+ function weierstrassPoints(opts) {
1197
+ const CURVE = validatePointOpts(opts);
1198
+ const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
1199
+ const toBytes = CURVE.toBytes ||
1200
+ ((_c, point, _isCompressed) => {
1201
+ const a = point.toAffine();
1202
+ return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
1203
+ });
1204
+ const fromBytes = CURVE.fromBytes ||
1205
+ ((bytes) => {
1206
+ // const head = bytes[0];
1207
+ const tail = bytes.subarray(1);
1208
+ // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
1209
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1210
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1211
+ return { x, y };
1212
+ });
1213
+ /**
1214
+ * y² = x³ + ax + b: Short weierstrass curve formula
1215
+ * @returns y²
1216
+ */
1217
+ function weierstrassEquation(x) {
1218
+ const { a, b } = CURVE;
1219
+ const x2 = Fp.sqr(x); // x * x
1220
+ const x3 = Fp.mul(x2, x); // x2 * x
1221
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
1222
+ }
1223
+ // Validate whether the passed curve params are valid.
1224
+ // We check if curve equation works for generator point.
1225
+ // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
1226
+ // ProjectivePoint class has not been initialized yet.
1227
+ if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
1228
+ throw new Error('bad generator point: equation left != right');
1229
+ // Valid group elements reside in range 1..n-1
1230
+ function isWithinCurveOrder(num) {
1231
+ return typeof num === 'bigint' && _0n < num && num < CURVE.n;
1232
+ }
1233
+ function assertGE(num) {
1234
+ if (!isWithinCurveOrder(num))
1235
+ throw new Error('Expected valid bigint: 0 < bigint < curve.n');
1236
+ }
1237
+ // Validates if priv key is valid and converts it to bigint.
1238
+ // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
1239
+ function normPrivateKeyToScalar(key) {
1240
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
1241
+ if (lengths && typeof key !== 'bigint') {
1242
+ if (key instanceof Uint8Array)
1243
+ key = bytesToHex(key);
1244
+ // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
1245
+ if (typeof key !== 'string' || !lengths.includes(key.length))
1246
+ throw new Error('Invalid key');
1247
+ key = key.padStart(nByteLength * 2, '0');
1248
+ }
1249
+ let num;
1250
+ try {
1251
+ num =
1252
+ typeof key === 'bigint'
1253
+ ? key
1254
+ : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
1255
+ }
1256
+ catch (error) {
1257
+ throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
1258
+ }
1259
+ if (wrapPrivateKey)
1260
+ num = mod(num, n); // disabled by default, enabled for BLS
1261
+ assertGE(num); // num in range [1..N-1]
1262
+ return num;
1263
+ }
1264
+ const pointPrecomputes = new Map();
1265
+ function assertPrjPoint(other) {
1266
+ if (!(other instanceof Point))
1267
+ throw new Error('ProjectivePoint expected');
1268
+ }
1269
+ /**
1270
+ * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
1271
+ * Default Point works in 2d / affine coordinates: (x, y)
1272
+ * We're doing calculations in projective, because its operations don't require costly inversion.
1273
+ */
1274
+ class Point {
1275
+ constructor(px, py, pz) {
1276
+ this.px = px;
1277
+ this.py = py;
1278
+ this.pz = pz;
1279
+ if (px == null || !Fp.isValid(px))
1280
+ throw new Error('x required');
1281
+ if (py == null || !Fp.isValid(py))
1282
+ throw new Error('y required');
1283
+ if (pz == null || !Fp.isValid(pz))
1284
+ throw new Error('z required');
1285
+ }
1286
+ // Does not validate if the point is on-curve.
1287
+ // Use fromHex instead, or call assertValidity() later.
1288
+ static fromAffine(p) {
1289
+ const { x, y } = p || {};
1290
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1291
+ throw new Error('invalid affine point');
1292
+ if (p instanceof Point)
1293
+ throw new Error('projective point not allowed');
1294
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
1295
+ // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
1296
+ if (is0(x) && is0(y))
1297
+ return Point.ZERO;
1298
+ return new Point(x, y, Fp.ONE);
1299
+ }
1300
+ get x() {
1301
+ return this.toAffine().x;
1302
+ }
1303
+ get y() {
1304
+ return this.toAffine().y;
1305
+ }
1306
+ /**
1307
+ * Takes a bunch of Projective Points but executes only one
1308
+ * inversion on all of them. Inversion is very slow operation,
1309
+ * so this improves performance massively.
1310
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
1311
+ */
1312
+ static normalizeZ(points) {
1313
+ const toInv = Fp.invertBatch(points.map((p) => p.pz));
1314
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1315
+ }
1316
+ /**
1317
+ * Converts hash string or Uint8Array to Point.
1318
+ * @param hex short/long ECDSA hex
1319
+ */
1320
+ static fromHex(hex) {
1321
+ const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));
1322
+ P.assertValidity();
1323
+ return P;
1324
+ }
1325
+ // Multiplies generator point by privateKey.
1326
+ static fromPrivateKey(privateKey) {
1327
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1328
+ }
1329
+ // "Private method", don't use it directly
1330
+ _setWindowSize(windowSize) {
1331
+ this._WINDOW_SIZE = windowSize;
1332
+ pointPrecomputes.delete(this);
1333
+ }
1334
+ // A point on curve is valid if it conforms to equation.
1335
+ assertValidity() {
1336
+ if (this.is0()) {
1337
+ // (0, 1, 0) aka ZERO is invalid in most contexts.
1338
+ // In BLS, ZERO can be serialized, so we allow it.
1339
+ // (0, 0, 0) is wrong representation of ZERO and is always invalid.
1340
+ if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
1341
+ return;
1342
+ throw new Error('bad point: ZERO');
1343
+ }
1344
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
1345
+ const { x, y } = this.toAffine();
1346
+ // Check if x, y are valid field elements
1347
+ if (!Fp.isValid(x) || !Fp.isValid(y))
1348
+ throw new Error('bad point: x or y not FE');
1349
+ const left = Fp.sqr(y); // y²
1350
+ const right = weierstrassEquation(x); // x³ + ax + b
1351
+ if (!Fp.eql(left, right))
1352
+ throw new Error('bad point: equation left != right');
1353
+ if (!this.isTorsionFree())
1354
+ throw new Error('bad point: not in prime-order subgroup');
1355
+ }
1356
+ hasEvenY() {
1357
+ const { y } = this.toAffine();
1358
+ if (Fp.isOdd)
1359
+ return !Fp.isOdd(y);
1360
+ throw new Error("Field doesn't support isOdd");
1361
+ }
1362
+ /**
1363
+ * Compare one point to another.
1364
+ */
1365
+ equals(other) {
1366
+ assertPrjPoint(other);
1367
+ const { px: X1, py: Y1, pz: Z1 } = this;
1368
+ const { px: X2, py: Y2, pz: Z2 } = other;
1369
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1370
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1371
+ return U1 && U2;
1372
+ }
1373
+ /**
1374
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
1375
+ */
1376
+ negate() {
1377
+ return new Point(this.px, Fp.neg(this.py), this.pz);
1378
+ }
1379
+ // Renes-Costello-Batina exception-free doubling formula.
1380
+ // There is 30% faster Jacobian formula, but it is not complete.
1381
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1382
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1383
+ double() {
1384
+ const { a, b } = CURVE;
1385
+ const b3 = Fp.mul(b, _3n);
1386
+ const { px: X1, py: Y1, pz: Z1 } = this;
1387
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
1388
+ let t0 = Fp.mul(X1, X1); // step 1
1389
+ let t1 = Fp.mul(Y1, Y1);
1390
+ let t2 = Fp.mul(Z1, Z1);
1391
+ let t3 = Fp.mul(X1, Y1);
1392
+ t3 = Fp.add(t3, t3); // step 5
1393
+ Z3 = Fp.mul(X1, Z1);
1394
+ Z3 = Fp.add(Z3, Z3);
1395
+ X3 = Fp.mul(a, Z3);
1396
+ Y3 = Fp.mul(b3, t2);
1397
+ Y3 = Fp.add(X3, Y3); // step 10
1398
+ X3 = Fp.sub(t1, Y3);
1399
+ Y3 = Fp.add(t1, Y3);
1400
+ Y3 = Fp.mul(X3, Y3);
1401
+ X3 = Fp.mul(t3, X3);
1402
+ Z3 = Fp.mul(b3, Z3); // step 15
1403
+ t2 = Fp.mul(a, t2);
1404
+ t3 = Fp.sub(t0, t2);
1405
+ t3 = Fp.mul(a, t3);
1406
+ t3 = Fp.add(t3, Z3);
1407
+ Z3 = Fp.add(t0, t0); // step 20
1408
+ t0 = Fp.add(Z3, t0);
1409
+ t0 = Fp.add(t0, t2);
1410
+ t0 = Fp.mul(t0, t3);
1411
+ Y3 = Fp.add(Y3, t0);
1412
+ t2 = Fp.mul(Y1, Z1); // step 25
1413
+ t2 = Fp.add(t2, t2);
1414
+ t0 = Fp.mul(t2, t3);
1415
+ X3 = Fp.sub(X3, t0);
1416
+ Z3 = Fp.mul(t2, t1);
1417
+ Z3 = Fp.add(Z3, Z3); // step 30
1418
+ Z3 = Fp.add(Z3, Z3);
1419
+ return new Point(X3, Y3, Z3);
1420
+ }
1421
+ // Renes-Costello-Batina exception-free addition formula.
1422
+ // There is 30% faster Jacobian formula, but it is not complete.
1423
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1424
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1425
+ add(other) {
1426
+ assertPrjPoint(other);
1427
+ const { px: X1, py: Y1, pz: Z1 } = this;
1428
+ const { px: X2, py: Y2, pz: Z2 } = other;
1429
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
1430
+ const a = CURVE.a;
1431
+ const b3 = Fp.mul(CURVE.b, _3n);
1432
+ let t0 = Fp.mul(X1, X2); // step 1
1433
+ let t1 = Fp.mul(Y1, Y2);
1434
+ let t2 = Fp.mul(Z1, Z2);
1435
+ let t3 = Fp.add(X1, Y1);
1436
+ let t4 = Fp.add(X2, Y2); // step 5
1437
+ t3 = Fp.mul(t3, t4);
1438
+ t4 = Fp.add(t0, t1);
1439
+ t3 = Fp.sub(t3, t4);
1440
+ t4 = Fp.add(X1, Z1);
1441
+ let t5 = Fp.add(X2, Z2); // step 10
1442
+ t4 = Fp.mul(t4, t5);
1443
+ t5 = Fp.add(t0, t2);
1444
+ t4 = Fp.sub(t4, t5);
1445
+ t5 = Fp.add(Y1, Z1);
1446
+ X3 = Fp.add(Y2, Z2); // step 15
1447
+ t5 = Fp.mul(t5, X3);
1448
+ X3 = Fp.add(t1, t2);
1449
+ t5 = Fp.sub(t5, X3);
1450
+ Z3 = Fp.mul(a, t4);
1451
+ X3 = Fp.mul(b3, t2); // step 20
1452
+ Z3 = Fp.add(X3, Z3);
1453
+ X3 = Fp.sub(t1, Z3);
1454
+ Z3 = Fp.add(t1, Z3);
1455
+ Y3 = Fp.mul(X3, Z3);
1456
+ t1 = Fp.add(t0, t0); // step 25
1457
+ t1 = Fp.add(t1, t0);
1458
+ t2 = Fp.mul(a, t2);
1459
+ t4 = Fp.mul(b3, t4);
1460
+ t1 = Fp.add(t1, t2);
1461
+ t2 = Fp.sub(t0, t2); // step 30
1462
+ t2 = Fp.mul(a, t2);
1463
+ t4 = Fp.add(t4, t2);
1464
+ t0 = Fp.mul(t1, t4);
1465
+ Y3 = Fp.add(Y3, t0);
1466
+ t0 = Fp.mul(t5, t4); // step 35
1467
+ X3 = Fp.mul(t3, X3);
1468
+ X3 = Fp.sub(X3, t0);
1469
+ t0 = Fp.mul(t3, t1);
1470
+ Z3 = Fp.mul(t5, Z3);
1471
+ Z3 = Fp.add(Z3, t0); // step 40
1472
+ return new Point(X3, Y3, Z3);
1473
+ }
1474
+ subtract(other) {
1475
+ return this.add(other.negate());
1476
+ }
1477
+ is0() {
1478
+ return this.equals(Point.ZERO);
1479
+ }
1480
+ wNAF(n) {
1481
+ return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
1482
+ const toInv = Fp.invertBatch(comp.map((p) => p.pz));
1483
+ return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1484
+ });
1485
+ }
1486
+ /**
1487
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1488
+ * It's faster, but should only be used when you don't care about
1489
+ * an exposed private key e.g. sig verification, which works over *public* keys.
1490
+ */
1491
+ multiplyUnsafe(n) {
1492
+ const I = Point.ZERO;
1493
+ if (n === _0n)
1494
+ return I;
1495
+ assertGE(n); // Will throw on 0
1496
+ if (n === _1n)
1497
+ return this;
1498
+ const { endo } = CURVE;
1499
+ if (!endo)
1500
+ return wnaf.unsafeLadder(this, n);
1501
+ // Apply endomorphism
1502
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1503
+ let k1p = I;
1504
+ let k2p = I;
1505
+ let d = this;
1506
+ while (k1 > _0n || k2 > _0n) {
1507
+ if (k1 & _1n)
1508
+ k1p = k1p.add(d);
1509
+ if (k2 & _1n)
1510
+ k2p = k2p.add(d);
1511
+ d = d.double();
1512
+ k1 >>= _1n;
1513
+ k2 >>= _1n;
1514
+ }
1515
+ if (k1neg)
1516
+ k1p = k1p.negate();
1517
+ if (k2neg)
1518
+ k2p = k2p.negate();
1519
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1520
+ return k1p.add(k2p);
1521
+ }
1522
+ /**
1523
+ * Constant time multiplication.
1524
+ * Uses wNAF method. Windowed method may be 10% faster,
1525
+ * but takes 2x longer to generate and consumes 2x memory.
1526
+ * Uses precomputes when available.
1527
+ * Uses endomorphism for Koblitz curves.
1528
+ * @param scalar by which the point would be multiplied
1529
+ * @returns New point
1530
+ */
1531
+ multiply(scalar) {
1532
+ assertGE(scalar);
1533
+ let n = scalar;
1534
+ let point, fake; // Fake point is used to const-time mult
1535
+ const { endo } = CURVE;
1536
+ if (endo) {
1537
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1538
+ let { p: k1p, f: f1p } = this.wNAF(k1);
1539
+ let { p: k2p, f: f2p } = this.wNAF(k2);
1540
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
1541
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
1542
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1543
+ point = k1p.add(k2p);
1544
+ fake = f1p.add(f2p);
1545
+ }
1546
+ else {
1547
+ const { p, f } = this.wNAF(n);
1548
+ point = p;
1549
+ fake = f;
1550
+ }
1551
+ // Normalize `z` for both points, but return only real one
1552
+ return Point.normalizeZ([point, fake])[0];
1553
+ }
1554
+ /**
1555
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
1556
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
1557
+ * The trick could be useful if both P and Q are not G (not in our case).
1558
+ * @returns non-zero affine point
1559
+ */
1560
+ multiplyAndAddUnsafe(Q, a, b) {
1561
+ const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
1562
+ const mul = (P, a // Select faster multiply() method
1563
+ ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
1564
+ const sum = mul(this, a).add(mul(Q, b));
1565
+ return sum.is0() ? undefined : sum;
1566
+ }
1567
+ // Converts Projective point to affine (x, y) coordinates.
1568
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1569
+ // (x, y, z) ∋ (x=x/z, y=y/z)
1570
+ toAffine(iz) {
1571
+ const { px: x, py: y, pz: z } = this;
1572
+ const is0 = this.is0();
1573
+ // If invZ was 0, we return zero point. However we still want to execute
1574
+ // all operations, so we replace invZ with a random number, 1.
1575
+ if (iz == null)
1576
+ iz = is0 ? Fp.ONE : Fp.inv(z);
1577
+ const ax = Fp.mul(x, iz);
1578
+ const ay = Fp.mul(y, iz);
1579
+ const zz = Fp.mul(z, iz);
1580
+ if (is0)
1581
+ return { x: Fp.ZERO, y: Fp.ZERO };
1582
+ if (!Fp.eql(zz, Fp.ONE))
1583
+ throw new Error('invZ was invalid');
1584
+ return { x: ax, y: ay };
1585
+ }
1586
+ isTorsionFree() {
1587
+ const { h: cofactor, isTorsionFree } = CURVE;
1588
+ if (cofactor === _1n)
1589
+ return true; // No subgroups, always torsion-free
1590
+ if (isTorsionFree)
1591
+ return isTorsionFree(Point, this);
1592
+ throw new Error('isTorsionFree() has not been declared for the elliptic curve');
1593
+ }
1594
+ clearCofactor() {
1595
+ const { h: cofactor, clearCofactor } = CURVE;
1596
+ if (cofactor === _1n)
1597
+ return this; // Fast-path
1598
+ if (clearCofactor)
1599
+ return clearCofactor(Point, this);
1600
+ return this.multiplyUnsafe(CURVE.h);
1601
+ }
1602
+ toRawBytes(isCompressed = true) {
1603
+ this.assertValidity();
1604
+ return toBytes(Point, this, isCompressed);
1605
+ }
1606
+ toHex(isCompressed = true) {
1607
+ return bytesToHex(this.toRawBytes(isCompressed));
1608
+ }
1609
+ }
1610
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1611
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1612
+ const _bits = CURVE.nBitLength;
1613
+ const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
1614
+ // Validate if generator point is on curve
1615
+ return {
1616
+ CURVE,
1617
+ ProjectivePoint: Point,
1618
+ normPrivateKeyToScalar,
1619
+ weierstrassEquation,
1620
+ isWithinCurveOrder,
1621
+ };
1622
+ }
1623
+ function validateOpts(curve) {
1624
+ const opts = validateBasic(curve);
1625
+ validateObject(opts, {
1626
+ hash: 'hash',
1627
+ hmac: 'function',
1628
+ randomBytes: 'function',
1629
+ }, {
1630
+ bits2int: 'function',
1631
+ bits2int_modN: 'function',
1632
+ lowS: 'boolean',
1633
+ });
1634
+ return Object.freeze({ lowS: true, ...opts });
1635
+ }
1636
+ function weierstrass(curveDef) {
1637
+ const CURVE = validateOpts(curveDef);
1638
+ const { Fp, n: CURVE_ORDER } = CURVE;
1639
+ const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
1640
+ const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
1641
+ function isValidFieldElement(num) {
1642
+ return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
1643
+ }
1644
+ function modN(a) {
1645
+ return mod(a, CURVE_ORDER);
1646
+ }
1647
+ function invN(a) {
1648
+ return invert(a, CURVE_ORDER);
1649
+ }
1650
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
1651
+ ...CURVE,
1652
+ toBytes(_c, point, isCompressed) {
1653
+ const a = point.toAffine();
1654
+ const x = Fp.toBytes(a.x);
1655
+ const cat = concatBytes;
1656
+ if (isCompressed) {
1657
+ return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
1658
+ }
1659
+ else {
1660
+ return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
1661
+ }
1662
+ },
1663
+ fromBytes(bytes) {
1664
+ const len = bytes.length;
1665
+ const head = bytes[0];
1666
+ const tail = bytes.subarray(1);
1667
+ // this.assertValidity() is done inside of fromHex
1668
+ if (len === compressedLen && (head === 0x02 || head === 0x03)) {
1669
+ const x = bytesToNumberBE(tail);
1670
+ if (!isValidFieldElement(x))
1671
+ throw new Error('Point is not on curve');
1672
+ const y2 = weierstrassEquation(x); // y² = x³ + ax + b
1673
+ let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
1674
+ const isYOdd = (y & _1n) === _1n;
1675
+ // ECDSA
1676
+ const isHeadOdd = (head & 1) === 1;
1677
+ if (isHeadOdd !== isYOdd)
1678
+ y = Fp.neg(y);
1679
+ return { x, y };
1680
+ }
1681
+ else if (len === uncompressedLen && head === 0x04) {
1682
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1683
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1684
+ return { x, y };
1685
+ }
1686
+ else {
1687
+ throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
1688
+ }
1689
+ },
1690
+ });
1691
+ const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
1692
+ function isBiggerThanHalfOrder(number) {
1693
+ const HALF = CURVE_ORDER >> _1n;
1694
+ return number > HALF;
1695
+ }
1696
+ function normalizeS(s) {
1697
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1698
+ }
1699
+ // slice bytes num
1700
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1701
+ /**
1702
+ * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
1703
+ */
1704
+ class Signature {
1705
+ constructor(r, s, recovery) {
1706
+ this.r = r;
1707
+ this.s = s;
1708
+ this.recovery = recovery;
1709
+ this.assertValidity();
1710
+ }
1711
+ // pair (bytes of r, bytes of s)
1712
+ static fromCompact(hex) {
1713
+ const l = CURVE.nByteLength;
1714
+ hex = ensureBytes('compactSignature', hex, l * 2);
1715
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1716
+ }
1717
+ // DER encoded ECDSA signature
1718
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
1719
+ static fromDER(hex) {
1720
+ const { r, s } = DER.toSig(ensureBytes('DER', hex));
1721
+ return new Signature(r, s);
1722
+ }
1723
+ assertValidity() {
1724
+ // can use assertGE here
1725
+ if (!isWithinCurveOrder(this.r))
1726
+ throw new Error('r must be 0 < r < CURVE.n');
1727
+ if (!isWithinCurveOrder(this.s))
1728
+ throw new Error('s must be 0 < s < CURVE.n');
1729
+ }
1730
+ addRecoveryBit(recovery) {
1731
+ return new Signature(this.r, this.s, recovery);
1732
+ }
1733
+ recoverPublicKey(msgHash) {
1734
+ const { r, s, recovery: rec } = this;
1735
+ const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
1736
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
1737
+ throw new Error('recovery id invalid');
1738
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1739
+ if (radj >= Fp.ORDER)
1740
+ throw new Error('recovery id 2 or 3 invalid');
1741
+ const prefix = (rec & 1) === 0 ? '02' : '03';
1742
+ const R = Point.fromHex(prefix + numToNByteStr(radj));
1743
+ const ir = invN(radj); // r^-1
1744
+ const u1 = modN(-h * ir); // -hr^-1
1745
+ const u2 = modN(s * ir); // sr^-1
1746
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
1747
+ if (!Q)
1748
+ throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
1749
+ Q.assertValidity();
1750
+ return Q;
1751
+ }
1752
+ // Signatures should be low-s, to prevent malleability.
1753
+ hasHighS() {
1754
+ return isBiggerThanHalfOrder(this.s);
1755
+ }
1756
+ normalizeS() {
1757
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1758
+ }
1759
+ // DER-encoded
1760
+ toDERRawBytes() {
1761
+ return hexToBytes(this.toDERHex());
1762
+ }
1763
+ toDERHex() {
1764
+ return DER.hexFromSig({ r: this.r, s: this.s });
1765
+ }
1766
+ // padded bytes of r, then padded bytes of s
1767
+ toCompactRawBytes() {
1768
+ return hexToBytes(this.toCompactHex());
1769
+ }
1770
+ toCompactHex() {
1771
+ return numToNByteStr(this.r) + numToNByteStr(this.s);
1772
+ }
1773
+ }
1774
+ const utils = {
1775
+ isValidPrivateKey(privateKey) {
1776
+ try {
1777
+ normPrivateKeyToScalar(privateKey);
1778
+ return true;
1779
+ }
1780
+ catch (error) {
1781
+ return false;
1782
+ }
1783
+ },
1784
+ normPrivateKeyToScalar: normPrivateKeyToScalar,
1785
+ /**
1786
+ * Produces cryptographically secure private key from random of size
1787
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
1788
+ */
1789
+ randomPrivateKey: () => {
1790
+ const length = getMinHashLength(CURVE.n);
1791
+ return mapHashToField(CURVE.randomBytes(length), CURVE.n);
1792
+ },
1793
+ /**
1794
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
1795
+ * Allows to massively speed-up `point.multiply(scalar)`.
1796
+ * @returns cached point
1797
+ * @example
1798
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
1799
+ * fast.multiply(privKey); // much faster ECDH now
1800
+ */
1801
+ precompute(windowSize = 8, point = Point.BASE) {
1802
+ point._setWindowSize(windowSize);
1803
+ point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
1804
+ return point;
1805
+ },
1806
+ };
1807
+ /**
1808
+ * Computes public key for a private key. Checks for validity of the private key.
1809
+ * @param privateKey private key
1810
+ * @param isCompressed whether to return compact (default), or full key
1811
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
1812
+ */
1813
+ function getPublicKey(privateKey, isCompressed = true) {
1814
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
1815
+ }
1816
+ /**
1817
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
1818
+ */
1819
+ function isProbPub(item) {
1820
+ const arr = item instanceof Uint8Array;
1821
+ const str = typeof item === 'string';
1822
+ const len = (arr || str) && item.length;
1823
+ if (arr)
1824
+ return len === compressedLen || len === uncompressedLen;
1825
+ if (str)
1826
+ return len === 2 * compressedLen || len === 2 * uncompressedLen;
1827
+ if (item instanceof Point)
1828
+ return true;
1829
+ return false;
1830
+ }
1831
+ /**
1832
+ * ECDH (Elliptic Curve Diffie Hellman).
1833
+ * Computes shared public key from private key and public key.
1834
+ * Checks: 1) private key validity 2) shared key is on-curve.
1835
+ * Does NOT hash the result.
1836
+ * @param privateA private key
1837
+ * @param publicB different public key
1838
+ * @param isCompressed whether to return compact (default), or full key
1839
+ * @returns shared public key
1840
+ */
1841
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
1842
+ if (isProbPub(privateA))
1843
+ throw new Error('first arg must be private key');
1844
+ if (!isProbPub(publicB))
1845
+ throw new Error('second arg must be public key');
1846
+ const b = Point.fromHex(publicB); // check for being on-curve
1847
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1848
+ }
1849
+ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
1850
+ // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
1851
+ // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
1852
+ // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
1853
+ const bits2int = CURVE.bits2int ||
1854
+ function (bytes) {
1855
+ // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
1856
+ // for some cases, since bytes.length * 8 is not actual bitLength.
1857
+ const num = bytesToNumberBE(bytes); // check for == u8 done here
1858
+ const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
1859
+ return delta > 0 ? num >> BigInt(delta) : num;
1860
+ };
1861
+ const bits2int_modN = CURVE.bits2int_modN ||
1862
+ function (bytes) {
1863
+ return modN(bits2int(bytes)); // can't use bytesToNumberBE here
1864
+ };
1865
+ // NOTE: pads output with zero as per spec
1866
+ const ORDER_MASK = bitMask(CURVE.nBitLength);
1867
+ /**
1868
+ * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
1869
+ */
1870
+ function int2octets(num) {
1871
+ if (typeof num !== 'bigint')
1872
+ throw new Error('bigint expected');
1873
+ if (!(_0n <= num && num < ORDER_MASK))
1874
+ throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
1875
+ // works with order, can have different size than numToField!
1876
+ return numberToBytesBE(num, CURVE.nByteLength);
1877
+ }
1878
+ // Steps A, D of RFC6979 3.2
1879
+ // Creates RFC6979 seed; converts msg/privKey to numbers.
1880
+ // Used only in sign, not in verify.
1881
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
1882
+ // Also it can be bigger for P224 + SHA256
1883
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
1884
+ if (['recovered', 'canonical'].some((k) => k in opts))
1885
+ throw new Error('sign() legacy options not supported');
1886
+ const { hash, randomBytes } = CURVE;
1887
+ let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
1888
+ if (lowS == null)
1889
+ lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
1890
+ msgHash = ensureBytes('msgHash', msgHash);
1891
+ if (prehash)
1892
+ msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
1893
+ // We can't later call bits2octets, since nested bits2int is broken for curves
1894
+ // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
1895
+ // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
1896
+ const h1int = bits2int_modN(msgHash);
1897
+ const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
1898
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1899
+ // extraEntropy. RFC6979 3.6: additional k' (optional).
1900
+ if (ent != null) {
1901
+ // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
1902
+ const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
1903
+ seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
1904
+ }
1905
+ const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
1906
+ const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
1907
+ // Converts signature params into point w r/s, checks result for validity.
1908
+ function k2sig(kBytes) {
1909
+ // RFC 6979 Section 3.2, step 3: k = bits2int(T)
1910
+ const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
1911
+ if (!isWithinCurveOrder(k))
1912
+ return; // Important: all mod() calls here must be done over N
1913
+ const ik = invN(k); // k^-1 mod n
1914
+ const q = Point.BASE.multiply(k).toAffine(); // q = Gk
1915
+ const r = modN(q.x); // r = q.x mod n
1916
+ if (r === _0n)
1917
+ return;
1918
+ // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
1919
+ // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
1920
+ // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
1921
+ const s = modN(ik * modN(m + r * d)); // Not using blinding here
1922
+ if (s === _0n)
1923
+ return;
1924
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
1925
+ let normS = s;
1926
+ if (lowS && isBiggerThanHalfOrder(s)) {
1927
+ normS = normalizeS(s); // if lowS was passed, ensure s is always
1928
+ recovery ^= 1; // // in the bottom half of N
1929
+ }
1930
+ return new Signature(r, normS, recovery); // use normS, not s
1931
+ }
1932
+ return { seed, k2sig };
1933
+ }
1934
+ const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
1935
+ const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
1936
+ /**
1937
+ * Signs message hash with a private key.
1938
+ * ```
1939
+ * sign(m, d, k) where
1940
+ * (x, y) = G × k
1941
+ * r = x mod n
1942
+ * s = (m + dr)/k mod n
1943
+ * ```
1944
+ * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
1945
+ * @param privKey private key
1946
+ * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
1947
+ * @returns signature with recovery param
1948
+ */
1949
+ function sign(msgHash, privKey, opts = defaultSigOpts) {
1950
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
1951
+ const C = CURVE;
1952
+ const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
1953
+ return drbg(seed, k2sig); // Steps B, C, D, E, F, G
1954
+ }
1955
+ // Enable precomputes. Slows down first publicKey computation by 20ms.
1956
+ Point.BASE._setWindowSize(8);
1957
+ // utils.precompute(8, ProjectivePoint.BASE)
1958
+ /**
1959
+ * Verifies a signature against message hash and public key.
1960
+ * Rejects lowS signatures by default: to override,
1961
+ * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
1962
+ *
1963
+ * ```
1964
+ * verify(r, s, h, P) where
1965
+ * U1 = hs^-1 mod n
1966
+ * U2 = rs^-1 mod n
1967
+ * R = U1⋅G - U2⋅P
1968
+ * mod(R.x, n) == r
1969
+ * ```
1970
+ */
1971
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
1972
+ const sg = signature;
1973
+ msgHash = ensureBytes('msgHash', msgHash);
1974
+ publicKey = ensureBytes('publicKey', publicKey);
1975
+ if ('strict' in opts)
1976
+ throw new Error('options.strict was renamed to lowS');
1977
+ const { lowS, prehash } = opts;
1978
+ let _sig = undefined;
1979
+ let P;
1980
+ try {
1981
+ if (typeof sg === 'string' || sg instanceof Uint8Array) {
1982
+ // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
1983
+ // Since DER can also be 2*nByteLength bytes, we check for it first.
1984
+ try {
1985
+ _sig = Signature.fromDER(sg);
1986
+ }
1987
+ catch (derError) {
1988
+ if (!(derError instanceof DER.Err))
1989
+ throw derError;
1990
+ _sig = Signature.fromCompact(sg);
1991
+ }
1992
+ }
1993
+ else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
1994
+ const { r, s } = sg;
1995
+ _sig = new Signature(r, s);
1996
+ }
1997
+ else {
1998
+ throw new Error('PARSE');
1999
+ }
2000
+ P = Point.fromHex(publicKey);
2001
+ }
2002
+ catch (error) {
2003
+ if (error.message === 'PARSE')
2004
+ throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
2005
+ return false;
2006
+ }
2007
+ if (lowS && _sig.hasHighS())
2008
+ return false;
2009
+ if (prehash)
2010
+ msgHash = CURVE.hash(msgHash);
2011
+ const { r, s } = _sig;
2012
+ const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
2013
+ const is = invN(s); // s^-1
2014
+ const u1 = modN(h * is); // u1 = hs^-1 mod n
2015
+ const u2 = modN(r * is); // u2 = rs^-1 mod n
2016
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
2017
+ if (!R)
2018
+ return false;
2019
+ const v = modN(R.x);
2020
+ return v === r;
2021
+ }
2022
+ return {
2023
+ CURVE,
2024
+ getPublicKey,
2025
+ getSharedSecret,
2026
+ sign,
2027
+ verify,
2028
+ ProjectivePoint: Point,
2029
+ Signature,
2030
+ utils,
2031
+ };
2032
+ }
2033
+ /**
2034
+ * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
2035
+ * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
2036
+ * b = True and y = sqrt(u / v) if (u / v) is square in F, and
2037
+ * b = False and y = sqrt(Z * (u / v)) otherwise.
2038
+ * @param Fp
2039
+ * @param Z
2040
+ * @returns
2041
+ */
2042
+ function SWUFpSqrtRatio(Fp, Z) {
2043
+ // Generic implementation
2044
+ const q = Fp.ORDER;
2045
+ let l = _0n;
2046
+ for (let o = q - _1n; o % _2n === _0n; o /= _2n)
2047
+ l += _1n;
2048
+ const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
2049
+ // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
2050
+ // 2n ** c1 == 2n << (c1-1)
2051
+ const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
2052
+ const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
2053
+ const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
2054
+ const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
2055
+ const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
2056
+ const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic
2057
+ const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
2058
+ const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
2059
+ let sqrtRatio = (u, v) => {
2060
+ let tv1 = c6; // 1. tv1 = c6
2061
+ let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
2062
+ let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
2063
+ tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
2064
+ let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
2065
+ tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
2066
+ tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
2067
+ tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
2068
+ tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
2069
+ let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
2070
+ tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
2071
+ let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
2072
+ tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
2073
+ tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
2074
+ tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
2075
+ tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
2076
+ // 17. for i in (c1, c1 - 1, ..., 2):
2077
+ for (let i = c1; i > _1n; i--) {
2078
+ let tv5 = i - _2n; // 18. tv5 = i - 2
2079
+ tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5
2080
+ let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
2081
+ const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
2082
+ tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
2083
+ tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
2084
+ tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
2085
+ tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
2086
+ tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
2087
+ }
2088
+ return { isValid: isQR, value: tv3 };
2089
+ };
2090
+ if (Fp.ORDER % _4n === _3n) {
2091
+ // sqrt_ratio_3mod4(u, v)
2092
+ const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
2093
+ const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
2094
+ sqrtRatio = (u, v) => {
2095
+ let tv1 = Fp.sqr(v); // 1. tv1 = v^2
2096
+ const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
2097
+ tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
2098
+ let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
2099
+ y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
2100
+ const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
2101
+ const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
2102
+ const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
2103
+ let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
2104
+ return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
2105
+ };
2106
+ }
2107
+ // No curves uses that
2108
+ // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
2109
+ return sqrtRatio;
2110
+ }
2111
+ /**
2112
+ * Simplified Shallue-van de Woestijne-Ulas Method
2113
+ * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
2114
+ */
2115
+ function mapToCurveSimpleSWU(Fp, opts) {
2116
+ validateField(Fp);
2117
+ if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
2118
+ throw new Error('mapToCurveSimpleSWU: invalid opts');
2119
+ const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
2120
+ if (!Fp.isOdd)
2121
+ throw new Error('Fp.isOdd is not implemented!');
2122
+ // Input: u, an element of F.
2123
+ // Output: (x, y), a point on E.
2124
+ return (u) => {
2125
+ // prettier-ignore
2126
+ let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
2127
+ tv1 = Fp.sqr(u); // 1. tv1 = u^2
2128
+ tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1
2129
+ tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
2130
+ tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
2131
+ tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
2132
+ tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3
2133
+ tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
2134
+ tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4
2135
+ tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
2136
+ tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
2137
+ tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6
2138
+ tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
2139
+ tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
2140
+ tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
2141
+ tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6
2142
+ tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
2143
+ x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
2144
+ const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
2145
+ y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
2146
+ y = Fp.mul(y, value); // 20. y = y * y1
2147
+ x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
2148
+ y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
2149
+ const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
2150
+ y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
2151
+ x = Fp.div(x, tv4); // 25. x = x / tv4
2152
+ return { x, y };
2153
+ };
2154
+ }
2155
+
2156
+ export { bytesToHex as A, numberToBytesBE as B, Field as F, Hash as H, concatBytes as a, bytes as b, concatBytes$1 as c, bytesToNumberBE as d, exists as e, bitLen as f, weierstrassPoints as g, hash as h, getMinHashLength as i, mapHashToField as j, bitGet as k, ensureBytes as l, mod as m, number as n, FpInvertBatch as o, pow2 as p, FpPow as q, randomBytes as r, sha256 as s, toBytes as t, utf8ToBytes as u, validateObject as v, weierstrass as w, bitMask as x, mapToCurveSimpleSWU as y, bitSet as z };