@happyvertical/smrt-profiles 0.51.13 → 0.51.15
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/chunks/{ApiKey-DIqCzx-g.js → ApiKey-BZmbOTnL.js} +3 -3
- package/dist/chunks/{ApiKey-DIqCzx-g.js.map → ApiKey-BZmbOTnL.js.map} +1 -1
- package/dist/chunks/{ApiKeyCollection-CNFptBxU.js → ApiKeyCollection-Bfb_nw81.js} +3 -3
- package/dist/chunks/{ApiKeyCollection-CNFptBxU.js.map → ApiKeyCollection-Bfb_nw81.js.map} +1 -1
- package/dist/chunks/{AuditLogCollection-DxR3ZG6_.js → AuditLogCollection-B1YonCAP.js} +2 -2
- package/dist/chunks/{AuditLogCollection-DxR3ZG6_.js.map → AuditLogCollection-B1YonCAP.js.map} +1 -1
- package/dist/chunks/NostrIdentity-n70E0vck.js +4279 -0
- package/dist/chunks/NostrIdentity-n70E0vck.js.map +1 -0
- package/dist/chunks/{NostrIdentityCollection-BXtvB0Sd.js → NostrIdentityCollection-Ca74dkaL.js} +2 -2
- package/dist/chunks/{NostrIdentityCollection-BXtvB0Sd.js.map → NostrIdentityCollection-Ca74dkaL.js.map} +1 -1
- package/dist/chunks/{OidcIdentity-DISriiph.js → OidcIdentity-CChQnYNH.js} +3 -3
- package/dist/chunks/{OidcIdentity-DISriiph.js.map → OidcIdentity-CChQnYNH.js.map} +1 -1
- package/dist/chunks/{OidcIdentityCollection-B6im_oL_.js → OidcIdentityCollection-D3L0WYbM.js} +3 -3
- package/dist/chunks/{OidcIdentityCollection-B6im_oL_.js.map → OidcIdentityCollection-D3L0WYbM.js.map} +1 -1
- package/dist/chunks/{ProfileAssetCollection-CuwaiTOk.js → ProfileAssetCollection-V8u4wqSL.js} +3 -3
- package/dist/chunks/{ProfileAssetCollection-CuwaiTOk.js.map → ProfileAssetCollection-V8u4wqSL.js.map} +1 -1
- package/dist/chunks/{ProfileCollection-BAC5weFA.js → ProfileCollection-BvhD2cfL.js} +24 -24
- package/dist/chunks/{ProfileCollection-BAC5weFA.js.map → ProfileCollection-BvhD2cfL.js.map} +1 -1
- package/dist/chunks/{ProfileMetadataCollection-DyVxb-Tn.js → ProfileMetadataCollection-DxX_BJKV.js} +2 -2
- package/dist/chunks/{ProfileMetadataCollection-DyVxb-Tn.js.map → ProfileMetadataCollection-DxX_BJKV.js.map} +1 -1
- package/dist/chunks/{ProfileMetafieldCollection-KSYFXBxU.js → ProfileMetafieldCollection-CMKhVi2I.js} +2 -2
- package/dist/chunks/{ProfileMetafieldCollection-KSYFXBxU.js.map → ProfileMetafieldCollection-CMKhVi2I.js.map} +1 -1
- package/dist/chunks/{ProfileRelationshipCollection-DigPX3kC.js → ProfileRelationshipCollection-DUVgaIqf.js} +5 -5
- package/dist/chunks/{ProfileRelationshipCollection-DigPX3kC.js.map → ProfileRelationshipCollection-DUVgaIqf.js.map} +1 -1
- package/dist/chunks/{ProfileRelationshipTermCollection-UkhmGHcr.js → ProfileRelationshipTermCollection-DtA9OM23.js} +2 -2
- package/dist/chunks/{ProfileRelationshipTermCollection-UkhmGHcr.js.map → ProfileRelationshipTermCollection-DtA9OM23.js.map} +1 -1
- package/dist/chunks/{ProfileRelationshipType-D1WLqC2B.js → ProfileRelationshipType-BRiRka6t.js} +2 -2
- package/dist/chunks/{ProfileRelationshipType-D1WLqC2B.js.map → ProfileRelationshipType-BRiRka6t.js.map} +1 -1
- package/dist/chunks/{ProfileRelationshipTypeCollection-BapU-NS3.js → ProfileRelationshipTypeCollection-BdXwd7Kf.js} +3 -3
- package/dist/chunks/{ProfileRelationshipTypeCollection-BapU-NS3.js.map → ProfileRelationshipTypeCollection-BdXwd7Kf.js.map} +1 -1
- package/dist/chunks/{oidcProvisioningPrimitives-BPWWsNb7.js → oidcProvisioningPrimitives-CjOkg3Zd.js} +4 -4
- package/dist/chunks/{oidcProvisioningPrimitives-BPWWsNb7.js.map → oidcProvisioningPrimitives-CjOkg3Zd.js.map} +1 -1
- package/dist/chunks/{resolveIdentity-QEWj65PQ.js → resolveIdentity-73HQnTlT.js} +16 -16
- package/dist/chunks/{resolveIdentity-QEWj65PQ.js.map → resolveIdentity-73HQnTlT.js.map} +1 -1
- package/dist/index.d.ts +27 -0
- package/dist/index.js +22 -22
- package/dist/internal/oidc-provisioning.d.ts +119 -14
- package/dist/internal/oidc-provisioning.js +2 -2
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +6 -6
- package/dist/types.d.ts +27 -0
- package/dist/utils.d.ts +27 -0
- package/dist/utils.js +4 -4
- package/package.json +10 -10
- package/dist/chunks/NostrIdentity-CbnAJgg9.js +0 -3155
- package/dist/chunks/NostrIdentity-CbnAJgg9.js.map +0 -1
- package/dist/oidc-provisioning.d.ts +0 -95
|
@@ -0,0 +1,4279 @@
|
|
|
1
|
+
import { SmrtObject, field, foreignKey, smrt } from "@happyvertical/smrt-core";
|
|
2
|
+
import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
|
|
3
|
+
//#region \0rolldown/runtime.js
|
|
4
|
+
var __defProp$1 = Object.defineProperty;
|
|
5
|
+
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
6
|
+
var __exportAll = (all, no_symbols) => {
|
|
7
|
+
let target = {};
|
|
8
|
+
for (var name in all) __defProp$1(target, name, {
|
|
9
|
+
get: all[name],
|
|
10
|
+
enumerable: true
|
|
11
|
+
});
|
|
12
|
+
if (!no_symbols) __defProp$1(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
+
return target;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
|
|
17
|
+
var fromNumH = (n) => n / 2 ** 32 | 0;
|
|
18
|
+
var fromNumL = (n) => n >>> 0;
|
|
19
|
+
function setU64FromNum(view, byteOffset, n, isLE) {
|
|
20
|
+
const h = fromNumH(n);
|
|
21
|
+
const l = fromNumL(n);
|
|
22
|
+
view.setUint32(byteOffset, isLE ? l : h, isLE);
|
|
23
|
+
view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
|
|
27
|
+
/**
|
|
28
|
+
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
29
|
+
* @param a - value to test
|
|
30
|
+
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
31
|
+
* @example
|
|
32
|
+
* Check whether a value is a Uint8Array-compatible view.
|
|
33
|
+
* ```ts
|
|
34
|
+
* isBytes(new Uint8Array([1, 2, 3]));
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
function isBytes$1(a) {
|
|
38
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
|
39
|
+
}
|
|
40
|
+
var atitle$1 = (title) => title ? `"${title}" ` : "";
|
|
41
|
+
/**
|
|
42
|
+
* Asserts something is a non-negative integer.
|
|
43
|
+
* @param n - number to validate
|
|
44
|
+
* @param title - label included in thrown errors
|
|
45
|
+
* @returns The validated number.
|
|
46
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
47
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
48
|
+
* @example
|
|
49
|
+
* Validate a non-negative integer option.
|
|
50
|
+
* ```ts
|
|
51
|
+
* anumber(32, 'length');
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
function anumber$1(n, title = "") {
|
|
55
|
+
if (typeof n !== "number") throw new TypeError(atitle$1(title) + "expected number, got " + typeof n);
|
|
56
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle$1(title) + "expected integer >= 0, got " + n);
|
|
57
|
+
return n;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Asserts something is Uint8Array.
|
|
61
|
+
* @param value - value to validate
|
|
62
|
+
* @param length - optional exact length constraint
|
|
63
|
+
* @param title - label included in thrown errors
|
|
64
|
+
* @returns The validated byte array.
|
|
65
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
66
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
67
|
+
* @example
|
|
68
|
+
* Validate that a value is a byte array.
|
|
69
|
+
* ```ts
|
|
70
|
+
* abytes(new Uint8Array([1, 2, 3]));
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
function abytes$1(value, length, title = "") {
|
|
74
|
+
if (isBytes$1(value) && (length === void 0 || value.length === length)) return value;
|
|
75
|
+
if (length !== void 0) anumber$1(length, "length");
|
|
76
|
+
const bytes = isBytes$1(value);
|
|
77
|
+
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
|
78
|
+
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
79
|
+
const message = atitle$1(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
|
80
|
+
if (!bytes) throw new TypeError(message);
|
|
81
|
+
throw new RangeError(message);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Asserts something is a wrapped hash constructor.
|
|
85
|
+
* @param h - hash constructor to validate
|
|
86
|
+
* @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
|
|
87
|
+
* @throws On invalid hash metadata ranges or values. {@link RangeError}
|
|
88
|
+
* @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
|
|
89
|
+
* @example
|
|
90
|
+
* Validate a callable hash wrapper.
|
|
91
|
+
* ```ts
|
|
92
|
+
* import { ahash } from '@noble/hashes/utils.js';
|
|
93
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
94
|
+
* ahash(sha256);
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
function ahash(h) {
|
|
98
|
+
if (typeof h !== "function" || typeof h.create !== "function") throw new TypeError("expected hash wrapped by utils.createHasher");
|
|
99
|
+
anumber$1(h.outputLen);
|
|
100
|
+
anumber$1(h.blockLen);
|
|
101
|
+
if (h.outputLen < 1 || h.blockLen < 1) throw new Error("hash blockLen / outputLen must be >= 1");
|
|
102
|
+
}
|
|
103
|
+
var aobject$1 = (value, label) => {
|
|
104
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
|
|
105
|
+
};
|
|
106
|
+
var aopts = (value, label) => {
|
|
107
|
+
aobject$1(value, label);
|
|
108
|
+
const proto = Object.getPrototypeOf(value);
|
|
109
|
+
if (proto !== Object.prototype && proto !== null) throw new TypeError(`"${label}" expected plain object`);
|
|
110
|
+
if (Object.hasOwn(value, "__proto__")) throw new TypeError(`"${label}.__proto__" is not allowed`);
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Asserts a hash instance has not been destroyed or finished.
|
|
114
|
+
* @param instance - hash instance to validate
|
|
115
|
+
* @param checkFinished - whether to reject finalized instances
|
|
116
|
+
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
117
|
+
* @example
|
|
118
|
+
* Validate that a hash instance is still usable.
|
|
119
|
+
* ```ts
|
|
120
|
+
* import { aexists } from '@noble/hashes/utils.js';
|
|
121
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
122
|
+
* const hash = sha256.create();
|
|
123
|
+
* aexists(hash);
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
function aexists(instance, checkFinished = true) {
|
|
127
|
+
if (instance.destroyed) throw new Error("hash was destroyed");
|
|
128
|
+
if (checkFinished && instance.finished) throw new Error("digest() was already called");
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Asserts output is a sufficiently-sized byte array.
|
|
132
|
+
* @param out - destination buffer
|
|
133
|
+
* @param instance - hash instance providing output length
|
|
134
|
+
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
135
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
136
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
137
|
+
* @example
|
|
138
|
+
* Validate a caller-provided digest buffer.
|
|
139
|
+
* ```ts
|
|
140
|
+
* import { aoutput } from '@noble/hashes/utils.js';
|
|
141
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
142
|
+
* const hash = sha256.create();
|
|
143
|
+
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
function aoutput(out, instance) {
|
|
147
|
+
abytes$1(out, void 0, "output");
|
|
148
|
+
const min = instance.outputLen;
|
|
149
|
+
if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
153
|
+
* @param arrays - arrays to overwrite with zeros
|
|
154
|
+
* @example
|
|
155
|
+
* Zeroize sensitive buffers in place.
|
|
156
|
+
* ```ts
|
|
157
|
+
* clean(new Uint8Array([1, 2, 3]));
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
function clean(...arrays) {
|
|
161
|
+
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Creates a DataView for byte-level manipulation.
|
|
165
|
+
* @param arr - source typed array
|
|
166
|
+
* @returns DataView over the same buffer region.
|
|
167
|
+
* @example
|
|
168
|
+
* Create a DataView over an existing buffer.
|
|
169
|
+
* ```ts
|
|
170
|
+
* createView(new Uint8Array(4));
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
function createView(arr) {
|
|
174
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Rotate-right operation for uint32 values.
|
|
178
|
+
* @param word - source word
|
|
179
|
+
* @param shift - shift amount in bits
|
|
180
|
+
* @returns Rotated word.
|
|
181
|
+
* @example
|
|
182
|
+
* Rotate a 32-bit word to the right.
|
|
183
|
+
* ```ts
|
|
184
|
+
* rotr(0x12345678, 8);
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
function rotr(word, shift) {
|
|
188
|
+
return word << 32 - shift | word >>> shift;
|
|
189
|
+
}
|
|
190
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
|
|
191
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
192
|
+
/**
|
|
193
|
+
* Convert byte array to hex string.
|
|
194
|
+
* Uses the built-in function when available and assumes it matches the tested
|
|
195
|
+
* fallback semantics.
|
|
196
|
+
* @param bytes - bytes to encode
|
|
197
|
+
* @returns Lowercase hexadecimal string.
|
|
198
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
199
|
+
* @example
|
|
200
|
+
* Convert bytes to lowercase hexadecimal.
|
|
201
|
+
* ```ts
|
|
202
|
+
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
function bytesToHex$1(bytes) {
|
|
206
|
+
abytes$1(bytes);
|
|
207
|
+
if (hasHexBuiltin) return bytes.toHex();
|
|
208
|
+
let hex = "";
|
|
209
|
+
for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
|
|
210
|
+
return hex;
|
|
211
|
+
}
|
|
212
|
+
function asciiToBase16(ch) {
|
|
213
|
+
return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - 55 : ch >= 97 && ch <= 102 ? ch - 87 : void 0;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
217
|
+
* @param hex - hexadecimal string to decode
|
|
218
|
+
* @returns Decoded bytes.
|
|
219
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
220
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
221
|
+
* @example
|
|
222
|
+
* Decode lowercase hexadecimal into bytes.
|
|
223
|
+
* ```ts
|
|
224
|
+
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
function hexToBytes$1(hex) {
|
|
228
|
+
if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
|
|
229
|
+
if (hasHexBuiltin) try {
|
|
230
|
+
return Uint8Array.fromHex(hex);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error instanceof SyntaxError) throw new RangeError(error.message);
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
const hl = hex.length;
|
|
236
|
+
const al = hl / 2;
|
|
237
|
+
if (hl % 2) throw new RangeError("hex string expected, got unpadded hex of length " + hl);
|
|
238
|
+
const array = new Uint8Array(al);
|
|
239
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
240
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
241
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
242
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
243
|
+
const char = hex[hi] + hex[hi + 1];
|
|
244
|
+
throw new RangeError("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
|
|
245
|
+
}
|
|
246
|
+
array[ai] = n1 * 16 + n2;
|
|
247
|
+
}
|
|
248
|
+
return array;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Copies several Uint8Arrays into one.
|
|
252
|
+
* @param arrays - arrays to concatenate
|
|
253
|
+
* @returns Concatenated byte array.
|
|
254
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
255
|
+
* @example
|
|
256
|
+
* Concatenate multiple byte arrays.
|
|
257
|
+
* ```ts
|
|
258
|
+
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
|
259
|
+
* ```
|
|
260
|
+
*/
|
|
261
|
+
function concatBytes$1(...arrays) {
|
|
262
|
+
let sum = 0;
|
|
263
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
264
|
+
const a = arrays[i];
|
|
265
|
+
abytes$1(a);
|
|
266
|
+
sum += a.length;
|
|
267
|
+
}
|
|
268
|
+
const res = new Uint8Array(sum);
|
|
269
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
270
|
+
const a = arrays[i];
|
|
271
|
+
res.set(a, pad);
|
|
272
|
+
pad += a.length;
|
|
273
|
+
}
|
|
274
|
+
return res;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Merges default options and passed options.
|
|
278
|
+
* @param defaults - base option object
|
|
279
|
+
* @param opts - user overrides
|
|
280
|
+
* @param title - label included in thrown override errors
|
|
281
|
+
* @returns Fresh merged option object with a null prototype.
|
|
282
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
283
|
+
* @example
|
|
284
|
+
* Merge user overrides onto default options.
|
|
285
|
+
* ```ts
|
|
286
|
+
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
function checkOpts(defaults, opts, title = "opts") {
|
|
290
|
+
aopts(defaults, "defaults");
|
|
291
|
+
if (opts !== void 0) aopts(opts, title);
|
|
292
|
+
return Object.assign(Object.create(null), defaults, opts);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Creates a callable hash function from a stateful class constructor.
|
|
296
|
+
* @param hashCons - hash constructor or factory
|
|
297
|
+
* @param info - optional metadata such as DER OID
|
|
298
|
+
* @returns Frozen callable hash wrapper with `.create()`.
|
|
299
|
+
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
300
|
+
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
301
|
+
* init time.
|
|
302
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
303
|
+
* @example
|
|
304
|
+
* Wrap a stateful hash constructor into a callable helper.
|
|
305
|
+
* ```ts
|
|
306
|
+
* import { createHasher } from '@noble/hashes/utils.js';
|
|
307
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
308
|
+
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
309
|
+
* wrapped(new Uint8Array([1]));
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
312
|
+
function createHasher(hashCons, info = {}) {
|
|
313
|
+
if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
|
|
314
|
+
info = checkOpts({}, info, "info");
|
|
315
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
316
|
+
const tmp = hashCons(void 0);
|
|
317
|
+
hashC.outputLen = tmp.outputLen;
|
|
318
|
+
hashC.blockLen = tmp.blockLen;
|
|
319
|
+
hashC.canXOF = tmp.canXOF;
|
|
320
|
+
hashC.create = (opts) => hashCons(opts);
|
|
321
|
+
Object.assign(hashC, info);
|
|
322
|
+
return Object.freeze(hashC);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
|
|
326
|
+
* @param bytesLength - number of random bytes to generate
|
|
327
|
+
* @returns Random bytes.
|
|
328
|
+
* The platform `getRandomValues()` implementation still defines any
|
|
329
|
+
* single-call length cap, and this helper rejects oversize requests
|
|
330
|
+
* with a stable library `RangeError` instead of host-specific errors.
|
|
331
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
332
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
333
|
+
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
|
|
334
|
+
* @example
|
|
335
|
+
* Generate a fresh random key or nonce.
|
|
336
|
+
* ```ts
|
|
337
|
+
* const key = randomBytes(16);
|
|
338
|
+
* ```
|
|
339
|
+
*/
|
|
340
|
+
function randomBytes$2(bytesLength = 32) {
|
|
341
|
+
anumber$1(bytesLength, "bytesLength");
|
|
342
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
343
|
+
if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
|
|
344
|
+
if (bytesLength > 65536) throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
345
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
349
|
+
* @param suffix - final OID byte for the selected hash.
|
|
350
|
+
* The helper accepts any byte even though only the documented NIST hash
|
|
351
|
+
* suffixes are meaningful downstream.
|
|
352
|
+
* @returns Object containing the DER-encoded OID.
|
|
353
|
+
* @example
|
|
354
|
+
* Build OID metadata for a NIST hash.
|
|
355
|
+
* ```ts
|
|
356
|
+
* oidNist(0x01);
|
|
357
|
+
* ```
|
|
358
|
+
*/
|
|
359
|
+
var oidNist = (suffix) => ({ oid: Uint8Array.from([
|
|
360
|
+
6,
|
|
361
|
+
9,
|
|
362
|
+
96,
|
|
363
|
+
134,
|
|
364
|
+
72,
|
|
365
|
+
1,
|
|
366
|
+
101,
|
|
367
|
+
3,
|
|
368
|
+
4,
|
|
369
|
+
2,
|
|
370
|
+
suffix
|
|
371
|
+
]) });
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
|
|
374
|
+
/**
|
|
375
|
+
* Internal Merkle-Damgard hash utils.
|
|
376
|
+
* @module
|
|
377
|
+
*/
|
|
378
|
+
/**
|
|
379
|
+
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
|
380
|
+
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
|
381
|
+
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
|
382
|
+
* set the same bit.
|
|
383
|
+
* @param a - selector word
|
|
384
|
+
* @param b - word chosen when selector bit is set
|
|
385
|
+
* @param c - word chosen when selector bit is clear
|
|
386
|
+
* @returns Mixed 32-bit word.
|
|
387
|
+
* @example
|
|
388
|
+
* Combine three words with the shared 32-bit choice primitive.
|
|
389
|
+
* ```ts
|
|
390
|
+
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
|
391
|
+
* ```
|
|
392
|
+
*/
|
|
393
|
+
function Chi(a, b, c) {
|
|
394
|
+
return a & b ^ ~a & c;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
|
398
|
+
* Returns bits shared by at least two inputs.
|
|
399
|
+
* @param a - first input word
|
|
400
|
+
* @param b - second input word
|
|
401
|
+
* @param c - third input word
|
|
402
|
+
* @returns Mixed 32-bit word.
|
|
403
|
+
* @example
|
|
404
|
+
* Combine three words with the shared 32-bit majority primitive.
|
|
405
|
+
* ```ts
|
|
406
|
+
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
|
407
|
+
* ```
|
|
408
|
+
*/
|
|
409
|
+
function Maj(a, b, c) {
|
|
410
|
+
return a & b ^ a & c ^ b & c;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Merkle-Damgard hash construction base class.
|
|
414
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
415
|
+
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
|
416
|
+
* strings with partial-byte tails.
|
|
417
|
+
* @param blockLen - internal block size in bytes
|
|
418
|
+
* @param outputLen - digest size in bytes
|
|
419
|
+
* @param padOffset - trailing length field size in bytes
|
|
420
|
+
* @param isLE - whether length and state words are encoded in little-endian
|
|
421
|
+
* @example
|
|
422
|
+
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
|
423
|
+
* ```ts
|
|
424
|
+
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
|
425
|
+
* const hash = new _SHA1();
|
|
426
|
+
* hash.update(new Uint8Array([97, 98, 99]));
|
|
427
|
+
* hash.digest();
|
|
428
|
+
* ```
|
|
429
|
+
*/
|
|
430
|
+
var HashMD = class {
|
|
431
|
+
blockLen;
|
|
432
|
+
outputLen;
|
|
433
|
+
canXOF = false;
|
|
434
|
+
padOffset;
|
|
435
|
+
isLE;
|
|
436
|
+
buffer;
|
|
437
|
+
view;
|
|
438
|
+
finished = false;
|
|
439
|
+
length = 0;
|
|
440
|
+
pos = 0;
|
|
441
|
+
destroyed = false;
|
|
442
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
443
|
+
this.blockLen = blockLen;
|
|
444
|
+
this.outputLen = outputLen;
|
|
445
|
+
this.padOffset = padOffset;
|
|
446
|
+
this.isLE = isLE;
|
|
447
|
+
this.buffer = new Uint8Array(blockLen);
|
|
448
|
+
this.view = createView(this.buffer);
|
|
449
|
+
}
|
|
450
|
+
update(data) {
|
|
451
|
+
aexists(this);
|
|
452
|
+
abytes$1(data);
|
|
453
|
+
const { view, buffer, blockLen } = this;
|
|
454
|
+
const len = data.length;
|
|
455
|
+
let processed = false;
|
|
456
|
+
for (let pos = 0; pos < len;) {
|
|
457
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
458
|
+
if (take === blockLen) {
|
|
459
|
+
const dataView = createView(data);
|
|
460
|
+
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
|
|
461
|
+
processed = true;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
465
|
+
this.pos += take;
|
|
466
|
+
pos += take;
|
|
467
|
+
if (this.pos === blockLen) {
|
|
468
|
+
this.process(view, 0);
|
|
469
|
+
this.pos = 0;
|
|
470
|
+
processed = true;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
this.length += data.length;
|
|
474
|
+
if (processed) this.roundClean();
|
|
475
|
+
return this;
|
|
476
|
+
}
|
|
477
|
+
digestInto(out) {
|
|
478
|
+
aexists(this);
|
|
479
|
+
aoutput(out, this);
|
|
480
|
+
this.finished = true;
|
|
481
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
482
|
+
let { pos } = this;
|
|
483
|
+
buffer[pos++] = 128;
|
|
484
|
+
buffer.fill(0, pos);
|
|
485
|
+
if (this.padOffset > blockLen - pos) {
|
|
486
|
+
this.process(view, 0);
|
|
487
|
+
buffer.fill(0);
|
|
488
|
+
}
|
|
489
|
+
setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
|
|
490
|
+
this.process(view, 0);
|
|
491
|
+
this.roundClean();
|
|
492
|
+
const oview = out === buffer ? view : createView(out);
|
|
493
|
+
const len = this.outputLen;
|
|
494
|
+
const outLen = len / 4;
|
|
495
|
+
const state = this.get();
|
|
496
|
+
if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
|
|
497
|
+
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
|
|
498
|
+
}
|
|
499
|
+
digest() {
|
|
500
|
+
const { buffer, outputLen } = this;
|
|
501
|
+
this.digestInto(buffer);
|
|
502
|
+
const res = buffer.slice(0, outputLen);
|
|
503
|
+
this.destroy();
|
|
504
|
+
return res;
|
|
505
|
+
}
|
|
506
|
+
_cloneIntoMeta(to) {
|
|
507
|
+
const { buffer, length, finished, destroyed, pos } = this;
|
|
508
|
+
to.destroyed = destroyed;
|
|
509
|
+
to.finished = finished;
|
|
510
|
+
to.length = length;
|
|
511
|
+
to.pos = pos;
|
|
512
|
+
if (pos) to.buffer.set(buffer);
|
|
513
|
+
return to;
|
|
514
|
+
}
|
|
515
|
+
clone() {
|
|
516
|
+
return this._cloneInto();
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
/**
|
|
520
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
521
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
522
|
+
*/
|
|
523
|
+
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
|
524
|
+
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
|
525
|
+
* it as read-only because constructors copy words from it by index. */
|
|
526
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
527
|
+
1779033703,
|
|
528
|
+
3144134277,
|
|
529
|
+
1013904242,
|
|
530
|
+
2773480762,
|
|
531
|
+
1359893119,
|
|
532
|
+
2600822924,
|
|
533
|
+
528734635,
|
|
534
|
+
1541459225
|
|
535
|
+
]);
|
|
536
|
+
//#endregion
|
|
537
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js
|
|
538
|
+
/**
|
|
539
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
540
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
541
|
+
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
|
|
542
|
+
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
|
|
543
|
+
* @module
|
|
544
|
+
*/
|
|
545
|
+
/**
|
|
546
|
+
* SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
|
|
547
|
+
* of the cube roots of the first 64 primes (2..311).
|
|
548
|
+
*/
|
|
549
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
550
|
+
1116352408,
|
|
551
|
+
1899447441,
|
|
552
|
+
3049323471,
|
|
553
|
+
3921009573,
|
|
554
|
+
961987163,
|
|
555
|
+
1508970993,
|
|
556
|
+
2453635748,
|
|
557
|
+
2870763221,
|
|
558
|
+
3624381080,
|
|
559
|
+
310598401,
|
|
560
|
+
607225278,
|
|
561
|
+
1426881987,
|
|
562
|
+
1925078388,
|
|
563
|
+
2162078206,
|
|
564
|
+
2614888103,
|
|
565
|
+
3248222580,
|
|
566
|
+
3835390401,
|
|
567
|
+
4022224774,
|
|
568
|
+
264347078,
|
|
569
|
+
604807628,
|
|
570
|
+
770255983,
|
|
571
|
+
1249150122,
|
|
572
|
+
1555081692,
|
|
573
|
+
1996064986,
|
|
574
|
+
2554220882,
|
|
575
|
+
2821834349,
|
|
576
|
+
2952996808,
|
|
577
|
+
3210313671,
|
|
578
|
+
3336571891,
|
|
579
|
+
3584528711,
|
|
580
|
+
113926993,
|
|
581
|
+
338241895,
|
|
582
|
+
666307205,
|
|
583
|
+
773529912,
|
|
584
|
+
1294757372,
|
|
585
|
+
1396182291,
|
|
586
|
+
1695183700,
|
|
587
|
+
1986661051,
|
|
588
|
+
2177026350,
|
|
589
|
+
2456956037,
|
|
590
|
+
2730485921,
|
|
591
|
+
2820302411,
|
|
592
|
+
3259730800,
|
|
593
|
+
3345764771,
|
|
594
|
+
3516065817,
|
|
595
|
+
3600352804,
|
|
596
|
+
4094571909,
|
|
597
|
+
275423344,
|
|
598
|
+
430227734,
|
|
599
|
+
506948616,
|
|
600
|
+
659060556,
|
|
601
|
+
883997877,
|
|
602
|
+
958139571,
|
|
603
|
+
1322822218,
|
|
604
|
+
1537002063,
|
|
605
|
+
1747873779,
|
|
606
|
+
1955562222,
|
|
607
|
+
2024104815,
|
|
608
|
+
2227730452,
|
|
609
|
+
2361852424,
|
|
610
|
+
2428436474,
|
|
611
|
+
2756734187,
|
|
612
|
+
3204031479,
|
|
613
|
+
3329325298
|
|
614
|
+
]);
|
|
615
|
+
/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
|
|
616
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
617
|
+
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
|
|
618
|
+
var SHA2_32B = class extends HashMD {
|
|
619
|
+
A = 0;
|
|
620
|
+
B = 0;
|
|
621
|
+
C = 0;
|
|
622
|
+
D = 0;
|
|
623
|
+
E = 0;
|
|
624
|
+
F = 0;
|
|
625
|
+
G = 0;
|
|
626
|
+
H = 0;
|
|
627
|
+
constructor(outputLen, IV) {
|
|
628
|
+
super(64, outputLen, 8, false);
|
|
629
|
+
this.A = IV[0] | 0;
|
|
630
|
+
this.B = IV[1] | 0;
|
|
631
|
+
this.C = IV[2] | 0;
|
|
632
|
+
this.D = IV[3] | 0;
|
|
633
|
+
this.E = IV[4] | 0;
|
|
634
|
+
this.F = IV[5] | 0;
|
|
635
|
+
this.G = IV[6] | 0;
|
|
636
|
+
this.H = IV[7] | 0;
|
|
637
|
+
}
|
|
638
|
+
get() {
|
|
639
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
640
|
+
return [
|
|
641
|
+
A,
|
|
642
|
+
B,
|
|
643
|
+
C,
|
|
644
|
+
D,
|
|
645
|
+
E,
|
|
646
|
+
F,
|
|
647
|
+
G,
|
|
648
|
+
H
|
|
649
|
+
];
|
|
650
|
+
}
|
|
651
|
+
set(A, B, C, D, E, F, G, H) {
|
|
652
|
+
this.A = A | 0;
|
|
653
|
+
this.B = B | 0;
|
|
654
|
+
this.C = C | 0;
|
|
655
|
+
this.D = D | 0;
|
|
656
|
+
this.E = E | 0;
|
|
657
|
+
this.F = F | 0;
|
|
658
|
+
this.G = G | 0;
|
|
659
|
+
this.H = H | 0;
|
|
660
|
+
}
|
|
661
|
+
_cloneInto(to) {
|
|
662
|
+
(to ||= new this.constructor()).set(...this.get());
|
|
663
|
+
return this._cloneIntoMeta(to);
|
|
664
|
+
}
|
|
665
|
+
process(view, offset) {
|
|
666
|
+
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
|
|
667
|
+
for (let i = 16; i < 64; i++) {
|
|
668
|
+
const W15 = SHA256_W[i - 15];
|
|
669
|
+
const W2 = SHA256_W[i - 2];
|
|
670
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
671
|
+
SHA256_W[i] = (rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10) + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
672
|
+
}
|
|
673
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
674
|
+
for (let i = 0; i < 64; i++) {
|
|
675
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
676
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
677
|
+
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
|
|
678
|
+
H = G;
|
|
679
|
+
G = F;
|
|
680
|
+
F = E;
|
|
681
|
+
E = D + T1 | 0;
|
|
682
|
+
D = C;
|
|
683
|
+
C = B;
|
|
684
|
+
B = A;
|
|
685
|
+
A = T1 + T2 | 0;
|
|
686
|
+
}
|
|
687
|
+
A = A + this.A | 0;
|
|
688
|
+
B = B + this.B | 0;
|
|
689
|
+
C = C + this.C | 0;
|
|
690
|
+
D = D + this.D | 0;
|
|
691
|
+
E = E + this.E | 0;
|
|
692
|
+
F = F + this.F | 0;
|
|
693
|
+
G = G + this.G | 0;
|
|
694
|
+
H = H + this.H | 0;
|
|
695
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
696
|
+
}
|
|
697
|
+
roundClean() {
|
|
698
|
+
clean(SHA256_W);
|
|
699
|
+
}
|
|
700
|
+
destroy() {
|
|
701
|
+
this.destroyed = true;
|
|
702
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
703
|
+
clean(this.buffer);
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
|
|
707
|
+
var _SHA256 = class extends SHA2_32B {
|
|
708
|
+
constructor() {
|
|
709
|
+
super(32, SHA256_IV);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
/**
|
|
713
|
+
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
|
|
714
|
+
*
|
|
715
|
+
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
|
|
716
|
+
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
717
|
+
* - Each sha256 hash is executing 2^18 bit operations.
|
|
718
|
+
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
|
|
719
|
+
* @param msg - message bytes to hash
|
|
720
|
+
* @param opts - Reserved hash options.
|
|
721
|
+
* @returns Digest bytes.
|
|
722
|
+
* @example
|
|
723
|
+
* Hash a message with SHA2-256.
|
|
724
|
+
* ```ts
|
|
725
|
+
* sha256(new Uint8Array([97, 98, 99]));
|
|
726
|
+
* ```
|
|
727
|
+
*/
|
|
728
|
+
var sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
|
|
729
|
+
//#endregion
|
|
730
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js
|
|
731
|
+
/**
|
|
732
|
+
* Hex, bytes and number utilities.
|
|
733
|
+
* @module
|
|
734
|
+
*/
|
|
735
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
736
|
+
/**
|
|
737
|
+
* Validates that a value is an array, optionally validating each element.
|
|
738
|
+
* @param item - Value to validate.
|
|
739
|
+
* @param title - Label included in thrown errors.
|
|
740
|
+
* @param inner - Optional per-element validator, called with the element and its label.
|
|
741
|
+
* @returns The validated array.
|
|
742
|
+
* @example
|
|
743
|
+
* Validate an array of points before batch processing.
|
|
744
|
+
*
|
|
745
|
+
* ```ts
|
|
746
|
+
* aarray([1n, 2n], 'scalars');
|
|
747
|
+
* ```
|
|
748
|
+
*/
|
|
749
|
+
function aarray(item, title, inner = () => {}) {
|
|
750
|
+
if (!Array.isArray(item)) throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
|
751
|
+
for (let i = 0; i < item.length; i++) inner(item[i], `${title}[${i}]`);
|
|
752
|
+
return item;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Validates that a value is a byte array.
|
|
756
|
+
* @param value - Value to validate.
|
|
757
|
+
* @param length - Optional exact byte length.
|
|
758
|
+
* @param title - Optional field name.
|
|
759
|
+
* @returns Original byte array.
|
|
760
|
+
* @example
|
|
761
|
+
* Reject non-byte input before passing data into curve code.
|
|
762
|
+
*
|
|
763
|
+
* ```ts
|
|
764
|
+
* abytes(new Uint8Array(1));
|
|
765
|
+
* ```
|
|
766
|
+
*/
|
|
767
|
+
var abytes = (value, length, title) => abytes$1(value, length, title);
|
|
768
|
+
/**
|
|
769
|
+
* Validates that a value is a non-negative safe integer.
|
|
770
|
+
* @param n - Value to validate.
|
|
771
|
+
* @param title - Optional field name.
|
|
772
|
+
* @returns The validated number.
|
|
773
|
+
* @example
|
|
774
|
+
* Validate a numeric length before allocating buffers.
|
|
775
|
+
*
|
|
776
|
+
* ```ts
|
|
777
|
+
* anumber(1);
|
|
778
|
+
* ```
|
|
779
|
+
*/
|
|
780
|
+
var anumber = anumber$1;
|
|
781
|
+
/**
|
|
782
|
+
* Asserts something is a string.
|
|
783
|
+
* @param value - Value to validate.
|
|
784
|
+
* @param title - Label included in thrown errors.
|
|
785
|
+
* @returns The validated string.
|
|
786
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
787
|
+
* @example
|
|
788
|
+
* Validate a label string.
|
|
789
|
+
*
|
|
790
|
+
* ```ts
|
|
791
|
+
* astring('example', 'label');
|
|
792
|
+
* ```
|
|
793
|
+
*/
|
|
794
|
+
function astring(value, title = "") {
|
|
795
|
+
if (typeof value !== "string") {
|
|
796
|
+
const prefix = title && `"${title}" `;
|
|
797
|
+
throw new TypeError(prefix + "expected string, got type=" + typeof value);
|
|
798
|
+
}
|
|
799
|
+
return value;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Asserts something is a plain object-ish value, not null or array.
|
|
803
|
+
* @param value - Value to validate.
|
|
804
|
+
* @param title - Label included in thrown errors.
|
|
805
|
+
* @returns The validated object.
|
|
806
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
807
|
+
* @example
|
|
808
|
+
* Validate an options object before checking fields.
|
|
809
|
+
*
|
|
810
|
+
* ```ts
|
|
811
|
+
* aobject({ flag: true });
|
|
812
|
+
* ```
|
|
813
|
+
*/
|
|
814
|
+
function aobject(value, title = "object") {
|
|
815
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
|
|
816
|
+
return value;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Asserts something is a function.
|
|
820
|
+
* @param value - Value to validate.
|
|
821
|
+
* @param title - Label included in thrown errors.
|
|
822
|
+
* @returns The validated function.
|
|
823
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
824
|
+
* @example
|
|
825
|
+
* Validate a required method before calling it.
|
|
826
|
+
*
|
|
827
|
+
* ```ts
|
|
828
|
+
* afunction(() => true, 'predicate');
|
|
829
|
+
* ```
|
|
830
|
+
*/
|
|
831
|
+
function afunction(value, title) {
|
|
832
|
+
if (typeof value !== "function") throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
|
|
833
|
+
return value;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Encodes bytes as lowercase hex.
|
|
837
|
+
* @param bytes - Bytes to encode.
|
|
838
|
+
* @returns Lowercase hex string.
|
|
839
|
+
* @example
|
|
840
|
+
* Serialize bytes as hex for logging or fixtures.
|
|
841
|
+
*
|
|
842
|
+
* ```ts
|
|
843
|
+
* bytesToHex(Uint8Array.of(1, 2, 3));
|
|
844
|
+
* ```
|
|
845
|
+
*/
|
|
846
|
+
var bytesToHex = bytesToHex$1;
|
|
847
|
+
/**
|
|
848
|
+
* Concatenates byte arrays.
|
|
849
|
+
* @param arrays - Byte arrays to join.
|
|
850
|
+
* @returns Concatenated bytes.
|
|
851
|
+
* @example
|
|
852
|
+
* Join domain-separated chunks into one buffer.
|
|
853
|
+
*
|
|
854
|
+
* ```ts
|
|
855
|
+
* concatBytes(Uint8Array.of(1), Uint8Array.of(2));
|
|
856
|
+
* ```
|
|
857
|
+
*/
|
|
858
|
+
var concatBytes = (...arrays) => concatBytes$1(...arrays);
|
|
859
|
+
/**
|
|
860
|
+
* Decodes lowercase or uppercase hex into bytes.
|
|
861
|
+
* @param hex - Hex string to decode.
|
|
862
|
+
* @returns Decoded bytes.
|
|
863
|
+
* @example
|
|
864
|
+
* Parse fixture hex into bytes before hashing.
|
|
865
|
+
*
|
|
866
|
+
* ```ts
|
|
867
|
+
* hexToBytes('0102');
|
|
868
|
+
* ```
|
|
869
|
+
*/
|
|
870
|
+
var hexToBytes = (hex) => hexToBytes$1(hex);
|
|
871
|
+
/**
|
|
872
|
+
* Checks whether a value is a Uint8Array.
|
|
873
|
+
* @param a - Value to inspect.
|
|
874
|
+
* @returns `true` when `a` is a Uint8Array.
|
|
875
|
+
* @example
|
|
876
|
+
* Branch on byte input before decoding it.
|
|
877
|
+
*
|
|
878
|
+
* ```ts
|
|
879
|
+
* isBytes(new Uint8Array(1));
|
|
880
|
+
* ```
|
|
881
|
+
*/
|
|
882
|
+
var isBytes = isBytes$1;
|
|
883
|
+
/**
|
|
884
|
+
* Reads random bytes from the platform CSPRNG.
|
|
885
|
+
* @param bytesLength - Number of random bytes to read.
|
|
886
|
+
* @returns Fresh random bytes.
|
|
887
|
+
* @example
|
|
888
|
+
* Generate a random seed for a keypair.
|
|
889
|
+
*
|
|
890
|
+
* ```ts
|
|
891
|
+
* randomBytes(2);
|
|
892
|
+
* ```
|
|
893
|
+
*/
|
|
894
|
+
var randomBytes$1 = (bytesLength) => randomBytes$2(bytesLength);
|
|
895
|
+
var _0n$5 = /* @__PURE__ */ BigInt(0);
|
|
896
|
+
var _1n$3 = /* @__PURE__ */ BigInt(1);
|
|
897
|
+
var atitle = (title) => title ? `"${title}" ` : "";
|
|
898
|
+
/**
|
|
899
|
+
* Validates that a flag is boolean.
|
|
900
|
+
* @param value - Value to validate.
|
|
901
|
+
* @param title - Optional field name.
|
|
902
|
+
* @returns Original value.
|
|
903
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
904
|
+
* @example
|
|
905
|
+
* Reject non-boolean option flags early.
|
|
906
|
+
*
|
|
907
|
+
* ```ts
|
|
908
|
+
* abool(true);
|
|
909
|
+
* ```
|
|
910
|
+
*/
|
|
911
|
+
function abool(value, title = "") {
|
|
912
|
+
if (typeof value !== "boolean") throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
|
|
913
|
+
return value;
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Validates that a value is a non-negative bigint or safe integer.
|
|
917
|
+
* @param n - Value to validate.
|
|
918
|
+
* @returns The same validated value.
|
|
919
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
920
|
+
* @example
|
|
921
|
+
* Validate one integer-like value before serializing it.
|
|
922
|
+
*
|
|
923
|
+
* ```ts
|
|
924
|
+
* abignumber(1n);
|
|
925
|
+
* ```
|
|
926
|
+
*/
|
|
927
|
+
function abignumber(n) {
|
|
928
|
+
if (typeof n === "bigint") {
|
|
929
|
+
if (!isPosBig(n)) throw new RangeError("positive bigint expected, got " + n);
|
|
930
|
+
} else anumber(n);
|
|
931
|
+
return n;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Validates that a value is a safe integer.
|
|
935
|
+
* @param value - Integer to validate.
|
|
936
|
+
* @param title - Optional field name.
|
|
937
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
938
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
939
|
+
* @example
|
|
940
|
+
* Validate a window size before scalar arithmetic uses it.
|
|
941
|
+
*
|
|
942
|
+
* ```ts
|
|
943
|
+
* asafenumber(1);
|
|
944
|
+
* ```
|
|
945
|
+
*/
|
|
946
|
+
function asafenumber(value, title = "") {
|
|
947
|
+
if (typeof value !== "number") {
|
|
948
|
+
const prefix = title && `"${title}" `;
|
|
949
|
+
throw new TypeError(prefix + "expected number, got type=" + typeof value);
|
|
950
|
+
}
|
|
951
|
+
if (!Number.isSafeInteger(value)) {
|
|
952
|
+
const prefix = title && `"${title}" `;
|
|
953
|
+
throw new RangeError(prefix + "expected safe integer, got " + value);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Encodes a bigint into even-length big-endian hex.
|
|
958
|
+
* The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
|
|
959
|
+
* gets one leading zero nibble so the result always represents whole bytes.
|
|
960
|
+
* @param num - Number to encode.
|
|
961
|
+
* @returns Big-endian hex string.
|
|
962
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
963
|
+
* @example
|
|
964
|
+
* Encode a scalar into hex without a `0x` prefix.
|
|
965
|
+
*
|
|
966
|
+
* ```ts
|
|
967
|
+
* numberToHexUnpadded(255n);
|
|
968
|
+
* ```
|
|
969
|
+
*/
|
|
970
|
+
function numberToHexUnpadded(num) {
|
|
971
|
+
const hex = abignumber(num).toString(16);
|
|
972
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Parses a big-endian hex string into bigint.
|
|
976
|
+
* Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
|
|
977
|
+
* same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
|
|
978
|
+
* @param hex - Hex string without `0x`.
|
|
979
|
+
* @returns Parsed bigint value.
|
|
980
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
981
|
+
* @example
|
|
982
|
+
* Parse a scalar from fixture hex.
|
|
983
|
+
*
|
|
984
|
+
* ```ts
|
|
985
|
+
* hexToNumber('ff');
|
|
986
|
+
* ```
|
|
987
|
+
*/
|
|
988
|
+
function hexToNumber(hex) {
|
|
989
|
+
if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
|
|
990
|
+
return hex === "" ? _0n$5 : BigInt("0x" + hex);
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Parses big-endian bytes into bigint.
|
|
994
|
+
* @param bytes - Bytes in big-endian order.
|
|
995
|
+
* @returns Parsed bigint value.
|
|
996
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
997
|
+
* @example
|
|
998
|
+
* Read a scalar encoded in network byte order.
|
|
999
|
+
*
|
|
1000
|
+
* ```ts
|
|
1001
|
+
* bytesToNumberBE(Uint8Array.of(1, 0));
|
|
1002
|
+
* ```
|
|
1003
|
+
*/
|
|
1004
|
+
function bytesToNumberBE(bytes) {
|
|
1005
|
+
return hexToNumber(bytesToHex$1(bytes));
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Parses little-endian bytes into bigint.
|
|
1009
|
+
* @param bytes - Bytes in little-endian order.
|
|
1010
|
+
* @returns Parsed bigint value.
|
|
1011
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1012
|
+
* @example
|
|
1013
|
+
* Read a scalar encoded in little-endian form.
|
|
1014
|
+
*
|
|
1015
|
+
* ```ts
|
|
1016
|
+
* bytesToNumberLE(Uint8Array.of(1, 0));
|
|
1017
|
+
* ```
|
|
1018
|
+
*/
|
|
1019
|
+
function bytesToNumberLE(bytes) {
|
|
1020
|
+
return hexToNumber(bytesToHex$1(copyBytes(abytes$1(bytes)).reverse()));
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Encodes a bigint into fixed-length big-endian bytes.
|
|
1024
|
+
* @param n - Number to encode.
|
|
1025
|
+
* @param len - Output length in bytes. Must be greater than zero.
|
|
1026
|
+
* @returns Big-endian byte array.
|
|
1027
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1028
|
+
* @throws If a documented runtime validation or state check fails. {@link Error}
|
|
1029
|
+
* @example
|
|
1030
|
+
* Serialize a scalar into a 32-byte field element.
|
|
1031
|
+
*
|
|
1032
|
+
* ```ts
|
|
1033
|
+
* numberToBytesBE(255n, 2);
|
|
1034
|
+
* ```
|
|
1035
|
+
*/
|
|
1036
|
+
function numberToBytesBE(n, len) {
|
|
1037
|
+
anumber$1(len);
|
|
1038
|
+
if (len === 0) throw new Error("zero output length is invalid");
|
|
1039
|
+
n = abignumber(n);
|
|
1040
|
+
const expectedLen = len * 2;
|
|
1041
|
+
const hex = n.toString(16);
|
|
1042
|
+
if (hex.length > expectedLen) throw new RangeError("number is too large");
|
|
1043
|
+
return hexToBytes$1(hex.padStart(expectedLen, "0"));
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Encodes a bigint into fixed-length little-endian bytes.
|
|
1047
|
+
* @param n - Number to encode.
|
|
1048
|
+
* @param len - Output length in bytes.
|
|
1049
|
+
* @returns Little-endian byte array.
|
|
1050
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1051
|
+
* @throws If a documented runtime validation or state check fails. {@link Error}
|
|
1052
|
+
* @example
|
|
1053
|
+
* Serialize a scalar for little-endian protocols.
|
|
1054
|
+
*
|
|
1055
|
+
* ```ts
|
|
1056
|
+
* numberToBytesLE(255n, 2);
|
|
1057
|
+
* ```
|
|
1058
|
+
*/
|
|
1059
|
+
function numberToBytesLE(n, len) {
|
|
1060
|
+
return numberToBytesBE(n, len).reverse();
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
|
|
1064
|
+
* and Buffer#slice creates mutable copy. Never use Buffers!
|
|
1065
|
+
* @param bytes - Bytes to copy.
|
|
1066
|
+
* @returns Detached copy.
|
|
1067
|
+
* @example
|
|
1068
|
+
* Make an isolated copy before mutating serialized bytes.
|
|
1069
|
+
*
|
|
1070
|
+
* ```ts
|
|
1071
|
+
* copyBytes(Uint8Array.of(1, 2, 3));
|
|
1072
|
+
* ```
|
|
1073
|
+
*/
|
|
1074
|
+
function copyBytes(bytes) {
|
|
1075
|
+
return Uint8Array.from(abytes(bytes));
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
|
|
1079
|
+
* Should be safe to use for things expected to be ASCII.
|
|
1080
|
+
* Returns exact same result as `TextEncoder` for ASCII or throws.
|
|
1081
|
+
* @param ascii - ASCII input text.
|
|
1082
|
+
* @returns Encoded bytes.
|
|
1083
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1084
|
+
* @example
|
|
1085
|
+
* Encode an ASCII domain-separation tag.
|
|
1086
|
+
*
|
|
1087
|
+
* ```ts
|
|
1088
|
+
* asciiToBytes('ABC');
|
|
1089
|
+
* ```
|
|
1090
|
+
*/
|
|
1091
|
+
function asciiToBytes(ascii) {
|
|
1092
|
+
if (typeof ascii !== "string") throw new TypeError("ascii string expected, got " + typeof ascii);
|
|
1093
|
+
return Uint8Array.from(ascii, (c, i) => {
|
|
1094
|
+
const charCode = c.charCodeAt(0);
|
|
1095
|
+
if (c.length !== 1 || charCode > 127) throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
|
|
1096
|
+
return charCode;
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Checks whether n is non-negative bigint. Historical name.
|
|
1101
|
+
* @param n - candidate value
|
|
1102
|
+
* @returns `true` when the value is bigint and 0 or larger
|
|
1103
|
+
* @example
|
|
1104
|
+
* Check a candidate scalar before range validation.
|
|
1105
|
+
*
|
|
1106
|
+
* ```ts
|
|
1107
|
+
* isPosBig(2n);
|
|
1108
|
+
* ```
|
|
1109
|
+
*/
|
|
1110
|
+
function isPosBig(n) {
|
|
1111
|
+
return typeof n === "bigint" && _0n$5 <= n;
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Checks whether a bigint lies inside a half-open range.
|
|
1115
|
+
* @param n - Candidate value.
|
|
1116
|
+
* @param min - Inclusive lower bound.
|
|
1117
|
+
* @param max - Exclusive upper bound.
|
|
1118
|
+
* @returns `true` when the value is inside the range.
|
|
1119
|
+
* @example
|
|
1120
|
+
* Check whether a candidate scalar fits the field order.
|
|
1121
|
+
*
|
|
1122
|
+
* ```ts
|
|
1123
|
+
* inRange(2n, 1n, 3n);
|
|
1124
|
+
* ```
|
|
1125
|
+
*/
|
|
1126
|
+
function inRange(n, min, max) {
|
|
1127
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Asserts `min <= n < max`. NOTE: upper bound is exclusive.
|
|
1131
|
+
* @param title - Value label for error messages.
|
|
1132
|
+
* @param n - Candidate value.
|
|
1133
|
+
* @param min - Inclusive lower bound.
|
|
1134
|
+
* @param max - Exclusive upper bound.
|
|
1135
|
+
* Wrong-type inputs are not separated from out-of-range values here: they still flow through the
|
|
1136
|
+
* shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
|
|
1137
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1138
|
+
* @example
|
|
1139
|
+
* Assert that a bigint stays within one half-open range.
|
|
1140
|
+
*
|
|
1141
|
+
* ```ts
|
|
1142
|
+
* aInRange('x', 2n, 1n, 256n);
|
|
1143
|
+
* ```
|
|
1144
|
+
*/
|
|
1145
|
+
function aInRange(title, n, min, max) {
|
|
1146
|
+
if (!inRange(n, min, max)) throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Calculates amount of bits in a bigint.
|
|
1150
|
+
* Same as `n.toString(2).length`
|
|
1151
|
+
* TODO: merge with nLength in modular
|
|
1152
|
+
* @param n - Value to inspect.
|
|
1153
|
+
* @returns Bit length.
|
|
1154
|
+
* @throws If the value is negative. {@link Error}
|
|
1155
|
+
* @example
|
|
1156
|
+
* Measure the bit length of a scalar before serialization.
|
|
1157
|
+
*
|
|
1158
|
+
* ```ts
|
|
1159
|
+
* bitLen(8n);
|
|
1160
|
+
* ```
|
|
1161
|
+
*/
|
|
1162
|
+
function bitLen(n) {
|
|
1163
|
+
if (n < _0n$5) throw new Error("expected non-negative bigint, got " + n);
|
|
1164
|
+
return n === _0n$5 ? 0 : n.toString(2).length;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
|
1168
|
+
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
|
1169
|
+
* @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
|
|
1170
|
+
* semantics and therefore produce `-1n`.
|
|
1171
|
+
* @returns Bitmask value.
|
|
1172
|
+
* @example
|
|
1173
|
+
* Calculate mask for N bits.
|
|
1174
|
+
*
|
|
1175
|
+
* ```ts
|
|
1176
|
+
* bitMask(4);
|
|
1177
|
+
* ```
|
|
1178
|
+
*/
|
|
1179
|
+
var bitMask = (n) => {
|
|
1180
|
+
asafenumber(n, "n");
|
|
1181
|
+
return (_1n$3 << BigInt(n)) - _1n$3;
|
|
1182
|
+
};
|
|
1183
|
+
/**
|
|
1184
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
1185
|
+
* @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
|
|
1186
|
+
* is not rejected here and would make the internal generate loop non-progressing.
|
|
1187
|
+
* @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
|
|
1188
|
+
* @param hmacFn - HMAC implementation.
|
|
1189
|
+
* @returns Function that will call DRBG until the predicate returns anything
|
|
1190
|
+
* other than `undefined`.
|
|
1191
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1192
|
+
* @example
|
|
1193
|
+
* Build a deterministic nonce generator for RFC6979-style signing.
|
|
1194
|
+
*
|
|
1195
|
+
* ```ts
|
|
1196
|
+
* import { createHmacDrbg } from '@noble/curves/utils.js';
|
|
1197
|
+
* import { hmac } from '@noble/hashes/hmac.js';
|
|
1198
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1199
|
+
* const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);
|
|
1200
|
+
* const drbg = createHmacDrbg(32, 32, hmacFn);
|
|
1201
|
+
* const seed = new Uint8Array(32);
|
|
1202
|
+
* drbg(seed, (bytes) => bytes);
|
|
1203
|
+
* ```
|
|
1204
|
+
*/
|
|
1205
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
1206
|
+
anumber$1(hashLen, "hashLen");
|
|
1207
|
+
anumber$1(qByteLen, "qByteLen");
|
|
1208
|
+
if (typeof hmacFn !== "function") throw new TypeError("hmacFn must be a function");
|
|
1209
|
+
const u8n = (len) => new Uint8Array(len);
|
|
1210
|
+
const NULL = Uint8Array.of();
|
|
1211
|
+
const byte0 = Uint8Array.of(0);
|
|
1212
|
+
const byte1 = Uint8Array.of(1);
|
|
1213
|
+
const _maxDrbgIters = 1e3;
|
|
1214
|
+
let v = u8n(hashLen);
|
|
1215
|
+
let k = u8n(hashLen);
|
|
1216
|
+
let i = 0;
|
|
1217
|
+
const reset = () => {
|
|
1218
|
+
v.fill(1);
|
|
1219
|
+
k.fill(0);
|
|
1220
|
+
i = 0;
|
|
1221
|
+
};
|
|
1222
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
1223
|
+
const reseed = (seed = NULL) => {
|
|
1224
|
+
k = h(byte0, seed);
|
|
1225
|
+
v = h();
|
|
1226
|
+
if (seed.length === 0) return;
|
|
1227
|
+
k = h(byte1, seed);
|
|
1228
|
+
v = h();
|
|
1229
|
+
};
|
|
1230
|
+
const gen = () => {
|
|
1231
|
+
if (i++ >= _maxDrbgIters) throw new Error("drbg: tried max amount of iterations");
|
|
1232
|
+
let len = 0;
|
|
1233
|
+
const out = [];
|
|
1234
|
+
while (len < qByteLen) {
|
|
1235
|
+
v = h();
|
|
1236
|
+
const sl = v.slice();
|
|
1237
|
+
out.push(sl);
|
|
1238
|
+
len += v.length;
|
|
1239
|
+
}
|
|
1240
|
+
return concatBytes(...out);
|
|
1241
|
+
};
|
|
1242
|
+
const genUntil = (seed, pred) => {
|
|
1243
|
+
reset();
|
|
1244
|
+
reseed(seed);
|
|
1245
|
+
let res = void 0;
|
|
1246
|
+
while ((res = pred(gen())) === void 0) reseed();
|
|
1247
|
+
reset();
|
|
1248
|
+
return res;
|
|
1249
|
+
};
|
|
1250
|
+
return genUntil;
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Validates declared required and optional field types on a plain object.
|
|
1254
|
+
* Extra keys are intentionally ignored because many callers validate only the subset they use from
|
|
1255
|
+
* richer option bags or runtime objects.
|
|
1256
|
+
* This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
|
|
1257
|
+
* one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.
|
|
1258
|
+
* @param object - Object to validate.
|
|
1259
|
+
* @param fields - Required field types.
|
|
1260
|
+
* @param optFields - Optional field types.
|
|
1261
|
+
* @param title - Object label included in thrown errors.
|
|
1262
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1263
|
+
* @example
|
|
1264
|
+
* Check user options before building a curve helper.
|
|
1265
|
+
*
|
|
1266
|
+
* ```ts
|
|
1267
|
+
* validateObject({ flag: true }, { flag: 'boolean' });
|
|
1268
|
+
* ```
|
|
1269
|
+
*/
|
|
1270
|
+
function validateObject(object, fields = {}, optFields = {}, title = "object") {
|
|
1271
|
+
aobject(object, title);
|
|
1272
|
+
aobject(fields, "fields");
|
|
1273
|
+
aobject(optFields, "optFields");
|
|
1274
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
1275
|
+
const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
|
1276
|
+
const val = object[fieldName];
|
|
1277
|
+
if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) throw new TypeError(`${label} is invalid: expected own property`);
|
|
1278
|
+
if (isOpt && val === void 0) return;
|
|
1279
|
+
const current = typeof val;
|
|
1280
|
+
if (current !== expectedType || val === null) throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
|
|
1281
|
+
}
|
|
1282
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
1283
|
+
iter(fields, false);
|
|
1284
|
+
iter(optFields, true);
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js
|
|
1288
|
+
/**
|
|
1289
|
+
* Utils for modular division and fields.
|
|
1290
|
+
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
|
1291
|
+
* There is no division: it is replaced by modular multiplicative inverse.
|
|
1292
|
+
* @module
|
|
1293
|
+
*/
|
|
1294
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1295
|
+
var _0n$4 = /* @__PURE__ */ BigInt(0), _1n$2 = /* @__PURE__ */ BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2);
|
|
1296
|
+
var _3n$1 = /* @__PURE__ */ BigInt(3), _4n$2 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
|
|
1297
|
+
var _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
|
|
1298
|
+
var _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);
|
|
1299
|
+
var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
|
|
1300
|
+
/**
|
|
1301
|
+
* @param a - Dividend value.
|
|
1302
|
+
* @param b - Positive modulus.
|
|
1303
|
+
* @returns Reduced value in `[0, b)` only when `b` is positive.
|
|
1304
|
+
* @throws If the modulus is not positive. {@link Error}
|
|
1305
|
+
* @example
|
|
1306
|
+
* Normalize a bigint into one field residue.
|
|
1307
|
+
*
|
|
1308
|
+
* ```ts
|
|
1309
|
+
* mod(-1n, 5n);
|
|
1310
|
+
* ```
|
|
1311
|
+
*/
|
|
1312
|
+
function mod(a, b) {
|
|
1313
|
+
if (b <= _0n$4) throw new Error("mod: expected positive modulus, got " + b);
|
|
1314
|
+
const result = a % b;
|
|
1315
|
+
return result >= _0n$4 ? result : b + result;
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Efficiently raise num to a power with modular reduction.
|
|
1319
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
1320
|
+
* Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
|
|
1321
|
+
* modulus instead of relying on the `power===0/1` fast paths to normalize it.
|
|
1322
|
+
* @param num - Base value.
|
|
1323
|
+
* @param power - Exponent value.
|
|
1324
|
+
* @param modulo - Reduction modulus.
|
|
1325
|
+
* @returns Modular exponentiation result.
|
|
1326
|
+
* @throws If the modulus or exponent is invalid. {@link Error}
|
|
1327
|
+
* @example
|
|
1328
|
+
* Raise one bigint to a modular power.
|
|
1329
|
+
*
|
|
1330
|
+
* ```ts
|
|
1331
|
+
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
|
1332
|
+
* ```
|
|
1333
|
+
*/
|
|
1334
|
+
function pow(num, power, modulo) {
|
|
1335
|
+
if (modulo <= _1n$2) throw new Error("pow: expected modulus > 1, got " + modulo);
|
|
1336
|
+
if (typeof power !== "bigint") throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
|
|
1337
|
+
if (power < _0n$4) throw new Error("invalid exponent, negatives unsupported");
|
|
1338
|
+
if (power === _0n$4) return _1n$2;
|
|
1339
|
+
if (power === _1n$2) return num;
|
|
1340
|
+
let d = num % modulo;
|
|
1341
|
+
if (d < _0n$4) d += modulo;
|
|
1342
|
+
if (power < POW_WINDOWED_MIN) {
|
|
1343
|
+
let p = _1n$2;
|
|
1344
|
+
while (power > _0n$4) {
|
|
1345
|
+
if (power & _1n$2) p = p * d % modulo;
|
|
1346
|
+
d = d * d % modulo;
|
|
1347
|
+
power >>= _1n$2;
|
|
1348
|
+
}
|
|
1349
|
+
return p;
|
|
1350
|
+
}
|
|
1351
|
+
const digits = [];
|
|
1352
|
+
while (power > _0n$4) {
|
|
1353
|
+
digits.push(Number(power & _15n));
|
|
1354
|
+
power >>= _4n$2;
|
|
1355
|
+
}
|
|
1356
|
+
const table = new Array(16);
|
|
1357
|
+
table[0] = _1n$2;
|
|
1358
|
+
table[1] = d;
|
|
1359
|
+
for (let i = 2; i < 16; i++) table[i] = table[i - 1] * d % modulo;
|
|
1360
|
+
let p = table[digits[digits.length - 1]];
|
|
1361
|
+
for (let w = digits.length - 2; w >= 0; w--) {
|
|
1362
|
+
p = p * p % modulo;
|
|
1363
|
+
p = p * p % modulo;
|
|
1364
|
+
p = p * p % modulo;
|
|
1365
|
+
p = p * p % modulo;
|
|
1366
|
+
const digit = digits[w];
|
|
1367
|
+
if (digit !== 0) p = p * table[digit] % modulo;
|
|
1368
|
+
}
|
|
1369
|
+
return p;
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
|
|
1373
|
+
* Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
|
|
1374
|
+
* modulus; the `power===0` fast path intentionally returns the input unchanged.
|
|
1375
|
+
* @param x - Base value.
|
|
1376
|
+
* @param power - Number of squarings.
|
|
1377
|
+
* @param modulo - Reduction modulus.
|
|
1378
|
+
* @returns Repeated-squaring result.
|
|
1379
|
+
* @throws If the exponent is negative. {@link Error}
|
|
1380
|
+
* @example
|
|
1381
|
+
* Apply repeated squaring inside one field.
|
|
1382
|
+
*
|
|
1383
|
+
* ```ts
|
|
1384
|
+
* pow2(3n, 2n, 11n);
|
|
1385
|
+
* ```
|
|
1386
|
+
*/
|
|
1387
|
+
function pow2(x, power, modulo) {
|
|
1388
|
+
if (modulo <= _1n$2) throw new Error("pow2: expected modulus > 1, got " + modulo);
|
|
1389
|
+
if (power < _0n$4) throw new Error("pow2: expected non-negative exponent, got " + power);
|
|
1390
|
+
let res = x;
|
|
1391
|
+
while (power-- > _0n$4) {
|
|
1392
|
+
res *= res;
|
|
1393
|
+
res %= modulo;
|
|
1394
|
+
}
|
|
1395
|
+
return res;
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Inverses number over modulo.
|
|
1399
|
+
* Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
|
|
1400
|
+
* @param number - Value to invert.
|
|
1401
|
+
* @param modulo - Modulus greater than 1.
|
|
1402
|
+
* @returns Multiplicative inverse.
|
|
1403
|
+
* @throws If the modulus is invalid or the inverse does not exist. {@link Error}
|
|
1404
|
+
* @example
|
|
1405
|
+
* Compute one modular inverse with the extended Euclidean algorithm.
|
|
1406
|
+
*
|
|
1407
|
+
* ```ts
|
|
1408
|
+
* invert(3n, 11n);
|
|
1409
|
+
* ```
|
|
1410
|
+
*/
|
|
1411
|
+
function invert(number, modulo) {
|
|
1412
|
+
if (number === _0n$4) throw new Error("invert: expected non-zero number");
|
|
1413
|
+
if (modulo <= _1n$2) throw new Error("invert: expected modulus > 1, got " + modulo);
|
|
1414
|
+
let a = mod(number, modulo);
|
|
1415
|
+
let b = modulo;
|
|
1416
|
+
let x = _0n$4, u = _1n$2;
|
|
1417
|
+
while (a !== _0n$4) {
|
|
1418
|
+
const q = b / a;
|
|
1419
|
+
const r = b - a * q;
|
|
1420
|
+
const m = x - u * q;
|
|
1421
|
+
b = a, a = r, x = u, u = m;
|
|
1422
|
+
}
|
|
1423
|
+
if (b !== _1n$2) throw new Error("invert: does not exist");
|
|
1424
|
+
return mod(x, modulo);
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.
|
|
1428
|
+
*
|
|
1429
|
+
* Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the
|
|
1430
|
+
* underlying square-and-multiply has the same control flow for every secret `a`: there is no
|
|
1431
|
+
* data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style
|
|
1432
|
+
* ECDSA nonce-inversion attacks). This is only "algorithmically" constant-time — JS bigint
|
|
1433
|
+
* multiplication/reduction is still value-dependent — and it is roughly 4x slower than
|
|
1434
|
+
* {@link invert}.
|
|
1435
|
+
*
|
|
1436
|
+
* REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be
|
|
1437
|
+
* a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error
|
|
1438
|
+
* instead of returning a wrong value.
|
|
1439
|
+
* @param a - Value to invert.
|
|
1440
|
+
* @param prime - Prime modulus.
|
|
1441
|
+
* @returns Multiplicative inverse in `[1, prime)`.
|
|
1442
|
+
* @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.
|
|
1443
|
+
* {@link Error}
|
|
1444
|
+
* @example
|
|
1445
|
+
* Compute one modular inverse without secret-dependent branching.
|
|
1446
|
+
*
|
|
1447
|
+
* ```ts
|
|
1448
|
+
* invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)
|
|
1449
|
+
* ```
|
|
1450
|
+
*/
|
|
1451
|
+
function invertCt(a, prime) {
|
|
1452
|
+
if (prime <= _1n$2) throw new Error("invertCt: expected prime modulus > 1, got " + prime);
|
|
1453
|
+
const an = mod(a, prime);
|
|
1454
|
+
if (an === _0n$4) throw new Error("invertCt: expected non-zero number");
|
|
1455
|
+
const inverse = pow(an, prime - _2n$2, prime);
|
|
1456
|
+
if (mod(an * inverse, prime) !== _1n$2) throw new Error("invertCt: does not exist");
|
|
1457
|
+
return inverse;
|
|
1458
|
+
}
|
|
1459
|
+
function assertIsSquare(Fp, root, n) {
|
|
1460
|
+
const F = Fp;
|
|
1461
|
+
if (!F.eql(F.sqr(root), n)) throw new Error("Cannot find square root");
|
|
1462
|
+
}
|
|
1463
|
+
function aoddModulus(order, fnName) {
|
|
1464
|
+
if ((order & _1n$2) === _0n$4) throw new Error(fnName + ": expected odd modulus, got " + order);
|
|
1465
|
+
}
|
|
1466
|
+
function sqrt3mod4(Fp, n) {
|
|
1467
|
+
const F = Fp;
|
|
1468
|
+
const p1div4 = (F.ORDER + _1n$2) / _4n$2;
|
|
1469
|
+
const root = F.pow(n, p1div4);
|
|
1470
|
+
assertIsSquare(F, root, n);
|
|
1471
|
+
return root;
|
|
1472
|
+
}
|
|
1473
|
+
function sqrt5mod8(Fp, n) {
|
|
1474
|
+
const F = Fp;
|
|
1475
|
+
const p5div8 = (F.ORDER - _5n) / _8n;
|
|
1476
|
+
const n2 = F.mul(n, _2n$2);
|
|
1477
|
+
const v = F.pow(n2, p5div8);
|
|
1478
|
+
const nv = F.mul(n, v);
|
|
1479
|
+
const i = F.mul(F.mul(nv, _2n$2), v);
|
|
1480
|
+
const root = F.mul(nv, F.sub(i, F.ONE));
|
|
1481
|
+
assertIsSquare(F, root, n);
|
|
1482
|
+
return root;
|
|
1483
|
+
}
|
|
1484
|
+
function sqrt9mod16(P) {
|
|
1485
|
+
const Fp_ = Field(P);
|
|
1486
|
+
const tn = tonelliShanks(P);
|
|
1487
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
1488
|
+
const c2 = tn(Fp_, c1);
|
|
1489
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
1490
|
+
const c4 = (P + _7n) / _16n;
|
|
1491
|
+
return ((Fp, n) => {
|
|
1492
|
+
const F = Fp;
|
|
1493
|
+
let tv1 = F.pow(n, c4);
|
|
1494
|
+
let tv2 = F.mul(tv1, c1);
|
|
1495
|
+
const tv3 = F.mul(tv1, c2);
|
|
1496
|
+
const tv4 = F.mul(tv1, c3);
|
|
1497
|
+
const e1 = F.eql(F.sqr(tv2), n);
|
|
1498
|
+
const e2 = F.eql(F.sqr(tv3), n);
|
|
1499
|
+
tv1 = F.cmov(tv1, tv2, e1);
|
|
1500
|
+
tv2 = F.cmov(tv4, tv3, e2);
|
|
1501
|
+
const e3 = F.eql(F.sqr(tv2), n);
|
|
1502
|
+
const root = F.cmov(tv1, tv2, e3);
|
|
1503
|
+
assertIsSquare(F, root, n);
|
|
1504
|
+
return root;
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Tonelli-Shanks square root search algorithm.
|
|
1509
|
+
* This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
|
|
1510
|
+
* and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
|
|
1511
|
+
* 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
|
|
1512
|
+
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
|
1513
|
+
* @param P - field order
|
|
1514
|
+
* @returns function that takes field Fp (created from P) and number n
|
|
1515
|
+
* @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
|
|
1516
|
+
* @example
|
|
1517
|
+
* Construct a square-root helper for primes that need Tonelli-Shanks.
|
|
1518
|
+
*
|
|
1519
|
+
* ```ts
|
|
1520
|
+
* import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
|
|
1521
|
+
* const Fp = Field(17n);
|
|
1522
|
+
* const sqrt = tonelliShanks(17n)(Fp, 4n);
|
|
1523
|
+
* ```
|
|
1524
|
+
*/
|
|
1525
|
+
function tonelliShanks(P) {
|
|
1526
|
+
if (P < _3n$1) throw new Error("sqrt is not defined for small field");
|
|
1527
|
+
aoddModulus(P, "tonelliShanks");
|
|
1528
|
+
let Q = P - _1n$2;
|
|
1529
|
+
let S = 0;
|
|
1530
|
+
while (Q % _2n$2 === _0n$4) {
|
|
1531
|
+
Q /= _2n$2;
|
|
1532
|
+
S++;
|
|
1533
|
+
}
|
|
1534
|
+
let Z = _2n$2;
|
|
1535
|
+
const _Fp = Field(P);
|
|
1536
|
+
while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
|
|
1537
|
+
if (S === 1) return sqrt3mod4;
|
|
1538
|
+
let cc = _Fp.pow(Z, Q);
|
|
1539
|
+
const Q1div2 = (Q + _1n$2) / _2n$2;
|
|
1540
|
+
return function tonelliSlow(Fp, n) {
|
|
1541
|
+
const F = Fp;
|
|
1542
|
+
if (F.is0(n)) return n;
|
|
1543
|
+
if (FpLegendre(F, n) !== 1) throw new Error("Cannot find square root");
|
|
1544
|
+
let M = S;
|
|
1545
|
+
let c = F.mul(F.ONE, cc);
|
|
1546
|
+
let t = F.pow(n, Q);
|
|
1547
|
+
let R = F.pow(n, Q1div2);
|
|
1548
|
+
while (!F.eql(t, F.ONE)) {
|
|
1549
|
+
if (F.is0(t)) throw new Error("Cannot find square root: probably non-prime P");
|
|
1550
|
+
let i = 1;
|
|
1551
|
+
let t_tmp = F.sqr(t);
|
|
1552
|
+
while (!F.eql(t_tmp, F.ONE)) {
|
|
1553
|
+
i++;
|
|
1554
|
+
t_tmp = F.sqr(t_tmp);
|
|
1555
|
+
if (i === M) throw new Error("Cannot find square root");
|
|
1556
|
+
}
|
|
1557
|
+
const exponent = _1n$2 << BigInt(M - i - 1);
|
|
1558
|
+
const b = F.pow(c, exponent);
|
|
1559
|
+
M = i;
|
|
1560
|
+
c = F.sqr(b);
|
|
1561
|
+
t = F.mul(t, c);
|
|
1562
|
+
R = F.mul(R, b);
|
|
1563
|
+
}
|
|
1564
|
+
return R;
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Square root for a finite field. Will try optimized versions first:
|
|
1569
|
+
*
|
|
1570
|
+
* 1. P ≡ 3 (mod 4)
|
|
1571
|
+
* 2. P ≡ 5 (mod 8)
|
|
1572
|
+
* 3. P ≡ 9 (mod 16)
|
|
1573
|
+
* 4. Tonelli-Shanks algorithm
|
|
1574
|
+
*
|
|
1575
|
+
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
|
1576
|
+
* For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
|
|
1577
|
+
* (used for hash-to-curve).
|
|
1578
|
+
* @param P - Field order.
|
|
1579
|
+
* @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
|
|
1580
|
+
* behavior and this selector assumes prime-field-style integer moduli.
|
|
1581
|
+
* @throws If the field is unsupported or the square root does not exist. {@link Error}
|
|
1582
|
+
* @example
|
|
1583
|
+
* Choose the square-root helper appropriate for one field modulus.
|
|
1584
|
+
*
|
|
1585
|
+
* ```ts
|
|
1586
|
+
* import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
|
|
1587
|
+
* const Fp = Field(17n);
|
|
1588
|
+
* const sqrt = FpSqrt(17n)(Fp, 4n);
|
|
1589
|
+
* ```
|
|
1590
|
+
*/
|
|
1591
|
+
function FpSqrt(P) {
|
|
1592
|
+
aoddModulus(P, "Fp.sqrt");
|
|
1593
|
+
if (P % _4n$2 === _3n$1) return sqrt3mod4;
|
|
1594
|
+
if (P % _8n === _5n) return sqrt5mod8;
|
|
1595
|
+
if (P % _16n === _9n) return sqrt9mod16(P);
|
|
1596
|
+
return tonelliShanks(P);
|
|
1597
|
+
}
|
|
1598
|
+
var FIELD_FIELDS = [
|
|
1599
|
+
"create",
|
|
1600
|
+
"isValid",
|
|
1601
|
+
"is0",
|
|
1602
|
+
"neg",
|
|
1603
|
+
"inv",
|
|
1604
|
+
"sqrt",
|
|
1605
|
+
"sqr",
|
|
1606
|
+
"eql",
|
|
1607
|
+
"add",
|
|
1608
|
+
"sub",
|
|
1609
|
+
"mul",
|
|
1610
|
+
"pow",
|
|
1611
|
+
"div",
|
|
1612
|
+
"addN",
|
|
1613
|
+
"subN",
|
|
1614
|
+
"mulN",
|
|
1615
|
+
"sqrN"
|
|
1616
|
+
];
|
|
1617
|
+
/**
|
|
1618
|
+
* @param field - Field implementation.
|
|
1619
|
+
* @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
|
|
1620
|
+
* does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
|
|
1621
|
+
* field-specific extras beyond positive `BYTES` / `BITS`.
|
|
1622
|
+
* @throws If the field shape or numeric metadata are invalid. {@link Error}
|
|
1623
|
+
* @example
|
|
1624
|
+
* Check that a field implementation exposes the operations curve code expects.
|
|
1625
|
+
*
|
|
1626
|
+
* ```ts
|
|
1627
|
+
* import { Field, validateField } from '@noble/curves/abstract/modular.js';
|
|
1628
|
+
* const Fp = validateField(Field(17n));
|
|
1629
|
+
* ```
|
|
1630
|
+
*/
|
|
1631
|
+
function validateField(field) {
|
|
1632
|
+
aobject(field, "field");
|
|
1633
|
+
if (typeof field.ORDER !== "bigint") throw new TypeError("param \"ORDER\" is invalid: expected bigint, got " + typeof field.ORDER);
|
|
1634
|
+
asafenumber(field.BYTES, "BYTES");
|
|
1635
|
+
asafenumber(field.BITS, "BITS");
|
|
1636
|
+
for (const name of FIELD_FIELDS) afunction(field[name], "field." + name);
|
|
1637
|
+
if (field.BYTES < 1 || field.BITS < 1) throw new Error("invalid field: expected BYTES/BITS > 0");
|
|
1638
|
+
if (field.ORDER <= _1n$2) throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
|
|
1639
|
+
return field;
|
|
1640
|
+
}
|
|
1641
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
1642
|
+
validateField(Fp);
|
|
1643
|
+
aarray(nums, "nums");
|
|
1644
|
+
abool(passZero, "passZero");
|
|
1645
|
+
const F = Fp;
|
|
1646
|
+
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
|
|
1647
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
1648
|
+
if (F.is0(num)) return acc;
|
|
1649
|
+
inverted[i] = acc;
|
|
1650
|
+
return F.mul(acc, num);
|
|
1651
|
+
}, F.ONE);
|
|
1652
|
+
const invertedAcc = F.inv(multipliedAcc);
|
|
1653
|
+
nums.reduceRight((acc, num, i) => {
|
|
1654
|
+
if (F.is0(num)) return acc;
|
|
1655
|
+
inverted[i] = F.mul(acc, inverted[i]);
|
|
1656
|
+
return F.mul(acc, num);
|
|
1657
|
+
}, invertedAcc);
|
|
1658
|
+
return inverted;
|
|
1659
|
+
}
|
|
1660
|
+
/**
|
|
1661
|
+
* Legendre symbol.
|
|
1662
|
+
* Legendre constant is used to calculate Legendre symbol (a | p)
|
|
1663
|
+
* which denotes the value of a^((p-1)/2) (mod p).
|
|
1664
|
+
*
|
|
1665
|
+
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
|
1666
|
+
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
|
1667
|
+
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
|
1668
|
+
* @param Fp - Field implementation.
|
|
1669
|
+
* @param n - Value to inspect.
|
|
1670
|
+
* @returns Legendre symbol.
|
|
1671
|
+
* @throws If the powered value does not match a valid Legendre symbol. {@link Error}
|
|
1672
|
+
* @example
|
|
1673
|
+
* Compute the Legendre symbol of one field element.
|
|
1674
|
+
*
|
|
1675
|
+
* ```ts
|
|
1676
|
+
* import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
|
|
1677
|
+
* const Fp = Field(17n);
|
|
1678
|
+
* const symbol = FpLegendre(Fp, 4n);
|
|
1679
|
+
* ```
|
|
1680
|
+
*/
|
|
1681
|
+
function FpLegendre(Fp, n) {
|
|
1682
|
+
validateField(Fp);
|
|
1683
|
+
const F = Fp;
|
|
1684
|
+
aoddModulus(F.ORDER, "FpLegendre");
|
|
1685
|
+
const p1mod2 = (F.ORDER - _1n$2) / _2n$2;
|
|
1686
|
+
const powered = F.pow(n, p1mod2);
|
|
1687
|
+
const yes = F.eql(powered, F.ONE);
|
|
1688
|
+
const zero = F.eql(powered, F.ZERO);
|
|
1689
|
+
const no = F.eql(powered, F.neg(F.ONE));
|
|
1690
|
+
if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
|
|
1691
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* @param n - Curve order. Callers are expected to pass a positive order.
|
|
1695
|
+
* @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
|
|
1696
|
+
* value when overriding the derived bit length.
|
|
1697
|
+
* @returns Byte and bit lengths.
|
|
1698
|
+
* @throws If the order or cached bit length is invalid. {@link Error}
|
|
1699
|
+
* @example
|
|
1700
|
+
* Measure the encoding sizes needed for one modulus.
|
|
1701
|
+
*
|
|
1702
|
+
* ```ts
|
|
1703
|
+
* nLength(255n);
|
|
1704
|
+
* ```
|
|
1705
|
+
*/
|
|
1706
|
+
function nLength(n, nBitLength) {
|
|
1707
|
+
if (nBitLength !== void 0) anumber(nBitLength);
|
|
1708
|
+
if (n <= _0n$4) throw new Error("invalid n length: expected positive n, got " + n);
|
|
1709
|
+
if (nBitLength !== void 0 && nBitLength < 1) throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
|
|
1710
|
+
const bits = bitLen(n);
|
|
1711
|
+
if (nBitLength !== void 0 && nBitLength < bits) throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
|
|
1712
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
|
|
1713
|
+
return {
|
|
1714
|
+
nBitLength: _nBitLength,
|
|
1715
|
+
nByteLength: Math.ceil(_nBitLength / 8)
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
|
|
1719
|
+
var _Field = class {
|
|
1720
|
+
ORDER;
|
|
1721
|
+
BITS;
|
|
1722
|
+
BYTES;
|
|
1723
|
+
isLE;
|
|
1724
|
+
ZERO = _0n$4;
|
|
1725
|
+
ONE = _1n$2;
|
|
1726
|
+
_lengths;
|
|
1727
|
+
_mod;
|
|
1728
|
+
constructor(ORDER, opts = {}) {
|
|
1729
|
+
if (ORDER <= _1n$2) throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
|
|
1730
|
+
let _nbitLength = void 0;
|
|
1731
|
+
this.isLE = false;
|
|
1732
|
+
if (opts != null && typeof opts === "object") {
|
|
1733
|
+
if (typeof opts.BITS === "number") _nbitLength = opts.BITS;
|
|
1734
|
+
if (typeof opts.sqrt === "function") Object.defineProperty(this, "sqrt", {
|
|
1735
|
+
value: opts.sqrt,
|
|
1736
|
+
enumerable: true
|
|
1737
|
+
});
|
|
1738
|
+
if (typeof opts.isLE === "boolean") this.isLE = opts.isLE;
|
|
1739
|
+
if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());
|
|
1740
|
+
if (typeof opts.modFromBytes === "boolean") this._mod = opts.modFromBytes;
|
|
1741
|
+
}
|
|
1742
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
1743
|
+
if (nByteLength > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
1744
|
+
this.ORDER = ORDER;
|
|
1745
|
+
this.BITS = nBitLength;
|
|
1746
|
+
this.BYTES = nByteLength;
|
|
1747
|
+
Object.freeze(this);
|
|
1748
|
+
}
|
|
1749
|
+
create(num) {
|
|
1750
|
+
return mod(num, this.ORDER);
|
|
1751
|
+
}
|
|
1752
|
+
isValid(num) {
|
|
1753
|
+
if (typeof num !== "bigint") throw new TypeError("invalid field element: expected bigint, got " + typeof num);
|
|
1754
|
+
return _0n$4 <= num && num < this.ORDER;
|
|
1755
|
+
}
|
|
1756
|
+
is0(num) {
|
|
1757
|
+
return num === _0n$4;
|
|
1758
|
+
}
|
|
1759
|
+
isValidNot0(num) {
|
|
1760
|
+
return !this.is0(num) && this.isValid(num);
|
|
1761
|
+
}
|
|
1762
|
+
isOdd(num) {
|
|
1763
|
+
return (num & _1n$2) === _1n$2;
|
|
1764
|
+
}
|
|
1765
|
+
neg(num) {
|
|
1766
|
+
return mod(-num, this.ORDER);
|
|
1767
|
+
}
|
|
1768
|
+
eql(lhs, rhs) {
|
|
1769
|
+
return lhs === rhs;
|
|
1770
|
+
}
|
|
1771
|
+
sqr(num) {
|
|
1772
|
+
return mod(num * num, this.ORDER);
|
|
1773
|
+
}
|
|
1774
|
+
add(lhs, rhs) {
|
|
1775
|
+
return mod(lhs + rhs, this.ORDER);
|
|
1776
|
+
}
|
|
1777
|
+
sub(lhs, rhs) {
|
|
1778
|
+
return mod(lhs - rhs, this.ORDER);
|
|
1779
|
+
}
|
|
1780
|
+
mul(lhs, rhs) {
|
|
1781
|
+
return mod(lhs * rhs, this.ORDER);
|
|
1782
|
+
}
|
|
1783
|
+
pow(num, power) {
|
|
1784
|
+
return pow(num, power, this.ORDER);
|
|
1785
|
+
}
|
|
1786
|
+
div(lhs, rhs) {
|
|
1787
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
1788
|
+
}
|
|
1789
|
+
sqrN(num) {
|
|
1790
|
+
return num * num;
|
|
1791
|
+
}
|
|
1792
|
+
addN(lhs, rhs) {
|
|
1793
|
+
return lhs + rhs;
|
|
1794
|
+
}
|
|
1795
|
+
subN(lhs, rhs) {
|
|
1796
|
+
return lhs - rhs;
|
|
1797
|
+
}
|
|
1798
|
+
mulN(lhs, rhs) {
|
|
1799
|
+
return lhs * rhs;
|
|
1800
|
+
}
|
|
1801
|
+
inv(num) {
|
|
1802
|
+
return invert(num, this.ORDER);
|
|
1803
|
+
}
|
|
1804
|
+
sqrt(num) {
|
|
1805
|
+
let sqrt = FIELD_SQRT.get(this);
|
|
1806
|
+
if (!sqrt) FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
|
|
1807
|
+
return sqrt(this, num);
|
|
1808
|
+
}
|
|
1809
|
+
toBytes(num) {
|
|
1810
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
1811
|
+
}
|
|
1812
|
+
fromBytes(bytes, skipValidation = false) {
|
|
1813
|
+
abytes(bytes);
|
|
1814
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
1815
|
+
if (allowedLengths) {
|
|
1816
|
+
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
1817
|
+
const padded = new Uint8Array(BYTES);
|
|
1818
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
1819
|
+
bytes = padded;
|
|
1820
|
+
}
|
|
1821
|
+
if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
1822
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
1823
|
+
if (modFromBytes) scalar = mod(scalar, ORDER);
|
|
1824
|
+
if (!skipValidation) {
|
|
1825
|
+
if (!this.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
|
|
1826
|
+
}
|
|
1827
|
+
return scalar;
|
|
1828
|
+
}
|
|
1829
|
+
invertBatch(lst) {
|
|
1830
|
+
return FpInvertBatch(this, lst, true);
|
|
1831
|
+
}
|
|
1832
|
+
cmov(a, b, condition) {
|
|
1833
|
+
abool(condition, "condition");
|
|
1834
|
+
return condition ? b : a;
|
|
1835
|
+
}
|
|
1836
|
+
};
|
|
1837
|
+
/**
|
|
1838
|
+
* Creates a finite field. Major performance optimizations:
|
|
1839
|
+
* * 1. Denormalized operations like mulN instead of mul.
|
|
1840
|
+
* * 2. Identical object shape: never add or remove keys.
|
|
1841
|
+
* * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
|
|
1842
|
+
* Fragile: always run a benchmark on a change.
|
|
1843
|
+
* Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
|
|
1844
|
+
* all elements for performance and protocol-flexibility reasons; callers are responsible for
|
|
1845
|
+
* supplying valid elements when they need canonical field behavior.
|
|
1846
|
+
* This is low-level code, please make sure you know what you're doing.
|
|
1847
|
+
*
|
|
1848
|
+
* Note about field properties:
|
|
1849
|
+
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
|
1850
|
+
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
|
1851
|
+
*
|
|
1852
|
+
* @param ORDER - field order, probably prime, or could be composite
|
|
1853
|
+
* @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
|
|
1854
|
+
* @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
|
|
1855
|
+
* into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
|
|
1856
|
+
* @example
|
|
1857
|
+
* Construct one prime field with optional overrides.
|
|
1858
|
+
*
|
|
1859
|
+
* ```ts
|
|
1860
|
+
* Field(11n);
|
|
1861
|
+
* ```
|
|
1862
|
+
*/
|
|
1863
|
+
function Field(ORDER, opts = {}) {
|
|
1864
|
+
Object.freeze(_Field.prototype);
|
|
1865
|
+
return new _Field(ORDER, opts);
|
|
1866
|
+
}
|
|
1867
|
+
/**
|
|
1868
|
+
* Returns total number of bytes consumed by the field element.
|
|
1869
|
+
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
|
1870
|
+
* @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
|
|
1871
|
+
* order greater than 1.
|
|
1872
|
+
* @returns byte length of field
|
|
1873
|
+
* @throws If the field order is not a bigint. {@link Error}
|
|
1874
|
+
* @example
|
|
1875
|
+
* Read the fixed-width byte length of one field.
|
|
1876
|
+
*
|
|
1877
|
+
* ```ts
|
|
1878
|
+
* getFieldBytesLength(255n);
|
|
1879
|
+
* ```
|
|
1880
|
+
*/
|
|
1881
|
+
function getFieldBytesLength(fieldOrder) {
|
|
1882
|
+
if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
|
|
1883
|
+
if (fieldOrder <= _1n$2) throw new Error("field order must be greater than 1");
|
|
1884
|
+
const bitLength = bitLen(fieldOrder - _1n$2);
|
|
1885
|
+
return Math.ceil(bitLength / 8);
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Returns minimal amount of bytes that can be safely reduced
|
|
1889
|
+
* by field order.
|
|
1890
|
+
* Should be 2^-128 for 128-bit curve such as P256.
|
|
1891
|
+
* This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
|
|
1892
|
+
* absolute floor for policy reasons.
|
|
1893
|
+
* @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
|
|
1894
|
+
* @returns byte length of target hash
|
|
1895
|
+
* @throws If the field order is invalid. {@link Error}
|
|
1896
|
+
* @example
|
|
1897
|
+
* Compute the minimum hash length needed for field reduction.
|
|
1898
|
+
*
|
|
1899
|
+
* ```ts
|
|
1900
|
+
* getMinHashLength(255n);
|
|
1901
|
+
* ```
|
|
1902
|
+
*/
|
|
1903
|
+
function getMinHashLength(fieldOrder) {
|
|
1904
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
1905
|
+
return length + Math.ceil(length / 2);
|
|
1906
|
+
}
|
|
1907
|
+
/**
|
|
1908
|
+
* "Constant-time" private key generation utility.
|
|
1909
|
+
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
|
1910
|
+
* and convert them into private scalar, with the modulo bias being negligible.
|
|
1911
|
+
* Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
|
|
1912
|
+
* 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
|
|
1913
|
+
* accidentally acceptable for real scalar derivation.
|
|
1914
|
+
* 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},
|
|
1915
|
+
* {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
|
|
1916
|
+
* {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
|
|
1917
|
+
* `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
|
|
1918
|
+
* @param key - Uniform input bytes.
|
|
1919
|
+
* @param fieldOrder - Size of subgroup.
|
|
1920
|
+
* @param isLE - interpret hash bytes as LE num
|
|
1921
|
+
* @returns valid private scalar
|
|
1922
|
+
* @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
|
|
1923
|
+
* @example
|
|
1924
|
+
* Map hash output into a private scalar range.
|
|
1925
|
+
*
|
|
1926
|
+
* ```ts
|
|
1927
|
+
* mapHashToField(new Uint8Array(48).fill(1), 255n);
|
|
1928
|
+
* ```
|
|
1929
|
+
*/
|
|
1930
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
1931
|
+
abytes(key);
|
|
1932
|
+
const len = key.length;
|
|
1933
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
1934
|
+
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
|
|
1935
|
+
if (len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
1936
|
+
const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$2) + _1n$2;
|
|
1937
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
1938
|
+
}
|
|
1939
|
+
//#endregion
|
|
1940
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js
|
|
1941
|
+
/**
|
|
1942
|
+
* Methods for elliptic curve multiplication by scalars.
|
|
1943
|
+
* Contains wNAF-based ScalarMultiplier, pippenger.
|
|
1944
|
+
* @module
|
|
1945
|
+
*/
|
|
1946
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1947
|
+
var _0n$3 = /* @__PURE__ */ BigInt(0);
|
|
1948
|
+
var _1n$1 = /* @__PURE__ */ BigInt(1);
|
|
1949
|
+
var _4n$1 = /* @__PURE__ */ BigInt(4);
|
|
1950
|
+
var BLIND_BYTES = 16;
|
|
1951
|
+
var BLIND_BITS = 128;
|
|
1952
|
+
var FW_WINDOW = 5;
|
|
1953
|
+
var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
|
|
1954
|
+
/**
|
|
1955
|
+
* Validates the static surface of a point constructor.
|
|
1956
|
+
* This is only a cheap sanity check for the constructor hooks and fields consumed by generic
|
|
1957
|
+
* factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
|
|
1958
|
+
* @param Point - Runtime point constructor.
|
|
1959
|
+
* @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
|
|
1960
|
+
* @example
|
|
1961
|
+
* Check that one point constructor exposes the static hooks generic helpers need.
|
|
1962
|
+
*
|
|
1963
|
+
* ```ts
|
|
1964
|
+
* import { ed25519 } from '@noble/curves/ed25519.js';
|
|
1965
|
+
* import { validatePointCons } from '@noble/curves/abstract/curve.js';
|
|
1966
|
+
* validatePointCons(ed25519.Point);
|
|
1967
|
+
* ```
|
|
1968
|
+
*/
|
|
1969
|
+
function validatePointCons(Point) {
|
|
1970
|
+
const pc = Point;
|
|
1971
|
+
if (typeof pc !== "function") throw new TypeError("\"Point\" expected constructor, got type=" + typeof Point);
|
|
1972
|
+
afunction(pc.fromAffine, "Point.fromAffine");
|
|
1973
|
+
afunction(pc.fromBytes, "Point.fromBytes");
|
|
1974
|
+
afunction(pc.fromHex, "Point.fromHex");
|
|
1975
|
+
aobject(pc.BASE, "Point.BASE");
|
|
1976
|
+
aobject(pc.ZERO, "Point.ZERO");
|
|
1977
|
+
validateField(pc.Fp);
|
|
1978
|
+
validateField(pc.Fn);
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Takes a bunch of Projective Points but executes only one
|
|
1982
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
1983
|
+
* so this improves performance massively.
|
|
1984
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
1985
|
+
* Input points are left unchanged; the normalized points are returned as fresh instances.
|
|
1986
|
+
* @param c - Point constructor.
|
|
1987
|
+
* @param points - Projective points.
|
|
1988
|
+
* @returns Fresh projective points reconstructed from normalized affine coordinates.
|
|
1989
|
+
* @example
|
|
1990
|
+
* Batch-normalize projective points with a single shared inversion.
|
|
1991
|
+
*
|
|
1992
|
+
* ```ts
|
|
1993
|
+
* import { normalizeZ } from '@noble/curves/abstract/curve.js';
|
|
1994
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
1995
|
+
* const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
|
|
1996
|
+
* ```
|
|
1997
|
+
*/
|
|
1998
|
+
function normalizeZ(c, points) {
|
|
1999
|
+
validatePointCons(c);
|
|
2000
|
+
validateMSMPoints(points, c);
|
|
2001
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
2002
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
2003
|
+
}
|
|
2004
|
+
function validateW(W, bits, min = 1) {
|
|
2005
|
+
if (!Number.isSafeInteger(W) || W < min || W > bits) throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
|
|
2006
|
+
}
|
|
2007
|
+
function validateTableBytes(numPoints, fpBytes) {
|
|
2008
|
+
const bytes = numPoints * (4 * fpBytes + 128);
|
|
2009
|
+
if (bytes > TABLE_BYTES_MAX) throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Probes an RNG once, at construction time: returns `undefined` when it is unavailable —
|
|
2013
|
+
* throws or returns malformed bytes — so callers can downgrade to their unblinded /
|
|
2014
|
+
* deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template
|
|
2015
|
+
* hardening), not a correctness or key-secrecy requirement, so availability-based
|
|
2016
|
+
* downgrade is acceptable.
|
|
2017
|
+
*
|
|
2018
|
+
* The downgrade decision is deliberately static. After a successful probe the RNG becomes
|
|
2019
|
+
* part of the trusted contract: later misbehavior must fail closed in per-call validation
|
|
2020
|
+
* (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip
|
|
2021
|
+
* blinding on demand. A probe can only ever classify broken environments, not adversarial
|
|
2022
|
+
* RNGs: a stateful RNG can always behave while probed and misbehave later.
|
|
2023
|
+
* @param randomBytes - RNG to probe, or `undefined` when the environment provides none.
|
|
2024
|
+
* @param length - Byte length requested from the probe call.
|
|
2025
|
+
* @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.
|
|
2026
|
+
* @example
|
|
2027
|
+
* Probe an RNG once before enabling scalar blinding.
|
|
2028
|
+
*
|
|
2029
|
+
* ```ts
|
|
2030
|
+
* import { probeRandomBytes } from '@noble/curves/abstract/curve.js';
|
|
2031
|
+
* import { randomBytes } from '@noble/hashes/utils.js';
|
|
2032
|
+
* const rng = probeRandomBytes(randomBytes, 16);
|
|
2033
|
+
* ```
|
|
2034
|
+
*/
|
|
2035
|
+
function probeRandomBytes(randomBytes, length) {
|
|
2036
|
+
if (randomBytes === void 0) return void 0;
|
|
2037
|
+
afunction(randomBytes, "randomBytes");
|
|
2038
|
+
try {
|
|
2039
|
+
const probe = randomBytes(length);
|
|
2040
|
+
if (!isBytes(probe) || probe.length !== length) return void 0;
|
|
2041
|
+
} catch {
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
return randomBytes;
|
|
2045
|
+
}
|
|
2046
|
+
function validateMSMPoints(points, c) {
|
|
2047
|
+
aarray(points, "points");
|
|
2048
|
+
points.forEach((p, i) => {
|
|
2049
|
+
if (!(p instanceof c)) throw new Error("invalid point at index " + i);
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
function validateMSMScalars(scalars, field, maxScalar) {
|
|
2053
|
+
if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
|
|
2054
|
+
scalars.forEach((s, i) => {
|
|
2055
|
+
if (!(maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar)) throw new Error("invalid scalar at index " + i);
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
2059
|
+
function getWindowSize(P) {
|
|
2060
|
+
return pointWindowSizes.get(P) || 1;
|
|
2061
|
+
}
|
|
2062
|
+
/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */
|
|
2063
|
+
function oddMultiples(p, size) {
|
|
2064
|
+
const dbl = p.double();
|
|
2065
|
+
const t = [p];
|
|
2066
|
+
for (let j = 1; j < size; j++) t.push(t[j - 1].add(dbl));
|
|
2067
|
+
return t;
|
|
2068
|
+
}
|
|
2069
|
+
/**
|
|
2070
|
+
* Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with
|
|
2071
|
+
* |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).
|
|
2072
|
+
*/
|
|
2073
|
+
function wnafDigits(n, W) {
|
|
2074
|
+
const size = 2 ** W;
|
|
2075
|
+
const half = size / 2;
|
|
2076
|
+
const mask = BigInt(size - 1);
|
|
2077
|
+
const d = [];
|
|
2078
|
+
while (n > _0n$3) {
|
|
2079
|
+
let w = 0;
|
|
2080
|
+
if (n & _1n$1) {
|
|
2081
|
+
w = Number(n & mask);
|
|
2082
|
+
if (w >= half) w -= size;
|
|
2083
|
+
n -= BigInt(w);
|
|
2084
|
+
}
|
|
2085
|
+
d.push(w);
|
|
2086
|
+
n >>= _1n$1;
|
|
2087
|
+
}
|
|
2088
|
+
return d;
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with
|
|
2092
|
+
* digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one
|
|
2093
|
+
* extra window for the final carry), so recoding length does not depend on the scalar.
|
|
2094
|
+
*/
|
|
2095
|
+
function signedWindowDigits(n, W, windows) {
|
|
2096
|
+
const size = 2 ** W;
|
|
2097
|
+
const half = size / 2;
|
|
2098
|
+
const mask = BigInt(size - 1);
|
|
2099
|
+
const shiftBy = BigInt(W);
|
|
2100
|
+
const d = [];
|
|
2101
|
+
for (let w = 0; w < windows; w++) {
|
|
2102
|
+
let v = Number(n & mask);
|
|
2103
|
+
n >>= shiftBy;
|
|
2104
|
+
if (v > half) {
|
|
2105
|
+
v -= size;
|
|
2106
|
+
n += _1n$1;
|
|
2107
|
+
}
|
|
2108
|
+
d.push(v);
|
|
2109
|
+
}
|
|
2110
|
+
if (n !== _0n$3) throw new Error("invalid wnaf");
|
|
2111
|
+
return d;
|
|
2112
|
+
}
|
|
2113
|
+
/**
|
|
2114
|
+
* Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared
|
|
2115
|
+
* accumulator per bit position of the longest recoding, one signed table addition per
|
|
2116
|
+
* nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.
|
|
2117
|
+
*/
|
|
2118
|
+
function wnafWalk(zero, tables, digits) {
|
|
2119
|
+
let max = 0;
|
|
2120
|
+
for (const d of digits) max = Math.max(max, d.length);
|
|
2121
|
+
let acc = zero;
|
|
2122
|
+
for (let bit = max - 1; bit >= 0; bit--) {
|
|
2123
|
+
if (bit !== max - 1) acc = acc.double();
|
|
2124
|
+
for (let i = 0; i < digits.length; i++) {
|
|
2125
|
+
const w = digits[i][bit];
|
|
2126
|
+
if (w) {
|
|
2127
|
+
const item = tables[i][Math.abs(w) - 1 >> 1];
|
|
2128
|
+
acc = acc.add(w < 0 ? item.negate() : item);
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
return acc;
|
|
2133
|
+
}
|
|
2134
|
+
/**
|
|
2135
|
+
* Elliptic curve multiplication of Point by scalar.
|
|
2136
|
+
* Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate
|
|
2137
|
+
* their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the
|
|
2138
|
+
* `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).
|
|
2139
|
+
* Table generation is expensive and happens on first call of `multiply()`
|
|
2140
|
+
* (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.
|
|
2141
|
+
*
|
|
2142
|
+
* Cached algorithm is signed fixed-window wNAF:
|
|
2143
|
+
* - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings
|
|
2144
|
+
* are baked in, so a multiplication is exactly one table addition per window
|
|
2145
|
+
* - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent
|
|
2146
|
+
* (basis of the constant-time path)
|
|
2147
|
+
* - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply
|
|
2148
|
+
* - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which
|
|
2149
|
+
* widens tables by 128 bits
|
|
2150
|
+
* @param Point - Point constructor.
|
|
2151
|
+
* @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.
|
|
2152
|
+
* @example
|
|
2153
|
+
* Elliptic curve multiplication of Point by scalar.
|
|
2154
|
+
*
|
|
2155
|
+
* ```ts
|
|
2156
|
+
* import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';
|
|
2157
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2158
|
+
* const mul = new ScalarMultiplier(p256.Point);
|
|
2159
|
+
* ```
|
|
2160
|
+
*/
|
|
2161
|
+
var ScalarMultiplier = class {
|
|
2162
|
+
Point;
|
|
2163
|
+
BASE;
|
|
2164
|
+
ZERO;
|
|
2165
|
+
randomBytes;
|
|
2166
|
+
wnafPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
2167
|
+
baseCanBeBlinded;
|
|
2168
|
+
bits;
|
|
2169
|
+
constructor(Point, randomBytes) {
|
|
2170
|
+
validatePointCons(Point);
|
|
2171
|
+
this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);
|
|
2172
|
+
this.Point = Point;
|
|
2173
|
+
this.BASE = Point.BASE;
|
|
2174
|
+
this.ZERO = Point.ZERO;
|
|
2175
|
+
this.bits = Point.Fn.BITS;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Creates a signed fixed-window wNAF precomputation table: for every window w, the
|
|
2179
|
+
* multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
|
|
2180
|
+
* so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
|
|
2181
|
+
* window absorbs the final carry of signed-digit recoding.
|
|
2182
|
+
* For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
|
|
2183
|
+
* @param point - Point instance
|
|
2184
|
+
* @param W - window size
|
|
2185
|
+
* @param bits - scalar bitlength the table must cover
|
|
2186
|
+
*/
|
|
2187
|
+
buildWnafTable(point, W, bits) {
|
|
2188
|
+
const windows = Math.ceil(bits / W) + 1;
|
|
2189
|
+
const half = 2 ** (W - 1);
|
|
2190
|
+
const comp = [];
|
|
2191
|
+
let base = point;
|
|
2192
|
+
for (let w = 0; w < windows; w++) {
|
|
2193
|
+
let acc = base;
|
|
2194
|
+
for (let i = 0; i < half; i++) {
|
|
2195
|
+
comp.push(acc);
|
|
2196
|
+
acc = acc.add(base);
|
|
2197
|
+
}
|
|
2198
|
+
base = comp[comp.length - 1].double();
|
|
2199
|
+
}
|
|
2200
|
+
return {
|
|
2201
|
+
W,
|
|
2202
|
+
bits,
|
|
2203
|
+
windows,
|
|
2204
|
+
comp
|
|
2205
|
+
};
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2208
|
+
* Implements ec multiplication using precomputed signed fixed-window wNAF tables.
|
|
2209
|
+
* Constant-time: fixed window count with one table addition per window — zero digits feed
|
|
2210
|
+
* the fake accumulator — and no doublings; the lookup scans the whole window slice.
|
|
2211
|
+
* Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
|
|
2212
|
+
* {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
|
|
2213
|
+
* signedWindowDigits throws if `n` exceeds the table.
|
|
2214
|
+
* @returns real and fake (for const-time) points
|
|
2215
|
+
*/
|
|
2216
|
+
wnafCachedCT(precomputes, n) {
|
|
2217
|
+
const { W, windows, comp } = precomputes;
|
|
2218
|
+
const half = 2 ** (W - 1);
|
|
2219
|
+
const digits = signedWindowDigits(n, W, windows);
|
|
2220
|
+
let p = this.ZERO;
|
|
2221
|
+
let f = this.BASE;
|
|
2222
|
+
for (let w = 0; w < windows; w++) {
|
|
2223
|
+
const digit = digits[w];
|
|
2224
|
+
const start = w * half;
|
|
2225
|
+
const idx = Math.abs(digit) - 1;
|
|
2226
|
+
let sel = comp[start];
|
|
2227
|
+
for (let i = 1; i < half; i++) sel = i === idx ? comp[start + i] : sel;
|
|
2228
|
+
const neg = sel.negate();
|
|
2229
|
+
if (digit === 0) f = f.add(comp[start]);
|
|
2230
|
+
else p = p.add(digit < 0 ? neg : sel);
|
|
2231
|
+
}
|
|
2232
|
+
return {
|
|
2233
|
+
p,
|
|
2234
|
+
f
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
getWnafPrecomputes(W, point, bits, transform) {
|
|
2238
|
+
let entries = this.wnafPrecomputes.get(point);
|
|
2239
|
+
let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
|
|
2240
|
+
if (!comp) {
|
|
2241
|
+
comp = this.buildWnafTable(point, W, bits);
|
|
2242
|
+
if (typeof transform === "function") comp = {
|
|
2243
|
+
...comp,
|
|
2244
|
+
comp: transform(comp.comp)
|
|
2245
|
+
};
|
|
2246
|
+
if (!entries) {
|
|
2247
|
+
entries = [];
|
|
2248
|
+
this.wnafPrecomputes.set(point, entries);
|
|
2249
|
+
}
|
|
2250
|
+
entries.push(comp);
|
|
2251
|
+
}
|
|
2252
|
+
return comp;
|
|
2253
|
+
}
|
|
2254
|
+
assertPoint(point) {
|
|
2255
|
+
if (!(point instanceof this.Point)) throw new TypeError("\"point\" expected Point instance, got type=" + typeof point);
|
|
2256
|
+
}
|
|
2257
|
+
validateMulInput(point, scalar) {
|
|
2258
|
+
this.assertPoint(point);
|
|
2259
|
+
if (!inRange(scalar, _1n$1, this.Point.Fn.ORDER)) throw new Error("invalid scalar");
|
|
2260
|
+
}
|
|
2261
|
+
runCT(point, n, bits, transform) {
|
|
2262
|
+
const W = getWindowSize(point);
|
|
2263
|
+
if (W === 1) return this.fixedWindowCT(point, n, bits);
|
|
2264
|
+
return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
|
|
2265
|
+
}
|
|
2266
|
+
mulCT(point, scalar, transform) {
|
|
2267
|
+
this.validateMulInput(point, scalar);
|
|
2268
|
+
return this.runCT(point, scalar, this.bits, transform);
|
|
2269
|
+
}
|
|
2270
|
+
mulCTBlinded(point, scalar, transform) {
|
|
2271
|
+
this.validateMulInput(point, scalar);
|
|
2272
|
+
if (this.randomBytes === void 0) throw new Error("randomBytes is required for scalar blinding");
|
|
2273
|
+
const bits = this.Point.Fn.BITS + BLIND_BITS;
|
|
2274
|
+
const blind = this.randomBytes(BLIND_BYTES);
|
|
2275
|
+
if (!isBytes(blind) || blind.length !== BLIND_BYTES) throw new Error("randomBytes returned invalid byte array");
|
|
2276
|
+
blind[0] = blind[0] & 63 | 128;
|
|
2277
|
+
const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
|
|
2278
|
+
return this.runCT(point, n, bits, transform);
|
|
2279
|
+
}
|
|
2280
|
+
/**
|
|
2281
|
+
* Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
|
|
2282
|
+
* A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
|
|
2283
|
+
* far cheaper to build for a single use. The point-operation sequence is independent of `n`:
|
|
2284
|
+
* build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
|
|
2285
|
+
* every table entry, and one addition (adds the identity when the window digit is 0 — never
|
|
2286
|
+
* skipped).
|
|
2287
|
+
*
|
|
2288
|
+
* `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
|
|
2289
|
+
* add), which holds for the Weierstrass/Edwards point types used here. The table is left in
|
|
2290
|
+
* projective form (no normalizeZ): normalizing this small a table costs more than the
|
|
2291
|
+
* mixed-add savings it would buy for a single multiply.
|
|
2292
|
+
* @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
|
|
2293
|
+
* (this path needs no fake accumulator — its op-count is already scalar-independent).
|
|
2294
|
+
*/
|
|
2295
|
+
fixedWindowCT(point, n, bits) {
|
|
2296
|
+
const W = FW_WINDOW;
|
|
2297
|
+
const size = 1 << W;
|
|
2298
|
+
const mask = bitMask(W);
|
|
2299
|
+
const table = new Array(size);
|
|
2300
|
+
table[0] = this.ZERO;
|
|
2301
|
+
for (let i = 1; i < size; i++) table[i] = table[i - 1].add(point);
|
|
2302
|
+
const windows = Math.ceil(bits / W);
|
|
2303
|
+
let acc = this.ZERO;
|
|
2304
|
+
for (let window = windows - 1; window >= 0; window--) {
|
|
2305
|
+
if (window !== windows - 1) for (let d = 0; d < W; d++) acc = acc.double();
|
|
2306
|
+
const digit = Number(n >> BigInt(window * W) & mask);
|
|
2307
|
+
let sel = table[0];
|
|
2308
|
+
for (let i = 1; i < size; i++) sel = i === digit ? table[i] : sel;
|
|
2309
|
+
acc = acc.add(sel);
|
|
2310
|
+
}
|
|
2311
|
+
return {
|
|
2312
|
+
p: acc,
|
|
2313
|
+
f: acc
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
shouldBlind(point, cofactor) {
|
|
2317
|
+
if (this.randomBytes === void 0) return false;
|
|
2318
|
+
if (cofactor === _1n$1) return true;
|
|
2319
|
+
if (point !== this.BASE) return false;
|
|
2320
|
+
if (this.baseCanBeBlinded === void 0) this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
|
|
2321
|
+
return this.baseCanBeBlinded;
|
|
2322
|
+
}
|
|
2323
|
+
mulSecret(point, scalar, cofactor, transform) {
|
|
2324
|
+
return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
|
|
2325
|
+
}
|
|
2326
|
+
mulUnsafe(point, scalar, transform) {
|
|
2327
|
+
this.assertPoint(point);
|
|
2328
|
+
if (!isPosBig(scalar)) throw new Error("invalid scalar");
|
|
2329
|
+
const W = getWindowSize(point);
|
|
2330
|
+
if (W === 1 || scalar >= this.Point.Fn.ORDER) return mulAddUnsafe(this.Point, [point], [scalar], true);
|
|
2331
|
+
const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
|
|
2332
|
+
return this.wnafCachedCT(precomputes, scalar).p;
|
|
2333
|
+
}
|
|
2334
|
+
setWindowSize(point, W) {
|
|
2335
|
+
this.assertPoint(point);
|
|
2336
|
+
validateW(W, this.bits);
|
|
2337
|
+
validateTableBytes((Math.ceil((this.bits + BLIND_BITS) / W) + 1) * 2 ** (W - 1), this.Point.Fp.BYTES);
|
|
2338
|
+
pointWindowSizes.set(point, W);
|
|
2339
|
+
this.wnafPrecomputes.delete(point);
|
|
2340
|
+
}
|
|
2341
|
+
hasWindowSize(point) {
|
|
2342
|
+
return getWindowSize(point) !== 1;
|
|
2343
|
+
}
|
|
2344
|
+
};
|
|
2345
|
+
/**
|
|
2346
|
+
* Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF
|
|
2347
|
+
* (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and
|
|
2348
|
+
* signed-digit recoding, but all walks share one doubling chain, so total cost is
|
|
2349
|
+
* `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate
|
|
2350
|
+
* multiplications. Intended for the 2-4 point shapes of signature verification
|
|
2351
|
+
* (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.
|
|
2352
|
+
*
|
|
2353
|
+
* Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;
|
|
2354
|
+
* fold negative signs into the points before calling.
|
|
2355
|
+
* @param c - Point constructor.
|
|
2356
|
+
* @param points - Array of curve points.
|
|
2357
|
+
* @param scalars - Array of non-negative scalars, same length as points.
|
|
2358
|
+
* @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.
|
|
2359
|
+
* Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks
|
|
2360
|
+
* (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.
|
|
2361
|
+
* @returns Combined multiplication result; identity for empty input.
|
|
2362
|
+
* @throws If the point set or scalar set is invalid. {@link Error}
|
|
2363
|
+
* @example
|
|
2364
|
+
* Combined multi-scalar multiplication via Strauss–Shamir.
|
|
2365
|
+
*
|
|
2366
|
+
* ```ts
|
|
2367
|
+
* import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';
|
|
2368
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2369
|
+
* const G = p256.Point.BASE;
|
|
2370
|
+
* const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)
|
|
2371
|
+
* ```
|
|
2372
|
+
*/
|
|
2373
|
+
function mulAddUnsafe(c, points, scalars, allowOversized = false) {
|
|
2374
|
+
validatePointCons(c);
|
|
2375
|
+
validateMSMPoints(points, c);
|
|
2376
|
+
abool(allowOversized, "allowOversized");
|
|
2377
|
+
validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n$1 : void 0);
|
|
2378
|
+
if (points.length !== scalars.length) throw new Error("arrays of points and scalars must have equal length");
|
|
2379
|
+
const tables = points.map((p) => oddMultiples(p, 4));
|
|
2380
|
+
const digits = scalars.map((n) => wnafDigits(n, 4));
|
|
2381
|
+
return wnafWalk(c.ZERO, tables, digits);
|
|
2382
|
+
}
|
|
2383
|
+
function createField(order, field, isLE) {
|
|
2384
|
+
if (field) {
|
|
2385
|
+
if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
2386
|
+
validateField(field);
|
|
2387
|
+
return field;
|
|
2388
|
+
} else return Field(order, { isLE });
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Validates basic CURVE shape and field membership, then creates fields.
|
|
2392
|
+
* This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
|
|
2393
|
+
* that the curve equation itself is otherwise sane.
|
|
2394
|
+
* @param type - Curve family.
|
|
2395
|
+
* @param CURVE - Curve parameters.
|
|
2396
|
+
* @param curveOpts - Optional field overrides. See {@link FpFn}:
|
|
2397
|
+
* - `Fp` (optional): Optional base-field override.
|
|
2398
|
+
* - `Fn` (optional): Optional scalar-field override.
|
|
2399
|
+
* @param FpFnLE - Whether field encoding is little-endian.
|
|
2400
|
+
* @returns Frozen curve parameters and fields.
|
|
2401
|
+
* @throws If the curve parameters or field overrides are invalid. {@link Error}
|
|
2402
|
+
* @example
|
|
2403
|
+
* Build curve fields from raw constants before constructing a curve instance.
|
|
2404
|
+
*
|
|
2405
|
+
* ```ts
|
|
2406
|
+
* const curve = createCurveFields('weierstrass', {
|
|
2407
|
+
* p: 17n,
|
|
2408
|
+
* n: 19n,
|
|
2409
|
+
* h: 1n,
|
|
2410
|
+
* a: 2n,
|
|
2411
|
+
* b: 2n,
|
|
2412
|
+
* Gx: 5n,
|
|
2413
|
+
* Gy: 1n,
|
|
2414
|
+
* });
|
|
2415
|
+
* ```
|
|
2416
|
+
*/
|
|
2417
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
2418
|
+
if (type !== "weierstrass" && type !== "edwards") throw new Error("expected curve type \"weierstrass\" or \"edwards\"");
|
|
2419
|
+
if (FpFnLE === void 0) FpFnLE = type === "edwards";
|
|
2420
|
+
if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
|
|
2421
|
+
validateObject(curveOpts);
|
|
2422
|
+
for (const p of [
|
|
2423
|
+
"p",
|
|
2424
|
+
"n",
|
|
2425
|
+
"h"
|
|
2426
|
+
]) {
|
|
2427
|
+
const val = CURVE[p];
|
|
2428
|
+
if (!(isPosBig(val) && val !== _0n$3)) throw new Error(`CURVE.${p} must be positive bigint`);
|
|
2429
|
+
}
|
|
2430
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
2431
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
2432
|
+
const params = [
|
|
2433
|
+
"Gx",
|
|
2434
|
+
"Gy",
|
|
2435
|
+
"a",
|
|
2436
|
+
type === "weierstrass" ? "b" : "d"
|
|
2437
|
+
];
|
|
2438
|
+
for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
2439
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
2440
|
+
return {
|
|
2441
|
+
CURVE,
|
|
2442
|
+
Fp,
|
|
2443
|
+
Fn
|
|
2444
|
+
};
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* @param randomSecretKey - Secret-key generator.
|
|
2448
|
+
* @param getPublicKey - Public-key derivation helper.
|
|
2449
|
+
* @returns Keypair generator.
|
|
2450
|
+
* @example
|
|
2451
|
+
* Build a `keygen()` helper from existing secret-key and public-key primitives.
|
|
2452
|
+
*
|
|
2453
|
+
* ```ts
|
|
2454
|
+
* import { createKeygen } from '@noble/curves/abstract/curve.js';
|
|
2455
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
2456
|
+
* const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
|
|
2457
|
+
* const pair = keygen();
|
|
2458
|
+
* ```
|
|
2459
|
+
*/
|
|
2460
|
+
function createKeygen(randomSecretKey, getPublicKey) {
|
|
2461
|
+
return function keygen(seed) {
|
|
2462
|
+
const secretKey = randomSecretKey(seed);
|
|
2463
|
+
return {
|
|
2464
|
+
secretKey,
|
|
2465
|
+
publicKey: getPublicKey(secretKey)
|
|
2466
|
+
};
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
//#endregion
|
|
2470
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js
|
|
2471
|
+
/**
|
|
2472
|
+
* HMAC: RFC2104 message authentication code.
|
|
2473
|
+
* @module
|
|
2474
|
+
*/
|
|
2475
|
+
/**
|
|
2476
|
+
* Internal class for HMAC.
|
|
2477
|
+
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
|
|
2478
|
+
* `HashLen` bytes long.
|
|
2479
|
+
*/
|
|
2480
|
+
var _HMAC = class {
|
|
2481
|
+
oHash;
|
|
2482
|
+
iHash;
|
|
2483
|
+
blockLen;
|
|
2484
|
+
outputLen;
|
|
2485
|
+
canXOF = false;
|
|
2486
|
+
finished = false;
|
|
2487
|
+
destroyed = false;
|
|
2488
|
+
constructor(hash, key) {
|
|
2489
|
+
ahash(hash);
|
|
2490
|
+
abytes$1(key, void 0, "key");
|
|
2491
|
+
this.iHash = hash.create();
|
|
2492
|
+
if (typeof this.iHash.update !== "function") throw new Error("expected Hash instance");
|
|
2493
|
+
this.blockLen = this.iHash.blockLen;
|
|
2494
|
+
this.outputLen = this.iHash.outputLen;
|
|
2495
|
+
const blockLen = this.blockLen;
|
|
2496
|
+
const pad = new Uint8Array(blockLen);
|
|
2497
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
2498
|
+
for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
|
|
2499
|
+
this.iHash.update(pad);
|
|
2500
|
+
this.oHash = hash.create();
|
|
2501
|
+
for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
|
|
2502
|
+
this.oHash.update(pad);
|
|
2503
|
+
clean(pad);
|
|
2504
|
+
}
|
|
2505
|
+
update(buf) {
|
|
2506
|
+
aexists(this);
|
|
2507
|
+
this.iHash.update(buf);
|
|
2508
|
+
return this;
|
|
2509
|
+
}
|
|
2510
|
+
digestInto(out) {
|
|
2511
|
+
aexists(this);
|
|
2512
|
+
aoutput(out, this);
|
|
2513
|
+
this.finished = true;
|
|
2514
|
+
const buf = out.subarray(0, this.outputLen);
|
|
2515
|
+
this.iHash.digestInto(buf);
|
|
2516
|
+
this.oHash.update(buf);
|
|
2517
|
+
this.oHash.digestInto(buf);
|
|
2518
|
+
this.destroy();
|
|
2519
|
+
}
|
|
2520
|
+
digest() {
|
|
2521
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
2522
|
+
this.digestInto(out);
|
|
2523
|
+
return out;
|
|
2524
|
+
}
|
|
2525
|
+
_cloneInto(to) {
|
|
2526
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
2527
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
|
|
2528
|
+
to = to;
|
|
2529
|
+
to.finished = finished;
|
|
2530
|
+
to.destroyed = destroyed;
|
|
2531
|
+
to.blockLen = blockLen;
|
|
2532
|
+
to.outputLen = outputLen;
|
|
2533
|
+
to.canXOF = canXOF;
|
|
2534
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
2535
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
2536
|
+
return to;
|
|
2537
|
+
}
|
|
2538
|
+
clone() {
|
|
2539
|
+
return this._cloneInto();
|
|
2540
|
+
}
|
|
2541
|
+
destroy() {
|
|
2542
|
+
this.destroyed = true;
|
|
2543
|
+
this.oHash.destroy();
|
|
2544
|
+
this.iHash.destroy();
|
|
2545
|
+
}
|
|
2546
|
+
};
|
|
2547
|
+
var hmac = /* @__PURE__ */ (() => {
|
|
2548
|
+
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
|
2549
|
+
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
|
2550
|
+
return hmac_;
|
|
2551
|
+
})();
|
|
2552
|
+
//#endregion
|
|
2553
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js
|
|
2554
|
+
/**
|
|
2555
|
+
* ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.
|
|
2556
|
+
* Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.
|
|
2557
|
+
* @module
|
|
2558
|
+
*/
|
|
2559
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2560
|
+
var _0n$2 = /* @__PURE__ */ BigInt(0);
|
|
2561
|
+
/**
|
|
2562
|
+
* @param m - Error message.
|
|
2563
|
+
* @example
|
|
2564
|
+
* Throw a DER-specific error when signature parsing encounters invalid bytes.
|
|
2565
|
+
*
|
|
2566
|
+
* ```ts
|
|
2567
|
+
* new DERErr('bad der');
|
|
2568
|
+
* ```
|
|
2569
|
+
*/
|
|
2570
|
+
var DERErr = class extends Error {
|
|
2571
|
+
constructor(m = "") {
|
|
2572
|
+
super(m);
|
|
2573
|
+
}
|
|
2574
|
+
};
|
|
2575
|
+
var _DER = {
|
|
2576
|
+
Err: DERErr,
|
|
2577
|
+
_tlv: {
|
|
2578
|
+
encode: (tag, data) => {
|
|
2579
|
+
const { Err: E } = _DER;
|
|
2580
|
+
asafenumber(tag, "tag");
|
|
2581
|
+
if (tag < 0 || tag > 255) throw new E("tlv.encode: wrong tag");
|
|
2582
|
+
astring(data, "data");
|
|
2583
|
+
if (data.length & 1) throw new E("tlv.encode: unpadded data");
|
|
2584
|
+
const dataLen = data.length / 2;
|
|
2585
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2586
|
+
if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
|
|
2587
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
2588
|
+
return numberToHexUnpadded(tag) + lenLen + len + data;
|
|
2589
|
+
},
|
|
2590
|
+
decode(tag, data) {
|
|
2591
|
+
const { Err: E } = _DER;
|
|
2592
|
+
data = abytes(data, void 0, "DER data");
|
|
2593
|
+
let pos = 0;
|
|
2594
|
+
if (tag < 0 || tag > 255) throw new E("tlv.decode: wrong tag");
|
|
2595
|
+
if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
|
|
2596
|
+
const first = data[pos++];
|
|
2597
|
+
const isLong = !!(first & 128);
|
|
2598
|
+
let length = 0;
|
|
2599
|
+
if (!isLong) length = first;
|
|
2600
|
+
else {
|
|
2601
|
+
const lenLen = first & 127;
|
|
2602
|
+
if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
|
|
2603
|
+
if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
|
|
2604
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2605
|
+
if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
|
|
2606
|
+
if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
|
|
2607
|
+
for (const b of lengthBytes) length = length << 8 | b;
|
|
2608
|
+
pos += lenLen;
|
|
2609
|
+
if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
|
|
2610
|
+
}
|
|
2611
|
+
const v = data.subarray(pos, pos + length);
|
|
2612
|
+
if (v.length !== length) throw new E("tlv.decode: wrong value length");
|
|
2613
|
+
return {
|
|
2614
|
+
v,
|
|
2615
|
+
l: data.subarray(pos + length)
|
|
2616
|
+
};
|
|
2617
|
+
}
|
|
2618
|
+
},
|
|
2619
|
+
_int: {
|
|
2620
|
+
encode(num) {
|
|
2621
|
+
const { Err: E } = _DER;
|
|
2622
|
+
abignumber(num);
|
|
2623
|
+
if (num < _0n$2) throw new E("integer: negative integers are not allowed");
|
|
2624
|
+
let hex = numberToHexUnpadded(num);
|
|
2625
|
+
if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
|
|
2626
|
+
if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
2627
|
+
return hex;
|
|
2628
|
+
},
|
|
2629
|
+
decode(data) {
|
|
2630
|
+
const { Err: E } = _DER;
|
|
2631
|
+
if (data.length < 1) throw new E("invalid signature integer: empty");
|
|
2632
|
+
if (data[0] & 128) throw new E("invalid signature integer: negative");
|
|
2633
|
+
if (data.length > 1 && data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
|
|
2634
|
+
return bytesToNumberBE(data);
|
|
2635
|
+
}
|
|
2636
|
+
},
|
|
2637
|
+
toSig(bytes, maxScalarBytes) {
|
|
2638
|
+
const { Err: E, _int: int, _tlv: tlv } = _DER;
|
|
2639
|
+
if (maxScalarBytes !== void 0) {
|
|
2640
|
+
asafenumber(maxScalarBytes, "maxScalarBytes");
|
|
2641
|
+
if (maxScalarBytes < 1) throw new E("invalid signature: maxScalarBytes must be positive");
|
|
2642
|
+
}
|
|
2643
|
+
const data = abytes(bytes, void 0, "signature");
|
|
2644
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
2645
|
+
if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
|
|
2646
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
2647
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
2648
|
+
if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
|
|
2649
|
+
if (maxScalarBytes !== void 0 && (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes)) throw new E("invalid signature: integer too large");
|
|
2650
|
+
return {
|
|
2651
|
+
r: int.decode(rBytes),
|
|
2652
|
+
s: int.decode(sBytes)
|
|
2653
|
+
};
|
|
2654
|
+
},
|
|
2655
|
+
hexFromSig(sig) {
|
|
2656
|
+
const { _tlv: tlv, _int: int } = _DER;
|
|
2657
|
+
validateObject(sig, {
|
|
2658
|
+
r: "bigint",
|
|
2659
|
+
s: "bigint"
|
|
2660
|
+
}, {}, "sig");
|
|
2661
|
+
const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
|
|
2662
|
+
return tlv.encode(48, seq);
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
/**
|
|
2666
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
|
2667
|
+
*
|
|
2668
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
|
2669
|
+
*
|
|
2670
|
+
* Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and
|
|
2671
|
+
* {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.
|
|
2672
|
+
* @example
|
|
2673
|
+
* ASN.1 DER encoding utilities.
|
|
2674
|
+
*
|
|
2675
|
+
* ```ts
|
|
2676
|
+
* const der = DER.hexFromSig({ r: 1n, s: 2n });
|
|
2677
|
+
* ```
|
|
2678
|
+
*/
|
|
2679
|
+
var DER = /* @__PURE__ */ (() => {
|
|
2680
|
+
Object.freeze(_DER._tlv);
|
|
2681
|
+
Object.freeze(_DER._int);
|
|
2682
|
+
return Object.freeze(_DER);
|
|
2683
|
+
})();
|
|
2684
|
+
//#endregion
|
|
2685
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/weierstrass.js
|
|
2686
|
+
/**
|
|
2687
|
+
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
|
|
2688
|
+
*
|
|
2689
|
+
* ### Design rationale for types
|
|
2690
|
+
*
|
|
2691
|
+
* * Interaction between classes from different curves should fail:
|
|
2692
|
+
* `k256.Point.BASE.add(p256.Point.BASE)`
|
|
2693
|
+
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
|
|
2694
|
+
* * Different calls of `curve()` would return different classes -
|
|
2695
|
+
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
|
|
2696
|
+
* it won't affect others
|
|
2697
|
+
*
|
|
2698
|
+
* TypeScript can't infer types for classes created inside a function. Classes is one instance
|
|
2699
|
+
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
|
|
2700
|
+
* unique type for every function call.
|
|
2701
|
+
*
|
|
2702
|
+
* We can use generic types via some param, like curve opts, but that would:
|
|
2703
|
+
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
|
|
2704
|
+
* which is hard to debug.
|
|
2705
|
+
* 2. Params can be generic and we can't enforce them to be constant value:
|
|
2706
|
+
* if somebody creates curve from non-constant params,
|
|
2707
|
+
* it would be allowed to interact with other curves with non-constant params
|
|
2708
|
+
*
|
|
2709
|
+
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
|
|
2710
|
+
* @module
|
|
2711
|
+
*/
|
|
2712
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2713
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
|
|
2714
|
+
/** Splits scalar for GLV endomorphism. */
|
|
2715
|
+
function _splitEndoScalar(k, basis, n) {
|
|
2716
|
+
aInRange("scalar", k, _0n$1, n);
|
|
2717
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
2718
|
+
const c1 = divNearest(b2 * k, n);
|
|
2719
|
+
const c2 = divNearest(-b1 * k, n);
|
|
2720
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
2721
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
2722
|
+
const k1neg = k1 < _0n$1;
|
|
2723
|
+
const k2neg = k2 < _0n$1;
|
|
2724
|
+
if (k1neg) k1 = -k1;
|
|
2725
|
+
if (k2neg) k2 = -k2;
|
|
2726
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n;
|
|
2727
|
+
if (k1 < _0n$1 || k1 >= MAX_NUM || k2 < _0n$1 || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed for k");
|
|
2728
|
+
return {
|
|
2729
|
+
k1neg,
|
|
2730
|
+
k1,
|
|
2731
|
+
k2neg,
|
|
2732
|
+
k2
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
function validateSigFormat(format) {
|
|
2736
|
+
if (![
|
|
2737
|
+
"compact",
|
|
2738
|
+
"recovered",
|
|
2739
|
+
"der"
|
|
2740
|
+
].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
|
|
2741
|
+
return format;
|
|
2742
|
+
}
|
|
2743
|
+
function validateSigOpts(opts, def) {
|
|
2744
|
+
validateObject(opts);
|
|
2745
|
+
const optsn = {};
|
|
2746
|
+
for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
2747
|
+
abool(optsn.lowS, "lowS");
|
|
2748
|
+
abool(optsn.prehash, "prehash");
|
|
2749
|
+
if (optsn.format !== void 0) validateSigFormat(optsn.format);
|
|
2750
|
+
return optsn;
|
|
2751
|
+
}
|
|
2752
|
+
var _0n$1 = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n$1 = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);
|
|
2753
|
+
/**
|
|
2754
|
+
* Creates weierstrass Point constructor, based on specified curve options.
|
|
2755
|
+
*
|
|
2756
|
+
* See {@link WeierstrassOpts}.
|
|
2757
|
+
* @param params - Curve parameters. See {@link WeierstrassOpts}.
|
|
2758
|
+
* @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.
|
|
2759
|
+
* @returns Weierstrass point constructor.
|
|
2760
|
+
* @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}
|
|
2761
|
+
*
|
|
2762
|
+
* @example
|
|
2763
|
+
* Construct a point type from explicit Weierstrass curve parameters.
|
|
2764
|
+
*
|
|
2765
|
+
* ```js
|
|
2766
|
+
* const opts = {
|
|
2767
|
+
* p: 0xfffffffffffffffffffffffffffffffeffffac73n,
|
|
2768
|
+
* n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,
|
|
2769
|
+
* h: 1n,
|
|
2770
|
+
* a: 0n,
|
|
2771
|
+
* b: 7n,
|
|
2772
|
+
* Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,
|
|
2773
|
+
* Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,
|
|
2774
|
+
* };
|
|
2775
|
+
* const secp160k1_Point = weierstrass(opts);
|
|
2776
|
+
* ```
|
|
2777
|
+
*/
|
|
2778
|
+
function weierstrass(params, extraOpts = {}) {
|
|
2779
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
2780
|
+
const Fp = validated.Fp;
|
|
2781
|
+
const Fn = validated.Fn;
|
|
2782
|
+
let CURVE = validated.CURVE;
|
|
2783
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
2784
|
+
validateObject(extraOpts, {}, {
|
|
2785
|
+
allowInfinityPoint: "boolean",
|
|
2786
|
+
clearCofactor: "function",
|
|
2787
|
+
isTorsionFree: "function",
|
|
2788
|
+
fromBytes: "function",
|
|
2789
|
+
toBytes: "function",
|
|
2790
|
+
endo: "object",
|
|
2791
|
+
randomBytes: "function"
|
|
2792
|
+
});
|
|
2793
|
+
const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes } = extraOpts;
|
|
2794
|
+
const randomBytes = extraOpts.randomBytes === void 0 ? randomBytes$1 : extraOpts.randomBytes;
|
|
2795
|
+
if (endoOpts) {
|
|
2796
|
+
if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== "bigint" || !Array.isArray(endoOpts.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
|
|
2797
|
+
}
|
|
2798
|
+
const endo = endoOpts ? {
|
|
2799
|
+
beta: endoOpts.beta,
|
|
2800
|
+
basises: endoOpts.basises.map((basis) => [...basis])
|
|
2801
|
+
} : void 0;
|
|
2802
|
+
const lengths = getWLengths(Fp, Fn);
|
|
2803
|
+
function assertCompressionIsSupported() {
|
|
2804
|
+
if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
2805
|
+
}
|
|
2806
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
2807
|
+
if (point.is0()) {
|
|
2808
|
+
if (!allowInfinityPoint) throw new Error("bad point: ZERO");
|
|
2809
|
+
return Uint8Array.of(0);
|
|
2810
|
+
}
|
|
2811
|
+
const { x, y } = point.toAffine();
|
|
2812
|
+
const bx = Fp.toBytes(x);
|
|
2813
|
+
abool(isCompressed, "isCompressed");
|
|
2814
|
+
if (isCompressed) {
|
|
2815
|
+
assertCompressionIsSupported();
|
|
2816
|
+
return concatBytes(pprefix(!Fp.isOdd(y)), bx);
|
|
2817
|
+
} else return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
2818
|
+
}
|
|
2819
|
+
function pointFromBytes(bytes) {
|
|
2820
|
+
abytes(bytes, void 0, "Point");
|
|
2821
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
2822
|
+
const length = bytes.length;
|
|
2823
|
+
const head = bytes[0];
|
|
2824
|
+
const tail = bytes.subarray(1);
|
|
2825
|
+
if (allowInfinityPoint && length === 1 && head === 0) return {
|
|
2826
|
+
x: Fp.ZERO,
|
|
2827
|
+
y: Fp.ZERO
|
|
2828
|
+
};
|
|
2829
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
2830
|
+
const x = Fp.fromBytes(tail);
|
|
2831
|
+
if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
|
|
2832
|
+
const y2 = weierstrassEquation(x);
|
|
2833
|
+
let y;
|
|
2834
|
+
try {
|
|
2835
|
+
y = Fp.sqrt(y2);
|
|
2836
|
+
} catch (sqrtError) {
|
|
2837
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
2838
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
2839
|
+
}
|
|
2840
|
+
assertCompressionIsSupported();
|
|
2841
|
+
const evenY = Fp.isOdd(y);
|
|
2842
|
+
if ((head & 1) === 1 !== evenY) y = Fp.neg(y);
|
|
2843
|
+
return {
|
|
2844
|
+
x,
|
|
2845
|
+
y
|
|
2846
|
+
};
|
|
2847
|
+
} else if (length === uncomp && head === 4) {
|
|
2848
|
+
const L = Fp.BYTES;
|
|
2849
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
2850
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
2851
|
+
if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
|
|
2852
|
+
return {
|
|
2853
|
+
x,
|
|
2854
|
+
y
|
|
2855
|
+
};
|
|
2856
|
+
} else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
2857
|
+
}
|
|
2858
|
+
const encodePoint = toBytes === void 0 ? pointToBytes : toBytes;
|
|
2859
|
+
const decodePoint = fromBytes === void 0 ? pointFromBytes : fromBytes;
|
|
2860
|
+
const b3 = Fp.mul(CURVE.b, _3n);
|
|
2861
|
+
const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);
|
|
2862
|
+
function weierstrassEquation(x) {
|
|
2863
|
+
const x2 = Fp.sqr(x);
|
|
2864
|
+
const x3 = Fp.mul(x2, x);
|
|
2865
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
2866
|
+
}
|
|
2867
|
+
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
|
|
2868
|
+
function isValidXY(x, y) {
|
|
2869
|
+
const left = Fp.sqr(y);
|
|
2870
|
+
const right = weierstrassEquation(x);
|
|
2871
|
+
return Fp.eql(left, right);
|
|
2872
|
+
}
|
|
2873
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
|
|
2874
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
|
|
2875
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
2876
|
+
if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
|
|
2877
|
+
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
|
|
2878
|
+
function acoord(title, n, banZero = false) {
|
|
2879
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
|
|
2880
|
+
return typeof n === "object" && n !== null ? Fp.create(n) : n;
|
|
2881
|
+
}
|
|
2882
|
+
function aprjpoint(other) {
|
|
2883
|
+
if (!(other instanceof Point)) throw new Error("Weierstrass Point expected");
|
|
2884
|
+
}
|
|
2885
|
+
function splitEndoScalarN(k) {
|
|
2886
|
+
if (!endo || !endo.basises) throw new Error("no endo");
|
|
2887
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
2888
|
+
}
|
|
2889
|
+
/**
|
|
2890
|
+
* Appends a (point, scalar) pair to the inputs of a vartime wNAF walk
|
|
2891
|
+
* ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width
|
|
2892
|
+
* pairs against P and ψ(P) = (β⋅x, y), halving the walk's shared doubling chain;
|
|
2893
|
+
* split signs fold into the points.
|
|
2894
|
+
*/
|
|
2895
|
+
function pushWnafPair(points, scalars, p, k) {
|
|
2896
|
+
if (!Fn.isValid(k)) throw new RangeError("invalid scalar: out of range");
|
|
2897
|
+
if (endo) {
|
|
2898
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);
|
|
2899
|
+
const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);
|
|
2900
|
+
points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);
|
|
2901
|
+
scalars.push(k1, k2);
|
|
2902
|
+
} else {
|
|
2903
|
+
points.push(p);
|
|
2904
|
+
scalars.push(k);
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
const validityCache = /* @__PURE__ */ new WeakSet();
|
|
2908
|
+
/**
|
|
2909
|
+
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
2910
|
+
* Default Point works in 2d / affine coordinates: (x, y).
|
|
2911
|
+
* We're doing calculations in projective, because its operations don't require costly inversion.
|
|
2912
|
+
*/
|
|
2913
|
+
class Point {
|
|
2914
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
2915
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
2916
|
+
static Fp = Fp;
|
|
2917
|
+
static Fn = Fn;
|
|
2918
|
+
X;
|
|
2919
|
+
Y;
|
|
2920
|
+
Z;
|
|
2921
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2922
|
+
constructor(X, Y, Z) {
|
|
2923
|
+
this.X = acoord("x", X);
|
|
2924
|
+
this.Y = acoord("y", Y, true);
|
|
2925
|
+
this.Z = acoord("z", Z);
|
|
2926
|
+
Object.freeze(this);
|
|
2927
|
+
}
|
|
2928
|
+
static CURVE() {
|
|
2929
|
+
return CURVE;
|
|
2930
|
+
}
|
|
2931
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2932
|
+
static fromAffine(p) {
|
|
2933
|
+
const { x, y } = p || {};
|
|
2934
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
|
|
2935
|
+
if (p instanceof Point) throw new Error("projective point not allowed");
|
|
2936
|
+
if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
|
|
2937
|
+
return new Point(x, y, Fp.ONE);
|
|
2938
|
+
}
|
|
2939
|
+
static fromBytes(bytes) {
|
|
2940
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
2941
|
+
P.assertValidity();
|
|
2942
|
+
return P;
|
|
2943
|
+
}
|
|
2944
|
+
static fromHex(hex) {
|
|
2945
|
+
return Point.fromBytes(hexToBytes(hex));
|
|
2946
|
+
}
|
|
2947
|
+
get x() {
|
|
2948
|
+
return this.toAffine().x;
|
|
2949
|
+
}
|
|
2950
|
+
get y() {
|
|
2951
|
+
return this.toAffine().y;
|
|
2952
|
+
}
|
|
2953
|
+
/**
|
|
2954
|
+
* @param isLazy - true will defer table computation until the first multiplication
|
|
2955
|
+
*/
|
|
2956
|
+
precompute(windowSize = 6, isLazy = true) {
|
|
2957
|
+
wnaf.setWindowSize(this, windowSize);
|
|
2958
|
+
if (!isLazy) this.multiply(_3n);
|
|
2959
|
+
return this;
|
|
2960
|
+
}
|
|
2961
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
2962
|
+
assertValidity() {
|
|
2963
|
+
const p = this;
|
|
2964
|
+
if (p.is0()) {
|
|
2965
|
+
if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) return;
|
|
2966
|
+
throw new Error("bad point: ZERO");
|
|
2967
|
+
}
|
|
2968
|
+
if (validityCache.has(p)) return;
|
|
2969
|
+
const { x, y } = p.toAffine();
|
|
2970
|
+
if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
|
|
2971
|
+
if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
|
|
2972
|
+
if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
|
|
2973
|
+
validityCache.add(p);
|
|
2974
|
+
}
|
|
2975
|
+
hasEvenY() {
|
|
2976
|
+
const { y } = this.toAffine();
|
|
2977
|
+
if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
|
|
2978
|
+
return !Fp.isOdd(y);
|
|
2979
|
+
}
|
|
2980
|
+
/** Compare one point to another. */
|
|
2981
|
+
equals(other) {
|
|
2982
|
+
aprjpoint(other);
|
|
2983
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2984
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2985
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
2986
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
2987
|
+
return U1 && U2;
|
|
2988
|
+
}
|
|
2989
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
2990
|
+
negate() {
|
|
2991
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
2992
|
+
}
|
|
2993
|
+
double() {
|
|
2994
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2995
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
2996
|
+
let t0 = Fp.mul(X1, X1);
|
|
2997
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
2998
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
2999
|
+
let t3 = Fp.mul(X1, Y1);
|
|
3000
|
+
t3 = Fp.add(t3, t3);
|
|
3001
|
+
Z3 = Fp.mul(X1, Z1);
|
|
3002
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3003
|
+
X3 = mulA(Z3);
|
|
3004
|
+
Y3 = Fp.mul(b3, t2);
|
|
3005
|
+
Y3 = Fp.add(X3, Y3);
|
|
3006
|
+
X3 = Fp.sub(t1, Y3);
|
|
3007
|
+
Y3 = Fp.add(t1, Y3);
|
|
3008
|
+
Y3 = Fp.mul(X3, Y3);
|
|
3009
|
+
X3 = Fp.mul(t3, X3);
|
|
3010
|
+
Z3 = Fp.mul(b3, Z3);
|
|
3011
|
+
t2 = mulA(t2);
|
|
3012
|
+
t3 = Fp.sub(t0, t2);
|
|
3013
|
+
t3 = mulA(t3);
|
|
3014
|
+
t3 = Fp.add(t3, Z3);
|
|
3015
|
+
Z3 = Fp.add(t0, t0);
|
|
3016
|
+
t0 = Fp.add(Z3, t0);
|
|
3017
|
+
t0 = Fp.add(t0, t2);
|
|
3018
|
+
t0 = Fp.mul(t0, t3);
|
|
3019
|
+
Y3 = Fp.add(Y3, t0);
|
|
3020
|
+
t2 = Fp.mul(Y1, Z1);
|
|
3021
|
+
t2 = Fp.add(t2, t2);
|
|
3022
|
+
t0 = Fp.mul(t2, t3);
|
|
3023
|
+
X3 = Fp.sub(X3, t0);
|
|
3024
|
+
Z3 = Fp.mul(t2, t1);
|
|
3025
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3026
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3027
|
+
return new Point(X3, Y3, Z3);
|
|
3028
|
+
}
|
|
3029
|
+
add(other) {
|
|
3030
|
+
aprjpoint(other);
|
|
3031
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
3032
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
3033
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
3034
|
+
let t0 = Fp.mul(X1, X2);
|
|
3035
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
3036
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
3037
|
+
let t3 = Fp.add(X1, Y1);
|
|
3038
|
+
let t4 = Fp.add(X2, Y2);
|
|
3039
|
+
t3 = Fp.mul(t3, t4);
|
|
3040
|
+
t4 = Fp.add(t0, t1);
|
|
3041
|
+
t3 = Fp.sub(t3, t4);
|
|
3042
|
+
t4 = Fp.add(X1, Z1);
|
|
3043
|
+
let t5 = Fp.add(X2, Z2);
|
|
3044
|
+
t4 = Fp.mul(t4, t5);
|
|
3045
|
+
t5 = Fp.add(t0, t2);
|
|
3046
|
+
t4 = Fp.sub(t4, t5);
|
|
3047
|
+
t5 = Fp.add(Y1, Z1);
|
|
3048
|
+
X3 = Fp.add(Y2, Z2);
|
|
3049
|
+
t5 = Fp.mul(t5, X3);
|
|
3050
|
+
X3 = Fp.add(t1, t2);
|
|
3051
|
+
t5 = Fp.sub(t5, X3);
|
|
3052
|
+
Z3 = mulA(t4);
|
|
3053
|
+
X3 = Fp.mul(b3, t2);
|
|
3054
|
+
Z3 = Fp.add(X3, Z3);
|
|
3055
|
+
X3 = Fp.sub(t1, Z3);
|
|
3056
|
+
Z3 = Fp.add(t1, Z3);
|
|
3057
|
+
Y3 = Fp.mul(X3, Z3);
|
|
3058
|
+
t1 = Fp.add(t0, t0);
|
|
3059
|
+
t1 = Fp.add(t1, t0);
|
|
3060
|
+
t2 = mulA(t2);
|
|
3061
|
+
t4 = Fp.mul(b3, t4);
|
|
3062
|
+
t1 = Fp.add(t1, t2);
|
|
3063
|
+
t2 = Fp.sub(t0, t2);
|
|
3064
|
+
t2 = mulA(t2);
|
|
3065
|
+
t4 = Fp.add(t4, t2);
|
|
3066
|
+
t0 = Fp.mul(t1, t4);
|
|
3067
|
+
Y3 = Fp.add(Y3, t0);
|
|
3068
|
+
t0 = Fp.mul(t5, t4);
|
|
3069
|
+
X3 = Fp.mul(t3, X3);
|
|
3070
|
+
X3 = Fp.sub(X3, t0);
|
|
3071
|
+
t0 = Fp.mul(t3, t1);
|
|
3072
|
+
Z3 = Fp.mul(t5, Z3);
|
|
3073
|
+
Z3 = Fp.add(Z3, t0);
|
|
3074
|
+
return new Point(X3, Y3, Z3);
|
|
3075
|
+
}
|
|
3076
|
+
subtract(other) {
|
|
3077
|
+
aprjpoint(other);
|
|
3078
|
+
return this.add(other.negate());
|
|
3079
|
+
}
|
|
3080
|
+
is0() {
|
|
3081
|
+
return this.equals(Point.ZERO);
|
|
3082
|
+
}
|
|
3083
|
+
/**
|
|
3084
|
+
* Constant time multiplication.
|
|
3085
|
+
* Uses precomputed tables (signed fixed-window wNAF) when available.
|
|
3086
|
+
* Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.
|
|
3087
|
+
* @param scalar - by which the point would be multiplied
|
|
3088
|
+
* @returns New point
|
|
3089
|
+
*/
|
|
3090
|
+
multiply(scalar) {
|
|
3091
|
+
if (!Fn.isValidNot0(scalar)) throw new RangeError("invalid scalar: out of range");
|
|
3092
|
+
const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
|
|
3093
|
+
return normalize([p, f])[0];
|
|
3094
|
+
}
|
|
3095
|
+
/**
|
|
3096
|
+
* Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting
|
|
3097
|
+
* when available (two half-width scalars sharing one halved doubling chain).
|
|
3098
|
+
* It's faster, but should only be used when you don't care about
|
|
3099
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
3100
|
+
*/
|
|
3101
|
+
multiplyUnsafe(scalar) {
|
|
3102
|
+
const p = this;
|
|
3103
|
+
const sc = scalar;
|
|
3104
|
+
if (!Fn.isValid(sc)) throw new RangeError("invalid scalar: out of range");
|
|
3105
|
+
if (sc === _0n$1 || p.is0()) return Point.ZERO;
|
|
3106
|
+
if (sc === _1n) return p;
|
|
3107
|
+
if (wnaf.hasWindowSize(this)) return wnaf.mulUnsafe(p, sc, normalize);
|
|
3108
|
+
const points = [];
|
|
3109
|
+
const scalars = [];
|
|
3110
|
+
pushWnafPair(points, scalars, p, sc);
|
|
3111
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).
|
|
3115
|
+
* Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism
|
|
3116
|
+
* (when available) halves the chain again by splitting each scalar into two half-width
|
|
3117
|
+
* parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.
|
|
3118
|
+
* Only for public scalars.
|
|
3119
|
+
*/
|
|
3120
|
+
mulAddUnsafe(a, other, b) {
|
|
3121
|
+
aprjpoint(other);
|
|
3122
|
+
const points = [];
|
|
3123
|
+
const scalars = [];
|
|
3124
|
+
pushWnafPair(points, scalars, this, a);
|
|
3125
|
+
pushWnafPair(points, scalars, other, b);
|
|
3126
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
3127
|
+
}
|
|
3128
|
+
/**
|
|
3129
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
3130
|
+
* (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
3131
|
+
* @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
3132
|
+
*/
|
|
3133
|
+
toAffine(invertedZ) {
|
|
3134
|
+
const p = this;
|
|
3135
|
+
let iz = invertedZ;
|
|
3136
|
+
if (iz != null && !Fp.isValid(iz)) throw new RangeError("\"invertedZ\" expected valid field element");
|
|
3137
|
+
const { X, Y, Z } = p;
|
|
3138
|
+
if (Fp.eql(Z, Fp.ONE)) return {
|
|
3139
|
+
x: X,
|
|
3140
|
+
y: Y
|
|
3141
|
+
};
|
|
3142
|
+
const is0 = p.is0();
|
|
3143
|
+
if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
3144
|
+
const x = Fp.mul(X, iz);
|
|
3145
|
+
const y = Fp.mul(Y, iz);
|
|
3146
|
+
const zz = Fp.mul(Z, iz);
|
|
3147
|
+
if (is0) return {
|
|
3148
|
+
x: Fp.ZERO,
|
|
3149
|
+
y: Fp.ZERO
|
|
3150
|
+
};
|
|
3151
|
+
if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
|
|
3152
|
+
return {
|
|
3153
|
+
x,
|
|
3154
|
+
y
|
|
3155
|
+
};
|
|
3156
|
+
}
|
|
3157
|
+
/**
|
|
3158
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
3159
|
+
* Always torsion-free for cofactor=1 curves.
|
|
3160
|
+
*/
|
|
3161
|
+
isTorsionFree() {
|
|
3162
|
+
if (cofactor === _1n) return true;
|
|
3163
|
+
if (isTorsionFree) return isTorsionFree(Point, this);
|
|
3164
|
+
return wnaf.mulUnsafe(this, CURVE_ORDER).is0();
|
|
3165
|
+
}
|
|
3166
|
+
clearCofactor() {
|
|
3167
|
+
if (cofactor === _1n) return this;
|
|
3168
|
+
if (clearCofactor) return clearCofactor(Point, this);
|
|
3169
|
+
return this.multiplyUnsafe(cofactor);
|
|
3170
|
+
}
|
|
3171
|
+
isSmallOrder() {
|
|
3172
|
+
if (cofactor === _1n) return this.is0();
|
|
3173
|
+
return this.clearCofactor().is0();
|
|
3174
|
+
}
|
|
3175
|
+
toBytes(isCompressed = true) {
|
|
3176
|
+
abool(isCompressed, "isCompressed");
|
|
3177
|
+
this.assertValidity();
|
|
3178
|
+
return encodePoint(Point, this, isCompressed);
|
|
3179
|
+
}
|
|
3180
|
+
toHex(isCompressed = true) {
|
|
3181
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
3182
|
+
}
|
|
3183
|
+
toString() {
|
|
3184
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
3185
|
+
}
|
|
3186
|
+
}
|
|
3187
|
+
const normalize = (points) => normalizeZ(Point, points);
|
|
3188
|
+
const wnaf = new ScalarMultiplier(Point, randomBytes);
|
|
3189
|
+
if (wnaf.bits >= 6) Point.BASE.precompute(6);
|
|
3190
|
+
Object.freeze(Point.prototype);
|
|
3191
|
+
Object.freeze(Point);
|
|
3192
|
+
return Point;
|
|
3193
|
+
}
|
|
3194
|
+
function pprefix(hasEvenY) {
|
|
3195
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
3196
|
+
}
|
|
3197
|
+
function getWLengths(Fp, Fn) {
|
|
3198
|
+
return {
|
|
3199
|
+
secretKey: Fn.BYTES,
|
|
3200
|
+
publicKey: 1 + Fp.BYTES,
|
|
3201
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
3202
|
+
publicKeyHasPrefix: true,
|
|
3203
|
+
signature: 2 * Fn.BYTES
|
|
3204
|
+
};
|
|
3205
|
+
}
|
|
3206
|
+
/**
|
|
3207
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3208
|
+
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
|
|
3209
|
+
* @param Point - Weierstrass point constructor.
|
|
3210
|
+
* @param ecdhOpts - Optional randomness helpers:
|
|
3211
|
+
* - `randomBytes` (optional): Optional RNG override.
|
|
3212
|
+
* @returns ECDH helper namespace.
|
|
3213
|
+
* @example
|
|
3214
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
3215
|
+
*
|
|
3216
|
+
* ```ts
|
|
3217
|
+
* import { ecdh } from '@noble/curves/abstract/weierstrass.js';
|
|
3218
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3219
|
+
* const dh = ecdh(p256.Point);
|
|
3220
|
+
* const alice = dh.keygen();
|
|
3221
|
+
* const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);
|
|
3222
|
+
* ```
|
|
3223
|
+
*/
|
|
3224
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
3225
|
+
validatePointCons(Point);
|
|
3226
|
+
const { Fn } = Point;
|
|
3227
|
+
const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes$1 : ecdhOpts.randomBytes;
|
|
3228
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: Math.max(getMinHashLength(Fn.ORDER), 16) });
|
|
3229
|
+
function isValidSecretKey(secretKey) {
|
|
3230
|
+
try {
|
|
3231
|
+
const num = Fn.fromBytes(secretKey);
|
|
3232
|
+
return Fn.isValidNot0(num);
|
|
3233
|
+
} catch (error) {
|
|
3234
|
+
return false;
|
|
3235
|
+
}
|
|
3236
|
+
}
|
|
3237
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
3238
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
3239
|
+
try {
|
|
3240
|
+
const l = publicKey.length;
|
|
3241
|
+
if (isCompressed === true && l !== comp) return false;
|
|
3242
|
+
if (isCompressed === false && l !== publicKeyUncompressed) return false;
|
|
3243
|
+
return !Point.fromBytes(publicKey).is0();
|
|
3244
|
+
} catch (error) {
|
|
3245
|
+
return false;
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* Produces cryptographically secure secret key from random of size
|
|
3250
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
3251
|
+
*/
|
|
3252
|
+
function randomSecretKey(seed) {
|
|
3253
|
+
seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
|
|
3254
|
+
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
3255
|
+
}
|
|
3256
|
+
/**
|
|
3257
|
+
* Computes public key for a secret key. Checks for validity of the secret key.
|
|
3258
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3259
|
+
* @returns Public key, full when isCompressed=false; short when isCompressed=true
|
|
3260
|
+
*/
|
|
3261
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
3262
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
3263
|
+
}
|
|
3264
|
+
/**
|
|
3265
|
+
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
|
|
3266
|
+
*/
|
|
3267
|
+
function isProbPub(item) {
|
|
3268
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
3269
|
+
const allowedLengths = Fn._lengths;
|
|
3270
|
+
if (!isBytes(item)) return void 0;
|
|
3271
|
+
const l = abytes(item, void 0, "key").length;
|
|
3272
|
+
const isPub = l === publicKey || l === publicKeyUncompressed;
|
|
3273
|
+
const isSec = l === secretKey || !!allowedLengths?.includes(l);
|
|
3274
|
+
if (isPub && isSec) return void 0;
|
|
3275
|
+
return isPub;
|
|
3276
|
+
}
|
|
3277
|
+
/**
|
|
3278
|
+
* ECDH (Elliptic Curve Diffie Hellman).
|
|
3279
|
+
* Computes encoded shared point from secret key A and public key B.
|
|
3280
|
+
* Checks: 1) secret key validity 2) shared key is on-curve.
|
|
3281
|
+
* Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.
|
|
3282
|
+
* Returns the encoded shared point on purpose: callers that need `x_P`
|
|
3283
|
+
* can derive it from the encoded point, but `x_P` alone cannot recover the
|
|
3284
|
+
* point/parity back.
|
|
3285
|
+
* This helper only exposes the fully validated public-key path, not cofactor DH.
|
|
3286
|
+
* @param isCompressed - whether to return compact (default), or full key
|
|
3287
|
+
* @returns shared point encoding
|
|
3288
|
+
*/
|
|
3289
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
3290
|
+
if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
|
|
3291
|
+
if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
|
|
3292
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
3293
|
+
const b = Point.fromBytes(publicKeyB);
|
|
3294
|
+
if (b.is0()) throw new Error("invalid public key: point at infinity");
|
|
3295
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
3296
|
+
}
|
|
3297
|
+
const utils = {
|
|
3298
|
+
isValidSecretKey,
|
|
3299
|
+
isValidPublicKey,
|
|
3300
|
+
randomSecretKey
|
|
3301
|
+
};
|
|
3302
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey);
|
|
3303
|
+
Object.freeze(utils);
|
|
3304
|
+
Object.freeze(lengths);
|
|
3305
|
+
return Object.freeze({
|
|
3306
|
+
getPublicKey,
|
|
3307
|
+
getSharedSecret,
|
|
3308
|
+
keygen,
|
|
3309
|
+
Point,
|
|
3310
|
+
utils,
|
|
3311
|
+
lengths
|
|
3312
|
+
});
|
|
3313
|
+
}
|
|
3314
|
+
/**
|
|
3315
|
+
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
|
|
3316
|
+
*
|
|
3317
|
+
* @param Point - created using {@link weierstrass} function
|
|
3318
|
+
* @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)
|
|
3319
|
+
* @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:
|
|
3320
|
+
* - `lowS`: Default low-S policy.
|
|
3321
|
+
* - `hmac`: HMAC implementation used by RFC6979 DRBG.
|
|
3322
|
+
* - `randomBytes`: Optional RNG override.
|
|
3323
|
+
* - `bits2int`: Optional hash-to-int conversion override.
|
|
3324
|
+
* - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.
|
|
3325
|
+
*
|
|
3326
|
+
* @returns ECDSA helper namespace.
|
|
3327
|
+
* @example
|
|
3328
|
+
* Create an ECDSA signer/verifier bundle for one curve implementation.
|
|
3329
|
+
*
|
|
3330
|
+
* ```ts
|
|
3331
|
+
* import { ecdsa } from '@noble/curves/abstract/weierstrass.js';
|
|
3332
|
+
* import { p256 } from '@noble/curves/nist.js';
|
|
3333
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
3334
|
+
* const p256ecdsa = ecdsa(p256.Point, sha256);
|
|
3335
|
+
* const { secretKey, publicKey } = p256ecdsa.keygen();
|
|
3336
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
3337
|
+
* const sig = p256ecdsa.sign(msg, secretKey);
|
|
3338
|
+
* const isValid = p256ecdsa.verify(sig, msg, publicKey);
|
|
3339
|
+
* ```
|
|
3340
|
+
*/
|
|
3341
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
3342
|
+
validatePointCons(Point);
|
|
3343
|
+
const hash_ = hash;
|
|
3344
|
+
ahash(hash_);
|
|
3345
|
+
validateObject(ecdsaOpts, {}, {
|
|
3346
|
+
hmac: "function",
|
|
3347
|
+
lowS: "boolean",
|
|
3348
|
+
randomBytes: "function",
|
|
3349
|
+
bits2int: "function",
|
|
3350
|
+
bits2int_modN: "function"
|
|
3351
|
+
});
|
|
3352
|
+
const opts = Object.assign({}, ecdsaOpts);
|
|
3353
|
+
const randomBytes = opts.randomBytes === void 0 ? randomBytes$1 : opts.randomBytes;
|
|
3354
|
+
const hmac$1 = opts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : opts.hmac;
|
|
3355
|
+
const { Fp, Fn } = Point;
|
|
3356
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
3357
|
+
const blindLength = getMinHashLength(CURVE_ORDER);
|
|
3358
|
+
const csprng = probeRandomBytes(randomBytes, blindLength);
|
|
3359
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);
|
|
3360
|
+
const defaultSigOpts = {
|
|
3361
|
+
prehash: true,
|
|
3362
|
+
lowS: typeof opts.lowS === "boolean" ? opts.lowS : true,
|
|
3363
|
+
format: "compact",
|
|
3364
|
+
extraEntropy: false
|
|
3365
|
+
};
|
|
3366
|
+
const hasLargeRecoveryLifts = CURVE_ORDER * _2n$1 + _1n < Fp.ORDER;
|
|
3367
|
+
function isBiggerThanHalfOrder(number) {
|
|
3368
|
+
return number > CURVE_ORDER >> _1n;
|
|
3369
|
+
}
|
|
3370
|
+
function validateRS(title, num) {
|
|
3371
|
+
if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
3372
|
+
return num;
|
|
3373
|
+
}
|
|
3374
|
+
function assertFieldSignIsSupported() {
|
|
3375
|
+
if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
|
|
3376
|
+
}
|
|
3377
|
+
function getRecoveryBit(x, y, r) {
|
|
3378
|
+
assertFieldSignIsSupported();
|
|
3379
|
+
return (x === r ? 0 : 2) | Number(Fp.isOdd(y));
|
|
3380
|
+
}
|
|
3381
|
+
function assertRecoverableCurve() {
|
|
3382
|
+
if (hasLargeRecoveryLifts) throw new Error("\"recovered\" sig type is not supported for cofactor >2 curves");
|
|
3383
|
+
}
|
|
3384
|
+
function validateSigLength(bytes, format) {
|
|
3385
|
+
validateSigFormat(format);
|
|
3386
|
+
const size = lengths.signature;
|
|
3387
|
+
return abytes(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0);
|
|
3388
|
+
}
|
|
3389
|
+
/**
|
|
3390
|
+
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
|
|
3391
|
+
*/
|
|
3392
|
+
class Signature {
|
|
3393
|
+
r;
|
|
3394
|
+
s;
|
|
3395
|
+
recovery;
|
|
3396
|
+
constructor(r, s, recovery) {
|
|
3397
|
+
this.r = validateRS("r", r);
|
|
3398
|
+
this.s = validateRS("s", s);
|
|
3399
|
+
if (recovery != null) {
|
|
3400
|
+
assertRecoverableCurve();
|
|
3401
|
+
if (![
|
|
3402
|
+
0,
|
|
3403
|
+
1,
|
|
3404
|
+
2,
|
|
3405
|
+
3
|
|
3406
|
+
].includes(recovery)) throw new Error("invalid recovery id");
|
|
3407
|
+
this.recovery = recovery;
|
|
3408
|
+
}
|
|
3409
|
+
Object.freeze(this);
|
|
3410
|
+
}
|
|
3411
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
3412
|
+
validateSigLength(bytes, format);
|
|
3413
|
+
let recid;
|
|
3414
|
+
if (format === "der") {
|
|
3415
|
+
if (bytes.length > 2 * Fn.BYTES + 16) throw new DER.Err("invalid signature: DER signature too long");
|
|
3416
|
+
const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);
|
|
3417
|
+
return new Signature(r, s);
|
|
3418
|
+
}
|
|
3419
|
+
if (format === "recovered") {
|
|
3420
|
+
recid = bytes[0];
|
|
3421
|
+
format = "compact";
|
|
3422
|
+
bytes = bytes.subarray(1);
|
|
3423
|
+
}
|
|
3424
|
+
const L = lengths.signature / 2;
|
|
3425
|
+
const r = bytes.subarray(0, L);
|
|
3426
|
+
const s = bytes.subarray(L, L * 2);
|
|
3427
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
3428
|
+
}
|
|
3429
|
+
static fromHex(hex, format) {
|
|
3430
|
+
return this.fromBytes(hexToBytes(hex), format);
|
|
3431
|
+
}
|
|
3432
|
+
assertRecovery() {
|
|
3433
|
+
const { recovery } = this;
|
|
3434
|
+
if (recovery == null) throw new Error("invalid recovery id: must be present");
|
|
3435
|
+
return recovery;
|
|
3436
|
+
}
|
|
3437
|
+
addRecoveryBit(recovery) {
|
|
3438
|
+
return new Signature(this.r, this.s, recovery);
|
|
3439
|
+
}
|
|
3440
|
+
recoverPublicKey(messageHash) {
|
|
3441
|
+
const { r, s } = this;
|
|
3442
|
+
const recovery = this.assertRecovery();
|
|
3443
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
|
|
3444
|
+
if (!Fp.isValid(radj)) throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
3445
|
+
const x = Fp.toBytes(radj);
|
|
3446
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
3447
|
+
const ir = Fn.inv(radj);
|
|
3448
|
+
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
3449
|
+
const u1 = Fn.create(-h * ir);
|
|
3450
|
+
const u2 = Fn.create(s * ir);
|
|
3451
|
+
const Q = Point.BASE.mulAddUnsafe(u1, R, u2);
|
|
3452
|
+
if (Q.is0()) throw new Error("invalid recovery: point at infinify");
|
|
3453
|
+
Q.assertValidity();
|
|
3454
|
+
return Q;
|
|
3455
|
+
}
|
|
3456
|
+
hasHighS() {
|
|
3457
|
+
return isBiggerThanHalfOrder(this.s);
|
|
3458
|
+
}
|
|
3459
|
+
toBytes(format = defaultSigOpts.format) {
|
|
3460
|
+
validateSigFormat(format);
|
|
3461
|
+
if (format === "der") return hexToBytes(DER.hexFromSig(this));
|
|
3462
|
+
const { r, s } = this;
|
|
3463
|
+
const rb = Fn.toBytes(r);
|
|
3464
|
+
const sb = Fn.toBytes(s);
|
|
3465
|
+
if (format === "recovered") {
|
|
3466
|
+
assertRecoverableCurve();
|
|
3467
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
3468
|
+
}
|
|
3469
|
+
return concatBytes(rb, sb);
|
|
3470
|
+
}
|
|
3471
|
+
toHex(format) {
|
|
3472
|
+
return bytesToHex(this.toBytes(format));
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
Object.freeze(Signature.prototype);
|
|
3476
|
+
Object.freeze(Signature);
|
|
3477
|
+
const bits2int = opts.bits2int === void 0 ? function bits2int_def(bytes) {
|
|
3478
|
+
if (bytes.length > 8192) throw new Error("input is too large");
|
|
3479
|
+
const num = bytesToNumberBE(bytes);
|
|
3480
|
+
const delta = bytes.length * 8 - fnBits;
|
|
3481
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
3482
|
+
} : opts.bits2int;
|
|
3483
|
+
const bits2int_modN = opts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
|
|
3484
|
+
return Fn.create(bits2int(bytes));
|
|
3485
|
+
} : opts.bits2int_modN;
|
|
3486
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
3487
|
+
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
|
|
3488
|
+
function int2octets(num) {
|
|
3489
|
+
aInRange("num < 2^" + fnBits, num, _0n$1, ORDER_MASK);
|
|
3490
|
+
return Fn.toBytes(num);
|
|
3491
|
+
}
|
|
3492
|
+
function validateMsgAndHash(message, prehash) {
|
|
3493
|
+
abytes(message, void 0, "message");
|
|
3494
|
+
return prehash ? abytes(hash_(message), void 0, "prehashed message") : message;
|
|
3495
|
+
}
|
|
3496
|
+
/**
|
|
3497
|
+
* Steps A, D of RFC6979 3.2.
|
|
3498
|
+
* Creates RFC6979 seed; converts msg/privKey to numbers.
|
|
3499
|
+
* Used only in sign, not in verify.
|
|
3500
|
+
*
|
|
3501
|
+
* Warning: we cannot assume here that message has same amount of bytes as curve order,
|
|
3502
|
+
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
|
|
3503
|
+
*/
|
|
3504
|
+
function prepSig(message, secretKey, opts) {
|
|
3505
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
3506
|
+
message = validateMsgAndHash(message, prehash);
|
|
3507
|
+
const h1int = bits2int_modN(message);
|
|
3508
|
+
const d = Fn.fromBytes(secretKey);
|
|
3509
|
+
if (!Fn.isValidNot0(d)) throw new Error("invalid private key");
|
|
3510
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3511
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
3512
|
+
const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
|
|
3513
|
+
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
3514
|
+
}
|
|
3515
|
+
const seed = concatBytes(...seedArgs);
|
|
3516
|
+
const m = h1int;
|
|
3517
|
+
function k2sig(kBytes) {
|
|
3518
|
+
const k = bits2int(kBytes);
|
|
3519
|
+
if (!Fn.isValidNot0(k)) return;
|
|
3520
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
3521
|
+
const r = Fn.create(q.x);
|
|
3522
|
+
if (r === _0n$1) return;
|
|
3523
|
+
let s;
|
|
3524
|
+
if (csprng !== void 0) {
|
|
3525
|
+
const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));
|
|
3526
|
+
const ibk = Fn.inv(Fn.mul(b, k));
|
|
3527
|
+
const bm = Fn.mul(b, m);
|
|
3528
|
+
const bd = Fn.mul(b, d);
|
|
3529
|
+
s = Fn.create(ibk * Fn.create(bm + bd * r));
|
|
3530
|
+
} else {
|
|
3531
|
+
const ik = invertCt(k, CURVE_ORDER);
|
|
3532
|
+
s = Fn.create(ik * Fn.create(m + r * d));
|
|
3533
|
+
}
|
|
3534
|
+
if (s === _0n$1) return;
|
|
3535
|
+
let recovery = getRecoveryBit(q.x, q.y, r);
|
|
3536
|
+
let normS = s;
|
|
3537
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
3538
|
+
normS = Fn.neg(s);
|
|
3539
|
+
recovery ^= 1;
|
|
3540
|
+
}
|
|
3541
|
+
return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
|
|
3542
|
+
}
|
|
3543
|
+
return {
|
|
3544
|
+
seed,
|
|
3545
|
+
k2sig
|
|
3546
|
+
};
|
|
3547
|
+
}
|
|
3548
|
+
/**
|
|
3549
|
+
* Signs a message or message hash with a secret key.
|
|
3550
|
+
* With the default `prehash: true`, raw message bytes are hashed internally;
|
|
3551
|
+
* only `{ prehash: false }` expects a caller-supplied digest.
|
|
3552
|
+
*
|
|
3553
|
+
* ```
|
|
3554
|
+
* sign(m, d) where
|
|
3555
|
+
* k = rfc6979_hmac_drbg(m, d)
|
|
3556
|
+
* (x, y) = G × k
|
|
3557
|
+
* r = x mod n
|
|
3558
|
+
* s = (m + dr) / k mod n
|
|
3559
|
+
* ```
|
|
3560
|
+
*/
|
|
3561
|
+
function sign(message, secretKey, opts = {}) {
|
|
3562
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
3563
|
+
return createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac$1)(seed, k2sig).toBytes(opts.format);
|
|
3564
|
+
}
|
|
3565
|
+
/**
|
|
3566
|
+
* Verifies a signature against message and public key.
|
|
3567
|
+
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
|
|
3568
|
+
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
|
|
3569
|
+
*
|
|
3570
|
+
* ```
|
|
3571
|
+
* verify(r, s, h, P) where
|
|
3572
|
+
* u1 = hs^-1 mod n
|
|
3573
|
+
* u2 = rs^-1 mod n
|
|
3574
|
+
* R = u1⋅G + u2⋅P
|
|
3575
|
+
* mod(R.x, n) == r
|
|
3576
|
+
* ```
|
|
3577
|
+
*/
|
|
3578
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
3579
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
3580
|
+
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
3581
|
+
message = validateMsgAndHash(message, prehash);
|
|
3582
|
+
if (!isBytes(signature)) {
|
|
3583
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
3584
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
3585
|
+
}
|
|
3586
|
+
validateSigLength(signature, format);
|
|
3587
|
+
try {
|
|
3588
|
+
const sig = Signature.fromBytes(signature, format);
|
|
3589
|
+
const P = Point.fromBytes(publicKey);
|
|
3590
|
+
if (P.is0()) return false;
|
|
3591
|
+
if (lowS && sig.hasHighS()) return false;
|
|
3592
|
+
const { r, s } = sig;
|
|
3593
|
+
const h = bits2int_modN(message);
|
|
3594
|
+
const is = Fn.inv(s);
|
|
3595
|
+
const u1 = Fn.create(h * is);
|
|
3596
|
+
const u2 = Fn.create(r * is);
|
|
3597
|
+
const R = Point.BASE.mulAddUnsafe(u1, P, u2);
|
|
3598
|
+
if (R.is0()) return false;
|
|
3599
|
+
const q = R.toAffine();
|
|
3600
|
+
if (Fn.create(q.x) !== r) return false;
|
|
3601
|
+
if (format === "recovered" && sig.recovery !== getRecoveryBit(q.x, q.y, r)) return false;
|
|
3602
|
+
return true;
|
|
3603
|
+
} catch (e) {
|
|
3604
|
+
return false;
|
|
3605
|
+
}
|
|
3606
|
+
}
|
|
3607
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
3608
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
3609
|
+
message = validateMsgAndHash(message, prehash);
|
|
3610
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
3611
|
+
}
|
|
3612
|
+
return Object.freeze({
|
|
3613
|
+
keygen,
|
|
3614
|
+
getPublicKey,
|
|
3615
|
+
getSharedSecret,
|
|
3616
|
+
utils,
|
|
3617
|
+
lengths,
|
|
3618
|
+
Point,
|
|
3619
|
+
sign,
|
|
3620
|
+
verify,
|
|
3621
|
+
recoverPublicKey,
|
|
3622
|
+
Signature,
|
|
3623
|
+
hash: hash_
|
|
3624
|
+
});
|
|
3625
|
+
}
|
|
3626
|
+
//#endregion
|
|
3627
|
+
//#region ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/secp256k1.js
|
|
3628
|
+
/**
|
|
3629
|
+
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
|
|
3630
|
+
*
|
|
3631
|
+
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
|
|
3632
|
+
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
|
|
3633
|
+
* @module
|
|
3634
|
+
*/
|
|
3635
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3636
|
+
var secp256k1_CURVE = {
|
|
3637
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
3638
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
3639
|
+
h: BigInt(1),
|
|
3640
|
+
a: BigInt(0),
|
|
3641
|
+
b: BigInt(7),
|
|
3642
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
3643
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
3644
|
+
};
|
|
3645
|
+
var secp256k1_ENDO = {
|
|
3646
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
3647
|
+
basises: [[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]
|
|
3648
|
+
};
|
|
3649
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
3650
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
3651
|
+
/**
|
|
3652
|
+
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
|
|
3653
|
+
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
|
|
3654
|
+
*/
|
|
3655
|
+
function sqrtMod(y) {
|
|
3656
|
+
const P = secp256k1_CURVE.p;
|
|
3657
|
+
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
3658
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
3659
|
+
const b2 = y * y * y % P;
|
|
3660
|
+
const b3 = b2 * b2 * y % P;
|
|
3661
|
+
const b11 = pow2(pow2(pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
|
|
3662
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
3663
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
3664
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
3665
|
+
const root = pow2(pow2(pow2(pow2(pow2(pow2(b88, _88n, P) * b88 % P, _44n, P) * b44 % P, _3n, P) * b3 % P, _23n, P) * b22 % P, _6n, P) * b2 % P, _2n, P);
|
|
3666
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
|
|
3667
|
+
return root;
|
|
3668
|
+
}
|
|
3669
|
+
var Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
3670
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
3671
|
+
Fp: Fpk1,
|
|
3672
|
+
endo: secp256k1_ENDO
|
|
3673
|
+
});
|
|
3674
|
+
/**
|
|
3675
|
+
* secp256k1 curve: ECDSA and ECDH methods.
|
|
3676
|
+
*
|
|
3677
|
+
* Uses sha256 to hash messages. To use a different hash,
|
|
3678
|
+
* pass `{ prehash: false }` to sign / verify.
|
|
3679
|
+
*
|
|
3680
|
+
* @example
|
|
3681
|
+
* Generate one secp256k1 keypair, sign a message, and verify it.
|
|
3682
|
+
*
|
|
3683
|
+
* ```js
|
|
3684
|
+
* import { secp256k1 } from '@noble/curves/secp256k1.js';
|
|
3685
|
+
* const { secretKey, publicKey } = secp256k1.keygen();
|
|
3686
|
+
* // const publicKey = secp256k1.getPublicKey(secretKey);
|
|
3687
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
3688
|
+
* const sig = secp256k1.sign(msg, secretKey);
|
|
3689
|
+
* const isValid = secp256k1.verify(sig, msg, publicKey);
|
|
3690
|
+
* // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });
|
|
3691
|
+
* ```
|
|
3692
|
+
*/
|
|
3693
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
|
|
3694
|
+
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
|
|
3695
|
+
var TAGGED_HASH_PREFIXES = Object.create(null);
|
|
3696
|
+
function taggedHash(tag, ...messages) {
|
|
3697
|
+
let tagP = TAGGED_HASH_PREFIXES[tag];
|
|
3698
|
+
if (tagP === void 0) {
|
|
3699
|
+
const tagH = sha256(asciiToBytes(tag));
|
|
3700
|
+
tagP = concatBytes(tagH, tagH);
|
|
3701
|
+
TAGGED_HASH_PREFIXES[tag] = tagP;
|
|
3702
|
+
}
|
|
3703
|
+
return sha256(concatBytes(tagP, ...messages));
|
|
3704
|
+
}
|
|
3705
|
+
var pointToBytes = (point) => point.toBytes(true).slice(1);
|
|
3706
|
+
var affineXToBytes = ({ x }) => Fpk1.toBytes(x);
|
|
3707
|
+
var hasEven = (y) => !Fpk1.isOdd(y);
|
|
3708
|
+
function schnorrGetExtPubKey(priv) {
|
|
3709
|
+
const { Fn, BASE } = Pointk1;
|
|
3710
|
+
const d_ = Fn.fromBytes(abytes(priv, 32, "secretKey"));
|
|
3711
|
+
const affine = BASE.multiply(d_).toAffine();
|
|
3712
|
+
return {
|
|
3713
|
+
scalar: hasEven(affine.y) ? d_ : Fn.neg(d_),
|
|
3714
|
+
bytes: affineXToBytes(affine)
|
|
3715
|
+
};
|
|
3716
|
+
}
|
|
3717
|
+
/**
|
|
3718
|
+
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
|
|
3719
|
+
* @returns valid point checked for being on-curve
|
|
3720
|
+
*/
|
|
3721
|
+
function lift_x(x) {
|
|
3722
|
+
const Fp = Fpk1;
|
|
3723
|
+
if (!Fp.isValidNot0(x)) throw new Error("invalid x: Fail if x ≥ p");
|
|
3724
|
+
const xx = Fp.sqr(x);
|
|
3725
|
+
const c = Fp.add(Fp.mulN(xx, x), BigInt(7));
|
|
3726
|
+
let y = Fp.sqrt(c);
|
|
3727
|
+
if (!hasEven(y)) y = Fp.neg(y);
|
|
3728
|
+
const p = Pointk1.fromAffine({
|
|
3729
|
+
x,
|
|
3730
|
+
y
|
|
3731
|
+
});
|
|
3732
|
+
p.assertValidity();
|
|
3733
|
+
return p;
|
|
3734
|
+
}
|
|
3735
|
+
var num = bytesToNumberBE;
|
|
3736
|
+
/** Create tagged hash, convert it to bigint, reduce modulo-n. */
|
|
3737
|
+
function challenge(...args) {
|
|
3738
|
+
return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args)));
|
|
3739
|
+
}
|
|
3740
|
+
/** Schnorr public key is just `x` coordinate of Point as per BIP340. */
|
|
3741
|
+
function schnorrGetPublicKey(secretKey) {
|
|
3742
|
+
return schnorrGetExtPubKey(secretKey).bytes;
|
|
3743
|
+
}
|
|
3744
|
+
/**
|
|
3745
|
+
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
|
|
3746
|
+
* `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not
|
|
3747
|
+
* be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden
|
|
3748
|
+
* deterministic signing against side-channel and fault-injection attacks.
|
|
3749
|
+
*/
|
|
3750
|
+
function schnorrSign(message, secretKey, auxRand = randomBytes$2(32)) {
|
|
3751
|
+
const { Fn, BASE } = Pointk1;
|
|
3752
|
+
const m = copyBytes(abytes(message, void 0, "message"));
|
|
3753
|
+
const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey);
|
|
3754
|
+
const a = abytes(auxRand, 32, "auxRand");
|
|
3755
|
+
const rand = taggedHash("BIP0340/nonce", Fn.toBytes(d ^ num(taggedHash("BIP0340/aux", a))), px, m);
|
|
3756
|
+
const k_ = Fn.create(num(rand));
|
|
3757
|
+
if (k_ === _0n) throw new Error("sign failed: k is zero");
|
|
3758
|
+
const affine = BASE.multiply(k_).toAffine();
|
|
3759
|
+
const k = hasEven(affine.y) ? k_ : Fn.neg(k_);
|
|
3760
|
+
const rx = affineXToBytes(affine);
|
|
3761
|
+
const e = challenge(rx, px, m);
|
|
3762
|
+
const sig = /* @__PURE__ */ new Uint8Array(64);
|
|
3763
|
+
sig.set(rx, 0);
|
|
3764
|
+
sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
|
|
3765
|
+
if (!schnorrVerify(sig, m, px)) throw new Error("sign: Invalid signature produced");
|
|
3766
|
+
return sig;
|
|
3767
|
+
}
|
|
3768
|
+
/**
|
|
3769
|
+
* Verifies Schnorr signature.
|
|
3770
|
+
* Will swallow errors & return false except for initial type validation of arguments.
|
|
3771
|
+
*/
|
|
3772
|
+
function schnorrVerify(signature, message, publicKey) {
|
|
3773
|
+
const { Fp, Fn, BASE } = Pointk1;
|
|
3774
|
+
const sig = abytes(signature, 64, "signature");
|
|
3775
|
+
const m = abytes(message, void 0, "message");
|
|
3776
|
+
const pub = abytes(publicKey, 32, "publicKey");
|
|
3777
|
+
try {
|
|
3778
|
+
const P = lift_x(num(pub));
|
|
3779
|
+
const rBytes = sig.subarray(0, 32);
|
|
3780
|
+
const r = num(rBytes);
|
|
3781
|
+
if (!Fp.isValidNot0(r)) return false;
|
|
3782
|
+
const s = num(sig.subarray(32, 64));
|
|
3783
|
+
if (!Fn.isValidNot0(s)) return false;
|
|
3784
|
+
const e = challenge(rBytes, pointToBytes(P), m);
|
|
3785
|
+
const R = BASE.mulAddUnsafe(s, P, Fn.neg(e));
|
|
3786
|
+
const { x, y } = R.toAffine();
|
|
3787
|
+
if (R.is0() || !hasEven(y) || !Fp.eql(x, r)) return false;
|
|
3788
|
+
return true;
|
|
3789
|
+
} catch (error) {
|
|
3790
|
+
return false;
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
/**
|
|
3794
|
+
* Schnorr signatures over secp256k1.
|
|
3795
|
+
* See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.
|
|
3796
|
+
* @example
|
|
3797
|
+
* Generate one BIP340 Schnorr keypair, sign a message, and verify it.
|
|
3798
|
+
*
|
|
3799
|
+
* ```js
|
|
3800
|
+
* import { schnorr } from '@noble/curves/secp256k1.js';
|
|
3801
|
+
* const { secretKey, publicKey } = schnorr.keygen();
|
|
3802
|
+
* // const publicKey = schnorr.getPublicKey(secretKey);
|
|
3803
|
+
* const msg = new TextEncoder().encode('hello');
|
|
3804
|
+
* const sig = schnorr.sign(msg, secretKey);
|
|
3805
|
+
* const isValid = schnorr.verify(sig, msg, publicKey);
|
|
3806
|
+
* ```
|
|
3807
|
+
*/
|
|
3808
|
+
var schnorr = /* @__PURE__ */ (() => {
|
|
3809
|
+
const size = 32;
|
|
3810
|
+
const seedLength = 48;
|
|
3811
|
+
const randomSecretKey = (seed) => {
|
|
3812
|
+
seed = seed === void 0 ? randomBytes$2(seedLength) : seed;
|
|
3813
|
+
return mapHashToField(abytes(seed, seedLength, "seed"), secp256k1_CURVE.n);
|
|
3814
|
+
};
|
|
3815
|
+
return Object.freeze({
|
|
3816
|
+
keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),
|
|
3817
|
+
getPublicKey: schnorrGetPublicKey,
|
|
3818
|
+
sign: schnorrSign,
|
|
3819
|
+
verify: schnorrVerify,
|
|
3820
|
+
Point: Pointk1,
|
|
3821
|
+
utils: Object.freeze({
|
|
3822
|
+
randomSecretKey,
|
|
3823
|
+
taggedHash,
|
|
3824
|
+
lift_x,
|
|
3825
|
+
pointToBytes
|
|
3826
|
+
}),
|
|
3827
|
+
lengths: Object.freeze({
|
|
3828
|
+
secretKey: size,
|
|
3829
|
+
publicKey: size,
|
|
3830
|
+
publicKeyHasPrefix: false,
|
|
3831
|
+
signature: size * 2,
|
|
3832
|
+
seed: seedLength
|
|
3833
|
+
})
|
|
3834
|
+
});
|
|
3835
|
+
})();
|
|
3836
|
+
//#endregion
|
|
3837
|
+
//#region src/auth/nostrCrypto.ts
|
|
3838
|
+
var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => {
|
|
3839
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3840
|
+
exports.bech32m = exports.bech32 = void 0;
|
|
3841
|
+
var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
3842
|
+
var ALPHABET_MAP = {};
|
|
3843
|
+
for (let z = 0; z < 32; z++) {
|
|
3844
|
+
const x = ALPHABET.charAt(z);
|
|
3845
|
+
ALPHABET_MAP[x] = z;
|
|
3846
|
+
}
|
|
3847
|
+
function polymodStep(pre) {
|
|
3848
|
+
const b = pre >> 25;
|
|
3849
|
+
return (pre & 33554431) << 5 ^ -(b >> 0 & 1) & 996825010 ^ -(b >> 1 & 1) & 642813549 ^ -(b >> 2 & 1) & 513874426 ^ -(b >> 3 & 1) & 1027748829 ^ -(b >> 4 & 1) & 705979059;
|
|
3850
|
+
}
|
|
3851
|
+
function prefixChk(prefix) {
|
|
3852
|
+
let chk = 1;
|
|
3853
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
3854
|
+
const c = prefix.charCodeAt(i);
|
|
3855
|
+
if (c < 33 || c > 126) return "Invalid prefix (" + prefix + ")";
|
|
3856
|
+
chk = polymodStep(chk) ^ c >> 5;
|
|
3857
|
+
}
|
|
3858
|
+
chk = polymodStep(chk);
|
|
3859
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
3860
|
+
const v = prefix.charCodeAt(i);
|
|
3861
|
+
chk = polymodStep(chk) ^ v & 31;
|
|
3862
|
+
}
|
|
3863
|
+
return chk;
|
|
3864
|
+
}
|
|
3865
|
+
function convert(data, inBits, outBits, pad) {
|
|
3866
|
+
let value = 0;
|
|
3867
|
+
let bits = 0;
|
|
3868
|
+
const maxV = (1 << outBits) - 1;
|
|
3869
|
+
const result = [];
|
|
3870
|
+
for (let i = 0; i < data.length; ++i) {
|
|
3871
|
+
value = value << inBits | data[i];
|
|
3872
|
+
bits += inBits;
|
|
3873
|
+
while (bits >= outBits) {
|
|
3874
|
+
bits -= outBits;
|
|
3875
|
+
result.push(value >> bits & maxV);
|
|
3876
|
+
}
|
|
3877
|
+
}
|
|
3878
|
+
if (pad) {
|
|
3879
|
+
if (bits > 0) result.push(value << outBits - bits & maxV);
|
|
3880
|
+
} else {
|
|
3881
|
+
if (bits >= inBits) return "Excess padding";
|
|
3882
|
+
if (value << outBits - bits & maxV) return "Non-zero padding";
|
|
3883
|
+
}
|
|
3884
|
+
return result;
|
|
3885
|
+
}
|
|
3886
|
+
function toWords(bytes) {
|
|
3887
|
+
return convert(bytes, 8, 5, true);
|
|
3888
|
+
}
|
|
3889
|
+
function fromWordsUnsafe(words) {
|
|
3890
|
+
const res = convert(words, 5, 8, false);
|
|
3891
|
+
if (Array.isArray(res)) return res;
|
|
3892
|
+
}
|
|
3893
|
+
function fromWords(words) {
|
|
3894
|
+
const res = convert(words, 5, 8, false);
|
|
3895
|
+
if (Array.isArray(res)) return res;
|
|
3896
|
+
throw new Error(res);
|
|
3897
|
+
}
|
|
3898
|
+
function getLibraryFromEncoding(encoding) {
|
|
3899
|
+
let ENCODING_CONST;
|
|
3900
|
+
if (encoding === "bech32") ENCODING_CONST = 1;
|
|
3901
|
+
else ENCODING_CONST = 734539939;
|
|
3902
|
+
function encode(prefix, words, LIMIT) {
|
|
3903
|
+
LIMIT = LIMIT || 90;
|
|
3904
|
+
if (prefix.length + 7 + words.length > LIMIT) throw new TypeError("Exceeds length limit");
|
|
3905
|
+
prefix = prefix.toLowerCase();
|
|
3906
|
+
let chk = prefixChk(prefix);
|
|
3907
|
+
if (typeof chk === "string") throw new Error(chk);
|
|
3908
|
+
let result = prefix + "1";
|
|
3909
|
+
for (let i = 0; i < words.length; ++i) {
|
|
3910
|
+
const x = words[i];
|
|
3911
|
+
if (x >> 5 !== 0) throw new Error("Non 5-bit word");
|
|
3912
|
+
chk = polymodStep(chk) ^ x;
|
|
3913
|
+
result += ALPHABET.charAt(x);
|
|
3914
|
+
}
|
|
3915
|
+
for (let i = 0; i < 6; ++i) chk = polymodStep(chk);
|
|
3916
|
+
chk ^= ENCODING_CONST;
|
|
3917
|
+
for (let i = 0; i < 6; ++i) {
|
|
3918
|
+
const v = chk >> (5 - i) * 5 & 31;
|
|
3919
|
+
result += ALPHABET.charAt(v);
|
|
3920
|
+
}
|
|
3921
|
+
return result;
|
|
3922
|
+
}
|
|
3923
|
+
function __decode(str, LIMIT) {
|
|
3924
|
+
LIMIT = LIMIT || 90;
|
|
3925
|
+
if (str.length < 8) return str + " too short";
|
|
3926
|
+
if (str.length > LIMIT) return "Exceeds length limit";
|
|
3927
|
+
const lowered = str.toLowerCase();
|
|
3928
|
+
const uppered = str.toUpperCase();
|
|
3929
|
+
if (str !== lowered && str !== uppered) return "Mixed-case string " + str;
|
|
3930
|
+
str = lowered;
|
|
3931
|
+
const split = str.lastIndexOf("1");
|
|
3932
|
+
if (split === -1) return "No separator character for " + str;
|
|
3933
|
+
if (split === 0) return "Missing prefix for " + str;
|
|
3934
|
+
const prefix = str.slice(0, split);
|
|
3935
|
+
const wordChars = str.slice(split + 1);
|
|
3936
|
+
if (wordChars.length < 6) return "Data too short";
|
|
3937
|
+
let chk = prefixChk(prefix);
|
|
3938
|
+
if (typeof chk === "string") return chk;
|
|
3939
|
+
const words = [];
|
|
3940
|
+
for (let i = 0; i < wordChars.length; ++i) {
|
|
3941
|
+
const c = wordChars.charAt(i);
|
|
3942
|
+
const v = ALPHABET_MAP[c];
|
|
3943
|
+
if (v === void 0) return "Unknown character " + c;
|
|
3944
|
+
chk = polymodStep(chk) ^ v;
|
|
3945
|
+
if (i + 6 >= wordChars.length) continue;
|
|
3946
|
+
words.push(v);
|
|
3947
|
+
}
|
|
3948
|
+
if (chk !== ENCODING_CONST) return "Invalid checksum for " + str;
|
|
3949
|
+
return {
|
|
3950
|
+
prefix,
|
|
3951
|
+
words
|
|
3952
|
+
};
|
|
3953
|
+
}
|
|
3954
|
+
function decodeUnsafe(str, LIMIT) {
|
|
3955
|
+
const res = __decode(str, LIMIT);
|
|
3956
|
+
if (typeof res === "object") return res;
|
|
3957
|
+
}
|
|
3958
|
+
function decode(str, LIMIT) {
|
|
3959
|
+
const res = __decode(str, LIMIT);
|
|
3960
|
+
if (typeof res === "object") return res;
|
|
3961
|
+
throw new Error(res);
|
|
3962
|
+
}
|
|
3963
|
+
return {
|
|
3964
|
+
decodeUnsafe,
|
|
3965
|
+
decode,
|
|
3966
|
+
encode,
|
|
3967
|
+
toWords,
|
|
3968
|
+
fromWordsUnsafe,
|
|
3969
|
+
fromWords
|
|
3970
|
+
};
|
|
3971
|
+
}
|
|
3972
|
+
exports.bech32 = getLibraryFromEncoding("bech32");
|
|
3973
|
+
exports.bech32m = getLibraryFromEncoding("bech32m");
|
|
3974
|
+
})))();
|
|
3975
|
+
function generateNostrKeypair() {
|
|
3976
|
+
const privkeyBytes = randomBytes(32);
|
|
3977
|
+
const privkey = Buffer.from(privkeyBytes).toString("hex");
|
|
3978
|
+
const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
|
|
3979
|
+
return {
|
|
3980
|
+
pubkey: Buffer.from(pubkeyBytes.slice(1)).toString("hex"),
|
|
3981
|
+
privkey
|
|
3982
|
+
};
|
|
3983
|
+
}
|
|
3984
|
+
function deriveEncryptionKey(masterSecret) {
|
|
3985
|
+
const salt = Buffer.from("nostr-privkey-encryption", "utf8");
|
|
3986
|
+
const info = Buffer.from("aes-256-gcm", "utf8");
|
|
3987
|
+
const keyMaterial = Buffer.from(masterSecret, "utf8");
|
|
3988
|
+
return Buffer.from(hkdfSync("sha256", keyMaterial, salt, info, 32));
|
|
3989
|
+
}
|
|
3990
|
+
function encryptPrivkey(privkey, masterSecret) {
|
|
3991
|
+
const key = deriveEncryptionKey(masterSecret);
|
|
3992
|
+
const iv = randomBytes(12);
|
|
3993
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
3994
|
+
const encrypted = Buffer.concat([cipher.update(privkey, "utf8"), cipher.final()]);
|
|
3995
|
+
const tag = cipher.getAuthTag();
|
|
3996
|
+
return {
|
|
3997
|
+
ciphertext: encrypted.toString("base64"),
|
|
3998
|
+
iv: iv.toString("base64"),
|
|
3999
|
+
tag: tag.toString("base64")
|
|
4000
|
+
};
|
|
4001
|
+
}
|
|
4002
|
+
function decryptPrivkey(encrypted, masterSecret) {
|
|
4003
|
+
const key = deriveEncryptionKey(masterSecret);
|
|
4004
|
+
const iv = Buffer.from(encrypted.iv, "base64");
|
|
4005
|
+
const tag = Buffer.from(encrypted.tag, "base64");
|
|
4006
|
+
const ciphertext = Buffer.from(encrypted.ciphertext, "base64");
|
|
4007
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
4008
|
+
decipher.setAuthTag(tag);
|
|
4009
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
4010
|
+
}
|
|
4011
|
+
function computeEventId(event) {
|
|
4012
|
+
const serialized = JSON.stringify([
|
|
4013
|
+
0,
|
|
4014
|
+
event.pubkey,
|
|
4015
|
+
event.created_at,
|
|
4016
|
+
event.kind,
|
|
4017
|
+
event.tags,
|
|
4018
|
+
event.content
|
|
4019
|
+
]);
|
|
4020
|
+
return createHash("sha256").update(serialized).digest("hex");
|
|
4021
|
+
}
|
|
4022
|
+
function signEvent(event, privkey) {
|
|
4023
|
+
const id = computeEventId(event);
|
|
4024
|
+
const privkeyBytes = Buffer.from(privkey, "hex");
|
|
4025
|
+
const idBytes = Buffer.from(id, "hex");
|
|
4026
|
+
const sig = schnorr.sign(idBytes, privkeyBytes);
|
|
4027
|
+
const sigHex = Buffer.from(sig).toString("hex");
|
|
4028
|
+
return {
|
|
4029
|
+
...event,
|
|
4030
|
+
id,
|
|
4031
|
+
sig: sigHex
|
|
4032
|
+
};
|
|
4033
|
+
}
|
|
4034
|
+
function verifyNostrSignature(event) {
|
|
4035
|
+
if (!event.id || !event.sig) return false;
|
|
4036
|
+
if (computeEventId(event) !== event.id) return false;
|
|
4037
|
+
try {
|
|
4038
|
+
const sigBytes = Buffer.from(event.sig, "hex");
|
|
4039
|
+
const idBytes = Buffer.from(event.id, "hex");
|
|
4040
|
+
const pubkeyBytes = Buffer.from(event.pubkey, "hex");
|
|
4041
|
+
return schnorr.verify(sigBytes, idBytes, pubkeyBytes);
|
|
4042
|
+
} catch {
|
|
4043
|
+
return false;
|
|
4044
|
+
}
|
|
4045
|
+
}
|
|
4046
|
+
function createAuthEvent(privkey, challenge, relay) {
|
|
4047
|
+
const privkeyBytes = Buffer.from(privkey, "hex");
|
|
4048
|
+
const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
|
|
4049
|
+
const pubkey = Buffer.from(pubkeyBytes.slice(1)).toString("hex");
|
|
4050
|
+
const tags = [["challenge", challenge]];
|
|
4051
|
+
if (relay) tags.push(["relay", relay]);
|
|
4052
|
+
return signEvent({
|
|
4053
|
+
pubkey,
|
|
4054
|
+
created_at: Math.floor(Date.now() / 1e3),
|
|
4055
|
+
kind: 22242,
|
|
4056
|
+
tags,
|
|
4057
|
+
content: ""
|
|
4058
|
+
}, privkey);
|
|
4059
|
+
}
|
|
4060
|
+
function verifyAuthEvent(event, expectedChallenge, maxAgeSeconds = 300) {
|
|
4061
|
+
if (event.kind !== 22242) return {
|
|
4062
|
+
valid: false,
|
|
4063
|
+
error: "Invalid event kind"
|
|
4064
|
+
};
|
|
4065
|
+
const age = Math.floor(Date.now() / 1e3) - event.created_at;
|
|
4066
|
+
if (age > maxAgeSeconds || age < -60) return {
|
|
4067
|
+
valid: false,
|
|
4068
|
+
error: "Event expired or too far in future"
|
|
4069
|
+
};
|
|
4070
|
+
const challengeTag = event.tags.find((t) => t[0] === "challenge");
|
|
4071
|
+
if (!challengeTag || challengeTag[1] !== expectedChallenge) return {
|
|
4072
|
+
valid: false,
|
|
4073
|
+
error: "Challenge mismatch"
|
|
4074
|
+
};
|
|
4075
|
+
if (!verifyNostrSignature(event)) return {
|
|
4076
|
+
valid: false,
|
|
4077
|
+
error: "Invalid signature"
|
|
4078
|
+
};
|
|
4079
|
+
return { valid: true };
|
|
4080
|
+
}
|
|
4081
|
+
function pubkeyToNpub(pubkey) {
|
|
4082
|
+
const words = import_dist.bech32.toWords(Buffer.from(pubkey, "hex"));
|
|
4083
|
+
return import_dist.bech32.encode("npub", words, 1e3);
|
|
4084
|
+
}
|
|
4085
|
+
function npubToPubkey(npub) {
|
|
4086
|
+
const { prefix, words } = import_dist.bech32.decode(npub, 1e3);
|
|
4087
|
+
if (prefix !== "npub") throw new Error("Invalid npub prefix");
|
|
4088
|
+
return Buffer.from(import_dist.bech32.fromWords(words)).toString("hex");
|
|
4089
|
+
}
|
|
4090
|
+
function privkeyToNsec(privkey) {
|
|
4091
|
+
const words = import_dist.bech32.toWords(Buffer.from(privkey, "hex"));
|
|
4092
|
+
return import_dist.bech32.encode("nsec", words, 1e3);
|
|
4093
|
+
}
|
|
4094
|
+
function nsecToPrivkey(nsec) {
|
|
4095
|
+
const { prefix, words } = import_dist.bech32.decode(nsec, 1e3);
|
|
4096
|
+
if (prefix !== "nsec") throw new Error("Invalid nsec prefix");
|
|
4097
|
+
return Buffer.from(import_dist.bech32.fromWords(words)).toString("hex");
|
|
4098
|
+
}
|
|
4099
|
+
function getPublicKey(privkey) {
|
|
4100
|
+
const privkeyBytes = Buffer.from(privkey, "hex");
|
|
4101
|
+
const pubkeyBytes = secp256k1.getPublicKey(privkeyBytes, true);
|
|
4102
|
+
return Buffer.from(pubkeyBytes.slice(1)).toString("hex");
|
|
4103
|
+
}
|
|
4104
|
+
function isValidPubkey(pubkey) {
|
|
4105
|
+
if (!/^[0-9a-f]{64}$/i.test(pubkey)) return false;
|
|
4106
|
+
try {
|
|
4107
|
+
const fullPubkey = Buffer.from(`02${pubkey}`, "hex");
|
|
4108
|
+
secp256k1.Point.fromBytes(fullPubkey);
|
|
4109
|
+
return true;
|
|
4110
|
+
} catch {
|
|
4111
|
+
return false;
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
function isValidPrivkey(privkey) {
|
|
4115
|
+
if (!/^[0-9a-f]{64}$/i.test(privkey)) return false;
|
|
4116
|
+
try {
|
|
4117
|
+
const privkeyBytes = Buffer.from(privkey, "hex");
|
|
4118
|
+
secp256k1.getPublicKey(privkeyBytes);
|
|
4119
|
+
return true;
|
|
4120
|
+
} catch {
|
|
4121
|
+
return false;
|
|
4122
|
+
}
|
|
4123
|
+
}
|
|
4124
|
+
//#endregion
|
|
4125
|
+
//#region src/models/NostrIdentity.ts
|
|
4126
|
+
var NostrIdentity_exports = /* @__PURE__ */ __exportAll({ NostrIdentity: () => NostrIdentity });
|
|
4127
|
+
var __defProp = Object.defineProperty;
|
|
4128
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4129
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
4130
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
4131
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
4132
|
+
if (kind && result) __defProp(target, key, result);
|
|
4133
|
+
return result;
|
|
4134
|
+
};
|
|
4135
|
+
var NostrIdentity = class extends SmrtObject {
|
|
4136
|
+
profileId;
|
|
4137
|
+
pubkey = "";
|
|
4138
|
+
/**
|
|
4139
|
+
* AES-256-GCM encrypted private key (base64-encoded ciphertext)
|
|
4140
|
+
*/
|
|
4141
|
+
encryptedPrivkey = "";
|
|
4142
|
+
/**
|
|
4143
|
+
* Initialization vector for AES-GCM decryption (base64)
|
|
4144
|
+
*/
|
|
4145
|
+
encryptionIv = "";
|
|
4146
|
+
/**
|
|
4147
|
+
* Authentication tag from AES-GCM (base64)
|
|
4148
|
+
*/
|
|
4149
|
+
encryptionTag = "";
|
|
4150
|
+
/**
|
|
4151
|
+
* Email address associated with this identity
|
|
4152
|
+
*/
|
|
4153
|
+
email = "";
|
|
4154
|
+
/**
|
|
4155
|
+
* Username for NIP-05 verification (e.g., "alice" for alice@domain.com)
|
|
4156
|
+
*/
|
|
4157
|
+
nip05Username = "";
|
|
4158
|
+
/**
|
|
4159
|
+
* Last time this identity was used for authentication
|
|
4160
|
+
*/
|
|
4161
|
+
lastUsedAt = null;
|
|
4162
|
+
/**
|
|
4163
|
+
* When this identity was verified via magic link
|
|
4164
|
+
*/
|
|
4165
|
+
verifiedAt = null;
|
|
4166
|
+
constructor(options = {}) {
|
|
4167
|
+
super(options);
|
|
4168
|
+
if (options.profileId) this.profileId = options.profileId;
|
|
4169
|
+
if (options.pubkey) this.pubkey = options.pubkey;
|
|
4170
|
+
if (options.encryptedPrivkey) this.encryptedPrivkey = options.encryptedPrivkey;
|
|
4171
|
+
if (options.encryptionIv) this.encryptionIv = options.encryptionIv;
|
|
4172
|
+
if (options.encryptionTag) this.encryptionTag = options.encryptionTag;
|
|
4173
|
+
if (options.email) this.email = options.email;
|
|
4174
|
+
if (options.nip05Username) this.nip05Username = options.nip05Username;
|
|
4175
|
+
if (options.lastUsedAt !== void 0) this.lastUsedAt = options.lastUsedAt;
|
|
4176
|
+
if (options.verifiedAt !== void 0) this.verifiedAt = options.verifiedAt;
|
|
4177
|
+
}
|
|
4178
|
+
/**
|
|
4179
|
+
* Get the linked Profile
|
|
4180
|
+
*/
|
|
4181
|
+
async getProfile() {
|
|
4182
|
+
return await this.getRelated("profileId");
|
|
4183
|
+
}
|
|
4184
|
+
/**
|
|
4185
|
+
* Find identity by public key
|
|
4186
|
+
*/
|
|
4187
|
+
static async findByPubkey(pubkey, options = {}) {
|
|
4188
|
+
const { NostrIdentityCollection } = await import("./NostrIdentityCollection-Ca74dkaL.js").then((n) => n.n);
|
|
4189
|
+
return await (await NostrIdentityCollection.create(options)).findOne({ where: { pubkey } });
|
|
4190
|
+
}
|
|
4191
|
+
/**
|
|
4192
|
+
* Find identity by email
|
|
4193
|
+
*/
|
|
4194
|
+
static async findByEmail(email, options = {}) {
|
|
4195
|
+
const { NostrIdentityCollection } = await import("./NostrIdentityCollection-Ca74dkaL.js").then((n) => n.n);
|
|
4196
|
+
return await (await NostrIdentityCollection.create(options)).findOne({ where: { email: email.toLowerCase() } });
|
|
4197
|
+
}
|
|
4198
|
+
/**
|
|
4199
|
+
* Find identity by NIP-05 username
|
|
4200
|
+
*/
|
|
4201
|
+
static async findByNip05(username, options = {}) {
|
|
4202
|
+
const { NostrIdentityCollection } = await import("./NostrIdentityCollection-Ca74dkaL.js").then((n) => n.n);
|
|
4203
|
+
return await (await NostrIdentityCollection.create(options)).findOne({ where: { nip05Username: username.toLowerCase() } });
|
|
4204
|
+
}
|
|
4205
|
+
/**
|
|
4206
|
+
* Decrypt the private key using the server master secret
|
|
4207
|
+
* @param masterSecret - SERVER_MASTER_SECRET from environment
|
|
4208
|
+
* @returns Hex-encoded private key
|
|
4209
|
+
*/
|
|
4210
|
+
decryptPrivkey(masterSecret) {
|
|
4211
|
+
return decryptPrivkey({
|
|
4212
|
+
ciphertext: this.encryptedPrivkey,
|
|
4213
|
+
iv: this.encryptionIv,
|
|
4214
|
+
tag: this.encryptionTag
|
|
4215
|
+
}, masterSecret);
|
|
4216
|
+
}
|
|
4217
|
+
/**
|
|
4218
|
+
* Get the full keypair (requires master secret)
|
|
4219
|
+
* @param masterSecret - SERVER_MASTER_SECRET from environment
|
|
4220
|
+
*/
|
|
4221
|
+
getKeypair(masterSecret) {
|
|
4222
|
+
const privkey = this.decryptPrivkey(masterSecret);
|
|
4223
|
+
return {
|
|
4224
|
+
pubkey: this.pubkey,
|
|
4225
|
+
privkey,
|
|
4226
|
+
npub: pubkeyToNpub(this.pubkey),
|
|
4227
|
+
nsec: privkeyToNsec(privkey)
|
|
4228
|
+
};
|
|
4229
|
+
}
|
|
4230
|
+
/**
|
|
4231
|
+
* Record usage of this identity
|
|
4232
|
+
*/
|
|
4233
|
+
async recordUsage() {
|
|
4234
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
4235
|
+
if (this.isPersisted) await this.loadFromId();
|
|
4236
|
+
this.lastUsedAt = /* @__PURE__ */ new Date();
|
|
4237
|
+
try {
|
|
4238
|
+
await this.save();
|
|
4239
|
+
return;
|
|
4240
|
+
} catch (error) {
|
|
4241
|
+
if (attempt === 3 || !(error instanceof Error && "code" in error && error.code === "RUNTIME_REVISION_CONFLICT")) throw error;
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
}
|
|
4245
|
+
/**
|
|
4246
|
+
* Mark this identity as verified
|
|
4247
|
+
*/
|
|
4248
|
+
async markVerified() {
|
|
4249
|
+
this.verifiedAt = /* @__PURE__ */ new Date();
|
|
4250
|
+
this.lastUsedAt = /* @__PURE__ */ new Date();
|
|
4251
|
+
await this.save();
|
|
4252
|
+
}
|
|
4253
|
+
/**
|
|
4254
|
+
* Check if this identity is verified
|
|
4255
|
+
*/
|
|
4256
|
+
isVerified() {
|
|
4257
|
+
return this.verifiedAt !== null;
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* Get the NIP-05 identifier (username@domain)
|
|
4261
|
+
* Note: Domain must be provided by the application
|
|
4262
|
+
*/
|
|
4263
|
+
getNip05Identifier(domain) {
|
|
4264
|
+
return `${this.nip05Username || this.email.split("@")[0]}@${domain}`;
|
|
4265
|
+
}
|
|
4266
|
+
};
|
|
4267
|
+
__decorateClass([foreignKey("Profile", { required: true })], NostrIdentity.prototype, "profileId", 2);
|
|
4268
|
+
__decorateClass([field({ indexed: true })], NostrIdentity.prototype, "pubkey", 2);
|
|
4269
|
+
NostrIdentity = __decorateClass([smrt({
|
|
4270
|
+
tableName: "nostr_identities",
|
|
4271
|
+
sensitive: true,
|
|
4272
|
+
api: { include: ["list", "get"] },
|
|
4273
|
+
mcp: { include: ["list", "get"] },
|
|
4274
|
+
cli: { include: ["list", "get"] }
|
|
4275
|
+
})], NostrIdentity);
|
|
4276
|
+
//#endregion
|
|
4277
|
+
export { verifyAuthEvent as _, decryptPrivkey as a, generateNostrKeypair as c, isValidPubkey as d, npubToPubkey as f, signEvent as g, pubkeyToNpub as h, createAuthEvent as i, getPublicKey as l, privkeyToNsec as m, NostrIdentity_exports as n, deriveEncryptionKey as o, nsecToPrivkey as p, computeEventId as r, encryptPrivkey as s, NostrIdentity as t, isValidPrivkey as u, verifyNostrSignature as v, __exportAll as y };
|
|
4278
|
+
|
|
4279
|
+
//# sourceMappingURL=NostrIdentity-n70E0vck.js.map
|