@decryption/curves 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/abstract/bls.d.ts +410 -0
  4. package/abstract/bls.js +433 -0
  5. package/abstract/curve.d.ts +441 -0
  6. package/abstract/curve.js +622 -0
  7. package/abstract/edwards.d.ts +319 -0
  8. package/abstract/edwards.js +697 -0
  9. package/abstract/fft.d.ts +438 -0
  10. package/abstract/fft.js +580 -0
  11. package/abstract/frost.d.ts +292 -0
  12. package/abstract/frost.js +705 -0
  13. package/abstract/hash-to-curve.d.ts +238 -0
  14. package/abstract/hash-to-curve.js +353 -0
  15. package/abstract/modular.d.ts +550 -0
  16. package/abstract/modular.js +872 -0
  17. package/abstract/montgomery.d.ts +95 -0
  18. package/abstract/montgomery.js +180 -0
  19. package/abstract/oprf.d.ts +354 -0
  20. package/abstract/oprf.js +358 -0
  21. package/abstract/poseidon.d.ts +198 -0
  22. package/abstract/poseidon.js +471 -0
  23. package/abstract/tower.d.ts +213 -0
  24. package/abstract/tower.js +963 -0
  25. package/abstract/weierstrass.d.ts +587 -0
  26. package/abstract/weierstrass.js +1421 -0
  27. package/bls12-381.d.ts +23 -0
  28. package/bls12-381.js +680 -0
  29. package/bn254.d.ts +74 -0
  30. package/bn254.js +248 -0
  31. package/ed25519.d.ts +211 -0
  32. package/ed25519.js +626 -0
  33. package/ed448.d.ts +184 -0
  34. package/ed448.js +596 -0
  35. package/esm/abstract/bls.js +429 -0
  36. package/esm/abstract/curve.js +610 -0
  37. package/esm/abstract/edwards.js +691 -0
  38. package/esm/abstract/fft.js +567 -0
  39. package/esm/abstract/frost.js +702 -0
  40. package/esm/abstract/hash-to-curve.js +345 -0
  41. package/esm/abstract/modular.js +849 -0
  42. package/esm/abstract/montgomery.js +177 -0
  43. package/esm/abstract/oprf.js +355 -0
  44. package/esm/abstract/poseidon.js +462 -0
  45. package/esm/abstract/tower.js +925 -0
  46. package/esm/abstract/weierstrass.js +1411 -0
  47. package/esm/bls12-381.js +677 -0
  48. package/esm/bn254.js +244 -0
  49. package/esm/ed25519.js +622 -0
  50. package/esm/ed448.js +593 -0
  51. package/esm/index.js +38 -0
  52. package/esm/misc.js +211 -0
  53. package/esm/nist.js +266 -0
  54. package/esm/secp256k1.js +465 -0
  55. package/esm/utils.js +597 -0
  56. package/esm/webcrypto.js +362 -0
  57. package/index.d.ts +0 -0
  58. package/index.js +38 -0
  59. package/misc.d.ts +113 -0
  60. package/misc.js +216 -0
  61. package/nist.d.ts +136 -0
  62. package/nist.js +269 -0
  63. package/package.json +46 -0
  64. package/secp256k1.d.ts +152 -0
  65. package/secp256k1.js +468 -0
  66. package/utils.d.ts +535 -0
  67. package/utils.js +626 -0
  68. package/webcrypto.d.ts +240 -0
  69. package/webcrypto.js +365 -0
