@blockcast/mmt-container 0.4.1 → 0.5.0-main.9c437a834da9

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 +3288 -272
  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 +7 -15
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +105 -62
  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 +62 -26
  26. package/dist/mmtp-router.d.ts.map +1 -1
  27. package/dist/mmtp-router.js +239 -163
  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 +46 -7
  34. package/dist/multicast-manager.d.ts.map +1 -1
  35. package/dist/multicast-manager.js +3283 -303
  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 +35 -109
  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 +287 -229
  56. package/src/multicast-auth-catalog.ts +81 -8
  57. package/src/multicast-manager.ts +182 -33
  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
@@ -5066,18 +5066,18 @@ function hevcNalUnitsContainIrap(nals) {
5066
5066
  return sawNal ? false : void 0;
5067
5067
  }
5068
5068
  function classifyHevcKeyframe(data) {
5069
- const split = splitHevcSample(data);
5070
- return split === null ? void 0 : hevcNalUnitsContainIrap(split.nals);
5069
+ const split2 = splitHevcSample(data);
5070
+ return split2 === null ? void 0 : hevcNalUnitsContainIrap(split2.nals);
5071
5071
  }
5072
5072
  function detectHevcKeyframe(data) {
5073
5073
  return classifyHevcKeyframe(data) === true;
5074
5074
  }
5075
5075
  function prepareHevcCmafSample(data, sampleEntry) {
5076
- const split = splitHevcSample(data);
5077
- if (split === null) return null;
5078
- const keyframe = hevcNalUnitsContainIrap(split.nals);
5076
+ const split2 = splitHevcSample(data);
5077
+ if (split2 === null) return null;
5078
+ const keyframe = hevcNalUnitsContainIrap(split2.nals);
5079
5079
  if (keyframe === void 0) return null;
5080
- const normalized = hevcNalUnitsToLengthPrefixed(data, split.nals, split.lengthPrefixed, sampleEntry);
5080
+ const normalized = hevcNalUnitsToLengthPrefixed(data, split2.nals, split2.lengthPrefixed, sampleEntry);
5081
5081
  return normalized === null ? null : { keyframe, data: normalized };
5082
5082
  }
5083
5083
  function normalizeHevcSampleToLengthPrefixed(data, sampleEntry) {
@@ -7566,14 +7566,22 @@ function toWindowMulticastSubscribeConfig(input) {
7566
7566
  if (input.packetIds?.some((id) => !isMulticastTrackPacketId(id)) || input.tracks?.some((track) => !isMulticastTrackPacketId(track.packetId))) {
7567
7567
  throw new RangeError(`multicast packetId must be an integer from 1 to ${MMTP_PACKET_ID_MAX2}; packetId 0 is the MMTP signaling flow and is never a track's`);
7568
7568
  }
7569
+ const source = input.source?.trim() || void 0;
7570
+ const senderAddress = input.senderAddress?.trim() || void 0;
7571
+ if (source && senderAddress) {
7572
+ throw new TypeError("multicast senderAddress is an ASM filter and never appears beside source");
7573
+ }
7569
7574
  const base = {
7570
7575
  group: input.group,
7571
7576
  port: input.port,
7572
- ...input.source?.trim() ? { source: input.source.trim() } : {},
7577
+ ...source ? { source } : {},
7573
7578
  consume: "bytes",
7574
7579
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
7575
7580
  };
7581
+ const filter = senderAddress ? { senderAddress } : {};
7576
7582
  if (input.atsc3) {
7583
+ if (senderAddress)
7584
+ throw new TypeError("an ATSC3 tuner request carries no senderAddress");
7577
7585
  const { frequency, plpId, serviceId } = input.atsc3;
7578
7586
  if (!Number.isInteger(frequency) || frequency < 1) {
7579
7587
  throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
@@ -7593,6 +7601,7 @@ function toWindowMulticastSubscribeConfig(input) {
7593
7601
  if (!wantsAmt) {
7594
7602
  const native = {
7595
7603
  ...base,
7604
+ ...filter,
7596
7605
  origin: "ip-multicast",
7597
7606
  ...input.tracks?.length ? { tracks: input.tracks.map(({ name, packetId }) => ({ name, packetId })) } : {}
7598
7607
  };
@@ -7618,6 +7627,7 @@ function toWindowMulticastSubscribeConfig(input) {
7618
7627
  }
7619
7628
  return {
7620
7629
  ...base,
7630
+ ...filter,
7621
7631
  origin: "amt",
7622
7632
  relay,
7623
7633
  relayPort
@@ -7643,6 +7653,9 @@ function isValidMulticastGroupAddress(address) {
7643
7653
  function normalizeMulticastEndpoint(endpoint) {
7644
7654
  const groupAddress = endpoint.groupAddress.trim().toLowerCase();
7645
7655
  const sourceAddress = endpoint.sourceAddress?.trim().toLowerCase() || void 0;
7656
+ const senderAddress = endpoint.senderAddress?.trim().toLowerCase() || void 0;
7657
+ if (sourceAddress && senderAddress)
7658
+ return void 0;
7646
7659
  const amtRelay = endpoint.amtRelay?.trim().toLowerCase() || void 0;
7647
7660
  if (!isValidMulticastGroupAddress(groupAddress) || !isPositivePort(endpoint.port))
7648
7661
  return void 0;
@@ -7653,6 +7666,7 @@ function normalizeMulticastEndpoint(endpoint) {
7653
7666
  return {
7654
7667
  groupAddress,
7655
7668
  ...sourceAddress ? { sourceAddress } : {},
7669
+ ...senderAddress ? { senderAddress } : {},
7656
7670
  port: endpoint.port,
7657
7671
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7658
7672
  ...amtRelay ? { amtRelay } : {},
@@ -7672,7 +7686,9 @@ function multicastEndpointKey(endpoint) {
7672
7686
  normalized.amtRelay ?? "",
7673
7687
  normalized.amtRelayPort ?? "",
7674
7688
  // A DRIAD join is a different gateway subscription from a native one.
7675
- ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
7689
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : [],
7690
+ // An ASM sender filter is a different subscription from the unfiltered join.
7691
+ ...normalized.senderAddress ? [{ senderAddress: normalized.senderAddress }] : []
7676
7692
  ]);
7677
7693
  }
7678
7694
  function isMulticastTrackPacketId(value) {
@@ -8930,14 +8946,14 @@ function validateNetworkSourceEntry(s, i) {
8930
8946
  }
8931
8947
  return;
8932
8948
  }
8933
- const inRange = (v, min, max) => Number.isInteger(v) && v >= min && v <= max;
8934
- if (!inRange(s.frequency, 1, Number.MAX_SAFE_INTEGER)) {
8949
+ const inRange2 = (v, min, max) => Number.isInteger(v) && v >= min && v <= max;
8950
+ if (!inRange2(s.frequency, 1, Number.MAX_SAFE_INTEGER)) {
8935
8951
  throw err("invalid_network_source", `frequency must be a positive integer in kHz; got ${s.frequency}`);
8936
8952
  }
8937
- if (s.plpId !== void 0 && !inRange(s.plpId, 0, 63)) {
8953
+ if (s.plpId !== void 0 && !inRange2(s.plpId, 0, 63)) {
8938
8954
  throw err("invalid_network_source", `plpId must be 0..63; got ${s.plpId}`);
8939
8955
  }
8940
- if (s.serviceId !== void 0 && !inRange(s.serviceId, 0, 65535)) {
8956
+ if (s.serviceId !== void 0 && !inRange2(s.serviceId, 0, 65535)) {
8941
8957
  throw err("invalid_network_source", `serviceId must be 0..65535; got ${s.serviceId}`);
8942
8958
  }
8943
8959
  if (s.slsUri !== void 0 && (typeof s.slsUri !== "string" || !isAbsoluteUri(s.slsUri))) {
@@ -10647,9 +10663,9 @@ var CmafBlockAssembler = class {
10647
10663
  const sample = splitH264SampleNalUnits(data);
10648
10664
  const nalTypes = describeH264NalTypes(sample.nals);
10649
10665
  const classify = classifyH264Keyframe(data);
10650
- const hex = Array.from(data.subarray(0, Math.min(48, data.length))).map((b) => b.toString(16).padStart(2, "0")).join(" ");
10666
+ const hex3 = Array.from(data.subarray(0, Math.min(48, data.length))).map((b) => b.toString(16).padStart(2, "0")).join(" ");
10651
10667
  console.log(
10652
- `[L4-KF-GATE] reject#${this.#keyframeRejectDumpCount} len=${data.length} metadataKf=${metadataKeyframe} classify=${classify} format=${sample.format} nalTypes=[${nalTypes.join(",")}] first48=[${hex}]`
10668
+ `[L4-KF-GATE] reject#${this.#keyframeRejectDumpCount} len=${data.length} metadataKf=${metadataKeyframe} classify=${classify} format=${sample.format} nalTypes=[${nalTypes.join(",")}] first48=[${hex3}]`
10653
10669
  );
10654
10670
  }
10655
10671
  /** Mark video as already synchronized by an external decoder path.
@@ -13257,6 +13273,79 @@ function decideGap(input) {
13257
13273
  });
13258
13274
  }
13259
13275
 
13276
+ // src/held-layer-admission.ts
13277
+ var HORIZON_CAP = 1073741824;
13278
+ function heldLayerAnchorHorizon(retentionBlocks, k) {
13279
+ return retentionBlocks === void 0 || k <= 0 ? HORIZON_CAP : Math.min(HORIZON_CAP, retentionBlocks * k);
13280
+ }
13281
+ var HeldLayerAdmission = class {
13282
+ #layerNames;
13283
+ #states;
13284
+ constructor(layers, heldLayers = [0]) {
13285
+ const held = new Set(heldLayers);
13286
+ this.#layerNames = new Set(layers.map((l) => l.repairTrackName));
13287
+ this.#states = layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }));
13288
+ }
13289
+ /**
13290
+ * Judges one repair packet, after the 4.5 discards and the size check and
13291
+ * before it places a block. `repairTrackName` is the subscribed repair
13292
+ * track, never inferred from RS_ID; without it only (b) runs. A packet on a
13293
+ * repair track the catalog does not list is `'discard'` and anchors nothing.
13294
+ * `sourceFrontier` is the newest source SS_ID, if any: a repair more than
13295
+ * `horizon` past it is judged without moving the anchored state.
13296
+ *
13297
+ * @returns undefined to admit, `'discard'`, or the fail-closed reason.
13298
+ */
13299
+ admit(repairTrackName, ssStart, rsbLength, horizon, sourceFrontier) {
13300
+ if (repairTrackName !== void 0 && !this.#layerNames.has(repairTrackName)) return "discard";
13301
+ const farAhead = sourceFrontier !== void 0 && serial32Precedes(sourceFrontier, ssStart) && serial32Distance(sourceFrontier, ssStart) > horizon;
13302
+ for (const state of this.#states) {
13303
+ let code;
13304
+ if (farAhead) {
13305
+ if (rsbLength < state.total) {
13306
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
13307
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
13308
+ }
13309
+ } else {
13310
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
13311
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
13312
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
13313
+ delete state.latestBelow;
13314
+ delete state.latestBelowRsb;
13315
+ }
13316
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
13317
+ if (rsbLength < state.total) {
13318
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
13319
+ else if (stale(ssStart)) continue;
13320
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
13321
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
13322
+ state.latestBelow = ssStart;
13323
+ state.latestBelowRsb = rsbLength;
13324
+ }
13325
+ } else if (!state.settled && !stale(ssStart)) {
13326
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
13327
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
13328
+ code = "below_anchored_total";
13329
+ ssStart = state.latestBelow;
13330
+ rsbLength = state.latestBelowRsb;
13331
+ }
13332
+ }
13333
+ }
13334
+ if (code !== void 0) {
13335
+ return {
13336
+ code,
13337
+ layer: state.layer,
13338
+ total: state.total,
13339
+ rsbLength,
13340
+ ssStart,
13341
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
13342
+ };
13343
+ }
13344
+ }
13345
+ return void 0;
13346
+ }
13347
+ };
13348
+
13260
13349
  // src/fec-manager.ts
13261
13350
  var RS_MAX_BLOCK_SYMBOLS = 255;
13262
13351
  var WORKER_ERROR_LOG_CAP = 5;
@@ -13771,12 +13860,12 @@ var FECManager = class _FECManager {
13771
13860
  * still be held behind it. Retirement is swept lazily here, on the stream's
13772
13861
  * own terminal events, so it needs no timer.
13773
13862
  */
13774
- #markTerminal(key, sbn, packetId, clean) {
13863
+ #markTerminal(key, sbn, packetId, clean2) {
13775
13864
  const nowMs = performance.now();
13776
13865
  this.#retireTerminalBlocks(packetId, nowMs);
13777
13866
  this.#forgetOrderedPending(key);
13778
13867
  this.#completedBlocks.add(key);
13779
- if (clean) this.#cleanlyCompletedBlocks.add(key);
13868
+ if (clean2) this.#cleanlyCompletedBlocks.add(key);
13780
13869
  this.#indexBlockKey(key, sbn, packetId);
13781
13870
  const config = this.#trackConfig(packetId);
13782
13871
  const expiresAtMs = nowMs + config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config);
@@ -15352,6 +15441,18 @@ var FECManager = class _FECManager {
15352
15441
  blockAnchorAtMs(sbn, packetId, catalogTrackName) {
15353
15442
  return this.#blockAnchorsMs.get(this.#blockKey(sbn, packetId, catalogTrackName));
15354
15443
  }
15444
+ /**
15445
+ * How long ago (ms) the oldest open block of the stream, one with an FEC
15446
+ * deadline, took its first accepted symbol; undefined with none open.
15447
+ */
15448
+ oldestOpenBlockAgeMs(packetId, catalogTrackName) {
15449
+ let oldest = Infinity;
15450
+ for (const key of this.#activeBlocks.keys()) {
15451
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue;
15452
+ oldest = Math.min(oldest, this.#blockAnchorsMs.get(key) ?? Infinity);
15453
+ }
15454
+ return oldest === Infinity ? void 0 : performance.now() - oldest;
15455
+ }
15355
15456
  /** Absolute fail deadline of a still-open block, or undefined. */
15356
15457
  blockDeadlineAtMs(sbn, packetId, catalogTrackName) {
15357
15458
  return this.#activeBlockDeadlinesMs.get(this.#blockKey(sbn, packetId, catalogTrackName));
@@ -16174,66 +16275,26 @@ var FECManager = class _FECManager {
16174
16275
  const config = this.#trackConfigs.get(packetId);
16175
16276
  const layers = config?.repairLayers;
16176
16277
  if (layers === void 0 || layers.length === 0) return true;
16177
- if (repairTrackName !== void 0 && !layers.some((l) => l.repairTrackName === repairTrackName)) {
16178
- return false;
16278
+ let admission = this.#heldLayerStates.get(streamKey);
16279
+ if (admission === void 0) {
16280
+ admission = new HeldLayerAdmission(layers, config.heldLayers);
16281
+ this.#heldLayerStates.set(streamKey, admission);
16179
16282
  }
16180
- let states = this.#heldLayerStates.get(streamKey);
16181
- if (states === void 0) {
16182
- const held = new Set(config.heldLayers ?? [0]);
16183
- states = layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }));
16184
- this.#heldLayerStates.set(streamKey, states);
16185
- }
16186
- const horizon = this.#layerAnchorHorizon(packetId);
16187
- const frontier = this.#sourceFrontiers.get(streamKey)?.sbn;
16188
- const farAhead = frontier !== void 0 && serial32Precedes(frontier, ssStart) && serial32Distance(frontier, ssStart) > horizon;
16189
- for (const state of states) {
16190
- let code;
16191
- if (farAhead) {
16192
- if (rsbLength < state.total) {
16193
- if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
16194
- else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
16195
- }
16196
- } else {
16197
- if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
16198
- const stale = (s) => serial32Distance(s, state.newest) > horizon;
16199
- if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
16200
- delete state.latestBelow;
16201
- delete state.latestBelowRsb;
16202
- }
16203
- if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
16204
- if (rsbLength < state.total) {
16205
- if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
16206
- else if (stale(ssStart)) continue;
16207
- else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
16208
- else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
16209
- state.latestBelow = ssStart;
16210
- state.latestBelowRsb = rsbLength;
16211
- }
16212
- } else if (!state.settled && !stale(ssStart)) {
16213
- if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
16214
- if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
16215
- code = "below_anchored_total";
16216
- ssStart = state.latestBelow;
16217
- rsbLength = state.latestBelowRsb;
16218
- }
16219
- }
16220
- }
16221
- if (code !== void 0) {
16222
- const reason = {
16223
- code,
16224
- layer: state.layer,
16225
- total: state.total,
16226
- rsbLength,
16227
- ssStart,
16228
- ...state.anchor === void 0 ? {} : { anchor: state.anchor }
16229
- };
16230
- this.#fecFailClosed.set(streamKey, reason);
16231
- this.#onFecFailClosed?.({ ...reason, packetId, catalogTrackName });
16232
- console.warn(
16233
- `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? "-"}: ${JSON.stringify(reason)}`
16234
- );
16235
- return false;
16236
- }
16283
+ const verdict = admission.admit(
16284
+ repairTrackName,
16285
+ ssStart,
16286
+ rsbLength,
16287
+ this.#layerAnchorHorizon(packetId),
16288
+ this.#sourceFrontiers.get(streamKey)?.sbn
16289
+ );
16290
+ if (verdict === "discard") return false;
16291
+ if (verdict !== void 0) {
16292
+ this.#fecFailClosed.set(streamKey, verdict);
16293
+ this.#onFecFailClosed?.({ ...verdict, packetId, catalogTrackName });
16294
+ console.warn(
16295
+ `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? "-"}: ${JSON.stringify(verdict)}`
16296
+ );
16297
+ return false;
16237
16298
  }
16238
16299
  return true;
16239
16300
  }
@@ -16243,15 +16304,13 @@ var FECManager = class _FECManager {
16243
16304
  * times K, capped at 2^30 so compared serials stay inside one half-window.
16244
16305
  */
16245
16306
  #layerAnchorHorizon(packetId) {
16246
- const cap = 1073741824;
16247
16307
  let blocks;
16248
16308
  try {
16249
16309
  blocks = this.isoRetentionBlocksForPacket(packetId);
16250
16310
  } catch {
16251
16311
  blocks = void 0;
16252
16312
  }
16253
- const k = this.#trackConfigs.get(packetId)?.k ?? 0;
16254
- return blocks === void 0 || k <= 0 ? cap : Math.min(cap, blocks * k);
16313
+ return heldLayerAnchorHorizon(blocks, this.#trackConfigs.get(packetId)?.k ?? 0);
16255
16314
  }
16256
16315
  /**
16257
16316
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), once,
@@ -19366,11 +19425,19 @@ var MmtpRouter = class {
19366
19425
  #fecManager;
19367
19426
  #defaultFecMapper;
19368
19427
  #fecMappersByPacketId = /* @__PURE__ */ new Map();
19369
- #manifestVerifier;
19370
- #ownsManifestVerifier;
19371
- #resolveManifestIdentity;
19372
- #resolveManifestIdentityForRoute;
19373
- #manifestRecoveryQueues = /* @__PURE__ */ new Map();
19428
+ /** Protected flows: one 7.2.7 receiver each, and the ingress its datagrams arrive with. */
19429
+ #provenance = /* @__PURE__ */ new Map();
19430
+ #onFlowProtected = null;
19431
+ #unadmittedListedDrops = 0;
19432
+ /** The ingress a held datagram arrived with; the receiver returns the same bytes on release. */
19433
+ #heldIngress = /* @__PURE__ */ new WeakMap();
19434
+ #unicastRepair = false;
19435
+ /** How to route a held unicast (MoQ) datagram once a record admits it. */
19436
+ #heldReplay = /* @__PURE__ */ new WeakMap();
19437
+ /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
19438
+ #provenanceStreamFlow = /* @__PURE__ */ new Map();
19439
+ #unregisteredFlowDrops = 0;
19440
+ #ambiguousRecoveredDrops = 0;
19374
19441
  // Temp state set by #processMMTP before calling parser.feed(),
19375
19442
  // read by the parser's onFrame callback for CMAF assembly + dedup.
19376
19443
  #currentFecInfo;
@@ -19507,10 +19574,6 @@ var MmtpRouter = class {
19507
19574
  this.#fecManager = config?.fecManager ?? null;
19508
19575
  this.#onFrameGap = config?.onFrameGap ?? null;
19509
19576
  this.#defaultFecMapper = config?.fecMapper ?? null;
19510
- this.#manifestVerifier = config?.manifestVerifier ?? null;
19511
- this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
19512
- this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;
19513
- this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;
19514
19577
  this.#parser = new MmtpContainerParser({
19515
19578
  mfuTimeoutMs: config?.mfuTimeoutMs,
19516
19579
  reassemblyPolicy: config?.reassemblyPolicy,
@@ -20042,29 +20105,162 @@ var MmtpRouter = class {
20042
20105
  }
20043
20106
  });
20044
20107
  }
20045
- registerManifestTrack(context) {
20046
- if (!this.#manifestVerifier) throw new Error("manifest verifier is not configured");
20047
- this.#manifestVerifier.registerTrack(context);
20048
- }
20049
- feedManifestFrame(trackName, frame) {
20050
- this.#manifestVerifier?.ingestManifestFrame(trackName, frame);
20051
- }
20052
- setManifestAuthMode(mode) {
20053
- this.#manifestVerifier?.setMode(mode);
20054
- if (mode !== "enforce") {
20055
- for (const queue of this.#manifestRecoveryQueues.values()) {
20056
- for (const item of queue) {
20057
- this.#routeProcessedFecSymbols(
20058
- item.blockId,
20059
- item.result,
20060
- item.ownerPacketId,
20061
- item.catalogTrackName
20062
- );
20108
+ /**
20109
+ * Protect a flow (draft-ramadan-moq-multicast-01 7.2.7): every multicast
20110
+ * datagram whose ingress names `ingress.flow`, source and repair alike, is
20111
+ * admitted by `receiver` before anything reads it, and an unadmitted one is
20112
+ * held or dropped. The caller owns the receiver's configuration; the router
20113
+ * releases it on `releaseProvenanceFlow` and on dispose.
20114
+ */
20115
+ registerProvenanceFlow(ingress, receiver) {
20116
+ this.#provenance.get(ingress.flow)?.receiver.release();
20117
+ this.#provenance.set(ingress.flow, { receiver, ingress });
20118
+ receiver.keepPendingAgeMs = () => this.#oldestOpenBlockAgeMs(ingress.flow);
20119
+ }
20120
+ /**
20121
+ * Declare that this receiver can request unicast repair (a repair FETCH
20122
+ * scheduler is wired): a protected flow then keeps the pending entries of
20123
+ * its open blocks for the repair to consume (7.2.7 step 2).
20124
+ */
20125
+ setUnicastRepair(enabled) {
20126
+ this.#unicastRepair = enabled;
20127
+ }
20128
+ #oldestOpenBlockAgeMs(flow) {
20129
+ const entry = this.#provenance.get(flow);
20130
+ if (!this.#unicastRepair || !entry) return void 0;
20131
+ let age;
20132
+ for (const { name, packetId } of entry.ingress.tracks) {
20133
+ const a = name ? this.#fecManager?.oldestOpenBlockAgeMs?.(packetId, name) : void 0;
20134
+ if (a !== void 0 && (age === void 0 || a > age)) age = a;
20135
+ }
20136
+ return age;
20137
+ }
20138
+ /**
20139
+ * Replace a registered flow's ingress (a rendition switch staged, committed
20140
+ * or cancelled) while keeping its receiver; a no-op for an unregistered flow.
20141
+ */
20142
+ updateProvenanceFlowIngress(ingress) {
20143
+ const entry = this.#provenance.get(ingress.flow);
20144
+ if (!entry) return;
20145
+ this.#provenance.set(ingress.flow, { ...entry, ingress });
20146
+ if (entry.protected) {
20147
+ for (const { name, packetId } of ingress.tracks) {
20148
+ if (name && !entry.ingress.tracks.some((t) => t.name === name && t.packetId === packetId)) {
20149
+ this.#fecManager?.resetTrack?.(packetId, name);
20063
20150
  }
20064
20151
  }
20065
- this.#manifestRecoveryQueues.clear();
20066
20152
  }
20067
20153
  }
20154
+ /**
20155
+ * Called once per protection of a flow: at the admission that makes this
20156
+ * router's consumers protected under it (7.2.7), after their unadmitted
20157
+ * holdings of its listed tracks are discarded. Again after an unprotect.
20158
+ */
20159
+ onProvenanceFlowProtected(cb) {
20160
+ this.#onFlowProtected = cb;
20161
+ }
20162
+ /**
20163
+ * The receiver ceased to hold the flow's endpoint on failover (7.2.7): drop
20164
+ * its state and hold queues (no expiry counted) and un-protect its tracks,
20165
+ * which then take MoQ again. The registration stays, so multicast resuming
20166
+ * protects the flow anew at its next admission.
20167
+ */
20168
+ unprotectProvenanceFlow(flow) {
20169
+ const entry = this.#provenance.get(flow);
20170
+ if (!entry) return;
20171
+ entry.receiver.release();
20172
+ entry.protected = false;
20173
+ }
20174
+ /** MoQ packets of a track a protected flow lists, dropped on its unicast path: duplicate, overflow, or listed by more than one flow. */
20175
+ get unadmittedListedDropCount() {
20176
+ return this.#unadmittedListedDrops;
20177
+ }
20178
+ /**
20179
+ * The admission that makes this router protected under `flow` (7.2.7):
20180
+ * its FEC instances discard what they hold of the flow's listed tracks so
20181
+ * no unadmitted symbol stands for an admitted one, then notify. Before it
20182
+ * nothing of the flow was admitted, so every such symbol is unadmitted.
20183
+ * The playback parse ledger is kept: it records MoQ copies already played,
20184
+ * not holdings, and clearing it re-emits that media (audio twice).
20185
+ * The FEC reset is the whole 7.2.7 discard here: no keyframe-overlay
20186
+ * instance exists to hold anything (repair-layers.ts is the catalog
20187
+ * contract only, no decoder), and packet_id 0 is never a listed track
20188
+ * (`ingressHasPacketId`), so nothing of it is held for the flow.
20189
+ */
20190
+ #noteFlowAdmitted(flow) {
20191
+ const entry = this.#provenance.get(flow);
20192
+ if (!entry || entry.protected) return;
20193
+ entry.protected = true;
20194
+ for (const { name, packetId } of entry.ingress.tracks) {
20195
+ if (name) this.#fecManager?.resetTrack?.(packetId, name);
20196
+ }
20197
+ this.#onFlowProtected?.(flow);
20198
+ }
20199
+ /**
20200
+ * Admit a MoQ datagram of `packetId` on the unicast path of the protected
20201
+ * flow that lists it (7.2.7). `unlisted`: no protected flow lists it, so it
20202
+ * is read as before. A held datagram is routed by `replay` when a record
20203
+ * admits it; one more than one protected flow lists is dropped. So is an
20204
+ * overlap copy: it never enters FEC accounting, so admitting it would leave
20205
+ * its multicast twin a duplicate and the block one symbol short.
20206
+ */
20207
+ #admitUnicast(packetId, packet, replay, overlapCopy = false) {
20208
+ let receiver;
20209
+ for (const entry of this.#provenance.values()) {
20210
+ if (!entry.protected || !ingressHasPacketId(entry.ingress, packetId)) continue;
20211
+ if (receiver || overlapCopy) {
20212
+ this.#unadmittedListedDrops++;
20213
+ return "dropped";
20214
+ }
20215
+ receiver = entry.receiver;
20216
+ }
20217
+ if (!receiver) return "unlisted";
20218
+ const { verdict } = receiver.onDatagram(packet, "unicast");
20219
+ if (verdict === "admitted") return "admitted";
20220
+ if (verdict === "held") {
20221
+ this.#heldReplay.set(packet, replay);
20222
+ return "held";
20223
+ }
20224
+ this.#unadmittedListedDrops++;
20225
+ return "dropped";
20226
+ }
20227
+ /**
20228
+ * Feed one bc-provenance record of `flow`: a datagram from `manifestPort`
20229
+ * (`multicast`) or an object of the manifest track (`mirror`). Held
20230
+ * datagrams the record admits are routed before this returns.
20231
+ */
20232
+ feedProvenanceRecord(flow, record, path) {
20233
+ const entry = this.#provenance.get(flow);
20234
+ if (!entry || this.#disposed) return "unregistered";
20235
+ const result = entry.receiver.onRecord(record, path);
20236
+ if (result.admitted.length > 0) {
20237
+ this.#noteFlowAdmitted(flow);
20238
+ this.#withDeferredFecPokes(() => {
20239
+ for (const datagram of result.admitted) {
20240
+ const replay = this.#heldReplay.get(datagram);
20241
+ if (replay) replay();
20242
+ else this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
20243
+ }
20244
+ });
20245
+ }
20246
+ return result.verdict;
20247
+ }
20248
+ /** The receiver ceased to hold the flow: its hold queues are dropped, not expired. */
20249
+ releaseProvenanceFlow(flow) {
20250
+ this.#provenance.get(flow)?.receiver.release();
20251
+ this.#provenance.delete(flow);
20252
+ for (const byName of this.#provenanceStreamFlow.values()) {
20253
+ for (const [name, bound] of byName) if (bound === flow) byName.delete(name);
20254
+ }
20255
+ }
20256
+ /** Multicast datagrams dropped because their ingress names a flow with no registered receiver. */
20257
+ get unregisteredFlowDropCount() {
20258
+ return this.#unregisteredFlowDrops;
20259
+ }
20260
+ /** Recovered packets dropped because more than one protected flow could own their stream. */
20261
+ get ambiguousRecoveredDropCount() {
20262
+ return this.#ambiguousRecoveredDrops;
20263
+ }
20068
20264
  /**
20069
20265
  * Main entry point: feed a raw MMTP packet for processing.
20070
20266
  *
@@ -20079,10 +20275,10 @@ var MmtpRouter = class {
20079
20275
  * they may never have crossed — and that attribution is what the physical-
20080
20276
  * delivery evidence path is built on. Absence is not multicast; say which.
20081
20277
  */
20082
- feedPacket(packet, source, manifestIdentity, ingress) {
20278
+ feedPacket(packet, source, ingress) {
20083
20279
  if (this.#disposed) return;
20084
20280
  this.#withDeferredFecPokes(() => {
20085
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
20281
+ this.#processMMTP(packet, source, false, ingress);
20086
20282
  });
20087
20283
  }
20088
20284
  /**
@@ -20117,7 +20313,7 @@ var MmtpRouter = class {
20117
20313
  feedOverlapCopy(packet, ingress) {
20118
20314
  if (this.#disposed) return;
20119
20315
  this.#withDeferredFecPokes(() => {
20120
- this.#processMMTP(packet, "moq", void 0, false, ingress, true);
20316
+ this.#processMMTP(packet, "moq", false, ingress, true);
20121
20317
  });
20122
20318
  }
20123
20319
  /**
@@ -20130,7 +20326,7 @@ var MmtpRouter = class {
20130
20326
  this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
20131
20327
  });
20132
20328
  }
20133
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
20329
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
20134
20330
  let header;
20135
20331
  try {
20136
20332
  header = parseMMTPHeader(packet);
@@ -20147,6 +20343,10 @@ var MmtpRouter = class {
20147
20343
  `[MmtpRouter] Dropping MoQ repair packet pid=${repairPacketId}: owner hint is required`
20148
20344
  );
20149
20345
  }
20346
+ if (ownerPacketId != null && !admitted) {
20347
+ const admit = this.#admitUnicast(ownerPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
20348
+ if (admit === "held" || admit === "dropped") return;
20349
+ }
20150
20350
  if (ownerPacketId != null && this.#fecManager) {
20151
20351
  this.#moqRepairPidCounts[repairPacketId] = (this.#moqRepairPidCounts[repairPacketId] || 0) + 1;
20152
20352
  this.#moqRepairOwnerCounts[ownerPacketId] = (this.#moqRepairOwnerCounts[ownerPacketId] || 0) + 1;
@@ -20410,7 +20610,6 @@ var MmtpRouter = class {
20410
20610
  this.#lastDirectSourceAudioCursorByStream.delete(streamKey);
20411
20611
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
20412
20612
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
20413
- this.#manifestRecoveryQueues.delete(streamKey);
20414
20613
  this.#deliveredVideoHighWaterByStream.delete(streamKey);
20415
20614
  this.#stream(packetId, catalogTrackName).duplicates.clear();
20416
20615
  const assemblersToReset = /* @__PURE__ */ new Set();
@@ -20460,7 +20659,6 @@ var MmtpRouter = class {
20460
20659
  this.#lastDirectSourceAudioCursorByStream.delete(key);
20461
20660
  this.#lastDirectEmittedAudioCursorByStream.delete(key);
20462
20661
  this.#pendingDirectRecoveredAudioByStream.delete(key);
20463
- this.#manifestRecoveryQueues.delete(key);
20464
20662
  this.#trackInitDelivered.delete(key);
20465
20663
  this.#parserDiagnostics.delete(key);
20466
20664
  this.#pendingFecPokes.delete(key);
@@ -20721,8 +20919,9 @@ var MmtpRouter = class {
20721
20919
  this.#parserDiagnostics.clear();
20722
20920
  this.#catalogTrackNamesByPacketId.clear();
20723
20921
  this.#repairOwnersByPacketId.clear();
20724
- if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();
20725
- this.#manifestRecoveryQueues.clear();
20922
+ for (const { receiver } of this.#provenance.values()) receiver.release();
20923
+ this.#provenance.clear();
20924
+ this.#provenanceStreamFlow.clear();
20726
20925
  for (const assembler of this.#mseAssemblers.values()) assembler.dispose();
20727
20926
  this.#mseAssemblers.clear();
20728
20927
  }
@@ -20999,7 +21198,7 @@ var MmtpRouter = class {
20999
21198
  * 1. parseHeader() → extract packetId + fecPayloadId for FEC feeding
21000
21199
  * 2. feed() → MFU extraction, reassembly, keyframe detection, emit via callbacks
21001
21200
  */
21002
- #processMMTP(packet, source, manifestIdentity, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
21201
+ #processMMTP(packet, source, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
21003
21202
  const parsed = this.#parser.parsePacket(packet);
21004
21203
  if (!parsed) return;
21005
21204
  const info = parsed.info;
@@ -21024,43 +21223,29 @@ var MmtpRouter = class {
21024
21223
  }
21025
21224
  const fecUnreadable = !info.isRepair && info.fecPayloadId != null && this.#fecManager !== null && this.#classifyPacketId(info.packetId) !== null && this.#configuredBlockProfile(info.packetId) === void 0;
21026
21225
  if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, "source");
21027
- if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {
21028
- let identity = manifestIdentity;
21029
- if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {
21030
- const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
21031
- const coordinates = this.#locateFecSource(info.packetId, catalogTrackName, info.fecPayloadId.ssId);
21032
- identity = coordinates === null ? void 0 : (this.#resolveManifestIdentityForRoute ? this.#resolveManifestIdentityForRoute({
21033
- packetId: info.packetId,
21034
- sbn: coordinates.sbn,
21035
- esi: coordinates.esi,
21036
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
21037
- recovered: false,
21038
- sourceSymbolFormat: "full-mmtp-packet"
21039
- }) : this.#resolveManifestIdentity(
21040
- info.packetId,
21041
- coordinates.sbn,
21042
- coordinates.esi,
21043
- catalogTrackName
21044
- )) ?? void 0;
21045
- }
21046
- if (identity) {
21047
- identity = {
21048
- ...identity,
21049
- packetId: info.packetId,
21050
- ...info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}
21051
- };
21052
- const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
21053
- let quarantined = false;
21054
- const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
21055
- if (!this.#disposed) {
21056
- this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
21057
- }
21058
- });
21059
- quarantined = admission.action === "stall";
21226
+ if (source === "multicast" && manifestAdmitted && !info.isRepair && ingress?.flow !== void 0) {
21227
+ let byName = this.#provenanceStreamFlow.get(info.packetId);
21228
+ if (!byName) this.#provenanceStreamFlow.set(info.packetId, byName = /* @__PURE__ */ new Map());
21229
+ byName.set(catalogTrackNameForPacket(ingress, info.packetId), ingress.flow);
21230
+ }
21231
+ if (source === "multicast" && !manifestAdmitted && ingress?.flow !== void 0) {
21232
+ const protectedFlow = this.#provenance.get(ingress.flow);
21233
+ if (!protectedFlow) {
21234
+ this.#unregisteredFlowDrops++;
21235
+ debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
21060
21236
  return;
21061
21237
  }
21062
- if (this.#manifestVerifier.config.mode === "enforce" && this.#manifestVerifier.config.onMissingManifest === "stall") {
21063
- console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);
21238
+ const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
21239
+ if (verdict === "admitted") {
21240
+ this.#noteFlowAdmitted(ingress.flow);
21241
+ this.#processMMTP(packet, source, true, ingress, overlapCopy);
21242
+ } else if (verdict === "held") this.#heldIngress.set(packet, ingress);
21243
+ return;
21244
+ }
21245
+ if (source === "moq" && !manifestAdmitted) {
21246
+ const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
21247
+ if (admit !== "unlisted") {
21248
+ if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
21064
21249
  return;
21065
21250
  }
21066
21251
  }
@@ -21661,101 +21846,51 @@ var MmtpRouter = class {
21661
21846
  });
21662
21847
  this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21663
21848
  }
21849
+ /**
21850
+ * A recovered source packet of a protected flow is admitted on its own
21851
+ * digest: its bytes with the SS_ID it was sent with (SS_Start + ESI)
21852
+ * appended are the datagram the record listed (7.2.7). One that no record
21853
+ * lists is dropped; holding it would let it out later as a multicast arrival.
21854
+ */
21664
21855
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21665
- if (!this.#manifestVerifier || ownerPacketId == null) {
21666
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21667
- return;
21668
- }
21669
- if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {
21670
- console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);
21671
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21672
- return;
21856
+ const receiver = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21857
+ if (receiver === "ambiguous") {
21858
+ this.#ambiguousRecoveredDrops += result.symbols.length;
21859
+ result = { ...result, symbols: [] };
21860
+ } else if (receiver) {
21861
+ result = {
21862
+ ...result,
21863
+ symbols: result.symbols.filter((sym) => {
21864
+ const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
21865
+ wire.set(sym.rawSymbol);
21866
+ new DataView(wire.buffer).setUint32(sym.rawSymbol.byteLength, this.#fecAnchorForRecovered(blockId, sym.index));
21867
+ return receiver.admitRecovered(wire);
21868
+ })
21869
+ };
21673
21870
  }
21674
- const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21675
- const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];
21676
- queue.push({ blockId, result, ownerPacketId, catalogTrackName });
21677
- this.#manifestRecoveryQueues.set(queueKey, queue);
21678
- if (queue.length > 1) return;
21679
- const drain = () => {
21680
- const next = queue[0];
21681
- if (!next) {
21682
- this.#manifestRecoveryQueues.delete(queueKey);
21683
- return;
21871
+ this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21872
+ }
21873
+ /**
21874
+ * The receiver a recovered packet of `packetId` answers to: the flow that
21875
+ * admitted the stream's source datagrams. Before any was admitted, the one
21876
+ * flow whose registration lists the stream; more than one (a repair flow
21877
+ * also lists its owners' source tracks) cannot be told apart, so none.
21878
+ */
21879
+ #provenanceFor(packetId, catalogTrackName) {
21880
+ const byName = this.#provenanceStreamFlow.get(packetId);
21881
+ const flows = new Set(
21882
+ catalogTrackName === void 0 || !byName ? byName?.values() : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)] : []
21883
+ );
21884
+ if (flows.size > 1) return "ambiguous";
21885
+ for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
21886
+ let match;
21887
+ for (const { receiver, ingress } of this.#provenance.values()) {
21888
+ if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === void 0 || t.name === catalogTrackName))) {
21889
+ if (match) return "ambiguous";
21890
+ match = receiver;
21684
21891
  }
21685
- this.#admitRecoveredResult(
21686
- next.blockId,
21687
- next.result,
21688
- next.ownerPacketId,
21689
- next.catalogTrackName,
21690
- () => {
21691
- queue.shift();
21692
- drain();
21693
- }
21694
- );
21695
- };
21696
- drain();
21697
- }
21698
- #admitRecoveredResult(blockId, result, ownerPacketId, catalogTrackName, done) {
21699
- const verifier = this.#manifestVerifier;
21700
- const resolveIdentity = this.#resolveManifestIdentity;
21701
- const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;
21702
- if (!verifier) {
21703
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21704
- done();
21705
- return;
21706
21892
  }
