@leofcoin/chain 1.10.16 → 1.10.18
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.
- package/exports/beacon-envelope.js +6 -6
- package/exports/beacon-epoch.js +1 -1
- package/exports/beacon-lifecycle.js +1 -1
- package/exports/beacon-round.js +1 -1
- package/exports/beacon.js +15 -14
- package/exports/browser/_commonjsHelpers-B85MJLTf.js +5 -0
- package/exports/browser/beacon-envelope.js +61 -150
- package/exports/browser/beacon-epoch.js +2 -2
- package/exports/browser/beacon-lifecycle.js +3 -3
- package/exports/browser/beacon-round.js +2 -2
- package/exports/browser/beacon-wire.js +3 -3
- package/exports/browser/beacon.js +2483 -1228
- package/exports/browser/{browser-CCfR9KOM-CvhDZrGu.js → browser-CCfR9KOM-CpStHgTj.js} +4 -4
- package/exports/browser/{browser-crypto-CeE-yId5.js → browser-crypto-CH0ua22L.js} +1 -1
- package/exports/browser/chain.js +151 -81
- package/exports/browser/{client-CAC7RVMf-Dmz_2A_5.js → client-C_pBoi1g-_pfKzCvX.js} +256 -80
- package/exports/browser/{connection-monitor-Cmv00mwl.js → connection-monitor-D-krNiRH.js} +1 -1
- package/exports/browser/{hkdf-CnZvwpZ9.js → hkdf-BUHINPFj.js} +2 -94
- package/exports/browser/{index-BC-KRBgE.js → index-DmuI-29u.js} +1 -1
- package/exports/browser/{index-dTQVgkpf-CuHJWO2l.js → index-dTQVgkpf-BbdshWB0.js} +4 -4
- package/exports/browser/index.browser-CFfJpgKV.js +857 -0
- package/exports/browser/{messages-Dw86z0zq-DrPw_nlZ.js → messages-BGHaihSi-eHZVl0y9.js} +4 -4
- package/exports/browser/{node-browser-DWSdi-XP.js → node-browser-BNe-en1l.js} +5 -5
- package/exports/browser/node-browser.js +4 -4
- package/exports/browser/{sha2-piimb6xL.js → sha2-BKcEJzgd.js} +144 -3
- package/exports/browser/weierstrass-BVfhtHbl.js +3596 -0
- package/exports/browser/workers/machine-worker.js +61 -19
- package/exports/chain.js +146 -73
- package/exports/workers/machine-worker.js +61 -19
- package/package.json +14 -13
- package/exports/browser/weierstrass-Q0QND1ZT.js +0 -2156
|
@@ -0,0 +1,3596 @@
|
|
|
1
|
+
import { c as abytes$1, i as isBytes$1, e as concatBytes$1, f as bytesToHex$1, r as randomBytes$1, b as anumber$1, h as hexToBytes$1, a as ahash, d as clean, g as aexists, j as aoutput } from './sha2-BKcEJzgd.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Hex, bytes and number utilities.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
8
|
+
/**
|
|
9
|
+
* Validates that a value is an array, optionally validating each element.
|
|
10
|
+
* @param item - Value to validate.
|
|
11
|
+
* @param title - Label included in thrown errors.
|
|
12
|
+
* @param inner - Optional per-element validator, called with the element and its label.
|
|
13
|
+
* @returns The validated array.
|
|
14
|
+
* @example
|
|
15
|
+
* Validate an array of points before batch processing.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* aarray([1n, 2n], 'scalars');
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
function aarray(item, title, inner = () => { }) {
|
|
22
|
+
if (!Array.isArray(item))
|
|
23
|
+
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
|
24
|
+
for (let i = 0; i < item.length; i++)
|
|
25
|
+
inner(item[i], `${title}[${i}]`);
|
|
26
|
+
return item;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Validates that a value is a byte array.
|
|
30
|
+
* @param value - Value to validate.
|
|
31
|
+
* @param length - Optional exact byte length.
|
|
32
|
+
* @param title - Optional field name.
|
|
33
|
+
* @returns Original byte array.
|
|
34
|
+
* @example
|
|
35
|
+
* Reject non-byte input before passing data into curve code.
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* abytes(new Uint8Array(1));
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
const abytes = (value, length, title) => abytes$1(value, length, title);
|
|
42
|
+
/**
|
|
43
|
+
* Validates that a value is a non-negative safe integer.
|
|
44
|
+
* @param n - Value to validate.
|
|
45
|
+
* @param title - Optional field name.
|
|
46
|
+
* @returns The validated number.
|
|
47
|
+
* @example
|
|
48
|
+
* Validate a numeric length before allocating buffers.
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* anumber(1);
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
const anumber = anumber$1;
|
|
55
|
+
/**
|
|
56
|
+
* Asserts something is a string.
|
|
57
|
+
* @param value - Value to validate.
|
|
58
|
+
* @param title - Label included in thrown errors.
|
|
59
|
+
* @returns The validated string.
|
|
60
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
61
|
+
* @example
|
|
62
|
+
* Validate a label string.
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* astring('example', 'label');
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
function astring(value, title = '') {
|
|
69
|
+
if (typeof value !== 'string') {
|
|
70
|
+
const prefix = title && `"${title}" `;
|
|
71
|
+
throw new TypeError(prefix + 'expected string, got type=' + typeof value);
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Asserts something is a plain object-ish value, not null or array.
|
|
77
|
+
* @param value - Value to validate.
|
|
78
|
+
* @param title - Label included in thrown errors.
|
|
79
|
+
* @returns The validated object.
|
|
80
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
81
|
+
* @example
|
|
82
|
+
* Validate an options object before checking fields.
|
|
83
|
+
*
|
|
84
|
+
* ```ts
|
|
85
|
+
* aobject({ flag: true });
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
function aobject(value, title = 'object') {
|
|
89
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
90
|
+
throw new TypeError(title === 'object'
|
|
91
|
+
? 'expected valid options object'
|
|
92
|
+
: `"${title}" expected object, got type=${typeof value}`);
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Asserts something is a function.
|
|
97
|
+
* @param value - Value to validate.
|
|
98
|
+
* @param title - Label included in thrown errors.
|
|
99
|
+
* @returns The validated function.
|
|
100
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
101
|
+
* @example
|
|
102
|
+
* Validate a required method before calling it.
|
|
103
|
+
*
|
|
104
|
+
* ```ts
|
|
105
|
+
* afunction(() => true, 'predicate');
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
function afunction(value, title) {
|
|
109
|
+
if (typeof value !== 'function')
|
|
110
|
+
throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Encodes bytes as lowercase hex.
|
|
115
|
+
* @param bytes - Bytes to encode.
|
|
116
|
+
* @returns Lowercase hex string.
|
|
117
|
+
* @example
|
|
118
|
+
* Serialize bytes as hex for logging or fixtures.
|
|
119
|
+
*
|
|
120
|
+
* ```ts
|
|
121
|
+
* bytesToHex(Uint8Array.of(1, 2, 3));
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
const bytesToHex = bytesToHex$1;
|
|
125
|
+
/**
|
|
126
|
+
* Concatenates byte arrays.
|
|
127
|
+
* @param arrays - Byte arrays to join.
|
|
128
|
+
* @returns Concatenated bytes.
|
|
129
|
+
* @example
|
|
130
|
+
* Join domain-separated chunks into one buffer.
|
|
131
|
+
*
|
|
132
|
+
* ```ts
|
|
133
|
+
* concatBytes(Uint8Array.of(1), Uint8Array.of(2));
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
const concatBytes = (...arrays) => concatBytes$1(...arrays);
|
|
137
|
+
/**
|
|
138
|
+
* Decodes lowercase or uppercase hex into bytes.
|
|
139
|
+
* @param hex - Hex string to decode.
|
|
140
|
+
* @returns Decoded bytes.
|
|
141
|
+
* @example
|
|
142
|
+
* Parse fixture hex into bytes before hashing.
|
|
143
|
+
*
|
|
144
|
+
* ```ts
|
|
145
|
+
* hexToBytes('0102');
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
const hexToBytes = (hex) => hexToBytes$1(hex);
|
|
149
|
+
/**
|
|
150
|
+
* Checks whether a value is a Uint8Array.
|
|
151
|
+
* @param a - Value to inspect.
|
|
152
|
+
* @returns `true` when `a` is a Uint8Array.
|
|
153
|
+
* @example
|
|
154
|
+
* Branch on byte input before decoding it.
|
|
155
|
+
*
|
|
156
|
+
* ```ts
|
|
157
|
+
* isBytes(new Uint8Array(1));
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
const isBytes = isBytes$1;
|
|
161
|
+
/**
|
|
162
|
+
* Reads random bytes from the platform CSPRNG.
|
|
163
|
+
* @param bytesLength - Number of random bytes to read.
|
|
164
|
+
* @returns Fresh random bytes.
|
|
165
|
+
* @example
|
|
166
|
+
* Generate a random seed for a keypair.
|
|
167
|
+
*
|
|
168
|
+
* ```ts
|
|
169
|
+
* randomBytes(2);
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
const randomBytes = (bytesLength) => randomBytes$1(bytesLength);
|
|
173
|
+
const _0n$4 = /* @__PURE__ */ BigInt(0);
|
|
174
|
+
const _1n$3 = /* @__PURE__ */ BigInt(1);
|
|
175
|
+
// Shared error-message prefix builder. Only called on throw paths, so assert
|
|
176
|
+
// success paths never pay for the string concatenation.
|
|
177
|
+
const atitle = (title) => (title ? `"${title}" ` : '');
|
|
178
|
+
/**
|
|
179
|
+
* Validates that a flag is boolean.
|
|
180
|
+
* @param value - Value to validate.
|
|
181
|
+
* @param title - Optional field name.
|
|
182
|
+
* @returns Original value.
|
|
183
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
184
|
+
* @example
|
|
185
|
+
* Reject non-boolean option flags early.
|
|
186
|
+
*
|
|
187
|
+
* ```ts
|
|
188
|
+
* abool(true);
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
function abool(value, title = '') {
|
|
192
|
+
if (typeof value !== 'boolean')
|
|
193
|
+
throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Validates that a value is a non-negative bigint or safe integer.
|
|
198
|
+
* @param n - Value to validate.
|
|
199
|
+
* @returns The same validated value.
|
|
200
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
201
|
+
* @example
|
|
202
|
+
* Validate one integer-like value before serializing it.
|
|
203
|
+
*
|
|
204
|
+
* ```ts
|
|
205
|
+
* abignumber(1n);
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
function abignumber(n) {
|
|
209
|
+
if (typeof n === 'bigint') {
|
|
210
|
+
if (!isPosBig(n))
|
|
211
|
+
throw new RangeError('positive bigint expected, got ' + n);
|
|
212
|
+
}
|
|
213
|
+
else
|
|
214
|
+
anumber(n);
|
|
215
|
+
return n;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Validates that a value is a safe integer.
|
|
219
|
+
* @param value - Integer to validate.
|
|
220
|
+
* @param title - Optional field name.
|
|
221
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
222
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
223
|
+
* @example
|
|
224
|
+
* Validate a window size before scalar arithmetic uses it.
|
|
225
|
+
*
|
|
226
|
+
* ```ts
|
|
227
|
+
* asafenumber(1);
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
function asafenumber(value, title = '') {
|
|
231
|
+
if (typeof value !== 'number') {
|
|
232
|
+
const prefix = title && `"${title}" `;
|
|
233
|
+
throw new TypeError(prefix + 'expected number, got type=' + typeof value);
|
|
234
|
+
}
|
|
235
|
+
if (!Number.isSafeInteger(value)) {
|
|
236
|
+
const prefix = title && `"${title}" `;
|
|
237
|
+
throw new RangeError(prefix + 'expected safe integer, got ' + value);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Encodes a bigint into even-length big-endian hex.
|
|
242
|
+
* The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
|
|
243
|
+
* gets one leading zero nibble so the result always represents whole bytes.
|
|
244
|
+
* @param num - Number to encode.
|
|
245
|
+
* @returns Big-endian hex string.
|
|
246
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
247
|
+
* @example
|
|
248
|
+
* Encode a scalar into hex without a `0x` prefix.
|
|
249
|
+
*
|
|
250
|
+
* ```ts
|
|
251
|
+
* numberToHexUnpadded(255n);
|
|
252
|
+
* ```
|
|
253
|
+
*/
|
|
254
|
+
function numberToHexUnpadded(num) {
|
|
255
|
+
const hex = abignumber(num).toString(16);
|
|
256
|
+
return hex.length & 1 ? '0' + hex : hex;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Parses a big-endian hex string into bigint.
|
|
260
|
+
* Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
|
|
261
|
+
* same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
|
|
262
|
+
* @param hex - Hex string without `0x`.
|
|
263
|
+
* @returns Parsed bigint value.
|
|
264
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
265
|
+
* @example
|
|
266
|
+
* Parse a scalar from fixture hex.
|
|
267
|
+
*
|
|
268
|
+
* ```ts
|
|
269
|
+
* hexToNumber('ff');
|
|
270
|
+
* ```
|
|
271
|
+
*/
|
|
272
|
+
function hexToNumber(hex) {
|
|
273
|
+
if (typeof hex !== 'string')
|
|
274
|
+
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
275
|
+
return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
|
|
276
|
+
}
|
|
277
|
+
// BE: Big Endian, LE: Little Endian
|
|
278
|
+
/**
|
|
279
|
+
* Parses big-endian bytes into bigint.
|
|
280
|
+
* @param bytes - Bytes in big-endian order.
|
|
281
|
+
* @returns Parsed bigint value.
|
|
282
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
283
|
+
* @example
|
|
284
|
+
* Read a scalar encoded in network byte order.
|
|
285
|
+
*
|
|
286
|
+
* ```ts
|
|
287
|
+
* bytesToNumberBE(Uint8Array.of(1, 0));
|
|
288
|
+
* ```
|
|
289
|
+
*/
|
|
290
|
+
function bytesToNumberBE(bytes) {
|
|
291
|
+
return hexToNumber(bytesToHex$1(bytes));
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Parses little-endian bytes into bigint.
|
|
295
|
+
* @param bytes - Bytes in little-endian order.
|
|
296
|
+
* @returns Parsed bigint value.
|
|
297
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
298
|
+
* @example
|
|
299
|
+
* Read a scalar encoded in little-endian form.
|
|
300
|
+
*
|
|
301
|
+
* ```ts
|
|
302
|
+
* bytesToNumberLE(Uint8Array.of(1, 0));
|
|
303
|
+
* ```
|
|
304
|
+
*/
|
|
305
|
+
function bytesToNumberLE(bytes) {
|
|
306
|
+
return hexToNumber(bytesToHex$1(copyBytes(abytes$1(bytes)).reverse()));
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Encodes a bigint into fixed-length big-endian bytes.
|
|
310
|
+
* @param n - Number to encode.
|
|
311
|
+
* @param len - Output length in bytes. Must be greater than zero.
|
|
312
|
+
* @returns Big-endian byte array.
|
|
313
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
314
|
+
* @throws If a documented runtime validation or state check fails. {@link Error}
|
|
315
|
+
* @example
|
|
316
|
+
* Serialize a scalar into a 32-byte field element.
|
|
317
|
+
*
|
|
318
|
+
* ```ts
|
|
319
|
+
* numberToBytesBE(255n, 2);
|
|
320
|
+
* ```
|
|
321
|
+
*/
|
|
322
|
+
function numberToBytesBE(n, len) {
|
|
323
|
+
anumber$1(len);
|
|
324
|
+
if (len === 0)
|
|
325
|
+
throw new Error('zero output length is invalid');
|
|
326
|
+
n = abignumber(n);
|
|
327
|
+
const expectedLen = len * 2;
|
|
328
|
+
const hex = n.toString(16);
|
|
329
|
+
// Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.
|
|
330
|
+
if (hex.length > expectedLen)
|
|
331
|
+
throw new RangeError('number is too large');
|
|
332
|
+
return hexToBytes$1(hex.padStart(expectedLen, '0'));
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Encodes a bigint into fixed-length little-endian bytes.
|
|
336
|
+
* @param n - Number to encode.
|
|
337
|
+
* @param len - Output length in bytes.
|
|
338
|
+
* @returns Little-endian byte array.
|
|
339
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
340
|
+
* @throws If a documented runtime validation or state check fails. {@link Error}
|
|
341
|
+
* @example
|
|
342
|
+
* Serialize a scalar for little-endian protocols.
|
|
343
|
+
*
|
|
344
|
+
* ```ts
|
|
345
|
+
* numberToBytesLE(255n, 2);
|
|
346
|
+
* ```
|
|
347
|
+
*/
|
|
348
|
+
function numberToBytesLE(n, len) {
|
|
349
|
+
return numberToBytesBE(n, len).reverse();
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
|
|
353
|
+
* and Buffer#slice creates mutable copy. Never use Buffers!
|
|
354
|
+
* @param bytes - Bytes to copy.
|
|
355
|
+
* @returns Detached copy.
|
|
356
|
+
* @example
|
|
357
|
+
* Make an isolated copy before mutating serialized bytes.
|
|
358
|
+
*
|
|
359
|
+
* ```ts
|
|
360
|
+
* copyBytes(Uint8Array.of(1, 2, 3));
|
|
361
|
+
* ```
|
|
362
|
+
*/
|
|
363
|
+
function copyBytes(bytes) {
|
|
364
|
+
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
|
365
|
+
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
|
366
|
+
return Uint8Array.from(abytes(bytes));
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
|
|
370
|
+
* Should be safe to use for things expected to be ASCII.
|
|
371
|
+
* Returns exact same result as `TextEncoder` for ASCII or throws.
|
|
372
|
+
* @param ascii - ASCII input text.
|
|
373
|
+
* @returns Encoded bytes.
|
|
374
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
375
|
+
* @example
|
|
376
|
+
* Encode an ASCII domain-separation tag.
|
|
377
|
+
*
|
|
378
|
+
* ```ts
|
|
379
|
+
* asciiToBytes('ABC');
|
|
380
|
+
* ```
|
|
381
|
+
*/
|
|
382
|
+
function asciiToBytes(ascii) {
|
|
383
|
+
if (typeof ascii !== 'string')
|
|
384
|
+
throw new TypeError('ascii string expected, got ' + typeof ascii);
|
|
385
|
+
return Uint8Array.from(ascii, (c, i) => {
|
|
386
|
+
const charCode = c.charCodeAt(0);
|
|
387
|
+
if (c.length !== 1 || charCode > 127) {
|
|
388
|
+
throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
|
|
389
|
+
}
|
|
390
|
+
return charCode;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Checks whether n is non-negative bigint. Historical name.
|
|
395
|
+
* @param n - candidate value
|
|
396
|
+
* @returns `true` when the value is bigint and 0 or larger
|
|
397
|
+
* @example
|
|
398
|
+
* Check a candidate scalar before range validation.
|
|
399
|
+
*
|
|
400
|
+
* ```ts
|
|
401
|
+
* isPosBig(2n);
|
|
402
|
+
* ```
|
|
403
|
+
*/
|
|
404
|
+
function isPosBig(n) {
|
|
405
|
+
return typeof n === 'bigint' && _0n$4 <= n;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Checks whether a bigint lies inside a half-open range.
|
|
409
|
+
* @param n - Candidate value.
|
|
410
|
+
* @param min - Inclusive lower bound.
|
|
411
|
+
* @param max - Exclusive upper bound.
|
|
412
|
+
* @returns `true` when the value is inside the range.
|
|
413
|
+
* @example
|
|
414
|
+
* Check whether a candidate scalar fits the field order.
|
|
415
|
+
*
|
|
416
|
+
* ```ts
|
|
417
|
+
* inRange(2n, 1n, 3n);
|
|
418
|
+
* ```
|
|
419
|
+
*/
|
|
420
|
+
function inRange(n, min, max) {
|
|
421
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Asserts `min <= n < max`. NOTE: upper bound is exclusive.
|
|
425
|
+
* @param title - Value label for error messages.
|
|
426
|
+
* @param n - Candidate value.
|
|
427
|
+
* @param min - Inclusive lower bound.
|
|
428
|
+
* @param max - Exclusive upper bound.
|
|
429
|
+
* Wrong-type inputs are not separated from out-of-range values here: they still flow through the
|
|
430
|
+
* shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
|
|
431
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
432
|
+
* @example
|
|
433
|
+
* Assert that a bigint stays within one half-open range.
|
|
434
|
+
*
|
|
435
|
+
* ```ts
|
|
436
|
+
* aInRange('x', 2n, 1n, 256n);
|
|
437
|
+
* ```
|
|
438
|
+
*/
|
|
439
|
+
function aInRange(title, n, min, max) {
|
|
440
|
+
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
|
441
|
+
// consider P=256n, min=0n, max=P
|
|
442
|
+
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
|
443
|
+
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
|
444
|
+
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
|
445
|
+
if (!inRange(n, min, max))
|
|
446
|
+
throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
|
447
|
+
}
|
|
448
|
+
// Bit operations
|
|
449
|
+
/**
|
|
450
|
+
* Calculates amount of bits in a bigint.
|
|
451
|
+
* Same as `n.toString(2).length`
|
|
452
|
+
* TODO: merge with nLength in modular
|
|
453
|
+
* @param n - Value to inspect.
|
|
454
|
+
* @returns Bit length.
|
|
455
|
+
* @throws If the value is negative. {@link Error}
|
|
456
|
+
* @example
|
|
457
|
+
* Measure the bit length of a scalar before serialization.
|
|
458
|
+
*
|
|
459
|
+
* ```ts
|
|
460
|
+
* bitLen(8n);
|
|
461
|
+
* ```
|
|
462
|
+
*/
|
|
463
|
+
function bitLen(n) {
|
|
464
|
+
// Size callers in this repo only use non-negative orders / scalars, so negative inputs are a
|
|
465
|
+
// contract bug and must not silently collapse to zero bits.
|
|
466
|
+
if (n < _0n$4)
|
|
467
|
+
throw new Error('expected non-negative bigint, got ' + n);
|
|
468
|
+
// Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.
|
|
469
|
+
return n === _0n$4 ? 0 : n.toString(2).length;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Gets single bit at position.
|
|
473
|
+
* NOTE: first bit position is 0 (same as arrays)
|
|
474
|
+
* Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
|
|
475
|
+
* @param n - Source value.
|
|
476
|
+
* @param pos - Bit position. Negative positions are passed through to raw
|
|
477
|
+
* bigint shift semantics; because the mask is built as `1n << pos`,
|
|
478
|
+
* they currently collapse to `0n` and make the helper a no-op.
|
|
479
|
+
* @returns Bit as bigint.
|
|
480
|
+
* @example
|
|
481
|
+
* Gets single bit at position.
|
|
482
|
+
*
|
|
483
|
+
* ```ts
|
|
484
|
+
* bitGet(5n, 0);
|
|
485
|
+
* ```
|
|
486
|
+
*/
|
|
487
|
+
function bitGet(n, pos) {
|
|
488
|
+
if (typeof n !== 'bigint')
|
|
489
|
+
throw new TypeError('"n" expected bigint, got type=' + typeof n);
|
|
490
|
+
asafenumber(pos, 'pos');
|
|
491
|
+
return (n >> BigInt(pos)) & _1n$3;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
|
495
|
+
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
|
496
|
+
* @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
|
|
497
|
+
* semantics and therefore produce `-1n`.
|
|
498
|
+
* @returns Bitmask value.
|
|
499
|
+
* @example
|
|
500
|
+
* Calculate mask for N bits.
|
|
501
|
+
*
|
|
502
|
+
* ```ts
|
|
503
|
+
* bitMask(4);
|
|
504
|
+
* ```
|
|
505
|
+
*/
|
|
506
|
+
const bitMask = (n) => {
|
|
507
|
+
asafenumber(n, 'n');
|
|
508
|
+
return (_1n$3 << BigInt(n)) - _1n$3;
|
|
509
|
+
};
|
|
510
|
+
/**
|
|
511
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
512
|
+
* @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
|
|
513
|
+
* is not rejected here and would make the internal generate loop non-progressing.
|
|
514
|
+
* @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
|
|
515
|
+
* @param hmacFn - HMAC implementation.
|
|
516
|
+
* @returns Function that will call DRBG until the predicate returns anything
|
|
517
|
+
* other than `undefined`.
|
|
518
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
519
|
+
* @example
|
|
520
|
+
* Build a deterministic nonce generator for RFC6979-style signing.
|
|
521
|
+
*
|
|
522
|
+
* ```ts
|
|
523
|
+
* import { createHmacDrbg } from '@noble/curves/utils.js';
|
|
524
|
+
* import { hmac } from '@noble/hashes/hmac.js';
|
|
525
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
526
|
+
* const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);
|
|
527
|
+
* const drbg = createHmacDrbg(32, 32, hmacFn);
|
|
528
|
+
* const seed = new Uint8Array(32);
|
|
529
|
+
* drbg(seed, (bytes) => bytes);
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
533
|
+
anumber$1(hashLen, 'hashLen');
|
|
534
|
+
anumber$1(qByteLen, 'qByteLen');
|
|
535
|
+
if (typeof hmacFn !== 'function')
|
|
536
|
+
throw new TypeError('hmacFn must be a function');
|
|
537
|
+
// creates Uint8Array
|
|
538
|
+
const u8n = (len) => new Uint8Array(len);
|
|
539
|
+
const NULL = Uint8Array.of();
|
|
540
|
+
const byte0 = Uint8Array.of(0x00);
|
|
541
|
+
const byte1 = Uint8Array.of(0x01);
|
|
542
|
+
const _maxDrbgIters = 1000;
|
|
543
|
+
// Step B, Step C: set hashLen to 8*ceil(hlen/8).
|
|
544
|
+
// Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.
|
|
545
|
+
let v = u8n(hashLen);
|
|
546
|
+
// Steps B and C of RFC6979 3.2.
|
|
547
|
+
let k = u8n(hashLen);
|
|
548
|
+
let i = 0; // Iterations counter, will throw when over 1000
|
|
549
|
+
const reset = () => {
|
|
550
|
+
v.fill(1);
|
|
551
|
+
k.fill(0);
|
|
552
|
+
i = 0;
|
|
553
|
+
};
|
|
554
|
+
// hmac(k)(v, ...values)
|
|
555
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
556
|
+
const reseed = (seed = NULL) => {
|
|
557
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
558
|
+
k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)
|
|
559
|
+
v = h(); // v = hmac(k || v)
|
|
560
|
+
if (seed.length === 0)
|
|
561
|
+
return;
|
|
562
|
+
k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)
|
|
563
|
+
v = h(); // v = hmac(k || v)
|
|
564
|
+
};
|
|
565
|
+
const gen = () => {
|
|
566
|
+
// HMAC-DRBG generate() function
|
|
567
|
+
if (i++ >= _maxDrbgIters)
|
|
568
|
+
throw new Error('drbg: tried max amount of iterations');
|
|
569
|
+
let len = 0;
|
|
570
|
+
const out = [];
|
|
571
|
+
while (len < qByteLen) {
|
|
572
|
+
v = h();
|
|
573
|
+
const sl = v.slice();
|
|
574
|
+
out.push(sl);
|
|
575
|
+
len += v.length;
|
|
576
|
+
}
|
|
577
|
+
return concatBytes(...out);
|
|
578
|
+
};
|
|
579
|
+
const genUntil = (seed, pred) => {
|
|
580
|
+
reset();
|
|
581
|
+
reseed(seed); // Steps D-G
|
|
582
|
+
let res = undefined; // Step H: grind until the predicate accepts a candidate.
|
|
583
|
+
// Falsy values like 0 are valid outputs.
|
|
584
|
+
while ((res = pred(gen())) === undefined)
|
|
585
|
+
reseed();
|
|
586
|
+
reset();
|
|
587
|
+
return res;
|
|
588
|
+
};
|
|
589
|
+
return genUntil;
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Validates declared required and optional field types on a plain object.
|
|
593
|
+
* Extra keys are intentionally ignored because many callers validate only the subset they use from
|
|
594
|
+
* richer option bags or runtime objects.
|
|
595
|
+
* This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
|
|
596
|
+
* one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.
|
|
597
|
+
* @param object - Object to validate.
|
|
598
|
+
* @param fields - Required field types.
|
|
599
|
+
* @param optFields - Optional field types.
|
|
600
|
+
* @param title - Object label included in thrown errors.
|
|
601
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
602
|
+
* @example
|
|
603
|
+
* Check user options before building a curve helper.
|
|
604
|
+
*
|
|
605
|
+
* ```ts
|
|
606
|
+
* validateObject({ flag: true }, { flag: 'boolean' });
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
function validateObject(object, fields = {}, optFields = {}, title = 'object') {
|
|
610
|
+
aobject(object, title);
|
|
611
|
+
aobject(fields, 'fields');
|
|
612
|
+
aobject(optFields, 'optFields');
|
|
613
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
614
|
+
const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
|
615
|
+
// Config fields must be explicit own properties. Optional inherited values are rejected too
|
|
616
|
+
// because callers keep reading the same options object after validation.
|
|
617
|
+
const val = object[fieldName];
|
|
618
|
+
// Runtime objects such as Field instances intentionally satisfy required method slots
|
|
619
|
+
// via their shared prototype.
|
|
620
|
+
if (!Object.hasOwn(object, fieldName) &&
|
|
621
|
+
(isOpt ? val !== undefined : expectedType !== 'function')) {
|
|
622
|
+
throw new TypeError(`${label} is invalid: expected own property`);
|
|
623
|
+
}
|
|
624
|
+
if (isOpt && val === undefined)
|
|
625
|
+
return;
|
|
626
|
+
const current = typeof val;
|
|
627
|
+
if (current !== expectedType || val === null)
|
|
628
|
+
throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
|
|
629
|
+
}
|
|
630
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
631
|
+
iter(fields, false);
|
|
632
|
+
iter(optFields, true);
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Throws not implemented error.
|
|
636
|
+
* @returns Never returns.
|
|
637
|
+
* @throws If the unfinished code path is reached. {@link Error}
|
|
638
|
+
* @example
|
|
639
|
+
* Surface the placeholder error from an unfinished code path.
|
|
640
|
+
*
|
|
641
|
+
* ```ts
|
|
642
|
+
* try {
|
|
643
|
+
* notImplemented();
|
|
644
|
+
* } catch {}
|
|
645
|
+
* ```
|
|
646
|
+
*/
|
|
647
|
+
const notImplemented = () => {
|
|
648
|
+
throw new Error('not implemented');
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Utils for modular division and fields.
|
|
653
|
+
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
|
654
|
+
* There is no division: it is replaced by modular multiplicative inverse.
|
|
655
|
+
* @module
|
|
656
|
+
*/
|
|
657
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
658
|
+
// Numbers aren't used in x25519 / x448 builds
|
|
659
|
+
// prettier-ignore
|
|
660
|
+
const _0n$3 = /* @__PURE__ */ BigInt(0), _1n$2 = /* @__PURE__ */ BigInt(1), _2n$1 = /* @__PURE__ */ BigInt(2);
|
|
661
|
+
// prettier-ignore
|
|
662
|
+
const _3n$1 = /* @__PURE__ */ BigInt(3), _4n$2 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
|
|
663
|
+
// prettier-ignore
|
|
664
|
+
const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
|
|
665
|
+
const _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);
|
|
666
|
+
// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's
|
|
667
|
+
// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).
|
|
668
|
+
const POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');
|
|
669
|
+
/**
|
|
670
|
+
* @param a - Dividend value.
|
|
671
|
+
* @param b - Positive modulus.
|
|
672
|
+
* @returns Reduced value in `[0, b)` only when `b` is positive.
|
|
673
|
+
* @throws If the modulus is not positive. {@link Error}
|
|
674
|
+
* @example
|
|
675
|
+
* Normalize a bigint into one field residue.
|
|
676
|
+
*
|
|
677
|
+
* ```ts
|
|
678
|
+
* mod(-1n, 5n);
|
|
679
|
+
* ```
|
|
680
|
+
*/
|
|
681
|
+
function mod(a, b) {
|
|
682
|
+
if (b <= _0n$3)
|
|
683
|
+
throw new Error('mod: expected positive modulus, got ' + b);
|
|
684
|
+
const result = a % b;
|
|
685
|
+
return result >= _0n$3 ? result : b + result;
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Efficiently raise num to a power with modular reduction.
|
|
689
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
690
|
+
* Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
|
|
691
|
+
* modulus instead of relying on the `power===0/1` fast paths to normalize it.
|
|
692
|
+
* @param num - Base value.
|
|
693
|
+
* @param power - Exponent value.
|
|
694
|
+
* @param modulo - Reduction modulus.
|
|
695
|
+
* @returns Modular exponentiation result.
|
|
696
|
+
* @throws If the modulus or exponent is invalid. {@link Error}
|
|
697
|
+
* @example
|
|
698
|
+
* Raise one bigint to a modular power.
|
|
699
|
+
*
|
|
700
|
+
* ```ts
|
|
701
|
+
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
|
702
|
+
* ```
|
|
703
|
+
*/
|
|
704
|
+
function pow(num, power, modulo) {
|
|
705
|
+
if (modulo <= _1n$2)
|
|
706
|
+
throw new Error('pow: expected modulus > 1, got ' + modulo);
|
|
707
|
+
// Non-bigint exponents coerce every comparison below to false and would silently return 1.
|
|
708
|
+
if (typeof power !== 'bigint')
|
|
709
|
+
throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);
|
|
710
|
+
if (power < _0n$3)
|
|
711
|
+
throw new Error('invalid exponent, negatives unsupported');
|
|
712
|
+
if (power === _0n$3)
|
|
713
|
+
return _1n$2;
|
|
714
|
+
if (power === _1n$2)
|
|
715
|
+
return num;
|
|
716
|
+
let d = num % modulo;
|
|
717
|
+
if (d < _0n$3)
|
|
718
|
+
d += modulo;
|
|
719
|
+
// Control flow in both branches below depends only on the exponent, never on `num` — invertCt()
|
|
720
|
+
// relies on that for its (public-exponent) secret-independence guarantee.
|
|
721
|
+
if (power < POW_WINDOWED_MIN) {
|
|
722
|
+
// Square-and-multiply: cheaper than the windowed path for short exponents.
|
|
723
|
+
let p = _1n$2;
|
|
724
|
+
while (power > _0n$3) {
|
|
725
|
+
if (power & _1n$2)
|
|
726
|
+
p = (p * d) % modulo;
|
|
727
|
+
d = (d * d) % modulo;
|
|
728
|
+
power >>= _1n$2;
|
|
729
|
+
}
|
|
730
|
+
return p;
|
|
731
|
+
}
|
|
732
|
+
// Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1
|
|
733
|
+
// multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense
|
|
734
|
+
// 256-bit exponents of sqrt / Legendre / invertCt.
|
|
735
|
+
const digits = [];
|
|
736
|
+
while (power > _0n$3) {
|
|
737
|
+
digits.push(Number(power & _15n));
|
|
738
|
+
power >>= _4n$2;
|
|
739
|
+
}
|
|
740
|
+
const table = new Array(16);
|
|
741
|
+
table[0] = _1n$2;
|
|
742
|
+
table[1] = d;
|
|
743
|
+
for (let i = 2; i < 16; i++)
|
|
744
|
+
table[i] = (table[i - 1] * d) % modulo;
|
|
745
|
+
let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0
|
|
746
|
+
for (let w = digits.length - 2; w >= 0; w--) {
|
|
747
|
+
p = (p * p) % modulo;
|
|
748
|
+
p = (p * p) % modulo;
|
|
749
|
+
p = (p * p) % modulo;
|
|
750
|
+
p = (p * p) % modulo;
|
|
751
|
+
const digit = digits[w];
|
|
752
|
+
if (digit !== 0)
|
|
753
|
+
p = (p * table[digit]) % modulo;
|
|
754
|
+
}
|
|
755
|
+
return p;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
|
|
759
|
+
* Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
|
|
760
|
+
* modulus; the `power===0` fast path intentionally returns the input unchanged.
|
|
761
|
+
* @param x - Base value.
|
|
762
|
+
* @param power - Number of squarings.
|
|
763
|
+
* @param modulo - Reduction modulus.
|
|
764
|
+
* @returns Repeated-squaring result.
|
|
765
|
+
* @throws If the exponent is negative. {@link Error}
|
|
766
|
+
* @example
|
|
767
|
+
* Apply repeated squaring inside one field.
|
|
768
|
+
*
|
|
769
|
+
* ```ts
|
|
770
|
+
* pow2(3n, 2n, 11n);
|
|
771
|
+
* ```
|
|
772
|
+
*/
|
|
773
|
+
function pow2(x, power, modulo) {
|
|
774
|
+
if (modulo <= _1n$2)
|
|
775
|
+
throw new Error('pow2: expected modulus > 1, got ' + modulo);
|
|
776
|
+
if (power < _0n$3)
|
|
777
|
+
throw new Error('pow2: expected non-negative exponent, got ' + power);
|
|
778
|
+
let res = x;
|
|
779
|
+
while (power-- > _0n$3) {
|
|
780
|
+
res *= res;
|
|
781
|
+
res %= modulo;
|
|
782
|
+
}
|
|
783
|
+
return res;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Inverses number over modulo.
|
|
787
|
+
* Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
|
|
788
|
+
* @param number - Value to invert.
|
|
789
|
+
* @param modulo - Modulus greater than 1.
|
|
790
|
+
* @returns Multiplicative inverse.
|
|
791
|
+
* @throws If the modulus is invalid or the inverse does not exist. {@link Error}
|
|
792
|
+
* @example
|
|
793
|
+
* Compute one modular inverse with the extended Euclidean algorithm.
|
|
794
|
+
*
|
|
795
|
+
* ```ts
|
|
796
|
+
* invert(3n, 11n);
|
|
797
|
+
* ```
|
|
798
|
+
*/
|
|
799
|
+
function invert(number, modulo) {
|
|
800
|
+
if (number === _0n$3)
|
|
801
|
+
throw new Error('invert: expected non-zero number');
|
|
802
|
+
// modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below "succeed" and return the
|
|
803
|
+
// useless inverse 0. Reject it like pow() and invertCt() do.
|
|
804
|
+
if (modulo <= _1n$2)
|
|
805
|
+
throw new Error('invert: expected modulus > 1, got ' + modulo);
|
|
806
|
+
// This is variable-time: the loop count depends on `number`. For a secret-independent
|
|
807
|
+
// (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).
|
|
808
|
+
let a = mod(number, modulo);
|
|
809
|
+
let b = modulo;
|
|
810
|
+
// Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`
|
|
811
|
+
// never affects the output, so it is not computed.
|
|
812
|
+
// prettier-ignore
|
|
813
|
+
let x = _0n$3, u = _1n$2;
|
|
814
|
+
while (a !== _0n$3) {
|
|
815
|
+
const q = b / a;
|
|
816
|
+
const r = b - a * q;
|
|
817
|
+
const m = x - u * q;
|
|
818
|
+
// prettier-ignore
|
|
819
|
+
b = a, a = r, x = u, u = m;
|
|
820
|
+
}
|
|
821
|
+
const gcd = b;
|
|
822
|
+
if (gcd !== _1n$2)
|
|
823
|
+
throw new Error('invert: does not exist');
|
|
824
|
+
return mod(x, modulo);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.
|
|
828
|
+
*
|
|
829
|
+
* Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the
|
|
830
|
+
* underlying square-and-multiply has the same control flow for every secret `a`: there is no
|
|
831
|
+
* data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style
|
|
832
|
+
* ECDSA nonce-inversion attacks). This is only "algorithmically" constant-time — JS bigint
|
|
833
|
+
* multiplication/reduction is still value-dependent — and it is roughly 4x slower than
|
|
834
|
+
* {@link invert}.
|
|
835
|
+
*
|
|
836
|
+
* REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be
|
|
837
|
+
* a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error
|
|
838
|
+
* instead of returning a wrong value.
|
|
839
|
+
* @param a - Value to invert.
|
|
840
|
+
* @param prime - Prime modulus.
|
|
841
|
+
* @returns Multiplicative inverse in `[1, prime)`.
|
|
842
|
+
* @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.
|
|
843
|
+
* {@link Error}
|
|
844
|
+
* @example
|
|
845
|
+
* Compute one modular inverse without secret-dependent branching.
|
|
846
|
+
*
|
|
847
|
+
* ```ts
|
|
848
|
+
* invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)
|
|
849
|
+
* ```
|
|
850
|
+
*/
|
|
851
|
+
function invertCt(a, prime) {
|
|
852
|
+
if (prime <= _1n$2)
|
|
853
|
+
throw new Error('invertCt: expected prime modulus > 1, got ' + prime);
|
|
854
|
+
const an = mod(a, prime);
|
|
855
|
+
if (an === _0n$3)
|
|
856
|
+
throw new Error('invertCt: expected non-zero number');
|
|
857
|
+
// Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.
|
|
858
|
+
const inverse = pow(an, prime - _2n$1, prime);
|
|
859
|
+
// O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.
|
|
860
|
+
if (mod(an * inverse, prime) !== _1n$2)
|
|
861
|
+
throw new Error('invertCt: does not exist');
|
|
862
|
+
return inverse;
|
|
863
|
+
}
|
|
864
|
+
function assertIsSquare(Fp, root, n) {
|
|
865
|
+
const F = Fp;
|
|
866
|
+
if (!F.eql(F.sqr(root), n))
|
|
867
|
+
throw new Error('Cannot find square root');
|
|
868
|
+
}
|
|
869
|
+
// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.
|
|
870
|
+
// An even ORDER makes their integer divisions — (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 — truncate and
|
|
871
|
+
// silently return a wrong result, so reject it explicitly at the entry points instead. This is a
|
|
872
|
+
// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by
|
|
873
|
+
// the Legendre-result / assertIsSquare checks).
|
|
874
|
+
function aoddModulus(order, fnName) {
|
|
875
|
+
if ((order & _1n$2) === _0n$3)
|
|
876
|
+
throw new Error(fnName + ': expected odd modulus, got ' + order);
|
|
877
|
+
}
|
|
878
|
+
// Not all roots are possible! Example which will throw:
|
|
879
|
+
// const NUM =
|
|
880
|
+
// n = 72057594037927816n;
|
|
881
|
+
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
|
882
|
+
function sqrt3mod4(Fp, n) {
|
|
883
|
+
const F = Fp;
|
|
884
|
+
const p1div4 = (F.ORDER + _1n$2) / _4n$2;
|
|
885
|
+
const root = F.pow(n, p1div4);
|
|
886
|
+
assertIsSquare(F, root, n);
|
|
887
|
+
return root;
|
|
888
|
+
}
|
|
889
|
+
// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV
|
|
890
|
+
// pseudocode verbatim.
|
|
891
|
+
function sqrt5mod8(Fp, n) {
|
|
892
|
+
const F = Fp;
|
|
893
|
+
const p5div8 = (F.ORDER - _5n) / _8n;
|
|
894
|
+
const n2 = F.mul(n, _2n$1);
|
|
895
|
+
const v = F.pow(n2, p5div8);
|
|
896
|
+
const nv = F.mul(n, v);
|
|
897
|
+
const i = F.mul(F.mul(nv, _2n$1), v);
|
|
898
|
+
const root = F.mul(nv, F.sub(i, F.ONE));
|
|
899
|
+
assertIsSquare(F, root, n);
|
|
900
|
+
return root;
|
|
901
|
+
}
|
|
902
|
+
// Based on RFC9380, Kong algorithm
|
|
903
|
+
// prettier-ignore
|
|
904
|
+
function sqrt9mod16(P) {
|
|
905
|
+
const Fp_ = Field(P);
|
|
906
|
+
const tn = tonelliShanks(P);
|
|
907
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
|
908
|
+
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
|
909
|
+
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
|
910
|
+
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
|
911
|
+
return ((Fp, n) => {
|
|
912
|
+
const F = Fp;
|
|
913
|
+
let tv1 = F.pow(n, c4); // 1. tv1 = x^c4
|
|
914
|
+
let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1
|
|
915
|
+
const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1
|
|
916
|
+
const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1
|
|
917
|
+
const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
|
918
|
+
const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
|
919
|
+
tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
|
920
|
+
tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
|
921
|
+
const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
|
922
|
+
const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
|
|
923
|
+
assertIsSquare(F, root, n);
|
|
924
|
+
return root;
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Tonelli-Shanks square root search algorithm.
|
|
929
|
+
* This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
|
|
930
|
+
* and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
|
|
931
|
+
* 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
|
|
932
|
+
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
|
933
|
+
* @param P - field order
|
|
934
|
+
* @returns function that takes field Fp (created from P) and number n
|
|
935
|
+
* @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
|
|
936
|
+
* @example
|
|
937
|
+
* Construct a square-root helper for primes that need Tonelli-Shanks.
|
|
938
|
+
*
|
|
939
|
+
* ```ts
|
|
940
|
+
* import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
|
|
941
|
+
* const Fp = Field(17n);
|
|
942
|
+
* const sqrt = tonelliShanks(17n)(Fp, 4n);
|
|
943
|
+
* ```
|
|
944
|
+
*/
|
|
945
|
+
function tonelliShanks(P) {
|
|
946
|
+
// Initialization (precomputation).
|
|
947
|
+
// Caching initialization could boost perf by 7%.
|
|
948
|
+
if (P < _3n$1)
|
|
949
|
+
throw new Error('sqrt is not defined for small field');
|
|
950
|
+
aoddModulus(P, 'tonelliShanks');
|
|
951
|
+
// Factor P - 1 = Q * 2^S, where Q is odd
|
|
952
|
+
let Q = P - _1n$2;
|
|
953
|
+
let S = 0;
|
|
954
|
+
while (Q % _2n$1 === _0n$3) {
|
|
955
|
+
Q /= _2n$1;
|
|
956
|
+
S++;
|
|
957
|
+
}
|
|
958
|
+
// Find the first quadratic non-residue Z >= 2
|
|
959
|
+
let Z = _2n$1;
|
|
960
|
+
const _Fp = Field(P);
|
|
961
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
962
|
+
// Basic primality test for P. After x iterations, chance of
|
|
963
|
+
// not finding quadratic non-residue is 2^x, so 2^1000.
|
|
964
|
+
if (Z++ > 1000)
|
|
965
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
966
|
+
}
|
|
967
|
+
// Fast-path; usually done before Z, but we do "primality test".
|
|
968
|
+
if (S === 1)
|
|
969
|
+
return sqrt3mod4;
|
|
970
|
+
// Slow-path
|
|
971
|
+
// TODO: test on Fp2 and others
|
|
972
|
+
let cc = _Fp.pow(Z, Q); // c = z^Q
|
|
973
|
+
const Q1div2 = (Q + _1n$2) / _2n$1;
|
|
974
|
+
return function tonelliSlow(Fp, n) {
|
|
975
|
+
const F = Fp;
|
|
976
|
+
if (F.is0(n))
|
|
977
|
+
return n;
|
|
978
|
+
// Check if n is a quadratic residue using Legendre symbol
|
|
979
|
+
if (FpLegendre(F, n) !== 1)
|
|
980
|
+
throw new Error('Cannot find square root');
|
|
981
|
+
// Initialize variables for the main loop
|
|
982
|
+
let M = S;
|
|
983
|
+
let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
|
984
|
+
let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
|
985
|
+
let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
|
986
|
+
// Main loop
|
|
987
|
+
// while t != 1
|
|
988
|
+
while (!F.eql(t, F.ONE)) {
|
|
989
|
+
// Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t
|
|
990
|
+
// means composite ORDER, where a fabricated root would be wrong: fail closed instead.
|
|
991
|
+
if (F.is0(t))
|
|
992
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
993
|
+
let i = 1;
|
|
994
|
+
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
|
995
|
+
let t_tmp = F.sqr(t); // t^(2^1)
|
|
996
|
+
while (!F.eql(t_tmp, F.ONE)) {
|
|
997
|
+
i++;
|
|
998
|
+
t_tmp = F.sqr(t_tmp); // t^(2^2)...
|
|
999
|
+
if (i === M)
|
|
1000
|
+
throw new Error('Cannot find square root');
|
|
1001
|
+
}
|
|
1002
|
+
// Calculate the exponent for b: 2^(M - i - 1)
|
|
1003
|
+
const exponent = _1n$2 << BigInt(M - i - 1); // bigint is important
|
|
1004
|
+
const b = F.pow(c, exponent); // b = 2^(M - i - 1)
|
|
1005
|
+
// Update variables
|
|
1006
|
+
M = i;
|
|
1007
|
+
c = F.sqr(b); // c = b^2
|
|
1008
|
+
t = F.mul(t, c); // t = (t * b^2)
|
|
1009
|
+
R = F.mul(R, b); // R = R*b
|
|
1010
|
+
}
|
|
1011
|
+
return R;
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Square root for a finite field. Will try optimized versions first:
|
|
1016
|
+
*
|
|
1017
|
+
* 1. P ≡ 3 (mod 4)
|
|
1018
|
+
* 2. P ≡ 5 (mod 8)
|
|
1019
|
+
* 3. P ≡ 9 (mod 16)
|
|
1020
|
+
* 4. Tonelli-Shanks algorithm
|
|
1021
|
+
*
|
|
1022
|
+
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
|
1023
|
+
* For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
|
|
1024
|
+
* (used for hash-to-curve).
|
|
1025
|
+
* @param P - Field order.
|
|
1026
|
+
* @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
|
|
1027
|
+
* behavior and this selector assumes prime-field-style integer moduli.
|
|
1028
|
+
* @throws If the field is unsupported or the square root does not exist. {@link Error}
|
|
1029
|
+
* @example
|
|
1030
|
+
* Choose the square-root helper appropriate for one field modulus.
|
|
1031
|
+
*
|
|
1032
|
+
* ```ts
|
|
1033
|
+
* import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
|
|
1034
|
+
* const Fp = Field(17n);
|
|
1035
|
+
* const sqrt = FpSqrt(17n)(Fp, 4n);
|
|
1036
|
+
* ```
|
|
1037
|
+
*/
|
|
1038
|
+
function FpSqrt(P) {
|
|
1039
|
+
aoddModulus(P, 'Fp.sqrt');
|
|
1040
|
+
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
|
1041
|
+
if (P % _4n$2 === _3n$1)
|
|
1042
|
+
return sqrt3mod4;
|
|
1043
|
+
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
|
1044
|
+
if (P % _8n === _5n)
|
|
1045
|
+
return sqrt5mod8;
|
|
1046
|
+
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
|
|
1047
|
+
if (P % _16n === _9n)
|
|
1048
|
+
return sqrt9mod16(P);
|
|
1049
|
+
// Tonelli-Shanks algorithm
|
|
1050
|
+
return tonelliShanks(P);
|
|
1051
|
+
}
|
|
1052
|
+
// prettier-ignore
|
|
1053
|
+
// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime
|
|
1054
|
+
// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and
|
|
1055
|
+
// field-specific extras like `isOdd` are left to the callers that actually need them.
|
|
1056
|
+
const FIELD_FIELDS = [
|
|
1057
|
+
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
|
1058
|
+
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
|
1059
|
+
'addN', 'subN', 'mulN', 'sqrN'
|
|
1060
|
+
];
|
|
1061
|
+
/**
|
|
1062
|
+
* @param field - Field implementation.
|
|
1063
|
+
* @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
|
|
1064
|
+
* does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
|
|
1065
|
+
* field-specific extras beyond positive `BYTES` / `BITS`.
|
|
1066
|
+
* @throws If the field shape or numeric metadata are invalid. {@link Error}
|
|
1067
|
+
* @example
|
|
1068
|
+
* Check that a field implementation exposes the operations curve code expects.
|
|
1069
|
+
*
|
|
1070
|
+
* ```ts
|
|
1071
|
+
* import { Field, validateField } from '@noble/curves/abstract/modular.js';
|
|
1072
|
+
* const Fp = validateField(Field(17n));
|
|
1073
|
+
* ```
|
|
1074
|
+
*/
|
|
1075
|
+
function validateField(field) {
|
|
1076
|
+
aobject(field, 'field');
|
|
1077
|
+
if (typeof field.ORDER !== 'bigint')
|
|
1078
|
+
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
|
|
1079
|
+
// Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /
|
|
1080
|
+
// infinite metadata breaks encoders and caches.
|
|
1081
|
+
asafenumber(field.BYTES, 'BYTES');
|
|
1082
|
+
asafenumber(field.BITS, 'BITS');
|
|
1083
|
+
for (const name of FIELD_FIELDS)
|
|
1084
|
+
afunction(field[name], 'field.' + name);
|
|
1085
|
+
// Runtime field implementations must expose positive byte/bit sizes; zero leaks through the
|
|
1086
|
+
// numeric shape checks above but still breaks encoding helpers and cached-length assumptions.
|
|
1087
|
+
if (field.BYTES < 1 || field.BITS < 1)
|
|
1088
|
+
throw new Error('invalid field: expected BYTES/BITS > 0');
|
|
1089
|
+
if (field.ORDER <= _1n$2)
|
|
1090
|
+
throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);
|
|
1091
|
+
return field;
|
|
1092
|
+
}
|
|
1093
|
+
// Generic field functions
|
|
1094
|
+
/**
|
|
1095
|
+
* Same as `pow` but for Fp: non-constant-time.
|
|
1096
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
1097
|
+
* @param Fp - Field implementation.
|
|
1098
|
+
* @param num - Base value.
|
|
1099
|
+
* @param power - Exponent value.
|
|
1100
|
+
* @returns Powered field element.
|
|
1101
|
+
* @throws If the exponent is negative. {@link Error}
|
|
1102
|
+
* @example
|
|
1103
|
+
* Raise one field element to a public exponent.
|
|
1104
|
+
*
|
|
1105
|
+
* ```ts
|
|
1106
|
+
* import { Field, FpPow } from '@noble/curves/abstract/modular.js';
|
|
1107
|
+
* const Fp = Field(17n);
|
|
1108
|
+
* const x = FpPow(Fp, 3n, 5n);
|
|
1109
|
+
* ```
|
|
1110
|
+
*/
|
|
1111
|
+
function FpPow(Fp, num, power) {
|
|
1112
|
+
validateField(Fp);
|
|
1113
|
+
const F = Fp;
|
|
1114
|
+
// Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to
|
|
1115
|
+
// false and would silently return ONE.
|
|
1116
|
+
if (typeof power !== 'bigint')
|
|
1117
|
+
throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);
|
|
1118
|
+
if (power < _0n$3)
|
|
1119
|
+
throw new Error('invalid exponent, negatives unsupported');
|
|
1120
|
+
if (power === _0n$3)
|
|
1121
|
+
return F.ONE;
|
|
1122
|
+
if (power === _1n$2)
|
|
1123
|
+
return num;
|
|
1124
|
+
if (power < POW_WINDOWED_MIN) {
|
|
1125
|
+
// Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon
|
|
1126
|
+
// sbox x^5), which would waste the 14-multiplication table build.
|
|
1127
|
+
let p = F.ONE;
|
|
1128
|
+
let d = num;
|
|
1129
|
+
while (power > _0n$3) {
|
|
1130
|
+
if (power & _1n$2)
|
|
1131
|
+
p = F.mul(p, d);
|
|
1132
|
+
d = F.sqr(d);
|
|
1133
|
+
power >>= _1n$2;
|
|
1134
|
+
}
|
|
1135
|
+
return p;
|
|
1136
|
+
}
|
|
1137
|
+
// Fixed 4-bit windows, MSB-first — same shape as pow() above, over generic field ops.
|
|
1138
|
+
// Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).
|
|
1139
|
+
const digits = [];
|
|
1140
|
+
while (power > _0n$3) {
|
|
1141
|
+
digits.push(Number(power & _15n));
|
|
1142
|
+
power >>= _4n$2;
|
|
1143
|
+
}
|
|
1144
|
+
const table = new Array(16);
|
|
1145
|
+
table[0] = F.ONE;
|
|
1146
|
+
table[1] = num;
|
|
1147
|
+
for (let i = 2; i < 16; i++)
|
|
1148
|
+
table[i] = F.mul(table[i - 1], num);
|
|
1149
|
+
let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0
|
|
1150
|
+
for (let w = digits.length - 2; w >= 0; w--) {
|
|
1151
|
+
p = F.sqr(F.sqr(F.sqr(F.sqr(p))));
|
|
1152
|
+
const digit = digits[w];
|
|
1153
|
+
if (digit !== 0)
|
|
1154
|
+
p = F.mul(p, table[digit]);
|
|
1155
|
+
}
|
|
1156
|
+
return p;
|
|
1157
|
+
}
|
|
1158
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
1159
|
+
validateField(Fp);
|
|
1160
|
+
aarray(nums, 'nums');
|
|
1161
|
+
abool(passZero, 'passZero');
|
|
1162
|
+
const F = Fp;
|
|
1163
|
+
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);
|
|
1164
|
+
// Walk from first to last, multiply them by each other MOD p
|
|
1165
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
1166
|
+
if (F.is0(num))
|
|
1167
|
+
return acc;
|
|
1168
|
+
inverted[i] = acc;
|
|
1169
|
+
return F.mul(acc, num);
|
|
1170
|
+
}, F.ONE);
|
|
1171
|
+
// Invert last element
|
|
1172
|
+
const invertedAcc = F.inv(multipliedAcc);
|
|
1173
|
+
// Walk from last to first, multiply them by inverted each other MOD p
|
|
1174
|
+
nums.reduceRight((acc, num, i) => {
|
|
1175
|
+
if (F.is0(num))
|
|
1176
|
+
return acc;
|
|
1177
|
+
// Non-zero `num` means the forward pass already stored a defined prefix product at index i.
|
|
1178
|
+
inverted[i] = F.mul(acc, inverted[i]);
|
|
1179
|
+
return F.mul(acc, num);
|
|
1180
|
+
}, invertedAcc);
|
|
1181
|
+
return inverted;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Legendre symbol.
|
|
1185
|
+
* Legendre constant is used to calculate Legendre symbol (a | p)
|
|
1186
|
+
* which denotes the value of a^((p-1)/2) (mod p).
|
|
1187
|
+
*
|
|
1188
|
+
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
|
1189
|
+
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
|
1190
|
+
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
|
1191
|
+
* @param Fp - Field implementation.
|
|
1192
|
+
* @param n - Value to inspect.
|
|
1193
|
+
* @returns Legendre symbol.
|
|
1194
|
+
* @throws If the powered value does not match a valid Legendre symbol. {@link Error}
|
|
1195
|
+
* @example
|
|
1196
|
+
* Compute the Legendre symbol of one field element.
|
|
1197
|
+
*
|
|
1198
|
+
* ```ts
|
|
1199
|
+
* import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
|
|
1200
|
+
* const Fp = Field(17n);
|
|
1201
|
+
* const symbol = FpLegendre(Fp, 4n);
|
|
1202
|
+
* ```
|
|
1203
|
+
*/
|
|
1204
|
+
function FpLegendre(Fp, n) {
|
|
1205
|
+
validateField(Fp);
|
|
1206
|
+
const F = Fp;
|
|
1207
|
+
aoddModulus(F.ORDER, 'FpLegendre');
|
|
1208
|
+
// We can use 3rd argument as optional cache of this value
|
|
1209
|
+
// but seems unneeded for now. The operation is very fast.
|
|
1210
|
+
const p1mod2 = (F.ORDER - _1n$2) / _2n$1;
|
|
1211
|
+
const powered = F.pow(n, p1mod2);
|
|
1212
|
+
const yes = F.eql(powered, F.ONE);
|
|
1213
|
+
const zero = F.eql(powered, F.ZERO);
|
|
1214
|
+
const no = F.eql(powered, F.neg(F.ONE));
|
|
1215
|
+
if (!yes && !zero && !no)
|
|
1216
|
+
throw new Error('invalid Legendre symbol result');
|
|
1217
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* @param Fp - Field implementation.
|
|
1221
|
+
* @param n - Value to inspect.
|
|
1222
|
+
* @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic
|
|
1223
|
+
* residue" terminology often reserves that name for the non-zero square class.
|
|
1224
|
+
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
|
1225
|
+
* @example
|
|
1226
|
+
* Check whether one field element has a square root in the field.
|
|
1227
|
+
*
|
|
1228
|
+
* ```ts
|
|
1229
|
+
* import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';
|
|
1230
|
+
* const Fp = Field(17n);
|
|
1231
|
+
* const isSquare = FpIsSquare(Fp, 4n);
|
|
1232
|
+
* ```
|
|
1233
|
+
*/
|
|
1234
|
+
function FpIsSquare(Fp, n) {
|
|
1235
|
+
const l = FpLegendre(Fp, n);
|
|
1236
|
+
// Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.
|
|
1237
|
+
return l !== -1;
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* @param n - Curve order. Callers are expected to pass a positive order.
|
|
1241
|
+
* @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
|
|
1242
|
+
* value when overriding the derived bit length.
|
|
1243
|
+
* @returns Byte and bit lengths.
|
|
1244
|
+
* @throws If the order or cached bit length is invalid. {@link Error}
|
|
1245
|
+
* @example
|
|
1246
|
+
* Measure the encoding sizes needed for one modulus.
|
|
1247
|
+
*
|
|
1248
|
+
* ```ts
|
|
1249
|
+
* nLength(255n);
|
|
1250
|
+
* ```
|
|
1251
|
+
*/
|
|
1252
|
+
function nLength(n, nBitLength) {
|
|
1253
|
+
// Bit size, byte size of CURVE.n
|
|
1254
|
+
if (nBitLength !== undefined)
|
|
1255
|
+
anumber(nBitLength);
|
|
1256
|
+
if (n <= _0n$3)
|
|
1257
|
+
throw new Error('invalid n length: expected positive n, got ' + n);
|
|
1258
|
+
if (nBitLength !== undefined && nBitLength < 1)
|
|
1259
|
+
throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);
|
|
1260
|
+
const bits = bitLen(n);
|
|
1261
|
+
// Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison
|
|
1262
|
+
// any math that relies on the derived field metadata.
|
|
1263
|
+
if (nBitLength !== undefined && nBitLength < bits)
|
|
1264
|
+
throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
|
|
1265
|
+
const _nBitLength = nBitLength !== undefined ? nBitLength : bits;
|
|
1266
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
1267
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
1268
|
+
}
|
|
1269
|
+
// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the
|
|
1270
|
+
// cached helper write would keep the field surface externally mutable.
|
|
1271
|
+
const FIELD_SQRT = new WeakMap();
|
|
1272
|
+
class _Field {
|
|
1273
|
+
ORDER;
|
|
1274
|
+
BITS;
|
|
1275
|
+
BYTES;
|
|
1276
|
+
isLE;
|
|
1277
|
+
ZERO = _0n$3;
|
|
1278
|
+
ONE = _1n$2;
|
|
1279
|
+
_lengths;
|
|
1280
|
+
_mod;
|
|
1281
|
+
constructor(ORDER, opts = {}) {
|
|
1282
|
+
// ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv
|
|
1283
|
+
// would stop modeling field arithmetic.
|
|
1284
|
+
if (ORDER <= _1n$2)
|
|
1285
|
+
throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);
|
|
1286
|
+
let _nbitLength = undefined;
|
|
1287
|
+
this.isLE = false;
|
|
1288
|
+
if (opts != null && typeof opts === 'object') {
|
|
1289
|
+
// Cached bit lengths are trusted here and should already be positive / consistent with ORDER.
|
|
1290
|
+
if (typeof opts.BITS === 'number')
|
|
1291
|
+
_nbitLength = opts.BITS;
|
|
1292
|
+
if (typeof opts.sqrt === 'function')
|
|
1293
|
+
// `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties
|
|
1294
|
+
// explicitly instead of relying on writable prototype shadowing via assignment.
|
|
1295
|
+
Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });
|
|
1296
|
+
if (typeof opts.isLE === 'boolean')
|
|
1297
|
+
this.isLE = opts.isLE;
|
|
1298
|
+
if (opts.allowedLengths)
|
|
1299
|
+
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
|
1300
|
+
if (typeof opts.modFromBytes === 'boolean')
|
|
1301
|
+
this._mod = opts.modFromBytes;
|
|
1302
|
+
}
|
|
1303
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
1304
|
+
if (nByteLength > 2048)
|
|
1305
|
+
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
|
1306
|
+
this.ORDER = ORDER;
|
|
1307
|
+
this.BITS = nBitLength;
|
|
1308
|
+
this.BYTES = nByteLength;
|
|
1309
|
+
Object.freeze(this);
|
|
1310
|
+
}
|
|
1311
|
+
create(num) {
|
|
1312
|
+
return mod(num, this.ORDER);
|
|
1313
|
+
}
|
|
1314
|
+
isValid(num) {
|
|
1315
|
+
if (typeof num !== 'bigint')
|
|
1316
|
+
throw new TypeError('invalid field element: expected bigint, got ' + typeof num);
|
|
1317
|
+
return _0n$3 <= num && num < this.ORDER; // 0 is valid element, but it's not invertible
|
|
1318
|
+
}
|
|
1319
|
+
is0(num) {
|
|
1320
|
+
return num === _0n$3;
|
|
1321
|
+
}
|
|
1322
|
+
// is valid and invertible
|
|
1323
|
+
isValidNot0(num) {
|
|
1324
|
+
return !this.is0(num) && this.isValid(num);
|
|
1325
|
+
}
|
|
1326
|
+
isOdd(num) {
|
|
1327
|
+
return (num & _1n$2) === _1n$2;
|
|
1328
|
+
}
|
|
1329
|
+
neg(num) {
|
|
1330
|
+
return mod(-num, this.ORDER);
|
|
1331
|
+
}
|
|
1332
|
+
eql(lhs, rhs) {
|
|
1333
|
+
return lhs === rhs;
|
|
1334
|
+
}
|
|
1335
|
+
sqr(num) {
|
|
1336
|
+
return mod(num * num, this.ORDER);
|
|
1337
|
+
}
|
|
1338
|
+
add(lhs, rhs) {
|
|
1339
|
+
return mod(lhs + rhs, this.ORDER);
|
|
1340
|
+
}
|
|
1341
|
+
sub(lhs, rhs) {
|
|
1342
|
+
return mod(lhs - rhs, this.ORDER);
|
|
1343
|
+
}
|
|
1344
|
+
mul(lhs, rhs) {
|
|
1345
|
+
return mod(lhs * rhs, this.ORDER);
|
|
1346
|
+
}
|
|
1347
|
+
pow(num, power) {
|
|
1348
|
+
return pow(num, power, this.ORDER);
|
|
1349
|
+
}
|
|
1350
|
+
div(lhs, rhs) {
|
|
1351
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
1352
|
+
}
|
|
1353
|
+
// Same as above, but doesn't normalize
|
|
1354
|
+
sqrN(num) {
|
|
1355
|
+
return num * num;
|
|
1356
|
+
}
|
|
1357
|
+
addN(lhs, rhs) {
|
|
1358
|
+
return lhs + rhs;
|
|
1359
|
+
}
|
|
1360
|
+
subN(lhs, rhs) {
|
|
1361
|
+
return lhs - rhs;
|
|
1362
|
+
}
|
|
1363
|
+
mulN(lhs, rhs) {
|
|
1364
|
+
return lhs * rhs;
|
|
1365
|
+
}
|
|
1366
|
+
inv(num) {
|
|
1367
|
+
return invert(num, this.ORDER);
|
|
1368
|
+
}
|
|
1369
|
+
sqrt(num) {
|
|
1370
|
+
// Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping
|
|
1371
|
+
// the field instance itself mutable.
|
|
1372
|
+
let sqrt = FIELD_SQRT.get(this);
|
|
1373
|
+
if (!sqrt)
|
|
1374
|
+
FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));
|
|
1375
|
+
return sqrt(this, num);
|
|
1376
|
+
}
|
|
1377
|
+
toBytes(num) {
|
|
1378
|
+
// Serialize fixed-width limbs without re-validating the field range. Callers that need a
|
|
1379
|
+
// canonical encoding must pass a valid element; some protocols intentionally serialize raw
|
|
1380
|
+
// residues here and reduce or validate them elsewhere.
|
|
1381
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
1382
|
+
}
|
|
1383
|
+
fromBytes(bytes, skipValidation = false) {
|
|
1384
|
+
abytes(bytes);
|
|
1385
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
1386
|
+
if (allowedLengths) {
|
|
1387
|
+
// `allowedLengths` must list real positive byte lengths; otherwise empty input would get
|
|
1388
|
+
// padded into zero and silently decode as a field element.
|
|
1389
|
+
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
1390
|
+
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
|
|
1391
|
+
}
|
|
1392
|
+
const padded = new Uint8Array(BYTES);
|
|
1393
|
+
// isLE add 0 to right, !isLE to the left.
|
|
1394
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
1395
|
+
bytes = padded;
|
|
1396
|
+
}
|
|
1397
|
+
if (bytes.length !== BYTES)
|
|
1398
|
+
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
|
1399
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
1400
|
+
if (modFromBytes)
|
|
1401
|
+
scalar = mod(scalar, ORDER);
|
|
1402
|
+
if (!skipValidation)
|
|
1403
|
+
if (!this.isValid(scalar))
|
|
1404
|
+
throw new Error('invalid field element: outside of range 0..ORDER');
|
|
1405
|
+
// Range validation is optional here because some protocols intentionally decode raw residues
|
|
1406
|
+
// and reduce or validate them elsewhere.
|
|
1407
|
+
return scalar;
|
|
1408
|
+
}
|
|
1409
|
+
// TODO: we don't need it here, move out to separate fn
|
|
1410
|
+
invertBatch(lst) {
|
|
1411
|
+
// `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking
|
|
1412
|
+
// `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use
|
|
1413
|
+
// `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.
|
|
1414
|
+
return FpInvertBatch(this, lst, true);
|
|
1415
|
+
}
|
|
1416
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
1417
|
+
// and it's unclear what to return in there.
|
|
1418
|
+
cmov(a, b, condition) {
|
|
1419
|
+
// Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject
|
|
1420
|
+
// non-boolean selectors here instead of letting JS truthiness silently change arithmetic.
|
|
1421
|
+
abool(condition, 'condition');
|
|
1422
|
+
return condition ? b : a;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Creates a finite field. Major performance optimizations:
|
|
1427
|
+
* * 1. Denormalized operations like mulN instead of mul.
|
|
1428
|
+
* * 2. Identical object shape: never add or remove keys.
|
|
1429
|
+
* * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
|
|
1430
|
+
* Fragile: always run a benchmark on a change.
|
|
1431
|
+
* Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
|
|
1432
|
+
* all elements for performance and protocol-flexibility reasons; callers are responsible for
|
|
1433
|
+
* supplying valid elements when they need canonical field behavior.
|
|
1434
|
+
* This is low-level code, please make sure you know what you're doing.
|
|
1435
|
+
*
|
|
1436
|
+
* Note about field properties:
|
|
1437
|
+
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
|
1438
|
+
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
|
1439
|
+
*
|
|
1440
|
+
* @param ORDER - field order, probably prime, or could be composite
|
|
1441
|
+
* @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
|
|
1442
|
+
* @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
|
|
1443
|
+
* into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
|
|
1444
|
+
* @example
|
|
1445
|
+
* Construct one prime field with optional overrides.
|
|
1446
|
+
*
|
|
1447
|
+
* ```ts
|
|
1448
|
+
* Field(11n);
|
|
1449
|
+
* ```
|
|
1450
|
+
*/
|
|
1451
|
+
function Field(ORDER, opts = {}) {
|
|
1452
|
+
// Freeze the shared method surface before any instance is reachable; otherwise callers can
|
|
1453
|
+
// poison every Field instance by monkey-patching `_Field.prototype` even if each instance is
|
|
1454
|
+
// frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers
|
|
1455
|
+
// that never construct a field; the call is idempotent and cheap.
|
|
1456
|
+
Object.freeze(_Field.prototype);
|
|
1457
|
+
return new _Field(ORDER, opts);
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Returns total number of bytes consumed by the field element.
|
|
1461
|
+
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
|
1462
|
+
* @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
|
|
1463
|
+
* order greater than 1.
|
|
1464
|
+
* @returns byte length of field
|
|
1465
|
+
* @throws If the field order is not a bigint. {@link Error}
|
|
1466
|
+
* @example
|
|
1467
|
+
* Read the fixed-width byte length of one field.
|
|
1468
|
+
*
|
|
1469
|
+
* ```ts
|
|
1470
|
+
* getFieldBytesLength(255n);
|
|
1471
|
+
* ```
|
|
1472
|
+
*/
|
|
1473
|
+
function getFieldBytesLength(fieldOrder) {
|
|
1474
|
+
if (typeof fieldOrder !== 'bigint')
|
|
1475
|
+
throw new Error('field order must be bigint');
|
|
1476
|
+
// Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.
|
|
1477
|
+
if (fieldOrder <= _1n$2)
|
|
1478
|
+
throw new Error('field order must be greater than 1');
|
|
1479
|
+
// Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.
|
|
1480
|
+
const bitLength = bitLen(fieldOrder - _1n$2);
|
|
1481
|
+
return Math.ceil(bitLength / 8);
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Returns minimal amount of bytes that can be safely reduced
|
|
1485
|
+
* by field order.
|
|
1486
|
+
* Should be 2^-128 for 128-bit curve such as P256.
|
|
1487
|
+
* This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
|
|
1488
|
+
* absolute floor for policy reasons.
|
|
1489
|
+
* @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
|
|
1490
|
+
* @returns byte length of target hash
|
|
1491
|
+
* @throws If the field order is invalid. {@link Error}
|
|
1492
|
+
* @example
|
|
1493
|
+
* Compute the minimum hash length needed for field reduction.
|
|
1494
|
+
*
|
|
1495
|
+
* ```ts
|
|
1496
|
+
* getMinHashLength(255n);
|
|
1497
|
+
* ```
|
|
1498
|
+
*/
|
|
1499
|
+
function getMinHashLength(fieldOrder) {
|
|
1500
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
1501
|
+
return length + Math.ceil(length / 2);
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* "Constant-time" private key generation utility.
|
|
1505
|
+
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
|
1506
|
+
* and convert them into private scalar, with the modulo bias being negligible.
|
|
1507
|
+
* Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
|
|
1508
|
+
* 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
|
|
1509
|
+
* accidentally acceptable for real scalar derivation.
|
|
1510
|
+
* See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},
|
|
1511
|
+
* {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
|
|
1512
|
+
* {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
|
|
1513
|
+
* `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
|
|
1514
|
+
* @param key - Uniform input bytes.
|
|
1515
|
+
* @param fieldOrder - Size of subgroup.
|
|
1516
|
+
* @param isLE - interpret hash bytes as LE num
|
|
1517
|
+
* @returns valid private scalar
|
|
1518
|
+
* @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
|
|
1519
|
+
* @example
|
|
1520
|
+
* Map hash output into a private scalar range.
|
|
1521
|
+
*
|
|
1522
|
+
* ```ts
|
|
1523
|
+
* mapHashToField(new Uint8Array(48).fill(1), 255n);
|
|
1524
|
+
* ```
|
|
1525
|
+
*/
|
|
1526
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
1527
|
+
abytes(key);
|
|
1528
|
+
const len = key.length;
|
|
1529
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
1530
|
+
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
|
|
1531
|
+
// No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge
|
|
1532
|
+
// inputs: easier to reason about JS timing / allocation behavior.
|
|
1533
|
+
if (len < minLen || len > 1024)
|
|
1534
|
+
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
|
1535
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
1536
|
+
// Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in
|
|
1537
|
+
// [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to
|
|
1538
|
+
// `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias
|
|
1539
|
+
// remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is
|
|
1540
|
+
// required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.
|
|
1541
|
+
const reduced = mod(num, fieldOrder - _1n$2) + _1n$2;
|
|
1542
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
/**
|
|
1546
|
+
* Methods for elliptic curve multiplication by scalars.
|
|
1547
|
+
* Contains wNAF-based ScalarMultiplier, pippenger.
|
|
1548
|
+
* @module
|
|
1549
|
+
*/
|
|
1550
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1551
|
+
const _0n$2 = /* @__PURE__ */ BigInt(0);
|
|
1552
|
+
const _1n$1 = /* @__PURE__ */ BigInt(1);
|
|
1553
|
+
const _4n$1 = /* @__PURE__ */ BigInt(4);
|
|
1554
|
+
const BLIND_BYTES = 16;
|
|
1555
|
+
const BLIND_BITS = 128;
|
|
1556
|
+
// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).
|
|
1557
|
+
// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single
|
|
1558
|
+
// multiply, unlike the larger per-point wNAF tables that only pay off when cached.
|
|
1559
|
+
const FW_WINDOW = 5;
|
|
1560
|
+
// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front
|
|
1561
|
+
// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an
|
|
1562
|
+
// effective hang) when the lazy table is built on first multiply.
|
|
1563
|
+
const TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
|
|
1564
|
+
/**
|
|
1565
|
+
* Validates the static surface of a point constructor.
|
|
1566
|
+
* This is only a cheap sanity check for the constructor hooks and fields consumed by generic
|
|
1567
|
+
* factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
|
|
1568
|
+
* @param Point - Runtime point constructor.
|
|
1569
|
+
* @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
|
|
1570
|
+
* @example
|
|
1571
|
+
* Check that one point constructor exposes the static hooks generic helpers need.
|
|
1572
|
+
*
|
|
1573
|
+
* ```ts
|
|
1574
|
+
* import { ed25519 } from '@noble/curves/ed25519.js';
|
|
1575
|
+
* import { validatePointCons } from '@noble/curves/abstract/curve.js';
|
|
1576
|
+
* validatePointCons(ed25519.Point);
|
|
1577
|
+
* ```
|
|
1578
|
+
*/
|
|
1579
|
+
function validatePointCons(Point) {
|
|
1580
|
+
const pc = Point;
|
|
1581
|
+
if (typeof pc !== 'function')
|
|
1582
|
+
throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
|
|
1583
|
+
afunction(pc.fromAffine, 'Point.fromAffine');
|
|
1584
|
+
afunction(pc.fromBytes, 'Point.fromBytes');
|
|
1585
|
+
afunction(pc.fromHex, 'Point.fromHex');
|
|
1586
|
+
// Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:
|
|
1587
|
+
// fail here with a typed error instead of an `undefined` access later.
|
|
1588
|
+
aobject(pc.BASE, 'Point.BASE');
|
|
1589
|
+
aobject(pc.ZERO, 'Point.ZERO');
|
|
1590
|
+
validateField(pc.Fp);
|
|
1591
|
+
validateField(pc.Fn);
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Takes a bunch of Projective Points but executes only one
|
|
1595
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
1596
|
+
* so this improves performance massively.
|
|
1597
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
1598
|
+
* Input points are left unchanged; the normalized points are returned as fresh instances.
|
|
1599
|
+
* @param c - Point constructor.
|
|
1600
|
+
* @param points - Projective points.
|
|
1601
|
+
* @returns Fresh projective points reconstructed from normalized affine coordinates.
|
|
1602
|
+
* @example
|
|
1603
|
+
* Batch-normalize projective points with a single shared inversion.
|
|
1604
|
+
*
|
|
1605
|
+
* ```ts
|
|
1606
|
+
* import { normalizeZ } from '@noble/curves/abstract/curve.js';
|
|
1607
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
1608
|
+
* const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
|
|
1609
|
+
* ```
|
|
1610
|
+
*/
|
|
1611
|
+
function normalizeZ(c, points) {
|
|
1612
|
+
// Match MSM helpers: reject malformed public inputs before reading projective internals.
|
|
1613
|
+
validatePointCons(c);
|
|
1614
|
+
validateMSMPoints(points, c);
|
|
1615
|
+
// Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`
|
|
1616
|
+
// yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal
|
|
1617
|
+
// is0 handling instead of using the batch inverse.
|
|
1618
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
1619
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
1620
|
+
}
|
|
1621
|
+
function validateW(W, bits, min = 1) {
|
|
1622
|
+
if (!Number.isSafeInteger(W) || W < min || W > bits)
|
|
1623
|
+
throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);
|
|
1624
|
+
}
|
|
1625
|
+
// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended
|
|
1626
|
+
// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the
|
|
1627
|
+
// largest table the checked parameters can produce.
|
|
1628
|
+
function validateTableBytes(numPoints, fpBytes) {
|
|
1629
|
+
const bytes = numPoints * (4 * fpBytes + 128);
|
|
1630
|
+
if (bytes > TABLE_BYTES_MAX)
|
|
1631
|
+
throw new Error('invalid window size: table would need ~' +
|
|
1632
|
+
Math.ceil(bytes / 2 ** 20) +
|
|
1633
|
+
' MiB, max ' +
|
|
1634
|
+
TABLE_BYTES_MAX / 2 ** 20 +
|
|
1635
|
+
' MiB');
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Probes an RNG once, at construction time: returns `undefined` when it is unavailable —
|
|
1639
|
+
* throws or returns malformed bytes — so callers can downgrade to their unblinded /
|
|
1640
|
+
* deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template
|
|
1641
|
+
* hardening), not a correctness or key-secrecy requirement, so availability-based
|
|
1642
|
+
* downgrade is acceptable.
|
|
1643
|
+
*
|
|
1644
|
+
* The downgrade decision is deliberately static. After a successful probe the RNG becomes
|
|
1645
|
+
* part of the trusted contract: later misbehavior must fail closed in per-call validation
|
|
1646
|
+
* (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip
|
|
1647
|
+
* blinding on demand. A probe can only ever classify broken environments, not adversarial
|
|
1648
|
+
* RNGs: a stateful RNG can always behave while probed and misbehave later.
|
|
1649
|
+
* @param randomBytes - RNG to probe, or `undefined` when the environment provides none.
|
|
1650
|
+
* @param length - Byte length requested from the probe call.
|
|
1651
|
+
* @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.
|
|
1652
|
+
* @example
|
|
1653
|
+
* Probe an RNG once before enabling scalar blinding.
|
|
1654
|
+
*
|
|
1655
|
+
* ```ts
|
|
1656
|
+
* import { probeRandomBytes } from '@noble/curves/abstract/curve.js';
|
|
1657
|
+
* import { randomBytes } from '@noble/hashes/utils.js';
|
|
1658
|
+
* const rng = probeRandomBytes(randomBytes, 16);
|
|
1659
|
+
* ```
|
|
1660
|
+
*/
|
|
1661
|
+
function probeRandomBytes(randomBytes, length) {
|
|
1662
|
+
if (randomBytes === undefined)
|
|
1663
|
+
return undefined;
|
|
1664
|
+
afunction(randomBytes, 'randomBytes');
|
|
1665
|
+
try {
|
|
1666
|
+
const probe = randomBytes(length);
|
|
1667
|
+
if (!isBytes(probe) || probe.length !== length)
|
|
1668
|
+
return undefined;
|
|
1669
|
+
}
|
|
1670
|
+
catch {
|
|
1671
|
+
return undefined;
|
|
1672
|
+
}
|
|
1673
|
+
return randomBytes;
|
|
1674
|
+
}
|
|
1675
|
+
function validateMSMPoints(points, c) {
|
|
1676
|
+
aarray(points, 'points');
|
|
1677
|
+
points.forEach((p, i) => {
|
|
1678
|
+
if (!(p instanceof c))
|
|
1679
|
+
throw new Error('invalid point at index ' + i);
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it
|
|
1683
|
+
// to 0 <= s < maxScalar for callers that accept oversized scalars.
|
|
1684
|
+
function validateMSMScalars(scalars, field, maxScalar) {
|
|
1685
|
+
if (!Array.isArray(scalars))
|
|
1686
|
+
throw new Error('array of scalars expected');
|
|
1687
|
+
scalars.forEach((s, i) => {
|
|
1688
|
+
const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;
|
|
1689
|
+
if (!ok)
|
|
1690
|
+
throw new Error('invalid scalar at index ' + i);
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1693
|
+
const pointWindowSizes = new WeakMap();
|
|
1694
|
+
function getWindowSize(P) {
|
|
1695
|
+
// `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.
|
|
1696
|
+
return pointWindowSizes.get(P) || 1;
|
|
1697
|
+
}
|
|
1698
|
+
/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */
|
|
1699
|
+
function oddMultiples(p, size) {
|
|
1700
|
+
const dbl = p.double();
|
|
1701
|
+
const t = [p];
|
|
1702
|
+
for (let j = 1; j < size; j++)
|
|
1703
|
+
t.push(t[j - 1].add(dbl));
|
|
1704
|
+
return t;
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with
|
|
1708
|
+
* |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).
|
|
1709
|
+
*/
|
|
1710
|
+
function wnafDigits(n, W) {
|
|
1711
|
+
const size = 2 ** W;
|
|
1712
|
+
const half = size / 2;
|
|
1713
|
+
const mask = BigInt(size - 1);
|
|
1714
|
+
const d = [];
|
|
1715
|
+
while (n > _0n$2) {
|
|
1716
|
+
let w = 0;
|
|
1717
|
+
if (n & _1n$1) {
|
|
1718
|
+
w = Number(n & mask); // n mod 2^W, odd
|
|
1719
|
+
if (w >= half)
|
|
1720
|
+
w -= size; // signed residue
|
|
1721
|
+
n -= BigInt(w); // n - w ≡ 0 mod 2^W: next W−1 digits are zero
|
|
1722
|
+
}
|
|
1723
|
+
d.push(w);
|
|
1724
|
+
n >>= _1n$1;
|
|
1725
|
+
}
|
|
1726
|
+
return d;
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with
|
|
1730
|
+
* digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one
|
|
1731
|
+
* extra window for the final carry), so recoding length does not depend on the scalar.
|
|
1732
|
+
*/
|
|
1733
|
+
function signedWindowDigits(n, W, windows) {
|
|
1734
|
+
const size = 2 ** W;
|
|
1735
|
+
const half = size / 2;
|
|
1736
|
+
const mask = BigInt(size - 1);
|
|
1737
|
+
const shiftBy = BigInt(W);
|
|
1738
|
+
const d = [];
|
|
1739
|
+
for (let w = 0; w < windows; w++) {
|
|
1740
|
+
let v = Number(n & mask);
|
|
1741
|
+
n >>= shiftBy;
|
|
1742
|
+
if (v > half) {
|
|
1743
|
+
v -= size; // negative digit, carry into the next window
|
|
1744
|
+
n += _1n$1;
|
|
1745
|
+
}
|
|
1746
|
+
d.push(v);
|
|
1747
|
+
}
|
|
1748
|
+
// Internal invariant: leftover bits mean the window count did not cover the scalar.
|
|
1749
|
+
if (n !== _0n$2)
|
|
1750
|
+
throw new Error('invalid wnaf');
|
|
1751
|
+
return d;
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared
|
|
1755
|
+
* accumulator per bit position of the longest recoding, one signed table addition per
|
|
1756
|
+
* nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.
|
|
1757
|
+
*/
|
|
1758
|
+
function wnafWalk(zero, tables, digits) {
|
|
1759
|
+
let max = 0;
|
|
1760
|
+
for (const d of digits)
|
|
1761
|
+
max = Math.max(max, d.length);
|
|
1762
|
+
let acc = zero;
|
|
1763
|
+
for (let bit = max - 1; bit >= 0; bit--) {
|
|
1764
|
+
if (bit !== max - 1)
|
|
1765
|
+
acc = acc.double();
|
|
1766
|
+
for (let i = 0; i < digits.length; i++) {
|
|
1767
|
+
const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below
|
|
1768
|
+
if (w) {
|
|
1769
|
+
const item = tables[i][(Math.abs(w) - 1) >> 1];
|
|
1770
|
+
acc = acc.add(w < 0 ? item.negate() : item);
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
return acc;
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Elliptic curve multiplication of Point by scalar.
|
|
1778
|
+
* Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate
|
|
1779
|
+
* their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the
|
|
1780
|
+
* `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).
|
|
1781
|
+
* Table generation is expensive and happens on first call of `multiply()`
|
|
1782
|
+
* (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.
|
|
1783
|
+
*
|
|
1784
|
+
* Cached algorithm is signed fixed-window wNAF:
|
|
1785
|
+
* - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings
|
|
1786
|
+
* are baked in, so a multiplication is exactly one table addition per window
|
|
1787
|
+
* - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent
|
|
1788
|
+
* (basis of the constant-time path)
|
|
1789
|
+
* - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply
|
|
1790
|
+
* - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which
|
|
1791
|
+
* widens tables by 128 bits
|
|
1792
|
+
* @param Point - Point constructor.
|
|
1793
|
+
* @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.
|
|
1794
|
+
* @example
|
|
1795
|
+
* Elliptic curve multiplication of Point by scalar.
|
|
1796
|
+
*
|
|
1797
|
+
* ```ts
|
|
1798
|
+
* import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';
|
|
1799
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
1800
|
+
* const mul = new ScalarMultiplier(p256.Point);
|
|
1801
|
+
* ```
|
|
1802
|
+
*/
|
|
1803
|
+
class ScalarMultiplier {
|
|
1804
|
+
Point;
|
|
1805
|
+
BASE;
|
|
1806
|
+
ZERO;
|
|
1807
|
+
randomBytes;
|
|
1808
|
+
wnafPrecomputes = new WeakMap();
|
|
1809
|
+
baseCanBeBlinded;
|
|
1810
|
+
bits;
|
|
1811
|
+
// Parametrized with a given Point class (not individual point)
|
|
1812
|
+
constructor(Point, randomBytes) {
|
|
1813
|
+
validatePointCons(Point);
|
|
1814
|
+
// Probe the RNG once (see {@link probeRandomBytes}): in environments without working
|
|
1815
|
+
// randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the
|
|
1816
|
+
// unblinded constant-time path instead of throwing on every multiply(). The shape of
|
|
1817
|
+
// returned bytes is still validated on every blinded call, where breakage fails closed.
|
|
1818
|
+
this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);
|
|
1819
|
+
this.Point = Point;
|
|
1820
|
+
this.BASE = Point.BASE;
|
|
1821
|
+
this.ZERO = Point.ZERO;
|
|
1822
|
+
this.bits = Point.Fn.BITS;
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Creates a signed fixed-window wNAF precomputation table: for every window w, the
|
|
1826
|
+
* multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
|
|
1827
|
+
* so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
|
|
1828
|
+
* window absorbs the final carry of signed-digit recoding.
|
|
1829
|
+
* For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
|
|
1830
|
+
* @param point - Point instance
|
|
1831
|
+
* @param W - window size
|
|
1832
|
+
* @param bits - scalar bitlength the table must cover
|
|
1833
|
+
*/
|
|
1834
|
+
buildWnafTable(point, W, bits) {
|
|
1835
|
+
// W needs no re-validation: its only source is setWindowSize(), which enforces
|
|
1836
|
+
// 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the
|
|
1837
|
+
// resulting table at ~2 GiB (sized against the wider blinded layout).
|
|
1838
|
+
const windows = Math.ceil(bits / W) + 1;
|
|
1839
|
+
const half = 2 ** (W - 1);
|
|
1840
|
+
const comp = [];
|
|
1841
|
+
let base = point;
|
|
1842
|
+
for (let w = 0; w < windows; w++) {
|
|
1843
|
+
let acc = base;
|
|
1844
|
+
for (let i = 0; i < half; i++) {
|
|
1845
|
+
comp.push(acc);
|
|
1846
|
+
acc = acc.add(base);
|
|
1847
|
+
}
|
|
1848
|
+
base = comp[comp.length - 1].double(); // 2⋅(2^(W−1)⋅base) = next window's base
|
|
1849
|
+
}
|
|
1850
|
+
return { W, bits, windows, comp };
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Implements ec multiplication using precomputed signed fixed-window wNAF tables.
|
|
1854
|
+
* Constant-time: fixed window count with one table addition per window — zero digits feed
|
|
1855
|
+
* the fake accumulator — and no doublings; the lookup scans the whole window slice.
|
|
1856
|
+
* Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
|
|
1857
|
+
* {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
|
|
1858
|
+
* signedWindowDigits throws if `n` exceeds the table.
|
|
1859
|
+
* @returns real and fake (for const-time) points
|
|
1860
|
+
*/
|
|
1861
|
+
wnafCachedCT(precomputes, n) {
|
|
1862
|
+
const { W, windows, comp } = precomputes;
|
|
1863
|
+
const half = 2 ** (W - 1);
|
|
1864
|
+
const digits = signedWindowDigits(n, W, windows);
|
|
1865
|
+
let p = this.ZERO;
|
|
1866
|
+
let f = this.BASE;
|
|
1867
|
+
for (let w = 0; w < windows; w++) {
|
|
1868
|
+
const digit = digits[w];
|
|
1869
|
+
const start = w * half;
|
|
1870
|
+
// Data-oblivious select: touch every entry of the window before the digit branch.
|
|
1871
|
+
const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused
|
|
1872
|
+
let sel = comp[start];
|
|
1873
|
+
for (let i = 1; i < half; i++)
|
|
1874
|
+
sel = i === idx ? comp[start + i] : sel;
|
|
1875
|
+
const neg = sel.negate(); // compute both signs; the digit only picks one
|
|
1876
|
+
if (digit === 0)
|
|
1877
|
+
f = f.add(comp[start]);
|
|
1878
|
+
else
|
|
1879
|
+
p = p.add(digit < 0 ? neg : sel);
|
|
1880
|
+
}
|
|
1881
|
+
return { p, f };
|
|
1882
|
+
}
|
|
1883
|
+
// Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
|
|
1884
|
+
// `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
|
|
1885
|
+
// incompatible `transform(...)` layouts and expect a separate cache entry.
|
|
1886
|
+
getWnafPrecomputes(W, point, bits, transform) {
|
|
1887
|
+
let entries = this.wnafPrecomputes.get(point);
|
|
1888
|
+
let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
|
|
1889
|
+
if (!comp) {
|
|
1890
|
+
comp = this.buildWnafTable(point, W, bits);
|
|
1891
|
+
if (typeof transform === 'function')
|
|
1892
|
+
comp = { ...comp, comp: transform(comp.comp) };
|
|
1893
|
+
if (!entries) {
|
|
1894
|
+
entries = [];
|
|
1895
|
+
this.wnafPrecomputes.set(point, entries);
|
|
1896
|
+
}
|
|
1897
|
+
entries.push(comp);
|
|
1898
|
+
}
|
|
1899
|
+
return comp;
|
|
1900
|
+
}
|
|
1901
|
+
assertPoint(point) {
|
|
1902
|
+
if (!(point instanceof this.Point))
|
|
1903
|
+
throw new TypeError('"point" expected Point instance, got type=' + typeof point);
|
|
1904
|
+
}
|
|
1905
|
+
// Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
|
|
1906
|
+
// callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
|
|
1907
|
+
// Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
|
|
1908
|
+
validateMulInput(point, scalar) {
|
|
1909
|
+
this.assertPoint(point);
|
|
1910
|
+
if (!inRange(scalar, _1n$1, this.Point.Fn.ORDER))
|
|
1911
|
+
throw new Error('invalid scalar');
|
|
1912
|
+
}
|
|
1913
|
+
// Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
|
|
1914
|
+
// ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
|
|
1915
|
+
// multiply. `n` must be < 2^bits.
|
|
1916
|
+
runCT(point, n, bits, transform) {
|
|
1917
|
+
const W = getWindowSize(point);
|
|
1918
|
+
if (W === 1)
|
|
1919
|
+
return this.fixedWindowCT(point, n, bits);
|
|
1920
|
+
return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
|
|
1921
|
+
}
|
|
1922
|
+
mulCT(point, scalar, transform) {
|
|
1923
|
+
this.validateMulInput(point, scalar);
|
|
1924
|
+
return this.runCT(point, scalar, this.bits, transform);
|
|
1925
|
+
}
|
|
1926
|
+
mulCTBlinded(point, scalar, transform) {
|
|
1927
|
+
this.validateMulInput(point, scalar);
|
|
1928
|
+
// Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This
|
|
1929
|
+
// equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always
|
|
1930
|
+
// for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).
|
|
1931
|
+
// Fail before building the (large) precompute table if randomness is unavailable.
|
|
1932
|
+
if (this.randomBytes === undefined)
|
|
1933
|
+
throw new Error('randomBytes is required for scalar blinding');
|
|
1934
|
+
const bits = this.Point.Fn.BITS + BLIND_BITS;
|
|
1935
|
+
const blind = this.randomBytes(BLIND_BYTES);
|
|
1936
|
+
if (!isBytes(blind) || blind.length !== BLIND_BYTES)
|
|
1937
|
+
throw new Error('randomBytes returned invalid byte array');
|
|
1938
|
+
// Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):
|
|
1939
|
+
// * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind
|
|
1940
|
+
// is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.
|
|
1941
|
+
// * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping
|
|
1942
|
+
// blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)
|
|
1943
|
+
// ceiling. Not strictly required for the bound (see below), but it reserves headroom so the
|
|
1944
|
+
// guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window
|
|
1945
|
+
// only ever holds a small carry, never a full digit.
|
|
1946
|
+
blind[0] = (blind[0] & 0x3f) | 0x80;
|
|
1947
|
+
// Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <
|
|
1948
|
+
// 2^(nBits+128), so n stays below 2^bits and within the blinded table's
|
|
1949
|
+
// window count. Both cached CT kernels run a fixed number of windows/rows with one point-add
|
|
1950
|
+
// each, so the add count is independent of scalar (constant-time).
|
|
1951
|
+
const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
|
|
1952
|
+
return this.runCT(point, n, bits, transform);
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
|
|
1956
|
+
* A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
|
|
1957
|
+
* far cheaper to build for a single use. The point-operation sequence is independent of `n`:
|
|
1958
|
+
* build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
|
|
1959
|
+
* every table entry, and one addition (adds the identity when the window digit is 0 — never
|
|
1960
|
+
* skipped).
|
|
1961
|
+
*
|
|
1962
|
+
* `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
|
|
1963
|
+
* add), which holds for the Weierstrass/Edwards point types used here. The table is left in
|
|
1964
|
+
* projective form (no normalizeZ): normalizing this small a table costs more than the
|
|
1965
|
+
* mixed-add savings it would buy for a single multiply.
|
|
1966
|
+
* @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
|
|
1967
|
+
* (this path needs no fake accumulator — its op-count is already scalar-independent).
|
|
1968
|
+
*/
|
|
1969
|
+
fixedWindowCT(point, n, bits) {
|
|
1970
|
+
const W = FW_WINDOW;
|
|
1971
|
+
const size = 1 << W;
|
|
1972
|
+
const mask = bitMask(W);
|
|
1973
|
+
// Flat table [O, point, 2*point, ..., (size-1)*point].
|
|
1974
|
+
const table = new Array(size);
|
|
1975
|
+
table[0] = this.ZERO;
|
|
1976
|
+
for (let i = 1; i < size; i++)
|
|
1977
|
+
table[i] = table[i - 1].add(point);
|
|
1978
|
+
// Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.
|
|
1979
|
+
const windows = Math.ceil(bits / W);
|
|
1980
|
+
let acc = this.ZERO;
|
|
1981
|
+
for (let window = windows - 1; window >= 0; window--) {
|
|
1982
|
+
// W doublings per window; skipped for the first (topmost) window, where acc is still the
|
|
1983
|
+
// identity. The skip is scalar-independent: it depends only on the loop index.
|
|
1984
|
+
if (window !== windows - 1)
|
|
1985
|
+
for (let d = 0; d < W; d++)
|
|
1986
|
+
acc = acc.double();
|
|
1987
|
+
const digit = Number((n >> BigInt(window * W)) & mask);
|
|
1988
|
+
// Data-oblivious select: touch every entry, same as wnafCachedCT.
|
|
1989
|
+
let sel = table[0];
|
|
1990
|
+
for (let i = 1; i < size; i++)
|
|
1991
|
+
sel = i === digit ? table[i] : sel;
|
|
1992
|
+
acc = acc.add(sel); // one add per window, even for digit 0
|
|
1993
|
+
}
|
|
1994
|
+
return { p: acc, f: acc };
|
|
1995
|
+
}
|
|
1996
|
+
shouldBlind(point, cofactor) {
|
|
1997
|
+
// No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.
|
|
1998
|
+
if (this.randomBytes === undefined)
|
|
1999
|
+
return false;
|
|
2000
|
+
if (cofactor === _1n$1)
|
|
2001
|
+
return true;
|
|
2002
|
+
if (point !== this.BASE)
|
|
2003
|
+
return false;
|
|
2004
|
+
if (this.baseCanBeBlinded === undefined)
|
|
2005
|
+
this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
|
|
2006
|
+
return this.baseCanBeBlinded;
|
|
2007
|
+
}
|
|
2008
|
+
mulSecret(point, scalar, cofactor, transform) {
|
|
2009
|
+
return this.shouldBlind(point, cofactor)
|
|
2010
|
+
? this.mulCTBlinded(point, scalar, transform)
|
|
2011
|
+
: this.mulCT(point, scalar, transform);
|
|
2012
|
+
}
|
|
2013
|
+
mulUnsafe(point, scalar, transform) {
|
|
2014
|
+
this.assertPoint(point);
|
|
2015
|
+
if (!isPosBig(scalar))
|
|
2016
|
+
throw new Error('invalid scalar');
|
|
2017
|
+
const W = getWindowSize(point);
|
|
2018
|
+
// W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 —
|
|
2019
|
+
// a cached table would be thrown away after one use. `allowOversized` swaps the
|
|
2020
|
+
// `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.
|
|
2021
|
+
//
|
|
2022
|
+
// Oversized scalar could happen when:
|
|
2023
|
+
// a) user passes large scalar on their own (rare)
|
|
2024
|
+
// b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`
|
|
2025
|
+
if (W === 1 || scalar >= this.Point.Fn.ORDER)
|
|
2026
|
+
return mulAddUnsafe(this.Point, [point], [scalar], true);
|
|
2027
|
+
// Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only
|
|
2028
|
+
// ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on
|
|
2029
|
+
// this path while doubling the cached-table code surface.
|
|
2030
|
+
const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
|
|
2031
|
+
return this.wnafCachedCT(precomputes, scalar).p;
|
|
2032
|
+
}
|
|
2033
|
+
// Remembers the window size used for precomputed wNAF multiplication of the given point
|
|
2034
|
+
// and drops any previously built tables. Usually only the base point is precomputed.
|
|
2035
|
+
// W=1 resets the point to the un-precomputed (table-less) paths.
|
|
2036
|
+
// W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
|
|
2037
|
+
setWindowSize(point, W) {
|
|
2038
|
+
this.assertPoint(point);
|
|
2039
|
+
validateW(W, this.bits);
|
|
2040
|
+
// Size against the widest table this W can produce: the blinded path adds BLIND_BITS.
|
|
2041
|
+
const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
|
|
2042
|
+
validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
|
|
2043
|
+
pointWindowSizes.set(point, W);
|
|
2044
|
+
this.wnafPrecomputes.delete(point);
|
|
2045
|
+
}
|
|
2046
|
+
// True when a window size is set: tables themselves are built lazily on first multiply.
|
|
2047
|
+
hasWindowSize(point) {
|
|
2048
|
+
return getWindowSize(point) !== 1;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF
|
|
2053
|
+
* (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and
|
|
2054
|
+
* signed-digit recoding, but all walks share one doubling chain, so total cost is
|
|
2055
|
+
* `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate
|
|
2056
|
+
* multiplications. Intended for the 2-4 point shapes of signature verification
|
|
2057
|
+
* (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.
|
|
2058
|
+
*
|
|
2059
|
+
* Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;
|
|
2060
|
+
* fold negative signs into the points before calling.
|
|
2061
|
+
* @param c - Point constructor.
|
|
2062
|
+
* @param points - Array of curve points.
|
|
2063
|
+
* @param scalars - Array of non-negative scalars, same length as points.
|
|
2064
|
+
* @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.
|
|
2065
|
+
* Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks
|
|
2066
|
+
* (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.
|
|
2067
|
+
* @returns Combined multiplication result; identity for empty input.
|
|
2068
|
+
* @throws If the point set or scalar set is invalid. {@link Error}
|
|
2069
|
+
* @example
|
|
2070
|
+
* Combined multi-scalar multiplication via Strauss–Shamir.
|
|
2071
|
+
*
|
|
2072
|
+
* ```ts
|
|
2073
|
+
* import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';
|
|
2074
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2075
|
+
* const G = p256.Point.BASE;
|
|
2076
|
+
* const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)
|
|
2077
|
+
* ```
|
|
2078
|
+
*/
|
|
2079
|
+
function mulAddUnsafe(c, points, scalars, allowOversized = false) {
|
|
2080
|
+
validatePointCons(c);
|
|
2081
|
+
validateMSMPoints(points, c);
|
|
2082
|
+
abool(allowOversized, 'allowOversized');
|
|
2083
|
+
// Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).
|
|
2084
|
+
validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n$1 : undefined);
|
|
2085
|
+
if (points.length !== scalars.length)
|
|
2086
|
+
throw new Error('arrays of points and scalars must have equal length');
|
|
2087
|
+
const tables = points.map((p) => oddMultiples(p, 4));
|
|
2088
|
+
const digits = scalars.map((n) => wnafDigits(n, 4));
|
|
2089
|
+
return wnafWalk(c.ZERO, tables, digits);
|
|
2090
|
+
}
|
|
2091
|
+
function createField(order, field, isLE) {
|
|
2092
|
+
if (field) {
|
|
2093
|
+
// Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback
|
|
2094
|
+
// fields, and validateField() below only checks the arithmetic subset, not full byte/cmov
|
|
2095
|
+
// behavior.
|
|
2096
|
+
if (field.ORDER !== order)
|
|
2097
|
+
throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
|
|
2098
|
+
validateField(field);
|
|
2099
|
+
return field;
|
|
2100
|
+
}
|
|
2101
|
+
else {
|
|
2102
|
+
return Field(order, { isLE });
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
/**
|
|
2106
|
+
* Validates basic CURVE shape and field membership, then creates fields.
|
|
2107
|
+
* This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
|
|
2108
|
+
* that the curve equation itself is otherwise sane.
|
|
2109
|
+
* @param type - Curve family.
|
|
2110
|
+
* @param CURVE - Curve parameters.
|
|
2111
|
+
* @param curveOpts - Optional field overrides. See {@link FpFn}:
|
|
2112
|
+
* - `Fp` (optional): Optional base-field override.
|
|
2113
|
+
* - `Fn` (optional): Optional scalar-field override.
|
|
2114
|
+
* @param FpFnLE - Whether field encoding is little-endian.
|
|
2115
|
+
* @returns Frozen curve parameters and fields.
|
|
2116
|
+
* @throws If the curve parameters or field overrides are invalid. {@link Error}
|
|
2117
|
+
* @example
|
|
2118
|
+
* Build curve fields from raw constants before constructing a curve instance.
|
|
2119
|
+
*
|
|
2120
|
+
* ```ts
|
|
2121
|
+
* const curve = createCurveFields('weierstrass', {
|
|
2122
|
+
* p: 17n,
|
|
2123
|
+
* n: 19n,
|
|
2124
|
+
* h: 1n,
|
|
2125
|
+
* a: 2n,
|
|
2126
|
+
* b: 2n,
|
|
2127
|
+
* Gx: 5n,
|
|
2128
|
+
* Gy: 1n,
|
|
2129
|
+
* });
|
|
2130
|
+
* ```
|
|
2131
|
+
*/
|
|
2132
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
2133
|
+
if (FpFnLE === undefined)
|
|
2134
|
+
FpFnLE = type === 'edwards';
|
|
2135
|
+
if (!CURVE || typeof CURVE !== 'object')
|
|
2136
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
2137
|
+
// Validate before reading Fp/Fn so explicit null fails with an options-object error.
|
|
2138
|
+
validateObject(curveOpts);
|
|
2139
|
+
for (const p of ['p', 'n', 'h']) {
|
|
2140
|
+
const val = CURVE[p];
|
|
2141
|
+
if (!(isPosBig(val) && val !== _0n$2))
|
|
2142
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
2143
|
+
}
|
|
2144
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
2145
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
2146
|
+
const _b = 'b' ;
|
|
2147
|
+
const params = ['Gx', 'Gy', 'a', _b];
|
|
2148
|
+
for (const p of params) {
|
|
2149
|
+
// @ts-ignore
|
|
2150
|
+
if (!Fp.isValid(CURVE[p]))
|
|
2151
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
2152
|
+
}
|
|
2153
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
2154
|
+
return { CURVE, Fp, Fn };
|
|
2155
|
+
}
|
|
2156
|
+
/**
|
|
2157
|
+
* @param randomSecretKey - Secret-key generator.
|
|
2158
|
+
* @param getPublicKey - Public-key derivation helper.
|
|
2159
|
+
* @returns Keypair generator.
|
|
2160
|
+
* @example
|
|
2161
|
+
* Build a `keygen()` helper from existing secret-key and public-key primitives.
|
|
2162
|
+
*
|
|
2163
|
+
* ```ts
|
|
2164
|
+
* import { createKeygen } from '@noble/curves/abstract/curve.js';
|
|
2165
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2166
|
+
* const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
|
|
2167
|
+
* const pair = keygen();
|
|
2168
|
+
* ```
|
|
2169
|
+
*/
|
|
2170
|
+
function createKeygen(randomSecretKey, getPublicKey) {
|
|
2171
|
+
return function keygen(seed) {
|
|
2172
|
+
const secretKey = randomSecretKey(seed);
|
|
2173
|
+
return { secretKey, publicKey: getPublicKey(secretKey) };
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
/**
|
|
2178
|
+
* HMAC: RFC2104 message authentication code.
|
|
2179
|
+
* @module
|
|
2180
|
+
*/
|
|
2181
|
+
/**
|
|
2182
|
+
* Internal class for HMAC.
|
|
2183
|
+
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
|
|
2184
|
+
* `HashLen` bytes long.
|
|
2185
|
+
*/
|
|
2186
|
+
class _HMAC {
|
|
2187
|
+
oHash;
|
|
2188
|
+
iHash;
|
|
2189
|
+
blockLen;
|
|
2190
|
+
outputLen;
|
|
2191
|
+
canXOF = false;
|
|
2192
|
+
finished = false;
|
|
2193
|
+
destroyed = false;
|
|
2194
|
+
constructor(hash, key) {
|
|
2195
|
+
ahash(hash);
|
|
2196
|
+
abytes$1(key, undefined, 'key');
|
|
2197
|
+
this.iHash = hash.create();
|
|
2198
|
+
if (typeof this.iHash.update !== 'function')
|
|
2199
|
+
throw new Error('expected Hash instance');
|
|
2200
|
+
this.blockLen = this.iHash.blockLen;
|
|
2201
|
+
this.outputLen = this.iHash.outputLen;
|
|
2202
|
+
const blockLen = this.blockLen;
|
|
2203
|
+
const pad = new Uint8Array(blockLen);
|
|
2204
|
+
// blockLen can be bigger than outputLen
|
|
2205
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
2206
|
+
for (let i = 0; i < pad.length; i++)
|
|
2207
|
+
pad[i] ^= 0x36;
|
|
2208
|
+
this.iHash.update(pad);
|
|
2209
|
+
// By doing update (processing of the first block) of the outer hash here,
|
|
2210
|
+
// we can re-use it between multiple calls via clone.
|
|
2211
|
+
this.oHash = hash.create();
|
|
2212
|
+
// Undo internal XOR && apply outer XOR
|
|
2213
|
+
for (let i = 0; i < pad.length; i++)
|
|
2214
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
|
2215
|
+
this.oHash.update(pad);
|
|
2216
|
+
clean(pad);
|
|
2217
|
+
}
|
|
2218
|
+
update(buf) {
|
|
2219
|
+
aexists(this);
|
|
2220
|
+
this.iHash.update(buf);
|
|
2221
|
+
return this;
|
|
2222
|
+
}
|
|
2223
|
+
digestInto(out) {
|
|
2224
|
+
aexists(this);
|
|
2225
|
+
aoutput(out, this);
|
|
2226
|
+
this.finished = true;
|
|
2227
|
+
const buf = out.subarray(0, this.outputLen);
|
|
2228
|
+
// Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
|
|
2229
|
+
// overwriting that same prefix with the final tag, leaving any oversized tail untouched.
|
|
2230
|
+
this.iHash.digestInto(buf);
|
|
2231
|
+
this.oHash.update(buf);
|
|
2232
|
+
this.oHash.digestInto(buf);
|
|
2233
|
+
this.destroy();
|
|
2234
|
+
}
|
|
2235
|
+
digest() {
|
|
2236
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
2237
|
+
this.digestInto(out);
|
|
2238
|
+
return out;
|
|
2239
|
+
}
|
|
2240
|
+
_cloneInto(to) {
|
|
2241
|
+
// Create new instance without calling constructor since the key
|
|
2242
|
+
// is already in state and we don't know it.
|
|
2243
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
2244
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
|
|
2245
|
+
to = to;
|
|
2246
|
+
to.finished = finished;
|
|
2247
|
+
to.destroyed = destroyed;
|
|
2248
|
+
to.blockLen = blockLen;
|
|
2249
|
+
to.outputLen = outputLen;
|
|
2250
|
+
to.canXOF = canXOF;
|
|
2251
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
2252
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
2253
|
+
return to;
|
|
2254
|
+
}
|
|
2255
|
+
clone() {
|
|
2256
|
+
return this._cloneInto();
|
|
2257
|
+
}
|
|
2258
|
+
destroy() {
|
|
2259
|
+
this.destroyed = true;
|
|
2260
|
+
this.oHash.destroy();
|
|
2261
|
+
this.iHash.destroy();
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
const hmac = /* @__PURE__ */ (() => {
|
|
2265
|
+
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
|
2266
|
+
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
|
2267
|
+
return hmac_;
|
|
2268
|
+
})();
|
|
2269
|
+
|
|
2270
|
+
/**
|
|
2271
|
+
* ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.
|
|
2272
|
+
* Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.
|
|
2273
|
+
* @module
|
|
2274
|
+
*/
|
|
2275
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2276
|
+
const _0n$1 = /* @__PURE__ */ BigInt(0);
|
|
2277
|
+
/**
|
|
2278
|
+
* @param m - Error message.
|
|
2279
|
+
* @example
|
|
2280
|
+
* Throw a DER-specific error when signature parsing encounters invalid bytes.
|
|
2281
|
+
*
|
|
2282
|
+
* ```ts
|
|
2283
|
+
* new DERErr('bad der');
|
|
2284
|
+
* ```
|
|
2285
|
+
*/
|
|
2286
|
+
class DERErr extends Error {
|
|
2287
|
+
constructor(m = '') {
|
|
2288
|
+
super(m);
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
// Plain const so the freezes can live inside the pure initializer of the `DER` export below:
|
|
2292
|
+
// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.
|
|
2293
|
+
const _DER = {
|
|
2294
|
+
// asn.1 DER encoding utils
|
|
2295
|
+
Err: DERErr,
|
|
2296
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
2297
|
+
_tlv: {
|
|
2298
|
+
encode: (tag, data) => {
|
|
2299
|
+
const { Err: E } = _DER;
|
|
2300
|
+
asafenumber(tag, 'tag');
|
|
2301
|
+
if (tag < 0 || tag > 255)
|
|
2302
|
+
throw new E('tlv.encode: wrong tag');
|
|
2303
|
+
astring(data, 'data');
|
|
2304
|
+
// Internal helper: callers hand this already-validated hex payload, so we only enforce
|
|
2305
|
+
// byte alignment here instead of re-validating every nibble.
|
|
2306
|
+
if (data.length & 1)
|
|
2307
|
+
throw new E('tlv.encode: unpadded data');
|
|
2308
|
+
const dataLen = data.length / 2;
|
|
2309
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2310
|
+
if ((len.length / 2) & 0b1000_0000)
|
|
2311
|
+
throw new E('tlv.encode: long form length too big');
|
|
2312
|
+
// length of length with long form flag
|
|
2313
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';
|
|
2314
|
+
const t = numberToHexUnpadded(tag);
|
|
2315
|
+
return t + lenLen + len + data;
|
|
2316
|
+
},
|
|
2317
|
+
// v - value, l - left bytes (unparsed)
|
|
2318
|
+
decode(tag, data) {
|
|
2319
|
+
const { Err: E } = _DER;
|
|
2320
|
+
data = abytes(data, undefined, 'DER data');
|
|
2321
|
+
let pos = 0;
|
|
2322
|
+
if (tag < 0 || tag > 255)
|
|
2323
|
+
throw new E('tlv.decode: wrong tag');
|
|
2324
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
2325
|
+
throw new E('tlv.decode: wrong tlv');
|
|
2326
|
+
const first = data[pos++];
|
|
2327
|
+
// First bit of first length byte is the short/long form flag.
|
|
2328
|
+
const isLong = !!(first & 0b1000_0000);
|
|
2329
|
+
let length = 0;
|
|
2330
|
+
if (!isLong)
|
|
2331
|
+
length = first;
|
|
2332
|
+
else {
|
|
2333
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
|
2334
|
+
const lenLen = first & 0b0111_1111;
|
|
2335
|
+
if (!lenLen)
|
|
2336
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
|
2337
|
+
// This would overflow u32 in JS.
|
|
2338
|
+
if (lenLen > 4)
|
|
2339
|
+
throw new E('tlv.decode(long): byte length is too big');
|
|
2340
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2341
|
+
if (lengthBytes.length !== lenLen)
|
|
2342
|
+
throw new E('tlv.decode: length bytes not complete');
|
|
2343
|
+
if (lengthBytes[0] === 0)
|
|
2344
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
|
2345
|
+
for (const b of lengthBytes)
|
|
2346
|
+
length = (length << 8) | b;
|
|
2347
|
+
pos += lenLen;
|
|
2348
|
+
if (length < 128)
|
|
2349
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
|
2350
|
+
}
|
|
2351
|
+
const v = data.subarray(pos, pos + length);
|
|
2352
|
+
if (v.length !== length)
|
|
2353
|
+
throw new E('tlv.decode: wrong value length');
|
|
2354
|
+
return { v, l: data.subarray(pos + length) };
|
|
2355
|
+
},
|
|
2356
|
+
},
|
|
2357
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
2358
|
+
// since we always use positive integers here. It must always be empty:
|
|
2359
|
+
// - add zero byte if exists
|
|
2360
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
2361
|
+
_int: {
|
|
2362
|
+
encode(num) {
|
|
2363
|
+
const { Err: E } = _DER;
|
|
2364
|
+
abignumber(num);
|
|
2365
|
+
if (num < _0n$1)
|
|
2366
|
+
throw new E('integer: negative integers are not allowed');
|
|
2367
|
+
let hex = numberToHexUnpadded(num);
|
|
2368
|
+
// Pad with zero byte if negative flag is present
|
|
2369
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
|
2370
|
+
hex = '00' + hex;
|
|
2371
|
+
if (hex.length & 1)
|
|
2372
|
+
throw new E('unexpected DER parsing assertion: unpadded hex');
|
|
2373
|
+
return hex;
|
|
2374
|
+
},
|
|
2375
|
+
decode(data) {
|
|
2376
|
+
const { Err: E } = _DER;
|
|
2377
|
+
if (data.length < 1)
|
|
2378
|
+
throw new E('invalid signature integer: empty');
|
|
2379
|
+
if (data[0] & 0b1000_0000)
|
|
2380
|
+
throw new E('invalid signature integer: negative');
|
|
2381
|
+
// Single-byte zero `00` is the canonical DER INTEGER encoding for zero.
|
|
2382
|
+
if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))
|
|
2383
|
+
throw new E('invalid signature integer: unnecessary leading zero');
|
|
2384
|
+
return bytesToNumberBE(data);
|
|
2385
|
+
},
|
|
2386
|
+
},
|
|
2387
|
+
toSig(bytes, maxScalarBytes) {
|
|
2388
|
+
// parse DER signature
|
|
2389
|
+
const { Err: E, _int: int, _tlv: tlv } = _DER;
|
|
2390
|
+
if (maxScalarBytes !== undefined) {
|
|
2391
|
+
asafenumber(maxScalarBytes, 'maxScalarBytes');
|
|
2392
|
+
if (maxScalarBytes < 1)
|
|
2393
|
+
throw new E('invalid signature: maxScalarBytes must be positive');
|
|
2394
|
+
}
|
|
2395
|
+
const data = abytes(bytes, undefined, 'signature');
|
|
2396
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
|
2397
|
+
if (seqLeftBytes.length)
|
|
2398
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2399
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
|
2400
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
|
2401
|
+
if (sLeftBytes.length)
|
|
2402
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2403
|
+
// Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.
|
|
2404
|
+
if (maxScalarBytes !== undefined &&
|
|
2405
|
+
(rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))
|
|
2406
|
+
throw new E('invalid signature: integer too large');
|
|
2407
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
2408
|
+
},
|
|
2409
|
+
hexFromSig(sig) {
|
|
2410
|
+
const { _tlv: tlv, _int: int } = _DER;
|
|
2411
|
+
validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');
|
|
2412
|
+
const rs = tlv.encode(0x02, int.encode(sig.r));
|
|
2413
|
+
const ss = tlv.encode(0x02, int.encode(sig.s));
|
|
2414
|
+
const seq = rs + ss;
|
|
2415
|
+
return tlv.encode(0x30, seq);
|
|
2416
|
+
},
|
|
2417
|
+
};
|
|
2418
|
+
/**
|
|
2419
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
|
2420
|
+
*
|
|
2421
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
|
2422
|
+
*
|
|
2423
|
+
* Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and
|
|
2424
|
+
* {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.
|
|
2425
|
+
* @example
|
|
2426
|
+
* ASN.1 DER encoding utilities.
|
|
2427
|
+
*
|
|
2428
|
+
* ```ts
|
|
2429
|
+
* const der = DER.hexFromSig({ r: 1n, s: 2n });
|
|
2430
|
+
* ```
|
|
2431
|
+
*/
|
|
2432
|
+
const DER = /* @__PURE__ */ (() => {
|
|
2433
|
+
Object.freeze(_DER._tlv);
|
|
2434
|
+
Object.freeze(_DER._int);
|
|
2435
|
+
return Object.freeze(_DER);
|
|
2436
|
+
})();
|
|
2437
|
+
|
|
2438
|
+
/**
|
|
2439
|
+
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
|
|
2440
|
+
*
|
|
2441
|
+
* ### Design rationale for types
|
|
2442
|
+
*
|
|
2443
|
+
* * Interaction between classes from different curves should fail:
|
|
2444
|
+
* `k256.Point.BASE.add(p256.Point.BASE)`
|
|
2445
|
+
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
|
|
2446
|
+
* * Different calls of `curve()` would return different classes -
|
|
2447
|
+
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
|
|
2448
|
+
* it won't affect others
|
|
2449
|
+
*
|
|
2450
|
+
* TypeScript can't infer types for classes created inside a function. Classes is one instance
|
|
2451
|
+
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
|
|
2452
|
+
* unique type for every function call.
|
|
2453
|
+
*
|
|
2454
|
+
* We can use generic types via some param, like curve opts, but that would:
|
|
2455
|
+
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
|
|
2456
|
+
* which is hard to debug.
|
|
2457
|
+
* 2. Params can be generic and we can't enforce them to be constant value:
|
|
2458
|
+
* if somebody creates curve from non-constant params,
|
|
2459
|
+
* it would be allowed to interact with other curves with non-constant params
|
|
2460
|
+
*
|
|
2461
|
+
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
|
|
2462
|
+
* @module
|
|
2463
|
+
*/
|
|
2464
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2465
|
+
// We construct the basis so `den` is always positive and equals `n`,
|
|
2466
|
+
// but the `num` sign depends on the basis, not on the secret value.
|
|
2467
|
+
// Exact half-way cases round away from zero, which keeps the split symmetric
|
|
2468
|
+
// around the reduced-basis boundaries used by endomorphism decomposition.
|
|
2469
|
+
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
|
|
2470
|
+
/** Splits scalar for GLV endomorphism. */
|
|
2471
|
+
function _splitEndoScalar(k, basis, n) {
|
|
2472
|
+
// Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
|
|
2473
|
+
// Since part can be negative, we need to do this on point.
|
|
2474
|
+
// Callers must provide a reduced GLV basis whose vectors satisfy
|
|
2475
|
+
// `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.
|
|
2476
|
+
// Reject unreduced scalars instead of silently treating them mod n.
|
|
2477
|
+
aInRange('scalar', k, _0n, n);
|
|
2478
|
+
// TODO: verifyScalar function which consumes lambda
|
|
2479
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
2480
|
+
const c1 = divNearest(b2 * k, n);
|
|
2481
|
+
const c2 = divNearest(-b1 * k, n);
|
|
2482
|
+
// |k1|/|k2| is < sqrt(N), but can be negative.
|
|
2483
|
+
// If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
|
|
2484
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
2485
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
2486
|
+
const k1neg = k1 < _0n;
|
|
2487
|
+
const k2neg = k2 < _0n;
|
|
2488
|
+
if (k1neg)
|
|
2489
|
+
k1 = -k1;
|
|
2490
|
+
if (k2neg)
|
|
2491
|
+
k2 = -k2;
|
|
2492
|
+
// Double check that resulting scalar is less than half bits of N: the wNAF pair walk
|
|
2493
|
+
// relies on the halves being short. This should only happen on wrong bases.
|
|
2494
|
+
// Also, the math inside is complex enough that this guard is worth keeping.
|
|
2495
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
|
|
2496
|
+
if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
|
|
2497
|
+
throw new Error('splitScalar (endomorphism): failed for k');
|
|
2498
|
+
}
|
|
2499
|
+
return { k1neg, k1, k2neg, k2 };
|
|
2500
|
+
}
|
|
2501
|
+
function validateSigFormat(format) {
|
|
2502
|
+
if (!['compact', 'recovered', 'der'].includes(format))
|
|
2503
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
2504
|
+
return format;
|
|
2505
|
+
}
|
|
2506
|
+
function validateSigOpts(opts, def) {
|
|
2507
|
+
validateObject(opts);
|
|
2508
|
+
const optsn = {};
|
|
2509
|
+
// Normalize only the declared option subset from `def`; unknown keys are
|
|
2510
|
+
// intentionally ignored so shared / superset option bags stay valid here too.
|
|
2511
|
+
// `extraEntropy` stays an opaque payload until the signing path consumes it.
|
|
2512
|
+
for (let optName of Object.keys(def)) {
|
|
2513
|
+
// @ts-ignore
|
|
2514
|
+
optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
|
|
2515
|
+
}
|
|
2516
|
+
abool(optsn.lowS, 'lowS');
|
|
2517
|
+
abool(optsn.prehash, 'prehash');
|
|
2518
|
+
if (optsn.format !== undefined)
|
|
2519
|
+
validateSigFormat(optsn.format);
|
|
2520
|
+
return optsn;
|
|
2521
|
+
}
|
|
2522
|
+
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
|
2523
|
+
// prettier-ignore
|
|
2524
|
+
const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);
|
|
2525
|
+
/**
|
|
2526
|
+
* Creates weierstrass Point constructor, based on specified curve options.
|
|
2527
|
+
*
|
|
2528
|
+
* See {@link WeierstrassOpts}.
|
|
2529
|
+
* @param params - Curve parameters. See {@link WeierstrassOpts}.
|
|
2530
|
+
* @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.
|
|
2531
|
+
* @returns Weierstrass point constructor.
|
|
2532
|
+
* @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}
|
|
2533
|
+
*
|
|
2534
|
+
* @example
|
|
2535
|
+
* Construct a point type from explicit Weierstrass curve parameters.
|
|
2536
|
+
*
|
|
2537
|
+
* ```js
|
|
2538
|
+
* const opts = {
|
|
2539
|
+
* p: 0xfffffffffffffffffffffffffffffffeffffac73n,
|
|
2540
|
+
* n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,
|
|
2541
|
+
* h: 1n,
|
|
2542
|
+
* a: 0n,
|
|
2543
|
+
* b: 7n,
|
|
2544
|
+
* Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,
|
|
2545
|
+
* Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,
|
|
2546
|
+
* };
|
|
2547
|
+
* const secp160k1_Point = weierstrass(opts);
|
|
2548
|
+
* ```
|
|
2549
|
+
*/
|
|
2550
|
+
function weierstrass(params, extraOpts = {}) {
|
|
2551
|
+
const validated = createCurveFields('weierstrass', params, extraOpts);
|
|
2552
|
+
const Fp = validated.Fp;
|
|
2553
|
+
const Fn = validated.Fn;
|
|
2554
|
+
let CURVE = validated.CURVE;
|
|
2555
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
2556
|
+
validateObject(extraOpts, {}, {
|
|
2557
|
+
allowInfinityPoint: 'boolean',
|
|
2558
|
+
clearCofactor: 'function',
|
|
2559
|
+
isTorsionFree: 'function',
|
|
2560
|
+
fromBytes: 'function',
|
|
2561
|
+
toBytes: 'function',
|
|
2562
|
+
endo: 'object',
|
|
2563
|
+
randomBytes: 'function',
|
|
2564
|
+
});
|
|
2565
|
+
// Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of
|
|
2566
|
+
// the caller's options must not change arithmetic, subgroup, or codec policy.
|
|
2567
|
+
const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;
|
|
2568
|
+
const randomBytes$1 = extraOpts.randomBytes === undefined ? randomBytes : extraOpts.randomBytes;
|
|
2569
|
+
if (endoOpts) {
|
|
2570
|
+
if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {
|
|
2571
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
const endo = endoOpts
|
|
2575
|
+
? {
|
|
2576
|
+
beta: endoOpts.beta,
|
|
2577
|
+
basises: endoOpts.basises.map((basis) => [...basis]),
|
|
2578
|
+
}
|
|
2579
|
+
: undefined;
|
|
2580
|
+
const lengths = getWLengths(Fp, Fn);
|
|
2581
|
+
function assertCompressionIsSupported() {
|
|
2582
|
+
if (!Fp.isOdd)
|
|
2583
|
+
throw new Error('compression is not supported: Field does not have .isOdd()');
|
|
2584
|
+
}
|
|
2585
|
+
// Implements IEEE P1363 point encoding
|
|
2586
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
2587
|
+
// Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the
|
|
2588
|
+
// encoder would emit an all-zero byte string that decodes back as a different point. Only
|
|
2589
|
+
// curves that opt into infinity as a public point value get the SEC 1 byte form.
|
|
2590
|
+
if (point.is0()) {
|
|
2591
|
+
if (!allowInfinityPoint)
|
|
2592
|
+
throw new Error('bad point: ZERO');
|
|
2593
|
+
return Uint8Array.of(0); // SEC 1 v2.0 §2.3.3
|
|
2594
|
+
}
|
|
2595
|
+
const { x, y } = point.toAffine();
|
|
2596
|
+
const bx = Fp.toBytes(x);
|
|
2597
|
+
abool(isCompressed, 'isCompressed');
|
|
2598
|
+
if (isCompressed) {
|
|
2599
|
+
assertCompressionIsSupported();
|
|
2600
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
2601
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
2602
|
+
}
|
|
2603
|
+
else {
|
|
2604
|
+
return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
function pointFromBytes(bytes) {
|
|
2608
|
+
abytes(bytes, undefined, 'Point');
|
|
2609
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
|
|
2610
|
+
const length = bytes.length;
|
|
2611
|
+
const head = bytes[0];
|
|
2612
|
+
const tail = bytes.subarray(1);
|
|
2613
|
+
// SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 rejects infinity as a public key.
|
|
2614
|
+
// Leaving 0x00 undecodable by default makes that rejection structural rather than a check:
|
|
2615
|
+
// callers reuse this parser as the strict key boundary, and infinity is simply not
|
|
2616
|
+
// expressible. Curves where infinity is a real wire value opt into the codec instead.
|
|
2617
|
+
// secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.
|
|
2618
|
+
if (allowInfinityPoint && length === 1 && head === 0x00)
|
|
2619
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
2620
|
+
// No actual validation is done here: use .assertValidity()
|
|
2621
|
+
if (length === comp && (head === 0x02 || head === 0x03)) {
|
|
2622
|
+
const x = Fp.fromBytes(tail);
|
|
2623
|
+
if (!Fp.isValid(x))
|
|
2624
|
+
throw new Error('bad point: is not on curve, wrong x');
|
|
2625
|
+
const y2 = weierstrassEquation(x); // y² = x³ + ax + b
|
|
2626
|
+
let y;
|
|
2627
|
+
try {
|
|
2628
|
+
y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
|
|
2629
|
+
}
|
|
2630
|
+
catch (sqrtError) {
|
|
2631
|
+
const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
|
|
2632
|
+
throw new Error('bad point: is not on curve, sqrt error' + err);
|
|
2633
|
+
}
|
|
2634
|
+
assertCompressionIsSupported();
|
|
2635
|
+
const evenY = Fp.isOdd(y);
|
|
2636
|
+
const evenH = (head & 1) === 1; // ECDSA-specific
|
|
2637
|
+
if (evenH !== evenY)
|
|
2638
|
+
y = Fp.neg(y);
|
|
2639
|
+
return { x, y };
|
|
2640
|
+
}
|
|
2641
|
+
else if (length === uncomp && head === 0x04) {
|
|
2642
|
+
// TODO: more checks
|
|
2643
|
+
const L = Fp.BYTES;
|
|
2644
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
2645
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
2646
|
+
if (!isValidXY(x, y))
|
|
2647
|
+
throw new Error('bad point: is not on curve');
|
|
2648
|
+
return { x, y };
|
|
2649
|
+
}
|
|
2650
|
+
else {
|
|
2651
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
const encodePoint = toBytes === undefined ? pointToBytes : toBytes;
|
|
2655
|
+
const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;
|
|
2656
|
+
// Hoisted from double() / add(): curve params never change after construction.
|
|
2657
|
+
// Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;
|
|
2658
|
+
// the selection depends only on public curve constants.
|
|
2659
|
+
const b3 = Fp.mul(CURVE.b, _3n);
|
|
2660
|
+
const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);
|
|
2661
|
+
function weierstrassEquation(x) {
|
|
2662
|
+
const x2 = Fp.sqr(x);
|
|
2663
|
+
const x3 = Fp.mul(x2, x);
|
|
2664
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
|
|
2665
|
+
}
|
|
2666
|
+
// TODO: move top-level
|
|
2667
|
+
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
|
|
2668
|
+
function isValidXY(x, y) {
|
|
2669
|
+
const left = Fp.sqr(y);
|
|
2670
|
+
const right = weierstrassEquation(x); // x³ + ax + b
|
|
2671
|
+
return Fp.eql(left, right);
|
|
2672
|
+
}
|
|
2673
|
+
// Keep constructor-time generator validation cheap: callers are responsible for supplying the
|
|
2674
|
+
// correct prime-order base point, while eager subgroup checks here would slow heavy module imports.
|
|
2675
|
+
// Test 1: equation y² = x³ + ax + b should work for generator point.
|
|
2676
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
2677
|
+
throw new Error('bad curve params: generator point');
|
|
2678
|
+
// Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
|
|
2679
|
+
// Guarantees curve is genus-1, smooth (non-singular).
|
|
2680
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
|
|
2681
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
2682
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
2683
|
+
throw new Error('bad curve params: a or b');
|
|
2684
|
+
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
|
|
2685
|
+
function acoord(title, n, banZero = false) {
|
|
2686
|
+
if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
|
|
2687
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
2688
|
+
// Extension-field elements are objects. Keep point coordinates detached from caller-owned
|
|
2689
|
+
// objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive
|
|
2690
|
+
// field elements (bigints in shipped prime fields) are already immutable values.
|
|
2691
|
+
return typeof n === 'object' && n !== null ? Fp.create(n) : n;
|
|
2692
|
+
}
|
|
2693
|
+
function aprjpoint(other) {
|
|
2694
|
+
if (!(other instanceof Point))
|
|
2695
|
+
throw new Error('Weierstrass Point expected');
|
|
2696
|
+
}
|
|
2697
|
+
function splitEndoScalarN(k) {
|
|
2698
|
+
if (!endo || !endo.basises)
|
|
2699
|
+
throw new Error('no endo');
|
|
2700
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
2701
|
+
}
|
|
2702
|
+
/**
|
|
2703
|
+
* Appends a (point, scalar) pair to the inputs of a vartime wNAF walk
|
|
2704
|
+
* ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width
|
|
2705
|
+
* pairs against P and ψ(P) = (β⋅x, y), halving the walk's shared doubling chain;
|
|
2706
|
+
* split signs fold into the points.
|
|
2707
|
+
*/
|
|
2708
|
+
function pushWnafPair(points, scalars, p, k) {
|
|
2709
|
+
if (!Fn.isValid(k))
|
|
2710
|
+
throw new RangeError('invalid scalar: out of range'); // 0 is valid
|
|
2711
|
+
if (endo) {
|
|
2712
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);
|
|
2713
|
+
const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);
|
|
2714
|
+
points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);
|
|
2715
|
+
scalars.push(k1, k2);
|
|
2716
|
+
}
|
|
2717
|
+
else {
|
|
2718
|
+
points.push(p);
|
|
2719
|
+
scalars.push(k);
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
// Successful assertValidity() results are cached: Point instances are frozen at construction,
|
|
2723
|
+
// so on-curve + subgroup facts cannot change afterwards. Only success is cached — invalid
|
|
2724
|
+
// points re-throw on every call. This matters most for pairing curves, where subgroup checks
|
|
2725
|
+
// cost a scalar multiplication and the same instance is re-validated across layers
|
|
2726
|
+
// (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.
|
|
2727
|
+
const validityCache = new WeakSet();
|
|
2728
|
+
/**
|
|
2729
|
+
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
2730
|
+
* Default Point works in 2d / affine coordinates: (x, y).
|
|
2731
|
+
* We're doing calculations in projective, because its operations don't require costly inversion.
|
|
2732
|
+
*/
|
|
2733
|
+
class Point {
|
|
2734
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
2735
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
2736
|
+
static Fp = Fp;
|
|
2737
|
+
static Fn = Fn;
|
|
2738
|
+
X;
|
|
2739
|
+
Y;
|
|
2740
|
+
Z;
|
|
2741
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2742
|
+
constructor(X, Y, Z) {
|
|
2743
|
+
this.X = acoord('x', X);
|
|
2744
|
+
// This is not just about ZERO / infinity: ambient curves can have real
|
|
2745
|
+
// finite points with y=0. Those points are 2-torsion, so they cannot lie
|
|
2746
|
+
// in the odd prime-order subgroups this point type is meant to represent.
|
|
2747
|
+
this.Y = acoord('y', Y, true);
|
|
2748
|
+
this.Z = acoord('z', Z);
|
|
2749
|
+
Object.freeze(this);
|
|
2750
|
+
}
|
|
2751
|
+
static CURVE() {
|
|
2752
|
+
return CURVE;
|
|
2753
|
+
}
|
|
2754
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2755
|
+
static fromAffine(p) {
|
|
2756
|
+
const { x, y } = p || {};
|
|
2757
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
2758
|
+
throw new Error('invalid affine point');
|
|
2759
|
+
if (p instanceof Point)
|
|
2760
|
+
throw new Error('projective point not allowed');
|
|
2761
|
+
// (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
|
|
2762
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
2763
|
+
return Point.ZERO;
|
|
2764
|
+
return new Point(x, y, Fp.ONE);
|
|
2765
|
+
}
|
|
2766
|
+
static fromBytes(bytes) {
|
|
2767
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
|
|
2768
|
+
P.assertValidity();
|
|
2769
|
+
return P;
|
|
2770
|
+
}
|
|
2771
|
+
static fromHex(hex) {
|
|
2772
|
+
return Point.fromBytes(hexToBytes(hex));
|
|
2773
|
+
}
|
|
2774
|
+
get x() {
|
|
2775
|
+
return this.toAffine().x;
|
|
2776
|
+
}
|
|
2777
|
+
get y() {
|
|
2778
|
+
return this.toAffine().y;
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* @param isLazy - true will defer table computation until the first multiplication
|
|
2782
|
+
*/
|
|
2783
|
+
precompute(windowSize = 6, isLazy = true) {
|
|
2784
|
+
wnaf.setWindowSize(this, windowSize);
|
|
2785
|
+
if (!isLazy)
|
|
2786
|
+
this.multiply(_3n); // random number
|
|
2787
|
+
return this;
|
|
2788
|
+
}
|
|
2789
|
+
// TODO: return `this`
|
|
2790
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
2791
|
+
assertValidity() {
|
|
2792
|
+
const p = this;
|
|
2793
|
+
if (p.is0()) {
|
|
2794
|
+
// (0, 1, 0) aka ZERO is invalid in most contexts.
|
|
2795
|
+
// In BLS, ZERO can be serialized, so we allow it.
|
|
2796
|
+
// Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points
|
|
2797
|
+
// like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.
|
|
2798
|
+
if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
|
|
2799
|
+
return;
|
|
2800
|
+
throw new Error('bad point: ZERO');
|
|
2801
|
+
}
|
|
2802
|
+
if (validityCache.has(p))
|
|
2803
|
+
return;
|
|
2804
|
+
// Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
|
|
2805
|
+
const { x, y } = p.toAffine();
|
|
2806
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
2807
|
+
throw new Error('bad point: x or y not field elements');
|
|
2808
|
+
if (!isValidXY(x, y))
|
|
2809
|
+
throw new Error('bad point: equation left != right');
|
|
2810
|
+
if (!p.isTorsionFree())
|
|
2811
|
+
throw new Error('bad point: not in prime-order subgroup');
|
|
2812
|
+
validityCache.add(p);
|
|
2813
|
+
}
|
|
2814
|
+
hasEvenY() {
|
|
2815
|
+
const { y } = this.toAffine();
|
|
2816
|
+
if (!Fp.isOdd)
|
|
2817
|
+
throw new Error("Field doesn't support isOdd");
|
|
2818
|
+
return !Fp.isOdd(y);
|
|
2819
|
+
}
|
|
2820
|
+
/** Compare one point to another. */
|
|
2821
|
+
equals(other) {
|
|
2822
|
+
aprjpoint(other);
|
|
2823
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2824
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2825
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
2826
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
2827
|
+
return U1 && U2;
|
|
2828
|
+
}
|
|
2829
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
2830
|
+
negate() {
|
|
2831
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
2832
|
+
}
|
|
2833
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
2834
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2835
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
2836
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
2837
|
+
double() {
|
|
2838
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2839
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2840
|
+
let t0 = Fp.mul(X1, X1); // step 1
|
|
2841
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
2842
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
2843
|
+
let t3 = Fp.mul(X1, Y1);
|
|
2844
|
+
t3 = Fp.add(t3, t3); // step 5
|
|
2845
|
+
Z3 = Fp.mul(X1, Z1);
|
|
2846
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2847
|
+
X3 = mulA(Z3);
|
|
2848
|
+
Y3 = Fp.mul(b3, t2);
|
|
2849
|
+
Y3 = Fp.add(X3, Y3); // step 10
|
|
2850
|
+
X3 = Fp.sub(t1, Y3);
|
|
2851
|
+
Y3 = Fp.add(t1, Y3);
|
|
2852
|
+
Y3 = Fp.mul(X3, Y3);
|
|
2853
|
+
X3 = Fp.mul(t3, X3);
|
|
2854
|
+
Z3 = Fp.mul(b3, Z3); // step 15
|
|
2855
|
+
t2 = mulA(t2);
|
|
2856
|
+
t3 = Fp.sub(t0, t2);
|
|
2857
|
+
t3 = mulA(t3);
|
|
2858
|
+
t3 = Fp.add(t3, Z3);
|
|
2859
|
+
Z3 = Fp.add(t0, t0); // step 20
|
|
2860
|
+
t0 = Fp.add(Z3, t0);
|
|
2861
|
+
t0 = Fp.add(t0, t2);
|
|
2862
|
+
t0 = Fp.mul(t0, t3);
|
|
2863
|
+
Y3 = Fp.add(Y3, t0);
|
|
2864
|
+
t2 = Fp.mul(Y1, Z1); // step 25
|
|
2865
|
+
t2 = Fp.add(t2, t2);
|
|
2866
|
+
t0 = Fp.mul(t2, t3);
|
|
2867
|
+
X3 = Fp.sub(X3, t0);
|
|
2868
|
+
Z3 = Fp.mul(t2, t1);
|
|
2869
|
+
Z3 = Fp.add(Z3, Z3); // step 30
|
|
2870
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2871
|
+
return new Point(X3, Y3, Z3);
|
|
2872
|
+
}
|
|
2873
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
2874
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2875
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
2876
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
2877
|
+
add(other) {
|
|
2878
|
+
aprjpoint(other);
|
|
2879
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2880
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2881
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2882
|
+
let t0 = Fp.mul(X1, X2); // step 1
|
|
2883
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
2884
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
2885
|
+
let t3 = Fp.add(X1, Y1);
|
|
2886
|
+
let t4 = Fp.add(X2, Y2); // step 5
|
|
2887
|
+
t3 = Fp.mul(t3, t4);
|
|
2888
|
+
t4 = Fp.add(t0, t1);
|
|
2889
|
+
t3 = Fp.sub(t3, t4);
|
|
2890
|
+
t4 = Fp.add(X1, Z1);
|
|
2891
|
+
let t5 = Fp.add(X2, Z2); // step 10
|
|
2892
|
+
t4 = Fp.mul(t4, t5);
|
|
2893
|
+
t5 = Fp.add(t0, t2);
|
|
2894
|
+
t4 = Fp.sub(t4, t5);
|
|
2895
|
+
t5 = Fp.add(Y1, Z1);
|
|
2896
|
+
X3 = Fp.add(Y2, Z2); // step 15
|
|
2897
|
+
t5 = Fp.mul(t5, X3);
|
|
2898
|
+
X3 = Fp.add(t1, t2);
|
|
2899
|
+
t5 = Fp.sub(t5, X3);
|
|
2900
|
+
Z3 = mulA(t4);
|
|
2901
|
+
X3 = Fp.mul(b3, t2); // step 20
|
|
2902
|
+
Z3 = Fp.add(X3, Z3);
|
|
2903
|
+
X3 = Fp.sub(t1, Z3);
|
|
2904
|
+
Z3 = Fp.add(t1, Z3);
|
|
2905
|
+
Y3 = Fp.mul(X3, Z3);
|
|
2906
|
+
t1 = Fp.add(t0, t0); // step 25
|
|
2907
|
+
t1 = Fp.add(t1, t0);
|
|
2908
|
+
t2 = mulA(t2);
|
|
2909
|
+
t4 = Fp.mul(b3, t4);
|
|
2910
|
+
t1 = Fp.add(t1, t2);
|
|
2911
|
+
t2 = Fp.sub(t0, t2); // step 30
|
|
2912
|
+
t2 = mulA(t2);
|
|
2913
|
+
t4 = Fp.add(t4, t2);
|
|
2914
|
+
t0 = Fp.mul(t1, t4);
|
|
2915
|
+
Y3 = Fp.add(Y3, t0);
|
|
2916
|
+
t0 = Fp.mul(t5, t4); // step 35
|
|
2917
|
+
X3 = Fp.mul(t3, X3);
|
|
2918
|
+
X3 = Fp.sub(X3, t0);
|
|
2919
|
+
t0 = Fp.mul(t3, t1);
|
|
2920
|
+
Z3 = Fp.mul(t5, Z3);
|
|
2921
|
+
Z3 = Fp.add(Z3, t0); // step 40
|
|
2922
|
+
return new Point(X3, Y3, Z3);
|
|
2923
|
+
}
|
|
2924
|
+
subtract(other) {
|
|
2925
|
+
// Validate before calling `negate()` so wrong inputs fail with the point guard
|
|
2926
|
+
// instead of leaking a foreign `negate()` error.
|
|
2927
|
+
aprjpoint(other);
|
|
2928
|
+
return this.add(other.negate());
|
|
2929
|
+
}
|
|
2930
|
+
is0() {
|
|
2931
|
+
return this.equals(Point.ZERO);
|
|
2932
|
+
}
|
|
2933
|
+
/**
|
|
2934
|
+
* Constant time multiplication.
|
|
2935
|
+
* Uses precomputed tables (signed fixed-window wNAF) when available.
|
|
2936
|
+
* Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.
|
|
2937
|
+
* @param scalar - by which the point would be multiplied
|
|
2938
|
+
* @returns New point
|
|
2939
|
+
*/
|
|
2940
|
+
multiply(scalar) {
|
|
2941
|
+
// Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.
|
|
2942
|
+
// In key/signature-style callers, those values usually mean broken hash/scalar plumbing,
|
|
2943
|
+
// and failing closed is safer than silently producing the identity point.
|
|
2944
|
+
if (!Fn.isValidNot0(scalar))
|
|
2945
|
+
throw new RangeError('invalid scalar: out of range'); // 0 is invalid
|
|
2946
|
+
const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
|
|
2947
|
+
return normalize([p, f])[0];
|
|
2948
|
+
}
|
|
2949
|
+
/**
|
|
2950
|
+
* Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting
|
|
2951
|
+
* when available (two half-width scalars sharing one halved doubling chain).
|
|
2952
|
+
* It's faster, but should only be used when you don't care about
|
|
2953
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
2954
|
+
*/
|
|
2955
|
+
multiplyUnsafe(scalar) {
|
|
2956
|
+
const p = this;
|
|
2957
|
+
const sc = scalar;
|
|
2958
|
+
// Public-scalar callers may need 0, but n and larger values stay rejected here too.
|
|
2959
|
+
// Reducing them mod n would turn bad caller input into an accidental identity point.
|
|
2960
|
+
if (!Fn.isValid(sc))
|
|
2961
|
+
throw new RangeError('invalid scalar: out of range'); // 0 is valid
|
|
2962
|
+
if (sc === _0n || p.is0())
|
|
2963
|
+
return Point.ZERO;
|
|
2964
|
+
if (sc === _1n)
|
|
2965
|
+
return p;
|
|
2966
|
+
if (wnaf.hasWindowSize(this))
|
|
2967
|
+
return wnaf.mulUnsafe(p, sc, normalize); // precomputes
|
|
2968
|
+
const points = [];
|
|
2969
|
+
const scalars = [];
|
|
2970
|
+
pushWnafPair(points, scalars, p, sc);
|
|
2971
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
2972
|
+
}
|
|
2973
|
+
/**
|
|
2974
|
+
* Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).
|
|
2975
|
+
* Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism
|
|
2976
|
+
* (when available) halves the chain again by splitting each scalar into two half-width
|
|
2977
|
+
* parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.
|
|
2978
|
+
* Only for public scalars.
|
|
2979
|
+
*/
|
|
2980
|
+
mulAddUnsafe(a, other, b) {
|
|
2981
|
+
aprjpoint(other);
|
|
2982
|
+
const points = [];
|
|
2983
|
+
const scalars = [];
|
|
2984
|
+
pushWnafPair(points, scalars, this, a);
|
|
2985
|
+
pushWnafPair(points, scalars, other, b);
|
|
2986
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
2987
|
+
}
|
|
2988
|
+
/**
|
|
2989
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
2990
|
+
* (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
2991
|
+
* @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
2992
|
+
*/
|
|
2993
|
+
toAffine(invertedZ) {
|
|
2994
|
+
const p = this;
|
|
2995
|
+
let iz = invertedZ;
|
|
2996
|
+
if (iz != null && !Fp.isValid(iz))
|
|
2997
|
+
throw new RangeError('"invertedZ" expected valid field element');
|
|
2998
|
+
const { X, Y, Z } = p;
|
|
2999
|
+
// Fast-path for normalized points
|
|
3000
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
3001
|
+
return { x: X, y: Y };
|
|
3002
|
+
const is0 = p.is0();
|
|
3003
|
+
// If invZ was 0, we return zero point. However we still want to execute
|
|
3004
|
+
// all operations, so we replace invZ with a random number, 1.
|
|
3005
|
+
if (iz == null)
|
|
3006
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
3007
|
+
const x = Fp.mul(X, iz);
|
|
3008
|
+
const y = Fp.mul(Y, iz);
|
|
3009
|
+
const zz = Fp.mul(Z, iz);
|
|
3010
|
+
if (is0)
|
|
3011
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
3012
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
3013
|
+
throw new Error('invZ was invalid');
|
|
3014
|
+
return { x, y };
|
|
3015
|
+
}
|
|
3016
|
+
/**
|
|
3017
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
3018
|
+
* Always torsion-free for cofactor=1 curves.
|
|
3019
|
+
*/
|
|
3020
|
+
isTorsionFree() {
|
|
3021
|
+
if (cofactor === _1n)
|
|
3022
|
+
return true;
|
|
3023
|
+
if (isTorsionFree)
|
|
3024
|
+
return isTorsionFree(Point, this);
|
|
3025
|
+
// unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER
|
|
3026
|
+
return wnaf.mulUnsafe(this, CURVE_ORDER).is0();
|
|
3027
|
+
}
|
|
3028
|
+
clearCofactor() {
|
|
3029
|
+
if (cofactor === _1n)
|
|
3030
|
+
return this; // Fast-path
|
|
3031
|
+
if (clearCofactor)
|
|
3032
|
+
return clearCofactor(Point, this);
|
|
3033
|
+
// Default fallback assumes the cofactor fits the usual subgroup-scalar
|
|
3034
|
+
// multiplyUnsafe() contract. Curves with larger / structured cofactors
|
|
3035
|
+
// should define a clearCofactor override anyway (e.g. psi/Frobenius maps).
|
|
3036
|
+
return this.multiplyUnsafe(cofactor);
|
|
3037
|
+
}
|
|
3038
|
+
isSmallOrder() {
|
|
3039
|
+
if (cofactor === _1n)
|
|
3040
|
+
return this.is0(); // Fast-path
|
|
3041
|
+
return this.clearCofactor().is0();
|
|
3042
|
+
}
|
|
3043
|
+
toBytes(isCompressed = true) {
|
|
3044
|
+
abool(isCompressed, 'isCompressed');
|
|
3045
|
+
// assertValidity() covers on-curve and subgroup membership. The encoder below repeats the
|
|
3046
|
+
// infinity check rather than relying on this call, so it stays correct for any caller.
|
|
3047
|
+
this.assertValidity();
|
|
3048
|
+
return encodePoint(Point, this, isCompressed);
|
|
3049
|
+
}
|
|
3050
|
+
toHex(isCompressed = true) {
|
|
3051
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
3052
|
+
}
|
|
3053
|
+
toString() {
|
|
3054
|
+
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
const normalize = (points) => normalizeZ(Point, points);
|
|
3058
|
+
const wnaf = new ScalarMultiplier(Point, randomBytes$1);
|
|
3059
|
+
// Enable W=6 wNAF precomputes. Slows down first publicKey computation.
|
|
3060
|
+
// Disable for tiny toy curves, with scalar fields < 6 bits.
|
|
3061
|
+
if (wnaf.bits >= 6)
|
|
3062
|
+
Point.BASE.precompute(6);
|
|
3063
|
+
Object.freeze(Point.prototype);
|
|
3064
|
+
Object.freeze(Point);
|
|
3065
|
+
return Point;
|
|
3066
|
+
}
|
|
3067
|
+
// Points start with byte 0x02 when y is even; otherwise 0x03
|
|
3068
|
+
function pprefix(hasEvenY) {
|
|
3069
|
+
return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
|
|
3070
|
+
}
|
|
3071
|
+
function getWLengths(Fp, Fn) {
|
|
3072
|
+
return {
|
|
3073
|
+
secretKey: Fn.BYTES,
|
|
3074
|
+
publicKey: 1 + Fp.BYTES,
|
|
3075
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
3076
|
+
publicKeyHasPrefix: true,
|
|
3077
|
+
// Raw compact `(r || s)` signature width; DER and recovered signatures use
|
|
3078
|
+
// different lengths outside this helper.
|
|
3079
|
+
signature: 2 * Fn.BYTES,
|
|
3080
|
+
};
|
|
3081
|
+
}
|
|
3082
|
+
/**
|
|
3083
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3084
|
+
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
|
|
3085
|
+
* @param Point - Weierstrass point constructor.
|
|
3086
|
+
* @param ecdhOpts - Optional randomness helpers:
|
|
3087
|
+
* - `randomBytes` (optional): Optional RNG override.
|
|
3088
|
+
* @returns ECDH helper namespace.
|
|
3089
|
+
* @example
|
|
3090
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3091
|
+
*
|
|
3092
|
+
* ```ts
|
|
3093
|
+
* import { ecdh } from '@noble/curves/abstract/weierstrass.js';
|
|
3094
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3095
|
+
* const dh = ecdh(p256.Point);
|
|
3096
|
+
* const alice = dh.keygen();
|
|
3097
|
+
* const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);
|
|
3098
|
+
* ```
|
|
3099
|
+
*/
|
|
3100
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
3101
|
+
validatePointCons(Point);
|
|
3102
|
+
const { Fn } = Point;
|
|
3103
|
+
const randomBytes_ = ecdhOpts.randomBytes === undefined ? randomBytes : ecdhOpts.randomBytes;
|
|
3104
|
+
// Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte
|
|
3105
|
+
// minimum even on toy curves.
|
|
3106
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
|
|
3107
|
+
seed: Math.max(getMinHashLength(Fn.ORDER), 16),
|
|
3108
|
+
});
|
|
3109
|
+
function isValidSecretKey(secretKey) {
|
|
3110
|
+
try {
|
|
3111
|
+
const num = Fn.fromBytes(secretKey);
|
|
3112
|
+
return Fn.isValidNot0(num);
|
|
3113
|
+
}
|
|
3114
|
+
catch (error) {
|
|
3115
|
+
return false;
|
|
3116
|
+
}
|
|
3117
|
+
}
|
|
3118
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
3119
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
3120
|
+
try {
|
|
3121
|
+
const l = publicKey.length;
|
|
3122
|
+
if (isCompressed === true && l !== comp)
|
|
3123
|
+
return false;
|
|
3124
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
3125
|
+
return false;
|
|
3126
|
+
// SEC 1 §3.2.2: the identity is never a valid public key, even on curves whose codec
|
|
3127
|
+
// can decode it.
|
|
3128
|
+
return !Point.fromBytes(publicKey).is0();
|
|
3129
|
+
}
|
|
3130
|
+
catch (error) {
|
|
3131
|
+
return false;
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Produces cryptographically secure secret key from random of size
|
|
3136
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
3137
|
+
*/
|
|
3138
|
+
function randomSecretKey(seed) {
|
|
3139
|
+
seed = seed === undefined ? randomBytes_(lengths.seed) : seed;
|
|
3140
|
+
return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
|
|
3141
|
+
}
|
|
3142
|
+
/**
|
|
3143
|
+
* Computes public key for a secret key. Checks for validity of the secret key.
|
|
3144
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3145
|
+
* @returns Public key, full when isCompressed=false; short when isCompressed=true
|
|
3146
|
+
*/
|
|
3147
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
3148
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
|
|
3152
|
+
*/
|
|
3153
|
+
function isProbPub(item) {
|
|
3154
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
3155
|
+
const allowedLengths = Fn._lengths;
|
|
3156
|
+
if (!isBytes(item))
|
|
3157
|
+
return undefined;
|
|
3158
|
+
const l = abytes(item, undefined, 'key').length;
|
|
3159
|
+
const isPub = l === publicKey || l === publicKeyUncompressed;
|
|
3160
|
+
const isSec = l === secretKey || !!allowedLengths?.includes(l);
|
|
3161
|
+
// P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.
|
|
3162
|
+
if (isPub && isSec)
|
|
3163
|
+
return undefined;
|
|
3164
|
+
return isPub;
|
|
3165
|
+
}
|
|
3166
|
+
/**
|
|
3167
|
+
* ECDH (Elliptic Curve Diffie Hellman).
|
|
3168
|
+
* Computes encoded shared point from secret key A and public key B.
|
|
3169
|
+
* Checks: 1) secret key validity 2) shared key is on-curve.
|
|
3170
|
+
* Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.
|
|
3171
|
+
* Returns the encoded shared point on purpose: callers that need `x_P`
|
|
3172
|
+
* can derive it from the encoded point, but `x_P` alone cannot recover the
|
|
3173
|
+
* point/parity back.
|
|
3174
|
+
* This helper only exposes the fully validated public-key path, not cofactor DH.
|
|
3175
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3176
|
+
* @returns shared point encoding
|
|
3177
|
+
*/
|
|
3178
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
3179
|
+
if (isProbPub(secretKeyA) === true)
|
|
3180
|
+
throw new Error('first arg must be private key');
|
|
3181
|
+
if (isProbPub(publicKeyB) === false)
|
|
3182
|
+
throw new Error('second arg must be public key');
|
|
3183
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
3184
|
+
const b = Point.fromBytes(publicKeyB); // checks for being on-curve
|
|
3185
|
+
if (b.is0())
|
|
3186
|
+
throw new Error('invalid public key: point at infinity');
|
|
3187
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
3188
|
+
}
|
|
3189
|
+
const utils = {
|
|
3190
|
+
isValidSecretKey,
|
|
3191
|
+
isValidPublicKey,
|
|
3192
|
+
randomSecretKey,
|
|
3193
|
+
};
|
|
3194
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey);
|
|
3195
|
+
Object.freeze(utils);
|
|
3196
|
+
Object.freeze(lengths);
|
|
3197
|
+
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
|
|
3198
|
+
}
|
|
3199
|
+
/**
|
|
3200
|
+
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
|
|
3201
|
+
*
|
|
3202
|
+
* @param Point - created using {@link weierstrass} function
|
|
3203
|
+
* @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)
|
|
3204
|
+
* @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:
|
|
3205
|
+
* - `lowS`: Default low-S policy.
|
|
3206
|
+
* - `hmac`: HMAC implementation used by RFC6979 DRBG.
|
|
3207
|
+
* - `randomBytes`: Optional RNG override.
|
|
3208
|
+
* - `bits2int`: Optional hash-to-int conversion override.
|
|
3209
|
+
* - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.
|
|
3210
|
+
*
|
|
3211
|
+
* @returns ECDSA helper namespace.
|
|
3212
|
+
* @example
|
|
3213
|
+
* Create an ECDSA signer/verifier bundle for one curve implementation.
|
|
3214
|
+
*
|
|
3215
|
+
* ```ts
|
|
3216
|
+
* import { ecdsa } from '@noble/curves/abstract/weierstrass.js';
|
|
3217
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3218
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
3219
|
+
* const p256ecdsa = ecdsa(p256.Point, sha256);
|
|
3220
|
+
* const { secretKey, publicKey } = p256ecdsa.keygen();
|
|
3221
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
3222
|
+
* const sig = p256ecdsa.sign(msg, secretKey);
|
|
3223
|
+
* const isValid = p256ecdsa.verify(sig, msg, publicKey);
|
|
3224
|
+
* ```
|
|
3225
|
+
*/
|
|
3226
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
3227
|
+
validatePointCons(Point);
|
|
3228
|
+
// Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.
|
|
3229
|
+
const hash_ = hash;
|
|
3230
|
+
ahash(hash_);
|
|
3231
|
+
validateObject(ecdsaOpts, {}, {
|
|
3232
|
+
hmac: 'function',
|
|
3233
|
+
lowS: 'boolean',
|
|
3234
|
+
randomBytes: 'function',
|
|
3235
|
+
bits2int: 'function',
|
|
3236
|
+
bits2int_modN: 'function',
|
|
3237
|
+
});
|
|
3238
|
+
const opts = Object.assign({}, ecdsaOpts);
|
|
3239
|
+
const randomBytes$1 = opts.randomBytes === undefined ? randomBytes : opts.randomBytes;
|
|
3240
|
+
const hmac$1 = opts.hmac === undefined
|
|
3241
|
+
? (key, msg) => hmac(hash_, key, msg)
|
|
3242
|
+
: opts.hmac;
|
|
3243
|
+
const { Fp, Fn } = Point;
|
|
3244
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
3245
|
+
// Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG
|
|
3246
|
+
// once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without
|
|
3247
|
+
// working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on
|
|
3248
|
+
// every sign(). The shape of returned bytes is still validated (by mapHashToField) on every
|
|
3249
|
+
// blinded call, where breakage fails closed.
|
|
3250
|
+
const blindLength = getMinHashLength(CURVE_ORDER);
|
|
3251
|
+
const csprng = probeRandomBytes(randomBytes$1, blindLength);
|
|
3252
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);
|
|
3253
|
+
const defaultSigOpts = {
|
|
3254
|
+
prehash: true,
|
|
3255
|
+
lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,
|
|
3256
|
+
format: 'compact',
|
|
3257
|
+
extraEntropy: false,
|
|
3258
|
+
};
|
|
3259
|
+
// SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature
|
|
3260
|
+
// format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.
|
|
3261
|
+
// A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the
|
|
3262
|
+
// smallest such lift is 1 + 2n, not 2n.
|
|
3263
|
+
const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;
|
|
3264
|
+
function isBiggerThanHalfOrder(number) {
|
|
3265
|
+
const HALF = CURVE_ORDER >> _1n;
|
|
3266
|
+
return number > HALF;
|
|
3267
|
+
}
|
|
3268
|
+
function validateRS(title, num) {
|
|
3269
|
+
if (!Fn.isValidNot0(num))
|
|
3270
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
3271
|
+
return num;
|
|
3272
|
+
}
|
|
3273
|
+
function assertFieldSignIsSupported() {
|
|
3274
|
+
if (!Fp.isOdd)
|
|
3275
|
+
throw new Error("Field doesn't support isOdd");
|
|
3276
|
+
}
|
|
3277
|
+
// Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:
|
|
3278
|
+
// bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).
|
|
3279
|
+
function getRecoveryBit(x, y, r) {
|
|
3280
|
+
assertFieldSignIsSupported();
|
|
3281
|
+
return (x === r ? 0 : 2) | Number(Fp.isOdd(y));
|
|
3282
|
+
}
|
|
3283
|
+
function assertRecoverableCurve() {
|
|
3284
|
+
// ECDSA recovery only supports curves where the current recovery id can distinguish
|
|
3285
|
+
// q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.
|
|
3286
|
+
// SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.
|
|
3287
|
+
// The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.
|
|
3288
|
+
// To easily get i, we either need to:
|
|
3289
|
+
// a. increase amount of valid recid values (4, 5...); OR
|
|
3290
|
+
// b. prohibit recovered signatures for those curves.
|
|
3291
|
+
if (hasLargeRecoveryLifts)
|
|
3292
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
3293
|
+
}
|
|
3294
|
+
function validateSigLength(bytes, format) {
|
|
3295
|
+
validateSigFormat(format);
|
|
3296
|
+
const size = lengths.signature;
|
|
3297
|
+
const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
|
|
3298
|
+
return abytes(bytes, sizer);
|
|
3299
|
+
}
|
|
3300
|
+
/**
|
|
3301
|
+
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
|
|
3302
|
+
*/
|
|
3303
|
+
class Signature {
|
|
3304
|
+
r;
|
|
3305
|
+
s;
|
|
3306
|
+
recovery;
|
|
3307
|
+
constructor(r, s, recovery) {
|
|
3308
|
+
this.r = validateRS('r', r); // r in [1..N-1];
|
|
3309
|
+
this.s = validateRS('s', s); // s in [1..N-1];
|
|
3310
|
+
if (recovery != null) {
|
|
3311
|
+
assertRecoverableCurve();
|
|
3312
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
3313
|
+
throw new Error('invalid recovery id');
|
|
3314
|
+
this.recovery = recovery;
|
|
3315
|
+
}
|
|
3316
|
+
Object.freeze(this);
|
|
3317
|
+
}
|
|
3318
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
3319
|
+
validateSigLength(bytes, format);
|
|
3320
|
+
let recid;
|
|
3321
|
+
if (format === 'der') {
|
|
3322
|
+
// Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the
|
|
3323
|
+
// total bound conservative so malformed inputs are rejected before parsing any INTEGER.
|
|
3324
|
+
if (bytes.length > 2 * Fn.BYTES + 16)
|
|
3325
|
+
throw new DER.Err('invalid signature: DER signature too long');
|
|
3326
|
+
const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);
|
|
3327
|
+
return new Signature(r, s);
|
|
3328
|
+
}
|
|
3329
|
+
if (format === 'recovered') {
|
|
3330
|
+
recid = bytes[0];
|
|
3331
|
+
format = 'compact';
|
|
3332
|
+
bytes = bytes.subarray(1);
|
|
3333
|
+
}
|
|
3334
|
+
const L = lengths.signature / 2;
|
|
3335
|
+
const r = bytes.subarray(0, L);
|
|
3336
|
+
const s = bytes.subarray(L, L * 2);
|
|
3337
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
3338
|
+
}
|
|
3339
|
+
static fromHex(hex, format) {
|
|
3340
|
+
return this.fromBytes(hexToBytes(hex), format);
|
|
3341
|
+
}
|
|
3342
|
+
assertRecovery() {
|
|
3343
|
+
const { recovery } = this;
|
|
3344
|
+
if (recovery == null)
|
|
3345
|
+
throw new Error('invalid recovery id: must be present');
|
|
3346
|
+
return recovery;
|
|
3347
|
+
}
|
|
3348
|
+
addRecoveryBit(recovery) {
|
|
3349
|
+
return new Signature(this.r, this.s, recovery);
|
|
3350
|
+
}
|
|
3351
|
+
// Unlike the top-level helper below, this method expects a digest that has
|
|
3352
|
+
// already been hashed to the curve's message representative.
|
|
3353
|
+
recoverPublicKey(messageHash) {
|
|
3354
|
+
const { r, s } = this;
|
|
3355
|
+
const recovery = this.assertRecovery();
|
|
3356
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
|
|
3357
|
+
if (!Fp.isValid(radj))
|
|
3358
|
+
throw new Error('invalid recovery id: sig.r+curve.n != R.x');
|
|
3359
|
+
const x = Fp.toBytes(radj);
|
|
3360
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
3361
|
+
const ir = Fn.inv(radj); // r^-1
|
|
3362
|
+
const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash
|
|
3363
|
+
const u1 = Fn.create(-h * ir); // -hr^-1
|
|
3364
|
+
const u2 = Fn.create(s * ir); // sr^-1
|
|
3365
|
+
// (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
|
|
3366
|
+
const Q = Point.BASE.mulAddUnsafe(u1, R, u2);
|
|
3367
|
+
if (Q.is0())
|
|
3368
|
+
throw new Error('invalid recovery: point at infinify');
|
|
3369
|
+
Q.assertValidity();
|
|
3370
|
+
return Q;
|
|
3371
|
+
}
|
|
3372
|
+
// Signatures should be low-s, to prevent malleability.
|
|
3373
|
+
hasHighS() {
|
|
3374
|
+
return isBiggerThanHalfOrder(this.s);
|
|
3375
|
+
}
|
|
3376
|
+
toBytes(format = defaultSigOpts.format) {
|
|
3377
|
+
validateSigFormat(format);
|
|
3378
|
+
if (format === 'der')
|
|
3379
|
+
return hexToBytes(DER.hexFromSig(this));
|
|
3380
|
+
const { r, s } = this;
|
|
3381
|
+
const rb = Fn.toBytes(r);
|
|
3382
|
+
const sb = Fn.toBytes(s);
|
|
3383
|
+
if (format === 'recovered') {
|
|
3384
|
+
assertRecoverableCurve();
|
|
3385
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
3386
|
+
}
|
|
3387
|
+
return concatBytes(rb, sb);
|
|
3388
|
+
}
|
|
3389
|
+
toHex(format) {
|
|
3390
|
+
return bytesToHex(this.toBytes(format));
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
Object.freeze(Signature.prototype);
|
|
3394
|
+
Object.freeze(Signature);
|
|
3395
|
+
// RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
|
|
3396
|
+
// FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
|
|
3397
|
+
// bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
|
|
3398
|
+
// int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
|
|
3399
|
+
const bits2int = opts.bits2int === undefined
|
|
3400
|
+
? function bits2int_def(bytes) {
|
|
3401
|
+
// Our custom check "just in case", for protection against DoS
|
|
3402
|
+
if (bytes.length > 8192)
|
|
3403
|
+
throw new Error('input is too large');
|
|
3404
|
+
// For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
|
|
3405
|
+
// for some cases, since bytes.length * 8 is not actual bitLength.
|
|
3406
|
+
const num = bytesToNumberBE(bytes); // check for == u8 done here
|
|
3407
|
+
const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
|
|
3408
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
3409
|
+
}
|
|
3410
|
+
: opts.bits2int;
|
|
3411
|
+
const bits2int_modN = opts.bits2int_modN === undefined
|
|
3412
|
+
? function bits2int_modN_def(bytes) {
|
|
3413
|
+
return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
|
|
3414
|
+
}
|
|
3415
|
+
: opts.bits2int_modN;
|
|
3416
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
3417
|
+
// Pads output with zero as per spec.
|
|
3418
|
+
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
|
|
3419
|
+
function int2octets(num) {
|
|
3420
|
+
aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
|
|
3421
|
+
return Fn.toBytes(num);
|
|
3422
|
+
}
|
|
3423
|
+
function validateMsgAndHash(message, prehash) {
|
|
3424
|
+
abytes(message, undefined, 'message');
|
|
3425
|
+
return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);
|
|
3426
|
+
}
|
|
3427
|
+
/**
|
|
3428
|
+
* Steps A, D of RFC6979 3.2.
|
|
3429
|
+
* Creates RFC6979 seed; converts msg/privKey to numbers.
|
|
3430
|
+
* Used only in sign, not in verify.
|
|
3431
|
+
*
|
|
3432
|
+
* Warning: we cannot assume here that message has same amount of bytes as curve order,
|
|
3433
|
+
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
|
|
3434
|
+
*/
|
|
3435
|
+
function prepSig(message, secretKey, opts) {
|
|
3436
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
3437
|
+
message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
|
|
3438
|
+
// We can't later call bits2octets, since nested bits2int is broken for curves
|
|
3439
|
+
// with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
|
|
3440
|
+
// const bits2octets = (bits) => int2octets(bits2int_modN(bits))
|
|
3441
|
+
const h1int = bits2int_modN(message);
|
|
3442
|
+
const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint
|
|
3443
|
+
if (!Fn.isValidNot0(d))
|
|
3444
|
+
throw new Error('invalid private key');
|
|
3445
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3446
|
+
// extraEntropy. RFC6979 3.6: additional k' (optional).
|
|
3447
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
3448
|
+
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
3449
|
+
// gen random bytes OR pass as-is
|
|
3450
|
+
const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
|
|
3451
|
+
seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes
|
|
3452
|
+
}
|
|
3453
|
+
const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
|
|
3454
|
+
const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!
|
|
3455
|
+
// Converts signature params into point w r/s, checks result for validity.
|
|
3456
|
+
// To transform k => Signature:
|
|
3457
|
+
// q = k⋅G
|
|
3458
|
+
// r = q.x mod n
|
|
3459
|
+
// s = k^-1(m + rd) mod n
|
|
3460
|
+
// The nonce inversion is blinded: with random b ∈ [1,n−1], s = (bk)^-1(bm + bdr) per
|
|
3461
|
+
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean
|
|
3462
|
+
// loop count depends on its input (cf. Minerva), but here it only ever sees b·k — uniformly
|
|
3463
|
+
// random, independent of k — so its timing reveals nothing about the nonce; b also masks d in
|
|
3464
|
+
// the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion
|
|
3465
|
+
// (invertCt), whose control flow is data-independent, at ~4x the inversion cost.
|
|
3466
|
+
function k2sig(kBytes) {
|
|
3467
|
+
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
|
|
3468
|
+
// Important: all mod() calls here must be done over N
|
|
3469
|
+
const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
|
|
3470
|
+
if (!Fn.isValidNot0(k))
|
|
3471
|
+
return; // Valid scalars (including k) must be in 1..N-1
|
|
3472
|
+
const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
|
|
3473
|
+
const r = Fn.create(q.x); // r = q.x mod n
|
|
3474
|
+
if (r === _0n)
|
|
3475
|
+
return;
|
|
3476
|
+
let s;
|
|
3477
|
+
if (csprng !== undefined) {
|
|
3478
|
+
// mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.
|
|
3479
|
+
const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));
|
|
3480
|
+
const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k
|
|
3481
|
+
const bm = Fn.mul(b, m);
|
|
3482
|
+
const bd = Fn.mul(b, d);
|
|
3483
|
+
s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n
|
|
3484
|
+
}
|
|
3485
|
+
else {
|
|
3486
|
+
const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow
|
|
3487
|
+
s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n
|
|
3488
|
+
}
|
|
3489
|
+
if (s === _0n)
|
|
3490
|
+
return;
|
|
3491
|
+
let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)
|
|
3492
|
+
let normS = s;
|
|
3493
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
3494
|
+
normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N
|
|
3495
|
+
recovery ^= 1;
|
|
3496
|
+
}
|
|
3497
|
+
return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);
|
|
3498
|
+
}
|
|
3499
|
+
return { seed, k2sig };
|
|
3500
|
+
}
|
|
3501
|
+
/**
|
|
3502
|
+
* Signs a message or message hash with a secret key.
|
|
3503
|
+
* With the default `prehash: true`, raw message bytes are hashed internally;
|
|
3504
|
+
* only `{ prehash: false }` expects a caller-supplied digest.
|
|
3505
|
+
*
|
|
3506
|
+
* ```
|
|
3507
|
+
* sign(m, d) where
|
|
3508
|
+
* k = rfc6979_hmac_drbg(m, d)
|
|
3509
|
+
* (x, y) = G × k
|
|
3510
|
+
* r = x mod n
|
|
3511
|
+
* s = (m + dr) / k mod n
|
|
3512
|
+
* ```
|
|
3513
|
+
*/
|
|
3514
|
+
function sign(message, secretKey, opts = {}) {
|
|
3515
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
|
|
3516
|
+
const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac$1);
|
|
3517
|
+
const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
|
|
3518
|
+
return sig.toBytes(opts.format);
|
|
3519
|
+
}
|
|
3520
|
+
/**
|
|
3521
|
+
* Verifies a signature against message and public key.
|
|
3522
|
+
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
|
|
3523
|
+
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
|
|
3524
|
+
*
|
|
3525
|
+
* ```
|
|
3526
|
+
* verify(r, s, h, P) where
|
|
3527
|
+
* u1 = hs^-1 mod n
|
|
3528
|
+
* u2 = rs^-1 mod n
|
|
3529
|
+
* R = u1⋅G + u2⋅P
|
|
3530
|
+
* mod(R.x, n) == r
|
|
3531
|
+
* ```
|
|
3532
|
+
*/
|
|
3533
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
3534
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
3535
|
+
publicKey = abytes(publicKey, undefined, 'publicKey');
|
|
3536
|
+
message = validateMsgAndHash(message, prehash);
|
|
3537
|
+
if (!isBytes(signature)) {
|
|
3538
|
+
const end = signature instanceof Signature ? ', use sig.toBytes()' : '';
|
|
3539
|
+
throw new Error('verify expects Uint8Array signature' + end);
|
|
3540
|
+
}
|
|
3541
|
+
validateSigLength(signature, format); // execute this twice because we want loud error
|
|
3542
|
+
try {
|
|
3543
|
+
const sig = Signature.fromBytes(signature, format);
|
|
3544
|
+
const P = Point.fromBytes(publicKey);
|
|
3545
|
+
// SEC 1 verification keys must not be the identity, even when the generic point decoder
|
|
3546
|
+
// permits infinity for another protocol (for example, a pairing curve).
|
|
3547
|
+
if (P.is0())
|
|
3548
|
+
return false;
|
|
3549
|
+
if (lowS && sig.hasHighS())
|
|
3550
|
+
return false;
|
|
3551
|
+
const { r, s } = sig;
|
|
3552
|
+
const h = bits2int_modN(message); // mod n, not mod p
|
|
3553
|
+
const is = Fn.inv(s); // s^-1 mod n
|
|
3554
|
+
const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
|
|
3555
|
+
const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
|
|
3556
|
+
const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1⋅G + u2⋅P, joint Strauss–Shamir
|
|
3557
|
+
if (R.is0())
|
|
3558
|
+
return false;
|
|
3559
|
+
const q = R.toAffine();
|
|
3560
|
+
const v = Fn.create(q.x); // v = R.x mod n
|
|
3561
|
+
if (v !== r)
|
|
3562
|
+
return false;
|
|
3563
|
+
// R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),
|
|
3564
|
+
// so binding the signature to its recovery id only needs R's parity/overflow bits.
|
|
3565
|
+
if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))
|
|
3566
|
+
return false;
|
|
3567
|
+
return true;
|
|
3568
|
+
}
|
|
3569
|
+
catch (e) {
|
|
3570
|
+
return false;
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
3574
|
+
// Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message
|
|
3575
|
+
// bytes first unless the caller passes `{ prehash: false }`.
|
|
3576
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
3577
|
+
message = validateMsgAndHash(message, prehash);
|
|
3578
|
+
return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
|
|
3579
|
+
}
|
|
3580
|
+
// utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.
|
|
3581
|
+
return Object.freeze({
|
|
3582
|
+
keygen,
|
|
3583
|
+
getPublicKey,
|
|
3584
|
+
getSharedSecret,
|
|
3585
|
+
utils,
|
|
3586
|
+
lengths,
|
|
3587
|
+
Point,
|
|
3588
|
+
sign,
|
|
3589
|
+
verify,
|
|
3590
|
+
recoverPublicKey,
|
|
3591
|
+
Signature,
|
|
3592
|
+
hash: hash_,
|
|
3593
|
+
});
|
|
3594
|
+
}
|
|
3595
|
+
|
|
3596
|
+
export { validatePointCons as A, bytesToHex as B, hexToBytes as C, numberToBytesBE as D, Field as F, asafenumber as a, abytes as b, copyBytes as c, concatBytes as d, ecdsa as e, asciiToBytes as f, bytesToNumberBE as g, hmac as h, isBytes as i, validateField as j, aarray as k, FpInvertBatch as l, mod as m, FpIsSquare as n, notImplemented as o, pow2 as p, getMinHashLength as q, mapHashToField as r, randomBytes as s, bitLen as t, FpPow as u, validateObject as v, weierstrass as w, FpLegendre as x, aInRange as y, bitGet as z };
|