@themoltnet/legreffier 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1707 -5
  2. package/package.json +7 -7
package/dist/index.js CHANGED
@@ -2,14 +2,38 @@
2
2
  import { jsxs, jsx } from "react/jsx-runtime";
3
3
  import { parseArgs } from "node:util";
4
4
  import { useInput, Box, Text, useApp, render } from "ink";
5
+ import { execFileSync } from "node:child_process";
5
6
  import { join } from "node:path";
6
7
  import { useState, useEffect, useReducer, useRef } from "react";
7
8
  import figlet from "figlet";
8
9
  import { readFile, writeFile, mkdir, chmod, rm } from "node:fs/promises";
9
10
  import { homedir } from "node:os";
10
- import { createHash, randomBytes as randomBytes$1 } from "crypto";
11
+ import { createHash, randomBytes as randomBytes$2 } from "crypto";
11
12
  import { parse, stringify } from "smol-toml";
12
13
  import open from "open";
14
+ const MOLTNET_GITCONFIG_RE = /\.moltnet\/([^/]+)\/gitconfig$/;
15
+ function resolveAgentName(nameFlag, gitConfigGlobal) {
16
+ if (nameFlag) return nameFlag;
17
+ if (gitConfigGlobal) {
18
+ const match = MOLTNET_GITCONFIG_RE.exec(gitConfigGlobal);
19
+ if (match) return match[1];
20
+ }
21
+ throw new Error(
22
+ "agent name required — use --name or set GIT_CONFIG_GLOBAL=.moltnet/<name>/gitconfig"
23
+ );
24
+ }
25
+ function resolveCredentialsPath(agentName, dir2) {
26
+ return join(dir2, ".moltnet", agentName, "moltnet.json");
27
+ }
28
+ function printGitHubToken(agentName, dir2) {
29
+ const credPath = resolveCredentialsPath(agentName, dir2);
30
+ const token = execFileSync(
31
+ "npx",
32
+ ["@themoltnet/cli", "github", "token", "--credentials", credPath],
33
+ { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
34
+ ).trim();
35
+ process.stdout.write(token);
36
+ }
13
37
  const colors = {
14
38
  // Primary — teal/cyan (The Network)
15
39
  primary: {
@@ -1161,6 +1185,1611 @@ const startLegreffierOnboarding = (options) => (options.client ?? client).post({
1161
1185
  }
1162
1186
  });
1163
1187
  const getLegreffierOnboardingStatus = (options) => (options.client ?? client).get({ url: "/public/legreffier/status/{workflowId}", ...options });
1188
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1189
+ function isBytes$1(a) {
1190
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1191
+ }
1192
+ function anumber(n, title = "") {
1193
+ if (!Number.isSafeInteger(n) || n < 0) {
1194
+ const prefix = title && `"${title}" `;
1195
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
1196
+ }
1197
+ }
1198
+ function abytes$1(value, length, title = "") {
1199
+ const bytes = isBytes$1(value);
1200
+ const len = value?.length;
1201
+ const needsLen = length !== void 0;
1202
+ if (!bytes || needsLen && len !== length) {
1203
+ const prefix = title && `"${title}" `;
1204
+ const ofLen = needsLen ? ` of length ${length}` : "";
1205
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
1206
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
1207
+ }
1208
+ return value;
1209
+ }
1210
+ function aexists(instance, checkFinished = true) {
1211
+ if (instance.destroyed)
1212
+ throw new Error("Hash instance has been destroyed");
1213
+ if (checkFinished && instance.finished)
1214
+ throw new Error("Hash#digest() has already been called");
1215
+ }
1216
+ function aoutput(out, instance) {
1217
+ abytes$1(out, void 0, "digestInto() output");
1218
+ const min = instance.outputLen;
1219
+ if (out.length < min) {
1220
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
1221
+ }
1222
+ }
1223
+ function clean(...arrays) {
1224
+ for (let i = 0; i < arrays.length; i++) {
1225
+ arrays[i].fill(0);
1226
+ }
1227
+ }
1228
+ function createView(arr) {
1229
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1230
+ }
1231
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
1232
+ // @ts-ignore
1233
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
1234
+ ))();
1235
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1236
+ function bytesToHex$1(bytes) {
1237
+ abytes$1(bytes);
1238
+ if (hasHexBuiltin)
1239
+ return bytes.toHex();
1240
+ let hex = "";
1241
+ for (let i = 0; i < bytes.length; i++) {
1242
+ hex += hexes[bytes[i]];
1243
+ }
1244
+ return hex;
1245
+ }
1246
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1247
+ function asciiToBase16(ch) {
1248
+ if (ch >= asciis._0 && ch <= asciis._9)
1249
+ return ch - asciis._0;
1250
+ if (ch >= asciis.A && ch <= asciis.F)
1251
+ return ch - (asciis.A - 10);
1252
+ if (ch >= asciis.a && ch <= asciis.f)
1253
+ return ch - (asciis.a - 10);
1254
+ return;
1255
+ }
1256
+ function hexToBytes$1(hex) {
1257
+ if (typeof hex !== "string")
1258
+ throw new Error("hex string expected, got " + typeof hex);
1259
+ if (hasHexBuiltin)
1260
+ return Uint8Array.fromHex(hex);
1261
+ const hl = hex.length;
1262
+ const al = hl / 2;
1263
+ if (hl % 2)
1264
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
1265
+ const array = new Uint8Array(al);
1266
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1267
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
1268
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1269
+ if (n1 === void 0 || n2 === void 0) {
1270
+ const char = hex[hi] + hex[hi + 1];
1271
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1272
+ }
1273
+ array[ai] = n1 * 16 + n2;
1274
+ }
1275
+ return array;
1276
+ }
1277
+ function concatBytes$1(...arrays) {
1278
+ let sum = 0;
1279
+ for (let i = 0; i < arrays.length; i++) {
1280
+ const a = arrays[i];
1281
+ abytes$1(a);
1282
+ sum += a.length;
1283
+ }
1284
+ const res = new Uint8Array(sum);
1285
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1286
+ const a = arrays[i];
1287
+ res.set(a, pad);
1288
+ pad += a.length;
1289
+ }
1290
+ return res;
1291
+ }
1292
+ function createHasher(hashCons, info = {}) {
1293
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
1294
+ const tmp = hashCons(void 0);
1295
+ hashC.outputLen = tmp.outputLen;
1296
+ hashC.blockLen = tmp.blockLen;
1297
+ hashC.create = (opts) => hashCons(opts);
1298
+ Object.assign(hashC, info);
1299
+ return Object.freeze(hashC);
1300
+ }
1301
+ function randomBytes$1(bytesLength = 32) {
1302
+ const cr2 = typeof globalThis === "object" ? globalThis.crypto : null;
1303
+ if (typeof cr2?.getRandomValues !== "function")
1304
+ throw new Error("crypto.getRandomValues must be defined");
1305
+ return cr2.getRandomValues(new Uint8Array(bytesLength));
1306
+ }
1307
+ const oidNist = (suffix) => ({
1308
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
1309
+ });
1310
+ class HashMD {
1311
+ blockLen;
1312
+ outputLen;
1313
+ padOffset;
1314
+ isLE;
1315
+ // For partial updates less than block size
1316
+ buffer;
1317
+ view;
1318
+ finished = false;
1319
+ length = 0;
1320
+ pos = 0;
1321
+ destroyed = false;
1322
+ constructor(blockLen, outputLen, padOffset, isLE) {
1323
+ this.blockLen = blockLen;
1324
+ this.outputLen = outputLen;
1325
+ this.padOffset = padOffset;
1326
+ this.isLE = isLE;
1327
+ this.buffer = new Uint8Array(blockLen);
1328
+ this.view = createView(this.buffer);
1329
+ }
1330
+ update(data) {
1331
+ aexists(this);
1332
+ abytes$1(data);
1333
+ const { view, buffer, blockLen } = this;
1334
+ const len = data.length;
1335
+ for (let pos = 0; pos < len; ) {
1336
+ const take = Math.min(blockLen - this.pos, len - pos);
1337
+ if (take === blockLen) {
1338
+ const dataView = createView(data);
1339
+ for (; blockLen <= len - pos; pos += blockLen)
1340
+ this.process(dataView, pos);
1341
+ continue;
1342
+ }
1343
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1344
+ this.pos += take;
1345
+ pos += take;
1346
+ if (this.pos === blockLen) {
1347
+ this.process(view, 0);
1348
+ this.pos = 0;
1349
+ }
1350
+ }
1351
+ this.length += data.length;
1352
+ this.roundClean();
1353
+ return this;
1354
+ }
1355
+ digestInto(out) {
1356
+ aexists(this);
1357
+ aoutput(out, this);
1358
+ this.finished = true;
1359
+ const { buffer, view, blockLen, isLE } = this;
1360
+ let { pos } = this;
1361
+ buffer[pos++] = 128;
1362
+ clean(this.buffer.subarray(pos));
1363
+ if (this.padOffset > blockLen - pos) {
1364
+ this.process(view, 0);
1365
+ pos = 0;
1366
+ }
1367
+ for (let i = pos; i < blockLen; i++)
1368
+ buffer[i] = 0;
1369
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
1370
+ this.process(view, 0);
1371
+ const oview = createView(out);
1372
+ const len = this.outputLen;
1373
+ if (len % 4)
1374
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
1375
+ const outLen = len / 4;
1376
+ const state = this.get();
1377
+ if (outLen > state.length)
1378
+ throw new Error("_sha2: outputLen bigger than state");
1379
+ for (let i = 0; i < outLen; i++)
1380
+ oview.setUint32(4 * i, state[i], isLE);
1381
+ }
1382
+ digest() {
1383
+ const { buffer, outputLen } = this;
1384
+ this.digestInto(buffer);
1385
+ const res = buffer.slice(0, outputLen);
1386
+ this.destroy();
1387
+ return res;
1388
+ }
1389
+ _cloneInto(to) {
1390
+ to ||= new this.constructor();
1391
+ to.set(...this.get());
1392
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1393
+ to.destroyed = destroyed;
1394
+ to.finished = finished;
1395
+ to.length = length;
1396
+ to.pos = pos;
1397
+ if (length % blockLen)
1398
+ to.buffer.set(buffer);
1399
+ return to;
1400
+ }
1401
+ clone() {
1402
+ return this._cloneInto();
1403
+ }
1404
+ }
1405
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1406
+ 1779033703,
1407
+ 4089235720,
1408
+ 3144134277,
1409
+ 2227873595,
1410
+ 1013904242,
1411
+ 4271175723,
1412
+ 2773480762,
1413
+ 1595750129,
1414
+ 1359893119,
1415
+ 2917565137,
1416
+ 2600822924,
1417
+ 725511199,
1418
+ 528734635,
1419
+ 4215389547,
1420
+ 1541459225,
1421
+ 327033209
1422
+ ]);
1423
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1424
+ const _32n = /* @__PURE__ */ BigInt(32);
1425
+ function fromBig(n, le = false) {
1426
+ if (le)
1427
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
1428
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1429
+ }
1430
+ function split(lst, le = false) {
1431
+ const len = lst.length;
1432
+ let Ah = new Uint32Array(len);
1433
+ let Al = new Uint32Array(len);
1434
+ for (let i = 0; i < len; i++) {
1435
+ const { h: h2, l } = fromBig(lst[i], le);
1436
+ [Ah[i], Al[i]] = [h2, l];
1437
+ }
1438
+ return [Ah, Al];
1439
+ }
1440
+ const shrSH = (h2, _l, s) => h2 >>> s;
1441
+ const shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
1442
+ const rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
1443
+ const rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
1444
+ const rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
1445
+ const rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
1446
+ function add(Ah, Al, Bh, Bl) {
1447
+ const l = (Al >>> 0) + (Bl >>> 0);
1448
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
1449
+ }
1450
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1451
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1452
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1453
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1454
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1455
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1456
+ const K512 = /* @__PURE__ */ (() => split([
1457
+ "0x428a2f98d728ae22",
1458
+ "0x7137449123ef65cd",
1459
+ "0xb5c0fbcfec4d3b2f",
1460
+ "0xe9b5dba58189dbbc",
1461
+ "0x3956c25bf348b538",
1462
+ "0x59f111f1b605d019",
1463
+ "0x923f82a4af194f9b",
1464
+ "0xab1c5ed5da6d8118",
1465
+ "0xd807aa98a3030242",
1466
+ "0x12835b0145706fbe",
1467
+ "0x243185be4ee4b28c",
1468
+ "0x550c7dc3d5ffb4e2",
1469
+ "0x72be5d74f27b896f",
1470
+ "0x80deb1fe3b1696b1",
1471
+ "0x9bdc06a725c71235",
1472
+ "0xc19bf174cf692694",
1473
+ "0xe49b69c19ef14ad2",
1474
+ "0xefbe4786384f25e3",
1475
+ "0x0fc19dc68b8cd5b5",
1476
+ "0x240ca1cc77ac9c65",
1477
+ "0x2de92c6f592b0275",
1478
+ "0x4a7484aa6ea6e483",
1479
+ "0x5cb0a9dcbd41fbd4",
1480
+ "0x76f988da831153b5",
1481
+ "0x983e5152ee66dfab",
1482
+ "0xa831c66d2db43210",
1483
+ "0xb00327c898fb213f",
1484
+ "0xbf597fc7beef0ee4",
1485
+ "0xc6e00bf33da88fc2",
1486
+ "0xd5a79147930aa725",
1487
+ "0x06ca6351e003826f",
1488
+ "0x142929670a0e6e70",
1489
+ "0x27b70a8546d22ffc",
1490
+ "0x2e1b21385c26c926",
1491
+ "0x4d2c6dfc5ac42aed",
1492
+ "0x53380d139d95b3df",
1493
+ "0x650a73548baf63de",
1494
+ "0x766a0abb3c77b2a8",
1495
+ "0x81c2c92e47edaee6",
1496
+ "0x92722c851482353b",
1497
+ "0xa2bfe8a14cf10364",
1498
+ "0xa81a664bbc423001",
1499
+ "0xc24b8b70d0f89791",
1500
+ "0xc76c51a30654be30",
1501
+ "0xd192e819d6ef5218",
1502
+ "0xd69906245565a910",
1503
+ "0xf40e35855771202a",
1504
+ "0x106aa07032bbd1b8",
1505
+ "0x19a4c116b8d2d0c8",
1506
+ "0x1e376c085141ab53",
1507
+ "0x2748774cdf8eeb99",
1508
+ "0x34b0bcb5e19b48a8",
1509
+ "0x391c0cb3c5c95a63",
1510
+ "0x4ed8aa4ae3418acb",
1511
+ "0x5b9cca4f7763e373",
1512
+ "0x682e6ff3d6b2b8a3",
1513
+ "0x748f82ee5defb2fc",
1514
+ "0x78a5636f43172f60",
1515
+ "0x84c87814a1f0ab72",
1516
+ "0x8cc702081a6439ec",
1517
+ "0x90befffa23631e28",
1518
+ "0xa4506cebde82bde9",
1519
+ "0xbef9a3f7b2c67915",
1520
+ "0xc67178f2e372532b",
1521
+ "0xca273eceea26619c",
1522
+ "0xd186b8c721c0c207",
1523
+ "0xeada7dd6cde0eb1e",
1524
+ "0xf57d4f7fee6ed178",
1525
+ "0x06f067aa72176fba",
1526
+ "0x0a637dc5a2c898a6",
1527
+ "0x113f9804bef90dae",
1528
+ "0x1b710b35131c471b",
1529
+ "0x28db77f523047d84",
1530
+ "0x32caab7b40c72493",
1531
+ "0x3c9ebe0a15c9bebc",
1532
+ "0x431d67c49c100d4c",
1533
+ "0x4cc5d4becb3e42b6",
1534
+ "0x597f299cfc657e2a",
1535
+ "0x5fcb6fab3ad6faec",
1536
+ "0x6c44198c4a475817"
1537
+ ].map((n) => BigInt(n))))();
1538
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1539
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1540
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1541
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1542
+ class SHA2_64B extends HashMD {
1543
+ constructor(outputLen) {
1544
+ super(128, outputLen, 16, false);
1545
+ }
1546
+ // prettier-ignore
1547
+ get() {
1548
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1549
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1550
+ }
1551
+ // prettier-ignore
1552
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1553
+ this.Ah = Ah | 0;
1554
+ this.Al = Al | 0;
1555
+ this.Bh = Bh | 0;
1556
+ this.Bl = Bl | 0;
1557
+ this.Ch = Ch | 0;
1558
+ this.Cl = Cl | 0;
1559
+ this.Dh = Dh | 0;
1560
+ this.Dl = Dl | 0;
1561
+ this.Eh = Eh | 0;
1562
+ this.El = El | 0;
1563
+ this.Fh = Fh | 0;
1564
+ this.Fl = Fl | 0;
1565
+ this.Gh = Gh | 0;
1566
+ this.Gl = Gl | 0;
1567
+ this.Hh = Hh | 0;
1568
+ this.Hl = Hl | 0;
1569
+ }
1570
+ process(view, offset) {
1571
+ for (let i = 0; i < 16; i++, offset += 4) {
1572
+ SHA512_W_H[i] = view.getUint32(offset);
1573
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1574
+ }
1575
+ for (let i = 16; i < 80; i++) {
1576
+ const W15h = SHA512_W_H[i - 15] | 0;
1577
+ const W15l = SHA512_W_L[i - 15] | 0;
1578
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1579
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1580
+ const W2h = SHA512_W_H[i - 2] | 0;
1581
+ const W2l = SHA512_W_L[i - 2] | 0;
1582
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1583
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1584
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1585
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1586
+ SHA512_W_H[i] = SUMh | 0;
1587
+ SHA512_W_L[i] = SUMl | 0;
1588
+ }
1589
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1590
+ for (let i = 0; i < 80; i++) {
1591
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1592
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1593
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1594
+ const CHIl = El & Fl ^ ~El & Gl;
1595
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1596
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1597
+ const T1l = T1ll | 0;
1598
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1599
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1600
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1601
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1602
+ Hh = Gh | 0;
1603
+ Hl = Gl | 0;
1604
+ Gh = Fh | 0;
1605
+ Gl = Fl | 0;
1606
+ Fh = Eh | 0;
1607
+ Fl = El | 0;
1608
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1609
+ Dh = Ch | 0;
1610
+ Dl = Cl | 0;
1611
+ Ch = Bh | 0;
1612
+ Cl = Bl | 0;
1613
+ Bh = Ah | 0;
1614
+ Bl = Al | 0;
1615
+ const All = add3L(T1l, sigma0l, MAJl);
1616
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1617
+ Al = All | 0;
1618
+ }
1619
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1620
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1621
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1622
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1623
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1624
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1625
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1626
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1627
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1628
+ }
1629
+ roundClean() {
1630
+ clean(SHA512_W_H, SHA512_W_L);
1631
+ }
1632
+ destroy() {
1633
+ clean(this.buffer);
1634
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1635
+ }
1636
+ }
1637
+ class _SHA512 extends SHA2_64B {
1638
+ Ah = SHA512_IV[0] | 0;
1639
+ Al = SHA512_IV[1] | 0;
1640
+ Bh = SHA512_IV[2] | 0;
1641
+ Bl = SHA512_IV[3] | 0;
1642
+ Ch = SHA512_IV[4] | 0;
1643
+ Cl = SHA512_IV[5] | 0;
1644
+ Dh = SHA512_IV[6] | 0;
1645
+ Dl = SHA512_IV[7] | 0;
1646
+ Eh = SHA512_IV[8] | 0;
1647
+ El = SHA512_IV[9] | 0;
1648
+ Fh = SHA512_IV[10] | 0;
1649
+ Fl = SHA512_IV[11] | 0;
1650
+ Gh = SHA512_IV[12] | 0;
1651
+ Gl = SHA512_IV[13] | 0;
1652
+ Hh = SHA512_IV[14] | 0;
1653
+ Hl = SHA512_IV[15] | 0;
1654
+ constructor() {
1655
+ super(64);
1656
+ }
1657
+ }
1658
+ const sha512 = /* @__PURE__ */ createHasher(
1659
+ () => new _SHA512(),
1660
+ /* @__PURE__ */ oidNist(3)
1661
+ );
1662
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1663
+ const _0n$3 = /* @__PURE__ */ BigInt(0);
1664
+ const _1n$4 = /* @__PURE__ */ BigInt(1);
1665
+ function abool(value, title = "") {
1666
+ if (typeof value !== "boolean") {
1667
+ const prefix = title && `"${title}" `;
1668
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
1669
+ }
1670
+ return value;
1671
+ }
1672
+ function abignumber(n) {
1673
+ if (typeof n === "bigint") {
1674
+ if (!isPosBig(n))
1675
+ throw new Error("positive bigint expected, got " + n);
1676
+ } else
1677
+ anumber(n);
1678
+ return n;
1679
+ }
1680
+ function hexToNumber(hex) {
1681
+ if (typeof hex !== "string")
1682
+ throw new Error("hex string expected, got " + typeof hex);
1683
+ return hex === "" ? _0n$3 : BigInt("0x" + hex);
1684
+ }
1685
+ function bytesToNumberBE(bytes) {
1686
+ return hexToNumber(bytesToHex$1(bytes));
1687
+ }
1688
+ function bytesToNumberLE(bytes) {
1689
+ return hexToNumber(bytesToHex$1(copyBytes(abytes$1(bytes)).reverse()));
1690
+ }
1691
+ function numberToBytesBE(n, len) {
1692
+ anumber(len);
1693
+ n = abignumber(n);
1694
+ const res = hexToBytes$1(n.toString(16).padStart(len * 2, "0"));
1695
+ if (res.length !== len)
1696
+ throw new Error("number too large");
1697
+ return res;
1698
+ }
1699
+ function numberToBytesLE(n, len) {
1700
+ return numberToBytesBE(n, len).reverse();
1701
+ }
1702
+ function copyBytes(bytes) {
1703
+ return Uint8Array.from(bytes);
1704
+ }
1705
+ const isPosBig = (n) => typeof n === "bigint" && _0n$3 <= n;
1706
+ function inRange(n, min, max) {
1707
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1708
+ }
1709
+ function aInRange(title, n, min, max) {
1710
+ if (!inRange(n, min, max))
1711
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1712
+ }
1713
+ const bitMask = (n) => (_1n$4 << BigInt(n)) - _1n$4;
1714
+ function validateObject(object, fields = {}, optFields = {}) {
1715
+ if (!object || typeof object !== "object")
1716
+ throw new Error("expected valid options object");
1717
+ function checkField(fieldName, expectedType, isOpt) {
1718
+ const val = object[fieldName];
1719
+ if (isOpt && val === void 0)
1720
+ return;
1721
+ const current = typeof val;
1722
+ if (current !== expectedType || val === null)
1723
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
1724
+ }
1725
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1726
+ iter(fields, false);
1727
+ iter(optFields, true);
1728
+ }
1729
+ function memoized(fn) {
1730
+ const map = /* @__PURE__ */ new WeakMap();
1731
+ return (arg, ...args) => {
1732
+ const val = map.get(arg);
1733
+ if (val !== void 0)
1734
+ return val;
1735
+ const computed = fn(arg, ...args);
1736
+ map.set(arg, computed);
1737
+ return computed;
1738
+ };
1739
+ }
1740
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1741
+ const _0n$2 = /* @__PURE__ */ BigInt(0), _1n$3 = /* @__PURE__ */ BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2);
1742
+ const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5);
1743
+ const _7n = /* @__PURE__ */ BigInt(7), _8n$2 = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
1744
+ const _16n = /* @__PURE__ */ BigInt(16);
1745
+ function mod(a, b) {
1746
+ const result = a % b;
1747
+ return result >= _0n$2 ? result : b + result;
1748
+ }
1749
+ function pow2$1(x, power, modulo) {
1750
+ let res = x;
1751
+ while (power-- > _0n$2) {
1752
+ res *= res;
1753
+ res %= modulo;
1754
+ }
1755
+ return res;
1756
+ }
1757
+ function invert$1(number, modulo) {
1758
+ if (number === _0n$2)
1759
+ throw new Error("invert: expected non-zero number");
1760
+ if (modulo <= _0n$2)
1761
+ throw new Error("invert: expected positive modulus, got " + modulo);
1762
+ let a = mod(number, modulo);
1763
+ let b = modulo;
1764
+ let x = _0n$2, u = _1n$3;
1765
+ while (a !== _0n$2) {
1766
+ const q = b / a;
1767
+ const r = b % a;
1768
+ const m = x - u * q;
1769
+ b = a, a = r, x = u, u = m;
1770
+ }
1771
+ const gcd = b;
1772
+ if (gcd !== _1n$3)
1773
+ throw new Error("invert: does not exist");
1774
+ return mod(x, modulo);
1775
+ }
1776
+ function assertIsSquare(Fp, root, n) {
1777
+ if (!Fp.eql(Fp.sqr(root), n))
1778
+ throw new Error("Cannot find square root");
1779
+ }
1780
+ function sqrt3mod4(Fp, n) {
1781
+ const p1div4 = (Fp.ORDER + _1n$3) / _4n;
1782
+ const root = Fp.pow(n, p1div4);
1783
+ assertIsSquare(Fp, root, n);
1784
+ return root;
1785
+ }
1786
+ function sqrt5mod8(Fp, n) {
1787
+ const p5div8 = (Fp.ORDER - _5n$1) / _8n$2;
1788
+ const n2 = Fp.mul(n, _2n$2);
1789
+ const v = Fp.pow(n2, p5div8);
1790
+ const nv = Fp.mul(n, v);
1791
+ const i = Fp.mul(Fp.mul(nv, _2n$2), v);
1792
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
1793
+ assertIsSquare(Fp, root, n);
1794
+ return root;
1795
+ }
1796
+ function sqrt9mod16(P2) {
1797
+ const Fp_ = Field(P2);
1798
+ const tn = tonelliShanks(P2);
1799
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1800
+ const c2 = tn(Fp_, c1);
1801
+ const c3 = tn(Fp_, Fp_.neg(c1));
1802
+ const c4 = (P2 + _7n) / _16n;
1803
+ return (Fp, n) => {
1804
+ let tv1 = Fp.pow(n, c4);
1805
+ let tv2 = Fp.mul(tv1, c1);
1806
+ const tv3 = Fp.mul(tv1, c2);
1807
+ const tv4 = Fp.mul(tv1, c3);
1808
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
1809
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
1810
+ tv1 = Fp.cmov(tv1, tv2, e1);
1811
+ tv2 = Fp.cmov(tv4, tv3, e2);
1812
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
1813
+ const root = Fp.cmov(tv1, tv2, e3);
1814
+ assertIsSquare(Fp, root, n);
1815
+ return root;
1816
+ };
1817
+ }
1818
+ function tonelliShanks(P2) {
1819
+ if (P2 < _3n)
1820
+ throw new Error("sqrt is not defined for small field");
1821
+ let Q = P2 - _1n$3;
1822
+ let S = 0;
1823
+ while (Q % _2n$2 === _0n$2) {
1824
+ Q /= _2n$2;
1825
+ S++;
1826
+ }
1827
+ let Z = _2n$2;
1828
+ const _Fp = Field(P2);
1829
+ while (FpLegendre(_Fp, Z) === 1) {
1830
+ if (Z++ > 1e3)
1831
+ throw new Error("Cannot find square root: probably non-prime P");
1832
+ }
1833
+ if (S === 1)
1834
+ return sqrt3mod4;
1835
+ let cc = _Fp.pow(Z, Q);
1836
+ const Q1div2 = (Q + _1n$3) / _2n$2;
1837
+ return function tonelliSlow(Fp, n) {
1838
+ if (Fp.is0(n))
1839
+ return n;
1840
+ if (FpLegendre(Fp, n) !== 1)
1841
+ throw new Error("Cannot find square root");
1842
+ let M2 = S;
1843
+ let c = Fp.mul(Fp.ONE, cc);
1844
+ let t = Fp.pow(n, Q);
1845
+ let R = Fp.pow(n, Q1div2);
1846
+ while (!Fp.eql(t, Fp.ONE)) {
1847
+ if (Fp.is0(t))
1848
+ return Fp.ZERO;
1849
+ let i = 1;
1850
+ let t_tmp = Fp.sqr(t);
1851
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
1852
+ i++;
1853
+ t_tmp = Fp.sqr(t_tmp);
1854
+ if (i === M2)
1855
+ throw new Error("Cannot find square root");
1856
+ }
1857
+ const exponent = _1n$3 << BigInt(M2 - i - 1);
1858
+ const b = Fp.pow(c, exponent);
1859
+ M2 = i;
1860
+ c = Fp.sqr(b);
1861
+ t = Fp.mul(t, c);
1862
+ R = Fp.mul(R, b);
1863
+ }
1864
+ return R;
1865
+ };
1866
+ }
1867
+ function FpSqrt(P2) {
1868
+ if (P2 % _4n === _3n)
1869
+ return sqrt3mod4;
1870
+ if (P2 % _8n$2 === _5n$1)
1871
+ return sqrt5mod8;
1872
+ if (P2 % _16n === _9n)
1873
+ return sqrt9mod16(P2);
1874
+ return tonelliShanks(P2);
1875
+ }
1876
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$3) === _1n$3;
1877
+ const FIELD_FIELDS = [
1878
+ "create",
1879
+ "isValid",
1880
+ "is0",
1881
+ "neg",
1882
+ "inv",
1883
+ "sqrt",
1884
+ "sqr",
1885
+ "eql",
1886
+ "add",
1887
+ "sub",
1888
+ "mul",
1889
+ "pow",
1890
+ "div",
1891
+ "addN",
1892
+ "subN",
1893
+ "mulN",
1894
+ "sqrN"
1895
+ ];
1896
+ function validateField(field) {
1897
+ const initial = {
1898
+ ORDER: "bigint",
1899
+ BYTES: "number",
1900
+ BITS: "number"
1901
+ };
1902
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1903
+ map[val] = "function";
1904
+ return map;
1905
+ }, initial);
1906
+ validateObject(field, opts);
1907
+ return field;
1908
+ }
1909
+ function FpPow(Fp, num, power) {
1910
+ if (power < _0n$2)
1911
+ throw new Error("invalid exponent, negatives unsupported");
1912
+ if (power === _0n$2)
1913
+ return Fp.ONE;
1914
+ if (power === _1n$3)
1915
+ return num;
1916
+ let p = Fp.ONE;
1917
+ let d = num;
1918
+ while (power > _0n$2) {
1919
+ if (power & _1n$3)
1920
+ p = Fp.mul(p, d);
1921
+ d = Fp.sqr(d);
1922
+ power >>= _1n$3;
1923
+ }
1924
+ return p;
1925
+ }
1926
+ function FpInvertBatch(Fp, nums, passZero = false) {
1927
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
1928
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1929
+ if (Fp.is0(num))
1930
+ return acc;
1931
+ inverted[i] = acc;
1932
+ return Fp.mul(acc, num);
1933
+ }, Fp.ONE);
1934
+ const invertedAcc = Fp.inv(multipliedAcc);
1935
+ nums.reduceRight((acc, num, i) => {
1936
+ if (Fp.is0(num))
1937
+ return acc;
1938
+ inverted[i] = Fp.mul(acc, inverted[i]);
1939
+ return Fp.mul(acc, num);
1940
+ }, invertedAcc);
1941
+ return inverted;
1942
+ }
1943
+ function FpLegendre(Fp, n) {
1944
+ const p1mod2 = (Fp.ORDER - _1n$3) / _2n$2;
1945
+ const powered = Fp.pow(n, p1mod2);
1946
+ const yes = Fp.eql(powered, Fp.ONE);
1947
+ const zero = Fp.eql(powered, Fp.ZERO);
1948
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1949
+ if (!yes && !zero && !no)
1950
+ throw new Error("invalid Legendre symbol result");
1951
+ return yes ? 1 : zero ? 0 : -1;
1952
+ }
1953
+ function nLength(n, nBitLength) {
1954
+ if (nBitLength !== void 0)
1955
+ anumber(nBitLength);
1956
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1957
+ const nByteLength = Math.ceil(_nBitLength / 8);
1958
+ return { nBitLength: _nBitLength, nByteLength };
1959
+ }
1960
+ class _Field {
1961
+ ORDER;
1962
+ BITS;
1963
+ BYTES;
1964
+ isLE;
1965
+ ZERO = _0n$2;
1966
+ ONE = _1n$3;
1967
+ _lengths;
1968
+ _sqrt;
1969
+ // cached sqrt
1970
+ _mod;
1971
+ constructor(ORDER, opts = {}) {
1972
+ if (ORDER <= _0n$2)
1973
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1974
+ let _nbitLength = void 0;
1975
+ this.isLE = false;
1976
+ if (opts != null && typeof opts === "object") {
1977
+ if (typeof opts.BITS === "number")
1978
+ _nbitLength = opts.BITS;
1979
+ if (typeof opts.sqrt === "function")
1980
+ this.sqrt = opts.sqrt;
1981
+ if (typeof opts.isLE === "boolean")
1982
+ this.isLE = opts.isLE;
1983
+ if (opts.allowedLengths)
1984
+ this._lengths = opts.allowedLengths?.slice();
1985
+ if (typeof opts.modFromBytes === "boolean")
1986
+ this._mod = opts.modFromBytes;
1987
+ }
1988
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1989
+ if (nByteLength > 2048)
1990
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1991
+ this.ORDER = ORDER;
1992
+ this.BITS = nBitLength;
1993
+ this.BYTES = nByteLength;
1994
+ this._sqrt = void 0;
1995
+ Object.preventExtensions(this);
1996
+ }
1997
+ create(num) {
1998
+ return mod(num, this.ORDER);
1999
+ }
2000
+ isValid(num) {
2001
+ if (typeof num !== "bigint")
2002
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
2003
+ return _0n$2 <= num && num < this.ORDER;
2004
+ }
2005
+ is0(num) {
2006
+ return num === _0n$2;
2007
+ }
2008
+ // is valid and invertible
2009
+ isValidNot0(num) {
2010
+ return !this.is0(num) && this.isValid(num);
2011
+ }
2012
+ isOdd(num) {
2013
+ return (num & _1n$3) === _1n$3;
2014
+ }
2015
+ neg(num) {
2016
+ return mod(-num, this.ORDER);
2017
+ }
2018
+ eql(lhs, rhs) {
2019
+ return lhs === rhs;
2020
+ }
2021
+ sqr(num) {
2022
+ return mod(num * num, this.ORDER);
2023
+ }
2024
+ add(lhs, rhs) {
2025
+ return mod(lhs + rhs, this.ORDER);
2026
+ }
2027
+ sub(lhs, rhs) {
2028
+ return mod(lhs - rhs, this.ORDER);
2029
+ }
2030
+ mul(lhs, rhs) {
2031
+ return mod(lhs * rhs, this.ORDER);
2032
+ }
2033
+ pow(num, power) {
2034
+ return FpPow(this, num, power);
2035
+ }
2036
+ div(lhs, rhs) {
2037
+ return mod(lhs * invert$1(rhs, this.ORDER), this.ORDER);
2038
+ }
2039
+ // Same as above, but doesn't normalize
2040
+ sqrN(num) {
2041
+ return num * num;
2042
+ }
2043
+ addN(lhs, rhs) {
2044
+ return lhs + rhs;
2045
+ }
2046
+ subN(lhs, rhs) {
2047
+ return lhs - rhs;
2048
+ }
2049
+ mulN(lhs, rhs) {
2050
+ return lhs * rhs;
2051
+ }
2052
+ inv(num) {
2053
+ return invert$1(num, this.ORDER);
2054
+ }
2055
+ sqrt(num) {
2056
+ if (!this._sqrt)
2057
+ this._sqrt = FpSqrt(this.ORDER);
2058
+ return this._sqrt(this, num);
2059
+ }
2060
+ toBytes(num) {
2061
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
2062
+ }
2063
+ fromBytes(bytes, skipValidation = false) {
2064
+ abytes$1(bytes);
2065
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
2066
+ if (allowedLengths) {
2067
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
2068
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
2069
+ }
2070
+ const padded = new Uint8Array(BYTES);
2071
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
2072
+ bytes = padded;
2073
+ }
2074
+ if (bytes.length !== BYTES)
2075
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
2076
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
2077
+ if (modFromBytes)
2078
+ scalar = mod(scalar, ORDER);
2079
+ if (!skipValidation) {
2080
+ if (!this.isValid(scalar))
2081
+ throw new Error("invalid field element: outside of range 0..ORDER");
2082
+ }
2083
+ return scalar;
2084
+ }
2085
+ // TODO: we don't need it here, move out to separate fn
2086
+ invertBatch(lst) {
2087
+ return FpInvertBatch(this, lst);
2088
+ }
2089
+ // We can't move this out because Fp6, Fp12 implement it
2090
+ // and it's unclear what to return in there.
2091
+ cmov(a, b, condition) {
2092
+ return condition ? b : a;
2093
+ }
2094
+ }
2095
+ function Field(ORDER, opts = {}) {
2096
+ return new _Field(ORDER, opts);
2097
+ }
2098
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2099
+ const _0n$1 = /* @__PURE__ */ BigInt(0);
2100
+ const _1n$2 = /* @__PURE__ */ BigInt(1);
2101
+ function negateCt(condition, item) {
2102
+ const neg = item.negate();
2103
+ return condition ? neg : item;
2104
+ }
2105
+ function normalizeZ(c, points) {
2106
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
2107
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
2108
+ }
2109
+ function validateW(W2, bits) {
2110
+ if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits)
2111
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2);
2112
+ }
2113
+ function calcWOpts(W2, scalarBits2) {
2114
+ validateW(W2, scalarBits2);
2115
+ const windows = Math.ceil(scalarBits2 / W2) + 1;
2116
+ const windowSize = 2 ** (W2 - 1);
2117
+ const maxNumber = 2 ** W2;
2118
+ const mask = bitMask(W2);
2119
+ const shiftBy = BigInt(W2);
2120
+ return { windows, windowSize, mask, maxNumber, shiftBy };
2121
+ }
2122
+ function calcOffsets(n, window, wOpts) {
2123
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
2124
+ let wbits = Number(n & mask);
2125
+ let nextN = n >> shiftBy;
2126
+ if (wbits > windowSize) {
2127
+ wbits -= maxNumber;
2128
+ nextN += _1n$2;
2129
+ }
2130
+ const offsetStart = window * windowSize;
2131
+ const offset = offsetStart + Math.abs(wbits) - 1;
2132
+ const isZero = wbits === 0;
2133
+ const isNeg = wbits < 0;
2134
+ const isNegF = window % 2 !== 0;
2135
+ const offsetF = offsetStart;
2136
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
2137
+ }
2138
+ const pointPrecomputes = /* @__PURE__ */ new WeakMap();
2139
+ const pointWindowSizes = /* @__PURE__ */ new WeakMap();
2140
+ function getW(P2) {
2141
+ return pointWindowSizes.get(P2) || 1;
2142
+ }
2143
+ function assert0(n) {
2144
+ if (n !== _0n$1)
2145
+ throw new Error("invalid wNAF");
2146
+ }
2147
+ let wNAF$1 = class wNAF {
2148
+ BASE;
2149
+ ZERO;
2150
+ Fn;
2151
+ bits;
2152
+ // Parametrized with a given Point class (not individual point)
2153
+ constructor(Point2, bits) {
2154
+ this.BASE = Point2.BASE;
2155
+ this.ZERO = Point2.ZERO;
2156
+ this.Fn = Point2.Fn;
2157
+ this.bits = bits;
2158
+ }
2159
+ // non-const time multiplication ladder
2160
+ _unsafeLadder(elm, n, p = this.ZERO) {
2161
+ let d = elm;
2162
+ while (n > _0n$1) {
2163
+ if (n & _1n$2)
2164
+ p = p.add(d);
2165
+ d = d.double();
2166
+ n >>= _1n$2;
2167
+ }
2168
+ return p;
2169
+ }
2170
+ /**
2171
+ * Creates a wNAF precomputation window. Used for caching.
2172
+ * Default window size is set by `utils.precompute()` and is equal to 8.
2173
+ * Number of precomputed points depends on the curve size:
2174
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
2175
+ * - 𝑊 is the window size
2176
+ * - 𝑛 is the bitlength of the curve order.
2177
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
2178
+ * @param point Point instance
2179
+ * @param W window size
2180
+ * @returns precomputed point tables flattened to a single array
2181
+ */
2182
+ precomputeWindow(point, W2) {
2183
+ const { windows, windowSize } = calcWOpts(W2, this.bits);
2184
+ const points = [];
2185
+ let p = point;
2186
+ let base = p;
2187
+ for (let window = 0; window < windows; window++) {
2188
+ base = p;
2189
+ points.push(base);
2190
+ for (let i = 1; i < windowSize; i++) {
2191
+ base = base.add(p);
2192
+ points.push(base);
2193
+ }
2194
+ p = base.double();
2195
+ }
2196
+ return points;
2197
+ }
2198
+ /**
2199
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
2200
+ * More compact implementation:
2201
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
2202
+ * @returns real and fake (for const-time) points
2203
+ */
2204
+ wNAF(W2, precomputes, n) {
2205
+ if (!this.Fn.isValid(n))
2206
+ throw new Error("invalid scalar");
2207
+ let p = this.ZERO;
2208
+ let f = this.BASE;
2209
+ const wo = calcWOpts(W2, this.bits);
2210
+ for (let window = 0; window < wo.windows; window++) {
2211
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
2212
+ n = nextN;
2213
+ if (isZero) {
2214
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
2215
+ } else {
2216
+ p = p.add(negateCt(isNeg, precomputes[offset]));
2217
+ }
2218
+ }
2219
+ assert0(n);
2220
+ return { p, f };
2221
+ }
2222
+ /**
2223
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
2224
+ * @param acc accumulator point to add result of multiplication
2225
+ * @returns point
2226
+ */
2227
+ wNAFUnsafe(W2, precomputes, n, acc = this.ZERO) {
2228
+ const wo = calcWOpts(W2, this.bits);
2229
+ for (let window = 0; window < wo.windows; window++) {
2230
+ if (n === _0n$1)
2231
+ break;
2232
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
2233
+ n = nextN;
2234
+ if (isZero) {
2235
+ continue;
2236
+ } else {
2237
+ const item = precomputes[offset];
2238
+ acc = acc.add(isNeg ? item.negate() : item);
2239
+ }
2240
+ }
2241
+ assert0(n);
2242
+ return acc;
2243
+ }
2244
+ getPrecomputes(W2, point, transform) {
2245
+ let comp = pointPrecomputes.get(point);
2246
+ if (!comp) {
2247
+ comp = this.precomputeWindow(point, W2);
2248
+ if (W2 !== 1) {
2249
+ if (typeof transform === "function")
2250
+ comp = transform(comp);
2251
+ pointPrecomputes.set(point, comp);
2252
+ }
2253
+ }
2254
+ return comp;
2255
+ }
2256
+ cached(point, scalar, transform) {
2257
+ const W2 = getW(point);
2258
+ return this.wNAF(W2, this.getPrecomputes(W2, point, transform), scalar);
2259
+ }
2260
+ unsafe(point, scalar, transform, prev) {
2261
+ const W2 = getW(point);
2262
+ if (W2 === 1)
2263
+ return this._unsafeLadder(point, scalar, prev);
2264
+ return this.wNAFUnsafe(W2, this.getPrecomputes(W2, point, transform), scalar, prev);
2265
+ }
2266
+ // We calculate precomputes for elliptic curve point multiplication
2267
+ // using windowed method. This specifies window size and
2268
+ // stores precomputed values. Usually only base point would be precomputed.
2269
+ createCache(P2, W2) {
2270
+ validateW(W2, this.bits);
2271
+ pointWindowSizes.set(P2, W2);
2272
+ pointPrecomputes.delete(P2);
2273
+ }
2274
+ hasCache(elm) {
2275
+ return getW(elm) !== 1;
2276
+ }
2277
+ };
2278
+ function createField(order, field, isLE) {
2279
+ if (field) {
2280
+ if (field.ORDER !== order)
2281
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
2282
+ validateField(field);
2283
+ return field;
2284
+ } else {
2285
+ return Field(order, { isLE });
2286
+ }
2287
+ }
2288
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
2289
+ if (FpFnLE === void 0)
2290
+ FpFnLE = type === "edwards";
2291
+ if (!CURVE || typeof CURVE !== "object")
2292
+ throw new Error(`expected valid ${type} CURVE object`);
2293
+ for (const p of ["p", "n", "h"]) {
2294
+ const val = CURVE[p];
2295
+ if (!(typeof val === "bigint" && val > _0n$1))
2296
+ throw new Error(`CURVE.${p} must be positive bigint`);
2297
+ }
2298
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
2299
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
2300
+ const _b = "d";
2301
+ const params = ["Gx", "Gy", "a", _b];
2302
+ for (const p of params) {
2303
+ if (!Fp.isValid(CURVE[p]))
2304
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
2305
+ }
2306
+ CURVE = Object.freeze(Object.assign({}, CURVE));
2307
+ return { CURVE, Fp, Fn };
2308
+ }
2309
+ function createKeygen(randomSecretKey, getPublicKey2) {
2310
+ return function keygen(seed) {
2311
+ const secretKey = randomSecretKey(seed);
2312
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
2313
+ };
2314
+ }
2315
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2316
+ const _0n = BigInt(0), _1n$1 = BigInt(1), _2n$1 = BigInt(2), _8n$1 = BigInt(8);
2317
+ function isEdValidXY(Fp, CURVE, x, y) {
2318
+ const x2 = Fp.sqr(x);
2319
+ const y2 = Fp.sqr(y);
2320
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
2321
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
2322
+ return Fp.eql(left, right);
2323
+ }
2324
+ function edwards(params, extraOpts = {}) {
2325
+ const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
2326
+ const { Fp, Fn } = validated;
2327
+ let CURVE = validated.CURVE;
2328
+ const { h: cofactor } = CURVE;
2329
+ validateObject(extraOpts, {}, { uvRatio: "function" });
2330
+ const MASK = _2n$1 << BigInt(Fn.BYTES * 8) - _1n$1;
2331
+ const modP = (n) => Fp.create(n);
2332
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
2333
+ try {
2334
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
2335
+ } catch (e) {
2336
+ return { isValid: false, value: _0n };
2337
+ }
2338
+ });
2339
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
2340
+ throw new Error("bad curve params: generator point");
2341
+ function acoord(title, n, banZero = false) {
2342
+ const min = banZero ? _1n$1 : _0n;
2343
+ aInRange("coordinate " + title, n, min, MASK);
2344
+ return n;
2345
+ }
2346
+ function aedpoint(other) {
2347
+ if (!(other instanceof Point2))
2348
+ throw new Error("EdwardsPoint expected");
2349
+ }
2350
+ const toAffineMemo = memoized((p, iz) => {
2351
+ const { X, Y, Z } = p;
2352
+ const is0 = p.is0();
2353
+ if (iz == null)
2354
+ iz = is0 ? _8n$1 : Fp.inv(Z);
2355
+ const x = modP(X * iz);
2356
+ const y = modP(Y * iz);
2357
+ const zz = Fp.mul(Z, iz);
2358
+ if (is0)
2359
+ return { x: _0n, y: _1n$1 };
2360
+ if (zz !== _1n$1)
2361
+ throw new Error("invZ was invalid");
2362
+ return { x, y };
2363
+ });
2364
+ const assertValidMemo = memoized((p) => {
2365
+ const { a, d } = CURVE;
2366
+ if (p.is0())
2367
+ throw new Error("bad point: ZERO");
2368
+ const { X, Y, Z, T } = p;
2369
+ const X2 = modP(X * X);
2370
+ const Y2 = modP(Y * Y);
2371
+ const Z2 = modP(Z * Z);
2372
+ const Z4 = modP(Z2 * Z2);
2373
+ const aX2 = modP(X2 * a);
2374
+ const left = modP(Z2 * modP(aX2 + Y2));
2375
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
2376
+ if (left !== right)
2377
+ throw new Error("bad point: equation left != right (1)");
2378
+ const XY = modP(X * Y);
2379
+ const ZT = modP(Z * T);
2380
+ if (XY !== ZT)
2381
+ throw new Error("bad point: equation left != right (2)");
2382
+ return true;
2383
+ });
2384
+ class Point2 {
2385
+ // base / generator point
2386
+ static BASE = new Point2(CURVE.Gx, CURVE.Gy, _1n$1, modP(CURVE.Gx * CURVE.Gy));
2387
+ // zero / infinity / identity point
2388
+ static ZERO = new Point2(_0n, _1n$1, _1n$1, _0n);
2389
+ // 0, 1, 1, 0
2390
+ // math field
2391
+ static Fp = Fp;
2392
+ // scalar field
2393
+ static Fn = Fn;
2394
+ X;
2395
+ Y;
2396
+ Z;
2397
+ T;
2398
+ constructor(X, Y, Z, T) {
2399
+ this.X = acoord("x", X);
2400
+ this.Y = acoord("y", Y);
2401
+ this.Z = acoord("z", Z, true);
2402
+ this.T = acoord("t", T);
2403
+ Object.freeze(this);
2404
+ }
2405
+ static CURVE() {
2406
+ return CURVE;
2407
+ }
2408
+ static fromAffine(p) {
2409
+ if (p instanceof Point2)
2410
+ throw new Error("extended point not allowed");
2411
+ const { x, y } = p || {};
2412
+ acoord("x", x);
2413
+ acoord("y", y);
2414
+ return new Point2(x, y, _1n$1, modP(x * y));
2415
+ }
2416
+ // Uses algo from RFC8032 5.1.3.
2417
+ static fromBytes(bytes, zip215 = false) {
2418
+ const len = Fp.BYTES;
2419
+ const { a, d } = CURVE;
2420
+ bytes = copyBytes(abytes$1(bytes, len, "point"));
2421
+ abool(zip215, "zip215");
2422
+ const normed = copyBytes(bytes);
2423
+ const lastByte = bytes[len - 1];
2424
+ normed[len - 1] = lastByte & -129;
2425
+ const y = bytesToNumberLE(normed);
2426
+ const max = zip215 ? MASK : Fp.ORDER;
2427
+ aInRange("point.y", y, _0n, max);
2428
+ const y2 = modP(y * y);
2429
+ const u = modP(y2 - _1n$1);
2430
+ const v = modP(d * y2 - a);
2431
+ let { isValid, value: x } = uvRatio2(u, v);
2432
+ if (!isValid)
2433
+ throw new Error("bad point: invalid y coordinate");
2434
+ const isXOdd = (x & _1n$1) === _1n$1;
2435
+ const isLastByteOdd = (lastByte & 128) !== 0;
2436
+ if (!zip215 && x === _0n && isLastByteOdd)
2437
+ throw new Error("bad point: x=0 and x_0=1");
2438
+ if (isLastByteOdd !== isXOdd)
2439
+ x = modP(-x);
2440
+ return Point2.fromAffine({ x, y });
2441
+ }
2442
+ static fromHex(hex, zip215 = false) {
2443
+ return Point2.fromBytes(hexToBytes$1(hex), zip215);
2444
+ }
2445
+ get x() {
2446
+ return this.toAffine().x;
2447
+ }
2448
+ get y() {
2449
+ return this.toAffine().y;
2450
+ }
2451
+ precompute(windowSize = 8, isLazy = true) {
2452
+ wnaf.createCache(this, windowSize);
2453
+ if (!isLazy)
2454
+ this.multiply(_2n$1);
2455
+ return this;
2456
+ }
2457
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
2458
+ assertValidity() {
2459
+ assertValidMemo(this);
2460
+ }
2461
+ // Compare one point to another.
2462
+ equals(other) {
2463
+ aedpoint(other);
2464
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2465
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2466
+ const X1Z2 = modP(X1 * Z2);
2467
+ const X2Z1 = modP(X2 * Z1);
2468
+ const Y1Z2 = modP(Y1 * Z2);
2469
+ const Y2Z1 = modP(Y2 * Z1);
2470
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
2471
+ }
2472
+ is0() {
2473
+ return this.equals(Point2.ZERO);
2474
+ }
2475
+ negate() {
2476
+ return new Point2(modP(-this.X), this.Y, this.Z, modP(-this.T));
2477
+ }
2478
+ // Fast algo for doubling Extended Point.
2479
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
2480
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
2481
+ double() {
2482
+ const { a } = CURVE;
2483
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2484
+ const A = modP(X1 * X1);
2485
+ const B = modP(Y1 * Y1);
2486
+ const C2 = modP(_2n$1 * modP(Z1 * Z1));
2487
+ const D = modP(a * A);
2488
+ const x1y1 = X1 + Y1;
2489
+ const E = modP(modP(x1y1 * x1y1) - A - B);
2490
+ const G2 = D + B;
2491
+ const F = G2 - C2;
2492
+ const H = D - B;
2493
+ const X3 = modP(E * F);
2494
+ const Y3 = modP(G2 * H);
2495
+ const T3 = modP(E * H);
2496
+ const Z3 = modP(F * G2);
2497
+ return new Point2(X3, Y3, Z3, T3);
2498
+ }
2499
+ // Fast algo for adding 2 Extended Points.
2500
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
2501
+ // Cost: 9M + 1*a + 1*d + 7add.
2502
+ add(other) {
2503
+ aedpoint(other);
2504
+ const { a, d } = CURVE;
2505
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
2506
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
2507
+ const A = modP(X1 * X2);
2508
+ const B = modP(Y1 * Y2);
2509
+ const C2 = modP(T1 * d * T2);
2510
+ const D = modP(Z1 * Z2);
2511
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
2512
+ const F = D - C2;
2513
+ const G2 = D + C2;
2514
+ const H = modP(B - a * A);
2515
+ const X3 = modP(E * F);
2516
+ const Y3 = modP(G2 * H);
2517
+ const T3 = modP(E * H);
2518
+ const Z3 = modP(F * G2);
2519
+ return new Point2(X3, Y3, Z3, T3);
2520
+ }
2521
+ subtract(other) {
2522
+ return this.add(other.negate());
2523
+ }
2524
+ // Constant-time multiplication.
2525
+ multiply(scalar) {
2526
+ if (!Fn.isValidNot0(scalar))
2527
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
2528
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point2, p2));
2529
+ return normalizeZ(Point2, [p, f])[0];
2530
+ }
2531
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
2532
+ // It's faster, but should only be used when you don't care about
2533
+ // an exposed private key e.g. sig verification.
2534
+ // Does NOT allow scalars higher than CURVE.n.
2535
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
2536
+ multiplyUnsafe(scalar, acc = Point2.ZERO) {
2537
+ if (!Fn.isValid(scalar))
2538
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
2539
+ if (scalar === _0n)
2540
+ return Point2.ZERO;
2541
+ if (this.is0() || scalar === _1n$1)
2542
+ return this;
2543
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point2, p), acc);
2544
+ }
2545
+ // Checks if point is of small order.
2546
+ // If you add something to small order point, you will have "dirty"
2547
+ // point with torsion component.
2548
+ // Multiplies point by cofactor and checks if the result is 0.
2549
+ isSmallOrder() {
2550
+ return this.multiplyUnsafe(cofactor).is0();
2551
+ }
2552
+ // Multiplies point by curve order and checks if the result is 0.
2553
+ // Returns `false` is the point is dirty.
2554
+ isTorsionFree() {
2555
+ return wnaf.unsafe(this, CURVE.n).is0();
2556
+ }
2557
+ // Converts Extended point to default (x, y) coordinates.
2558
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2559
+ toAffine(invertedZ) {
2560
+ return toAffineMemo(this, invertedZ);
2561
+ }
2562
+ clearCofactor() {
2563
+ if (cofactor === _1n$1)
2564
+ return this;
2565
+ return this.multiplyUnsafe(cofactor);
2566
+ }
2567
+ toBytes() {
2568
+ const { x, y } = this.toAffine();
2569
+ const bytes = Fp.toBytes(y);
2570
+ bytes[bytes.length - 1] |= x & _1n$1 ? 128 : 0;
2571
+ return bytes;
2572
+ }
2573
+ toHex() {
2574
+ return bytesToHex$1(this.toBytes());
2575
+ }
2576
+ toString() {
2577
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2578
+ }
2579
+ }
2580
+ const wnaf = new wNAF$1(Point2, Fn.BITS);
2581
+ Point2.BASE.precompute(8);
2582
+ return Point2;
2583
+ }
2584
+ function eddsa(Point2, cHash, eddsaOpts = {}) {
2585
+ if (typeof cHash !== "function")
2586
+ throw new Error('"hash" function param is required');
2587
+ validateObject(eddsaOpts, {}, {
2588
+ adjustScalarBytes: "function",
2589
+ randomBytes: "function",
2590
+ domain: "function",
2591
+ prehash: "function",
2592
+ mapToCurve: "function"
2593
+ });
2594
+ const { prehash } = eddsaOpts;
2595
+ const { BASE, Fp, Fn } = Point2;
2596
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes$1;
2597
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
2598
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
2599
+ abool(phflag, "phflag");
2600
+ if (ctx.length || phflag)
2601
+ throw new Error("Contexts/pre-hash are not supported");
2602
+ return data;
2603
+ });
2604
+ function modN_LE(hash) {
2605
+ return Fn.create(bytesToNumberLE(hash));
2606
+ }
2607
+ function getPrivateScalar(key) {
2608
+ const len = lengths.secretKey;
2609
+ abytes$1(key, lengths.secretKey, "secretKey");
2610
+ const hashed = abytes$1(cHash(key), 2 * len, "hashedSecretKey");
2611
+ const head = adjustScalarBytes2(hashed.slice(0, len));
2612
+ const prefix = hashed.slice(len, 2 * len);
2613
+ const scalar = modN_LE(head);
2614
+ return { head, prefix, scalar };
2615
+ }
2616
+ function getExtendedPublicKey2(secretKey) {
2617
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
2618
+ const point = BASE.multiply(scalar);
2619
+ const pointBytes = point.toBytes();
2620
+ return { head, prefix, scalar, point, pointBytes };
2621
+ }
2622
+ function getPublicKey2(secretKey) {
2623
+ return getExtendedPublicKey2(secretKey).pointBytes;
2624
+ }
2625
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
2626
+ const msg = concatBytes$1(...msgs);
2627
+ return modN_LE(cHash(domain(msg, abytes$1(context, void 0, "context"), !!prehash)));
2628
+ }
2629
+ function sign(msg, secretKey, options = {}) {
2630
+ msg = abytes$1(msg, void 0, "message");
2631
+ if (prehash)
2632
+ msg = prehash(msg);
2633
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey2(secretKey);
2634
+ const r = hashDomainToScalar(options.context, prefix, msg);
2635
+ const R = BASE.multiply(r).toBytes();
2636
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2637
+ const s = Fn.create(r + k * scalar);
2638
+ if (!Fn.isValid(s))
2639
+ throw new Error("sign failed: invalid s");
2640
+ const rs = concatBytes$1(R, Fn.toBytes(s));
2641
+ return abytes$1(rs, lengths.signature, "result");
2642
+ }
2643
+ const verifyOpts = { zip215: true };
2644
+ function verify(sig, msg, publicKey, options = verifyOpts) {
2645
+ const { context, zip215 } = options;
2646
+ const len = lengths.signature;
2647
+ sig = abytes$1(sig, len, "signature");
2648
+ msg = abytes$1(msg, void 0, "message");
2649
+ publicKey = abytes$1(publicKey, lengths.publicKey, "publicKey");
2650
+ if (zip215 !== void 0)
2651
+ abool(zip215, "zip215");
2652
+ if (prehash)
2653
+ msg = prehash(msg);
2654
+ const mid = len / 2;
2655
+ const r = sig.subarray(0, mid);
2656
+ const s = bytesToNumberLE(sig.subarray(mid, len));
2657
+ let A, R, SB;
2658
+ try {
2659
+ A = Point2.fromBytes(publicKey, zip215);
2660
+ R = Point2.fromBytes(r, zip215);
2661
+ SB = BASE.multiplyUnsafe(s);
2662
+ } catch (error) {
2663
+ return false;
2664
+ }
2665
+ if (!zip215 && A.isSmallOrder())
2666
+ return false;
2667
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
2668
+ const RkA = R.add(A.multiplyUnsafe(k));
2669
+ return RkA.subtract(SB).clearCofactor().is0();
2670
+ }
2671
+ const _size = Fp.BYTES;
2672
+ const lengths = {
2673
+ secretKey: _size,
2674
+ publicKey: _size,
2675
+ signature: 2 * _size,
2676
+ seed: _size
2677
+ };
2678
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
2679
+ return abytes$1(seed, lengths.seed, "seed");
2680
+ }
2681
+ function isValidSecretKey(key) {
2682
+ return isBytes$1(key) && key.length === Fn.BYTES;
2683
+ }
2684
+ function isValidPublicKey(key, zip215) {
2685
+ try {
2686
+ return !!Point2.fromBytes(key, zip215);
2687
+ } catch (error) {
2688
+ return false;
2689
+ }
2690
+ }
2691
+ const utils2 = {
2692
+ getExtendedPublicKey: getExtendedPublicKey2,
2693
+ randomSecretKey,
2694
+ isValidSecretKey,
2695
+ isValidPublicKey,
2696
+ /**
2697
+ * Converts ed public key to x public key. Uses formula:
2698
+ * - ed25519:
2699
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
2700
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
2701
+ * - ed448:
2702
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
2703
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
2704
+ */
2705
+ toMontgomery(publicKey) {
2706
+ const { y } = Point2.fromBytes(publicKey);
2707
+ const size = lengths.publicKey;
2708
+ const is25519 = size === 32;
2709
+ if (!is25519 && size !== 57)
2710
+ throw new Error("only defined for 25519 and 448");
2711
+ const u = is25519 ? Fp.div(_1n$1 + y, _1n$1 - y) : Fp.div(y - _1n$1, y + _1n$1);
2712
+ return Fp.toBytes(u);
2713
+ },
2714
+ toMontgomerySecret(secretKey) {
2715
+ const size = lengths.secretKey;
2716
+ abytes$1(secretKey, size);
2717
+ const hashed = cHash(secretKey.subarray(0, size));
2718
+ return adjustScalarBytes2(hashed).subarray(0, size);
2719
+ }
2720
+ };
2721
+ return Object.freeze({
2722
+ keygen: createKeygen(randomSecretKey, getPublicKey2),
2723
+ getPublicKey: getPublicKey2,
2724
+ sign,
2725
+ verify,
2726
+ utils: utils2,
2727
+ Point: Point2,
2728
+ lengths
2729
+ });
2730
+ }
2731
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2732
+ const _1n = BigInt(1), _2n = BigInt(2);
2733
+ const _5n = BigInt(5), _8n = BigInt(8);
2734
+ const ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2735
+ const ed25519_CURVE$1 = /* @__PURE__ */ (() => ({
2736
+ p: ed25519_CURVE_p,
2737
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2738
+ h: _8n,
2739
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2740
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2741
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2742
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2743
+ }))();
2744
+ function ed25519_pow_2_252_3(x) {
2745
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2746
+ const P2 = ed25519_CURVE_p;
2747
+ const x2 = x * x % P2;
2748
+ const b2 = x2 * x % P2;
2749
+ const b4 = pow2$1(b2, _2n, P2) * b2 % P2;
2750
+ const b5 = pow2$1(b4, _1n, P2) * x % P2;
2751
+ const b10 = pow2$1(b5, _5n, P2) * b5 % P2;
2752
+ const b20 = pow2$1(b10, _10n, P2) * b10 % P2;
2753
+ const b40 = pow2$1(b20, _20n, P2) * b20 % P2;
2754
+ const b80 = pow2$1(b40, _40n, P2) * b40 % P2;
2755
+ const b160 = pow2$1(b80, _80n, P2) * b80 % P2;
2756
+ const b240 = pow2$1(b160, _80n, P2) * b80 % P2;
2757
+ const b250 = pow2$1(b240, _10n, P2) * b10 % P2;
2758
+ const pow_p_5_8 = pow2$1(b250, _2n, P2) * x % P2;
2759
+ return { pow_p_5_8, b2 };
2760
+ }
2761
+ function adjustScalarBytes(bytes) {
2762
+ bytes[0] &= 248;
2763
+ bytes[31] &= 127;
2764
+ bytes[31] |= 64;
2765
+ return bytes;
2766
+ }
2767
+ const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2768
+ function uvRatio$1(u, v) {
2769
+ const P2 = ed25519_CURVE_p;
2770
+ const v3 = mod(v * v * v, P2);
2771
+ const v7 = mod(v3 * v3 * v, P2);
2772
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2773
+ let x = mod(u * v3 * pow, P2);
2774
+ const vx2 = mod(v * x * x, P2);
2775
+ const root1 = x;
2776
+ const root2 = mod(x * ED25519_SQRT_M1, P2);
2777
+ const useRoot1 = vx2 === u;
2778
+ const useRoot2 = vx2 === mod(-u, P2);
2779
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P2);
2780
+ if (useRoot1)
2781
+ x = root1;
2782
+ if (useRoot2 || noRoot)
2783
+ x = root2;
2784
+ if (isNegativeLE(x, P2))
2785
+ x = mod(-x, P2);
2786
+ return { isValid: useRoot1 || useRoot2, value: x };
2787
+ }
2788
+ const ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE$1, { uvRatio: uvRatio$1 });
2789
+ function ed(opts) {
2790
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
2791
+ }
2792
+ const ed25519 = /* @__PURE__ */ ed({});
1164
2793
  /*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
1165
2794
  const ed25519_CURVE = {
1166
2795
  p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
@@ -1389,7 +3018,7 @@ class Point {
1389
3018
  if (n === 1n)
1390
3019
  return this;
1391
3020
  if (this.equals(G))
1392
- return wNAF(n).p;
3021
+ return wNAF2(n).p;
1393
3022
  let p = I;
1394
3023
  let f = G;
1395
3024
  for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
@@ -1609,7 +3238,7 @@ const ctneg = (cnd, p) => {
1609
3238
  const n = p.negate();
1610
3239
  return cnd ? n : p;
1611
3240
  };
1612
- const wNAF = (n) => {
3241
+ const wNAF2 = (n) => {
1613
3242
  const comp = Gpows || (Gpows = precompute());
1614
3243
  let p = I;
1615
3244
  let f = G;
@@ -2759,6 +4388,24 @@ async function downloadSkills(repoDir, skillDir) {
2759
4388
  await writeFile(join(destDir, "SKILL.md"), content, "utf-8");
2760
4389
  }
2761
4390
  }
4391
+ function buildGhTokenRule(agentName) {
4392
+ return [
4393
+ "# GitHub CLI Authentication (LeGreffier)",
4394
+ "",
4395
+ `When \`GIT_CONFIG_GLOBAL\` is set to \`.moltnet/${agentName}/gitconfig\`,`,
4396
+ "authenticate all `gh` CLI commands as the GitHub App by prefixing them with:",
4397
+ "",
4398
+ "```bash",
4399
+ 'GH_TOKEN=$(moltnet github token --credentials "$(dirname "$GIT_CONFIG_GLOBAL")/moltnet.json") gh <command>',
4400
+ "```",
4401
+ "",
4402
+ "This ensures `gh pr create`, `gh issue create`, etc. use the",
4403
+ "GitHub App's identity instead of the user's personal token.",
4404
+ "",
4405
+ "The token is short-lived (~1 hour) and generated on each invocation.",
4406
+ ""
4407
+ ].join("\n");
4408
+ }
2762
4409
  function buildPermissions(agentName) {
2763
4410
  return [
2764
4411
  // Read-only git commands used by session activation & commit workflow
@@ -2767,8 +4414,12 @@ function buildPermissions(agentName) {
2767
4414
  "Bash(git log *)",
2768
4415
  "Bash(git rev-parse *)",
2769
4416
  "Bash(git worktree list)",
2770
- // Signing CLI
4417
+ // Signing CLI (native binary)
2771
4418
  "Bash(moltnet sign *)",
4419
+ "Bash(moltnet github token *)",
4420
+ // Signing CLI (npm package — equivalent commands)
4421
+ "Bash(npx @themoltnet/cli sign *)",
4422
+ "Bash(npx @themoltnet/cli github token *)",
2772
4423
  // Worktree symlink creation
2773
4424
  "Bash(ln -s *)",
2774
4425
  // All MCP tools for this agent's server
@@ -2857,6 +4508,15 @@ class ClaudeAdapter {
2857
4508
  clientSecret: opts.clientSecret
2858
4509
  });
2859
4510
  }
4511
+ async writeRules(opts) {
4512
+ const dir2 = join(opts.repoDir, ".claude", "rules");
4513
+ await mkdir(dir2, { recursive: true });
4514
+ await writeFile(
4515
+ join(dir2, "legreffier-gh.md"),
4516
+ buildGhTokenRule(opts.agentName),
4517
+ "utf-8"
4518
+ );
4519
+ }
2860
4520
  }
2861
4521
  class CodexAdapter {
2862
4522
  type = "codex";
@@ -2901,6 +4561,15 @@ class CodexAdapter {
2901
4561
  ];
2902
4562
  await writeFile(join(envDir, "env"), lines.join("\n") + "\n", "utf-8");
2903
4563
  }
4564
+ async writeRules(opts) {
4565
+ const dir2 = join(opts.repoDir, ".codex", "rules");
4566
+ await mkdir(dir2, { recursive: true });
4567
+ await writeFile(
4568
+ join(dir2, "legreffier-gh.md"),
4569
+ buildGhTokenRule(opts.agentName),
4570
+ "utf-8"
4571
+ );
4572
+ }
2904
4573
  }
2905
4574
  const adapters = {
2906
4575
  claude: new ClaudeAdapter(),
@@ -3339,7 +5008,7 @@ const cryptoService = {
3339
5008
  * Generate a random challenge for authentication
3340
5009
  */