@@ -0,0 +1,238 @@
1
+ /**
2
+ * hash-to-curve from RFC 9380.
3
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
4
+ * https://www.rfc-editor.org/rfc/rfc9380
5
+ * @module
6
+ */
7
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8
+ import type { CHash, TArg, TRet } from '../utils';
9
+ import type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve';
10
+ import { type IField } from './modular';
11
+ /** ASCII domain-separation tag or raw bytes. */
12
+ export type AsciiOrBytes = string | Uint8Array;
13
+ type H2CDefaults = {
14
+ DST: AsciiOrBytes;
15
+ expand: 'xmd' | 'xof';
16
+ hash: CHash;
17
+ p: bigint;
18
+ m: number;
19
+ k: number;
20
+ encodeDST?: AsciiOrBytes;
21
+ };
22
+ /**
23
+ * * `DST` is a domain separation tag, defined in section 2.2.5
24
+ * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
25
+ * * `m` is extension degree (1 for prime fields)
26
+ * * `k` is the target security target in bits (e.g. 128), from section 5.1
27
+ * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
28
+ * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
29
+ */
30
+ export type H2COpts = {
31
+ /** Domain separation tag. */
32
+ DST: AsciiOrBytes;
33
+ /** Expander family used by RFC 9380. */
34
+ expand: 'xmd' | 'xof';
35
+ /** Hash or XOF implementation used by the expander. */
36
+ hash: CHash;
37
+ /** Base-field characteristic. */
38
+ p: bigint;
39
+ /** Extension degree (`1` for prime fields). */
40
+ m: number;
41
+ /** Target security level in bits. */
42
+ k: number;
43
+ };
44
+ /** Hash-only subset of RFC 9380 options used by per-call overrides. */
45
+ export type H2CHashOpts = {
46
+ /** Expander family used by RFC 9380. */
47
+ expand: 'xmd' | 'xof';
48
+ /** Hash or XOF implementation used by the expander. */
49
+ hash: CHash;
50
+ };
51
+ /**
52
+ * Map one hash-to-field output tuple onto affine curve coordinates.
53
+ * Implementations receive the validated scalar tuple by reference for performance and MUST treat it
54
+ * as read-only. Callers that need scratch space should copy before mutating.
55
+ * @param scalar - Field-element tuple produced by `hash_to_field`.
56
+ * @returns Affine point before subgroup clearing.
57
+ */
58
+ export type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;
59
+ /** Per-call override for the domain-separation tag. */
60
+ export type H2CDSTOpts = {
61
+ /** Domain-separation tag override. */
62
+ DST: AsciiOrBytes;
63
+ };
64
+ /** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */
65
+ export type H2CHasherBase<PC extends PC_ANY> = {
66
+ /**
67
+ * Hash arbitrary bytes to one curve point.
68
+ * @param msg - Input message bytes.
69
+ * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
70
+ * @returns Curve point after hash-to-curve.
71
+ */
72
+ hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
73
+ /**
74
+ * Hash arbitrary bytes to one scalar.
75
+ * @param msg - Input message bytes.
76
+ * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
77
+ * @returns Scalar reduced into the target field.
78
+ */
79
+ hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;
80
+ /**
81
+ * Derive one curve point from non-uniform bytes without the random-oracle
82
+ * guarantees of `hashToCurve`.
83
+ * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve
84
+ * path instead of the random-oracle construction.
85
+ */
86
+ deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
87
+ /** Point constructor for the target curve. */
88
+ Point: PC;
89
+ };
90
+ /**
91
+ * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.
92
+ *
93
+ * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)
94
+ * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)
95
+ * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)
96
+ */
97
+ export type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {
98
+ /**
99
+ * Encode non-uniform bytes to one curve point.
100
+ * @param msg - Input message bytes.
101
+ * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
102
+ * @returns Curve point after encode-to-curve.
103
+ */
104
+ encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
105
+ /** Deterministic map from `hash_to_field` tuples into affine coordinates. */
106
+ mapToCurve: MapToCurve<PC_F<PC>>;
107
+ /** Default RFC 9380 options captured by this hasher bundle. */
108
+ defaults: H2CDefaults;
109
+ };
110
+ /**
111
+ * Produces a uniformly random byte string using a cryptographic hash
112
+ * function H that outputs b bits.
113
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
114
+ * @param msg - Input message.
115
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
116
+ * oversize-hashes DST when needed.
117
+ * @param lenInBytes - Output length.
118
+ * @param H - Hash function.
119
+ * @returns Uniform byte string.
120
+ * @throws If the message, DST, hash, or output length is invalid. {@link Error}
121
+ * @example
122
+ * Expand one message into uniform bytes with the XMD construction.
123
+ *
124
+ * ```ts
125
+ * import { expand_message_xmd } from './hash-to-curve';
126
+ * import { sha256 } from '@decryption/hashes/sha2';
127
+ * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
128
+ * ```
129
+ */
130
+ export declare function expand_message_xmd(msg: TArg<Uint8Array>, DST: TArg<AsciiOrBytes>, lenInBytes: number, H: TArg<CHash>): TRet<Uint8Array>;
131
+ /**
132
+ * Produces a uniformly random byte string using an extendable-output function (XOF) H.
133
+ * 1. The collision resistance of H MUST be at least k bits.
134
+ * 2. H MUST be an XOF that has been proved indifferentiable from
135
+ * a random oracle under a reasonable cryptographic assumption.
136
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
137
+ * @param msg - Input message.
138
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
139
+ * oversize-hashes DST when needed.
140
+ * @param lenInBytes - Output length.
141
+ * @param k - Target security level.
142
+ * @param H - XOF hash function.
143
+ * @returns Uniform byte string.
144
+ * @throws If the message, DST, XOF, or output length is invalid. {@link Error}
145
+ * @example
146
+ * Expand one message into uniform bytes with the XOF construction.
147
+ *
148
+ * ```ts
149
+ * import { expand_message_xof } from './hash-to-curve';
150
+ * import { shake256 } from '@decryption/hashes/sha3';
151
+ * const uniform = expand_message_xof(
152
+ * new TextEncoder().encode('hello noble'),
153
+ * 'DST',
154
+ * 32,
155
+ * 128,
156
+ * shake256
157
+ * );
158
+ * ```
159
+ */
160
+ export declare function expand_message_xof(msg: TArg<Uint8Array>, DST: TArg<AsciiOrBytes>, lenInBytes: number, k: number, H: TArg<CHash>): TRet<Uint8Array>;
161
+ /**
162
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
163
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
164
+ * @param msg - Input message bytes.
165
+ * @param count - Number of field elements to derive. Must be `>= 1`.
166
+ * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
167
+ * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
168
+ * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
169
+ * @example
170
+ * Hash one message into field elements before mapping it onto a curve.
171
+ *
172
+ * ```ts
173
+ * import { hash_to_field } from './hash-to-curve';
174
+ * import { sha256 } from '@decryption/hashes/sha2';
175
+ * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
176
+ * DST: 'DST',
177
+ * p: 17n,
178
+ * m: 1,
179
+ * k: 128,
180
+ * expand: 'xmd',
181
+ * hash: sha256,
182
+ * });
183
+ * ```
184
+ */
185
+ export declare function hash_to_field(msg: TArg<Uint8Array>, count: number, options: TArg<H2COpts>): bigint[][];
186
+ type XY<T> = (x: T, y: T) => {
187
+ x: T;
188
+ y: T;
189
+ };
190
+ type XYRatio<T> = [T[], T[], T[], T[]];
191
+ /**
192
+ * @param field - Field implementation.
193
+ * @param map - Isogeny coefficients.
194
+ * @returns Isogeny mapping helper.
195
+ * @example
196
+ * Build one rational isogeny map, then apply it to affine x/y coordinates.
197
+ *
198
+ * ```ts
199
+ * import { isogenyMap } from './hash-to-curve';
200
+ * import { Field } from './modular';
201
+ * const Fp = Field(17n);
202
+ * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);
203
+ * const point = iso(3n, 5n);
204
+ * ```
205
+ */
206
+ export declare function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T>;
207
+ export declare const _DST_scalar: "HashToScalar-";
208
+ /**
209
+ * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
210
+ * @param Point - Point constructor.
211
+ * @param mapToCurve - Map-to-curve function.
212
+ * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
213
+ * the shared defaults bundle for the returned helpers.
214
+ * @returns Hash-to-curve helper namespace.
215
+ * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
216
+ * @example
217
+ * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
218
+ *
219
+ * ```ts
220
+ * import { createHasher } from './hash-to-curve';
221
+ * import { p256 } from '../nist';
222
+ * import { sha256 } from '@decryption/hashes/sha2';
223
+ * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
224
+ * DST: 'P256_XMD:SHA-256_SSWU_RO_',
225
+ * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
226
+ * p: p256.Point.Fp.ORDER,
227
+ * m: 1,
228
+ * k: 128,
229
+ * expand: 'xmd',
230
+ * hash: sha256,
231
+ * });
232
+ * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
233
+ * ```
234
+ */
235
+ export declare function createHasher<PC extends PC_ANY>(Point: PC, mapToCurve: MapToCurve<PC_F<PC>>, defaults: TArg<H2COpts & {
236
+ encodeDST?: AsciiOrBytes;
237
+ }>): H2CHasher<PC>;
238
+ export {};
@@ -0,0 +1,353 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._DST_scalar = void 0;
4
+ exports.expand_message_xmd = expand_message_xmd;
5
+ exports.expand_message_xof = expand_message_xof;
6
+ exports.hash_to_field = hash_to_field;
7
+ exports.isogenyMap = isogenyMap;
8
+ exports.createHasher = createHasher;
9
+ const utils_1 = require("../utils");
10
+ const modular_1 = require("./modular");
11
+ // Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
12
+ const os2ip = utils_1.bytesToNumberBE;
13
+ // Integer to Octet Stream (numberToBytesBE).
14
+ function i2osp(value, length) {
15
+ (0, utils_1.asafenumber)(value);
16
+ (0, utils_1.asafenumber)(length);
17
+ // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should
18
+ // use bigint + numberToBytesBE instead of routing large widths through this small helper.
19
+ if (length < 0 || length > 4)
20
+ throw new Error('invalid I2OSP length: ' + length);
21
+ if (value < 0 || value > 2 ** (8 * length) - 1)
22
+ throw new Error('invalid I2OSP input: ' + value);
23
+ const res = Array.from({ length }).fill(0);
24
+ for (let i = length - 1; i >= 0; i--) {
25
+ res[i] = value & 0xff;
26
+ value >>>= 8;
27
+ }
28
+ return new Uint8Array(res);
29
+ }
30
+ // RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.
31
+ function strxor(a, b) {
32
+ const arr = new Uint8Array(a.length);
33
+ for (let i = 0; i < a.length; i++) {
34
+ arr[i] = a[i] ^ b[i];
35
+ }
36
+ return arr;
37
+ }
38
+ // User can always use utf8 if they want, by passing Uint8Array.
39
+ // If string is passed, we treat it as ASCII: other formats are likely a mistake.
40
+ function normDST(DST) {
41
+ if (!(0, utils_1.isBytes)(DST) && typeof DST !== 'string')
42
+ throw new Error('DST must be Uint8Array or ascii string');
43
+ const dst = typeof DST === 'string' ? (0, utils_1.asciiToBytes)(DST) : DST;
44
+ // RFC 9380 §3.1 requirement 2: tags "MUST have nonzero length".
45
+ if (dst.length === 0)
46
+ throw new Error('DST must be non-empty');
47
+ return dst;
48
+ }
49
+ /**
50
+ * Produces a uniformly random byte string using a cryptographic hash
51
+ * function H that outputs b bits.
52
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
53
+ * @param msg - Input message.
54
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
55
+ * oversize-hashes DST when needed.
56
+ * @param lenInBytes - Output length.
57
+ * @param H - Hash function.
58
+ * @returns Uniform byte string.
59
+ * @throws If the message, DST, hash, or output length is invalid. {@link Error}
60
+ * @example
61
+ * Expand one message into uniform bytes with the XMD construction.
62
+ *
63
+ * ```ts
64
+ * import { expand_message_xmd } from './hash-to-curve';
65
+ * import { sha256 } from '@decryption/hashes/sha2';
66
+ * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
67
+ * ```
68
+ */
69
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
70
+ (0, utils_1.abytes)(msg);
71
+ (0, utils_1.asafenumber)(lenInBytes);
72
+ DST = normDST(DST);
73
+ // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
74
+ if (DST.length > 255)
75
+ DST = H((0, utils_1.concatBytes)((0, utils_1.asciiToBytes)('H2C-OVERSIZE-DST-'), DST));
76
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
77
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
78
+ if (lenInBytes > 65535 || ell > 255)
79
+ throw new Error('expand_message_xmd: invalid lenInBytes');
80
+ const DST_prime = (0, utils_1.concatBytes)(DST, i2osp(DST.length, 1));
81
+ const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)
82
+ const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
83
+ const b = new Array(ell);
84
+ const b_0 = H((0, utils_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
85
+ b[0] = H((0, utils_1.concatBytes)(b_0, i2osp(1, 1), DST_prime));
86
+ // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`
87
+ // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`
88
+ // by reaching `I2OSP(256, 1)`.
89
+ for (let i = 1; i < ell; i++) {
90
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
91
+ b[i] = H((0, utils_1.concatBytes)(...args));
92
+ }
93
+ const pseudo_random_bytes = (0, utils_1.concatBytes)(...b);
94
+ return pseudo_random_bytes.slice(0, lenInBytes);
95
+ }
96
+ /**
97
+ * Produces a uniformly random byte string using an extendable-output function (XOF) H.
98
+ * 1. The collision resistance of H MUST be at least k bits.
99
+ * 2. H MUST be an XOF that has been proved indifferentiable from
100
+ * a random oracle under a reasonable cryptographic assumption.
101
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
102
+ * @param msg - Input message.
103
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
104
+ * oversize-hashes DST when needed.
105
+ * @param lenInBytes - Output length.
106
+ * @param k - Target security level.
107
+ * @param H - XOF hash function.
108
+ * @returns Uniform byte string.
109
+ * @throws If the message, DST, XOF, or output length is invalid. {@link Error}
110
+ * @example
111
+ * Expand one message into uniform bytes with the XOF construction.
112
+ *
113
+ * ```ts
114
+ * import { expand_message_xof } from './hash-to-curve';
115
+ * import { shake256 } from '@decryption/hashes/sha3';
116
+ * const uniform = expand_message_xof(
117
+ * new TextEncoder().encode('hello noble'),
118
+ * 'DST',
119
+ * 32,
120
+ * 128,
121
+ * shake256
122
+ * );
123
+ * ```
124
+ */
125
+ function expand_message_xof(msg, DST, lenInBytes, k, H) {
126
+ (0, utils_1.abytes)(msg);
127
+ (0, utils_1.asafenumber)(lenInBytes);
128
+ DST = normDST(DST);
129
+ // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
130
+ // RFC 9380 §5.3.3: DST = H("H2C-OVERSIZE-DST-" || a_very_long_DST, ceil(2 * k / 8)).
131
+ if (DST.length > 255) {
132
+ const dkLen = Math.ceil((2 * k) / 8);
133
+ DST = H.create({ dkLen }).update((0, utils_1.asciiToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
134
+ }
135
+ if (lenInBytes > 65535 || DST.length > 255)
136
+ throw new Error('expand_message_xof: invalid lenInBytes');
137
+ return (H.create({ dkLen: lenInBytes })
138
+ .update(msg)
139
+ .update(i2osp(lenInBytes, 2))
140
+ // 2. DST_prime = DST || I2OSP(len(DST), 1)
141
+ .update(DST)
142
+ .update(i2osp(DST.length, 1))
143
+ .digest());
144
+ }
145
+ /**
146
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
147
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
148
+ * @param msg - Input message bytes.
149
+ * @param count - Number of field elements to derive. Must be `>= 1`.
150
+ * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
151
+ * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
152
+ * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
153
+ * @example
154
+ * Hash one message into field elements before mapping it onto a curve.
155
+ *
156
+ * ```ts
157
+ * import { hash_to_field } from './hash-to-curve';
158
+ * import { sha256 } from '@decryption/hashes/sha2';
159
+ * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
160
+ * DST: 'DST',
161
+ * p: 17n,
162
+ * m: 1,
163
+ * k: 128,
164
+ * expand: 'xmd',
165
+ * hash: sha256,
166
+ * });
167
+ * ```
168
+ */
169
+ function hash_to_field(msg, count, options) {
170
+ (0, utils_1.validateObject)(options, {
171
+ p: 'bigint',
172
+ m: 'number',
173
+ k: 'number',
174
+ hash: 'function',
175
+ });
176
+ const { p, k, m, hash, expand, DST } = options;
177
+ (0, utils_1.asafenumber)(hash.outputLen, 'valid hash');
178
+ (0, utils_1.abytes)(msg);
179
+ (0, utils_1.asafenumber)(count);
180
+ // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires
181
+ // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.
182
+ if (count < 1)
183
+ throw new Error('hash_to_field: expected count >= 1');
184
+ if (m < 1)
185
+ throw new Error('hash_to_field: expected m >= 1');
186
+ const log2p = p.toString(2).length;
187
+ const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
188
+ const len_in_bytes = count * m * L;
189
+ let prb; // pseudo_random_bytes
190
+ if (expand === 'xmd') {
191
+ prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
192
+ }
193
+ else if (expand === 'xof') {
194
+ prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
195
+ }
196
+ else if (expand === '_internal_pass') {
197
+ // for internal tests only
198
+ prb = msg;
199
+ }
200
+ else {
201
+ throw new Error('expand must be "xmd" or "xof"');
202
+ }
203
+ const u = new Array(count);
204
+ for (let i = 0; i < count; i++) {
205
+ const e = new Array(m);
206
+ for (let j = 0; j < m; j++) {
207
+ const elm_offset = L * (j + i * m);
208
+ const tv = prb.subarray(elm_offset, elm_offset + L);
209
+ e[j] = (0, modular_1.mod)(os2ip(tv), p);
210
+ }
211
+ u[i] = e;
212
+ }
213
+ return u;
214
+ }
215
+ /**
216
+ * @param field - Field implementation.
217
+ * @param map - Isogeny coefficients.
218
+ * @returns Isogeny mapping helper.
219
+ * @example
220
+ * Build one rational isogeny map, then apply it to affine x/y coordinates.
221
+ *
222
+ * ```ts
223
+ * import { isogenyMap } from './hash-to-curve';
224
+ * import { Field } from './modular';
225
+ * const Fp = Field(17n);
226
+ * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);
227
+ * const point = iso(3n, 5n);
228
+ * ```
229
+ */
230
+ function isogenyMap(field, map) {
231
+ // Make same order as in spec
232
+ const coeff = map.map((i) => Array.from(i).reverse());
233
+ return (x, y) => {
234
+ const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
235
+ // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must
236
+ // return the identity on E.
237
+ // Shipped Weierstrass consumers encode that affine identity as all-zero
238
+ // coordinates, so `passZero=true` intentionally collapses zero
239
+ // denominators to `{ x: 0, y: 0 }`.
240
+ const [xd_inv, yd_inv] = (0, modular_1.FpInvertBatch)(field, [xd, yd], true);
241
+ x = field.mul(xn, xd_inv); // xNum / xDen
242
+ y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
243
+ return { x, y };
244
+ };
245
+ }
246
+ // Keep the shared DST removable when the selected bundle never hashes to scalar.
247
+ // Callers that need protocol-specific scalar domain separation must override this generic default.
248
+ // RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.
249
+ // Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior
250
+ // by mutating a shared Uint8Array in place.
251
+ exports._DST_scalar = 'HashToScalar-';
252
+ /**
253
+ * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
254
+ * @param Point - Point constructor.
255
+ * @param mapToCurve - Map-to-curve function.
256
+ * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
257
+ * the shared defaults bundle for the returned helpers.
258
+ * @returns Hash-to-curve helper namespace.
259
+ * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
260
+ * @example
261
+ * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
262
+ *
263
+ * ```ts
264
+ * import { createHasher } from './hash-to-curve';
265
+ * import { p256 } from '../nist';
266
+ * import { sha256 } from '@decryption/hashes/sha2';
267
+ * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
268
+ * DST: 'P256_XMD:SHA-256_SSWU_RO_',
269
+ * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
270
+ * p: p256.Point.Fp.ORDER,
271
+ * m: 1,
272
+ * k: 128,
273
+ * expand: 'xmd',
274
+ * hash: sha256,
275
+ * });
276
+ * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
277
+ * ```
278
+ */
279
+ function createHasher(Point, mapToCurve, defaults) {
280
+ if (typeof mapToCurve !== 'function')
281
+ throw new Error('mapToCurve() must be defined');
282
+ // `Point` is intentionally not shape-validated eagerly here: point constructors vary across
283
+ // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured
284
+ // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().
285
+ const snapshot = (src) => Object.freeze({
286
+ ...src,
287
+ DST: (0, utils_1.isBytes)(src.DST) ? (0, utils_1.copyBytes)(src.DST) : src.DST,
288
+ ...(src.encodeDST === undefined
289
+ ? {}
290
+ : { encodeDST: (0, utils_1.isBytes)(src.encodeDST) ? (0, utils_1.copyBytes)(src.encodeDST) : src.encodeDST }),
291
+ });
292
+ // Keep one private defaults snapshot for actual hashing and expose fresh
293
+ // detached snapshots via the public getter.
294
+ // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison
295
+ // the singleton hasher for every other consumer in the same process.
296
+ const safeDefaults = snapshot(defaults);
297
+ function map(num) {
298
+ return Point.fromAffine(mapToCurve(num));
299
+ }
300
+ function clear(initial) {
301
+ const P = initial.clearCofactor();
302
+ // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity
303
+ // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.
304
+ if (P.equals(Point.ZERO))
305
+ return Point.ZERO;
306
+ P.assertValidity();
307
+ return P;
308
+ }
309
+ return Object.freeze({
310
+ get defaults() {
311
+ return snapshot(safeDefaults);
312
+ },
313
+ Point,
314
+ hashToCurve(msg, options) {
315
+ const opts = Object.assign({}, safeDefaults, options);
316
+ const u = hash_to_field(msg, 2, opts);
317
+ const u0 = map(u[0]);
318
+ const u1 = map(u[1]);
319
+ return clear(u0.add(u1));
320
+ },
321
+ encodeToCurve(msg, options) {
322
+ const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
323
+ const opts = Object.assign({}, safeDefaults, optsDst, options);
324
+ const u = hash_to_field(msg, 1, opts);
325
+ const u0 = map(u[0]);
326
+ return clear(u0);
327
+ },
328
+ /** See {@link H2CHasher} */
329
+ mapToCurve(scalars) {
330
+ // Curves with m=1 accept only single scalar
331
+ if (safeDefaults.m === 1) {
332
+ if (typeof scalars !== 'bigint')
333
+ throw new Error('expected bigint (m=1)');
334
+ return clear(map([scalars]));
335
+ }
336
+ if (!Array.isArray(scalars))
337
+ throw new Error('expected array of bigints');
338
+ for (const i of scalars)
339
+ if (typeof i !== 'bigint')
340
+ throw new Error('expected array of bigints');
341
+ return clear(map(scalars));
342
+ },
343
+ // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
344
+ // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic
345
+ // `HashToScalar-` prefix above unless the caller overrides it per invocation.
346
+ hashToScalar(msg, options) {
347
+ // @ts-ignore
348
+ const N = Point.Fn.ORDER;
349
+ const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: exports._DST_scalar }, options);
350
+ return hash_to_field(msg, 1, opts)[0][0];
351
+ },
352
+ });
353
+ }