@terminal3/t3n-sdk 5.14.0 → 5.15.2
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/dist/cli/index.js +1 -1
- package/dist/index.d.ts +173 -10
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/scripts/sign-trust-manifest.mjs +3903 -0
- package/package.json +1 -1
|
@@ -0,0 +1,3903 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
4
|
+
* @param a - value to test
|
|
5
|
+
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
6
|
+
* @example
|
|
7
|
+
* Check whether a value is a Uint8Array-compatible view.
|
|
8
|
+
* ```ts
|
|
9
|
+
* isBytes(new Uint8Array([1, 2, 3]));
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
function isBytes$1(a) {
|
|
13
|
+
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
|
|
14
|
+
// The fallback still requires a real ArrayBuffer view, so plain
|
|
15
|
+
// JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
|
|
16
|
+
// `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
|
17
|
+
return (a instanceof Uint8Array ||
|
|
18
|
+
(ArrayBuffer.isView(a) &&
|
|
19
|
+
a.constructor.name === 'Uint8Array' &&
|
|
20
|
+
'BYTES_PER_ELEMENT' in a &&
|
|
21
|
+
a.BYTES_PER_ELEMENT === 1));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Asserts something is a non-negative integer.
|
|
25
|
+
* @param n - number to validate
|
|
26
|
+
* @param title - label included in thrown errors
|
|
27
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
28
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
29
|
+
* @example
|
|
30
|
+
* Validate a non-negative integer option.
|
|
31
|
+
* ```ts
|
|
32
|
+
* anumber(32, 'length');
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
function anumber$1(n, title = '') {
|
|
36
|
+
if (typeof n !== 'number') {
|
|
37
|
+
const prefix = title && `"${title}" `;
|
|
38
|
+
throw new TypeError(`${prefix}expected number, got ${typeof n}`);
|
|
39
|
+
}
|
|
40
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
41
|
+
const prefix = title && `"${title}" `;
|
|
42
|
+
throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Asserts something is Uint8Array.
|
|
47
|
+
* @param value - value to validate
|
|
48
|
+
* @param length - optional exact length constraint
|
|
49
|
+
* @param title - label included in thrown errors
|
|
50
|
+
* @returns The validated byte array.
|
|
51
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
52
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
53
|
+
* @example
|
|
54
|
+
* Validate that a value is a byte array.
|
|
55
|
+
* ```ts
|
|
56
|
+
* abytes(new Uint8Array([1, 2, 3]));
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
function abytes$1(value, length, title = '') {
|
|
60
|
+
const bytes = isBytes$1(value);
|
|
61
|
+
const len = value?.length;
|
|
62
|
+
const needsLen = length !== undefined;
|
|
63
|
+
if (!bytes || (needsLen && len !== length)) {
|
|
64
|
+
const prefix = title && `"${title}" `;
|
|
65
|
+
const ofLen = needsLen ? ` of length ${length}` : '';
|
|
66
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
67
|
+
const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
|
|
68
|
+
if (!bytes)
|
|
69
|
+
throw new TypeError(message);
|
|
70
|
+
throw new RangeError(message);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Asserts something is a wrapped hash constructor.
|
|
76
|
+
* @param h - hash constructor to validate
|
|
77
|
+
* @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
|
|
78
|
+
* @throws On invalid hash metadata ranges or values. {@link RangeError}
|
|
79
|
+
* @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
|
|
80
|
+
* @example
|
|
81
|
+
* Validate a callable hash wrapper.
|
|
82
|
+
* ```ts
|
|
83
|
+
* import { ahash } from '@noble/hashes/utils.js';
|
|
84
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
85
|
+
* ahash(sha256);
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
function ahash(h) {
|
|
89
|
+
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
90
|
+
throw new TypeError('Hash must wrapped by utils.createHasher');
|
|
91
|
+
anumber$1(h.outputLen);
|
|
92
|
+
anumber$1(h.blockLen);
|
|
93
|
+
// HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
|
|
94
|
+
// validation and can produce empty outputs instead of failing fast.
|
|
95
|
+
if (h.outputLen < 1)
|
|
96
|
+
throw new Error('"outputLen" must be >= 1');
|
|
97
|
+
if (h.blockLen < 1)
|
|
98
|
+
throw new Error('"blockLen" must be >= 1');
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Asserts a hash instance has not been destroyed or finished.
|
|
102
|
+
* @param instance - hash instance to validate
|
|
103
|
+
* @param checkFinished - whether to reject finalized instances
|
|
104
|
+
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
105
|
+
* @example
|
|
106
|
+
* Validate that a hash instance is still usable.
|
|
107
|
+
* ```ts
|
|
108
|
+
* import { aexists } from '@noble/hashes/utils.js';
|
|
109
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
110
|
+
* const hash = sha256.create();
|
|
111
|
+
* aexists(hash);
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
function aexists(instance, checkFinished = true) {
|
|
115
|
+
if (instance.destroyed)
|
|
116
|
+
throw new Error('Hash instance has been destroyed');
|
|
117
|
+
if (checkFinished && instance.finished)
|
|
118
|
+
throw new Error('Hash#digest() has already been called');
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Asserts output is a sufficiently-sized byte array.
|
|
122
|
+
* @param out - destination buffer
|
|
123
|
+
* @param instance - hash instance providing output length
|
|
124
|
+
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
125
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
126
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
127
|
+
* @example
|
|
128
|
+
* Validate a caller-provided digest buffer.
|
|
129
|
+
* ```ts
|
|
130
|
+
* import { aoutput } from '@noble/hashes/utils.js';
|
|
131
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
132
|
+
* const hash = sha256.create();
|
|
133
|
+
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
function aoutput(out, instance) {
|
|
137
|
+
abytes$1(out, undefined, 'digestInto() output');
|
|
138
|
+
const min = instance.outputLen;
|
|
139
|
+
if (out.length < min) {
|
|
140
|
+
throw new RangeError('"digestInto() output" expected to be of length >=' + min);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
145
|
+
* @param arrays - arrays to overwrite with zeros
|
|
146
|
+
* @example
|
|
147
|
+
* Zeroize sensitive buffers in place.
|
|
148
|
+
* ```ts
|
|
149
|
+
* clean(new Uint8Array([1, 2, 3]));
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
function clean(...arrays) {
|
|
153
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
154
|
+
arrays[i].fill(0);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Creates a DataView for byte-level manipulation.
|
|
159
|
+
* @param arr - source typed array
|
|
160
|
+
* @returns DataView over the same buffer region.
|
|
161
|
+
* @example
|
|
162
|
+
* Create a DataView over an existing buffer.
|
|
163
|
+
* ```ts
|
|
164
|
+
* createView(new Uint8Array(4));
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
function createView(arr) {
|
|
168
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Rotate-right operation for uint32 values.
|
|
172
|
+
* @param word - source word
|
|
173
|
+
* @param shift - shift amount in bits
|
|
174
|
+
* @returns Rotated word.
|
|
175
|
+
* @example
|
|
176
|
+
* Rotate a 32-bit word to the right.
|
|
177
|
+
* ```ts
|
|
178
|
+
* rotr(0x12345678, 8);
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
function rotr(word, shift) {
|
|
182
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
183
|
+
}
|
|
184
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
185
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
186
|
+
// @ts-ignore
|
|
187
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
188
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
189
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
190
|
+
/**
|
|
191
|
+
* Convert byte array to hex string.
|
|
192
|
+
* Uses the built-in function when available and assumes it matches the tested
|
|
193
|
+
* fallback semantics.
|
|
194
|
+
* @param bytes - bytes to encode
|
|
195
|
+
* @returns Lowercase hexadecimal string.
|
|
196
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
197
|
+
* @example
|
|
198
|
+
* Convert bytes to lowercase hexadecimal.
|
|
199
|
+
* ```ts
|
|
200
|
+
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
function bytesToHex$1(bytes) {
|
|
204
|
+
abytes$1(bytes);
|
|
205
|
+
// @ts-ignore
|
|
206
|
+
if (hasHexBuiltin)
|
|
207
|
+
return bytes.toHex();
|
|
208
|
+
// pre-caching improves the speed 6x
|
|
209
|
+
let hex = '';
|
|
210
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
211
|
+
hex += hexes[bytes[i]];
|
|
212
|
+
}
|
|
213
|
+
return hex;
|
|
214
|
+
}
|
|
215
|
+
// We use optimized technique to convert hex string to byte array
|
|
216
|
+
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
217
|
+
function asciiToBase16(ch) {
|
|
218
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
219
|
+
return ch - asciis._0; // '2' => 50-48
|
|
220
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
221
|
+
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
|
222
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
223
|
+
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
228
|
+
* @param hex - hexadecimal string to decode
|
|
229
|
+
* @returns Decoded bytes.
|
|
230
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
231
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
232
|
+
* @example
|
|
233
|
+
* Decode lowercase hexadecimal into bytes.
|
|
234
|
+
* ```ts
|
|
235
|
+
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
236
|
+
* ```
|
|
237
|
+
*/
|
|
238
|
+
function hexToBytes$1(hex) {
|
|
239
|
+
if (typeof hex !== 'string')
|
|
240
|
+
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
241
|
+
if (hasHexBuiltin) {
|
|
242
|
+
try {
|
|
243
|
+
return Uint8Array.fromHex(hex);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
if (error instanceof SyntaxError)
|
|
247
|
+
throw new RangeError(error.message);
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const hl = hex.length;
|
|
252
|
+
const al = hl / 2;
|
|
253
|
+
if (hl % 2)
|
|
254
|
+
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
|
255
|
+
const array = new Uint8Array(al);
|
|
256
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
257
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
258
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
259
|
+
if (n1 === undefined || n2 === undefined) {
|
|
260
|
+
const char = hex[hi] + hex[hi + 1];
|
|
261
|
+
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
262
|
+
}
|
|
263
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
264
|
+
}
|
|
265
|
+
return array;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Copies several Uint8Arrays into one.
|
|
269
|
+
* @param arrays - arrays to concatenate
|
|
270
|
+
* @returns Concatenated byte array.
|
|
271
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
272
|
+
* @example
|
|
273
|
+
* Concatenate multiple byte arrays.
|
|
274
|
+
* ```ts
|
|
275
|
+
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
function concatBytes$1(...arrays) {
|
|
279
|
+
let sum = 0;
|
|
280
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
281
|
+
const a = arrays[i];
|
|
282
|
+
abytes$1(a);
|
|
283
|
+
sum += a.length;
|
|
284
|
+
}
|
|
285
|
+
const res = new Uint8Array(sum);
|
|
286
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
287
|
+
const a = arrays[i];
|
|
288
|
+
res.set(a, pad);
|
|
289
|
+
pad += a.length;
|
|
290
|
+
}
|
|
291
|
+
return res;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Creates a callable hash function from a stateful class constructor.
|
|
295
|
+
* @param hashCons - hash constructor or factory
|
|
296
|
+
* @param info - optional metadata such as DER OID
|
|
297
|
+
* @returns Frozen callable hash wrapper with `.create()`.
|
|
298
|
+
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
299
|
+
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
300
|
+
* init time.
|
|
301
|
+
* @example
|
|
302
|
+
* Wrap a stateful hash constructor into a callable helper.
|
|
303
|
+
* ```ts
|
|
304
|
+
* import { createHasher } from '@noble/hashes/utils.js';
|
|
305
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
306
|
+
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
307
|
+
* wrapped(new Uint8Array([1]));
|
|
308
|
+
* ```
|
|
309
|
+
*/
|
|
310
|
+
function createHasher(hashCons, info = {}) {
|
|
311
|
+
const hashC = (msg, opts) => hashCons(opts)
|
|
312
|
+
.update(msg)
|
|
313
|
+
.digest();
|
|
314
|
+
const tmp = hashCons(undefined);
|
|
315
|
+
hashC.outputLen = tmp.outputLen;
|
|
316
|
+
hashC.blockLen = tmp.blockLen;
|
|
317
|
+
hashC.canXOF = tmp.canXOF;
|
|
318
|
+
hashC.create = (opts) => hashCons(opts);
|
|
319
|
+
Object.assign(hashC, info);
|
|
320
|
+
return Object.freeze(hashC);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
|
|
324
|
+
* @param bytesLength - number of random bytes to generate
|
|
325
|
+
* @returns Random bytes.
|
|
326
|
+
* The platform `getRandomValues()` implementation still defines any
|
|
327
|
+
* single-call length cap, and this helper rejects oversize requests
|
|
328
|
+
* with a stable library `RangeError` instead of host-specific errors.
|
|
329
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
330
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
331
|
+
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
|
|
332
|
+
* @example
|
|
333
|
+
* Generate a fresh random key or nonce.
|
|
334
|
+
* ```ts
|
|
335
|
+
* const key = randomBytes(16);
|
|
336
|
+
* ```
|
|
337
|
+
*/
|
|
338
|
+
function randomBytes$1(bytesLength = 32) {
|
|
339
|
+
// Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
|
|
340
|
+
anumber$1(bytesLength, 'bytesLength');
|
|
341
|
+
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
|
342
|
+
if (typeof cr?.getRandomValues !== 'function')
|
|
343
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
344
|
+
// Web Cryptography API Level 2 §10.1.1:
|
|
345
|
+
// if `byteLength > 65536`, throw `QuotaExceededError`.
|
|
346
|
+
// Keep the guard explicit so callers can see the quota in code
|
|
347
|
+
// instead of discovering it by reading the spec or host errors.
|
|
348
|
+
// This wrapper surfaces the same quota as a stable library RangeError.
|
|
349
|
+
if (bytesLength > 65536)
|
|
350
|
+
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
351
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
355
|
+
* @param suffix - final OID byte for the selected hash.
|
|
356
|
+
* The helper accepts any byte even though only the documented NIST hash
|
|
357
|
+
* suffixes are meaningful downstream.
|
|
358
|
+
* @returns Object containing the DER-encoded OID.
|
|
359
|
+
* @example
|
|
360
|
+
* Build OID metadata for a NIST hash.
|
|
361
|
+
* ```ts
|
|
362
|
+
* oidNist(0x01);
|
|
363
|
+
* ```
|
|
364
|
+
*/
|
|
365
|
+
const oidNist = (suffix) => ({
|
|
366
|
+
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
|
367
|
+
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
|
368
|
+
oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Internal Merkle-Damgard hash utils.
|
|
373
|
+
* @module
|
|
374
|
+
*/
|
|
375
|
+
/**
|
|
376
|
+
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
|
377
|
+
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
|
378
|
+
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
|
379
|
+
* set the same bit.
|
|
380
|
+
* @param a - selector word
|
|
381
|
+
* @param b - word chosen when selector bit is set
|
|
382
|
+
* @param c - word chosen when selector bit is clear
|
|
383
|
+
* @returns Mixed 32-bit word.
|
|
384
|
+
* @example
|
|
385
|
+
* Combine three words with the shared 32-bit choice primitive.
|
|
386
|
+
* ```ts
|
|
387
|
+
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
|
388
|
+
* ```
|
|
389
|
+
*/
|
|
390
|
+
function Chi(a, b, c) {
|
|
391
|
+
return (a & b) ^ (~a & c);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
|
395
|
+
* Returns bits shared by at least two inputs.
|
|
396
|
+
* @param a - first input word
|
|
397
|
+
* @param b - second input word
|
|
398
|
+
* @param c - third input word
|
|
399
|
+
* @returns Mixed 32-bit word.
|
|
400
|
+
* @example
|
|
401
|
+
* Combine three words with the shared 32-bit majority primitive.
|
|
402
|
+
* ```ts
|
|
403
|
+
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
|
404
|
+
* ```
|
|
405
|
+
*/
|
|
406
|
+
function Maj(a, b, c) {
|
|
407
|
+
return (a & b) ^ (a & c) ^ (b & c);
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Merkle-Damgard hash construction base class.
|
|
411
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
412
|
+
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
|
413
|
+
* strings with partial-byte tails.
|
|
414
|
+
* @param blockLen - internal block size in bytes
|
|
415
|
+
* @param outputLen - digest size in bytes
|
|
416
|
+
* @param padOffset - trailing length field size in bytes
|
|
417
|
+
* @param isLE - whether length and state words are encoded in little-endian
|
|
418
|
+
* @example
|
|
419
|
+
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
|
420
|
+
* ```ts
|
|
421
|
+
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
|
422
|
+
* const hash = new _SHA1();
|
|
423
|
+
* hash.update(new Uint8Array([97, 98, 99]));
|
|
424
|
+
* hash.digest();
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
class HashMD {
|
|
428
|
+
blockLen;
|
|
429
|
+
outputLen;
|
|
430
|
+
canXOF = false;
|
|
431
|
+
padOffset;
|
|
432
|
+
isLE;
|
|
433
|
+
// For partial updates less than block size
|
|
434
|
+
buffer;
|
|
435
|
+
view;
|
|
436
|
+
finished = false;
|
|
437
|
+
length = 0;
|
|
438
|
+
pos = 0;
|
|
439
|
+
destroyed = false;
|
|
440
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
441
|
+
this.blockLen = blockLen;
|
|
442
|
+
this.outputLen = outputLen;
|
|
443
|
+
this.padOffset = padOffset;
|
|
444
|
+
this.isLE = isLE;
|
|
445
|
+
this.buffer = new Uint8Array(blockLen);
|
|
446
|
+
this.view = createView(this.buffer);
|
|
447
|
+
}
|
|
448
|
+
update(data) {
|
|
449
|
+
aexists(this);
|
|
450
|
+
abytes$1(data);
|
|
451
|
+
const { view, buffer, blockLen } = this;
|
|
452
|
+
const len = data.length;
|
|
453
|
+
for (let pos = 0; pos < len;) {
|
|
454
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
455
|
+
// Fast path only when there is no buffered partial block: `take === blockLen` implies
|
|
456
|
+
// `this.pos === 0`, so we can process full blocks directly from the input view.
|
|
457
|
+
if (take === blockLen) {
|
|
458
|
+
const dataView = createView(data);
|
|
459
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
460
|
+
this.process(dataView, pos);
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
464
|
+
this.pos += take;
|
|
465
|
+
pos += take;
|
|
466
|
+
if (this.pos === blockLen) {
|
|
467
|
+
this.process(view, 0);
|
|
468
|
+
this.pos = 0;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
this.length += data.length;
|
|
472
|
+
this.roundClean();
|
|
473
|
+
return this;
|
|
474
|
+
}
|
|
475
|
+
digestInto(out) {
|
|
476
|
+
aexists(this);
|
|
477
|
+
aoutput(out, this);
|
|
478
|
+
this.finished = true;
|
|
479
|
+
// Padding
|
|
480
|
+
// We can avoid allocation of buffer for padding completely if it
|
|
481
|
+
// was previously not allocated here. But it won't change performance.
|
|
482
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
483
|
+
let { pos } = this;
|
|
484
|
+
// append the bit '1' to the message
|
|
485
|
+
buffer[pos++] = 0b10000000;
|
|
486
|
+
clean(this.buffer.subarray(pos));
|
|
487
|
+
// we have less than padOffset left in buffer, so we cannot put length in
|
|
488
|
+
// current block, need process it and pad again
|
|
489
|
+
if (this.padOffset > blockLen - pos) {
|
|
490
|
+
this.process(view, 0);
|
|
491
|
+
pos = 0;
|
|
492
|
+
}
|
|
493
|
+
// Pad until full block byte with zeros
|
|
494
|
+
for (let i = pos; i < blockLen; i++)
|
|
495
|
+
buffer[i] = 0;
|
|
496
|
+
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
|
|
497
|
+
// the padding fill above, and JS will overflow before user input can make that half non-zero.
|
|
498
|
+
// So we only need to write the low 64 bits here.
|
|
499
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
500
|
+
this.process(view, 0);
|
|
501
|
+
const oview = createView(out);
|
|
502
|
+
const len = this.outputLen;
|
|
503
|
+
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
|
|
504
|
+
if (len % 4)
|
|
505
|
+
throw new Error('_sha2: outputLen must be aligned to 32bit');
|
|
506
|
+
const outLen = len / 4;
|
|
507
|
+
const state = this.get();
|
|
508
|
+
if (outLen > state.length)
|
|
509
|
+
throw new Error('_sha2: outputLen bigger than state');
|
|
510
|
+
for (let i = 0; i < outLen; i++)
|
|
511
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
512
|
+
}
|
|
513
|
+
digest() {
|
|
514
|
+
const { buffer, outputLen } = this;
|
|
515
|
+
this.digestInto(buffer);
|
|
516
|
+
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
|
|
517
|
+
// fresh bytes to the caller.
|
|
518
|
+
const res = buffer.slice(0, outputLen);
|
|
519
|
+
this.destroy();
|
|
520
|
+
return res;
|
|
521
|
+
}
|
|
522
|
+
_cloneInto(to) {
|
|
523
|
+
to ||= new this.constructor();
|
|
524
|
+
to.set(...this.get());
|
|
525
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
526
|
+
to.destroyed = destroyed;
|
|
527
|
+
to.finished = finished;
|
|
528
|
+
to.length = length;
|
|
529
|
+
to.pos = pos;
|
|
530
|
+
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
|
|
531
|
+
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
|
|
532
|
+
if (length % blockLen)
|
|
533
|
+
to.buffer.set(buffer);
|
|
534
|
+
return to;
|
|
535
|
+
}
|
|
536
|
+
clone() {
|
|
537
|
+
return this._cloneInto();
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
542
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
543
|
+
*/
|
|
544
|
+
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
|
545
|
+
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
|
546
|
+
* it as read-only because constructors copy words from it by index. */
|
|
547
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
548
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
549
|
+
]);
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
553
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
554
|
+
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
|
|
555
|
+
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
|
|
556
|
+
* @module
|
|
557
|
+
*/
|
|
558
|
+
/**
|
|
559
|
+
* SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
|
|
560
|
+
* of the cube roots of the first 64 primes (2..311).
|
|
561
|
+
*/
|
|
562
|
+
// prettier-ignore
|
|
563
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
564
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
565
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
566
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
567
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
568
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
569
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
570
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
571
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
572
|
+
]);
|
|
573
|
+
/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
|
|
574
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
575
|
+
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
|
|
576
|
+
class SHA2_32B extends HashMD {
|
|
577
|
+
constructor(outputLen) {
|
|
578
|
+
super(64, outputLen, 8, false);
|
|
579
|
+
}
|
|
580
|
+
get() {
|
|
581
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
582
|
+
return [A, B, C, D, E, F, G, H];
|
|
583
|
+
}
|
|
584
|
+
// prettier-ignore
|
|
585
|
+
set(A, B, C, D, E, F, G, H) {
|
|
586
|
+
this.A = A | 0;
|
|
587
|
+
this.B = B | 0;
|
|
588
|
+
this.C = C | 0;
|
|
589
|
+
this.D = D | 0;
|
|
590
|
+
this.E = E | 0;
|
|
591
|
+
this.F = F | 0;
|
|
592
|
+
this.G = G | 0;
|
|
593
|
+
this.H = H | 0;
|
|
594
|
+
}
|
|
595
|
+
process(view, offset) {
|
|
596
|
+
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
|
|
597
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
598
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
599
|
+
for (let i = 16; i < 64; i++) {
|
|
600
|
+
const W15 = SHA256_W[i - 15];
|
|
601
|
+
const W2 = SHA256_W[i - 2];
|
|
602
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
|
|
603
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
|
|
604
|
+
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
|
|
605
|
+
}
|
|
606
|
+
// Compression function main loop, 64 rounds
|
|
607
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
608
|
+
for (let i = 0; i < 64; i++) {
|
|
609
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
610
|
+
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
611
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
612
|
+
const T2 = (sigma0 + Maj(A, B, C)) | 0;
|
|
613
|
+
H = G;
|
|
614
|
+
G = F;
|
|
615
|
+
F = E;
|
|
616
|
+
E = (D + T1) | 0;
|
|
617
|
+
D = C;
|
|
618
|
+
C = B;
|
|
619
|
+
B = A;
|
|
620
|
+
A = (T1 + T2) | 0;
|
|
621
|
+
}
|
|
622
|
+
// Add the compressed chunk to the current hash value
|
|
623
|
+
A = (A + this.A) | 0;
|
|
624
|
+
B = (B + this.B) | 0;
|
|
625
|
+
C = (C + this.C) | 0;
|
|
626
|
+
D = (D + this.D) | 0;
|
|
627
|
+
E = (E + this.E) | 0;
|
|
628
|
+
F = (F + this.F) | 0;
|
|
629
|
+
G = (G + this.G) | 0;
|
|
630
|
+
H = (H + this.H) | 0;
|
|
631
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
632
|
+
}
|
|
633
|
+
roundClean() {
|
|
634
|
+
clean(SHA256_W);
|
|
635
|
+
}
|
|
636
|
+
destroy() {
|
|
637
|
+
// HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
|
|
638
|
+
// update()/digest() callable on reused instances.
|
|
639
|
+
this.destroyed = true;
|
|
640
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
641
|
+
clean(this.buffer);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
|
|
645
|
+
class _SHA256 extends SHA2_32B {
|
|
646
|
+
// We cannot use array here since array allows indexing by variable
|
|
647
|
+
// which means optimizer/compiler cannot use registers.
|
|
648
|
+
A = SHA256_IV[0] | 0;
|
|
649
|
+
B = SHA256_IV[1] | 0;
|
|
650
|
+
C = SHA256_IV[2] | 0;
|
|
651
|
+
D = SHA256_IV[3] | 0;
|
|
652
|
+
E = SHA256_IV[4] | 0;
|
|
653
|
+
F = SHA256_IV[5] | 0;
|
|
654
|
+
G = SHA256_IV[6] | 0;
|
|
655
|
+
H = SHA256_IV[7] | 0;
|
|
656
|
+
constructor() {
|
|
657
|
+
super(32);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
|
|
662
|
+
*
|
|
663
|
+
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
|
|
664
|
+
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
665
|
+
* - Each sha256 hash is executing 2^18 bit operations.
|
|
666
|
+
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
|
|
667
|
+
* @param msg - message bytes to hash
|
|
668
|
+
* @returns Digest bytes.
|
|
669
|
+
* @example
|
|
670
|
+
* Hash a message with SHA2-256.
|
|
671
|
+
* ```ts
|
|
672
|
+
* sha256(new Uint8Array([97, 98, 99]));
|
|
673
|
+
* ```
|
|
674
|
+
*/
|
|
675
|
+
const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
|
|
676
|
+
/* @__PURE__ */ oidNist(0x01));
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Hex, bytes and number utilities.
|
|
680
|
+
* @module
|
|
681
|
+
*/
|
|
682
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
683
|
+
/**
|
|
684
|
+
* Validates that a value is a byte array.
|
|
685
|
+
* @param value - Value to validate.
|
|
686
|
+
* @param length - Optional exact byte length.
|
|
687
|
+
* @param title - Optional field name.
|
|
688
|
+
* @returns Original byte array.
|
|
689
|
+
* @example
|
|
690
|
+
* Reject non-byte input before passing data into curve code.
|
|
691
|
+
*
|
|
692
|
+
* ```ts
|
|
693
|
+
* abytes(new Uint8Array(1));
|
|
694
|
+
* ```
|
|
695
|
+
*/
|
|
696
|
+
const abytes = (value, length, title) => abytes$1(value, length, title);
|
|
697
|
+
/**
|
|
698
|
+
* Validates that a value is a non-negative safe integer.
|
|
699
|
+
* @param n - Value to validate.
|
|
700
|
+
* @param title - Optional field name.
|
|
701
|
+
* @example
|
|
702
|
+
* Validate a numeric length before allocating buffers.
|
|
703
|
+
*
|
|
704
|
+
* ```ts
|
|
705
|
+
* anumber(1);
|
|
706
|
+
* ```
|
|
707
|
+
*/
|
|
708
|
+
const anumber = anumber$1;
|
|
709
|
+
/**
|
|
710
|
+
* Encodes bytes as lowercase hex.
|
|
711
|
+
* @param bytes - Bytes to encode.
|
|
712
|
+
* @returns Lowercase hex string.
|
|
713
|
+
* @example
|
|
714
|
+
* Serialize bytes as hex for logging or fixtures.
|
|
715
|
+
*
|
|
716
|
+
* ```ts
|
|
717
|
+
* bytesToHex(Uint8Array.of(1, 2, 3));
|
|
718
|
+
* ```
|
|
719
|
+
*/
|
|
720
|
+
const bytesToHex = bytesToHex$1;
|
|
721
|
+
/**
|
|
722
|
+
* Concatenates byte arrays.
|
|
723
|
+
* @param arrays - Byte arrays to join.
|
|
724
|
+
* @returns Concatenated bytes.
|
|
725
|
+
* @example
|
|
726
|
+
* Join domain-separated chunks into one buffer.
|
|
727
|
+
*
|
|
728
|
+
* ```ts
|
|
729
|
+
* concatBytes(Uint8Array.of(1), Uint8Array.of(2));
|
|
730
|
+
* ```
|
|
731
|
+
*/
|
|
732
|
+
const concatBytes = (...arrays) => concatBytes$1(...arrays);
|
|
733
|
+
/**
|
|
734
|
+
* Decodes lowercase or uppercase hex into bytes.
|
|
735
|
+
* @param hex - Hex string to decode.
|
|
736
|
+
* @returns Decoded bytes.
|
|
737
|
+
* @example
|
|
738
|
+
* Parse fixture hex into bytes before hashing.
|
|
739
|
+
*
|
|
740
|
+
* ```ts
|
|
741
|
+
* hexToBytes('0102');
|
|
742
|
+
* ```
|
|
743
|
+
*/
|
|
744
|
+
const hexToBytes = (hex) => hexToBytes$1(hex);
|
|
745
|
+
/**
|
|
746
|
+
* Checks whether a value is a Uint8Array.
|
|
747
|
+
* @param a - Value to inspect.
|
|
748
|
+
* @returns `true` when `a` is a Uint8Array.
|
|
749
|
+
* @example
|
|
750
|
+
* Branch on byte input before decoding it.
|
|
751
|
+
*
|
|
752
|
+
* ```ts
|
|
753
|
+
* isBytes(new Uint8Array(1));
|
|
754
|
+
* ```
|
|
755
|
+
*/
|
|
756
|
+
const isBytes = isBytes$1;
|
|
757
|
+
/**
|
|
758
|
+
* Reads random bytes from the platform CSPRNG.
|
|
759
|
+
* @param bytesLength - Number of random bytes to read.
|
|
760
|
+
* @returns Fresh random bytes.
|
|
761
|
+
* @example
|
|
762
|
+
* Generate a random seed for a keypair.
|
|
763
|
+
*
|
|
764
|
+
* ```ts
|
|
765
|
+
* randomBytes(2);
|
|
766
|
+
* ```
|
|
767
|
+
*/
|
|
768
|
+
const randomBytes = (bytesLength) => randomBytes$1(bytesLength);
|
|
769
|
+
const _0n$3 = /* @__PURE__ */ BigInt(0);
|
|
770
|
+
const _1n$3 = /* @__PURE__ */ BigInt(1);
|
|
771
|
+
/**
|
|
772
|
+
* Validates that a flag is boolean.
|
|
773
|
+
* @param value - Value to validate.
|
|
774
|
+
* @param title - Optional field name.
|
|
775
|
+
* @returns Original value.
|
|
776
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
777
|
+
* @example
|
|
778
|
+
* Reject non-boolean option flags early.
|
|
779
|
+
*
|
|
780
|
+
* ```ts
|
|
781
|
+
* abool(true);
|
|
782
|
+
* ```
|
|
783
|
+
*/
|
|
784
|
+
function abool(value, title = '') {
|
|
785
|
+
if (typeof value !== 'boolean') {
|
|
786
|
+
const prefix = title && `"${title}" `;
|
|
787
|
+
throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);
|
|
788
|
+
}
|
|
789
|
+
return value;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Validates that a value is a non-negative bigint or safe integer.
|
|
793
|
+
* @param n - Value to validate.
|
|
794
|
+
* @returns The same validated value.
|
|
795
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
796
|
+
* @example
|
|
797
|
+
* Validate one integer-like value before serializing it.
|
|
798
|
+
*
|
|
799
|
+
* ```ts
|
|
800
|
+
* abignumber(1n);
|
|
801
|
+
* ```
|
|
802
|
+
*/
|
|
803
|
+
function abignumber(n) {
|
|
804
|
+
if (typeof n === 'bigint') {
|
|
805
|
+
if (!isPosBig(n))
|
|
806
|
+
throw new RangeError('positive bigint expected, got ' + n);
|
|
807
|
+
}
|
|
808
|
+
else
|
|
809
|
+
anumber(n);
|
|
810
|
+
return n;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Validates that a value is a safe integer.
|
|
814
|
+
* @param value - Integer to validate.
|
|
815
|
+
* @param title - Optional field name.
|
|
816
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
817
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
818
|
+
* @example
|
|
819
|
+
* Validate a window size before scalar arithmetic uses it.
|
|
820
|
+
*
|
|
821
|
+
* ```ts
|
|
822
|
+
* asafenumber(1);
|
|
823
|
+
* ```
|
|
824
|
+
*/
|
|
825
|
+
function asafenumber(value, title = '') {
|
|
826
|
+
if (typeof value !== 'number') {
|
|
827
|
+
const prefix = title && `"${title}" `;
|
|
828
|
+
throw new TypeError(prefix + 'expected number, got type=' + typeof value);
|
|
829
|
+
}
|
|
830
|
+
if (!Number.isSafeInteger(value)) {
|
|
831
|
+
const prefix = title && `"${title}" `;
|
|
832
|
+
throw new RangeError(prefix + 'expected safe integer, got ' + value);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Encodes a bigint into even-length big-endian hex.
|
|
837
|
+
* The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
|
|
838
|
+
* gets one leading zero nibble so the result always represents whole bytes.
|
|
839
|
+
* @param num - Number to encode.
|
|
840
|
+
* @returns Big-endian hex string.
|
|
841
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
842
|
+
* @example
|
|
843
|
+
* Encode a scalar into hex without a `0x` prefix.
|
|
844
|
+
*
|
|
845
|
+
* ```ts
|
|
846
|
+
* numberToHexUnpadded(255n);
|
|
847
|
+
* ```
|
|
848
|
+
*/
|
|
849
|
+
function numberToHexUnpadded(num) {
|
|
850
|
+
const hex = abignumber(num).toString(16);
|
|
851
|
+
return hex.length & 1 ? '0' + hex : hex;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Parses a big-endian hex string into bigint.
|
|
855
|
+
* Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
|
|
856
|
+
* same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
|
|
857
|
+
* @param hex - Hex string without `0x`.
|
|
858
|
+
* @returns Parsed bigint value.
|
|
859
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
860
|
+
* @example
|
|
861
|
+
* Parse a scalar from fixture hex.
|
|
862
|
+
*
|
|
863
|
+
* ```ts
|
|
864
|
+
* hexToNumber('ff');
|
|
865
|
+
* ```
|
|
866
|
+
*/
|
|
867
|
+
function hexToNumber(hex) {
|
|
868
|
+
if (typeof hex !== 'string')
|
|
869
|
+
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
870
|
+
return hex === '' ? _0n$3 : BigInt('0x' + hex); // Big Endian
|
|
871
|
+
}
|
|
872
|
+
// BE: Big Endian, LE: Little Endian
|
|
873
|
+
/**
|
|
874
|
+
* Parses big-endian bytes into bigint.
|
|
875
|
+
* @param bytes - Bytes in big-endian order.
|
|
876
|
+
* @returns Parsed bigint value.
|
|
877
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
878
|
+
* @example
|
|
879
|
+
* Read a scalar encoded in network byte order.
|
|
880
|
+
*
|
|
881
|
+
* ```ts
|
|
882
|
+
* bytesToNumberBE(Uint8Array.of(1, 0));
|
|
883
|
+
* ```
|
|
884
|
+
*/
|
|
885
|
+
function bytesToNumberBE(bytes) {
|
|
886
|
+
return hexToNumber(bytesToHex$1(bytes));
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Parses little-endian bytes into bigint.
|
|
890
|
+
* @param bytes - Bytes in little-endian order.
|
|
891
|
+
* @returns Parsed bigint value.
|
|
892
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
893
|
+
* @example
|
|
894
|
+
* Read a scalar encoded in little-endian form.
|
|
895
|
+
*
|
|
896
|
+
* ```ts
|
|
897
|
+
* bytesToNumberLE(Uint8Array.of(1, 0));
|
|
898
|
+
* ```
|
|
899
|
+
*/
|
|
900
|
+
function bytesToNumberLE(bytes) {
|
|
901
|
+
return hexToNumber(bytesToHex$1(copyBytes(abytes$1(bytes)).reverse()));
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Encodes a bigint into fixed-length big-endian bytes.
|
|
905
|
+
* @param n - Number to encode.
|
|
906
|
+
* @param len - Output length in bytes. Must be greater than zero.
|
|
907
|
+
* @returns Big-endian byte array.
|
|
908
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
909
|
+
* @example
|
|
910
|
+
* Serialize a scalar into a 32-byte field element.
|
|
911
|
+
*
|
|
912
|
+
* ```ts
|
|
913
|
+
* numberToBytesBE(255n, 2);
|
|
914
|
+
* ```
|
|
915
|
+
*/
|
|
916
|
+
function numberToBytesBE(n, len) {
|
|
917
|
+
anumber$1(len);
|
|
918
|
+
if (len === 0)
|
|
919
|
+
throw new RangeError('zero length');
|
|
920
|
+
n = abignumber(n);
|
|
921
|
+
const hex = n.toString(16);
|
|
922
|
+
// Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.
|
|
923
|
+
if (hex.length > len * 2)
|
|
924
|
+
throw new RangeError('number too large');
|
|
925
|
+
return hexToBytes$1(hex.padStart(len * 2, '0'));
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Encodes a bigint into fixed-length little-endian bytes.
|
|
929
|
+
* @param n - Number to encode.
|
|
930
|
+
* @param len - Output length in bytes.
|
|
931
|
+
* @returns Little-endian byte array.
|
|
932
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
933
|
+
* @example
|
|
934
|
+
* Serialize a scalar for little-endian protocols.
|
|
935
|
+
*
|
|
936
|
+
* ```ts
|
|
937
|
+
* numberToBytesLE(255n, 2);
|
|
938
|
+
* ```
|
|
939
|
+
*/
|
|
940
|
+
function numberToBytesLE(n, len) {
|
|
941
|
+
return numberToBytesBE(n, len).reverse();
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
|
|
945
|
+
* and Buffer#slice creates mutable copy. Never use Buffers!
|
|
946
|
+
* @param bytes - Bytes to copy.
|
|
947
|
+
* @returns Detached copy.
|
|
948
|
+
* @example
|
|
949
|
+
* Make an isolated copy before mutating serialized bytes.
|
|
950
|
+
*
|
|
951
|
+
* ```ts
|
|
952
|
+
* copyBytes(Uint8Array.of(1, 2, 3));
|
|
953
|
+
* ```
|
|
954
|
+
*/
|
|
955
|
+
function copyBytes(bytes) {
|
|
956
|
+
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
|
957
|
+
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
|
958
|
+
return Uint8Array.from(abytes(bytes));
|
|
959
|
+
}
|
|
960
|
+
// Historical name: this accepts non-negative bigints, including zero.
|
|
961
|
+
const isPosBig = (n) => typeof n === 'bigint' && _0n$3 <= n;
|
|
962
|
+
/**
|
|
963
|
+
* Checks whether a bigint lies inside a half-open range.
|
|
964
|
+
* @param n - Candidate value.
|
|
965
|
+
* @param min - Inclusive lower bound.
|
|
966
|
+
* @param max - Exclusive upper bound.
|
|
967
|
+
* @returns `true` when the value is inside the range.
|
|
968
|
+
* @example
|
|
969
|
+
* Check whether a candidate scalar fits the field order.
|
|
970
|
+
*
|
|
971
|
+
* ```ts
|
|
972
|
+
* inRange(2n, 1n, 3n);
|
|
973
|
+
* ```
|
|
974
|
+
*/
|
|
975
|
+
function inRange(n, min, max) {
|
|
976
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Asserts `min <= n < max`. NOTE: upper bound is exclusive.
|
|
980
|
+
* @param title - Value label for error messages.
|
|
981
|
+
* @param n - Candidate value.
|
|
982
|
+
* @param min - Inclusive lower bound.
|
|
983
|
+
* @param max - Exclusive upper bound.
|
|
984
|
+
* Wrong-type inputs are not separated from out-of-range values here: they still flow through the
|
|
985
|
+
* shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
|
|
986
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
987
|
+
* @example
|
|
988
|
+
* Assert that a bigint stays within one half-open range.
|
|
989
|
+
*
|
|
990
|
+
* ```ts
|
|
991
|
+
* aInRange('x', 2n, 1n, 256n);
|
|
992
|
+
* ```
|
|
993
|
+
*/
|
|
994
|
+
function aInRange(title, n, min, max) {
|
|
995
|
+
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
|
996
|
+
// consider P=256n, min=0n, max=P
|
|
997
|
+
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
|
998
|
+
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
|
999
|
+
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
|
1000
|
+
if (!inRange(n, min, max))
|
|
1001
|
+
throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
|
1002
|
+
}
|
|
1003
|
+
// Bit operations
|
|
1004
|
+
/**
|
|
1005
|
+
* Calculates amount of bits in a bigint.
|
|
1006
|
+
* Same as `n.toString(2).length`
|
|
1007
|
+
* TODO: merge with nLength in modular
|
|
1008
|
+
* @param n - Value to inspect.
|
|
1009
|
+
* @returns Bit length.
|
|
1010
|
+
* @throws If the value is negative. {@link Error}
|
|
1011
|
+
* @example
|
|
1012
|
+
* Measure the bit length of a scalar before serialization.
|
|
1013
|
+
*
|
|
1014
|
+
* ```ts
|
|
1015
|
+
* bitLen(8n);
|
|
1016
|
+
* ```
|
|
1017
|
+
*/
|
|
1018
|
+
function bitLen(n) {
|
|
1019
|
+
// Size callers in this repo only use non-negative orders / scalars, so negative inputs are a
|
|
1020
|
+
// contract bug and must not silently collapse to zero bits.
|
|
1021
|
+
if (n < _0n$3)
|
|
1022
|
+
throw new Error('expected non-negative bigint, got ' + n);
|
|
1023
|
+
let len;
|
|
1024
|
+
for (len = 0; n > _0n$3; n >>= _1n$3, len += 1)
|
|
1025
|
+
;
|
|
1026
|
+
return len;
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
|
1030
|
+
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
|
1031
|
+
* @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
|
|
1032
|
+
* semantics and therefore produce `-1n`.
|
|
1033
|
+
* @returns Bitmask value.
|
|
1034
|
+
* @example
|
|
1035
|
+
* Calculate mask for N bits.
|
|
1036
|
+
*
|
|
1037
|
+
* ```ts
|
|
1038
|
+
* bitMask(4);
|
|
1039
|
+
* ```
|
|
1040
|
+
*/
|
|
1041
|
+
const bitMask = (n) => (_1n$3 << BigInt(n)) - _1n$3;
|
|
1042
|
+
/**
|
|
1043
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
1044
|
+
* @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
|
|
1045
|
+
* is not rejected here and would make the internal generate loop non-progressing.
|
|
1046
|
+
* @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
|
|
1047
|
+
* @param hmacFn - HMAC implementation.
|
|
1048
|
+
* @returns Function that will call DRBG until the predicate returns anything
|
|
1049
|
+
* other than `undefined`.
|
|
1050
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1051
|
+
* @example
|
|
1052
|
+
* Build a deterministic nonce generator for RFC6979-style signing.
|
|
1053
|
+
*
|
|
1054
|
+
* ```ts
|
|
1055
|
+
* import { createHmacDrbg } from '@noble/curves/utils.js';
|
|
1056
|
+
* import { hmac } from '@noble/hashes/hmac.js';
|
|
1057
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1058
|
+
* const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));
|
|
1059
|
+
* const seed = new Uint8Array(32);
|
|
1060
|
+
* drbg(seed, (bytes) => bytes);
|
|
1061
|
+
* ```
|
|
1062
|
+
*/
|
|
1063
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
1064
|
+
anumber$1(hashLen, 'hashLen');
|
|
1065
|
+
anumber$1(qByteLen, 'qByteLen');
|
|
1066
|
+
if (typeof hmacFn !== 'function')
|
|
1067
|
+
throw new TypeError('hmacFn must be a function');
|
|
1068
|
+
// creates Uint8Array
|
|
1069
|
+
const u8n = (len) => new Uint8Array(len);
|
|
1070
|
+
const NULL = Uint8Array.of();
|
|
1071
|
+
const byte0 = Uint8Array.of(0x00);
|
|
1072
|
+
const byte1 = Uint8Array.of(0x01);
|
|
1073
|
+
const _maxDrbgIters = 1000;
|
|
1074
|
+
// Step B, Step C: set hashLen to 8*ceil(hlen/8).
|
|
1075
|
+
// Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.
|
|
1076
|
+
let v = u8n(hashLen);
|
|
1077
|
+
// Steps B and C of RFC6979 3.2.
|
|
1078
|
+
let k = u8n(hashLen);
|
|
1079
|
+
let i = 0; // Iterations counter, will throw when over 1000
|
|
1080
|
+
const reset = () => {
|
|
1081
|
+
v.fill(1);
|
|
1082
|
+
k.fill(0);
|
|
1083
|
+
i = 0;
|
|
1084
|
+
};
|
|
1085
|
+
// hmac(k)(v, ...values)
|
|
1086
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
1087
|
+
const reseed = (seed = NULL) => {
|
|
1088
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
1089
|
+
k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)
|
|
1090
|
+
v = h(); // v = hmac(k || v)
|
|
1091
|
+
if (seed.length === 0)
|
|
1092
|
+
return;
|
|
1093
|
+
k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)
|
|
1094
|
+
v = h(); // v = hmac(k || v)
|
|
1095
|
+
};
|
|
1096
|
+
const gen = () => {
|
|
1097
|
+
// HMAC-DRBG generate() function
|
|
1098
|
+
if (i++ >= _maxDrbgIters)
|
|
1099
|
+
throw new Error('drbg: tried max amount of iterations');
|
|
1100
|
+
let len = 0;
|
|
1101
|
+
const out = [];
|
|
1102
|
+
while (len < qByteLen) {
|
|
1103
|
+
v = h();
|
|
1104
|
+
const sl = v.slice();
|
|
1105
|
+
out.push(sl);
|
|
1106
|
+
len += v.length;
|
|
1107
|
+
}
|
|
1108
|
+
return concatBytes(...out);
|
|
1109
|
+
};
|
|
1110
|
+
const genUntil = (seed, pred) => {
|
|
1111
|
+
reset();
|
|
1112
|
+
reseed(seed); // Steps D-G
|
|
1113
|
+
let res = undefined; // Step H: grind until the predicate accepts a candidate.
|
|
1114
|
+
// Falsy values like 0 are valid outputs.
|
|
1115
|
+
while ((res = pred(gen())) === undefined)
|
|
1116
|
+
reseed();
|
|
1117
|
+
reset();
|
|
1118
|
+
return res;
|
|
1119
|
+
};
|
|
1120
|
+
return genUntil;
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Validates declared required and optional field types on a plain object.
|
|
1124
|
+
* Extra keys are intentionally ignored because many callers validate only the subset they use from
|
|
1125
|
+
* richer option bags or runtime objects.
|
|
1126
|
+
* @param object - Object to validate.
|
|
1127
|
+
* @param fields - Required field types.
|
|
1128
|
+
* @param optFields - Optional field types.
|
|
1129
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1130
|
+
* @example
|
|
1131
|
+
* Check user options before building a curve helper.
|
|
1132
|
+
*
|
|
1133
|
+
* ```ts
|
|
1134
|
+
* validateObject({ flag: true }, { flag: 'boolean' });
|
|
1135
|
+
* ```
|
|
1136
|
+
*/
|
|
1137
|
+
function validateObject(object, fields = {}, optFields = {}) {
|
|
1138
|
+
if (Object.prototype.toString.call(object) !== '[object Object]')
|
|
1139
|
+
throw new TypeError('expected valid options object');
|
|
1140
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
1141
|
+
// Config/data fields must be explicit own properties, but runtime objects such as Field
|
|
1142
|
+
// instances intentionally satisfy required method slots via their shared prototype.
|
|
1143
|
+
if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))
|
|
1144
|
+
throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
|
|
1145
|
+
const val = object[fieldName];
|
|
1146
|
+
if (isOpt && val === undefined)
|
|
1147
|
+
return;
|
|
1148
|
+
const current = typeof val;
|
|
1149
|
+
if (current !== expectedType || val === null)
|
|
1150
|
+
throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
1151
|
+
}
|
|
1152
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
1153
|
+
iter(fields, false);
|
|
1154
|
+
iter(optFields, true);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* Utils for modular division and fields.
|
|
1159
|
+
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
|
1160
|
+
* There is no division: it is replaced by modular multiplicative inverse.
|
|
1161
|
+
* @module
|
|
1162
|
+
*/
|
|
1163
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1164
|
+
// Numbers aren't used in x25519 / x448 builds
|
|
1165
|
+
// prettier-ignore
|
|
1166
|
+
const _0n$2 = /* @__PURE__ */ BigInt(0), _1n$2 = /* @__PURE__ */ BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2);
|
|
1167
|
+
// prettier-ignore
|
|
1168
|
+
const _3n$1 = /* @__PURE__ */ BigInt(3), _4n$1 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
|
|
1169
|
+
// prettier-ignore
|
|
1170
|
+
const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
|
|
1171
|
+
const _16n = /* @__PURE__ */ BigInt(16);
|
|
1172
|
+
/**
|
|
1173
|
+
* @param a - Dividend value.
|
|
1174
|
+
* @param b - Positive modulus.
|
|
1175
|
+
* @returns Reduced value in `[0, b)` only when `b` is positive.
|
|
1176
|
+
* @throws If the modulus is not positive. {@link Error}
|
|
1177
|
+
* @example
|
|
1178
|
+
* Normalize a bigint into one field residue.
|
|
1179
|
+
*
|
|
1180
|
+
* ```ts
|
|
1181
|
+
* mod(-1n, 5n);
|
|
1182
|
+
* ```
|
|
1183
|
+
*/
|
|
1184
|
+
function mod(a, b) {
|
|
1185
|
+
if (b <= _0n$2)
|
|
1186
|
+
throw new Error('mod: expected positive modulus, got ' + b);
|
|
1187
|
+
const result = a % b;
|
|
1188
|
+
return result >= _0n$2 ? result : b + result;
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
|
|
1192
|
+
* Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
|
|
1193
|
+
* modulus; the `power===0` fast path intentionally returns the input unchanged.
|
|
1194
|
+
* @param x - Base value.
|
|
1195
|
+
* @param power - Number of squarings.
|
|
1196
|
+
* @param modulo - Reduction modulus.
|
|
1197
|
+
* @returns Repeated-squaring result.
|
|
1198
|
+
* @throws If the exponent is negative. {@link Error}
|
|
1199
|
+
* @example
|
|
1200
|
+
* Apply repeated squaring inside one field.
|
|
1201
|
+
*
|
|
1202
|
+
* ```ts
|
|
1203
|
+
* pow2(3n, 2n, 11n);
|
|
1204
|
+
* ```
|
|
1205
|
+
*/
|
|
1206
|
+
function pow2(x, power, modulo) {
|
|
1207
|
+
if (power < _0n$2)
|
|
1208
|
+
throw new Error('pow2: expected non-negative exponent, got ' + power);
|
|
1209
|
+
let res = x;
|
|
1210
|
+
while (power-- > _0n$2) {
|
|
1211
|
+
res *= res;
|
|
1212
|
+
res %= modulo;
|
|
1213
|
+
}
|
|
1214
|
+
return res;
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Inverses number over modulo.
|
|
1218
|
+
* Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
|
|
1219
|
+
* @param number - Value to invert.
|
|
1220
|
+
* @param modulo - Positive modulus.
|
|
1221
|
+
* @returns Multiplicative inverse.
|
|
1222
|
+
* @throws If the modulus is invalid or the inverse does not exist. {@link Error}
|
|
1223
|
+
* @example
|
|
1224
|
+
* Compute one modular inverse with the extended Euclidean algorithm.
|
|
1225
|
+
*
|
|
1226
|
+
* ```ts
|
|
1227
|
+
* invert(3n, 11n);
|
|
1228
|
+
* ```
|
|
1229
|
+
*/
|
|
1230
|
+
function invert(number, modulo) {
|
|
1231
|
+
if (number === _0n$2)
|
|
1232
|
+
throw new Error('invert: expected non-zero number');
|
|
1233
|
+
if (modulo <= _0n$2)
|
|
1234
|
+
throw new Error('invert: expected positive modulus, got ' + modulo);
|
|
1235
|
+
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
|
1236
|
+
let a = mod(number, modulo);
|
|
1237
|
+
let b = modulo;
|
|
1238
|
+
// prettier-ignore
|
|
1239
|
+
let x = _0n$2, u = _1n$2;
|
|
1240
|
+
while (a !== _0n$2) {
|
|
1241
|
+
const q = b / a;
|
|
1242
|
+
const r = b - a * q;
|
|
1243
|
+
const m = x - u * q;
|
|
1244
|
+
// prettier-ignore
|
|
1245
|
+
b = a, a = r, x = u, u = m;
|
|
1246
|
+
}
|
|
1247
|
+
const gcd = b;
|
|
1248
|
+
if (gcd !== _1n$2)
|
|
1249
|
+
throw new Error('invert: does not exist');
|
|
1250
|
+
return mod(x, modulo);
|
|
1251
|
+
}
|
|
1252
|
+
function assertIsSquare(Fp, root, n) {
|
|
1253
|
+
const F = Fp;
|
|
1254
|
+
if (!F.eql(F.sqr(root), n))
|
|
1255
|
+
throw new Error('Cannot find square root');
|
|
1256
|
+
}
|
|
1257
|
+
// Not all roots are possible! Example which will throw:
|
|
1258
|
+
// const NUM =
|
|
1259
|
+
// n = 72057594037927816n;
|
|
1260
|
+
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
|
1261
|
+
function sqrt3mod4(Fp, n) {
|
|
1262
|
+
const F = Fp;
|
|
1263
|
+
const p1div4 = (F.ORDER + _1n$2) / _4n$1;
|
|
1264
|
+
const root = F.pow(n, p1div4);
|
|
1265
|
+
assertIsSquare(F, root, n);
|
|
1266
|
+
return root;
|
|
1267
|
+
}
|
|
1268
|
+
// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV
|
|
1269
|
+
// pseudocode verbatim.
|
|
1270
|
+
function sqrt5mod8(Fp, n) {
|
|
1271
|
+
const F = Fp;
|
|
1272
|
+
const p5div8 = (F.ORDER - _5n) / _8n;
|
|
1273
|
+
const n2 = F.mul(n, _2n$2);
|
|
1274
|
+
const v = F.pow(n2, p5div8);
|
|
1275
|
+
const nv = F.mul(n, v);
|
|
1276
|
+
const i = F.mul(F.mul(nv, _2n$2), v);
|
|
1277
|
+
const root = F.mul(nv, F.sub(i, F.ONE));
|
|
1278
|
+
assertIsSquare(F, root, n);
|
|
1279
|
+
return root;
|
|
1280
|
+
}
|
|
1281
|
+
// Based on RFC9380, Kong algorithm
|
|
1282
|
+
// prettier-ignore
|
|
1283
|
+
function sqrt9mod16(P) {
|
|
1284
|
+
const Fp_ = Field(P);
|
|
1285
|
+
const tn = tonelliShanks(P);
|
|
1286
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
|
1287
|
+
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
|
1288
|
+
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
|
1289
|
+
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
|
1290
|
+
return ((Fp, n) => {
|
|
1291
|
+
const F = Fp;
|
|
1292
|
+
let tv1 = F.pow(n, c4); // 1. tv1 = x^c4
|
|
1293
|
+
let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1
|
|
1294
|
+
const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1
|
|
1295
|
+
const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1
|
|
1296
|
+
const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
|
1297
|
+
const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
|
1298
|
+
tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
|
1299
|
+
tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
|
1300
|
+
const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
|
1301
|
+
const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
|
|
1302
|
+
assertIsSquare(F, root, n);
|
|
1303
|
+
return root;
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Tonelli-Shanks square root search algorithm.
|
|
1308
|
+
* This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
|
|
1309
|
+
* and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
|
|
1310
|
+
* 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
|
|
1311
|
+
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
|
1312
|
+
* @param P - field order
|
|
1313
|
+
* @returns function that takes field Fp (created from P) and number n
|
|
1314
|
+
* @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
|
|
1315
|
+
* @example
|
|
1316
|
+
* Construct a square-root helper for primes that need Tonelli-Shanks.
|
|
1317
|
+
*
|
|
1318
|
+
* ```ts
|
|
1319
|
+
* import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
|
|
1320
|
+
* const Fp = Field(17n);
|
|
1321
|
+
* const sqrt = tonelliShanks(17n)(Fp, 4n);
|
|
1322
|
+
* ```
|
|
1323
|
+
*/
|
|
1324
|
+
function tonelliShanks(P) {
|
|
1325
|
+
// Initialization (precomputation).
|
|
1326
|
+
// Caching initialization could boost perf by 7%.
|
|
1327
|
+
if (P < _3n$1)
|
|
1328
|
+
throw new Error('sqrt is not defined for small field');
|
|
1329
|
+
// Factor P - 1 = Q * 2^S, where Q is odd
|
|
1330
|
+
let Q = P - _1n$2;
|
|
1331
|
+
let S = 0;
|
|
1332
|
+
while (Q % _2n$2 === _0n$2) {
|
|
1333
|
+
Q /= _2n$2;
|
|
1334
|
+
S++;
|
|
1335
|
+
}
|
|
1336
|
+
// Find the first quadratic non-residue Z >= 2
|
|
1337
|
+
let Z = _2n$2;
|
|
1338
|
+
const _Fp = Field(P);
|
|
1339
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
1340
|
+
// Basic primality test for P. After x iterations, chance of
|
|
1341
|
+
// not finding quadratic non-residue is 2^x, so 2^1000.
|
|
1342
|
+
if (Z++ > 1000)
|
|
1343
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
1344
|
+
}
|
|
1345
|
+
// Fast-path; usually done before Z, but we do "primality test".
|
|
1346
|
+
if (S === 1)
|
|
1347
|
+
return sqrt3mod4;
|
|
1348
|
+
// Slow-path
|
|
1349
|
+
// TODO: test on Fp2 and others
|
|
1350
|
+
let cc = _Fp.pow(Z, Q); // c = z^Q
|
|
1351
|
+
const Q1div2 = (Q + _1n$2) / _2n$2;
|
|
1352
|
+
return function tonelliSlow(Fp, n) {
|
|
1353
|
+
const F = Fp;
|
|
1354
|
+
if (F.is0(n))
|
|
1355
|
+
return n;
|
|
1356
|
+
// Check if n is a quadratic residue using Legendre symbol
|
|
1357
|
+
if (FpLegendre(F, n) !== 1)
|
|
1358
|
+
throw new Error('Cannot find square root');
|
|
1359
|
+
// Initialize variables for the main loop
|
|
1360
|
+
let M = S;
|
|
1361
|
+
let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
|
1362
|
+
let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
|
1363
|
+
let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
|
1364
|
+
// Main loop
|
|
1365
|
+
// while t != 1
|
|
1366
|
+
while (!F.eql(t, F.ONE)) {
|
|
1367
|
+
if (F.is0(t))
|
|
1368
|
+
return F.ZERO; // if t=0 return R=0
|
|
1369
|
+
let i = 1;
|
|
1370
|
+
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
|
1371
|
+
let t_tmp = F.sqr(t); // t^(2^1)
|
|
1372
|
+
while (!F.eql(t_tmp, F.ONE)) {
|
|
1373
|
+
i++;
|
|
1374
|
+
t_tmp = F.sqr(t_tmp); // t^(2^2)...
|
|
1375
|
+
if (i === M)
|
|
1376
|
+
throw new Error('Cannot find square root');
|
|
1377
|
+
}
|
|
1378
|
+
// Calculate the exponent for b: 2^(M - i - 1)
|
|
1379
|
+
const exponent = _1n$2 << BigInt(M - i - 1); // bigint is important
|
|
1380
|
+
const b = F.pow(c, exponent); // b = 2^(M - i - 1)
|
|
1381
|
+
// Update variables
|
|
1382
|
+
M = i;
|
|
1383
|
+
c = F.sqr(b); // c = b^2
|
|
1384
|
+
t = F.mul(t, c); // t = (t * b^2)
|
|
1385
|
+
R = F.mul(R, b); // R = R*b
|
|
1386
|
+
}
|
|
1387
|
+
return R;
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Square root for a finite field. Will try optimized versions first:
|
|
1392
|
+
*
|
|
1393
|
+
* 1. P ≡ 3 (mod 4)
|
|
1394
|
+
* 2. P ≡ 5 (mod 8)
|
|
1395
|
+
* 3. P ≡ 9 (mod 16)
|
|
1396
|
+
* 4. Tonelli-Shanks algorithm
|
|
1397
|
+
*
|
|
1398
|
+
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
|
1399
|
+
* For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
|
|
1400
|
+
* (used for hash-to-curve).
|
|
1401
|
+
* @param P - Field order.
|
|
1402
|
+
* @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
|
|
1403
|
+
* behavior and this selector assumes prime-field-style integer moduli.
|
|
1404
|
+
* @throws If the field is unsupported or the square root does not exist. {@link Error}
|
|
1405
|
+
* @example
|
|
1406
|
+
* Choose the square-root helper appropriate for one field modulus.
|
|
1407
|
+
*
|
|
1408
|
+
* ```ts
|
|
1409
|
+
* import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
|
|
1410
|
+
* const Fp = Field(17n);
|
|
1411
|
+
* const sqrt = FpSqrt(17n)(Fp, 4n);
|
|
1412
|
+
* ```
|
|
1413
|
+
*/
|
|
1414
|
+
function FpSqrt(P) {
|
|
1415
|
+
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
|
1416
|
+
if (P % _4n$1 === _3n$1)
|
|
1417
|
+
return sqrt3mod4;
|
|
1418
|
+
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
|
1419
|
+
if (P % _8n === _5n)
|
|
1420
|
+
return sqrt5mod8;
|
|
1421
|
+
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
|
|
1422
|
+
if (P % _16n === _9n)
|
|
1423
|
+
return sqrt9mod16(P);
|
|
1424
|
+
// Tonelli-Shanks algorithm
|
|
1425
|
+
return tonelliShanks(P);
|
|
1426
|
+
}
|
|
1427
|
+
// prettier-ignore
|
|
1428
|
+
// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime
|
|
1429
|
+
// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and
|
|
1430
|
+
// field-specific extras like `isOdd` are left to the callers that actually need them.
|
|
1431
|
+
const FIELD_FIELDS = [
|
|
1432
|
+
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
|
1433
|
+
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
|
1434
|
+
'addN', 'subN', 'mulN', 'sqrN'
|
|
1435
|
+
];
|
|
1436
|
+
/**
|
|
1437
|
+
* @param field - Field implementation.
|
|
1438
|
+
* @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
|
|
1439
|
+
* does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
|
|
1440
|
+
* field-specific extras beyond positive `BYTES` / `BITS`.
|
|
1441
|
+
* @throws If the field shape or numeric metadata are invalid. {@link Error}
|
|
1442
|
+
* @example
|
|
1443
|
+
* Check that a field implementation exposes the operations curve code expects.
|
|
1444
|
+
*
|
|
1445
|
+
* ```ts
|
|
1446
|
+
* import { Field, validateField } from '@noble/curves/abstract/modular.js';
|
|
1447
|
+
* const Fp = validateField(Field(17n));
|
|
1448
|
+
* ```
|
|
1449
|
+
*/
|
|
1450
|
+
function validateField(field) {
|
|
1451
|
+
const initial = {
|
|
1452
|
+
ORDER: 'bigint',
|
|
1453
|
+
BYTES: 'number',
|
|
1454
|
+
BITS: 'number',
|
|
1455
|
+
};
|
|
1456
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
1457
|
+
map[val] = 'function';
|
|
1458
|
+
return map;
|
|
1459
|
+
}, initial);
|
|
1460
|
+
validateObject(field, opts);
|
|
1461
|
+
// Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /
|
|
1462
|
+
// infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.
|
|
1463
|
+
asafenumber(field.BYTES, 'BYTES');
|
|
1464
|
+
asafenumber(field.BITS, 'BITS');
|
|
1465
|
+
// Runtime field implementations must expose positive byte/bit sizes; zero leaks through the
|
|
1466
|
+
// numeric shape checks above but still breaks encoding helpers and cached-length assumptions.
|
|
1467
|
+
if (field.BYTES < 1 || field.BITS < 1)
|
|
1468
|
+
throw new Error('invalid field: expected BYTES/BITS > 0');
|
|
1469
|
+
if (field.ORDER <= _1n$2)
|
|
1470
|
+
throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);
|
|
1471
|
+
return field;
|
|
1472
|
+
}
|
|
1473
|
+
// Generic field functions
|
|
1474
|
+
/**
|
|
1475
|
+
* Same as `pow` but for Fp: non-constant-time.
|
|
1476
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
1477
|
+
* @param Fp - Field implementation.
|
|
1478
|
+
* @param num - Base value.
|
|
1479
|
+
* @param power - Exponent value.
|
|
1480
|
+
* @returns Powered field element.
|
|
1481
|
+
* @throws If the exponent is negative. {@link Error}
|
|
1482
|
+
* @example
|
|
1483
|
+
* Raise one field element to a public exponent.
|
|
1484
|
+
*
|
|
1485
|
+
* ```ts
|
|
1486
|
+
* import { Field, FpPow } from '@noble/curves/abstract/modular.js';
|
|
1487
|
+
* const Fp = Field(17n);
|
|
1488
|
+
* const x = FpPow(Fp, 3n, 5n);
|
|
1489
|
+
* ```
|
|
1490
|
+
*/
|
|
1491
|
+
function FpPow(Fp, num, power) {
|
|
1492
|
+
const F = Fp;
|
|
1493
|
+
if (power < _0n$2)
|
|
1494
|
+
throw new Error('invalid exponent, negatives unsupported');
|
|
1495
|
+
if (power === _0n$2)
|
|
1496
|
+
return F.ONE;
|
|
1497
|
+
if (power === _1n$2)
|
|
1498
|
+
return num;
|
|
1499
|
+
let p = F.ONE;
|
|
1500
|
+
let d = num;
|
|
1501
|
+
while (power > _0n$2) {
|
|
1502
|
+
if (power & _1n$2)
|
|
1503
|
+
p = F.mul(p, d);
|
|
1504
|
+
d = F.sqr(d);
|
|
1505
|
+
power >>= _1n$2;
|
|
1506
|
+
}
|
|
1507
|
+
return p;
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Efficiently invert an array of Field elements.
|
|
1511
|
+
* Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
|
|
1512
|
+
* @param Fp - Field implementation.
|
|
1513
|
+
* @param nums - Values to invert.
|
|
1514
|
+
* @param passZero - map 0 to 0 (instead of undefined)
|
|
1515
|
+
* @returns Inverted values.
|
|
1516
|
+
* @example
|
|
1517
|
+
* Invert several field elements with one shared inversion.
|
|
1518
|
+
*
|
|
1519
|
+
* ```ts
|
|
1520
|
+
* import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
|
|
1521
|
+
* const Fp = Field(17n);
|
|
1522
|
+
* const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
|
|
1523
|
+
* ```
|
|
1524
|
+
*/
|
|
1525
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
1526
|
+
const F = Fp;
|
|
1527
|
+
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);
|
|
1528
|
+
// Walk from first to last, multiply them by each other MOD p
|
|
1529
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
1530
|
+
if (F.is0(num))
|
|
1531
|
+
return acc;
|
|
1532
|
+
inverted[i] = acc;
|
|
1533
|
+
return F.mul(acc, num);
|
|
1534
|
+
}, F.ONE);
|
|
1535
|
+
// Invert last element
|
|
1536
|
+
const invertedAcc = F.inv(multipliedAcc);
|
|
1537
|
+
// Walk from last to first, multiply them by inverted each other MOD p
|
|
1538
|
+
nums.reduceRight((acc, num, i) => {
|
|
1539
|
+
if (F.is0(num))
|
|
1540
|
+
return acc;
|
|
1541
|
+
inverted[i] = F.mul(acc, inverted[i]);
|
|
1542
|
+
return F.mul(acc, num);
|
|
1543
|
+
}, invertedAcc);
|
|
1544
|
+
return inverted;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Legendre symbol.
|
|
1548
|
+
* Legendre constant is used to calculate Legendre symbol (a | p)
|
|
1549
|
+
* which denotes the value of a^((p-1)/2) (mod p).
|
|
1550
|
+
*
|
|
1551
|
+
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
|
1552
|
+
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
|
1553
|
+
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
|
1554
|
+
* @param Fp - Field implementation.
|
|
1555
|
+
* @param n - Value to inspect.
|
|
1556
|
+
* @returns Legendre symbol.
|
|
1557
|
+
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
|
1558
|
+
* @example
|
|
1559
|
+
* Compute the Legendre symbol of one field element.
|
|
1560
|
+
*
|
|
1561
|
+
* ```ts
|
|
1562
|
+
* import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
|
|
1563
|
+
* const Fp = Field(17n);
|
|
1564
|
+
* const symbol = FpLegendre(Fp, 4n);
|
|
1565
|
+
* ```
|
|
1566
|
+
*/
|
|
1567
|
+
function FpLegendre(Fp, n) {
|
|
1568
|
+
const F = Fp;
|
|
1569
|
+
// We can use 3rd argument as optional cache of this value
|
|
1570
|
+
// but seems unneeded for now. The operation is very fast.
|
|
1571
|
+
const p1mod2 = (F.ORDER - _1n$2) / _2n$2;
|
|
1572
|
+
const powered = F.pow(n, p1mod2);
|
|
1573
|
+
const yes = F.eql(powered, F.ONE);
|
|
1574
|
+
const zero = F.eql(powered, F.ZERO);
|
|
1575
|
+
const no = F.eql(powered, F.neg(F.ONE));
|
|
1576
|
+
if (!yes && !zero && !no)
|
|
1577
|
+
throw new Error('invalid Legendre symbol result');
|
|
1578
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
1579
|
+
}
|
|
1580
|
+
/**
|
|
1581
|
+
* @param n - Curve order. Callers are expected to pass a positive order.
|
|
1582
|
+
* @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
|
|
1583
|
+
* value when overriding the derived bit length.
|
|
1584
|
+
* @returns Byte and bit lengths.
|
|
1585
|
+
* @throws If the order or cached bit length is invalid. {@link Error}
|
|
1586
|
+
* @example
|
|
1587
|
+
* Measure the encoding sizes needed for one modulus.
|
|
1588
|
+
*
|
|
1589
|
+
* ```ts
|
|
1590
|
+
* nLength(255n);
|
|
1591
|
+
* ```
|
|
1592
|
+
*/
|
|
1593
|
+
function nLength(n, nBitLength) {
|
|
1594
|
+
// Bit size, byte size of CURVE.n
|
|
1595
|
+
if (nBitLength !== undefined)
|
|
1596
|
+
anumber(nBitLength);
|
|
1597
|
+
if (n <= _0n$2)
|
|
1598
|
+
throw new Error('invalid n length: expected positive n, got ' + n);
|
|
1599
|
+
if (nBitLength !== undefined && nBitLength < 1)
|
|
1600
|
+
throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);
|
|
1601
|
+
const bits = bitLen(n);
|
|
1602
|
+
// Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison
|
|
1603
|
+
// any math that relies on the derived field metadata.
|
|
1604
|
+
if (nBitLength !== undefined && nBitLength < bits)
|
|
1605
|
+
throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
|
|
1606
|
+
const _nBitLength = nBitLength !== undefined ? nBitLength : bits;
|
|
1607
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
1608
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
1609
|
+
}
|
|
1610
|
+
// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the
|
|
1611
|
+
// cached helper write would keep the field surface externally mutable.
|
|
1612
|
+
const FIELD_SQRT = new WeakMap();
|
|
1613
|
+
class _Field {
|
|
1614
|
+
ORDER;
|
|
1615
|
+
BITS;
|
|
1616
|
+
BYTES;
|
|
1617
|
+
isLE;
|
|
1618
|
+
ZERO = _0n$2;
|
|
1619
|
+
ONE = _1n$2;
|
|
1620
|
+
_lengths;
|
|
1621
|
+
_mod;
|
|
1622
|
+
constructor(ORDER, opts = {}) {
|
|
1623
|
+
// ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv
|
|
1624
|
+
// would stop modeling field arithmetic.
|
|
1625
|
+
if (ORDER <= _1n$2)
|
|
1626
|
+
throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);
|
|
1627
|
+
let _nbitLength = undefined;
|
|
1628
|
+
this.isLE = false;
|
|
1629
|
+
if (opts != null && typeof opts === 'object') {
|
|
1630
|
+
// Cached bit lengths are trusted here and should already be positive / consistent with ORDER.
|
|
1631
|
+
if (typeof opts.BITS === 'number')
|
|
1632
|
+
_nbitLength = opts.BITS;
|
|
1633
|
+
if (typeof opts.sqrt === 'function')
|
|
1634
|
+
// `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties
|
|
1635
|
+
// explicitly instead of relying on writable prototype shadowing via assignment.
|
|
1636
|
+
Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });
|
|
1637
|
+
if (typeof opts.isLE === 'boolean')
|
|
1638
|
+
this.isLE = opts.isLE;
|
|
1639
|
+
if (opts.allowedLengths)
|
|
1640
|
+
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
|
1641
|
+
if (typeof opts.modFromBytes === 'boolean')
|
|
1642
|
+
this._mod = opts.modFromBytes;
|
|
1643
|
+
}
|
|
1644
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
1645
|
+
if (nByteLength > 2048)
|
|
1646
|
+
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
|
1647
|
+
this.ORDER = ORDER;
|
|
1648
|
+
this.BITS = nBitLength;
|
|
1649
|
+
this.BYTES = nByteLength;
|
|
1650
|
+
Object.freeze(this);
|
|
1651
|
+
}
|
|
1652
|
+
create(num) {
|
|
1653
|
+
return mod(num, this.ORDER);
|
|
1654
|
+
}
|
|
1655
|
+
isValid(num) {
|
|
1656
|
+
if (typeof num !== 'bigint')
|
|
1657
|
+
throw new TypeError('invalid field element: expected bigint, got ' + typeof num);
|
|
1658
|
+
return _0n$2 <= num && num < this.ORDER; // 0 is valid element, but it's not invertible
|
|
1659
|
+
}
|
|
1660
|
+
is0(num) {
|
|
1661
|
+
return num === _0n$2;
|
|
1662
|
+
}
|
|
1663
|
+
// is valid and invertible
|
|
1664
|
+
isValidNot0(num) {
|
|
1665
|
+
return !this.is0(num) && this.isValid(num);
|
|
1666
|
+
}
|
|
1667
|
+
isOdd(num) {
|
|
1668
|
+
return (num & _1n$2) === _1n$2;
|
|
1669
|
+
}
|
|
1670
|
+
neg(num) {
|
|
1671
|
+
return mod(-num, this.ORDER);
|
|
1672
|
+
}
|
|
1673
|
+
eql(lhs, rhs) {
|
|
1674
|
+
return lhs === rhs;
|
|
1675
|
+
}
|
|
1676
|
+
sqr(num) {
|
|
1677
|
+
return mod(num * num, this.ORDER);
|
|
1678
|
+
}
|
|
1679
|
+
add(lhs, rhs) {
|
|
1680
|
+
return mod(lhs + rhs, this.ORDER);
|
|
1681
|
+
}
|
|
1682
|
+
sub(lhs, rhs) {
|
|
1683
|
+
return mod(lhs - rhs, this.ORDER);
|
|
1684
|
+
}
|
|
1685
|
+
mul(lhs, rhs) {
|
|
1686
|
+
return mod(lhs * rhs, this.ORDER);
|
|
1687
|
+
}
|
|
1688
|
+
pow(num, power) {
|
|
1689
|
+
return FpPow(this, num, power);
|
|
1690
|
+
}
|
|
1691
|
+
div(lhs, rhs) {
|
|
1692
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
1693
|
+
}
|
|
1694
|
+
// Same as above, but doesn't normalize
|
|
1695
|
+
sqrN(num) {
|
|
1696
|
+
return num * num;
|
|
1697
|
+
}
|
|
1698
|
+
addN(lhs, rhs) {
|
|
1699
|
+
return lhs + rhs;
|
|
1700
|
+
}
|
|
1701
|
+
subN(lhs, rhs) {
|
|
1702
|
+
return lhs - rhs;
|
|
1703
|
+
}
|
|
1704
|
+
mulN(lhs, rhs) {
|
|
1705
|
+
return lhs * rhs;
|
|
1706
|
+
}
|
|
1707
|
+
inv(num) {
|
|
1708
|
+
return invert(num, this.ORDER);
|
|
1709
|
+
}
|
|
1710
|
+
sqrt(num) {
|
|
1711
|
+
// Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping
|
|
1712
|
+
// the field instance itself mutable.
|
|
1713
|
+
let sqrt = FIELD_SQRT.get(this);
|
|
1714
|
+
if (!sqrt)
|
|
1715
|
+
FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));
|
|
1716
|
+
return sqrt(this, num);
|
|
1717
|
+
}
|
|
1718
|
+
toBytes(num) {
|
|
1719
|
+
// Serialize fixed-width limbs without re-validating the field range. Callers that need a
|
|
1720
|
+
// canonical encoding must pass a valid element; some protocols intentionally serialize raw
|
|
1721
|
+
// residues here and reduce or validate them elsewhere.
|
|
1722
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
1723
|
+
}
|
|
1724
|
+
fromBytes(bytes, skipValidation = false) {
|
|
1725
|
+
abytes(bytes);
|
|
1726
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
1727
|
+
if (allowedLengths) {
|
|
1728
|
+
// `allowedLengths` must list real positive byte lengths; otherwise empty input would get
|
|
1729
|
+
// padded into zero and silently decode as a field element.
|
|
1730
|
+
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
1731
|
+
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
|
|
1732
|
+
}
|
|
1733
|
+
const padded = new Uint8Array(BYTES);
|
|
1734
|
+
// isLE add 0 to right, !isLE to the left.
|
|
1735
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
1736
|
+
bytes = padded;
|
|
1737
|
+
}
|
|
1738
|
+
if (bytes.length !== BYTES)
|
|
1739
|
+
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
|
1740
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
1741
|
+
if (modFromBytes)
|
|
1742
|
+
scalar = mod(scalar, ORDER);
|
|
1743
|
+
if (!skipValidation)
|
|
1744
|
+
if (!this.isValid(scalar))
|
|
1745
|
+
throw new Error('invalid field element: outside of range 0..ORDER');
|
|
1746
|
+
// Range validation is optional here because some protocols intentionally decode raw residues
|
|
1747
|
+
// and reduce or validate them elsewhere.
|
|
1748
|
+
return scalar;
|
|
1749
|
+
}
|
|
1750
|
+
// TODO: we don't need it here, move out to separate fn
|
|
1751
|
+
invertBatch(lst) {
|
|
1752
|
+
return FpInvertBatch(this, lst);
|
|
1753
|
+
}
|
|
1754
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
1755
|
+
// and it's unclear what to return in there.
|
|
1756
|
+
cmov(a, b, condition) {
|
|
1757
|
+
// Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject
|
|
1758
|
+
// non-boolean selectors here instead of letting JS truthiness silently change arithmetic.
|
|
1759
|
+
abool(condition, 'condition');
|
|
1760
|
+
return condition ? b : a;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
// Freeze the shared method surface too; otherwise callers can still poison every Field instance by
|
|
1764
|
+
// monkey-patching `_Field.prototype` even if each instance is frozen.
|
|
1765
|
+
Object.freeze(_Field.prototype);
|
|
1766
|
+
/**
|
|
1767
|
+
* Creates a finite field. Major performance optimizations:
|
|
1768
|
+
* * 1. Denormalized operations like mulN instead of mul.
|
|
1769
|
+
* * 2. Identical object shape: never add or remove keys.
|
|
1770
|
+
* * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
|
|
1771
|
+
* Fragile: always run a benchmark on a change.
|
|
1772
|
+
* Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
|
|
1773
|
+
* all elements for performance and protocol-flexibility reasons; callers are responsible for
|
|
1774
|
+
* supplying valid elements when they need canonical field behavior.
|
|
1775
|
+
* This is low-level code, please make sure you know what you're doing.
|
|
1776
|
+
*
|
|
1777
|
+
* Note about field properties:
|
|
1778
|
+
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
|
1779
|
+
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
|
1780
|
+
*
|
|
1781
|
+
* @param ORDER - field order, probably prime, or could be composite
|
|
1782
|
+
* @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
|
|
1783
|
+
* @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
|
|
1784
|
+
* into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
|
|
1785
|
+
* @example
|
|
1786
|
+
* Construct one prime field with optional overrides.
|
|
1787
|
+
*
|
|
1788
|
+
* ```ts
|
|
1789
|
+
* Field(11n);
|
|
1790
|
+
* ```
|
|
1791
|
+
*/
|
|
1792
|
+
function Field(ORDER, opts = {}) {
|
|
1793
|
+
return new _Field(ORDER, opts);
|
|
1794
|
+
}
|
|
1795
|
+
/**
|
|
1796
|
+
* Returns total number of bytes consumed by the field element.
|
|
1797
|
+
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
|
1798
|
+
* @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
|
|
1799
|
+
* order greater than 1.
|
|
1800
|
+
* @returns byte length of field
|
|
1801
|
+
* @throws If the field order is not a bigint. {@link Error}
|
|
1802
|
+
* @example
|
|
1803
|
+
* Read the fixed-width byte length of one field.
|
|
1804
|
+
*
|
|
1805
|
+
* ```ts
|
|
1806
|
+
* getFieldBytesLength(255n);
|
|
1807
|
+
* ```
|
|
1808
|
+
*/
|
|
1809
|
+
function getFieldBytesLength(fieldOrder) {
|
|
1810
|
+
if (typeof fieldOrder !== 'bigint')
|
|
1811
|
+
throw new Error('field order must be bigint');
|
|
1812
|
+
// Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.
|
|
1813
|
+
if (fieldOrder <= _1n$2)
|
|
1814
|
+
throw new Error('field order must be greater than 1');
|
|
1815
|
+
// Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.
|
|
1816
|
+
const bitLength = bitLen(fieldOrder - _1n$2);
|
|
1817
|
+
return Math.ceil(bitLength / 8);
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* Returns minimal amount of bytes that can be safely reduced
|
|
1821
|
+
* by field order.
|
|
1822
|
+
* Should be 2^-128 for 128-bit curve such as P256.
|
|
1823
|
+
* This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
|
|
1824
|
+
* absolute floor for policy reasons.
|
|
1825
|
+
* @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
|
|
1826
|
+
* @returns byte length of target hash
|
|
1827
|
+
* @throws If the field order is invalid. {@link Error}
|
|
1828
|
+
* @example
|
|
1829
|
+
* Compute the minimum hash length needed for field reduction.
|
|
1830
|
+
*
|
|
1831
|
+
* ```ts
|
|
1832
|
+
* getMinHashLength(255n);
|
|
1833
|
+
* ```
|
|
1834
|
+
*/
|
|
1835
|
+
function getMinHashLength(fieldOrder) {
|
|
1836
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
1837
|
+
return length + Math.ceil(length / 2);
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* "Constant-time" private key generation utility.
|
|
1841
|
+
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
|
1842
|
+
* and convert them into private scalar, with the modulo bias being negligible.
|
|
1843
|
+
* Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
|
|
1844
|
+
* 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
|
|
1845
|
+
* accidentally acceptable for real scalar derivation.
|
|
1846
|
+
* 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},
|
|
1847
|
+
* {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
|
|
1848
|
+
* {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
|
|
1849
|
+
* `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
|
|
1850
|
+
* @param key - Uniform input bytes.
|
|
1851
|
+
* @param fieldOrder - Size of subgroup.
|
|
1852
|
+
* @param isLE - interpret hash bytes as LE num
|
|
1853
|
+
* @returns valid private scalar
|
|
1854
|
+
* @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
|
|
1855
|
+
* @example
|
|
1856
|
+
* Map hash output into a private scalar range.
|
|
1857
|
+
*
|
|
1858
|
+
* ```ts
|
|
1859
|
+
* mapHashToField(new Uint8Array(48).fill(1), 255n);
|
|
1860
|
+
* ```
|
|
1861
|
+
*/
|
|
1862
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
1863
|
+
abytes(key);
|
|
1864
|
+
const len = key.length;
|
|
1865
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
1866
|
+
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
|
|
1867
|
+
// No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge
|
|
1868
|
+
// inputs: easier to reason about JS timing / allocation behavior.
|
|
1869
|
+
if (len < minLen || len > 1024)
|
|
1870
|
+
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
|
1871
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
1872
|
+
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
|
1873
|
+
const reduced = mod(num, fieldOrder - _1n$2) + _1n$2;
|
|
1874
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
/**
|
|
1878
|
+
* Methods for elliptic curve multiplication by scalars.
|
|
1879
|
+
* Contains wNAF, pippenger.
|
|
1880
|
+
* @module
|
|
1881
|
+
*/
|
|
1882
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1883
|
+
const _0n$1 = /* @__PURE__ */ BigInt(0);
|
|
1884
|
+
const _1n$1 = /* @__PURE__ */ BigInt(1);
|
|
1885
|
+
/**
|
|
1886
|
+
* Computes both candidates first, but the final selection still branches on `condition`, so this
|
|
1887
|
+
* is not a strict constant-time CMOV primitive.
|
|
1888
|
+
* @param condition - Whether to negate the point.
|
|
1889
|
+
* @param item - Point-like value.
|
|
1890
|
+
* @returns Original or negated value.
|
|
1891
|
+
* @example
|
|
1892
|
+
* Keep the point or return its negation based on one boolean branch.
|
|
1893
|
+
*
|
|
1894
|
+
* ```ts
|
|
1895
|
+
* import { negateCt } from '@noble/curves/abstract/curve.js';
|
|
1896
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
1897
|
+
* const maybeNegated = negateCt(true, p256.Point.BASE);
|
|
1898
|
+
* ```
|
|
1899
|
+
*/
|
|
1900
|
+
function negateCt(condition, item) {
|
|
1901
|
+
const neg = item.negate();
|
|
1902
|
+
return condition ? neg : item;
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Takes a bunch of Projective Points but executes only one
|
|
1906
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
1907
|
+
* so this improves performance massively.
|
|
1908
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
1909
|
+
* Input points are left unchanged; the normalized points are returned as fresh instances.
|
|
1910
|
+
* @param c - Point constructor.
|
|
1911
|
+
* @param points - Projective points.
|
|
1912
|
+
* @returns Fresh projective points reconstructed from normalized affine coordinates.
|
|
1913
|
+
* @example
|
|
1914
|
+
* Batch-normalize projective points with a single shared inversion.
|
|
1915
|
+
*
|
|
1916
|
+
* ```ts
|
|
1917
|
+
* import { normalizeZ } from '@noble/curves/abstract/curve.js';
|
|
1918
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
1919
|
+
* const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
|
|
1920
|
+
* ```
|
|
1921
|
+
*/
|
|
1922
|
+
function normalizeZ(c, points) {
|
|
1923
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
1924
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
1925
|
+
}
|
|
1926
|
+
function validateW(W, bits) {
|
|
1927
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
1928
|
+
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
|
1929
|
+
}
|
|
1930
|
+
function calcWOpts(W, scalarBits) {
|
|
1931
|
+
validateW(W, scalarBits);
|
|
1932
|
+
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
|
1933
|
+
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
|
1934
|
+
const maxNumber = 2 ** W; // W=8 256
|
|
1935
|
+
const mask = bitMask(W); // W=8 255 == mask 0b11111111
|
|
1936
|
+
const shiftBy = BigInt(W); // W=8 8
|
|
1937
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
1938
|
+
}
|
|
1939
|
+
function calcOffsets(n, window, wOpts) {
|
|
1940
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
1941
|
+
let wbits = Number(n & mask); // extract W bits.
|
|
1942
|
+
let nextN = n >> shiftBy; // shift number by W bits.
|
|
1943
|
+
// What actually happens here:
|
|
1944
|
+
// const highestBit = Number(mask ^ (mask >> 1n));
|
|
1945
|
+
// let wbits2 = wbits - 1; // skip zero
|
|
1946
|
+
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
|
1947
|
+
// split if bits > max: +224 => 256-32
|
|
1948
|
+
if (wbits > windowSize) {
|
|
1949
|
+
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
|
1950
|
+
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
|
1951
|
+
nextN += _1n$1; // +256 (carry)
|
|
1952
|
+
}
|
|
1953
|
+
const offsetStart = window * windowSize;
|
|
1954
|
+
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero
|
|
1955
|
+
const isZero = wbits === 0; // is current window slice a 0?
|
|
1956
|
+
const isNeg = wbits < 0; // is current window slice negative?
|
|
1957
|
+
const isNegF = window % 2 !== 0; // fake branch noise only
|
|
1958
|
+
const offsetF = offsetStart; // fake branch noise only
|
|
1959
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
1960
|
+
}
|
|
1961
|
+
// Since points in different groups cannot be equal (different object constructor),
|
|
1962
|
+
// we can have single place to store precomputes.
|
|
1963
|
+
// Allows to make points frozen / immutable.
|
|
1964
|
+
const pointPrecomputes = new WeakMap();
|
|
1965
|
+
const pointWindowSizes = new WeakMap();
|
|
1966
|
+
function getW(P) {
|
|
1967
|
+
// To disable precomputes:
|
|
1968
|
+
// return 1;
|
|
1969
|
+
// `1` is also the uncached sentinel: use the ladder / non-precomputed path.
|
|
1970
|
+
return pointWindowSizes.get(P) || 1;
|
|
1971
|
+
}
|
|
1972
|
+
function assert0(n) {
|
|
1973
|
+
// Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop
|
|
1974
|
+
// count is inconsistent, not that the original caller provided a bad scalar.
|
|
1975
|
+
if (n !== _0n$1)
|
|
1976
|
+
throw new Error('invalid wNAF');
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Elliptic curve multiplication of Point by scalar. Fragile.
|
|
1980
|
+
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
|
|
1981
|
+
* but may take much longer on slow devices. Actual generation will happen on
|
|
1982
|
+
* first call of `multiply()`. By default, `BASE` point is precomputed.
|
|
1983
|
+
*
|
|
1984
|
+
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
|
1985
|
+
* Creates precomputation tables for fast multiplication:
|
|
1986
|
+
* - private scalar is split by fixed size windows of W bits
|
|
1987
|
+
* - every window point is collected from window's table & added to accumulator
|
|
1988
|
+
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
|
1989
|
+
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
|
1990
|
+
* - +1 window is neccessary for wNAF
|
|
1991
|
+
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
|
1992
|
+
*
|
|
1993
|
+
* TODO: research returning a 2d JS array of windows instead of a single window.
|
|
1994
|
+
* This would allow windows to be in different memory locations.
|
|
1995
|
+
* @param Point - Point constructor.
|
|
1996
|
+
* @param bits - Scalar bit length.
|
|
1997
|
+
* @example
|
|
1998
|
+
* Elliptic curve multiplication of Point by scalar.
|
|
1999
|
+
*
|
|
2000
|
+
* ```ts
|
|
2001
|
+
* import { wNAF } from '@noble/curves/abstract/curve.js';
|
|
2002
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2003
|
+
* const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
|
|
2004
|
+
* ```
|
|
2005
|
+
*/
|
|
2006
|
+
class wNAF {
|
|
2007
|
+
BASE;
|
|
2008
|
+
ZERO;
|
|
2009
|
+
Fn;
|
|
2010
|
+
bits;
|
|
2011
|
+
// Parametrized with a given Point class (not individual point)
|
|
2012
|
+
constructor(Point, bits) {
|
|
2013
|
+
this.BASE = Point.BASE;
|
|
2014
|
+
this.ZERO = Point.ZERO;
|
|
2015
|
+
this.Fn = Point.Fn;
|
|
2016
|
+
this.bits = bits;
|
|
2017
|
+
}
|
|
2018
|
+
// non-const time multiplication ladder
|
|
2019
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
2020
|
+
let d = elm;
|
|
2021
|
+
while (n > _0n$1) {
|
|
2022
|
+
if (n & _1n$1)
|
|
2023
|
+
p = p.add(d);
|
|
2024
|
+
d = d.double();
|
|
2025
|
+
n >>= _1n$1;
|
|
2026
|
+
}
|
|
2027
|
+
return p;
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
2031
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
2032
|
+
* Number of precomputed points depends on the curve size:
|
|
2033
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
2034
|
+
* - 𝑊 is the window size
|
|
2035
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
2036
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
2037
|
+
* @param point - Point instance
|
|
2038
|
+
* @param W - window size
|
|
2039
|
+
* @returns precomputed point tables flattened to a single array
|
|
2040
|
+
*/
|
|
2041
|
+
precomputeWindow(point, W) {
|
|
2042
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
2043
|
+
const points = [];
|
|
2044
|
+
let p = point;
|
|
2045
|
+
let base = p;
|
|
2046
|
+
for (let window = 0; window < windows; window++) {
|
|
2047
|
+
base = p;
|
|
2048
|
+
points.push(base);
|
|
2049
|
+
// i=1, bc we skip 0
|
|
2050
|
+
for (let i = 1; i < windowSize; i++) {
|
|
2051
|
+
base = base.add(p);
|
|
2052
|
+
points.push(base);
|
|
2053
|
+
}
|
|
2054
|
+
p = base.double();
|
|
2055
|
+
}
|
|
2056
|
+
return points;
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
2060
|
+
* More compact implementation:
|
|
2061
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
2062
|
+
* @returns real and fake (for const-time) points
|
|
2063
|
+
*/
|
|
2064
|
+
wNAF(W, precomputes, n) {
|
|
2065
|
+
// Scalar should be smaller than field order
|
|
2066
|
+
if (!this.Fn.isValid(n))
|
|
2067
|
+
throw new Error('invalid scalar');
|
|
2068
|
+
// Accumulators
|
|
2069
|
+
let p = this.ZERO;
|
|
2070
|
+
let f = this.BASE;
|
|
2071
|
+
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
|
2072
|
+
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
|
2073
|
+
// there is negate now: it is possible that negated element from low value
|
|
2074
|
+
// would be the same as high element, which will create carry into next window.
|
|
2075
|
+
// It's not obvious how this can fail, but still worth investigating later.
|
|
2076
|
+
const wo = calcWOpts(W, this.bits);
|
|
2077
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
2078
|
+
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
|
2079
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
2080
|
+
n = nextN;
|
|
2081
|
+
if (isZero) {
|
|
2082
|
+
// bits are 0: add garbage to fake point
|
|
2083
|
+
// Important part for const-time getPublicKey: add random "noise" point to f.
|
|
2084
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
2085
|
+
}
|
|
2086
|
+
else {
|
|
2087
|
+
// bits are 1: add to result point
|
|
2088
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
assert0(n);
|
|
2092
|
+
// Return both real and fake points so JIT keeps the noise path alive.
|
|
2093
|
+
// Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,
|
|
2094
|
+
// which weakens the noise path and leaves this only "less const-time" by about one bigint mul.
|
|
2095
|
+
return { p, f };
|
|
2096
|
+
}
|
|
2097
|
+
/**
|
|
2098
|
+
* Implements unsafe EC multiplication using precomputed tables
|
|
2099
|
+
* and w-ary non-adjacent form.
|
|
2100
|
+
* @param acc - accumulator point to add result of multiplication
|
|
2101
|
+
* @returns point
|
|
2102
|
+
*/
|
|
2103
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
2104
|
+
const wo = calcWOpts(W, this.bits);
|
|
2105
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
2106
|
+
if (n === _0n$1)
|
|
2107
|
+
break; // Early-exit, skip 0 value
|
|
2108
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
2109
|
+
n = nextN;
|
|
2110
|
+
if (isZero) {
|
|
2111
|
+
// Window bits are 0: skip processing.
|
|
2112
|
+
// Move to next window.
|
|
2113
|
+
continue;
|
|
2114
|
+
}
|
|
2115
|
+
else {
|
|
2116
|
+
const item = precomputes[offset];
|
|
2117
|
+
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
assert0(n);
|
|
2121
|
+
return acc;
|
|
2122
|
+
}
|
|
2123
|
+
getPrecomputes(W, point, transform) {
|
|
2124
|
+
// Cache key is only point identity plus the remembered window size; callers must not reuse the
|
|
2125
|
+
// same point with incompatible `transform(...)` layouts and expect a separate cache entry.
|
|
2126
|
+
let comp = pointPrecomputes.get(point);
|
|
2127
|
+
if (!comp) {
|
|
2128
|
+
comp = this.precomputeWindow(point, W);
|
|
2129
|
+
if (W !== 1) {
|
|
2130
|
+
// Doing transform outside of if brings 15% perf hit
|
|
2131
|
+
if (typeof transform === 'function')
|
|
2132
|
+
comp = transform(comp);
|
|
2133
|
+
pointPrecomputes.set(point, comp);
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
return comp;
|
|
2137
|
+
}
|
|
2138
|
+
cached(point, scalar, transform) {
|
|
2139
|
+
const W = getW(point);
|
|
2140
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
2141
|
+
}
|
|
2142
|
+
unsafe(point, scalar, transform, prev) {
|
|
2143
|
+
const W = getW(point);
|
|
2144
|
+
if (W === 1)
|
|
2145
|
+
return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
|
|
2146
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
2147
|
+
}
|
|
2148
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
2149
|
+
// using windowed method. This specifies window size and
|
|
2150
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
2151
|
+
createCache(P, W) {
|
|
2152
|
+
validateW(W, this.bits);
|
|
2153
|
+
pointWindowSizes.set(P, W);
|
|
2154
|
+
pointPrecomputes.delete(P);
|
|
2155
|
+
}
|
|
2156
|
+
hasCache(elm) {
|
|
2157
|
+
return getW(elm) !== 1;
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
/**
|
|
2161
|
+
* Endomorphism-specific multiplication for Koblitz curves.
|
|
2162
|
+
* Cost: 128 dbl, 0-256 adds.
|
|
2163
|
+
* @param Point - Point constructor.
|
|
2164
|
+
* @param point - Input point.
|
|
2165
|
+
* @param k1 - First non-negative absolute scalar chunk.
|
|
2166
|
+
* @param k2 - Second non-negative absolute scalar chunk.
|
|
2167
|
+
* @returns Partial multiplication results.
|
|
2168
|
+
* @example
|
|
2169
|
+
* Endomorphism-specific multiplication for Koblitz curves.
|
|
2170
|
+
*
|
|
2171
|
+
* ```ts
|
|
2172
|
+
* import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';
|
|
2173
|
+
* import { secp256k1 } from '@noble/curves/secp256k1.js';
|
|
2174
|
+
* const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);
|
|
2175
|
+
* ```
|
|
2176
|
+
*/
|
|
2177
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
2178
|
+
let acc = point;
|
|
2179
|
+
let p1 = Point.ZERO;
|
|
2180
|
+
let p2 = Point.ZERO;
|
|
2181
|
+
while (k1 > _0n$1 || k2 > _0n$1) {
|
|
2182
|
+
if (k1 & _1n$1)
|
|
2183
|
+
p1 = p1.add(acc);
|
|
2184
|
+
if (k2 & _1n$1)
|
|
2185
|
+
p2 = p2.add(acc);
|
|
2186
|
+
acc = acc.double();
|
|
2187
|
+
k1 >>= _1n$1;
|
|
2188
|
+
k2 >>= _1n$1;
|
|
2189
|
+
}
|
|
2190
|
+
return { p1, p2 };
|
|
2191
|
+
}
|
|
2192
|
+
function createField(order, field, isLE) {
|
|
2193
|
+
if (field) {
|
|
2194
|
+
// Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback
|
|
2195
|
+
// fields, and validateField() below only checks the arithmetic subset, not full byte/cmov
|
|
2196
|
+
// behavior.
|
|
2197
|
+
if (field.ORDER !== order)
|
|
2198
|
+
throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
|
|
2199
|
+
validateField(field);
|
|
2200
|
+
return field;
|
|
2201
|
+
}
|
|
2202
|
+
else {
|
|
2203
|
+
return Field(order, { isLE });
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
/**
|
|
2207
|
+
* Validates basic CURVE shape and field membership, then creates fields.
|
|
2208
|
+
* This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
|
|
2209
|
+
* that the curve equation itself is otherwise sane.
|
|
2210
|
+
* @param type - Curve family.
|
|
2211
|
+
* @param CURVE - Curve parameters.
|
|
2212
|
+
* @param curveOpts - Optional field overrides:
|
|
2213
|
+
* - `Fp` (optional): Optional base-field override.
|
|
2214
|
+
* - `Fn` (optional): Optional scalar-field override.
|
|
2215
|
+
* @param FpFnLE - Whether field encoding is little-endian.
|
|
2216
|
+
* @returns Frozen curve parameters and fields.
|
|
2217
|
+
* @throws If the curve parameters or field overrides are invalid. {@link Error}
|
|
2218
|
+
* @example
|
|
2219
|
+
* Build curve fields from raw constants before constructing a curve instance.
|
|
2220
|
+
*
|
|
2221
|
+
* ```ts
|
|
2222
|
+
* const curve = createCurveFields('weierstrass', {
|
|
2223
|
+
* p: 17n,
|
|
2224
|
+
* n: 19n,
|
|
2225
|
+
* h: 1n,
|
|
2226
|
+
* a: 2n,
|
|
2227
|
+
* b: 2n,
|
|
2228
|
+
* Gx: 5n,
|
|
2229
|
+
* Gy: 1n,
|
|
2230
|
+
* });
|
|
2231
|
+
* ```
|
|
2232
|
+
*/
|
|
2233
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
2234
|
+
if (FpFnLE === undefined)
|
|
2235
|
+
FpFnLE = type === 'edwards';
|
|
2236
|
+
if (!CURVE || typeof CURVE !== 'object')
|
|
2237
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
2238
|
+
for (const p of ['p', 'n', 'h']) {
|
|
2239
|
+
const val = CURVE[p];
|
|
2240
|
+
if (!(typeof val === 'bigint' && val > _0n$1))
|
|
2241
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
2242
|
+
}
|
|
2243
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
2244
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
2245
|
+
const _b = 'b' ;
|
|
2246
|
+
const params = ['Gx', 'Gy', 'a', _b];
|
|
2247
|
+
for (const p of params) {
|
|
2248
|
+
// @ts-ignore
|
|
2249
|
+
if (!Fp.isValid(CURVE[p]))
|
|
2250
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
2251
|
+
}
|
|
2252
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
2253
|
+
return { CURVE, Fp, Fn };
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* @param randomSecretKey - Secret-key generator.
|
|
2257
|
+
* @param getPublicKey - Public-key derivation helper.
|
|
2258
|
+
* @returns Keypair generator.
|
|
2259
|
+
* @example
|
|
2260
|
+
* Build a `keygen()` helper from existing secret-key and public-key primitives.
|
|
2261
|
+
*
|
|
2262
|
+
* ```ts
|
|
2263
|
+
* import { createKeygen } from '@noble/curves/abstract/curve.js';
|
|
2264
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2265
|
+
* const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
|
|
2266
|
+
* const pair = keygen();
|
|
2267
|
+
* ```
|
|
2268
|
+
*/
|
|
2269
|
+
function createKeygen(randomSecretKey, getPublicKey) {
|
|
2270
|
+
return function keygen(seed) {
|
|
2271
|
+
const secretKey = randomSecretKey(seed);
|
|
2272
|
+
return { secretKey, publicKey: getPublicKey(secretKey) };
|
|
2273
|
+
};
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/**
|
|
2277
|
+
* HMAC: RFC2104 message authentication code.
|
|
2278
|
+
* @module
|
|
2279
|
+
*/
|
|
2280
|
+
/**
|
|
2281
|
+
* Internal class for HMAC.
|
|
2282
|
+
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
|
|
2283
|
+
* `HashLen` bytes long.
|
|
2284
|
+
*/
|
|
2285
|
+
class _HMAC {
|
|
2286
|
+
oHash;
|
|
2287
|
+
iHash;
|
|
2288
|
+
blockLen;
|
|
2289
|
+
outputLen;
|
|
2290
|
+
canXOF = false;
|
|
2291
|
+
finished = false;
|
|
2292
|
+
destroyed = false;
|
|
2293
|
+
constructor(hash, key) {
|
|
2294
|
+
ahash(hash);
|
|
2295
|
+
abytes$1(key, undefined, 'key');
|
|
2296
|
+
this.iHash = hash.create();
|
|
2297
|
+
if (typeof this.iHash.update !== 'function')
|
|
2298
|
+
throw new Error('Expected instance of class which extends utils.Hash');
|
|
2299
|
+
this.blockLen = this.iHash.blockLen;
|
|
2300
|
+
this.outputLen = this.iHash.outputLen;
|
|
2301
|
+
const blockLen = this.blockLen;
|
|
2302
|
+
const pad = new Uint8Array(blockLen);
|
|
2303
|
+
// blockLen can be bigger than outputLen
|
|
2304
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
2305
|
+
for (let i = 0; i < pad.length; i++)
|
|
2306
|
+
pad[i] ^= 0x36;
|
|
2307
|
+
this.iHash.update(pad);
|
|
2308
|
+
// By doing update (processing of the first block) of the outer hash here,
|
|
2309
|
+
// we can re-use it between multiple calls via clone.
|
|
2310
|
+
this.oHash = hash.create();
|
|
2311
|
+
// Undo internal XOR && apply outer XOR
|
|
2312
|
+
for (let i = 0; i < pad.length; i++)
|
|
2313
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
|
2314
|
+
this.oHash.update(pad);
|
|
2315
|
+
clean(pad);
|
|
2316
|
+
}
|
|
2317
|
+
update(buf) {
|
|
2318
|
+
aexists(this);
|
|
2319
|
+
this.iHash.update(buf);
|
|
2320
|
+
return this;
|
|
2321
|
+
}
|
|
2322
|
+
digestInto(out) {
|
|
2323
|
+
aexists(this);
|
|
2324
|
+
aoutput(out, this);
|
|
2325
|
+
this.finished = true;
|
|
2326
|
+
const buf = out.subarray(0, this.outputLen);
|
|
2327
|
+
// Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
|
|
2328
|
+
// overwriting that same prefix with the final tag, leaving any oversized tail untouched.
|
|
2329
|
+
this.iHash.digestInto(buf);
|
|
2330
|
+
this.oHash.update(buf);
|
|
2331
|
+
this.oHash.digestInto(buf);
|
|
2332
|
+
this.destroy();
|
|
2333
|
+
}
|
|
2334
|
+
digest() {
|
|
2335
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
2336
|
+
this.digestInto(out);
|
|
2337
|
+
return out;
|
|
2338
|
+
}
|
|
2339
|
+
_cloneInto(to) {
|
|
2340
|
+
// Create new instance without calling constructor since the key
|
|
2341
|
+
// is already in state and we don't know it.
|
|
2342
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
2343
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
2344
|
+
to = to;
|
|
2345
|
+
to.finished = finished;
|
|
2346
|
+
to.destroyed = destroyed;
|
|
2347
|
+
to.blockLen = blockLen;
|
|
2348
|
+
to.outputLen = outputLen;
|
|
2349
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
2350
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
2351
|
+
return to;
|
|
2352
|
+
}
|
|
2353
|
+
clone() {
|
|
2354
|
+
return this._cloneInto();
|
|
2355
|
+
}
|
|
2356
|
+
destroy() {
|
|
2357
|
+
this.destroyed = true;
|
|
2358
|
+
this.oHash.destroy();
|
|
2359
|
+
this.iHash.destroy();
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
const hmac = /* @__PURE__ */ (() => {
|
|
2363
|
+
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
|
2364
|
+
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
|
2365
|
+
return hmac_;
|
|
2366
|
+
})();
|
|
2367
|
+
|
|
2368
|
+
/**
|
|
2369
|
+
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
|
|
2370
|
+
*
|
|
2371
|
+
* ### Design rationale for types
|
|
2372
|
+
*
|
|
2373
|
+
* * Interaction between classes from different curves should fail:
|
|
2374
|
+
* `k256.Point.BASE.add(p256.Point.BASE)`
|
|
2375
|
+
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
|
|
2376
|
+
* * Different calls of `curve()` would return different classes -
|
|
2377
|
+
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
|
|
2378
|
+
* it won't affect others
|
|
2379
|
+
*
|
|
2380
|
+
* TypeScript can't infer types for classes created inside a function. Classes is one instance
|
|
2381
|
+
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
|
|
2382
|
+
* unique type for every function call.
|
|
2383
|
+
*
|
|
2384
|
+
* We can use generic types via some param, like curve opts, but that would:
|
|
2385
|
+
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
|
|
2386
|
+
* which is hard to debug.
|
|
2387
|
+
* 2. Params can be generic and we can't enforce them to be constant value:
|
|
2388
|
+
* if somebody creates curve from non-constant params,
|
|
2389
|
+
* it would be allowed to interact with other curves with non-constant params
|
|
2390
|
+
*
|
|
2391
|
+
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
|
|
2392
|
+
* @module
|
|
2393
|
+
*/
|
|
2394
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2395
|
+
// We construct the basis so `den` is always positive and equals `n`,
|
|
2396
|
+
// but the `num` sign depends on the basis, not on the secret value.
|
|
2397
|
+
// Exact half-way cases round away from zero, which keeps the split symmetric
|
|
2398
|
+
// around the reduced-basis boundaries used by endomorphism decomposition.
|
|
2399
|
+
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
|
|
2400
|
+
/** Splits scalar for GLV endomorphism. */
|
|
2401
|
+
function _splitEndoScalar(k, basis, n) {
|
|
2402
|
+
// Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
|
|
2403
|
+
// Since part can be negative, we need to do this on point.
|
|
2404
|
+
// Callers must provide a reduced GLV basis whose vectors satisfy
|
|
2405
|
+
// `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.
|
|
2406
|
+
// Reject unreduced scalars instead of silently treating them mod n.
|
|
2407
|
+
aInRange('scalar', k, _0n, n);
|
|
2408
|
+
// TODO: verifyScalar function which consumes lambda
|
|
2409
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
2410
|
+
const c1 = divNearest(b2 * k, n);
|
|
2411
|
+
const c2 = divNearest(-b1 * k, n);
|
|
2412
|
+
// |k1|/|k2| is < sqrt(N), but can be negative.
|
|
2413
|
+
// If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
|
|
2414
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
2415
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
2416
|
+
const k1neg = k1 < _0n;
|
|
2417
|
+
const k2neg = k2 < _0n;
|
|
2418
|
+
if (k1neg)
|
|
2419
|
+
k1 = -k1;
|
|
2420
|
+
if (k2neg)
|
|
2421
|
+
k2 = -k2;
|
|
2422
|
+
// Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
|
|
2423
|
+
// This should only happen on wrong bases.
|
|
2424
|
+
// Also, the math inside is complex enough that this guard is worth keeping.
|
|
2425
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
|
|
2426
|
+
if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
|
|
2427
|
+
throw new Error('splitScalar (endomorphism): failed for k');
|
|
2428
|
+
}
|
|
2429
|
+
return { k1neg, k1, k2neg, k2 };
|
|
2430
|
+
}
|
|
2431
|
+
function validateSigFormat(format) {
|
|
2432
|
+
if (!['compact', 'recovered', 'der'].includes(format))
|
|
2433
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
2434
|
+
return format;
|
|
2435
|
+
}
|
|
2436
|
+
function validateSigOpts(opts, def) {
|
|
2437
|
+
validateObject(opts);
|
|
2438
|
+
const optsn = {};
|
|
2439
|
+
// Normalize only the declared option subset from `def`; unknown keys are
|
|
2440
|
+
// intentionally ignored so shared / superset option bags stay valid here too.
|
|
2441
|
+
// `extraEntropy` stays an opaque payload until the signing path consumes it.
|
|
2442
|
+
for (let optName of Object.keys(def)) {
|
|
2443
|
+
// @ts-ignore
|
|
2444
|
+
optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
|
|
2445
|
+
}
|
|
2446
|
+
abool(optsn.lowS, 'lowS');
|
|
2447
|
+
abool(optsn.prehash, 'prehash');
|
|
2448
|
+
if (optsn.format !== undefined)
|
|
2449
|
+
validateSigFormat(optsn.format);
|
|
2450
|
+
return optsn;
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* @param m - Error message.
|
|
2454
|
+
* @example
|
|
2455
|
+
* Throw a DER-specific error when signature parsing encounters invalid bytes.
|
|
2456
|
+
*
|
|
2457
|
+
* ```ts
|
|
2458
|
+
* new DERErr('bad der');
|
|
2459
|
+
* ```
|
|
2460
|
+
*/
|
|
2461
|
+
class DERErr extends Error {
|
|
2462
|
+
constructor(m = '') {
|
|
2463
|
+
super(m);
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
|
2468
|
+
*
|
|
2469
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
|
2470
|
+
*
|
|
2471
|
+
* Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and
|
|
2472
|
+
* {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.
|
|
2473
|
+
* @example
|
|
2474
|
+
* ASN.1 DER encoding utilities.
|
|
2475
|
+
*
|
|
2476
|
+
* ```ts
|
|
2477
|
+
* const der = DER.hexFromSig({ r: 1n, s: 2n });
|
|
2478
|
+
* ```
|
|
2479
|
+
*/
|
|
2480
|
+
const DER = {
|
|
2481
|
+
// asn.1 DER encoding utils
|
|
2482
|
+
Err: DERErr,
|
|
2483
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
2484
|
+
_tlv: {
|
|
2485
|
+
encode: (tag, data) => {
|
|
2486
|
+
const { Err: E } = DER;
|
|
2487
|
+
asafenumber(tag, 'tag');
|
|
2488
|
+
if (tag < 0 || tag > 255)
|
|
2489
|
+
throw new E('tlv.encode: wrong tag');
|
|
2490
|
+
if (typeof data !== 'string')
|
|
2491
|
+
throw new TypeError('"data" expected string, got type=' + typeof data);
|
|
2492
|
+
// Internal helper: callers hand this already-validated hex payload, so we only enforce
|
|
2493
|
+
// byte alignment here instead of re-validating every nibble.
|
|
2494
|
+
if (data.length & 1)
|
|
2495
|
+
throw new E('tlv.encode: unpadded data');
|
|
2496
|
+
const dataLen = data.length / 2;
|
|
2497
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2498
|
+
if ((len.length / 2) & 0b1000_0000)
|
|
2499
|
+
throw new E('tlv.encode: long form length too big');
|
|
2500
|
+
// length of length with long form flag
|
|
2501
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';
|
|
2502
|
+
const t = numberToHexUnpadded(tag);
|
|
2503
|
+
return t + lenLen + len + data;
|
|
2504
|
+
},
|
|
2505
|
+
// v - value, l - left bytes (unparsed)
|
|
2506
|
+
decode(tag, data) {
|
|
2507
|
+
const { Err: E } = DER;
|
|
2508
|
+
data = abytes(data, undefined, 'DER data');
|
|
2509
|
+
let pos = 0;
|
|
2510
|
+
if (tag < 0 || tag > 255)
|
|
2511
|
+
throw new E('tlv.encode: wrong tag');
|
|
2512
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
2513
|
+
throw new E('tlv.decode: wrong tlv');
|
|
2514
|
+
const first = data[pos++];
|
|
2515
|
+
// First bit of first length byte is the short/long form flag.
|
|
2516
|
+
const isLong = !!(first & 0b1000_0000);
|
|
2517
|
+
let length = 0;
|
|
2518
|
+
if (!isLong)
|
|
2519
|
+
length = first;
|
|
2520
|
+
else {
|
|
2521
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
|
2522
|
+
const lenLen = first & 0b0111_1111;
|
|
2523
|
+
if (!lenLen)
|
|
2524
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
|
2525
|
+
// This would overflow u32 in JS.
|
|
2526
|
+
if (lenLen > 4)
|
|
2527
|
+
throw new E('tlv.decode(long): byte length is too big');
|
|
2528
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2529
|
+
if (lengthBytes.length !== lenLen)
|
|
2530
|
+
throw new E('tlv.decode: length bytes not complete');
|
|
2531
|
+
if (lengthBytes[0] === 0)
|
|
2532
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
|
2533
|
+
for (const b of lengthBytes)
|
|
2534
|
+
length = (length << 8) | b;
|
|
2535
|
+
pos += lenLen;
|
|
2536
|
+
if (length < 128)
|
|
2537
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
|
2538
|
+
}
|
|
2539
|
+
const v = data.subarray(pos, pos + length);
|
|
2540
|
+
if (v.length !== length)
|
|
2541
|
+
throw new E('tlv.decode: wrong value length');
|
|
2542
|
+
return { v, l: data.subarray(pos + length) };
|
|
2543
|
+
},
|
|
2544
|
+
},
|
|
2545
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
2546
|
+
// since we always use positive integers here. It must always be empty:
|
|
2547
|
+
// - add zero byte if exists
|
|
2548
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
2549
|
+
_int: {
|
|
2550
|
+
encode(num) {
|
|
2551
|
+
const { Err: E } = DER;
|
|
2552
|
+
abignumber(num);
|
|
2553
|
+
if (num < _0n)
|
|
2554
|
+
throw new E('integer: negative integers are not allowed');
|
|
2555
|
+
let hex = numberToHexUnpadded(num);
|
|
2556
|
+
// Pad with zero byte if negative flag is present
|
|
2557
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
|
2558
|
+
hex = '00' + hex;
|
|
2559
|
+
if (hex.length & 1)
|
|
2560
|
+
throw new E('unexpected DER parsing assertion: unpadded hex');
|
|
2561
|
+
return hex;
|
|
2562
|
+
},
|
|
2563
|
+
decode(data) {
|
|
2564
|
+
const { Err: E } = DER;
|
|
2565
|
+
if (data.length < 1)
|
|
2566
|
+
throw new E('invalid signature integer: empty');
|
|
2567
|
+
if (data[0] & 0b1000_0000)
|
|
2568
|
+
throw new E('invalid signature integer: negative');
|
|
2569
|
+
// Single-byte zero `00` is the canonical DER INTEGER encoding for zero.
|
|
2570
|
+
if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))
|
|
2571
|
+
throw new E('invalid signature integer: unnecessary leading zero');
|
|
2572
|
+
return bytesToNumberBE(data);
|
|
2573
|
+
},
|
|
2574
|
+
},
|
|
2575
|
+
toSig(bytes) {
|
|
2576
|
+
// parse DER signature
|
|
2577
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
2578
|
+
const data = abytes(bytes, undefined, 'signature');
|
|
2579
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
|
2580
|
+
if (seqLeftBytes.length)
|
|
2581
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2582
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
|
2583
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
|
2584
|
+
if (sLeftBytes.length)
|
|
2585
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2586
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
2587
|
+
},
|
|
2588
|
+
hexFromSig(sig) {
|
|
2589
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
2590
|
+
const rs = tlv.encode(0x02, int.encode(sig.r));
|
|
2591
|
+
const ss = tlv.encode(0x02, int.encode(sig.s));
|
|
2592
|
+
const seq = rs + ss;
|
|
2593
|
+
return tlv.encode(0x30, seq);
|
|
2594
|
+
},
|
|
2595
|
+
};
|
|
2596
|
+
Object.freeze(DER._tlv);
|
|
2597
|
+
Object.freeze(DER._int);
|
|
2598
|
+
Object.freeze(DER);
|
|
2599
|
+
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
|
2600
|
+
// prettier-ignore
|
|
2601
|
+
const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n$1 = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);
|
|
2602
|
+
/**
|
|
2603
|
+
* Creates weierstrass Point constructor, based on specified curve options.
|
|
2604
|
+
*
|
|
2605
|
+
* See {@link WeierstrassOpts}.
|
|
2606
|
+
* @param params - Curve parameters. See {@link WeierstrassOpts}.
|
|
2607
|
+
* @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.
|
|
2608
|
+
* @returns Weierstrass point constructor.
|
|
2609
|
+
* @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}
|
|
2610
|
+
*
|
|
2611
|
+
* @example
|
|
2612
|
+
* Construct a point type from explicit Weierstrass curve parameters.
|
|
2613
|
+
*
|
|
2614
|
+
* ```js
|
|
2615
|
+
* const opts = {
|
|
2616
|
+
* p: 0xfffffffffffffffffffffffffffffffeffffac73n,
|
|
2617
|
+
* n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,
|
|
2618
|
+
* h: 1n,
|
|
2619
|
+
* a: 0n,
|
|
2620
|
+
* b: 7n,
|
|
2621
|
+
* Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,
|
|
2622
|
+
* Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,
|
|
2623
|
+
* };
|
|
2624
|
+
* const secp160k1_Point = weierstrass(opts);
|
|
2625
|
+
* ```
|
|
2626
|
+
*/
|
|
2627
|
+
function weierstrass(params, extraOpts = {}) {
|
|
2628
|
+
const validated = createCurveFields('weierstrass', params, extraOpts);
|
|
2629
|
+
const Fp = validated.Fp;
|
|
2630
|
+
const Fn = validated.Fn;
|
|
2631
|
+
let CURVE = validated.CURVE;
|
|
2632
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
2633
|
+
validateObject(extraOpts, {}, {
|
|
2634
|
+
allowInfinityPoint: 'boolean',
|
|
2635
|
+
clearCofactor: 'function',
|
|
2636
|
+
isTorsionFree: 'function',
|
|
2637
|
+
fromBytes: 'function',
|
|
2638
|
+
toBytes: 'function',
|
|
2639
|
+
endo: 'object',
|
|
2640
|
+
});
|
|
2641
|
+
// Snapshot constructor-time flags whose later mutation would otherwise change
|
|
2642
|
+
// validity semantics of an already-built point type.
|
|
2643
|
+
const { endo, allowInfinityPoint } = extraOpts;
|
|
2644
|
+
if (endo) {
|
|
2645
|
+
// validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
|
|
2646
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
|
|
2647
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
const lengths = getWLengths(Fp, Fn);
|
|
2651
|
+
function assertCompressionIsSupported() {
|
|
2652
|
+
if (!Fp.isOdd)
|
|
2653
|
+
throw new Error('compression is not supported: Field does not have .isOdd()');
|
|
2654
|
+
}
|
|
2655
|
+
// Implements IEEE P1363 point encoding
|
|
2656
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
2657
|
+
// SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves
|
|
2658
|
+
// that opt into infinity as a public point value should expose that byte form.
|
|
2659
|
+
if (allowInfinityPoint && point.is0())
|
|
2660
|
+
return Uint8Array.of(0);
|
|
2661
|
+
const { x, y } = point.toAffine();
|
|
2662
|
+
const bx = Fp.toBytes(x);
|
|
2663
|
+
abool(isCompressed, 'isCompressed');
|
|
2664
|
+
if (isCompressed) {
|
|
2665
|
+
assertCompressionIsSupported();
|
|
2666
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
2667
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
2668
|
+
}
|
|
2669
|
+
else {
|
|
2670
|
+
return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
function pointFromBytes(bytes) {
|
|
2674
|
+
abytes(bytes, undefined, 'Point');
|
|
2675
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
|
|
2676
|
+
const length = bytes.length;
|
|
2677
|
+
const head = bytes[0];
|
|
2678
|
+
const tail = bytes.subarray(1);
|
|
2679
|
+
if (allowInfinityPoint && length === 1 && head === 0x00)
|
|
2680
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
2681
|
+
// SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation
|
|
2682
|
+
// rejects infinity. We therefore keep 0x00 rejected by default because callers
|
|
2683
|
+
// reuse this parser as the strict public-key boundary, and only admit it when
|
|
2684
|
+
// the curve explicitly opts into infinity as a public point value. secp256k1
|
|
2685
|
+
// crosstests show OpenSSL raw point codecs accept 0x00 too.
|
|
2686
|
+
// No actual validation is done here: use .assertValidity()
|
|
2687
|
+
if (length === comp && (head === 0x02 || head === 0x03)) {
|
|
2688
|
+
const x = Fp.fromBytes(tail);
|
|
2689
|
+
if (!Fp.isValid(x))
|
|
2690
|
+
throw new Error('bad point: is not on curve, wrong x');
|
|
2691
|
+
const y2 = weierstrassEquation(x); // y² = x³ + ax + b
|
|
2692
|
+
let y;
|
|
2693
|
+
try {
|
|
2694
|
+
y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
|
|
2695
|
+
}
|
|
2696
|
+
catch (sqrtError) {
|
|
2697
|
+
const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
|
|
2698
|
+
throw new Error('bad point: is not on curve, sqrt error' + err);
|
|
2699
|
+
}
|
|
2700
|
+
assertCompressionIsSupported();
|
|
2701
|
+
const evenY = Fp.isOdd(y);
|
|
2702
|
+
const evenH = (head & 1) === 1; // ECDSA-specific
|
|
2703
|
+
if (evenH !== evenY)
|
|
2704
|
+
y = Fp.neg(y);
|
|
2705
|
+
return { x, y };
|
|
2706
|
+
}
|
|
2707
|
+
else if (length === uncomp && head === 0x04) {
|
|
2708
|
+
// TODO: more checks
|
|
2709
|
+
const L = Fp.BYTES;
|
|
2710
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
2711
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
2712
|
+
if (!isValidXY(x, y))
|
|
2713
|
+
throw new Error('bad point: is not on curve');
|
|
2714
|
+
return { x, y };
|
|
2715
|
+
}
|
|
2716
|
+
else {
|
|
2717
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;
|
|
2721
|
+
const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;
|
|
2722
|
+
function weierstrassEquation(x) {
|
|
2723
|
+
const x2 = Fp.sqr(x); // x * x
|
|
2724
|
+
const x3 = Fp.mul(x2, x); // x² * x
|
|
2725
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
|
|
2726
|
+
}
|
|
2727
|
+
// TODO: move top-level
|
|
2728
|
+
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
|
|
2729
|
+
function isValidXY(x, y) {
|
|
2730
|
+
const left = Fp.sqr(y); // y²
|
|
2731
|
+
const right = weierstrassEquation(x); // x³ + ax + b
|
|
2732
|
+
return Fp.eql(left, right);
|
|
2733
|
+
}
|
|
2734
|
+
// Keep constructor-time generator validation cheap: callers are responsible for supplying the
|
|
2735
|
+
// correct prime-order base point, while eager subgroup checks here would slow heavy module imports.
|
|
2736
|
+
// Test 1: equation y² = x³ + ax + b should work for generator point.
|
|
2737
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
2738
|
+
throw new Error('bad curve params: generator point');
|
|
2739
|
+
// Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
|
|
2740
|
+
// Guarantees curve is genus-1, smooth (non-singular).
|
|
2741
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
|
|
2742
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
2743
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
2744
|
+
throw new Error('bad curve params: a or b');
|
|
2745
|
+
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
|
|
2746
|
+
function acoord(title, n, banZero = false) {
|
|
2747
|
+
if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
|
|
2748
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
2749
|
+
return n;
|
|
2750
|
+
}
|
|
2751
|
+
function aprjpoint(other) {
|
|
2752
|
+
if (!(other instanceof Point))
|
|
2753
|
+
throw new Error('Weierstrass Point expected');
|
|
2754
|
+
}
|
|
2755
|
+
function splitEndoScalarN(k) {
|
|
2756
|
+
if (!endo || !endo.basises)
|
|
2757
|
+
throw new Error('no endo');
|
|
2758
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
2759
|
+
}
|
|
2760
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
2761
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
2762
|
+
k1p = negateCt(k1neg, k1p);
|
|
2763
|
+
k2p = negateCt(k2neg, k2p);
|
|
2764
|
+
return k1p.add(k2p);
|
|
2765
|
+
}
|
|
2766
|
+
/**
|
|
2767
|
+
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
2768
|
+
* Default Point works in 2d / affine coordinates: (x, y).
|
|
2769
|
+
* We're doing calculations in projective, because its operations don't require costly inversion.
|
|
2770
|
+
*/
|
|
2771
|
+
class Point {
|
|
2772
|
+
// base / generator point
|
|
2773
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
2774
|
+
// zero / infinity / identity point
|
|
2775
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
|
|
2776
|
+
// math field
|
|
2777
|
+
static Fp = Fp;
|
|
2778
|
+
// scalar field
|
|
2779
|
+
static Fn = Fn;
|
|
2780
|
+
X;
|
|
2781
|
+
Y;
|
|
2782
|
+
Z;
|
|
2783
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2784
|
+
constructor(X, Y, Z) {
|
|
2785
|
+
this.X = acoord('x', X);
|
|
2786
|
+
// This is not just about ZERO / infinity: ambient curves can have real
|
|
2787
|
+
// finite points with y=0. Those points are 2-torsion, so they cannot lie
|
|
2788
|
+
// in the odd prime-order subgroups this point type is meant to represent.
|
|
2789
|
+
this.Y = acoord('y', Y, true);
|
|
2790
|
+
this.Z = acoord('z', Z);
|
|
2791
|
+
Object.freeze(this);
|
|
2792
|
+
}
|
|
2793
|
+
static CURVE() {
|
|
2794
|
+
return CURVE;
|
|
2795
|
+
}
|
|
2796
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2797
|
+
static fromAffine(p) {
|
|
2798
|
+
const { x, y } = p || {};
|
|
2799
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
2800
|
+
throw new Error('invalid affine point');
|
|
2801
|
+
if (p instanceof Point)
|
|
2802
|
+
throw new Error('projective point not allowed');
|
|
2803
|
+
// (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
|
|
2804
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
2805
|
+
return Point.ZERO;
|
|
2806
|
+
return new Point(x, y, Fp.ONE);
|
|
2807
|
+
}
|
|
2808
|
+
static fromBytes(bytes) {
|
|
2809
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
|
|
2810
|
+
P.assertValidity();
|
|
2811
|
+
return P;
|
|
2812
|
+
}
|
|
2813
|
+
static fromHex(hex) {
|
|
2814
|
+
return Point.fromBytes(hexToBytes(hex));
|
|
2815
|
+
}
|
|
2816
|
+
get x() {
|
|
2817
|
+
return this.toAffine().x;
|
|
2818
|
+
}
|
|
2819
|
+
get y() {
|
|
2820
|
+
return this.toAffine().y;
|
|
2821
|
+
}
|
|
2822
|
+
/**
|
|
2823
|
+
*
|
|
2824
|
+
* @param windowSize
|
|
2825
|
+
* @param isLazy - true will defer table computation until the first multiplication
|
|
2826
|
+
* @returns
|
|
2827
|
+
*/
|
|
2828
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
2829
|
+
wnaf.createCache(this, windowSize);
|
|
2830
|
+
if (!isLazy)
|
|
2831
|
+
this.multiply(_3n); // random number
|
|
2832
|
+
return this;
|
|
2833
|
+
}
|
|
2834
|
+
// TODO: return `this`
|
|
2835
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
2836
|
+
assertValidity() {
|
|
2837
|
+
const p = this;
|
|
2838
|
+
if (p.is0()) {
|
|
2839
|
+
// (0, 1, 0) aka ZERO is invalid in most contexts.
|
|
2840
|
+
// In BLS, ZERO can be serialized, so we allow it.
|
|
2841
|
+
// Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points
|
|
2842
|
+
// like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.
|
|
2843
|
+
if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
|
|
2844
|
+
return;
|
|
2845
|
+
throw new Error('bad point: ZERO');
|
|
2846
|
+
}
|
|
2847
|
+
// Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
|
|
2848
|
+
const { x, y } = p.toAffine();
|
|
2849
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
2850
|
+
throw new Error('bad point: x or y not field elements');
|
|
2851
|
+
if (!isValidXY(x, y))
|
|
2852
|
+
throw new Error('bad point: equation left != right');
|
|
2853
|
+
if (!p.isTorsionFree())
|
|
2854
|
+
throw new Error('bad point: not in prime-order subgroup');
|
|
2855
|
+
}
|
|
2856
|
+
hasEvenY() {
|
|
2857
|
+
const { y } = this.toAffine();
|
|
2858
|
+
if (!Fp.isOdd)
|
|
2859
|
+
throw new Error("Field doesn't support isOdd");
|
|
2860
|
+
return !Fp.isOdd(y);
|
|
2861
|
+
}
|
|
2862
|
+
/** Compare one point to another. */
|
|
2863
|
+
equals(other) {
|
|
2864
|
+
aprjpoint(other);
|
|
2865
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2866
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2867
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
2868
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
2869
|
+
return U1 && U2;
|
|
2870
|
+
}
|
|
2871
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
2872
|
+
negate() {
|
|
2873
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
2874
|
+
}
|
|
2875
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
2876
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2877
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
2878
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
2879
|
+
double() {
|
|
2880
|
+
const { a, b } = CURVE;
|
|
2881
|
+
const b3 = Fp.mul(b, _3n);
|
|
2882
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2883
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2884
|
+
let t0 = Fp.mul(X1, X1); // step 1
|
|
2885
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
2886
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
2887
|
+
let t3 = Fp.mul(X1, Y1);
|
|
2888
|
+
t3 = Fp.add(t3, t3); // step 5
|
|
2889
|
+
Z3 = Fp.mul(X1, Z1);
|
|
2890
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2891
|
+
X3 = Fp.mul(a, Z3);
|
|
2892
|
+
Y3 = Fp.mul(b3, t2);
|
|
2893
|
+
Y3 = Fp.add(X3, Y3); // step 10
|
|
2894
|
+
X3 = Fp.sub(t1, Y3);
|
|
2895
|
+
Y3 = Fp.add(t1, Y3);
|
|
2896
|
+
Y3 = Fp.mul(X3, Y3);
|
|
2897
|
+
X3 = Fp.mul(t3, X3);
|
|
2898
|
+
Z3 = Fp.mul(b3, Z3); // step 15
|
|
2899
|
+
t2 = Fp.mul(a, t2);
|
|
2900
|
+
t3 = Fp.sub(t0, t2);
|
|
2901
|
+
t3 = Fp.mul(a, t3);
|
|
2902
|
+
t3 = Fp.add(t3, Z3);
|
|
2903
|
+
Z3 = Fp.add(t0, t0); // step 20
|
|
2904
|
+
t0 = Fp.add(Z3, t0);
|
|
2905
|
+
t0 = Fp.add(t0, t2);
|
|
2906
|
+
t0 = Fp.mul(t0, t3);
|
|
2907
|
+
Y3 = Fp.add(Y3, t0);
|
|
2908
|
+
t2 = Fp.mul(Y1, Z1); // step 25
|
|
2909
|
+
t2 = Fp.add(t2, t2);
|
|
2910
|
+
t0 = Fp.mul(t2, t3);
|
|
2911
|
+
X3 = Fp.sub(X3, t0);
|
|
2912
|
+
Z3 = Fp.mul(t2, t1);
|
|
2913
|
+
Z3 = Fp.add(Z3, Z3); // step 30
|
|
2914
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2915
|
+
return new Point(X3, Y3, Z3);
|
|
2916
|
+
}
|
|
2917
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
2918
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2919
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
2920
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
2921
|
+
add(other) {
|
|
2922
|
+
aprjpoint(other);
|
|
2923
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2924
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2925
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2926
|
+
const a = CURVE.a;
|
|
2927
|
+
const b3 = Fp.mul(CURVE.b, _3n);
|
|
2928
|
+
let t0 = Fp.mul(X1, X2); // step 1
|
|
2929
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
2930
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
2931
|
+
let t3 = Fp.add(X1, Y1);
|
|
2932
|
+
let t4 = Fp.add(X2, Y2); // step 5
|
|
2933
|
+
t3 = Fp.mul(t3, t4);
|
|
2934
|
+
t4 = Fp.add(t0, t1);
|
|
2935
|
+
t3 = Fp.sub(t3, t4);
|
|
2936
|
+
t4 = Fp.add(X1, Z1);
|
|
2937
|
+
let t5 = Fp.add(X2, Z2); // step 10
|
|
2938
|
+
t4 = Fp.mul(t4, t5);
|
|
2939
|
+
t5 = Fp.add(t0, t2);
|
|
2940
|
+
t4 = Fp.sub(t4, t5);
|
|
2941
|
+
t5 = Fp.add(Y1, Z1);
|
|
2942
|
+
X3 = Fp.add(Y2, Z2); // step 15
|
|
2943
|
+
t5 = Fp.mul(t5, X3);
|
|
2944
|
+
X3 = Fp.add(t1, t2);
|
|
2945
|
+
t5 = Fp.sub(t5, X3);
|
|
2946
|
+
Z3 = Fp.mul(a, t4);
|
|
2947
|
+
X3 = Fp.mul(b3, t2); // step 20
|
|
2948
|
+
Z3 = Fp.add(X3, Z3);
|
|
2949
|
+
X3 = Fp.sub(t1, Z3);
|
|
2950
|
+
Z3 = Fp.add(t1, Z3);
|
|
2951
|
+
Y3 = Fp.mul(X3, Z3);
|
|
2952
|
+
t1 = Fp.add(t0, t0); // step 25
|
|
2953
|
+
t1 = Fp.add(t1, t0);
|
|
2954
|
+
t2 = Fp.mul(a, t2);
|
|
2955
|
+
t4 = Fp.mul(b3, t4);
|
|
2956
|
+
t1 = Fp.add(t1, t2);
|
|
2957
|
+
t2 = Fp.sub(t0, t2); // step 30
|
|
2958
|
+
t2 = Fp.mul(a, t2);
|
|
2959
|
+
t4 = Fp.add(t4, t2);
|
|
2960
|
+
t0 = Fp.mul(t1, t4);
|
|
2961
|
+
Y3 = Fp.add(Y3, t0);
|
|
2962
|
+
t0 = Fp.mul(t5, t4); // step 35
|
|
2963
|
+
X3 = Fp.mul(t3, X3);
|
|
2964
|
+
X3 = Fp.sub(X3, t0);
|
|
2965
|
+
t0 = Fp.mul(t3, t1);
|
|
2966
|
+
Z3 = Fp.mul(t5, Z3);
|
|
2967
|
+
Z3 = Fp.add(Z3, t0); // step 40
|
|
2968
|
+
return new Point(X3, Y3, Z3);
|
|
2969
|
+
}
|
|
2970
|
+
subtract(other) {
|
|
2971
|
+
// Validate before calling `negate()` so wrong inputs fail with the point guard
|
|
2972
|
+
// instead of leaking a foreign `negate()` error.
|
|
2973
|
+
aprjpoint(other);
|
|
2974
|
+
return this.add(other.negate());
|
|
2975
|
+
}
|
|
2976
|
+
is0() {
|
|
2977
|
+
return this.equals(Point.ZERO);
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Constant time multiplication.
|
|
2981
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
2982
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
2983
|
+
* Uses precomputes when available.
|
|
2984
|
+
* Uses endomorphism for Koblitz curves.
|
|
2985
|
+
* @param scalar - by which the point would be multiplied
|
|
2986
|
+
* @returns New point
|
|
2987
|
+
*/
|
|
2988
|
+
multiply(scalar) {
|
|
2989
|
+
const { endo } = extraOpts;
|
|
2990
|
+
// Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.
|
|
2991
|
+
// In key/signature-style callers, those values usually mean broken hash/scalar plumbing,
|
|
2992
|
+
// and failing closed is safer than silently producing the identity point.
|
|
2993
|
+
if (!Fn.isValidNot0(scalar))
|
|
2994
|
+
throw new RangeError('invalid scalar: out of range'); // 0 is invalid
|
|
2995
|
+
let point, fake; // Fake point is used to const-time mult
|
|
2996
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
2997
|
+
/** See docs for {@link EndomorphismOpts} */
|
|
2998
|
+
if (endo) {
|
|
2999
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
3000
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
3001
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
3002
|
+
fake = k1f.add(k2f);
|
|
3003
|
+
point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
|
|
3004
|
+
}
|
|
3005
|
+
else {
|
|
3006
|
+
const { p, f } = mul(scalar);
|
|
3007
|
+
point = p;
|
|
3008
|
+
fake = f;
|
|
3009
|
+
}
|
|
3010
|
+
// Normalize `z` for both points, but return only real one
|
|
3011
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
3012
|
+
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
3015
|
+
* It's faster, but should only be used when you don't care about
|
|
3016
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
3017
|
+
*/
|
|
3018
|
+
multiplyUnsafe(scalar) {
|
|
3019
|
+
const { endo } = extraOpts;
|
|
3020
|
+
const p = this;
|
|
3021
|
+
const sc = scalar;
|
|
3022
|
+
// Public-scalar callers may need 0, but n and larger values stay rejected here too.
|
|
3023
|
+
// Reducing them mod n would turn bad caller input into an accidental identity point.
|
|
3024
|
+
if (!Fn.isValid(sc))
|
|
3025
|
+
throw new RangeError('invalid scalar: out of range'); // 0 is valid
|
|
3026
|
+
if (sc === _0n || p.is0())
|
|
3027
|
+
return Point.ZERO; // 0
|
|
3028
|
+
if (sc === _1n)
|
|
3029
|
+
return p; // 1
|
|
3030
|
+
if (wnaf.hasCache(this))
|
|
3031
|
+
return this.multiply(sc); // precomputes
|
|
3032
|
+
// We don't have method for double scalar multiplication (aP + bQ):
|
|
3033
|
+
// Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.
|
|
3034
|
+
if (endo) {
|
|
3035
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
3036
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
|
|
3037
|
+
return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
|
|
3038
|
+
}
|
|
3039
|
+
else {
|
|
3040
|
+
return wnaf.unsafe(p, sc);
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
3045
|
+
* (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
3046
|
+
* @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
3047
|
+
*/
|
|
3048
|
+
toAffine(invertedZ) {
|
|
3049
|
+
const p = this;
|
|
3050
|
+
let iz = invertedZ;
|
|
3051
|
+
const { X, Y, Z } = p;
|
|
3052
|
+
// Fast-path for normalized points
|
|
3053
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
3054
|
+
return { x: X, y: Y };
|
|
3055
|
+
const is0 = p.is0();
|
|
3056
|
+
// If invZ was 0, we return zero point. However we still want to execute
|
|
3057
|
+
// all operations, so we replace invZ with a random number, 1.
|
|
3058
|
+
if (iz == null)
|
|
3059
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
3060
|
+
const x = Fp.mul(X, iz);
|
|
3061
|
+
const y = Fp.mul(Y, iz);
|
|
3062
|
+
const zz = Fp.mul(Z, iz);
|
|
3063
|
+
if (is0)
|
|
3064
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
3065
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
3066
|
+
throw new Error('invZ was invalid');
|
|
3067
|
+
return { x, y };
|
|
3068
|
+
}
|
|
3069
|
+
/**
|
|
3070
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
3071
|
+
* Always torsion-free for cofactor=1 curves.
|
|
3072
|
+
*/
|
|
3073
|
+
isTorsionFree() {
|
|
3074
|
+
const { isTorsionFree } = extraOpts;
|
|
3075
|
+
if (cofactor === _1n)
|
|
3076
|
+
return true;
|
|
3077
|
+
if (isTorsionFree)
|
|
3078
|
+
return isTorsionFree(Point, this);
|
|
3079
|
+
return wnaf.unsafe(this, CURVE_ORDER).is0();
|
|
3080
|
+
}
|
|
3081
|
+
clearCofactor() {
|
|
3082
|
+
const { clearCofactor } = extraOpts;
|
|
3083
|
+
if (cofactor === _1n)
|
|
3084
|
+
return this; // Fast-path
|
|
3085
|
+
if (clearCofactor)
|
|
3086
|
+
return clearCofactor(Point, this);
|
|
3087
|
+
// Default fallback assumes the cofactor fits the usual subgroup-scalar
|
|
3088
|
+
// multiplyUnsafe() contract. Curves with larger / structured cofactors
|
|
3089
|
+
// should define a clearCofactor override anyway (e.g. psi/Frobenius maps).
|
|
3090
|
+
return this.multiplyUnsafe(cofactor);
|
|
3091
|
+
}
|
|
3092
|
+
isSmallOrder() {
|
|
3093
|
+
if (cofactor === _1n)
|
|
3094
|
+
return this.is0(); // Fast-path
|
|
3095
|
+
return this.clearCofactor().is0();
|
|
3096
|
+
}
|
|
3097
|
+
toBytes(isCompressed = true) {
|
|
3098
|
+
abool(isCompressed, 'isCompressed');
|
|
3099
|
+
// Same policy as pointFromBytes(): keep ZERO out of the default byte surface because
|
|
3100
|
+
// callers use these encodings as public keys, where SEC 1 validation rejects infinity.
|
|
3101
|
+
this.assertValidity();
|
|
3102
|
+
return encodePoint(Point, this, isCompressed);
|
|
3103
|
+
}
|
|
3104
|
+
toHex(isCompressed = true) {
|
|
3105
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
3106
|
+
}
|
|
3107
|
+
toString() {
|
|
3108
|
+
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
const bits = Fn.BITS;
|
|
3112
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
3113
|
+
// Tiny toy curves can have scalar fields narrower than 8 bits. Skip the
|
|
3114
|
+
// eager W=8 cache there instead of rejecting an otherwise valid constructor.
|
|
3115
|
+
if (bits >= 8)
|
|
3116
|
+
Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
|
3117
|
+
Object.freeze(Point.prototype);
|
|
3118
|
+
Object.freeze(Point);
|
|
3119
|
+
return Point;
|
|
3120
|
+
}
|
|
3121
|
+
// Points start with byte 0x02 when y is even; otherwise 0x03
|
|
3122
|
+
function pprefix(hasEvenY) {
|
|
3123
|
+
return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
|
|
3124
|
+
}
|
|
3125
|
+
function getWLengths(Fp, Fn) {
|
|
3126
|
+
return {
|
|
3127
|
+
secretKey: Fn.BYTES,
|
|
3128
|
+
publicKey: 1 + Fp.BYTES,
|
|
3129
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
3130
|
+
publicKeyHasPrefix: true,
|
|
3131
|
+
// Raw compact `(r || s)` signature width; DER and recovered signatures use
|
|
3132
|
+
// different lengths outside this helper.
|
|
3133
|
+
signature: 2 * Fn.BYTES,
|
|
3134
|
+
};
|
|
3135
|
+
}
|
|
3136
|
+
/**
|
|
3137
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3138
|
+
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
|
|
3139
|
+
* @param Point - Weierstrass point constructor.
|
|
3140
|
+
* @param ecdhOpts - Optional randomness helpers:
|
|
3141
|
+
* - `randomBytes` (optional): Optional RNG override.
|
|
3142
|
+
* @returns ECDH helper namespace.
|
|
3143
|
+
* @example
|
|
3144
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3145
|
+
*
|
|
3146
|
+
* ```ts
|
|
3147
|
+
* import { ecdh } from '@noble/curves/abstract/weierstrass.js';
|
|
3148
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3149
|
+
* const dh = ecdh(p256.Point);
|
|
3150
|
+
* const alice = dh.keygen();
|
|
3151
|
+
* const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);
|
|
3152
|
+
* ```
|
|
3153
|
+
*/
|
|
3154
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
3155
|
+
const { Fn } = Point;
|
|
3156
|
+
const randomBytes_ = ecdhOpts.randomBytes === undefined ? randomBytes : ecdhOpts.randomBytes;
|
|
3157
|
+
// Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte
|
|
3158
|
+
// minimum even on toy curves.
|
|
3159
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
|
|
3160
|
+
seed: Math.max(getMinHashLength(Fn.ORDER), 16),
|
|
3161
|
+
});
|
|
3162
|
+
function isValidSecretKey(secretKey) {
|
|
3163
|
+
try {
|
|
3164
|
+
const num = Fn.fromBytes(secretKey);
|
|
3165
|
+
return Fn.isValidNot0(num);
|
|
3166
|
+
}
|
|
3167
|
+
catch (error) {
|
|
3168
|
+
return false;
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
3172
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
3173
|
+
try {
|
|
3174
|
+
const l = publicKey.length;
|
|
3175
|
+
if (isCompressed === true && l !== comp)
|
|
3176
|
+
return false;
|
|
3177
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
3178
|
+
return false;
|
|
3179
|
+
return !!Point.fromBytes(publicKey);
|
|
3180
|
+
}
|
|
3181
|
+
catch (error) {
|
|
3182
|
+
return false;
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Produces cryptographically secure secret key from random of size
|
|
3187
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
3188
|
+
*/
|
|
3189
|
+
function randomSecretKey(seed) {
|
|
3190
|
+
seed = seed === undefined ? randomBytes_(lengths.seed) : seed;
|
|
3191
|
+
return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
|
|
3192
|
+
}
|
|
3193
|
+
/**
|
|
3194
|
+
* Computes public key for a secret key. Checks for validity of the secret key.
|
|
3195
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3196
|
+
* @returns Public key, full when isCompressed=false; short when isCompressed=true
|
|
3197
|
+
*/
|
|
3198
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
3199
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
3200
|
+
}
|
|
3201
|
+
/**
|
|
3202
|
+
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
|
|
3203
|
+
*/
|
|
3204
|
+
function isProbPub(item) {
|
|
3205
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
3206
|
+
const allowedLengths = Fn._lengths;
|
|
3207
|
+
if (!isBytes(item))
|
|
3208
|
+
return undefined;
|
|
3209
|
+
const l = abytes(item, undefined, 'key').length;
|
|
3210
|
+
const isPub = l === publicKey || l === publicKeyUncompressed;
|
|
3211
|
+
const isSec = l === secretKey || !!allowedLengths?.includes(l);
|
|
3212
|
+
// P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.
|
|
3213
|
+
if (isPub && isSec)
|
|
3214
|
+
return undefined;
|
|
3215
|
+
return isPub;
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
3218
|
+
* ECDH (Elliptic Curve Diffie Hellman).
|
|
3219
|
+
* Computes encoded shared point from secret key A and public key B.
|
|
3220
|
+
* Checks: 1) secret key validity 2) shared key is on-curve.
|
|
3221
|
+
* Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.
|
|
3222
|
+
* Returns the encoded shared point on purpose: callers that need `x_P`
|
|
3223
|
+
* can derive it from the encoded point, but `x_P` alone cannot recover the
|
|
3224
|
+
* point/parity back.
|
|
3225
|
+
* This helper only exposes the fully validated public-key path, not cofactor DH.
|
|
3226
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3227
|
+
* @returns shared point encoding
|
|
3228
|
+
*/
|
|
3229
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
3230
|
+
if (isProbPub(secretKeyA) === true)
|
|
3231
|
+
throw new Error('first arg must be private key');
|
|
3232
|
+
if (isProbPub(publicKeyB) === false)
|
|
3233
|
+
throw new Error('second arg must be public key');
|
|
3234
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
3235
|
+
const b = Point.fromBytes(publicKeyB); // checks for being on-curve
|
|
3236
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
3237
|
+
}
|
|
3238
|
+
const utils = {
|
|
3239
|
+
isValidSecretKey,
|
|
3240
|
+
isValidPublicKey,
|
|
3241
|
+
randomSecretKey,
|
|
3242
|
+
};
|
|
3243
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey);
|
|
3244
|
+
Object.freeze(utils);
|
|
3245
|
+
Object.freeze(lengths);
|
|
3246
|
+
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
|
|
3250
|
+
*
|
|
3251
|
+
* @param Point - created using {@link weierstrass} function
|
|
3252
|
+
* @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)
|
|
3253
|
+
* @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:
|
|
3254
|
+
* - `lowS`: Default low-S policy.
|
|
3255
|
+
* - `hmac`: HMAC implementation used by RFC6979 DRBG.
|
|
3256
|
+
* - `randomBytes`: Optional RNG override.
|
|
3257
|
+
* - `bits2int`: Optional hash-to-int conversion override.
|
|
3258
|
+
* - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.
|
|
3259
|
+
*
|
|
3260
|
+
* @returns ECDSA helper namespace.
|
|
3261
|
+
* @example
|
|
3262
|
+
* Create an ECDSA signer/verifier bundle for one curve implementation.
|
|
3263
|
+
*
|
|
3264
|
+
* ```ts
|
|
3265
|
+
* import { ecdsa } from '@noble/curves/abstract/weierstrass.js';
|
|
3266
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3267
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
3268
|
+
* const p256ecdsa = ecdsa(p256.Point, sha256);
|
|
3269
|
+
* const { secretKey, publicKey } = p256ecdsa.keygen();
|
|
3270
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
3271
|
+
* const sig = p256ecdsa.sign(msg, secretKey);
|
|
3272
|
+
* const isValid = p256ecdsa.verify(sig, msg, publicKey);
|
|
3273
|
+
* ```
|
|
3274
|
+
*/
|
|
3275
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
3276
|
+
// Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.
|
|
3277
|
+
const hash_ = hash;
|
|
3278
|
+
ahash(hash_);
|
|
3279
|
+
validateObject(ecdsaOpts, {}, {
|
|
3280
|
+
hmac: 'function',
|
|
3281
|
+
lowS: 'boolean',
|
|
3282
|
+
randomBytes: 'function',
|
|
3283
|
+
bits2int: 'function',
|
|
3284
|
+
bits2int_modN: 'function',
|
|
3285
|
+
});
|
|
3286
|
+
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
3287
|
+
const randomBytes$1 = ecdsaOpts.randomBytes === undefined ? randomBytes : ecdsaOpts.randomBytes;
|
|
3288
|
+
const hmac$1 = ecdsaOpts.hmac === undefined
|
|
3289
|
+
? (key, msg) => hmac(hash_, key, msg)
|
|
3290
|
+
: ecdsaOpts.hmac;
|
|
3291
|
+
const { Fp, Fn } = Point;
|
|
3292
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
3293
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
3294
|
+
const defaultSigOpts = {
|
|
3295
|
+
prehash: true,
|
|
3296
|
+
lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,
|
|
3297
|
+
format: 'compact',
|
|
3298
|
+
extraEntropy: false,
|
|
3299
|
+
};
|
|
3300
|
+
// SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature
|
|
3301
|
+
// format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.
|
|
3302
|
+
// A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the
|
|
3303
|
+
// smallest such lift is 1 + 2n, not 2n.
|
|
3304
|
+
const hasLargeRecoveryLifts = CURVE_ORDER * _2n$1 + _1n < Fp.ORDER;
|
|
3305
|
+
function isBiggerThanHalfOrder(number) {
|
|
3306
|
+
const HALF = CURVE_ORDER >> _1n;
|
|
3307
|
+
return number > HALF;
|
|
3308
|
+
}
|
|
3309
|
+
function validateRS(title, num) {
|
|
3310
|
+
if (!Fn.isValidNot0(num))
|
|
3311
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
3312
|
+
return num;
|
|
3313
|
+
}
|
|
3314
|
+
function assertRecoverableCurve() {
|
|
3315
|
+
// ECDSA recovery only supports curves where the current recovery id can distinguish
|
|
3316
|
+
// q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.
|
|
3317
|
+
// SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.
|
|
3318
|
+
// The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.
|
|
3319
|
+
// To easily get i, we either need to:
|
|
3320
|
+
// a. increase amount of valid recid values (4, 5...); OR
|
|
3321
|
+
// b. prohibit recovered signatures for those curves.
|
|
3322
|
+
if (hasLargeRecoveryLifts)
|
|
3323
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
3324
|
+
}
|
|
3325
|
+
function validateSigLength(bytes, format) {
|
|
3326
|
+
validateSigFormat(format);
|
|
3327
|
+
const size = lengths.signature;
|
|
3328
|
+
const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
|
|
3329
|
+
return abytes(bytes, sizer);
|
|
3330
|
+
}
|
|
3331
|
+
/**
|
|
3332
|
+
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
|
|
3333
|
+
*/
|
|
3334
|
+
class Signature {
|
|
3335
|
+
r;
|
|
3336
|
+
s;
|
|
3337
|
+
recovery;
|
|
3338
|
+
constructor(r, s, recovery) {
|
|
3339
|
+
this.r = validateRS('r', r); // r in [1..N-1];
|
|
3340
|
+
this.s = validateRS('s', s); // s in [1..N-1];
|
|
3341
|
+
if (recovery != null) {
|
|
3342
|
+
assertRecoverableCurve();
|
|
3343
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
3344
|
+
throw new Error('invalid recovery id');
|
|
3345
|
+
this.recovery = recovery;
|
|
3346
|
+
}
|
|
3347
|
+
Object.freeze(this);
|
|
3348
|
+
}
|
|
3349
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
3350
|
+
validateSigLength(bytes, format);
|
|
3351
|
+
let recid;
|
|
3352
|
+
if (format === 'der') {
|
|
3353
|
+
const { r, s } = DER.toSig(abytes(bytes));
|
|
3354
|
+
return new Signature(r, s);
|
|
3355
|
+
}
|
|
3356
|
+
if (format === 'recovered') {
|
|
3357
|
+
recid = bytes[0];
|
|
3358
|
+
format = 'compact';
|
|
3359
|
+
bytes = bytes.subarray(1);
|
|
3360
|
+
}
|
|
3361
|
+
const L = lengths.signature / 2;
|
|
3362
|
+
const r = bytes.subarray(0, L);
|
|
3363
|
+
const s = bytes.subarray(L, L * 2);
|
|
3364
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
3365
|
+
}
|
|
3366
|
+
static fromHex(hex, format) {
|
|
3367
|
+
return this.fromBytes(hexToBytes(hex), format);
|
|
3368
|
+
}
|
|
3369
|
+
assertRecovery() {
|
|
3370
|
+
const { recovery } = this;
|
|
3371
|
+
if (recovery == null)
|
|
3372
|
+
throw new Error('invalid recovery id: must be present');
|
|
3373
|
+
return recovery;
|
|
3374
|
+
}
|
|
3375
|
+
addRecoveryBit(recovery) {
|
|
3376
|
+
return new Signature(this.r, this.s, recovery);
|
|
3377
|
+
}
|
|
3378
|
+
// Unlike the top-level helper below, this method expects a digest that has
|
|
3379
|
+
// already been hashed to the curve's message representative.
|
|
3380
|
+
recoverPublicKey(messageHash) {
|
|
3381
|
+
const { r, s } = this;
|
|
3382
|
+
const recovery = this.assertRecovery();
|
|
3383
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
|
|
3384
|
+
if (!Fp.isValid(radj))
|
|
3385
|
+
throw new Error('invalid recovery id: sig.r+curve.n != R.x');
|
|
3386
|
+
const x = Fp.toBytes(radj);
|
|
3387
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
3388
|
+
const ir = Fn.inv(radj); // r^-1
|
|
3389
|
+
const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash
|
|
3390
|
+
const u1 = Fn.create(-h * ir); // -hr^-1
|
|
3391
|
+
const u2 = Fn.create(s * ir); // sr^-1
|
|
3392
|
+
// (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
|
|
3393
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
3394
|
+
if (Q.is0())
|
|
3395
|
+
throw new Error('invalid recovery: point at infinify');
|
|
3396
|
+
Q.assertValidity();
|
|
3397
|
+
return Q;
|
|
3398
|
+
}
|
|
3399
|
+
// Signatures should be low-s, to prevent malleability.
|
|
3400
|
+
hasHighS() {
|
|
3401
|
+
return isBiggerThanHalfOrder(this.s);
|
|
3402
|
+
}
|
|
3403
|
+
toBytes(format = defaultSigOpts.format) {
|
|
3404
|
+
validateSigFormat(format);
|
|
3405
|
+
if (format === 'der')
|
|
3406
|
+
return hexToBytes(DER.hexFromSig(this));
|
|
3407
|
+
const { r, s } = this;
|
|
3408
|
+
const rb = Fn.toBytes(r);
|
|
3409
|
+
const sb = Fn.toBytes(s);
|
|
3410
|
+
if (format === 'recovered') {
|
|
3411
|
+
assertRecoverableCurve();
|
|
3412
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
3413
|
+
}
|
|
3414
|
+
return concatBytes(rb, sb);
|
|
3415
|
+
}
|
|
3416
|
+
toHex(format) {
|
|
3417
|
+
return bytesToHex(this.toBytes(format));
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
Object.freeze(Signature.prototype);
|
|
3421
|
+
Object.freeze(Signature);
|
|
3422
|
+
// RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
|
|
3423
|
+
// FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
|
|
3424
|
+
// bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
|
|
3425
|
+
// int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
|
|
3426
|
+
const bits2int = ecdsaOpts.bits2int === undefined
|
|
3427
|
+
? function bits2int_def(bytes) {
|
|
3428
|
+
// Our custom check "just in case", for protection against DoS
|
|
3429
|
+
if (bytes.length > 8192)
|
|
3430
|
+
throw new Error('input is too large');
|
|
3431
|
+
// For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
|
|
3432
|
+
// for some cases, since bytes.length * 8 is not actual bitLength.
|
|
3433
|
+
const num = bytesToNumberBE(bytes); // check for == u8 done here
|
|
3434
|
+
const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
|
|
3435
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
3436
|
+
}
|
|
3437
|
+
: ecdsaOpts.bits2int;
|
|
3438
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN === undefined
|
|
3439
|
+
? function bits2int_modN_def(bytes) {
|
|
3440
|
+
return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
|
|
3441
|
+
}
|
|
3442
|
+
: ecdsaOpts.bits2int_modN;
|
|
3443
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
3444
|
+
// Pads output with zero as per spec.
|
|
3445
|
+
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
|
|
3446
|
+
function int2octets(num) {
|
|
3447
|
+
aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
|
|
3448
|
+
return Fn.toBytes(num);
|
|
3449
|
+
}
|
|
3450
|
+
function validateMsgAndHash(message, prehash) {
|
|
3451
|
+
abytes(message, undefined, 'message');
|
|
3452
|
+
return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);
|
|
3453
|
+
}
|
|
3454
|
+
/**
|
|
3455
|
+
* Steps A, D of RFC6979 3.2.
|
|
3456
|
+
* Creates RFC6979 seed; converts msg/privKey to numbers.
|
|
3457
|
+
* Used only in sign, not in verify.
|
|
3458
|
+
*
|
|
3459
|
+
* Warning: we cannot assume here that message has same amount of bytes as curve order,
|
|
3460
|
+
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
|
|
3461
|
+
*/
|
|
3462
|
+
function prepSig(message, secretKey, opts) {
|
|
3463
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
3464
|
+
message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
|
|
3465
|
+
// We can't later call bits2octets, since nested bits2int is broken for curves
|
|
3466
|
+
// with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
|
|
3467
|
+
// const bits2octets = (bits) => int2octets(bits2int_modN(bits))
|
|
3468
|
+
const h1int = bits2int_modN(message);
|
|
3469
|
+
const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint
|
|
3470
|
+
if (!Fn.isValidNot0(d))
|
|
3471
|
+
throw new Error('invalid private key');
|
|
3472
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3473
|
+
// extraEntropy. RFC6979 3.6: additional k' (optional).
|
|
3474
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
3475
|
+
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
3476
|
+
// gen random bytes OR pass as-is
|
|
3477
|
+
const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
|
|
3478
|
+
seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes
|
|
3479
|
+
}
|
|
3480
|
+
const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
|
|
3481
|
+
const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!
|
|
3482
|
+
// Converts signature params into point w r/s, checks result for validity.
|
|
3483
|
+
// To transform k => Signature:
|
|
3484
|
+
// q = k⋅G
|
|
3485
|
+
// r = q.x mod n
|
|
3486
|
+
// s = k^-1(m + rd) mod n
|
|
3487
|
+
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
|
|
3488
|
+
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
|
|
3489
|
+
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
|
|
3490
|
+
function k2sig(kBytes) {
|
|
3491
|
+
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
|
|
3492
|
+
// Important: all mod() calls here must be done over N
|
|
3493
|
+
const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
|
|
3494
|
+
if (!Fn.isValidNot0(k))
|
|
3495
|
+
return; // Valid scalars (including k) must be in 1..N-1
|
|
3496
|
+
const ik = Fn.inv(k); // k^-1 mod n
|
|
3497
|
+
const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
|
|
3498
|
+
const r = Fn.create(q.x); // r = q.x mod n
|
|
3499
|
+
if (r === _0n)
|
|
3500
|
+
return;
|
|
3501
|
+
const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n
|
|
3502
|
+
if (s === _0n)
|
|
3503
|
+
return;
|
|
3504
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)
|
|
3505
|
+
let normS = s;
|
|
3506
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
3507
|
+
normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N
|
|
3508
|
+
recovery ^= 1;
|
|
3509
|
+
}
|
|
3510
|
+
return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);
|
|
3511
|
+
}
|
|
3512
|
+
return { seed, k2sig };
|
|
3513
|
+
}
|
|
3514
|
+
/**
|
|
3515
|
+
* Signs a message or message hash with a secret key.
|
|
3516
|
+
* With the default `prehash: true`, raw message bytes are hashed internally;
|
|
3517
|
+
* only `{ prehash: false }` expects a caller-supplied digest.
|
|
3518
|
+
*
|
|
3519
|
+
* ```
|
|
3520
|
+
* sign(m, d) where
|
|
3521
|
+
* k = rfc6979_hmac_drbg(m, d)
|
|
3522
|
+
* (x, y) = G × k
|
|
3523
|
+
* r = x mod n
|
|
3524
|
+
* s = (m + dr) / k mod n
|
|
3525
|
+
* ```
|
|
3526
|
+
*/
|
|
3527
|
+
function sign(message, secretKey, opts = {}) {
|
|
3528
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
|
|
3529
|
+
const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac$1);
|
|
3530
|
+
const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
|
|
3531
|
+
return sig.toBytes(opts.format);
|
|
3532
|
+
}
|
|
3533
|
+
/**
|
|
3534
|
+
* Verifies a signature against message and public key.
|
|
3535
|
+
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
|
|
3536
|
+
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
|
|
3537
|
+
*
|
|
3538
|
+
* ```
|
|
3539
|
+
* verify(r, s, h, P) where
|
|
3540
|
+
* u1 = hs^-1 mod n
|
|
3541
|
+
* u2 = rs^-1 mod n
|
|
3542
|
+
* R = u1⋅G + u2⋅P
|
|
3543
|
+
* mod(R.x, n) == r
|
|
3544
|
+
* ```
|
|
3545
|
+
*/
|
|
3546
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
3547
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
3548
|
+
publicKey = abytes(publicKey, undefined, 'publicKey');
|
|
3549
|
+
message = validateMsgAndHash(message, prehash);
|
|
3550
|
+
if (!isBytes(signature)) {
|
|
3551
|
+
const end = signature instanceof Signature ? ', use sig.toBytes()' : '';
|
|
3552
|
+
throw new Error('verify expects Uint8Array signature' + end);
|
|
3553
|
+
}
|
|
3554
|
+
validateSigLength(signature, format); // execute this twice because we want loud error
|
|
3555
|
+
try {
|
|
3556
|
+
const sig = Signature.fromBytes(signature, format);
|
|
3557
|
+
const P = Point.fromBytes(publicKey);
|
|
3558
|
+
if (lowS && sig.hasHighS())
|
|
3559
|
+
return false;
|
|
3560
|
+
const { r, s } = sig;
|
|
3561
|
+
const h = bits2int_modN(message); // mod n, not mod p
|
|
3562
|
+
const is = Fn.inv(s); // s^-1 mod n
|
|
3563
|
+
const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
|
|
3564
|
+
const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
|
|
3565
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
|
|
3566
|
+
if (R.is0())
|
|
3567
|
+
return false;
|
|
3568
|
+
const v = Fn.create(R.x); // v = r.x mod n
|
|
3569
|
+
return v === r;
|
|
3570
|
+
}
|
|
3571
|
+
catch (e) {
|
|
3572
|
+
return false;
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
3576
|
+
// Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message
|
|
3577
|
+
// bytes first unless the caller passes `{ prehash: false }`.
|
|
3578
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
3579
|
+
message = validateMsgAndHash(message, prehash);
|
|
3580
|
+
return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
|
|
3581
|
+
}
|
|
3582
|
+
return Object.freeze({
|
|
3583
|
+
keygen,
|
|
3584
|
+
getPublicKey,
|
|
3585
|
+
getSharedSecret,
|
|
3586
|
+
utils,
|
|
3587
|
+
lengths,
|
|
3588
|
+
Point,
|
|
3589
|
+
sign,
|
|
3590
|
+
verify,
|
|
3591
|
+
recoverPublicKey,
|
|
3592
|
+
Signature,
|
|
3593
|
+
hash: hash_,
|
|
3594
|
+
});
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
/**
|
|
3598
|
+
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
|
|
3599
|
+
*
|
|
3600
|
+
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
|
|
3601
|
+
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
|
|
3602
|
+
* @module
|
|
3603
|
+
*/
|
|
3604
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3605
|
+
// Seems like generator was produced from some seed:
|
|
3606
|
+
// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`
|
|
3607
|
+
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
|
|
3608
|
+
const secp256k1_CURVE = {
|
|
3609
|
+
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
|
|
3610
|
+
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
|
|
3611
|
+
h: BigInt(1),
|
|
3612
|
+
a: BigInt(0),
|
|
3613
|
+
b: BigInt(7),
|
|
3614
|
+
Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
|
|
3615
|
+
Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
|
|
3616
|
+
};
|
|
3617
|
+
const secp256k1_ENDO = {
|
|
3618
|
+
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
|
|
3619
|
+
basises: [
|
|
3620
|
+
[BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
|
|
3621
|
+
[BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
|
|
3622
|
+
],
|
|
3623
|
+
};
|
|
3624
|
+
const _2n = /* @__PURE__ */ BigInt(2);
|
|
3625
|
+
/**
|
|
3626
|
+
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
|
|
3627
|
+
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
|
|
3628
|
+
*/
|
|
3629
|
+
function sqrtMod(y) {
|
|
3630
|
+
const P = secp256k1_CURVE.p;
|
|
3631
|
+
// prettier-ignore
|
|
3632
|
+
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
3633
|
+
// prettier-ignore
|
|
3634
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
3635
|
+
const b2 = (y * y * y) % P; // x^3, 11
|
|
3636
|
+
const b3 = (b2 * b2 * y) % P; // x^7
|
|
3637
|
+
const b6 = (pow2(b3, _3n, P) * b3) % P;
|
|
3638
|
+
const b9 = (pow2(b6, _3n, P) * b3) % P;
|
|
3639
|
+
const b11 = (pow2(b9, _2n, P) * b2) % P;
|
|
3640
|
+
const b22 = (pow2(b11, _11n, P) * b11) % P;
|
|
3641
|
+
const b44 = (pow2(b22, _22n, P) * b22) % P;
|
|
3642
|
+
const b88 = (pow2(b44, _44n, P) * b44) % P;
|
|
3643
|
+
const b176 = (pow2(b88, _88n, P) * b88) % P;
|
|
3644
|
+
const b220 = (pow2(b176, _44n, P) * b44) % P;
|
|
3645
|
+
const b223 = (pow2(b220, _3n, P) * b3) % P;
|
|
3646
|
+
const t1 = (pow2(b223, _23n, P) * b22) % P;
|
|
3647
|
+
const t2 = (pow2(t1, _6n, P) * b2) % P;
|
|
3648
|
+
const root = pow2(t2, _2n, P);
|
|
3649
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
3650
|
+
throw new Error('Cannot find square root');
|
|
3651
|
+
return root;
|
|
3652
|
+
}
|
|
3653
|
+
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
3654
|
+
const Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
3655
|
+
Fp: Fpk1,
|
|
3656
|
+
endo: secp256k1_ENDO,
|
|
3657
|
+
});
|
|
3658
|
+
/**
|
|
3659
|
+
* secp256k1 curve: ECDSA and ECDH methods.
|
|
3660
|
+
*
|
|
3661
|
+
* Uses sha256 to hash messages. To use a different hash,
|
|
3662
|
+
* pass `{ prehash: false }` to sign / verify.
|
|
3663
|
+
*
|
|
3664
|
+
* @example
|
|
3665
|
+
* Generate one secp256k1 keypair, sign a message, and verify it.
|
|
3666
|
+
*
|
|
3667
|
+
* ```js
|
|
3668
|
+
* import { secp256k1 } from '@noble/curves/secp256k1.js';
|
|
3669
|
+
* const { secretKey, publicKey } = secp256k1.keygen();
|
|
3670
|
+
* // const publicKey = secp256k1.getPublicKey(secretKey);
|
|
3671
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
3672
|
+
* const sig = secp256k1.sign(msg, secretKey);
|
|
3673
|
+
* const isValid = secp256k1.verify(sig, msg, publicKey);
|
|
3674
|
+
* // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });
|
|
3675
|
+
* ```
|
|
3676
|
+
*/
|
|
3677
|
+
const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
|
|
3678
|
+
|
|
3679
|
+
function canonicalize (object, seen = new Set()) {
|
|
3680
|
+
if (typeof object === 'number' && isNaN(object)) {
|
|
3681
|
+
throw new Error('NaN is not allowed');
|
|
3682
|
+
}
|
|
3683
|
+
|
|
3684
|
+
if (typeof object === 'number' && !isFinite(object)) {
|
|
3685
|
+
throw new Error('Infinity is not allowed');
|
|
3686
|
+
}
|
|
3687
|
+
|
|
3688
|
+
if (object === null || typeof object !== 'object') {
|
|
3689
|
+
return JSON.stringify(object);
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3692
|
+
if (typeof object.toJSON === 'function') {
|
|
3693
|
+
if (seen.has(object)) {
|
|
3694
|
+
throw new Error('Circular reference detected');
|
|
3695
|
+
}
|
|
3696
|
+
seen.add(object);
|
|
3697
|
+
const result = canonicalize(object.toJSON(), seen);
|
|
3698
|
+
seen.delete(object);
|
|
3699
|
+
return result;
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
if (seen.has(object)) {
|
|
3703
|
+
throw new Error('Circular reference detected');
|
|
3704
|
+
}
|
|
3705
|
+
seen.add(object);
|
|
3706
|
+
|
|
3707
|
+
let result;
|
|
3708
|
+
if (Array.isArray(object)) {
|
|
3709
|
+
const values = object.map((cv) => {
|
|
3710
|
+
const value = cv === undefined || typeof cv === 'symbol' ? null : cv;
|
|
3711
|
+
return canonicalize(value, seen);
|
|
3712
|
+
});
|
|
3713
|
+
result = `[${values.join(',')}]`;
|
|
3714
|
+
} else {
|
|
3715
|
+
const parts = [];
|
|
3716
|
+
for (const key of Object.keys(object).sort()) {
|
|
3717
|
+
if (object[key] === undefined || typeof object[key] === 'symbol') {
|
|
3718
|
+
continue;
|
|
3719
|
+
}
|
|
3720
|
+
parts.push(`${canonicalize(key)}:${canonicalize(object[key], seen)}`);
|
|
3721
|
+
}
|
|
3722
|
+
result = `{${parts.join(',')}}`;
|
|
3723
|
+
}
|
|
3724
|
+
|
|
3725
|
+
seen.delete(object);
|
|
3726
|
+
return result;
|
|
3727
|
+
}
|
|
3728
|
+
|
|
3729
|
+
/**
|
|
3730
|
+
* Operator-signed trust-manifest distribution.
|
|
3731
|
+
*
|
|
3732
|
+
* The SDK's attestation check (see `TrustAnchor`) needs a trusted source
|
|
3733
|
+
* for the expected cluster identity — the set of node peer IDs and the
|
|
3734
|
+
* allow-listed RTMR1/RTMR3 image measurements (RTMR1 is the real rootfs
|
|
3735
|
+
* signal, RTMR3 is kept for backward compatibility — see `TrustAnchor`'s
|
|
3736
|
+
* own doc comment). Without a trusted source, every
|
|
3737
|
+
* caller has to hand-pin those values or fall back to
|
|
3738
|
+
* `{ unsafe_trust_server: true }`, which disables verification entirely.
|
|
3739
|
+
*
|
|
3740
|
+
* A trust manifest is a small JSON document published by the cluster
|
|
3741
|
+
* operator to a public URL (a GCS bucket) and signed with the operator's
|
|
3742
|
+
* secp256k1 key. Its public half is baked into the SDK per environment
|
|
3743
|
+
* (`OPERATOR_PUBLIC_KEYS`). `fetchTrustedManifest(env)` fetches the
|
|
3744
|
+
* manifest, verifies the signature against the pinned operator key, and
|
|
3745
|
+
* returns a {@link TrustAnchor} that plugs straight into
|
|
3746
|
+
* `T3nClientConfig.trustAnchor`.
|
|
3747
|
+
*
|
|
3748
|
+
* Trust model: the operator key is the root of trust. A network attacker
|
|
3749
|
+
* can serve any bytes at the manifest URL, but cannot forge a signature
|
|
3750
|
+
* for a manifest naming their own node identities/measurements without
|
|
3751
|
+
* the operator's private key. The manifest only ever *narrows* trust to
|
|
3752
|
+
* the real cluster — it never widens what the on-quote RTMR1/RTMR3
|
|
3753
|
+
* pinning and peer-id set-equality already enforce inside the WASM
|
|
3754
|
+
* verifier.
|
|
3755
|
+
*/
|
|
3756
|
+
/**
|
|
3757
|
+
* Deterministic bytes the operator signs and the client verifies: the
|
|
3758
|
+
* SHA-256 of the RFC 8785 (JCS) canonical JSON of the payload. Sharing
|
|
3759
|
+
* this one helper between the signer and the verifier is what guarantees
|
|
3760
|
+
* both sides hash identical bytes regardless of key ordering or
|
|
3761
|
+
* whitespace.
|
|
3762
|
+
*/
|
|
3763
|
+
function canonicalManifestBytes(payload) {
|
|
3764
|
+
const canonical = canonicalize(payload);
|
|
3765
|
+
if (typeof canonical !== "string") {
|
|
3766
|
+
throw new Error("trust manifest payload is not canonicalizable JSON");
|
|
3767
|
+
}
|
|
3768
|
+
return sha256(new TextEncoder().encode(canonical));
|
|
3769
|
+
}
|
|
3770
|
+
|
|
3771
|
+
/**
|
|
3772
|
+
* Sign a trust manifest with the operator's secp256k1 private key.
|
|
3773
|
+
*
|
|
3774
|
+
* Emits the full signed manifest JSON to stdout. Used by the post-deploy
|
|
3775
|
+
* CI job that publishes the manifest to GCS, reproducible by hand for
|
|
3776
|
+
* local verification, and (MAT-2198) bundled by the SDK's own build into
|
|
3777
|
+
* a standalone `dist/scripts/sign-trust-manifest.mjs` — a dependency-free
|
|
3778
|
+
* ESM file shipped in the AWS release tarball as `bin/sign-trust-manifest.mjs`,
|
|
3779
|
+
* runnable with plain `node` and no repo checkout / pnpm install, for
|
|
3780
|
+
* clients who only ever have the downloaded release, not the source tree.
|
|
3781
|
+
*
|
|
3782
|
+
* It signs the SAME bytes the SDK verifies — it imports
|
|
3783
|
+
* `canonicalManifestBytes` from the SDK source, so the signer and the
|
|
3784
|
+
* `fetchTrustedManifest` verifier can never drift.
|
|
3785
|
+
*
|
|
3786
|
+
* Usage (TDX):
|
|
3787
|
+
* MANIFEST_OPERATOR_SIGNING_KEY=<hex-32-byte-privkey> \
|
|
3788
|
+
* tsx scripts/sign-trust-manifest.ts \
|
|
3789
|
+
* --cluster staging \
|
|
3790
|
+
* --version 1 \
|
|
3791
|
+
* --peer-ids '["12D3KooW...","12D3KooW...","12D3KooW..."]' \
|
|
3792
|
+
* --rtmr3 '["<base64-48-bytes>","<base64-48-bytes>"]' \
|
|
3793
|
+
* --rtmr1 '["<base64-48-bytes>","<base64-48-bytes>"]' \
|
|
3794
|
+
* --signed-at 2026-07-20T00:00:00Z
|
|
3795
|
+
*
|
|
3796
|
+
* Usage (all-SEV-SNP, e.g. an AWS-only fleet — MAT-2198):
|
|
3797
|
+
* MANIFEST_OPERATOR_SIGNING_KEY=<hex-32-byte-privkey> \
|
|
3798
|
+
* tsx scripts/sign-trust-manifest.ts \
|
|
3799
|
+
* --cluster my-aws-cluster \
|
|
3800
|
+
* --version 1 \
|
|
3801
|
+
* --peer-ids '["12D3KooW...","12D3KooW...","12D3KooW..."]' \
|
|
3802
|
+
* --sev-snp-measurements '["<base64-48-bytes>"]' \
|
|
3803
|
+
* --sev-snp-product Milan \
|
|
3804
|
+
* --signed-at 2026-07-20T00:00:00Z
|
|
3805
|
+
*
|
|
3806
|
+
* --rtmr3/--rtmr1 and --sev-snp-measurements/--sev-snp-product are each
|
|
3807
|
+
* optional, but at least one vendor's pair must be non-empty — an anchor
|
|
3808
|
+
* with nothing in either allow-list would trust any node. --rtmr3/--rtmr1
|
|
3809
|
+
* describe the same TDX fleet and must be omitted/empty together, never
|
|
3810
|
+
* just one. --sev-snp-product is required only when --sev-snp-measurements
|
|
3811
|
+
* is non-empty.
|
|
3812
|
+
*
|
|
3813
|
+
* The private key is read only from the MANIFEST_OPERATOR_SIGNING_KEY
|
|
3814
|
+
* environment variable (never a CLI arg, so it does not land in process
|
|
3815
|
+
* listings / CI logs).
|
|
3816
|
+
*/
|
|
3817
|
+
function arg(name) {
|
|
3818
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
3819
|
+
if (i < 0)
|
|
3820
|
+
return undefined;
|
|
3821
|
+
// A flag with no following value (e.g. --sev-snp-measurements as the
|
|
3822
|
+
// final argv token) is a malformed invocation, not "flag omitted" -
|
|
3823
|
+
// process.argv[i + 1] would otherwise silently return undefined for
|
|
3824
|
+
// both cases, and a caller like the optional --sev-snp-measurements
|
|
3825
|
+
// parsing would convert that into an empty allow-list and sign an
|
|
3826
|
+
// all-TDX manifest instead of failing loudly.
|
|
3827
|
+
if (i + 1 >= process.argv.length) {
|
|
3828
|
+
throw new Error(`--${name} was given but no value followed it`);
|
|
3829
|
+
}
|
|
3830
|
+
return process.argv[i + 1];
|
|
3831
|
+
}
|
|
3832
|
+
function requireArg(name) {
|
|
3833
|
+
const v = arg(name);
|
|
3834
|
+
if (v === undefined) {
|
|
3835
|
+
throw new Error(`missing required --${name}`);
|
|
3836
|
+
}
|
|
3837
|
+
return v;
|
|
3838
|
+
}
|
|
3839
|
+
function parseJsonStringArray(name, raw) {
|
|
3840
|
+
const parsed = JSON.parse(raw);
|
|
3841
|
+
if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === "string")) {
|
|
3842
|
+
throw new Error(`--${name} must be a JSON array of strings`);
|
|
3843
|
+
}
|
|
3844
|
+
return parsed;
|
|
3845
|
+
}
|
|
3846
|
+
function main() {
|
|
3847
|
+
const privHex = process.env.MANIFEST_OPERATOR_SIGNING_KEY;
|
|
3848
|
+
if (!privHex) {
|
|
3849
|
+
throw new Error("MANIFEST_OPERATOR_SIGNING_KEY (hex secp256k1 private key) is required");
|
|
3850
|
+
}
|
|
3851
|
+
const peerIds = parseJsonStringArray("peer-ids", requireArg("peer-ids"));
|
|
3852
|
+
if (peerIds.length === 0) {
|
|
3853
|
+
throw new Error("peer-ids must be non-empty");
|
|
3854
|
+
}
|
|
3855
|
+
// --rtmr3/--rtmr1 are optional, like --sev-snp-measurements: an
|
|
3856
|
+
// all-SEV-SNP fleet (the normal shape for an AWS-only deployment,
|
|
3857
|
+
// MAT-2198) has no TDX measurements at all. They still describe the
|
|
3858
|
+
// same TDX fleet together, though, so one present without the other
|
|
3859
|
+
// is a real usage error, not a valid partial state.
|
|
3860
|
+
const rtmr3Raw = arg("rtmr3");
|
|
3861
|
+
const rtmr3 = rtmr3Raw === undefined ? [] : parseJsonStringArray("rtmr3", rtmr3Raw);
|
|
3862
|
+
const rtmr1Raw = arg("rtmr1");
|
|
3863
|
+
const rtmr1 = rtmr1Raw === undefined ? [] : parseJsonStringArray("rtmr1", rtmr1Raw);
|
|
3864
|
+
if ((rtmr3.length === 0) !== (rtmr1.length === 0)) {
|
|
3865
|
+
throw new Error("--rtmr3 and --rtmr1 must both be omitted/empty or both be non-empty " +
|
|
3866
|
+
"(they describe the same TDX fleet)");
|
|
3867
|
+
}
|
|
3868
|
+
const sevSnpMeasurementsRaw = arg("sev-snp-measurements");
|
|
3869
|
+
const sevSnpMeasurements = sevSnpMeasurementsRaw === undefined
|
|
3870
|
+
? []
|
|
3871
|
+
: parseJsonStringArray("sev-snp-measurements", sevSnpMeasurementsRaw);
|
|
3872
|
+
const sevSnpProduct = arg("sev-snp-product");
|
|
3873
|
+
if (sevSnpMeasurements.length > 0 && sevSnpProduct === undefined) {
|
|
3874
|
+
throw new Error("--sev-snp-product is required when --sev-snp-measurements is non-empty");
|
|
3875
|
+
}
|
|
3876
|
+
if (rtmr3.length === 0 && sevSnpMeasurements.length === 0) {
|
|
3877
|
+
throw new Error("at least one of --rtmr3/--rtmr1 (TDX) or --sev-snp-measurements " +
|
|
3878
|
+
"(SEV-SNP) must be non-empty — an empty anchor would trust any node");
|
|
3879
|
+
}
|
|
3880
|
+
const payload = {
|
|
3881
|
+
cluster: requireArg("cluster"),
|
|
3882
|
+
version: Number(requireArg("version")),
|
|
3883
|
+
peer_ids: peerIds,
|
|
3884
|
+
rtmr3_allowlist: rtmr3,
|
|
3885
|
+
rtmr1_allowlist: rtmr1,
|
|
3886
|
+
...(sevSnpMeasurements.length > 0
|
|
3887
|
+
? { sev_snp_measurement_allowlist: sevSnpMeasurements }
|
|
3888
|
+
: {}),
|
|
3889
|
+
...(sevSnpProduct === undefined ? {} : { sev_snp_product: sevSnpProduct }),
|
|
3890
|
+
signed_at: requireArg("signed-at"),
|
|
3891
|
+
};
|
|
3892
|
+
if (!Number.isInteger(payload.version) || payload.version < 1) {
|
|
3893
|
+
throw new Error("--version must be a positive integer");
|
|
3894
|
+
}
|
|
3895
|
+
const digest = canonicalManifestBytes(payload);
|
|
3896
|
+
const signature = secp256k1.sign(digest, hexToBytes$1(privHex.replace(/^0x/, "")));
|
|
3897
|
+
const manifest = {
|
|
3898
|
+
...payload,
|
|
3899
|
+
signature: bytesToHex$1(signature),
|
|
3900
|
+
};
|
|
3901
|
+
process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
|
|
3902
|
+
}
|
|
3903
|
+
main();
|