@blockcast/mmt-container 0.4.1 → 0.5.0-main.34c7b9c2cfa0

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