3341
5010
  generateChallenge() {
3342
- return `moltnet:challenge:${randomBytes$1(32).toString("hex")}:${Date.now()}`;
5011
+ return `moltnet:challenge:${randomBytes$2(32).toString("hex")}:${Date.now()}`;
3343
5012
  },
3344
5013
  /**
3345
5014
  * Derive public key from private key
@@ -3358,6 +5027,24 @@ const cryptoService = {
3358
5027
  const publicKeyBytes = this.parsePublicKey(publicKey);
3359
5028
  return this.generateFingerprint(publicKeyBytes);
3360
5029
  },
5030
+ /**
5031
+ * Derive an X25519 private key from an Ed25519 private key seed.
5032
+ * Uses SHA-512 expansion + clamping per RFC 7748 / RFC 8032.
5033
+ */
5034
+ deriveX25519PrivateKey(ed25519PrivateKeyBase64) {
5035
+ const seed = new Uint8Array(Buffer.from(ed25519PrivateKeyBase64, "base64"));
5036
+ const x25519Priv = ed25519.utils.toMontgomerySecret(seed);
5037
+ return Buffer.from(x25519Priv).toString("base64");
5038
+ },
5039
+ /**
5040
+ * Derive an X25519 public key from an Ed25519 public key.
5041
+ * Uses the Edwards → Montgomery birational map.
5042
+ */
5043
+ deriveX25519PublicKey(ed25519PublicKey) {
5044
+ const edPubBytes = this.parsePublicKey(ed25519PublicKey);
5045
+ const x25519Pub = ed25519.utils.toMontgomery(edPubBytes);
5046
+ return `x25519:${Buffer.from(x25519Pub).toString("base64")}`;
5047
+ },
3361
5048
  /**
3362
5049
  * Create a proof of identity ownership (for DCR metadata)
3363
5050
  */
