@blockcast/mmt-container 0.4.1 → 0.5.0-main.2c1f81817995

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +2 -2
  2. package/dist/browser-runtime.js +3458 -356
  3. package/dist/browser-runtime.js.map +4 -4
  4. package/dist/cmcd-producer.d.ts +5 -1
  5. package/dist/cmcd-producer.d.ts.map +1 -1
  6. package/dist/cmcd-producer.js.map +2 -2
  7. package/dist/delivery-catalog.js +18 -2
  8. package/dist/delivery-catalog.js.map +2 -2
  9. package/dist/fec-manager.d.ts +21 -16
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +177 -80
  12. package/dist/fec-manager.js.map +3 -3
  13. package/dist/held-layer-admission.d.ts +58 -0
  14. package/dist/held-layer-admission.d.ts.map +1 -0
  15. package/dist/held-layer-admission.js +105 -0
  16. package/dist/held-layer-admission.js.map +7 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +2 -2
  19. package/dist/mmtp-container-parser.no-modules.js +2682 -1023
  20. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  21. package/dist/mmtp-fec-session.d.ts +36 -3
  22. package/dist/mmtp-fec-session.d.ts.map +1 -1
  23. package/dist/mmtp-fec-session.js +114 -5
  24. package/dist/mmtp-fec-session.js.map +3 -3
  25. package/dist/mmtp-router.d.ts +72 -28
  26. package/dist/mmtp-router.d.ts.map +1 -1
  27. package/dist/mmtp-router.js +321 -203
  28. package/dist/mmtp-router.js.map +2 -2
  29. package/dist/multicast-auth-catalog.d.ts +10 -2
  30. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  31. package/dist/multicast-auth-catalog.js +422 -22
  32. package/dist/multicast-auth-catalog.js.map +4 -4
  33. package/dist/multicast-manager.d.ts +48 -9
  34. package/dist/multicast-manager.d.ts.map +1 -1
  35. package/dist/multicast-manager.js +3406 -340
  36. package/dist/multicast-manager.js.map +4 -4
  37. package/dist/multicast-transport.d.ts +4 -1
  38. package/dist/multicast-transport.d.ts.map +1 -1
  39. package/dist/multicast-transport.js +20 -3
  40. package/dist/multicast-transport.js.map +2 -2
  41. package/dist/no-modules.d.ts +1 -2
  42. package/dist/no-modules.d.ts.map +1 -1
  43. package/dist/no-modules.js +2668 -1007
  44. package/dist/no-modules.js.map +4 -4
  45. package/dist/repair-fetch.d.ts +10 -1
  46. package/dist/repair-fetch.d.ts.map +1 -1
  47. package/dist/repair-fetch.js +5 -2
  48. package/dist/repair-fetch.js.map +2 -2
  49. package/package.json +5 -14
  50. package/src/cmcd-producer.ts +6 -1
  51. package/src/fec-manager.ts +121 -131
  52. package/src/held-layer-admission.ts +161 -0
  53. package/src/index.ts +5 -9
  54. package/src/mmtp-fec-session.ts +76 -3
  55. package/src/mmtp-router.ts +390 -272
  56. package/src/multicast-auth-catalog.ts +81 -8
  57. package/src/multicast-manager.ts +189 -48
  58. package/src/multicast-transport.ts +6 -2
  59. package/src/no-modules.ts +1 -6
  60. package/src/repair-fetch.ts +24 -4
  61. package/dist/manifest-auth-plan.d.ts +0 -31
  62. package/dist/manifest-auth-plan.d.ts.map +0 -1
  63. package/dist/manifest-auth-plan.js +0 -426
  64. package/dist/manifest-auth-plan.js.map +0 -7
  65. package/dist/source-auth.d.ts +0 -2
  66. package/dist/source-auth.d.ts.map +0 -1
  67. package/dist/source-auth.js +0 -3912
  68. package/dist/source-auth.js.map +0 -7
  69. package/src/manifest-auth-plan.ts +0 -55
  70. package/src/source-auth.ts +0 -1
  71. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  72. package/test-vectors/source-auth-v1.json +0 -61
