@arcblock/did-noise 0.0.0-stage → 1.30.25

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/LICENSE +13 -0
  2. package/esm/chacha20poly1305.d.mts +18 -0
  3. package/esm/chacha20poly1305.mjs +152 -0
  4. package/esm/chain-node-mesh.d.mts +79 -0
  5. package/esm/chain-node-mesh.mjs +187 -0
  6. package/esm/http-transport.d.mts +72 -0
  7. package/esm/http-transport.mjs +216 -0
  8. package/esm/index.d.mts +6 -0
  9. package/esm/index.mjs +7 -0
  10. package/esm/mesh-tunnel.d.mts +165 -0
  11. package/esm/mesh-tunnel.mjs +350 -0
  12. package/esm/noise-session.d.mts +157 -0
  13. package/esm/noise-session.mjs +491 -0
  14. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  15. package/lib/_vendor/@noble/curves/abstract/curve.cjs +338 -0
  16. package/lib/_vendor/@noble/curves/abstract/edwards.cjs +542 -0
  17. package/lib/_vendor/@noble/curves/abstract/hash-to-curve.cjs +72 -0
  18. package/lib/_vendor/@noble/curves/abstract/modular.cjs +557 -0
  19. package/lib/_vendor/@noble/curves/abstract/montgomery.cjs +149 -0
  20. package/lib/_vendor/@noble/curves/ed25519.cjs +302 -0
  21. package/lib/_vendor/@noble/curves/utils.cjs +436 -0
  22. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  23. package/lib/_vendor/@noble/hashes/_blake.cjs +300 -0
  24. package/lib/_vendor/@noble/hashes/_md.cjs +194 -0
  25. package/lib/_vendor/@noble/hashes/_u64.cjs +60 -0
  26. package/lib/_vendor/@noble/hashes/blake2.cjs +291 -0
  27. package/lib/_vendor/@noble/hashes/hkdf.cjs +104 -0
  28. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  29. package/lib/_vendor/@noble/hashes/sha2.cjs +417 -0
  30. package/lib/_vendor/@noble/hashes/utils.cjs +422 -0
  31. package/lib/chacha20poly1305.cjs +153 -0
  32. package/lib/chacha20poly1305.d.cts +18 -0
  33. package/lib/chain-node-mesh.cjs +189 -0
  34. package/lib/chain-node-mesh.d.cts +79 -0
  35. package/lib/http-transport.cjs +219 -0
  36. package/lib/http-transport.d.cts +72 -0
  37. package/lib/index.cjs +31 -0
  38. package/lib/index.d.cts +6 -0
  39. package/lib/mesh-tunnel.cjs +354 -0
  40. package/lib/mesh-tunnel.d.cts +165 -0
  41. package/lib/noise-session.cjs +503 -0
  42. package/lib/noise-session.d.cts +157 -0
  43. package/package.json +80 -4
  44. package/README.md +0 -3