@@ -4014,6 +5701,8 @@ function SetupApp({
4014
5701
  written.push(`${agentType}: skills`);
4015
5702
  await adapter.writeSettings(opts);
4016
5703
  written.push(`${agentType}: settings`);
5704
+ await adapter.writeRules(opts);
5705
+ written.push(`${agentType}: gh token rule`);
4017
5706
  }
4018
5707
  setFilesWritten(written);
4019
5708
  setSummary({
@@ -4100,6 +5789,19 @@ const name = values["name"];
4100
5789
  const agentFlags = values["agent"] ?? [];
4101
5790
  const apiUrl = values["api-url"] ?? process.env.MOLTNET_API_URL ?? "https://api.themolt.net";
4102
5791
  const dir = values["dir"] ?? process.cwd();
5792
+ if (subcommand === "github" && positionals[1] === "token") {
5793
+ try {
5794
+ const agentName = resolveAgentName(name, process.env.GIT_CONFIG_GLOBAL);
5795
+ printGitHubToken(agentName, dir);
5796
+ process.exit(0);
5797
+ } catch (err2) {
5798
+ process.stderr.write(
5799
+ `Error: ${err2 instanceof Error ? err2.message : String(err2)}
5800
+ `
5801
+ );
5802
+ process.exit(1);
5803
+ }
5804
+ }
4103
5805
  if (!name) {
4104
5806
  const usage = subcommand === "setup" ? "Usage: legreffier setup --name <agent-name> [--agent claude] [--agent codex] [--dir <path>]" : "Usage: legreffier [init] --name <agent-name> [--agent claude] [--agent codex] [--api-url <url>] [--dir <path>]";
4105
5807
  process.stderr.write(usage + "\n");