21707
- if (!resolveIdentity && !resolveIdentityForRoute) throw new Error("manifest identity resolver disappeared during admission");
21708
- const symbols = result.symbols;
21709
- const admitNext = (index) => {
21710
- const symbol = symbols[index];
21711
- if (!symbol) {
21712
- done();
21713
- return;
21714
- }
21715
- const identity = resolveIdentityForRoute ? resolveIdentityForRoute({
21716
- packetId: ownerPacketId,
21717
- sbn: blockId,
21718
- esi: symbol.index,
21719
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
21720
- recovered: true,
21721
- sourceSymbolFormat: "fec-padded-recovery"
21722
- }) : resolveIdentity(ownerPacketId, blockId, symbol.index, catalogTrackName);
21723
- if (!identity) {
21724
- console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);
21725
- this.#routeProcessedFecSymbols(
21726
- blockId,
21727
- { ...result, symbols: [symbol] },
21728
- ownerPacketId,
21729
- catalogTrackName
21730
- );
21731
- admitNext(index + 1);
21732
- return;
21733
- }
21734
- const admission = verifier.admitObject(
21735
- {
21736
- ...identity,
21737
- packetId: ownerPacketId
21738
- },
21739
- symbol.rawSymbol,
21740
- () => {
21741
- if (!this.#disposed) {
21742
- this.#routeProcessedFecSymbols(
21743
- blockId,
21744
- { ...result, symbols: [symbol] },
21745
- ownerPacketId,
21746
- catalogTrackName
21747
- );
21748
- }
21749
- admitNext(index + 1);
21750
- },
21751
- // A stalled symbol that is later discarded instead of played must still
21752
- // advance this loop; enforce mode never calls the release callback for
21753
- // it (BLO-30095).
21754
- () => admitNext(index + 1)
21755
- );
21756
- if (admission.action === "drop") admitNext(index + 1);
21757
- };
21758
- admitNext(0);
21893
+ return match;
21759
21894
  }
21760
21895
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21761
21896
  if (ownerPacketId == null) return;