@@ -7,6 +7,7 @@ var BlockcastMmt = (() => {
7
7
  var __typeError = (msg) => {
8
8
  throw TypeError(msg);
9
9
  };
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
11
  var __export = (target, all) => {
11
12
  for (var name in all)
12
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -19,7 +20,8 @@ var BlockcastMmt = (() => {
19
20
  }
20
21
  return to;
21
22
  };
22
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
24
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
23
25
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
24
26
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
25
27
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
@@ -37,9 +39,9 @@ var BlockcastMmt = (() => {
37
39
  // src/no-modules.ts
38
40
  var no_modules_exports = {};
39
41
  __export(no_modules_exports, {
42
+ BcProvenanceV2Receiver: () => BcProvenanceV2Receiver,
40
43
  CmsfCatalogValidationError: () => CmsfCatalogValidationError,
41
44
  FEC_INACTIVE_REASONS: () => FEC_INACTIVE_REASONS,
42
- ManifestVerifier: () => ManifestVerifier,
43
45
  MmtpContainerParser: () => MmtpContainerParser,
44
46
  MmtpFecSession: () => MmtpFecSession,
45
47
  MmtpToCmaf: () => MmtpToCmaf,
@@ -47,14 +49,11 @@ var BlockcastMmt = (() => {
47
49
  catalogAtsc3NetworkSource: () => catalogAtsc3NetworkSource,
48
50
  catalogDeclaresFec: () => catalogDeclaresFec,
49
51
  catalogFecInterleaveMs: () => catalogFecInterleaveMs,
50
- createManifestAuthPlan: () => createManifestAuthPlan,
51
52
  createWasmMmtpContainerParser: () => createWasmMmtpContainerParser,
52
- createWebCryptoEd25519Verifier: () => createWebCryptoEd25519Verifier,
53
53
  datagramMfuReassembly: () => datagramMfuReassembly,
54
54
  fecBlockBudgetMs: () => fecBlockBudgetMs,
55
55
  fecBlockDeadlineMs: () => fecBlockDeadlineMs,
56
56
  isFmp4InitSegment: () => isFmp4InitSegment,
57
- manifestBindingId: () => manifestBindingId,
58
57
  mmtpFrameReorderWindowFrames: () => mmtpFrameReorderWindowFrames,
59
58
  reliableMoqMfuReassembly: () => reliableMoqMfuReassembly,
60
59
  resolveFecState: () => resolveFecState,
@@ -8223,14 +8222,90 @@ var BlockcastMmt = (() => {
8223
8222
  return INACTIVE["reliable-moq"];
8224
8223
  }
8225
8224
 
8225
+ // src/held-layer-admission.ts
8226
+ var HORIZON_CAP = 1073741824;
8227
+ function heldLayerAnchorHorizon(retentionBlocks, k) {
8228
+ return retentionBlocks === void 0 || k <= 0 ? HORIZON_CAP : Math.min(HORIZON_CAP, retentionBlocks * k);
8229
+ }
8230
+ var _layerNames, _states;
8231
+ var HeldLayerAdmission = class {
8232
+ constructor(layers, heldLayers = [0]) {
8233
+ __privateAdd(this, _layerNames);
8234
+ __privateAdd(this, _states);
8235
+ const held = new Set(heldLayers);
8236
+ __privateSet(this, _layerNames, new Set(layers.map((l) => l.repairTrackName)));
8237
+ __privateSet(this, _states, layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols })));
8238
+ }
8239
+ /**
8240
+ * Judges one repair packet, after the 4.5 discards and the size check and
8241
+ * before it places a block. `repairTrackName` is the subscribed repair
8242
+ * track, never inferred from RS_ID; without it only (b) runs. A packet on a
8243
+ * repair track the catalog does not list is `'discard'` and anchors nothing.
8244
+ * `sourceFrontier` is the newest source SS_ID, if any: a repair more than
8245
+ * `horizon` past it is judged without moving the anchored state.
8246
+ *
8247
+ * @returns undefined to admit, `'discard'`, or the fail-closed reason.
8248
+ */
8249
+ admit(repairTrackName, ssStart, rsbLength, horizon, sourceFrontier) {
8250
+ if (repairTrackName !== void 0 && !__privateGet(this, _layerNames).has(repairTrackName)) return "discard";
8251
+ const farAhead = sourceFrontier !== void 0 && serial32Precedes(sourceFrontier, ssStart) && serial32Distance(sourceFrontier, ssStart) > horizon;
8252
+ for (const state of __privateGet(this, _states)) {
8253
+ let code;
8254
+ if (farAhead) {
8255
+ if (rsbLength < state.total) {
8256
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
8257
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
8258
+ }
8259
+ } else {
8260
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
8261
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
8262
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
8263
+ delete state.latestBelow;
8264
+ delete state.latestBelowRsb;
8265
+ }
8266
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
8267
+ if (rsbLength < state.total) {
8268
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
8269
+ else if (stale(ssStart)) continue;
8270
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
8271
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
8272
+ state.latestBelow = ssStart;
8273
+ state.latestBelowRsb = rsbLength;
8274
+ }
8275
+ } else if (!state.settled && !stale(ssStart)) {
8276
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
8277
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
8278
+ code = "below_anchored_total";
8279
+ ssStart = state.latestBelow;
8280
+ rsbLength = state.latestBelowRsb;
8281
+ }
8282
+ }
8283
+ }
8284
+ if (code !== void 0) {
8285
+ return {
8286
+ code,
8287
+ layer: state.layer,
8288
+ total: state.total,
8289
+ rsbLength,
8290
+ ssStart,
8291
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
8292
+ };
8293
+ }
8294
+ }
8295
+ return void 0;
8296
+ }
8297
+ };
8298
+ _layerNames = new WeakMap();
8299
+ _states = new WeakMap();
8300
+
8226
8301
  // src/mmtp-fec-session.ts
8227
8302
  var PATH_BITS = { moq: 1, multicast: 2 };
8228
8303
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8229
- var _decoder, _blocks, _settled, _have, _newest, _prunedAt, _repairPacketId, _stats3, _MmtpFecSession_instances, drop_fn2, noteNewest_fn, blockStartOf_fn, countHeld_fn, noteMixed_fn, behindHorizon_fn, settle_fn, settleClean_fn, settleDecoded_fn, retireBehindHorizon_fn;
8304
+ var _decoder, _blocks, _settled, _have, _newest, _prunedAt, _repairPacketId, _newestSource, _heldLayers, _anchorHorizon, _stats3, _MmtpFecSession_instances, drop_fn2, noteNewest_fn, blockStartOf_fn, countHeld_fn, noteMixed_fn, behindHorizon_fn, settle_fn, settleClean_fn, settleDecoded_fn, retireBehindHorizon_fn;
8230
8305
  var MmtpFecSession = class {
8231
8306
  /**
8232
8307
  * @throws when the catalog block lacks or misstates a field the session
8233
- * needs: the block profile, K, T, `interleaveDepthMs` or
8308
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
8234
8309
  * `reorderToleranceMs`. None is defaulted.
8235
8310
  */
8236
8311
  constructor(config) {
@@ -8249,6 +8324,9 @@ var BlockcastMmt = (() => {
8249
8324
  /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8250
8325
  __privateAdd(this, _prunedAt);
8251
8326
  __privateAdd(this, _repairPacketId);
8327
+ __privateAdd(this, _newestSource);
8328
+ __privateAdd(this, _heldLayers);
8329
+ __privateAdd(this, _anchorHorizon);
8252
8330
  __privateAdd(this, _stats3, {
8253
8331
  sourceSymbols: 0,
8254
8332
  repairSymbols: 0,
@@ -8261,7 +8339,8 @@ var BlockcastMmt = (() => {
8261
8339
  dropped: {},
8262
8340
  sourceSymbolsByPath: { moq: 0, multicast: 0 },
8263
8341
  repairSymbolsByPath: { moq: 0, multicast: 0 },
8264
- mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
8342
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
8343
+ failClosed: null
8265
8344
  });
8266
8345
  const fec = config?.fec;
8267
8346
  if (!fec || typeof fec !== "object") {
@@ -8273,6 +8352,7 @@ var BlockcastMmt = (() => {
8273
8352
  }
8274
8353
  this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8275
8354
  this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8355
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
8276
8356
  this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8277
8357
  const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8278
8358
  const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
@@ -8280,6 +8360,18 @@ var BlockcastMmt = (() => {
8280
8360
  fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8281
8361
  interleaveDepthMs
8282
8362
  );
8363
+ __privateSet(this, _heldLayers, new HeldLayerAdmission(
8364
+ config.repairLayers ?? [
8365
+ {
8366
+ layer: 0,
8367
+ repairTrackName: typeof fec.repairTrack === "string" ? fec.repairTrack : "",
8368
+ rsIdOffset: 0,
8369
+ repairSymbols: this.repairSymbols
8370
+ }
8371
+ ],
8372
+ config.heldLayers
8373
+ ));
8374
+ __privateSet(this, _anchorHorizon, heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols));
8283
8375
  if (typeof config.Decoder !== "function") {
8284
8376
  throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8285
8377
  }
@@ -8302,7 +8394,8 @@ var BlockcastMmt = (() => {
8302
8394
  dropped: { ...__privateGet(this, _stats3).dropped },
8303
8395
  sourceSymbolsByPath: { ...__privateGet(this, _stats3).sourceSymbolsByPath },
8304
8396
  repairSymbolsByPath: { ...__privateGet(this, _stats3).repairSymbolsByPath },
8305
- mixedPath: { ...__privateGet(this, _stats3).mixedPath }
8397
+ mixedPath: { ...__privateGet(this, _stats3).mixedPath },
8398
+ failClosed: __privateGet(this, _stats3).failClosed && { ...__privateGet(this, _stats3).failClosed }
8306
8399
  };
8307
8400
  }
8308
8401
  /**
@@ -8327,6 +8420,7 @@ var BlockcastMmt = (() => {
8327
8420
  __privateGet(this, _stats3).sourceSymbols++;
8328
8421
  __privateGet(this, _stats3).sourceSymbolsByPath[path]++;
8329
8422
  __privateMethod(this, _MmtpFecSession_instances, noteNewest_fn).call(this, ssId);
8423
+ if (__privateGet(this, _newestSource) === void 0 || serial32Precedes(__privateGet(this, _newestSource), ssId)) __privateSet(this, _newestSource, ssId);
8330
8424
  const start = __privateMethod(this, _MmtpFecSession_instances, blockStartOf_fn).call(this, ssId);
8331
8425
  const block = start === void 0 ? void 0 : __privateGet(this, _blocks).get(start);
8332
8426
  if (block) {
@@ -8355,14 +8449,17 @@ var BlockcastMmt = (() => {
8355
8449
  * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8356
8450
  * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8357
8451
  * repair packet fixes its packet ID and a packet of any other is refused.
8358
- * `path` is where it was received, as for addSource().
8452
+ * `path` is where it was received, as for addSource(). `repairTrackName`
8453
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
8454
+ * track the layers do not list is refused as `repair:unlisted-track`.
8359
8455
  *
8360
8456
  * @returns the protected packets this repair symbol recovered, as for
8361
8457
  * addSource().
8362
8458
  */
8363
- addRepair(packet, path = "moq") {
8459
+ addRepair(packet, path = "moq", repairTrackName) {
8364
8460
  const decoder = __privateGet(this, _decoder);
8365
8461
  if (!decoder) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:released");
8462
+ if (__privateGet(this, _stats3).failClosed) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:fail-closed");
8366
8463
  const pathBit = PATH_BITS[path];
8367
8464
  if (!pathBit) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:unknown-path");
8368
8465
  let header;
@@ -8383,6 +8480,18 @@ var BlockcastMmt = (() => {
8383
8480
  if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8384
8481
  return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:rs-block-length");
8385
8482
  }
8483
+ const verdict = __privateGet(this, _heldLayers).admit(
8484
+ repairTrackName,
8485
+ frame.ssStart,
8486
+ frame.rsbLength,
8487
+ __privateGet(this, _anchorHorizon),
8488
+ __privateGet(this, _newestSource)
8489
+ );
8490
+ if (verdict === "discard") return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:unlisted-track");
8491
+ if (verdict !== void 0) {
8492
+ __privateGet(this, _stats3).failClosed = verdict;
8493
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:fail-closed");
8494
+ }
8386
8495
  const start = frame.ssStart;
8387
8496
  let block = __privateGet(this, _blocks).get(start);
8388
8497
  if (block && block.ssbLength !== frame.ssbLength) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:conflicting-ssb-length");
@@ -8439,6 +8548,9 @@ var BlockcastMmt = (() => {
8439
8548
  _newest = new WeakMap();
8440
8549
  _prunedAt = new WeakMap();
8441
8550
  _repairPacketId = new WeakMap();
8551
+ _newestSource = new WeakMap();
8552
+ _heldLayers = new WeakMap();
8553
+ _anchorHorizon = new WeakMap();
8442
8554
  _stats3 = new WeakMap();
8443
8555
  _MmtpFecSession_instances = new WeakSet();
8444
8556
  drop_fn2 = function(reason) {
@@ -9297,6 +9409,9 @@ var BlockcastMmt = (() => {
9297
9409
  _audioSampleCount = new WeakMap();
9298
9410
  _aacFrameSamples = new WeakMap();
9299
9411
 
9412
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/crypto.js
9413
+ var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
9414
+
9300
9415
  // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/utils.js
9301
9416
  function isBytes(a) {
9302
9417
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -9324,32 +9439,63 @@ var BlockcastMmt = (() => {
9324
9439
  throw new Error("digestInto() expects output buffer of length at least " + min);
9325
9440
  }
9326
9441
  }
9327
- function u8(arr) {
9328
- return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
9329
- }
9330
- function u322(arr) {
9331
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
9332
- }
9333
9442
  function clean(...arrays) {
9334
9443
  for (let i = 0; i < arrays.length; i++) {
9335
9444
  arrays[i].fill(0);
9336
9445
  }
9337
9446
  }
9447
+ function createView(arr) {
9448
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9449
+ }
9338
9450
  function rotr(word, shift) {
9339
9451
  return word << 32 - shift | word >>> shift;
9340
9452
  }
9341
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
9342
- function byteSwap(word) {
9343
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
9453
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9454
+ // @ts-ignore
9455
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9456
+ ))();
9457
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9458
+ function bytesToHex(bytes) {
9459
+ abytes(bytes);
9460
+ if (hasHexBuiltin)
9461
+ return bytes.toHex();
9462
+ let hex2 = "";
9463
+ for (let i = 0; i < bytes.length; i++) {
9464
+ hex2 += hexes[bytes[i]];
9465
+ }
9466
+ return hex2;
9467
+ }
9468
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9469
+ function asciiToBase16(ch) {
9470
+ if (ch >= asciis._0 && ch <= asciis._9)
9471
+ return ch - asciis._0;
9472
+ if (ch >= asciis.A && ch <= asciis.F)
9473
+ return ch - (asciis.A - 10);
9474
+ if (ch >= asciis.a && ch <= asciis.f)
9475
+ return ch - (asciis.a - 10);
9476
+ return;
9477
+ }
9478
+ function hexToBytes(hex2) {
9479
+ if (typeof hex2 !== "string")
9480
+ throw new Error("hex string expected, got " + typeof hex2);
9481
+ if (hasHexBuiltin)
9482
+ return Uint8Array.fromHex(hex2);
9483
+ const hl = hex2.length;
9484
+ const al = hl / 2;
9485
+ if (hl % 2)
9486
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9487
+ const array = new Uint8Array(al);
9488
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9489
+ const n1 = asciiToBase16(hex2.charCodeAt(hi));
9490
+ const n2 = asciiToBase16(hex2.charCodeAt(hi + 1));
9491
+ if (n1 === void 0 || n2 === void 0) {
9492
+ const char = hex2[hi] + hex2[hi + 1];
9493
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9494
+ }
9495
+ array[ai] = n1 * 16 + n2;
9496
+ }
9497
+ return array;
9344
9498
  }
9345
- var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n);
9346
- function byteSwap32(arr) {
9347
- for (let i = 0; i < arr.length; i++) {
9348
- arr[i] = byteSwap(arr[i]);
9349
- }
9350
- return arr;
9351
- }
9352
- var swap32IfBE = isLE ? (u) => u : byteSwap32;
9353
9499
  function utf8ToBytes(str) {
9354
9500
  if (typeof str !== "string")
9355
9501
  throw new Error("string expected");
@@ -9361,114 +9507,126 @@ var BlockcastMmt = (() => {
9361
9507
  abytes(data);
9362
9508
  return data;
9363
9509
  }
9510
+ function concatBytes(...arrays) {
9511
+ let sum = 0;
9512
+ for (let i = 0; i < arrays.length; i++) {
9513
+ const a = arrays[i];
9514
+ abytes(a);
9515
+ sum += a.length;
9516
+ }
9517
+ const res = new Uint8Array(sum);
9518
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9519
+ const a = arrays[i];
9520
+ res.set(a, pad);
9521
+ pad += a.length;
9522
+ }
9523
+ return res;
9524
+ }
9364
9525
  var Hash = class {
9365
9526
  };
9366
- function createXOFer(hashCons) {
9367
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
9368
- const tmp = hashCons({});
9527
+ function createHasher(hashCons) {
9528
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
9529
+ const tmp = hashCons();
9369
9530
  hashC.outputLen = tmp.outputLen;
9370
9531
  hashC.blockLen = tmp.blockLen;
9371
- hashC.create = (opts) => hashCons(opts);
9532
+ hashC.create = () => hashCons();
9372
9533
  return hashC;
9373
9534
  }
9374
-
9375
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_md.js
9376
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9377
- 1779033703,
9378
- 3144134277,
9379
- 1013904242,
9380
- 2773480762,
9381
- 1359893119,
9382
- 2600822924,
9383
- 528734635,
9384
- 1541459225
9385
- ]);
9386
-
9387
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_u64.js
9388
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
9389
- var _32n = /* @__PURE__ */ BigInt(32);
9390
- function fromBig(n, le = false) {
9391
- if (le)
9392
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
9393
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
9394
- }
9395
-
9396
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_blake.js
9397
- function G1s(a, b, c, d, x) {
9398
- a = a + b + x | 0;
9399
- d = rotr(d ^ a, 16);
9400
- c = c + d | 0;
9401
- b = rotr(b ^ c, 12);
9402
- return { a, b, c, d };
9403
- }
9404
- function G2s(a, b, c, d, x) {
9405
- a = a + b + x | 0;
9406
- d = rotr(d ^ a, 8);
9407
- c = c + d | 0;
9408
- b = rotr(b ^ c, 7);
9409
- return { a, b, c, d };
9535
+ function randomBytes(bytesLength = 32) {
9536
+ if (crypto && typeof crypto.getRandomValues === "function") {
9537
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
9538
+ }
9539
+ if (crypto && typeof crypto.randomBytes === "function") {
9540
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
9541
+ }
9542
+ throw new Error("crypto.getRandomValues must be defined");
9410
9543
  }
9411
9544
 
9412
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/blake2.js
9413
- var BLAKE2 = class extends Hash {
9414
- constructor(blockLen, outputLen) {
9545
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_md.js
9546
+ function setBigUint64(view2, byteOffset, value, isLE) {
9547
+ if (typeof view2.setBigUint64 === "function")
9548
+ return view2.setBigUint64(byteOffset, value, isLE);
9549
+ const _32n2 = BigInt(32);
9550
+ const _u32_max = BigInt(4294967295);
9551
+ const wh = Number(value >> _32n2 & _u32_max);
9552
+ const wl = Number(value & _u32_max);
9553
+ const h = isLE ? 4 : 0;
9554
+ const l = isLE ? 0 : 4;
9555
+ view2.setUint32(byteOffset + h, wh, isLE);
9556
+ view2.setUint32(byteOffset + l, wl, isLE);
9557
+ }
9558
+ function Chi(a, b, c) {
9559
+ return a & b ^ ~a & c;
9560
+ }
9561
+ function Maj(a, b, c) {
9562
+ return a & b ^ a & c ^ b & c;
9563
+ }
9564
+ var HashMD = class extends Hash {
9565
+ constructor(blockLen, outputLen, padOffset, isLE) {
9415
9566
  super();
9416
9567
  this.finished = false;
9417
- this.destroyed = false;
9418
9568
  this.length = 0;
9419
9569
  this.pos = 0;
9420
- anumber(blockLen);
9421
- anumber(outputLen);
9570
+ this.destroyed = false;
9422
9571
  this.blockLen = blockLen;
9423
9572
  this.outputLen = outputLen;
9573
+ this.padOffset = padOffset;
9574
+ this.isLE = isLE;
9424
9575
  this.buffer = new Uint8Array(blockLen);
9425
- this.buffer32 = u322(this.buffer);
9576
+ this.view = createView(this.buffer);
9426
9577
  }
9427
9578
  update(data) {
9428
9579
  aexists(this);
9429
9580
  data = toBytes(data);
9430
9581
  abytes(data);
9431
- const { blockLen, buffer, buffer32 } = this;
9582
+ const { view: view2, buffer, blockLen } = this;
9432
9583
  const len = data.length;
9433
- const offset = data.byteOffset;
9434
- const buf = data.buffer;
9435
9584
  for (let pos = 0; pos < len; ) {
9436
- if (this.pos === blockLen) {
9437
- swap32IfBE(buffer32);
9438
- this.compress(buffer32, 0, false);
9439
- swap32IfBE(buffer32);
9440
- this.pos = 0;
9441
- }
9442
9585
  const take = Math.min(blockLen - this.pos, len - pos);
9443
- const dataOffset = offset + pos;
9444
- if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
9445
- const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
9446
- swap32IfBE(data32);
9447
- for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
9448
- this.length += blockLen;
9449
- this.compress(data32, pos32, false);
9450
- }
9451
- swap32IfBE(data32);
9586
+ if (take === blockLen) {
9587
+ const dataView = createView(data);
9588
+ for (; blockLen <= len - pos; pos += blockLen)
9589
+ this.process(dataView, pos);
9452
9590
  continue;
9453
9591
  }
9454
9592
  buffer.set(data.subarray(pos, pos + take), this.pos);
9455
9593
  this.pos += take;
9456
- this.length += take;
9457
9594
  pos += take;
9595
+ if (this.pos === blockLen) {
9596
+ this.process(view2, 0);
9597
+ this.pos = 0;
9598
+ }
9458
9599
  }
9600
+ this.length += data.length;
9601
+ this.roundClean();
9459
9602
  return this;
9460
9603
  }
9461
9604
  digestInto(out) {
9462
9605
  aexists(this);
9463
9606
  aoutput(out, this);
9464
- const { pos, buffer32 } = this;
9465
9607
  this.finished = true;
9608
+ const { buffer, view: view2, blockLen, isLE } = this;
9609
+ let { pos } = this;
9610
+ buffer[pos++] = 128;
9466
9611
  clean(this.buffer.subarray(pos));
9467
- swap32IfBE(buffer32);
9468
- this.compress(buffer32, 0, true);
9469
- swap32IfBE(buffer32);
9470
- const out32 = u322(out);
9471
- this.get().forEach((v, i) => out32[i] = swap8IfBE(v));
9612
+ if (this.padOffset > blockLen - pos) {
9613
+ this.process(view2, 0);
9614
+ pos = 0;
9615
+ }
9616
+ for (let i = pos; i < blockLen; i++)
9617
+ buffer[i] = 0;
9618
+ setBigUint64(view2, blockLen - 8, BigInt(this.length * 8), isLE);
9619
+ this.process(view2, 0);
9620
+ const oview = createView(out);
9621
+ const len = this.outputLen;
9622
+ if (len % 4)
9623
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
9624
+ const outLen = len / 4;
9625
+ const state = this.get();
9626
+ if (outLen > state.length)
9627
+ throw new Error("_sha2: outputLen bigger than state");
9628
+ for (let i = 0; i < outLen; i++)
9629
+ oview.setUint32(4 * i, state[i], isLE);
9472
9630
  }
9473
9631
  digest() {
9474
9632
  const { buffer, outputLen } = this;
@@ -9478,1012 +9636,2513 @@ var BlockcastMmt = (() => {
9478
9636
  return res;
9479
9637
  }
9480
9638
  _cloneInto(to) {
9481
- const { buffer, length, finished, destroyed, outputLen, pos } = this;
9482
- to || (to = new this.constructor({ dkLen: outputLen }));
9639
+ to || (to = new this.constructor());
9483
9640
  to.set(...this.get());
9484
- to.buffer.set(buffer);
9641
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9485
9642
  to.destroyed = destroyed;
9486
9643
  to.finished = finished;
9487
9644
  to.length = length;
9488
9645
  to.pos = pos;
9489
- to.outputLen = outputLen;
9646
+ if (length % blockLen)
9647
+ to.buffer.set(buffer);
9490
9648
  return to;
9491
9649
  }
9492
9650
  clone() {
9493
9651
  return this._cloneInto();
9494
9652
  }
9495
9653
  };
9496
- function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
9497
- let j = 0;
9498
- for (let i = 0; i < rounds; i++) {
9499
- ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
9500
- ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
9501
- ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
9502
- ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
9503
- ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
9504
- ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
9505
- ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
9506
- ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
9507
- ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
9508
- ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
9509
- ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
9510
- ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
9511
- ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
9512
- ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
9513
- ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
9514
- ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
9515
- }
9516
- return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
9654
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9655
+ 1779033703,
9656
+ 3144134277,
9657
+ 1013904242,
9658
+ 2773480762,
9659
+ 1359893119,
9660
+ 2600822924,
9661
+ 528734635,
9662
+ 1541459225
9663
+ ]);
9664
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
9665
+ 1779033703,
9666
+ 4089235720,
9667
+ 3144134277,
9668
+ 2227873595,
9669
+ 1013904242,
9670
+ 4271175723,
9671
+ 2773480762,
9672
+ 1595750129,
9673
+ 1359893119,
9674
+ 2917565137,
9675
+ 2600822924,
9676
+ 725511199,
9677
+ 528734635,
9678
+ 4215389547,
9679
+ 1541459225,
9680
+ 327033209
9681
+ ]);
9682
+
9683
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_u64.js
9684
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
9685
+ var _32n = /* @__PURE__ */ BigInt(32);
9686
+ function fromBig(n, le = false) {
9687
+ if (le)
9688
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
9689
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
9517
9690
  }
9691
+ function split(lst, le = false) {
9692
+ const len = lst.length;
9693
+ let Ah = new Uint32Array(len);
9694
+ let Al = new Uint32Array(len);
9695
+ for (let i = 0; i < len; i++) {
9696
+ const { h, l } = fromBig(lst[i], le);
9697
+ [Ah[i], Al[i]] = [h, l];
9698
+ }
9699
+ return [Ah, Al];
9700
+ }
9701
+ var shrSH = (h, _l, s) => h >>> s;
9702
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
9703
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
9704
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
9705
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
9706
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
9707
+ function add(Ah, Al, Bh, Bl) {
9708
+ const l = (Al >>> 0) + (Bl >>> 0);
9709
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
9710
+ }
9711
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
9712
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
9713
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
9714
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
9715
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
9716
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
9518
9717
 
9519
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/blake3.js
9520
- var B3_Flags = {
9521
- CHUNK_START: 1,
9522
- CHUNK_END: 2,
9523
- PARENT: 4,
9524
- ROOT: 8,
9525
- KEYED_HASH: 16,
9526
- DERIVE_KEY_CONTEXT: 32,
9527
- DERIVE_KEY_MATERIAL: 64
9528
- };
9529
- var B3_IV = SHA256_IV.slice();
9530
- var B3_SIGMA = /* @__PURE__ */ (() => {
9531
- const Id = Array.from({ length: 16 }, (_, i) => i);
9532
- const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
9533
- const res = [];
9534
- for (let i = 0, v = Id; i < 7; i++, v = permute(v))
9535
- res.push(...v);
9536
- return Uint8Array.from(res);
9537
- })();
9538
- var BLAKE3 = class _BLAKE3 extends BLAKE2 {
9539
- constructor(opts = {}, flags = 0) {
9540
- super(64, opts.dkLen === void 0 ? 32 : opts.dkLen);
9541
- this.chunkPos = 0;
9542
- this.chunksDone = 0;
9543
- this.flags = 0 | 0;
9544
- this.stack = [];
9545
- this.posOut = 0;
9546
- this.bufferOut32 = new Uint32Array(16);
9547
- this.chunkOut = 0;
9548
- this.enableXOF = true;
9549
- const { key, context } = opts;
9550
- const hasContext = context !== void 0;
9551
- if (key !== void 0) {
9552
- if (hasContext)
9553
- throw new Error('Only "key" or "context" can be specified at same time');
9554
- const k = toBytes(key).slice();
9555
- abytes(k, 32);
9556
- this.IV = u322(k);
9557
- swap32IfBE(this.IV);
9558
- this.flags = flags | B3_Flags.KEYED_HASH;
9559
- } else if (hasContext) {
9560
- const ctx = toBytes(context);
9561
- const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT).update(ctx).digest();
9562
- this.IV = u322(contextKey);
9563
- swap32IfBE(this.IV);
9564
- this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
9565
- } else {
9566
- this.IV = B3_IV.slice();
9567
- this.flags = flags;
9568
- }
9569
- this.state = this.IV.slice();
9570
- this.bufferOut = u8(this.bufferOut32);
9718
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/sha2.js
9719
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9720
+ 1116352408,
9721
+ 1899447441,
9722
+ 3049323471,
9723
+ 3921009573,
9724
+ 961987163,
9725
+ 1508970993,
9726
+ 2453635748,
9727
+ 2870763221,
9728
+ 3624381080,
9729
+ 310598401,
9730
+ 607225278,
9731
+ 1426881987,
9732
+ 1925078388,
9733
+ 2162078206,
9734
+ 2614888103,
9735
+ 3248222580,
9736
+ 3835390401,
9737
+ 4022224774,
9738
+ 264347078,
9739
+ 604807628,
9740
+ 770255983,
9741
+ 1249150122,
9742
+ 1555081692,
9743
+ 1996064986,
9744
+ 2554220882,
9745
+ 2821834349,
9746
+ 2952996808,
9747
+ 3210313671,
9748
+ 3336571891,
9749
+ 3584528711,
9750
+ 113926993,
9751
+ 338241895,
9752
+ 666307205,
9753
+ 773529912,
9754
+ 1294757372,
9755
+ 1396182291,
9756
+ 1695183700,
9757
+ 1986661051,
9758
+ 2177026350,
9759
+ 2456956037,
9760
+ 2730485921,
9761
+ 2820302411,
9762
+ 3259730800,
9763
+ 3345764771,
9764
+ 3516065817,
9765
+ 3600352804,
9766
+ 4094571909,
9767
+ 275423344,
9768
+ 430227734,
9769
+ 506948616,
9770
+ 659060556,
9771
+ 883997877,
9772
+ 958139571,
9773
+ 1322822218,
9774
+ 1537002063,
9775
+ 1747873779,
9776
+ 1955562222,
9777
+ 2024104815,
9778
+ 2227730452,
9779
+ 2361852424,
9780
+ 2428436474,
9781
+ 2756734187,
9782
+ 3204031479,
9783
+ 3329325298
9784
+ ]);
9785
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9786
+ var SHA256 = class extends HashMD {
9787
+ constructor(outputLen = 32) {
9788
+ super(64, outputLen, 8, false);
9789
+ this.A = SHA256_IV[0] | 0;
9790
+ this.B = SHA256_IV[1] | 0;
9791
+ this.C = SHA256_IV[2] | 0;
9792
+ this.D = SHA256_IV[3] | 0;
9793
+ this.E = SHA256_IV[4] | 0;
9794
+ this.F = SHA256_IV[5] | 0;
9795
+ this.G = SHA256_IV[6] | 0;
9796
+ this.H = SHA256_IV[7] | 0;
9571
9797
  }
9572
- // Unused
9573
9798
  get() {
9574
- return [];
9575
- }
9576
- set() {
9577
- }
9578
- b2Compress(counter, flags, buf, bufPos = 0) {
9579
- const { state: s, pos } = this;
9580
- const { h, l } = fromBig(BigInt(counter), true);
9581
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
9582
- s[0] = v0 ^ v8;
9583
- s[1] = v1 ^ v9;
9584
- s[2] = v2 ^ v10;
9585
- s[3] = v3 ^ v11;
9586
- s[4] = v4 ^ v12;
9587
- s[5] = v5 ^ v13;
9588
- s[6] = v6 ^ v14;
9589
- s[7] = v7 ^ v15;
9590
- }
9591
- compress(buf, bufPos = 0, isLast = false) {
9592
- let flags = this.flags;
9593
- if (!this.chunkPos)
9594
- flags |= B3_Flags.CHUNK_START;
9595
- if (this.chunkPos === 15 || isLast)
9596
- flags |= B3_Flags.CHUNK_END;
9597
- if (!isLast)
9598
- this.pos = this.blockLen;
9599
- this.b2Compress(this.chunksDone, flags, buf, bufPos);
9600
- this.chunkPos += 1;
9601
- if (this.chunkPos === 16 || isLast) {
9602
- let chunk = this.state;
9603
- this.state = this.IV.slice();
9604
- for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
9605
- if (!(last = this.stack.pop()))
9606
- break;
9607
- this.buffer32.set(last, 0);
9608
- this.buffer32.set(chunk, 8);
9609
- this.pos = this.blockLen;
9610
- this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
9611
- chunk = this.state;
9612
- this.state = this.IV.slice();
9613
- }
9614
- this.chunksDone++;
9615
- this.chunkPos = 0;
9616
- this.stack.push(chunk);
9617
- }
9618
- this.pos = 0;
9619
- }
9620
- _cloneInto(to) {
9621
- to = super._cloneInto(to);
9622
- const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
9623
- to.state.set(state.slice());
9624
- to.stack = stack.map((i) => Uint32Array.from(i));
9625
- to.IV.set(IV);
9626
- to.flags = flags;
9627
- to.chunkPos = chunkPos;
9628
- to.chunksDone = chunksDone;
9629
- to.posOut = posOut;
9630
- to.chunkOut = chunkOut;
9631
- to.enableXOF = this.enableXOF;
9632
- to.bufferOut32.set(this.bufferOut32);
9633
- return to;
9799
+ const { A, B, C, D, E, F, G, H } = this;
9800
+ return [A, B, C, D, E, F, G, H];
9801
+ }
9802
+ // prettier-ignore
9803
+ set(A, B, C, D, E, F, G, H) {
9804
+ this.A = A | 0;
9805
+ this.B = B | 0;
9806
+ this.C = C | 0;
9807
+ this.D = D | 0;
9808
+ this.E = E | 0;
9809
+ this.F = F | 0;
9810
+ this.G = G | 0;
9811
+ this.H = H | 0;
9812
+ }
9813
+ process(view2, offset) {
9814
+ for (let i = 0; i < 16; i++, offset += 4)
9815
+ SHA256_W[i] = view2.getUint32(offset, false);
9816
+ for (let i = 16; i < 64; i++) {
9817
+ const W15 = SHA256_W[i - 15];
9818
+ const W2 = SHA256_W[i - 2];
9819
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9820
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9821
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9822
+ }
9823
+ let { A, B, C, D, E, F, G, H } = this;
9824
+ for (let i = 0; i < 64; i++) {
9825
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9826
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9827
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9828
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9829
+ H = G;
9830
+ G = F;
9831
+ F = E;
9832
+ E = D + T1 | 0;
9833
+ D = C;
9834
+ C = B;
9835
+ B = A;
9836
+ A = T1 + T2 | 0;
9837
+ }
9838
+ A = A + this.A | 0;
9839
+ B = B + this.B | 0;
9840
+ C = C + this.C | 0;
9841
+ D = D + this.D | 0;
9842
+ E = E + this.E | 0;
9843
+ F = F + this.F | 0;
9844
+ G = G + this.G | 0;
9845
+ H = H + this.H | 0;
9846
+ this.set(A, B, C, D, E, F, G, H);
9847
+ }
9848
+ roundClean() {
9849
+ clean(SHA256_W);
9634
9850
  }
9635
9851
  destroy() {
9636
- this.destroyed = true;
9637
- clean(this.state, this.buffer32, this.IV, this.bufferOut32);
9638
- clean(...this.stack);
9639
- }
9640
- // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
9641
- b2CompressOut() {
9642
- const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
9643
- const { h, l } = fromBig(BigInt(this.chunkOut++));
9644
- swap32IfBE(buffer32);
9645
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
9646
- out32[0] = v0 ^ v8;
9647
- out32[1] = v1 ^ v9;
9648
- out32[2] = v2 ^ v10;
9649
- out32[3] = v3 ^ v11;
9650
- out32[4] = v4 ^ v12;
9651
- out32[5] = v5 ^ v13;
9652
- out32[6] = v6 ^ v14;
9653
- out32[7] = v7 ^ v15;
9654
- out32[8] = s[0] ^ v8;
9655
- out32[9] = s[1] ^ v9;
9656
- out32[10] = s[2] ^ v10;
9657
- out32[11] = s[3] ^ v11;
9658
- out32[12] = s[4] ^ v12;
9659
- out32[13] = s[5] ^ v13;
9660
- out32[14] = s[6] ^ v14;
9661
- out32[15] = s[7] ^ v15;
9662
- swap32IfBE(buffer32);
9663
- swap32IfBE(out32);
9664
- this.posOut = 0;
9665
- }
9666
- finish() {
9667
- if (this.finished)
9668
- return;
9669
- this.finished = true;
9670
- clean(this.buffer.subarray(this.pos));
9671
- let flags = this.flags | B3_Flags.ROOT;
9672
- if (this.stack.length) {
9673
- flags |= B3_Flags.PARENT;
9674
- swap32IfBE(this.buffer32);
9675
- this.compress(this.buffer32, 0, true);
9676
- swap32IfBE(this.buffer32);
9677
- this.chunksDone = 0;
9678
- this.pos = this.blockLen;
9679
- } else {
9680
- flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
9681
- }
9682
- this.flags = flags;
9683
- this.b2CompressOut();
9684
- }
9685
- writeInto(out) {
9686
- aexists(this, false);
9687
- abytes(out);
9688
- this.finish();
9689
- const { blockLen, bufferOut } = this;
9690
- for (let pos = 0, len = out.length; pos < len; ) {
9691
- if (this.posOut >= blockLen)
9692
- this.b2CompressOut();
9693
- const take = Math.min(blockLen - this.posOut, len - pos);
9694
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
9695
- this.posOut += take;
9696
- pos += take;
9697
- }
9698
- return out;
9852
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9853
+ clean(this.buffer);
9699
9854
  }
9700
- xofInto(out) {
9701
- if (!this.enableXOF)
9702
- throw new Error("XOF is not possible after digest call");
9703
- return this.writeInto(out);
9704
- }
9705
- xof(bytes) {
9706
- anumber(bytes);
9707
- return this.xofInto(new Uint8Array(bytes));
9708
- }
9709
- digestInto(out) {
9710
- aoutput(out, this);
9711
- if (this.finished)
9712
- throw new Error("digest() was already called");
9713
- this.enableXOF = false;
9714
- this.writeInto(out);
9715
- this.destroy();
9716
- return out;
9855
+ };
9856
+ var K512 = /* @__PURE__ */ (() => split([
9857
+ "0x428a2f98d728ae22",
9858
+ "0x7137449123ef65cd",
9859
+ "0xb5c0fbcfec4d3b2f",
9860
+ "0xe9b5dba58189dbbc",
9861
+ "0x3956c25bf348b538",
9862
+ "0x59f111f1b605d019",
9863
+ "0x923f82a4af194f9b",
9864
+ "0xab1c5ed5da6d8118",
9865
+ "0xd807aa98a3030242",
9866
+ "0x12835b0145706fbe",
9867
+ "0x243185be4ee4b28c",
9868
+ "0x550c7dc3d5ffb4e2",
9869
+ "0x72be5d74f27b896f",
9870
+ "0x80deb1fe3b1696b1",
9871
+ "0x9bdc06a725c71235",
9872
+ "0xc19bf174cf692694",
9873
+ "0xe49b69c19ef14ad2",
9874
+ "0xefbe4786384f25e3",
9875
+ "0x0fc19dc68b8cd5b5",
9876
+ "0x240ca1cc77ac9c65",
9877
+ "0x2de92c6f592b0275",
9878
+ "0x4a7484aa6ea6e483",
9879
+ "0x5cb0a9dcbd41fbd4",
9880
+ "0x76f988da831153b5",
9881
+ "0x983e5152ee66dfab",
9882
+ "0xa831c66d2db43210",
9883
+ "0xb00327c898fb213f",
9884
+ "0xbf597fc7beef0ee4",
9885
+ "0xc6e00bf33da88fc2",
9886
+ "0xd5a79147930aa725",
9887
+ "0x06ca6351e003826f",
9888
+ "0x142929670a0e6e70",
9889
+ "0x27b70a8546d22ffc",
9890
+ "0x2e1b21385c26c926",
9891
+ "0x4d2c6dfc5ac42aed",
9892
+ "0x53380d139d95b3df",
9893
+ "0x650a73548baf63de",
9894
+ "0x766a0abb3c77b2a8",
9895
+ "0x81c2c92e47edaee6",
9896
+ "0x92722c851482353b",
9897
+ "0xa2bfe8a14cf10364",
9898
+ "0xa81a664bbc423001",
9899
+ "0xc24b8b70d0f89791",
9900
+ "0xc76c51a30654be30",
9901
+ "0xd192e819d6ef5218",
9902
+ "0xd69906245565a910",
9903
+ "0xf40e35855771202a",
9904
+ "0x106aa07032bbd1b8",
9905
+ "0x19a4c116b8d2d0c8",
9906
+ "0x1e376c085141ab53",
9907
+ "0x2748774cdf8eeb99",
9908
+ "0x34b0bcb5e19b48a8",
9909
+ "0x391c0cb3c5c95a63",
9910
+ "0x4ed8aa4ae3418acb",
9911
+ "0x5b9cca4f7763e373",
9912
+ "0x682e6ff3d6b2b8a3",
9913
+ "0x748f82ee5defb2fc",
9914
+ "0x78a5636f43172f60",
9915
+ "0x84c87814a1f0ab72",
9916
+ "0x8cc702081a6439ec",
9917
+ "0x90befffa23631e28",
9918
+ "0xa4506cebde82bde9",
9919
+ "0xbef9a3f7b2c67915",
9920
+ "0xc67178f2e372532b",
9921
+ "0xca273eceea26619c",
9922
+ "0xd186b8c721c0c207",
9923
+ "0xeada7dd6cde0eb1e",
9924
+ "0xf57d4f7fee6ed178",
9925
+ "0x06f067aa72176fba",
9926
+ "0x0a637dc5a2c898a6",
9927
+ "0x113f9804bef90dae",
9928
+ "0x1b710b35131c471b",
9929
+ "0x28db77f523047d84",
9930
+ "0x32caab7b40c72493",
9931
+ "0x3c9ebe0a15c9bebc",
9932
+ "0x431d67c49c100d4c",
9933
+ "0x4cc5d4becb3e42b6",
9934
+ "0x597f299cfc657e2a",
9935
+ "0x5fcb6fab3ad6faec",
9936
+ "0x6c44198c4a475817"
9937
+ ].map((n) => BigInt(n))))();
9938
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
9939
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
9940
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
9941
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
9942
+ var SHA512 = class extends HashMD {
9943
+ constructor(outputLen = 64) {
9944
+ super(128, outputLen, 16, false);
9945
+ this.Ah = SHA512_IV[0] | 0;
9946
+ this.Al = SHA512_IV[1] | 0;
9947
+ this.Bh = SHA512_IV[2] | 0;
9948
+ this.Bl = SHA512_IV[3] | 0;
9949
+ this.Ch = SHA512_IV[4] | 0;
9950
+ this.Cl = SHA512_IV[5] | 0;
9951
+ this.Dh = SHA512_IV[6] | 0;
9952
+ this.Dl = SHA512_IV[7] | 0;
9953
+ this.Eh = SHA512_IV[8] | 0;
9954
+ this.El = SHA512_IV[9] | 0;
9955
+ this.Fh = SHA512_IV[10] | 0;
9956
+ this.Fl = SHA512_IV[11] | 0;
9957
+ this.Gh = SHA512_IV[12] | 0;
9958
+ this.Gl = SHA512_IV[13] | 0;
9959
+ this.Hh = SHA512_IV[14] | 0;
9960
+ this.Hl = SHA512_IV[15] | 0;
9961
+ }
9962
+ // prettier-ignore
9963
+ get() {
9964
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
9965
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
9966
+ }
9967
+ // prettier-ignore
9968
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
9969
+ this.Ah = Ah | 0;
9970
+ this.Al = Al | 0;
9971
+ this.Bh = Bh | 0;
9972
+ this.Bl = Bl | 0;
9973
+ this.Ch = Ch | 0;
9974
+ this.Cl = Cl | 0;
9975
+ this.Dh = Dh | 0;
9976
+ this.Dl = Dl | 0;
9977
+ this.Eh = Eh | 0;
9978
+ this.El = El | 0;
9979
+ this.Fh = Fh | 0;
9980
+ this.Fl = Fl | 0;
9981
+ this.Gh = Gh | 0;
9982
+ this.Gl = Gl | 0;
9983
+ this.Hh = Hh | 0;
9984
+ this.Hl = Hl | 0;
9985
+ }
9986
+ process(view2, offset) {
9987
+ for (let i = 0; i < 16; i++, offset += 4) {
9988
+ SHA512_W_H[i] = view2.getUint32(offset);
9989
+ SHA512_W_L[i] = view2.getUint32(offset += 4);
9990
+ }
9991
+ for (let i = 16; i < 80; i++) {
9992
+ const W15h = SHA512_W_H[i - 15] | 0;
9993
+ const W15l = SHA512_W_L[i - 15] | 0;
9994
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
9995
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
9996
+ const W2h = SHA512_W_H[i - 2] | 0;
9997
+ const W2l = SHA512_W_L[i - 2] | 0;
9998
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
9999
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
10000
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
10001
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
10002
+ SHA512_W_H[i] = SUMh | 0;
10003
+ SHA512_W_L[i] = SUMl | 0;
10004
+ }
10005
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
10006
+ for (let i = 0; i < 80; i++) {
10007
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
10008
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
10009
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
10010
+ const CHIl = El & Fl ^ ~El & Gl;
10011
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
10012
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
10013
+ const T1l = T1ll | 0;
10014
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
10015
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
10016
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
10017
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
10018
+ Hh = Gh | 0;
10019
+ Hl = Gl | 0;
10020
+ Gh = Fh | 0;
10021
+ Gl = Fl | 0;
10022
+ Fh = Eh | 0;
10023
+ Fl = El | 0;
10024
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
10025
+ Dh = Ch | 0;
10026
+ Dl = Cl | 0;
10027
+ Ch = Bh | 0;
10028
+ Cl = Bl | 0;
10029
+ Bh = Ah | 0;
10030
+ Bl = Al | 0;
10031
+ const All = add3L(T1l, sigma0l, MAJl);
10032
+ Ah = add3H(All, T1h, sigma0h, MAJh);
10033
+ Al = All | 0;
10034
+ }
10035
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
10036
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
10037
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
10038
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
10039
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
10040
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
10041
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
10042
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
10043
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
10044
+ }
10045
+ roundClean() {
10046
+ clean(SHA512_W_H, SHA512_W_L);
9717
10047
  }
9718
- digest() {
9719
- return this.digestInto(new Uint8Array(this.outputLen));
10048
+ destroy() {
10049
+ clean(this.buffer);
10050
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
9720
10051
  }
9721
10052
  };
9722
- var blake3 = /* @__PURE__ */ createXOFer((opts) => new BLAKE3(opts));
10053
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
10054
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
9723
10055
 
9724
- // ../mmt-manifest-verify/dist/source-auth.js
9725
- var SOURCE_AUTH_MANIFEST_VERSION = 1;
9726
- var SOURCE_AUTH_OBJECT_ENTRY_FRAME = 1;
9727
- var SOURCE_AUTH_GROUP_CLOSE_FRAME = 2;
9728
- var SOURCE_AUTH_OBJECT_ENTRY_LENGTH = 52;
9729
- var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
9730
- var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
9731
- var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
9732
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
9733
- var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
9734
- function requireBytes(name, value, length) {
9735
- if (value.byteLength !== length) {
9736
- throw new Error(`${name} must be ${length} bytes, got ${value.byteLength}`);
9737
- }
9738
- }
9739
- function requireU32(name, value) {
9740
- if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
9741
- throw new Error(`${name} must be an unsigned 32-bit integer`);
9742
- }
9743
- }
9744
- function requireU64(name, value) {
9745
- if (value < 0n || value > 0xffffffffffffffffn) {
9746
- throw new Error(`${name} must be an unsigned 64-bit integer`);
9747
- }
9748
- }
9749
- function requireTrueLength(value) {
9750
- requireU32("trueLength", value);
9751
- if (value > SOURCE_AUTH_MAX_TRUE_LENGTH) {
9752
- throw new Error(`trueLength exceeds the ${SOURCE_AUTH_MAX_TRUE_LENGTH}-byte profile maximum`);
9753
- }
9754
- }
9755
- function sourceAuthObjectDigest(object) {
9756
- return blake3(object);
9757
- }
9758
- function sourceAuthLeafHash(groupId, objectId, digest, trueLength) {
9759
- requireU64("groupId", groupId);
9760
- requireU32("objectId", objectId);
9761
- requireBytes("digest", digest, 32);
9762
- requireTrueLength(trueLength);
9763
- const preimage = new Uint8Array(49);
9764
- const view2 = new DataView(preimage.buffer);
9765
- view2.setBigUint64(1, groupId);
9766
- view2.setUint32(9, objectId);
9767
- preimage.set(digest, 13);
9768
- view2.setUint32(45, trueLength);
9769
- return blake3(preimage);
9770
- }
9771
- function sourceAuthMerkleRoot(entries) {
9772
- if (entries.length === 0)
9773
- throw new Error("Merkle tree requires at least one object");
9774
- if (entries.length > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
9775
- throw new Error(`group exceeds ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP} objects`);
9776
- }
9777
- const groupId = entries[0].groupId;
9778
- const objectIds = /* @__PURE__ */ new Set();
9779
- const ordered = [...entries].sort((left, right) => left.objectId - right.objectId);
9780
- let level = ordered.map((entry) => {
9781
- if (entry.groupId !== groupId)
9782
- throw new Error("Merkle entries must belong to one group");
9783
- if (objectIds.has(entry.objectId))
9784
- throw new Error(`duplicate objectId ${entry.objectId}`);
9785
- objectIds.add(entry.objectId);
9786
- return sourceAuthLeafHash(entry.groupId, entry.objectId, entry.digest, entry.trueLength);
9787
- });
9788
- while (level.length > 1) {
9789
- const parents = [];
9790
- for (let index = 0; index < level.length; index += 2) {
9791
- const left = level[index];
9792
- const right = level[index + 1] ?? left;
9793
- const preimage = new Uint8Array(65);
9794
- preimage[0] = 1;
9795
- preimage.set(left, 1);
9796
- preimage.set(right, 33);
9797
- parents.push(blake3(preimage));
9798
- }
9799
- level = parents;
9800
- }
9801
- return level[0];
9802
- }
9803
- function sourceAuthSignaturePreimage(authScope, groupId, objectCount, root) {
9804
- requireU32("objectCount", objectCount);
9805
- if (objectCount === 0 || objectCount > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
9806
- throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
9807
- }
9808
- requireU64("groupId", groupId);
9809
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
9810
- requireBytes("root", root, 32);
9811
- const preimage = new Uint8Array(100);
9812
- const view2 = new DataView(preimage.buffer);
9813
- preimage.set(SIGNATURE_DOMAIN);
9814
- preimage.set(authScope, 24);
9815
- view2.setBigUint64(56, groupId);
9816
- view2.setUint32(64, objectCount);
9817
- preimage.set(root, 68);
9818
- return preimage;
9819
- }
9820
- function decodeSourceAuthManifestFrame(frame) {
9821
- const frameType = frame[0];
9822
- const expectedLength = frameType === SOURCE_AUTH_OBJECT_ENTRY_FRAME ? SOURCE_AUTH_OBJECT_ENTRY_LENGTH : frameType === SOURCE_AUTH_GROUP_CLOSE_FRAME ? SOURCE_AUTH_GROUP_CLOSE_LENGTH : 0;
9823
- if (expectedLength === 0)
9824
- throw new Error(`unsupported manifest frame type ${frameType}`);
9825
- if (frame.byteLength !== expectedLength) {
9826
- throw new Error(`manifest frame has invalid length ${frame.byteLength} for type ${frameType}`);
9827
- }
9828
- if (frame[1] !== SOURCE_AUTH_MANIFEST_VERSION) {
9829
- throw new Error(`unsupported manifest version ${frame[1]}`);
9830
- }
9831
- if (frame[2] !== 0 || frame[3] !== 0)
9832
- throw new Error("manifest reserved bits must be zero");
9833
- const view2 = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
9834
- const groupId = view2.getBigUint64(4);
9835
- if (frameType === SOURCE_AUTH_OBJECT_ENTRY_FRAME) {
9836
- const entry = {
9837
- kind: "object",
9838
- groupId,
9839
- objectId: view2.getUint32(12),
9840
- trueLength: view2.getUint32(16),
9841
- digest: frame.slice(20, 52)
9842
- };
9843
- requireTrueLength(entry.trueLength);
9844
- return entry;
9845
- }
9846
- const close = {
9847
- kind: "close",
9848
- groupId,
9849
- objectCount: view2.getUint32(12),
9850
- root: frame.slice(16, 48),
9851
- signature: frame.slice(48, 112)
9852
- };
9853
- if (close.objectCount === 0 || close.objectCount > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
9854
- throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
9855
- }
9856
- return close;
9857
- }
10056
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/sha256.js
10057
+ var sha2562 = sha256;
9858
10058
 
9859
- // ../mmt-manifest-verify/dist/verifier.js
9860
- function manifestKeyFor(keys, epoch, kid) {
9861
- if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9862
- return void 0;
9863
- if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9864
- return void 0;
9865
- let signer;
9866
- for (const key of keys) {
9867
- if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9868
- signer = key;
9869
- }
9870
- if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9871
- return void 0;
9872
- return signer.publicKey;
9873
- }
9874
- function manifestBindingId(trackName, sourceSymbolFormat) {
9875
- return JSON.stringify([trackName, sourceSymbolFormat]);
9876
- }
9877
- function createWebCryptoEd25519Verifier(subtle = globalThis.crypto.subtle) {
9878
- return async (publicKey, message, signature) => {
9879
- const keyBytes = Uint8Array.from(publicKey);
9880
- const messageBytes = Uint8Array.from(message);
9881
- const signatureBytes = Uint8Array.from(signature);
9882
- const key = await subtle.importKey("raw", keyBytes.buffer, "Ed25519", false, ["verify"]);
9883
- return subtle.verify("Ed25519", key, signatureBytes.buffer, messageBytes.buffer);
9884
- };
9885
- }
9886
- var FAILURE_REASONS = [
9887
- "sigInvalid",
9888
- "digestMismatch",
9889
- "manifestLate",
9890
- "manifestAbsent",
9891
- "verifierError"
9892
- ];
9893
- var equalBytes = (left, right) => {
10059
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10060
+ var BCPV2_HEADER_LENGTH = 68;
10061
+ var BCPV2_SIGNATURE_LENGTH = 64;
10062
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10063
+ var BCPV2_MAX_RECORD_LENGTH = 1316;
10064
+ var BCPV2_MAX_DIGESTS = 37;
10065
+ var BCPV2_HASH_ALG_SHA256 = 1;
10066
+ var text = new TextEncoder();
10067
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10068
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10069
+ function equalBytes(left, right) {
9894
10070
  if (left.byteLength !== right.byteLength)
9895
10071
  return false;
9896
- let diff = 0;
10072
+ let different = 0;
9897
10073
  for (let index = 0; index < left.byteLength; index++)
9898
- diff |= left[index] ^ right[index];
9899
- return diff === 0;
9900
- };
9901
- var isPromiseLike = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
9902
- var _config, _verifySignature, _onFailure, _tracks2, _stats4, _disposed2, _ManifestVerifier_instances, requireTrack_fn, group_fn, validateIdentity_fn, admitAgainstEntry_fn, rejectOrShadow_fn, resolvePending_fn, closeGroup_fn, finishGroupSignature_fn, verifyAcceptedSignature_fn, failGroup_fn, removePending_fn, quarantine_fn, enforceCap_fn, giveUpOnPending_fn, failOpenTrack_fn, failOpenGroup_fn, releaseAllQuarantine_fn, failure_fn;
9903
- var ManifestVerifier = class {
9904
- constructor(options) {
9905
- __privateAdd(this, _ManifestVerifier_instances);
9906
- __privateAdd(this, _config);
9907
- __privateAdd(this, _verifySignature);
9908
- __privateAdd(this, _onFailure);
9909
- __privateAdd(this, _tracks2, /* @__PURE__ */ new Map());
9910
- __privateAdd(this, _stats4, {
9911
- verified: 0,
9912
- failures: Object.fromEntries(FAILURE_REASONS.map((reason) => [reason, 0])),
9913
- quarantinedBytes: 0
9914
- });
9915
- __privateAdd(this, _disposed2, false);
9916
- __privateSet(this, _config, { ...options.manifestAuth });
9917
- __privateSet(this, _verifySignature, options.verifySignature);
9918
- __privateSet(this, _onFailure, options.onFailure);
10074
+ different |= left[index] ^ right[index];
10075
+ return different === 0;
10076
+ }
10077
+ function u16(value) {
10078
+ const result = new Uint8Array(2);
10079
+ new DataView(result.buffer).setUint16(0, value);
10080
+ return result;
10081
+ }
10082
+ function u322(value) {
10083
+ const result = new Uint8Array(4);
10084
+ new DataView(result.buffer).setUint32(0, value);
10085
+ return result;
10086
+ }
10087
+ function validU32(value) {
10088
+ return Number.isInteger(value) && value >= 0 && value <= 4294967295;
10089
+ }
10090
+ function validPort(value) {
10091
+ return Number.isInteger(value) && value >= 0 && value <= 65535;
10092
+ }
10093
+ function parseIpv4(address) {
10094
+ const fields = address.split(".");
10095
+ if (fields.length !== 4 || fields.some((field) => !/^\d+$/.test(field))) {
10096
+ throw new Error(`invalid IPv4 address ${address}`);
10097
+ }
10098
+ const values = fields.map(Number);
10099
+ if (values.some((value, index) => value > 255 || String(value) !== fields[index])) {
10100
+ throw new Error(`invalid IPv4 address ${address}`);
10101
+ }
10102
+ return Uint8Array.from(values);
10103
+ }
10104
+ function parseIpv6(address) {
10105
+ const compressed = address.includes("::");
10106
+ if ((address.match(/::/g) ?? []).length > 1)
10107
+ throw new Error(`invalid IPv6 address ${address}`);
10108
+ const [leftText, rightText = ""] = address.split("::");
10109
+ const left = leftText ? leftText.split(":") : [];
10110
+ const right = rightText ? rightText.split(":") : [];
10111
+ if (left.some((group) => group.includes(".")) || right.some((group) => group.includes("."))) {
10112
+ throw new Error(`invalid IPv6 address ${address}`);
10113
+ }
10114
+ const missing = 8 - left.length - right.length;
10115
+ if (missing < 0 || !compressed && missing !== 0 || compressed && missing < 1) {
10116
+ throw new Error(`invalid IPv6 address ${address}`);
10117
+ }
10118
+ const groups = [...left, ...Array.from({ length: missing }, () => "0"), ...right];
10119
+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/i.test(group))) {
10120
+ throw new Error(`invalid IPv6 address ${address}`);
10121
+ }
10122
+ const result = new Uint8Array(16);
10123
+ const view2 = new DataView(result.buffer);
10124
+ groups.forEach((group, index) => view2.setUint16(index * 2, Number.parseInt(group, 16)));
10125
+ return result;
10126
+ }
10127
+ function parseBcProvenanceV2Address(address) {
10128
+ if (address.includes(":"))
10129
+ return parseIpv6(address);
10130
+ return parseIpv4(address);
10131
+ }
10132
+ function endpointBytes(endpoint) {
10133
+ if (!validPort(endpoint.port) || !validPort(endpoint.manifestPort) || !validU32(endpoint.streamId)) {
10134
+ throw new Error("invalid BCPV2 endpoint");
9919
10135
  }
9920
- get config() {
9921
- return __privateGet(this, _config);
10136
+ const source = parseBcProvenanceV2Address(endpoint.sourceAddress);
10137
+ const group = parseBcProvenanceV2Address(endpoint.groupAddress);
10138
+ if (source.byteLength !== group.byteLength)
10139
+ throw new Error("endpoint address families differ");
10140
+ return { source, group };
10141
+ }
10142
+ function readU32(view2, offset) {
10143
+ return view2.getUint32(offset);
10144
+ }
10145
+ function readU642(view2, offset) {
10146
+ return view2.getBigUint64(offset);
10147
+ }
10148
+ function decodeBcProvenanceV2Record(input) {
10149
+ const bytes = Uint8Array.from(input);
10150
+ if (bytes.byteLength < BCPV2_MIN_RECORD_LENGTH || bytes.byteLength > BCPV2_MAX_RECORD_LENGTH || (bytes.byteLength - 132) % 32 !== 0) {
10151
+ throw new Error("invalid BCPV2 record length");
9922
10152
  }
9923
- get stats() {
9924
- let quarantined = 0;
9925
- for (const track of __privateGet(this, _tracks2).values())
9926
- quarantined += track.quarantine.length;
9927
- return {
9928
- verified: __privateGet(this, _stats4).verified,
9929
- failures: { ...__privateGet(this, _stats4).failures },
9930
- quarantined,
9931
- quarantinedBytes: __privateGet(this, _stats4).quarantinedBytes
9932
- };
10153
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10154
+ if (!equalBytes(bytes.subarray(0, 4), MAGIC))
10155
+ throw new Error("invalid BCPV2 record magic");
10156
+ const count = view2.getUint16(28);
10157
+ if (count < 1 || count > BCPV2_MAX_DIGESTS || bytes.byteLength !== 132 + count * 32) {
10158
+ throw new Error("invalid BCPV2 record count");
9933
10159
  }
9934
- setMode(mode) {
9935
- __privateSet(this, _config, { ...__privateGet(this, _config), mode });
9936
- if (mode !== "enforce")
9937
- __privateMethod(this, _ManifestVerifier_instances, releaseAllQuarantine_fn).call(this, false);
9938
- }
9939
- registerTrack(context) {
9940
- const bindingId = context.bindingId ?? context.trackName;
9941
- if (__privateGet(this, _tracks2).has(bindingId)) {
9942
- throw new Error(`manifest binding ${bindingId} is already registered`);
9943
- }
9944
- if (!Number.isFinite(context.bitrate) || context.bitrate <= 0) {
9945
- throw new Error("manifest track bitrate must be > 0");
9946
- }
9947
- if (!Number.isFinite(context.groupDurationMs) || context.groupDurationMs <= 0) {
9948
- throw new Error("manifest track groupDurationMs must be > 0");
9949
- }
9950
- if (context.authScope.byteLength !== 32)
9951
- throw new Error("manifest authScope must be 32 bytes");
9952
- for (const key of context.keys) {
9953
- if (key.publicKey.byteLength !== 32)
9954
- throw new Error("manifest keys must carry 32-byte public keys");
9955
- }
9956
- if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
9957
- throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9958
- }
9959
- for (const [name, value] of Object.entries({
9960
- broadcastNamespaceId: context.broadcastNamespaceId,
9961
- trackName: context.trackName,
9962
- codec: context.codec,
9963
- timing: context.timing,
9964
- fecGeometry: context.fecGeometry
9965
- })) {
9966
- if (value.length === 0)
9967
- throw new Error(`manifest ${name} must not be empty`);
9968
- }
9969
- __privateGet(this, _tracks2).set(bindingId, {
9970
- context: { ...context, bindingId },
9971
- groups: /* @__PURE__ */ new Map(),
9972
- quarantine: [],
9973
- quarantinedBytes: 0,
9974
- capBytes: Math.ceil(context.bitrate * context.groupDurationMs / 8e3),
9975
- manifestEntries: 0,
9976
- maxManifestEntries: Math.ceil(context.bitrate * context.groupDurationMs / (8e3 * 52)),
9977
- maxGroups: context.mapper.d + 1
9978
- });
10160
+ const body = bytes.slice(0, bytes.byteLength - BCPV2_SIGNATURE_LENGTH);
10161
+ const digests = [];
10162
+ for (let index = 0; index < count; index++) {
10163
+ digests.push(bytes.slice(BCPV2_HEADER_LENGTH + index * 32, BCPV2_HEADER_LENGTH + (index + 1) * 32));
9979
10164
  }
9980
- ingestManifestFrame(bindingId, frameBytes) {
9981
- const track = __privateMethod(this, _ManifestVerifier_instances, requireTrack_fn).call(this, bindingId);
10165
+ return {
10166
+ kid: readU32(view2, 4),
10167
+ epoch: readU32(view2, 8),
10168
+ mseq: readU642(view2, 12),
10169
+ firstSeq: readU642(view2, 20),
10170
+ count,
10171
+ hashAlg: bytes[30],
10172
+ flags: bytes[31],
10173
+ sent: readU32(view2, 32),
10174
+ ctx: bytes.slice(36, 68),
10175
+ digests,
10176
+ signature: bytes.slice(bytes.byteLength - BCPV2_SIGNATURE_LENGTH),
10177
+ body,
10178
+ raw: bytes
10179
+ };
10180
+ }
10181
+ function bcProvenanceV2SignedMessage(record, endpoint) {
10182
+ const { source, group } = endpointBytes(endpoint);
10183
+ const prefix = new Uint8Array(SIGNING_DOMAIN.byteLength + 4 + source.byteLength + group.byteLength + 2);
10184
+ let offset = 0;
10185
+ prefix.set(SIGNING_DOMAIN, offset);
10186
+ offset += SIGNING_DOMAIN.byteLength;
10187
+ prefix.set(u322(endpoint.streamId), offset);
10188
+ offset += 4;
10189
+ prefix.set(source, offset);
10190
+ offset += source.byteLength;
10191
+ prefix.set(group, offset);
10192
+ offset += group.byteLength;
10193
+ prefix.set(u16(endpoint.manifestPort), offset);
10194
+ const message = new Uint8Array(prefix.byteLength + record.body.byteLength);
10195
+ message.set(prefix);
10196
+ message.set(record.body, prefix.byteLength);
10197
+ return message;
10198
+ }
10199
+ function bcProvenanceV2DatagramDigest(endpoint, payload) {
10200
+ if (payload.byteLength > 65535)
10201
+ throw new Error("datagram payload exceeds u16 length");
10202
+ const { source, group } = endpointBytes(endpoint);
10203
+ const pseudoheader = new Uint8Array(source.byteLength + group.byteLength + 2 + 2 + 2 + 2 + 4);
10204
+ let offset = 0;
10205
+ pseudoheader.set(source, offset);
10206
+ offset += source.byteLength;
10207
+ pseudoheader.set(group, offset);
10208
+ offset += group.byteLength;
10209
+ pseudoheader.set([0, 17], offset);
10210
+ offset += 2;
10211
+ pseudoheader.set(u16(payload.byteLength), offset);
10212
+ offset += 2;
10213
+ pseudoheader.set(u16(endpoint.port), offset);
10214
+ offset += 2;
10215
+ pseudoheader.set(u16(endpoint.port), offset);
10216
+ offset += 2;
10217
+ pseudoheader.set(u322(endpoint.streamId), offset);
10218
+ const input = new Uint8Array(pseudoheader.byteLength + payload.byteLength);
10219
+ input.set(pseudoheader);
10220
+ input.set(payload, pseudoheader.byteLength);
10221
+ return sha2562(input);
10222
+ }
10223
+
10224
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/utils.js
10225
+ var _0n = /* @__PURE__ */ BigInt(0);
10226
+ var _1n = /* @__PURE__ */ BigInt(1);
10227
+ function _abool2(value, title = "") {
10228
+ if (typeof value !== "boolean") {
10229
+ const prefix = title && `"${title}"`;
10230
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
10231
+ }
10232
+ return value;
10233
+ }
10234
+ function _abytes2(value, length, title = "") {
10235
+ const bytes = isBytes(value);
10236
+ const len = value?.length;
10237
+ const needsLen = length !== void 0;
10238
+ if (!bytes || needsLen && len !== length) {
10239
+ const prefix = title && `"${title}" `;
10240
+ const ofLen = needsLen ? ` of length ${length}` : "";
10241
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
10242
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
10243
+ }
10244
+ return value;
10245
+ }
10246
+ function hexToNumber(hex2) {
10247
+ if (typeof hex2 !== "string")
10248
+ throw new Error("hex string expected, got " + typeof hex2);
10249
+ return hex2 === "" ? _0n : BigInt("0x" + hex2);
10250
+ }
10251
+ function bytesToNumberBE(bytes) {
10252
+ return hexToNumber(bytesToHex(bytes));
10253
+ }
10254
+ function bytesToNumberLE(bytes) {
10255
+ abytes(bytes);
10256
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
10257
+ }
10258
+ function numberToBytesBE(n, len) {
10259
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
10260
+ }
10261
+ function numberToBytesLE(n, len) {
10262
+ return numberToBytesBE(n, len).reverse();
10263
+ }
10264
+ function ensureBytes(title, hex2, expectedLength) {
10265
+ let res;
10266
+ if (typeof hex2 === "string") {
9982
10267
  try {
9983
- const frame = decodeSourceAuthManifestFrame(frameBytes);
9984
- const groupId = frame.groupId;
9985
- const group = __privateMethod(this, _ManifestVerifier_instances, group_fn).call(this, track, groupId);
9986
- if (frame.kind === "object") {
9987
- if (group.close || group.signaturePending || group.failed) {
9988
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
9989
- return;
9990
- }
9991
- if (group.entries.has(frame.objectId)) {
9992
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
9993
- return;
9994
- }
9995
- if (group.entries.size >= 4096 || track.manifestEntries >= track.maxManifestEntries) {
9996
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
9997
- return;
9998
- }
9999
- group.entries.set(frame.objectId, frame);
10000
- track.manifestEntries++;
10001
- const pending = group.pending.get(frame.objectId);
10002
- if (pending) {
10003
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestLate");
10004
- __privateMethod(this, _ManifestVerifier_instances, resolvePending_fn).call(this, track, group, pending, frame);
10005
- }
10006
- if (group.pendingClose && group.entries.size === group.pendingClose.objectCount) {
10007
- const close = group.pendingClose;
10008
- group.pendingClose = void 0;
10009
- __privateMethod(this, _ManifestVerifier_instances, closeGroup_fn).call(this, track, groupId, group, close);
10010
- }
10011
- return;
10012
- }
10013
- __privateMethod(this, _ManifestVerifier_instances, closeGroup_fn).call(this, track, groupId, group, frame);
10014
- } catch {
10015
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, bindingId, groupId: 0, objectId: 0 }, "verifierError");
10268
+ res = hexToBytes(hex2);
10269
+ } catch (e) {
10270
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
10016
10271
  }
10272
+ } else if (isBytes(hex2)) {
10273
+ res = Uint8Array.from(hex2);
10274
+ } else {
10275
+ throw new Error(title + " must be hex string or Uint8Array");
10017
10276
  }
10018
- admitObject(identity, data, release, discard) {
10019
- if (__privateGet(this, _config).mode === "off") {
10020
- release();
10021
- return { action: "play", verified: false };
10022
- }
10023
- const track = __privateGet(this, _tracks2).get(identity.bindingId ?? identity.trackName);
10024
- if (!track) {
10025
- release();
10026
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, identity, "verifierError");
10027
- return { action: "play", verified: false, reason: "verifierError" };
10028
- }
10029
- try {
10030
- if (!__privateMethod(this, _ManifestVerifier_instances, validateIdentity_fn).call(this, track, identity)) {
10031
- return __privateMethod(this, _ManifestVerifier_instances, rejectOrShadow_fn).call(this, identity, release, "digestMismatch");
10277
+ const len = res.length;
10278
+ if (typeof expectedLength === "number" && len !== expectedLength)
10279
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
10280
+ return res;
10281
+ }
10282
+ function equalBytes2(a, b) {
10283
+ if (a.length !== b.length)
10284
+ return false;
10285
+ let diff = 0;
10286
+ for (let i = 0; i < a.length; i++)
10287
+ diff |= a[i] ^ b[i];
10288
+ return diff === 0;
10289
+ }
10290
+ function copyBytes(bytes) {
10291
+ return Uint8Array.from(bytes);
10292
+ }
10293
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
10294
+ function inRange(n, min, max) {
10295
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
10296
+ }
10297
+ function aInRange(title, n, min, max) {
10298
+ if (!inRange(n, min, max))
10299
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
10300
+ }
10301
+ function bitLen(n) {
10302
+ let len;
10303
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
10304
+ ;
10305
+ return len;
10306
+ }
10307
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
10308
+ function _validateObject(object, fields, optFields = {}) {
10309
+ if (!object || typeof object !== "object")
10310
+ throw new Error("expected valid options object");
10311
+ function checkField(fieldName, expectedType, isOpt) {
10312
+ const val = object[fieldName];
10313
+ if (isOpt && val === void 0)
10314
+ return;
10315
+ const current = typeof val;
10316
+ if (current !== expectedType || val === null)
10317
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
10318
+ }
10319
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
10320
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
10321
+ }
10322
+ var notImplemented = () => {
10323
+ throw new Error("not implemented");
10324
+ };
10325
+ function memoized(fn) {
10326
+ const map = /* @__PURE__ */ new WeakMap();
10327
+ return (arg, ...args) => {
10328
+ const val = map.get(arg);
10329
+ if (val !== void 0)
10330
+ return val;
10331
+ const computed = fn(arg, ...args);
10332
+ map.set(arg, computed);
10333
+ return computed;
10334
+ };
10335
+ }
10336
+
10337
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/modular.js
10338
+ var _0n2 = BigInt(0);
10339
+ var _1n2 = BigInt(1);
10340
+ var _2n = /* @__PURE__ */ BigInt(2);
10341
+ var _3n = /* @__PURE__ */ BigInt(3);
10342
+ var _4n = /* @__PURE__ */ BigInt(4);
10343
+ var _5n = /* @__PURE__ */ BigInt(5);
10344
+ var _7n = /* @__PURE__ */ BigInt(7);
10345
+ var _8n = /* @__PURE__ */ BigInt(8);
10346
+ var _9n = /* @__PURE__ */ BigInt(9);
10347
+ var _16n = /* @__PURE__ */ BigInt(16);
10348
+ function mod(a, b) {
10349
+ const result = a % b;
10350
+ return result >= _0n2 ? result : b + result;
10351
+ }
10352
+ function pow2(x, power, modulo) {
10353
+ let res = x;
10354
+ while (power-- > _0n2) {
10355
+ res *= res;
10356
+ res %= modulo;
10357
+ }
10358
+ return res;
10359
+ }
10360
+ function invert(number, modulo) {
10361
+ if (number === _0n2)
10362
+ throw new Error("invert: expected non-zero number");
10363
+ if (modulo <= _0n2)
10364
+ throw new Error("invert: expected positive modulus, got " + modulo);
10365
+ let a = mod(number, modulo);
10366
+ let b = modulo;
10367
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
10368
+ while (a !== _0n2) {
10369
+ const q = b / a;
10370
+ const r = b % a;
10371
+ const m = x - u * q;
10372
+ const n = y - v * q;
10373
+ b = a, a = r, x = u, y = v, u = m, v = n;
10374
+ }
10375
+ const gcd = b;
10376
+ if (gcd !== _1n2)
10377
+ throw new Error("invert: does not exist");
10378
+ return mod(x, modulo);
10379
+ }
10380
+ function assertIsSquare(Fp2, root, n) {
10381
+ if (!Fp2.eql(Fp2.sqr(root), n))
10382
+ throw new Error("Cannot find square root");
10383
+ }
10384
+ function sqrt3mod4(Fp2, n) {
10385
+ const p1div4 = (Fp2.ORDER + _1n2) / _4n;
10386
+ const root = Fp2.pow(n, p1div4);
10387
+ assertIsSquare(Fp2, root, n);
10388
+ return root;
10389
+ }
10390
+ function sqrt5mod8(Fp2, n) {
10391
+ const p5div8 = (Fp2.ORDER - _5n) / _8n;
10392
+ const n2 = Fp2.mul(n, _2n);
10393
+ const v = Fp2.pow(n2, p5div8);
10394
+ const nv = Fp2.mul(n, v);
10395
+ const i = Fp2.mul(Fp2.mul(nv, _2n), v);
10396
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
10397
+ assertIsSquare(Fp2, root, n);
10398
+ return root;
10399
+ }
10400
+ function sqrt9mod16(P) {
10401
+ const Fp_ = Field(P);
10402
+ const tn = tonelliShanks(P);
10403
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
10404
+ const c2 = tn(Fp_, c1);
10405
+ const c3 = tn(Fp_, Fp_.neg(c1));
10406
+ const c4 = (P + _7n) / _16n;
10407
+ return (Fp2, n) => {
10408
+ let tv1 = Fp2.pow(n, c4);
10409
+ let tv2 = Fp2.mul(tv1, c1);
10410
+ const tv3 = Fp2.mul(tv1, c2);
10411
+ const tv4 = Fp2.mul(tv1, c3);
10412
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
10413
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
10414
+ tv1 = Fp2.cmov(tv1, tv2, e1);
10415
+ tv2 = Fp2.cmov(tv4, tv3, e2);
10416
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
10417
+ const root = Fp2.cmov(tv1, tv2, e3);
10418
+ assertIsSquare(Fp2, root, n);
10419
+ return root;
10420
+ };
10421
+ }
10422
+ function tonelliShanks(P) {
10423
+ if (P < _3n)
10424
+ throw new Error("sqrt is not defined for small field");
10425
+ let Q = P - _1n2;
10426
+ let S = 0;
10427
+ while (Q % _2n === _0n2) {
10428
+ Q /= _2n;
10429
+ S++;
10430
+ }
10431
+ let Z = _2n;
10432
+ const _Fp = Field(P);
10433
+ while (FpLegendre(_Fp, Z) === 1) {
10434
+ if (Z++ > 1e3)
10435
+ throw new Error("Cannot find square root: probably non-prime P");
10436
+ }
10437
+ if (S === 1)
10438
+ return sqrt3mod4;
10439
+ let cc = _Fp.pow(Z, Q);
10440
+ const Q1div2 = (Q + _1n2) / _2n;
10441
+ return function tonelliSlow(Fp2, n) {
10442
+ if (Fp2.is0(n))
10443
+ return n;
10444
+ if (FpLegendre(Fp2, n) !== 1)
10445
+ throw new Error("Cannot find square root");
10446
+ let M = S;
10447
+ let c = Fp2.mul(Fp2.ONE, cc);
10448
+ let t = Fp2.pow(n, Q);
10449
+ let R = Fp2.pow(n, Q1div2);
10450
+ while (!Fp2.eql(t, Fp2.ONE)) {
10451
+ if (Fp2.is0(t))
10452
+ return Fp2.ZERO;
10453
+ let i = 1;
10454
+ let t_tmp = Fp2.sqr(t);
10455
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
10456
+ i++;
10457
+ t_tmp = Fp2.sqr(t_tmp);
10458
+ if (i === M)
10459
+ throw new Error("Cannot find square root");
10032
10460
  }
10033
- const group = __privateMethod(this, _ManifestVerifier_instances, group_fn).call(this, track, BigInt(identity.groupId));
10034
- if (group.failed === "sigInvalid" || group.failed === "digestMismatch") {
10035
- return __privateMethod(this, _ManifestVerifier_instances, rejectOrShadow_fn).call(this, identity, release, group.failed);
10461
+ const exponent = _1n2 << BigInt(M - i - 1);
10462
+ const b = Fp2.pow(c, exponent);
10463
+ M = i;
10464
+ c = Fp2.sqr(b);
10465
+ t = Fp2.mul(t, c);
10466
+ R = Fp2.mul(R, b);
10467
+ }
10468
+ return R;
10469
+ };
10470
+ }
10471
+ function FpSqrt(P) {
10472
+ if (P % _4n === _3n)
10473
+ return sqrt3mod4;
10474
+ if (P % _8n === _5n)
10475
+ return sqrt5mod8;
10476
+ if (P % _16n === _9n)
10477
+ return sqrt9mod16(P);
10478
+ return tonelliShanks(P);
10479
+ }
10480
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
10481
+ var FIELD_FIELDS = [
10482
+ "create",
10483
+ "isValid",
10484
+ "is0",
10485
+ "neg",
10486
+ "inv",
10487
+ "sqrt",
10488
+ "sqr",
10489
+ "eql",
10490
+ "add",
10491
+ "sub",
10492
+ "mul",
10493
+ "pow",
10494
+ "div",
10495
+ "addN",
10496
+ "subN",
10497
+ "mulN",
10498
+ "sqrN"
10499
+ ];
10500
+ function validateField(field) {
10501
+ const initial = {
10502
+ ORDER: "bigint",
10503
+ MASK: "bigint",
10504
+ BYTES: "number",
10505
+ BITS: "number"
10506
+ };
10507
+ const opts = FIELD_FIELDS.reduce((map, val) => {
10508
+ map[val] = "function";
10509
+ return map;
10510
+ }, initial);
10511
+ _validateObject(field, opts);
10512
+ return field;
10513
+ }
10514
+ function FpPow(Fp2, num, power) {
10515
+ if (power < _0n2)
10516
+ throw new Error("invalid exponent, negatives unsupported");
10517
+ if (power === _0n2)
10518
+ return Fp2.ONE;
10519
+ if (power === _1n2)
10520
+ return num;
10521
+ let p = Fp2.ONE;
10522
+ let d = num;
10523
+ while (power > _0n2) {
10524
+ if (power & _1n2)
10525
+ p = Fp2.mul(p, d);
10526
+ d = Fp2.sqr(d);
10527
+ power >>= _1n2;
10528
+ }
10529
+ return p;
10530
+ }
10531
+ function FpInvertBatch(Fp2, nums, passZero = false) {
10532
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
10533
+ const multipliedAcc = nums.reduce((acc, num, i) => {
10534
+ if (Fp2.is0(num))
10535
+ return acc;
10536
+ inverted[i] = acc;
10537
+ return Fp2.mul(acc, num);
10538
+ }, Fp2.ONE);
10539
+ const invertedAcc = Fp2.inv(multipliedAcc);
10540
+ nums.reduceRight((acc, num, i) => {
10541
+ if (Fp2.is0(num))
10542
+ return acc;
10543
+ inverted[i] = Fp2.mul(acc, inverted[i]);
10544
+ return Fp2.mul(acc, num);
10545
+ }, invertedAcc);
10546
+ return inverted;
10547
+ }
10548
+ function FpLegendre(Fp2, n) {
10549
+ const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
10550
+ const powered = Fp2.pow(n, p1mod2);
10551
+ const yes = Fp2.eql(powered, Fp2.ONE);
10552
+ const zero = Fp2.eql(powered, Fp2.ZERO);
10553
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
10554
+ if (!yes && !zero && !no)
10555
+ throw new Error("invalid Legendre symbol result");
10556
+ return yes ? 1 : zero ? 0 : -1;
10557
+ }
10558
+ function nLength(n, nBitLength) {
10559
+ if (nBitLength !== void 0)
10560
+ anumber(nBitLength);
10561
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10562
+ const nByteLength = Math.ceil(_nBitLength / 8);
10563
+ return { nBitLength: _nBitLength, nByteLength };
10564
+ }
10565
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
10566
+ if (ORDER <= _0n2)
10567
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10568
+ let _nbitLength = void 0;
10569
+ let _sqrt = void 0;
10570
+ let modFromBytes = false;
10571
+ let allowedLengths = void 0;
10572
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
10573
+ if (opts.sqrt || isLE)
10574
+ throw new Error("cannot specify opts in two arguments");
10575
+ const _opts = bitLenOrOpts;
10576
+ if (_opts.BITS)
10577
+ _nbitLength = _opts.BITS;
10578
+ if (_opts.sqrt)
10579
+ _sqrt = _opts.sqrt;
10580
+ if (typeof _opts.isLE === "boolean")
10581
+ isLE = _opts.isLE;
10582
+ if (typeof _opts.modFromBytes === "boolean")
10583
+ modFromBytes = _opts.modFromBytes;
10584
+ allowedLengths = _opts.allowedLengths;
10585
+ } else {
10586
+ if (typeof bitLenOrOpts === "number")
10587
+ _nbitLength = bitLenOrOpts;
10588
+ if (opts.sqrt)
10589
+ _sqrt = opts.sqrt;
10590
+ }
10591
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
10592
+ if (BYTES > 2048)
10593
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10594
+ let sqrtP;
10595
+ const f = Object.freeze({
10596
+ ORDER,
10597
+ isLE,
10598
+ BITS,
10599
+ BYTES,
10600
+ MASK: bitMask(BITS),
10601
+ ZERO: _0n2,
10602
+ ONE: _1n2,
10603
+ allowedLengths,
10604
+ create: (num) => mod(num, ORDER),
10605
+ isValid: (num) => {
10606
+ if (typeof num !== "bigint")
10607
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
10608
+ return _0n2 <= num && num < ORDER;
10609
+ },
10610
+ is0: (num) => num === _0n2,
10611
+ // is valid and invertible
10612
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
10613
+ isOdd: (num) => (num & _1n2) === _1n2,
10614
+ neg: (num) => mod(-num, ORDER),
10615
+ eql: (lhs, rhs) => lhs === rhs,
10616
+ sqr: (num) => mod(num * num, ORDER),
10617
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
10618
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
10619
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
10620
+ pow: (num, power) => FpPow(f, num, power),
10621
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
10622
+ // Same as above, but doesn't normalize
10623
+ sqrN: (num) => num * num,
10624
+ addN: (lhs, rhs) => lhs + rhs,
10625
+ subN: (lhs, rhs) => lhs - rhs,
10626
+ mulN: (lhs, rhs) => lhs * rhs,
10627
+ inv: (num) => invert(num, ORDER),
10628
+ sqrt: _sqrt || ((n) => {
10629
+ if (!sqrtP)
10630
+ sqrtP = FpSqrt(ORDER);
10631
+ return sqrtP(f, n);
10632
+ }),
10633
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
10634
+ fromBytes: (bytes, skipValidation = true) => {
10635
+ if (allowedLengths) {
10636
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10637
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10638
+ }
10639
+ const padded = new Uint8Array(BYTES);
10640
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10641
+ bytes = padded;
10036
10642
  }
10037
- const entry = group.entries.get(identity.objectId);
10038
- if (entry)
10039
- return __privateMethod(this, _ManifestVerifier_instances, admitAgainstEntry_fn).call(this, track, group, identity, data, release, entry, discard);
10040
- if (__privateGet(this, _config).mode === "shadow" || __privateGet(this, _config).onMissingManifest === "fallback-shadow") {
10041
- release();
10042
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, identity, "manifestAbsent");
10043
- return { action: "play", verified: false, reason: "manifestAbsent" };
10643
+ if (bytes.length !== BYTES)
10644
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10645
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10646
+ if (modFromBytes)
10647
+ scalar = mod(scalar, ORDER);
10648
+ if (!skipValidation) {
10649
+ if (!f.isValid(scalar))
10650
+ throw new Error("invalid field element: outside of range 0..ORDER");
10044
10651
  }
10045
- if (!__privateMethod(this, _ManifestVerifier_instances, quarantine_fn).call(this, track, group, { identity, data, release, discard, bytes: data.byteLength })) {
10046
- return { action: "drop", verified: false };
10652
+ return scalar;
10653
+ },
10654
+ // TODO: we don't need it here, move out to separate fn
10655
+ invertBatch: (lst) => FpInvertBatch(f, lst),
10656
+ // We can't move this out because Fp6, Fp12 implement it
10657
+ // and it's unclear what to return in there.
10658
+ cmov: (a, b, c) => c ? b : a
10659
+ });
10660
+ return Object.freeze(f);
10661
+ }
10662
+
10663
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/curve.js
10664
+ var _0n3 = BigInt(0);
10665
+ var _1n3 = BigInt(1);
10666
+ function negateCt(condition, item) {
10667
+ const neg = item.negate();
10668
+ return condition ? neg : item;
10669
+ }
10670
+ function normalizeZ(c, points) {
10671
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10672
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10673
+ }
10674
+ function validateW(W, bits) {
10675
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10676
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10677
+ }
10678
+ function calcWOpts(W, scalarBits) {
10679
+ validateW(W, scalarBits);
10680
+ const windows = Math.ceil(scalarBits / W) + 1;
10681
+ const windowSize = 2 ** (W - 1);
10682
+ const maxNumber = 2 ** W;
10683
+ const mask = bitMask(W);
10684
+ const shiftBy = BigInt(W);
10685
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10686
+ }
10687
+ function calcOffsets(n, window, wOpts) {
10688
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10689
+ let wbits = Number(n & mask);
10690
+ let nextN = n >> shiftBy;
10691
+ if (wbits > windowSize) {
10692
+ wbits -= maxNumber;
10693
+ nextN += _1n3;
10694
+ }
10695
+ const offsetStart = window * windowSize;
10696
+ const offset = offsetStart + Math.abs(wbits) - 1;
10697
+ const isZero = wbits === 0;
10698
+ const isNeg = wbits < 0;
10699
+ const isNegF = window % 2 !== 0;
10700
+ const offsetF = offsetStart;
10701
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10702
+ }
10703
+ function validateMSMPoints(points, c) {
10704
+ if (!Array.isArray(points))
10705
+ throw new Error("array expected");
10706
+ points.forEach((p, i) => {
10707
+ if (!(p instanceof c))
10708
+ throw new Error("invalid point at index " + i);
10709
+ });
10710
+ }
10711
+ function validateMSMScalars(scalars, field) {
10712
+ if (!Array.isArray(scalars))
10713
+ throw new Error("array of scalars expected");
10714
+ scalars.forEach((s, i) => {
10715
+ if (!field.isValid(s))
10716
+ throw new Error("invalid scalar at index " + i);
10717
+ });
10718
+ }
10719
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10720
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10721
+ function getW(P) {
10722
+ return pointWindowSizes.get(P) || 1;
10723
+ }
10724
+ function assert0(n) {
10725
+ if (n !== _0n3)
10726
+ throw new Error("invalid wNAF");
10727
+ }
10728
+ var wNAF = class {
10729
+ // Parametrized with a given Point class (not individual point)
10730
+ constructor(Point, bits) {
10731
+ this.BASE = Point.BASE;
10732
+ this.ZERO = Point.ZERO;
10733
+ this.Fn = Point.Fn;
10734
+ this.bits = bits;
10735
+ }
10736
+ // non-const time multiplication ladder
10737
+ _unsafeLadder(elm, n, p = this.ZERO) {
10738
+ let d = elm;
10739
+ while (n > _0n3) {
10740
+ if (n & _1n3)
10741
+ p = p.add(d);
10742
+ d = d.double();
10743
+ n >>= _1n3;
10744
+ }
10745
+ return p;
10746
+ }
10747
+ /**
10748
+ * Creates a wNAF precomputation window. Used for caching.
10749
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10750
+ * Number of precomputed points depends on the curve size:
10751
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10752
+ * - 𝑊 is the window size
10753
+ * - 𝑛 is the bitlength of the curve order.
10754
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10755
+ * @param point Point instance
10756
+ * @param W window size
10757
+ * @returns precomputed point tables flattened to a single array
10758
+ */
10759
+ precomputeWindow(point, W) {
10760
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10761
+ const points = [];
10762
+ let p = point;
10763
+ let base = p;
10764
+ for (let window = 0; window < windows; window++) {
10765
+ base = p;
10766
+ points.push(base);
10767
+ for (let i = 1; i < windowSize; i++) {
10768
+ base = base.add(p);
10769
+ points.push(base);
10047
10770
  }
10048
- return { action: "stall", verified: false };
10049
- } catch {
10050
- release();
10051
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, identity, "verifierError");
10052
- return { action: "play", verified: false, reason: "verifierError" };
10771
+ p = base.double();
10053
10772
  }
10773
+ return points;
10054
10774
  }
10055
- dispose() {
10056
- if (__privateGet(this, _disposed2))
10057
- return;
10058
- __privateSet(this, _disposed2, true);
10059
- __privateMethod(this, _ManifestVerifier_instances, releaseAllQuarantine_fn).call(this, false);
10060
- __privateGet(this, _tracks2).clear();
10061
- }
10062
- };
10063
- _config = new WeakMap();
10064
- _verifySignature = new WeakMap();
10065
- _onFailure = new WeakMap();
10066
- _tracks2 = new WeakMap();
10067
- _stats4 = new WeakMap();
10068
- _disposed2 = new WeakMap();
10069
- _ManifestVerifier_instances = new WeakSet();
10070
- requireTrack_fn = function(bindingId) {
10071
- const track = __privateGet(this, _tracks2).get(bindingId);
10072
- if (!track)
10073
- throw new Error(`unknown manifest binding ${bindingId}`);
10074
- return track;
10075
- };
10076
- group_fn = function(track, groupId) {
10077
- let group = track.groups.get(groupId);
10078
- if (!group) {
10079
- group = { entries: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), rootVerified: false };
10080
- track.groups.set(groupId, group);
10081
- while (track.groups.size > track.maxGroups) {
10082
- const oldest = track.groups.entries().next().value;
10083
- if (!oldest)
10084
- break;
10085
- const [oldestId, oldestGroup] = oldest;
10086
- for (const pending of [...oldestGroup.pending.values()]) {
10087
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, oldestGroup, pending);
10088
- __privateMethod(this, _ManifestVerifier_instances, giveUpOnPending_fn).call(this, pending);
10089
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
10775
+ /**
10776
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10777
+ * More compact implementation:
10778
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10779
+ * @returns real and fake (for const-time) points
10780
+ */
10781
+ wNAF(W, precomputes, n) {
10782
+ if (!this.Fn.isValid(n))
10783
+ throw new Error("invalid scalar");
10784
+ let p = this.ZERO;
10785
+ let f = this.BASE;
10786
+ const wo = calcWOpts(W, this.bits);
10787
+ for (let window = 0; window < wo.windows; window++) {
10788
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10789
+ n = nextN;
10790
+ if (isZero) {
10791
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10792
+ } else {
10793
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10090
10794
  }
10091
- track.manifestEntries -= oldestGroup.entries.size;
10092
- track.groups.delete(oldestId);
10093
10795
  }
10796
+ assert0(n);
10797
+ return { p, f };
10094
10798
  }
10095
- return group;
10096
- };
10097
- validateIdentity_fn = function(track, identity) {
10098
- const coordinates = track.context.mapper.derive(Number(identity.groupId), identity.objectId);
10099
- return identity.ssId === void 0 || coordinates.ssId === identity.ssId;
10100
- };
10101
- admitAgainstEntry_fn = function(track, group, identity, data, release, entry, discard) {
10102
- if (entry.trueLength !== data.byteLength) {
10103
- return __privateMethod(this, _ManifestVerifier_instances, rejectOrShadow_fn).call(this, identity, release, "digestMismatch");
10104
- }
10105
- const digestMatches = equalBytes(sourceAuthObjectDigest(data.subarray(0, entry.trueLength)), entry.digest);
10106
- if (!digestMatches)
10107
- return __privateMethod(this, _ManifestVerifier_instances, rejectOrShadow_fn).call(this, identity, release, "digestMismatch");
10108
- if (!track.context.manifestChannelAuthenticated && !group.rootVerified) {
10109
- if (__privateGet(this, _config).mode === "shadow") {
10110
- release();
10111
- return { action: "play", verified: false };
10112
- }
10113
- if (!__privateMethod(this, _ManifestVerifier_instances, quarantine_fn).call(this, track, group, { identity, data, release, discard, bytes: data.byteLength })) {
10114
- return { action: "drop", verified: false };
10115
- }
10116
- return { action: "stall", verified: false };
10117
- }
10118
- release();
10119
- __privateGet(this, _stats4).verified++;
10120
- return { action: "play", verified: true };
10121
- };
10122
- rejectOrShadow_fn = function(identity, release, reason) {
10123
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, identity, reason);
10124
- if (__privateGet(this, _config).mode === "enforce") {
10125
- console.warn(JSON.stringify({ event: "manifest-enforce-drop", track: identity.trackName, group: String(identity.groupId), object: identity.objectId, reason }));
10126
- return { action: "drop", verified: false, reason };
10127
- }
10128
- release();
10129
- return { action: "play", verified: false, reason };
10130
- };
10131
- resolvePending_fn = function(track, group, pending, entry) {
10132
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10133
- __privateMethod(this, _ManifestVerifier_instances, admitAgainstEntry_fn).call(this, track, group, pending.identity, pending.data, pending.release, entry, pending.discard);
10134
- };
10135
- closeGroup_fn = function(track, groupId, group, close) {
10136
- if (group.close || group.signaturePending)
10137
- return;
10138
- const entries = [...group.entries.values()];
10139
- if (entries.length !== close.objectCount) {
10140
- group.pendingClose = close;
10141
- const hadPending = group.pending.size > 0;
10142
- if (__privateGet(this, _config).onMissingManifest === "fallback-shadow" || __privateGet(this, _config).mode === "shadow") {
10143
- for (const pending of [...group.pending.values()]) {
10144
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10145
- pending.release();
10146
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
10147
- }
10148
- } else {
10149
- for (const pending of group.pending.values()) {
10150
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
10799
+ /**
10800
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10801
+ * @param acc accumulator point to add result of multiplication
10802
+ * @returns point
10803
+ */
10804
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10805
+ const wo = calcWOpts(W, this.bits);
10806
+ for (let window = 0; window < wo.windows; window++) {
10807
+ if (n === _0n3)
10808
+ break;
10809
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10810
+ n = nextN;
10811
+ if (isZero) {
10812
+ continue;
10813
+ } else {
10814
+ const item = precomputes[offset];
10815
+ acc = acc.add(isNeg ? item.negate() : item);
10151
10816
  }
10152
10817
  }
10153
- if (!hadPending) {
10154
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, groupId, objectId: 0 }, "manifestAbsent");
10818
+ assert0(n);
10819
+ return acc;
10820
+ }
10821
+ getPrecomputes(W, point, transform) {
10822
+ let comp = pointPrecomputes.get(point);
10823
+ if (!comp) {
10824
+ comp = this.precomputeWindow(point, W);
10825
+ if (W !== 1) {
10826
+ if (typeof transform === "function")
10827
+ comp = transform(comp);
10828
+ pointPrecomputes.set(point, comp);
10829
+ }
10155
10830
  }
10156
- return;
10831
+ return comp;
10157
10832
  }
10158
- if (!equalBytes(sourceAuthMerkleRoot(entries), close.root)) {
10159
- group.failed = "digestMismatch";
10160
- __privateMethod(this, _ManifestVerifier_instances, failGroup_fn).call(this, track, groupId, group, "digestMismatch");
10161
- return;
10833
+ cached(point, scalar, transform) {
10834
+ const W = getW(point);
10835
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10162
10836
  }
10163
- const preimage = sourceAuthSignaturePreimage(track.context.authScope, close.groupId, close.objectCount, close.root);
10164
- let signatureValid;
10165
- try {
10166
- signatureValid = __privateMethod(this, _ManifestVerifier_instances, verifyAcceptedSignature_fn).call(this, track, preimage, close.signature);
10167
- } catch {
10168
- __privateMethod(this, _ManifestVerifier_instances, failOpenGroup_fn).call(this, track, groupId, group);
10169
- return;
10837
+ unsafe(point, scalar, transform, prev) {
10838
+ const W = getW(point);
10839
+ if (W === 1)
10840
+ return this._unsafeLadder(point, scalar, prev);
10841
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10170
10842
  }
10171
- if (isPromiseLike(signatureValid)) {
10172
- group.signaturePending = true;
10173
- void signatureValid.then((valid) => {
10174
- if (__privateGet(this, _disposed2))
10175
- return;
10176
- group.signaturePending = false;
10177
- __privateMethod(this, _ManifestVerifier_instances, finishGroupSignature_fn).call(this, track, groupId, group, close, valid);
10178
- }, () => {
10179
- if (__privateGet(this, _disposed2))
10180
- return;
10181
- group.signaturePending = false;
10182
- __privateMethod(this, _ManifestVerifier_instances, failOpenGroup_fn).call(this, track, groupId, group);
10183
- });
10184
- return;
10843
+ // We calculate precomputes for elliptic curve point multiplication
10844
+ // using windowed method. This specifies window size and
10845
+ // stores precomputed values. Usually only base point would be precomputed.
10846
+ createCache(P, W) {
10847
+ validateW(W, this.bits);
10848
+ pointWindowSizes.set(P, W);
10849
+ pointPrecomputes.delete(P);
10185
10850
  }
10186
- __privateMethod(this, _ManifestVerifier_instances, finishGroupSignature_fn).call(this, track, groupId, group, close, signatureValid);
10187
- };
10188
- finishGroupSignature_fn = function(track, groupId, group, close, signatureValid) {
10189
- if (!signatureValid) {
10190
- group.failed = "sigInvalid";
10191
- __privateMethod(this, _ManifestVerifier_instances, failGroup_fn).call(this, track, groupId, group, "sigInvalid");
10192
- return;
10193
- }
10194
- group.failed = void 0;
10195
- group.close = close;
10196
- group.pendingClose = void 0;
10197
- group.rootVerified = true;
10198
- for (const pending of [...group.pending.values()]) {
10199
- const entry = group.entries.get(pending.identity.objectId);
10200
- if (entry)
10201
- __privateMethod(this, _ManifestVerifier_instances, resolvePending_fn).call(this, track, group, pending, entry);
10202
- else if (__privateGet(this, _config).onMissingManifest === "fallback-shadow") {
10203
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10204
- pending.release();
10205
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
10206
- }
10851
+ hasCache(elm) {
10852
+ return getW(elm) !== 1;
10207
10853
  }
10208
10854
  };
10209
- verifyAcceptedSignature_fn = function(track, message, signature) {
10210
- const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
10211
- const pending = [];
10212
- let hadSynchronousError = false;
10213
- for (const key of keys) {
10855
+ function pippenger(c, fieldN, points, scalars) {
10856
+ validateMSMPoints(points, c);
10857
+ validateMSMScalars(scalars, fieldN);
10858
+ const plength = points.length;
10859
+ const slength = scalars.length;
10860
+ if (plength !== slength)
10861
+ throw new Error("arrays of points and scalars must have equal length");
10862
+ const zero = c.ZERO;
10863
+ const wbits = bitLen(BigInt(plength));
10864
+ let windowSize = 1;
10865
+ if (wbits > 12)
10866
+ windowSize = wbits - 3;
10867
+ else if (wbits > 4)
10868
+ windowSize = wbits - 2;
10869
+ else if (wbits > 0)
10870
+ windowSize = 2;
10871
+ const MASK = bitMask(windowSize);
10872
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
10873
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
10874
+ let sum = zero;
10875
+ for (let i = lastBits; i >= 0; i -= windowSize) {
10876
+ buckets.fill(zero);
10877
+ for (let j = 0; j < slength; j++) {
10878
+ const scalar = scalars[j];
10879
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
10880
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
10881
+ }
10882
+ let resI = zero;
10883
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
10884
+ sumI = sumI.add(buckets[j]);
10885
+ resI = resI.add(sumI);
10886
+ }
10887
+ sum = sum.add(resI);
10888
+ if (i !== 0)
10889
+ for (let j = 0; j < windowSize; j++)
10890
+ sum = sum.double();
10891
+ }
10892
+ return sum;
10893
+ }
10894
+ function createField(order, field, isLE) {
10895
+ if (field) {
10896
+ if (field.ORDER !== order)
10897
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10898
+ validateField(field);
10899
+ return field;
10900
+ } else {
10901
+ return Field(order, { isLE });
10902
+ }
10903
+ }
10904
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10905
+ if (FpFnLE === void 0)
10906
+ FpFnLE = type === "edwards";
10907
+ if (!CURVE || typeof CURVE !== "object")
10908
+ throw new Error(`expected valid ${type} CURVE object`);
10909
+ for (const p of ["p", "n", "h"]) {
10910
+ const val = CURVE[p];
10911
+ if (!(typeof val === "bigint" && val > _0n3))
10912
+ throw new Error(`CURVE.${p} must be positive bigint`);
10913
+ }
10914
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10915
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10916
+ const _b = type === "weierstrass" ? "b" : "d";
10917
+ const params = ["Gx", "Gy", "a", _b];
10918
+ for (const p of params) {
10919
+ if (!Fp2.isValid(CURVE[p]))
10920
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10921
+ }
10922
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10923
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
10924
+ }
10925
+
10926
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/edwards.js
10927
+ var _0n4 = BigInt(0);
10928
+ var _1n4 = BigInt(1);
10929
+ var _2n2 = BigInt(2);
10930
+ var _8n2 = BigInt(8);
10931
+ function isEdValidXY(Fp2, CURVE, x, y) {
10932
+ const x2 = Fp2.sqr(x);
10933
+ const y2 = Fp2.sqr(y);
10934
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
10935
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
10936
+ return Fp2.eql(left, right);
10937
+ }
10938
+ function edwards(params, extraOpts = {}) {
10939
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
10940
+ const { Fp: Fp2, Fn: Fn2 } = validated;
10941
+ let CURVE = validated.CURVE;
10942
+ const { h: cofactor } = CURVE;
10943
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
10944
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
10945
+ const modP = (n) => Fp2.create(n);
10946
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
10214
10947
  try {
10215
- const result = __privateGet(this, _verifySignature).call(this, key, message, signature);
10216
- if (isPromiseLike(result)) {
10217
- pending.push(Promise.resolve(result).then((valid) => valid, () => "error"));
10218
- } else if (result) {
10219
- return true;
10220
- }
10221
- } catch {
10222
- hadSynchronousError = true;
10948
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
10949
+ } catch (e) {
10950
+ return { isValid: false, value: _0n4 };
10223
10951
  }
10952
+ });
10953
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
10954
+ throw new Error("bad curve params: generator point");
10955
+ function acoord(title, n, banZero = false) {
10956
+ const min = banZero ? _1n4 : _0n4;
10957
+ aInRange("coordinate " + title, n, min, MASK);
10958
+ return n;
10959
+ }
10960
+ function aextpoint(other) {
10961
+ if (!(other instanceof Point))
10962
+ throw new Error("ExtendedPoint expected");
10963
+ }
10964
+ const toAffineMemo = memoized((p, iz) => {
10965
+ const { X, Y, Z } = p;
10966
+ const is0 = p.is0();
10967
+ if (iz == null)
10968
+ iz = is0 ? _8n2 : Fp2.inv(Z);
10969
+ const x = modP(X * iz);
10970
+ const y = modP(Y * iz);
10971
+ const zz = Fp2.mul(Z, iz);
10972
+ if (is0)
10973
+ return { x: _0n4, y: _1n4 };
10974
+ if (zz !== _1n4)
10975
+ throw new Error("invZ was invalid");
10976
+ return { x, y };
10977
+ });
10978
+ const assertValidMemo = memoized((p) => {
10979
+ const { a, d } = CURVE;
10980
+ if (p.is0())
10981
+ throw new Error("bad point: ZERO");
10982
+ const { X, Y, Z, T } = p;
10983
+ const X2 = modP(X * X);
10984
+ const Y2 = modP(Y * Y);
10985
+ const Z2 = modP(Z * Z);
10986
+ const Z4 = modP(Z2 * Z2);
10987
+ const aX2 = modP(X2 * a);
10988
+ const left = modP(Z2 * modP(aX2 + Y2));
10989
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
10990
+ if (left !== right)
10991
+ throw new Error("bad point: equation left != right (1)");
10992
+ const XY = modP(X * Y);
10993
+ const ZT = modP(Z * T);
10994
+ if (XY !== ZT)
10995
+ throw new Error("bad point: equation left != right (2)");
10996
+ return true;
10997
+ });
10998
+ class Point {
10999
+ constructor(X, Y, Z, T) {
11000
+ this.X = acoord("x", X);
11001
+ this.Y = acoord("y", Y);
11002
+ this.Z = acoord("z", Z, true);
11003
+ this.T = acoord("t", T);
11004
+ Object.freeze(this);
11005
+ }
11006
+ static CURVE() {
11007
+ return CURVE;
11008
+ }
11009
+ static fromAffine(p) {
11010
+ if (p instanceof Point)
11011
+ throw new Error("extended point not allowed");
11012
+ const { x, y } = p || {};
11013
+ acoord("x", x);
11014
+ acoord("y", y);
11015
+ return new Point(x, y, _1n4, modP(x * y));
11016
+ }
11017
+ // Uses algo from RFC8032 5.1.3.
11018
+ static fromBytes(bytes, zip215 = false) {
11019
+ const len = Fp2.BYTES;
11020
+ const { a, d } = CURVE;
11021
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
11022
+ _abool2(zip215, "zip215");
11023
+ const normed = copyBytes(bytes);
11024
+ const lastByte = bytes[len - 1];
11025
+ normed[len - 1] = lastByte & ~128;
11026
+ const y = bytesToNumberLE(normed);
11027
+ const max = zip215 ? MASK : Fp2.ORDER;
11028
+ aInRange("point.y", y, _0n4, max);
11029
+ const y2 = modP(y * y);
11030
+ const u = modP(y2 - _1n4);
11031
+ const v = modP(d * y2 - a);
11032
+ let { isValid, value: x } = uvRatio2(u, v);
11033
+ if (!isValid)
11034
+ throw new Error("bad point: invalid y coordinate");
11035
+ const isXOdd = (x & _1n4) === _1n4;
11036
+ const isLastByteOdd = (lastByte & 128) !== 0;
11037
+ if (!zip215 && x === _0n4 && isLastByteOdd)
11038
+ throw new Error("bad point: x=0 and x_0=1");
11039
+ if (isLastByteOdd !== isXOdd)
11040
+ x = modP(-x);
11041
+ return Point.fromAffine({ x, y });
11042
+ }
11043
+ static fromHex(bytes, zip215 = false) {
11044
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
11045
+ }
11046
+ get x() {
11047
+ return this.toAffine().x;
11048
+ }
11049
+ get y() {
11050
+ return this.toAffine().y;
11051
+ }
11052
+ precompute(windowSize = 8, isLazy = true) {
11053
+ wnaf.createCache(this, windowSize);
11054
+ if (!isLazy)
11055
+ this.multiply(_2n2);
11056
+ return this;
11057
+ }
11058
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
11059
+ assertValidity() {
11060
+ assertValidMemo(this);
11061
+ }
11062
+ // Compare one point to another.
11063
+ equals(other) {
11064
+ aextpoint(other);
11065
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11066
+ const { X: X2, Y: Y2, Z: Z2 } = other;
11067
+ const X1Z2 = modP(X1 * Z2);
11068
+ const X2Z1 = modP(X2 * Z1);
11069
+ const Y1Z2 = modP(Y1 * Z2);
11070
+ const Y2Z1 = modP(Y2 * Z1);
11071
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
11072
+ }
11073
+ is0() {
11074
+ return this.equals(Point.ZERO);
11075
+ }
11076
+ negate() {
11077
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
11078
+ }
11079
+ // Fast algo for doubling Extended Point.
11080
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
11081
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
11082
+ double() {
11083
+ const { a } = CURVE;
11084
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11085
+ const A = modP(X1 * X1);
11086
+ const B = modP(Y1 * Y1);
11087
+ const C = modP(_2n2 * modP(Z1 * Z1));
11088
+ const D = modP(a * A);
11089
+ const x1y1 = X1 + Y1;
11090
+ const E = modP(modP(x1y1 * x1y1) - A - B);
11091
+ const G = D + B;
11092
+ const F = G - C;
11093
+ const H = D - B;
11094
+ const X3 = modP(E * F);
11095
+ const Y3 = modP(G * H);
11096
+ const T3 = modP(E * H);
11097
+ const Z3 = modP(F * G);
11098
+ return new Point(X3, Y3, Z3, T3);
11099
+ }
11100
+ // Fast algo for adding 2 Extended Points.
11101
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
11102
+ // Cost: 9M + 1*a + 1*d + 7add.
11103
+ add(other) {
11104
+ aextpoint(other);
11105
+ const { a, d } = CURVE;
11106
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
11107
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
11108
+ const A = modP(X1 * X2);
11109
+ const B = modP(Y1 * Y2);
11110
+ const C = modP(T1 * d * T2);
11111
+ const D = modP(Z1 * Z2);
11112
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
11113
+ const F = D - C;
11114
+ const G = D + C;
11115
+ const H = modP(B - a * A);
11116
+ const X3 = modP(E * F);
11117
+ const Y3 = modP(G * H);
11118
+ const T3 = modP(E * H);
11119
+ const Z3 = modP(F * G);
11120
+ return new Point(X3, Y3, Z3, T3);
11121
+ }
11122
+ subtract(other) {
11123
+ return this.add(other.negate());
11124
+ }
11125
+ // Constant-time multiplication.
11126
+ multiply(scalar) {
11127
+ if (!Fn2.isValidNot0(scalar))
11128
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
11129
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
11130
+ return normalizeZ(Point, [p, f])[0];
11131
+ }
11132
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
11133
+ // It's faster, but should only be used when you don't care about
11134
+ // an exposed private key e.g. sig verification.
11135
+ // Does NOT allow scalars higher than CURVE.n.
11136
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
11137
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
11138
+ if (!Fn2.isValid(scalar))
11139
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
11140
+ if (scalar === _0n4)
11141
+ return Point.ZERO;
11142
+ if (this.is0() || scalar === _1n4)
11143
+ return this;
11144
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
11145
+ }
11146
+ // Checks if point is of small order.
11147
+ // If you add something to small order point, you will have "dirty"
11148
+ // point with torsion component.
11149
+ // Multiplies point by cofactor and checks if the result is 0.
11150
+ isSmallOrder() {
11151
+ return this.multiplyUnsafe(cofactor).is0();
11152
+ }
11153
+ // Multiplies point by curve order and checks if the result is 0.
11154
+ // Returns `false` is the point is dirty.
11155
+ isTorsionFree() {
11156
+ return wnaf.unsafe(this, CURVE.n).is0();
11157
+ }
11158
+ // Converts Extended point to default (x, y) coordinates.
11159
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
11160
+ toAffine(invertedZ) {
11161
+ return toAffineMemo(this, invertedZ);
11162
+ }
11163
+ clearCofactor() {
11164
+ if (cofactor === _1n4)
11165
+ return this;
11166
+ return this.multiplyUnsafe(cofactor);
11167
+ }
11168
+ toBytes() {
11169
+ const { x, y } = this.toAffine();
11170
+ const bytes = Fp2.toBytes(y);
11171
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
11172
+ return bytes;
11173
+ }
11174
+ toHex() {
11175
+ return bytesToHex(this.toBytes());
11176
+ }
11177
+ toString() {
11178
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11179
+ }
11180
+ // TODO: remove
11181
+ get ex() {
11182
+ return this.X;
11183
+ }
11184
+ get ey() {
11185
+ return this.Y;
11186
+ }
11187
+ get ez() {
11188
+ return this.Z;
11189
+ }
11190
+ get et() {
11191
+ return this.T;
11192
+ }
11193
+ static normalizeZ(points) {
11194
+ return normalizeZ(Point, points);
11195
+ }
11196
+ static msm(points, scalars) {
11197
+ return pippenger(Point, Fn2, points, scalars);
11198
+ }
11199
+ _setWindowSize(windowSize) {
11200
+ this.precompute(windowSize);
11201
+ }
11202
+ toRawBytes() {
11203
+ return this.toBytes();
11204
+ }
11205
+ }
11206
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
11207
+ Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
11208
+ Point.Fp = Fp2;
11209
+ Point.Fn = Fn2;
11210
+ const wnaf = new wNAF(Point, Fn2.BITS);
11211
+ Point.BASE.precompute(8);
11212
+ return Point;
11213
+ }
11214
+ var PrimeEdwardsPoint = class {
11215
+ constructor(ep) {
11216
+ this.ep = ep;
11217
+ }
11218
+ // Static methods that must be implemented by subclasses
11219
+ static fromBytes(_bytes) {
11220
+ notImplemented();
11221
+ }
11222
+ static fromHex(_hex) {
11223
+ notImplemented();
11224
+ }
11225
+ get x() {
11226
+ return this.toAffine().x;
11227
+ }
11228
+ get y() {
11229
+ return this.toAffine().y;
11230
+ }
11231
+ // Common implementations
11232
+ clearCofactor() {
11233
+ return this;
10224
11234
  }
10225
- if (pending.length === 0) {
10226
- if (hadSynchronousError)
10227
- throw new Error("manifest signature verifier unavailable");
10228
- return false;
11235
+ assertValidity() {
11236
+ this.ep.assertValidity();
10229
11237
  }
10230
- return Promise.all(pending).then((results) => {
10231
- if (results.some((valid) => valid === true))
10232
- return true;
10233
- if (hadSynchronousError || results.some((valid) => valid === "error")) {
10234
- throw new Error("manifest signature verifier unavailable");
10235
- }
10236
- return false;
10237
- });
10238
- };
10239
- failGroup_fn = function(track, groupId, group, reason) {
10240
- if (group.pending.size === 0) {
10241
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, groupId, objectId: 0 }, reason);
10242
- return;
11238
+ toAffine(invertedZ) {
11239
+ return this.ep.toAffine(invertedZ);
10243
11240
  }
10244
- for (const pending of [...group.pending.values()]) {
10245
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10246
- if (__privateMethod(this, _ManifestVerifier_instances, rejectOrShadow_fn).call(this, pending.identity, pending.release, reason).action === "drop") {
10247
- pending.discard?.();
10248
- }
11241
+ toHex() {
11242
+ return bytesToHex(this.toBytes());
10249
11243
  }
10250
- };
10251
- removePending_fn = function(track, group, pending) {
10252
- if (group.pending.get(pending.identity.objectId) === pending) {
10253
- group.pending.delete(pending.identity.objectId);
10254
- }
10255
- const index = track.quarantine.indexOf(pending);
10256
- if (index >= 0)
10257
- track.quarantine.splice(index, 1);
10258
- track.quarantinedBytes -= pending.bytes;
10259
- __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
10260
- };
10261
- quarantine_fn = function(track, group, pending) {
10262
- if (group.pending.has(pending.identity.objectId))
11244
+ toString() {
11245
+ return this.toHex();
11246
+ }
11247
+ isTorsionFree() {
11248
+ return true;
11249
+ }
11250
+ isSmallOrder() {
10263
11251
  return false;
10264
- group.pending.set(pending.identity.objectId, pending);
10265
- track.quarantine.push(pending);
10266
- track.quarantinedBytes += pending.bytes;
10267
- __privateGet(this, _stats4).quarantinedBytes += pending.bytes;
10268
- __privateMethod(this, _ManifestVerifier_instances, enforceCap_fn).call(this, track);
10269
- return true;
10270
- };
10271
- enforceCap_fn = function(track) {
10272
- while (track.quarantinedBytes > track.capBytes && track.quarantine.length > 0) {
10273
- const pending = track.quarantine.shift();
10274
- const group = track.groups.get(BigInt(pending.identity.groupId));
10275
- if (group)
10276
- group.pending.delete(pending.identity.objectId);
10277
- track.quarantinedBytes -= pending.bytes;
10278
- __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
10279
- __privateMethod(this, _ManifestVerifier_instances, giveUpOnPending_fn).call(this, pending);
10280
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
10281
- console.warn(`[ManifestVerifier] quarantine cap eviction track=${pending.identity.trackName} group=${pending.identity.groupId} object=${pending.identity.objectId} disposition=${__privateGet(this, _config).mode === "enforce" ? "drop" : "fail-open"}`);
10282
11252
  }
10283
- };
10284
- /**
10285
- * Stop waiting for a manifest that never arrived. In `enforce` the object is
10286
- * discarded: an eviction is a rejection, not a deferred play, so unverified
10287
- * media never reaches the player two groups after the stall was recorded
10288
- * (BLO-30095, CTO disposition on the issue thread).
10289
- *
10290
- * Deliberately NOT used by `#failOpenGroup`/`#failOpenTrack` — failing open on
10291
- * a genuine verifier fault is correct and stays untouched.
10292
- */
10293
- giveUpOnPending_fn = function(pending) {
10294
- if (__privateGet(this, _config).mode !== "enforce") {
10295
- pending.release();
10296
- return;
11253
+ add(other) {
11254
+ this.assertSame(other);
11255
+ return this.init(this.ep.add(other.ep));
10297
11256
  }
10298
- pending.discard?.();
10299
- };
10300
- failOpenTrack_fn = function(track, reason) {
10301
- for (const pending of [...track.quarantine]) {
10302
- const group = track.groups.get(BigInt(pending.identity.groupId));
10303
- if (group)
10304
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10305
- pending.release();
10306
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, reason);
11257
+ subtract(other) {
11258
+ this.assertSame(other);
11259
+ return this.init(this.ep.subtract(other.ep));
10307
11260
  }
10308
- };
10309
- failOpenGroup_fn = function(track, groupId, group) {
10310
- const pending = [...group.pending.values()];
10311
- if (pending.length === 0) {
10312
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, { trackName: track.context.trackName, groupId, objectId: 0 }, "verifierError");
10313
- return;
11261
+ multiply(scalar) {
11262
+ return this.init(this.ep.multiply(scalar));
10314
11263
  }
10315
- for (const object of pending) {
10316
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, object);
10317
- object.release();
10318
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, object.identity, "verifierError");
11264
+ multiplyUnsafe(scalar) {
11265
+ return this.init(this.ep.multiplyUnsafe(scalar));
10319
11266
  }
10320
- };
10321
- releaseAllQuarantine_fn = function(countFailure) {
10322
- for (const track of __privateGet(this, _tracks2).values()) {
10323
- for (const pending of [...track.quarantine]) {
10324
- const group = track.groups.get(BigInt(pending.identity.groupId));
10325
- if (group)
10326
- __privateMethod(this, _ManifestVerifier_instances, removePending_fn).call(this, track, group, pending);
10327
- pending.release();
10328
- if (countFailure)
10329
- __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "verifierError");
10330
- }
11267
+ double() {
11268
+ return this.init(this.ep.double());
11269
+ }
11270
+ negate() {
11271
+ return this.init(this.ep.negate());
11272
+ }
11273
+ precompute(windowSize, isLazy) {
11274
+ return this.init(this.ep.precompute(windowSize, isLazy));
11275
+ }
11276
+ /** @deprecated use `toBytes` */
11277
+ toRawBytes() {
11278
+ return this.toBytes();
10331
11279
  }
10332
11280
  };
10333
- failure_fn = function(identity, reason) {
10334
- var _a;
10335
- __privateGet(this, _stats4).failures[reason]++;
10336
- (_a = __privateGet(this, _onFailure)) == null ? void 0 : _a.call(this, {
10337
- trackName: identity.trackName,
10338
- ...identity.bindingId === void 0 ? {} : { bindingId: identity.bindingId },
10339
- groupId: identity.groupId,
10340
- objectId: identity.objectId,
10341
- reason
11281
+ function eddsa(Point, cHash, eddsaOpts = {}) {
11282
+ if (typeof cHash !== "function")
11283
+ throw new Error('"hash" function param is required');
11284
+ _validateObject(eddsaOpts, {}, {
11285
+ adjustScalarBytes: "function",
11286
+ randomBytes: "function",
11287
+ domain: "function",
11288
+ prehash: "function",
11289
+ mapToCurve: "function"
10342
11290
  });
10343
- };
10344
-
10345
- // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10346
- var BCPV2_HEADER_LENGTH = 68;
10347
- var BCPV2_SIGNATURE_LENGTH = 64;
10348
- var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10349
- var text = new TextEncoder();
10350
- var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10351
- var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10352
-
10353
- // src/multicast-auth-catalog.ts
10354
- var RAW_ED25519_KEY_LENGTH = 32;
10355
- var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10356
- var DEFAULT_MANIFEST_TIMER_MS = 20;
10357
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10358
- function encodeBase64Url(bytes) {
10359
- let output = "";
10360
- for (let i = 0; i < bytes.length; i += 3) {
10361
- const b0 = bytes[i];
10362
- const b1 = bytes[i + 1];
10363
- const b2 = bytes[i + 2];
10364
- output += BASE64URL_ALPHABET[b0 >> 2];
10365
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10366
- if (b1 === void 0) break;
10367
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10368
- if (b2 === void 0) break;
10369
- output += BASE64URL_ALPHABET[b2 & 63];
10370
- }
10371
- return output;
10372
- }
10373
- var BASE64URL_DECODE_TABLE = (() => {
10374
- const table = new Int8Array(128).fill(-1);
10375
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10376
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10377
- }
10378
- return table;
10379
- })();
10380
- function decodeBase64Url(text2) {
10381
- if (text2.length % 4 === 1) {
10382
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10383
- }
10384
- const bytes = [];
10385
- let buffer = 0;
10386
- let bits = 0;
10387
- for (let i = 0; i < text2.length; i++) {
10388
- const code = text2.charCodeAt(i);
10389
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10390
- if (value === void 0 || value < 0) {
10391
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10392
- }
10393
- buffer = buffer << 6 | value;
10394
- bits += 6;
10395
- if (bits >= 8) {
10396
- bits -= 8;
10397
- bytes.push(buffer >> bits & 255);
10398
- }
10399
- }
10400
- const decoded = Uint8Array.from(bytes);
10401
- if (encodeBase64Url(decoded) !== text2) {
10402
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10403
- }
10404
- return decoded;
10405
- }
10406
- function decodeEd25519PublicKey(publicKey) {
10407
- const bytes = decodeBase64Url(publicKey);
10408
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10409
- throw new Error(
10410
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10411
- );
11291
+ const { prehash } = eddsaOpts;
11292
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
11293
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
11294
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
11295
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
11296
+ _abool2(phflag, "phflag");
11297
+ if (ctx.length || phflag)
11298
+ throw new Error("Contexts/pre-hash are not supported");
11299
+ return data;
11300
+ });
11301
+ function modN_LE(hash) {
11302
+ return Fn2.create(bytesToNumberLE(hash));
11303
+ }
11304
+ function getPrivateScalar(key) {
11305
+ const len = lengths.secretKey;
11306
+ key = ensureBytes("private key", key, len);
11307
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
11308
+ const head = adjustScalarBytes2(hashed.slice(0, len));
11309
+ const prefix = hashed.slice(len, 2 * len);
11310
+ const scalar = modN_LE(head);
11311
+ return { head, prefix, scalar };
11312
+ }
11313
+ function getExtendedPublicKey(secretKey) {
11314
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
11315
+ const point = BASE.multiply(scalar);
11316
+ const pointBytes = point.toBytes();
11317
+ return { head, prefix, scalar, point, pointBytes };
11318
+ }
11319
+ function getPublicKey(secretKey) {
11320
+ return getExtendedPublicKey(secretKey).pointBytes;
11321
+ }
11322
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
11323
+ const msg = concatBytes(...msgs);
11324
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
11325
+ }
11326
+ function sign(msg, secretKey, options = {}) {
11327
+ msg = ensureBytes("message", msg);
11328
+ if (prehash)
11329
+ msg = prehash(msg);
11330
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
11331
+ const r = hashDomainToScalar(options.context, prefix, msg);
11332
+ const R = BASE.multiply(r).toBytes();
11333
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
11334
+ const s = Fn2.create(r + k * scalar);
11335
+ if (!Fn2.isValid(s))
11336
+ throw new Error("sign failed: invalid s");
11337
+ const rs = concatBytes(R, Fn2.toBytes(s));
11338
+ return _abytes2(rs, lengths.signature, "result");
11339
+ }
11340
+ const verifyOpts = { zip215: true };
11341
+ function verify(sig, msg, publicKey, options = verifyOpts) {
11342
+ const { context, zip215 } = options;
11343
+ const len = lengths.signature;
11344
+ sig = ensureBytes("signature", sig, len);
11345
+ msg = ensureBytes("message", msg);
11346
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
11347
+ if (zip215 !== void 0)
11348
+ _abool2(zip215, "zip215");
11349
+ if (prehash)
11350
+ msg = prehash(msg);
11351
+ const mid = len / 2;
11352
+ const r = sig.subarray(0, mid);
11353
+ const s = bytesToNumberLE(sig.subarray(mid, len));
11354
+ let A, R, SB;
11355
+ try {
11356
+ A = Point.fromBytes(publicKey, zip215);
11357
+ R = Point.fromBytes(r, zip215);
11358
+ SB = BASE.multiplyUnsafe(s);
11359
+ } catch (error) {
11360
+ return false;
11361
+ }
11362
+ if (!zip215 && A.isSmallOrder())
11363
+ return false;
11364
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
11365
+ const RkA = R.add(A.multiplyUnsafe(k));
11366
+ return RkA.subtract(SB).clearCofactor().is0();
11367
+ }
11368
+ const _size = Fp2.BYTES;
11369
+ const lengths = {
11370
+ secretKey: _size,
11371
+ publicKey: _size,
11372
+ signature: 2 * _size,
11373
+ seed: _size
11374
+ };
11375
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
11376
+ return _abytes2(seed, lengths.seed, "seed");
10412
11377
  }
10413
- return bytes;
10414
- }
10415
- function resolveMulticastAuthCatalog(catalog, options = {}) {
10416
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10417
- throw new Error("[multicast-auth-catalog] catalog must be an object");
11378
+ function keygen(seed) {
11379
+ const secretKey = utils.randomSecretKey(seed);
11380
+ return { secretKey, publicKey: getPublicKey(secretKey) };
10418
11381
  }
10419
- const issues = multicastCatalogIssues(catalog, options);
10420
- const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10421
- if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10422
- const multicast = catalog["multicast"];
10423
- const auth = multicast?.["auth"];
10424
- if (auth === void 0) {
10425
- if (options.requireAuth) {
10426
- throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
11382
+ function isValidSecretKey(key) {
11383
+ return isBytes(key) && key.length === Fn2.BYTES;
11384
+ }
11385
+ function isValidPublicKey(key, zip215) {
11386
+ try {
11387
+ return !!Point.fromBytes(key, zip215);
11388
+ } catch (error) {
11389
+ return false;
10427
11390
  }
10428
- return void 0;
10429
11391
  }
10430
- const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10431
- const endpoints = multicast["endpoints"] ?? [];
10432
- const flows = [];
10433
- endpoints.forEach((endpoint, endpointIndex) => {
10434
- if (ignored.has(endpointIndex)) return;
10435
- const flowAuth = endpoint["auth"];
10436
- flows.push({
10437
- endpointIndex,
10438
- source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10439
- groupAddress: endpoint["groupAddress"],
10440
- port: endpoint["port"],
10441
- bandwidth: endpoint["bandwidth"],
10442
- manifestPort: flowAuth.manifestPort,
10443
- streamId: flowAuth.streamId,
10444
- maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10445
- manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10446
- ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10447
- tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10448
- name,
10449
- packetId
10450
- }))
10451
- });
11392
+ const utils = {
11393
+ getExtendedPublicKey,
11394
+ randomSecretKey,
11395
+ isValidSecretKey,
11396
+ isValidPublicKey,
11397
+ /**
11398
+ * Converts ed public key to x public key. Uses formula:
11399
+ * - ed25519:
11400
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
11401
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
11402
+ * - ed448:
11403
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
11404
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
11405
+ */
11406
+ toMontgomery(publicKey) {
11407
+ const { y } = Point.fromBytes(publicKey);
11408
+ const size = lengths.publicKey;
11409
+ const is25519 = size === 32;
11410
+ if (!is25519 && size !== 57)
11411
+ throw new Error("only defined for 25519 and 448");
11412
+ const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
11413
+ return Fp2.toBytes(u);
11414
+ },
11415
+ toMontgomerySecret(secretKey) {
11416
+ const size = lengths.secretKey;
11417
+ _abytes2(secretKey, size);
11418
+ const hashed = cHash(secretKey.subarray(0, size));
11419
+ return adjustScalarBytes2(hashed).subarray(0, size);
11420
+ },
11421
+ /** @deprecated */
11422
+ randomPrivateKey: randomSecretKey,
11423
+ /** @deprecated */
11424
+ precompute(windowSize = 8, point = Point.BASE) {
11425
+ return point.precompute(windowSize, false);
11426
+ }
11427
+ };
11428
+ return Object.freeze({
11429
+ keygen,
11430
+ getPublicKey,
11431
+ sign,
11432
+ verify,
11433
+ utils,
11434
+ Point,
11435
+ lengths
10452
11436
  });
10453
- return {
10454
- keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10455
- minEpoch: auth.minEpoch,
10456
- flows
11437
+ }
11438
+ function _eddsa_legacy_opts_to_new(c) {
11439
+ const CURVE = {
11440
+ a: c.a,
11441
+ d: c.d,
11442
+ p: c.Fp.ORDER,
11443
+ n: c.n,
11444
+ h: c.h,
11445
+ Gx: c.Gx,
11446
+ Gy: c.Gy
11447
+ };
11448
+ const Fp2 = c.Fp;
11449
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
11450
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
11451
+ const eddsaOpts = {
11452
+ randomBytes: c.randomBytes,
11453
+ adjustScalarBytes: c.adjustScalarBytes,
11454
+ domain: c.domain,
11455
+ prehash: c.prehash,
11456
+ mapToCurve: c.mapToCurve
10457
11457
  };
11458
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
11459
+ }
11460
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
11461
+ const Point = eddsa2.Point;
11462
+ const legacy = Object.assign({}, eddsa2, {
11463
+ ExtendedPoint: Point,
11464
+ CURVE: c,
11465
+ nBitLength: Point.Fn.BITS,
11466
+ nByteLength: Point.Fn.BYTES
11467
+ });
11468
+ return legacy;
10458
11469
  }
10459
- function multicastAuthKeyFor(resolved, kid, epoch) {
10460
- return manifestKeyFor(resolved.keys, epoch, kid);
11470
+ function twistedEdwards(c) {
11471
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
11472
+ const Point = edwards(CURVE, curveOpts);
11473
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
11474
+ return _eddsa_new_output_to_legacy(c, EDDSA);
10461
11475
  }
10462
11476
 
10463
- // src/manifest-auth-plan.ts
10464
- function createManifestAuthPlan(catalog, options = {}) {
10465
- const resolved = resolveMulticastAuthCatalog(catalog, options);
10466
- if (!resolved) return void 0;
10467
- const byManifestTrack = /* @__PURE__ */ new Map();
10468
- for (const flow of resolved.flows) {
10469
- if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
11477
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/ed25519.js
11478
+ var _0n5 = /* @__PURE__ */ BigInt(0);
11479
+ var _1n5 = BigInt(1);
11480
+ var _2n3 = BigInt(2);
11481
+ var _3n2 = BigInt(3);
11482
+ var _5n2 = BigInt(5);
11483
+ var _8n3 = BigInt(8);
11484
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
11485
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
11486
+ p: ed25519_CURVE_p,
11487
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
11488
+ h: _8n3,
11489
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
11490
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
11491
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
11492
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
11493
+ }))();
11494
+ function ed25519_pow_2_252_3(x) {
11495
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
11496
+ const P = ed25519_CURVE_p;
11497
+ const x2 = x * x % P;
11498
+ const b2 = x2 * x % P;
11499
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
11500
+ const b5 = pow2(b4, _1n5, P) * x % P;
11501
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
11502
+ const b20 = pow2(b10, _10n, P) * b10 % P;
11503
+ const b40 = pow2(b20, _20n, P) * b20 % P;
11504
+ const b80 = pow2(b40, _40n, P) * b40 % P;
11505
+ const b160 = pow2(b80, _80n, P) * b80 % P;
11506
+ const b240 = pow2(b160, _80n, P) * b80 % P;
11507
+ const b250 = pow2(b240, _10n, P) * b10 % P;
11508
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
11509
+ return { pow_p_5_8, b2 };
11510
+ }
11511
+ function adjustScalarBytes(bytes) {
11512
+ bytes[0] &= 248;
11513
+ bytes[31] &= 127;
11514
+ bytes[31] |= 64;
11515
+ return bytes;
11516
+ }
11517
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
11518
+ function uvRatio(u, v) {
11519
+ const P = ed25519_CURVE_p;
11520
+ const v3 = mod(v * v * v, P);
11521
+ const v7 = mod(v3 * v3 * v, P);
11522
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
11523
+ let x = mod(u * v3 * pow, P);
11524
+ const vx2 = mod(v * x * x, P);
11525
+ const root1 = x;
11526
+ const root2 = mod(x * ED25519_SQRT_M1, P);
11527
+ const useRoot1 = vx2 === u;
11528
+ const useRoot2 = vx2 === mod(-u, P);
11529
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
11530
+ if (useRoot1)
11531
+ x = root1;
11532
+ if (useRoot2 || noRoot)
11533
+ x = root2;
11534
+ if (isNegativeLE(x, P))
11535
+ x = mod(-x, P);
11536
+ return { isValid: useRoot1 || useRoot2, value: x };
11537
+ }
11538
+ var Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
11539
+ var Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
11540
+ var ed25519Defaults = /* @__PURE__ */ (() => ({
11541
+ ...ed25519_CURVE,
11542
+ Fp,
11543
+ hash: sha512,
11544
+ adjustScalarBytes,
11545
+ // dom2
11546
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
11547
+ // Constant-time, u/√v
11548
+ uvRatio
11549
+ }))();
11550
+ var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
11551
+ var SQRT_M1 = ED25519_SQRT_M1;
11552
+ var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
11553
+ var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
11554
+ var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
11555
+ var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
11556
+ var invertSqrt = (number) => uvRatio(_1n5, number);
11557
+ var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
11558
+ var bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
11559
+ function calcElligatorRistrettoMap(r0) {
11560
+ const { d } = ed25519_CURVE;
11561
+ const P = ed25519_CURVE_p;
11562
+ const mod2 = (n) => Fp.create(n);
11563
+ const r = mod2(SQRT_M1 * r0 * r0);
11564
+ const Ns = mod2((r + _1n5) * ONE_MINUS_D_SQ);
11565
+ let c = BigInt(-1);
11566
+ const D = mod2((c - d * r) * mod2(r + d));
11567
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
11568
+ let s_ = mod2(s * r0);
11569
+ if (!isNegativeLE(s_, P))
11570
+ s_ = mod2(-s_);
11571
+ if (!Ns_D_is_sq)
11572
+ s = s_;
11573
+ if (!Ns_D_is_sq)
11574
+ c = r;
11575
+ const Nt = mod2(c * (r - _1n5) * D_MINUS_ONE_SQ - D);
11576
+ const s2 = s * s;
11577
+ const W0 = mod2((s + s) * D);
11578
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
11579
+ const W2 = mod2(_1n5 - s2);
11580
+ const W3 = mod2(_1n5 + s2);
11581
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
11582
+ }
11583
+ function ristretto255_map(bytes) {
11584
+ abytes(bytes, 64);
11585
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
11586
+ const R1 = calcElligatorRistrettoMap(r1);
11587
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
11588
+ const R2 = calcElligatorRistrettoMap(r2);
11589
+ return new _RistrettoPoint(R1.add(R2));
11590
+ }
11591
+ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
11592
+ constructor(ep) {
11593
+ super(ep);
11594
+ }
11595
+ static fromAffine(ap) {
11596
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
11597
+ }
11598
+ assertSame(other) {
11599
+ if (!(other instanceof __RistrettoPoint))
11600
+ throw new Error("RistrettoPoint expected");
11601
+ }
11602
+ init(ep) {
11603
+ return new __RistrettoPoint(ep);
11604
+ }
11605
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
11606
+ static hashToCurve(hex2) {
11607
+ return ristretto255_map(ensureBytes("ristrettoHash", hex2, 64));
11608
+ }
11609
+ static fromBytes(bytes) {
11610
+ abytes(bytes, 32);
11611
+ const { a, d } = ed25519_CURVE;
11612
+ const P = ed25519_CURVE_p;
11613
+ const mod2 = (n) => Fp.create(n);
11614
+ const s = bytes255ToNumberLE(bytes);
11615
+ if (!equalBytes2(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
11616
+ throw new Error("invalid ristretto255 encoding 1");
11617
+ const s2 = mod2(s * s);
11618
+ const u1 = mod2(_1n5 + a * s2);
11619
+ const u2 = mod2(_1n5 - a * s2);
11620
+ const u1_2 = mod2(u1 * u1);
11621
+ const u2_2 = mod2(u2 * u2);
11622
+ const v = mod2(a * d * u1_2 - u2_2);
11623
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
11624
+ const Dx = mod2(I * u2);
11625
+ const Dy = mod2(I * Dx * v);
11626
+ let x = mod2((s + s) * Dx);
11627
+ if (isNegativeLE(x, P))
11628
+ x = mod2(-x);
11629
+ const y = mod2(u1 * Dy);
11630
+ const t = mod2(x * y);
11631
+ if (!isValid || isNegativeLE(t, P) || y === _0n5)
11632
+ throw new Error("invalid ristretto255 encoding 2");
11633
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n5, t));
10470
11634
  }
10471
- return {
10472
- keys: resolved.keys,
10473
- minEpoch: resolved.minEpoch,
10474
- flows: resolved.flows,
10475
- manifestTracks: [...byManifestTrack.keys()],
10476
- keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10477
- flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10478
- flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
10479
- };
11635
+ /**
11636
+ * Converts ristretto-encoded string to ristretto point.
11637
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
11638
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
11639
+ */
11640
+ static fromHex(hex2) {
11641
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex2, 32));
11642
+ }
11643
+ static msm(points, scalars) {
11644
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
11645
+ }
11646
+ /**
11647
+ * Encodes ristretto point to Uint8Array.
11648
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
11649
+ */
11650
+ toBytes() {
11651
+ let { X, Y, Z, T } = this.ep;
11652
+ const P = ed25519_CURVE_p;
11653
+ const mod2 = (n) => Fp.create(n);
11654
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
11655
+ const u2 = mod2(X * Y);
11656
+ const u2sq = mod2(u2 * u2);
11657
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
11658
+ const D1 = mod2(invsqrt * u1);
11659
+ const D2 = mod2(invsqrt * u2);
11660
+ const zInv = mod2(D1 * D2 * T);
11661
+ let D;
11662
+ if (isNegativeLE(T * zInv, P)) {
11663
+ let _x = mod2(Y * SQRT_M1);
11664
+ let _y = mod2(X * SQRT_M1);
11665
+ X = _x;
11666
+ Y = _y;
11667
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
11668
+ } else {
11669
+ D = D2;
11670
+ }
11671
+ if (isNegativeLE(X * zInv, P))
11672
+ Y = mod2(-Y);
11673
+ let s = mod2((Z - Y) * D);
11674
+ if (isNegativeLE(s, P))
11675
+ s = mod2(-s);
11676
+ return Fp.toBytes(s);
11677
+ }
11678
+ /**
11679
+ * Compares two Ristretto points.
11680
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
11681
+ */
11682
+ equals(other) {
11683
+ this.assertSame(other);
11684
+ const { X: X1, Y: Y1 } = this.ep;
11685
+ const { X: X2, Y: Y2 } = other.ep;
11686
+ const mod2 = (n) => Fp.create(n);
11687
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
11688
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
11689
+ return one || two;
11690
+ }
11691
+ is0() {
11692
+ return this.equals(__RistrettoPoint.ZERO);
11693
+ }
11694
+ };
11695
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
11696
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
11697
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
11698
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
11699
+
11700
+ // ../mmt-manifest-verify/dist/bc-provenance-v2-receiver.js
11701
+ var BCPV2_LEAD_BOUND_MS = 5e3;
11702
+ var REPLAY_WINDOW = 64n;
11703
+ var BUCKET_DEPTH = 64;
11704
+ var BUCKET_RATE_PER_MS = 1;
11705
+ var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
11706
+ function sameBytes(a, b) {
11707
+ if (a.byteLength !== b.byteLength)
11708
+ return false;
11709
+ let diff = 0;
11710
+ for (let i = 0; i < a.byteLength; i++)
11711
+ diff |= a[i] ^ b[i];
11712
+ return diff === 0;
10480
11713
  }
11714
+ var BcProvenanceV2Receiver = class {
11715
+ constructor(cfg) {
11716
+ __publicField(this, "maxAuthDelayMs");
11717
+ __publicField(this, "manifestTimerMs");
11718
+ __publicField(this, "widenMs");
11719
+ /** Datagrams that left a hold queue at expiry, per path: the loss signal for failover. */
11720
+ __publicField(this, "expired", { multicast: 0, unicast: 0 });
11721
+ /**
11722
+ * Unicast repair (Section 7.2.7 step 2): on a receiver that can request it, how
11723
+ * long ago (ms) the first packet admitted into the oldest open block with an FEC
11724
+ * deadline was admitted; undefined with none open. A pending entry still live
11725
+ * then is kept instead of expiring, and is released with the block, under the
11726
+ * open-block bound of [MOQ-FEC] Section 9.
11727
+ */
11728
+ __publicField(this, "keepPendingAgeMs", null);
11729
+ __publicField(this, "cfg");
11730
+ __publicField(this, "now");
11731
+ __publicField(this, "verifySig");
11732
+ __publicField(this, "accepted");
11733
+ __publicField(this, "queueLimit");
11734
+ __publicField(this, "current", null);
11735
+ __publicField(this, "previous", null);
11736
+ __publicField(this, "graceStart", {});
11737
+ __publicField(this, "hashAlg", null);
11738
+ __publicField(this, "verified", /* @__PURE__ */ new Map());
11739
+ __publicField(this, "highest", { multicast: /* @__PURE__ */ new Map(), mirror: /* @__PURE__ */ new Map() });
11740
+ __publicField(this, "closedAt", /* @__PURE__ */ new Map());
11741
+ __publicField(this, "lead", null);
11742
+ __publicField(this, "pending", /* @__PURE__ */ new Map());
11743
+ __publicField(this, "admittedUntil", /* @__PURE__ */ new Map());
11744
+ __publicField(this, "hold", { multicast: [], unicast: [] });
11745
+ __publicField(this, "holdBytes", { multicast: 0, unicast: 0 });
11746
+ __publicField(this, "order", 0);
11747
+ __publicField(this, "buckets");
11748
+ this.maxAuthDelayMs = cfg.maxAuthDelayMs ?? 200;
11749
+ this.manifestTimerMs = cfg.manifestTimerMs ?? 20;
11750
+ if (!(this.maxAuthDelayMs >= 50 && this.maxAuthDelayMs <= 1e3) || !(this.manifestTimerMs >= 1)) {
11751
+ throw new Error("BCPV2 endpoint ignored: maxAuthDelayMs or manifestTimerMs out of range");
11752
+ }
11753
+ if (!(cfg.bandwidth > 0))
11754
+ throw new Error("BCPV2 endpoint ignored: protected endpoint without bandwidth");
11755
+ const kids = new Set(cfg.keys.map((k) => k.kid));
11756
+ const firsts = new Set(cfg.keys.map((k) => k.firstEpoch));
11757
+ if (cfg.keys.length < 1 || kids.size !== cfg.keys.length || firsts.size !== cfg.keys.length) {
11758
+ throw new Error("BCPV2 key set invalid: no keys, or a repeated kid or firstEpoch");
11759
+ }
11760
+ this.cfg = cfg;
11761
+ this.widenMs = Math.min(Math.max(cfg.widenMs ?? 0, 0), BCPV2_LEAD_BOUND_MS);
11762
+ this.now = cfg.now ?? Date.now;
11763
+ this.verifySig = cfg.verifySignature ?? ((pk, msg, sig) => {
11764
+ try {
11765
+ return ed25519.verify(sig, msg, pk, { zip215: false });
11766
+ } catch {
11767
+ return false;
11768
+ }
11769
+ });
11770
+ this.accepted = cfg.acceptedHashAlgs ?? [BCPV2_HASH_ALG_SHA256];
11771
+ const bandwidth = Math.min(cfg.bandwidth, 1e10);
11772
+ this.queueLimit = {
11773
+ multicast: this.maxAuthDelayMs * bandwidth / 8e3,
11774
+ unicast: (this.maxAuthDelayMs + this.widenMs) * bandwidth / 8e3
11775
+ };
11776
+ const t = this.now();
11777
+ this.buckets = {
11778
+ multicast: { tokens: BUCKET_DEPTH, last: t, dropped: 0 },
11779
+ mirror: { tokens: BUCKET_DEPTH, last: t, dropped: 0 }
11780
+ };
11781
+ }
11782
+ get grace() {
11783
+ return this.maxAuthDelayMs + 2 * this.manifestTimerMs;
11784
+ }
11785
+ /** The mirror's lead in force: 0 without a manifest track, the bound until one is measured. */
11786
+ get leadMs() {
11787
+ if (!this.cfg.applyLead)
11788
+ return 0;
11789
+ return this.lead ?? BCPV2_LEAD_BOUND_MS;
11790
+ }
11791
+ /** Step 1: a record datagram on `manifestPort`, or a record object of the manifest track. */
11792
+ onRecord(bytes, path) {
11793
+ var _a;
11794
+ const now = this.now();
11795
+ this.expire(now);
11796
+ const drop = (verdict) => ({ verdict, admitted: [] });
11797
+ const len = bytes.byteLength;
11798
+ if (len < BCPV2_MIN_RECORD_LENGTH || len > BCPV2_MAX_RECORD_LENGTH || (len - 132) % 32 !== 0)
11799
+ return drop("length");
11800
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, len);
11801
+ if (view2.getUint32(0) !== 1296583986)
11802
+ return drop("magic");
11803
+ const kid = view2.getUint32(4);
11804
+ const epoch = view2.getUint32(8);
11805
+ const mseq = view2.getBigUint64(12);
11806
+ const count = view2.getUint16(28);
11807
+ const hashAlg = bytes[30];
11808
+ const sent = view2.getUint32(32);
11809
+ const key = this.cfg.keys.find((k) => k.kid === kid);
11810
+ if (!key)
11811
+ return drop("kid");
11812
+ const next = Math.min(...this.cfg.keys.map((k) => k.firstEpoch).filter((f) => f > key.firstEpoch), Infinity);
11813
+ if (epoch < key.firstEpoch || epoch >= next)
11814
+ return drop("epoch");
11815
+ const id = `${kid}:${epoch}:${mseq}`;
11816
+ const seen = this.verified.get(id);
11817
+ if (seen) {
11818
+ const admitted2 = hex(sha2562(bytes)) === seen.digest ? this.arrival(seen, path, now) : [];
11819
+ return { verdict: "duplicate", admitted: admitted2 };
11820
+ }
11821
+ const ke = `${kid}:${epoch}`;
11822
+ if (this.current === null) {
11823
+ if (epoch < this.cfg.minEpoch || epoch < (this.cfg.pinnedEpochFloor?.get(kid) ?? 0))
11824
+ return drop("epoch");
11825
+ } else if (epoch < this.current.epoch && !this.previousAdmitted(epoch, path, now)) {
11826
+ return drop("epoch");
11827
+ }
11828
+ const floor = this.floor(ke, path);
11829
+ if (floor !== void 0 && mseq <= floor - REPLAY_WINDOW)
11830
+ return drop("mseq");
11831
+ const closed = this.closedAt.get(ke);
11832
+ if (closed !== void 0 && mseq > closed)
11833
+ return drop("closed");
11834
+ if (this.cfg.checkFreshness !== false) {
11835
+ const behind = 7e3 + this.maxAuthDelayMs + (path === "mirror" ? this.widenMs : 0);
11836
+ if (sent * 1e3 < now - behind || sent * 1e3 > now + 6e3)
11837
+ return drop("sent");
11838
+ }
11839
+ if (count !== (len - 132) / 32)
11840
+ return drop("count");
11841
+ if (!this.accepted.includes(hashAlg) || this.hashAlg !== null && hashAlg !== this.hashAlg)
11842
+ return drop("hash_alg");
11843
+ if (this.cfg.catalogCtx && !sameBytes(bytes.subarray(36, 68), this.cfg.catalogCtx))
11844
+ return drop("ctx");
11845
+ if (!this.take(path, now))
11846
+ return drop("budget");
11847
+ const record = decodeBcProvenanceV2Record(bytes);
11848
+ if (!this.verifySig(key.publicKey, bcProvenanceV2SignedMessage(record, this.cfg.endpoint), record.signature)) {
11849
+ return drop("signature");
11850
+ }
11851
+ if (this.current === null || epoch > this.current.epoch) {
11852
+ if (this.current !== null) {
11853
+ this.previous = { epoch: this.current.epoch, deadline: now + BCPV2_LEAD_BOUND_MS + this.grace };
11854
+ }
11855
+ this.current = { epoch, since: now };
11856
+ this.graceStart = { [path]: now };
11857
+ if (this.hashAlg === null) {
11858
+ this.hashAlg = hashAlg;
11859
+ for (const queue of Object.values(this.hold)) {
11860
+ for (const held of queue)
11861
+ held.digest ?? (held.digest = this.digest(held.datagram));
11862
+ }
11863
+ }
11864
+ } else if (epoch === this.current.epoch) {
11865
+ (_a = this.graceStart)[path] ?? (_a[path] = now);
11866
+ }
11867
+ const entry = {
11868
+ kid,
11869
+ epoch,
11870
+ mseq,
11871
+ path,
11872
+ arrival: now,
11873
+ sent,
11874
+ digest: hex(sha2562(bytes)),
11875
+ pairs: record.digests.map((d, i) => ({ digest: hex(d), seq: record.firstSeq + BigInt(i), admitted: false })),
11876
+ awaitingMulticast: path === "mirror"
11877
+ };
11878
+ this.verified.set(id, entry);
11879
+ this.raise(ke, path, mseq);
11880
+ if (record.flags & 1)
11881
+ this.closedAt.set(ke, mseq);
11882
+ const widen = path === "mirror" ? this.cfg.applyLead ? this.leadMs : this.widenMs : 0;
11883
+ const admitted = [];
11884
+ for (const pair of entry.pairs)
11885
+ this.handlePair(pair, now, now + this.grace + widen, now, admitted);
11886
+ this.dropAdmittedHeld();
11887
+ this.prune(now);
11888
+ return { verdict: "verified", admitted };
11889
+ }
11890
+ /** Step 2: a data datagram on `port` (or a packet of a listed track over MoQ unicast). */
11891
+ onDatagram(datagram, path) {
11892
+ const now = this.now();
11893
+ this.expire(now);
11894
+ if (this.hashAlg !== null) {
11895
+ const d = this.digest(datagram);
11896
+ if (this.consumePending(d, now))
11897
+ return { verdict: "admitted", admitted: [datagram] };
11898
+ if (this.admittedUntil.has(d))
11899
+ return { verdict: "duplicate", admitted: [] };
11900
+ return this.enqueue({ digest: d, datagram, expiry: 0, order: 0 }, path, now);
11901
+ }
11902
+ return this.enqueue({ datagram, expiry: 0, order: 0 }, path, now);
11903
+ }
11904
+ /**
11905
+ * A source packet recovered by FEC decode, its base SS_ID (SS_Start + ESI)
11906
+ * appended: admitted only on a pending entry it consumes, never held. One no
11907
+ * verified record lists, or a copy of an admitted packet, is dropped.
11908
+ */
11909
+ admitRecovered(datagram) {
11910
+ const now = this.now();
11911
+ this.expire(now);
11912
+ return this.hashAlg !== null && this.consumePending(this.digest(datagram), now);
11913
+ }
11914
+ /**
11915
+ * Discard the per-flow state on a `streamId` change or a key-set change that fails the
11916
+ * flow's current (kid, epoch): budgets and hold queues survive, held digests are cleared.
11917
+ */
11918
+ resetGeneration() {
11919
+ this.current = null;
11920
+ this.previous = null;
11921
+ this.graceStart = {};
11922
+ this.hashAlg = null;
11923
+ this.verified.clear();
11924
+ this.highest = { multicast: /* @__PURE__ */ new Map(), mirror: /* @__PURE__ */ new Map() };
11925
+ this.closedAt.clear();
11926
+ this.lead = null;
11927
+ this.pending.clear();
11928
+ this.admittedUntil.clear();
11929
+ for (const queue of Object.values(this.hold))
11930
+ for (const held of queue)
11931
+ held.digest = void 0;
11932
+ }
11933
+ /** The receiver ceased to hold the endpoint: drop everything; no drop here is an expiry. */
11934
+ release() {
11935
+ this.resetGeneration();
11936
+ this.hold = { multicast: [], unicast: [] };
11937
+ this.holdBytes = { multicast: 0, unicast: 0 };
11938
+ }
11939
+ digest(datagram) {
11940
+ return hex(bcProvenanceV2DatagramDigest(this.cfg.endpoint, datagram));
11941
+ }
11942
+ /** Consume the lowest-seq pending entry for `digest`, admitting it. */
11943
+ consumePending(digest, now) {
11944
+ const list = this.pending.get(digest);
11945
+ if (!list?.length)
11946
+ return false;
11947
+ list.sort((a, b) => a.pair.seq < b.pair.seq ? -1 : a.pair.seq > b.pair.seq ? 1 : 0);
11948
+ const hit = list.shift();
11949
+ if (list.length === 0)
11950
+ this.pending.delete(digest);
11951
+ hit.pair.pending = void 0;
11952
+ hit.pair.admitted = true;
11953
+ this.admittedUntil.set(digest, now + this.maxAuthDelayMs + this.leadMs);
11954
+ return true;
11955
+ }
11956
+ enqueue(held, path, now) {
11957
+ if (this.holdBytes[path] + held.datagram.byteLength > this.queueLimit[path]) {
11958
+ return { verdict: "overflow", admitted: [] };
11959
+ }
11960
+ held.expiry = now + this.maxAuthDelayMs + (path === "unicast" ? this.widenMs : 0);
11961
+ held.order = this.order++;
11962
+ this.hold[path].push(held);
11963
+ this.holdBytes[path] += held.datagram.byteLength;
11964
+ return { verdict: "held", admitted: [] };
11965
+ }
11966
+ /** Remove and return the oldest held datagram with `digest`, across both queues. */
11967
+ takeHeld(digest) {
11968
+ let best;
11969
+ for (const path of ["multicast", "unicast"]) {
11970
+ const index = this.hold[path].findIndex((h) => h.digest === digest);
11971
+ if (index >= 0 && (!best || this.hold[path][index].order < best.order)) {
11972
+ best = { path, index, order: this.hold[path][index].order };
11973
+ }
11974
+ }
11975
+ if (!best)
11976
+ return void 0;
11977
+ const [held] = this.hold[best.path].splice(best.index, 1);
11978
+ this.holdBytes[best.path] -= held.datagram.byteLength;
11979
+ return held.datagram;
11980
+ }
11981
+ dropAdmittedHeld() {
11982
+ for (const path of ["multicast", "unicast"]) {
11983
+ this.hold[path] = this.hold[path].filter((h) => {
11984
+ const keep = h.digest === void 0 || !this.admittedUntil.has(h.digest);
11985
+ if (!keep)
11986
+ this.holdBytes[path] -= h.datagram.byteLength;
11987
+ return keep;
11988
+ });
11989
+ }
11990
+ }
11991
+ /** Step 1 pair handling: admit a held copy, or insert a pending entry. */
11992
+ handlePair(pair, now, expiry, inserted, out) {
11993
+ const datagram = this.takeHeld(pair.digest);
11994
+ if (datagram) {
11995
+ pair.admitted = true;
11996
+ this.admittedUntil.set(pair.digest, now + this.maxAuthDelayMs + this.leadMs);
11997
+ out.push(datagram);
11998
+ return;
11999
+ }
12000
+ const entry = { pair, inserted, expiry };
12001
+ pair.pending = entry;
12002
+ const list = this.pending.get(pair.digest);
12003
+ if (list)
12004
+ list.push(entry);
12005
+ else
12006
+ this.pending.set(pair.digest, [entry]);
12007
+ }
12008
+ /** A byte-identical copy dropped by the already-verified lookup. */
12009
+ arrival(seen, path, now) {
12010
+ var _a;
12011
+ const ke = `${seen.kid}:${seen.epoch}`;
12012
+ this.raise(ke, path, seen.mseq);
12013
+ if (this.current && seen.epoch === this.current.epoch)
12014
+ (_a = this.graceStart)[path] ?? (_a[path] = now);
12015
+ if (path !== "multicast" || !seen.awaitingMulticast)
12016
+ return [];
12017
+ seen.awaitingMulticast = false;
12018
+ if (!this.cfg.applyLead)
12019
+ return [];
12020
+ const t = this.manifestTimerMs;
12021
+ const interval = Math.min(Math.ceil((now - seen.arrival) / t) * t, BCPV2_LEAD_BOUND_MS);
12022
+ if (this.lead === null) {
12023
+ this.lead = interval;
12024
+ return [];
12025
+ }
12026
+ if (interval <= this.lead)
12027
+ return [];
12028
+ this.lead = interval;
12029
+ const out = [];
12030
+ const records = [seen, ...[...this.verified.values()].filter((v) => v.awaitingMulticast && v.arrival >= now - interval)];
12031
+ for (const v of records) {
12032
+ for (const pair of v.pairs) {
12033
+ if (pair.admitted) {
12034
+ this.admittedUntil.set(pair.digest, now + this.maxAuthDelayMs + interval);
12035
+ } else if (pair.pending) {
12036
+ pair.pending.expiry = pair.pending.inserted + this.grace + interval;
12037
+ } else {
12038
+ this.handlePair(pair, now, now + this.grace + interval, now, out);
12039
+ }
12040
+ }
12041
+ }
12042
+ this.dropAdmittedHeld();
12043
+ return out;
12044
+ }
12045
+ previousAdmitted(epoch, path, now) {
12046
+ if (!this.previous || epoch !== this.previous.epoch)
12047
+ return false;
12048
+ const m = this.graceStart.multicast;
12049
+ if (path === "multicast")
12050
+ return m === void 0 || now <= m + this.grace;
12051
+ const starts = [m, this.graceStart.mirror].filter((s) => s !== void 0);
12052
+ return starts.length > 0 && now <= Math.min(...starts) + this.grace;
12053
+ }
12054
+ /** The replay floor this record meets: its path's, or the higher of both from the mirror. */
12055
+ floor(ke, path) {
12056
+ const m = this.highest.multicast.get(ke);
12057
+ if (path === "multicast")
12058
+ return m;
12059
+ const r = this.highest.mirror.get(ke);
12060
+ if (m === void 0)
12061
+ return r;
12062
+ return r === void 0 || m > r ? m : r;
12063
+ }
12064
+ raise(ke, path, mseq) {
12065
+ const h = this.highest[path].get(ke);
12066
+ if (h === void 0 || mseq > h)
12067
+ this.highest[path].set(ke, mseq);
12068
+ }
12069
+ take(path, now) {
12070
+ const b = this.buckets[path];
12071
+ b.tokens = Math.min(BUCKET_DEPTH, b.tokens + (now - b.last) * BUCKET_RATE_PER_MS);
12072
+ b.last = now;
12073
+ if (b.tokens < 1) {
12074
+ b.dropped++;
12075
+ return false;
12076
+ }
12077
+ b.tokens -= 1;
12078
+ return true;
12079
+ }
12080
+ expire(now) {
12081
+ for (const path of ["multicast", "unicast"]) {
12082
+ this.hold[path] = this.hold[path].filter((h) => {
12083
+ if (h.expiry > now)
12084
+ return true;
12085
+ this.holdBytes[path] -= h.datagram.byteLength;
12086
+ this.expired[path]++;
12087
+ return false;
12088
+ });
12089
+ }
12090
+ let keepFrom = null;
12091
+ for (const [d, list] of this.pending) {
12092
+ const live = list.filter((p) => {
12093
+ if (p.expiry > now)
12094
+ return true;
12095
+ if (keepFrom === null) {
12096
+ const age = this.keepPendingAgeMs?.();
12097
+ keepFrom = age === void 0 ? void 0 : now - age;
12098
+ }
12099
+ if (keepFrom !== void 0 && keepFrom !== null && p.expiry > keepFrom)
12100
+ return true;
12101
+ p.pair.pending = void 0;
12102
+ return false;
12103
+ });
12104
+ if (live.length)
12105
+ this.pending.set(d, live);
12106
+ else
12107
+ this.pending.delete(d);
12108
+ }
12109
+ for (const [d, until] of this.admittedUntil)
12110
+ if (until <= now)
12111
+ this.admittedUntil.delete(d);
12112
+ if (this.previous && now > this.previous.deadline)
12113
+ this.previous = null;
12114
+ }
12115
+ /**
12116
+ * Retire verified entries below their arrival path's replay floor, keeping a mirrored entry
12117
+ * while the freshness check would still pass its copy on `manifestPort`.
12118
+ * ponytail: linear scan per record; index by (kid, epoch) if retained sets grow past a few thousand.
12119
+ */
12120
+ prune(now) {
12121
+ const retention = 7e3 + this.maxAuthDelayMs;
12122
+ for (const [id, v] of this.verified) {
12123
+ const h = this.highest[v.path].get(`${v.kid}:${v.epoch}`);
12124
+ const aboveFloor = h === void 0 || v.mseq > h - REPLAY_WINDOW;
12125
+ const fresh = this.cfg.checkFreshness === false ? v.arrival + retention >= now : v.sent * 1e3 + retention >= now;
12126
+ const current = this.current && (v.epoch === this.current.epoch || v.epoch === this.previous?.epoch);
12127
+ if (current && (aboveFloor || v.path === "mirror" && fresh))
12128
+ continue;
12129
+ this.verified.delete(id);
12130
+ }
12131
+ }
12132
+ };
10481
12133
  return __toCommonJS(no_modules_exports);
10482
12134
  })();
10483
12135
  /*! Bundled license information:
10484
12136
 
10485
12137
  @noble/hashes/esm/utils.js:
10486
12138
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
12139
+
12140
+ @noble/curves/esm/utils.js:
12141
+ @noble/curves/esm/abstract/modular.js:
12142
+ @noble/curves/esm/abstract/curve.js:
12143
+ @noble/curves/esm/abstract/edwards.js:
12144
+ @noble/curves/esm/ed25519.js:
12145
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
10487
12146
  */
10488
12147
  globalThis.BlockcastMmt = BlockcastMmt;
10489
12148
  //# sourceMappingURL=mmtp-container-parser.no-modules.js.map