@linkedclaw/openclaw-plugin 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14,8 +14,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
14
14
  var __esm = (fn, res) => function __init() {
15
15
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
16
  };
17
- var __commonJS = (cb, mod) => function __require2() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ var __commonJS = (cb, mod2) => function __require2() {
18
+ return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
19
19
  };
20
20
  var __export = (target, all) => {
21
21
  for (var name in all)
@@ -29,13 +29,13 @@ var __copyProps = (to, from, except, desc) => {
29
29
  }
30
30
  return to;
31
31
  };
32
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
33
33
  // If the importer is in node compatibility mode or this is not an ESM
34
34
  // file that has been converted to a CommonJS file using a Babel-
35
35
  // compatible transform (i.e. "__esModule" has not been set), then set
36
36
  // "default" to the CommonJS "module.exports" for node compatibility.
37
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
- mod
37
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
38
+ mod2
39
39
  ));
40
40
 
41
41
  // ../../../../linkedclaw/node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js
@@ -65,10 +65,10 @@ var require_constants = __commonJS({
65
65
  var require_buffer_util = __commonJS({
66
66
  "../../../../linkedclaw/node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
67
67
  "use strict";
68
- var { EMPTY_BUFFER } = require_constants();
68
+ var { EMPTY_BUFFER: EMPTY_BUFFER2 } = require_constants();
69
69
  var FastBuffer = Buffer[Symbol.species];
70
- function concat(list, totalLength) {
71
- if (list.length === 0) return EMPTY_BUFFER;
70
+ function concat2(list, totalLength) {
71
+ if (list.length === 0) return EMPTY_BUFFER2;
72
72
  if (list.length === 1) return list[0];
73
73
  const target = Buffer.allocUnsafe(totalLength);
74
74
  let offset = 0;
@@ -113,7 +113,7 @@ var require_buffer_util = __commonJS({
113
113
  return buf;
114
114
  }
115
115
  module.exports = {
116
- concat,
116
+ concat: concat2,
117
117
  mask: _mask,
118
118
  toArrayBuffer,
119
119
  toBuffer,
@@ -778,11 +778,11 @@ var require_receiver = __commonJS({
778
778
  var PerMessageDeflate2 = require_permessage_deflate();
779
779
  var {
780
780
  BINARY_TYPES,
781
- EMPTY_BUFFER,
781
+ EMPTY_BUFFER: EMPTY_BUFFER2,
782
782
  kStatusCode,
783
783
  kWebSocket
784
784
  } = require_constants();
785
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
785
+ var { concat: concat2, toArrayBuffer, unmask } = require_buffer_util();
786
786
  var { isValidStatusCode, isValidUTF8 } = require_validation();
787
787
  var FastBuffer = Buffer[Symbol.species];
788
788
  var GET_INFO = 0;
@@ -1152,7 +1152,7 @@ var require_receiver = __commonJS({
1152
1152
  * @private
1153
1153
  */
1154
1154
  getData(cb) {
1155
- let data = EMPTY_BUFFER;
1155
+ let data = EMPTY_BUFFER2;
1156
1156
  if (this._payloadLength) {
1157
1157
  if (this._bufferedBytes < this._payloadLength) {
1158
1158
  this._loop = false;
@@ -1228,9 +1228,9 @@ var require_receiver = __commonJS({
1228
1228
  if (this._opcode === 2) {
1229
1229
  let data;
1230
1230
  if (this._binaryType === "nodebuffer") {
1231
- data = concat(fragments, messageLength);
1231
+ data = concat2(fragments, messageLength);
1232
1232
  } else if (this._binaryType === "arraybuffer") {
1233
- data = toArrayBuffer(concat(fragments, messageLength));
1233
+ data = toArrayBuffer(concat2(fragments, messageLength));
1234
1234
  } else if (this._binaryType === "blob") {
1235
1235
  data = new Blob(fragments);
1236
1236
  } else {
@@ -1248,7 +1248,7 @@ var require_receiver = __commonJS({
1248
1248
  });
1249
1249
  }
1250
1250
  } else {
1251
- const buf = concat(fragments, messageLength);
1251
+ const buf = concat2(fragments, messageLength);
1252
1252
  if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1253
1253
  const error = this.createError(
1254
1254
  Error,
@@ -1284,7 +1284,7 @@ var require_receiver = __commonJS({
1284
1284
  if (this._opcode === 8) {
1285
1285
  if (data.length === 0) {
1286
1286
  this._loop = false;
1287
- this.emit("conclude", 1005, EMPTY_BUFFER);
1287
+ this.emit("conclude", 1005, EMPTY_BUFFER2);
1288
1288
  this.end();
1289
1289
  } else {
1290
1290
  const code = data.readUInt16BE(0);
@@ -1369,7 +1369,7 @@ var require_sender = __commonJS({
1369
1369
  var { Duplex } = __require("stream");
1370
1370
  var { randomFillSync } = __require("crypto");
1371
1371
  var PerMessageDeflate2 = require_permessage_deflate();
1372
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1372
+ var { EMPTY_BUFFER: EMPTY_BUFFER2, kWebSocket, NOOP } = require_constants();
1373
1373
  var { isBlob, isValidStatusCode } = require_validation();
1374
1374
  var { mask: applyMask, toBuffer } = require_buffer_util();
1375
1375
  var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
@@ -1506,7 +1506,7 @@ var require_sender = __commonJS({
1506
1506
  close(code, data, mask, cb) {
1507
1507
  let buf;
1508
1508
  if (code === void 0) {
1509
- buf = EMPTY_BUFFER;
1509
+ buf = EMPTY_BUFFER2;
1510
1510
  } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1511
1511
  throw new TypeError("First argument must be a valid error code number");
1512
1512
  } else if (data === void 0 || !data.length) {
@@ -2241,7 +2241,7 @@ var require_websocket = __commonJS({
2241
2241
  var http = __require("http");
2242
2242
  var net = __require("net");
2243
2243
  var tls = __require("tls");
2244
- var { randomBytes, createHash } = __require("crypto");
2244
+ var { randomBytes: randomBytes4, createHash } = __require("crypto");
2245
2245
  var { Duplex, Readable } = __require("stream");
2246
2246
  var { URL: URL2 } = __require("url");
2247
2247
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2251,7 +2251,7 @@ var require_websocket = __commonJS({
2251
2251
  var {
2252
2252
  BINARY_TYPES,
2253
2253
  CLOSE_TIMEOUT,
2254
- EMPTY_BUFFER,
2254
+ EMPTY_BUFFER: EMPTY_BUFFER2,
2255
2255
  GUID,
2256
2256
  kForOnEventAttribute,
2257
2257
  kListener,
@@ -2282,7 +2282,7 @@ var require_websocket = __commonJS({
2282
2282
  this._closeCode = 1006;
2283
2283
  this._closeFrameReceived = false;
2284
2284
  this._closeFrameSent = false;
2285
- this._closeMessage = EMPTY_BUFFER;
2285
+ this._closeMessage = EMPTY_BUFFER2;
2286
2286
  this._closeTimer = null;
2287
2287
  this._errorEmitted = false;
2288
2288
  this._extensions = {};
@@ -2539,7 +2539,7 @@ var require_websocket = __commonJS({
2539
2539
  return;
2540
2540
  }
2541
2541
  if (mask === void 0) mask = !this._isServer;
2542
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2542
+ this._sender.ping(data || EMPTY_BUFFER2, mask, cb);
2543
2543
  }
2544
2544
  /**
2545
2545
  * Send a pong.
@@ -2566,7 +2566,7 @@ var require_websocket = __commonJS({
2566
2566
  return;
2567
2567
  }
2568
2568
  if (mask === void 0) mask = !this._isServer;
2569
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2569
+ this._sender.pong(data || EMPTY_BUFFER2, mask, cb);
2570
2570
  }
2571
2571
  /**
2572
2572
  * Resume the socket.
@@ -2618,7 +2618,7 @@ var require_websocket = __commonJS({
2618
2618
  if (!this._extensions[PerMessageDeflate2.extensionName]) {
2619
2619
  opts.compress = false;
2620
2620
  }
2621
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2621
+ this._sender.send(data || EMPTY_BUFFER2, opts, cb);
2622
2622
  }
2623
2623
  /**
2624
2624
  * Forcibly close the connection.
@@ -2771,7 +2771,7 @@ var require_websocket = __commonJS({
2771
2771
  }
2772
2772
  }
2773
2773
  const defaultPort = isSecure ? 443 : 80;
2774
- const key = randomBytes(16).toString("base64");
2774
+ const key = randomBytes4(16).toString("base64");
2775
2775
  const request = isSecure ? https.request : http.request;
2776
2776
  const protocolSet = /* @__PURE__ */ new Set();
2777
2777
  let perMessageDeflate;
@@ -8049,6 +8049,23 @@ var AttributionEdgeListSchema = external_exports.object({
8049
8049
  edges: external_exports.array(AttributionEdgeSchema),
8050
8050
  capped: external_exports.boolean()
8051
8051
  }).passthrough();
8052
+ var KeyTransparencyEntrySchema = external_exports.object({
8053
+ seq: external_exports.number().int().nullable().optional(),
8054
+ agent_id: external_exports.string(),
8055
+ key_id: external_exports.string(),
8056
+ x25519_public_key: external_exports.string(),
8057
+ ed25519_handshake_key: external_exports.string(),
8058
+ expires_at: external_exports.string(),
8059
+ prev_hash: external_exports.string(),
8060
+ entry_hash: external_exports.string(),
8061
+ observed_at: external_exports.string()
8062
+ }).passthrough();
8063
+ var KeyTransparencyLogSchema = external_exports.object({
8064
+ agent_id: external_exports.string(),
8065
+ genesis_hash: external_exports.string(),
8066
+ head_hash: external_exports.string(),
8067
+ entries: external_exports.array(KeyTransparencyEntrySchema)
8068
+ }).passthrough();
8052
8069
 
8053
8070
  // ../../../../linkedclaw/sdk/provider-ts/dist/client.js
8054
8071
  var VALID_FORK_POLICIES = ["self_only", "licensed", "open"];
@@ -8114,6 +8131,10 @@ var ProviderClient = class {
8114
8131
  }
8115
8132
  return RegisterResponseSchema.parse(await res.json());
8116
8133
  }
8134
+ /** @implements POST /api/v1/me/handshake-key */
8135
+ async publishHandshakeKey(params) {
8136
+ return this.request("/api/v1/me/handshake-key", { method: "POST", body: JSON.stringify(params) }, external_exports.record(external_exports.unknown()));
8137
+ }
8117
8138
  // ───────── Resolve / Handles ─────────
8118
8139
  /** @implements GET /api/v1/resolve/{handle} */
8119
8140
  async resolveHandle(handle2) {
@@ -8134,7 +8155,8 @@ var ProviderClient = class {
8134
8155
  capability: options?.capability,
8135
8156
  owner: options?.owner,
8136
8157
  status: options?.status,
8137
- sort: options?.sort
8158
+ sort: options?.sort,
8159
+ rank: options?.rank
8138
8160
  })}`, { method: "GET" }, external_exports.array(AgentSchema));
8139
8161
  }
8140
8162
  /** @implements GET /api/v1/agents/{agent_id} */
@@ -8143,7 +8165,7 @@ var ProviderClient = class {
8143
8165
  }
8144
8166
  /** @implements POST /api/v1/agents */
8145
8167
  async createAgent(params) {
8146
- const { slug, name, capabilities, description, forkPolicy, capabilitiesMeta, status, slotFulfillment } = params;
8168
+ const { slug, name, capabilities, description, forkPolicy, capabilitiesMeta, status, slotFulfillment, encryptionKey } = params;
8147
8169
  if (forkPolicy !== void 0 && !VALID_FORK_POLICIES.includes(forkPolicy)) {
8148
8170
  throw new Error(`forkPolicy must be one of ${VALID_FORK_POLICIES.join(", ")}, got ${JSON.stringify(forkPolicy)}`);
8149
8171
  }
@@ -8162,6 +8184,8 @@ var ProviderClient = class {
8162
8184
  body.capabilities_meta = capabilitiesMeta;
8163
8185
  if (slotFulfillment !== void 0 && slotFulfillment.length > 0)
8164
8186
  body.slot_fulfillment = [...new Set(slotFulfillment)];
8187
+ if (encryptionKey !== void 0)
8188
+ body.encryption_key = encryptionKey;
8165
8189
  return this.request("/api/v1/agents", { method: "POST", body: JSON.stringify(body) }, AgentSchema);
8166
8190
  }
8167
8191
  /** @implements PUT /api/v1/agents/{agent_id} */
@@ -8388,6 +8412,14 @@ var ProviderClient = class {
8388
8412
  throw new Error(`LinkedClaw /.well-known/agent-signing-key.json ${res.status}`);
8389
8413
  return res.json();
8390
8414
  }
8415
+ /** @implements GET /.well-known/key-transparency.json */
8416
+ async keyTransparencyLog(agentId) {
8417
+ const url = `${this.baseUrl}/.well-known/key-transparency.json?agent_id=${encodeURIComponent(agentId)}`;
8418
+ const res = await this.fetchImpl(url, { method: "GET" });
8419
+ if (!res.ok)
8420
+ throw new Error(`LinkedClaw /.well-known/key-transparency.json ${res.status}`);
8421
+ return KeyTransparencyLogSchema.parse(await res.json());
8422
+ }
8391
8423
  /** @implements GET /metrics */
8392
8424
  async metrics() {
8393
8425
  const res = await this.fetchImpl(`${this.baseUrl}/metrics`, { method: "GET" });
@@ -8429,7 +8461,9 @@ function parseInbound(frame) {
8429
8461
  session_id: str(frame, "session_id"),
8430
8462
  requester_id: strOrEmpty(frame, "requester_id"),
8431
8463
  capability: strOrEmpty(frame, "capability"),
8432
- ...frame.scope !== void 0 ? { scope: frame.scope } : {}
8464
+ ...frame.scope !== void 0 ? { scope: frame.scope } : {},
8465
+ ...typeof frame.eph_enc_pub === "string" ? { eph_enc_pub: frame.eph_enc_pub } : {},
8466
+ ...typeof frame.eph_enc_sig === "string" ? { eph_enc_sig: frame.eph_enc_sig } : {}
8433
8467
  };
8434
8468
  case MessageType.SESSION_MESSAGE:
8435
8469
  return {
@@ -8454,7 +8488,11 @@ function parseInbound(frame) {
8454
8488
  ...typeof frame.manifest_id === "string" ? { manifest_id: frame.manifest_id } : {},
8455
8489
  ...frame.manifest !== void 0 && frame.manifest !== null ? { manifest: frame.manifest } : {},
8456
8490
  ...typeof frame.requester_id === "string" ? { requester_id: frame.requester_id } : {},
8457
- ...typeof frame.timeout_seconds === "number" ? { timeout_seconds: frame.timeout_seconds } : {}
8491
+ ...typeof frame.timeout_seconds === "number" ? { timeout_seconds: frame.timeout_seconds } : {},
8492
+ ...typeof frame.eph_sender_pub === "string" ? { eph_sender_pub: frame.eph_sender_pub } : {},
8493
+ ...typeof frame.eph_sender_sig === "string" ? { eph_sender_sig: frame.eph_sender_sig } : {},
8494
+ ...typeof frame.nonce === "string" ? { nonce: frame.nonce } : {},
8495
+ ...typeof frame.ciphertext === "string" ? { ciphertext: frame.ciphertext } : {}
8458
8496
  };
8459
8497
  case MessageType.GIG_TASK: {
8460
8498
  return {
@@ -8491,6 +8529,3430 @@ var DEFAULT_RELAY_URL = "wss://api.linkedclaw.com/ws";
8491
8529
 
8492
8530
  // ../../../../linkedclaw/sdk/provider-runtime-ts/dist/index.js
8493
8531
  import { EventEmitter } from "events";
8532
+ import { randomBytes as randomBytes3 } from "crypto";
8533
+ import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, openSync as openSync2, renameSync as renameSync2, writeSync as writeSync2 } from "fs";
8534
+ import { dirname as dirname2, join as join2 } from "path";
8535
+
8536
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js
8537
+ import * as nc from "crypto";
8538
+ var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
8539
+
8540
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
8541
+ function isBytes(a) {
8542
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
8543
+ }
8544
+ function anumber(n) {
8545
+ if (!Number.isSafeInteger(n) || n < 0)
8546
+ throw new Error("positive integer expected, got " + n);
8547
+ }
8548
+ function abytes(b, ...lengths) {
8549
+ if (!isBytes(b))
8550
+ throw new Error("Uint8Array expected");
8551
+ if (lengths.length > 0 && !lengths.includes(b.length))
8552
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
8553
+ }
8554
+ function ahash(h) {
8555
+ if (typeof h !== "function" || typeof h.create !== "function")
8556
+ throw new Error("Hash should be wrapped by utils.createHasher");
8557
+ anumber(h.outputLen);
8558
+ anumber(h.blockLen);
8559
+ }
8560
+ function aexists(instance, checkFinished = true) {
8561
+ if (instance.destroyed)
8562
+ throw new Error("Hash instance has been destroyed");
8563
+ if (checkFinished && instance.finished)
8564
+ throw new Error("Hash#digest() has already been called");
8565
+ }
8566
+ function aoutput(out, instance) {
8567
+ abytes(out);
8568
+ const min = instance.outputLen;
8569
+ if (out.length < min) {
8570
+ throw new Error("digestInto() expects output buffer of length at least " + min);
8571
+ }
8572
+ }
8573
+ function clean(...arrays) {
8574
+ for (let i = 0; i < arrays.length; i++) {
8575
+ arrays[i].fill(0);
8576
+ }
8577
+ }
8578
+ function createView(arr) {
8579
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
8580
+ }
8581
+ function rotr(word, shift) {
8582
+ return word << 32 - shift | word >>> shift;
8583
+ }
8584
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
8585
+ // @ts-ignore
8586
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
8587
+ ))();
8588
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
8589
+ function bytesToHex(bytes) {
8590
+ abytes(bytes);
8591
+ if (hasHexBuiltin)
8592
+ return bytes.toHex();
8593
+ let hex = "";
8594
+ for (let i = 0; i < bytes.length; i++) {
8595
+ hex += hexes[bytes[i]];
8596
+ }
8597
+ return hex;
8598
+ }
8599
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
8600
+ function asciiToBase16(ch) {
8601
+ if (ch >= asciis._0 && ch <= asciis._9)
8602
+ return ch - asciis._0;
8603
+ if (ch >= asciis.A && ch <= asciis.F)
8604
+ return ch - (asciis.A - 10);
8605
+ if (ch >= asciis.a && ch <= asciis.f)
8606
+ return ch - (asciis.a - 10);
8607
+ return;
8608
+ }
8609
+ function hexToBytes(hex) {
8610
+ if (typeof hex !== "string")
8611
+ throw new Error("hex string expected, got " + typeof hex);
8612
+ if (hasHexBuiltin)
8613
+ return Uint8Array.fromHex(hex);
8614
+ const hl = hex.length;
8615
+ const al = hl / 2;
8616
+ if (hl % 2)
8617
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
8618
+ const array = new Uint8Array(al);
8619
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
8620
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
8621
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
8622
+ if (n1 === void 0 || n2 === void 0) {
8623
+ const char = hex[hi] + hex[hi + 1];
8624
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
8625
+ }
8626
+ array[ai] = n1 * 16 + n2;
8627
+ }
8628
+ return array;
8629
+ }
8630
+ function utf8ToBytes(str2) {
8631
+ if (typeof str2 !== "string")
8632
+ throw new Error("string expected");
8633
+ return new Uint8Array(new TextEncoder().encode(str2));
8634
+ }
8635
+ function toBytes(data) {
8636
+ if (typeof data === "string")
8637
+ data = utf8ToBytes(data);
8638
+ abytes(data);
8639
+ return data;
8640
+ }
8641
+ function concatBytes(...arrays) {
8642
+ let sum = 0;
8643
+ for (let i = 0; i < arrays.length; i++) {
8644
+ const a = arrays[i];
8645
+ abytes(a);
8646
+ sum += a.length;
8647
+ }
8648
+ const res = new Uint8Array(sum);
8649
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
8650
+ const a = arrays[i];
8651
+ res.set(a, pad);
8652
+ pad += a.length;
8653
+ }
8654
+ return res;
8655
+ }
8656
+ var Hash = class {
8657
+ };
8658
+ function createHasher(hashCons) {
8659
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
8660
+ const tmp = hashCons();
8661
+ hashC.outputLen = tmp.outputLen;
8662
+ hashC.blockLen = tmp.blockLen;
8663
+ hashC.create = () => hashCons();
8664
+ return hashC;
8665
+ }
8666
+ function randomBytes(bytesLength = 32) {
8667
+ if (crypto2 && typeof crypto2.getRandomValues === "function") {
8668
+ return crypto2.getRandomValues(new Uint8Array(bytesLength));
8669
+ }
8670
+ if (crypto2 && typeof crypto2.randomBytes === "function") {
8671
+ return Uint8Array.from(crypto2.randomBytes(bytesLength));
8672
+ }
8673
+ throw new Error("crypto.getRandomValues must be defined");
8674
+ }
8675
+
8676
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
8677
+ function setBigUint64(view, byteOffset, value, isLE2) {
8678
+ if (typeof view.setBigUint64 === "function")
8679
+ return view.setBigUint64(byteOffset, value, isLE2);
8680
+ const _32n2 = BigInt(32);
8681
+ const _u32_max = BigInt(4294967295);
8682
+ const wh = Number(value >> _32n2 & _u32_max);
8683
+ const wl = Number(value & _u32_max);
8684
+ const h = isLE2 ? 4 : 0;
8685
+ const l = isLE2 ? 0 : 4;
8686
+ view.setUint32(byteOffset + h, wh, isLE2);
8687
+ view.setUint32(byteOffset + l, wl, isLE2);
8688
+ }
8689
+ function Chi(a, b, c) {
8690
+ return a & b ^ ~a & c;
8691
+ }
8692
+ function Maj(a, b, c) {
8693
+ return a & b ^ a & c ^ b & c;
8694
+ }
8695
+ var HashMD = class extends Hash {
8696
+ constructor(blockLen, outputLen, padOffset, isLE2) {
8697
+ super();
8698
+ this.finished = false;
8699
+ this.length = 0;
8700
+ this.pos = 0;
8701
+ this.destroyed = false;
8702
+ this.blockLen = blockLen;
8703
+ this.outputLen = outputLen;
8704
+ this.padOffset = padOffset;
8705
+ this.isLE = isLE2;
8706
+ this.buffer = new Uint8Array(blockLen);
8707
+ this.view = createView(this.buffer);
8708
+ }
8709
+ update(data) {
8710
+ aexists(this);
8711
+ data = toBytes(data);
8712
+ abytes(data);
8713
+ const { view, buffer, blockLen } = this;
8714
+ const len = data.length;
8715
+ for (let pos = 0; pos < len; ) {
8716
+ const take = Math.min(blockLen - this.pos, len - pos);
8717
+ if (take === blockLen) {
8718
+ const dataView = createView(data);
8719
+ for (; blockLen <= len - pos; pos += blockLen)
8720
+ this.process(dataView, pos);
8721
+ continue;
8722
+ }
8723
+ buffer.set(data.subarray(pos, pos + take), this.pos);
8724
+ this.pos += take;
8725
+ pos += take;
8726
+ if (this.pos === blockLen) {
8727
+ this.process(view, 0);
8728
+ this.pos = 0;
8729
+ }
8730
+ }
8731
+ this.length += data.length;
8732
+ this.roundClean();
8733
+ return this;
8734
+ }
8735
+ digestInto(out) {
8736
+ aexists(this);
8737
+ aoutput(out, this);
8738
+ this.finished = true;
8739
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
8740
+ let { pos } = this;
8741
+ buffer[pos++] = 128;
8742
+ clean(this.buffer.subarray(pos));
8743
+ if (this.padOffset > blockLen - pos) {
8744
+ this.process(view, 0);
8745
+ pos = 0;
8746
+ }
8747
+ for (let i = pos; i < blockLen; i++)
8748
+ buffer[i] = 0;
8749
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
8750
+ this.process(view, 0);
8751
+ const oview = createView(out);
8752
+ const len = this.outputLen;
8753
+ if (len % 4)
8754
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
8755
+ const outLen = len / 4;
8756
+ const state = this.get();
8757
+ if (outLen > state.length)
8758
+ throw new Error("_sha2: outputLen bigger than state");
8759
+ for (let i = 0; i < outLen; i++)
8760
+ oview.setUint32(4 * i, state[i], isLE2);
8761
+ }
8762
+ digest() {
8763
+ const { buffer, outputLen } = this;
8764
+ this.digestInto(buffer);
8765
+ const res = buffer.slice(0, outputLen);
8766
+ this.destroy();
8767
+ return res;
8768
+ }
8769
+ _cloneInto(to) {
8770
+ to || (to = new this.constructor());
8771
+ to.set(...this.get());
8772
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
8773
+ to.destroyed = destroyed;
8774
+ to.finished = finished;
8775
+ to.length = length;
8776
+ to.pos = pos;
8777
+ if (length % blockLen)
8778
+ to.buffer.set(buffer);
8779
+ return to;
8780
+ }
8781
+ clone() {
8782
+ return this._cloneInto();
8783
+ }
8784
+ };
8785
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
8786
+ 1779033703,
8787
+ 3144134277,
8788
+ 1013904242,
8789
+ 2773480762,
8790
+ 1359893119,
8791
+ 2600822924,
8792
+ 528734635,
8793
+ 1541459225
8794
+ ]);
8795
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
8796
+ 1779033703,
8797
+ 4089235720,
8798
+ 3144134277,
8799
+ 2227873595,
8800
+ 1013904242,
8801
+ 4271175723,
8802
+ 2773480762,
8803
+ 1595750129,
8804
+ 1359893119,
8805
+ 2917565137,
8806
+ 2600822924,
8807
+ 725511199,
8808
+ 528734635,
8809
+ 4215389547,
8810
+ 1541459225,
8811
+ 327033209
8812
+ ]);
8813
+
8814
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js
8815
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
8816
+ var _32n = /* @__PURE__ */ BigInt(32);
8817
+ function fromBig(n, le = false) {
8818
+ if (le)
8819
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
8820
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
8821
+ }
8822
+ function split(lst, le = false) {
8823
+ const len = lst.length;
8824
+ let Ah = new Uint32Array(len);
8825
+ let Al = new Uint32Array(len);
8826
+ for (let i = 0; i < len; i++) {
8827
+ const { h, l } = fromBig(lst[i], le);
8828
+ [Ah[i], Al[i]] = [h, l];
8829
+ }
8830
+ return [Ah, Al];
8831
+ }
8832
+ var shrSH = (h, _l, s) => h >>> s;
8833
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
8834
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
8835
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
8836
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
8837
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
8838
+ function add(Ah, Al, Bh, Bl) {
8839
+ const l = (Al >>> 0) + (Bl >>> 0);
8840
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
8841
+ }
8842
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
8843
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
8844
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
8845
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
8846
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
8847
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
8848
+
8849
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
8850
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
8851
+ 1116352408,
8852
+ 1899447441,
8853
+ 3049323471,
8854
+ 3921009573,
8855
+ 961987163,
8856
+ 1508970993,
8857
+ 2453635748,
8858
+ 2870763221,
8859
+ 3624381080,
8860
+ 310598401,
8861
+ 607225278,
8862
+ 1426881987,
8863
+ 1925078388,
8864
+ 2162078206,
8865
+ 2614888103,
8866
+ 3248222580,
8867
+ 3835390401,
8868
+ 4022224774,
8869
+ 264347078,
8870
+ 604807628,
8871
+ 770255983,
8872
+ 1249150122,
8873
+ 1555081692,
8874
+ 1996064986,
8875
+ 2554220882,
8876
+ 2821834349,
8877
+ 2952996808,
8878
+ 3210313671,
8879
+ 3336571891,
8880
+ 3584528711,
8881
+ 113926993,
8882
+ 338241895,
8883
+ 666307205,
8884
+ 773529912,
8885
+ 1294757372,
8886
+ 1396182291,
8887
+ 1695183700,
8888
+ 1986661051,
8889
+ 2177026350,
8890
+ 2456956037,
8891
+ 2730485921,
8892
+ 2820302411,
8893
+ 3259730800,
8894
+ 3345764771,
8895
+ 3516065817,
8896
+ 3600352804,
8897
+ 4094571909,
8898
+ 275423344,
8899
+ 430227734,
8900
+ 506948616,
8901
+ 659060556,
8902
+ 883997877,
8903
+ 958139571,
8904
+ 1322822218,
8905
+ 1537002063,
8906
+ 1747873779,
8907
+ 1955562222,
8908
+ 2024104815,
8909
+ 2227730452,
8910
+ 2361852424,
8911
+ 2428436474,
8912
+ 2756734187,
8913
+ 3204031479,
8914
+ 3329325298
8915
+ ]);
8916
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
8917
+ var SHA256 = class extends HashMD {
8918
+ constructor(outputLen = 32) {
8919
+ super(64, outputLen, 8, false);
8920
+ this.A = SHA256_IV[0] | 0;
8921
+ this.B = SHA256_IV[1] | 0;
8922
+ this.C = SHA256_IV[2] | 0;
8923
+ this.D = SHA256_IV[3] | 0;
8924
+ this.E = SHA256_IV[4] | 0;
8925
+ this.F = SHA256_IV[5] | 0;
8926
+ this.G = SHA256_IV[6] | 0;
8927
+ this.H = SHA256_IV[7] | 0;
8928
+ }
8929
+ get() {
8930
+ const { A, B, C, D, E, F, G, H } = this;
8931
+ return [A, B, C, D, E, F, G, H];
8932
+ }
8933
+ // prettier-ignore
8934
+ set(A, B, C, D, E, F, G, H) {
8935
+ this.A = A | 0;
8936
+ this.B = B | 0;
8937
+ this.C = C | 0;
8938
+ this.D = D | 0;
8939
+ this.E = E | 0;
8940
+ this.F = F | 0;
8941
+ this.G = G | 0;
8942
+ this.H = H | 0;
8943
+ }
8944
+ process(view, offset) {
8945
+ for (let i = 0; i < 16; i++, offset += 4)
8946
+ SHA256_W[i] = view.getUint32(offset, false);
8947
+ for (let i = 16; i < 64; i++) {
8948
+ const W15 = SHA256_W[i - 15];
8949
+ const W2 = SHA256_W[i - 2];
8950
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
8951
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
8952
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
8953
+ }
8954
+ let { A, B, C, D, E, F, G, H } = this;
8955
+ for (let i = 0; i < 64; i++) {
8956
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
8957
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
8958
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
8959
+ const T2 = sigma0 + Maj(A, B, C) | 0;
8960
+ H = G;
8961
+ G = F;
8962
+ F = E;
8963
+ E = D + T1 | 0;
8964
+ D = C;
8965
+ C = B;
8966
+ B = A;
8967
+ A = T1 + T2 | 0;
8968
+ }
8969
+ A = A + this.A | 0;
8970
+ B = B + this.B | 0;
8971
+ C = C + this.C | 0;
8972
+ D = D + this.D | 0;
8973
+ E = E + this.E | 0;
8974
+ F = F + this.F | 0;
8975
+ G = G + this.G | 0;
8976
+ H = H + this.H | 0;
8977
+ this.set(A, B, C, D, E, F, G, H);
8978
+ }
8979
+ roundClean() {
8980
+ clean(SHA256_W);
8981
+ }
8982
+ destroy() {
8983
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
8984
+ clean(this.buffer);
8985
+ }
8986
+ };
8987
+ var K512 = /* @__PURE__ */ (() => split([
8988
+ "0x428a2f98d728ae22",
8989
+ "0x7137449123ef65cd",
8990
+ "0xb5c0fbcfec4d3b2f",
8991
+ "0xe9b5dba58189dbbc",
8992
+ "0x3956c25bf348b538",
8993
+ "0x59f111f1b605d019",
8994
+ "0x923f82a4af194f9b",
8995
+ "0xab1c5ed5da6d8118",
8996
+ "0xd807aa98a3030242",
8997
+ "0x12835b0145706fbe",
8998
+ "0x243185be4ee4b28c",
8999
+ "0x550c7dc3d5ffb4e2",
9000
+ "0x72be5d74f27b896f",
9001
+ "0x80deb1fe3b1696b1",
9002
+ "0x9bdc06a725c71235",
9003
+ "0xc19bf174cf692694",
9004
+ "0xe49b69c19ef14ad2",
9005
+ "0xefbe4786384f25e3",
9006
+ "0x0fc19dc68b8cd5b5",
9007
+ "0x240ca1cc77ac9c65",
9008
+ "0x2de92c6f592b0275",
9009
+ "0x4a7484aa6ea6e483",
9010
+ "0x5cb0a9dcbd41fbd4",
9011
+ "0x76f988da831153b5",
9012
+ "0x983e5152ee66dfab",
9013
+ "0xa831c66d2db43210",
9014
+ "0xb00327c898fb213f",
9015
+ "0xbf597fc7beef0ee4",
9016
+ "0xc6e00bf33da88fc2",
9017
+ "0xd5a79147930aa725",
9018
+ "0x06ca6351e003826f",
9019
+ "0x142929670a0e6e70",
9020
+ "0x27b70a8546d22ffc",
9021
+ "0x2e1b21385c26c926",
9022
+ "0x4d2c6dfc5ac42aed",
9023
+ "0x53380d139d95b3df",
9024
+ "0x650a73548baf63de",
9025
+ "0x766a0abb3c77b2a8",
9026
+ "0x81c2c92e47edaee6",
9027
+ "0x92722c851482353b",
9028
+ "0xa2bfe8a14cf10364",
9029
+ "0xa81a664bbc423001",
9030
+ "0xc24b8b70d0f89791",
9031
+ "0xc76c51a30654be30",
9032
+ "0xd192e819d6ef5218",
9033
+ "0xd69906245565a910",
9034
+ "0xf40e35855771202a",
9035
+ "0x106aa07032bbd1b8",
9036
+ "0x19a4c116b8d2d0c8",
9037
+ "0x1e376c085141ab53",
9038
+ "0x2748774cdf8eeb99",
9039
+ "0x34b0bcb5e19b48a8",
9040
+ "0x391c0cb3c5c95a63",
9041
+ "0x4ed8aa4ae3418acb",
9042
+ "0x5b9cca4f7763e373",
9043
+ "0x682e6ff3d6b2b8a3",
9044
+ "0x748f82ee5defb2fc",
9045
+ "0x78a5636f43172f60",
9046
+ "0x84c87814a1f0ab72",
9047
+ "0x8cc702081a6439ec",
9048
+ "0x90befffa23631e28",
9049
+ "0xa4506cebde82bde9",
9050
+ "0xbef9a3f7b2c67915",
9051
+ "0xc67178f2e372532b",
9052
+ "0xca273eceea26619c",
9053
+ "0xd186b8c721c0c207",
9054
+ "0xeada7dd6cde0eb1e",
9055
+ "0xf57d4f7fee6ed178",
9056
+ "0x06f067aa72176fba",
9057
+ "0x0a637dc5a2c898a6",
9058
+ "0x113f9804bef90dae",
9059
+ "0x1b710b35131c471b",
9060
+ "0x28db77f523047d84",
9061
+ "0x32caab7b40c72493",
9062
+ "0x3c9ebe0a15c9bebc",
9063
+ "0x431d67c49c100d4c",
9064
+ "0x4cc5d4becb3e42b6",
9065
+ "0x597f299cfc657e2a",
9066
+ "0x5fcb6fab3ad6faec",
9067
+ "0x6c44198c4a475817"
9068
+ ].map((n) => BigInt(n))))();
9069
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
9070
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
9071
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
9072
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
9073
+ var SHA512 = class extends HashMD {
9074
+ constructor(outputLen = 64) {
9075
+ super(128, outputLen, 16, false);
9076
+ this.Ah = SHA512_IV[0] | 0;
9077
+ this.Al = SHA512_IV[1] | 0;
9078
+ this.Bh = SHA512_IV[2] | 0;
9079
+ this.Bl = SHA512_IV[3] | 0;
9080
+ this.Ch = SHA512_IV[4] | 0;
9081
+ this.Cl = SHA512_IV[5] | 0;
9082
+ this.Dh = SHA512_IV[6] | 0;
9083
+ this.Dl = SHA512_IV[7] | 0;
9084
+ this.Eh = SHA512_IV[8] | 0;
9085
+ this.El = SHA512_IV[9] | 0;
9086
+ this.Fh = SHA512_IV[10] | 0;
9087
+ this.Fl = SHA512_IV[11] | 0;
9088
+ this.Gh = SHA512_IV[12] | 0;
9089
+ this.Gl = SHA512_IV[13] | 0;
9090
+ this.Hh = SHA512_IV[14] | 0;
9091
+ this.Hl = SHA512_IV[15] | 0;
9092
+ }
9093
+ // prettier-ignore
9094
+ get() {
9095
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
9096
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
9097
+ }
9098
+ // prettier-ignore
9099
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
9100
+ this.Ah = Ah | 0;
9101
+ this.Al = Al | 0;
9102
+ this.Bh = Bh | 0;
9103
+ this.Bl = Bl | 0;
9104
+ this.Ch = Ch | 0;
9105
+ this.Cl = Cl | 0;
9106
+ this.Dh = Dh | 0;
9107
+ this.Dl = Dl | 0;
9108
+ this.Eh = Eh | 0;
9109
+ this.El = El | 0;
9110
+ this.Fh = Fh | 0;
9111
+ this.Fl = Fl | 0;
9112
+ this.Gh = Gh | 0;
9113
+ this.Gl = Gl | 0;
9114
+ this.Hh = Hh | 0;
9115
+ this.Hl = Hl | 0;
9116
+ }
9117
+ process(view, offset) {
9118
+ for (let i = 0; i < 16; i++, offset += 4) {
9119
+ SHA512_W_H[i] = view.getUint32(offset);
9120
+ SHA512_W_L[i] = view.getUint32(offset += 4);
9121
+ }
9122
+ for (let i = 16; i < 80; i++) {
9123
+ const W15h = SHA512_W_H[i - 15] | 0;
9124
+ const W15l = SHA512_W_L[i - 15] | 0;
9125
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
9126
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
9127
+ const W2h = SHA512_W_H[i - 2] | 0;
9128
+ const W2l = SHA512_W_L[i - 2] | 0;
9129
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
9130
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
9131
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
9132
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
9133
+ SHA512_W_H[i] = SUMh | 0;
9134
+ SHA512_W_L[i] = SUMl | 0;
9135
+ }
9136
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
9137
+ for (let i = 0; i < 80; i++) {
9138
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
9139
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
9140
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
9141
+ const CHIl = El & Fl ^ ~El & Gl;
9142
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
9143
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
9144
+ const T1l = T1ll | 0;
9145
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
9146
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
9147
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
9148
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
9149
+ Hh = Gh | 0;
9150
+ Hl = Gl | 0;
9151
+ Gh = Fh | 0;
9152
+ Gl = Fl | 0;
9153
+ Fh = Eh | 0;
9154
+ Fl = El | 0;
9155
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
9156
+ Dh = Ch | 0;
9157
+ Dl = Cl | 0;
9158
+ Ch = Bh | 0;
9159
+ Cl = Bl | 0;
9160
+ Bh = Ah | 0;
9161
+ Bl = Al | 0;
9162
+ const All = add3L(T1l, sigma0l, MAJl);
9163
+ Ah = add3H(All, T1h, sigma0h, MAJh);
9164
+ Al = All | 0;
9165
+ }
9166
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
9167
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
9168
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
9169
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
9170
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
9171
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
9172
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
9173
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
9174
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
9175
+ }
9176
+ roundClean() {
9177
+ clean(SHA512_W_H, SHA512_W_L);
9178
+ }
9179
+ destroy() {
9180
+ clean(this.buffer);
9181
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
9182
+ }
9183
+ };
9184
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
9185
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
9186
+
9187
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
9188
+ var _0n = /* @__PURE__ */ BigInt(0);
9189
+ var _1n = /* @__PURE__ */ BigInt(1);
9190
+ function _abool2(value, title = "") {
9191
+ if (typeof value !== "boolean") {
9192
+ const prefix = title && `"${title}"`;
9193
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9194
+ }
9195
+ return value;
9196
+ }
9197
+ function _abytes2(value, length, title = "") {
9198
+ const bytes = isBytes(value);
9199
+ const len = value?.length;
9200
+ const needsLen = length !== void 0;
9201
+ if (!bytes || needsLen && len !== length) {
9202
+ const prefix = title && `"${title}" `;
9203
+ const ofLen = needsLen ? ` of length ${length}` : "";
9204
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9205
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9206
+ }
9207
+ return value;
9208
+ }
9209
+ function hexToNumber(hex) {
9210
+ if (typeof hex !== "string")
9211
+ throw new Error("hex string expected, got " + typeof hex);
9212
+ return hex === "" ? _0n : BigInt("0x" + hex);
9213
+ }
9214
+ function bytesToNumberBE(bytes) {
9215
+ return hexToNumber(bytesToHex(bytes));
9216
+ }
9217
+ function bytesToNumberLE(bytes) {
9218
+ abytes(bytes);
9219
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
9220
+ }
9221
+ function numberToBytesBE(n, len) {
9222
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
9223
+ }
9224
+ function numberToBytesLE(n, len) {
9225
+ return numberToBytesBE(n, len).reverse();
9226
+ }
9227
+ function ensureBytes(title, hex, expectedLength) {
9228
+ let res;
9229
+ if (typeof hex === "string") {
9230
+ try {
9231
+ res = hexToBytes(hex);
9232
+ } catch (e) {
9233
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
9234
+ }
9235
+ } else if (isBytes(hex)) {
9236
+ res = Uint8Array.from(hex);
9237
+ } else {
9238
+ throw new Error(title + " must be hex string or Uint8Array");
9239
+ }
9240
+ const len = res.length;
9241
+ if (typeof expectedLength === "number" && len !== expectedLength)
9242
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
9243
+ return res;
9244
+ }
9245
+ function equalBytes(a, b) {
9246
+ if (a.length !== b.length)
9247
+ return false;
9248
+ let diff = 0;
9249
+ for (let i = 0; i < a.length; i++)
9250
+ diff |= a[i] ^ b[i];
9251
+ return diff === 0;
9252
+ }
9253
+ function copyBytes(bytes) {
9254
+ return Uint8Array.from(bytes);
9255
+ }
9256
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9257
+ function inRange(n, min, max) {
9258
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9259
+ }
9260
+ function aInRange(title, n, min, max) {
9261
+ if (!inRange(n, min, max))
9262
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9263
+ }
9264
+ function bitLen(n) {
9265
+ let len;
9266
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9267
+ ;
9268
+ return len;
9269
+ }
9270
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9271
+ function _validateObject(object, fields, optFields = {}) {
9272
+ if (!object || typeof object !== "object")
9273
+ throw new Error("expected valid options object");
9274
+ function checkField(fieldName, expectedType, isOpt) {
9275
+ const val = object[fieldName];
9276
+ if (isOpt && val === void 0)
9277
+ return;
9278
+ const current = typeof val;
9279
+ if (current !== expectedType || val === null)
9280
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9281
+ }
9282
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
9283
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
9284
+ }
9285
+ var notImplemented = () => {
9286
+ throw new Error("not implemented");
9287
+ };
9288
+ function memoized(fn) {
9289
+ const map = /* @__PURE__ */ new WeakMap();
9290
+ return (arg, ...args) => {
9291
+ const val = map.get(arg);
9292
+ if (val !== void 0)
9293
+ return val;
9294
+ const computed = fn(arg, ...args);
9295
+ map.set(arg, computed);
9296
+ return computed;
9297
+ };
9298
+ }
9299
+
9300
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
9301
+ var _0n2 = BigInt(0);
9302
+ var _1n2 = BigInt(1);
9303
+ var _2n = /* @__PURE__ */ BigInt(2);
9304
+ var _3n = /* @__PURE__ */ BigInt(3);
9305
+ var _4n = /* @__PURE__ */ BigInt(4);
9306
+ var _5n = /* @__PURE__ */ BigInt(5);
9307
+ var _7n = /* @__PURE__ */ BigInt(7);
9308
+ var _8n = /* @__PURE__ */ BigInt(8);
9309
+ var _9n = /* @__PURE__ */ BigInt(9);
9310
+ var _16n = /* @__PURE__ */ BigInt(16);
9311
+ function mod(a, b) {
9312
+ const result = a % b;
9313
+ return result >= _0n2 ? result : b + result;
9314
+ }
9315
+ function pow2(x, power, modulo) {
9316
+ let res = x;
9317
+ while (power-- > _0n2) {
9318
+ res *= res;
9319
+ res %= modulo;
9320
+ }
9321
+ return res;
9322
+ }
9323
+ function invert(number, modulo) {
9324
+ if (number === _0n2)
9325
+ throw new Error("invert: expected non-zero number");
9326
+ if (modulo <= _0n2)
9327
+ throw new Error("invert: expected positive modulus, got " + modulo);
9328
+ let a = mod(number, modulo);
9329
+ let b = modulo;
9330
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9331
+ while (a !== _0n2) {
9332
+ const q = b / a;
9333
+ const r = b % a;
9334
+ const m = x - u * q;
9335
+ const n = y - v * q;
9336
+ b = a, a = r, x = u, y = v, u = m, v = n;
9337
+ }
9338
+ const gcd = b;
9339
+ if (gcd !== _1n2)
9340
+ throw new Error("invert: does not exist");
9341
+ return mod(x, modulo);
9342
+ }
9343
+ function assertIsSquare(Fp2, root, n) {
9344
+ if (!Fp2.eql(Fp2.sqr(root), n))
9345
+ throw new Error("Cannot find square root");
9346
+ }
9347
+ function sqrt3mod4(Fp2, n) {
9348
+ const p1div4 = (Fp2.ORDER + _1n2) / _4n;
9349
+ const root = Fp2.pow(n, p1div4);
9350
+ assertIsSquare(Fp2, root, n);
9351
+ return root;
9352
+ }
9353
+ function sqrt5mod8(Fp2, n) {
9354
+ const p5div8 = (Fp2.ORDER - _5n) / _8n;
9355
+ const n2 = Fp2.mul(n, _2n);
9356
+ const v = Fp2.pow(n2, p5div8);
9357
+ const nv = Fp2.mul(n, v);
9358
+ const i = Fp2.mul(Fp2.mul(nv, _2n), v);
9359
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
9360
+ assertIsSquare(Fp2, root, n);
9361
+ return root;
9362
+ }
9363
+ function sqrt9mod16(P) {
9364
+ const Fp_ = Field(P);
9365
+ const tn = tonelliShanks(P);
9366
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9367
+ const c2 = tn(Fp_, c1);
9368
+ const c3 = tn(Fp_, Fp_.neg(c1));
9369
+ const c4 = (P + _7n) / _16n;
9370
+ return (Fp2, n) => {
9371
+ let tv1 = Fp2.pow(n, c4);
9372
+ let tv2 = Fp2.mul(tv1, c1);
9373
+ const tv3 = Fp2.mul(tv1, c2);
9374
+ const tv4 = Fp2.mul(tv1, c3);
9375
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
9376
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
9377
+ tv1 = Fp2.cmov(tv1, tv2, e1);
9378
+ tv2 = Fp2.cmov(tv4, tv3, e2);
9379
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
9380
+ const root = Fp2.cmov(tv1, tv2, e3);
9381
+ assertIsSquare(Fp2, root, n);
9382
+ return root;
9383
+ };
9384
+ }
9385
+ function tonelliShanks(P) {
9386
+ if (P < _3n)
9387
+ throw new Error("sqrt is not defined for small field");
9388
+ let Q = P - _1n2;
9389
+ let S = 0;
9390
+ while (Q % _2n === _0n2) {
9391
+ Q /= _2n;
9392
+ S++;
9393
+ }
9394
+ let Z = _2n;
9395
+ const _Fp = Field(P);
9396
+ while (FpLegendre(_Fp, Z) === 1) {
9397
+ if (Z++ > 1e3)
9398
+ throw new Error("Cannot find square root: probably non-prime P");
9399
+ }
9400
+ if (S === 1)
9401
+ return sqrt3mod4;
9402
+ let cc = _Fp.pow(Z, Q);
9403
+ const Q1div2 = (Q + _1n2) / _2n;
9404
+ return function tonelliSlow(Fp2, n) {
9405
+ if (Fp2.is0(n))
9406
+ return n;
9407
+ if (FpLegendre(Fp2, n) !== 1)
9408
+ throw new Error("Cannot find square root");
9409
+ let M = S;
9410
+ let c = Fp2.mul(Fp2.ONE, cc);
9411
+ let t = Fp2.pow(n, Q);
9412
+ let R = Fp2.pow(n, Q1div2);
9413
+ while (!Fp2.eql(t, Fp2.ONE)) {
9414
+ if (Fp2.is0(t))
9415
+ return Fp2.ZERO;
9416
+ let i = 1;
9417
+ let t_tmp = Fp2.sqr(t);
9418
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
9419
+ i++;
9420
+ t_tmp = Fp2.sqr(t_tmp);
9421
+ if (i === M)
9422
+ throw new Error("Cannot find square root");
9423
+ }
9424
+ const exponent = _1n2 << BigInt(M - i - 1);
9425
+ const b = Fp2.pow(c, exponent);
9426
+ M = i;
9427
+ c = Fp2.sqr(b);
9428
+ t = Fp2.mul(t, c);
9429
+ R = Fp2.mul(R, b);
9430
+ }
9431
+ return R;
9432
+ };
9433
+ }
9434
+ function FpSqrt(P) {
9435
+ if (P % _4n === _3n)
9436
+ return sqrt3mod4;
9437
+ if (P % _8n === _5n)
9438
+ return sqrt5mod8;
9439
+ if (P % _16n === _9n)
9440
+ return sqrt9mod16(P);
9441
+ return tonelliShanks(P);
9442
+ }
9443
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
9444
+ var FIELD_FIELDS = [
9445
+ "create",
9446
+ "isValid",
9447
+ "is0",
9448
+ "neg",
9449
+ "inv",
9450
+ "sqrt",
9451
+ "sqr",
9452
+ "eql",
9453
+ "add",
9454
+ "sub",
9455
+ "mul",
9456
+ "pow",
9457
+ "div",
9458
+ "addN",
9459
+ "subN",
9460
+ "mulN",
9461
+ "sqrN"
9462
+ ];
9463
+ function validateField(field) {
9464
+ const initial = {
9465
+ ORDER: "bigint",
9466
+ MASK: "bigint",
9467
+ BYTES: "number",
9468
+ BITS: "number"
9469
+ };
9470
+ const opts = FIELD_FIELDS.reduce((map, val) => {
9471
+ map[val] = "function";
9472
+ return map;
9473
+ }, initial);
9474
+ _validateObject(field, opts);
9475
+ return field;
9476
+ }
9477
+ function FpPow(Fp2, num, power) {
9478
+ if (power < _0n2)
9479
+ throw new Error("invalid exponent, negatives unsupported");
9480
+ if (power === _0n2)
9481
+ return Fp2.ONE;
9482
+ if (power === _1n2)
9483
+ return num;
9484
+ let p = Fp2.ONE;
9485
+ let d = num;
9486
+ while (power > _0n2) {
9487
+ if (power & _1n2)
9488
+ p = Fp2.mul(p, d);
9489
+ d = Fp2.sqr(d);
9490
+ power >>= _1n2;
9491
+ }
9492
+ return p;
9493
+ }
9494
+ function FpInvertBatch(Fp2, nums, passZero = false) {
9495
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
9496
+ const multipliedAcc = nums.reduce((acc, num, i) => {
9497
+ if (Fp2.is0(num))
9498
+ return acc;
9499
+ inverted[i] = acc;
9500
+ return Fp2.mul(acc, num);
9501
+ }, Fp2.ONE);
9502
+ const invertedAcc = Fp2.inv(multipliedAcc);
9503
+ nums.reduceRight((acc, num, i) => {
9504
+ if (Fp2.is0(num))
9505
+ return acc;
9506
+ inverted[i] = Fp2.mul(acc, inverted[i]);
9507
+ return Fp2.mul(acc, num);
9508
+ }, invertedAcc);
9509
+ return inverted;
9510
+ }
9511
+ function FpLegendre(Fp2, n) {
9512
+ const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
9513
+ const powered = Fp2.pow(n, p1mod2);
9514
+ const yes = Fp2.eql(powered, Fp2.ONE);
9515
+ const zero = Fp2.eql(powered, Fp2.ZERO);
9516
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
9517
+ if (!yes && !zero && !no)
9518
+ throw new Error("invalid Legendre symbol result");
9519
+ return yes ? 1 : zero ? 0 : -1;
9520
+ }
9521
+ function nLength(n, nBitLength) {
9522
+ if (nBitLength !== void 0)
9523
+ anumber(nBitLength);
9524
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
9525
+ const nByteLength = Math.ceil(_nBitLength / 8);
9526
+ return { nBitLength: _nBitLength, nByteLength };
9527
+ }
9528
+ function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
9529
+ if (ORDER <= _0n2)
9530
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
9531
+ let _nbitLength = void 0;
9532
+ let _sqrt = void 0;
9533
+ let modFromBytes = false;
9534
+ let allowedLengths = void 0;
9535
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
9536
+ if (opts.sqrt || isLE2)
9537
+ throw new Error("cannot specify opts in two arguments");
9538
+ const _opts = bitLenOrOpts;
9539
+ if (_opts.BITS)
9540
+ _nbitLength = _opts.BITS;
9541
+ if (_opts.sqrt)
9542
+ _sqrt = _opts.sqrt;
9543
+ if (typeof _opts.isLE === "boolean")
9544
+ isLE2 = _opts.isLE;
9545
+ if (typeof _opts.modFromBytes === "boolean")
9546
+ modFromBytes = _opts.modFromBytes;
9547
+ allowedLengths = _opts.allowedLengths;
9548
+ } else {
9549
+ if (typeof bitLenOrOpts === "number")
9550
+ _nbitLength = bitLenOrOpts;
9551
+ if (opts.sqrt)
9552
+ _sqrt = opts.sqrt;
9553
+ }
9554
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
9555
+ if (BYTES > 2048)
9556
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
9557
+ let sqrtP;
9558
+ const f = Object.freeze({
9559
+ ORDER,
9560
+ isLE: isLE2,
9561
+ BITS,
9562
+ BYTES,
9563
+ MASK: bitMask(BITS),
9564
+ ZERO: _0n2,
9565
+ ONE: _1n2,
9566
+ allowedLengths,
9567
+ create: (num) => mod(num, ORDER),
9568
+ isValid: (num) => {
9569
+ if (typeof num !== "bigint")
9570
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
9571
+ return _0n2 <= num && num < ORDER;
9572
+ },
9573
+ is0: (num) => num === _0n2,
9574
+ // is valid and invertible
9575
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
9576
+ isOdd: (num) => (num & _1n2) === _1n2,
9577
+ neg: (num) => mod(-num, ORDER),
9578
+ eql: (lhs, rhs) => lhs === rhs,
9579
+ sqr: (num) => mod(num * num, ORDER),
9580
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
9581
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
9582
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
9583
+ pow: (num, power) => FpPow(f, num, power),
9584
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
9585
+ // Same as above, but doesn't normalize
9586
+ sqrN: (num) => num * num,
9587
+ addN: (lhs, rhs) => lhs + rhs,
9588
+ subN: (lhs, rhs) => lhs - rhs,
9589
+ mulN: (lhs, rhs) => lhs * rhs,
9590
+ inv: (num) => invert(num, ORDER),
9591
+ sqrt: _sqrt || ((n) => {
9592
+ if (!sqrtP)
9593
+ sqrtP = FpSqrt(ORDER);
9594
+ return sqrtP(f, n);
9595
+ }),
9596
+ toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
9597
+ fromBytes: (bytes, skipValidation = true) => {
9598
+ if (allowedLengths) {
9599
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
9600
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
9601
+ }
9602
+ const padded = new Uint8Array(BYTES);
9603
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
9604
+ bytes = padded;
9605
+ }
9606
+ if (bytes.length !== BYTES)
9607
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
9608
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
9609
+ if (modFromBytes)
9610
+ scalar = mod(scalar, ORDER);
9611
+ if (!skipValidation) {
9612
+ if (!f.isValid(scalar))
9613
+ throw new Error("invalid field element: outside of range 0..ORDER");
9614
+ }
9615
+ return scalar;
9616
+ },
9617
+ // TODO: we don't need it here, move out to separate fn
9618
+ invertBatch: (lst) => FpInvertBatch(f, lst),
9619
+ // We can't move this out because Fp6, Fp12 implement it
9620
+ // and it's unclear what to return in there.
9621
+ cmov: (a, b, c) => c ? b : a
9622
+ });
9623
+ return Object.freeze(f);
9624
+ }
9625
+
9626
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
9627
+ var _0n3 = BigInt(0);
9628
+ var _1n3 = BigInt(1);
9629
+ function negateCt(condition, item) {
9630
+ const neg = item.negate();
9631
+ return condition ? neg : item;
9632
+ }
9633
+ function normalizeZ(c, points) {
9634
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
9635
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
9636
+ }
9637
+ function validateW(W, bits) {
9638
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
9639
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
9640
+ }
9641
+ function calcWOpts(W, scalarBits) {
9642
+ validateW(W, scalarBits);
9643
+ const windows = Math.ceil(scalarBits / W) + 1;
9644
+ const windowSize = 2 ** (W - 1);
9645
+ const maxNumber = 2 ** W;
9646
+ const mask = bitMask(W);
9647
+ const shiftBy = BigInt(W);
9648
+ return { windows, windowSize, mask, maxNumber, shiftBy };
9649
+ }
9650
+ function calcOffsets(n, window, wOpts) {
9651
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
9652
+ let wbits = Number(n & mask);
9653
+ let nextN = n >> shiftBy;
9654
+ if (wbits > windowSize) {
9655
+ wbits -= maxNumber;
9656
+ nextN += _1n3;
9657
+ }
9658
+ const offsetStart = window * windowSize;
9659
+ const offset = offsetStart + Math.abs(wbits) - 1;
9660
+ const isZero = wbits === 0;
9661
+ const isNeg = wbits < 0;
9662
+ const isNegF = window % 2 !== 0;
9663
+ const offsetF = offsetStart;
9664
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
9665
+ }
9666
+ function validateMSMPoints(points, c) {
9667
+ if (!Array.isArray(points))
9668
+ throw new Error("array expected");
9669
+ points.forEach((p, i) => {
9670
+ if (!(p instanceof c))
9671
+ throw new Error("invalid point at index " + i);
9672
+ });
9673
+ }
9674
+ function validateMSMScalars(scalars, field) {
9675
+ if (!Array.isArray(scalars))
9676
+ throw new Error("array of scalars expected");
9677
+ scalars.forEach((s, i) => {
9678
+ if (!field.isValid(s))
9679
+ throw new Error("invalid scalar at index " + i);
9680
+ });
9681
+ }
9682
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
9683
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
9684
+ function getW(P) {
9685
+ return pointWindowSizes.get(P) || 1;
9686
+ }
9687
+ function assert0(n) {
9688
+ if (n !== _0n3)
9689
+ throw new Error("invalid wNAF");
9690
+ }
9691
+ var wNAF = class {
9692
+ // Parametrized with a given Point class (not individual point)
9693
+ constructor(Point, bits) {
9694
+ this.BASE = Point.BASE;
9695
+ this.ZERO = Point.ZERO;
9696
+ this.Fn = Point.Fn;
9697
+ this.bits = bits;
9698
+ }
9699
+ // non-const time multiplication ladder
9700
+ _unsafeLadder(elm, n, p = this.ZERO) {
9701
+ let d = elm;
9702
+ while (n > _0n3) {
9703
+ if (n & _1n3)
9704
+ p = p.add(d);
9705
+ d = d.double();
9706
+ n >>= _1n3;
9707
+ }
9708
+ return p;
9709
+ }
9710
+ /**
9711
+ * Creates a wNAF precomputation window. Used for caching.
9712
+ * Default window size is set by `utils.precompute()` and is equal to 8.
9713
+ * Number of precomputed points depends on the curve size:
9714
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
9715
+ * - 𝑊 is the window size
9716
+ * - 𝑛 is the bitlength of the curve order.
9717
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
9718
+ * @param point Point instance
9719
+ * @param W window size
9720
+ * @returns precomputed point tables flattened to a single array
9721
+ */
9722
+ precomputeWindow(point, W) {
9723
+ const { windows, windowSize } = calcWOpts(W, this.bits);
9724
+ const points = [];
9725
+ let p = point;
9726
+ let base = p;
9727
+ for (let window = 0; window < windows; window++) {
9728
+ base = p;
9729
+ points.push(base);
9730
+ for (let i = 1; i < windowSize; i++) {
9731
+ base = base.add(p);
9732
+ points.push(base);
9733
+ }
9734
+ p = base.double();
9735
+ }
9736
+ return points;
9737
+ }
9738
+ /**
9739
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
9740
+ * More compact implementation:
9741
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
9742
+ * @returns real and fake (for const-time) points
9743
+ */
9744
+ wNAF(W, precomputes, n) {
9745
+ if (!this.Fn.isValid(n))
9746
+ throw new Error("invalid scalar");
9747
+ let p = this.ZERO;
9748
+ let f = this.BASE;
9749
+ const wo = calcWOpts(W, this.bits);
9750
+ for (let window = 0; window < wo.windows; window++) {
9751
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
9752
+ n = nextN;
9753
+ if (isZero) {
9754
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
9755
+ } else {
9756
+ p = p.add(negateCt(isNeg, precomputes[offset]));
9757
+ }
9758
+ }
9759
+ assert0(n);
9760
+ return { p, f };
9761
+ }
9762
+ /**
9763
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
9764
+ * @param acc accumulator point to add result of multiplication
9765
+ * @returns point
9766
+ */
9767
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
9768
+ const wo = calcWOpts(W, this.bits);
9769
+ for (let window = 0; window < wo.windows; window++) {
9770
+ if (n === _0n3)
9771
+ break;
9772
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
9773
+ n = nextN;
9774
+ if (isZero) {
9775
+ continue;
9776
+ } else {
9777
+ const item = precomputes[offset];
9778
+ acc = acc.add(isNeg ? item.negate() : item);
9779
+ }
9780
+ }
9781
+ assert0(n);
9782
+ return acc;
9783
+ }
9784
+ getPrecomputes(W, point, transform) {
9785
+ let comp = pointPrecomputes.get(point);
9786
+ if (!comp) {
9787
+ comp = this.precomputeWindow(point, W);
9788
+ if (W !== 1) {
9789
+ if (typeof transform === "function")
9790
+ comp = transform(comp);
9791
+ pointPrecomputes.set(point, comp);
9792
+ }
9793
+ }
9794
+ return comp;
9795
+ }
9796
+ cached(point, scalar, transform) {
9797
+ const W = getW(point);
9798
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
9799
+ }
9800
+ unsafe(point, scalar, transform, prev) {
9801
+ const W = getW(point);
9802
+ if (W === 1)
9803
+ return this._unsafeLadder(point, scalar, prev);
9804
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
9805
+ }
9806
+ // We calculate precomputes for elliptic curve point multiplication
9807
+ // using windowed method. This specifies window size and
9808
+ // stores precomputed values. Usually only base point would be precomputed.
9809
+ createCache(P, W) {
9810
+ validateW(W, this.bits);
9811
+ pointWindowSizes.set(P, W);
9812
+ pointPrecomputes.delete(P);
9813
+ }
9814
+ hasCache(elm) {
9815
+ return getW(elm) !== 1;
9816
+ }
9817
+ };
9818
+ function pippenger(c, fieldN, points, scalars) {
9819
+ validateMSMPoints(points, c);
9820
+ validateMSMScalars(scalars, fieldN);
9821
+ const plength = points.length;
9822
+ const slength = scalars.length;
9823
+ if (plength !== slength)
9824
+ throw new Error("arrays of points and scalars must have equal length");
9825
+ const zero = c.ZERO;
9826
+ const wbits = bitLen(BigInt(plength));
9827
+ let windowSize = 1;
9828
+ if (wbits > 12)
9829
+ windowSize = wbits - 3;
9830
+ else if (wbits > 4)
9831
+ windowSize = wbits - 2;
9832
+ else if (wbits > 0)
9833
+ windowSize = 2;
9834
+ const MASK = bitMask(windowSize);
9835
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
9836
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
9837
+ let sum = zero;
9838
+ for (let i = lastBits; i >= 0; i -= windowSize) {
9839
+ buckets.fill(zero);
9840
+ for (let j = 0; j < slength; j++) {
9841
+ const scalar = scalars[j];
9842
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
9843
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
9844
+ }
9845
+ let resI = zero;
9846
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
9847
+ sumI = sumI.add(buckets[j]);
9848
+ resI = resI.add(sumI);
9849
+ }
9850
+ sum = sum.add(resI);
9851
+ if (i !== 0)
9852
+ for (let j = 0; j < windowSize; j++)
9853
+ sum = sum.double();
9854
+ }
9855
+ return sum;
9856
+ }
9857
+ function createField(order, field, isLE2) {
9858
+ if (field) {
9859
+ if (field.ORDER !== order)
9860
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
9861
+ validateField(field);
9862
+ return field;
9863
+ } else {
9864
+ return Field(order, { isLE: isLE2 });
9865
+ }
9866
+ }
9867
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
9868
+ if (FpFnLE === void 0)
9869
+ FpFnLE = type === "edwards";
9870
+ if (!CURVE || typeof CURVE !== "object")
9871
+ throw new Error(`expected valid ${type} CURVE object`);
9872
+ for (const p of ["p", "n", "h"]) {
9873
+ const val = CURVE[p];
9874
+ if (!(typeof val === "bigint" && val > _0n3))
9875
+ throw new Error(`CURVE.${p} must be positive bigint`);
9876
+ }
9877
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
9878
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
9879
+ const _b = type === "weierstrass" ? "b" : "d";
9880
+ const params = ["Gx", "Gy", "a", _b];
9881
+ for (const p of params) {
9882
+ if (!Fp2.isValid(CURVE[p]))
9883
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
9884
+ }
9885
+ CURVE = Object.freeze(Object.assign({}, CURVE));
9886
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
9887
+ }
9888
+
9889
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js
9890
+ var _0n4 = BigInt(0);
9891
+ var _1n4 = BigInt(1);
9892
+ var _2n2 = BigInt(2);
9893
+ var _8n2 = BigInt(8);
9894
+ function isEdValidXY(Fp2, CURVE, x, y) {
9895
+ const x2 = Fp2.sqr(x);
9896
+ const y2 = Fp2.sqr(y);
9897
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
9898
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
9899
+ return Fp2.eql(left, right);
9900
+ }
9901
+ function edwards(params, extraOpts = {}) {
9902
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
9903
+ const { Fp: Fp2, Fn: Fn2 } = validated;
9904
+ let CURVE = validated.CURVE;
9905
+ const { h: cofactor } = CURVE;
9906
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
9907
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
9908
+ const modP = (n) => Fp2.create(n);
9909
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
9910
+ try {
9911
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
9912
+ } catch (e) {
9913
+ return { isValid: false, value: _0n4 };
9914
+ }
9915
+ });
9916
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
9917
+ throw new Error("bad curve params: generator point");
9918
+ function acoord(title, n, banZero = false) {
9919
+ const min = banZero ? _1n4 : _0n4;
9920
+ aInRange("coordinate " + title, n, min, MASK);
9921
+ return n;
9922
+ }
9923
+ function aextpoint(other) {
9924
+ if (!(other instanceof Point))
9925
+ throw new Error("ExtendedPoint expected");
9926
+ }
9927
+ const toAffineMemo = memoized((p, iz) => {
9928
+ const { X, Y, Z } = p;
9929
+ const is0 = p.is0();
9930
+ if (iz == null)
9931
+ iz = is0 ? _8n2 : Fp2.inv(Z);
9932
+ const x = modP(X * iz);
9933
+ const y = modP(Y * iz);
9934
+ const zz = Fp2.mul(Z, iz);
9935
+ if (is0)
9936
+ return { x: _0n4, y: _1n4 };
9937
+ if (zz !== _1n4)
9938
+ throw new Error("invZ was invalid");
9939
+ return { x, y };
9940
+ });
9941
+ const assertValidMemo = memoized((p) => {
9942
+ const { a, d } = CURVE;
9943
+ if (p.is0())
9944
+ throw new Error("bad point: ZERO");
9945
+ const { X, Y, Z, T } = p;
9946
+ const X2 = modP(X * X);
9947
+ const Y2 = modP(Y * Y);
9948
+ const Z2 = modP(Z * Z);
9949
+ const Z4 = modP(Z2 * Z2);
9950
+ const aX2 = modP(X2 * a);
9951
+ const left = modP(Z2 * modP(aX2 + Y2));
9952
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
9953
+ if (left !== right)
9954
+ throw new Error("bad point: equation left != right (1)");
9955
+ const XY = modP(X * Y);
9956
+ const ZT = modP(Z * T);
9957
+ if (XY !== ZT)
9958
+ throw new Error("bad point: equation left != right (2)");
9959
+ return true;
9960
+ });
9961
+ class Point {
9962
+ constructor(X, Y, Z, T) {
9963
+ this.X = acoord("x", X);
9964
+ this.Y = acoord("y", Y);
9965
+ this.Z = acoord("z", Z, true);
9966
+ this.T = acoord("t", T);
9967
+ Object.freeze(this);
9968
+ }
9969
+ static CURVE() {
9970
+ return CURVE;
9971
+ }
9972
+ static fromAffine(p) {
9973
+ if (p instanceof Point)
9974
+ throw new Error("extended point not allowed");
9975
+ const { x, y } = p || {};
9976
+ acoord("x", x);
9977
+ acoord("y", y);
9978
+ return new Point(x, y, _1n4, modP(x * y));
9979
+ }
9980
+ // Uses algo from RFC8032 5.1.3.
9981
+ static fromBytes(bytes, zip215 = false) {
9982
+ const len = Fp2.BYTES;
9983
+ const { a, d } = CURVE;
9984
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
9985
+ _abool2(zip215, "zip215");
9986
+ const normed = copyBytes(bytes);
9987
+ const lastByte = bytes[len - 1];
9988
+ normed[len - 1] = lastByte & ~128;
9989
+ const y = bytesToNumberLE(normed);
9990
+ const max = zip215 ? MASK : Fp2.ORDER;
9991
+ aInRange("point.y", y, _0n4, max);
9992
+ const y2 = modP(y * y);
9993
+ const u = modP(y2 - _1n4);
9994
+ const v = modP(d * y2 - a);
9995
+ let { isValid: isValid2, value: x } = uvRatio2(u, v);
9996
+ if (!isValid2)
9997
+ throw new Error("bad point: invalid y coordinate");
9998
+ const isXOdd = (x & _1n4) === _1n4;
9999
+ const isLastByteOdd = (lastByte & 128) !== 0;
10000
+ if (!zip215 && x === _0n4 && isLastByteOdd)
10001
+ throw new Error("bad point: x=0 and x_0=1");
10002
+ if (isLastByteOdd !== isXOdd)
10003
+ x = modP(-x);
10004
+ return Point.fromAffine({ x, y });
10005
+ }
10006
+ static fromHex(bytes, zip215 = false) {
10007
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
10008
+ }
10009
+ get x() {
10010
+ return this.toAffine().x;
10011
+ }
10012
+ get y() {
10013
+ return this.toAffine().y;
10014
+ }
10015
+ precompute(windowSize = 8, isLazy = true) {
10016
+ wnaf.createCache(this, windowSize);
10017
+ if (!isLazy)
10018
+ this.multiply(_2n2);
10019
+ return this;
10020
+ }
10021
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
10022
+ assertValidity() {
10023
+ assertValidMemo(this);
10024
+ }
10025
+ // Compare one point to another.
10026
+ equals(other) {
10027
+ aextpoint(other);
10028
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10029
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10030
+ const X1Z2 = modP(X1 * Z2);
10031
+ const X2Z1 = modP(X2 * Z1);
10032
+ const Y1Z2 = modP(Y1 * Z2);
10033
+ const Y2Z1 = modP(Y2 * Z1);
10034
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
10035
+ }
10036
+ is0() {
10037
+ return this.equals(Point.ZERO);
10038
+ }
10039
+ negate() {
10040
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
10041
+ }
10042
+ // Fast algo for doubling Extended Point.
10043
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
10044
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
10045
+ double() {
10046
+ const { a } = CURVE;
10047
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10048
+ const A = modP(X1 * X1);
10049
+ const B = modP(Y1 * Y1);
10050
+ const C = modP(_2n2 * modP(Z1 * Z1));
10051
+ const D = modP(a * A);
10052
+ const x1y1 = X1 + Y1;
10053
+ const E = modP(modP(x1y1 * x1y1) - A - B);
10054
+ const G = D + B;
10055
+ const F = G - C;
10056
+ const H = D - B;
10057
+ const X3 = modP(E * F);
10058
+ const Y3 = modP(G * H);
10059
+ const T3 = modP(E * H);
10060
+ const Z3 = modP(F * G);
10061
+ return new Point(X3, Y3, Z3, T3);
10062
+ }
10063
+ // Fast algo for adding 2 Extended Points.
10064
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
10065
+ // Cost: 9M + 1*a + 1*d + 7add.
10066
+ add(other) {
10067
+ aextpoint(other);
10068
+ const { a, d } = CURVE;
10069
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
10070
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
10071
+ const A = modP(X1 * X2);
10072
+ const B = modP(Y1 * Y2);
10073
+ const C = modP(T1 * d * T2);
10074
+ const D = modP(Z1 * Z2);
10075
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
10076
+ const F = D - C;
10077
+ const G = D + C;
10078
+ const H = modP(B - a * A);
10079
+ const X3 = modP(E * F);
10080
+ const Y3 = modP(G * H);
10081
+ const T3 = modP(E * H);
10082
+ const Z3 = modP(F * G);
10083
+ return new Point(X3, Y3, Z3, T3);
10084
+ }
10085
+ subtract(other) {
10086
+ return this.add(other.negate());
10087
+ }
10088
+ // Constant-time multiplication.
10089
+ multiply(scalar) {
10090
+ if (!Fn2.isValidNot0(scalar))
10091
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
10092
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
10093
+ return normalizeZ(Point, [p, f])[0];
10094
+ }
10095
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
10096
+ // It's faster, but should only be used when you don't care about
10097
+ // an exposed private key e.g. sig verification.
10098
+ // Does NOT allow scalars higher than CURVE.n.
10099
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
10100
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
10101
+ if (!Fn2.isValid(scalar))
10102
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
10103
+ if (scalar === _0n4)
10104
+ return Point.ZERO;
10105
+ if (this.is0() || scalar === _1n4)
10106
+ return this;
10107
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
10108
+ }
10109
+ // Checks if point is of small order.
10110
+ // If you add something to small order point, you will have "dirty"
10111
+ // point with torsion component.
10112
+ // Multiplies point by cofactor and checks if the result is 0.
10113
+ isSmallOrder() {
10114
+ return this.multiplyUnsafe(cofactor).is0();
10115
+ }
10116
+ // Multiplies point by curve order and checks if the result is 0.
10117
+ // Returns `false` is the point is dirty.
10118
+ isTorsionFree() {
10119
+ return wnaf.unsafe(this, CURVE.n).is0();
10120
+ }
10121
+ // Converts Extended point to default (x, y) coordinates.
10122
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
10123
+ toAffine(invertedZ) {
10124
+ return toAffineMemo(this, invertedZ);
10125
+ }
10126
+ clearCofactor() {
10127
+ if (cofactor === _1n4)
10128
+ return this;
10129
+ return this.multiplyUnsafe(cofactor);
10130
+ }
10131
+ toBytes() {
10132
+ const { x, y } = this.toAffine();
10133
+ const bytes = Fp2.toBytes(y);
10134
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
10135
+ return bytes;
10136
+ }
10137
+ toHex() {
10138
+ return bytesToHex(this.toBytes());
10139
+ }
10140
+ toString() {
10141
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
10142
+ }
10143
+ // TODO: remove
10144
+ get ex() {
10145
+ return this.X;
10146
+ }
10147
+ get ey() {
10148
+ return this.Y;
10149
+ }
10150
+ get ez() {
10151
+ return this.Z;
10152
+ }
10153
+ get et() {
10154
+ return this.T;
10155
+ }
10156
+ static normalizeZ(points) {
10157
+ return normalizeZ(Point, points);
10158
+ }
10159
+ static msm(points, scalars) {
10160
+ return pippenger(Point, Fn2, points, scalars);
10161
+ }
10162
+ _setWindowSize(windowSize) {
10163
+ this.precompute(windowSize);
10164
+ }
10165
+ toRawBytes() {
10166
+ return this.toBytes();
10167
+ }
10168
+ }
10169
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
10170
+ Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
10171
+ Point.Fp = Fp2;
10172
+ Point.Fn = Fn2;
10173
+ const wnaf = new wNAF(Point, Fn2.BITS);
10174
+ Point.BASE.precompute(8);
10175
+ return Point;
10176
+ }
10177
+ var PrimeEdwardsPoint = class {
10178
+ constructor(ep) {
10179
+ this.ep = ep;
10180
+ }
10181
+ // Static methods that must be implemented by subclasses
10182
+ static fromBytes(_bytes) {
10183
+ notImplemented();
10184
+ }
10185
+ static fromHex(_hex) {
10186
+ notImplemented();
10187
+ }
10188
+ get x() {
10189
+ return this.toAffine().x;
10190
+ }
10191
+ get y() {
10192
+ return this.toAffine().y;
10193
+ }
10194
+ // Common implementations
10195
+ clearCofactor() {
10196
+ return this;
10197
+ }
10198
+ assertValidity() {
10199
+ this.ep.assertValidity();
10200
+ }
10201
+ toAffine(invertedZ) {
10202
+ return this.ep.toAffine(invertedZ);
10203
+ }
10204
+ toHex() {
10205
+ return bytesToHex(this.toBytes());
10206
+ }
10207
+ toString() {
10208
+ return this.toHex();
10209
+ }
10210
+ isTorsionFree() {
10211
+ return true;
10212
+ }
10213
+ isSmallOrder() {
10214
+ return false;
10215
+ }
10216
+ add(other) {
10217
+ this.assertSame(other);
10218
+ return this.init(this.ep.add(other.ep));
10219
+ }
10220
+ subtract(other) {
10221
+ this.assertSame(other);
10222
+ return this.init(this.ep.subtract(other.ep));
10223
+ }
10224
+ multiply(scalar) {
10225
+ return this.init(this.ep.multiply(scalar));
10226
+ }
10227
+ multiplyUnsafe(scalar) {
10228
+ return this.init(this.ep.multiplyUnsafe(scalar));
10229
+ }
10230
+ double() {
10231
+ return this.init(this.ep.double());
10232
+ }
10233
+ negate() {
10234
+ return this.init(this.ep.negate());
10235
+ }
10236
+ precompute(windowSize, isLazy) {
10237
+ return this.init(this.ep.precompute(windowSize, isLazy));
10238
+ }
10239
+ /** @deprecated use `toBytes` */
10240
+ toRawBytes() {
10241
+ return this.toBytes();
10242
+ }
10243
+ };
10244
+ function eddsa(Point, cHash, eddsaOpts = {}) {
10245
+ if (typeof cHash !== "function")
10246
+ throw new Error('"hash" function param is required');
10247
+ _validateObject(eddsaOpts, {}, {
10248
+ adjustScalarBytes: "function",
10249
+ randomBytes: "function",
10250
+ domain: "function",
10251
+ prehash: "function",
10252
+ mapToCurve: "function"
10253
+ });
10254
+ const { prehash } = eddsaOpts;
10255
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
10256
+ const randomBytes4 = eddsaOpts.randomBytes || randomBytes;
10257
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
10258
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
10259
+ _abool2(phflag, "phflag");
10260
+ if (ctx.length || phflag)
10261
+ throw new Error("Contexts/pre-hash are not supported");
10262
+ return data;
10263
+ });
10264
+ function modN_LE(hash) {
10265
+ return Fn2.create(bytesToNumberLE(hash));
10266
+ }
10267
+ function getPrivateScalar(key) {
10268
+ const len = lengths.secretKey;
10269
+ key = ensureBytes("private key", key, len);
10270
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
10271
+ const head = adjustScalarBytes2(hashed.slice(0, len));
10272
+ const prefix = hashed.slice(len, 2 * len);
10273
+ const scalar = modN_LE(head);
10274
+ return { head, prefix, scalar };
10275
+ }
10276
+ function getExtendedPublicKey(secretKey) {
10277
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
10278
+ const point = BASE.multiply(scalar);
10279
+ const pointBytes = point.toBytes();
10280
+ return { head, prefix, scalar, point, pointBytes };
10281
+ }
10282
+ function getPublicKey(secretKey) {
10283
+ return getExtendedPublicKey(secretKey).pointBytes;
10284
+ }
10285
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
10286
+ const msg = concatBytes(...msgs);
10287
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
10288
+ }
10289
+ function sign(msg, secretKey, options = {}) {
10290
+ msg = ensureBytes("message", msg);
10291
+ if (prehash)
10292
+ msg = prehash(msg);
10293
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
10294
+ const r = hashDomainToScalar(options.context, prefix, msg);
10295
+ const R = BASE.multiply(r).toBytes();
10296
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
10297
+ const s = Fn2.create(r + k * scalar);
10298
+ if (!Fn2.isValid(s))
10299
+ throw new Error("sign failed: invalid s");
10300
+ const rs = concatBytes(R, Fn2.toBytes(s));
10301
+ return _abytes2(rs, lengths.signature, "result");
10302
+ }
10303
+ const verifyOpts = { zip215: true };
10304
+ function verify(sig, msg, publicKey, options = verifyOpts) {
10305
+ const { context, zip215 } = options;
10306
+ const len = lengths.signature;
10307
+ sig = ensureBytes("signature", sig, len);
10308
+ msg = ensureBytes("message", msg);
10309
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
10310
+ if (zip215 !== void 0)
10311
+ _abool2(zip215, "zip215");
10312
+ if (prehash)
10313
+ msg = prehash(msg);
10314
+ const mid = len / 2;
10315
+ const r = sig.subarray(0, mid);
10316
+ const s = bytesToNumberLE(sig.subarray(mid, len));
10317
+ let A, R, SB;
10318
+ try {
10319
+ A = Point.fromBytes(publicKey, zip215);
10320
+ R = Point.fromBytes(r, zip215);
10321
+ SB = BASE.multiplyUnsafe(s);
10322
+ } catch (error) {
10323
+ return false;
10324
+ }
10325
+ if (!zip215 && A.isSmallOrder())
10326
+ return false;
10327
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
10328
+ const RkA = R.add(A.multiplyUnsafe(k));
10329
+ return RkA.subtract(SB).clearCofactor().is0();
10330
+ }
10331
+ const _size = Fp2.BYTES;
10332
+ const lengths = {
10333
+ secretKey: _size,
10334
+ publicKey: _size,
10335
+ signature: 2 * _size,
10336
+ seed: _size
10337
+ };
10338
+ function randomSecretKey(seed = randomBytes4(lengths.seed)) {
10339
+ return _abytes2(seed, lengths.seed, "seed");
10340
+ }
10341
+ function keygen(seed) {
10342
+ const secretKey = utils.randomSecretKey(seed);
10343
+ return { secretKey, publicKey: getPublicKey(secretKey) };
10344
+ }
10345
+ function isValidSecretKey(key) {
10346
+ return isBytes(key) && key.length === Fn2.BYTES;
10347
+ }
10348
+ function isValidPublicKey(key, zip215) {
10349
+ try {
10350
+ return !!Point.fromBytes(key, zip215);
10351
+ } catch (error) {
10352
+ return false;
10353
+ }
10354
+ }
10355
+ const utils = {
10356
+ getExtendedPublicKey,
10357
+ randomSecretKey,
10358
+ isValidSecretKey,
10359
+ isValidPublicKey,
10360
+ /**
10361
+ * Converts ed public key to x public key. Uses formula:
10362
+ * - ed25519:
10363
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
10364
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
10365
+ * - ed448:
10366
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
10367
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
10368
+ */
10369
+ toMontgomery(publicKey) {
10370
+ const { y } = Point.fromBytes(publicKey);
10371
+ const size = lengths.publicKey;
10372
+ const is25519 = size === 32;
10373
+ if (!is25519 && size !== 57)
10374
+ throw new Error("only defined for 25519 and 448");
10375
+ const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
10376
+ return Fp2.toBytes(u);
10377
+ },
10378
+ toMontgomerySecret(secretKey) {
10379
+ const size = lengths.secretKey;
10380
+ _abytes2(secretKey, size);
10381
+ const hashed = cHash(secretKey.subarray(0, size));
10382
+ return adjustScalarBytes2(hashed).subarray(0, size);
10383
+ },
10384
+ /** @deprecated */
10385
+ randomPrivateKey: randomSecretKey,
10386
+ /** @deprecated */
10387
+ precompute(windowSize = 8, point = Point.BASE) {
10388
+ return point.precompute(windowSize, false);
10389
+ }
10390
+ };
10391
+ return Object.freeze({
10392
+ keygen,
10393
+ getPublicKey,
10394
+ sign,
10395
+ verify,
10396
+ utils,
10397
+ Point,
10398
+ lengths
10399
+ });
10400
+ }
10401
+ function _eddsa_legacy_opts_to_new(c) {
10402
+ const CURVE = {
10403
+ a: c.a,
10404
+ d: c.d,
10405
+ p: c.Fp.ORDER,
10406
+ n: c.n,
10407
+ h: c.h,
10408
+ Gx: c.Gx,
10409
+ Gy: c.Gy
10410
+ };
10411
+ const Fp2 = c.Fp;
10412
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
10413
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
10414
+ const eddsaOpts = {
10415
+ randomBytes: c.randomBytes,
10416
+ adjustScalarBytes: c.adjustScalarBytes,
10417
+ domain: c.domain,
10418
+ prehash: c.prehash,
10419
+ mapToCurve: c.mapToCurve
10420
+ };
10421
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
10422
+ }
10423
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
10424
+ const Point = eddsa2.Point;
10425
+ const legacy = Object.assign({}, eddsa2, {
10426
+ ExtendedPoint: Point,
10427
+ CURVE: c,
10428
+ nBitLength: Point.Fn.BITS,
10429
+ nByteLength: Point.Fn.BYTES
10430
+ });
10431
+ return legacy;
10432
+ }
10433
+ function twistedEdwards(c) {
10434
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
10435
+ const Point = edwards(CURVE, curveOpts);
10436
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
10437
+ return _eddsa_new_output_to_legacy(c, EDDSA);
10438
+ }
10439
+
10440
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js
10441
+ var _0n5 = BigInt(0);
10442
+ var _1n5 = BigInt(1);
10443
+ var _2n3 = BigInt(2);
10444
+ function validateOpts(curve) {
10445
+ _validateObject(curve, {
10446
+ adjustScalarBytes: "function",
10447
+ powPminus2: "function"
10448
+ });
10449
+ return Object.freeze({ ...curve });
10450
+ }
10451
+ function montgomery(curveDef) {
10452
+ const CURVE = validateOpts(curveDef);
10453
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
10454
+ const is25519 = type === "x25519";
10455
+ if (!is25519 && type !== "x448")
10456
+ throw new Error("invalid type");
10457
+ const randomBytes_ = rand || randomBytes;
10458
+ const montgomeryBits = is25519 ? 255 : 448;
10459
+ const fieldLen = is25519 ? 32 : 56;
10460
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
10461
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
10462
+ const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
10463
+ const maxAdded = is25519 ? BigInt(8) * _2n3 ** BigInt(251) - _1n5 : BigInt(4) * _2n3 ** BigInt(445) - _1n5;
10464
+ const maxScalar = minScalar + maxAdded + _1n5;
10465
+ const modP = (n) => mod(n, P);
10466
+ const GuBytes = encodeU(Gu);
10467
+ function encodeU(u) {
10468
+ return numberToBytesLE(modP(u), fieldLen);
10469
+ }
10470
+ function decodeU(u) {
10471
+ const _u = ensureBytes("u coordinate", u, fieldLen);
10472
+ if (is25519)
10473
+ _u[31] &= 127;
10474
+ return modP(bytesToNumberLE(_u));
10475
+ }
10476
+ function decodeScalar(scalar) {
10477
+ return bytesToNumberLE(adjustScalarBytes2(ensureBytes("scalar", scalar, fieldLen)));
10478
+ }
10479
+ function scalarMult(scalar, u) {
10480
+ const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
10481
+ if (pu === _0n5)
10482
+ throw new Error("invalid private or public key received");
10483
+ return encodeU(pu);
10484
+ }
10485
+ function scalarMultBase(scalar) {
10486
+ return scalarMult(scalar, GuBytes);
10487
+ }
10488
+ function cswap(swap, x_2, x_3) {
10489
+ const dummy = modP(swap * (x_2 - x_3));
10490
+ x_2 = modP(x_2 - dummy);
10491
+ x_3 = modP(x_3 + dummy);
10492
+ return { x_2, x_3 };
10493
+ }
10494
+ function montgomeryLadder(u, scalar) {
10495
+ aInRange("u", u, _0n5, P);
10496
+ aInRange("scalar", scalar, minScalar, maxScalar);
10497
+ const k = scalar;
10498
+ const x_1 = u;
10499
+ let x_2 = _1n5;
10500
+ let z_2 = _0n5;
10501
+ let x_3 = u;
10502
+ let z_3 = _1n5;
10503
+ let swap = _0n5;
10504
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
10505
+ const k_t = k >> t & _1n5;
10506
+ swap ^= k_t;
10507
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
10508
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
10509
+ swap = k_t;
10510
+ const A = x_2 + z_2;
10511
+ const AA = modP(A * A);
10512
+ const B = x_2 - z_2;
10513
+ const BB = modP(B * B);
10514
+ const E = AA - BB;
10515
+ const C = x_3 + z_3;
10516
+ const D = x_3 - z_3;
10517
+ const DA = modP(D * A);
10518
+ const CB = modP(C * B);
10519
+ const dacb = DA + CB;
10520
+ const da_cb = DA - CB;
10521
+ x_3 = modP(dacb * dacb);
10522
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
10523
+ x_2 = modP(AA * BB);
10524
+ z_2 = modP(E * (AA + modP(a24 * E)));
10525
+ }
10526
+ ({ x_2, x_3 } = cswap(swap, x_2, x_3));
10527
+ ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
10528
+ const z2 = powPminus2(z_2);
10529
+ return modP(x_2 * z2);
10530
+ }
10531
+ const lengths = {
10532
+ secretKey: fieldLen,
10533
+ publicKey: fieldLen,
10534
+ seed: fieldLen
10535
+ };
10536
+ const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
10537
+ abytes(seed, lengths.seed);
10538
+ return seed;
10539
+ };
10540
+ function keygen(seed) {
10541
+ const secretKey = randomSecretKey(seed);
10542
+ return { secretKey, publicKey: scalarMultBase(secretKey) };
10543
+ }
10544
+ const utils = {
10545
+ randomSecretKey,
10546
+ randomPrivateKey: randomSecretKey
10547
+ };
10548
+ return {
10549
+ keygen,
10550
+ getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
10551
+ getPublicKey: (secretKey) => scalarMultBase(secretKey),
10552
+ scalarMult,
10553
+ scalarMultBase,
10554
+ utils,
10555
+ GuBytes: GuBytes.slice(),
10556
+ lengths
10557
+ };
10558
+ }
10559
+
10560
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js
10561
+ var _0n6 = /* @__PURE__ */ BigInt(0);
10562
+ var _1n6 = BigInt(1);
10563
+ var _2n4 = BigInt(2);
10564
+ var _3n2 = BigInt(3);
10565
+ var _5n2 = BigInt(5);
10566
+ var _8n3 = BigInt(8);
10567
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
10568
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
10569
+ p: ed25519_CURVE_p,
10570
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
10571
+ h: _8n3,
10572
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
10573
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
10574
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
10575
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
10576
+ }))();
10577
+ function ed25519_pow_2_252_3(x) {
10578
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
10579
+ const P = ed25519_CURVE_p;
10580
+ const x2 = x * x % P;
10581
+ const b2 = x2 * x % P;
10582
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
10583
+ const b5 = pow2(b4, _1n6, P) * x % P;
10584
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
10585
+ const b20 = pow2(b10, _10n, P) * b10 % P;
10586
+ const b40 = pow2(b20, _20n, P) * b20 % P;
10587
+ const b80 = pow2(b40, _40n, P) * b40 % P;
10588
+ const b160 = pow2(b80, _80n, P) * b80 % P;
10589
+ const b240 = pow2(b160, _80n, P) * b80 % P;
10590
+ const b250 = pow2(b240, _10n, P) * b10 % P;
10591
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
10592
+ return { pow_p_5_8, b2 };
10593
+ }
10594
+ function adjustScalarBytes(bytes) {
10595
+ bytes[0] &= 248;
10596
+ bytes[31] &= 127;
10597
+ bytes[31] |= 64;
10598
+ return bytes;
10599
+ }
10600
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
10601
+ function uvRatio(u, v) {
10602
+ const P = ed25519_CURVE_p;
10603
+ const v3 = mod(v * v * v, P);
10604
+ const v7 = mod(v3 * v3 * v, P);
10605
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
10606
+ let x = mod(u * v3 * pow, P);
10607
+ const vx2 = mod(v * x * x, P);
10608
+ const root1 = x;
10609
+ const root2 = mod(x * ED25519_SQRT_M1, P);
10610
+ const useRoot1 = vx2 === u;
10611
+ const useRoot2 = vx2 === mod(-u, P);
10612
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
10613
+ if (useRoot1)
10614
+ x = root1;
10615
+ if (useRoot2 || noRoot)
10616
+ x = root2;
10617
+ if (isNegativeLE(x, P))
10618
+ x = mod(-x, P);
10619
+ return { isValid: useRoot1 || useRoot2, value: x };
10620
+ }
10621
+ var Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
10622
+ var Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
10623
+ var ed25519Defaults = /* @__PURE__ */ (() => ({
10624
+ ...ed25519_CURVE,
10625
+ Fp,
10626
+ hash: sha512,
10627
+ adjustScalarBytes,
10628
+ // dom2
10629
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
10630
+ // Constant-time, u/√v
10631
+ uvRatio
10632
+ }))();
10633
+ var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
10634
+ var x25519 = /* @__PURE__ */ (() => {
10635
+ const P = Fp.ORDER;
10636
+ return montgomery({
10637
+ P,
10638
+ type: "x25519",
10639
+ powPminus2: (x) => {
10640
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
10641
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
10642
+ },
10643
+ adjustScalarBytes
10644
+ });
10645
+ })();
10646
+ var SQRT_M1 = ED25519_SQRT_M1;
10647
+ var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
10648
+ var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
10649
+ var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
10650
+ var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
10651
+ var invertSqrt = (number) => uvRatio(_1n6, number);
10652
+ var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
10653
+ var bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
10654
+ function calcElligatorRistrettoMap(r0) {
10655
+ const { d } = ed25519_CURVE;
10656
+ const P = ed25519_CURVE_p;
10657
+ const mod2 = (n) => Fp.create(n);
10658
+ const r = mod2(SQRT_M1 * r0 * r0);
10659
+ const Ns = mod2((r + _1n6) * ONE_MINUS_D_SQ);
10660
+ let c = BigInt(-1);
10661
+ const D = mod2((c - d * r) * mod2(r + d));
10662
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
10663
+ let s_ = mod2(s * r0);
10664
+ if (!isNegativeLE(s_, P))
10665
+ s_ = mod2(-s_);
10666
+ if (!Ns_D_is_sq)
10667
+ s = s_;
10668
+ if (!Ns_D_is_sq)
10669
+ c = r;
10670
+ const Nt = mod2(c * (r - _1n6) * D_MINUS_ONE_SQ - D);
10671
+ const s2 = s * s;
10672
+ const W0 = mod2((s + s) * D);
10673
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
10674
+ const W2 = mod2(_1n6 - s2);
10675
+ const W3 = mod2(_1n6 + s2);
10676
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
10677
+ }
10678
+ function ristretto255_map(bytes) {
10679
+ abytes(bytes, 64);
10680
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
10681
+ const R1 = calcElligatorRistrettoMap(r1);
10682
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
10683
+ const R2 = calcElligatorRistrettoMap(r2);
10684
+ return new _RistrettoPoint(R1.add(R2));
10685
+ }
10686
+ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
10687
+ constructor(ep) {
10688
+ super(ep);
10689
+ }
10690
+ static fromAffine(ap) {
10691
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
10692
+ }
10693
+ assertSame(other) {
10694
+ if (!(other instanceof __RistrettoPoint))
10695
+ throw new Error("RistrettoPoint expected");
10696
+ }
10697
+ init(ep) {
10698
+ return new __RistrettoPoint(ep);
10699
+ }
10700
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
10701
+ static hashToCurve(hex) {
10702
+ return ristretto255_map(ensureBytes("ristrettoHash", hex, 64));
10703
+ }
10704
+ static fromBytes(bytes) {
10705
+ abytes(bytes, 32);
10706
+ const { a, d } = ed25519_CURVE;
10707
+ const P = ed25519_CURVE_p;
10708
+ const mod2 = (n) => Fp.create(n);
10709
+ const s = bytes255ToNumberLE(bytes);
10710
+ if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
10711
+ throw new Error("invalid ristretto255 encoding 1");
10712
+ const s2 = mod2(s * s);
10713
+ const u1 = mod2(_1n6 + a * s2);
10714
+ const u2 = mod2(_1n6 - a * s2);
10715
+ const u1_2 = mod2(u1 * u1);
10716
+ const u2_2 = mod2(u2 * u2);
10717
+ const v = mod2(a * d * u1_2 - u2_2);
10718
+ const { isValid: isValid2, value: I } = invertSqrt(mod2(v * u2_2));
10719
+ const Dx = mod2(I * u2);
10720
+ const Dy = mod2(I * Dx * v);
10721
+ let x = mod2((s + s) * Dx);
10722
+ if (isNegativeLE(x, P))
10723
+ x = mod2(-x);
10724
+ const y = mod2(u1 * Dy);
10725
+ const t = mod2(x * y);
10726
+ if (!isValid2 || isNegativeLE(t, P) || y === _0n6)
10727
+ throw new Error("invalid ristretto255 encoding 2");
10728
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n6, t));
10729
+ }
10730
+ /**
10731
+ * Converts ristretto-encoded string to ristretto point.
10732
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
10733
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
10734
+ */
10735
+ static fromHex(hex) {
10736
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex, 32));
10737
+ }
10738
+ static msm(points, scalars) {
10739
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
10740
+ }
10741
+ /**
10742
+ * Encodes ristretto point to Uint8Array.
10743
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
10744
+ */
10745
+ toBytes() {
10746
+ let { X, Y, Z, T } = this.ep;
10747
+ const P = ed25519_CURVE_p;
10748
+ const mod2 = (n) => Fp.create(n);
10749
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
10750
+ const u2 = mod2(X * Y);
10751
+ const u2sq = mod2(u2 * u2);
10752
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
10753
+ const D1 = mod2(invsqrt * u1);
10754
+ const D2 = mod2(invsqrt * u2);
10755
+ const zInv = mod2(D1 * D2 * T);
10756
+ let D;
10757
+ if (isNegativeLE(T * zInv, P)) {
10758
+ let _x = mod2(Y * SQRT_M1);
10759
+ let _y = mod2(X * SQRT_M1);
10760
+ X = _x;
10761
+ Y = _y;
10762
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
10763
+ } else {
10764
+ D = D2;
10765
+ }
10766
+ if (isNegativeLE(X * zInv, P))
10767
+ Y = mod2(-Y);
10768
+ let s = mod2((Z - Y) * D);
10769
+ if (isNegativeLE(s, P))
10770
+ s = mod2(-s);
10771
+ return Fp.toBytes(s);
10772
+ }
10773
+ /**
10774
+ * Compares two Ristretto points.
10775
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
10776
+ */
10777
+ equals(other) {
10778
+ this.assertSame(other);
10779
+ const { X: X1, Y: Y1 } = this.ep;
10780
+ const { X: X2, Y: Y2 } = other.ep;
10781
+ const mod2 = (n) => Fp.create(n);
10782
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
10783
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
10784
+ return one || two;
10785
+ }
10786
+ is0() {
10787
+ return this.equals(__RistrettoPoint.ZERO);
10788
+ }
10789
+ };
10790
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
10791
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
10792
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
10793
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
10794
+
10795
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
10796
+ function isBytes2(a) {
10797
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
10798
+ }
10799
+ function abool(b) {
10800
+ if (typeof b !== "boolean")
10801
+ throw new Error(`boolean expected, not ${b}`);
10802
+ }
10803
+ function anumber2(n) {
10804
+ if (!Number.isSafeInteger(n) || n < 0)
10805
+ throw new Error("positive integer expected, got " + n);
10806
+ }
10807
+ function abytes2(b, ...lengths) {
10808
+ if (!isBytes2(b))
10809
+ throw new Error("Uint8Array expected");
10810
+ if (lengths.length > 0 && !lengths.includes(b.length))
10811
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
10812
+ }
10813
+ function aexists2(instance, checkFinished = true) {
10814
+ if (instance.destroyed)
10815
+ throw new Error("Hash instance has been destroyed");
10816
+ if (checkFinished && instance.finished)
10817
+ throw new Error("Hash#digest() has already been called");
10818
+ }
10819
+ function aoutput2(out, instance) {
10820
+ abytes2(out);
10821
+ const min = instance.outputLen;
10822
+ if (out.length < min) {
10823
+ throw new Error("digestInto() expects output buffer of length at least " + min);
10824
+ }
10825
+ }
10826
+ function u32(arr) {
10827
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
10828
+ }
10829
+ function clean2(...arrays) {
10830
+ for (let i = 0; i < arrays.length; i++) {
10831
+ arrays[i].fill(0);
10832
+ }
10833
+ }
10834
+ function createView2(arr) {
10835
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
10836
+ }
10837
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
10838
+ function utf8ToBytes2(str2) {
10839
+ if (typeof str2 !== "string")
10840
+ throw new Error("string expected");
10841
+ return new Uint8Array(new TextEncoder().encode(str2));
10842
+ }
10843
+ function toBytes2(data) {
10844
+ if (typeof data === "string")
10845
+ data = utf8ToBytes2(data);
10846
+ else if (isBytes2(data))
10847
+ data = copyBytes2(data);
10848
+ else
10849
+ throw new Error("Uint8Array expected, got " + typeof data);
10850
+ return data;
10851
+ }
10852
+ function checkOpts(defaults, opts) {
10853
+ if (opts == null || typeof opts !== "object")
10854
+ throw new Error("options must be defined");
10855
+ const merged = Object.assign(defaults, opts);
10856
+ return merged;
10857
+ }
10858
+ function equalBytes2(a, b) {
10859
+ if (a.length !== b.length)
10860
+ return false;
10861
+ let diff = 0;
10862
+ for (let i = 0; i < a.length; i++)
10863
+ diff |= a[i] ^ b[i];
10864
+ return diff === 0;
10865
+ }
10866
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
10867
+ function wrappedCipher(key, ...args) {
10868
+ abytes2(key);
10869
+ if (!isLE)
10870
+ throw new Error("Non little-endian hardware is not yet supported");
10871
+ if (params.nonceLength !== void 0) {
10872
+ const nonce = args[0];
10873
+ if (!nonce)
10874
+ throw new Error("nonce / iv required");
10875
+ if (params.varSizeNonce)
10876
+ abytes2(nonce);
10877
+ else
10878
+ abytes2(nonce, params.nonceLength);
10879
+ }
10880
+ const tagl = params.tagLength;
10881
+ if (tagl && args[1] !== void 0) {
10882
+ abytes2(args[1]);
10883
+ }
10884
+ const cipher = constructor(key, ...args);
10885
+ const checkOutput = (fnLength, output) => {
10886
+ if (output !== void 0) {
10887
+ if (fnLength !== 2)
10888
+ throw new Error("cipher output not supported");
10889
+ abytes2(output);
10890
+ }
10891
+ };
10892
+ let called = false;
10893
+ const wrCipher = {
10894
+ encrypt(data, output) {
10895
+ if (called)
10896
+ throw new Error("cannot encrypt() twice with same key + nonce");
10897
+ called = true;
10898
+ abytes2(data);
10899
+ checkOutput(cipher.encrypt.length, output);
10900
+ return cipher.encrypt(data, output);
10901
+ },
10902
+ decrypt(data, output) {
10903
+ abytes2(data);
10904
+ if (tagl && data.length < tagl)
10905
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
10906
+ checkOutput(cipher.decrypt.length, output);
10907
+ return cipher.decrypt(data, output);
10908
+ }
10909
+ };
10910
+ return wrCipher;
10911
+ }
10912
+ Object.assign(wrappedCipher, params);
10913
+ return wrappedCipher;
10914
+ };
10915
+ function getOutput(expectedLength, out, onlyAligned = true) {
10916
+ if (out === void 0)
10917
+ return new Uint8Array(expectedLength);
10918
+ if (out.length !== expectedLength)
10919
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
10920
+ if (onlyAligned && !isAligned32(out))
10921
+ throw new Error("invalid output, must be aligned");
10922
+ return out;
10923
+ }
10924
+ function setBigUint642(view, byteOffset, value, isLE2) {
10925
+ if (typeof view.setBigUint64 === "function")
10926
+ return view.setBigUint64(byteOffset, value, isLE2);
10927
+ const _32n2 = BigInt(32);
10928
+ const _u32_max = BigInt(4294967295);
10929
+ const wh = Number(value >> _32n2 & _u32_max);
10930
+ const wl = Number(value & _u32_max);
10931
+ const h = isLE2 ? 4 : 0;
10932
+ const l = isLE2 ? 0 : 4;
10933
+ view.setUint32(byteOffset + h, wh, isLE2);
10934
+ view.setUint32(byteOffset + l, wl, isLE2);
10935
+ }
10936
+ function u64Lengths(dataLength, aadLength, isLE2) {
10937
+ abool(isLE2);
10938
+ const num = new Uint8Array(16);
10939
+ const view = createView2(num);
10940
+ setBigUint642(view, 0, BigInt(aadLength), isLE2);
10941
+ setBigUint642(view, 8, BigInt(dataLength), isLE2);
10942
+ return num;
10943
+ }
10944
+ function isAligned32(bytes) {
10945
+ return bytes.byteOffset % 4 === 0;
10946
+ }
10947
+ function copyBytes2(bytes) {
10948
+ return Uint8Array.from(bytes);
10949
+ }
10950
+
10951
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/_arx.js
10952
+ var _utf8ToBytes = (str2) => Uint8Array.from(str2.split("").map((c) => c.charCodeAt(0)));
10953
+ var sigma16 = _utf8ToBytes("expand 16-byte k");
10954
+ var sigma32 = _utf8ToBytes("expand 32-byte k");
10955
+ var sigma16_32 = u32(sigma16);
10956
+ var sigma32_32 = u32(sigma32);
10957
+ function rotl(a, b) {
10958
+ return a << b | a >>> 32 - b;
10959
+ }
10960
+ function isAligned322(b) {
10961
+ return b.byteOffset % 4 === 0;
10962
+ }
10963
+ var BLOCK_LEN = 64;
10964
+ var BLOCK_LEN32 = 16;
10965
+ var MAX_COUNTER = 2 ** 32 - 1;
10966
+ var U32_EMPTY = new Uint32Array();
10967
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
10968
+ const len = data.length;
10969
+ const block = new Uint8Array(BLOCK_LEN);
10970
+ const b32 = u32(block);
10971
+ const isAligned = isAligned322(data) && isAligned322(output);
10972
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
10973
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
10974
+ for (let pos = 0; pos < len; counter++) {
10975
+ core(sigma, key, nonce, b32, counter, rounds);
10976
+ if (counter >= MAX_COUNTER)
10977
+ throw new Error("arx: counter overflow");
10978
+ const take = Math.min(BLOCK_LEN, len - pos);
10979
+ if (isAligned && take === BLOCK_LEN) {
10980
+ const pos32 = pos / 4;
10981
+ if (pos % 4 !== 0)
10982
+ throw new Error("arx: invalid block position");
10983
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
10984
+ posj = pos32 + j;
10985
+ o32[posj] = d32[posj] ^ b32[j];
10986
+ }
10987
+ pos += BLOCK_LEN;
10988
+ continue;
10989
+ }
10990
+ for (let j = 0, posj; j < take; j++) {
10991
+ posj = pos + j;
10992
+ output[posj] = data[posj] ^ block[j];
10993
+ }
10994
+ pos += take;
10995
+ }
10996
+ }
10997
+ function createCipher(core, opts) {
10998
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
10999
+ if (typeof core !== "function")
11000
+ throw new Error("core must be a function");
11001
+ anumber2(counterLength);
11002
+ anumber2(rounds);
11003
+ abool(counterRight);
11004
+ abool(allowShortKeys);
11005
+ return (key, nonce, data, output, counter = 0) => {
11006
+ abytes2(key);
11007
+ abytes2(nonce);
11008
+ abytes2(data);
11009
+ const len = data.length;
11010
+ if (output === void 0)
11011
+ output = new Uint8Array(len);
11012
+ abytes2(output);
11013
+ anumber2(counter);
11014
+ if (counter < 0 || counter >= MAX_COUNTER)
11015
+ throw new Error("arx: counter overflow");
11016
+ if (output.length < len)
11017
+ throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
11018
+ const toClean = [];
11019
+ let l = key.length;
11020
+ let k;
11021
+ let sigma;
11022
+ if (l === 32) {
11023
+ toClean.push(k = copyBytes2(key));
11024
+ sigma = sigma32_32;
11025
+ } else if (l === 16 && allowShortKeys) {
11026
+ k = new Uint8Array(32);
11027
+ k.set(key);
11028
+ k.set(key, 16);
11029
+ sigma = sigma16_32;
11030
+ toClean.push(k);
11031
+ } else {
11032
+ throw new Error(`arx: invalid 32-byte key, got length=${l}`);
11033
+ }
11034
+ if (!isAligned322(nonce))
11035
+ toClean.push(nonce = copyBytes2(nonce));
11036
+ const k32 = u32(k);
11037
+ if (extendNonceFn) {
11038
+ if (nonce.length !== 24)
11039
+ throw new Error(`arx: extended nonce must be 24 bytes`);
11040
+ extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
11041
+ nonce = nonce.subarray(16);
11042
+ }
11043
+ const nonceNcLen = 16 - counterLength;
11044
+ if (nonceNcLen !== nonce.length)
11045
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
11046
+ if (nonceNcLen !== 12) {
11047
+ const nc2 = new Uint8Array(12);
11048
+ nc2.set(nonce, counterRight ? 0 : 12 - nonce.length);
11049
+ nonce = nc2;
11050
+ toClean.push(nonce);
11051
+ }
11052
+ const n32 = u32(nonce);
11053
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
11054
+ clean2(...toClean);
11055
+ return output;
11056
+ };
11057
+ }
11058
+
11059
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/_poly1305.js
11060
+ var u8to16 = (a, i) => a[i++] & 255 | (a[i++] & 255) << 8;
11061
+ var Poly1305 = class {
11062
+ constructor(key) {
11063
+ this.blockLen = 16;
11064
+ this.outputLen = 16;
11065
+ this.buffer = new Uint8Array(16);
11066
+ this.r = new Uint16Array(10);
11067
+ this.h = new Uint16Array(10);
11068
+ this.pad = new Uint16Array(8);
11069
+ this.pos = 0;
11070
+ this.finished = false;
11071
+ key = toBytes2(key);
11072
+ abytes2(key, 32);
11073
+ const t0 = u8to16(key, 0);
11074
+ const t1 = u8to16(key, 2);
11075
+ const t2 = u8to16(key, 4);
11076
+ const t3 = u8to16(key, 6);
11077
+ const t4 = u8to16(key, 8);
11078
+ const t5 = u8to16(key, 10);
11079
+ const t6 = u8to16(key, 12);
11080
+ const t7 = u8to16(key, 14);
11081
+ this.r[0] = t0 & 8191;
11082
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
11083
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
11084
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
11085
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
11086
+ this.r[5] = t4 >>> 1 & 8190;
11087
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
11088
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
11089
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
11090
+ this.r[9] = t7 >>> 5 & 127;
11091
+ for (let i = 0; i < 8; i++)
11092
+ this.pad[i] = u8to16(key, 16 + 2 * i);
11093
+ }
11094
+ process(data, offset, isLast = false) {
11095
+ const hibit = isLast ? 0 : 1 << 11;
11096
+ const { h, r } = this;
11097
+ const r0 = r[0];
11098
+ const r1 = r[1];
11099
+ const r2 = r[2];
11100
+ const r3 = r[3];
11101
+ const r4 = r[4];
11102
+ const r5 = r[5];
11103
+ const r6 = r[6];
11104
+ const r7 = r[7];
11105
+ const r8 = r[8];
11106
+ const r9 = r[9];
11107
+ const t0 = u8to16(data, offset + 0);
11108
+ const t1 = u8to16(data, offset + 2);
11109
+ const t2 = u8to16(data, offset + 4);
11110
+ const t3 = u8to16(data, offset + 6);
11111
+ const t4 = u8to16(data, offset + 8);
11112
+ const t5 = u8to16(data, offset + 10);
11113
+ const t6 = u8to16(data, offset + 12);
11114
+ const t7 = u8to16(data, offset + 14);
11115
+ let h0 = h[0] + (t0 & 8191);
11116
+ let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
11117
+ let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
11118
+ let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
11119
+ let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
11120
+ let h5 = h[5] + (t4 >>> 1 & 8191);
11121
+ let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
11122
+ let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
11123
+ let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
11124
+ let h9 = h[9] + (t7 >>> 5 | hibit);
11125
+ let c = 0;
11126
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
11127
+ c = d0 >>> 13;
11128
+ d0 &= 8191;
11129
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
11130
+ c += d0 >>> 13;
11131
+ d0 &= 8191;
11132
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
11133
+ c = d1 >>> 13;
11134
+ d1 &= 8191;
11135
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
11136
+ c += d1 >>> 13;
11137
+ d1 &= 8191;
11138
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
11139
+ c = d2 >>> 13;
11140
+ d2 &= 8191;
11141
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
11142
+ c += d2 >>> 13;
11143
+ d2 &= 8191;
11144
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
11145
+ c = d3 >>> 13;
11146
+ d3 &= 8191;
11147
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
11148
+ c += d3 >>> 13;
11149
+ d3 &= 8191;
11150
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
11151
+ c = d4 >>> 13;
11152
+ d4 &= 8191;
11153
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
11154
+ c += d4 >>> 13;
11155
+ d4 &= 8191;
11156
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
11157
+ c = d5 >>> 13;
11158
+ d5 &= 8191;
11159
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
11160
+ c += d5 >>> 13;
11161
+ d5 &= 8191;
11162
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
11163
+ c = d6 >>> 13;
11164
+ d6 &= 8191;
11165
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
11166
+ c += d6 >>> 13;
11167
+ d6 &= 8191;
11168
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
11169
+ c = d7 >>> 13;
11170
+ d7 &= 8191;
11171
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
11172
+ c += d7 >>> 13;
11173
+ d7 &= 8191;
11174
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
11175
+ c = d8 >>> 13;
11176
+ d8 &= 8191;
11177
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
11178
+ c += d8 >>> 13;
11179
+ d8 &= 8191;
11180
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
11181
+ c = d9 >>> 13;
11182
+ d9 &= 8191;
11183
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
11184
+ c += d9 >>> 13;
11185
+ d9 &= 8191;
11186
+ c = (c << 2) + c | 0;
11187
+ c = c + d0 | 0;
11188
+ d0 = c & 8191;
11189
+ c = c >>> 13;
11190
+ d1 += c;
11191
+ h[0] = d0;
11192
+ h[1] = d1;
11193
+ h[2] = d2;
11194
+ h[3] = d3;
11195
+ h[4] = d4;
11196
+ h[5] = d5;
11197
+ h[6] = d6;
11198
+ h[7] = d7;
11199
+ h[8] = d8;
11200
+ h[9] = d9;
11201
+ }
11202
+ finalize() {
11203
+ const { h, pad } = this;
11204
+ const g = new Uint16Array(10);
11205
+ let c = h[1] >>> 13;
11206
+ h[1] &= 8191;
11207
+ for (let i = 2; i < 10; i++) {
11208
+ h[i] += c;
11209
+ c = h[i] >>> 13;
11210
+ h[i] &= 8191;
11211
+ }
11212
+ h[0] += c * 5;
11213
+ c = h[0] >>> 13;
11214
+ h[0] &= 8191;
11215
+ h[1] += c;
11216
+ c = h[1] >>> 13;
11217
+ h[1] &= 8191;
11218
+ h[2] += c;
11219
+ g[0] = h[0] + 5;
11220
+ c = g[0] >>> 13;
11221
+ g[0] &= 8191;
11222
+ for (let i = 1; i < 10; i++) {
11223
+ g[i] = h[i] + c;
11224
+ c = g[i] >>> 13;
11225
+ g[i] &= 8191;
11226
+ }
11227
+ g[9] -= 1 << 13;
11228
+ let mask = (c ^ 1) - 1;
11229
+ for (let i = 0; i < 10; i++)
11230
+ g[i] &= mask;
11231
+ mask = ~mask;
11232
+ for (let i = 0; i < 10; i++)
11233
+ h[i] = h[i] & mask | g[i];
11234
+ h[0] = (h[0] | h[1] << 13) & 65535;
11235
+ h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
11236
+ h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
11237
+ h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
11238
+ h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
11239
+ h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
11240
+ h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
11241
+ h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
11242
+ let f = h[0] + pad[0];
11243
+ h[0] = f & 65535;
11244
+ for (let i = 1; i < 8; i++) {
11245
+ f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
11246
+ h[i] = f & 65535;
11247
+ }
11248
+ clean2(g);
11249
+ }
11250
+ update(data) {
11251
+ aexists2(this);
11252
+ data = toBytes2(data);
11253
+ abytes2(data);
11254
+ const { buffer, blockLen } = this;
11255
+ const len = data.length;
11256
+ for (let pos = 0; pos < len; ) {
11257
+ const take = Math.min(blockLen - this.pos, len - pos);
11258
+ if (take === blockLen) {
11259
+ for (; blockLen <= len - pos; pos += blockLen)
11260
+ this.process(data, pos);
11261
+ continue;
11262
+ }
11263
+ buffer.set(data.subarray(pos, pos + take), this.pos);
11264
+ this.pos += take;
11265
+ pos += take;
11266
+ if (this.pos === blockLen) {
11267
+ this.process(buffer, 0, false);
11268
+ this.pos = 0;
11269
+ }
11270
+ }
11271
+ return this;
11272
+ }
11273
+ destroy() {
11274
+ clean2(this.h, this.r, this.buffer, this.pad);
11275
+ }
11276
+ digestInto(out) {
11277
+ aexists2(this);
11278
+ aoutput2(out, this);
11279
+ this.finished = true;
11280
+ const { buffer, h } = this;
11281
+ let { pos } = this;
11282
+ if (pos) {
11283
+ buffer[pos++] = 1;
11284
+ for (; pos < 16; pos++)
11285
+ buffer[pos] = 0;
11286
+ this.process(buffer, 0, true);
11287
+ }
11288
+ this.finalize();
11289
+ let opos = 0;
11290
+ for (let i = 0; i < 8; i++) {
11291
+ out[opos++] = h[i] >>> 0;
11292
+ out[opos++] = h[i] >>> 8;
11293
+ }
11294
+ return out;
11295
+ }
11296
+ digest() {
11297
+ const { buffer, outputLen } = this;
11298
+ this.digestInto(buffer);
11299
+ const res = buffer.slice(0, outputLen);
11300
+ this.destroy();
11301
+ return res;
11302
+ }
11303
+ };
11304
+ function wrapConstructorWithKey(hashCons) {
11305
+ const hashC = (msg, key) => hashCons(key).update(toBytes2(msg)).digest();
11306
+ const tmp = hashCons(new Uint8Array(32));
11307
+ hashC.outputLen = tmp.outputLen;
11308
+ hashC.blockLen = tmp.blockLen;
11309
+ hashC.create = (key) => hashCons(key);
11310
+ return hashC;
11311
+ }
11312
+ var poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));
11313
+
11314
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/chacha.js
11315
+ function chachaCore(s, k, n, out, cnt, rounds = 20) {
11316
+ let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
11317
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
11318
+ for (let r = 0; r < rounds; r += 2) {
11319
+ x00 = x00 + x04 | 0;
11320
+ x12 = rotl(x12 ^ x00, 16);
11321
+ x08 = x08 + x12 | 0;
11322
+ x04 = rotl(x04 ^ x08, 12);
11323
+ x00 = x00 + x04 | 0;
11324
+ x12 = rotl(x12 ^ x00, 8);
11325
+ x08 = x08 + x12 | 0;
11326
+ x04 = rotl(x04 ^ x08, 7);
11327
+ x01 = x01 + x05 | 0;
11328
+ x13 = rotl(x13 ^ x01, 16);
11329
+ x09 = x09 + x13 | 0;
11330
+ x05 = rotl(x05 ^ x09, 12);
11331
+ x01 = x01 + x05 | 0;
11332
+ x13 = rotl(x13 ^ x01, 8);
11333
+ x09 = x09 + x13 | 0;
11334
+ x05 = rotl(x05 ^ x09, 7);
11335
+ x02 = x02 + x06 | 0;
11336
+ x14 = rotl(x14 ^ x02, 16);
11337
+ x10 = x10 + x14 | 0;
11338
+ x06 = rotl(x06 ^ x10, 12);
11339
+ x02 = x02 + x06 | 0;
11340
+ x14 = rotl(x14 ^ x02, 8);
11341
+ x10 = x10 + x14 | 0;
11342
+ x06 = rotl(x06 ^ x10, 7);
11343
+ x03 = x03 + x07 | 0;
11344
+ x15 = rotl(x15 ^ x03, 16);
11345
+ x11 = x11 + x15 | 0;
11346
+ x07 = rotl(x07 ^ x11, 12);
11347
+ x03 = x03 + x07 | 0;
11348
+ x15 = rotl(x15 ^ x03, 8);
11349
+ x11 = x11 + x15 | 0;
11350
+ x07 = rotl(x07 ^ x11, 7);
11351
+ x00 = x00 + x05 | 0;
11352
+ x15 = rotl(x15 ^ x00, 16);
11353
+ x10 = x10 + x15 | 0;
11354
+ x05 = rotl(x05 ^ x10, 12);
11355
+ x00 = x00 + x05 | 0;
11356
+ x15 = rotl(x15 ^ x00, 8);
11357
+ x10 = x10 + x15 | 0;
11358
+ x05 = rotl(x05 ^ x10, 7);
11359
+ x01 = x01 + x06 | 0;
11360
+ x12 = rotl(x12 ^ x01, 16);
11361
+ x11 = x11 + x12 | 0;
11362
+ x06 = rotl(x06 ^ x11, 12);
11363
+ x01 = x01 + x06 | 0;
11364
+ x12 = rotl(x12 ^ x01, 8);
11365
+ x11 = x11 + x12 | 0;
11366
+ x06 = rotl(x06 ^ x11, 7);
11367
+ x02 = x02 + x07 | 0;
11368
+ x13 = rotl(x13 ^ x02, 16);
11369
+ x08 = x08 + x13 | 0;
11370
+ x07 = rotl(x07 ^ x08, 12);
11371
+ x02 = x02 + x07 | 0;
11372
+ x13 = rotl(x13 ^ x02, 8);
11373
+ x08 = x08 + x13 | 0;
11374
+ x07 = rotl(x07 ^ x08, 7);
11375
+ x03 = x03 + x04 | 0;
11376
+ x14 = rotl(x14 ^ x03, 16);
11377
+ x09 = x09 + x14 | 0;
11378
+ x04 = rotl(x04 ^ x09, 12);
11379
+ x03 = x03 + x04 | 0;
11380
+ x14 = rotl(x14 ^ x03, 8);
11381
+ x09 = x09 + x14 | 0;
11382
+ x04 = rotl(x04 ^ x09, 7);
11383
+ }
11384
+ let oi = 0;
11385
+ out[oi++] = y00 + x00 | 0;
11386
+ out[oi++] = y01 + x01 | 0;
11387
+ out[oi++] = y02 + x02 | 0;
11388
+ out[oi++] = y03 + x03 | 0;
11389
+ out[oi++] = y04 + x04 | 0;
11390
+ out[oi++] = y05 + x05 | 0;
11391
+ out[oi++] = y06 + x06 | 0;
11392
+ out[oi++] = y07 + x07 | 0;
11393
+ out[oi++] = y08 + x08 | 0;
11394
+ out[oi++] = y09 + x09 | 0;
11395
+ out[oi++] = y10 + x10 | 0;
11396
+ out[oi++] = y11 + x11 | 0;
11397
+ out[oi++] = y12 + x12 | 0;
11398
+ out[oi++] = y13 + x13 | 0;
11399
+ out[oi++] = y14 + x14 | 0;
11400
+ out[oi++] = y15 + x15 | 0;
11401
+ }
11402
+ function hchacha(s, k, i, o32) {
11403
+ let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];
11404
+ for (let r = 0; r < 20; r += 2) {
11405
+ x00 = x00 + x04 | 0;
11406
+ x12 = rotl(x12 ^ x00, 16);
11407
+ x08 = x08 + x12 | 0;
11408
+ x04 = rotl(x04 ^ x08, 12);
11409
+ x00 = x00 + x04 | 0;
11410
+ x12 = rotl(x12 ^ x00, 8);
11411
+ x08 = x08 + x12 | 0;
11412
+ x04 = rotl(x04 ^ x08, 7);
11413
+ x01 = x01 + x05 | 0;
11414
+ x13 = rotl(x13 ^ x01, 16);
11415
+ x09 = x09 + x13 | 0;
11416
+ x05 = rotl(x05 ^ x09, 12);
11417
+ x01 = x01 + x05 | 0;
11418
+ x13 = rotl(x13 ^ x01, 8);
11419
+ x09 = x09 + x13 | 0;
11420
+ x05 = rotl(x05 ^ x09, 7);
11421
+ x02 = x02 + x06 | 0;
11422
+ x14 = rotl(x14 ^ x02, 16);
11423
+ x10 = x10 + x14 | 0;
11424
+ x06 = rotl(x06 ^ x10, 12);
11425
+ x02 = x02 + x06 | 0;
11426
+ x14 = rotl(x14 ^ x02, 8);
11427
+ x10 = x10 + x14 | 0;
11428
+ x06 = rotl(x06 ^ x10, 7);
11429
+ x03 = x03 + x07 | 0;
11430
+ x15 = rotl(x15 ^ x03, 16);
11431
+ x11 = x11 + x15 | 0;
11432
+ x07 = rotl(x07 ^ x11, 12);
11433
+ x03 = x03 + x07 | 0;
11434
+ x15 = rotl(x15 ^ x03, 8);
11435
+ x11 = x11 + x15 | 0;
11436
+ x07 = rotl(x07 ^ x11, 7);
11437
+ x00 = x00 + x05 | 0;
11438
+ x15 = rotl(x15 ^ x00, 16);
11439
+ x10 = x10 + x15 | 0;
11440
+ x05 = rotl(x05 ^ x10, 12);
11441
+ x00 = x00 + x05 | 0;
11442
+ x15 = rotl(x15 ^ x00, 8);
11443
+ x10 = x10 + x15 | 0;
11444
+ x05 = rotl(x05 ^ x10, 7);
11445
+ x01 = x01 + x06 | 0;
11446
+ x12 = rotl(x12 ^ x01, 16);
11447
+ x11 = x11 + x12 | 0;
11448
+ x06 = rotl(x06 ^ x11, 12);
11449
+ x01 = x01 + x06 | 0;
11450
+ x12 = rotl(x12 ^ x01, 8);
11451
+ x11 = x11 + x12 | 0;
11452
+ x06 = rotl(x06 ^ x11, 7);
11453
+ x02 = x02 + x07 | 0;
11454
+ x13 = rotl(x13 ^ x02, 16);
11455
+ x08 = x08 + x13 | 0;
11456
+ x07 = rotl(x07 ^ x08, 12);
11457
+ x02 = x02 + x07 | 0;
11458
+ x13 = rotl(x13 ^ x02, 8);
11459
+ x08 = x08 + x13 | 0;
11460
+ x07 = rotl(x07 ^ x08, 7);
11461
+ x03 = x03 + x04 | 0;
11462
+ x14 = rotl(x14 ^ x03, 16);
11463
+ x09 = x09 + x14 | 0;
11464
+ x04 = rotl(x04 ^ x09, 12);
11465
+ x03 = x03 + x04 | 0;
11466
+ x14 = rotl(x14 ^ x03, 8);
11467
+ x09 = x09 + x14 | 0;
11468
+ x04 = rotl(x04 ^ x09, 7);
11469
+ }
11470
+ let oi = 0;
11471
+ o32[oi++] = x00;
11472
+ o32[oi++] = x01;
11473
+ o32[oi++] = x02;
11474
+ o32[oi++] = x03;
11475
+ o32[oi++] = x12;
11476
+ o32[oi++] = x13;
11477
+ o32[oi++] = x14;
11478
+ o32[oi++] = x15;
11479
+ }
11480
+ var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
11481
+ counterRight: false,
11482
+ counterLength: 4,
11483
+ allowShortKeys: false
11484
+ });
11485
+ var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
11486
+ counterRight: false,
11487
+ counterLength: 8,
11488
+ extendNonceFn: hchacha,
11489
+ allowShortKeys: false
11490
+ });
11491
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
11492
+ var updatePadded = (h, msg) => {
11493
+ h.update(msg);
11494
+ const left = msg.length % 16;
11495
+ if (left)
11496
+ h.update(ZEROS16.subarray(left));
11497
+ };
11498
+ var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
11499
+ function computeTag(fn, key, nonce, data, AAD) {
11500
+ const authKey = fn(key, nonce, ZEROS32);
11501
+ const h = poly1305.create(authKey);
11502
+ if (AAD)
11503
+ updatePadded(h, AAD);
11504
+ updatePadded(h, data);
11505
+ const num = u64Lengths(data.length, AAD ? AAD.length : 0, true);
11506
+ h.update(num);
11507
+ const res = h.digest();
11508
+ clean2(authKey, num);
11509
+ return res;
11510
+ }
11511
+ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
11512
+ const tagLength = 16;
11513
+ return {
11514
+ encrypt(plaintext, output) {
11515
+ const plength = plaintext.length;
11516
+ output = getOutput(plength + tagLength, output, false);
11517
+ output.set(plaintext);
11518
+ const oPlain = output.subarray(0, -tagLength);
11519
+ xorStream(key, nonce, oPlain, oPlain, 1);
11520
+ const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
11521
+ output.set(tag, plength);
11522
+ clean2(tag);
11523
+ return output;
11524
+ },
11525
+ decrypt(ciphertext, output) {
11526
+ output = getOutput(ciphertext.length - tagLength, output, false);
11527
+ const data = ciphertext.subarray(0, -tagLength);
11528
+ const passedTag = ciphertext.subarray(-tagLength);
11529
+ const tag = computeTag(xorStream, key, nonce, data, AAD);
11530
+ if (!equalBytes2(passedTag, tag))
11531
+ throw new Error("invalid tag");
11532
+ output.set(ciphertext.subarray(0, -tagLength));
11533
+ xorStream(key, nonce, output, output, 1);
11534
+ clean2(tag);
11535
+ return output;
11536
+ }
11537
+ };
11538
+ };
11539
+ var chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));
11540
+ var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));
11541
+
11542
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
11543
+ var HMAC = class extends Hash {
11544
+ constructor(hash, _key) {
11545
+ super();
11546
+ this.finished = false;
11547
+ this.destroyed = false;
11548
+ ahash(hash);
11549
+ const key = toBytes(_key);
11550
+ this.iHash = hash.create();
11551
+ if (typeof this.iHash.update !== "function")
11552
+ throw new Error("Expected instance of class which extends utils.Hash");
11553
+ this.blockLen = this.iHash.blockLen;
11554
+ this.outputLen = this.iHash.outputLen;
11555
+ const blockLen = this.blockLen;
11556
+ const pad = new Uint8Array(blockLen);
11557
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
11558
+ for (let i = 0; i < pad.length; i++)
11559
+ pad[i] ^= 54;
11560
+ this.iHash.update(pad);
11561
+ this.oHash = hash.create();
11562
+ for (let i = 0; i < pad.length; i++)
11563
+ pad[i] ^= 54 ^ 92;
11564
+ this.oHash.update(pad);
11565
+ clean(pad);
11566
+ }
11567
+ update(buf) {
11568
+ aexists(this);
11569
+ this.iHash.update(buf);
11570
+ return this;
11571
+ }
11572
+ digestInto(out) {
11573
+ aexists(this);
11574
+ abytes(out, this.outputLen);
11575
+ this.finished = true;
11576
+ this.iHash.digestInto(out);
11577
+ this.oHash.update(out);
11578
+ this.oHash.digestInto(out);
11579
+ this.destroy();
11580
+ }
11581
+ digest() {
11582
+ const out = new Uint8Array(this.oHash.outputLen);
11583
+ this.digestInto(out);
11584
+ return out;
11585
+ }
11586
+ _cloneInto(to) {
11587
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
11588
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
11589
+ to = to;
11590
+ to.finished = finished;
11591
+ to.destroyed = destroyed;
11592
+ to.blockLen = blockLen;
11593
+ to.outputLen = outputLen;
11594
+ to.oHash = oHash._cloneInto(to.oHash);
11595
+ to.iHash = iHash._cloneInto(to.iHash);
11596
+ return to;
11597
+ }
11598
+ clone() {
11599
+ return this._cloneInto();
11600
+ }
11601
+ destroy() {
11602
+ this.destroyed = true;
11603
+ this.oHash.destroy();
11604
+ this.iHash.destroy();
11605
+ }
11606
+ };
11607
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
11608
+ hmac.create = (hash, key) => new HMAC(hash, key);
11609
+
11610
+ // ../../../../linkedclaw/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hkdf.js
11611
+ function extract(hash, ikm, salt) {
11612
+ ahash(hash);
11613
+ if (salt === void 0)
11614
+ salt = new Uint8Array(hash.outputLen);
11615
+ return hmac(hash, toBytes(salt), toBytes(ikm));
11616
+ }
11617
+ var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
11618
+ var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
11619
+ function expand(hash, prk, info, length = 32) {
11620
+ ahash(hash);
11621
+ anumber(length);
11622
+ const olen = hash.outputLen;
11623
+ if (length > 255 * olen)
11624
+ throw new Error("Length should be <= 255*HashLen");
11625
+ const blocks = Math.ceil(length / olen);
11626
+ if (info === void 0)
11627
+ info = EMPTY_BUFFER;
11628
+ const okm = new Uint8Array(blocks * olen);
11629
+ const HMAC2 = hmac.create(hash, prk);
11630
+ const HMACTmp = HMAC2._cloneInto();
11631
+ const T = new Uint8Array(HMAC2.outputLen);
11632
+ for (let counter = 0; counter < blocks; counter++) {
11633
+ HKDF_COUNTER[0] = counter + 1;
11634
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
11635
+ okm.set(T, olen * counter);
11636
+ HMAC2._cloneInto(HMACTmp);
11637
+ }
11638
+ HMAC2.destroy();
11639
+ HMACTmp.destroy();
11640
+ clean(T, HKDF_COUNTER);
11641
+ return okm.slice(0, length);
11642
+ }
11643
+ var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
11644
+
11645
+ // ../../../../linkedclaw/sdk/crypto-ts/dist/index.js
11646
+ var SESSION_INFO_PREFIX = new TextEncoder().encode("linkedclaw/l1/session/v1");
11647
+ var INVOKE_INFO_PREFIX = new TextEncoder().encode("linkedclaw/l1/invoke/v1");
11648
+ var HANDSHAKE_SIG_PREFIX = new TextEncoder().encode("linkedclaw/l1/handshake/v1");
11649
+ var RELEASE_SIG_PREFIX = new TextEncoder().encode("linkedclaw/l1/release/v1");
11650
+ var KEY_LEN = 32;
11651
+ var NONCE_LEN = 24;
11652
+ var PAD_BUCKETS = [256, 1024, 4096, 16384, 65536, 262144];
11653
+ var CryptoError = class extends Error {
11654
+ constructor(message) {
11655
+ super(message);
11656
+ this.name = "CryptoError";
11657
+ }
11658
+ };
11659
+ function sortKeysDeep(obj) {
11660
+ if (obj === null || typeof obj !== "object")
11661
+ return obj;
11662
+ if (Array.isArray(obj))
11663
+ return obj.map(sortKeysDeep);
11664
+ const sorted = {};
11665
+ for (const k of Object.keys(obj).sort()) {
11666
+ sorted[k] = sortKeysDeep(obj[k]);
11667
+ }
11668
+ return sorted;
11669
+ }
11670
+ function canonicalJson(obj) {
11671
+ const compact = JSON.stringify(sortKeysDeep(obj));
11672
+ return compact.replace(/[€-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
11673
+ }
11674
+ function b64url(b) {
11675
+ let bin = "";
11676
+ for (let i = 0; i < b.length; i++)
11677
+ bin += String.fromCharCode(b[i]);
11678
+ const base64 = btoa(bin);
11679
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
11680
+ }
11681
+ function unb64url(s) {
11682
+ const padded = s + "=".repeat(-s.length & 3);
11683
+ const standard = padded.replace(/-/g, "+").replace(/_/g, "/");
11684
+ const bin = atob(standard);
11685
+ const out = new Uint8Array(bin.length);
11686
+ for (let i = 0; i < bin.length; i++)
11687
+ out[i] = bin.charCodeAt(i);
11688
+ return out;
11689
+ }
11690
+ function generateX25519Keypair() {
11691
+ const priv = x25519.utils.randomPrivateKey();
11692
+ const pub = x25519.getPublicKey(priv);
11693
+ return { priv, pub };
11694
+ }
11695
+ function generateEd25519Keypair() {
11696
+ const priv = ed25519.utils.randomPrivateKey();
11697
+ const pub = ed25519.getPublicKey(priv);
11698
+ return { priv, pub };
11699
+ }
11700
+ function x25519PublicFromPrivate(priv) {
11701
+ return x25519.getPublicKey(priv);
11702
+ }
11703
+ function ed25519PublicFromPrivate(priv) {
11704
+ return ed25519.getPublicKey(priv);
11705
+ }
11706
+ function ecdh(privateRaw, peerPublicRaw) {
11707
+ return x25519.getSharedSecret(privateRaw, peerPublicRaw);
11708
+ }
11709
+ function hkdfKey(ikm, info) {
11710
+ return new Uint8Array(hkdf(sha256, ikm, void 0, info, KEY_LEN));
11711
+ }
11712
+ function concat(...arrays) {
11713
+ const total = arrays.reduce((n, a) => n + a.length, 0);
11714
+ const out = new Uint8Array(total);
11715
+ let offset = 0;
11716
+ for (const a of arrays) {
11717
+ out.set(a, offset);
11718
+ offset += a.length;
11719
+ }
11720
+ return out;
11721
+ }
11722
+ function deriveSessionKey(myEphPriv, peerEphPub, requesterEphPub, providerEphPub) {
11723
+ const ikm = ecdh(myEphPriv, peerEphPub);
11724
+ const info = concat(SESSION_INFO_PREFIX, requesterEphPub, providerEphPub);
11725
+ return hkdfKey(ikm, info);
11726
+ }
11727
+ function deriveInvokeKeyRecipient(recipientStaticPriv, senderEphPub, recipientKeyId) {
11728
+ const ikm = ecdh(recipientStaticPriv, senderEphPub);
11729
+ const info = concat(INVOKE_INFO_PREFIX, senderEphPub, new TextEncoder().encode(recipientKeyId));
11730
+ return hkdfKey(ikm, info);
11731
+ }
11732
+ function aeadSealWithNonce(key, nonce, plaintext, aad) {
11733
+ const cipher = xchacha20poly1305(key, nonce, aad);
11734
+ return cipher.encrypt(plaintext);
11735
+ }
11736
+ function aeadSeal(key, plaintext, aad = new Uint8Array(0)) {
11737
+ const nonce = new Uint8Array(NONCE_LEN);
11738
+ crypto.getRandomValues(nonce);
11739
+ const ciphertext = aeadSealWithNonce(key, nonce, plaintext, aad);
11740
+ return { nonce, ciphertext };
11741
+ }
11742
+ function aeadOpen(key, nonce, ciphertext, aad = new Uint8Array(0)) {
11743
+ try {
11744
+ const cipher = xchacha20poly1305(key, nonce, aad);
11745
+ return cipher.decrypt(ciphertext);
11746
+ } catch {
11747
+ throw new CryptoError("AEAD open failed (bad key/nonce/AAD/tag)");
11748
+ }
11749
+ }
11750
+ var LEN_PREFIX = 4;
11751
+ var MAX_BUCKET = PAD_BUCKETS[PAD_BUCKETS.length - 1];
11752
+ function bucketFor(total) {
11753
+ for (const b of PAD_BUCKETS) {
11754
+ if (total <= b)
11755
+ return b;
11756
+ }
11757
+ return Math.ceil(total / MAX_BUCKET) * MAX_BUCKET;
11758
+ }
11759
+ function padFrame(plaintext) {
11760
+ const total = LEN_PREFIX + plaintext.length;
11761
+ const bucket = bucketFor(total);
11762
+ const out = new Uint8Array(bucket);
11763
+ const view = new DataView(out.buffer);
11764
+ view.setUint32(0, plaintext.length, false);
11765
+ out.set(plaintext, LEN_PREFIX);
11766
+ return out;
11767
+ }
11768
+ function unpadFrame(padded) {
11769
+ if (padded.length < LEN_PREFIX) {
11770
+ throw new CryptoError("padded frame too short for length prefix");
11771
+ }
11772
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
11773
+ const n = view.getUint32(0, false);
11774
+ if (LEN_PREFIX + n > padded.length) {
11775
+ throw new CryptoError("declared frame length exceeds padded buffer");
11776
+ }
11777
+ if (padded.length !== bucketFor(LEN_PREFIX + n)) {
11778
+ throw new CryptoError("padded frame length is not a canonical bucket size");
11779
+ }
11780
+ for (let i = LEN_PREFIX + n; i < padded.length; i++) {
11781
+ if (padded[i] !== 0) {
11782
+ throw new CryptoError("non-zero bytes in padding region");
11783
+ }
11784
+ }
11785
+ return padded.slice(LEN_PREFIX, LEN_PREFIX + n);
11786
+ }
11787
+ function sealFrame(key, plaintext, aad = new Uint8Array(0)) {
11788
+ return aeadSeal(key, padFrame(plaintext), aad);
11789
+ }
11790
+ function openFrame(key, nonce, ciphertext, aad = new Uint8Array(0)) {
11791
+ return unpadFrame(aeadOpen(key, nonce, ciphertext, aad));
11792
+ }
11793
+ function signEphemeral(handshakePriv, ephPub) {
11794
+ const msg = concat(HANDSHAKE_SIG_PREFIX, ephPub);
11795
+ return ed25519.sign(msg, handshakePriv);
11796
+ }
11797
+ function signRelease(handshakePriv, sessionId, k) {
11798
+ const msg = concat(RELEASE_SIG_PREFIX, new TextEncoder().encode(sessionId), k);
11799
+ return ed25519.sign(msg, handshakePriv);
11800
+ }
11801
+ var KARCHIVE_INFO_PREFIX = new TextEncoder().encode("linkedclaw/l1/karchive/v1");
11802
+ var MAX_CHUNK_PLAINTEXT = 16380;
11803
+ var MAX_CHUNKS = 256;
11804
+ function buildChunkAad(sessionId, messageKind, senderRole, group, index, total) {
11805
+ const json = canonicalJson({
11806
+ group,
11807
+ index,
11808
+ message_kind: messageKind,
11809
+ sender_role: senderRole,
11810
+ session_id: sessionId,
11811
+ total
11812
+ });
11813
+ return new TextEncoder().encode(json);
11814
+ }
11815
+ function reassembleChunks(parts) {
11816
+ if (parts.length === 0)
11817
+ throw new CryptoError("reassembleChunks: no parts");
11818
+ const totals = new Set(parts.map(([, t]) => t));
11819
+ if (totals.size !== 1)
11820
+ throw new CryptoError("reassembleChunks: inconsistent total across chunks");
11821
+ const total = totals.values().next().value;
11822
+ if (!(total >= 2 && total <= MAX_CHUNKS))
11823
+ throw new CryptoError(`reassembleChunks: total ${total} out of range [2, ${MAX_CHUNKS}]`);
11824
+ if (parts.length !== total)
11825
+ throw new CryptoError(`reassembleChunks: have ${parts.length} chunks, expected ${total}`);
11826
+ const byIndex = /* @__PURE__ */ new Map();
11827
+ for (const [index, , pt] of parts) {
11828
+ if (!(index >= 0 && index < total))
11829
+ throw new CryptoError(`reassembleChunks: index ${index} out of range`);
11830
+ if (byIndex.has(index))
11831
+ throw new CryptoError(`reassembleChunks: duplicate index ${index}`);
11832
+ byIndex.set(index, pt);
11833
+ }
11834
+ let outLen = 0;
11835
+ for (let i = 0; i < total; i++) {
11836
+ const c = byIndex.get(i);
11837
+ if (!c)
11838
+ throw new CryptoError("reassembleChunks: indices are not a complete contiguous run");
11839
+ outLen += c.length;
11840
+ }
11841
+ const out = new Uint8Array(outLen);
11842
+ let off = 0;
11843
+ for (let i = 0; i < total; i++) {
11844
+ const c = byIndex.get(i);
11845
+ out.set(c, off);
11846
+ off += c.length;
11847
+ }
11848
+ return out;
11849
+ }
11850
+ function sealChunkedMessage(k, plaintext, opts) {
11851
+ const { messageKind, senderRole, sessionId } = opts;
11852
+ if (plaintext.length <= MAX_CHUNK_PLAINTEXT) {
11853
+ const aad = new TextEncoder().encode(canonicalJson({ message_kind: messageKind, sender_role: senderRole, session_id: sessionId }));
11854
+ const { nonce, ciphertext } = sealFrame(k, plaintext, aad);
11855
+ return [{ type: "sealed", nonce: b64url(nonce), ciphertext: b64url(ciphertext) }];
11856
+ }
11857
+ const total = Math.ceil(plaintext.length / MAX_CHUNK_PLAINTEXT);
11858
+ if (total > MAX_CHUNKS)
11859
+ throw new CryptoError(`sealChunkedMessage: ${total} chunks exceeds MAX_CHUNKS ${MAX_CHUNKS}`);
11860
+ const groupBytes = new Uint8Array(16);
11861
+ crypto.getRandomValues(groupBytes);
11862
+ const group = b64url(groupBytes);
11863
+ const frames = [];
11864
+ for (let index = 0; index < total; index++) {
11865
+ const part = plaintext.subarray(index * MAX_CHUNK_PLAINTEXT, (index + 1) * MAX_CHUNK_PLAINTEXT);
11866
+ const aad = buildChunkAad(sessionId, messageKind, senderRole, group, index, total);
11867
+ const { nonce, ciphertext } = sealFrame(k, part, aad);
11868
+ frames.push({ type: "sealed", nonce: b64url(nonce), ciphertext: b64url(ciphertext), chunk: { group, index, total } });
11869
+ }
11870
+ return frames;
11871
+ }
11872
+
11873
+ // ../../../../linkedclaw/sdk/keystore-ts/dist/index.js
11874
+ import { randomBytes as randomBytes2 } from "crypto";
11875
+ import { closeSync, linkSync, mkdirSync, openSync, readFileSync as readFileSync2, unlinkSync as unlinkSync2, writeSync } from "fs";
11876
+ import { dirname } from "path";
11877
+ function makeIdentity(ed25519Private, keyId, x25519Private) {
11878
+ const ident = {
11879
+ ed25519Private,
11880
+ keyId,
11881
+ x25519Private,
11882
+ get ed25519Public() {
11883
+ return ed25519PublicFromPrivate(this.ed25519Private);
11884
+ },
11885
+ get x25519Public() {
11886
+ return this.x25519Private === void 0 ? void 0 : x25519PublicFromPrivate(this.x25519Private);
11887
+ }
11888
+ };
11889
+ return ident;
11890
+ }
11891
+ function loadOrCreateIdentity(path, opts = {}) {
11892
+ const existing = _internals.tryLoad(path);
11893
+ if (existing !== void 0) {
11894
+ return existing;
11895
+ }
11896
+ const { priv: edPriv } = generateEd25519Keypair();
11897
+ const xPriv = opts.withX25519 ? generateX25519Keypair().priv : void 0;
11898
+ const keyId = `k1_${randomBytes2(6).toString("hex")}`;
11899
+ const record = { ed25519_priv: b64url(edPriv), key_id: keyId };
11900
+ if (xPriv !== void 0) {
11901
+ record.x25519_priv = b64url(xPriv);
11902
+ }
11903
+ if (exclusiveWriteJson(path, record)) {
11904
+ return makeIdentity(edPriv, keyId, xPriv);
11905
+ }
11906
+ const winner = _internals.tryLoad(path);
11907
+ if (winner === void 0) {
11908
+ throw new Error(`key store at ${JSON.stringify(path)} reported as existing but could not be read`);
11909
+ }
11910
+ return winner;
11911
+ }
11912
+ function tryLoad(path) {
11913
+ let raw;
11914
+ try {
11915
+ raw = readFileSync2(path, "utf8");
11916
+ } catch (err) {
11917
+ if (err.code === "ENOENT") {
11918
+ return void 0;
11919
+ }
11920
+ throw err;
11921
+ }
11922
+ const data = JSON.parse(raw);
11923
+ const xRaw = data.x25519_priv;
11924
+ return makeIdentity(unb64url(data.ed25519_priv), data.key_id, xRaw ? unb64url(xRaw) : void 0);
11925
+ }
11926
+ function exclusiveWriteJson(path, record) {
11927
+ const dir = dirname(path);
11928
+ mkdirSync(dir, { recursive: true });
11929
+ const tmp = `${dir}/.tmp_keystore_${randomBytes2(8).toString("hex")}`;
11930
+ const fd = openSync(tmp, "wx");
11931
+ try {
11932
+ try {
11933
+ writeSync(fd, JSON.stringify(record));
11934
+ } finally {
11935
+ closeSync(fd);
11936
+ }
11937
+ try {
11938
+ linkSync(tmp, path);
11939
+ } catch (err) {
11940
+ if (err.code === "EEXIST") {
11941
+ return false;
11942
+ }
11943
+ throw err;
11944
+ }
11945
+ return true;
11946
+ } finally {
11947
+ try {
11948
+ unlinkSync2(tmp);
11949
+ } catch {
11950
+ }
11951
+ }
11952
+ }
11953
+ var _internals = { tryLoad };
11954
+
11955
+ // ../../../../linkedclaw/sdk/provider-runtime-ts/dist/index.js
8494
11956
  var NetworkError = class extends Error {
8495
11957
  constructor(message, cause) {
8496
11958
  super(message);
@@ -8781,6 +12243,77 @@ var HandlerError = class extends Error {
8781
12243
  this.code = code;
8782
12244
  }
8783
12245
  };
12246
+ var CHUNK_RUN_TIMEOUT_MS = 6e4;
12247
+ var ChunkRunBuffer = class {
12248
+ key;
12249
+ sessionId;
12250
+ timeoutMs;
12251
+ group = null;
12252
+ total = null;
12253
+ senderRole = null;
12254
+ expected = 0;
12255
+ parts = [];
12256
+ deadline = 0;
12257
+ constructor(key, sessionId, timeoutMs = CHUNK_RUN_TIMEOUT_MS) {
12258
+ this.key = key;
12259
+ this.sessionId = sessionId;
12260
+ this.timeoutMs = timeoutMs;
12261
+ }
12262
+ get inProgress() {
12263
+ return this.group !== null;
12264
+ }
12265
+ reset() {
12266
+ this.group = null;
12267
+ this.total = null;
12268
+ this.senderRole = null;
12269
+ this.expected = 0;
12270
+ this.parts = [];
12271
+ this.deadline = 0;
12272
+ }
12273
+ feed(frame, senderRole) {
12274
+ const chunk = frame.chunk;
12275
+ const { group, index, total } = chunk;
12276
+ const now = Date.now();
12277
+ if (this.group === null) {
12278
+ if (index !== 0) throw new CryptoError("chunk run must start at index 0");
12279
+ if (typeof total !== "number" || total < 2 || total > MAX_CHUNKS)
12280
+ throw new CryptoError(`invalid chunk total ${total}`);
12281
+ this.group = group;
12282
+ this.total = total;
12283
+ this.senderRole = senderRole;
12284
+ this.deadline = now + this.timeoutMs;
12285
+ } else {
12286
+ if (now > this.deadline) {
12287
+ this.reset();
12288
+ throw new CryptoError("chunk run timed out");
12289
+ }
12290
+ if (group !== this.group || total !== this.total) {
12291
+ this.reset();
12292
+ throw new CryptoError("chunk group/total mismatch");
12293
+ }
12294
+ if (senderRole !== this.senderRole) {
12295
+ this.reset();
12296
+ throw new CryptoError("chunk sender role mismatch");
12297
+ }
12298
+ if (index !== this.expected) {
12299
+ this.reset();
12300
+ throw new CryptoError("chunk index gap/reorder");
12301
+ }
12302
+ }
12303
+ const aad = buildChunkAad(this.sessionId, "human_message", this.senderRole, group, index, total);
12304
+ const nonce = unb64url(frame.nonce);
12305
+ const ciphertext = unb64url(frame.ciphertext);
12306
+ const pt = openFrame(this.key, nonce, ciphertext, aad);
12307
+ this.parts.push([index, total, pt]);
12308
+ this.expected += 1;
12309
+ if (index === total - 1) {
12310
+ const joined = reassembleChunks(this.parts);
12311
+ this.reset();
12312
+ return joined;
12313
+ }
12314
+ return null;
12315
+ }
12316
+ };
8784
12317
  var DEFAULT_INVOKE_TIMEOUT_MS = 3e4;
8785
12318
  var DEFAULT_SESSION_TURN_TIMEOUT_MS = 6e4;
8786
12319
  var DEFAULT_GIG_TASK_OFFER_TIMEOUT_MS = 3e4;
@@ -8793,6 +12326,9 @@ var ProviderRuntime = class {
8793
12326
  relay;
8794
12327
  handler;
8795
12328
  config;
12329
+ kArchive;
12330
+ registration;
12331
+ onEvent;
8796
12332
  activeSessions = /* @__PURE__ */ new Map();
8797
12333
  inFlightInvokes = /* @__PURE__ */ new Set();
8798
12334
  inFlightGigTasks = /* @__PURE__ */ new Set();
@@ -8804,6 +12340,164 @@ var ProviderRuntime = class {
8804
12340
  this.relay = deps.relay;
8805
12341
  this.handler = deps.handler;
8806
12342
  this.config = deps.config;
12343
+ this.kArchive = deps.kArchive;
12344
+ this.registration = deps.registration;
12345
+ this.onEvent = deps.onEvent;
12346
+ }
12347
+ emitEvent(name, detail = {}) {
12348
+ if (!this.onEvent) return;
12349
+ try {
12350
+ this.onEvent(name, detail);
12351
+ } catch {
12352
+ }
12353
+ }
12354
+ /**
12355
+ * Resolve the L1 key-store file path (R3). Explicit `keyStorePath` wins; else derive
12356
+ * `<configDir>/identity.json`; else `null` — the in-process-keys fallback (NOT
12357
+ * restart-safe). Mirrors py `ProviderSkill._key_store_path`.
12358
+ */
12359
+ keyStorePath() {
12360
+ if (this.config.keyStorePath) return this.config.keyStorePath;
12361
+ if (this.config.configDir) return join2(this.config.configDir, "identity.json");
12362
+ return null;
12363
+ }
12364
+ /**
12365
+ * Load the durable L1 handshake identity (R3): the key store is the SOLE authoritative
12366
+ * source, so keys are NEVER regenerated across restart — the published public half
12367
+ * always matches the held private half (closes #24).
12368
+ *
12369
+ * Migration (R-2): if the store is absent but the config carries legacy caller-supplied
12370
+ * keys, SEED the store from them once (regenerating mid-migration IS the mismatch we're
12371
+ * fixing), then load from the store — the store then wins and the config key fields are
12372
+ * no longer trusted. When no path is available, fall back to in-process generated keys
12373
+ * (back-compat, NOT restart-safe) with a loud warning.
12374
+ *
12375
+ * Returns { x25519Priv, ed25519Priv, keyId }.
12376
+ */
12377
+ loadL1Identity() {
12378
+ const path = this.keyStorePath();
12379
+ if (path === null) {
12380
+ console.warn(
12381
+ "ProviderRuntime.register: no key-store path (set config.keyStorePath or config.configDir) \u2014 generating in-process L1 keys that do NOT survive a restart; the published handshake key will diverge on the next boot"
12382
+ );
12383
+ const ed25519Priv = generateEd25519Keypair().priv;
12384
+ const x25519Priv = generateX25519Keypair().priv;
12385
+ return { x25519Priv, ed25519Priv, keyId: `k1_${randomBytes3(6).toString("hex")}` };
12386
+ }
12387
+ if (!existsSync2(path) && this.config.x25519PrivateKey && this.config.ed25519HandshakePrivateKey) {
12388
+ this.seedKeyStore(path);
12389
+ }
12390
+ const ident = loadOrCreateIdentity(path, { withX25519: true });
12391
+ if (ident.x25519Private === void 0) {
12392
+ throw new Error(`key store at ${JSON.stringify(path)} has no x25519 key \u2014 provider L1 requires both halves`);
12393
+ }
12394
+ return { x25519Priv: ident.x25519Private, ed25519Priv: ident.ed25519Private, keyId: ident.keyId };
12395
+ }
12396
+ /**
12397
+ * Write the legacy caller-supplied keys into the key store verbatim (no regen), using
12398
+ * the same on-disk format as @linkedclaw/keystore so a subsequent loadOrCreateIdentity
12399
+ * reads them back unchanged. Atomic via tmp+rename. Mirrors py `_seed_key_store`.
12400
+ */
12401
+ seedKeyStore(path) {
12402
+ const record = {
12403
+ ed25519_priv: this.config.ed25519HandshakePrivateKey,
12404
+ // already b64url
12405
+ key_id: this.config.encKeyId || "k1_default",
12406
+ x25519_priv: this.config.x25519PrivateKey
12407
+ };
12408
+ const dir = dirname2(path);
12409
+ mkdirSync2(dir, { recursive: true });
12410
+ const tmp = join2(dir, `.tmp_keystore_seed_${randomBytes3(8).toString("hex")}`);
12411
+ const fd = openSync2(tmp, "wx");
12412
+ try {
12413
+ writeSync2(fd, JSON.stringify(record));
12414
+ } finally {
12415
+ closeSync2(fd);
12416
+ }
12417
+ renameSync2(tmp, path);
12418
+ }
12419
+ /**
12420
+ * Register (or reconcile) this provider's listing, persisting + always re-publishing the
12421
+ * L1 `encryption_key` derived from the held private key (R3). Idempotent: a daemon
12422
+ * restart re-lists, finds its own listing by slug, and PUTs to reuse — never 409s itself
12423
+ * out. Mirrors py `ProviderSkill.register`. Returns the agent_id.
12424
+ */
12425
+ async register() {
12426
+ if (!this.registration) {
12427
+ throw new Error("register(): no registration client injected (deps.registration)");
12428
+ }
12429
+ if (!this.config.agentSlug) {
12430
+ throw new Error("register(): config.agentSlug is required to reconcile the listing");
12431
+ }
12432
+ const { x25519Priv, ed25519Priv, keyId } = this.loadL1Identity();
12433
+ this.config.x25519PrivateKey = b64url(x25519Priv);
12434
+ this.config.ed25519HandshakePrivateKey = b64url(ed25519Priv);
12435
+ this.config.encKeyId = keyId;
12436
+ const expiresAt = new Date(Date.now() + 730 * 24 * 60 * 60 * 1e3).toISOString();
12437
+ const encryptionKey = {
12438
+ x25519_public_key: b64url(x25519PublicFromPrivate(x25519Priv)),
12439
+ ed25519_handshake_key: b64url(ed25519PublicFromPrivate(ed25519Priv)),
12440
+ key_id: keyId,
12441
+ expires_at: expiresAt
12442
+ };
12443
+ const existing = await this.findOwnListing();
12444
+ if (existing !== void 0) {
12445
+ return this.reuseExistingListing(existing, encryptionKey);
12446
+ }
12447
+ const body = {
12448
+ slug: this.config.agentSlug,
12449
+ name: this.config.agentName ?? this.config.agentSlug,
12450
+ description: this.config.agentDescription ?? "",
12451
+ capabilities: this.config.capabilities ?? [],
12452
+ status: "online",
12453
+ encryption_key: encryptionKey
12454
+ };
12455
+ if (this.config.forkPolicy !== void 0) body.fork_policy = this.config.forkPolicy;
12456
+ if (this.config.capabilitiesMeta !== void 0) body.capabilities_meta = this.config.capabilitiesMeta;
12457
+ let created;
12458
+ try {
12459
+ created = await this.registration.create(body);
12460
+ } catch (err) {
12461
+ if (err.status === 409) {
12462
+ const raced = await this.findOwnListing();
12463
+ if (raced !== void 0) {
12464
+ return this.reuseExistingListing(raced, encryptionKey);
12465
+ }
12466
+ }
12467
+ throw err;
12468
+ }
12469
+ const agentId = String(created.agent_id ?? "");
12470
+ this.config.agentId = agentId;
12471
+ return agentId;
12472
+ }
12473
+ /**
12474
+ * Reconcile an existing listing to our current state via replace (PUT). ALWAYS
12475
+ * re-publishes the L1 key block so the published public half can never diverge from the
12476
+ * held private half (the #24 bug). Safe and idempotent ONLY because the key store
12477
+ * guarantees we loaded the same key across restart — the server treats an unchanged
12478
+ * (key_id, x25519_public_key) as a no-op. A *deliberate* key rotation must therefore go
12479
+ * through a distinct path (replace the key store), NEVER a restart; restart re-publish
12480
+ * == no-op. Called from both the normal reuse branch AND the 409 race-recovery branch.
12481
+ * Mirrors py `_reuse_existing_listing`.
12482
+ */
12483
+ async reuseExistingListing(existing, encryptionKey) {
12484
+ const agentId = String(existing.agent_id ?? "");
12485
+ this.config.agentId = agentId;
12486
+ const update = {
12487
+ name: this.config.agentName ?? this.config.agentSlug,
12488
+ description: this.config.agentDescription ?? "",
12489
+ capabilities: this.config.capabilities ?? [],
12490
+ status: "online",
12491
+ encryption_key: encryptionKey
12492
+ };
12493
+ if (this.config.capabilitiesMeta !== void 0) update.capabilities_meta = this.config.capabilitiesMeta;
12494
+ await this.registration.replace(agentId, update);
12495
+ return agentId;
12496
+ }
12497
+ /** Return this runtime's existing listing (matched by slug) or undefined. */
12498
+ async findOwnListing() {
12499
+ const listings = await this.registration.listOwn();
12500
+ return listings.find((a) => a.slug === this.config.agentSlug);
8807
12501
  }
8808
12502
  /**
8809
12503
  * Connect the relay and start dispatching inbound events. Resolves once the
@@ -8835,9 +12529,11 @@ var ProviderRuntime = class {
8835
12529
  this.relay.on("connected", () => {
8836
12530
  this.connected = true;
8837
12531
  this.fatal = null;
12532
+ this.emitEvent("connected", { agentId: this.config.agentId });
8838
12533
  });
8839
- this.relay.on("disconnected", () => {
12534
+ this.relay.on("disconnected", (reason) => {
8840
12535
  this.connected = false;
12536
+ this.emitEvent("disconnected", { reason });
8841
12537
  });
8842
12538
  this.relay.on("fatal", (info) => {
8843
12539
  this.fatal = info;
@@ -8853,6 +12549,22 @@ var ProviderRuntime = class {
8853
12549
  }
8854
12550
  async stop() {
8855
12551
  this.running = false;
12552
+ if (this.activeSessions.size > 0) {
12553
+ this.emitEvent("draining", { live_sessions: this.activeSessions.size });
12554
+ }
12555
+ if (this.handler.onSessionEnd) {
12556
+ for (const sessionId of [...this.activeSessions.keys()]) {
12557
+ try {
12558
+ await this.handler.onSessionEnd({
12559
+ type: "session.end",
12560
+ session_id: sessionId,
12561
+ reason: "provider_shutdown"
12562
+ });
12563
+ } catch {
12564
+ }
12565
+ }
12566
+ }
12567
+ this.activeSessions.clear();
8856
12568
  await this.relay.stop();
8857
12569
  this.connected = false;
8858
12570
  }
@@ -8941,21 +12653,74 @@ var ProviderRuntime = class {
8941
12653
  });
8942
12654
  return;
8943
12655
  }
8944
- this.activeSessions.set(evt.session_id, {
12656
+ const activeSession = {
8945
12657
  requesterId: evt.requester_id,
8946
12658
  capability: evt.capability,
8947
12659
  replySeq: 0
8948
- });
8949
- await this.send({ type: MessageType.SESSION_ACCEPT, session_id: evt.session_id });
12660
+ };
12661
+ const acceptExtras = {};
12662
+ const reqEphB64 = evt.eph_enc_pub;
12663
+ if (reqEphB64 && this.config.x25519PrivateKey && this.config.ed25519HandshakePrivateKey) {
12664
+ const reqEph = unb64url(reqEphB64);
12665
+ const { priv: pephPriv, pub: pephPub } = generateX25519Keypair();
12666
+ const psig = signEphemeral(unb64url(this.config.ed25519HandshakePrivateKey), pephPub);
12667
+ const K = deriveSessionKey(pephPriv, reqEph, reqEph, pephPub);
12668
+ activeSession.K = K;
12669
+ this.kArchive?.put(evt.session_id, K);
12670
+ acceptExtras.eph_enc_pub = b64url(pephPub);
12671
+ acceptExtras.eph_enc_sig = b64url(psig);
12672
+ }
12673
+ this.activeSessions.set(evt.session_id, activeSession);
12674
+ await this.send({ type: MessageType.SESSION_ACCEPT, session_id: evt.session_id, ...acceptExtras });
12675
+ this.emitEvent("session_accepted", { session_id: evt.session_id, requester_id: evt.requester_id });
8950
12676
  }
8951
12677
  async handleSessionMessage(evt) {
8952
12678
  const session = this.activeSessions.get(evt.session_id);
8953
12679
  if (!session) return;
8954
12680
  const timeout = this.config.sessionTurnTimeoutMs ?? DEFAULT_SESSION_TURN_TIMEOUT_MS;
12681
+ let handlerEvt = evt;
12682
+ if (session.K) {
12683
+ if (!session.chunkBuffer) {
12684
+ session.chunkBuffer = new ChunkRunBuffer(session.K, evt.session_id, timeout);
12685
+ }
12686
+ const p = evt.payload;
12687
+ if (p && p.type === "sealed") {
12688
+ try {
12689
+ if (p.chunk) {
12690
+ const joined = session.chunkBuffer.feed(p, "requester");
12691
+ if (joined === null) return;
12692
+ const opened = JSON.parse(new TextDecoder().decode(joined));
12693
+ handlerEvt = { ...evt, payload: opened };
12694
+ } else {
12695
+ if (session.chunkBuffer.inProgress) {
12696
+ throw new CryptoError("standalone frame interleaved into chunk run");
12697
+ }
12698
+ const K = session.K;
12699
+ const nonce = unb64url(p.nonce);
12700
+ const ciphertext = unb64url(p.ciphertext);
12701
+ const aad = new TextEncoder().encode(
12702
+ canonicalJson({ message_kind: "human_message", sender_role: "requester", session_id: evt.session_id })
12703
+ );
12704
+ const plaintext = openFrame(K, nonce, ciphertext, aad);
12705
+ const opened = JSON.parse(new TextDecoder().decode(plaintext));
12706
+ handlerEvt = { ...evt, payload: opened };
12707
+ }
12708
+ } catch (err) {
12709
+ if (!(err instanceof CryptoError)) throw err;
12710
+ await this.send({
12711
+ type: MessageType.SESSION_END,
12712
+ session_id: evt.session_id,
12713
+ reason: "sealed_frame_invalid"
12714
+ });
12715
+ this.activeSessions.delete(evt.session_id);
12716
+ return;
12717
+ }
12718
+ }
12719
+ }
8955
12720
  let reply;
8956
12721
  try {
8957
12722
  reply = await withTimeout(
8958
- Promise.resolve(this.handler.onSessionMessage(this.scopeInbound(evt))),
12723
+ Promise.resolve(this.handler.onSessionMessage(this.scopeInbound(handlerEvt))),
8959
12724
  timeout,
8960
12725
  "session_turn_timeout"
8961
12726
  );
@@ -8969,14 +12734,33 @@ var ProviderRuntime = class {
8969
12734
  return;
8970
12735
  }
8971
12736
  if (reply === null || reply === void 0) return;
8972
- const { payload, seq } = normalizeReply(reply, session.replySeq + 1);
8973
- session.replySeq = seq;
8974
- await this.send({
8975
- type: MessageType.SESSION_MESSAGE,
8976
- session_id: evt.session_id,
8977
- seq,
8978
- payload: this.sanitizeOut(payload)
8979
- });
12737
+ const { payload } = normalizeReply(reply, session.replySeq + 1);
12738
+ const sanitizedPayload = this.sanitizeOut(payload);
12739
+ if (session.K) {
12740
+ const K = session.K;
12741
+ const frames = sealChunkedMessage(K, new TextEncoder().encode(JSON.stringify(sanitizedPayload)), {
12742
+ messageKind: "human_message",
12743
+ senderRole: "provider",
12744
+ sessionId: evt.session_id
12745
+ });
12746
+ for (const fr of frames) {
12747
+ session.replySeq += 1;
12748
+ await this.send({
12749
+ type: MessageType.SESSION_MESSAGE,
12750
+ session_id: evt.session_id,
12751
+ seq: session.replySeq,
12752
+ payload: fr
12753
+ });
12754
+ }
12755
+ } else {
12756
+ session.replySeq += 1;
12757
+ await this.send({
12758
+ type: MessageType.SESSION_MESSAGE,
12759
+ session_id: evt.session_id,
12760
+ seq: session.replySeq,
12761
+ payload: sanitizedPayload
12762
+ });
12763
+ }
8980
12764
  }
8981
12765
  async handleSessionEnd(evt) {
8982
12766
  this.activeSessions.delete(evt.session_id);
@@ -8999,10 +12783,38 @@ var ProviderRuntime = class {
8999
12783
  }
9000
12784
  this.inFlightInvokes.add(evt.invoke_id);
9001
12785
  const timeoutMs = (evt.timeout_seconds !== void 0 ? evt.timeout_seconds * 1e3 : this.config.invokeTimeoutMs) ?? DEFAULT_INVOKE_TIMEOUT_MS;
12786
+ const ephSenderPubB64 = evt.eph_sender_pub;
12787
+ let invokeKAndEph;
12788
+ let handlerEvt = evt;
12789
+ if (ephSenderPubB64 && evt.nonce && evt.ciphertext && this.config.x25519PrivateKey && this.config.encKeyId) {
12790
+ try {
12791
+ const ephSenderPub = unb64url(ephSenderPubB64);
12792
+ const K_invoke = deriveInvokeKeyRecipient(
12793
+ unb64url(this.config.x25519PrivateKey),
12794
+ ephSenderPub,
12795
+ this.config.encKeyId
12796
+ );
12797
+ const nonce = unb64url(evt.nonce);
12798
+ const ciphertext = unb64url(evt.ciphertext);
12799
+ const plaintext = openFrame(K_invoke, nonce, ciphertext, ephSenderPub);
12800
+ const opened = JSON.parse(new TextDecoder().decode(plaintext));
12801
+ handlerEvt = { ...evt, input: opened };
12802
+ invokeKAndEph = { K: K_invoke, ephSenderPub };
12803
+ } catch (err) {
12804
+ if (!(err instanceof CryptoError)) throw err;
12805
+ this.inFlightInvokes.delete(evt.invoke_id);
12806
+ await this.send({
12807
+ type: MessageType.INVOKE_RESULT,
12808
+ invoke_id: evt.invoke_id,
12809
+ error: { code: "sealed_frame_invalid", message: "sealed invoke frame could not be decrypted" }
12810
+ });
12811
+ return;
12812
+ }
12813
+ }
9002
12814
  let result;
9003
12815
  try {
9004
12816
  result = await withTimeout(
9005
- Promise.resolve(this.handler.onInvoke(this.scopeInbound(evt))),
12817
+ Promise.resolve(this.handler.onInvoke(this.scopeInbound(handlerEvt))),
9006
12818
  timeoutMs,
9007
12819
  "invoke_timeout"
9008
12820
  );
@@ -9023,7 +12835,20 @@ var ProviderRuntime = class {
9023
12835
  if (result.error) {
9024
12836
  frame.error = result.error;
9025
12837
  } else {
9026
- frame.result = this.sanitizeOut(result.output ?? {});
12838
+ const sanitizedOutput = this.sanitizeOut(result.output ?? {});
12839
+ if (invokeKAndEph) {
12840
+ const { K, ephSenderPub } = invokeKAndEph;
12841
+ const { nonce, ciphertext } = sealFrame(
12842
+ K,
12843
+ new TextEncoder().encode(JSON.stringify(sanitizedOutput)),
12844
+ ephSenderPub
12845
+ );
12846
+ frame.eph_sender_pub = b64url(ephSenderPub);
12847
+ frame.nonce = b64url(nonce);
12848
+ frame.ciphertext = b64url(ciphertext);
12849
+ } else {
12850
+ frame.result = sanitizedOutput;
12851
+ }
9027
12852
  }
9028
12853
  await this.send(frame);
9029
12854
  }
@@ -9109,6 +12934,46 @@ var ProviderRuntime = class {
9109
12934
  await new Promise((r) => setTimeout(r, jitter));
9110
12935
  }
9111
12936
  }
12937
+ /**
12938
+ * Release this session's K to the arbiter (R5 dispute-unlock). Retrieves K from
12939
+ * live session state, falling back to the injected archive (survives a restart),
12940
+ * signs it with the provider's Ed25519 handshake key, and POSTs the existing
12941
+ * /api/v1/sessions/{id}/release-key endpoint. Fail-loud if K or keys are absent.
12942
+ */
12943
+ async releaseKey(sessionId) {
12944
+ const networkUrl = this.config.networkUrl;
12945
+ if (!networkUrl) throw new Error("releaseKey: networkUrl not configured");
12946
+ const apiKey = this.config.apiKey;
12947
+ if (!apiKey) throw new Error("releaseKey: apiKey not configured");
12948
+ const privB64 = this.config.ed25519HandshakePrivateKey;
12949
+ if (!privB64) throw new Error("releaseKey: ed25519HandshakePrivateKey not configured");
12950
+ const keyId = this.config.encKeyId;
12951
+ if (!keyId) throw new Error("releaseKey: encKeyId not configured");
12952
+ const live = this.activeSessions.get(sessionId);
12953
+ const k = live?.K ?? this.kArchive?.get(sessionId) ?? null;
12954
+ if (!k) throw new Error(`releaseKey: no K available for session ${sessionId}`);
12955
+ const handshakePriv = unb64url(privB64);
12956
+ const handshakePub = ed25519PublicFromPrivate(handshakePriv);
12957
+ const sig = signRelease(handshakePriv, sessionId, k);
12958
+ const body = {
12959
+ session_key: b64url(k),
12960
+ key_id: keyId,
12961
+ releaser_handshake_pub: b64url(handshakePub),
12962
+ signature: b64url(sig)
12963
+ };
12964
+ const res = await fetch(`${networkUrl}/api/v1/sessions/${sessionId}/release-key`, {
12965
+ method: "POST",
12966
+ headers: {
12967
+ "content-type": "application/json",
12968
+ authorization: `Bearer ${apiKey}`
12969
+ },
12970
+ body: JSON.stringify(body)
12971
+ });
12972
+ if (!res.ok) {
12973
+ throw new Error(`releaseKey: server returned ${res.status} ${res.statusText}`);
12974
+ }
12975
+ return res.json();
12976
+ }
9112
12977
  async send(frame) {
9113
12978
  await this.relay.send(frame);
9114
12979
  }
@@ -9153,19 +13018,19 @@ function escapeRegex(s) {
9153
13018
  }
9154
13019
 
9155
13020
  // src/cli-config.ts
9156
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
13021
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
9157
13022
  import { homedir as homedir2 } from "os";
9158
- import { join as join2 } from "path";
13023
+ import { join as join3 } from "path";
9159
13024
  function resolveCliConfigPath() {
9160
- const dir = process.env["LINKEDCLAW_CONFIG_DIR"] ?? join2(homedir2(), ".linkedclaw");
9161
- return join2(dir, "config.yaml");
13025
+ const dir = process.env["LINKEDCLAW_CONFIG_DIR"] ?? join3(homedir2(), ".linkedclaw");
13026
+ return join3(dir, "config.yaml");
9162
13027
  }
9163
13028
  var BORROWABLE_KEYS = /* @__PURE__ */ new Set(["apiKey", "cloudUrl", "relayUrl"]);
9164
13029
  function readCliConfig(path = resolveCliConfigPath()) {
9165
- if (!existsSync2(path)) return {};
13030
+ if (!existsSync3(path)) return {};
9166
13031
  let raw;
9167
13032
  try {
9168
- raw = readFileSync2(path, "utf8");
13033
+ raw = readFileSync3(path, "utf8");
9169
13034
  } catch {
9170
13035
  return {};
9171
13036
  }
@@ -9449,6 +13314,10 @@ var ProviderHolder = class {
9449
13314
  await runtime.run();
9450
13315
  this.runtime = runtime;
9451
13316
  } catch (err) {
13317
+ try {
13318
+ await runtime.stop();
13319
+ } catch {
13320
+ }
9452
13321
  this.runtime = null;
9453
13322
  throw err;
9454
13323
  }
@@ -9775,4 +13644,20 @@ export {
9775
13644
  redactApiKey,
9776
13645
  registerLinkedClawPlugin
9777
13646
  };
13647
+ /*! Bundled license information:
13648
+
13649
+ @noble/hashes/esm/utils.js:
13650
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
13651
+
13652
+ @noble/curves/esm/utils.js:
13653
+ @noble/curves/esm/abstract/modular.js:
13654
+ @noble/curves/esm/abstract/curve.js:
13655
+ @noble/curves/esm/abstract/edwards.js:
13656
+ @noble/curves/esm/abstract/montgomery.js:
13657
+ @noble/curves/esm/ed25519.js:
13658
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
13659
+
13660
+ @noble/ciphers/esm/utils.js:
13661
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
13662
+ */
9778
13663
  //# sourceMappingURL=index.js.map