@@ -0,0 +1,557 @@
1
+ const require_utils = require('../utils.cjs');
2
+
3
+ //#region ../../node_modules/@noble/curves/abstract/modular.js
4
+ /**
5
+ * Utils for modular division and fields.
6
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
7
+ * There is no division: it is replaced by modular multiplicative inverse.
8
+ * @module
9
+ */
10
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);
12
+ const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
13
+ const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
14
+ const _16n = /* @__PURE__ */ BigInt(16);
15
+ /**
16
+ * @param a - Dividend value.
17
+ * @param b - Positive modulus.
18
+ * @returns Reduced value in `[0, b)` only when `b` is positive.
19
+ * @throws If the modulus is not positive. {@link Error}
20
+ * @example
21
+ * Normalize a bigint into one field residue.
22
+ *
23
+ * ```ts
24
+ * mod(-1n, 5n);
25
+ * ```
26
+ */
27
+ function mod(a, b) {
28
+ if (b <= _0n) throw new Error("mod: expected positive modulus, got " + b);
29
+ const result = a % b;
30
+ return result >= _0n ? result : b + result;
31
+ }
32
+ /**
33
+ * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
34
+ * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
35
+ * modulus; the `power===0` fast path intentionally returns the input unchanged.
36
+ * @param x - Base value.
37
+ * @param power - Number of squarings.
38
+ * @param modulo - Reduction modulus.
39
+ * @returns Repeated-squaring result.
40
+ * @throws If the exponent is negative. {@link Error}
41
+ * @example
42
+ * Apply repeated squaring inside one field.
43
+ *
44
+ * ```ts
45
+ * pow2(3n, 2n, 11n);
46
+ * ```
47
+ */
48
+ function pow2(x, power, modulo) {
49
+ if (power < _0n) throw new Error("pow2: expected non-negative exponent, got " + power);
50
+ let res = x;
51
+ while (power-- > _0n) {
52
+ res *= res;
53
+ res %= modulo;
54
+ }
55
+ return res;
56
+ }
57
+ /**
58
+ * Inverses number over modulo.
59
+ * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
60
+ * @param number - Value to invert.
61
+ * @param modulo - Positive modulus.
62
+ * @returns Multiplicative inverse.
63
+ * @throws If the modulus is invalid or the inverse does not exist. {@link Error}
64
+ * @example
65
+ * Compute one modular inverse with the extended Euclidean algorithm.
66
+ *
67
+ * ```ts
68
+ * invert(3n, 11n);
69
+ * ```
70
+ */
71
+ function invert(number, modulo) {
72
+ if (number === _0n) throw new Error("invert: expected non-zero number");
73
+ if (modulo <= _0n) throw new Error("invert: expected positive modulus, got " + modulo);
74
+ let a = mod(number, modulo);
75
+ let b = modulo;
76
+ let x = _0n, y = _1n, u = _1n, v = _0n;
77
+ while (a !== _0n) {
78
+ const q = b / a;
79
+ const r = b - a * q;
80
+ const m = x - u * q;
81
+ const n = y - v * q;
82
+ b = a, a = r, x = u, y = v, u = m, v = n;
83
+ }
84
+ if (b !== _1n) throw new Error("invert: does not exist");
85
+ return mod(x, modulo);
86
+ }
87
+ function assertIsSquare(Fp, root, n) {
88
+ const F = Fp;
89
+ if (!F.eql(F.sqr(root), n)) throw new Error("Cannot find square root");
90
+ }
91
+ function sqrt3mod4(Fp, n) {
92
+ const F = Fp;
93
+ const p1div4 = (F.ORDER + _1n) / _4n;
94
+ const root = F.pow(n, p1div4);
95
+ assertIsSquare(F, root, n);
96
+ return root;
97
+ }
98
+ function sqrt5mod8(Fp, n) {
99
+ const F = Fp;
100
+ const p5div8 = (F.ORDER - _5n) / _8n;
101
+ const n2 = F.mul(n, _2n);
102
+ const v = F.pow(n2, p5div8);
103
+ const nv = F.mul(n, v);
104
+ const i = F.mul(F.mul(nv, _2n), v);
105
+ const root = F.mul(nv, F.sub(i, F.ONE));
106
+ assertIsSquare(F, root, n);
107
+ return root;
108
+ }
109
+ function sqrt9mod16(P) {
110
+ const Fp_ = Field(P);
111
+ const tn = tonelliShanks(P);
112
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
113
+ const c2 = tn(Fp_, c1);
114
+ const c3 = tn(Fp_, Fp_.neg(c1));
115
+ const c4 = (P + _7n) / _16n;
116
+ return ((Fp, n) => {
117
+ const F = Fp;
118
+ let tv1 = F.pow(n, c4);
119
+ let tv2 = F.mul(tv1, c1);
120
+ const tv3 = F.mul(tv1, c2);
121
+ const tv4 = F.mul(tv1, c3);
122
+ const e1 = F.eql(F.sqr(tv2), n);
123
+ const e2 = F.eql(F.sqr(tv3), n);
124
+ tv1 = F.cmov(tv1, tv2, e1);
125
+ tv2 = F.cmov(tv4, tv3, e2);
126
+ const e3 = F.eql(F.sqr(tv2), n);
127
+ const root = F.cmov(tv1, tv2, e3);
128
+ assertIsSquare(F, root, n);
129
+ return root;
130
+ });
131
+ }
132
+ /**
133
+ * Tonelli-Shanks square root search algorithm.
134
+ * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
135
+ * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
136
+ * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
137
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
138
+ * @param P - field order
139
+ * @returns function that takes field Fp (created from P) and number n
140
+ * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
141
+ * @example
142
+ * Construct a square-root helper for primes that need Tonelli-Shanks.
143
+ *
144
+ * ```ts
145
+ * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
146
+ * const Fp = Field(17n);
147
+ * const sqrt = tonelliShanks(17n)(Fp, 4n);
148
+ * ```
149
+ */
150
+ function tonelliShanks(P) {
151
+ if (P < _3n) throw new Error("sqrt is not defined for small field");
152
+ let Q = P - _1n;
153
+ let S = 0;
154
+ while (Q % _2n === _0n) {
155
+ Q /= _2n;
156
+ S++;
157
+ }
158
+ let Z = _2n;
159
+ const _Fp = Field(P);
160
+ while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
161
+ if (S === 1) return sqrt3mod4;
162
+ let cc = _Fp.pow(Z, Q);
163
+ const Q1div2 = (Q + _1n) / _2n;
164
+ return function tonelliSlow(Fp, n) {
165
+ const F = Fp;
166
+ if (F.is0(n)) return n;
167
+ if (FpLegendre(F, n) !== 1) throw new Error("Cannot find square root");
168
+ let M = S;
169
+ let c = F.mul(F.ONE, cc);
170
+ let t = F.pow(n, Q);
171
+ let R = F.pow(n, Q1div2);
172
+ while (!F.eql(t, F.ONE)) {
173
+ if (F.is0(t)) return F.ZERO;
174
+ let i = 1;
175
+ let t_tmp = F.sqr(t);
176
+ while (!F.eql(t_tmp, F.ONE)) {
177
+ i++;
178
+ t_tmp = F.sqr(t_tmp);
179
+ if (i === M) throw new Error("Cannot find square root");
180
+ }
181
+ const exponent = _1n << BigInt(M - i - 1);
182
+ const b = F.pow(c, exponent);
183
+ M = i;
184
+ c = F.sqr(b);
185
+ t = F.mul(t, c);
186
+ R = F.mul(R, b);
187
+ }
188
+ return R;
189
+ };
190
+ }
191
+ /**
192
+ * Square root for a finite field. Will try optimized versions first:
193
+ *
194
+ * 1. P ≡ 3 (mod 4)
195
+ * 2. P ≡ 5 (mod 8)
196
+ * 3. P ≡ 9 (mod 16)
197
+ * 4. Tonelli-Shanks algorithm
198
+ *
199
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
200
+ * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
201
+ * (used for hash-to-curve).
202
+ * @param P - Field order.
203
+ * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
204
+ * behavior and this selector assumes prime-field-style integer moduli.
205
+ * @throws If the field is unsupported or the square root does not exist. {@link Error}
206
+ * @example
207
+ * Choose the square-root helper appropriate for one field modulus.
208
+ *
209
+ * ```ts
210
+ * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
211
+ * const Fp = Field(17n);
212
+ * const sqrt = FpSqrt(17n)(Fp, 4n);
213
+ * ```
214
+ */
215
+ function FpSqrt(P) {
216
+ if (P % _4n === _3n) return sqrt3mod4;
217
+ if (P % _8n === _5n) return sqrt5mod8;
218
+ if (P % _16n === _9n) return sqrt9mod16(P);
219
+ return tonelliShanks(P);
220
+ }
221
+ /**
222
+ * @param num - Value to inspect.
223
+ * @param modulo - Field modulus.
224
+ * @returns `true` when the least-significant little-endian bit is set.
225
+ * @throws If the modulus is invalid for `mod(...)`. {@link Error}
226
+ * @example
227
+ * Inspect the low bit used by little-endian sign conventions.
228
+ *
229
+ * ```ts
230
+ * isNegativeLE(3n, 11n);
231
+ * ```
232
+ */
233
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
234
+ const FIELD_FIELDS = [
235
+ "create",
236
+ "isValid",
237
+ "is0",
238
+ "neg",
239
+ "inv",
240
+ "sqrt",
241
+ "sqr",
242
+ "eql",
243
+ "add",
244
+ "sub",
245
+ "mul",
246
+ "pow",
247
+ "div",
248
+ "addN",
249
+ "subN",
250
+ "mulN",
251
+ "sqrN"
252
+ ];
253
+ /**
254
+ * @param field - Field implementation.
255
+ * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
256
+ * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
257
+ * field-specific extras beyond positive `BYTES` / `BITS`.
258
+ * @throws If the field shape or numeric metadata are invalid. {@link Error}
259
+ * @example
260
+ * Check that a field implementation exposes the operations curve code expects.
261
+ *
262
+ * ```ts
263
+ * import { Field, validateField } from '@noble/curves/abstract/modular.js';
264
+ * const Fp = validateField(Field(17n));
265
+ * ```
266
+ */
267
+ function validateField(field) {
268
+ require_utils.validateObject(field, FIELD_FIELDS.reduce((map, val) => {
269
+ map[val] = "function";
270
+ return map;
271
+ }, {
272
+ ORDER: "bigint",
273
+ BYTES: "number",
274
+ BITS: "number"
275
+ }));
276
+ require_utils.asafenumber(field.BYTES, "BYTES");
277
+ require_utils.asafenumber(field.BITS, "BITS");
278
+ if (field.BYTES < 1 || field.BITS < 1) throw new Error("invalid field: expected BYTES/BITS > 0");
279
+ if (field.ORDER <= _1n) throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
280
+ return field;
281
+ }
282
+ /**
283
+ * Same as `pow` but for Fp: non-constant-time.
284
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
285
+ * @param Fp - Field implementation.
286
+ * @param num - Base value.
287
+ * @param power - Exponent value.
288
+ * @returns Powered field element.
289
+ * @throws If the exponent is negative. {@link Error}
290
+ * @example
291
+ * Raise one field element to a public exponent.
292
+ *
293
+ * ```ts
294
+ * import { Field, FpPow } from '@noble/curves/abstract/modular.js';
295
+ * const Fp = Field(17n);
296
+ * const x = FpPow(Fp, 3n, 5n);
297
+ * ```
298
+ */
299
+ function FpPow(Fp, num, power) {
300
+ const F = Fp;
301
+ if (power < _0n) throw new Error("invalid exponent, negatives unsupported");
302
+ if (power === _0n) return F.ONE;
303
+ if (power === _1n) return num;
304
+ let p = F.ONE;
305
+ let d = num;
306
+ while (power > _0n) {
307
+ if (power & _1n) p = F.mul(p, d);
308
+ d = F.sqr(d);
309
+ power >>= _1n;
310
+ }
311
+ return p;
312
+ }
313
+ /**
314
+ * Efficiently invert an array of Field elements.
315
+ * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
316
+ * @param Fp - Field implementation.
317
+ * @param nums - Values to invert.
318
+ * @param passZero - map 0 to 0 (instead of undefined)
319
+ * @returns Inverted values.
320
+ * @example
321
+ * Invert several field elements with one shared inversion.
322
+ *
323
+ * ```ts
324
+ * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
325
+ * const Fp = Field(17n);
326
+ * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
327
+ * ```
328
+ */
329
+ function FpInvertBatch(Fp, nums, passZero = false) {
330
+ const F = Fp;
331
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
332
+ const multipliedAcc = nums.reduce((acc, num, i) => {
333
+ if (F.is0(num)) return acc;
334
+ inverted[i] = acc;
335
+ return F.mul(acc, num);
336
+ }, F.ONE);
337
+ const invertedAcc = F.inv(multipliedAcc);
338
+ nums.reduceRight((acc, num, i) => {
339
+ if (F.is0(num)) return acc;
340
+ inverted[i] = F.mul(acc, inverted[i]);
341
+ return F.mul(acc, num);
342
+ }, invertedAcc);
343
+ return inverted;
344
+ }
345
+ /**
346
+ * Legendre symbol.
347
+ * Legendre constant is used to calculate Legendre symbol (a | p)
348
+ * which denotes the value of a^((p-1)/2) (mod p).
349
+ *
350
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
351
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
352
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
353
+ * @param Fp - Field implementation.
354
+ * @param n - Value to inspect.
355
+ * @returns Legendre symbol.
356
+ * @throws If the field returns an invalid Legendre symbol value. {@link Error}
357
+ * @example
358
+ * Compute the Legendre symbol of one field element.
359
+ *
360
+ * ```ts
361
+ * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
362
+ * const Fp = Field(17n);
363
+ * const symbol = FpLegendre(Fp, 4n);
364
+ * ```
365
+ */
366
+ function FpLegendre(Fp, n) {
367
+ const F = Fp;
368
+ const p1mod2 = (F.ORDER - _1n) / _2n;
369
+ const powered = F.pow(n, p1mod2);
370
+ const yes = F.eql(powered, F.ONE);
371
+ const zero = F.eql(powered, F.ZERO);
372
+ const no = F.eql(powered, F.neg(F.ONE));
373
+ if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
374
+ return yes ? 1 : zero ? 0 : -1;
375
+ }
376
+ /**
377
+ * @param n - Curve order. Callers are expected to pass a positive order.
378
+ * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
379
+ * value when overriding the derived bit length.
380
+ * @returns Byte and bit lengths.
381
+ * @throws If the order or cached bit length is invalid. {@link Error}
382
+ * @example
383
+ * Measure the encoding sizes needed for one modulus.
384
+ *
385
+ * ```ts
386
+ * nLength(255n);
387
+ * ```
388
+ */
389
+ function nLength(n, nBitLength) {
390
+ if (nBitLength !== void 0) require_utils.anumber(nBitLength);
391
+ if (n <= _0n) throw new Error("invalid n length: expected positive n, got " + n);
392
+ if (nBitLength !== void 0 && nBitLength < 1) throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
393
+ const bits = require_utils.bitLen(n);
394
+ if (nBitLength !== void 0 && nBitLength < bits) throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
395
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
396
+ return {
397
+ nBitLength: _nBitLength,
398
+ nByteLength: Math.ceil(_nBitLength / 8)
399
+ };
400
+ }
401
+ const FIELD_SQRT = /* @__PURE__ */ new WeakMap();
402
+ var _Field = class {
403
+ ORDER;
404
+ BITS;
405
+ BYTES;
406
+ isLE;
407
+ ZERO = _0n;
408
+ ONE = _1n;
409
+ _lengths;
410
+ _mod;
411
+ constructor(ORDER, opts = {}) {
412
+ if (ORDER <= _1n) throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
413
+ let _nbitLength = void 0;
414
+ this.isLE = false;
415
+ if (opts != null && typeof opts === "object") {
416
+ if (typeof opts.BITS === "number") _nbitLength = opts.BITS;
417
+ if (typeof opts.sqrt === "function") Object.defineProperty(this, "sqrt", {
418
+ value: opts.sqrt,
419
+ enumerable: true
420
+ });
421
+ if (typeof opts.isLE === "boolean") this.isLE = opts.isLE;
422
+ if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());
423
+ if (typeof opts.modFromBytes === "boolean") this._mod = opts.modFromBytes;
424
+ }
425
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
426
+ if (nByteLength > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
427
+ this.ORDER = ORDER;
428
+ this.BITS = nBitLength;
429
+ this.BYTES = nByteLength;
430
+ Object.freeze(this);
431
+ }
432
+ create(num) {
433
+ return mod(num, this.ORDER);
434
+ }
435
+ isValid(num) {
436
+ if (typeof num !== "bigint") throw new TypeError("invalid field element: expected bigint, got " + typeof num);
437
+ return _0n <= num && num < this.ORDER;
438
+ }
439
+ is0(num) {
440
+ return num === _0n;
441
+ }
442
+ isValidNot0(num) {
443
+ return !this.is0(num) && this.isValid(num);
444
+ }
445
+ isOdd(num) {
446
+ return (num & _1n) === _1n;
447
+ }
448
+ neg(num) {
449
+ return mod(-num, this.ORDER);
450
+ }
451
+ eql(lhs, rhs) {
452
+ return lhs === rhs;
453
+ }
454
+ sqr(num) {
455
+ return mod(num * num, this.ORDER);
456
+ }
457
+ add(lhs, rhs) {
458
+ return mod(lhs + rhs, this.ORDER);
459
+ }
460
+ sub(lhs, rhs) {
461
+ return mod(lhs - rhs, this.ORDER);
462
+ }
463
+ mul(lhs, rhs) {
464
+ return mod(lhs * rhs, this.ORDER);
465
+ }
466
+ pow(num, power) {
467
+ return FpPow(this, num, power);
468
+ }
469
+ div(lhs, rhs) {
470
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
471
+ }
472
+ sqrN(num) {
473
+ return num * num;
474
+ }
475
+ addN(lhs, rhs) {
476
+ return lhs + rhs;
477
+ }
478
+ subN(lhs, rhs) {
479
+ return lhs - rhs;
480
+ }
481
+ mulN(lhs, rhs) {
482
+ return lhs * rhs;
483
+ }
484
+ inv(num) {
485
+ return invert(num, this.ORDER);
486
+ }
487
+ sqrt(num) {
488
+ let sqrt = FIELD_SQRT.get(this);
489
+ if (!sqrt) FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
490
+ return sqrt(this, num);
491
+ }
492
+ toBytes(num) {
493
+ return this.isLE ? require_utils.numberToBytesLE(num, this.BYTES) : require_utils.numberToBytesBE(num, this.BYTES);
494
+ }
495
+ fromBytes(bytes, skipValidation = false) {
496
+ require_utils.abytes(bytes);
497
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
498
+ if (allowedLengths) {
499
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
500
+ const padded = new Uint8Array(BYTES);
501
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
502
+ bytes = padded;
503
+ }
504
+ if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
505
+ let scalar = isLE ? require_utils.bytesToNumberLE(bytes) : require_utils.bytesToNumberBE(bytes);
506
+ if (modFromBytes) scalar = mod(scalar, ORDER);
507
+ if (!skipValidation) {
508
+ if (!this.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
509
+ }
510
+ return scalar;
511
+ }
512
+ invertBatch(lst) {
513
+ return FpInvertBatch(this, lst);
514
+ }
515
+ cmov(a, b, condition) {
516
+ require_utils.abool(condition, "condition");
517
+ return condition ? b : a;
518
+ }
519
+ };
520
+ Object.freeze(_Field.prototype);
521
+ /**
522
+ * Creates a finite field. Major performance optimizations:
523
+ * * 1. Denormalized operations like mulN instead of mul.
524
+ * * 2. Identical object shape: never add or remove keys.
525
+ * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
526
+ * Fragile: always run a benchmark on a change.
527
+ * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
528
+ * all elements for performance and protocol-flexibility reasons; callers are responsible for
529
+ * supplying valid elements when they need canonical field behavior.
530
+ * This is low-level code, please make sure you know what you're doing.
531
+ *
532
+ * Note about field properties:
533
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
534
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
535
+ *
536
+ * @param ORDER - field order, probably prime, or could be composite
537
+ * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
538
+ * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
539
+ * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
540
+ * @example
541
+ * Construct one prime field with optional overrides.
542
+ *
543
+ * ```ts
544
+ * Field(11n);
545
+ * ```
546
+ */
547
+ function Field(ORDER, opts = {}) {
548
+ return new _Field(ORDER, opts);
549
+ }
550
+
551
+ //#endregion
552
+ exports.Field = Field;
553
+ exports.FpInvertBatch = FpInvertBatch;
554
+ exports.isNegativeLE = isNegativeLE;
555
+ exports.mod = mod;
556
+ exports.pow2 = pow2;
557
+ exports.validateField = validateField;
@@ -0,0 +1,149 @@
1
+ const require_utils = require('../utils.cjs');
2
+ const require_modular = require('./modular.cjs');
3
+ const require_curve = require('./curve.cjs');
4
+
5
+ //#region ../../node_modules/@noble/curves/abstract/montgomery.js
6
+ /**
7
+ * Montgomery curve methods. It's not really whole montgomery curve,
8
+ * just bunch of very specific methods for X25519 / X448 from
9
+ * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
10
+ * @module
11
+ */
12
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13
+ const _0n = BigInt(0);
14
+ const _1n = BigInt(1);
15
+ const _2n = BigInt(2);
16
+ function validateOpts(curve) {
17
+ require_utils.validateObject(curve, {
18
+ P: "bigint",
19
+ type: "string",
20
+ adjustScalarBytes: "function",
21
+ powPminus2: "function"
22
+ }, { randomBytes: "function" });
23
+ return Object.freeze({ ...curve });
24
+ }
25
+ /**
26
+ * @param curveDef - Montgomery curve definition.
27
+ * @returns ECDH helper namespace.
28
+ * @throws If the curve definition or derived shared point is invalid. {@link Error}
29
+ * @example
30
+ * Perform one X25519 key exchange through the generic Montgomery helper.
31
+ *
32
+ * ```ts
33
+ * import { x25519 } from '@noble/curves/ed25519.js';
34
+ * const alice = x25519.keygen();
35
+ * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);
36
+ * ```
37
+ */
38
+ function montgomery(curveDef) {
39
+ const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = validateOpts(curveDef);
40
+ const is25519 = type === "x25519";
41
+ if (!is25519 && type !== "x448") throw new Error("invalid type");
42
+ const randomBytes_ = rand === void 0 ? require_utils.randomBytes : rand;
43
+ const montgomeryBits = is25519 ? 255 : 448;
44
+ const fieldLen = is25519 ? 32 : 56;
45
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
46
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
47
+ const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);
48
+ const maxScalar = minScalar + (is25519 ? BigInt(8) * _2n ** BigInt(251) - _1n : BigInt(4) * _2n ** BigInt(445) - _1n) + _1n;
49
+ const modP = (n) => require_modular.mod(n, P);
50
+ const GuBytes = encodeU(Gu);
51
+ function encodeU(u) {
52
+ return require_utils.numberToBytesLE(modP(u), fieldLen);
53
+ }
54
+ function decodeU(u) {
55
+ const _u = require_utils.copyBytes(require_utils.abytes(u, fieldLen, "uCoordinate"));
56
+ if (is25519) _u[31] &= 127;
57
+ return modP(require_utils.bytesToNumberLE(_u));
58
+ }
59
+ function decodeScalar(scalar) {
60
+ return require_utils.bytesToNumberLE(adjustScalarBytes(require_utils.copyBytes(require_utils.abytes(scalar, fieldLen, "scalar"))));
61
+ }
62
+ function scalarMult(scalar, u) {
63
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
64
+ if (pu === _0n) throw new Error("invalid private or public key received");
65
+ return encodeU(pu);
66
+ }
67
+ function scalarMultBase(scalar) {
68
+ return scalarMult(scalar, GuBytes);
69
+ }
70
+ const getPublicKey = scalarMultBase;
71
+ const getSharedSecret = scalarMult;
72
+ function cswap(swap, x_2, x_3) {
73
+ const dummy = modP(swap * (x_2 - x_3));
74
+ x_2 = modP(x_2 - dummy);
75
+ x_3 = modP(x_3 + dummy);
76
+ return {
77
+ x_2,
78
+ x_3
79
+ };
80
+ }
81
+ /**
82
+ * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.
83
+ * @param pointU - decoded Montgomery u coordinate for the selected curve
84
+ * @param scalar - decoded clamped scalar by which the point is multiplied
85
+ * @returns resulting Montgomery u coordinate for the selected curve
86
+ */
87
+ function montgomeryLadder(u, scalar) {
88
+ require_utils.aInRange("u", u, _0n, P);
89
+ require_utils.aInRange("scalar", scalar, minScalar, maxScalar);
90
+ const k = scalar;
91
+ const x_1 = u;
92
+ let x_2 = _1n;
93
+ let z_2 = _0n;
94
+ let x_3 = u;
95
+ let z_3 = _1n;
96
+ let swap = _0n;
97
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
98
+ const k_t = k >> t & _1n;
99
+ swap ^= k_t;
100
+ ({x_2, x_3} = cswap(swap, x_2, x_3));
101
+ ({x_2: z_2, x_3: z_3} = cswap(swap, z_2, z_3));
102
+ swap = k_t;
103
+ const A = x_2 + z_2;
104
+ const AA = modP(A * A);
105
+ const B = x_2 - z_2;
106
+ const BB = modP(B * B);
107
+ const E = AA - BB;
108
+ const C = x_3 + z_3;
109
+ const DA = modP((x_3 - z_3) * A);
110
+ const CB = modP(C * B);
111
+ const dacb = DA + CB;
112
+ const da_cb = DA - CB;
113
+ x_3 = modP(dacb * dacb);
114
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
115
+ x_2 = modP(AA * BB);
116
+ z_2 = modP(E * (AA + modP(a24 * E)));
117
+ }
118
+ ({x_2, x_3} = cswap(swap, x_2, x_3));
119
+ ({x_2: z_2, x_3: z_3} = cswap(swap, z_2, z_3));
120
+ const z2 = powPminus2(z_2);
121
+ return modP(x_2 * z2);
122
+ }
123
+ const lengths = {
124
+ secretKey: fieldLen,
125
+ publicKey: fieldLen,
126
+ seed: fieldLen
127
+ };
128
+ const randomSecretKey = (seed) => {
129
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
130
+ require_utils.abytes(seed, lengths.seed, "seed");
131
+ return seed;
132
+ };
133
+ const utils = { randomSecretKey };
134
+ Object.freeze(lengths);
135
+ Object.freeze(utils);
136
+ return Object.freeze({
137
+ keygen: require_curve.createKeygen(randomSecretKey, getPublicKey),
138
+ getSharedSecret,
139
+ getPublicKey,
140
+ scalarMult,
141
+ scalarMultBase,
142
+ utils,
143
+ GuBytes: GuBytes.slice(),
144
+ lengths
145
+ });
146
+ }
147
+
148
+ //#endregion
149
+ exports.montgomery = montgomery;