@ternent/seal-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2068 @@
1
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ function isBytes(a) {
3
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
4
+ }
5
+ function anumber(n, title = "") {
6
+ if (!Number.isSafeInteger(n) || n < 0) {
7
+ const prefix = title && `"${title}" `;
8
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9
+ }
10
+ }
11
+ function abytes(value, length, title = "") {
12
+ const bytes = isBytes(value);
13
+ const len = value?.length;
14
+ const needsLen = length !== void 0;
15
+ if (!bytes || needsLen && len !== length) {
16
+ const prefix = title && `"${title}" `;
17
+ const ofLen = needsLen ? ` of length ${length}` : "";
18
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
19
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
20
+ }
21
+ return value;
22
+ }
23
+ function aexists(instance, checkFinished = true) {
24
+ if (instance.destroyed)
25
+ throw new Error("Hash instance has been destroyed");
26
+ if (checkFinished && instance.finished)
27
+ throw new Error("Hash#digest() has already been called");
28
+ }
29
+ function aoutput(out, instance) {
30
+ abytes(out, void 0, "digestInto() output");
31
+ const min = instance.outputLen;
32
+ if (out.length < min) {
33
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
34
+ }
35
+ }
36
+ function clean(...arrays) {
37
+ for (let i = 0; i < arrays.length; i++) {
38
+ arrays[i].fill(0);
39
+ }
40
+ }
41
+ function createView(arr) {
42
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
43
+ }
44
+ function rotr(word, shift) {
45
+ return word << 32 - shift | word >>> shift;
46
+ }
47
+ const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
48
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
49
+ function bytesToHex$1(bytes) {
50
+ abytes(bytes);
51
+ if (hasHexBuiltin)
52
+ return bytes.toHex();
53
+ let hex = "";
54
+ for (let i = 0; i < bytes.length; i++) {
55
+ hex += hexes[bytes[i]];
56
+ }
57
+ return hex;
58
+ }
59
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
60
+ function asciiToBase16(ch) {
61
+ if (ch >= asciis._0 && ch <= asciis._9)
62
+ return ch - asciis._0;
63
+ if (ch >= asciis.A && ch <= asciis.F)
64
+ return ch - (asciis.A - 10);
65
+ if (ch >= asciis.a && ch <= asciis.f)
66
+ return ch - (asciis.a - 10);
67
+ return;
68
+ }
69
+ function hexToBytes(hex) {
70
+ if (typeof hex !== "string")
71
+ throw new Error("hex string expected, got " + typeof hex);
72
+ if (hasHexBuiltin)
73
+ return Uint8Array.fromHex(hex);
74
+ const hl = hex.length;
75
+ const al = hl / 2;
76
+ if (hl % 2)
77
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
78
+ const array = new Uint8Array(al);
79
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
80
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
81
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
82
+ if (n1 === void 0 || n2 === void 0) {
83
+ const char = hex[hi] + hex[hi + 1];
84
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
85
+ }
86
+ array[ai] = n1 * 16 + n2;
87
+ }
88
+ return array;
89
+ }
90
+ function concatBytes$1(...arrays) {
91
+ let sum = 0;
92
+ for (let i = 0; i < arrays.length; i++) {
93
+ const a = arrays[i];
94
+ abytes(a);
95
+ sum += a.length;
96
+ }
97
+ const res = new Uint8Array(sum);
98
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
99
+ const a = arrays[i];
100
+ res.set(a, pad);
101
+ pad += a.length;
102
+ }
103
+ return res;
104
+ }
105
+ function createHasher(hashCons, info = {}) {
106
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
107
+ const tmp = hashCons(void 0);
108
+ hashC.outputLen = tmp.outputLen;
109
+ hashC.blockLen = tmp.blockLen;
110
+ hashC.create = (opts) => hashCons(opts);
111
+ Object.assign(hashC, info);
112
+ return Object.freeze(hashC);
113
+ }
114
+ function randomBytes(bytesLength = 32) {
115
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
116
+ if (typeof cr?.getRandomValues !== "function")
117
+ throw new Error("crypto.getRandomValues must be defined");
118
+ return cr.getRandomValues(new Uint8Array(bytesLength));
119
+ }
120
+ const oidNist = (suffix) => ({
121
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
122
+ });
123
+ function Chi(a, b, c) {
124
+ return a & b ^ ~a & c;
125
+ }
126
+ function Maj(a, b, c) {
127
+ return a & b ^ a & c ^ b & c;
128
+ }
129
+ class HashMD {
130
+ blockLen;
131
+ outputLen;
132
+ padOffset;
133
+ isLE;
134
+ buffer;
135
+ view;
136
+ finished = false;
137
+ length = 0;
138
+ pos = 0;
139
+ destroyed = false;
140
+ constructor(blockLen, outputLen, padOffset, isLE) {
141
+ this.blockLen = blockLen;
142
+ this.outputLen = outputLen;
143
+ this.padOffset = padOffset;
144
+ this.isLE = isLE;
145
+ this.buffer = new Uint8Array(blockLen);
146
+ this.view = createView(this.buffer);
147
+ }
148
+ update(data) {
149
+ aexists(this);
150
+ abytes(data);
151
+ const { view, buffer, blockLen } = this;
152
+ const len = data.length;
153
+ for (let pos = 0; pos < len; ) {
154
+ const take = Math.min(blockLen - this.pos, len - pos);
155
+ if (take === blockLen) {
156
+ const dataView = createView(data);
157
+ for (; blockLen <= len - pos; pos += blockLen)
158
+ this.process(dataView, pos);
159
+ continue;
160
+ }
161
+ buffer.set(data.subarray(pos, pos + take), this.pos);
162
+ this.pos += take;
163
+ pos += take;
164
+ if (this.pos === blockLen) {
165
+ this.process(view, 0);
166
+ this.pos = 0;
167
+ }
168
+ }
169
+ this.length += data.length;
170
+ this.roundClean();
171
+ return this;
172
+ }
173
+ digestInto(out) {
174
+ aexists(this);
175
+ aoutput(out, this);
176
+ this.finished = true;
177
+ const { buffer, view, blockLen, isLE } = this;
178
+ let { pos } = this;
179
+ buffer[pos++] = 128;
180
+ clean(this.buffer.subarray(pos));
181
+ if (this.padOffset > blockLen - pos) {
182
+ this.process(view, 0);
183
+ pos = 0;
184
+ }
185
+ for (let i = pos; i < blockLen; i++)
186
+ buffer[i] = 0;
187
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
188
+ this.process(view, 0);
189
+ const oview = createView(out);
190
+ const len = this.outputLen;
191
+ if (len % 4)
192
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
193
+ const outLen = len / 4;
194
+ const state = this.get();
195
+ if (outLen > state.length)
196
+ throw new Error("_sha2: outputLen bigger than state");
197
+ for (let i = 0; i < outLen; i++)
198
+ oview.setUint32(4 * i, state[i], isLE);
199
+ }
200
+ digest() {
201
+ const { buffer, outputLen } = this;
202
+ this.digestInto(buffer);
203
+ const res = buffer.slice(0, outputLen);
204
+ this.destroy();
205
+ return res;
206
+ }
207
+ _cloneInto(to) {
208
+ to ||= new this.constructor();
209
+ to.set(...this.get());
210
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
211
+ to.destroyed = destroyed;
212
+ to.finished = finished;
213
+ to.length = length;
214
+ to.pos = pos;
215
+ if (length % blockLen)
216
+ to.buffer.set(buffer);
217
+ return to;
218
+ }
219
+ clone() {
220
+ return this._cloneInto();
221
+ }
222
+ }
223
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
224
+ 1779033703,
225
+ 3144134277,
226
+ 1013904242,
227
+ 2773480762,
228
+ 1359893119,
229
+ 2600822924,
230
+ 528734635,
231
+ 1541459225
232
+ ]);
233
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
234
+ 1779033703,
235
+ 4089235720,
236
+ 3144134277,
237
+ 2227873595,
238
+ 1013904242,
239
+ 4271175723,
240
+ 2773480762,
241
+ 1595750129,
242
+ 1359893119,
243
+ 2917565137,
244
+ 2600822924,
245
+ 725511199,
246
+ 528734635,
247
+ 4215389547,
248
+ 1541459225,
249
+ 327033209
250
+ ]);
251
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
252
+ const _32n = /* @__PURE__ */ BigInt(32);
253
+ function fromBig(n, le = false) {
254
+ if (le)
255
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
256
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
257
+ }
258
+ function split(lst, le = false) {
259
+ const len = lst.length;
260
+ let Ah = new Uint32Array(len);
261
+ let Al = new Uint32Array(len);
262
+ for (let i = 0; i < len; i++) {
263
+ const { h, l } = fromBig(lst[i], le);
264
+ [Ah[i], Al[i]] = [h, l];
265
+ }
266
+ return [Ah, Al];
267
+ }
268
+ const shrSH = (h, _l, s) => h >>> s;
269
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
270
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
271
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
272
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
273
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
274
+ function add(Ah, Al, Bh, Bl) {
275
+ const l = (Al >>> 0) + (Bl >>> 0);
276
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
277
+ }
278
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
279
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
280
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
281
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
282
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
283
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
284
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
285
+ 1116352408,
286
+ 1899447441,
287
+ 3049323471,
288
+ 3921009573,
289
+ 961987163,
290
+ 1508970993,
291
+ 2453635748,
292
+ 2870763221,
293
+ 3624381080,
294
+ 310598401,
295
+ 607225278,
296
+ 1426881987,
297
+ 1925078388,
298
+ 2162078206,
299
+ 2614888103,
300
+ 3248222580,
301
+ 3835390401,
302
+ 4022224774,
303
+ 264347078,
304
+ 604807628,
305
+ 770255983,
306
+ 1249150122,
307
+ 1555081692,
308
+ 1996064986,
309
+ 2554220882,
310
+ 2821834349,
311
+ 2952996808,
312
+ 3210313671,
313
+ 3336571891,
314
+ 3584528711,
315
+ 113926993,
316
+ 338241895,
317
+ 666307205,
318
+ 773529912,
319
+ 1294757372,
320
+ 1396182291,
321
+ 1695183700,
322
+ 1986661051,
323
+ 2177026350,
324
+ 2456956037,
325
+ 2730485921,
326
+ 2820302411,
327
+ 3259730800,
328
+ 3345764771,
329
+ 3516065817,
330
+ 3600352804,
331
+ 4094571909,
332
+ 275423344,
333
+ 430227734,
334
+ 506948616,
335
+ 659060556,
336
+ 883997877,
337
+ 958139571,
338
+ 1322822218,
339
+ 1537002063,
340
+ 1747873779,
341
+ 1955562222,
342
+ 2024104815,
343
+ 2227730452,
344
+ 2361852424,
345
+ 2428436474,
346
+ 2756734187,
347
+ 3204031479,
348
+ 3329325298
349
+ ]);
350
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
351
+ class SHA2_32B extends HashMD {
352
+ constructor(outputLen) {
353
+ super(64, outputLen, 8, false);
354
+ }
355
+ get() {
356
+ const { A, B, C, D, E, F, G, H } = this;
357
+ return [A, B, C, D, E, F, G, H];
358
+ }
359
+ set(A, B, C, D, E, F, G, H) {
360
+ this.A = A | 0;
361
+ this.B = B | 0;
362
+ this.C = C | 0;
363
+ this.D = D | 0;
364
+ this.E = E | 0;
365
+ this.F = F | 0;
366
+ this.G = G | 0;
367
+ this.H = H | 0;
368
+ }
369
+ process(view, offset) {
370
+ for (let i = 0; i < 16; i++, offset += 4)
371
+ SHA256_W[i] = view.getUint32(offset, false);
372
+ for (let i = 16; i < 64; i++) {
373
+ const W15 = SHA256_W[i - 15];
374
+ const W2 = SHA256_W[i - 2];
375
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
376
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
377
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
378
+ }
379
+ let { A, B, C, D, E, F, G, H } = this;
380
+ for (let i = 0; i < 64; i++) {
381
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
382
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
383
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
384
+ const T2 = sigma0 + Maj(A, B, C) | 0;
385
+ H = G;
386
+ G = F;
387
+ F = E;
388
+ E = D + T1 | 0;
389
+ D = C;
390
+ C = B;
391
+ B = A;
392
+ A = T1 + T2 | 0;
393
+ }
394
+ A = A + this.A | 0;
395
+ B = B + this.B | 0;
396
+ C = C + this.C | 0;
397
+ D = D + this.D | 0;
398
+ E = E + this.E | 0;
399
+ F = F + this.F | 0;
400
+ G = G + this.G | 0;
401
+ H = H + this.H | 0;
402
+ this.set(A, B, C, D, E, F, G, H);
403
+ }
404
+ roundClean() {
405
+ clean(SHA256_W);
406
+ }
407
+ destroy() {
408
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
409
+ clean(this.buffer);
410
+ }
411
+ }
412
+ class _SHA256 extends SHA2_32B {
413
+ A = SHA256_IV[0] | 0;
414
+ B = SHA256_IV[1] | 0;
415
+ C = SHA256_IV[2] | 0;
416
+ D = SHA256_IV[3] | 0;
417
+ E = SHA256_IV[4] | 0;
418
+ F = SHA256_IV[5] | 0;
419
+ G = SHA256_IV[6] | 0;
420
+ H = SHA256_IV[7] | 0;
421
+ constructor() {
422
+ super(32);
423
+ }
424
+ }
425
+ const K512 = /* @__PURE__ */ (() => split([
426
+ "0x428a2f98d728ae22",
427
+ "0x7137449123ef65cd",
428
+ "0xb5c0fbcfec4d3b2f",
429
+ "0xe9b5dba58189dbbc",
430
+ "0x3956c25bf348b538",
431
+ "0x59f111f1b605d019",
432
+ "0x923f82a4af194f9b",
433
+ "0xab1c5ed5da6d8118",
434
+ "0xd807aa98a3030242",
435
+ "0x12835b0145706fbe",
436
+ "0x243185be4ee4b28c",
437
+ "0x550c7dc3d5ffb4e2",
438
+ "0x72be5d74f27b896f",
439
+ "0x80deb1fe3b1696b1",
440
+ "0x9bdc06a725c71235",
441
+ "0xc19bf174cf692694",
442
+ "0xe49b69c19ef14ad2",
443
+ "0xefbe4786384f25e3",
444
+ "0x0fc19dc68b8cd5b5",
445
+ "0x240ca1cc77ac9c65",
446
+ "0x2de92c6f592b0275",
447
+ "0x4a7484aa6ea6e483",
448
+ "0x5cb0a9dcbd41fbd4",
449
+ "0x76f988da831153b5",
450
+ "0x983e5152ee66dfab",
451
+ "0xa831c66d2db43210",
452
+ "0xb00327c898fb213f",
453
+ "0xbf597fc7beef0ee4",
454
+ "0xc6e00bf33da88fc2",
455
+ "0xd5a79147930aa725",
456
+ "0x06ca6351e003826f",
457
+ "0x142929670a0e6e70",
458
+ "0x27b70a8546d22ffc",
459
+ "0x2e1b21385c26c926",
460
+ "0x4d2c6dfc5ac42aed",
461
+ "0x53380d139d95b3df",
462
+ "0x650a73548baf63de",
463
+ "0x766a0abb3c77b2a8",
464
+ "0x81c2c92e47edaee6",
465
+ "0x92722c851482353b",
466
+ "0xa2bfe8a14cf10364",
467
+ "0xa81a664bbc423001",
468
+ "0xc24b8b70d0f89791",
469
+ "0xc76c51a30654be30",
470
+ "0xd192e819d6ef5218",
471
+ "0xd69906245565a910",
472
+ "0xf40e35855771202a",
473
+ "0x106aa07032bbd1b8",
474
+ "0x19a4c116b8d2d0c8",
475
+ "0x1e376c085141ab53",
476
+ "0x2748774cdf8eeb99",
477
+ "0x34b0bcb5e19b48a8",
478
+ "0x391c0cb3c5c95a63",
479
+ "0x4ed8aa4ae3418acb",
480
+ "0x5b9cca4f7763e373",
481
+ "0x682e6ff3d6b2b8a3",
482
+ "0x748f82ee5defb2fc",
483
+ "0x78a5636f43172f60",
484
+ "0x84c87814a1f0ab72",
485
+ "0x8cc702081a6439ec",
486
+ "0x90befffa23631e28",
487
+ "0xa4506cebde82bde9",
488
+ "0xbef9a3f7b2c67915",
489
+ "0xc67178f2e372532b",
490
+ "0xca273eceea26619c",
491
+ "0xd186b8c721c0c207",
492
+ "0xeada7dd6cde0eb1e",
493
+ "0xf57d4f7fee6ed178",
494
+ "0x06f067aa72176fba",
495
+ "0x0a637dc5a2c898a6",
496
+ "0x113f9804bef90dae",
497
+ "0x1b710b35131c471b",
498
+ "0x28db77f523047d84",
499
+ "0x32caab7b40c72493",
500
+ "0x3c9ebe0a15c9bebc",
501
+ "0x431d67c49c100d4c",
502
+ "0x4cc5d4becb3e42b6",
503
+ "0x597f299cfc657e2a",
504
+ "0x5fcb6fab3ad6faec",
505
+ "0x6c44198c4a475817"
506
+ ].map((n) => BigInt(n))))();
507
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
508
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
509
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
510
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
511
+ class SHA2_64B extends HashMD {
512
+ constructor(outputLen) {
513
+ super(128, outputLen, 16, false);
514
+ }
515
+ get() {
516
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
517
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
518
+ }
519
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
520
+ this.Ah = Ah | 0;
521
+ this.Al = Al | 0;
522
+ this.Bh = Bh | 0;
523
+ this.Bl = Bl | 0;
524
+ this.Ch = Ch | 0;
525
+ this.Cl = Cl | 0;
526
+ this.Dh = Dh | 0;
527
+ this.Dl = Dl | 0;
528
+ this.Eh = Eh | 0;
529
+ this.El = El | 0;
530
+ this.Fh = Fh | 0;
531
+ this.Fl = Fl | 0;
532
+ this.Gh = Gh | 0;
533
+ this.Gl = Gl | 0;
534
+ this.Hh = Hh | 0;
535
+ this.Hl = Hl | 0;
536
+ }
537
+ process(view, offset) {
538
+ for (let i = 0; i < 16; i++, offset += 4) {
539
+ SHA512_W_H[i] = view.getUint32(offset);
540
+ SHA512_W_L[i] = view.getUint32(offset += 4);
541
+ }
542
+ for (let i = 16; i < 80; i++) {
543
+ const W15h = SHA512_W_H[i - 15] | 0;
544
+ const W15l = SHA512_W_L[i - 15] | 0;
545
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
546
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
547
+ const W2h = SHA512_W_H[i - 2] | 0;
548
+ const W2l = SHA512_W_L[i - 2] | 0;
549
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
550
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
551
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
552
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
553
+ SHA512_W_H[i] = SUMh | 0;
554
+ SHA512_W_L[i] = SUMl | 0;
555
+ }
556
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
557
+ for (let i = 0; i < 80; i++) {
558
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
559
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
560
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
561
+ const CHIl = El & Fl ^ ~El & Gl;
562
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
563
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
564
+ const T1l = T1ll | 0;
565
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
566
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
567
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
568
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
569
+ Hh = Gh | 0;
570
+ Hl = Gl | 0;
571
+ Gh = Fh | 0;
572
+ Gl = Fl | 0;
573
+ Fh = Eh | 0;
574
+ Fl = El | 0;
575
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
576
+ Dh = Ch | 0;
577
+ Dl = Cl | 0;
578
+ Ch = Bh | 0;
579
+ Cl = Bl | 0;
580
+ Bh = Ah | 0;
581
+ Bl = Al | 0;
582
+ const All = add3L(T1l, sigma0l, MAJl);
583
+ Ah = add3H(All, T1h, sigma0h, MAJh);
584
+ Al = All | 0;
585
+ }
586
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
587
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
588
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
589
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
590
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
591
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
592
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
593
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
594
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
595
+ }
596
+ roundClean() {
597
+ clean(SHA512_W_H, SHA512_W_L);
598
+ }
599
+ destroy() {
600
+ clean(this.buffer);
601
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
602
+ }
603
+ }
604
+ class _SHA512 extends SHA2_64B {
605
+ Ah = SHA512_IV[0] | 0;
606
+ Al = SHA512_IV[1] | 0;
607
+ Bh = SHA512_IV[2] | 0;
608
+ Bl = SHA512_IV[3] | 0;
609
+ Ch = SHA512_IV[4] | 0;
610
+ Cl = SHA512_IV[5] | 0;
611
+ Dh = SHA512_IV[6] | 0;
612
+ Dl = SHA512_IV[7] | 0;
613
+ Eh = SHA512_IV[8] | 0;
614
+ El = SHA512_IV[9] | 0;
615
+ Fh = SHA512_IV[10] | 0;
616
+ Fl = SHA512_IV[11] | 0;
617
+ Gh = SHA512_IV[12] | 0;
618
+ Gl = SHA512_IV[13] | 0;
619
+ Hh = SHA512_IV[14] | 0;
620
+ Hl = SHA512_IV[15] | 0;
621
+ constructor() {
622
+ super(64);
623
+ }
624
+ }
625
+ const sha256 = /* @__PURE__ */ createHasher(
626
+ () => new _SHA256(),
627
+ /* @__PURE__ */ oidNist(1)
628
+ );
629
+ const sha512 = /* @__PURE__ */ createHasher(
630
+ () => new _SHA512(),
631
+ /* @__PURE__ */ oidNist(3)
632
+ );
633
+ const _0n$4 = /* @__PURE__ */ BigInt(0);
634
+ const _1n$4 = /* @__PURE__ */ BigInt(1);
635
+ function abool(value, title = "") {
636
+ if (typeof value !== "boolean") {
637
+ const prefix = title && `"${title}" `;
638
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
639
+ }
640
+ return value;
641
+ }
642
+ function abignumber(n) {
643
+ if (typeof n === "bigint") {
644
+ if (!isPosBig(n))
645
+ throw new Error("positive bigint expected, got " + n);
646
+ } else
647
+ anumber(n);
648
+ return n;
649
+ }
650
+ function hexToNumber(hex) {
651
+ if (typeof hex !== "string")
652
+ throw new Error("hex string expected, got " + typeof hex);
653
+ return hex === "" ? _0n$4 : BigInt("0x" + hex);
654
+ }
655
+ function bytesToNumberBE(bytes) {
656
+ return hexToNumber(bytesToHex$1(bytes));
657
+ }
658
+ function bytesToNumberLE(bytes) {
659
+ return hexToNumber(bytesToHex$1(copyBytes(abytes(bytes)).reverse()));
660
+ }
661
+ function numberToBytesBE(n, len) {
662
+ anumber(len);
663
+ n = abignumber(n);
664
+ const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
665
+ if (res.length !== len)
666
+ throw new Error("number too large");
667
+ return res;
668
+ }
669
+ function numberToBytesLE(n, len) {
670
+ return numberToBytesBE(n, len).reverse();
671
+ }
672
+ function equalBytes(a, b) {
673
+ if (a.length !== b.length)
674
+ return false;
675
+ let diff = 0;
676
+ for (let i = 0; i < a.length; i++)
677
+ diff |= a[i] ^ b[i];
678
+ return diff === 0;
679
+ }
680
+ function copyBytes(bytes) {
681
+ return Uint8Array.from(bytes);
682
+ }
683
+ const isPosBig = (n) => typeof n === "bigint" && _0n$4 <= n;
684
+ function inRange(n, min, max) {
685
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
686
+ }
687
+ function aInRange(title, n, min, max) {
688
+ if (!inRange(n, min, max))
689
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
690
+ }
691
+ const bitMask = (n) => (_1n$4 << BigInt(n)) - _1n$4;
692
+ function validateObject(object, fields = {}, optFields = {}) {
693
+ if (!object || typeof object !== "object")
694
+ throw new Error("expected valid options object");
695
+ function checkField(fieldName, expectedType, isOpt) {
696
+ const val = object[fieldName];
697
+ if (isOpt && val === void 0)
698
+ return;
699
+ const current = typeof val;
700
+ if (current !== expectedType || val === null)
701
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
702
+ }
703
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
704
+ iter(fields, false);
705
+ iter(optFields, true);
706
+ }
707
+ const notImplemented = () => {
708
+ throw new Error("not implemented");
709
+ };
710
+ function memoized(fn) {
711
+ const map = /* @__PURE__ */ new WeakMap();
712
+ return (arg, ...args) => {
713
+ const val = map.get(arg);
714
+ if (val !== void 0)
715
+ return val;
716
+ const computed = fn(arg, ...args);
717
+ map.set(arg, computed);
718
+ return computed;
719
+ };
720
+ }
721
+ const _0n$3 = /* @__PURE__ */ BigInt(0), _1n$3 = /* @__PURE__ */ BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2);
722
+ const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5);
723
+ const _7n = /* @__PURE__ */ BigInt(7), _8n$2 = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
724
+ const _16n = /* @__PURE__ */ BigInt(16);
725
+ function mod(a, b) {
726
+ const result = a % b;
727
+ return result >= _0n$3 ? result : b + result;
728
+ }
729
+ function pow2(x, power, modulo) {
730
+ let res = x;
731
+ while (power-- > _0n$3) {
732
+ res *= res;
733
+ res %= modulo;
734
+ }
735
+ return res;
736
+ }
737
+ function invert(number, modulo) {
738
+ if (number === _0n$3)
739
+ throw new Error("invert: expected non-zero number");
740
+ if (modulo <= _0n$3)
741
+ throw new Error("invert: expected positive modulus, got " + modulo);
742
+ let a = mod(number, modulo);
743
+ let b = modulo;
744
+ let x = _0n$3, u = _1n$3;
745
+ while (a !== _0n$3) {
746
+ const q = b / a;
747
+ const r = b % a;
748
+ const m = x - u * q;
749
+ b = a, a = r, x = u, u = m;
750
+ }
751
+ const gcd = b;
752
+ if (gcd !== _1n$3)
753
+ throw new Error("invert: does not exist");
754
+ return mod(x, modulo);
755
+ }
756
+ function assertIsSquare(Fp2, root, n) {
757
+ if (!Fp2.eql(Fp2.sqr(root), n))
758
+ throw new Error("Cannot find square root");
759
+ }
760
+ function sqrt3mod4(Fp2, n) {
761
+ const p1div4 = (Fp2.ORDER + _1n$3) / _4n;
762
+ const root = Fp2.pow(n, p1div4);
763
+ assertIsSquare(Fp2, root, n);
764
+ return root;
765
+ }
766
+ function sqrt5mod8(Fp2, n) {
767
+ const p5div8 = (Fp2.ORDER - _5n$1) / _8n$2;
768
+ const n2 = Fp2.mul(n, _2n$2);
769
+ const v = Fp2.pow(n2, p5div8);
770
+ const nv = Fp2.mul(n, v);
771
+ const i = Fp2.mul(Fp2.mul(nv, _2n$2), v);
772
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
773
+ assertIsSquare(Fp2, root, n);
774
+ return root;
775
+ }
776
+ function sqrt9mod16(P) {
777
+ const Fp_ = Field(P);
778
+ const tn = tonelliShanks(P);
779
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
780
+ const c2 = tn(Fp_, c1);
781
+ const c3 = tn(Fp_, Fp_.neg(c1));
782
+ const c4 = (P + _7n) / _16n;
783
+ return (Fp2, n) => {
784
+ let tv1 = Fp2.pow(n, c4);
785
+ let tv2 = Fp2.mul(tv1, c1);
786
+ const tv3 = Fp2.mul(tv1, c2);
787
+ const tv4 = Fp2.mul(tv1, c3);
788
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
789
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
790
+ tv1 = Fp2.cmov(tv1, tv2, e1);
791
+ tv2 = Fp2.cmov(tv4, tv3, e2);
792
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
793
+ const root = Fp2.cmov(tv1, tv2, e3);
794
+ assertIsSquare(Fp2, root, n);
795
+ return root;
796
+ };
797
+ }
798
+ function tonelliShanks(P) {
799
+ if (P < _3n)
800
+ throw new Error("sqrt is not defined for small field");
801
+ let Q = P - _1n$3;
802
+ let S = 0;
803
+ while (Q % _2n$2 === _0n$3) {
804
+ Q /= _2n$2;
805
+ S++;
806
+ }
807
+ let Z = _2n$2;
808
+ const _Fp = Field(P);
809
+ while (FpLegendre(_Fp, Z) === 1) {
810
+ if (Z++ > 1e3)
811
+ throw new Error("Cannot find square root: probably non-prime P");
812
+ }
813
+ if (S === 1)
814
+ return sqrt3mod4;
815
+ let cc = _Fp.pow(Z, Q);
816
+ const Q1div2 = (Q + _1n$3) / _2n$2;
817
+ return function tonelliSlow(Fp2, n) {
818
+ if (Fp2.is0(n))
819
+ return n;
820
+ if (FpLegendre(Fp2, n) !== 1)
821
+ throw new Error("Cannot find square root");
822
+ let M = S;
823
+ let c = Fp2.mul(Fp2.ONE, cc);
824
+ let t = Fp2.pow(n, Q);
825
+ let R = Fp2.pow(n, Q1div2);
826
+ while (!Fp2.eql(t, Fp2.ONE)) {
827
+ if (Fp2.is0(t))
828
+ return Fp2.ZERO;
829
+ let i = 1;
830
+ let t_tmp = Fp2.sqr(t);
831
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
832
+ i++;
833
+ t_tmp = Fp2.sqr(t_tmp);
834
+ if (i === M)
835
+ throw new Error("Cannot find square root");
836
+ }
837
+ const exponent = _1n$3 << BigInt(M - i - 1);
838
+ const b = Fp2.pow(c, exponent);
839
+ M = i;
840
+ c = Fp2.sqr(b);
841
+ t = Fp2.mul(t, c);
842
+ R = Fp2.mul(R, b);
843
+ }
844
+ return R;
845
+ };
846
+ }
847
+ function FpSqrt(P) {
848
+ if (P % _4n === _3n)
849
+ return sqrt3mod4;
850
+ if (P % _8n$2 === _5n$1)
851
+ return sqrt5mod8;
852
+ if (P % _16n === _9n)
853
+ return sqrt9mod16(P);
854
+ return tonelliShanks(P);
855
+ }
856
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$3) === _1n$3;
857
+ const FIELD_FIELDS = [
858
+ "create",
859
+ "isValid",
860
+ "is0",
861
+ "neg",
862
+ "inv",
863
+ "sqrt",
864
+ "sqr",
865
+ "eql",
866
+ "add",
867
+ "sub",
868
+ "mul",
869
+ "pow",
870
+ "div",
871
+ "addN",
872
+ "subN",
873
+ "mulN",
874
+ "sqrN"
875
+ ];
876
+ function validateField(field) {
877
+ const initial = {
878
+ ORDER: "bigint",
879
+ BYTES: "number",
880
+ BITS: "number"
881
+ };
882
+ const opts = FIELD_FIELDS.reduce((map, val) => {
883
+ map[val] = "function";
884
+ return map;
885
+ }, initial);
886
+ validateObject(field, opts);
887
+ return field;
888
+ }
889
+ function FpPow(Fp2, num, power) {
890
+ if (power < _0n$3)
891
+ throw new Error("invalid exponent, negatives unsupported");
892
+ if (power === _0n$3)
893
+ return Fp2.ONE;
894
+ if (power === _1n$3)
895
+ return num;
896
+ let p = Fp2.ONE;
897
+ let d = num;
898
+ while (power > _0n$3) {
899
+ if (power & _1n$3)
900
+ p = Fp2.mul(p, d);
901
+ d = Fp2.sqr(d);
902
+ power >>= _1n$3;
903
+ }
904
+ return p;
905
+ }
906
+ function FpInvertBatch(Fp2, nums, passZero = false) {
907
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
908
+ const multipliedAcc = nums.reduce((acc, num, i) => {
909
+ if (Fp2.is0(num))
910
+ return acc;
911
+ inverted[i] = acc;
912
+ return Fp2.mul(acc, num);
913
+ }, Fp2.ONE);
914
+ const invertedAcc = Fp2.inv(multipliedAcc);
915
+ nums.reduceRight((acc, num, i) => {
916
+ if (Fp2.is0(num))
917
+ return acc;
918
+ inverted[i] = Fp2.mul(acc, inverted[i]);
919
+ return Fp2.mul(acc, num);
920
+ }, invertedAcc);
921
+ return inverted;
922
+ }
923
+ function FpLegendre(Fp2, n) {
924
+ const p1mod2 = (Fp2.ORDER - _1n$3) / _2n$2;
925
+ const powered = Fp2.pow(n, p1mod2);
926
+ const yes = Fp2.eql(powered, Fp2.ONE);
927
+ const zero = Fp2.eql(powered, Fp2.ZERO);
928
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
929
+ if (!yes && !zero && !no)
930
+ throw new Error("invalid Legendre symbol result");
931
+ return yes ? 1 : zero ? 0 : -1;
932
+ }
933
+ function nLength(n, nBitLength) {
934
+ if (nBitLength !== void 0)
935
+ anumber(nBitLength);
936
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
937
+ const nByteLength = Math.ceil(_nBitLength / 8);
938
+ return { nBitLength: _nBitLength, nByteLength };
939
+ }
940
+ class _Field {
941
+ ORDER;
942
+ BITS;
943
+ BYTES;
944
+ isLE;
945
+ ZERO = _0n$3;
946
+ ONE = _1n$3;
947
+ _lengths;
948
+ _sqrt;
949
+ _mod;
950
+ constructor(ORDER, opts = {}) {
951
+ if (ORDER <= _0n$3)
952
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
953
+ let _nbitLength = void 0;
954
+ this.isLE = false;
955
+ if (opts != null && typeof opts === "object") {
956
+ if (typeof opts.BITS === "number")
957
+ _nbitLength = opts.BITS;
958
+ if (typeof opts.sqrt === "function")
959
+ this.sqrt = opts.sqrt;
960
+ if (typeof opts.isLE === "boolean")
961
+ this.isLE = opts.isLE;
962
+ if (opts.allowedLengths)
963
+ this._lengths = opts.allowedLengths?.slice();
964
+ if (typeof opts.modFromBytes === "boolean")
965
+ this._mod = opts.modFromBytes;
966
+ }
967
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
968
+ if (nByteLength > 2048)
969
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
970
+ this.ORDER = ORDER;
971
+ this.BITS = nBitLength;
972
+ this.BYTES = nByteLength;
973
+ this._sqrt = void 0;
974
+ Object.preventExtensions(this);
975
+ }
976
+ create(num) {
977
+ return mod(num, this.ORDER);
978
+ }
979
+ isValid(num) {
980
+ if (typeof num !== "bigint")
981
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
982
+ return _0n$3 <= num && num < this.ORDER;
983
+ }
984
+ is0(num) {
985
+ return num === _0n$3;
986
+ }
987
+ isValidNot0(num) {
988
+ return !this.is0(num) && this.isValid(num);
989
+ }
990
+ isOdd(num) {
991
+ return (num & _1n$3) === _1n$3;
992
+ }
993
+ neg(num) {
994
+ return mod(-num, this.ORDER);
995
+ }
996
+ eql(lhs, rhs) {
997
+ return lhs === rhs;
998
+ }
999
+ sqr(num) {
1000
+ return mod(num * num, this.ORDER);
1001
+ }
1002
+ add(lhs, rhs) {
1003
+ return mod(lhs + rhs, this.ORDER);
1004
+ }
1005
+ sub(lhs, rhs) {
1006
+ return mod(lhs - rhs, this.ORDER);
1007
+ }
1008
+ mul(lhs, rhs) {
1009
+ return mod(lhs * rhs, this.ORDER);
1010
+ }
1011
+ pow(num, power) {
1012
+ return FpPow(this, num, power);
1013
+ }
1014
+ div(lhs, rhs) {
1015
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1016
+ }
1017
+ sqrN(num) {
1018
+ return num * num;
1019
+ }
1020
+ addN(lhs, rhs) {
1021
+ return lhs + rhs;
1022
+ }
1023
+ subN(lhs, rhs) {
1024
+ return lhs - rhs;
1025
+ }
1026
+ mulN(lhs, rhs) {
1027
+ return lhs * rhs;
1028
+ }
1029
+ inv(num) {
1030
+ return invert(num, this.ORDER);
1031
+ }
1032
+ sqrt(num) {
1033
+ if (!this._sqrt)
1034
+ this._sqrt = FpSqrt(this.ORDER);
1035
+ return this._sqrt(this, num);
1036
+ }
1037
+ toBytes(num) {
1038
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1039
+ }
1040
+ fromBytes(bytes, skipValidation = false) {
1041
+ abytes(bytes);
1042
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
1043
+ if (allowedLengths) {
1044
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1045
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1046
+ }
1047
+ const padded = new Uint8Array(BYTES);
1048
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1049
+ bytes = padded;
1050
+ }
1051
+ if (bytes.length !== BYTES)
1052
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1053
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1054
+ if (modFromBytes)
1055
+ scalar = mod(scalar, ORDER);
1056
+ if (!skipValidation) {
1057
+ if (!this.isValid(scalar))
1058
+ throw new Error("invalid field element: outside of range 0..ORDER");
1059
+ }
1060
+ return scalar;
1061
+ }
1062
+ invertBatch(lst) {
1063
+ return FpInvertBatch(this, lst);
1064
+ }
1065
+ cmov(a, b, condition) {
1066
+ return condition ? b : a;
1067
+ }
1068
+ }
1069
+ function Field(ORDER, opts = {}) {
1070
+ return new _Field(ORDER, opts);
1071
+ }
1072
+ const _0n$2 = /* @__PURE__ */ BigInt(0);
1073
+ const _1n$2 = /* @__PURE__ */ BigInt(1);
1074
+ function negateCt(condition, item) {
1075
+ const neg = item.negate();
1076
+ return condition ? neg : item;
1077
+ }
1078
+ function normalizeZ(c, points) {
1079
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1080
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1081
+ }
1082
+ function validateW(W, bits) {
1083
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1084
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1085
+ }
1086
+ function calcWOpts(W, scalarBits) {
1087
+ validateW(W, scalarBits);
1088
+ const windows = Math.ceil(scalarBits / W) + 1;
1089
+ const windowSize = 2 ** (W - 1);
1090
+ const maxNumber = 2 ** W;
1091
+ const mask = bitMask(W);
1092
+ const shiftBy = BigInt(W);
1093
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1094
+ }
1095
+ function calcOffsets(n, window, wOpts) {
1096
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1097
+ let wbits = Number(n & mask);
1098
+ let nextN = n >> shiftBy;
1099
+ if (wbits > windowSize) {
1100
+ wbits -= maxNumber;
1101
+ nextN += _1n$2;
1102
+ }
1103
+ const offsetStart = window * windowSize;
1104
+ const offset = offsetStart + Math.abs(wbits) - 1;
1105
+ const isZero = wbits === 0;
1106
+ const isNeg = wbits < 0;
1107
+ const isNegF = window % 2 !== 0;
1108
+ const offsetF = offsetStart;
1109
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1110
+ }
1111
+ const pointPrecomputes = /* @__PURE__ */ new WeakMap();
1112
+ const pointWindowSizes = /* @__PURE__ */ new WeakMap();
1113
+ function getW(P) {
1114
+ return pointWindowSizes.get(P) || 1;
1115
+ }
1116
+ function assert0(n) {
1117
+ if (n !== _0n$2)
1118
+ throw new Error("invalid wNAF");
1119
+ }
1120
+ class wNAF {
1121
+ BASE;
1122
+ ZERO;
1123
+ Fn;
1124
+ bits;
1125
+ constructor(Point, bits) {
1126
+ this.BASE = Point.BASE;
1127
+ this.ZERO = Point.ZERO;
1128
+ this.Fn = Point.Fn;
1129
+ this.bits = bits;
1130
+ }
1131
+ _unsafeLadder(elm, n, p = this.ZERO) {
1132
+ let d = elm;
1133
+ while (n > _0n$2) {
1134
+ if (n & _1n$2)
1135
+ p = p.add(d);
1136
+ d = d.double();
1137
+ n >>= _1n$2;
1138
+ }
1139
+ return p;
1140
+ }
1141
+ precomputeWindow(point, W) {
1142
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1143
+ const points = [];
1144
+ let p = point;
1145
+ let base = p;
1146
+ for (let window = 0; window < windows; window++) {
1147
+ base = p;
1148
+ points.push(base);
1149
+ for (let i = 1; i < windowSize; i++) {
1150
+ base = base.add(p);
1151
+ points.push(base);
1152
+ }
1153
+ p = base.double();
1154
+ }
1155
+ return points;
1156
+ }
1157
+ wNAF(W, precomputes, n) {
1158
+ if (!this.Fn.isValid(n))
1159
+ throw new Error("invalid scalar");
1160
+ let p = this.ZERO;
1161
+ let f = this.BASE;
1162
+ const wo = calcWOpts(W, this.bits);
1163
+ for (let window = 0; window < wo.windows; window++) {
1164
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1165
+ n = nextN;
1166
+ if (isZero) {
1167
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1168
+ } else {
1169
+ p = p.add(negateCt(isNeg, precomputes[offset]));
1170
+ }
1171
+ }
1172
+ assert0(n);
1173
+ return { p, f };
1174
+ }
1175
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1176
+ const wo = calcWOpts(W, this.bits);
1177
+ for (let window = 0; window < wo.windows; window++) {
1178
+ if (n === _0n$2)
1179
+ break;
1180
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1181
+ n = nextN;
1182
+ if (isZero) {
1183
+ continue;
1184
+ } else {
1185
+ const item = precomputes[offset];
1186
+ acc = acc.add(isNeg ? item.negate() : item);
1187
+ }
1188
+ }
1189
+ assert0(n);
1190
+ return acc;
1191
+ }
1192
+ getPrecomputes(W, point, transform) {
1193
+ let comp = pointPrecomputes.get(point);
1194
+ if (!comp) {
1195
+ comp = this.precomputeWindow(point, W);
1196
+ if (W !== 1) {
1197
+ if (typeof transform === "function")
1198
+ comp = transform(comp);
1199
+ pointPrecomputes.set(point, comp);
1200
+ }
1201
+ }
1202
+ return comp;
1203
+ }
1204
+ cached(point, scalar, transform) {
1205
+ const W = getW(point);
1206
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1207
+ }
1208
+ unsafe(point, scalar, transform, prev) {
1209
+ const W = getW(point);
1210
+ if (W === 1)
1211
+ return this._unsafeLadder(point, scalar, prev);
1212
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1213
+ }
1214
+ createCache(P, W) {
1215
+ validateW(W, this.bits);
1216
+ pointWindowSizes.set(P, W);
1217
+ pointPrecomputes.delete(P);
1218
+ }
1219
+ hasCache(elm) {
1220
+ return getW(elm) !== 1;
1221
+ }
1222
+ }
1223
+ function createField(order, field, isLE) {
1224
+ if (field) {
1225
+ if (field.ORDER !== order)
1226
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1227
+ validateField(field);
1228
+ return field;
1229
+ } else {
1230
+ return Field(order, { isLE });
1231
+ }
1232
+ }
1233
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1234
+ if (FpFnLE === void 0)
1235
+ FpFnLE = type === "edwards";
1236
+ if (!CURVE || typeof CURVE !== "object")
1237
+ throw new Error(`expected valid ${type} CURVE object`);
1238
+ for (const p of ["p", "n", "h"]) {
1239
+ const val = CURVE[p];
1240
+ if (!(typeof val === "bigint" && val > _0n$2))
1241
+ throw new Error(`CURVE.${p} must be positive bigint`);
1242
+ }
1243
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1244
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1245
+ const _b = type === "weierstrass" ? "b" : "d";
1246
+ const params = ["Gx", "Gy", "a", _b];
1247
+ for (const p of params) {
1248
+ if (!Fp2.isValid(CURVE[p]))
1249
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1250
+ }
1251
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1252
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
1253
+ }
1254
+ function createKeygen(randomSecretKey, getPublicKey) {
1255
+ return function keygen(seed) {
1256
+ const secretKey = randomSecretKey(seed);
1257
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1258
+ };
1259
+ }
1260
+ const _0n$1 = BigInt(0), _1n$1 = BigInt(1), _2n$1 = BigInt(2), _8n$1 = BigInt(8);
1261
+ function isEdValidXY(Fp2, CURVE, x, y) {
1262
+ const x2 = Fp2.sqr(x);
1263
+ const y2 = Fp2.sqr(y);
1264
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
1265
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
1266
+ return Fp2.eql(left, right);
1267
+ }
1268
+ function edwards(params, extraOpts = {}) {
1269
+ const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1270
+ const { Fp: Fp2, Fn: Fn2 } = validated;
1271
+ let CURVE = validated.CURVE;
1272
+ const { h: cofactor } = CURVE;
1273
+ validateObject(extraOpts, {}, { uvRatio: "function" });
1274
+ const MASK = _2n$1 << BigInt(Fn2.BYTES * 8) - _1n$1;
1275
+ const modP = (n) => Fp2.create(n);
1276
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1277
+ try {
1278
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
1279
+ } catch (e) {
1280
+ return { isValid: false, value: _0n$1 };
1281
+ }
1282
+ });
1283
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
1284
+ throw new Error("bad curve params: generator point");
1285
+ function acoord(title, n, banZero = false) {
1286
+ const min = banZero ? _1n$1 : _0n$1;
1287
+ aInRange("coordinate " + title, n, min, MASK);
1288
+ return n;
1289
+ }
1290
+ function aedpoint(other) {
1291
+ if (!(other instanceof Point))
1292
+ throw new Error("EdwardsPoint expected");
1293
+ }
1294
+ const toAffineMemo = memoized((p, iz) => {
1295
+ const { X, Y, Z } = p;
1296
+ const is0 = p.is0();
1297
+ if (iz == null)
1298
+ iz = is0 ? _8n$1 : Fp2.inv(Z);
1299
+ const x = modP(X * iz);
1300
+ const y = modP(Y * iz);
1301
+ const zz = Fp2.mul(Z, iz);
1302
+ if (is0)
1303
+ return { x: _0n$1, y: _1n$1 };
1304
+ if (zz !== _1n$1)
1305
+ throw new Error("invZ was invalid");
1306
+ return { x, y };
1307
+ });
1308
+ const assertValidMemo = memoized((p) => {
1309
+ const { a, d } = CURVE;
1310
+ if (p.is0())
1311
+ throw new Error("bad point: ZERO");
1312
+ const { X, Y, Z, T } = p;
1313
+ const X2 = modP(X * X);
1314
+ const Y2 = modP(Y * Y);
1315
+ const Z2 = modP(Z * Z);
1316
+ const Z4 = modP(Z2 * Z2);
1317
+ const aX2 = modP(X2 * a);
1318
+ const left = modP(Z2 * modP(aX2 + Y2));
1319
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1320
+ if (left !== right)
1321
+ throw new Error("bad point: equation left != right (1)");
1322
+ const XY = modP(X * Y);
1323
+ const ZT = modP(Z * T);
1324
+ if (XY !== ZT)
1325
+ throw new Error("bad point: equation left != right (2)");
1326
+ return true;
1327
+ });
1328
+ class Point {
1329
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$1, modP(CURVE.Gx * CURVE.Gy));
1330
+ static ZERO = new Point(_0n$1, _1n$1, _1n$1, _0n$1);
1331
+ static Fp = Fp2;
1332
+ static Fn = Fn2;
1333
+ X;
1334
+ Y;
1335
+ Z;
1336
+ T;
1337
+ constructor(X, Y, Z, T) {
1338
+ this.X = acoord("x", X);
1339
+ this.Y = acoord("y", Y);
1340
+ this.Z = acoord("z", Z, true);
1341
+ this.T = acoord("t", T);
1342
+ Object.freeze(this);
1343
+ }
1344
+ static CURVE() {
1345
+ return CURVE;
1346
+ }
1347
+ static fromAffine(p) {
1348
+ if (p instanceof Point)
1349
+ throw new Error("extended point not allowed");
1350
+ const { x, y } = p || {};
1351
+ acoord("x", x);
1352
+ acoord("y", y);
1353
+ return new Point(x, y, _1n$1, modP(x * y));
1354
+ }
1355
+ static fromBytes(bytes, zip215 = false) {
1356
+ const len = Fp2.BYTES;
1357
+ const { a, d } = CURVE;
1358
+ bytes = copyBytes(abytes(bytes, len, "point"));
1359
+ abool(zip215, "zip215");
1360
+ const normed = copyBytes(bytes);
1361
+ const lastByte = bytes[len - 1];
1362
+ normed[len - 1] = lastByte & ~128;
1363
+ const y = bytesToNumberLE(normed);
1364
+ const max = zip215 ? MASK : Fp2.ORDER;
1365
+ aInRange("point.y", y, _0n$1, max);
1366
+ const y2 = modP(y * y);
1367
+ const u = modP(y2 - _1n$1);
1368
+ const v = modP(d * y2 - a);
1369
+ let { isValid, value: x } = uvRatio2(u, v);
1370
+ if (!isValid)
1371
+ throw new Error("bad point: invalid y coordinate");
1372
+ const isXOdd = (x & _1n$1) === _1n$1;
1373
+ const isLastByteOdd = (lastByte & 128) !== 0;
1374
+ if (!zip215 && x === _0n$1 && isLastByteOdd)
1375
+ throw new Error("bad point: x=0 and x_0=1");
1376
+ if (isLastByteOdd !== isXOdd)
1377
+ x = modP(-x);
1378
+ return Point.fromAffine({ x, y });
1379
+ }
1380
+ static fromHex(hex, zip215 = false) {
1381
+ return Point.fromBytes(hexToBytes(hex), zip215);
1382
+ }
1383
+ get x() {
1384
+ return this.toAffine().x;
1385
+ }
1386
+ get y() {
1387
+ return this.toAffine().y;
1388
+ }
1389
+ precompute(windowSize = 8, isLazy = true) {
1390
+ wnaf.createCache(this, windowSize);
1391
+ if (!isLazy)
1392
+ this.multiply(_2n$1);
1393
+ return this;
1394
+ }
1395
+ assertValidity() {
1396
+ assertValidMemo(this);
1397
+ }
1398
+ equals(other) {
1399
+ aedpoint(other);
1400
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1401
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1402
+ const X1Z2 = modP(X1 * Z2);
1403
+ const X2Z1 = modP(X2 * Z1);
1404
+ const Y1Z2 = modP(Y1 * Z2);
1405
+ const Y2Z1 = modP(Y2 * Z1);
1406
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1407
+ }
1408
+ is0() {
1409
+ return this.equals(Point.ZERO);
1410
+ }
1411
+ negate() {
1412
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1413
+ }
1414
+ double() {
1415
+ const { a } = CURVE;
1416
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1417
+ const A = modP(X1 * X1);
1418
+ const B = modP(Y1 * Y1);
1419
+ const C = modP(_2n$1 * modP(Z1 * Z1));
1420
+ const D = modP(a * A);
1421
+ const x1y1 = X1 + Y1;
1422
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1423
+ const G = D + B;
1424
+ const F = G - C;
1425
+ const H = D - B;
1426
+ const X3 = modP(E * F);
1427
+ const Y3 = modP(G * H);
1428
+ const T3 = modP(E * H);
1429
+ const Z3 = modP(F * G);
1430
+ return new Point(X3, Y3, Z3, T3);
1431
+ }
1432
+ add(other) {
1433
+ aedpoint(other);
1434
+ const { a, d } = CURVE;
1435
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1436
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1437
+ const A = modP(X1 * X2);
1438
+ const B = modP(Y1 * Y2);
1439
+ const C = modP(T1 * d * T2);
1440
+ const D = modP(Z1 * Z2);
1441
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1442
+ const F = D - C;
1443
+ const G = D + C;
1444
+ const H = modP(B - a * A);
1445
+ const X3 = modP(E * F);
1446
+ const Y3 = modP(G * H);
1447
+ const T3 = modP(E * H);
1448
+ const Z3 = modP(F * G);
1449
+ return new Point(X3, Y3, Z3, T3);
1450
+ }
1451
+ subtract(other) {
1452
+ return this.add(other.negate());
1453
+ }
1454
+ multiply(scalar) {
1455
+ if (!Fn2.isValidNot0(scalar))
1456
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1457
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1458
+ return normalizeZ(Point, [p, f])[0];
1459
+ }
1460
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
1461
+ if (!Fn2.isValid(scalar))
1462
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1463
+ if (scalar === _0n$1)
1464
+ return Point.ZERO;
1465
+ if (this.is0() || scalar === _1n$1)
1466
+ return this;
1467
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1468
+ }
1469
+ isSmallOrder() {
1470
+ return this.multiplyUnsafe(cofactor).is0();
1471
+ }
1472
+ isTorsionFree() {
1473
+ return wnaf.unsafe(this, CURVE.n).is0();
1474
+ }
1475
+ toAffine(invertedZ) {
1476
+ return toAffineMemo(this, invertedZ);
1477
+ }
1478
+ clearCofactor() {
1479
+ if (cofactor === _1n$1)
1480
+ return this;
1481
+ return this.multiplyUnsafe(cofactor);
1482
+ }
1483
+ toBytes() {
1484
+ const { x, y } = this.toAffine();
1485
+ const bytes = Fp2.toBytes(y);
1486
+ bytes[bytes.length - 1] |= x & _1n$1 ? 128 : 0;
1487
+ return bytes;
1488
+ }
1489
+ toHex() {
1490
+ return bytesToHex$1(this.toBytes());
1491
+ }
1492
+ toString() {
1493
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1494
+ }
1495
+ }
1496
+ const wnaf = new wNAF(Point, Fn2.BITS);
1497
+ Point.BASE.precompute(8);
1498
+ return Point;
1499
+ }
1500
+ class PrimeEdwardsPoint {
1501
+ static BASE;
1502
+ static ZERO;
1503
+ static Fp;
1504
+ static Fn;
1505
+ ep;
1506
+ constructor(ep) {
1507
+ this.ep = ep;
1508
+ }
1509
+ static fromBytes(_bytes) {
1510
+ notImplemented();
1511
+ }
1512
+ static fromHex(_hex) {
1513
+ notImplemented();
1514
+ }
1515
+ get x() {
1516
+ return this.toAffine().x;
1517
+ }
1518
+ get y() {
1519
+ return this.toAffine().y;
1520
+ }
1521
+ clearCofactor() {
1522
+ return this;
1523
+ }
1524
+ assertValidity() {
1525
+ this.ep.assertValidity();
1526
+ }
1527
+ toAffine(invertedZ) {
1528
+ return this.ep.toAffine(invertedZ);
1529
+ }
1530
+ toHex() {
1531
+ return bytesToHex$1(this.toBytes());
1532
+ }
1533
+ toString() {
1534
+ return this.toHex();
1535
+ }
1536
+ isTorsionFree() {
1537
+ return true;
1538
+ }
1539
+ isSmallOrder() {
1540
+ return false;
1541
+ }
1542
+ add(other) {
1543
+ this.assertSame(other);
1544
+ return this.init(this.ep.add(other.ep));
1545
+ }
1546
+ subtract(other) {
1547
+ this.assertSame(other);
1548
+ return this.init(this.ep.subtract(other.ep));
1549
+ }
1550
+ multiply(scalar) {
1551
+ return this.init(this.ep.multiply(scalar));
1552
+ }
1553
+ multiplyUnsafe(scalar) {
1554
+ return this.init(this.ep.multiplyUnsafe(scalar));
1555
+ }
1556
+ double() {
1557
+ return this.init(this.ep.double());
1558
+ }
1559
+ negate() {
1560
+ return this.init(this.ep.negate());
1561
+ }
1562
+ precompute(windowSize, isLazy) {
1563
+ return this.init(this.ep.precompute(windowSize, isLazy));
1564
+ }
1565
+ }
1566
+ function eddsa(Point, cHash, eddsaOpts = {}) {
1567
+ if (typeof cHash !== "function")
1568
+ throw new Error('"hash" function param is required');
1569
+ validateObject(eddsaOpts, {}, {
1570
+ adjustScalarBytes: "function",
1571
+ randomBytes: "function",
1572
+ domain: "function",
1573
+ prehash: "function",
1574
+ mapToCurve: "function"
1575
+ });
1576
+ const { prehash } = eddsaOpts;
1577
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
1578
+ const randomBytes$1 = eddsaOpts.randomBytes || randomBytes;
1579
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1580
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1581
+ abool(phflag, "phflag");
1582
+ if (ctx.length || phflag)
1583
+ throw new Error("Contexts/pre-hash are not supported");
1584
+ return data;
1585
+ });
1586
+ function modN_LE(hash) {
1587
+ return Fn2.create(bytesToNumberLE(hash));
1588
+ }
1589
+ function getPrivateScalar(key) {
1590
+ const len = lengths.secretKey;
1591
+ abytes(key, lengths.secretKey, "secretKey");
1592
+ const hashed = abytes(cHash(key), 2 * len, "hashedSecretKey");
1593
+ const head = adjustScalarBytes2(hashed.slice(0, len));
1594
+ const prefix = hashed.slice(len, 2 * len);
1595
+ const scalar = modN_LE(head);
1596
+ return { head, prefix, scalar };
1597
+ }
1598
+ function getExtendedPublicKey(secretKey) {
1599
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
1600
+ const point = BASE.multiply(scalar);
1601
+ const pointBytes = point.toBytes();
1602
+ return { head, prefix, scalar, point, pointBytes };
1603
+ }
1604
+ function getPublicKey(secretKey) {
1605
+ return getExtendedPublicKey(secretKey).pointBytes;
1606
+ }
1607
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1608
+ const msg = concatBytes$1(...msgs);
1609
+ return modN_LE(cHash(domain(msg, abytes(context, void 0, "context"), !!prehash)));
1610
+ }
1611
+ function sign(msg, secretKey, options = {}) {
1612
+ msg = abytes(msg, void 0, "message");
1613
+ if (prehash)
1614
+ msg = prehash(msg);
1615
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1616
+ const r = hashDomainToScalar(options.context, prefix, msg);
1617
+ const R = BASE.multiply(r).toBytes();
1618
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1619
+ const s = Fn2.create(r + k * scalar);
1620
+ if (!Fn2.isValid(s))
1621
+ throw new Error("sign failed: invalid s");
1622
+ const rs = concatBytes$1(R, Fn2.toBytes(s));
1623
+ return abytes(rs, lengths.signature, "result");
1624
+ }
1625
+ const verifyOpts = { zip215: true };
1626
+ function verify(sig, msg, publicKey, options = verifyOpts) {
1627
+ const { context, zip215 } = options;
1628
+ const len = lengths.signature;
1629
+ sig = abytes(sig, len, "signature");
1630
+ msg = abytes(msg, void 0, "message");
1631
+ publicKey = abytes(publicKey, lengths.publicKey, "publicKey");
1632
+ if (zip215 !== void 0)
1633
+ abool(zip215, "zip215");
1634
+ if (prehash)
1635
+ msg = prehash(msg);
1636
+ const mid = len / 2;
1637
+ const r = sig.subarray(0, mid);
1638
+ const s = bytesToNumberLE(sig.subarray(mid, len));
1639
+ let A, R, SB;
1640
+ try {
1641
+ A = Point.fromBytes(publicKey, zip215);
1642
+ R = Point.fromBytes(r, zip215);
1643
+ SB = BASE.multiplyUnsafe(s);
1644
+ } catch (error) {
1645
+ return false;
1646
+ }
1647
+ if (!zip215 && A.isSmallOrder())
1648
+ return false;
1649
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
1650
+ const RkA = R.add(A.multiplyUnsafe(k));
1651
+ return RkA.subtract(SB).clearCofactor().is0();
1652
+ }
1653
+ const _size = Fp2.BYTES;
1654
+ const lengths = {
1655
+ secretKey: _size,
1656
+ publicKey: _size,
1657
+ signature: 2 * _size,
1658
+ seed: _size
1659
+ };
1660
+ function randomSecretKey(seed = randomBytes$1(lengths.seed)) {
1661
+ return abytes(seed, lengths.seed, "seed");
1662
+ }
1663
+ function isValidSecretKey(key) {
1664
+ return isBytes(key) && key.length === Fn2.BYTES;
1665
+ }
1666
+ function isValidPublicKey(key, zip215) {
1667
+ try {
1668
+ return !!Point.fromBytes(key, zip215);
1669
+ } catch (error) {
1670
+ return false;
1671
+ }
1672
+ }
1673
+ const utils = {
1674
+ getExtendedPublicKey,
1675
+ randomSecretKey,
1676
+ isValidSecretKey,
1677
+ isValidPublicKey,
1678
+ toMontgomery(publicKey) {
1679
+ const { y } = Point.fromBytes(publicKey);
1680
+ const size = lengths.publicKey;
1681
+ const is25519 = size === 32;
1682
+ if (!is25519 && size !== 57)
1683
+ throw new Error("only defined for 25519 and 448");
1684
+ const u = is25519 ? Fp2.div(_1n$1 + y, _1n$1 - y) : Fp2.div(y - _1n$1, y + _1n$1);
1685
+ return Fp2.toBytes(u);
1686
+ },
1687
+ toMontgomerySecret(secretKey) {
1688
+ const size = lengths.secretKey;
1689
+ abytes(secretKey, size);
1690
+ const hashed = cHash(secretKey.subarray(0, size));
1691
+ return adjustScalarBytes2(hashed).subarray(0, size);
1692
+ }
1693
+ };
1694
+ return Object.freeze({
1695
+ keygen: createKeygen(randomSecretKey, getPublicKey),
1696
+ getPublicKey,
1697
+ sign,
1698
+ verify,
1699
+ utils,
1700
+ Point,
1701
+ lengths
1702
+ });
1703
+ }
1704
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2);
1705
+ const _5n = BigInt(5), _8n = BigInt(8);
1706
+ const ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
1707
+ const ed25519_CURVE = /* @__PURE__ */ (() => ({
1708
+ p: ed25519_CURVE_p,
1709
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
1710
+ h: _8n,
1711
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
1712
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
1713
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
1714
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
1715
+ }))();
1716
+ function ed25519_pow_2_252_3(x) {
1717
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1718
+ const P = ed25519_CURVE_p;
1719
+ const x2 = x * x % P;
1720
+ const b2 = x2 * x % P;
1721
+ const b4 = pow2(b2, _2n, P) * b2 % P;
1722
+ const b5 = pow2(b4, _1n, P) * x % P;
1723
+ const b10 = pow2(b5, _5n, P) * b5 % P;
1724
+ const b20 = pow2(b10, _10n, P) * b10 % P;
1725
+ const b40 = pow2(b20, _20n, P) * b20 % P;
1726
+ const b80 = pow2(b40, _40n, P) * b40 % P;
1727
+ const b160 = pow2(b80, _80n, P) * b80 % P;
1728
+ const b240 = pow2(b160, _80n, P) * b80 % P;
1729
+ const b250 = pow2(b240, _10n, P) * b10 % P;
1730
+ const pow_p_5_8 = pow2(b250, _2n, P) * x % P;
1731
+ return { pow_p_5_8, b2 };
1732
+ }
1733
+ function adjustScalarBytes(bytes) {
1734
+ bytes[0] &= 248;
1735
+ bytes[31] &= 127;
1736
+ bytes[31] |= 64;
1737
+ return bytes;
1738
+ }
1739
+ const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1740
+ function uvRatio(u, v) {
1741
+ const P = ed25519_CURVE_p;
1742
+ const v3 = mod(v * v * v, P);
1743
+ const v7 = mod(v3 * v3 * v, P);
1744
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1745
+ let x = mod(u * v3 * pow, P);
1746
+ const vx2 = mod(v * x * x, P);
1747
+ const root1 = x;
1748
+ const root2 = mod(x * ED25519_SQRT_M1, P);
1749
+ const useRoot1 = vx2 === u;
1750
+ const useRoot2 = vx2 === mod(-u, P);
1751
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
1752
+ if (useRoot1)
1753
+ x = root1;
1754
+ if (useRoot2 || noRoot)
1755
+ x = root2;
1756
+ if (isNegativeLE(x, P))
1757
+ x = mod(-x, P);
1758
+ return { isValid: useRoot1 || useRoot2, value: x };
1759
+ }
1760
+ const ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
1761
+ const Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
1762
+ const Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
1763
+ function ed(opts) {
1764
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
1765
+ }
1766
+ const ed25519 = /* @__PURE__ */ ed({});
1767
+ const SQRT_M1 = ED25519_SQRT_M1;
1768
+ const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
1769
+ const invertSqrt = (number) => uvRatio(_1n, number);
1770
+ const MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1771
+ const bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
1772
+ class _RistrettoPoint extends PrimeEdwardsPoint {
1773
+ static BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();
1774
+ static ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();
1775
+ static Fp = /* @__PURE__ */ (() => Fp)();
1776
+ static Fn = /* @__PURE__ */ (() => Fn)();
1777
+ constructor(ep) {
1778
+ super(ep);
1779
+ }
1780
+ static fromAffine(ap) {
1781
+ return new _RistrettoPoint(ed25519_Point.fromAffine(ap));
1782
+ }
1783
+ assertSame(other) {
1784
+ if (!(other instanceof _RistrettoPoint))
1785
+ throw new Error("RistrettoPoint expected");
1786
+ }
1787
+ init(ep) {
1788
+ return new _RistrettoPoint(ep);
1789
+ }
1790
+ static fromBytes(bytes) {
1791
+ abytes(bytes, 32);
1792
+ const { a, d } = ed25519_CURVE;
1793
+ const P = ed25519_CURVE_p;
1794
+ const mod2 = (n) => Fp.create(n);
1795
+ const s = bytes255ToNumberLE(bytes);
1796
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
1797
+ throw new Error("invalid ristretto255 encoding 1");
1798
+ const s2 = mod2(s * s);
1799
+ const u1 = mod2(_1n + a * s2);
1800
+ const u2 = mod2(_1n - a * s2);
1801
+ const u1_2 = mod2(u1 * u1);
1802
+ const u2_2 = mod2(u2 * u2);
1803
+ const v = mod2(a * d * u1_2 - u2_2);
1804
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
1805
+ const Dx = mod2(I * u2);
1806
+ const Dy = mod2(I * Dx * v);
1807
+ let x = mod2((s + s) * Dx);
1808
+ if (isNegativeLE(x, P))
1809
+ x = mod2(-x);
1810
+ const y = mod2(u1 * Dy);
1811
+ const t = mod2(x * y);
1812
+ if (!isValid || isNegativeLE(t, P) || y === _0n)
1813
+ throw new Error("invalid ristretto255 encoding 2");
1814
+ return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));
1815
+ }
1816
+ static fromHex(hex) {
1817
+ return _RistrettoPoint.fromBytes(hexToBytes(hex));
1818
+ }
1819
+ toBytes() {
1820
+ let { X, Y, Z, T } = this.ep;
1821
+ const P = ed25519_CURVE_p;
1822
+ const mod2 = (n) => Fp.create(n);
1823
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
1824
+ const u2 = mod2(X * Y);
1825
+ const u2sq = mod2(u2 * u2);
1826
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
1827
+ const D1 = mod2(invsqrt * u1);
1828
+ const D2 = mod2(invsqrt * u2);
1829
+ const zInv = mod2(D1 * D2 * T);
1830
+ let D;
1831
+ if (isNegativeLE(T * zInv, P)) {
1832
+ let _x = mod2(Y * SQRT_M1);
1833
+ let _y = mod2(X * SQRT_M1);
1834
+ X = _x;
1835
+ Y = _y;
1836
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
1837
+ } else {
1838
+ D = D2;
1839
+ }
1840
+ if (isNegativeLE(X * zInv, P))
1841
+ Y = mod2(-Y);
1842
+ let s = mod2((Z - Y) * D);
1843
+ if (isNegativeLE(s, P))
1844
+ s = mod2(-s);
1845
+ return Fp.toBytes(s);
1846
+ }
1847
+ equals(other) {
1848
+ this.assertSame(other);
1849
+ const { X: X1, Y: Y1 } = this.ep;
1850
+ const { X: X2, Y: Y2 } = other.ep;
1851
+ const mod2 = (n) => Fp.create(n);
1852
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
1853
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
1854
+ return one || two;
1855
+ }
1856
+ is0() {
1857
+ return this.equals(_RistrettoPoint.ZERO);
1858
+ }
1859
+ }
1860
+ const IDENTITY_FORMAT = "ternent-identity";
1861
+ const IDENTITY_VERSION = "2";
1862
+ const IDENTITY_ALGORITHM = "Ed25519";
1863
+ const ED25519_CONTEXT = "ternent-seal/v2";
1864
+ const IDENTITY_MATERIAL_KIND = "seed";
1865
+ new TextEncoder().encode("ed25519 seed");
1866
+ function isRecord(value) {
1867
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1868
+ }
1869
+ function concatBytes(...parts) {
1870
+ const length = parts.reduce((sum, part) => sum + part.length, 0);
1871
+ const output = new Uint8Array(length);
1872
+ let offset = 0;
1873
+ for (const part of parts) {
1874
+ output.set(part, offset);
1875
+ offset += part.length;
1876
+ }
1877
+ return output;
1878
+ }
1879
+ function ensureBytes(value, label) {
1880
+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
1881
+ if (bytes.length === 0) {
1882
+ throw new Error(`${label} must not be empty.`);
1883
+ }
1884
+ return bytes;
1885
+ }
1886
+ function bytesToHex(bytes) {
1887
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
1888
+ ""
1889
+ );
1890
+ }
1891
+ function normalizeBase64Url(value) {
1892
+ return String(value || "").trim().replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
1893
+ }
1894
+ function base64Encode(bytes) {
1895
+ const buffer = globalThis.Buffer;
1896
+ if (buffer) {
1897
+ return buffer.from(bytes).toString("base64");
1898
+ }
1899
+ let binary = "";
1900
+ for (const byte of bytes) {
1901
+ binary += String.fromCharCode(byte);
1902
+ }
1903
+ if (typeof btoa !== "undefined") {
1904
+ return btoa(binary);
1905
+ }
1906
+ throw new Error("Base64 encoding is not available in this runtime.");
1907
+ }
1908
+ function base64Decode(value) {
1909
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
1910
+ const buffer = globalThis.Buffer;
1911
+ if (buffer) {
1912
+ return new Uint8Array(buffer.from(normalized, "base64"));
1913
+ }
1914
+ if (typeof atob !== "undefined") {
1915
+ const binary = atob(normalized);
1916
+ const bytes = new Uint8Array(binary.length);
1917
+ for (let index = 0; index < binary.length; index += 1) {
1918
+ bytes[index] = binary.charCodeAt(index);
1919
+ }
1920
+ return bytes;
1921
+ }
1922
+ throw new Error("Base64 decoding is not available in this runtime.");
1923
+ }
1924
+ function base64UrlEncode(bytes) {
1925
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
1926
+ }
1927
+ function base64UrlDecode(value) {
1928
+ const normalized = normalizeBase64Url(value);
1929
+ if (!normalized) {
1930
+ throw new Error("Base64url value is required.");
1931
+ }
1932
+ const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
1933
+ return base64Decode(`${normalized}${pad}`);
1934
+ }
1935
+ function utf8Bytes(value) {
1936
+ return new TextEncoder().encode(value);
1937
+ }
1938
+ function combineContext(payload, context = ED25519_CONTEXT) {
1939
+ return concatBytes(utf8Bytes(context), new Uint8Array([0]), payload);
1940
+ }
1941
+ function isSerializedIdentity(value) {
1942
+ return isRecord(value) && value.format === IDENTITY_FORMAT && value.version === IDENTITY_VERSION && value.algorithm === IDENTITY_ALGORITHM && typeof value.createdAt === "string" && typeof value.publicKey === "string" && typeof value.keyId === "string" && isRecord(value.material) && value.material.kind === IDENTITY_MATERIAL_KIND && typeof value.material.seed === "string";
1943
+ }
1944
+ function toCanonicalIdentity(identity) {
1945
+ return {
1946
+ format: identity.format,
1947
+ version: identity.version,
1948
+ algorithm: identity.algorithm,
1949
+ createdAt: identity.createdAt,
1950
+ publicKey: identity.publicKey,
1951
+ keyId: identity.keyId,
1952
+ material: {
1953
+ kind: identity.material.kind,
1954
+ seed: identity.material.seed
1955
+ }
1956
+ };
1957
+ }
1958
+ function resolveSeedBytes(input) {
1959
+ if (input instanceof Uint8Array || input instanceof ArrayBuffer) {
1960
+ const bytes = ensureBytes(input, "Seed");
1961
+ if (bytes.length !== 32) {
1962
+ throw new Error("Seed must be 32 bytes.");
1963
+ }
1964
+ return bytes;
1965
+ }
1966
+ if (typeof input === "string") {
1967
+ const bytes = base64UrlDecode(input);
1968
+ if (bytes.length !== 32) {
1969
+ throw new Error("Seed must be 32 bytes.");
1970
+ }
1971
+ return bytes;
1972
+ }
1973
+ if (isSerializedIdentity(input)) {
1974
+ return resolveSeedBytes(input.material.seed);
1975
+ }
1976
+ throw new Error("A valid identity or 32-byte seed is required.");
1977
+ }
1978
+ function resolvePublicKeyBytes(input) {
1979
+ if (input instanceof Uint8Array || input instanceof ArrayBuffer) {
1980
+ const bytes = ensureBytes(input, "Public key");
1981
+ if (bytes.length !== 32) {
1982
+ throw new Error("Public key must be 32 bytes.");
1983
+ }
1984
+ return bytes;
1985
+ }
1986
+ if (typeof input === "string") {
1987
+ const bytes = base64UrlDecode(input);
1988
+ if (bytes.length !== 32) {
1989
+ throw new Error("Public key must be 32 bytes.");
1990
+ }
1991
+ return bytes;
1992
+ }
1993
+ if (isSerializedIdentity(input)) {
1994
+ return resolvePublicKeyBytes(input.publicKey);
1995
+ }
1996
+ if (isRecord(input) && "publicKey" in input) {
1997
+ return resolvePublicKeyBytes(
1998
+ input.publicKey
1999
+ );
2000
+ }
2001
+ throw new Error("A valid 32-byte public key is required.");
2002
+ }
2003
+ async function deriveKeyId(publicKey) {
2004
+ return bytesToHex(sha256(resolvePublicKeyBytes(publicKey)));
2005
+ }
2006
+ function parseIdentity(input) {
2007
+ const parsed = typeof input === "string" ? JSON.parse(input) : input;
2008
+ if (!isSerializedIdentity(parsed)) {
2009
+ throw new Error("Identity payload must be a ternent-identity v2 object.");
2010
+ }
2011
+ return toCanonicalIdentity(parsed);
2012
+ }
2013
+ function serializeIdentity(identity, pretty = true) {
2014
+ return `${JSON.stringify(parseIdentity(identity), null, pretty ? 2 : 0)}
2015
+ `;
2016
+ }
2017
+ async function signBytes(identityOrSeed, payload, options = {}) {
2018
+ return base64UrlEncode(
2019
+ ed25519.sign(
2020
+ combineContext(ensureBytes(payload, "Payload"), options.context),
2021
+ resolveSeedBytes(identityOrSeed)
2022
+ )
2023
+ );
2024
+ }
2025
+ async function verifyBytes(publicKey, payload, signature, options = {}) {
2026
+ return ed25519.verify(
2027
+ base64UrlDecode(signature),
2028
+ combineContext(ensureBytes(payload, "Payload"), options.context),
2029
+ resolvePublicKeyBytes(publicKey)
2030
+ );
2031
+ }
2032
+ async function signUtf8(identityOrSeed, value, options = {}) {
2033
+ return signBytes(identityOrSeed, utf8Bytes(value), options);
2034
+ }
2035
+ async function verifyUtf8(publicKey, value, signature, options = {}) {
2036
+ return verifyBytes(publicKey, utf8Bytes(value), signature, options);
2037
+ }
2038
+ const SEAL_SIGNATURE_CONTEXT = "ternent-seal/v2";
2039
+ function exportIdentityJson(identity) {
2040
+ return serializeIdentity(identity);
2041
+ }
2042
+ async function resolveSealSigner(input) {
2043
+ const identity = parseIdentity(input.identity);
2044
+ const keyId = await deriveKeyId(identity.publicKey);
2045
+ if (keyId !== identity.keyId) {
2046
+ throw new Error("Identity keyId does not match the signer public key.");
2047
+ }
2048
+ return {
2049
+ identity,
2050
+ publicKey: identity.publicKey,
2051
+ keyId
2052
+ };
2053
+ }
2054
+ async function signSealUtf8(identity, value) {
2055
+ return signUtf8(identity, value, {
2056
+ context: SEAL_SIGNATURE_CONTEXT
2057
+ });
2058
+ }
2059
+ async function verifySealUtf8(signature, value, publicKey) {
2060
+ return verifyUtf8(publicKey, value, signature, {
2061
+ context: SEAL_SIGNATURE_CONTEXT
2062
+ });
2063
+ }
2064
+ async function verifyPublicKeyKeyId(publicKey, keyId) {
2065
+ return await deriveKeyId(publicKey) === keyId;
2066
+ }
2067
+ export { SEAL_SIGNATURE_CONTEXT as S, verifySealUtf8 as a, exportIdentityJson as e, parseIdentity as p, resolveSealSigner as r, signSealUtf8 as s, verifyPublicKeyKeyId as v };
2068
+ //# sourceMappingURL=crypto-38954ec7.js.map