@@ -22652,10 +22787,11 @@ var MulticastTransport = class {
22652
22787
  try {
22653
22788
  const packetIds = config.packetIds?.length ? new Set(config.packetIds) : null;
22654
22789
  console.log(
22655
- `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress}, ${config.groupAddress}, ${config.port})`
22790
+ `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress ?? config.senderAddress ?? "*"}, ${config.groupAddress}, ${config.port})`
22656
22791
  );
22657
22792
  const subscribeConfig = toWindowMulticastSubscribeConfig({
22658
22793
  source: config.sourceAddress,
22794
+ senderAddress: config.senderAddress,
22659
22795
  group: config.groupAddress,
22660
22796
  port: config.port,
22661
22797
  mode: config.mode,
@@ -23251,6 +23387,2726 @@ var MulticastTransport = class {
23251
23387
  }
23252
23388
  };
23253
23389
 
23390
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/crypto.js
23391
+ var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
23392
+
23393
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/utils.js
23394
+ function isBytes(a) {
23395
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
23396
+ }
23397
+ function anumber(n) {
23398
+ if (!Number.isSafeInteger(n) || n < 0)
23399
+ throw new Error("positive integer expected, got " + n);
23400
+ }
23401
+ function abytes(b, ...lengths) {
23402
+ if (!isBytes(b))
23403
+ throw new Error("Uint8Array expected");
23404
+ if (lengths.length > 0 && !lengths.includes(b.length))
23405
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
23406
+ }
23407
+ function aexists(instance, checkFinished = true) {
23408
+ if (instance.destroyed)
23409
+ throw new Error("Hash instance has been destroyed");
23410
+ if (checkFinished && instance.finished)
23411
+ throw new Error("Hash#digest() has already been called");
23412
+ }
23413
+ function aoutput(out, instance) {
23414
+ abytes(out);
23415
+ const min = instance.outputLen;
23416
+ if (out.length < min) {
23417
+ throw new Error("digestInto() expects output buffer of length at least " + min);
23418
+ }
23419
+ }
23420
+ function clean(...arrays) {
23421
+ for (let i = 0; i < arrays.length; i++) {
23422
+ arrays[i].fill(0);
23423
+ }
23424
+ }
23425
+ function createView(arr) {
23426
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
23427
+ }
23428
+ function rotr(word, shift) {
23429
+ return word << 32 - shift | word >>> shift;
23430
+ }
23431
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
23432
+ // @ts-ignore
23433
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
23434
+ ))();
23435
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
23436
+ function bytesToHex(bytes) {
23437
+ abytes(bytes);
23438
+ if (hasHexBuiltin)
23439
+ return bytes.toHex();
23440
+ let hex3 = "";
23441
+ for (let i = 0; i < bytes.length; i++) {
23442
+ hex3 += hexes[bytes[i]];
23443
+ }
23444
+ return hex3;
23445
+ }
23446
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
23447
+ function asciiToBase16(ch) {
23448
+ if (ch >= asciis._0 && ch <= asciis._9)
23449
+ return ch - asciis._0;
23450
+ if (ch >= asciis.A && ch <= asciis.F)
23451
+ return ch - (asciis.A - 10);
23452
+ if (ch >= asciis.a && ch <= asciis.f)
23453
+ return ch - (asciis.a - 10);
23454
+ return;
23455
+ }
23456
+ function hexToBytes(hex3) {
23457
+ if (typeof hex3 !== "string")
23458
+ throw new Error("hex string expected, got " + typeof hex3);
23459
+ if (hasHexBuiltin)
23460
+ return Uint8Array.fromHex(hex3);
23461
+ const hl = hex3.length;
23462
+ const al = hl / 2;
23463
+ if (hl % 2)
23464
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
23465
+ const array = new Uint8Array(al);
23466
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
23467
+ const n1 = asciiToBase16(hex3.charCodeAt(hi));
23468
+ const n2 = asciiToBase16(hex3.charCodeAt(hi + 1));
23469
+ if (n1 === void 0 || n2 === void 0) {
23470
+ const char = hex3[hi] + hex3[hi + 1];
23471
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
23472
+ }
23473
+ array[ai] = n1 * 16 + n2;
23474
+ }
23475
+ return array;
23476
+ }
23477
+ function utf8ToBytes(str) {
23478
+ if (typeof str !== "string")
23479
+ throw new Error("string expected");
23480
+ return new Uint8Array(new TextEncoder().encode(str));
23481
+ }
23482
+ function toBytes(data) {
23483
+ if (typeof data === "string")
23484
+ data = utf8ToBytes(data);
23485
+ abytes(data);
23486
+ return data;
23487
+ }
23488
+ function concatBytes(...arrays) {
23489
+ let sum = 0;
23490
+ for (let i = 0; i < arrays.length; i++) {
23491
+ const a = arrays[i];
23492
+ abytes(a);
23493
+ sum += a.length;
23494
+ }
23495
+ const res = new Uint8Array(sum);
23496
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
23497
+ const a = arrays[i];
23498
+ res.set(a, pad);
23499
+ pad += a.length;
23500
+ }
23501
+ return res;
23502
+ }
23503
+ var Hash = class {
23504
+ };
23505
+ function createHasher(hashCons) {
23506
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
23507
+ const tmp = hashCons();
23508
+ hashC.outputLen = tmp.outputLen;
23509
+ hashC.blockLen = tmp.blockLen;
23510
+ hashC.create = () => hashCons();
23511
+ return hashC;
23512
+ }
23513
+ function randomBytes(bytesLength = 32) {
23514
+ if (crypto2 && typeof crypto2.getRandomValues === "function") {
23515
+ return crypto2.getRandomValues(new Uint8Array(bytesLength));
23516
+ }
23517
+ if (crypto2 && typeof crypto2.randomBytes === "function") {
23518
+ return Uint8Array.from(crypto2.randomBytes(bytesLength));
23519
+ }
23520
+ throw new Error("crypto.getRandomValues must be defined");
23521
+ }
23522
+
23523
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_md.js
23524
+ function setBigUint64(view2, byteOffset, value, isLE) {
23525
+ if (typeof view2.setBigUint64 === "function")
23526
+ return view2.setBigUint64(byteOffset, value, isLE);
23527
+ const _32n2 = BigInt(32);
23528
+ const _u32_max = BigInt(4294967295);
23529
+ const wh = Number(value >> _32n2 & _u32_max);
23530
+ const wl = Number(value & _u32_max);
23531
+ const h = isLE ? 4 : 0;
23532
+ const l = isLE ? 0 : 4;
23533
+ view2.setUint32(byteOffset + h, wh, isLE);
23534
+ view2.setUint32(byteOffset + l, wl, isLE);
23535
+ }
23536
+ function Chi(a, b, c) {
23537
+ return a & b ^ ~a & c;
23538
+ }
23539
+ function Maj(a, b, c) {
23540
+ return a & b ^ a & c ^ b & c;
23541
+ }
23542
+ var HashMD = class extends Hash {
23543
+ constructor(blockLen, outputLen, padOffset, isLE) {
23544
+ super();
23545
+ this.finished = false;
23546
+ this.length = 0;
23547
+ this.pos = 0;
23548
+ this.destroyed = false;
23549
+ this.blockLen = blockLen;
23550
+ this.outputLen = outputLen;
23551
+ this.padOffset = padOffset;
23552
+ this.isLE = isLE;
23553
+ this.buffer = new Uint8Array(blockLen);
23554
+ this.view = createView(this.buffer);
23555
+ }
23556
+ update(data) {
23557
+ aexists(this);
23558
+ data = toBytes(data);
23559
+ abytes(data);
23560
+ const { view: view2, buffer, blockLen } = this;
23561
+ const len = data.length;
23562
+ for (let pos = 0; pos < len; ) {
23563
+ const take = Math.min(blockLen - this.pos, len - pos);
23564
+ if (take === blockLen) {
23565
+ const dataView = createView(data);
23566
+ for (; blockLen <= len - pos; pos += blockLen)
23567
+ this.process(dataView, pos);
23568
+ continue;
23569
+ }
23570
+ buffer.set(data.subarray(pos, pos + take), this.pos);
23571
+ this.pos += take;
23572
+ pos += take;
23573
+ if (this.pos === blockLen) {
23574
+ this.process(view2, 0);
23575
+ this.pos = 0;
23576
+ }
23577
+ }
23578
+ this.length += data.length;
23579
+ this.roundClean();
23580
+ return this;
23581
+ }
23582
+ digestInto(out) {
23583
+ aexists(this);
23584
+ aoutput(out, this);
23585
+ this.finished = true;
23586
+ const { buffer, view: view2, blockLen, isLE } = this;
23587
+ let { pos } = this;
23588
+ buffer[pos++] = 128;
23589
+ clean(this.buffer.subarray(pos));
23590
+ if (this.padOffset > blockLen - pos) {
23591
+ this.process(view2, 0);
23592
+ pos = 0;
23593
+ }
23594
+ for (let i = pos; i < blockLen; i++)
23595
+ buffer[i] = 0;
23596
+ setBigUint64(view2, blockLen - 8, BigInt(this.length * 8), isLE);
23597
+ this.process(view2, 0);
23598
+ const oview = createView(out);
23599
+ const len = this.outputLen;
23600
+ if (len % 4)
23601
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
23602
+ const outLen = len / 4;
23603
+ const state = this.get();
23604
+ if (outLen > state.length)
23605
+ throw new Error("_sha2: outputLen bigger than state");
23606
+ for (let i = 0; i < outLen; i++)
23607
+ oview.setUint32(4 * i, state[i], isLE);
23608
+ }
23609
+ digest() {
23610
+ const { buffer, outputLen } = this;
23611
+ this.digestInto(buffer);
23612
+ const res = buffer.slice(0, outputLen);
23613
+ this.destroy();
23614
+ return res;
23615
+ }
23616
+ _cloneInto(to) {
23617
+ to || (to = new this.constructor());
23618
+ to.set(...this.get());
23619
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
23620
+ to.destroyed = destroyed;
23621
+ to.finished = finished;
23622
+ to.length = length;
23623
+ to.pos = pos;
23624
+ if (length % blockLen)
23625
+ to.buffer.set(buffer);
23626
+ return to;
23627
+ }
23628
+ clone() {
23629
+ return this._cloneInto();
23630
+ }
23631
+ };
23632
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
23633
+ 1779033703,
23634
+ 3144134277,
23635
+ 1013904242,
23636
+ 2773480762,
23637
+ 1359893119,
23638
+ 2600822924,
23639
+ 528734635,
23640
+ 1541459225
23641
+ ]);
23642
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
23643
+ 1779033703,
23644
+ 4089235720,
23645
+ 3144134277,
23646
+ 2227873595,
23647
+ 1013904242,
23648
+ 4271175723,
23649
+ 2773480762,
23650
+ 1595750129,
23651
+ 1359893119,
23652
+ 2917565137,
23653
+ 2600822924,
23654
+ 725511199,
23655
+ 528734635,
23656
+ 4215389547,
23657
+ 1541459225,
23658
+ 327033209
23659
+ ]);
23660
+
23661
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_u64.js
23662
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
23663
+ var _32n = /* @__PURE__ */ BigInt(32);
23664
+ function fromBig(n, le = false) {
23665
+ if (le)
23666
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
23667
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
23668
+ }
23669
+ function split(lst, le = false) {
23670
+ const len = lst.length;
23671
+ let Ah = new Uint32Array(len);
23672
+ let Al = new Uint32Array(len);
23673
+ for (let i = 0; i < len; i++) {
23674
+ const { h, l } = fromBig(lst[i], le);
23675
+ [Ah[i], Al[i]] = [h, l];
23676
+ }
23677
+ return [Ah, Al];
23678
+ }
23679
+ var shrSH = (h, _l, s) => h >>> s;
23680
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
23681
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
23682
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
23683
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
23684
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
23685
+ function add(Ah, Al, Bh, Bl) {
23686
+ const l = (Al >>> 0) + (Bl >>> 0);
23687
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
23688
+ }
23689
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
23690
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
23691
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
23692
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
23693
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
23694
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
23695
+
23696
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/sha2.js
23697
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
23698
+ 1116352408,
23699
+ 1899447441,
23700
+ 3049323471,
23701
+ 3921009573,
23702
+ 961987163,
23703
+ 1508970993,
23704
+ 2453635748,
23705
+ 2870763221,
23706
+ 3624381080,
23707
+ 310598401,
23708
+ 607225278,
23709
+ 1426881987,
23710
+ 1925078388,
23711
+ 2162078206,
23712
+ 2614888103,
23713
+ 3248222580,
23714
+ 3835390401,
23715
+ 4022224774,
23716
+ 264347078,
23717
+ 604807628,
23718
+ 770255983,
23719
+ 1249150122,
23720
+ 1555081692,
23721
+ 1996064986,
23722
+ 2554220882,
23723
+ 2821834349,
23724
+ 2952996808,
23725
+ 3210313671,
23726
+ 3336571891,
23727
+ 3584528711,
23728
+ 113926993,
23729
+ 338241895,
23730
+ 666307205,
23731
+ 773529912,
23732
+ 1294757372,
23733
+ 1396182291,
23734
+ 1695183700,
23735
+ 1986661051,
23736
+ 2177026350,
23737
+ 2456956037,
23738
+ 2730485921,
23739
+ 2820302411,
23740
+ 3259730800,
23741
+ 3345764771,
23742
+ 3516065817,
23743
+ 3600352804,
23744
+ 4094571909,
23745
+ 275423344,
23746
+ 430227734,
23747
+ 506948616,
23748
+ 659060556,
23749
+ 883997877,
23750
+ 958139571,
23751
+ 1322822218,
23752
+ 1537002063,
23753
+ 1747873779,
23754
+ 1955562222,
23755
+ 2024104815,
23756
+ 2227730452,
23757
+ 2361852424,
23758
+ 2428436474,
23759
+ 2756734187,
23760
+ 3204031479,
23761
+ 3329325298
23762
+ ]);
23763
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
23764
+ var SHA256 = class extends HashMD {
23765
+ constructor(outputLen = 32) {
23766
+ super(64, outputLen, 8, false);
23767
+ this.A = SHA256_IV[0] | 0;
23768
+ this.B = SHA256_IV[1] | 0;
23769
+ this.C = SHA256_IV[2] | 0;
23770
+ this.D = SHA256_IV[3] | 0;
23771
+ this.E = SHA256_IV[4] | 0;
23772
+ this.F = SHA256_IV[5] | 0;
23773
+ this.G = SHA256_IV[6] | 0;
23774
+ this.H = SHA256_IV[7] | 0;
23775
+ }
23776
+ get() {
23777
+ const { A, B, C, D, E, F, G, H } = this;
23778
+ return [A, B, C, D, E, F, G, H];
23779
+ }
23780
+ // prettier-ignore
23781
+ set(A, B, C, D, E, F, G, H) {
23782
+ this.A = A | 0;
23783
+ this.B = B | 0;
23784
+ this.C = C | 0;
23785
+ this.D = D | 0;
23786
+ this.E = E | 0;
23787
+ this.F = F | 0;
23788
+ this.G = G | 0;
23789
+ this.H = H | 0;
23790
+ }
23791
+ process(view2, offset) {
23792
+ for (let i = 0; i < 16; i++, offset += 4)
23793
+ SHA256_W[i] = view2.getUint32(offset, false);
23794
+ for (let i = 16; i < 64; i++) {
23795
+ const W15 = SHA256_W[i - 15];
23796
+ const W2 = SHA256_W[i - 2];
23797
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
23798
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
23799
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
23800
+ }
23801
+ let { A, B, C, D, E, F, G, H } = this;
23802
+ for (let i = 0; i < 64; i++) {
23803
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
23804
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
23805
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
23806
+ const T2 = sigma0 + Maj(A, B, C) | 0;
23807
+ H = G;
23808
+ G = F;
23809
+ F = E;
23810
+ E = D + T1 | 0;
23811
+ D = C;
23812
+ C = B;
23813
+ B = A;
23814
+ A = T1 + T2 | 0;
23815
+ }
23816
+ A = A + this.A | 0;
23817
+ B = B + this.B | 0;
23818
+ C = C + this.C | 0;
23819
+ D = D + this.D | 0;
23820
+ E = E + this.E | 0;
23821
+ F = F + this.F | 0;
23822
+ G = G + this.G | 0;
23823
+ H = H + this.H | 0;
23824
+ this.set(A, B, C, D, E, F, G, H);
23825
+ }
23826
+ roundClean() {
23827
+ clean(SHA256_W);
23828
+ }
23829
+ destroy() {
23830
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
23831
+ clean(this.buffer);
23832
+ }
23833
+ };
23834
+ var K512 = /* @__PURE__ */ (() => split([
23835
+ "0x428a2f98d728ae22",
23836
+ "0x7137449123ef65cd",
23837
+ "0xb5c0fbcfec4d3b2f",
23838
+ "0xe9b5dba58189dbbc",
23839
+ "0x3956c25bf348b538",
23840
+ "0x59f111f1b605d019",
23841
+ "0x923f82a4af194f9b",
23842
+ "0xab1c5ed5da6d8118",
23843
+ "0xd807aa98a3030242",
23844
+ "0x12835b0145706fbe",
23845
+ "0x243185be4ee4b28c",
23846
+ "0x550c7dc3d5ffb4e2",
23847
+ "0x72be5d74f27b896f",
23848
+ "0x80deb1fe3b1696b1",
23849
+ "0x9bdc06a725c71235",
23850
+ "0xc19bf174cf692694",
23851
+ "0xe49b69c19ef14ad2",
23852
+ "0xefbe4786384f25e3",
23853
+ "0x0fc19dc68b8cd5b5",
23854
+ "0x240ca1cc77ac9c65",
23855
+ "0x2de92c6f592b0275",
23856
+ "0x4a7484aa6ea6e483",
23857
+ "0x5cb0a9dcbd41fbd4",
23858
+ "0x76f988da831153b5",
23859
+ "0x983e5152ee66dfab",
23860
+ "0xa831c66d2db43210",
23861
+ "0xb00327c898fb213f",
23862
+ "0xbf597fc7beef0ee4",
23863
+ "0xc6e00bf33da88fc2",
23864
+ "0xd5a79147930aa725",
23865
+ "0x06ca6351e003826f",
23866
+ "0x142929670a0e6e70",
23867
+ "0x27b70a8546d22ffc",
23868
+ "0x2e1b21385c26c926",
23869
+ "0x4d2c6dfc5ac42aed",
23870
+ "0x53380d139d95b3df",
23871
+ "0x650a73548baf63de",
23872
+ "0x766a0abb3c77b2a8",
23873
+ "0x81c2c92e47edaee6",
23874
+ "0x92722c851482353b",
23875
+ "0xa2bfe8a14cf10364",
23876
+ "0xa81a664bbc423001",
23877
+ "0xc24b8b70d0f89791",
23878
+ "0xc76c51a30654be30",
23879
+ "0xd192e819d6ef5218",
23880
+ "0xd69906245565a910",
23881
+ "0xf40e35855771202a",
23882
+ "0x106aa07032bbd1b8",
23883
+ "0x19a4c116b8d2d0c8",
23884
+ "0x1e376c085141ab53",
23885
+ "0x2748774cdf8eeb99",
23886
+ "0x34b0bcb5e19b48a8",
23887
+ "0x391c0cb3c5c95a63",
23888
+ "0x4ed8aa4ae3418acb",
23889
+ "0x5b9cca4f7763e373",
23890
+ "0x682e6ff3d6b2b8a3",
23891
+ "0x748f82ee5defb2fc",
23892
+ "0x78a5636f43172f60",
23893
+ "0x84c87814a1f0ab72",
23894
+ "0x8cc702081a6439ec",
23895
+ "0x90befffa23631e28",
23896
+ "0xa4506cebde82bde9",
23897
+ "0xbef9a3f7b2c67915",
23898
+ "0xc67178f2e372532b",
23899
+ "0xca273eceea26619c",
23900
+ "0xd186b8c721c0c207",
23901
+ "0xeada7dd6cde0eb1e",
23902
+ "0xf57d4f7fee6ed178",
23903
+ "0x06f067aa72176fba",
23904
+ "0x0a637dc5a2c898a6",
23905
+ "0x113f9804bef90dae",
23906
+ "0x1b710b35131c471b",
23907
+ "0x28db77f523047d84",
23908
+ "0x32caab7b40c72493",
23909
+ "0x3c9ebe0a15c9bebc",
23910
+ "0x431d67c49c100d4c",
23911
+ "0x4cc5d4becb3e42b6",
23912
+ "0x597f299cfc657e2a",
23913
+ "0x5fcb6fab3ad6faec",
23914
+ "0x6c44198c4a475817"
23915
+ ].map((n) => BigInt(n))))();
23916
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
23917
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
23918
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
23919
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
23920
+ var SHA512 = class extends HashMD {
23921
+ constructor(outputLen = 64) {
23922
+ super(128, outputLen, 16, false);
23923
+ this.Ah = SHA512_IV[0] | 0;
23924
+ this.Al = SHA512_IV[1] | 0;
23925
+ this.Bh = SHA512_IV[2] | 0;
23926
+ this.Bl = SHA512_IV[3] | 0;
23927
+ this.Ch = SHA512_IV[4] | 0;
23928
+ this.Cl = SHA512_IV[5] | 0;
23929
+ this.Dh = SHA512_IV[6] | 0;
23930
+ this.Dl = SHA512_IV[7] | 0;
23931
+ this.Eh = SHA512_IV[8] | 0;
23932
+ this.El = SHA512_IV[9] | 0;
23933
+ this.Fh = SHA512_IV[10] | 0;
23934
+ this.Fl = SHA512_IV[11] | 0;
23935
+ this.Gh = SHA512_IV[12] | 0;
23936
+ this.Gl = SHA512_IV[13] | 0;
23937
+ this.Hh = SHA512_IV[14] | 0;
23938
+ this.Hl = SHA512_IV[15] | 0;
23939
+ }
23940
+ // prettier-ignore
23941
+ get() {
23942
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
23943
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
23944
+ }
23945
+ // prettier-ignore
23946
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
23947
+ this.Ah = Ah | 0;
23948
+ this.Al = Al | 0;
23949
+ this.Bh = Bh | 0;
23950
+ this.Bl = Bl | 0;
23951
+ this.Ch = Ch | 0;
23952
+ this.Cl = Cl | 0;
23953
+ this.Dh = Dh | 0;
23954
+ this.Dl = Dl | 0;
23955
+ this.Eh = Eh | 0;
23956
+ this.El = El | 0;
23957
+ this.Fh = Fh | 0;
23958
+ this.Fl = Fl | 0;
23959
+ this.Gh = Gh | 0;
23960
+ this.Gl = Gl | 0;
23961
+ this.Hh = Hh | 0;
23962
+ this.Hl = Hl | 0;
23963
+ }
23964
+ process(view2, offset) {
23965
+ for (let i = 0; i < 16; i++, offset += 4) {
23966
+ SHA512_W_H[i] = view2.getUint32(offset);
23967
+ SHA512_W_L[i] = view2.getUint32(offset += 4);
23968
+ }
23969
+ for (let i = 16; i < 80; i++) {
23970
+ const W15h = SHA512_W_H[i - 15] | 0;
23971
+ const W15l = SHA512_W_L[i - 15] | 0;
23972
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
23973
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
23974
+ const W2h = SHA512_W_H[i - 2] | 0;
23975
+ const W2l = SHA512_W_L[i - 2] | 0;
23976
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
23977
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
23978
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
23979
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
23980
+ SHA512_W_H[i] = SUMh | 0;
23981
+ SHA512_W_L[i] = SUMl | 0;
23982
+ }
23983
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
23984
+ for (let i = 0; i < 80; i++) {
23985
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
23986
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
23987
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
23988
+ const CHIl = El & Fl ^ ~El & Gl;
23989
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
23990
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
23991
+ const T1l = T1ll | 0;
23992
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
23993
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
23994
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
23995
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
23996
+ Hh = Gh | 0;
23997
+ Hl = Gl | 0;
23998
+ Gh = Fh | 0;
23999
+ Gl = Fl | 0;
24000
+ Fh = Eh | 0;
24001
+ Fl = El | 0;
24002
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
24003
+ Dh = Ch | 0;
24004
+ Dl = Cl | 0;
24005
+ Ch = Bh | 0;
24006
+ Cl = Bl | 0;
24007
+ Bh = Ah | 0;
24008
+ Bl = Al | 0;
24009
+ const All = add3L(T1l, sigma0l, MAJl);
24010
+ Ah = add3H(All, T1h, sigma0h, MAJh);
24011
+ Al = All | 0;
24012
+ }
24013
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
24014
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
24015
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
24016
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
24017
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
24018
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
24019
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
24020
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
24021
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
24022
+ }
24023
+ roundClean() {
24024
+ clean(SHA512_W_H, SHA512_W_L);
24025
+ }
24026
+ destroy() {
24027
+ clean(this.buffer);
24028
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
24029
+ }
24030
+ };
24031
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
24032
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
24033
+
24034
+ // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/sha256.js
24035
+ var sha2562 = sha256;
24036
+
24037
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
24038
+ var BCPV2_HEADER_LENGTH = 68;
24039
+ var BCPV2_SIGNATURE_LENGTH = 64;
24040
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
24041
+ var BCPV2_MAX_RECORD_LENGTH = 1316;
24042
+ var BCPV2_MAX_DIGESTS = 37;
24043
+ var BCPV2_HASH_ALG_SHA256 = 1;
24044
+ var text = new TextEncoder();
24045
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
24046
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
24047
+ function equalBytes(left, right) {
24048
+ if (left.byteLength !== right.byteLength)
24049
+ return false;
24050
+ let different = 0;
24051
+ for (let index = 0; index < left.byteLength; index++)
24052
+ different |= left[index] ^ right[index];
24053
+ return different === 0;
24054
+ }
24055
+ function u16(value) {
24056
+ const result = new Uint8Array(2);
24057
+ new DataView(result.buffer).setUint16(0, value);
24058
+ return result;
24059
+ }
24060
+ function u322(value) {
24061
+ const result = new Uint8Array(4);
24062
+ new DataView(result.buffer).setUint32(0, value);
24063
+ return result;
24064
+ }
24065
+ function validU32(value) {
24066
+ return Number.isInteger(value) && value >= 0 && value <= 4294967295;
24067
+ }
24068
+ function validPort(value) {
24069
+ return Number.isInteger(value) && value >= 0 && value <= 65535;
24070
+ }
24071
+ function parseIpv4(address) {
24072
+ const fields = address.split(".");
24073
+ if (fields.length !== 4 || fields.some((field) => !/^\d+$/.test(field))) {
24074
+ throw new Error(`invalid IPv4 address ${address}`);
24075
+ }
24076
+ const values = fields.map(Number);
24077
+ if (values.some((value, index) => value > 255 || String(value) !== fields[index])) {
24078
+ throw new Error(`invalid IPv4 address ${address}`);
24079
+ }
24080
+ return Uint8Array.from(values);
24081
+ }
24082
+ function parseIpv6(address) {
24083
+ const compressed = address.includes("::");
24084
+ if ((address.match(/::/g) ?? []).length > 1)
24085
+ throw new Error(`invalid IPv6 address ${address}`);
24086
+ const [leftText, rightText = ""] = address.split("::");
24087
+ const left = leftText ? leftText.split(":") : [];
24088
+ const right = rightText ? rightText.split(":") : [];
24089
+ if (left.some((group) => group.includes(".")) || right.some((group) => group.includes("."))) {
24090
+ throw new Error(`invalid IPv6 address ${address}`);
24091
+ }
24092
+ const missing = 8 - left.length - right.length;
24093
+ if (missing < 0 || !compressed && missing !== 0 || compressed && missing < 1) {
24094
+ throw new Error(`invalid IPv6 address ${address}`);
24095
+ }
24096
+ const groups = [...left, ...Array.from({ length: missing }, () => "0"), ...right];
24097
+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/i.test(group))) {
24098
+ throw new Error(`invalid IPv6 address ${address}`);
24099
+ }
24100
+ const result = new Uint8Array(16);
24101
+ const view2 = new DataView(result.buffer);
24102
+ groups.forEach((group, index) => view2.setUint16(index * 2, Number.parseInt(group, 16)));
24103
+ return result;
24104
+ }
24105
+ function parseBcProvenanceV2Address(address) {
24106
+ if (address.includes(":"))
24107
+ return parseIpv6(address);
24108
+ return parseIpv4(address);
24109
+ }
24110
+ function endpointBytes(endpoint) {
24111
+ if (!validPort(endpoint.port) || !validPort(endpoint.manifestPort) || !validU32(endpoint.streamId)) {
24112
+ throw new Error("invalid BCPV2 endpoint");
24113
+ }
24114
+ const source = parseBcProvenanceV2Address(endpoint.sourceAddress);
24115
+ const group = parseBcProvenanceV2Address(endpoint.groupAddress);
24116
+ if (source.byteLength !== group.byteLength)
24117
+ throw new Error("endpoint address families differ");
24118
+ return { source, group };
24119
+ }
24120
+ function readU32(view2, offset) {
24121
+ return view2.getUint32(offset);
24122
+ }
24123
+ function readU642(view2, offset) {
24124
+ return view2.getBigUint64(offset);
24125
+ }
24126
+ function decodeBcProvenanceV2Record(input) {
24127
+ const bytes = Uint8Array.from(input);
24128
+ if (bytes.byteLength < BCPV2_MIN_RECORD_LENGTH || bytes.byteLength > BCPV2_MAX_RECORD_LENGTH || (bytes.byteLength - 132) % 32 !== 0) {
24129
+ throw new Error("invalid BCPV2 record length");
24130
+ }
24131
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
24132
+ if (!equalBytes(bytes.subarray(0, 4), MAGIC))
24133
+ throw new Error("invalid BCPV2 record magic");
24134
+ const count = view2.getUint16(28);
24135
+ if (count < 1 || count > BCPV2_MAX_DIGESTS || bytes.byteLength !== 132 + count * 32) {
24136
+ throw new Error("invalid BCPV2 record count");
24137
+ }
24138
+ const body = bytes.slice(0, bytes.byteLength - BCPV2_SIGNATURE_LENGTH);
24139
+ const digests = [];
24140
+ for (let index = 0; index < count; index++) {
24141
+ digests.push(bytes.slice(BCPV2_HEADER_LENGTH + index * 32, BCPV2_HEADER_LENGTH + (index + 1) * 32));
24142
+ }
24143
+ return {
24144
+ kid: readU32(view2, 4),
24145
+ epoch: readU32(view2, 8),
24146
+ mseq: readU642(view2, 12),
24147
+ firstSeq: readU642(view2, 20),
24148
+ count,
24149
+ hashAlg: bytes[30],
24150
+ flags: bytes[31],
24151
+ sent: readU32(view2, 32),
24152
+ ctx: bytes.slice(36, 68),
24153
+ digests,
24154
+ signature: bytes.slice(bytes.byteLength - BCPV2_SIGNATURE_LENGTH),
24155
+ body,
24156
+ raw: bytes
24157
+ };
24158
+ }
24159
+ function bcProvenanceV2SignedMessage(record, endpoint) {
24160
+ const { source, group } = endpointBytes(endpoint);
24161
+ const prefix = new Uint8Array(SIGNING_DOMAIN.byteLength + 4 + source.byteLength + group.byteLength + 2);
24162
+ let offset = 0;
24163
+ prefix.set(SIGNING_DOMAIN, offset);
24164
+ offset += SIGNING_DOMAIN.byteLength;
24165
+ prefix.set(u322(endpoint.streamId), offset);
24166
+ offset += 4;
24167
+ prefix.set(source, offset);
24168
+ offset += source.byteLength;
24169
+ prefix.set(group, offset);
24170
+ offset += group.byteLength;
24171
+ prefix.set(u16(endpoint.manifestPort), offset);
24172
+ const message = new Uint8Array(prefix.byteLength + record.body.byteLength);
24173
+ message.set(prefix);
24174
+ message.set(record.body, prefix.byteLength);
24175
+ return message;
24176
+ }
24177
+ function bcProvenanceV2DatagramDigest(endpoint, payload) {
24178
+ if (payload.byteLength > 65535)
24179
+ throw new Error("datagram payload exceeds u16 length");
24180
+ const { source, group } = endpointBytes(endpoint);
24181
+ const pseudoheader = new Uint8Array(source.byteLength + group.byteLength + 2 + 2 + 2 + 2 + 4);
24182
+ let offset = 0;
24183
+ pseudoheader.set(source, offset);
24184
+ offset += source.byteLength;
24185
+ pseudoheader.set(group, offset);
24186
+ offset += group.byteLength;
24187
+ pseudoheader.set([0, 17], offset);
24188
+ offset += 2;
24189
+ pseudoheader.set(u16(payload.byteLength), offset);
24190
+ offset += 2;
24191
+ pseudoheader.set(u16(endpoint.port), offset);
24192
+ offset += 2;
24193
+ pseudoheader.set(u16(endpoint.port), offset);
24194
+ offset += 2;
24195
+ pseudoheader.set(u322(endpoint.streamId), offset);
24196
+ const input = new Uint8Array(pseudoheader.byteLength + payload.byteLength);
24197
+ input.set(pseudoheader);
24198
+ input.set(payload, pseudoheader.byteLength);
24199
+ return sha2562(input);
24200
+ }
24201
+
24202
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/utils.js
24203
+ var _0n = /* @__PURE__ */ BigInt(0);
24204
+ var _1n = /* @__PURE__ */ BigInt(1);
24205
+ function _abool2(value, title = "") {
24206
+ if (typeof value !== "boolean") {
24207
+ const prefix = title && `"${title}"`;
24208
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
24209
+ }
24210
+ return value;
24211
+ }
24212
+ function _abytes2(value, length, title = "") {
24213
+ const bytes = isBytes(value);
24214
+ const len = value?.length;
24215
+ const needsLen = length !== void 0;
24216
+ if (!bytes || needsLen && len !== length) {
24217
+ const prefix = title && `"${title}" `;
24218
+ const ofLen = needsLen ? ` of length ${length}` : "";
24219
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
24220
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
24221
+ }
24222
+ return value;
24223
+ }
24224
+ function hexToNumber(hex3) {
24225
+ if (typeof hex3 !== "string")
24226
+ throw new Error("hex string expected, got " + typeof hex3);
24227
+ return hex3 === "" ? _0n : BigInt("0x" + hex3);
24228
+ }
24229
+ function bytesToNumberBE(bytes) {
24230
+ return hexToNumber(bytesToHex(bytes));
24231
+ }
24232
+ function bytesToNumberLE(bytes) {
24233
+ abytes(bytes);
24234
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
24235
+ }
24236
+ function numberToBytesBE(n, len) {
24237
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
24238
+ }
24239
+ function numberToBytesLE(n, len) {
24240
+ return numberToBytesBE(n, len).reverse();
24241
+ }
24242
+ function ensureBytes(title, hex3, expectedLength) {
24243
+ let res;
24244
+ if (typeof hex3 === "string") {
24245
+ try {
24246
+ res = hexToBytes(hex3);
24247
+ } catch (e) {
24248
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
24249
+ }
24250
+ } else if (isBytes(hex3)) {
24251
+ res = Uint8Array.from(hex3);
24252
+ } else {
24253
+ throw new Error(title + " must be hex string or Uint8Array");
24254
+ }
24255
+ const len = res.length;
24256
+ if (typeof expectedLength === "number" && len !== expectedLength)
24257
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
24258
+ return res;
24259
+ }
24260
+ function equalBytes2(a, b) {
24261
+ if (a.length !== b.length)
24262
+ return false;
24263
+ let diff = 0;
24264
+ for (let i = 0; i < a.length; i++)
24265
+ diff |= a[i] ^ b[i];
24266
+ return diff === 0;
24267
+ }
24268
+ function copyBytes(bytes) {
24269
+ return Uint8Array.from(bytes);
24270
+ }
24271
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
24272
+ function inRange(n, min, max) {
24273
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
24274
+ }
24275
+ function aInRange(title, n, min, max) {
24276
+ if (!inRange(n, min, max))
24277
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
24278
+ }
24279
+ function bitLen(n) {
24280
+ let len;
24281
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
24282
+ ;
24283
+ return len;
24284
+ }
24285
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
24286
+ function _validateObject(object2, fields, optFields = {}) {
24287
+ if (!object2 || typeof object2 !== "object")
24288
+ throw new Error("expected valid options object");
24289
+ function checkField2(fieldName, expectedType, isOpt) {
24290
+ const val = object2[fieldName];
24291
+ if (isOpt && val === void 0)
24292
+ return;
24293
+ const current = typeof val;
24294
+ if (current !== expectedType || val === null)
24295
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
24296
+ }
24297
+ Object.entries(fields).forEach(([k, v]) => checkField2(k, v, false));
24298
+ Object.entries(optFields).forEach(([k, v]) => checkField2(k, v, true));
24299
+ }
24300
+ var notImplemented = () => {
24301
+ throw new Error("not implemented");
24302
+ };
24303
+ function memoized(fn) {
24304
+ const map = /* @__PURE__ */ new WeakMap();
24305
+ return (arg, ...args) => {
24306
+ const val = map.get(arg);
24307
+ if (val !== void 0)
24308
+ return val;
24309
+ const computed = fn(arg, ...args);
24310
+ map.set(arg, computed);
24311
+ return computed;
24312
+ };
24313
+ }
24314
+
24315
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/modular.js
24316
+ var _0n2 = BigInt(0);
24317
+ var _1n2 = BigInt(1);
24318
+ var _2n = /* @__PURE__ */ BigInt(2);
24319
+ var _3n = /* @__PURE__ */ BigInt(3);
24320
+ var _4n = /* @__PURE__ */ BigInt(4);
24321
+ var _5n = /* @__PURE__ */ BigInt(5);
24322
+ var _7n = /* @__PURE__ */ BigInt(7);
24323
+ var _8n = /* @__PURE__ */ BigInt(8);
24324
+ var _9n = /* @__PURE__ */ BigInt(9);
24325
+ var _16n = /* @__PURE__ */ BigInt(16);
24326
+ function mod(a, b) {
24327
+ const result = a % b;
24328
+ return result >= _0n2 ? result : b + result;
24329
+ }
24330
+ function pow2(x, power, modulo) {
24331
+ let res = x;
24332
+ while (power-- > _0n2) {
24333
+ res *= res;
24334
+ res %= modulo;
24335
+ }
24336
+ return res;
24337
+ }
24338
+ function invert(number, modulo) {
24339
+ if (number === _0n2)
24340
+ throw new Error("invert: expected non-zero number");
24341
+ if (modulo <= _0n2)
24342
+ throw new Error("invert: expected positive modulus, got " + modulo);
24343
+ let a = mod(number, modulo);
24344
+ let b = modulo;
24345
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
24346
+ while (a !== _0n2) {
24347
+ const q = b / a;
24348
+ const r = b % a;
24349
+ const m = x - u * q;
24350
+ const n = y - v * q;
24351
+ b = a, a = r, x = u, y = v, u = m, v = n;
24352
+ }
24353
+ const gcd = b;
24354
+ if (gcd !== _1n2)
24355
+ throw new Error("invert: does not exist");
24356
+ return mod(x, modulo);
24357
+ }
24358
+ function assertIsSquare(Fp2, root, n) {
24359
+ if (!Fp2.eql(Fp2.sqr(root), n))
24360
+ throw new Error("Cannot find square root");
24361
+ }
24362
+ function sqrt3mod4(Fp2, n) {
24363
+ const p1div4 = (Fp2.ORDER + _1n2) / _4n;
24364
+ const root = Fp2.pow(n, p1div4);
24365
+ assertIsSquare(Fp2, root, n);
24366
+ return root;
24367
+ }
24368
+ function sqrt5mod8(Fp2, n) {
24369
+ const p5div8 = (Fp2.ORDER - _5n) / _8n;
24370
+ const n2 = Fp2.mul(n, _2n);
24371
+ const v = Fp2.pow(n2, p5div8);
24372
+ const nv = Fp2.mul(n, v);
24373
+ const i = Fp2.mul(Fp2.mul(nv, _2n), v);
24374
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
24375
+ assertIsSquare(Fp2, root, n);
24376
+ return root;
24377
+ }
24378
+ function sqrt9mod16(P) {
24379
+ const Fp_ = Field(P);
24380
+ const tn = tonelliShanks(P);
24381
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
24382
+ const c2 = tn(Fp_, c1);
24383
+ const c3 = tn(Fp_, Fp_.neg(c1));
24384
+ const c4 = (P + _7n) / _16n;
24385
+ return (Fp2, n) => {
24386
+ let tv1 = Fp2.pow(n, c4);
24387
+ let tv2 = Fp2.mul(tv1, c1);
24388
+ const tv3 = Fp2.mul(tv1, c2);
24389
+ const tv4 = Fp2.mul(tv1, c3);
24390
+ const e1 = Fp2.eql(Fp2.sqr(tv2), n);
24391
+ const e2 = Fp2.eql(Fp2.sqr(tv3), n);
24392
+ tv1 = Fp2.cmov(tv1, tv2, e1);
24393
+ tv2 = Fp2.cmov(tv4, tv3, e2);
24394
+ const e3 = Fp2.eql(Fp2.sqr(tv2), n);
24395
+ const root = Fp2.cmov(tv1, tv2, e3);
24396
+ assertIsSquare(Fp2, root, n);
24397
+ return root;
24398
+ };
24399
+ }
24400
+ function tonelliShanks(P) {
24401
+ if (P < _3n)
24402
+ throw new Error("sqrt is not defined for small field");
24403
+ let Q = P - _1n2;
24404
+ let S = 0;
24405
+ while (Q % _2n === _0n2) {
24406
+ Q /= _2n;
24407
+ S++;
24408
+ }
24409
+ let Z = _2n;
24410
+ const _Fp = Field(P);
24411
+ while (FpLegendre(_Fp, Z) === 1) {
24412
+ if (Z++ > 1e3)
24413
+ throw new Error("Cannot find square root: probably non-prime P");
24414
+ }
24415
+ if (S === 1)
24416
+ return sqrt3mod4;
24417
+ let cc = _Fp.pow(Z, Q);
24418
+ const Q1div2 = (Q + _1n2) / _2n;
24419
+ return function tonelliSlow(Fp2, n) {
24420
+ if (Fp2.is0(n))
24421
+ return n;
24422
+ if (FpLegendre(Fp2, n) !== 1)
24423
+ throw new Error("Cannot find square root");
24424
+ let M = S;
24425
+ let c = Fp2.mul(Fp2.ONE, cc);
24426
+ let t = Fp2.pow(n, Q);
24427
+ let R = Fp2.pow(n, Q1div2);
24428
+ while (!Fp2.eql(t, Fp2.ONE)) {
24429
+ if (Fp2.is0(t))
24430
+ return Fp2.ZERO;
24431
+ let i = 1;
24432
+ let t_tmp = Fp2.sqr(t);
24433
+ while (!Fp2.eql(t_tmp, Fp2.ONE)) {
24434
+ i++;
24435
+ t_tmp = Fp2.sqr(t_tmp);
24436
+ if (i === M)
24437
+ throw new Error("Cannot find square root");
24438
+ }
24439
+ const exponent = _1n2 << BigInt(M - i - 1);
24440
+ const b = Fp2.pow(c, exponent);
24441
+ M = i;
24442
+ c = Fp2.sqr(b);
24443
+ t = Fp2.mul(t, c);
24444
+ R = Fp2.mul(R, b);
24445
+ }
24446
+ return R;
24447
+ };
24448
+ }
24449
+ function FpSqrt(P) {
24450
+ if (P % _4n === _3n)
24451
+ return sqrt3mod4;
24452
+ if (P % _8n === _5n)
24453
+ return sqrt5mod8;
24454
+ if (P % _16n === _9n)
24455
+ return sqrt9mod16(P);
24456
+ return tonelliShanks(P);
24457
+ }
24458
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
24459
+ var FIELD_FIELDS = [
24460
+ "create",
24461
+ "isValid",
24462
+ "is0",
24463
+ "neg",
24464
+ "inv",
24465
+ "sqrt",
24466
+ "sqr",
24467
+ "eql",
24468
+ "add",
24469
+ "sub",
24470
+ "mul",
24471
+ "pow",
24472
+ "div",
24473
+ "addN",
24474
+ "subN",
24475
+ "mulN",
24476
+ "sqrN"
24477
+ ];
24478
+ function validateField(field) {
24479
+ const initial = {
24480
+ ORDER: "bigint",
24481
+ MASK: "bigint",
24482
+ BYTES: "number",
24483
+ BITS: "number"
24484
+ };
24485
+ const opts = FIELD_FIELDS.reduce((map, val) => {
24486
+ map[val] = "function";
24487
+ return map;
24488
+ }, initial);
24489
+ _validateObject(field, opts);
24490
+ return field;
24491
+ }
24492
+ function FpPow(Fp2, num, power) {
24493
+ if (power < _0n2)
24494
+ throw new Error("invalid exponent, negatives unsupported");
24495
+ if (power === _0n2)
24496
+ return Fp2.ONE;
24497
+ if (power === _1n2)
24498
+ return num;
24499
+ let p = Fp2.ONE;
24500
+ let d = num;
24501
+ while (power > _0n2) {
24502
+ if (power & _1n2)
24503
+ p = Fp2.mul(p, d);
24504
+ d = Fp2.sqr(d);
24505
+ power >>= _1n2;
24506
+ }
24507
+ return p;
24508
+ }
24509
+ function FpInvertBatch(Fp2, nums, passZero = false) {
24510
+ const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0);
24511
+ const multipliedAcc = nums.reduce((acc, num, i) => {
24512
+ if (Fp2.is0(num))
24513
+ return acc;
24514
+ inverted[i] = acc;
24515
+ return Fp2.mul(acc, num);
24516
+ }, Fp2.ONE);
24517
+ const invertedAcc = Fp2.inv(multipliedAcc);
24518
+ nums.reduceRight((acc, num, i) => {
24519
+ if (Fp2.is0(num))
24520
+ return acc;
24521
+ inverted[i] = Fp2.mul(acc, inverted[i]);
24522
+ return Fp2.mul(acc, num);
24523
+ }, invertedAcc);
24524
+ return inverted;
24525
+ }
24526
+ function FpLegendre(Fp2, n) {
24527
+ const p1mod2 = (Fp2.ORDER - _1n2) / _2n;
24528
+ const powered = Fp2.pow(n, p1mod2);
24529
+ const yes = Fp2.eql(powered, Fp2.ONE);
24530
+ const zero = Fp2.eql(powered, Fp2.ZERO);
24531
+ const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE));
24532
+ if (!yes && !zero && !no)
24533
+ throw new Error("invalid Legendre symbol result");
24534
+ return yes ? 1 : zero ? 0 : -1;
24535
+ }
24536
+ function nLength(n, nBitLength) {
24537
+ if (nBitLength !== void 0)
24538
+ anumber(nBitLength);
24539
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
24540
+ const nByteLength = Math.ceil(_nBitLength / 8);
24541
+ return { nBitLength: _nBitLength, nByteLength };
24542
+ }
24543
+ function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
24544
+ if (ORDER <= _0n2)
24545
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
24546
+ let _nbitLength = void 0;
24547
+ let _sqrt = void 0;
24548
+ let modFromBytes = false;
24549
+ let allowedLengths = void 0;
24550
+ if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
24551
+ if (opts.sqrt || isLE)
24552
+ throw new Error("cannot specify opts in two arguments");
24553
+ const _opts = bitLenOrOpts;
24554
+ if (_opts.BITS)
24555
+ _nbitLength = _opts.BITS;
24556
+ if (_opts.sqrt)
24557
+ _sqrt = _opts.sqrt;
24558
+ if (typeof _opts.isLE === "boolean")
24559
+ isLE = _opts.isLE;
24560
+ if (typeof _opts.modFromBytes === "boolean")
24561
+ modFromBytes = _opts.modFromBytes;
24562
+ allowedLengths = _opts.allowedLengths;
24563
+ } else {
24564
+ if (typeof bitLenOrOpts === "number")
24565
+ _nbitLength = bitLenOrOpts;
24566
+ if (opts.sqrt)
24567
+ _sqrt = opts.sqrt;
24568
+ }
24569
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
24570
+ if (BYTES > 2048)
24571
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
24572
+ let sqrtP;
24573
+ const f = Object.freeze({
24574
+ ORDER,
24575
+ isLE,
24576
+ BITS,
24577
+ BYTES,
24578
+ MASK: bitMask(BITS),
24579
+ ZERO: _0n2,
24580
+ ONE: _1n2,
24581
+ allowedLengths,
24582
+ create: (num) => mod(num, ORDER),
24583
+ isValid: (num) => {
24584
+ if (typeof num !== "bigint")
24585
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
24586
+ return _0n2 <= num && num < ORDER;
24587
+ },
24588
+ is0: (num) => num === _0n2,
24589
+ // is valid and invertible
24590
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
24591
+ isOdd: (num) => (num & _1n2) === _1n2,
24592
+ neg: (num) => mod(-num, ORDER),
24593
+ eql: (lhs, rhs) => lhs === rhs,
24594
+ sqr: (num) => mod(num * num, ORDER),
24595
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
24596
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
24597
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
24598
+ pow: (num, power) => FpPow(f, num, power),
24599
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
24600
+ // Same as above, but doesn't normalize
24601
+ sqrN: (num) => num * num,
24602
+ addN: (lhs, rhs) => lhs + rhs,
24603
+ subN: (lhs, rhs) => lhs - rhs,
24604
+ mulN: (lhs, rhs) => lhs * rhs,
24605
+ inv: (num) => invert(num, ORDER),
24606
+ sqrt: _sqrt || ((n) => {
24607
+ if (!sqrtP)
24608
+ sqrtP = FpSqrt(ORDER);
24609
+ return sqrtP(f, n);
24610
+ }),
24611
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
24612
+ fromBytes: (bytes, skipValidation = true) => {
24613
+ if (allowedLengths) {
24614
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
24615
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
24616
+ }
24617
+ const padded = new Uint8Array(BYTES);
24618
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
24619
+ bytes = padded;
24620
+ }
24621
+ if (bytes.length !== BYTES)
24622
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
24623
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
24624
+ if (modFromBytes)
24625
+ scalar = mod(scalar, ORDER);
24626
+ if (!skipValidation) {
24627
+ if (!f.isValid(scalar))
24628
+ throw new Error("invalid field element: outside of range 0..ORDER");
24629
+ }
24630
+ return scalar;
24631
+ },
24632
+ // TODO: we don't need it here, move out to separate fn
24633
+ invertBatch: (lst) => FpInvertBatch(f, lst),
24634
+ // We can't move this out because Fp6, Fp12 implement it
24635
+ // and it's unclear what to return in there.
24636
+ cmov: (a, b, c) => c ? b : a
24637
+ });
24638
+ return Object.freeze(f);
24639
+ }
24640
+
24641
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/curve.js
24642
+ var _0n3 = BigInt(0);
24643
+ var _1n3 = BigInt(1);
24644
+ function negateCt(condition, item) {
24645
+ const neg = item.negate();
24646
+ return condition ? neg : item;
24647
+ }
24648
+ function normalizeZ(c, points) {
24649
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
24650
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
24651
+ }
24652
+ function validateW(W, bits) {
24653
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
24654
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
24655
+ }
24656
+ function calcWOpts(W, scalarBits) {
24657
+ validateW(W, scalarBits);
24658
+ const windows = Math.ceil(scalarBits / W) + 1;
24659
+ const windowSize = 2 ** (W - 1);
24660
+ const maxNumber = 2 ** W;
24661
+ const mask = bitMask(W);
24662
+ const shiftBy = BigInt(W);
24663
+ return { windows, windowSize, mask, maxNumber, shiftBy };
24664
+ }
24665
+ function calcOffsets(n, window2, wOpts) {
24666
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
24667
+ let wbits = Number(n & mask);
24668
+ let nextN = n >> shiftBy;
24669
+ if (wbits > windowSize) {
24670
+ wbits -= maxNumber;
24671
+ nextN += _1n3;
24672
+ }
24673
+ const offsetStart = window2 * windowSize;
24674
+ const offset = offsetStart + Math.abs(wbits) - 1;
24675
+ const isZero = wbits === 0;
24676
+ const isNeg = wbits < 0;
24677
+ const isNegF = window2 % 2 !== 0;
24678
+ const offsetF = offsetStart;
24679
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
24680
+ }
24681
+ function validateMSMPoints(points, c) {
24682
+ if (!Array.isArray(points))
24683
+ throw new Error("array expected");
24684
+ points.forEach((p, i) => {
24685
+ if (!(p instanceof c))
24686
+ throw new Error("invalid point at index " + i);
24687
+ });
24688
+ }
24689
+ function validateMSMScalars(scalars, field) {
24690
+ if (!Array.isArray(scalars))
24691
+ throw new Error("array of scalars expected");
24692
+ scalars.forEach((s, i) => {
24693
+ if (!field.isValid(s))
24694
+ throw new Error("invalid scalar at index " + i);
24695
+ });
24696
+ }
24697
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
24698
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
24699
+ function getW(P) {
24700
+ return pointWindowSizes.get(P) || 1;
24701
+ }
24702
+ function assert0(n) {
24703
+ if (n !== _0n3)
24704
+ throw new Error("invalid wNAF");
24705
+ }
24706
+ var wNAF = class {
24707
+ // Parametrized with a given Point class (not individual point)
24708
+ constructor(Point, bits) {
24709
+ this.BASE = Point.BASE;
24710
+ this.ZERO = Point.ZERO;
24711
+ this.Fn = Point.Fn;
24712
+ this.bits = bits;
24713
+ }
24714
+ // non-const time multiplication ladder
24715
+ _unsafeLadder(elm, n, p = this.ZERO) {
24716
+ let d = elm;
24717
+ while (n > _0n3) {
24718
+ if (n & _1n3)
24719
+ p = p.add(d);
24720
+ d = d.double();
24721
+ n >>= _1n3;
24722
+ }
24723
+ return p;
24724
+ }
24725
+ /**
24726
+ * Creates a wNAF precomputation window. Used for caching.
24727
+ * Default window size is set by `utils.precompute()` and is equal to 8.
24728
+ * Number of precomputed points depends on the curve size:
24729
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
24730
+ * - 𝑊 is the window size
24731
+ * - 𝑛 is the bitlength of the curve order.
24732
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
24733
+ * @param point Point instance
24734
+ * @param W window size
24735
+ * @returns precomputed point tables flattened to a single array
24736
+ */
24737
+ precomputeWindow(point, W) {
24738
+ const { windows, windowSize } = calcWOpts(W, this.bits);
24739
+ const points = [];
24740
+ let p = point;
24741
+ let base = p;
24742
+ for (let window2 = 0; window2 < windows; window2++) {
24743
+ base = p;
24744
+ points.push(base);
24745
+ for (let i = 1; i < windowSize; i++) {
24746
+ base = base.add(p);
24747
+ points.push(base);
24748
+ }
24749
+ p = base.double();
24750
+ }
24751
+ return points;
24752
+ }
24753
+ /**
24754
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
24755
+ * More compact implementation:
24756
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
24757
+ * @returns real and fake (for const-time) points
24758
+ */
24759
+ wNAF(W, precomputes, n) {
24760
+ if (!this.Fn.isValid(n))
24761
+ throw new Error("invalid scalar");
24762
+ let p = this.ZERO;
24763
+ let f = this.BASE;
24764
+ const wo = calcWOpts(W, this.bits);
24765
+ for (let window2 = 0; window2 < wo.windows; window2++) {
24766
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
24767
+ n = nextN;
24768
+ if (isZero) {
24769
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
24770
+ } else {
24771
+ p = p.add(negateCt(isNeg, precomputes[offset]));
24772
+ }
24773
+ }
24774
+ assert0(n);
24775
+ return { p, f };
24776
+ }
24777
+ /**
24778
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
24779
+ * @param acc accumulator point to add result of multiplication
24780
+ * @returns point
24781
+ */
24782
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
24783
+ const wo = calcWOpts(W, this.bits);
24784
+ for (let window2 = 0; window2 < wo.windows; window2++) {
24785
+ if (n === _0n3)
24786
+ break;
24787
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo);
24788
+ n = nextN;
24789
+ if (isZero) {
24790
+ continue;
24791
+ } else {
24792
+ const item = precomputes[offset];
24793
+ acc = acc.add(isNeg ? item.negate() : item);
24794
+ }
24795
+ }
24796
+ assert0(n);
24797
+ return acc;
24798
+ }
24799
+ getPrecomputes(W, point, transform) {
24800
+ let comp = pointPrecomputes.get(point);
24801
+ if (!comp) {
24802
+ comp = this.precomputeWindow(point, W);
24803
+ if (W !== 1) {
24804
+ if (typeof transform === "function")
24805
+ comp = transform(comp);
24806
+ pointPrecomputes.set(point, comp);
24807
+ }
24808
+ }
24809
+ return comp;
24810
+ }
24811
+ cached(point, scalar, transform) {
24812
+ const W = getW(point);
24813
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
24814
+ }
24815
+ unsafe(point, scalar, transform, prev) {
24816
+ const W = getW(point);
24817
+ if (W === 1)
24818
+ return this._unsafeLadder(point, scalar, prev);
24819
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
24820
+ }
24821
+ // We calculate precomputes for elliptic curve point multiplication
24822
+ // using windowed method. This specifies window size and
24823
+ // stores precomputed values. Usually only base point would be precomputed.
24824
+ createCache(P, W) {
24825
+ validateW(W, this.bits);
24826
+ pointWindowSizes.set(P, W);
24827
+ pointPrecomputes.delete(P);
24828
+ }
24829
+ hasCache(elm) {
24830
+ return getW(elm) !== 1;
24831
+ }
24832
+ };
24833
+ function pippenger(c, fieldN, points, scalars) {
24834
+ validateMSMPoints(points, c);
24835
+ validateMSMScalars(scalars, fieldN);
24836
+ const plength = points.length;
24837
+ const slength = scalars.length;
24838
+ if (plength !== slength)
24839
+ throw new Error("arrays of points and scalars must have equal length");
24840
+ const zero = c.ZERO;
24841
+ const wbits = bitLen(BigInt(plength));
24842
+ let windowSize = 1;
24843
+ if (wbits > 12)
24844
+ windowSize = wbits - 3;
24845
+ else if (wbits > 4)
24846
+ windowSize = wbits - 2;
24847
+ else if (wbits > 0)
24848
+ windowSize = 2;
24849
+ const MASK = bitMask(windowSize);
24850
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
24851
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
24852
+ let sum = zero;
24853
+ for (let i = lastBits; i >= 0; i -= windowSize) {
24854
+ buckets.fill(zero);
24855
+ for (let j = 0; j < slength; j++) {
24856
+ const scalar = scalars[j];
24857
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
24858
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
24859
+ }
24860
+ let resI = zero;
24861
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
24862
+ sumI = sumI.add(buckets[j]);
24863
+ resI = resI.add(sumI);
24864
+ }
24865
+ sum = sum.add(resI);
24866
+ if (i !== 0)
24867
+ for (let j = 0; j < windowSize; j++)
24868
+ sum = sum.double();
24869
+ }
24870
+ return sum;
24871
+ }
24872
+ function createField(order, field, isLE) {
24873
+ if (field) {
24874
+ if (field.ORDER !== order)
24875
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
24876
+ validateField(field);
24877
+ return field;
24878
+ } else {
24879
+ return Field(order, { isLE });
24880
+ }
24881
+ }
24882
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
24883
+ if (FpFnLE === void 0)
24884
+ FpFnLE = type === "edwards";
24885
+ if (!CURVE || typeof CURVE !== "object")
24886
+ throw new Error(`expected valid ${type} CURVE object`);
24887
+ for (const p of ["p", "n", "h"]) {
24888
+ const val = CURVE[p];
24889
+ if (!(typeof val === "bigint" && val > _0n3))
24890
+ throw new Error(`CURVE.${p} must be positive bigint`);
24891
+ }
24892
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
24893
+ const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
24894
+ const _b = type === "weierstrass" ? "b" : "d";
24895
+ const params = ["Gx", "Gy", "a", _b];
24896
+ for (const p of params) {
24897
+ if (!Fp2.isValid(CURVE[p]))
24898
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
24899
+ }
24900
+ CURVE = Object.freeze(Object.assign({}, CURVE));
24901
+ return { CURVE, Fp: Fp2, Fn: Fn2 };
24902
+ }
24903
+
24904
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/abstract/edwards.js
24905
+ var _0n4 = BigInt(0);
24906
+ var _1n4 = BigInt(1);
24907
+ var _2n2 = BigInt(2);
24908
+ var _8n2 = BigInt(8);
24909
+ function isEdValidXY(Fp2, CURVE, x, y) {
24910
+ const x2 = Fp2.sqr(x);
24911
+ const y2 = Fp2.sqr(y);
24912
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
24913
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
24914
+ return Fp2.eql(left, right);
24915
+ }
24916
+ function edwards(params, extraOpts = {}) {
24917
+ const validated = _createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
24918
+ const { Fp: Fp2, Fn: Fn2 } = validated;
24919
+ let CURVE = validated.CURVE;
24920
+ const { h: cofactor } = CURVE;
24921
+ _validateObject(extraOpts, {}, { uvRatio: "function" });
24922
+ const MASK = _2n2 << BigInt(Fn2.BYTES * 8) - _1n4;
24923
+ const modP = (n) => Fp2.create(n);
24924
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
24925
+ try {
24926
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
24927
+ } catch (e) {
24928
+ return { isValid: false, value: _0n4 };
24929
+ }
24930
+ });
24931
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
24932
+ throw new Error("bad curve params: generator point");
24933
+ function acoord(title, n, banZero = false) {
24934
+ const min = banZero ? _1n4 : _0n4;
24935
+ aInRange("coordinate " + title, n, min, MASK);
24936
+ return n;
24937
+ }
24938
+ function aextpoint(other) {
24939
+ if (!(other instanceof Point))
24940
+ throw new Error("ExtendedPoint expected");
24941
+ }
24942
+ const toAffineMemo = memoized((p, iz) => {
24943
+ const { X, Y, Z } = p;
24944
+ const is0 = p.is0();
24945
+ if (iz == null)
24946
+ iz = is0 ? _8n2 : Fp2.inv(Z);
24947
+ const x = modP(X * iz);
24948
+ const y = modP(Y * iz);
24949
+ const zz = Fp2.mul(Z, iz);
24950
+ if (is0)
24951
+ return { x: _0n4, y: _1n4 };
24952
+ if (zz !== _1n4)
24953
+ throw new Error("invZ was invalid");
24954
+ return { x, y };
24955
+ });
24956
+ const assertValidMemo = memoized((p) => {
24957
+ const { a, d } = CURVE;
24958
+ if (p.is0())
24959
+ throw new Error("bad point: ZERO");
24960
+ const { X, Y, Z, T } = p;
24961
+ const X2 = modP(X * X);
24962
+ const Y2 = modP(Y * Y);
24963
+ const Z2 = modP(Z * Z);
24964
+ const Z4 = modP(Z2 * Z2);
24965
+ const aX2 = modP(X2 * a);
24966
+ const left = modP(Z2 * modP(aX2 + Y2));
24967
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
24968
+ if (left !== right)
24969
+ throw new Error("bad point: equation left != right (1)");
24970
+ const XY = modP(X * Y);
24971
+ const ZT = modP(Z * T);
24972
+ if (XY !== ZT)
24973
+ throw new Error("bad point: equation left != right (2)");
24974
+ return true;
24975
+ });
24976
+ class Point {
24977
+ constructor(X, Y, Z, T) {
24978
+ this.X = acoord("x", X);
24979
+ this.Y = acoord("y", Y);
24980
+ this.Z = acoord("z", Z, true);
24981
+ this.T = acoord("t", T);
24982
+ Object.freeze(this);
24983
+ }
24984
+ static CURVE() {
24985
+ return CURVE;
24986
+ }
24987
+ static fromAffine(p) {
24988
+ if (p instanceof Point)
24989
+ throw new Error("extended point not allowed");
24990
+ const { x, y } = p || {};
24991
+ acoord("x", x);
24992
+ acoord("y", y);
24993
+ return new Point(x, y, _1n4, modP(x * y));
24994
+ }
24995
+ // Uses algo from RFC8032 5.1.3.
24996
+ static fromBytes(bytes, zip215 = false) {
24997
+ const len = Fp2.BYTES;
24998
+ const { a, d } = CURVE;
24999
+ bytes = copyBytes(_abytes2(bytes, len, "point"));
25000
+ _abool2(zip215, "zip215");
25001
+ const normed = copyBytes(bytes);
25002
+ const lastByte = bytes[len - 1];
25003
+ normed[len - 1] = lastByte & ~128;
25004
+ const y = bytesToNumberLE(normed);
25005
+ const max = zip215 ? MASK : Fp2.ORDER;
25006
+ aInRange("point.y", y, _0n4, max);
25007
+ const y2 = modP(y * y);
25008
+ const u = modP(y2 - _1n4);
25009
+ const v = modP(d * y2 - a);
25010
+ let { isValid, value: x } = uvRatio2(u, v);
25011
+ if (!isValid)
25012
+ throw new Error("bad point: invalid y coordinate");
25013
+ const isXOdd = (x & _1n4) === _1n4;
25014
+ const isLastByteOdd = (lastByte & 128) !== 0;
25015
+ if (!zip215 && x === _0n4 && isLastByteOdd)
25016
+ throw new Error("bad point: x=0 and x_0=1");
25017
+ if (isLastByteOdd !== isXOdd)
25018
+ x = modP(-x);
25019
+ return Point.fromAffine({ x, y });
25020
+ }
25021
+ static fromHex(bytes, zip215 = false) {
25022
+ return Point.fromBytes(ensureBytes("point", bytes), zip215);
25023
+ }
25024
+ get x() {
25025
+ return this.toAffine().x;
25026
+ }
25027
+ get y() {
25028
+ return this.toAffine().y;
25029
+ }
25030
+ precompute(windowSize = 8, isLazy = true) {
25031
+ wnaf.createCache(this, windowSize);
25032
+ if (!isLazy)
25033
+ this.multiply(_2n2);
25034
+ return this;
25035
+ }
25036
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
25037
+ assertValidity() {
25038
+ assertValidMemo(this);
25039
+ }
25040
+ // Compare one point to another.
25041
+ equals(other) {
25042
+ aextpoint(other);
25043
+ const { X: X1, Y: Y1, Z: Z1 } = this;
25044
+ const { X: X2, Y: Y2, Z: Z2 } = other;
25045
+ const X1Z2 = modP(X1 * Z2);
25046
+ const X2Z1 = modP(X2 * Z1);
25047
+ const Y1Z2 = modP(Y1 * Z2);
25048
+ const Y2Z1 = modP(Y2 * Z1);
25049
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
25050
+ }
25051
+ is0() {
25052
+ return this.equals(Point.ZERO);
25053
+ }
25054
+ negate() {
25055
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
25056
+ }
25057
+ // Fast algo for doubling Extended Point.
25058
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
25059
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
25060
+ double() {
25061
+ const { a } = CURVE;
25062
+ const { X: X1, Y: Y1, Z: Z1 } = this;
25063
+ const A = modP(X1 * X1);
25064
+ const B = modP(Y1 * Y1);
25065
+ const C = modP(_2n2 * modP(Z1 * Z1));
25066
+ const D = modP(a * A);
25067
+ const x1y1 = X1 + Y1;
25068
+ const E = modP(modP(x1y1 * x1y1) - A - B);
25069
+ const G = D + B;
25070
+ const F = G - C;
25071
+ const H = D - B;
25072
+ const X3 = modP(E * F);
25073
+ const Y3 = modP(G * H);
25074
+ const T3 = modP(E * H);
25075
+ const Z3 = modP(F * G);
25076
+ return new Point(X3, Y3, Z3, T3);
25077
+ }
25078
+ // Fast algo for adding 2 Extended Points.
25079
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
25080
+ // Cost: 9M + 1*a + 1*d + 7add.
25081
+ add(other) {
25082
+ aextpoint(other);
25083
+ const { a, d } = CURVE;
25084
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
25085
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
25086
+ const A = modP(X1 * X2);
25087
+ const B = modP(Y1 * Y2);
25088
+ const C = modP(T1 * d * T2);
25089
+ const D = modP(Z1 * Z2);
25090
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
25091
+ const F = D - C;
25092
+ const G = D + C;
25093
+ const H = modP(B - a * A);
25094
+ const X3 = modP(E * F);
25095
+ const Y3 = modP(G * H);
25096
+ const T3 = modP(E * H);
25097
+ const Z3 = modP(F * G);
25098
+ return new Point(X3, Y3, Z3, T3);
25099
+ }
25100
+ subtract(other) {
25101
+ return this.add(other.negate());
25102
+ }
25103
+ // Constant-time multiplication.
25104
+ multiply(scalar) {
25105
+ if (!Fn2.isValidNot0(scalar))
25106
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
25107
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
25108
+ return normalizeZ(Point, [p, f])[0];
25109
+ }
25110
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
25111
+ // It's faster, but should only be used when you don't care about
25112
+ // an exposed private key e.g. sig verification.
25113
+ // Does NOT allow scalars higher than CURVE.n.
25114
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
25115
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
25116
+ if (!Fn2.isValid(scalar))
25117
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
25118
+ if (scalar === _0n4)
25119
+ return Point.ZERO;
25120
+ if (this.is0() || scalar === _1n4)
25121
+ return this;
25122
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
25123
+ }
25124
+ // Checks if point is of small order.
25125
+ // If you add something to small order point, you will have "dirty"
25126
+ // point with torsion component.
25127
+ // Multiplies point by cofactor and checks if the result is 0.
25128
+ isSmallOrder() {
25129
+ return this.multiplyUnsafe(cofactor).is0();
25130
+ }
25131
+ // Multiplies point by curve order and checks if the result is 0.
25132
+ // Returns `false` is the point is dirty.
25133
+ isTorsionFree() {
25134
+ return wnaf.unsafe(this, CURVE.n).is0();
25135
+ }
25136
+ // Converts Extended point to default (x, y) coordinates.
25137
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
25138
+ toAffine(invertedZ) {
25139
+ return toAffineMemo(this, invertedZ);
25140
+ }
25141
+ clearCofactor() {
25142
+ if (cofactor === _1n4)
25143
+ return this;
25144
+ return this.multiplyUnsafe(cofactor);
25145
+ }
25146
+ toBytes() {
25147
+ const { x, y } = this.toAffine();
25148
+ const bytes = Fp2.toBytes(y);
25149
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
25150
+ return bytes;
25151
+ }
25152
+ toHex() {
25153
+ return bytesToHex(this.toBytes());
25154
+ }
25155
+ toString() {
25156
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
25157
+ }
25158
+ // TODO: remove
25159
+ get ex() {
25160
+ return this.X;
25161
+ }
25162
+ get ey() {
25163
+ return this.Y;
25164
+ }
25165
+ get ez() {
25166
+ return this.Z;
25167
+ }
25168
+ get et() {
25169
+ return this.T;
25170
+ }
25171
+ static normalizeZ(points) {
25172
+ return normalizeZ(Point, points);
25173
+ }
25174
+ static msm(points, scalars) {
25175
+ return pippenger(Point, Fn2, points, scalars);
25176
+ }
25177
+ _setWindowSize(windowSize) {
25178
+ this.precompute(windowSize);
25179
+ }
25180
+ toRawBytes() {
25181
+ return this.toBytes();
25182
+ }
25183
+ }
25184
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
25185
+ Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
25186
+ Point.Fp = Fp2;
25187
+ Point.Fn = Fn2;
25188
+ const wnaf = new wNAF(Point, Fn2.BITS);
25189
+ Point.BASE.precompute(8);
25190
+ return Point;
25191
+ }
25192
+ var PrimeEdwardsPoint = class {
25193
+ constructor(ep) {
25194
+ this.ep = ep;
25195
+ }
25196
+ // Static methods that must be implemented by subclasses
25197
+ static fromBytes(_bytes) {
25198
+ notImplemented();
25199
+ }
25200
+ static fromHex(_hex) {
25201
+ notImplemented();
25202
+ }
25203
+ get x() {
25204
+ return this.toAffine().x;
25205
+ }
25206
+ get y() {
25207
+ return this.toAffine().y;
25208
+ }
25209
+ // Common implementations
25210
+ clearCofactor() {
25211
+ return this;
25212
+ }
25213
+ assertValidity() {
25214
+ this.ep.assertValidity();
25215
+ }
25216
+ toAffine(invertedZ) {
25217
+ return this.ep.toAffine(invertedZ);
25218
+ }
25219
+ toHex() {
25220
+ return bytesToHex(this.toBytes());
25221
+ }
25222
+ toString() {
25223
+ return this.toHex();
25224
+ }
25225
+ isTorsionFree() {
25226
+ return true;
25227
+ }
25228
+ isSmallOrder() {
25229
+ return false;
25230
+ }
25231
+ add(other) {
25232
+ this.assertSame(other);
25233
+ return this.init(this.ep.add(other.ep));
25234
+ }
25235
+ subtract(other) {
25236
+ this.assertSame(other);
25237
+ return this.init(this.ep.subtract(other.ep));
25238
+ }
25239
+ multiply(scalar) {
25240
+ return this.init(this.ep.multiply(scalar));
25241
+ }
25242
+ multiplyUnsafe(scalar) {
25243
+ return this.init(this.ep.multiplyUnsafe(scalar));
25244
+ }
25245
+ double() {
25246
+ return this.init(this.ep.double());
25247
+ }
25248
+ negate() {
25249
+ return this.init(this.ep.negate());
25250
+ }
25251
+ precompute(windowSize, isLazy) {
25252
+ return this.init(this.ep.precompute(windowSize, isLazy));
25253
+ }
25254
+ /** @deprecated use `toBytes` */
25255
+ toRawBytes() {
25256
+ return this.toBytes();
25257
+ }
25258
+ };
25259
+ function eddsa(Point, cHash, eddsaOpts = {}) {
25260
+ if (typeof cHash !== "function")
25261
+ throw new Error('"hash" function param is required');
25262
+ _validateObject(eddsaOpts, {}, {
25263
+ adjustScalarBytes: "function",
25264
+ randomBytes: "function",
25265
+ domain: "function",
25266
+ prehash: "function",
25267
+ mapToCurve: "function"
25268
+ });
25269
+ const { prehash } = eddsaOpts;
25270
+ const { BASE, Fp: Fp2, Fn: Fn2 } = Point;
25271
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
25272
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
25273
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
25274
+ _abool2(phflag, "phflag");
25275
+ if (ctx.length || phflag)
25276
+ throw new Error("Contexts/pre-hash are not supported");
25277
+ return data;
25278
+ });
25279
+ function modN_LE(hash) {
25280
+ return Fn2.create(bytesToNumberLE(hash));
25281
+ }
25282
+ function getPrivateScalar(key) {
25283
+ const len = lengths.secretKey;
25284
+ key = ensureBytes("private key", key, len);
25285
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
25286
+ const head = adjustScalarBytes2(hashed.slice(0, len));
25287
+ const prefix = hashed.slice(len, 2 * len);
25288
+ const scalar = modN_LE(head);
25289
+ return { head, prefix, scalar };
25290
+ }
25291
+ function getExtendedPublicKey(secretKey) {
25292
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
25293
+ const point = BASE.multiply(scalar);
25294
+ const pointBytes = point.toBytes();
25295
+ return { head, prefix, scalar, point, pointBytes };
25296
+ }
25297
+ function getPublicKey(secretKey) {
25298
+ return getExtendedPublicKey(secretKey).pointBytes;
25299
+ }
25300
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
25301
+ const msg = concatBytes(...msgs);
25302
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
25303
+ }
25304
+ function sign(msg, secretKey, options = {}) {
25305
+ msg = ensureBytes("message", msg);
25306
+ if (prehash)
25307
+ msg = prehash(msg);
25308
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
25309
+ const r = hashDomainToScalar(options.context, prefix, msg);
25310
+ const R = BASE.multiply(r).toBytes();
25311
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
25312
+ const s = Fn2.create(r + k * scalar);
25313
+ if (!Fn2.isValid(s))
25314
+ throw new Error("sign failed: invalid s");
25315
+ const rs = concatBytes(R, Fn2.toBytes(s));
25316
+ return _abytes2(rs, lengths.signature, "result");
25317
+ }
25318
+ const verifyOpts = { zip215: true };
25319
+ function verify(sig, msg, publicKey, options = verifyOpts) {
25320
+ const { context, zip215 } = options;
25321
+ const len = lengths.signature;
25322
+ sig = ensureBytes("signature", sig, len);
25323
+ msg = ensureBytes("message", msg);
25324
+ publicKey = ensureBytes("publicKey", publicKey, lengths.publicKey);
25325
+ if (zip215 !== void 0)
25326
+ _abool2(zip215, "zip215");
25327
+ if (prehash)
25328
+ msg = prehash(msg);
25329
+ const mid = len / 2;
25330
+ const r = sig.subarray(0, mid);
25331
+ const s = bytesToNumberLE(sig.subarray(mid, len));
25332
+ let A, R, SB;
25333
+ try {
25334
+ A = Point.fromBytes(publicKey, zip215);
25335
+ R = Point.fromBytes(r, zip215);
25336
+ SB = BASE.multiplyUnsafe(s);
25337
+ } catch (error) {
25338
+ return false;
25339
+ }
25340
+ if (!zip215 && A.isSmallOrder())
25341
+ return false;
25342
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
25343
+ const RkA = R.add(A.multiplyUnsafe(k));
25344
+ return RkA.subtract(SB).clearCofactor().is0();
25345
+ }
25346
+ const _size = Fp2.BYTES;
25347
+ const lengths = {
25348
+ secretKey: _size,
25349
+ publicKey: _size,
25350
+ signature: 2 * _size,
25351
+ seed: _size
25352
+ };
25353
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
25354
+ return _abytes2(seed, lengths.seed, "seed");
25355
+ }
25356
+ function keygen(seed) {
25357
+ const secretKey = utils.randomSecretKey(seed);
25358
+ return { secretKey, publicKey: getPublicKey(secretKey) };
25359
+ }
25360
+ function isValidSecretKey(key) {
25361
+ return isBytes(key) && key.length === Fn2.BYTES;
25362
+ }
25363
+ function isValidPublicKey(key, zip215) {
25364
+ try {
25365
+ return !!Point.fromBytes(key, zip215);
25366
+ } catch (error) {
25367
+ return false;
25368
+ }
25369
+ }
25370
+ const utils = {
25371
+ getExtendedPublicKey,
25372
+ randomSecretKey,
25373
+ isValidSecretKey,
25374
+ isValidPublicKey,
25375
+ /**
25376
+ * Converts ed public key to x public key. Uses formula:
25377
+ * - ed25519:
25378
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
25379
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
25380
+ * - ed448:
25381
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
25382
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
25383
+ */
25384
+ toMontgomery(publicKey) {
25385
+ const { y } = Point.fromBytes(publicKey);
25386
+ const size = lengths.publicKey;
25387
+ const is25519 = size === 32;
25388
+ if (!is25519 && size !== 57)
25389
+ throw new Error("only defined for 25519 and 448");
25390
+ const u = is25519 ? Fp2.div(_1n4 + y, _1n4 - y) : Fp2.div(y - _1n4, y + _1n4);
25391
+ return Fp2.toBytes(u);
25392
+ },
25393
+ toMontgomerySecret(secretKey) {
25394
+ const size = lengths.secretKey;
25395
+ _abytes2(secretKey, size);
25396
+ const hashed = cHash(secretKey.subarray(0, size));
25397
+ return adjustScalarBytes2(hashed).subarray(0, size);
25398
+ },
25399
+ /** @deprecated */
25400
+ randomPrivateKey: randomSecretKey,
25401
+ /** @deprecated */
25402
+ precompute(windowSize = 8, point = Point.BASE) {
25403
+ return point.precompute(windowSize, false);
25404
+ }
25405
+ };
25406
+ return Object.freeze({
25407
+ keygen,
25408
+ getPublicKey,
25409
+ sign,
25410
+ verify,
25411
+ utils,
25412
+ Point,
25413
+ lengths
25414
+ });
25415
+ }
25416
+ function _eddsa_legacy_opts_to_new(c) {
25417
+ const CURVE = {
25418
+ a: c.a,
25419
+ d: c.d,
25420
+ p: c.Fp.ORDER,
25421
+ n: c.n,
25422
+ h: c.h,
25423
+ Gx: c.Gx,
25424
+ Gy: c.Gy
25425
+ };
25426
+ const Fp2 = c.Fp;
25427
+ const Fn2 = Field(CURVE.n, c.nBitLength, true);
25428
+ const curveOpts = { Fp: Fp2, Fn: Fn2, uvRatio: c.uvRatio };
25429
+ const eddsaOpts = {
25430
+ randomBytes: c.randomBytes,
25431
+ adjustScalarBytes: c.adjustScalarBytes,
25432
+ domain: c.domain,
25433
+ prehash: c.prehash,
25434
+ mapToCurve: c.mapToCurve
25435
+ };
25436
+ return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
25437
+ }
25438
+ function _eddsa_new_output_to_legacy(c, eddsa2) {
25439
+ const Point = eddsa2.Point;
25440
+ const legacy = Object.assign({}, eddsa2, {
25441
+ ExtendedPoint: Point,
25442
+ CURVE: c,
25443
+ nBitLength: Point.Fn.BITS,
25444
+ nByteLength: Point.Fn.BYTES
25445
+ });
25446
+ return legacy;
25447
+ }
25448
+ function twistedEdwards(c) {
25449
+ const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
25450
+ const Point = edwards(CURVE, curveOpts);
25451
+ const EDDSA = eddsa(Point, hash, eddsaOpts);
25452
+ return _eddsa_new_output_to_legacy(c, EDDSA);
25453
+ }
25454
+
25455
+ // ../mmt-manifest-verify/node_modules/@noble/curves/esm/ed25519.js
25456
+ var _0n5 = /* @__PURE__ */ BigInt(0);
25457
+ var _1n5 = BigInt(1);
25458
+ var _2n3 = BigInt(2);
25459
+ var _3n2 = BigInt(3);
25460
+ var _5n2 = BigInt(5);
25461
+ var _8n3 = BigInt(8);
25462
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
25463
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
25464
+ p: ed25519_CURVE_p,
25465
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
25466
+ h: _8n3,
25467
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
25468
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
25469
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
25470
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
25471
+ }))();
25472
+ function ed25519_pow_2_252_3(x) {
25473
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
25474
+ const P = ed25519_CURVE_p;
25475
+ const x2 = x * x % P;
25476
+ const b2 = x2 * x % P;
25477
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
25478
+ const b5 = pow2(b4, _1n5, P) * x % P;
25479
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
25480
+ const b20 = pow2(b10, _10n, P) * b10 % P;
25481
+ const b40 = pow2(b20, _20n, P) * b20 % P;
25482
+ const b80 = pow2(b40, _40n, P) * b40 % P;
25483
+ const b160 = pow2(b80, _80n, P) * b80 % P;
25484
+ const b240 = pow2(b160, _80n, P) * b80 % P;
25485
+ const b250 = pow2(b240, _10n, P) * b10 % P;
25486
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
25487
+ return { pow_p_5_8, b2 };
25488
+ }
25489
+ function adjustScalarBytes(bytes) {
25490
+ bytes[0] &= 248;
25491
+ bytes[31] &= 127;
25492
+ bytes[31] |= 64;
25493
+ return bytes;
25494
+ }
25495
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
25496
+ function uvRatio(u, v) {
25497
+ const P = ed25519_CURVE_p;
25498
+ const v3 = mod(v * v * v, P);
25499
+ const v7 = mod(v3 * v3 * v, P);
25500
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
25501
+ let x = mod(u * v3 * pow, P);
25502
+ const vx2 = mod(v * x * x, P);
25503
+ const root1 = x;
25504
+ const root2 = mod(x * ED25519_SQRT_M1, P);
25505
+ const useRoot1 = vx2 === u;
25506
+ const useRoot2 = vx2 === mod(-u, P);
25507
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
25508
+ if (useRoot1)
25509
+ x = root1;
25510
+ if (useRoot2 || noRoot)
25511
+ x = root2;
25512
+ if (isNegativeLE(x, P))
25513
+ x = mod(-x, P);
25514
+ return { isValid: useRoot1 || useRoot2, value: x };
25515
+ }
25516
+ var Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();
25517
+ var Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();
25518
+ var ed25519Defaults = /* @__PURE__ */ (() => ({
25519
+ ...ed25519_CURVE,
25520
+ Fp,
25521
+ hash: sha512,
25522
+ adjustScalarBytes,
25523
+ // dom2
25524
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
25525
+ // Constant-time, u/√v
25526
+ uvRatio
25527
+ }))();
25528
+ var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
25529
+ var SQRT_M1 = ED25519_SQRT_M1;
25530
+ var SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");
25531
+ var INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");
25532
+ var ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");
25533
+ var D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
25534
+ var invertSqrt = (number) => uvRatio(_1n5, number);
25535
+ var MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
25536
+ var bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
25537
+ function calcElligatorRistrettoMap(r0) {
25538
+ const { d } = ed25519_CURVE;
25539
+ const P = ed25519_CURVE_p;
25540
+ const mod2 = (n) => Fp.create(n);
25541
+ const r = mod2(SQRT_M1 * r0 * r0);
25542
+ const Ns = mod2((r + _1n5) * ONE_MINUS_D_SQ);
25543
+ let c = BigInt(-1);
25544
+ const D = mod2((c - d * r) * mod2(r + d));
25545
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
25546
+ let s_ = mod2(s * r0);
25547
+ if (!isNegativeLE(s_, P))
25548
+ s_ = mod2(-s_);
25549
+ if (!Ns_D_is_sq)
25550
+ s = s_;
25551
+ if (!Ns_D_is_sq)
25552
+ c = r;
25553
+ const Nt = mod2(c * (r - _1n5) * D_MINUS_ONE_SQ - D);
25554
+ const s2 = s * s;
25555
+ const W0 = mod2((s + s) * D);
25556
+ const W1 = mod2(Nt * SQRT_AD_MINUS_ONE);
25557
+ const W2 = mod2(_1n5 - s2);
25558
+ const W3 = mod2(_1n5 + s2);
25559
+ return new ed25519.Point(mod2(W0 * W3), mod2(W2 * W1), mod2(W1 * W3), mod2(W0 * W2));
25560
+ }
25561
+ function ristretto255_map(bytes) {
25562
+ abytes(bytes, 64);
25563
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
25564
+ const R1 = calcElligatorRistrettoMap(r1);
25565
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
25566
+ const R2 = calcElligatorRistrettoMap(r2);
25567
+ return new _RistrettoPoint(R1.add(R2));
25568
+ }
25569
+ var _RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
25570
+ constructor(ep) {
25571
+ super(ep);
25572
+ }
25573
+ static fromAffine(ap) {
25574
+ return new __RistrettoPoint(ed25519.Point.fromAffine(ap));
25575
+ }
25576
+ assertSame(other) {
25577
+ if (!(other instanceof __RistrettoPoint))
25578
+ throw new Error("RistrettoPoint expected");
25579
+ }
25580
+ init(ep) {
25581
+ return new __RistrettoPoint(ep);
25582
+ }
25583
+ /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
25584
+ static hashToCurve(hex3) {
25585
+ return ristretto255_map(ensureBytes("ristrettoHash", hex3, 64));
25586
+ }
25587
+ static fromBytes(bytes) {
25588
+ abytes(bytes, 32);
25589
+ const { a, d } = ed25519_CURVE;
25590
+ const P = ed25519_CURVE_p;
25591
+ const mod2 = (n) => Fp.create(n);
25592
+ const s = bytes255ToNumberLE(bytes);
25593
+ if (!equalBytes2(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
25594
+ throw new Error("invalid ristretto255 encoding 1");
25595
+ const s2 = mod2(s * s);
25596
+ const u1 = mod2(_1n5 + a * s2);
25597
+ const u2 = mod2(_1n5 - a * s2);
25598
+ const u1_2 = mod2(u1 * u1);
25599
+ const u2_2 = mod2(u2 * u2);
25600
+ const v = mod2(a * d * u1_2 - u2_2);
25601
+ const { isValid, value: I } = invertSqrt(mod2(v * u2_2));
25602
+ const Dx = mod2(I * u2);
25603
+ const Dy = mod2(I * Dx * v);
25604
+ let x = mod2((s + s) * Dx);
25605
+ if (isNegativeLE(x, P))
25606
+ x = mod2(-x);
25607
+ const y = mod2(u1 * Dy);
25608
+ const t = mod2(x * y);
25609
+ if (!isValid || isNegativeLE(t, P) || y === _0n5)
25610
+ throw new Error("invalid ristretto255 encoding 2");
25611
+ return new __RistrettoPoint(new ed25519.Point(x, y, _1n5, t));
25612
+ }
25613
+ /**
25614
+ * Converts ristretto-encoded string to ristretto point.
25615
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
25616
+ * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
25617
+ */
25618
+ static fromHex(hex3) {
25619
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex3, 32));
25620
+ }
25621
+ static msm(points, scalars) {
25622
+ return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
25623
+ }
25624
+ /**
25625
+ * Encodes ristretto point to Uint8Array.
25626
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
25627
+ */
25628
+ toBytes() {
25629
+ let { X, Y, Z, T } = this.ep;
25630
+ const P = ed25519_CURVE_p;
25631
+ const mod2 = (n) => Fp.create(n);
25632
+ const u1 = mod2(mod2(Z + Y) * mod2(Z - Y));
25633
+ const u2 = mod2(X * Y);
25634
+ const u2sq = mod2(u2 * u2);
25635
+ const { value: invsqrt } = invertSqrt(mod2(u1 * u2sq));
25636
+ const D1 = mod2(invsqrt * u1);
25637
+ const D2 = mod2(invsqrt * u2);
25638
+ const zInv = mod2(D1 * D2 * T);
25639
+ let D;
25640
+ if (isNegativeLE(T * zInv, P)) {
25641
+ let _x = mod2(Y * SQRT_M1);
25642
+ let _y = mod2(X * SQRT_M1);
25643
+ X = _x;
25644
+ Y = _y;
25645
+ D = mod2(D1 * INVSQRT_A_MINUS_D);
25646
+ } else {
25647
+ D = D2;
25648
+ }
25649
+ if (isNegativeLE(X * zInv, P))
25650
+ Y = mod2(-Y);
25651
+ let s = mod2((Z - Y) * D);
25652
+ if (isNegativeLE(s, P))
25653
+ s = mod2(-s);
25654
+ return Fp.toBytes(s);
25655
+ }
25656
+ /**
25657
+ * Compares two Ristretto points.
25658
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
25659
+ */
25660
+ equals(other) {
25661
+ this.assertSame(other);
25662
+ const { X: X1, Y: Y1 } = this.ep;
25663
+ const { X: X2, Y: Y2 } = other.ep;
25664
+ const mod2 = (n) => Fp.create(n);
25665
+ const one = mod2(X1 * Y2) === mod2(Y1 * X2);
25666
+ const two = mod2(Y1 * Y2) === mod2(X1 * X2);
25667
+ return one || two;
25668
+ }
25669
+ is0() {
25670
+ return this.equals(__RistrettoPoint.ZERO);
25671
+ }
25672
+ };
25673
+ _RistrettoPoint.BASE = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();
25674
+ _RistrettoPoint.ZERO = /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();
25675
+ _RistrettoPoint.Fp = /* @__PURE__ */ (() => Fp)();
25676
+ _RistrettoPoint.Fn = /* @__PURE__ */ (() => Fn)();
25677
+
25678
+ // ../mmt-manifest-verify/dist/bc-provenance-v2-receiver.js
25679
+ var BCPV2_LEAD_BOUND_MS = 5e3;
25680
+ var REPLAY_WINDOW = 64n;
25681
+ var BUCKET_DEPTH = 64;
25682
+ var BUCKET_RATE_PER_MS = 1;
25683
+ var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
25684
+ function sameBytes(a, b) {
25685
+ if (a.byteLength !== b.byteLength)
25686
+ return false;
25687
+ let diff = 0;
25688
+ for (let i = 0; i < a.byteLength; i++)
25689
+ diff |= a[i] ^ b[i];
25690
+ return diff === 0;
25691
+ }
25692
+ var BcProvenanceV2Receiver = class {
25693
+ maxAuthDelayMs;
25694
+ manifestTimerMs;
25695
+ widenMs;
25696
+ /** Datagrams that left a hold queue at expiry, per path: the loss signal for failover. */
25697
+ expired = { multicast: 0, unicast: 0 };
25698
+ /**
25699
+ * Unicast repair (Section 7.2.7 step 2): on a receiver that can request it, how
25700
+ * long ago (ms) the first packet admitted into the oldest open block with an FEC
25701
+ * deadline was admitted; undefined with none open. A pending entry still live
25702
+ * then is kept instead of expiring, and is released with the block, under the
25703
+ * open-block bound of [MOQ-FEC] Section 9.
25704
+ */
25705
+ keepPendingAgeMs = null;
25706
+ cfg;
25707
+ now;
25708
+ verifySig;
25709
+ accepted;
25710
+ queueLimit;
25711
+ current = null;
25712
+ previous = null;
25713
+ graceStart = {};
25714
+ hashAlg = null;
25715
+ verified = /* @__PURE__ */ new Map();
25716
+ highest = { multicast: /* @__PURE__ */ new Map(), mirror: /* @__PURE__ */ new Map() };
25717
+ closedAt = /* @__PURE__ */ new Map();
25718
+ lead = null;
25719
+ pending = /* @__PURE__ */ new Map();
25720
+ admittedUntil = /* @__PURE__ */ new Map();
25721
+ hold = { multicast: [], unicast: [] };
25722
+ holdBytes = { multicast: 0, unicast: 0 };
25723
+ order = 0;
25724
+ buckets;
25725
+ constructor(cfg) {
25726
+ this.maxAuthDelayMs = cfg.maxAuthDelayMs ?? 200;
25727
+ this.manifestTimerMs = cfg.manifestTimerMs ?? 20;
25728
+ if (!(this.maxAuthDelayMs >= 50 && this.maxAuthDelayMs <= 1e3) || !(this.manifestTimerMs >= 1)) {
25729
+ throw new Error("BCPV2 endpoint ignored: maxAuthDelayMs or manifestTimerMs out of range");
25730
+ }
25731
+ if (!(cfg.bandwidth > 0))
25732
+ throw new Error("BCPV2 endpoint ignored: protected endpoint without bandwidth");
25733
+ const kids = new Set(cfg.keys.map((k) => k.kid));
25734
+ const firsts = new Set(cfg.keys.map((k) => k.firstEpoch));
25735
+ if (cfg.keys.length < 1 || kids.size !== cfg.keys.length || firsts.size !== cfg.keys.length) {
25736
+ throw new Error("BCPV2 key set invalid: no keys, or a repeated kid or firstEpoch");
25737
+ }
25738
+ this.cfg = cfg;
25739
+ this.widenMs = Math.min(Math.max(cfg.widenMs ?? 0, 0), BCPV2_LEAD_BOUND_MS);
25740
+ this.now = cfg.now ?? Date.now;
25741
+ this.verifySig = cfg.verifySignature ?? ((pk, msg, sig) => {
25742
+ try {
25743
+ return ed25519.verify(sig, msg, pk, { zip215: false });
25744
+ } catch {
25745
+ return false;
25746
+ }
25747
+ });
25748
+ this.accepted = cfg.acceptedHashAlgs ?? [BCPV2_HASH_ALG_SHA256];
25749
+ const bandwidth = Math.min(cfg.bandwidth, 1e10);
25750
+ this.queueLimit = {
25751
+ multicast: this.maxAuthDelayMs * bandwidth / 8e3,
25752
+ unicast: (this.maxAuthDelayMs + this.widenMs) * bandwidth / 8e3
25753
+ };
25754
+ const t = this.now();
25755
+ this.buckets = {
25756
+ multicast: { tokens: BUCKET_DEPTH, last: t, dropped: 0 },
25757
+ mirror: { tokens: BUCKET_DEPTH, last: t, dropped: 0 }
25758
+ };
25759
+ }
25760
+ get grace() {
25761
+ return this.maxAuthDelayMs + 2 * this.manifestTimerMs;
25762
+ }
25763
+ /** The mirror's lead in force: 0 without a manifest track, the bound until one is measured. */
25764
+ get leadMs() {
25765
+ if (!this.cfg.applyLead)
25766
+ return 0;
25767
+ return this.lead ?? BCPV2_LEAD_BOUND_MS;
25768
+ }
25769
+ /** Step 1: a record datagram on `manifestPort`, or a record object of the manifest track. */
25770
+ onRecord(bytes, path) {
25771
+ const now = this.now();
25772
+ this.expire(now);
25773
+ const drop = (verdict) => ({ verdict, admitted: [] });
25774
+ const len = bytes.byteLength;
25775
+ if (len < BCPV2_MIN_RECORD_LENGTH || len > BCPV2_MAX_RECORD_LENGTH || (len - 132) % 32 !== 0)
25776
+ return drop("length");
25777
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, len);
25778
+ if (view2.getUint32(0) !== 1296583986)
25779
+ return drop("magic");
25780
+ const kid = view2.getUint32(4);
25781
+ const epoch = view2.getUint32(8);
25782
+ const mseq = view2.getBigUint64(12);
25783
+ const count = view2.getUint16(28);
25784
+ const hashAlg = bytes[30];
25785
+ const sent = view2.getUint32(32);
25786
+ const key = this.cfg.keys.find((k) => k.kid === kid);
25787
+ if (!key)
25788
+ return drop("kid");
25789
+ const next = Math.min(...this.cfg.keys.map((k) => k.firstEpoch).filter((f) => f > key.firstEpoch), Infinity);
25790
+ if (epoch < key.firstEpoch || epoch >= next)
25791
+ return drop("epoch");
25792
+ const id = `${kid}:${epoch}:${mseq}`;
25793
+ const seen = this.verified.get(id);
25794
+ if (seen) {
25795
+ const admitted2 = hex(sha2562(bytes)) === seen.digest ? this.arrival(seen, path, now) : [];
25796
+ return { verdict: "duplicate", admitted: admitted2 };
25797
+ }
25798
+ const ke = `${kid}:${epoch}`;
25799
+ if (this.current === null) {
25800
+ if (epoch < this.cfg.minEpoch || epoch < (this.cfg.pinnedEpochFloor?.get(kid) ?? 0))
25801
+ return drop("epoch");
25802
+ } else if (epoch < this.current.epoch && !this.previousAdmitted(epoch, path, now)) {
25803
+ return drop("epoch");
25804
+ }
25805
+ const floor = this.floor(ke, path);
25806
+ if (floor !== void 0 && mseq <= floor - REPLAY_WINDOW)
25807
+ return drop("mseq");
25808
+ const closed = this.closedAt.get(ke);
25809
+ if (closed !== void 0 && mseq > closed)
25810
+ return drop("closed");
25811
+ if (this.cfg.checkFreshness !== false) {
25812
+ const behind = 7e3 + this.maxAuthDelayMs + (path === "mirror" ? this.widenMs : 0);
25813
+ if (sent * 1e3 < now - behind || sent * 1e3 > now + 6e3)
25814
+ return drop("sent");
25815
+ }
25816
+ if (count !== (len - 132) / 32)
25817
+ return drop("count");
25818
+ if (!this.accepted.includes(hashAlg) || this.hashAlg !== null && hashAlg !== this.hashAlg)
25819
+ return drop("hash_alg");
25820
+ if (this.cfg.catalogCtx && !sameBytes(bytes.subarray(36, 68), this.cfg.catalogCtx))
25821
+ return drop("ctx");
25822
+ if (!this.take(path, now))
25823
+ return drop("budget");
25824
+ const record = decodeBcProvenanceV2Record(bytes);
25825
+ if (!this.verifySig(key.publicKey, bcProvenanceV2SignedMessage(record, this.cfg.endpoint), record.signature)) {
25826
+ return drop("signature");
25827
+ }
25828
+ if (this.current === null || epoch > this.current.epoch) {
25829
+ if (this.current !== null) {
25830
+ this.previous = { epoch: this.current.epoch, deadline: now + BCPV2_LEAD_BOUND_MS + this.grace };
25831
+ }
25832
+ this.current = { epoch, since: now };
25833
+ this.graceStart = { [path]: now };
25834
+ if (this.hashAlg === null) {
25835
+ this.hashAlg = hashAlg;
25836
+ for (const queue of Object.values(this.hold)) {
25837
+ for (const held of queue)
25838
+ held.digest ??= this.digest(held.datagram);
25839
+ }
25840
+ }
25841
+ } else if (epoch === this.current.epoch) {
25842
+ this.graceStart[path] ??= now;
25843
+ }
25844
+ const entry = {
25845
+ kid,
25846
+ epoch,
25847
+ mseq,
25848
+ path,
25849
+ arrival: now,
25850
+ sent,
25851
+ digest: hex(sha2562(bytes)),
25852
+ pairs: record.digests.map((d, i) => ({ digest: hex(d), seq: record.firstSeq + BigInt(i), admitted: false })),
25853
+ awaitingMulticast: path === "mirror"
25854
+ };
25855
+ this.verified.set(id, entry);
25856
+ this.raise(ke, path, mseq);
25857
+ if (record.flags & 1)
25858
+ this.closedAt.set(ke, mseq);
25859
+ const widen = path === "mirror" ? this.cfg.applyLead ? this.leadMs : this.widenMs : 0;
25860
+ const admitted = [];
25861
+ for (const pair of entry.pairs)
25862
+ this.handlePair(pair, now, now + this.grace + widen, now, admitted);
25863
+ this.dropAdmittedHeld();
25864
+ this.prune(now);
25865
+ return { verdict: "verified", admitted };
25866
+ }
25867
+ /** Step 2: a data datagram on `port` (or a packet of a listed track over MoQ unicast). */
25868
+ onDatagram(datagram, path) {
25869
+ const now = this.now();
25870
+ this.expire(now);
25871
+ if (this.hashAlg !== null) {
25872
+ const d = this.digest(datagram);
25873
+ if (this.consumePending(d, now))
25874
+ return { verdict: "admitted", admitted: [datagram] };
25875
+ if (this.admittedUntil.has(d))
25876
+ return { verdict: "duplicate", admitted: [] };
25877
+ return this.enqueue({ digest: d, datagram, expiry: 0, order: 0 }, path, now);
25878
+ }
25879
+ return this.enqueue({ datagram, expiry: 0, order: 0 }, path, now);
25880
+ }
25881
+ /**
25882
+ * A source packet recovered by FEC decode, its base SS_ID (SS_Start + ESI)
25883
+ * appended: admitted only on a pending entry it consumes, never held. One no
25884
+ * verified record lists, or a copy of an admitted packet, is dropped.
25885
+ */
25886
+ admitRecovered(datagram) {
25887
+ const now = this.now();
25888
+ this.expire(now);
25889
+ return this.hashAlg !== null && this.consumePending(this.digest(datagram), now);
25890
+ }
25891
+ /**
25892
+ * Discard the per-flow state on a `streamId` change or a key-set change that fails the
25893
+ * flow's current (kid, epoch): budgets and hold queues survive, held digests are cleared.
25894
+ */
25895
+ resetGeneration() {
25896
+ this.current = null;
25897
+ this.previous = null;
25898
+ this.graceStart = {};
25899
+ this.hashAlg = null;
25900
+ this.verified.clear();
25901
+ this.highest = { multicast: /* @__PURE__ */ new Map(), mirror: /* @__PURE__ */ new Map() };
25902
+ this.closedAt.clear();
25903
+ this.lead = null;
25904
+ this.pending.clear();
25905
+ this.admittedUntil.clear();
25906
+ for (const queue of Object.values(this.hold))
25907
+ for (const held of queue)
25908
+ held.digest = void 0;
25909
+ }
25910
+ /** The receiver ceased to hold the endpoint: drop everything; no drop here is an expiry. */
25911
+ release() {
25912
+ this.resetGeneration();
25913
+ this.hold = { multicast: [], unicast: [] };
25914
+ this.holdBytes = { multicast: 0, unicast: 0 };
25915
+ }
25916
+ digest(datagram) {
25917
+ return hex(bcProvenanceV2DatagramDigest(this.cfg.endpoint, datagram));
25918
+ }
25919
+ /** Consume the lowest-seq pending entry for `digest`, admitting it. */
25920
+ consumePending(digest, now) {
25921
+ const list = this.pending.get(digest);
25922
+ if (!list?.length)
25923
+ return false;
25924
+ list.sort((a, b) => a.pair.seq < b.pair.seq ? -1 : a.pair.seq > b.pair.seq ? 1 : 0);
25925
+ const hit = list.shift();
25926
+ if (list.length === 0)
25927
+ this.pending.delete(digest);
25928
+ hit.pair.pending = void 0;
25929
+ hit.pair.admitted = true;
25930
+ this.admittedUntil.set(digest, now + this.maxAuthDelayMs + this.leadMs);
25931
+ return true;
25932
+ }
25933
+ enqueue(held, path, now) {
25934
+ if (this.holdBytes[path] + held.datagram.byteLength > this.queueLimit[path]) {
25935
+ return { verdict: "overflow", admitted: [] };
25936
+ }
25937
+ held.expiry = now + this.maxAuthDelayMs + (path === "unicast" ? this.widenMs : 0);
25938
+ held.order = this.order++;
25939
+ this.hold[path].push(held);
25940
+ this.holdBytes[path] += held.datagram.byteLength;
25941
+ return { verdict: "held", admitted: [] };
25942
+ }
25943
+ /** Remove and return the oldest held datagram with `digest`, across both queues. */
25944
+ takeHeld(digest) {
25945
+ let best;
25946
+ for (const path of ["multicast", "unicast"]) {
25947
+ const index = this.hold[path].findIndex((h) => h.digest === digest);
25948
+ if (index >= 0 && (!best || this.hold[path][index].order < best.order)) {
25949
+ best = { path, index, order: this.hold[path][index].order };
25950
+ }
25951
+ }
25952
+ if (!best)
25953
+ return void 0;
25954
+ const [held] = this.hold[best.path].splice(best.index, 1);
25955
+ this.holdBytes[best.path] -= held.datagram.byteLength;
25956
+ return held.datagram;
25957
+ }
25958
+ dropAdmittedHeld() {
25959
+ for (const path of ["multicast", "unicast"]) {
25960
+ this.hold[path] = this.hold[path].filter((h) => {
25961
+ const keep = h.digest === void 0 || !this.admittedUntil.has(h.digest);
25962
+ if (!keep)
25963
+ this.holdBytes[path] -= h.datagram.byteLength;
25964
+ return keep;
25965
+ });
25966
+ }
25967
+ }
25968
+ /** Step 1 pair handling: admit a held copy, or insert a pending entry. */
25969
+ handlePair(pair, now, expiry, inserted, out) {
25970
+ const datagram = this.takeHeld(pair.digest);
25971
+ if (datagram) {
25972
+ pair.admitted = true;
25973
+ this.admittedUntil.set(pair.digest, now + this.maxAuthDelayMs + this.leadMs);
25974
+ out.push(datagram);
25975
+ return;
25976
+ }
25977
+ const entry = { pair, inserted, expiry };
25978
+ pair.pending = entry;
25979
+ const list = this.pending.get(pair.digest);
25980
+ if (list)
25981
+ list.push(entry);
25982
+ else
25983
+ this.pending.set(pair.digest, [entry]);
25984
+ }
25985
+ /** A byte-identical copy dropped by the already-verified lookup. */
25986
+ arrival(seen, path, now) {
25987
+ const ke = `${seen.kid}:${seen.epoch}`;
25988
+ this.raise(ke, path, seen.mseq);
25989
+ if (this.current && seen.epoch === this.current.epoch)
25990
+ this.graceStart[path] ??= now;
25991
+ if (path !== "multicast" || !seen.awaitingMulticast)
25992
+ return [];
25993
+ seen.awaitingMulticast = false;
25994
+ if (!this.cfg.applyLead)
25995
+ return [];
25996
+ const t = this.manifestTimerMs;
25997
+ const interval = Math.min(Math.ceil((now - seen.arrival) / t) * t, BCPV2_LEAD_BOUND_MS);
25998
+ if (this.lead === null) {
25999
+ this.lead = interval;
26000
+ return [];
26001
+ }
26002
+ if (interval <= this.lead)
26003
+ return [];
26004
+ this.lead = interval;
26005
+ const out = [];
26006
+ const records = [seen, ...[...this.verified.values()].filter((v) => v.awaitingMulticast && v.arrival >= now - interval)];
26007
+ for (const v of records) {
26008
+ for (const pair of v.pairs) {
26009
+ if (pair.admitted) {
26010
+ this.admittedUntil.set(pair.digest, now + this.maxAuthDelayMs + interval);
26011
+ } else if (pair.pending) {
26012
+ pair.pending.expiry = pair.pending.inserted + this.grace + interval;
26013
+ } else {
26014
+ this.handlePair(pair, now, now + this.grace + interval, now, out);
26015
+ }
26016
+ }
26017
+ }
26018
+ this.dropAdmittedHeld();
26019
+ return out;
26020
+ }
26021
+ previousAdmitted(epoch, path, now) {
26022
+ if (!this.previous || epoch !== this.previous.epoch)
26023
+ return false;
26024
+ const m = this.graceStart.multicast;
26025
+ if (path === "multicast")
26026
+ return m === void 0 || now <= m + this.grace;
26027
+ const starts = [m, this.graceStart.mirror].filter((s) => s !== void 0);
26028
+ return starts.length > 0 && now <= Math.min(...starts) + this.grace;
26029
+ }
26030
+ /** The replay floor this record meets: its path's, or the higher of both from the mirror. */
26031
+ floor(ke, path) {
26032
+ const m = this.highest.multicast.get(ke);
26033
+ if (path === "multicast")
26034
+ return m;
26035
+ const r = this.highest.mirror.get(ke);
26036
+ if (m === void 0)
26037
+ return r;
26038
+ return r === void 0 || m > r ? m : r;
26039
+ }
26040
+ raise(ke, path, mseq) {
26041
+ const h = this.highest[path].get(ke);
26042
+ if (h === void 0 || mseq > h)
26043
+ this.highest[path].set(ke, mseq);
26044
+ }
26045
+ take(path, now) {
26046
+ const b = this.buckets[path];
26047
+ b.tokens = Math.min(BUCKET_DEPTH, b.tokens + (now - b.last) * BUCKET_RATE_PER_MS);
26048
+ b.last = now;
26049
+ if (b.tokens < 1) {
26050
+ b.dropped++;
26051
+ return false;
26052
+ }
26053
+ b.tokens -= 1;
26054
+ return true;
26055
+ }
26056
+ expire(now) {
26057
+ for (const path of ["multicast", "unicast"]) {
26058
+ this.hold[path] = this.hold[path].filter((h) => {
26059
+ if (h.expiry > now)
26060
+ return true;
26061
+ this.holdBytes[path] -= h.datagram.byteLength;
26062
+ this.expired[path]++;
26063
+ return false;
26064
+ });
26065
+ }
26066
+ let keepFrom = null;
26067
+ for (const [d, list] of this.pending) {
26068
+ const live = list.filter((p) => {
26069
+ if (p.expiry > now)
26070
+ return true;
26071
+ if (keepFrom === null) {
26072
+ const age = this.keepPendingAgeMs?.();
26073
+ keepFrom = age === void 0 ? void 0 : now - age;
26074
+ }
26075
+ if (keepFrom !== void 0 && keepFrom !== null && p.expiry > keepFrom)
26076
+ return true;
26077
+ p.pair.pending = void 0;
26078
+ return false;
26079
+ });
26080
+ if (live.length)
26081
+ this.pending.set(d, live);
26082
+ else
26083
+ this.pending.delete(d);
26084
+ }
26085
+ for (const [d, until] of this.admittedUntil)
26086
+ if (until <= now)
26087
+ this.admittedUntil.delete(d);
26088
+ if (this.previous && now > this.previous.deadline)
26089
+ this.previous = null;
26090
+ }
26091
+ /**
26092
+ * Retire verified entries below their arrival path's replay floor, keeping a mirrored entry
26093
+ * while the freshness check would still pass its copy on `manifestPort`.
26094
+ * ponytail: linear scan per record; index by (kid, epoch) if retained sets grow past a few thousand.
26095
+ */
26096
+ prune(now) {
26097
+ const retention = 7e3 + this.maxAuthDelayMs;
26098
+ for (const [id, v] of this.verified) {
26099
+ const h = this.highest[v.path].get(`${v.kid}:${v.epoch}`);
26100
+ const aboveFloor = h === void 0 || v.mseq > h - REPLAY_WINDOW;
26101
+ const fresh = this.cfg.checkFreshness === false ? v.arrival + retention >= now : v.sent * 1e3 + retention >= now;
26102
+ const current = this.current && (v.epoch === this.current.epoch || v.epoch === this.previous?.epoch);
26103
+ if (current && (aboveFloor || v.path === "mirror" && fresh))
26104
+ continue;
26105
+ this.verified.delete(id);
26106
+ }
26107
+ }
26108
+ };
26109
+
23254
26110
  // src/catalog-network-source.ts
