@continuonai/rcan-ts 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17,15 +17,15 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
21
21
  // If the importer is in node compatibility mode or this is not an ESM
22
22
  // file that has been converted to a CommonJS file using a Babel-
23
23
  // compatible transform (i.e. "__esModule" has not been set), then set
24
24
  // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
25
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
26
+ mod2
27
27
  ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
29
29
 
30
30
  // src/index.ts
31
31
  var index_exports = {};
@@ -109,15 +109,20 @@ __export(index_exports, {
109
109
  clientAllowsTool: () => clientAllowsTool,
110
110
  decodeBleFrames: () => decodeBleFrames,
111
111
  decodeCompact: () => decodeCompact,
112
+ decodeHybridSig: () => decodeHybridSig,
112
113
  decodeMinimal: () => decodeMinimal,
114
+ decodeMlDsaPublicKeyJwk: () => decodeMlDsaPublicKeyJwk,
113
115
  encodeBleFrames: () => encodeBleFrames,
114
116
  encodeCompact: () => encodeCompact,
117
+ encodeHybridSig: () => encodeHybridSig,
115
118
  encodeMinimal: () => encodeMinimal,
119
+ encodeMlDsaPublicKeyJwk: () => encodeMlDsaPublicKeyJwk,
116
120
  extractIdentityFromJwt: () => extractIdentityFromJwt,
117
121
  extractLoaFromJwt: () => extractLoaFromJwt,
118
122
  extractRoleFromJwt: () => extractRoleFromJwt,
119
123
  fetchCanonicalSchema: () => fetchCanonicalSchema,
120
124
  fetchRRFRevocations: () => fetchRRFRevocations,
125
+ generateMlDsaKeypair: () => generateMlDsaKeypair,
121
126
  isAuthorityRequestValid: () => isAuthorityRequestValid,
122
127
  isM2mTrustedRevoked: () => isM2mTrustedRevoked,
123
128
  isPreemptedBy: () => isPreemptedBy,
@@ -154,7 +159,9 @@ __export(index_exports, {
154
159
  parseM2mTrustedToken: () => parseM2mTrustedToken,
155
160
  roleFromJwtLevel: () => roleFromJwtLevel,
156
161
  selectTransport: () => selectTransport,
162
+ signHybrid: () => signHybrid,
157
163
  signMessage: () => signMessage,
164
+ signMlDsa: () => signMlDsa,
158
165
  validateAuthorityAccess: () => validateAuthorityAccess,
159
166
  validateCompetitionScope: () => validateCompetitionScope,
160
167
  validateConfig: () => validateConfig,
@@ -176,9 +183,11 @@ __export(index_exports, {
176
183
  validateURI: () => validateURI,
177
184
  validateV22DelegationChain: () => validateDelegationChain2,
178
185
  validateVersionCompat: () => validateVersionCompat,
186
+ verifyHybrid: () => verifyHybrid,
179
187
  verifyM2mTrustedToken: () => verifyM2mTrustedToken,
180
188
  verifyM2mTrustedTokenClaims: () => verifyM2mTrustedTokenClaims,
181
189
  verifyMessage: () => verifyMessage,
190
+ verifyMlDsa: () => verifyMlDsa,
182
191
  verifyPQSignature: () => verifyPQSignature,
183
192
  verifyV22MediaChunkHash: () => verifyMediaChunkHash
184
193
  });
@@ -533,6 +542,1708 @@ function validateDelegationChain(chain) {
533
542
  }
534
543
 
535
544
  // src/crypto.ts
545
+ var import_ml_dsa = require("@noble/post-quantum/ml-dsa.js");
546
+
547
+ // node_modules/@noble/hashes/utils.js
548
+ function isBytes(a) {
549
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
550
+ }
551
+ function anumber(n, title = "") {
552
+ if (!Number.isSafeInteger(n) || n < 0) {
553
+ const prefix = title && `"${title}" `;
554
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
555
+ }
556
+ }
557
+ function abytes(value, length, title = "") {
558
+ const bytes = isBytes(value);
559
+ const len = value?.length;
560
+ const needsLen = length !== void 0;
561
+ if (!bytes || needsLen && len !== length) {
562
+ const prefix = title && `"${title}" `;
563
+ const ofLen = needsLen ? ` of length ${length}` : "";
564
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
565
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
566
+ }
567
+ return value;
568
+ }
569
+ function aexists(instance, checkFinished = true) {
570
+ if (instance.destroyed)
571
+ throw new Error("Hash instance has been destroyed");
572
+ if (checkFinished && instance.finished)
573
+ throw new Error("Hash#digest() has already been called");
574
+ }
575
+ function aoutput(out, instance) {
576
+ abytes(out, void 0, "digestInto() output");
577
+ const min = instance.outputLen;
578
+ if (out.length < min) {
579
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
580
+ }
581
+ }
582
+ function clean(...arrays) {
583
+ for (let i = 0; i < arrays.length; i++) {
584
+ arrays[i].fill(0);
585
+ }
586
+ }
587
+ function createView(arr) {
588
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
589
+ }
590
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
591
+ // @ts-ignore
592
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
593
+ ))();
594
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
595
+ function bytesToHex(bytes) {
596
+ abytes(bytes);
597
+ if (hasHexBuiltin)
598
+ return bytes.toHex();
599
+ let hex = "";
600
+ for (let i = 0; i < bytes.length; i++) {
601
+ hex += hexes[bytes[i]];
602
+ }
603
+ return hex;
604
+ }
605
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
606
+ function asciiToBase16(ch) {
607
+ if (ch >= asciis._0 && ch <= asciis._9)
608
+ return ch - asciis._0;
609
+ if (ch >= asciis.A && ch <= asciis.F)
610
+ return ch - (asciis.A - 10);
611
+ if (ch >= asciis.a && ch <= asciis.f)
612
+ return ch - (asciis.a - 10);
613
+ return;
614
+ }
615
+ function hexToBytes(hex) {
616
+ if (typeof hex !== "string")
617
+ throw new Error("hex string expected, got " + typeof hex);
618
+ if (hasHexBuiltin)
619
+ return Uint8Array.fromHex(hex);
620
+ const hl = hex.length;
621
+ const al = hl / 2;
622
+ if (hl % 2)
623
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
624
+ const array = new Uint8Array(al);
625
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
626
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
627
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
628
+ if (n1 === void 0 || n2 === void 0) {
629
+ const char = hex[hi] + hex[hi + 1];
630
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
631
+ }
632
+ array[ai] = n1 * 16 + n2;
633
+ }
634
+ return array;
635
+ }
636
+ function concatBytes(...arrays) {
637
+ let sum = 0;
638
+ for (let i = 0; i < arrays.length; i++) {
639
+ const a = arrays[i];
640
+ abytes(a);
641
+ sum += a.length;
642
+ }
643
+ const res = new Uint8Array(sum);
644
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
645
+ const a = arrays[i];
646
+ res.set(a, pad);
647
+ pad += a.length;
648
+ }
649
+ return res;
650
+ }
651
+ function createHasher(hashCons, info = {}) {
652
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
653
+ const tmp = hashCons(void 0);
654
+ hashC.outputLen = tmp.outputLen;
655
+ hashC.blockLen = tmp.blockLen;
656
+ hashC.create = (opts) => hashCons(opts);
657
+ Object.assign(hashC, info);
658
+ return Object.freeze(hashC);
659
+ }
660
+ function randomBytes(bytesLength = 32) {
661
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
662
+ if (typeof cr?.getRandomValues !== "function")
663
+ throw new Error("crypto.getRandomValues must be defined");
664
+ return cr.getRandomValues(new Uint8Array(bytesLength));
665
+ }
666
+ var oidNist = (suffix) => ({
667
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
668
+ });
669
+
670
+ // node_modules/@noble/hashes/_md.js
671
+ var HashMD = class {
672
+ blockLen;
673
+ outputLen;
674
+ padOffset;
675
+ isLE;
676
+ // For partial updates less than block size
677
+ buffer;
678
+ view;
679
+ finished = false;
680
+ length = 0;
681
+ pos = 0;
682
+ destroyed = false;
683
+ constructor(blockLen, outputLen, padOffset, isLE) {
684
+ this.blockLen = blockLen;
685
+ this.outputLen = outputLen;
686
+ this.padOffset = padOffset;
687
+ this.isLE = isLE;
688
+ this.buffer = new Uint8Array(blockLen);
689
+ this.view = createView(this.buffer);
690
+ }
691
+ update(data) {
692
+ aexists(this);
693
+ abytes(data);
694
+ const { view, buffer, blockLen } = this;
695
+ const len = data.length;
696
+ for (let pos = 0; pos < len; ) {
697
+ const take = Math.min(blockLen - this.pos, len - pos);
698
+ if (take === blockLen) {
699
+ const dataView = createView(data);
700
+ for (; blockLen <= len - pos; pos += blockLen)
701
+ this.process(dataView, pos);
702
+ continue;
703
+ }
704
+ buffer.set(data.subarray(pos, pos + take), this.pos);
705
+ this.pos += take;
706
+ pos += take;
707
+ if (this.pos === blockLen) {
708
+ this.process(view, 0);
709
+ this.pos = 0;
710
+ }
711
+ }
712
+ this.length += data.length;
713
+ this.roundClean();
714
+ return this;
715
+ }
716
+ digestInto(out) {
717
+ aexists(this);
718
+ aoutput(out, this);
719
+ this.finished = true;
720
+ const { buffer, view, blockLen, isLE } = this;
721
+ let { pos } = this;
722
+ buffer[pos++] = 128;
723
+ clean(this.buffer.subarray(pos));
724
+ if (this.padOffset > blockLen - pos) {
725
+ this.process(view, 0);
726
+ pos = 0;
727
+ }
728
+ for (let i = pos; i < blockLen; i++)
729
+ buffer[i] = 0;
730
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
731
+ this.process(view, 0);
732
+ const oview = createView(out);
733
+ const len = this.outputLen;
734
+ if (len % 4)
735
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
736
+ const outLen = len / 4;
737
+ const state = this.get();
738
+ if (outLen > state.length)
739
+ throw new Error("_sha2: outputLen bigger than state");
740
+ for (let i = 0; i < outLen; i++)
741
+ oview.setUint32(4 * i, state[i], isLE);
742
+ }
743
+ digest() {
744
+ const { buffer, outputLen } = this;
745
+ this.digestInto(buffer);
746
+ const res = buffer.slice(0, outputLen);
747
+ this.destroy();
748
+ return res;
749
+ }
750
+ _cloneInto(to) {
751
+ to ||= new this.constructor();
752
+ to.set(...this.get());
753
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
754
+ to.destroyed = destroyed;
755
+ to.finished = finished;
756
+ to.length = length;
757
+ to.pos = pos;
758
+ if (length % blockLen)
759
+ to.buffer.set(buffer);
760
+ return to;
761
+ }
762
+ clone() {
763
+ return this._cloneInto();
764
+ }
765
+ };
766
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
767
+ 1779033703,
768
+ 4089235720,
769
+ 3144134277,
770
+ 2227873595,
771
+ 1013904242,
772
+ 4271175723,
773
+ 2773480762,
774
+ 1595750129,
775
+ 1359893119,
776
+ 2917565137,
777
+ 2600822924,
778
+ 725511199,
779
+ 528734635,
780
+ 4215389547,
781
+ 1541459225,
782
+ 327033209
783
+ ]);
784
+
785
+ // node_modules/@noble/hashes/_u64.js
786
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
787
+ var _32n = /* @__PURE__ */ BigInt(32);
788
+ function fromBig(n, le = false) {
789
+ if (le)
790
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
791
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
792
+ }
793
+ function split(lst, le = false) {
794
+ const len = lst.length;
795
+ let Ah = new Uint32Array(len);
796
+ let Al = new Uint32Array(len);
797
+ for (let i = 0; i < len; i++) {
798
+ const { h, l } = fromBig(lst[i], le);
799
+ [Ah[i], Al[i]] = [h, l];
800
+ }
801
+ return [Ah, Al];
802
+ }
803
+ var shrSH = (h, _l, s) => h >>> s;
804
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
805
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
806
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
807
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
808
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
809
+ function add(Ah, Al, Bh, Bl) {
810
+ const l = (Al >>> 0) + (Bl >>> 0);
811
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
812
+ }
813
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
814
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
815
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
816
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
817
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
818
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
819
+
820
+ // node_modules/@noble/hashes/sha2.js
821
+ var K512 = /* @__PURE__ */ (() => split([
822
+ "0x428a2f98d728ae22",
823
+ "0x7137449123ef65cd",
824
+ "0xb5c0fbcfec4d3b2f",
825
+ "0xe9b5dba58189dbbc",
826
+ "0x3956c25bf348b538",
827
+ "0x59f111f1b605d019",
828
+ "0x923f82a4af194f9b",
829
+ "0xab1c5ed5da6d8118",
830
+ "0xd807aa98a3030242",
831
+ "0x12835b0145706fbe",
832
+ "0x243185be4ee4b28c",
833
+ "0x550c7dc3d5ffb4e2",
834
+ "0x72be5d74f27b896f",
835
+ "0x80deb1fe3b1696b1",
836
+ "0x9bdc06a725c71235",
837
+ "0xc19bf174cf692694",
838
+ "0xe49b69c19ef14ad2",
839
+ "0xefbe4786384f25e3",
840
+ "0x0fc19dc68b8cd5b5",
841
+ "0x240ca1cc77ac9c65",
842
+ "0x2de92c6f592b0275",
843
+ "0x4a7484aa6ea6e483",
844
+ "0x5cb0a9dcbd41fbd4",
845
+ "0x76f988da831153b5",
846
+ "0x983e5152ee66dfab",
847
+ "0xa831c66d2db43210",
848
+ "0xb00327c898fb213f",
849
+ "0xbf597fc7beef0ee4",
850
+ "0xc6e00bf33da88fc2",
851
+ "0xd5a79147930aa725",
852
+ "0x06ca6351e003826f",
853
+ "0x142929670a0e6e70",
854
+ "0x27b70a8546d22ffc",
855
+ "0x2e1b21385c26c926",
856
+ "0x4d2c6dfc5ac42aed",
857
+ "0x53380d139d95b3df",
858
+ "0x650a73548baf63de",
859
+ "0x766a0abb3c77b2a8",
860
+ "0x81c2c92e47edaee6",
861
+ "0x92722c851482353b",
862
+ "0xa2bfe8a14cf10364",
863
+ "0xa81a664bbc423001",
864
+ "0xc24b8b70d0f89791",
865
+ "0xc76c51a30654be30",
866
+ "0xd192e819d6ef5218",
867
+ "0xd69906245565a910",
868
+ "0xf40e35855771202a",
869
+ "0x106aa07032bbd1b8",
870
+ "0x19a4c116b8d2d0c8",
871
+ "0x1e376c085141ab53",
872
+ "0x2748774cdf8eeb99",
873
+ "0x34b0bcb5e19b48a8",
874
+ "0x391c0cb3c5c95a63",
875
+ "0x4ed8aa4ae3418acb",
876
+ "0x5b9cca4f7763e373",
877
+ "0x682e6ff3d6b2b8a3",
878
+ "0x748f82ee5defb2fc",
879
+ "0x78a5636f43172f60",
880
+ "0x84c87814a1f0ab72",
881
+ "0x8cc702081a6439ec",
882
+ "0x90befffa23631e28",
883
+ "0xa4506cebde82bde9",
884
+ "0xbef9a3f7b2c67915",
885
+ "0xc67178f2e372532b",
886
+ "0xca273eceea26619c",
887
+ "0xd186b8c721c0c207",
888
+ "0xeada7dd6cde0eb1e",
889
+ "0xf57d4f7fee6ed178",
890
+ "0x06f067aa72176fba",
891
+ "0x0a637dc5a2c898a6",
892
+ "0x113f9804bef90dae",
893
+ "0x1b710b35131c471b",
894
+ "0x28db77f523047d84",
895
+ "0x32caab7b40c72493",
896
+ "0x3c9ebe0a15c9bebc",
897
+ "0x431d67c49c100d4c",
898
+ "0x4cc5d4becb3e42b6",
899
+ "0x597f299cfc657e2a",
900
+ "0x5fcb6fab3ad6faec",
901
+ "0x6c44198c4a475817"
902
+ ].map((n) => BigInt(n))))();
903
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
904
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
905
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
906
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
907
+ var SHA2_64B = class extends HashMD {
908
+ constructor(outputLen) {
909
+ super(128, outputLen, 16, false);
910
+ }
911
+ // prettier-ignore
912
+ get() {
913
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
914
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
915
+ }
916
+ // prettier-ignore
917
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
918
+ this.Ah = Ah | 0;
919
+ this.Al = Al | 0;
920
+ this.Bh = Bh | 0;
921
+ this.Bl = Bl | 0;
922
+ this.Ch = Ch | 0;
923
+ this.Cl = Cl | 0;
924
+ this.Dh = Dh | 0;
925
+ this.Dl = Dl | 0;
926
+ this.Eh = Eh | 0;
927
+ this.El = El | 0;
928
+ this.Fh = Fh | 0;
929
+ this.Fl = Fl | 0;
930
+ this.Gh = Gh | 0;
931
+ this.Gl = Gl | 0;
932
+ this.Hh = Hh | 0;
933
+ this.Hl = Hl | 0;
934
+ }
935
+ process(view, offset) {
936
+ for (let i = 0; i < 16; i++, offset += 4) {
937
+ SHA512_W_H[i] = view.getUint32(offset);
938
+ SHA512_W_L[i] = view.getUint32(offset += 4);
939
+ }
940
+ for (let i = 16; i < 80; i++) {
941
+ const W15h = SHA512_W_H[i - 15] | 0;
942
+ const W15l = SHA512_W_L[i - 15] | 0;
943
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
944
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
945
+ const W2h = SHA512_W_H[i - 2] | 0;
946
+ const W2l = SHA512_W_L[i - 2] | 0;
947
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
948
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
949
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
950
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
951
+ SHA512_W_H[i] = SUMh | 0;
952
+ SHA512_W_L[i] = SUMl | 0;
953
+ }
954
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
955
+ for (let i = 0; i < 80; i++) {
956
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
957
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
958
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
959
+ const CHIl = El & Fl ^ ~El & Gl;
960
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
961
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
962
+ const T1l = T1ll | 0;
963
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
964
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
965
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
966
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
967
+ Hh = Gh | 0;
968
+ Hl = Gl | 0;
969
+ Gh = Fh | 0;
970
+ Gl = Fl | 0;
971
+ Fh = Eh | 0;
972
+ Fl = El | 0;
973
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
974
+ Dh = Ch | 0;
975
+ Dl = Cl | 0;
976
+ Ch = Bh | 0;
977
+ Cl = Bl | 0;
978
+ Bh = Ah | 0;
979
+ Bl = Al | 0;
980
+ const All = add3L(T1l, sigma0l, MAJl);
981
+ Ah = add3H(All, T1h, sigma0h, MAJh);
982
+ Al = All | 0;
983
+ }
984
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
985
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
986
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
987
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
988
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
989
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
990
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
991
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
992
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
993
+ }
994
+ roundClean() {
995
+ clean(SHA512_W_H, SHA512_W_L);
996
+ }
997
+ destroy() {
998
+ clean(this.buffer);
999
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1000
+ }
1001
+ };
1002
+ var _SHA512 = class extends SHA2_64B {
1003
+ Ah = SHA512_IV[0] | 0;
1004
+ Al = SHA512_IV[1] | 0;
1005
+ Bh = SHA512_IV[2] | 0;
1006
+ Bl = SHA512_IV[3] | 0;
1007
+ Ch = SHA512_IV[4] | 0;
1008
+ Cl = SHA512_IV[5] | 0;
1009
+ Dh = SHA512_IV[6] | 0;
1010
+ Dl = SHA512_IV[7] | 0;
1011
+ Eh = SHA512_IV[8] | 0;
1012
+ El = SHA512_IV[9] | 0;
1013
+ Fh = SHA512_IV[10] | 0;
1014
+ Fl = SHA512_IV[11] | 0;
1015
+ Gh = SHA512_IV[12] | 0;
1016
+ Gl = SHA512_IV[13] | 0;
1017
+ Hh = SHA512_IV[14] | 0;
1018
+ Hl = SHA512_IV[15] | 0;
1019
+ constructor() {
1020
+ super(64);
1021
+ }
1022
+ };
1023
+ var sha512 = /* @__PURE__ */ createHasher(
1024
+ () => new _SHA512(),
1025
+ /* @__PURE__ */ oidNist(3)
1026
+ );
1027
+
1028
+ // node_modules/@noble/curves/utils.js
1029
+ var _0n = /* @__PURE__ */ BigInt(0);
1030
+ var _1n = /* @__PURE__ */ BigInt(1);
1031
+ function abool(value, title = "") {
1032
+ if (typeof value !== "boolean") {
1033
+ const prefix = title && `"${title}" `;
1034
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
1035
+ }
1036
+ return value;
1037
+ }
1038
+ function abignumber(n) {
1039
+ if (typeof n === "bigint") {
1040
+ if (!isPosBig(n))
1041
+ throw new Error("positive bigint expected, got " + n);
1042
+ } else
1043
+ anumber(n);
1044
+ return n;
1045
+ }
1046
+ function hexToNumber(hex) {
1047
+ if (typeof hex !== "string")
1048
+ throw new Error("hex string expected, got " + typeof hex);
1049
+ return hex === "" ? _0n : BigInt("0x" + hex);
1050
+ }
1051
+ function bytesToNumberBE(bytes) {
1052
+ return hexToNumber(bytesToHex(bytes));
1053
+ }
1054
+ function bytesToNumberLE(bytes) {
1055
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
1056
+ }
1057
+ function numberToBytesBE(n, len) {
1058
+ anumber(len);
1059
+ n = abignumber(n);
1060
+ const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
1061
+ if (res.length !== len)
1062
+ throw new Error("number too large");
1063
+ return res;
1064
+ }
1065
+ function numberToBytesLE(n, len) {
1066
+ return numberToBytesBE(n, len).reverse();
1067
+ }
1068
+ function copyBytes(bytes) {
1069
+ return Uint8Array.from(bytes);
1070
+ }
1071
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
1072
+ function inRange(n, min, max) {
1073
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1074
+ }
1075
+ function aInRange(title, n, min, max) {
1076
+ if (!inRange(n, min, max))
1077
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1078
+ }
1079
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
1080
+ function validateObject(object, fields = {}, optFields = {}) {
1081
+ if (!object || typeof object !== "object")
1082
+ throw new Error("expected valid options object");
1083
+ function checkField(fieldName, expectedType, isOpt) {
1084
+ const val = object[fieldName];
1085
+ if (isOpt && val === void 0)
1086
+ return;
1087
+ const current = typeof val;
1088
+ if (current !== expectedType || val === null)
1089
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
1090
+ }
1091
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1092
+ iter(fields, false);
1093
+ iter(optFields, true);
1094
+ }
1095
+ function memoized(fn) {
1096
+ const map = /* @__PURE__ */ new WeakMap();
1097
+ return (arg, ...args) => {
1098
+ const val = map.get(arg);
1099
+ if (val !== void 0)
1100
+ return val;
1101
+ const computed = fn(arg, ...args);
1102
+ map.set(arg, computed);
1103
+ return computed;
1104
+ };
1105
+ }
1106
+
1107
+ // node_modules/@noble/curves/abstract/modular.js
1108
+ var _0n2 = /* @__PURE__ */ BigInt(0);
1109
+ var _1n2 = /* @__PURE__ */ BigInt(1);
1110
+ var _2n = /* @__PURE__ */ BigInt(2);
1111
+ var _3n = /* @__PURE__ */ BigInt(3);
1112
+ var _4n = /* @__PURE__ */ BigInt(4);
1113
+ var _5n = /* @__PURE__ */ BigInt(5);
1114
+ var _7n = /* @__PURE__ */ BigInt(7);
1115
+ var _8n = /* @__PURE__ */ BigInt(8);
1116
+ var _9n = /* @__PURE__ */ BigInt(9);
1117
+ var _16n = /* @__PURE__ */ BigInt(16);
1118
+ function mod(a, b) {
1119
+ const result = a % b;
1120
+ return result >= _0n2 ? result : b + result;
1121
+ }
1122
+ function pow2(x, power, modulo) {
1123
+ let res = x;
1124
+ while (power-- > _0n2) {
1125
+ res *= res;
1126
+ res %= modulo;
1127
+ }
1128
+ return res;
1129
+ }
1130
+ function invert(number, modulo) {
1131
+ if (number === _0n2)
1132
+ throw new Error("invert: expected non-zero number");
1133
+ if (modulo <= _0n2)
1134
+ throw new Error("invert: expected positive modulus, got " + modulo);
1135
+ let a = mod(number, modulo);
1136
+ let b = modulo;
1137
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1138
+ while (a !== _0n2) {
1139
+ const q = b / a;
1140
+ const r = b % a;
1141
+ const m = x - u * q;
1142
+ const n = y - v * q;
1143
+ b = a, a = r, x = u, y = v, u = m, v = n;
1144
+ }
1145
+ const gcd = b;
1146
+ if (gcd !== _1n2)
1147
+ throw new Error("invert: does not exist");
1148
+ return mod(x, modulo);
1149
+ }
1150
+ function assertIsSquare(Fp, root, n) {
1151
+ if (!Fp.eql(Fp.sqr(root), n))
1152
+ throw new Error("Cannot find square root");
1153
+ }
1154
+ function sqrt3mod4(Fp, n) {
1155
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
1156
+ const root = Fp.pow(n, p1div4);
1157
+ assertIsSquare(Fp, root, n);
1158
+ return root;
1159
+ }
1160
+ function sqrt5mod8(Fp, n) {
1161
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
1162
+ const n2 = Fp.mul(n, _2n);
1163
+ const v = Fp.pow(n2, p5div8);
1164
+ const nv = Fp.mul(n, v);
1165
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
1166
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
1167
+ assertIsSquare(Fp, root, n);
1168
+ return root;
1169
+ }
1170
+ function sqrt9mod16(P) {
1171
+ const Fp_ = Field(P);
1172
+ const tn = tonelliShanks(P);
1173
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1174
+ const c2 = tn(Fp_, c1);
1175
+ const c3 = tn(Fp_, Fp_.neg(c1));
1176
+ const c4 = (P + _7n) / _16n;
1177
+ return (Fp, n) => {
1178
+ let tv1 = Fp.pow(n, c4);
1179
+ let tv2 = Fp.mul(tv1, c1);
1180
+ const tv3 = Fp.mul(tv1, c2);
1181
+ const tv4 = Fp.mul(tv1, c3);
1182
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
1183
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
1184
+ tv1 = Fp.cmov(tv1, tv2, e1);
1185
+ tv2 = Fp.cmov(tv4, tv3, e2);
1186
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
1187
+ const root = Fp.cmov(tv1, tv2, e3);
1188
+ assertIsSquare(Fp, root, n);
1189
+ return root;
1190
+ };
1191
+ }
1192
+ function tonelliShanks(P) {
1193
+ if (P < _3n)
1194
+ throw new Error("sqrt is not defined for small field");
1195
+ let Q = P - _1n2;
1196
+ let S = 0;
1197
+ while (Q % _2n === _0n2) {
1198
+ Q /= _2n;
1199
+ S++;
1200
+ }
1201
+ let Z = _2n;
1202
+ const _Fp = Field(P);
1203
+ while (FpLegendre(_Fp, Z) === 1) {
1204
+ if (Z++ > 1e3)
1205
+ throw new Error("Cannot find square root: probably non-prime P");
1206
+ }
1207
+ if (S === 1)
1208
+ return sqrt3mod4;
1209
+ let cc = _Fp.pow(Z, Q);
1210
+ const Q1div2 = (Q + _1n2) / _2n;
1211
+ return function tonelliSlow(Fp, n) {
1212
+ if (Fp.is0(n))
1213
+ return n;
1214
+ if (FpLegendre(Fp, n) !== 1)
1215
+ throw new Error("Cannot find square root");
1216
+ let M = S;
1217
+ let c = Fp.mul(Fp.ONE, cc);
1218
+ let t = Fp.pow(n, Q);
1219
+ let R = Fp.pow(n, Q1div2);
1220
+ while (!Fp.eql(t, Fp.ONE)) {
1221
+ if (Fp.is0(t))
1222
+ return Fp.ZERO;
1223
+ let i = 1;
1224
+ let t_tmp = Fp.sqr(t);
1225
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
1226
+ i++;
1227
+ t_tmp = Fp.sqr(t_tmp);
1228
+ if (i === M)
1229
+ throw new Error("Cannot find square root");
1230
+ }
1231
+ const exponent = _1n2 << BigInt(M - i - 1);
1232
+ const b = Fp.pow(c, exponent);
1233
+ M = i;
1234
+ c = Fp.sqr(b);
1235
+ t = Fp.mul(t, c);
1236
+ R = Fp.mul(R, b);
1237
+ }
1238
+ return R;
1239
+ };
1240
+ }
1241
+ function FpSqrt(P) {
1242
+ if (P % _4n === _3n)
1243
+ return sqrt3mod4;
1244
+ if (P % _8n === _5n)
1245
+ return sqrt5mod8;
1246
+ if (P % _16n === _9n)
1247
+ return sqrt9mod16(P);
1248
+ return tonelliShanks(P);
1249
+ }
1250
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1251
+ var FIELD_FIELDS = [
1252
+ "create",
1253
+ "isValid",
1254
+ "is0",
1255
+ "neg",
1256
+ "inv",
1257
+ "sqrt",
1258
+ "sqr",
1259
+ "eql",
1260
+ "add",
1261
+ "sub",
1262
+ "mul",
1263
+ "pow",
1264
+ "div",
1265
+ "addN",
1266
+ "subN",
1267
+ "mulN",
1268
+ "sqrN"
1269
+ ];
1270
+ function validateField(field) {
1271
+ const initial = {
1272
+ ORDER: "bigint",
1273
+ BYTES: "number",
1274
+ BITS: "number"
1275
+ };
1276
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1277
+ map[val] = "function";
1278
+ return map;
1279
+ }, initial);
1280
+ validateObject(field, opts);
1281
+ return field;
1282
+ }
1283
+ function FpPow(Fp, num, power) {
1284
+ if (power < _0n2)
1285
+ throw new Error("invalid exponent, negatives unsupported");
1286
+ if (power === _0n2)
1287
+ return Fp.ONE;
1288
+ if (power === _1n2)
1289
+ return num;
1290
+ let p = Fp.ONE;
1291
+ let d = num;
1292
+ while (power > _0n2) {
1293
+ if (power & _1n2)
1294
+ p = Fp.mul(p, d);
1295
+ d = Fp.sqr(d);
1296
+ power >>= _1n2;
1297
+ }
1298
+ return p;
1299
+ }
1300
+ function FpInvertBatch(Fp, nums, passZero = false) {
1301
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
1302
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1303
+ if (Fp.is0(num))
1304
+ return acc;
1305
+ inverted[i] = acc;
1306
+ return Fp.mul(acc, num);
1307
+ }, Fp.ONE);
1308
+ const invertedAcc = Fp.inv(multipliedAcc);
1309
+ nums.reduceRight((acc, num, i) => {
1310
+ if (Fp.is0(num))
1311
+ return acc;
1312
+ inverted[i] = Fp.mul(acc, inverted[i]);
1313
+ return Fp.mul(acc, num);
1314
+ }, invertedAcc);
1315
+ return inverted;
1316
+ }
1317
+ function FpLegendre(Fp, n) {
1318
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
1319
+ const powered = Fp.pow(n, p1mod2);
1320
+ const yes = Fp.eql(powered, Fp.ONE);
1321
+ const zero = Fp.eql(powered, Fp.ZERO);
1322
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1323
+ if (!yes && !zero && !no)
1324
+ throw new Error("invalid Legendre symbol result");
1325
+ return yes ? 1 : zero ? 0 : -1;
1326
+ }
1327
+ function nLength(n, nBitLength) {
1328
+ if (nBitLength !== void 0)
1329
+ anumber(nBitLength);
1330
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1331
+ const nByteLength = Math.ceil(_nBitLength / 8);
1332
+ return { nBitLength: _nBitLength, nByteLength };
1333
+ }
1334
+ var _Field = class {
1335
+ ORDER;
1336
+ BITS;
1337
+ BYTES;
1338
+ isLE;
1339
+ ZERO = _0n2;
1340
+ ONE = _1n2;
1341
+ _lengths;
1342
+ _sqrt;
1343
+ // cached sqrt
1344
+ _mod;
1345
+ constructor(ORDER, opts = {}) {
1346
+ if (ORDER <= _0n2)
1347
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1348
+ let _nbitLength = void 0;
1349
+ this.isLE = false;
1350
+ if (opts != null && typeof opts === "object") {
1351
+ if (typeof opts.BITS === "number")
1352
+ _nbitLength = opts.BITS;
1353
+ if (typeof opts.sqrt === "function")
1354
+ this.sqrt = opts.sqrt;
1355
+ if (typeof opts.isLE === "boolean")
1356
+ this.isLE = opts.isLE;
1357
+ if (opts.allowedLengths)
1358
+ this._lengths = opts.allowedLengths?.slice();
1359
+ if (typeof opts.modFromBytes === "boolean")
1360
+ this._mod = opts.modFromBytes;
1361
+ }
1362
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1363
+ if (nByteLength > 2048)
1364
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1365
+ this.ORDER = ORDER;
1366
+ this.BITS = nBitLength;
1367
+ this.BYTES = nByteLength;
1368
+ this._sqrt = void 0;
1369
+ Object.preventExtensions(this);
1370
+ }
1371
+ create(num) {
1372
+ return mod(num, this.ORDER);
1373
+ }
1374
+ isValid(num) {
1375
+ if (typeof num !== "bigint")
1376
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
1377
+ return _0n2 <= num && num < this.ORDER;
1378
+ }
1379
+ is0(num) {
1380
+ return num === _0n2;
1381
+ }
1382
+ // is valid and invertible
1383
+ isValidNot0(num) {
1384
+ return !this.is0(num) && this.isValid(num);
1385
+ }
1386
+ isOdd(num) {
1387
+ return (num & _1n2) === _1n2;
1388
+ }
1389
+ neg(num) {
1390
+ return mod(-num, this.ORDER);
1391
+ }
1392
+ eql(lhs, rhs) {
1393
+ return lhs === rhs;
1394
+ }
1395
+ sqr(num) {
1396
+ return mod(num * num, this.ORDER);
1397
+ }
1398
+ add(lhs, rhs) {
1399
+ return mod(lhs + rhs, this.ORDER);
1400
+ }
1401
+ sub(lhs, rhs) {
1402
+ return mod(lhs - rhs, this.ORDER);
1403
+ }
1404
+ mul(lhs, rhs) {
1405
+ return mod(lhs * rhs, this.ORDER);
1406
+ }
1407
+ pow(num, power) {
1408
+ return FpPow(this, num, power);
1409
+ }
1410
+ div(lhs, rhs) {
1411
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1412
+ }
1413
+ // Same as above, but doesn't normalize
1414
+ sqrN(num) {
1415
+ return num * num;
1416
+ }
1417
+ addN(lhs, rhs) {
1418
+ return lhs + rhs;
1419
+ }
1420
+ subN(lhs, rhs) {
1421
+ return lhs - rhs;
1422
+ }
1423
+ mulN(lhs, rhs) {
1424
+ return lhs * rhs;
1425
+ }
1426
+ inv(num) {
1427
+ return invert(num, this.ORDER);
1428
+ }
1429
+ sqrt(num) {
1430
+ if (!this._sqrt)
1431
+ this._sqrt = FpSqrt(this.ORDER);
1432
+ return this._sqrt(this, num);
1433
+ }
1434
+ toBytes(num) {
1435
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1436
+ }
1437
+ fromBytes(bytes, skipValidation = false) {
1438
+ abytes(bytes);
1439
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
1440
+ if (allowedLengths) {
1441
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1442
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1443
+ }
1444
+ const padded = new Uint8Array(BYTES);
1445
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1446
+ bytes = padded;
1447
+ }
1448
+ if (bytes.length !== BYTES)
1449
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1450
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1451
+ if (modFromBytes)
1452
+ scalar = mod(scalar, ORDER);
1453
+ if (!skipValidation) {
1454
+ if (!this.isValid(scalar))
1455
+ throw new Error("invalid field element: outside of range 0..ORDER");
1456
+ }
1457
+ return scalar;
1458
+ }
1459
+ // TODO: we don't need it here, move out to separate fn
1460
+ invertBatch(lst) {
1461
+ return FpInvertBatch(this, lst);
1462
+ }
1463
+ // We can't move this out because Fp6, Fp12 implement it
1464
+ // and it's unclear what to return in there.
1465
+ cmov(a, b, condition) {
1466
+ return condition ? b : a;
1467
+ }
1468
+ };
1469
+ function Field(ORDER, opts = {}) {
1470
+ return new _Field(ORDER, opts);
1471
+ }
1472
+
1473
+ // node_modules/@noble/curves/abstract/curve.js
1474
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1475
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1476
+ function negateCt(condition, item) {
1477
+ const neg = item.negate();
1478
+ return condition ? neg : item;
1479
+ }
1480
+ function normalizeZ(c, points) {
1481
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1482
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1483
+ }
1484
+ function validateW(W, bits) {
1485
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1486
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1487
+ }
1488
+ function calcWOpts(W, scalarBits) {
1489
+ validateW(W, scalarBits);
1490
+ const windows = Math.ceil(scalarBits / W) + 1;
1491
+ const windowSize = 2 ** (W - 1);
1492
+ const maxNumber = 2 ** W;
1493
+ const mask = bitMask(W);
1494
+ const shiftBy = BigInt(W);
1495
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1496
+ }
1497
+ function calcOffsets(n, window, wOpts) {
1498
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1499
+ let wbits = Number(n & mask);
1500
+ let nextN = n >> shiftBy;
1501
+ if (wbits > windowSize) {
1502
+ wbits -= maxNumber;
1503
+ nextN += _1n3;
1504
+ }
1505
+ const offsetStart = window * windowSize;
1506
+ const offset = offsetStart + Math.abs(wbits) - 1;
1507
+ const isZero = wbits === 0;
1508
+ const isNeg = wbits < 0;
1509
+ const isNegF = window % 2 !== 0;
1510
+ const offsetF = offsetStart;
1511
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1512
+ }
1513
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1514
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1515
+ function getW(P) {
1516
+ return pointWindowSizes.get(P) || 1;
1517
+ }
1518
+ function assert0(n) {
1519
+ if (n !== _0n3)
1520
+ throw new Error("invalid wNAF");
1521
+ }
1522
+ var wNAF = class {
1523
+ BASE;
1524
+ ZERO;
1525
+ Fn;
1526
+ bits;
1527
+ // Parametrized with a given Point class (not individual point)
1528
+ constructor(Point, bits) {
1529
+ this.BASE = Point.BASE;
1530
+ this.ZERO = Point.ZERO;
1531
+ this.Fn = Point.Fn;
1532
+ this.bits = bits;
1533
+ }
1534
+ // non-const time multiplication ladder
1535
+ _unsafeLadder(elm, n, p = this.ZERO) {
1536
+ let d = elm;
1537
+ while (n > _0n3) {
1538
+ if (n & _1n3)
1539
+ p = p.add(d);
1540
+ d = d.double();
1541
+ n >>= _1n3;
1542
+ }
1543
+ return p;
1544
+ }
1545
+ /**
1546
+ * Creates a wNAF precomputation window. Used for caching.
1547
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1548
+ * Number of precomputed points depends on the curve size:
1549
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1550
+ * - 𝑊 is the window size
1551
+ * - 𝑛 is the bitlength of the curve order.
1552
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1553
+ * @param point Point instance
1554
+ * @param W window size
1555
+ * @returns precomputed point tables flattened to a single array
1556
+ */
1557
+ precomputeWindow(point, W) {
1558
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1559
+ const points = [];
1560
+ let p = point;
1561
+ let base = p;
1562
+ for (let window = 0; window < windows; window++) {
1563
+ base = p;
1564
+ points.push(base);
1565
+ for (let i = 1; i < windowSize; i++) {
1566
+ base = base.add(p);
1567
+ points.push(base);
1568
+ }
1569
+ p = base.double();
1570
+ }
1571
+ return points;
1572
+ }
1573
+ /**
1574
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1575
+ * More compact implementation:
1576
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1577
+ * @returns real and fake (for const-time) points
1578
+ */
1579
+ wNAF(W, precomputes, n) {
1580
+ if (!this.Fn.isValid(n))
1581
+ throw new Error("invalid scalar");
1582
+ let p = this.ZERO;
1583
+ let f = this.BASE;
1584
+ const wo = calcWOpts(W, this.bits);
1585
+ for (let window = 0; window < wo.windows; window++) {
1586
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1587
+ n = nextN;
1588
+ if (isZero) {
1589
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1590
+ } else {
1591
+ p = p.add(negateCt(isNeg, precomputes[offset]));
1592
+ }
1593
+ }
1594
+ assert0(n);
1595
+ return { p, f };
1596
+ }
1597
+ /**
1598
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1599
+ * @param acc accumulator point to add result of multiplication
1600
+ * @returns point
1601
+ */
1602
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1603
+ const wo = calcWOpts(W, this.bits);
1604
+ for (let window = 0; window < wo.windows; window++) {
1605
+ if (n === _0n3)
1606
+ break;
1607
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1608
+ n = nextN;
1609
+ if (isZero) {
1610
+ continue;
1611
+ } else {
1612
+ const item = precomputes[offset];
1613
+ acc = acc.add(isNeg ? item.negate() : item);
1614
+ }
1615
+ }
1616
+ assert0(n);
1617
+ return acc;
1618
+ }
1619
+ getPrecomputes(W, point, transform) {
1620
+ let comp = pointPrecomputes.get(point);
1621
+ if (!comp) {
1622
+ comp = this.precomputeWindow(point, W);
1623
+ if (W !== 1) {
1624
+ if (typeof transform === "function")
1625
+ comp = transform(comp);
1626
+ pointPrecomputes.set(point, comp);
1627
+ }
1628
+ }
1629
+ return comp;
1630
+ }
1631
+ cached(point, scalar, transform) {
1632
+ const W = getW(point);
1633
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1634
+ }
1635
+ unsafe(point, scalar, transform, prev) {
1636
+ const W = getW(point);
1637
+ if (W === 1)
1638
+ return this._unsafeLadder(point, scalar, prev);
1639
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1640
+ }
1641
+ // We calculate precomputes for elliptic curve point multiplication
1642
+ // using windowed method. This specifies window size and
1643
+ // stores precomputed values. Usually only base point would be precomputed.
1644
+ createCache(P, W) {
1645
+ validateW(W, this.bits);
1646
+ pointWindowSizes.set(P, W);
1647
+ pointPrecomputes.delete(P);
1648
+ }
1649
+ hasCache(elm) {
1650
+ return getW(elm) !== 1;
1651
+ }
1652
+ };
1653
+ function createField(order, field, isLE) {
1654
+ if (field) {
1655
+ if (field.ORDER !== order)
1656
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1657
+ validateField(field);
1658
+ return field;
1659
+ } else {
1660
+ return Field(order, { isLE });
1661
+ }
1662
+ }
1663
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1664
+ if (FpFnLE === void 0)
1665
+ FpFnLE = type === "edwards";
1666
+ if (!CURVE || typeof CURVE !== "object")
1667
+ throw new Error(`expected valid ${type} CURVE object`);
1668
+ for (const p of ["p", "n", "h"]) {
1669
+ const val = CURVE[p];
1670
+ if (!(typeof val === "bigint" && val > _0n3))
1671
+ throw new Error(`CURVE.${p} must be positive bigint`);
1672
+ }
1673
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1674
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1675
+ const _b = type === "weierstrass" ? "b" : "d";
1676
+ const params = ["Gx", "Gy", "a", _b];
1677
+ for (const p of params) {
1678
+ if (!Fp.isValid(CURVE[p]))
1679
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1680
+ }
1681
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1682
+ return { CURVE, Fp, Fn };
1683
+ }
1684
+ function createKeygen(randomSecretKey, getPublicKey) {
1685
+ return function keygen(seed) {
1686
+ const secretKey = randomSecretKey(seed);
1687
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1688
+ };
1689
+ }
1690
+
1691
+ // node_modules/@noble/curves/abstract/edwards.js
1692
+ var _0n4 = BigInt(0);
1693
+ var _1n4 = BigInt(1);
1694
+ var _2n2 = BigInt(2);
1695
+ var _8n2 = BigInt(8);
1696
+ function isEdValidXY(Fp, CURVE, x, y) {
1697
+ const x2 = Fp.sqr(x);
1698
+ const y2 = Fp.sqr(y);
1699
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
1700
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
1701
+ return Fp.eql(left, right);
1702
+ }
1703
+ function edwards(params, extraOpts = {}) {
1704
+ const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1705
+ const { Fp, Fn } = validated;
1706
+ let CURVE = validated.CURVE;
1707
+ const { h: cofactor } = CURVE;
1708
+ validateObject(extraOpts, {}, { uvRatio: "function" });
1709
+ const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
1710
+ const modP = (n) => Fp.create(n);
1711
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1712
+ try {
1713
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
1714
+ } catch (e) {
1715
+ return { isValid: false, value: _0n4 };
1716
+ }
1717
+ });
1718
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
1719
+ throw new Error("bad curve params: generator point");
1720
+ function acoord(title, n, banZero = false) {
1721
+ const min = banZero ? _1n4 : _0n4;
1722
+ aInRange("coordinate " + title, n, min, MASK);
1723
+ return n;
1724
+ }
1725
+ function aedpoint(other) {
1726
+ if (!(other instanceof Point))
1727
+ throw new Error("EdwardsPoint expected");
1728
+ }
1729
+ const toAffineMemo = memoized((p, iz) => {
1730
+ const { X, Y, Z } = p;
1731
+ const is0 = p.is0();
1732
+ if (iz == null)
1733
+ iz = is0 ? _8n2 : Fp.inv(Z);
1734
+ const x = modP(X * iz);
1735
+ const y = modP(Y * iz);
1736
+ const zz = Fp.mul(Z, iz);
1737
+ if (is0)
1738
+ return { x: _0n4, y: _1n4 };
1739
+ if (zz !== _1n4)
1740
+ throw new Error("invZ was invalid");
1741
+ return { x, y };
1742
+ });
1743
+ const assertValidMemo = memoized((p) => {
1744
+ const { a, d } = CURVE;
1745
+ if (p.is0())
1746
+ throw new Error("bad point: ZERO");
1747
+ const { X, Y, Z, T } = p;
1748
+ const X2 = modP(X * X);
1749
+ const Y2 = modP(Y * Y);
1750
+ const Z2 = modP(Z * Z);
1751
+ const Z4 = modP(Z2 * Z2);
1752
+ const aX2 = modP(X2 * a);
1753
+ const left = modP(Z2 * modP(aX2 + Y2));
1754
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1755
+ if (left !== right)
1756
+ throw new Error("bad point: equation left != right (1)");
1757
+ const XY = modP(X * Y);
1758
+ const ZT = modP(Z * T);
1759
+ if (XY !== ZT)
1760
+ throw new Error("bad point: equation left != right (2)");
1761
+ return true;
1762
+ });
1763
+ class Point {
1764
+ // base / generator point
1765
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1766
+ // zero / infinity / identity point
1767
+ static ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1768
+ // 0, 1, 1, 0
1769
+ // math field
1770
+ static Fp = Fp;
1771
+ // scalar field
1772
+ static Fn = Fn;
1773
+ X;
1774
+ Y;
1775
+ Z;
1776
+ T;
1777
+ constructor(X, Y, Z, T) {
1778
+ this.X = acoord("x", X);
1779
+ this.Y = acoord("y", Y);
1780
+ this.Z = acoord("z", Z, true);
1781
+ this.T = acoord("t", T);
1782
+ Object.freeze(this);
1783
+ }
1784
+ static CURVE() {
1785
+ return CURVE;
1786
+ }
1787
+ static fromAffine(p) {
1788
+ if (p instanceof Point)
1789
+ throw new Error("extended point not allowed");
1790
+ const { x, y } = p || {};
1791
+ acoord("x", x);
1792
+ acoord("y", y);
1793
+ return new Point(x, y, _1n4, modP(x * y));
1794
+ }
1795
+ // Uses algo from RFC8032 5.1.3.
1796
+ static fromBytes(bytes, zip215 = false) {
1797
+ const len = Fp.BYTES;
1798
+ const { a, d } = CURVE;
1799
+ bytes = copyBytes(abytes(bytes, len, "point"));
1800
+ abool(zip215, "zip215");
1801
+ const normed = copyBytes(bytes);
1802
+ const lastByte = bytes[len - 1];
1803
+ normed[len - 1] = lastByte & ~128;
1804
+ const y = bytesToNumberLE(normed);
1805
+ const max = zip215 ? MASK : Fp.ORDER;
1806
+ aInRange("point.y", y, _0n4, max);
1807
+ const y2 = modP(y * y);
1808
+ const u = modP(y2 - _1n4);
1809
+ const v = modP(d * y2 - a);
1810
+ let { isValid, value: x } = uvRatio2(u, v);
1811
+ if (!isValid)
1812
+ throw new Error("bad point: invalid y coordinate");
1813
+ const isXOdd = (x & _1n4) === _1n4;
1814
+ const isLastByteOdd = (lastByte & 128) !== 0;
1815
+ if (!zip215 && x === _0n4 && isLastByteOdd)
1816
+ throw new Error("bad point: x=0 and x_0=1");
1817
+ if (isLastByteOdd !== isXOdd)
1818
+ x = modP(-x);
1819
+ return Point.fromAffine({ x, y });
1820
+ }
1821
+ static fromHex(hex, zip215 = false) {
1822
+ return Point.fromBytes(hexToBytes(hex), zip215);
1823
+ }
1824
+ get x() {
1825
+ return this.toAffine().x;
1826
+ }
1827
+ get y() {
1828
+ return this.toAffine().y;
1829
+ }
1830
+ precompute(windowSize = 8, isLazy = true) {
1831
+ wnaf.createCache(this, windowSize);
1832
+ if (!isLazy)
1833
+ this.multiply(_2n2);
1834
+ return this;
1835
+ }
1836
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1837
+ assertValidity() {
1838
+ assertValidMemo(this);
1839
+ }
1840
+ // Compare one point to another.
1841
+ equals(other) {
1842
+ aedpoint(other);
1843
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1844
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1845
+ const X1Z2 = modP(X1 * Z2);
1846
+ const X2Z1 = modP(X2 * Z1);
1847
+ const Y1Z2 = modP(Y1 * Z2);
1848
+ const Y2Z1 = modP(Y2 * Z1);
1849
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1850
+ }
1851
+ is0() {
1852
+ return this.equals(Point.ZERO);
1853
+ }
1854
+ negate() {
1855
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1856
+ }
1857
+ // Fast algo for doubling Extended Point.
1858
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1859
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1860
+ double() {
1861
+ const { a } = CURVE;
1862
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1863
+ const A = modP(X1 * X1);
1864
+ const B = modP(Y1 * Y1);
1865
+ const C = modP(_2n2 * modP(Z1 * Z1));
1866
+ const D = modP(a * A);
1867
+ const x1y1 = X1 + Y1;
1868
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1869
+ const G = D + B;
1870
+ const F = G - C;
1871
+ const H = D - B;
1872
+ const X3 = modP(E * F);
1873
+ const Y3 = modP(G * H);
1874
+ const T3 = modP(E * H);
1875
+ const Z3 = modP(F * G);
1876
+ return new Point(X3, Y3, Z3, T3);
1877
+ }
1878
+ // Fast algo for adding 2 Extended Points.
1879
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1880
+ // Cost: 9M + 1*a + 1*d + 7add.
1881
+ add(other) {
1882
+ aedpoint(other);
1883
+ const { a, d } = CURVE;
1884
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1885
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1886
+ const A = modP(X1 * X2);
1887
+ const B = modP(Y1 * Y2);
1888
+ const C = modP(T1 * d * T2);
1889
+ const D = modP(Z1 * Z2);
1890
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1891
+ const F = D - C;
1892
+ const G = D + C;
1893
+ const H = modP(B - a * A);
1894
+ const X3 = modP(E * F);
1895
+ const Y3 = modP(G * H);
1896
+ const T3 = modP(E * H);
1897
+ const Z3 = modP(F * G);
1898
+ return new Point(X3, Y3, Z3, T3);
1899
+ }
1900
+ subtract(other) {
1901
+ return this.add(other.negate());
1902
+ }
1903
+ // Constant-time multiplication.
1904
+ multiply(scalar) {
1905
+ if (!Fn.isValidNot0(scalar))
1906
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1907
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1908
+ return normalizeZ(Point, [p, f])[0];
1909
+ }
1910
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1911
+ // It's faster, but should only be used when you don't care about
1912
+ // an exposed private key e.g. sig verification.
1913
+ // Does NOT allow scalars higher than CURVE.n.
1914
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1915
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
1916
+ if (!Fn.isValid(scalar))
1917
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1918
+ if (scalar === _0n4)
1919
+ return Point.ZERO;
1920
+ if (this.is0() || scalar === _1n4)
1921
+ return this;
1922
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1923
+ }
1924
+ // Checks if point is of small order.
1925
+ // If you add something to small order point, you will have "dirty"
1926
+ // point with torsion component.
1927
+ // Multiplies point by cofactor and checks if the result is 0.
1928
+ isSmallOrder() {
1929
+ return this.multiplyUnsafe(cofactor).is0();
1930
+ }
1931
+ // Multiplies point by curve order and checks if the result is 0.
1932
+ // Returns `false` is the point is dirty.
1933
+ isTorsionFree() {
1934
+ return wnaf.unsafe(this, CURVE.n).is0();
1935
+ }
1936
+ // Converts Extended point to default (x, y) coordinates.
1937
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1938
+ toAffine(invertedZ) {
1939
+ return toAffineMemo(this, invertedZ);
1940
+ }
1941
+ clearCofactor() {
1942
+ if (cofactor === _1n4)
1943
+ return this;
1944
+ return this.multiplyUnsafe(cofactor);
1945
+ }
1946
+ toBytes() {
1947
+ const { x, y } = this.toAffine();
1948
+ const bytes = Fp.toBytes(y);
1949
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1950
+ return bytes;
1951
+ }
1952
+ toHex() {
1953
+ return bytesToHex(this.toBytes());
1954
+ }
1955
+ toString() {
1956
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1957
+ }
1958
+ }
1959
+ const wnaf = new wNAF(Point, Fn.BITS);
1960
+ Point.BASE.precompute(8);
1961
+ return Point;
1962
+ }
1963
+ function eddsa(Point, cHash, eddsaOpts = {}) {
1964
+ if (typeof cHash !== "function")
1965
+ throw new Error('"hash" function param is required');
1966
+ validateObject(eddsaOpts, {}, {
1967
+ adjustScalarBytes: "function",
1968
+ randomBytes: "function",
1969
+ domain: "function",
1970
+ prehash: "function",
1971
+ mapToCurve: "function"
1972
+ });
1973
+ const { prehash } = eddsaOpts;
1974
+ const { BASE, Fp, Fn } = Point;
1975
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
1976
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1977
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1978
+ abool(phflag, "phflag");
1979
+ if (ctx.length || phflag)
1980
+ throw new Error("Contexts/pre-hash are not supported");
1981
+ return data;
1982
+ });
1983
+ function modN_LE(hash) {
1984
+ return Fn.create(bytesToNumberLE(hash));
1985
+ }
1986
+ function getPrivateScalar(key) {
1987
+ const len = lengths.secretKey;
1988
+ abytes(key, lengths.secretKey, "secretKey");
1989
+ const hashed = abytes(cHash(key), 2 * len, "hashedSecretKey");
1990
+ const head = adjustScalarBytes2(hashed.slice(0, len));
1991
+ const prefix = hashed.slice(len, 2 * len);
1992
+ const scalar = modN_LE(head);
1993
+ return { head, prefix, scalar };
1994
+ }
1995
+ function getExtendedPublicKey(secretKey) {
1996
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
1997
+ const point = BASE.multiply(scalar);
1998
+ const pointBytes = point.toBytes();
1999
+ return { head, prefix, scalar, point, pointBytes };
2000
+ }
2001
+ function getPublicKey(secretKey) {
2002
+ return getExtendedPublicKey(secretKey).pointBytes;
2003
+ }
2004
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
2005
+ const msg = concatBytes(...msgs);
2006
+ return modN_LE(cHash(domain(msg, abytes(context, void 0, "context"), !!prehash)));
2007
+ }
2008
+ function sign(msg, secretKey, options = {}) {
2009
+ msg = abytes(msg, void 0, "message");
2010
+ if (prehash)
2011
+ msg = prehash(msg);
2012
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
2013
+ const r = hashDomainToScalar(options.context, prefix, msg);
2014
+ const R = BASE.multiply(r).toBytes();
2015
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2016
+ const s = Fn.create(r + k * scalar);
2017
+ if (!Fn.isValid(s))
2018
+ throw new Error("sign failed: invalid s");
2019
+ const rs = concatBytes(R, Fn.toBytes(s));
2020
+ return abytes(rs, lengths.signature, "result");
2021
+ }
2022
+ const verifyOpts = { zip215: true };
2023
+ function verify(sig, msg, publicKey, options = verifyOpts) {
2024
+ const { context, zip215 } = options;
2025
+ const len = lengths.signature;
2026
+ sig = abytes(sig, len, "signature");
2027
+ msg = abytes(msg, void 0, "message");
2028
+ publicKey = abytes(publicKey, lengths.publicKey, "publicKey");
2029
+ if (zip215 !== void 0)
2030
+ abool(zip215, "zip215");
2031
+ if (prehash)
2032
+ msg = prehash(msg);
2033
+ const mid = len / 2;
2034
+ const r = sig.subarray(0, mid);
2035
+ const s = bytesToNumberLE(sig.subarray(mid, len));
2036
+ let A, R, SB;
2037
+ try {
2038
+ A = Point.fromBytes(publicKey, zip215);
2039
+ R = Point.fromBytes(r, zip215);
2040
+ SB = BASE.multiplyUnsafe(s);
2041
+ } catch (error) {
2042
+ return false;
2043
+ }
2044
+ if (!zip215 && A.isSmallOrder())
2045
+ return false;
2046
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
2047
+ const RkA = R.add(A.multiplyUnsafe(k));
2048
+ return RkA.subtract(SB).clearCofactor().is0();
2049
+ }
2050
+ const _size = Fp.BYTES;
2051
+ const lengths = {
2052
+ secretKey: _size,
2053
+ publicKey: _size,
2054
+ signature: 2 * _size,
2055
+ seed: _size
2056
+ };
2057
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
2058
+ return abytes(seed, lengths.seed, "seed");
2059
+ }
2060
+ function isValidSecretKey(key) {
2061
+ return isBytes(key) && key.length === Fn.BYTES;
2062
+ }
2063
+ function isValidPublicKey(key, zip215) {
2064
+ try {
2065
+ return !!Point.fromBytes(key, zip215);
2066
+ } catch (error) {
2067
+ return false;
2068
+ }
2069
+ }
2070
+ const utils = {
2071
+ getExtendedPublicKey,
2072
+ randomSecretKey,
2073
+ isValidSecretKey,
2074
+ isValidPublicKey,
2075
+ /**
2076
+ * Converts ed public key to x public key. Uses formula:
2077
+ * - ed25519:
2078
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
2079
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
2080
+ * - ed448:
2081
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
2082
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
2083
+ */
2084
+ toMontgomery(publicKey) {
2085
+ const { y } = Point.fromBytes(publicKey);
2086
+ const size = lengths.publicKey;
2087
+ const is25519 = size === 32;
2088
+ if (!is25519 && size !== 57)
2089
+ throw new Error("only defined for 25519 and 448");
2090
+ const u = is25519 ? Fp.div(_1n4 + y, _1n4 - y) : Fp.div(y - _1n4, y + _1n4);
2091
+ return Fp.toBytes(u);
2092
+ },
2093
+ toMontgomerySecret(secretKey) {
2094
+ const size = lengths.secretKey;
2095
+ abytes(secretKey, size);
2096
+ const hashed = cHash(secretKey.subarray(0, size));
2097
+ return adjustScalarBytes2(hashed).subarray(0, size);
2098
+ }
2099
+ };
2100
+ return Object.freeze({
2101
+ keygen: createKeygen(randomSecretKey, getPublicKey),
2102
+ getPublicKey,
2103
+ sign,
2104
+ verify,
2105
+ utils,
2106
+ Point,
2107
+ lengths
2108
+ });
2109
+ }
2110
+
2111
+ // node_modules/@noble/curves/ed25519.js
2112
+ var _1n5 = BigInt(1);
2113
+ var _2n3 = BigInt(2);
2114
+ var _5n2 = BigInt(5);
2115
+ var _8n3 = BigInt(8);
2116
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2117
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
2118
+ p: ed25519_CURVE_p,
2119
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2120
+ h: _8n3,
2121
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2122
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2123
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2124
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2125
+ }))();
2126
+ function ed25519_pow_2_252_3(x) {
2127
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2128
+ const P = ed25519_CURVE_p;
2129
+ const x2 = x * x % P;
2130
+ const b2 = x2 * x % P;
2131
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
2132
+ const b5 = pow2(b4, _1n5, P) * x % P;
2133
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2134
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2135
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2136
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2137
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2138
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2139
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2140
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
2141
+ return { pow_p_5_8, b2 };
2142
+ }
2143
+ function adjustScalarBytes(bytes) {
2144
+ bytes[0] &= 248;
2145
+ bytes[31] &= 127;
2146
+ bytes[31] |= 64;
2147
+ return bytes;
2148
+ }
2149
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2150
+ function uvRatio(u, v) {
2151
+ const P = ed25519_CURVE_p;
2152
+ const v3 = mod(v * v * v, P);
2153
+ const v7 = mod(v3 * v3 * v, P);
2154
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2155
+ let x = mod(u * v3 * pow, P);
2156
+ const vx2 = mod(v * x * x, P);
2157
+ const root1 = x;
2158
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2159
+ const useRoot1 = vx2 === u;
2160
+ const useRoot2 = vx2 === mod(-u, P);
2161
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2162
+ if (useRoot1)
2163
+ x = root1;
2164
+ if (useRoot2 || noRoot)
2165
+ x = root2;
2166
+ if (isNegativeLE(x, P))
2167
+ x = mod(-x, P);
2168
+ return { isValid: useRoot1 || useRoot2, value: x };
2169
+ }
2170
+ var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2171
+ function ed(opts) {
2172
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
2173
+ }
2174
+ var ed25519 = /* @__PURE__ */ ed({});
2175
+
2176
+ // src/crypto.ts
2177
+ function toB64url(bytes) {
2178
+ let bin = "";
2179
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
2180
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2181
+ }
2182
+ function fromB64url(s) {
2183
+ const padded = s.replace(/-/g, "+").replace(/_/g, "/");
2184
+ const bin = atob(padded);
2185
+ const out = new Uint8Array(bin.length);
2186
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2187
+ return out;
2188
+ }
2189
+ function generateMlDsaKeypair() {
2190
+ const kp = import_ml_dsa.ml_dsa65.keygen();
2191
+ return { privateKey: kp.secretKey, publicKey: kp.publicKey };
2192
+ }
2193
+ function signMlDsa(privateKey, message) {
2194
+ return import_ml_dsa.ml_dsa65.sign(message, privateKey);
2195
+ }
2196
+ function verifyMlDsa(publicKey, message, sig) {
2197
+ return import_ml_dsa.ml_dsa65.verify(sig, message, publicKey);
2198
+ }
2199
+ function signHybrid(ed25519Priv, mlDsaPriv, msg) {
2200
+ return {
2201
+ profile: "pqc-hybrid-v1",
2202
+ ed25519Sig: ed25519.sign(msg, ed25519Priv),
2203
+ mlDsaSig: import_ml_dsa.ml_dsa65.sign(msg, mlDsaPriv)
2204
+ };
2205
+ }
2206
+ function verifyHybrid(ed25519Pub, mlDsaPub, msg, sig) {
2207
+ if (sig.profile !== "pqc-hybrid-v1") return false;
2208
+ return ed25519.verify(sig.ed25519Sig, msg, ed25519Pub) && import_ml_dsa.ml_dsa65.verify(sig.mlDsaSig, msg, mlDsaPub);
2209
+ }
2210
+ function encodeHybridSig(sig) {
2211
+ return `pqc-hybrid-v1.${toB64url(sig.ed25519Sig)}.${toB64url(sig.mlDsaSig)}`;
2212
+ }
2213
+ function decodeHybridSig(s) {
2214
+ const parts = s.split(".");
2215
+ if (parts.length !== 3 || parts[0] !== "pqc-hybrid-v1") {
2216
+ throw new Error(
2217
+ `Invalid hybrid signature: expected "pqc-hybrid-v1.<ed25519b64>.<mldsab64>", got "${s.slice(0, 40)}..."`
2218
+ );
2219
+ }
2220
+ return {
2221
+ profile: "pqc-hybrid-v1",
2222
+ ed25519Sig: fromB64url(parts[1]),
2223
+ mlDsaSig: fromB64url(parts[2])
2224
+ };
2225
+ }
2226
+ function encodeMlDsaPublicKeyJwk(pub) {
2227
+ return {
2228
+ kty: "OKP",
2229
+ alg: "ML-DSA-65",
2230
+ use: "sig",
2231
+ x: toB64url(pub)
2232
+ };
2233
+ }
2234
+ function decodeMlDsaPublicKeyJwk(jwk) {
2235
+ const j = jwk;
2236
+ if (j["kty"] !== "OKP" || j["alg"] !== "ML-DSA-65") {
2237
+ throw new Error(
2238
+ `Invalid ML-DSA-65 JWK: expected kty="OKP" alg="ML-DSA-65", got kty="${j["kty"]}" alg="${j["alg"]}"`
2239
+ );
2240
+ }
2241
+ const x = j["x"];
2242
+ if (typeof x !== "string" || x.length === 0) {
2243
+ throw new Error("Invalid ML-DSA-65 JWK: missing or empty x field");
2244
+ }
2245
+ return fromB64url(x);
2246
+ }
536
2247
  function generateUUID() {
537
2248
  if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.randomUUID === "function") {
538
2249
  return globalThis.crypto.randomUUID();
@@ -628,11 +2339,11 @@ function sha256(msg) {
628
2339
  let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762;
629
2340
  let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
630
2341
  const msgLen = msg.length;
631
- const bitLen = msgLen * 8;
2342
+ const bitLen2 = msgLen * 8;
632
2343
  const padded = [...msg];
633
2344
  padded.push(128);
634
2345
  while (padded.length % 64 !== 56) padded.push(0);
635
- for (let i = 7; i >= 0; i--) padded.push(bitLen / Math.pow(2, i * 8) & 255);
2346
+ for (let i = 7; i >= 0; i--) padded.push(bitLen2 / Math.pow(2, i * 8) & 255);
636
2347
  for (let i = 0; i < padded.length; i += 64) {
637
2348
  const w = [];
638
2349
  for (let j = 0; j < 16; j++) {
@@ -3541,15 +5252,20 @@ var RCAN_VERSION = "1.6";
3541
5252
  clientAllowsTool,
3542
5253
  decodeBleFrames,
3543
5254
  decodeCompact,
5255
+ decodeHybridSig,
3544
5256
  decodeMinimal,
5257
+ decodeMlDsaPublicKeyJwk,
3545
5258
  encodeBleFrames,
3546
5259
  encodeCompact,
5260
+ encodeHybridSig,
3547
5261
  encodeMinimal,
5262
+ encodeMlDsaPublicKeyJwk,
3548
5263
  extractIdentityFromJwt,
3549
5264
  extractLoaFromJwt,
3550
5265
  extractRoleFromJwt,
3551
5266
  fetchCanonicalSchema,
3552
5267
  fetchRRFRevocations,
5268
+ generateMlDsaKeypair,
3553
5269
  isAuthorityRequestValid,
3554
5270
  isM2mTrustedRevoked,
3555
5271
  isPreemptedBy,
@@ -3586,7 +5302,9 @@ var RCAN_VERSION = "1.6";
3586
5302
  parseM2mTrustedToken,
3587
5303
  roleFromJwtLevel,
3588
5304
  selectTransport,
5305
+ signHybrid,
3589
5306
  signMessage,
5307
+ signMlDsa,
3590
5308
  validateAuthorityAccess,
3591
5309
  validateCompetitionScope,
3592
5310
  validateConfig,
@@ -3608,10 +5326,24 @@ var RCAN_VERSION = "1.6";
3608
5326
  validateURI,
3609
5327
  validateV22DelegationChain,
3610
5328
  validateVersionCompat,
5329
+ verifyHybrid,
3611
5330
  verifyM2mTrustedToken,
3612
5331
  verifyM2mTrustedTokenClaims,
3613
5332
  verifyMessage,
5333
+ verifyMlDsa,
3614
5334
  verifyPQSignature,
3615
5335
  verifyV22MediaChunkHash
3616
5336
  });
5337
+ /*! Bundled license information:
5338
+
5339
+ @noble/hashes/utils.js:
5340
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5341
+
5342
+ @noble/curves/utils.js:
5343
+ @noble/curves/abstract/modular.js:
5344
+ @noble/curves/abstract/curve.js:
5345
+ @noble/curves/abstract/edwards.js:
5346
+ @noble/curves/ed25519.js:
5347
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5348
+ */
3617
5349
  //# sourceMappingURL=index.js.map