23255
26111
  function normalizePort(value) {
23256
26112
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
@@ -23602,11 +26458,12 @@ function resolveCatalogTrackFec(catalog, tracks) {
23602
26458
  }
23603
26459
 
23604
26460
  // src/multicast-manager.ts
23605
- function freezeIngress(tracks) {
26461
+ function freezeIngress(tracks, flow) {
23606
26462
  return Object.freeze({
23607
26463
  tracks: Object.freeze(
23608
26464
  [...tracks].map(({ name, packetId }) => Object.freeze({ name, packetId }))
23609
- )
26465
+ ),
26466
+ ...flow === void 0 ? {} : { flow }
23610
26467
  });
23611
26468
  }
23612
26469
  function sameIdSet(a, b) {
@@ -23636,6 +26493,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23636
26493
  repairsSkippedRttExceedsBudget: 0,
23637
26494
  repairsSkippedPresentationDelayUnavailable: 0,
23638
26495
  repairsSkippedRangeNoAnchor: 0,
26496
+ repairsSkippedGroupCannotComplete: 0,
23639
26497
  lastRepairSkip: null,
23640
26498
  keyframeRepairFetchesSent: 0,
23641
26499
  rangeRepairFetchesSent: 0,
@@ -23720,7 +26578,9 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23720
26578
  var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23721
26579
  "rtt-unmeasured",
23722
26580
  "rtt-exceeds-budget",
23723
- "presentation-delay-unavailable"
26581
+ "presentation-delay-unavailable",
26582
+ "range-no-anchor",
26583
+ "group-cannot-complete"
23724
26584
  ]);
23725
26585
  var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23726
26586
  var GAP_REASONS = {
@@ -23938,7 +26798,7 @@ function altGroupKey(track) {
23938
26798
  }
23939
26799
  function repairTrackNamesBySource(tracks) {
23940
26800
  const bySource = /* @__PURE__ */ new Map();
23941
- const add = (source, repair) => {
26801
+ const add2 = (source, repair) => {
23942
26802
  if (!source || !repair) return;
23943
26803
  const names = bySource.get(source) ?? /* @__PURE__ */ new Set();
23944
26804
  names.add(repair);
@@ -23946,9 +26806,9 @@ function repairTrackNamesBySource(tracks) {
23946
26806
  };
23947
26807
  for (const track of tracks) {
23948
26808
  const repairTrack = typeof track.fec === "object" && track.fec !== null ? track.fec.repairTrack : void 0;
23949
- if (typeof repairTrack === "string") add(track.name, repairTrack);
26809
+ if (typeof repairTrack === "string") add2(track.name, repairTrack);
23950
26810
  if (track.packaging === "fec-repair" && Array.isArray(track.depends) && track.depends.length === 1) {
23951
- add(track.depends[0], track.name);
26811
+ add2(track.depends[0], track.name);
23952
26812
  }
23953
26813
  }
23954
26814
  return bySource;
@@ -23958,6 +26818,10 @@ var MulticastManager = class {
23958
26818
  #router;
23959
26819
  #hostMfuTimeoutMs;
23960
26820
  #transport;
26821
+ /** The protected flow of the current join and its manifestPort subscription. */
26822
+ #provenanceJoin = null;
26823
+ #onFailback = null;
26824
+ #failbackHooked = false;
23961
26825
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
23962
26826
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
23963
26827
  #repairReleases = /* @__PURE__ */ new Map();
@@ -24010,10 +26874,6 @@ var MulticastManager = class {
24010
26874
  reassemblyPolicy: options?.reassemblyPolicy,
24011
26875
  reassembler: options?.reassembler,
24012
26876
  maxBufferedMfus: options?.maxBufferedMfus,
24013
- manifestVerifier: options?.manifestVerifier,
24014
- manifestVerifierOwnership: options?.manifestVerifierOwnership,
24015
- resolveManifestIdentity: options?.resolveManifestIdentity,
24016
- resolveManifestIdentityForRoute: options?.resolveManifestIdentityForRoute,
24017
26877
  // The router has reset its own state for the stream; reset the rest.
24018
26878
  onPublisherRestart: (packetId, catalogTrackName) => {
24019
26879
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
@@ -24060,7 +26920,7 @@ var MulticastManager = class {
24060
26920
  });
24061
26921
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
24062
26922
  this.#transport = new MulticastTransport((packet, ingress) => {
24063
- this.#router.feedPacket(packet, "multicast", void 0, ingress);
26923
+ this.#router.feedPacket(packet, "multicast", ingress);
24064
26924
  });
24065
26925
  this.#transport.onDelivery((delivery) => {
24066
26926
  this.#fec.setMulticastSymbolDelivery(delivery);
@@ -24153,6 +27013,10 @@ var MulticastManager = class {
24153
27013
  get router() {
24154
27014
  return this.#router;
24155
27015
  }
27016
+ /** Repair FETCH wiring (wireRepairFetch): this manager can request unicast repair. */
27017
+ setUnicastRepair(enabled) {
27018
+ this.#router.setUnicastRepair(enabled);
27019
+ }
24156
27020
  get transport() {
24157
27021
  return this.#transport;
24158
27022
  }
@@ -24563,8 +27427,35 @@ var MulticastManager = class {
24563
27427
  onTakeover(cb) {
24564
27428
  this.#transport.onTakeover(cb);
24565
27429
  }
27430
+ /** Failback un-protects the join's flow (7.2.7 failover), so the fallback's MoQ packets are read. */
24566
27431
  onFailback(cb) {
24567
- this.#transport.onFailback(cb);
27432
+ this.#onFailback = cb;
27433
+ this.#hookFailback();
27434
+ }
27435
+ /**
27436
+ * Install the manager's own failback listener on the media transport, which
27437
+ * arms its silence watchdog: a protected join un-protects on failover even
27438
+ * when no player listens, else its tracks' MoQ copies stay dropped.
27439
+ */
27440
+ #hookFailback() {
27441
+ if (this.#failbackHooked) return;
27442
+ this.#failbackHooked = true;
27443
+ this.#transport.onFailback((reason) => {
27444
+ const joined = this.#provenanceJoin;
27445
+ if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
27446
+ this.#onFailback?.(reason);
27447
+ });
27448
+ }
27449
+ /**
27450
+ * A protected join's handoff (draft -01 7.2.7), before `onTakeover`: its
27451
+ * first admitted datagram. MoQ copies of the flow's tracks the router still
27452
+ * held unadmitted are discarded, and later ones are dropped. Fires again
27453
+ * after a failback once multicast resumes.
27454
+ */
27455
+ onProtected(cb) {
27456
+ this.#router.onProvenanceFlowProtected(cb && ((flow) => {
27457
+ if (this.#provenanceJoin?.flow === flow) cb();
27458
+ }));
24568
27459
  }
24569
27460
  /** See MulticastTransport.onDataPlaneLive: the join's first accepted packet. */
24570
27461
  onDataPlaneLive(cb) {
@@ -24580,6 +27471,12 @@ var MulticastManager = class {
24580
27471
  return MulticastTransport.isAvailable();
24581
27472
  }
24582
27473
  async join(config) {
27474
+ const provenanceFlow = config.provenance?.flow;
27475
+ if (provenanceFlow !== void 0 && ((config.sourceAddress ?? config.senderAddress) !== provenanceFlow.source || config.groupAddress !== provenanceFlow.groupAddress || config.port !== provenanceFlow.port)) {
27476
+ throw new RangeError(
27477
+ "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
27478
+ );
27479
+ }
24583
27480
  const staged = this.#renditionSwitch;
24584
27481
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
24585
27482
  this.configureFec(config);
@@ -24587,16 +27484,21 @@ var MulticastManager = class {
24587
27484
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
24588
27485
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
24589
27486
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
24590
- const ingress = ingressTracks === void 0 ? void 0 : {
27487
+ this.#releaseProvenanceJoin();
27488
+ const provenance = config.provenance;
27489
+ const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
27490
+ const ingress = protectedTracks === void 0 ? void 0 : {
24591
27491
  tracks: Object.freeze(
24592
- ingressTracks.map(
27492
+ protectedTracks.map(
24593
27493
  ({ name, packetId }) => Object.freeze({ name, packetId })
24594
27494
  )
24595
- )
27495
+ ),
27496
+ ...provenance === void 0 ? {} : { flow: multicastProvenanceFlowKey(provenance.flow) }
24596
27497
  };
24597
27498
  const amtRelay = config.amtRelay;
24598
27499
  const transportConfig = {
24599
27500
  sourceAddress: config.sourceAddress,
27501
+ senderAddress: config.senderAddress,
24600
27502
  groupAddress: config.groupAddress,
24601
27503
  port: config.port,
24602
27504
  mode: config.mode,
@@ -24623,7 +27525,61 @@ var MulticastManager = class {
24623
27525
  packetIds: config.packetIds,
24624
27526
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
24625
27527
  };
24626
- return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
27528
+ if (provenance !== void 0) this.#joinProvenance(provenance, ingress, transportConfig);
27529
+ const protectedJoin = this.#provenanceJoin;
27530
+ const joined = await (ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress));
27531
+ if (!joined && protectedJoin !== null && this.#provenanceJoin === protectedJoin) this.#releaseProvenanceJoin();
27532
+ return joined;
27533
+ }
27534
+ /**
27535
+ * Register the protected flow and subscribe its `manifestPort` on the same
27536
+ * `(S, G)` with its own listener (draft -01 7.2.7), so records reach the
27537
+ * flow's receiver and media datagrams are held until one admits them. A
27538
+ * manifest subscription that fails to join admits nothing: the media is
27539
+ * held and expires, never read unauthenticated.
27540
+ */
27541
+ #joinProvenance(provenance, ingress, media) {
27542
+ const { flow, auth } = provenance;
27543
+ const receiver = new BcProvenanceV2Receiver({
27544
+ ...provenance.receiver,
27545
+ // The caller's ctx when it passes one, else the catalog's: an explicit
27546
+ // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
27547
+ catalogCtx: provenance.receiver?.catalogCtx ?? flow.ctx,
27548
+ endpoint: {
27549
+ sourceAddress: flow.source,
27550
+ groupAddress: flow.groupAddress,
27551
+ port: flow.port,
27552
+ manifestPort: flow.manifestPort,
27553
+ streamId: flow.streamId
27554
+ },
27555
+ keys: auth.keys,
27556
+ minEpoch: auth.minEpoch,
27557
+ bandwidth: flow.bandwidth,
27558
+ maxAuthDelayMs: flow.maxAuthDelayMs,
27559
+ manifestTimerMs: flow.manifestTimerMs
27560
+ });
27561
+ this.#router.registerProvenanceFlow(ingress, receiver);
27562
+ this.#hookFailback();
27563
+ const manifest = new MulticastTransport((record) => {
27564
+ if (this.#provenanceJoin?.manifest === manifest) {
27565
+ this.#router.feedProvenanceRecord(ingress.flow, record, "multicast");
27566
+ }
27567
+ });
27568
+ this.#provenanceJoin = { flow: ingress.flow, manifest };
27569
+ const { packetIds: _packetIds, tracks: _tracks, ...path } = media;
27570
+ void manifest.join({ ...path, port: flow.manifestPort }).then((joined) => {
27571
+ if (!joined && this.#provenanceJoin?.manifest === manifest) {
27572
+ console.warn(`[MulticastManager] manifestPort ${flow.groupAddress}:${flow.manifestPort} not joined`, manifest.lastJoinOutcome);
27573
+ }
27574
+ });
27575
+ }
27576
+ /** Un-protect: drop the flow's hold queues (no expiry counted) and leave its manifestPort. */
27577
+ #releaseProvenanceJoin() {
27578
+ const joined = this.#provenanceJoin;
27579
+ if (joined === null) return;
27580
+ this.#provenanceJoin = null;
27581
+ joined.manifest.dispose();
27582
+ this.#router.releaseProvenanceFlow(joined.flow);
24627
27583
  }
24628
27584
  /**
24629
27585
  * Join the selected rung's dedicated repair groups beside the media join
@@ -24653,10 +27609,11 @@ var MulticastManager = class {
24653
27609
  this.#applyRepairOwners(repairOwners);
24654
27610
  for (const endpoint of endpoints) {
24655
27611
  const ingress = {
24656
- tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
27612
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
27613
+ ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24657
27614
  };
24658
27615
  const onPacket = (packet) => {
24659
- if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
27616
+ if (!released) this.#router.feedPacket(packet, "multicast", ingress);
24660
27617
  };
24661
27618
  const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
24662
27619
  if (typeof provider === "function") {
@@ -24794,7 +27751,7 @@ var MulticastManager = class {
24794
27751
  for (const track of [...live.tracks, ...request.tracks]) {
24795
27752
  stagedTracks.set(`${track.packetId}\0${track.name}`, track);
24796
27753
  }
24797
- const stagedIngress = freezeIngress(stagedTracks.values());
27754
+ const stagedIngress = freezeIngress(stagedTracks.values(), live.flow);
24798
27755
  const stagedPacketIds = committedPacketIds === void 0 || livePacketIds === null ? null : /* @__PURE__ */ new Set([...livePacketIds, ...committedPacketIds]);
24799
27756
  const widened = stagedPacketIds !== null && !sameIdSet(stagedPacketIds, livePacketIds);
24800
27757
  const active = {
@@ -24805,7 +27762,7 @@ var MulticastManager = class {
24805
27762
  liveIngress: live,
24806
27763
  livePacketIds,
24807
27764
  widened,
24808
- committedIngress: freezeIngress(request.tracks),
27765
+ committedIngress: freezeIngress(request.tracks, live.flow),
24809
27766
  committedPacketIds,
24810
27767
  router: null,
24811
27768
  state: "staged"
@@ -24818,7 +27775,7 @@ var MulticastManager = class {
24818
27775
  let widening;
24819
27776
  try {
24820
27777
  if (widened) widening = this.#transport.setPacketIds([...stagedPacketIds]);
24821
- this.#transport.setContext(stagedIngress);
27778
+ this.#setSwitchIngress(stagedIngress);
24822
27779
  } catch (error) {
24823
27780
  active.router.cancel();
24824
27781
  throw error;
@@ -24839,6 +27796,11 @@ var MulticastManager = class {
24839
27796
  }
24840
27797
  };
24841
27798
  }
27799
+ /** Route a switch's ingress and keep a protected flow's registration in step (7.2.7). */
27800
+ #setSwitchIngress(ingress) {
27801
+ this.#transport.setContext(ingress);
27802
+ if (ingress.flow !== void 0) this.#router.updateProvenanceFlowIngress({ ...ingress, flow: ingress.flow });
27803
+ }
24842
27804
  /** The router committed the staged switch (it already retired `from`). */
24843
27805
  #commitRenditionSwitch(active, commit) {
24844
27806
  if (this.#renditionSwitch !== active) return;
@@ -24846,7 +27808,7 @@ var MulticastManager = class {
24846
27808
  active.state = "committed";
24847
27809
  active.router = null;
24848
27810
  if (this.#transport.joined) {
24849
- this.#transport.setContext(active.committedIngress);
27811
+ this.#setSwitchIngress(active.committedIngress);
24850
27812
  if (active.committedPacketIds !== void 0) {
24851
27813
  this.#transport.setPacketIds(active.committedPacketIds).catch((error) => {
24852
27814
  console.warn(
@@ -24882,7 +27844,7 @@ var MulticastManager = class {
24882
27844
  active.router = null;
24883
27845
  if (restore) {
24884
27846
  if (this.#transport.joined) {
24885
- this.#transport.setContext(active.liveIngress);
27847
+ this.#setSwitchIngress(active.liveIngress);
24886
27848
  if (active.widened && active.livePacketIds !== null) {
24887
27849
  this.#transport.setPacketIds([...active.livePacketIds]).catch((error) => {
24888
27850
  console.warn(
@@ -25268,6 +28230,7 @@ var MulticastManager = class {
25268
28230
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
25269
28231
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
25270
28232
  else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
28233
+ else if (reason === "group-cannot-complete") stats.repairsSkippedGroupCannotComplete++;
25271
28234
  else stats.repairsSkippedPresentationDelayUnavailable++;
25272
28235
  stats.lastRepairSkip = {
25273
28236
  reason,
@@ -25463,11 +28426,15 @@ var MulticastManager = class {
25463
28426
  this.#trackResetObservers.clear();
25464
28427
  this.#repairLifecycleObservers.clear();
25465
28428
  this.#transport.dispose();
28429
+ this.#releaseProvenanceJoin();
25466
28430
  for (const release of [...this.#repairReleases.keys()]) release();
25467
28431
  this.#router.dispose();
25468
28432
  this.#fec.dispose();
25469
28433
  }
25470
28434
  };
28435
+ function multicastProvenanceFlowKey(flow) {
28436
+ return JSON.stringify([flow.source, flow.groupAddress, flow.port]);
28437
+ }
25471
28438
 
25472
28439
  // src/fec-worker-setup.ts
25473
28440
  async function setupFecWorkerForTrack(opts) {
@@ -27279,6 +30246,9 @@ var MmtpFecSession = class {
27279
30246
  /** The newest SS_ID when the remembered SS_IDs were last pruned. */
27280
30247
  #prunedAt;
27281
30248
  #repairPacketId;
30249
+ #newestSource;
30250
+ #heldLayers;
30251
+ #anchorHorizon;
27282
30252
  #stats = {
27283
30253
  sourceSymbols: 0,
27284
30254
  repairSymbols: 0,
@@ -27291,11 +30261,12 @@ var MmtpFecSession = class {
27291
30261
  dropped: {},
27292
30262
  sourceSymbolsByPath: { moq: 0, multicast: 0 },
27293
30263
  repairSymbolsByPath: { moq: 0, multicast: 0 },
27294
- mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
30264
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
30265
+ failClosed: null
27295
30266
  };
27296
30267
  /**
27297
30268
  * @throws when the catalog block lacks or misstates a field the session
27298
- * needs: the block profile, K, T, `interleaveDepthMs` or
30269
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
27299
30270
  * `reorderToleranceMs`. None is defaulted.
27300
30271
  */
27301
30272
  constructor(config) {
@@ -27309,6 +30280,7 @@ var MmtpFecSession = class {
27309
30280
  }
27310
30281
  this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
27311
30282
  this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
30283
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
27312
30284
  this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
27313
30285
  const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
27314
30286
  const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
@@ -27316,6 +30288,18 @@ var MmtpFecSession = class {
27316
30288
  fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
27317
30289
  interleaveDepthMs
27318
30290
  );
30291
+ this.#heldLayers = new HeldLayerAdmission(
30292
+ config.repairLayers ?? [
30293
+ {
30294
+ layer: 0,
30295
+ repairTrackName: typeof fec.repairTrack === "string" ? fec.repairTrack : "",
30296
+ rsIdOffset: 0,
30297
+ repairSymbols: this.repairSymbols
30298
+ }
30299
+ ],
30300
+ config.heldLayers
30301
+ );
30302
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
27319
30303
  if (typeof config.Decoder !== "function") {
27320
30304
  throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
27321
30305
  }
@@ -27338,7 +30322,8 @@ var MmtpFecSession = class {
27338
30322
  dropped: { ...this.#stats.dropped },
27339
30323
  sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
27340
30324
  repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
27341
- mixedPath: { ...this.#stats.mixedPath }
30325
+ mixedPath: { ...this.#stats.mixedPath },
30326
+ failClosed: this.#stats.failClosed && { ...this.#stats.failClosed }
27342
30327
  };
27343
30328
  }
27344
30329
  /**
@@ -27363,6 +30348,7 @@ var MmtpFecSession = class {
27363
30348
  this.#stats.sourceSymbols++;
27364
30349
  this.#stats.sourceSymbolsByPath[path]++;
27365
30350
  this.#noteNewest(ssId);
30351
+ if (this.#newestSource === void 0 || serial32Precedes(this.#newestSource, ssId)) this.#newestSource = ssId;
27366
30352
  const start = this.#blockStartOf(ssId);
27367
30353
  const block = start === void 0 ? void 0 : this.#blocks.get(start);
27368
30354
  if (block) {
@@ -27391,14 +30377,17 @@ var MmtpFecSession = class {
27391
30377
  * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
27392
30378
  * 23008-1 C.5.3). A repair track carries one repair flow, so the first
27393
30379
  * repair packet fixes its packet ID and a packet of any other is refused.
27394
- * `path` is where it was received, as for addSource().
30380
+ * `path` is where it was received, as for addSource(). `repairTrackName`
30381
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
30382
+ * track the layers do not list is refused as `repair:unlisted-track`.
27395
30383
  *
27396
30384
  * @returns the protected packets this repair symbol recovered, as for
27397
30385
  * addSource().
27398
30386
  */
27399
- addRepair(packet, path = "moq") {
30387
+ addRepair(packet, path = "moq", repairTrackName) {
27400
30388
  const decoder = this.#decoder;
27401
30389
  if (!decoder) return this.#drop("repair:released");
30390
+ if (this.#stats.failClosed) return this.#drop("repair:fail-closed");
27402
30391
  const pathBit = PATH_BITS[path];
27403
30392
  if (!pathBit) return this.#drop("repair:unknown-path");
27404
30393
  let header;
@@ -27419,6 +30408,18 @@ var MmtpFecSession = class {
27419
30408
  if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
27420
30409
  return this.#drop("repair:rs-block-length");
27421
30410
  }
30411
+ const verdict = this.#heldLayers.admit(
30412
+ repairTrackName,
30413
+ frame.ssStart,
30414
+ frame.rsbLength,
30415
+ this.#anchorHorizon,
30416
+ this.#newestSource
30417
+ );
30418
+ if (verdict === "discard") return this.#drop("repair:unlisted-track");
30419
+ if (verdict !== void 0) {
30420
+ this.#stats.failClosed = verdict;
30421
+ return this.#drop("repair:fail-closed");
30422
+ }
27422
30423
  const start = frame.ssStart;
27423
30424
  let block = this.#blocks.get(start);
27424
30425
  if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
@@ -27638,6 +30639,7 @@ function wireRepairFetch(mc, opts) {
27638
30639
  if (opts.rangeTransport !== void 0 && (typeof opts.repairEpochReference !== "function" || !mc.onUndelimitedLoss || !mc.closeIsoHoles)) {
27639
30640
  throw new Error("[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses");
27640
30641
  }
30642
+ mc.setUnicastRepair?.(true);
27641
30643
  const entries = /* @__PURE__ */ new Map();
27642
30644
  const warnedNoTarget = /* @__PURE__ */ new Set();
27643
30645
  let disposed = false;
@@ -27689,12 +30691,13 @@ function wireRepairFetch(mc, opts) {
27689
30691
  const admit = (entry, now) => {
27690
30692
  const budgetMs = entry.deadlineAt - now;
27691
30693
  const rttMs = readRtt();
27692
- if (rttMs !== null && rttMs < budgetMs) return rttMs;
30694
+ const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
30695
+ if (reason === null) return rttMs;
27693
30696
  retire(entry);
27694
30697
  releaseHold(entry);
27695
30698
  clearEntry(entry);
27696
30699
  mc.noteRepairSkipped(
27697
- rttMs === null ? "rtt-unmeasured" : "rtt-exceeds-budget",
30700
+ reason,
27698
30701
  { rttMs, budgetMs, priority: entry.priority },
27699
30702
  entry.sbn,
27700
30703
  entry.packetId,
@@ -28123,6 +31126,7 @@ function wireRepairFetch(mc, opts) {
28123
31126
  }
28124
31127
  return () => {
28125
31128
  disposed = true;
31129
+ mc.setUnicastRepair?.(false);
28126
31130
  removeResetObserver();
28127
31131
  removeLifecycleObserver();
28128
31132
  for (const entry of [...entries.values()]) {
@@ -28332,4 +31336,16 @@ export {
28332
31336
  wireRepairFetch,
28333
31337
  wrapAdtsFrame
28334
31338
  };
31339
+ /*! Bundled license information:
31340
+
31341
+ @noble/hashes/esm/utils.js:
31342
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
31343
+
31344
+ @noble/curves/esm/utils.js:
31345
+ @noble/curves/esm/abstract/modular.js:
31346
+ @noble/curves/esm/abstract/curve.js:
31347
+ @noble/curves/esm/abstract/edwards.js:
31348
+ @noble/curves/esm/ed25519.js:
31349
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
31350
+ */
28335
31351
  //# sourceMappingURL=browser-runtime.js.map