@taquito/signer 25.0.0 → 25.1.0-beta0

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.
@@ -49,7 +49,7 @@
49
49
  * isBytes(new Uint8Array([1, 2, 3]));
50
50
  * ```
51
51
  */
52
- function isBytes$1(a) {
52
+ function isBytes$2(a) {
53
53
  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
54
54
  // The fallback still requires a real ArrayBuffer view, so plain
55
55
  // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
@@ -72,7 +72,7 @@
72
72
  * anumber(32, 'length');
73
73
  * ```
74
74
  */
75
- function anumber$1(n, title = '') {
75
+ function anumber$2(n, title = '') {
76
76
  if (typeof n !== 'number') {
77
77
  const prefix = title && `"${title}" `;
78
78
  throw new TypeError(`${prefix}expected number, got ${typeof n}`);
@@ -96,8 +96,8 @@
96
96
  * abytes(new Uint8Array([1, 2, 3]));
97
97
  * ```
98
98
  */
99
- function abytes(value, length, title = '') {
100
- const bytes = isBytes$1(value);
99
+ function abytes$1(value, length, title = '') {
100
+ const bytes = isBytes$2(value);
101
101
  const len = value?.length;
102
102
  const needsLen = length !== undefined;
103
103
  if (!bytes || (needsLen && len !== length)) {
@@ -125,11 +125,11 @@
125
125
  * ahash(sha256);
126
126
  * ```
127
127
  */
128
- function ahash(h) {
128
+ function ahash$1(h) {
129
129
  if (typeof h !== 'function' || typeof h.create !== 'function')
130
130
  throw new TypeError('Hash must wrapped by utils.createHasher');
131
- anumber$1(h.outputLen);
132
- anumber$1(h.blockLen);
131
+ anumber$2(h.outputLen);
132
+ anumber$2(h.blockLen);
133
133
  // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
134
134
  // validation and can produce empty outputs instead of failing fast.
135
135
  if (h.outputLen < 1)
@@ -151,7 +151,7 @@
151
151
  * aexists(hash);
152
152
  * ```
153
153
  */
154
- function aexists(instance, checkFinished = true) {
154
+ function aexists$1(instance, checkFinished = true) {
155
155
  if (instance.destroyed)
156
156
  throw new Error('Hash instance has been destroyed');
157
157
  if (checkFinished && instance.finished)
@@ -173,8 +173,8 @@
173
173
  * aoutput(new Uint8Array(hash.outputLen), hash);
174
174
  * ```
175
175
  */
176
- function aoutput(out, instance) {
177
- abytes(out, undefined, 'digestInto() output');
176
+ function aoutput$1(out, instance) {
177
+ abytes$1(out, undefined, 'digestInto() output');
178
178
  const min = instance.outputLen;
179
179
  if (out.length < min) {
180
180
  throw new RangeError('"digestInto() output" expected to be of length >=' + min);
@@ -192,7 +192,7 @@
192
192
  * u32(new Uint8Array(8));
193
193
  * ```
194
194
  */
195
- function u32(arr) {
195
+ function u32$1(arr) {
196
196
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
197
197
  }
198
198
  /**
@@ -204,7 +204,7 @@
204
204
  * clean(new Uint8Array([1, 2, 3]));
205
205
  * ```
206
206
  */
207
- function clean(...arrays) {
207
+ function clean$1(...arrays) {
208
208
  for (let i = 0; i < arrays.length; i++) {
209
209
  arrays[i].fill(0);
210
210
  }
@@ -237,7 +237,7 @@
237
237
  return (word << (32 - shift)) | (word >>> shift);
238
238
  }
239
239
  /** Whether the current platform is little-endian. */
240
- const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
240
+ const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
241
241
  /**
242
242
  * Byte-swap operation for uint32 values.
243
243
  * @param word - source word
@@ -248,7 +248,7 @@
248
248
  * byteSwap(0x11223344);
249
249
  * ```
250
250
  */
251
- function byteSwap(word) {
251
+ function byteSwap$1(word) {
252
252
  return (((word << 24) & 0xff000000) |
253
253
  ((word << 8) & 0xff0000) |
254
254
  ((word >>> 8) & 0xff00) |
@@ -264,9 +264,9 @@
264
264
  * swap8IfBE(0x11223344);
265
265
  * ```
266
266
  */
267
- const swap8IfBE = isLE
267
+ const swap8IfBE = isLE$1
268
268
  ? (n) => n
269
- : (n) => byteSwap(n) >>> 0;
269
+ : (n) => byteSwap$1(n) >>> 0;
270
270
  /**
271
271
  * Byte-swaps every word of a Uint32Array in place.
272
272
  * @param arr - array to mutate
@@ -277,9 +277,9 @@
277
277
  * byteSwap32(new Uint32Array([0x11223344]));
278
278
  * ```
279
279
  */
280
- function byteSwap32(arr) {
280
+ function byteSwap32$1(arr) {
281
281
  for (let i = 0; i < arr.length; i++) {
282
- arr[i] = byteSwap(arr[i]);
282
+ arr[i] = byteSwap$1(arr[i]);
283
283
  }
284
284
  return arr;
285
285
  }
@@ -294,9 +294,9 @@
294
294
  * swap32IfBE(new Uint32Array([0x11223344]));
295
295
  * ```
296
296
  */
297
- const swap32IfBE = isLE
297
+ const swap32IfBE$1 = isLE$1
298
298
  ? (u) => u
299
- : byteSwap32;
299
+ : byteSwap32$1;
300
300
  /**
301
301
  * Converts string to bytes using UTF8 encoding.
302
302
  * Built-in doesn't validate input to be string: we do the check.
@@ -331,7 +331,7 @@
331
331
  function kdfInputToBytes(data, errorTitle = '') {
332
332
  if (typeof data === 'string')
333
333
  return utf8ToBytes(data);
334
- return abytes(data, undefined, errorTitle);
334
+ return abytes$1(data, undefined, errorTitle);
335
335
  }
336
336
  /**
337
337
  * Merges default options and passed options.
@@ -345,7 +345,7 @@
345
345
  * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
346
346
  * ```
347
347
  */
348
- function checkOpts(defaults, opts) {
348
+ function checkOpts$1(defaults, opts) {
349
349
  if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
350
350
  throw new TypeError('options must be object or undefined');
351
351
  const merged = Object.assign(defaults, opts);
@@ -368,7 +368,7 @@
368
368
  * wrapped(new Uint8Array([1]));
369
369
  * ```
370
370
  */
371
- function createHasher(hashCons, info = {}) {
371
+ function createHasher$1(hashCons, info = {}) {
372
372
  const hashC = (msg, opts) => hashCons(opts)
373
373
  .update(msg)
374
374
  .digest();
@@ -392,7 +392,7 @@
392
392
  * oidNist(0x01);
393
393
  * ```
394
394
  */
395
- const oidNist = (suffix) => ({
395
+ const oidNist$1 = (suffix) => ({
396
396
  // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
397
397
  // Larger suffix values would need base-128 OID encoding and a different length byte.
398
398
  oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
@@ -507,8 +507,8 @@
507
507
  this.view = createView(this.buffer);
508
508
  }
509
509
  update(data) {
510
- aexists(this);
511
- abytes(data);
510
+ aexists$1(this);
511
+ abytes$1(data);
512
512
  const { view, buffer, blockLen } = this;
513
513
  const len = data.length;
514
514
  for (let pos = 0; pos < len;) {
@@ -534,8 +534,8 @@
534
534
  return this;
535
535
  }
536
536
  digestInto(out) {
537
- aexists(this);
538
- aoutput(out, this);
537
+ aexists$1(this);
538
+ aoutput$1(out, this);
539
539
  this.finished = true;
540
540
  // Padding
541
541
  // We can avoid allocation of buffer for padding completely if it
@@ -544,7 +544,7 @@
544
544
  let { pos } = this;
545
545
  // append the bit '1' to the message
546
546
  buffer[pos++] = 0b10000000;
547
- clean(this.buffer.subarray(pos));
547
+ clean$1(this.buffer.subarray(pos));
548
548
  // we have less than padOffset left in buffer, so we cannot put length in
549
549
  // current block, need process it and pad again
550
550
  if (this.padOffset > blockLen - pos) {
@@ -617,23 +617,23 @@
617
617
  0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
618
618
  ]);
619
619
 
620
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
621
- const _32n = /* @__PURE__ */ BigInt(32);
620
+ const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
621
+ const _32n$1 = /* @__PURE__ */ BigInt(32);
622
622
  // Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
623
623
  // }` to match little-endian word order rather than the property names.
624
- function fromBig(n, le = false) {
624
+ function fromBig$1(n, le = false) {
625
625
  if (le)
626
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
627
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
626
+ return { h: Number(n & U32_MASK64$1), l: Number((n >> _32n$1) & U32_MASK64$1) };
627
+ return { h: Number((n >> _32n$1) & U32_MASK64$1) | 0, l: Number(n & U32_MASK64$1) | 0 };
628
628
  }
629
629
  // Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
630
630
  // holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
631
- function split(lst, le = false) {
631
+ function split$1(lst, le = false) {
632
632
  const len = lst.length;
633
633
  let Ah = new Uint32Array(len);
634
634
  let Al = new Uint32Array(len);
635
635
  for (let i = 0; i < len; i++) {
636
- const { h, l } = fromBig(lst[i], le);
636
+ const { h, l } = fromBig$1(lst[i], le);
637
637
  [Ah[i], Al[i]] = [h, l];
638
638
  }
639
639
  return [Ah, Al];
@@ -739,7 +739,7 @@
739
739
  ((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh));
740
740
  }
741
741
  function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
742
- anumber$1(keyLen);
742
+ anumber$2(keyLen);
743
743
  // RFC 7693 §2.1 requires digest length nn in 1..keyLen.
744
744
  if (outputLen <= 0 || outputLen > keyLen)
745
745
  throw new Error('outputLen bigger than keyLen');
@@ -748,9 +748,9 @@
748
748
  if (key !== undefined && (key.length < 1 || key.length > keyLen))
749
749
  throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
750
750
  if (salt !== undefined)
751
- abytes(salt, saltLen, 'salt');
751
+ abytes$1(salt, saltLen, 'salt');
752
752
  if (personalization !== undefined)
753
- abytes(personalization, persLen, 'personalization');
753
+ abytes$1(personalization, persLen, 'personalization');
754
754
  }
755
755
  /** Internal base class for BLAKE2. */
756
756
  class _BLAKE2 {
@@ -764,16 +764,16 @@
764
764
  outputLen;
765
765
  canXOF = false;
766
766
  constructor(blockLen, outputLen) {
767
- anumber$1(blockLen);
768
- anumber$1(outputLen);
767
+ anumber$2(blockLen);
768
+ anumber$2(outputLen);
769
769
  this.blockLen = blockLen;
770
770
  this.outputLen = outputLen;
771
771
  this.buffer = new Uint8Array(blockLen);
772
- this.buffer32 = u32(this.buffer);
772
+ this.buffer32 = u32$1(this.buffer);
773
773
  }
774
774
  update(data) {
775
- aexists(this);
776
- abytes(data);
775
+ aexists$1(this);
776
+ abytes$1(data);
777
777
  // Main difference with other hashes: there is flag for last block,
778
778
  // so we cannot process current block before we know that there
779
779
  // is the next one. This significantly complicates logic and reduces ability
@@ -785,9 +785,9 @@
785
785
  for (let pos = 0; pos < len;) {
786
786
  // If buffer is full and we still have input (don't process last block, same as blake2s)
787
787
  if (this.pos === blockLen) {
788
- swap32IfBE(buffer32);
788
+ swap32IfBE$1(buffer32);
789
789
  this.compress(buffer32, 0, false);
790
- swap32IfBE(buffer32);
790
+ swap32IfBE$1(buffer32);
791
791
  this.pos = 0;
792
792
  }
793
793
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -795,12 +795,12 @@
795
795
  // Zero-copy only for full, 4-byte-aligned, non-final blocks.
796
796
  if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
797
797
  const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
798
- swap32IfBE(data32);
798
+ swap32IfBE$1(data32);
799
799
  for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
800
800
  this.length += blockLen;
801
801
  this.compress(data32, pos32, false);
802
802
  }
803
- swap32IfBE(data32);
803
+ swap32IfBE$1(data32);
804
804
  continue;
805
805
  }
806
806
  buffer.set(data.subarray(pos, pos + take), this.pos);
@@ -811,20 +811,20 @@
811
811
  return this;
812
812
  }
813
813
  digestInto(out) {
814
- aexists(this);
815
- aoutput(out, this);
814
+ aexists$1(this);
815
+ aoutput$1(out, this);
816
816
  const { pos, buffer32 } = this;
817
817
  this.finished = true;
818
818
  // Padding
819
- clean(this.buffer.subarray(pos));
820
- swap32IfBE(buffer32);
819
+ clean$1(this.buffer.subarray(pos));
820
+ swap32IfBE$1(buffer32);
821
821
  this.compress(buffer32, 0, true);
822
- swap32IfBE(buffer32);
822
+ swap32IfBE$1(buffer32);
823
823
  // Reject unaligned views explicitly instead of hiding them behind a full scratch copy.
824
824
  if (out.byteOffset & 3)
825
825
  throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
826
826
  const state = this.get();
827
- const out32 = u32(out);
827
+ const out32 = u32$1(out);
828
828
  const full = Math.floor(this.outputLen / 4);
829
829
  for (let i = 0; i < full; i++)
830
830
  out32[i] = swap8IfBE(state[i]);
@@ -888,23 +888,23 @@
888
888
  let { key, personalization, salt } = opts;
889
889
  let keyLength = 0;
890
890
  if (key !== undefined) {
891
- abytes(key, undefined, 'key');
891
+ abytes$1(key, undefined, 'key');
892
892
  keyLength = key.length;
893
893
  }
894
894
  // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`;
895
895
  // the high 32 bits stay at `IV[0]`.
896
896
  this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
897
897
  if (salt !== undefined) {
898
- abytes(salt, undefined, 'salt');
899
- const slt = u32(salt);
898
+ abytes$1(salt, undefined, 'salt');
899
+ const slt = u32$1(salt);
900
900
  this.v4l ^= swap8IfBE(slt[0]);
901
901
  this.v4h ^= swap8IfBE(slt[1]);
902
902
  this.v5l ^= swap8IfBE(slt[2]);
903
903
  this.v5h ^= swap8IfBE(slt[3]);
904
904
  }
905
905
  if (personalization !== undefined) {
906
- abytes(personalization, undefined, 'personalization');
907
- const pers = u32(personalization);
906
+ abytes$1(personalization, undefined, 'personalization');
907
+ const pers = u32$1(personalization);
908
908
  this.v6l ^= swap8IfBE(pers[0]);
909
909
  this.v6h ^= swap8IfBE(pers[1]);
910
910
  this.v7l ^= swap8IfBE(pers[2]);
@@ -944,7 +944,7 @@
944
944
  compress(msg, offset, isLast) {
945
945
  this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
946
946
  BBUF.set(B2B_IV, 16); // Second half from IV.
947
- let { h, l } = fromBig(BigInt(this.length));
947
+ let { h, l } = fromBig$1(BigInt(this.length));
948
948
  BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.
949
949
  BBUF[25] = B2B_IV[9] ^ h; // High word.
950
950
  // Invert all bits for last block
@@ -990,11 +990,11 @@
990
990
  this.v6h ^= BBUF[13] ^ BBUF[29];
991
991
  this.v7l ^= BBUF[14] ^ BBUF[30];
992
992
  this.v7h ^= BBUF[15] ^ BBUF[31];
993
- clean(BBUF);
993
+ clean$1(BBUF);
994
994
  }
995
995
  destroy() {
996
996
  this.destroyed = true;
997
- clean(this.buffer32);
997
+ clean$1(this.buffer32);
998
998
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
999
999
  }
1000
1000
  }
@@ -1011,7 +1011,7 @@
1011
1011
  * blake2b(new Uint8Array([97, 98, 99]));
1012
1012
  * ```
1013
1013
  */
1014
- const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));
1014
+ const blake2b = /* @__PURE__ */ createHasher$1((opts) => new _BLAKE2b(opts));
1015
1015
 
1016
1016
  var _EdKey_keyPair, _EdPublicKey_key;
1017
1017
  function generateKeyPairFromSeed$1(seed) {
@@ -1387,8 +1387,8 @@
1387
1387
  finished = false;
1388
1388
  destroyed = false;
1389
1389
  constructor(hash, key) {
1390
- ahash(hash);
1391
- abytes(key, undefined, 'key');
1390
+ ahash$1(hash);
1391
+ abytes$1(key, undefined, 'key');
1392
1392
  this.iHash = hash.create();
1393
1393
  if (typeof this.iHash.update !== 'function')
1394
1394
  throw new Error('Expected instance of class which extends utils.Hash');
@@ -1408,16 +1408,16 @@
1408
1408
  for (let i = 0; i < pad.length; i++)
1409
1409
  pad[i] ^= 0x36 ^ 0x5c;
1410
1410
  this.oHash.update(pad);
1411
- clean(pad);
1411
+ clean$1(pad);
1412
1412
  }
1413
1413
  update(buf) {
1414
- aexists(this);
1414
+ aexists$1(this);
1415
1415
  this.iHash.update(buf);
1416
1416
  return this;
1417
1417
  }
1418
1418
  digestInto(out) {
1419
- aexists(this);
1420
- aoutput(out, this);
1419
+ aexists$1(this);
1420
+ aoutput$1(out, this);
1421
1421
  this.finished = true;
1422
1422
  const buf = out.subarray(0, this.outputLen);
1423
1423
  // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
@@ -1467,12 +1467,12 @@
1467
1467
  */
1468
1468
  // Common start and end for sync/async functions
1469
1469
  function pbkdf2Init(hash, _password, _salt, _opts) {
1470
- ahash(hash);
1471
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
1470
+ ahash$1(hash);
1471
+ const opts = checkOpts$1({ dkLen: 32, asyncTick: 10 }, _opts);
1472
1472
  const { c, dkLen, asyncTick } = opts;
1473
- anumber$1(c, 'c');
1474
- anumber$1(dkLen, 'dkLen');
1475
- anumber$1(asyncTick, 'asyncTick');
1473
+ anumber$2(c, 'c');
1474
+ anumber$2(dkLen, 'dkLen');
1475
+ anumber$2(asyncTick, 'asyncTick');
1476
1476
  if (c < 1)
1477
1477
  throw new Error('iterations (c) must be >= 1');
1478
1478
  // RFC 8018 §5.2 defines `dkLen` as "a positive integer".
@@ -1499,7 +1499,7 @@
1499
1499
  PRFSalt.destroy();
1500
1500
  if (prfW)
1501
1501
  prfW.destroy();
1502
- clean(u);
1502
+ clean$1(u);
1503
1503
  return DK;
1504
1504
  }
1505
1505
  /**
@@ -1630,14 +1630,14 @@
1630
1630
  this.set(A, B, C, D, E, F, G, H);
1631
1631
  }
1632
1632
  roundClean() {
1633
- clean(SHA256_W);
1633
+ clean$1(SHA256_W);
1634
1634
  }
1635
1635
  destroy() {
1636
1636
  // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
1637
1637
  // update()/digest() callable on reused instances.
1638
1638
  this.destroyed = true;
1639
1639
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
1640
- clean(this.buffer);
1640
+ clean$1(this.buffer);
1641
1641
  }
1642
1642
  }
1643
1643
  /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
@@ -1660,7 +1660,7 @@
1660
1660
  // SHA-384 / SHA-512 round constants from RFC 6234 §5.2:
1661
1661
  // 80 full 64-bit words split into high/low halves.
1662
1662
  // prettier-ignore
1663
- const K512 = /* @__PURE__ */ (() => split([
1663
+ const K512 = /* @__PURE__ */ (() => split$1([
1664
1664
  '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
1665
1665
  '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
1666
1666
  '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
@@ -1788,13 +1788,13 @@
1788
1788
  this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1789
1789
  }
1790
1790
  roundClean() {
1791
- clean(SHA512_W_H, SHA512_W_L);
1791
+ clean$1(SHA512_W_H, SHA512_W_L);
1792
1792
  }
1793
1793
  destroy() {
1794
1794
  // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
1795
1795
  // update()/digest() callable on reused instances.
1796
1796
  this.destroyed = true;
1797
- clean(this.buffer);
1797
+ clean$1(this.buffer);
1798
1798
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1799
1799
  }
1800
1800
  }
@@ -1835,8 +1835,8 @@
1835
1835
  * sha256(new Uint8Array([97, 98, 99]));
1836
1836
  * ```
1837
1837
  */
1838
- const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
1839
- /* @__PURE__ */ oidNist(0x01));
1838
+ const sha256 = /* @__PURE__ */ createHasher$1(() => new _SHA256(),
1839
+ /* @__PURE__ */ oidNist$1(0x01));
1840
1840
  /**
1841
1841
  * SHA2-512 hash function from RFC 4634.
1842
1842
  * @param msg - message bytes to hash
@@ -1847,11 +1847,11 @@
1847
1847
  * sha512(new Uint8Array([97, 98, 99]));
1848
1848
  * ```
1849
1849
  */
1850
- const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(),
1851
- /* @__PURE__ */ oidNist(0x03));
1850
+ const sha512 = /* @__PURE__ */ createHasher$1(() => new _SHA512(),
1851
+ /* @__PURE__ */ oidNist$1(0x03));
1852
1852
 
1853
1853
  /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1854
- function isBytes(a) {
1854
+ function isBytes$1(a) {
1855
1855
  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The
1856
1856
  // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized
1857
1857
  // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the
@@ -1884,7 +1884,7 @@
1884
1884
  throw new TypeError(`${label}: string expected`);
1885
1885
  return true;
1886
1886
  }
1887
- function anumber(n) {
1887
+ function anumber$1(n) {
1888
1888
  if (typeof n !== 'number')
1889
1889
  throw new TypeError(`number expected, got ${typeof n}`);
1890
1890
  if (!Number.isSafeInteger(n))
@@ -1971,7 +1971,7 @@
1971
1971
  * @__NO_SIDE_EFFECTS__
1972
1972
  */
1973
1973
  function padding(bits, chr = '=') {
1974
- anumber(bits);
1974
+ anumber$1(bits);
1975
1975
  astr('padding', chr);
1976
1976
  return {
1977
1977
  encode(data) {
@@ -2012,7 +2012,7 @@
2012
2012
  let pos = 0;
2013
2013
  const res = [];
2014
2014
  const digits = Array.from(data, (d) => {
2015
- anumber(d);
2015
+ anumber$1(d);
2016
2016
  if (d < 0 || d >= from)
2017
2017
  throw new Error(`invalid integer: ${d}`);
2018
2018
  return d;
@@ -2080,7 +2080,7 @@
2080
2080
  const mask = powers[to] - 1;
2081
2081
  const res = [];
2082
2082
  for (const n of data) {
2083
- anumber(n);
2083
+ anumber$1(n);
2084
2084
  if (n >= max)
2085
2085
  throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
2086
2086
  carry = (carry << from) | n;
@@ -2109,12 +2109,12 @@
2109
2109
  * @__NO_SIDE_EFFECTS__
2110
2110
  */
2111
2111
  function radix(num) {
2112
- anumber(num);
2112
+ anumber$1(num);
2113
2113
  const _256 = 2 ** 8;
2114
2114
  // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.
2115
2115
  return {
2116
2116
  encode: (bytes) => {
2117
- if (!isBytes(bytes))
2117
+ if (!isBytes$1(bytes))
2118
2118
  throw new TypeError('radix.encode input should be Uint8Array');
2119
2119
  return convertRadix(Array.from(bytes), _256, num);
2120
2120
  },
@@ -2130,7 +2130,7 @@
2130
2130
  * @__NO_SIDE_EFFECTS__
2131
2131
  */
2132
2132
  function radix2(bits, revPadding = false) {
2133
- anumber(bits);
2133
+ anumber$1(bits);
2134
2134
  if (bits <= 0 || bits > 32)
2135
2135
  throw new RangeError('radix2: bits should be in (0..32]');
2136
2136
  if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
@@ -2139,7 +2139,7 @@
2139
2139
  // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.
2140
2140
  return {
2141
2141
  encode: (bytes) => {
2142
- if (!isBytes(bytes))
2142
+ if (!isBytes$1(bytes))
2143
2143
  throw new TypeError('radix2.encode input should be Uint8Array');
2144
2144
  return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
2145
2145
  },
@@ -2150,7 +2150,7 @@
2150
2150
  };
2151
2151
  }
2152
2152
  function checksum(len, fn) {
2153
- anumber(len);
2153
+ anumber$1(len);
2154
2154
  // Reject degenerate zero-byte checksums up front so callers don't accidentally
2155
2155
  // build a no-op checksum stage.
2156
2156
  if (len <= 0)
@@ -2161,7 +2161,7 @@
2161
2161
  // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.
2162
2162
  return {
2163
2163
  encode(data) {
2164
- if (!isBytes(data))
2164
+ if (!isBytes$1(data))
2165
2165
  throw new TypeError('checksum.encode: input should be Uint8Array');
2166
2166
  const sum = _fn(data).slice(0, len);
2167
2167
  const res = new Uint8Array(data.length + len);
@@ -2170,7 +2170,7 @@
2170
2170
  return res;
2171
2171
  },
2172
2172
  decode(data) {
2173
- if (!isBytes(data))
2173
+ if (!isBytes$1(data))
2174
2174
  throw new TypeError('checksum.decode: input should be Uint8Array');
2175
2175
  const payload = data.slice(0, -len);
2176
2176
  const oldChecksum = data.slice(-len);
@@ -2219,7 +2219,7 @@
2219
2219
  }
2220
2220
  // BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.
2221
2221
  function aentropy(ent) {
2222
- abytes(ent);
2222
+ abytes$1(ent);
2223
2223
  if (![16, 20, 24, 28, 32].includes(ent.length))
2224
2224
  throw new RangeError('invalid entropy length');
2225
2225
  }
@@ -4768,60 +4768,2576 @@ zoo`.split('\n'));
4768
4768
  }
4769
4769
  _BLSPublicKey_key = new WeakMap();
4770
4770
 
4771
- var _InMemorySigner_key;
4772
4771
  /**
4773
- * A local implementation of the signer. Will represent a Tezos account and be able to produce signature in its behalf
4774
- *
4775
- * @remarks If running in production and dealing with tokens that have real value, it is strongly recommended to use a HSM backed signer so that private key material is not stored in memory or on disk
4776
- * @throws InvalidMnemonicError
4772
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
4773
+ * @param a - value to test
4774
+ * @returns `true` when the value is a Uint8Array-compatible view.
4775
+ * @example
4776
+ * Check whether a value is a Uint8Array-compatible view.
4777
+ * ```ts
4778
+ * isBytes(new Uint8Array([1, 2, 3]));
4779
+ * ```
4777
4780
  */
4778
- class InMemorySigner {
4779
- static fromFundraiser(email, password, mnemonic) {
4780
- if (!validateMnemonic(mnemonic, wordlist)) {
4781
- throw new InvalidMnemonicError();
4782
- }
4783
- const seed = mnemonicToSeedSync(mnemonic, `${email}${password}`);
4784
- const key = utils$1.b58Encode(seed.subarray(0, 32), utils$1.PrefixV2.Ed25519Seed);
4785
- return new InMemorySigner(key);
4781
+ function isBytes(a) {
4782
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
4783
+ // The fallback still requires a real ArrayBuffer view, so plain
4784
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
4785
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
4786
+ return (a instanceof Uint8Array ||
4787
+ (ArrayBuffer.isView(a) &&
4788
+ a.constructor.name === 'Uint8Array' &&
4789
+ 'BYTES_PER_ELEMENT' in a &&
4790
+ a.BYTES_PER_ELEMENT === 1));
4791
+ }
4792
+ // Shared error-message prefix builder. Only called on throw paths, so assert
4793
+ // success paths never pay for the string concatenation.
4794
+ const atitle$1 = (title) => (title ? `"${title}" ` : '');
4795
+ /**
4796
+ * Asserts something is a non-negative integer.
4797
+ * @param n - number to validate
4798
+ * @param title - label included in thrown errors
4799
+ * @returns The validated number.
4800
+ * @throws On wrong argument types. {@link TypeError}
4801
+ * @throws On wrong argument ranges or values. {@link RangeError}
4802
+ * @example
4803
+ * Validate a non-negative integer option.
4804
+ * ```ts
4805
+ * anumber(32, 'length');
4806
+ * ```
4807
+ */
4808
+ function anumber(n, title = '') {
4809
+ if (typeof n !== 'number')
4810
+ throw new TypeError(atitle$1(title) + 'expected number, got ' + typeof n);
4811
+ if (!Number.isSafeInteger(n) || n < 0)
4812
+ throw new RangeError(atitle$1(title) + 'expected integer >= 0, got ' + n);
4813
+ return n;
4814
+ }
4815
+ /**
4816
+ * Asserts something is a boolean.
4817
+ * @param value - value to validate
4818
+ * @param title - label included in thrown errors
4819
+ * @returns The validated boolean.
4820
+ * @throws On wrong argument types. {@link TypeError}
4821
+ * @example
4822
+ * Validate a boolean option.
4823
+ * ```ts
4824
+ * abool(true, 'enableXOF');
4825
+ * ```
4826
+ */
4827
+ function abool$1(value, title = '') {
4828
+ if (typeof value !== 'boolean')
4829
+ throw new TypeError(atitle$1(title) + 'expected boolean, got type=' + typeof value);
4830
+ return value;
4831
+ }
4832
+ /**
4833
+ * Asserts something is Uint8Array.
4834
+ * @param value - value to validate
4835
+ * @param length - optional exact length constraint
4836
+ * @param title - label included in thrown errors
4837
+ * @returns The validated byte array.
4838
+ * @throws On wrong argument types. {@link TypeError}
4839
+ * @throws On wrong argument ranges or values. {@link RangeError}
4840
+ * @example
4841
+ * Validate that a value is a byte array.
4842
+ * ```ts
4843
+ * abytes(new Uint8Array([1, 2, 3]));
4844
+ * ```
4845
+ */
4846
+ function abytes(value, length, title = '') {
4847
+ // Success path first: this runs at the start of every update() / digestInto(), and the
4848
+ // common `abytes(data)` form must not pay for length handling it does not use.
4849
+ if (isBytes(value) && (length === undefined || value.length === length))
4850
+ return value;
4851
+ // Error path: recompute freely to build the exact message.
4852
+ if (length !== undefined)
4853
+ anumber(length, 'length');
4854
+ const bytes = isBytes(value);
4855
+ const ofLen = length !== undefined ? ` of length ${length}` : '';
4856
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
4857
+ const message = atitle$1(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
4858
+ if (!bytes)
4859
+ throw new TypeError(message);
4860
+ throw new RangeError(message);
4861
+ }
4862
+ /**
4863
+ * Asserts something is a wrapped hash constructor.
4864
+ * @param h - hash constructor to validate
4865
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
4866
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
4867
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
4868
+ * @example
4869
+ * Validate a callable hash wrapper.
4870
+ * ```ts
4871
+ * import { ahash } from '@noble/hashes/utils.js';
4872
+ * import { sha256 } from '@noble/hashes/sha2.js';
4873
+ * ahash(sha256);
4874
+ * ```
4875
+ */
4876
+ function ahash(h) {
4877
+ if (typeof h !== 'function' || typeof h.create !== 'function')
4878
+ throw new TypeError('expected hash wrapped by utils.createHasher');
4879
+ anumber(h.outputLen);
4880
+ anumber(h.blockLen);
4881
+ // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
4882
+ // validation and can produce empty outputs instead of failing fast.
4883
+ if (h.outputLen < 1 || h.blockLen < 1)
4884
+ throw new Error('hash blockLen / outputLen must be >= 1');
4885
+ }
4886
+ const aobject$2 = (value, label) => {
4887
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
4888
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
4889
+ };
4890
+ const aopts = (value, label) => {
4891
+ aobject$2(value, label);
4892
+ const proto = Object.getPrototypeOf(value);
4893
+ if (proto !== Object.prototype && proto !== null)
4894
+ throw new TypeError(`"${label}" expected plain object`);
4895
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
4896
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
4897
+ if (Object.hasOwn(value, '__proto__'))
4898
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
4899
+ };
4900
+ /**
4901
+ * Asserts a hash instance has not been destroyed or finished.
4902
+ * @param instance - hash instance to validate
4903
+ * @param checkFinished - whether to reject finalized instances
4904
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
4905
+ * @example
4906
+ * Validate that a hash instance is still usable.
4907
+ * ```ts
4908
+ * import { aexists } from '@noble/hashes/utils.js';
4909
+ * import { sha256 } from '@noble/hashes/sha2.js';
4910
+ * const hash = sha256.create();
4911
+ * aexists(hash);
4912
+ * ```
4913
+ */
4914
+ function aexists(instance, checkFinished = true) {
4915
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
4916
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
4917
+ if (instance.destroyed)
4918
+ throw new Error('hash was destroyed');
4919
+ if (checkFinished && instance.finished)
4920
+ throw new Error('digest() was already called');
4921
+ }
4922
+ /**
4923
+ * Asserts output is a sufficiently-sized byte array.
4924
+ * @param out - destination buffer
4925
+ * @param instance - hash instance providing output length
4926
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
4927
+ * @throws On wrong argument types. {@link TypeError}
4928
+ * @throws On wrong argument ranges or values. {@link RangeError}
4929
+ * @example
4930
+ * Validate a caller-provided digest buffer.
4931
+ * ```ts
4932
+ * import { aoutput } from '@noble/hashes/utils.js';
4933
+ * import { sha256 } from '@noble/hashes/sha2.js';
4934
+ * const hash = sha256.create();
4935
+ * aoutput(new Uint8Array(hash.outputLen), hash);
4936
+ * ```
4937
+ */
4938
+ function aoutput(out, instance) {
4939
+ abytes(out, undefined, 'output');
4940
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
4941
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
4942
+ const min = instance.outputLen;
4943
+ if (!(out.length >= min)) {
4944
+ throw new RangeError('"output" expected length >= ' + min);
4786
4945
  }
4787
- static async fromSecretKey(key, passphrase) {
4788
- return new InMemorySigner(key, passphrase);
4946
+ }
4947
+ /**
4948
+ * Casts a typed array view to Uint32Array.
4949
+ * `arr.byteOffset` must already be 4-byte aligned or the platform
4950
+ * Uint32Array constructor will throw.
4951
+ * @param arr - source typed array
4952
+ * @returns Uint32Array view over the same buffer.
4953
+ * @example
4954
+ * Reinterpret a byte array as 32-bit words.
4955
+ * ```ts
4956
+ * u32(new Uint8Array(8));
4957
+ * ```
4958
+ */
4959
+ function u32(arr) {
4960
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
4961
+ }
4962
+ /**
4963
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
4964
+ * @param arrays - arrays to overwrite with zeros
4965
+ * @example
4966
+ * Zeroize sensitive buffers in place.
4967
+ * ```ts
4968
+ * clean(new Uint8Array([1, 2, 3]));
4969
+ * ```
4970
+ */
4971
+ function clean(...arrays) {
4972
+ for (let i = 0; i < arrays.length; i++) {
4973
+ arrays[i].fill(0);
4789
4974
  }
4790
- /**
4791
- *
4792
- * Instantiation of an InMemorySigner instance from a mnemonic
4793
- * @returns InMemorySigner
4794
- * @throws InvalidMnemonicError
4795
- */
4796
- static fromMnemonic({ mnemonic, password = '', derivationPath = "44'/1729'/0'/0'", curve = 'ed25519', }) {
4797
- // check if curve is defined if not default tz1
4798
- if (!validateMnemonic(mnemonic, wordlist)) {
4799
- // avoiding exposing mnemonic again in case of mistake making invalid
4800
- throw new InvalidMnemonicError();
4801
- }
4802
- const seed = mnemonicToSeedSync(mnemonic, password);
4803
- const sk = generateSecretKey(seed, derivationPath, curve);
4804
- return new InMemorySigner(sk);
4975
+ }
4976
+ /** Whether the current platform is little-endian. */
4977
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
4978
+ /**
4979
+ * Byte-swap operation for uint32 values.
4980
+ * @param word - source word
4981
+ * @returns Word with reversed byte order.
4982
+ * @example
4983
+ * Reverse the byte order of a 32-bit word.
4984
+ * ```ts
4985
+ * byteSwap(0x11223344);
4986
+ * ```
4987
+ */
4988
+ function byteSwap(word) {
4989
+ return (((word << 24) & 0xff000000) |
4990
+ ((word << 8) & 0xff0000) |
4991
+ ((word >>> 8) & 0xff00) |
4992
+ ((word >>> 24) & 0xff));
4993
+ }
4994
+ /**
4995
+ * Byte-swaps every word of a Uint32Array in place.
4996
+ * @param arr - array to mutate
4997
+ * @returns The same array after mutation; callers pass live state arrays here.
4998
+ * @example
4999
+ * Reverse the byte order of every word in place.
5000
+ * ```ts
5001
+ * byteSwap32(new Uint32Array([0x11223344]));
5002
+ * ```
5003
+ */
5004
+ function byteSwap32(arr) {
5005
+ for (let i = 0; i < arr.length; i++) {
5006
+ arr[i] = byteSwap(arr[i]);
4805
5007
  }
4806
- /**
4807
- *
4808
- * @param key Encoded private key
4809
- * @param passphrase Passphrase to decrypt the private key if it is encrypted
4810
- * @throws InvalidKeyError
4811
- *
4812
- */
4813
- constructor(key, passphrase) {
4814
- _InMemorySigner_key.set(this, void 0);
4815
- const keyPrefixes = [
4816
- utils$1.PrefixV2.Ed25519EncryptedSeed,
4817
- utils$1.PrefixV2.Ed25519Seed,
4818
- utils$1.PrefixV2.Ed25519SecretKey,
4819
- utils$1.PrefixV2.Secp256k1EncryptedSecretKey,
4820
- utils$1.PrefixV2.Secp256k1SecretKey,
5008
+ return arr;
5009
+ }
5010
+ /**
5011
+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.
5012
+ * @param u - array to normalize for host endianness
5013
+ * @returns Original or byte-swapped array depending on platform endianness.
5014
+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
5015
+ * @example
5016
+ * Normalize a word array for host endianness.
5017
+ * ```ts
5018
+ * swap32IfBE(new Uint32Array([0x11223344]));
5019
+ * ```
5020
+ */
5021
+ const swap32IfBE = isLE
5022
+ ? (u) => u
5023
+ : byteSwap32;
5024
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
5025
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
5026
+ // @ts-ignore
5027
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
5028
+ // Array where index 0xf0 (240) is mapped to string 'f0'
5029
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
5030
+ /**
5031
+ * Convert byte array to hex string.
5032
+ * Uses the built-in function when available and assumes it matches the tested
5033
+ * fallback semantics.
5034
+ * @param bytes - bytes to encode
5035
+ * @returns Lowercase hexadecimal string.
5036
+ * @throws On wrong argument types. {@link TypeError}
5037
+ * @example
5038
+ * Convert bytes to lowercase hexadecimal.
5039
+ * ```ts
5040
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
5041
+ * ```
5042
+ */
5043
+ function bytesToHex(bytes) {
5044
+ abytes(bytes);
5045
+ // @ts-ignore
5046
+ if (hasHexBuiltin)
5047
+ return bytes.toHex();
5048
+ // pre-caching improves the speed 6x
5049
+ let hex = '';
5050
+ for (let i = 0; i < bytes.length; i++) {
5051
+ hex += hexes[bytes[i]];
5052
+ }
5053
+ return hex;
5054
+ }
5055
+ /**
5056
+ * Copies several Uint8Arrays into one.
5057
+ * @param arrays - arrays to concatenate
5058
+ * @returns Concatenated byte array.
5059
+ * @throws On wrong argument types. {@link TypeError}
5060
+ * @example
5061
+ * Concatenate multiple byte arrays.
5062
+ * ```ts
5063
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
5064
+ * ```
5065
+ */
5066
+ function concatBytes(...arrays) {
5067
+ let sum = 0;
5068
+ for (let i = 0; i < arrays.length; i++) {
5069
+ const a = arrays[i];
5070
+ abytes(a);
5071
+ sum += a.length;
5072
+ }
5073
+ const res = new Uint8Array(sum);
5074
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
5075
+ const a = arrays[i];
5076
+ res.set(a, pad);
5077
+ pad += a.length;
5078
+ }
5079
+ return res;
5080
+ }
5081
+ /**
5082
+ * Merges default options and passed options.
5083
+ * @param defaults - base option object
5084
+ * @param opts - user overrides
5085
+ * @param title - label included in thrown override errors
5086
+ * @returns Fresh merged option object with a null prototype.
5087
+ * @throws On wrong argument types. {@link TypeError}
5088
+ * @example
5089
+ * Merge user overrides onto default options.
5090
+ * ```ts
5091
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
5092
+ * ```
5093
+ */
5094
+ function checkOpts(defaults, opts, title = 'opts') {
5095
+ aopts(defaults, 'defaults');
5096
+ if (opts !== undefined)
5097
+ aopts(opts, title);
5098
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
5099
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
5100
+ const merged = Object.assign(Object.create(null), defaults, opts);
5101
+ return merged;
5102
+ }
5103
+ /**
5104
+ * Creates a callable hash function from a stateful class constructor.
5105
+ * @param hashCons - hash constructor or factory
5106
+ * @param info - optional metadata such as DER OID
5107
+ * @returns Frozen callable hash wrapper with `.create()`.
5108
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
5109
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
5110
+ * init time.
5111
+ * @throws On wrong argument types. {@link TypeError}
5112
+ * @example
5113
+ * Wrap a stateful hash constructor into a callable helper.
5114
+ * ```ts
5115
+ * import { createHasher } from '@noble/hashes/utils.js';
5116
+ * import { sha256 } from '@noble/hashes/sha2.js';
5117
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
5118
+ * wrapped(new Uint8Array([1]));
5119
+ * ```
5120
+ */
5121
+ function createHasher(hashCons, info = {}) {
5122
+ if (typeof hashCons !== 'function')
5123
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
5124
+ info = checkOpts({}, info, 'info');
5125
+ const hashC = (msg, opts) => hashCons(opts)
5126
+ .update(msg)
5127
+ .digest();
5128
+ const tmp = hashCons(undefined);
5129
+ hashC.outputLen = tmp.outputLen;
5130
+ hashC.blockLen = tmp.blockLen;
5131
+ hashC.canXOF = tmp.canXOF;
5132
+ hashC.create = (opts) => hashCons(opts);
5133
+ Object.assign(hashC, info);
5134
+ return Object.freeze(hashC);
5135
+ }
5136
+ /**
5137
+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
5138
+ * @param bytesLength - number of random bytes to generate
5139
+ * @returns Random bytes.
5140
+ * The platform `getRandomValues()` implementation still defines any
5141
+ * single-call length cap, and this helper rejects oversize requests
5142
+ * with a stable library `RangeError` instead of host-specific errors.
5143
+ * @throws On wrong argument types. {@link TypeError}
5144
+ * @throws On wrong argument ranges or values. {@link RangeError}
5145
+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
5146
+ * @example
5147
+ * Generate a fresh random key or nonce.
5148
+ * ```ts
5149
+ * const key = randomBytes(16);
5150
+ * ```
5151
+ */
5152
+ function randomBytes$1(bytesLength = 32) {
5153
+ // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
5154
+ anumber(bytesLength, 'bytesLength');
5155
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
5156
+ if (typeof cr?.getRandomValues !== 'function')
5157
+ throw new Error('crypto.getRandomValues must be defined');
5158
+ // Web Cryptography API Level 2 §10.1.1:
5159
+ // if `byteLength > 65536`, throw `QuotaExceededError`.
5160
+ // Keep the guard explicit so callers can see the quota in code
5161
+ // instead of discovering it by reading the spec or host errors.
5162
+ // This wrapper surfaces the same quota as a stable library RangeError.
5163
+ if (bytesLength > 65536)
5164
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
5165
+ return cr.getRandomValues(new Uint8Array(bytesLength));
5166
+ }
5167
+ /**
5168
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
5169
+ * @param suffix - final OID byte for the selected hash.
5170
+ * The helper accepts any byte even though only the documented NIST hash
5171
+ * suffixes are meaningful downstream.
5172
+ * @returns Object containing the DER-encoded OID.
5173
+ * @example
5174
+ * Build OID metadata for a NIST hash.
5175
+ * ```ts
5176
+ * oidNist(0x01);
5177
+ * ```
5178
+ */
5179
+ const oidNist = (suffix) => ({
5180
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
5181
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
5182
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
5183
+ });
5184
+
5185
+ /**
5186
+ * Hex, bytes and number utilities.
5187
+ * @module
5188
+ */
5189
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5190
+ /**
5191
+ * Asserts something is a plain object-ish value, not null or array.
5192
+ * @param value - Value to validate.
5193
+ * @param title - Label included in thrown errors.
5194
+ * @returns The validated object.
5195
+ * @throws On wrong argument types. {@link TypeError}
5196
+ * @example
5197
+ * Validate an options object before checking fields.
5198
+ *
5199
+ * ```ts
5200
+ * aobject({ flag: true });
5201
+ * ```
5202
+ */
5203
+ function aobject$1(value, title = 'object') {
5204
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
5205
+ throw new TypeError(title === 'object'
5206
+ ? 'expected valid options object'
5207
+ : `"${title}" expected object, got type=${typeof value}`);
5208
+ return value;
5209
+ }
5210
+ // Shared error-message prefix builder. Only called on throw paths, so assert
5211
+ // success paths never pay for the string concatenation.
5212
+ const atitle = (title) => (title ? `"${title}" ` : '');
5213
+ /**
5214
+ * Validates that a flag is boolean.
5215
+ * @param value - Value to validate.
5216
+ * @param title - Optional field name.
5217
+ * @returns Original value.
5218
+ * @throws On wrong argument types. {@link TypeError}
5219
+ * @example
5220
+ * Reject non-boolean option flags early.
5221
+ *
5222
+ * ```ts
5223
+ * abool(true);
5224
+ * ```
5225
+ */
5226
+ function abool(value, title = '') {
5227
+ if (typeof value !== 'boolean')
5228
+ throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
5229
+ return value;
5230
+ }
5231
+ /**
5232
+ * Validates declared required and optional field types on a plain object.
5233
+ * Extra keys are intentionally ignored because many callers validate only the subset they use from
5234
+ * richer option bags or runtime objects.
5235
+ * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
5236
+ * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.
5237
+ * @param object - Object to validate.
5238
+ * @param fields - Required field types.
5239
+ * @param optFields - Optional field types.
5240
+ * @param title - Object label included in thrown errors.
5241
+ * @throws On wrong argument types. {@link TypeError}
5242
+ * @example
5243
+ * Check user options before building a curve helper.
5244
+ *
5245
+ * ```ts
5246
+ * validateObject({ flag: true }, { flag: 'boolean' });
5247
+ * ```
5248
+ */
5249
+ function validateObject(object, fields = {}, optFields = {}, title = 'object') {
5250
+ aobject$1(object, title);
5251
+ aobject$1(fields, 'fields');
5252
+ aobject$1(optFields, 'optFields');
5253
+ function checkField(fieldName, expectedType, isOpt) {
5254
+ const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
5255
+ // Config fields must be explicit own properties. Optional inherited values are rejected too
5256
+ // because callers keep reading the same options object after validation.
5257
+ const val = object[fieldName];
5258
+ // Runtime objects such as Field instances intentionally satisfy required method slots
5259
+ // via their shared prototype.
5260
+ if (!Object.hasOwn(object, fieldName) &&
5261
+ (isOpt ? val !== undefined : expectedType !== 'function')) {
5262
+ throw new TypeError(`${label} is invalid: expected own property`);
5263
+ }
5264
+ if (isOpt && val === undefined)
5265
+ return;
5266
+ const current = typeof val;
5267
+ if (current !== expectedType || val === null)
5268
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
5269
+ }
5270
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
5271
+ iter(fields, false);
5272
+ iter(optFields, true);
5273
+ }
5274
+
5275
+ const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
5276
+ const _32n = /* @__PURE__ */ BigInt(32);
5277
+ // Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
5278
+ // }` to match little-endian word order rather than the property names.
5279
+ function fromBig(n, le = false) {
5280
+ if (le)
5281
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
5282
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
5283
+ }
5284
+ // Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
5285
+ // holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
5286
+ function split(lst, le = false) {
5287
+ const len = lst.length;
5288
+ let Ah = new Uint32Array(len);
5289
+ let Al = new Uint32Array(len);
5290
+ for (let i = 0; i < len; i++) {
5291
+ const { h, l } = fromBig(lst[i], le);
5292
+ [Ah[i], Al[i]] = [h, l];
5293
+ }
5294
+ return [Ah, Al];
5295
+ }
5296
+
5297
+ /**
5298
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
5299
+ * Different from older hashes, the internal state is bigger than output size.
5300
+ *
5301
+ * Check out
5302
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},
5303
+ * {@link https://keccak.team/keccak.html | Website}, and
5304
+ * {@link https://crypto.stackexchange.com/q/15727 | the differences between
5305
+ * SHA-3 and Keccak}.
5306
+ *
5307
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
5308
+ * @module
5309
+ */
5310
+ // No __PURE__ annotations in sha3 header:
5311
+ // EVERYTHING is in fact used on every export.
5312
+ // Various per round constants calculations
5313
+ const _0n = BigInt(0);
5314
+ const _1n = BigInt(1);
5315
+ const _2n = BigInt(2);
5316
+ const _7n = BigInt(7);
5317
+ const _256n = BigInt(256);
5318
+ // FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors
5319
+ // taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.
5320
+ const _0x71n = BigInt(0x71);
5321
+ const SHA3_PI = [];
5322
+ const SHA3_ROTL = [];
5323
+ const _SHA3_IOTA = []; // no pure annotation: var is always used
5324
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
5325
+ // Pi
5326
+ [x, y] = [y, (2 * x + 3 * y) % 5];
5327
+ SHA3_PI.push(2 * (5 * y + x));
5328
+ // Rotational
5329
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
5330
+ // Iota
5331
+ let t = _0n;
5332
+ for (let j = 0; j < 7; j++) {
5333
+ R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
5334
+ if (R & _2n)
5335
+ t ^= _1n << ((_1n << BigInt(j)) - _1n);
5336
+ }
5337
+ _SHA3_IOTA.push(t);
5338
+ }
5339
+ const IOTAS = split(_SHA3_IOTA, true);
5340
+ // `split(..., true)` keeps the local little-endian lane-word layout used by
5341
+ // `state32`, so these `H` / `L` tables follow the file's first-word /
5342
+ // second-word lane slots rather than `_u64.ts`'s usual high/low naming.
5343
+ const SHA3_IOTA_H = IOTAS[0];
5344
+ const SHA3_IOTA_L = IOTAS[1];
5345
+ // 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can
5346
+ // inline them into keccakP — the import path costs ~24% on sha3_256. SHA3 is the only
5347
+ // consumer of left-rotates; other hashes use right-rotates from _u64.
5348
+ // Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.
5349
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
5350
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
5351
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
5352
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
5353
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
5354
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
5355
+ // Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.
5356
+ // keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.
5357
+ const B = new Uint32Array(5 * 2);
5358
+ /**
5359
+ * `keccakf1600` internal permutation, additionally allows adjusting the round count.
5360
+ * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
5361
+ * in this file's local little-endian lane-word order
5362
+ * @param rounds - number of rounds to execute
5363
+ * @throws On wrong argument types. {@link TypeError}
5364
+ * @throws On wrong argument ranges or values. {@link RangeError}
5365
+ * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
5366
+ * @example
5367
+ * Permute a Keccak state with the default 24 rounds.
5368
+ * ```ts
5369
+ * keccakP(new Uint32Array(50));
5370
+ * ```
5371
+ */
5372
+ function keccakP(s, rounds = 24) {
5373
+ if (!(s instanceof Uint32Array))
5374
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
5375
+ if (s.length !== 50)
5376
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
5377
+ anumber(rounds, 'rounds');
5378
+ // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.
5379
+ if (rounds < 1 || rounds > 24)
5380
+ throw new Error('"rounds" expected integer 1..24');
5381
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
5382
+ for (let round = 24 - rounds; round < 24; round++) {
5383
+ // Theta θ
5384
+ for (let x = 0; x < 10; x++)
5385
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
5386
+ for (let x = 0; x < 10; x += 2) {
5387
+ const idx1 = (x + 8) % 10;
5388
+ const idx0 = (x + 2) % 10;
5389
+ const B0 = B[idx0];
5390
+ const B1 = B[idx0 + 1];
5391
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
5392
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
5393
+ for (let y = 0; y < 50; y += 10) {
5394
+ s[x + y] ^= Th;
5395
+ s[x + y + 1] ^= Tl;
5396
+ }
5397
+ }
5398
+ // Rho (ρ) and Pi (π)
5399
+ let curH = s[2];
5400
+ let curL = s[3];
5401
+ for (let t = 0; t < 24; t++) {
5402
+ const shift = SHA3_ROTL[t];
5403
+ const Th = rotlH(curH, curL, shift);
5404
+ const Tl = rotlL(curH, curL, shift);
5405
+ const PI = SHA3_PI[t];
5406
+ curH = s[PI];
5407
+ curL = s[PI + 1];
5408
+ s[PI] = Th;
5409
+ s[PI + 1] = Tl;
5410
+ }
5411
+ // Chi (χ)
5412
+ // Same as:
5413
+ // for (let x = 0; x < 10; x++) B[x] = s[y + x];
5414
+ // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
5415
+ for (let y = 0; y < 50; y += 10) {
5416
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
5417
+ s[y] ^= ~s[y + 2] & s[y + 4];
5418
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
5419
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
5420
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
5421
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
5422
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
5423
+ s[y + 6] ^= ~s[y + 8] & b0;
5424
+ s[y + 7] ^= ~s[y + 9] & b1;
5425
+ s[y + 8] ^= ~b0 & b2;
5426
+ s[y + 9] ^= ~b1 & b3;
5427
+ }
5428
+ // Iota (ι)
5429
+ s[0] ^= SHA3_IOTA_H[round];
5430
+ s[1] ^= SHA3_IOTA_L[round];
5431
+ }
5432
+ clean(B);
5433
+ }
5434
+ /**
5435
+ * Keccak sponge function.
5436
+ * @param blockLen - absorb/squeeze rate in bytes
5437
+ * @param suffix - domain separation suffix byte
5438
+ * @param outputLen - default digest length in bytes. This base sponge only
5439
+ * requires a non-negative integer; wrappers that need positive output
5440
+ * lengths must enforce that themselves.
5441
+ * @param enableXOF - whether XOF output is allowed
5442
+ * @param rounds - number of Keccak-f rounds
5443
+ * @example
5444
+ * Build a sponge state, absorb bytes, then finalize a digest.
5445
+ * ```ts
5446
+ * const hash = new Keccak(136, 0x06, 32);
5447
+ * hash.update(new Uint8Array([1, 2, 3]));
5448
+ * hash.digest();
5449
+ * ```
5450
+ */
5451
+ class Keccak {
5452
+ state;
5453
+ pos = 0;
5454
+ posOut = 0;
5455
+ finished = false;
5456
+ state32;
5457
+ destroyed = false;
5458
+ blockLen;
5459
+ suffix;
5460
+ outputLen;
5461
+ canXOF;
5462
+ enableXOF = false;
5463
+ rounds;
5464
+ // NOTE: we accept arguments in bytes instead of bits here.
5465
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
5466
+ anumber(blockLen, 'blockLen');
5467
+ anumber(suffix, 'suffix');
5468
+ anumber(rounds, 'rounds');
5469
+ abool$1(enableXOF, 'enableXOF');
5470
+ this.blockLen = blockLen;
5471
+ this.suffix = suffix;
5472
+ this.outputLen = outputLen;
5473
+ this.enableXOF = enableXOF;
5474
+ this.canXOF = enableXOF;
5475
+ this.rounds = rounds;
5476
+ // Can be passed from user as dkLen
5477
+ anumber(outputLen, 'outputLen');
5478
+ // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.
5479
+ if (!(0 < blockLen && blockLen < 200))
5480
+ throw new Error('"blockLen" must be 1..199');
5481
+ this.state = new Uint8Array(200);
5482
+ this.state32 = u32(this.state);
5483
+ }
5484
+ clone() {
5485
+ return this._cloneInto();
5486
+ }
5487
+ keccak() {
5488
+ swap32IfBE(this.state32);
5489
+ keccakP(this.state32, this.rounds);
5490
+ swap32IfBE(this.state32);
5491
+ this.posOut = 0;
5492
+ this.pos = 0;
5493
+ }
5494
+ update(data) {
5495
+ aexists(this);
5496
+ abytes(data);
5497
+ const { blockLen, state, state32 } = this;
5498
+ const len = data.length;
5499
+ // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.
5500
+ // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.
5501
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
5502
+ const blockLen32 = blockLen / 4;
5503
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;
5504
+ for (let pos = 0; pos < len;) {
5505
+ if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
5506
+ for (let i = 0, o = pos / 4; i < blockLen32; i++)
5507
+ state32[i] ^= data32[o + i];
5508
+ pos += blockLen;
5509
+ // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,
5510
+ // so it must reflect the fully-absorbed block before the permutation fires.
5511
+ this.pos = blockLen;
5512
+ this.keccak();
5513
+ continue;
5514
+ }
5515
+ const take = Math.min(blockLen - this.pos, len - pos);
5516
+ for (let i = 0; i < take; i++)
5517
+ state[this.pos++] ^= data[pos++];
5518
+ if (this.pos === blockLen)
5519
+ this.keccak();
5520
+ }
5521
+ return this;
5522
+ }
5523
+ finish() {
5524
+ if (this.finished)
5525
+ return;
5526
+ this.finished = true;
5527
+ const { state, suffix, pos, blockLen } = this;
5528
+ // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.
5529
+ // These byte values already include the first padding bit, while the
5530
+ // final `0x80` below supplies the closing `1` bit in the last rate byte.
5531
+ state[pos] ^= suffix;
5532
+ // If that combined suffix lands in the last rate byte and already sets
5533
+ // bit 7, absorb it first so the final pad10*1 bit can be xored into a
5534
+ // fresh block.
5535
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
5536
+ this.keccak();
5537
+ state[blockLen - 1] ^= 0x80;
5538
+ this.keccak();
5539
+ }
5540
+ writeInto(out) {
5541
+ aexists(this, false);
5542
+ abytes(out);
5543
+ this.finish();
5544
+ const bufferOut = this.state;
5545
+ const { blockLen } = this;
5546
+ for (let pos = 0, len = out.length; pos < len;) {
5547
+ if (this.posOut >= blockLen)
5548
+ this.keccak();
5549
+ const take = Math.min(blockLen - this.posOut, len - pos);
5550
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
5551
+ this.posOut += take;
5552
+ pos += take;
5553
+ }
5554
+ return out;
5555
+ }
5556
+ xofInto(out) {
5557
+ // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base
5558
+ // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/
5559
+ // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.
5560
+ if (!this.enableXOF)
5561
+ throw new Error('XOF is not enabled');
5562
+ return this.writeInto(out);
5563
+ }
5564
+ xof(bytes) {
5565
+ anumber(bytes);
5566
+ return this.xofInto(new Uint8Array(bytes));
5567
+ }
5568
+ digestInto(out) {
5569
+ aoutput(out, this);
5570
+ if (this.finished)
5571
+ throw new Error('digest() was already called');
5572
+ // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.
5573
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
5574
+ this.destroy();
5575
+ }
5576
+ digest() {
5577
+ const out = new Uint8Array(this.outputLen);
5578
+ this.digestInto(out);
5579
+ return out;
5580
+ }
5581
+ destroy() {
5582
+ this.destroyed = true;
5583
+ clean(this.state);
5584
+ }
5585
+ _cloneInto(to) {
5586
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
5587
+ to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
5588
+ // Reused destinations can come from a different rate/capacity variant, so clone must rewrite
5589
+ // the sponge geometry as well as the state words.
5590
+ to.blockLen = blockLen;
5591
+ to.state32.set(this.state32);
5592
+ // Sponge padding and XOF output are positional, so both offsets are part of the clone state.
5593
+ to.pos = this.pos;
5594
+ to.posOut = this.posOut;
5595
+ to.finished = this.finished;
5596
+ to.rounds = rounds;
5597
+ // Suffix can change in cSHAKE
5598
+ to.suffix = suffix;
5599
+ to.outputLen = outputLen;
5600
+ to.enableXOF = enableXOF;
5601
+ // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone
5602
+ // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.
5603
+ to.canXOF = this.canXOF;
5604
+ to.destroyed = this.destroyed;
5605
+ return to;
5606
+ }
5607
+ }
5608
+ const genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {
5609
+ opts = checkOpts({}, opts);
5610
+ return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);
5611
+ }, info);
5612
+ /**
5613
+ * SHAKE128 XOF with 128-bit security and a 16-byte default output.
5614
+ * @param msg - message bytes to hash
5615
+ * @param opts - Optional output-length override. See {@link ShakeOpts}.
5616
+ * @returns Digest bytes.
5617
+ * @example
5618
+ * Hash a message with SHAKE128.
5619
+ * ```ts
5620
+ * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });
5621
+ * ```
5622
+ */
5623
+ const shake128 =
5624
+ /* @__PURE__ */
5625
+ genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));
5626
+ /**
5627
+ * SHAKE256 XOF with 256-bit security and a 32-byte default output.
5628
+ * @param msg - message bytes to hash
5629
+ * @param opts - Optional output-length override. See {@link ShakeOpts}.
5630
+ * @returns Digest bytes.
5631
+ * @example
5632
+ * Hash a message with SHAKE256.
5633
+ * ```ts
5634
+ * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });
5635
+ * ```
5636
+ */
5637
+ const shake256 =
5638
+ /* @__PURE__ */
5639
+ genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));
5640
+
5641
+ /**
5642
+ * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
5643
+ * API may change at any time. The code has not been audited. Feature requests are welcome.
5644
+ * @module
5645
+ */
5646
+ function checkU32(n, title = 'n') {
5647
+ // 0xff_ff_ff_ff
5648
+ if (typeof n !== 'number')
5649
+ throw new TypeError(`wrong u32 integer "${title}": expected number, got type=${typeof n}`);
5650
+ if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
5651
+ throw new RangeError(`wrong u32 integer "${title}": expected 0..4294967295, got ${n}`);
5652
+ return n;
5653
+ }
5654
+ /**
5655
+ * Checks if integer is in form of `1 << X`.
5656
+ * @param x - Integer to inspect.
5657
+ * @returns `true` when the value is a power of two.
5658
+ * @example
5659
+ * Validate that an FFT size is a power of two.
5660
+ *
5661
+ * ```ts
5662
+ * isPowerOfTwo(8);
5663
+ * ```
5664
+ */
5665
+ function isPowerOfTwo(x) {
5666
+ checkU32(x, 'x');
5667
+ return (x & (x - 1)) === 0 && x !== 0;
5668
+ }
5669
+ /**
5670
+ * @param n - Value to reverse.
5671
+ * @param bits - Number of bits to use.
5672
+ * @returns Bit-reversed integer.
5673
+ * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
5674
+ * @example
5675
+ * Reverse the low `bits` bits of one index.
5676
+ *
5677
+ * ```ts
5678
+ * reverseBits(3, 3);
5679
+ * ```
5680
+ */
5681
+ function reverseBits(n, bits) {
5682
+ checkU32(n);
5683
+ if (typeof bits !== 'number')
5684
+ throw new TypeError('"bits" expected number, got type=' + typeof bits);
5685
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
5686
+ throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
5687
+ let reversed = 0;
5688
+ for (let i = 0; i < bits; i++, n >>>= 1)
5689
+ reversed = (reversed << 1) | (n & 1);
5690
+ // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.
5691
+ return reversed >>> 0;
5692
+ }
5693
+ /**
5694
+ * Similar to `bitLen(x)-1` but much faster for small integers, like indices.
5695
+ * @param n - Input value.
5696
+ * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.
5697
+ * @example
5698
+ * Compute the radix-2 stage count for one transform size.
5699
+ *
5700
+ * ```ts
5701
+ * log2(8);
5702
+ * ```
5703
+ */
5704
+ function log2(n) {
5705
+ checkU32(n);
5706
+ return 31 - Math.clz32(n);
5707
+ }
5708
+ /**
5709
+ * Moves lowest bit to highest position, which at first step splits
5710
+ * array on even and odd indices, then it applied again to each part,
5711
+ * which is core of fft
5712
+ * @param values - Mutable coefficient array.
5713
+ * @returns Mutated input array.
5714
+ * @throws If the array length is not a positive power of two. {@link Error}
5715
+ * @example
5716
+ * Reorder coefficients into bit-reversed order in place.
5717
+ *
5718
+ * ```ts
5719
+ * const values = Uint8Array.from([0, 1, 2, 3]);
5720
+ * bitReversalInplace(values);
5721
+ * ```
5722
+ */
5723
+ function bitReversalInplace(values) {
5724
+ if (!values ||
5725
+ typeof values !== 'object' ||
5726
+ typeof values.length !== 'number')
5727
+ throw new TypeError('"values" expected array-like, got type=' + typeof values);
5728
+ const n = values.length;
5729
+ // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.
5730
+ if (!isPowerOfTwo(n))
5731
+ throw new Error('expected positive power-of-two length, got ' + n);
5732
+ const bits = log2(n);
5733
+ for (let i = 0; i < n; i++) {
5734
+ const j = reverseBits(i, bits);
5735
+ if (i < j) {
5736
+ const tmp = values[i];
5737
+ values[i] = values[j];
5738
+ values[j] = tmp;
5739
+ }
5740
+ }
5741
+ return values;
5742
+ }
5743
+ /**
5744
+ * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
5745
+ *
5746
+ * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cooley-Tukey
5747
+ * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande
5748
+ *
5749
+ * DIT takes brp input, returns natural output.
5750
+ * DIF takes natural input, returns brp output.
5751
+ *
5752
+ * The output is actually identical. Time / frequence distinction is not meaningful
5753
+ * for Polynomial multiplication in fields.
5754
+ * Which means if protocol supports/needs brp output/inputs, then we can skip this step.
5755
+ *
5756
+ * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
5757
+ * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
5758
+ *
5759
+ * `invertButterflies` indexes roots by a per-butterfly-group counter (`grp`): forward
5760
+ * (`dit: false`) reads `roots[grp]` with grp = 1..; inverse (`dit: true`) reads `roots[N - grp]`
5761
+ * with grp restarting at 1. With `skipStages: 0` one table serves both directions (ωᴺ = 1 makes
5762
+ * the reversed walk self-inverse). With `skipStages > 0` the inverse walk starts at `N - 1`
5763
+ * instead of continuing where the skipped stages would have left off, so the caller must supply
5764
+ * a table shaped for that (ML-KEM: `ζ^BitRev7(i)` over all N=256 indices, whose aliased upper
5765
+ * half is exactly the FIPS 203 inverse walk).
5766
+ * @param F - Field operations.
5767
+ * @param coreOpts - FFT configuration. See {@link FFTCoreOpts}:
5768
+ * - `N`: Transform size. Must be a power of two.
5769
+ * - `roots`: Stage roots for the selected transform size.
5770
+ * - `dit`: Whether to run the DIT variant instead of DIF.
5771
+ * - `invertButterflies` (optional): Whether to invert butterfly placement.
5772
+ * - `skipStages` (optional): Number of initial stages to skip.
5773
+ * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.
5774
+ * @returns Low-level FFT loop.
5775
+ * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}
5776
+ * @example
5777
+ * Constructs different flavors of FFT.
5778
+ *
5779
+ * ```ts
5780
+ * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';
5781
+ * import { Field } from '@noble/curves/abstract/modular.js';
5782
+ * const Fp = Field(17n);
5783
+ * const roots = rootsOfUnity(Fp).roots(2);
5784
+ * const loop = FFTCore(Fp, { N: 4, roots, dit: true });
5785
+ * const values = loop([1n, 2n, 3n, 4n]);
5786
+ * ```
5787
+ */
5788
+ const FFTCore = (F, coreOpts) => {
5789
+ validateObject(coreOpts, { N: 'number', roots: 'object', dit: 'boolean' }, { invertButterflies: 'boolean', skipStages: 'number', brp: 'boolean' }, 'coreOpts');
5790
+ const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
5791
+ checkU32(N, 'coreOpts.N');
5792
+ const bits = log2(N);
5793
+ if (!isPowerOfTwo(N))
5794
+ throw new Error('FFT: Polynomial size should be power of two');
5795
+ checkU32(skipStages, 'coreOpts.skipStages');
5796
+ const maxSkipStages = bits === 0 ? 0 : bits - 1;
5797
+ // Skipping every stage leaves only boundary layout changes, not a valid FFT loop shape.
5798
+ if (skipStages > maxSkipStages)
5799
+ throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);
5800
+ // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.
5801
+ if (roots.length !== N)
5802
+ throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);
5803
+ const isDit = dit !== invertButterflies;
5804
+ return (values) => {
5805
+ if (values.length !== N)
5806
+ throw new Error('FFT: wrong Polynomial length');
5807
+ if (dit && brp)
5808
+ bitReversalInplace(values);
5809
+ for (let i = 0, g = 1; i < bits - skipStages; i++) {
5810
+ // For each stage s (sub-FFT length m = 2^s)
5811
+ const s = dit ? i + 1 + skipStages : bits - i;
5812
+ const m = 1 << s;
5813
+ const m2 = m >> 1;
5814
+ const stride = N >> s;
5815
+ // Loop over each subarray of length m
5816
+ for (let k = 0; k < N; k += m) {
5817
+ // Loop over each butterfly within the subarray
5818
+ for (let j = 0, grp = g++; j < m2; j++) {
5819
+ const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
5820
+ const i0 = k + j;
5821
+ const i1 = k + j + m2;
5822
+ const omega = roots[rootPos];
5823
+ const b = values[i1];
5824
+ const a = values[i0];
5825
+ // Inlining gives us 10% perf in kyber vs functions
5826
+ if (isDit) {
5827
+ const t = F.mul(b, omega); // Standard DIT butterfly
5828
+ values[i0] = F.add(a, t);
5829
+ values[i1] = F.sub(a, t);
5830
+ }
5831
+ else if (invertButterflies) {
5832
+ values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
5833
+ values[i1] = F.mul(F.sub(b, a), omega);
5834
+ }
5835
+ else {
5836
+ values[i0] = F.add(a, b); // Standard DIF butterfly
5837
+ values[i1] = F.mul(F.sub(a, b), omega);
5838
+ }
5839
+ }
5840
+ }
5841
+ }
5842
+ if (!dit && brp)
5843
+ bitReversalInplace(values);
5844
+ return values;
5845
+ };
5846
+ };
5847
+
5848
+ /**
5849
+ * Utilities for hex, bytearray and number handling.
5850
+ * @module
5851
+ */
5852
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
5853
+ /**
5854
+ * Asserts that a value is a byte array and optionally checks its length.
5855
+ * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`
5856
+ * values through the upstream validator.
5857
+ * This helper throws on malformed input, so APIs that must return `false` need to guard lengths
5858
+ * before decoding or before calling it.
5859
+ * @example
5860
+ * Validate that a value is a byte array with the expected length.
5861
+ * ```ts
5862
+ * abytes(new Uint8Array([1]), 1);
5863
+ * ```
5864
+ */
5865
+ const abytesDoc = abytes;
5866
+ /**
5867
+ * Returns cryptographically secure random bytes.
5868
+ * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.
5869
+ * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,
5870
+ * so negative and fractional values both throw instead of truncating through JS `ToIndex`.
5871
+ * @param bytesLength - Number of random bytes to generate.
5872
+ * @returns Fresh random bytes.
5873
+ * @example
5874
+ * Generate a fresh random seed.
5875
+ * ```ts
5876
+ * const seed = randomBytes(4);
5877
+ * ```
5878
+ */
5879
+ const randomBytes = randomBytes$1;
5880
+ function aarray(item, title, inner = () => { }) {
5881
+ if (!Array.isArray(item))
5882
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
5883
+ for (let i = 0; i < item.length; i++)
5884
+ inner(item[i], `${title}[${i}]`);
5885
+ return item;
5886
+ }
5887
+ function aobject(value, title = 'object') {
5888
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
5889
+ throw new TypeError(title === 'object'
5890
+ ? 'expected valid options object'
5891
+ : `"${title}" expected object, got type=${typeof value}`);
5892
+ return value;
5893
+ }
5894
+ /**
5895
+ * Compares two byte arrays in a length-constant way for equal lengths.
5896
+ * Inputs are validated as byte arrays; unequal lengths return `false` immediately.
5897
+ * @param a - First byte array.
5898
+ * @param b - Second byte array.
5899
+ * @returns Whether both arrays contain the same bytes.
5900
+ * @example
5901
+ * Compare two byte arrays for equality.
5902
+ * ```ts
5903
+ * equalBytes(new Uint8Array([1]), new Uint8Array([1]));
5904
+ * ```
5905
+ */
5906
+ function equalBytes(a, b) {
5907
+ a = abytes(a);
5908
+ b = abytes(b);
5909
+ if (a.length !== b.length)
5910
+ return false;
5911
+ let diff = 0;
5912
+ for (let i = 0; i < a.length; i++)
5913
+ diff |= a[i] ^ b[i];
5914
+ return diff === 0;
5915
+ }
5916
+ /**
5917
+ * Validates that an options bag is a plain object.
5918
+ * @param opts - Options object to validate.
5919
+ * @throws On wrong argument types. {@link TypeError}
5920
+ * @example
5921
+ * Validate that an options bag is a plain object.
5922
+ * ```ts
5923
+ * validateOpts({});
5924
+ * ```
5925
+ */
5926
+ function validateOpts(opts) {
5927
+ // Arrays silently passed here before, but these call sites expect named option-bag fields.
5928
+ if (isBytes(opts))
5929
+ throw new TypeError('"opts" expected object, got Uint8Array');
5930
+ aobject(opts, 'opts');
5931
+ const proto = Object.getPrototypeOf(opts);
5932
+ // Options are security parameters, not general class instances. Restricting the bag to own
5933
+ // properties prevents values injected through Object.prototype (or a custom shared prototype)
5934
+ // from silently changing signing behavior. Null-prototype records remain supported.
5935
+ if (proto !== null && proto !== Object.prototype)
5936
+ throw new TypeError('"opts" expected a plain object');
5937
+ }
5938
+ // Frozen because they are exported: an unfrozen array export lets anything in the
5939
+ // process push a key onto the accepted set and silently re-open exactly the hole this
5940
+ // validation closes.
5941
+ /** Keys accepted by `verify`. */
5942
+ const VER_OPT_KEYS = /* @__PURE__ */ Object.freeze([
5943
+ 'context',
5944
+ ]);
5945
+ /** Keys accepted by `sign`. */
5946
+ const SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([
5947
+ 'context',
5948
+ 'extraEntropy',
5949
+ ]);
5950
+ /**
5951
+ * Rejects option keys the caller did not mean to set.
5952
+ *
5953
+ * Validating the types of known keys while ignoring unknown ones makes a typo
5954
+ * indistinguishable from an omission, and for these options an omission is a
5955
+ * security downgrade rather than a no-op: `{ ctx }` instead of `{ context }` signs
5956
+ * with no domain separation, succeeds, and verifies for anyone who also supplies
5957
+ * none. Nothing at any layer reports it. TypeScript catches this through excess
5958
+ * property checks, so the exposure is JavaScript callers specifically.
5959
+ *
5960
+ * @param opts - Options object to check.
5961
+ * @param allowed - The keys this call site accepts.
5962
+ * Returns a frozen null-prototype snapshot so later reads cannot fall through to a polluted
5963
+ * prototype. Like `checkOpts()` in noble-hashes, only enumerable own properties are copied.
5964
+ * @throws If any other copied key is present or the bag has a custom prototype. {@link TypeError}
5965
+ * @returns Sanitized snapshot of the enumerable own options.
5966
+ * @example
5967
+ * Accept a known option key. A key the list does not name, such as `ctx`, throws instead.
5968
+ * ```ts
5969
+ * import { checkOptKeys } from '@noble/post-quantum/utils.js';
5970
+ * checkOptKeys({ context: new Uint8Array() }, ['context']);
5971
+ * ```
5972
+ */
5973
+ function checkOptKeys(opts, allowed) {
5974
+ validateOpts(opts);
5975
+ // Snapshot once before validation: Object.assign follows the same own-enumerable option-bag
5976
+ // semantics as noble-hashes, while the null prototype keeps omitted fields immune to pollution.
5977
+ const normalized = Object.assign(Object.create(null), opts);
5978
+ for (const [k, v] of Object.entries(normalized)) {
5979
+ // `undefined` means unset everywhere else in these validators, and building an options bag by
5980
+ // spread is a normal way to reach these calls, so present-but-undefined stays equivalent to
5981
+ // omission.
5982
+ if (v === undefined)
5983
+ continue;
5984
+ if (!allowed.includes(k))
5985
+ throw new TypeError('unexpected option "' + String(k) + '"; expected one of: ' + allowed.join(', '));
5986
+ }
5987
+ return Object.freeze(normalized);
5988
+ }
5989
+ /**
5990
+ * Validates common verification options.
5991
+ * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support
5992
+ * further after this shared plain-object gate.
5993
+ * @param opts - Verification options. See {@link VerOpts}.
5994
+ * @param allowed - Keys this call site accepts. Defaults to {@link VER_OPT_KEYS}; surfaces that
5995
+ * take extra keys, or take fewer, pass their own list.
5996
+ * @throws On wrong argument types. {@link TypeError}
5997
+ * @returns Frozen null-prototype snapshot of the validated options.
5998
+ * @example
5999
+ * Validate common verification options.
6000
+ * ```ts
6001
+ * validateVerOpts({ context: new Uint8Array([1]) });
6002
+ * ```
6003
+ */
6004
+ function validateVerOpts(opts, allowed = VER_OPT_KEYS) {
6005
+ const normalized = checkOptKeys(opts, allowed);
6006
+ if (normalized.context !== undefined)
6007
+ abytes(normalized.context, undefined, 'opts.context');
6008
+ return normalized;
6009
+ }
6010
+ /**
6011
+ * Validates common signing options.
6012
+ * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific
6013
+ * restrictions are enforced later by callers.
6014
+ * @param opts - Signing options. See {@link SigOpts}.
6015
+ * @param allowed - Keys this call site accepts. Defaults to {@link SIG_OPT_KEYS}; surfaces that
6016
+ * take extra keys, or take fewer, pass their own list.
6017
+ * @throws On wrong argument types. {@link TypeError}
6018
+ * @returns Frozen null-prototype snapshot of the validated options.
6019
+ * @example
6020
+ * Validate common signing options.
6021
+ * ```ts
6022
+ * validateSigOpts({ extraEntropy: new Uint8Array([1]) });
6023
+ * ```
6024
+ */
6025
+ function validateSigOpts(opts, allowed = SIG_OPT_KEYS) {
6026
+ const normalized = checkOptKeys(opts, allowed);
6027
+ if (normalized.context !== undefined)
6028
+ abytes(normalized.context, undefined, 'opts.context');
6029
+ if (normalized.extraEntropy !== false && normalized.extraEntropy !== undefined)
6030
+ abytes(normalized.extraEntropy, undefined, 'opts.extraEntropy');
6031
+ return normalized;
6032
+ }
6033
+ /**
6034
+ * Builds a fixed-layout coder from byte lengths and nested coders.
6035
+ * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that
6036
+ * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`
6037
+ * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards
6038
+ * caller-owned bytes, it must do so only after detaching them into a disposable copy.
6039
+ * @param label - Label used in validation errors.
6040
+ * @param lengths - Field lengths or nested coders.
6041
+ * @returns Composite fixed-length coder.
6042
+ * @example
6043
+ * Build a fixed-layout coder from byte lengths and nested coders.
6044
+ * ```ts
6045
+ * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);
6046
+ * ```
6047
+ */
6048
+ function splitCoder(label, ...lengths) {
6049
+ const getLength = (c) => typeof c === 'number' ? c : c.bytesLen;
6050
+ const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
6051
+ return {
6052
+ bytesLen,
6053
+ encode: (bufs) => {
6054
+ const res = new Uint8Array(bytesLen);
6055
+ for (let i = 0, pos = 0; i < lengths.length; i++) {
6056
+ const c = lengths[i];
6057
+ const l = getLength(c);
6058
+ const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]);
6059
+ abytes(b, l, label);
6060
+ res.set(b, pos);
6061
+ if (typeof c !== 'number')
6062
+ b.fill(0); // clean
6063
+ pos += l;
6064
+ }
6065
+ return res;
6066
+ },
6067
+ decode: (buf) => {
6068
+ abytes(buf, bytesLen, label);
6069
+ const res = [];
6070
+ for (const c of lengths) {
6071
+ const l = getLength(c);
6072
+ const b = buf.subarray(0, l);
6073
+ res.push(typeof c === 'number' ? b : c.decode(b));
6074
+ buf = buf.subarray(l);
6075
+ }
6076
+ return res;
6077
+ },
6078
+ };
6079
+ }
6080
+ // nano-packed.array (fixed size)
6081
+ /**
6082
+ * Builds a fixed-length vector coder from another fixed-length coder.
6083
+ * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.
6084
+ * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into
6085
+ * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned
6086
+ * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts
6087
+ * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.
6088
+ * @param c - Element coder.
6089
+ * @param vecLen - Number of elements in the vector.
6090
+ * @returns Fixed-length vector coder.
6091
+ * @example
6092
+ * Build a fixed-length vector coder from another fixed-length coder.
6093
+ * ```ts
6094
+ * vecCoder(
6095
+ * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },
6096
+ * 2
6097
+ * ).encode([1, 2]);
6098
+ * ```
6099
+ */
6100
+ function vecCoder(c, vecLen) {
6101
+ const coder = c;
6102
+ const bytesLen = vecLen * coder.bytesLen;
6103
+ return {
6104
+ bytesLen,
6105
+ encode: (u) => {
6106
+ const uArr = aarray(u, 'u');
6107
+ if (uArr.length !== vecLen)
6108
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
6109
+ const res = new Uint8Array(bytesLen);
6110
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
6111
+ const b = coder.encode(uArr[i]);
6112
+ res.set(b, pos);
6113
+ b.fill(0); // clean
6114
+ pos += b.length;
6115
+ }
6116
+ return res;
6117
+ },
6118
+ decode: (a) => {
6119
+ abytes(a, bytesLen);
6120
+ const r = [];
6121
+ for (let i = 0; i < a.length; i += coder.bytesLen)
6122
+ r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
6123
+ return r;
6124
+ },
6125
+ };
6126
+ }
6127
+ /**
6128
+ * Overwrites supported typed-array inputs with zeroes in place.
6129
+ * Accepts direct typed arrays and one-level arrays of them.
6130
+ * @param list - Typed arrays or one-level lists of typed arrays to clear.
6131
+ * @example
6132
+ * Overwrite typed arrays with zeroes.
6133
+ * ```ts
6134
+ * const buf = Uint8Array.of(1, 2, 3);
6135
+ * cleanBytes(buf);
6136
+ * ```
6137
+ */
6138
+ function cleanBytes(...list) {
6139
+ for (const t of list) {
6140
+ if (Array.isArray(t))
6141
+ for (const b of t)
6142
+ b.fill(0);
6143
+ else
6144
+ t.fill(0);
6145
+ }
6146
+ }
6147
+ /**
6148
+ * Creates a 32-bit mask with the lowest `bits` bits set.
6149
+ * @param bits - Number of low bits to keep.
6150
+ * @returns Bit mask with `bits` ones.
6151
+ * @throws On wrong argument types. {@link TypeError}
6152
+ * @throws On wrong argument ranges or values. {@link RangeError}
6153
+ * @example
6154
+ * Create a low-bit mask for packed-field operations.
6155
+ * ```ts
6156
+ * const mask = getMask(4);
6157
+ * ```
6158
+ */
6159
+ function getMask(bits) {
6160
+ anumber(bits, 'bits');
6161
+ if (bits > 32)
6162
+ throw new RangeError('"bits" expected <= 32, got ' + bits);
6163
+ // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.
6164
+ return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;
6165
+ }
6166
+ /** Shared empty byte array used as the default context. */
6167
+ const EMPTY = /* @__PURE__ */ Uint8Array.of();
6168
+ /**
6169
+ * Builds the domain-separated message payload for the pure sign/verify paths.
6170
+ * Context length `255` is valid; only `ctx.length > 255` is rejected.
6171
+ * @param msg - Message bytes.
6172
+ * @param ctx - Optional context bytes.
6173
+ * @returns Domain-separated message payload.
6174
+ * @throws On wrong argument ranges or values. {@link RangeError}
6175
+ * @example
6176
+ * Build the domain-separated payload before direct signing.
6177
+ * ```ts
6178
+ * const payload = getMessage(new Uint8Array([1, 2]));
6179
+ * ```
6180
+ */
6181
+ function getMessage(msg, ctx = EMPTY) {
6182
+ abytes(msg, undefined, 'msg');
6183
+ abytes(ctx, undefined, 'ctx');
6184
+ if (ctx.length > 255)
6185
+ throw new RangeError('context should be 255 bytes or less');
6186
+ return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);
6187
+ }
6188
+ // DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the
6189
+ // FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,
6190
+ // SHAKE256, or another approved hash/XOF under that subtree.
6191
+ // 06 09 60 86 48 01 65 03 04 02
6192
+ const oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);
6193
+ /**
6194
+ * Output length, in bytes, that each XOF OID under this arc denotes.
6195
+ *
6196
+ * Unlike a fixed hash, an XOF's OID is a promise about the digest length: RFC 8702
6197
+ * defines id-shake128 as SHAKE128 with 256-bit output and id-shake256 as SHAKE256 with
6198
+ * 512-bit output, and FIPS 204 / FIPS 205 use exactly those pairings for pre-hash. Both
6199
+ * bare noble-hashes defaults are half these values, so neither can be signed under its
6200
+ * own OID.
6201
+ */
6202
+ const XOF_OID_OUTPUT_LEN = /* @__PURE__ */ (() => ({
6203
+ '060960864801650304020b': 32, // id-shake128, SHAKE128(M, 256)
6204
+ '060960864801650304020c': 64, // id-shake256, SHAKE256(M, 512)
6205
+ }))();
6206
+ /**
6207
+ * Validates that a hash exposes a NIST hash OID and enough collision resistance.
6208
+ * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST
6209
+ * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.
6210
+ * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend
6211
+ * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.
6212
+ * @param hash - Hash function to validate.
6213
+ * @param requiredStrength - Minimum required collision-resistance strength in bits.
6214
+ * @throws If the hash metadata or collision resistance is insufficient. {@link Error}
6215
+ * @example
6216
+ * Validate that a hash exposes a NIST hash OID and enough collision resistance.
6217
+ * ```ts
6218
+ * import { sha256 } from '@noble/hashes/sha2.js';
6219
+ * import { checkHash } from '@noble/post-quantum/utils.js';
6220
+ * checkHash(sha256, 128);
6221
+ * ```
6222
+ */
6223
+ function checkHash(hash, requiredStrength = 0) {
6224
+ if (typeof hash !== 'function' || typeof hash.create !== 'function')
6225
+ throw new TypeError('"hash" expected hash function, got type=' + typeof hash);
6226
+ ahash(hash);
6227
+ anumber(requiredStrength, 'requiredStrength');
6228
+ const oid = hash.oid;
6229
+ abytes(oid, undefined, 'hash.oid');
6230
+ if (!equalBytes(oid.subarray(0, 10), oidNistP))
6231
+ throw new Error('"hash.oid" is invalid: expected NIST hash');
6232
+ // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST
6233
+ // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is
6234
+ // the tighter runtime check, so enforce that lower bound here.
6235
+ // XOFs under this arc are identified by an OID that fixes their output length:
6236
+ // FIPS 204 §5.4.1 (SHAKE128) and FIPS 205 §10.2.2 (both SHAKEs), matching RFC 8702, pair
6237
+ // id-shake128 with SHAKE128(M, 256) and id-shake256 with SHAKE256(M, 512). getMessagePrehash embeds
6238
+ // hash.oid beside hash(msg), so a shorter digest signs an M' that claims a length
6239
+ // it does not have: noble-hashes' bare shake256 defaults to 32 bytes and cleared
6240
+ // the collision bound at the 128-bit level, producing signatures a conformant
6241
+ // verifier rejects because it recomputes 512 bits. Check the length the OID
6242
+ // denotes rather than the generic bound.
6243
+ const xofLen = XOF_OID_OUTPUT_LEN[bytesToHex(oid)];
6244
+ if (xofLen !== undefined && hash.outputLen !== xofLen) {
6245
+ throw new Error('Pre-hash XOF output length must be ' + xofLen + ' bytes for this OID, got: ' + hash.outputLen);
6246
+ }
6247
+ const collisionResistance = (hash.outputLen * 8) / 2;
6248
+ if (requiredStrength > collisionResistance) {
6249
+ throw new Error('Pre-hash security strength too low: ' +
6250
+ collisionResistance +
6251
+ ', required: ' +
6252
+ requiredStrength);
6253
+ }
6254
+ }
6255
+ /**
6256
+ * Builds the domain-separated prehash payload for the prehash sign/verify paths.
6257
+ * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper
6258
+ * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.
6259
+ * Context length `255` is valid; only `ctx.length > 255` is rejected.
6260
+ * @param hash - Prehash function.
6261
+ * @param msg - Message bytes.
6262
+ * @param ctx - Optional context bytes.
6263
+ * @returns Domain-separated prehash payload.
6264
+ * @throws On wrong argument ranges or values. {@link RangeError}
6265
+ * @example
6266
+ * Build the domain-separated prehash payload for external hashing.
6267
+ * ```ts
6268
+ * import { sha256 } from '@noble/hashes/sha2.js';
6269
+ * import { getMessagePrehash } from '@noble/post-quantum/utils.js';
6270
+ * getMessagePrehash(sha256, new Uint8Array([1, 2]));
6271
+ * ```
6272
+ */
6273
+ function getMessagePrehash(hash, msg, ctx = EMPTY) {
6274
+ checkHash(hash);
6275
+ abytes(msg, undefined, 'msg');
6276
+ abytes(ctx, undefined, 'ctx');
6277
+ if (ctx.length > 255)
6278
+ throw new RangeError('context should be 255 bytes or less');
6279
+ const hashed = hash(msg);
6280
+ return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);
6281
+ }
6282
+
6283
+ /**
6284
+ * Internal methods for lattice-based ML-KEM and ML-DSA.
6285
+ * @module
6286
+ */
6287
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
6288
+ /**
6289
+ * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.
6290
+ * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.
6291
+ * @returns CRYSTALS arithmetic and encoding helpers.
6292
+ * @example
6293
+ * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.
6294
+ * ```ts
6295
+ * const crystals = genCrystals({
6296
+ * newPoly: (n) => new Uint16Array(n),
6297
+ * N: 256,
6298
+ * Q: 3329,
6299
+ * F: 3303,
6300
+ * ROOT_OF_UNITY: 17,
6301
+ * brvBits: 7,
6302
+ * isKyber: true,
6303
+ * });
6304
+ * const reduced = crystals.mod(-1);
6305
+ * ```
6306
+ */
6307
+ const genCrystals = (opts) => {
6308
+ // isKyber: true means Kyber, false means Dilithium
6309
+ const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits} = opts;
6310
+ // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by
6311
+ // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.
6312
+ const mod = (a, modulo = Q) => {
6313
+ const result = (a % modulo) | 0;
6314
+ return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;
6315
+ };
6316
+ // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the
6317
+ // positive midpoint when `modulo` is even.
6318
+ // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.
6319
+ const smod = (a, modulo = Q) => {
6320
+ const r = mod(a, modulo) | 0;
6321
+ return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;
6322
+ };
6323
+ // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while
6324
+ // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.
6325
+ function getZettas() {
6326
+ const out = newPoly(N);
6327
+ for (let i = 0; i < N; i++) {
6328
+ const b = reverseBits(i, brvBits);
6329
+ const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);
6330
+ out[i] = Number(p) | 0;
6331
+ }
6332
+ return out;
6333
+ }
6334
+ const nttZetas = getZettas();
6335
+ // Number-Theoretic Transform
6336
+ // Explained: https://electricdusk.com/ntt.html
6337
+ // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,
6338
+ // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.
6339
+ const inv = (_a) => {
6340
+ throw new Error('not implemented');
6341
+ };
6342
+ // ML-KEM (Kyber) polynomials always enter the transform reduced to [0, Q), so add/sub only
6343
+ // need one conditional correction instead of `%`; measured ~20% faster NTT there.
6344
+ // ML-DSA keeps the generic mod() path on purpose: its first forward stage sees centered
6345
+ // (negative) coefficients, and `sub(a, t)` can drop below -Q (t is a mul output in [0, Q)),
6346
+ // so a single correction is not enough. A guarded fast path with mod() fallback was measured
6347
+ // slower than plain `%` for the 23-bit Q (V8 int32 modulo is one div; the branches lose).
6348
+ const field = {
6349
+ add: (a, b) => mod((a | 0) + (b | 0)) | 0,
6350
+ sub: (a, b) => mod((a | 0) - (b | 0)) | 0,
6351
+ mul: (a, b) => mod((a | 0) * (b | 0)) | 0,
6352
+ inv,
6353
+ };
6354
+ const nttOpts = {
6355
+ N,
6356
+ roots: nttZetas,
6357
+ invertButterflies: true,
6358
+ skipStages: 0,
6359
+ brp: false,
6360
+ };
6361
+ const dif = FFTCore(field, { dit: false, ...nttOpts });
6362
+ const dit = FFTCore(field, { dit: true, ...nttOpts });
6363
+ const NTT = {
6364
+ encode: (r) => {
6365
+ return dif(r);
6366
+ },
6367
+ decode: (r) => {
6368
+ dit(r);
6369
+ // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14
6370
+ // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.
6371
+ // kyber uses 128 here, because brv && stuff
6372
+ for (let i = 0; i < r.length; i++)
6373
+ r[i] = mod(F * r[i]);
6374
+ return r;
6375
+ },
6376
+ };
6377
+ // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /
6378
+ // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.
6379
+ const bitsCoder = (d, c) => {
6380
+ // Validate the carry shape once: JS bitwise operations silently truncate wider accumulators.
6381
+ for (let i = 0, bufLen = 0; i < N; i++) {
6382
+ bufLen += d;
6383
+ if (bufLen > 32)
6384
+ getMask(bufLen);
6385
+ bufLen %= 8;
6386
+ }
6387
+ const mask = getMask(d);
6388
+ const bytesLen = d * (N / 8);
6389
+ return {
6390
+ bytesLen,
6391
+ encode: (poly_) => {
6392
+ const poly = poly_;
6393
+ const r = new Uint8Array(bytesLen);
6394
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
6395
+ buf |= (c.encode(poly[i]) & mask) << bufLen;
6396
+ bufLen += d;
6397
+ // Take the low byte directly: `& 0xff` matches the previous getMask(bufLen) result
6398
+ // after Uint8Array truncation, without a validated function call per output byte.
6399
+ for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
6400
+ r[pos++] = buf & 0xff;
6401
+ }
6402
+ return r;
6403
+ },
6404
+ decode: (bytes) => {
6405
+ const r = newPoly(N);
6406
+ for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
6407
+ buf |= bytes[i] << bufLen;
6408
+ bufLen += 8;
6409
+ for (; bufLen >= d; bufLen -= d, buf >>= d)
6410
+ r[pos++] = c.decode(buf & mask);
6411
+ }
6412
+ return r;
6413
+ },
6414
+ };
6415
+ };
6416
+ return {
6417
+ mod,
6418
+ smod,
6419
+ nttZetas: nttZetas,
6420
+ NTT: {
6421
+ encode: (r) => NTT.encode(r),
6422
+ decode: (r) => NTT.decode(r),
6423
+ },
6424
+ bitsCoder: bitsCoder,
6425
+ };
6426
+ };
6427
+ const createXofShake = (shake) => (seed, blockLen) => {
6428
+ if (!blockLen)
6429
+ blockLen = shake.blockLen;
6430
+ // Optimizations that won't mater:
6431
+ // - cached seed update (two .update(), on start and on the end)
6432
+ // - another cache which cloned into working copy
6433
+ // Faster than multiple updates, since seed less than blockLen
6434
+ const _seed = new Uint8Array(seed.length + 2);
6435
+ _seed.set(seed);
6436
+ const seedLen = seed.length;
6437
+ const buf = new Uint8Array(blockLen); // == shake128.blockLen
6438
+ let h = shake.create({});
6439
+ let calls = 0;
6440
+ let xofs = 0;
6441
+ return {
6442
+ stats: () => ({ calls, xofs }),
6443
+ get: (x, y) => {
6444
+ // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate
6445
+ // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.
6446
+ _seed[seedLen + 0] = x;
6447
+ _seed[seedLen + 1] = y;
6448
+ h.destroy();
6449
+ h = shake.create({}).update(_seed);
6450
+ calls++;
6451
+ return () => {
6452
+ xofs++;
6453
+ return h.xofInto(buf);
6454
+ };
6455
+ },
6456
+ clean: () => {
6457
+ h.destroy();
6458
+ cleanBytes(buf, _seed);
6459
+ },
6460
+ };
6461
+ };
6462
+ /**
6463
+ * SHAKE128-based extendable-output reader factory used by ML-KEM.
6464
+ * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously
6465
+ * returned readers, and each squeeze reuses one mutable internal output buffer.
6466
+ * @param seed - Seed bytes for the reader.
6467
+ * @param blockLen - Optional output block length.
6468
+ * @returns Stateful XOF reader.
6469
+ * @example
6470
+ * Build the ML-KEM SHAKE128 matrix expander and read one block.
6471
+ * ```ts
6472
+ * import { randomBytes } from '@noble/post-quantum/utils.js';
6473
+ * import { XOF128 } from '@noble/post-quantum/_crystals.js';
6474
+ * const reader = XOF128(randomBytes(32));
6475
+ * const block = reader.get(0, 0)();
6476
+ * ```
6477
+ */
6478
+ const XOF128 = /* @__PURE__ */ createXofShake(shake128);
6479
+ /**
6480
+ * SHAKE256-based extendable-output reader factory used by ML-DSA.
6481
+ * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned
6482
+ * readers, and reuses one mutable internal output buffer for each squeeze.
6483
+ * @param seed - Seed bytes for the reader.
6484
+ * @param blockLen - Optional output block length.
6485
+ * @returns Stateful XOF reader.
6486
+ * @example
6487
+ * Build the ML-DSA SHAKE256 coefficient expander and read one block.
6488
+ * ```ts
6489
+ * import { randomBytes } from '@noble/post-quantum/utils.js';
6490
+ * import { XOF256 } from '@noble/post-quantum/_crystals.js';
6491
+ * const reader = XOF256(randomBytes(32));
6492
+ * const block = reader.get(0, 0)();
6493
+ * ```
6494
+ */
6495
+ const XOF256 = /* @__PURE__ */ createXofShake(shake256);
6496
+
6497
+ /**
6498
+ * ML-DSA: Module Lattice-based Digital Signature Algorithm from
6499
+ * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.
6500
+ *
6501
+ * Has similar internals to ML-KEM, but their keys and params are different.
6502
+ * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),
6503
+ * [repo](https://github.com/pq-crystals/dilithium).
6504
+ * @module
6505
+ */
6506
+ /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
6507
+ /**
6508
+ * Keys each internal surface accepts.
6509
+ *
6510
+ * `context` is deliberately absent from both. The internal functions never read it: the
6511
+ * public wrappers consume it when they format `M'` and must not pass it down, because a
6512
+ * key that is accepted and then not acted on is the same silent downgrade this validation
6513
+ * exists to prevent. `externalMu` is the mirror case, existing here and rejected above.
6514
+ * `extraEntropy` is signing-only, so verification does not take it either.
6515
+ */
6516
+ const INTERNAL_SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([
6517
+ 'extraEntropy',
6518
+ 'externalMu',
6519
+ ]);
6520
+ const INTERNAL_VER_OPT_KEYS = /* @__PURE__ */ Object.freeze(['externalMu']);
6521
+ function validateInternalOpts(opts, allowed) {
6522
+ const normalized = checkOptKeys(opts, allowed);
6523
+ if (normalized.externalMu !== undefined)
6524
+ abool(normalized.externalMu, 'opts.externalMu');
6525
+ return normalized;
6526
+ }
6527
+ // Constants
6528
+ // FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients.
6529
+ const N = 256;
6530
+ // 2**23 − 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints
6531
+ const Q = 8380417;
6532
+ // FIPS 204 §2.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT.
6533
+ const ROOT_OF_UNITY = 1753;
6534
+ // f = 256**−1 mod q, pow(256, -1, q) = 8347681 (python3)
6535
+ const F = 8347681;
6536
+ // FIPS 204 Table 1 / §7.4 fixes d = 13 dropped low bits for Power2Round on t.
6537
+ const D = 13;
6538
+ // FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87;
6539
+ // §7.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint.
6540
+ // Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.
6541
+ const GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;
6542
+ const GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;
6543
+ /** Internal params for different versions of ML-DSA */
6544
+ // prettier-ignore
6545
+ /** Built-in ML-DSA parameter presets keyed by security categories `2/3/5`
6546
+ * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`.
6547
+ * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later,
6548
+ * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers.
6549
+ */
6550
+ const PARAMS = /* @__PURE__ */ (() => Object.freeze({
6551
+ 2: Object.freeze({
6552
+ K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80
6553
+ }),
6554
+ 3: Object.freeze({
6555
+ K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55
6556
+ }),
6557
+ 5: Object.freeze({
6558
+ K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75
6559
+ }),
6560
+ }))();
6561
+ const newPoly = (n) => new Int32Array(n);
6562
+ // Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal,
6563
+ // and Int32Array polys because ordinary-form coefficients can be negative / centered.
6564
+ const crystals = /* @__PURE__ */ genCrystals({
6565
+ N,
6566
+ Q,
6567
+ F,
6568
+ ROOT_OF_UNITY,
6569
+ newPoly,
6570
+ brvBits: 8,
6571
+ });
6572
+ const id = (n) => n;
6573
+ // compress()/verify() must be compatible in both directions:
6574
+ // wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps.
6575
+ // malformed-input rejection only happens through the optional verify hook.
6576
+ const polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, {
6577
+ encode: (i) => compress(verify(i)),
6578
+ decode: (i) => verify(compress(i)),
6579
+ });
6580
+ // Mutates `a` in place; callers must pass same-length polynomials.
6581
+ // NOTE: conditional-reduction variants (as in ml-kem) were measured performance-neutral here —
6582
+ // int32 `%` with 23-bit Q is already cheap — so the simpler mod() form is kept for audit.
6583
+ const polyAdd = (a_, b_) => {
6584
+ const a = a_;
6585
+ const b = b_;
6586
+ for (let i = 0; i < a.length; i++)
6587
+ a[i] = crystals.mod(a[i] + b[i]);
6588
+ return a;
6589
+ };
6590
+ // Mutates `a` in place; callers must pass same-length polynomials.
6591
+ const polySub = (a_, b_) => {
6592
+ const a = a_;
6593
+ const b = b_;
6594
+ for (let i = 0; i < a.length; i++)
6595
+ a[i] = crystals.mod(a[i] - b[i]);
6596
+ return a;
6597
+ };
6598
+ // Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.
6599
+ const polyShiftl = (p_) => {
6600
+ const p = p_;
6601
+ for (let i = 0; i < N; i++)
6602
+ p[i] <<= D;
6603
+ return p;
6604
+ };
6605
+ const polyChknorm = (p_, B) => {
6606
+ const p = p_;
6607
+ // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.
6608
+ for (let i = 0; i < N; i++)
6609
+ if (Math.abs(crystals.smod(p[i])) >= B)
6610
+ return true;
6611
+ return false;
6612
+ };
6613
+ // Both inputs must already be in NTT / `T_q` form.
6614
+ const MultiplyNTTs = (a_, b_) => {
6615
+ const a = a_;
6616
+ const b = b_;
6617
+ // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,
6618
+ // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,
6619
+ // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).
6620
+ // Barrett reduction is slower than mod :(
6621
+ const c = newPoly(N);
6622
+ for (let i = 0; i < a.length; i++)
6623
+ c[i] = crystals.mod(a[i] * b[i]);
6624
+ return c;
6625
+ };
6626
+ // Return poly in NTT representation
6627
+ function RejNTTPoly(xof_) {
6628
+ const xof = xof_;
6629
+ // Samples a polynomial ∈ Tq. xof() must return byte lengths divisible by 3.
6630
+ const r = newPoly(N);
6631
+ // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(
6632
+ for (let j = 0; j < N;) {
6633
+ const b = xof();
6634
+ if (b.length % 3)
6635
+ throw new Error('RejNTTPoly: unaligned block');
6636
+ for (let i = 0; j < N && i <= b.length - 3; i += 3) {
6637
+ // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate.
6638
+ const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes
6639
+ if (t < Q)
6640
+ r[j++] = t;
6641
+ }
6642
+ }
6643
+ return r;
6644
+ }
6645
+ // Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the
6646
+ // Table 2 byte lengths / hash-width choices used by the public wrappers below.
6647
+ function getDilithium(opts_) {
6648
+ const opts = opts_;
6649
+ const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;
6650
+ const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;
6651
+ if (![2, 4].includes(ETA))
6652
+ throw new Error('Wrong ETA');
6653
+ if (![1 << 17, 1 << 19].includes(GAMMA1))
6654
+ throw new Error('Wrong GAMMA1');
6655
+ if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))
6656
+ throw new Error('Wrong GAMMA2');
6657
+ const BETA = TAU * ETA;
6658
+ const decompose = (r) => {
6659
+ // Decomposes r into (r1, r0) such that r ≡ r1(2γ2) + r0 mod q.
6660
+ const rPlus = crystals.mod(r);
6661
+ const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;
6662
+ // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`.
6663
+ if (rPlus - r0 === Q - 1)
6664
+ return { r1: 0 | 0, r0: (r0 - 1) | 0 };
6665
+ const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;
6666
+ return { r1, r0 }; // r1 = HighBits, r0 = LowBits
6667
+ };
6668
+ const HighBits = (r) => decompose(r).r1;
6669
+ const LowBits = (r) => decompose(r).r0;
6670
+ const MakeHint = (z, r) => {
6671
+ // Compute hint bit indicating whether adding z to r alters the high bits of r.
6672
+ // FIPS 204 §6.2 also permits the Section 5.1 alternative from [6], which uses the
6673
+ // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally.
6674
+ // This optimized predicate only applies to those transformed Section 5.1 inputs; it is
6675
+ // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs.
6676
+ // From dilithium code
6677
+ const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;
6678
+ // from FIPS204:
6679
+ // // const r1 = HighBits(r);
6680
+ // // const v1 = HighBits(r + z);
6681
+ // // const res1 = +(r1 !== v1);
6682
+ // But they return different results! However, decompose is same.
6683
+ // So, either there is a bug in Dilithium ref implementation or in FIPS204.
6684
+ // For now, lets use dilithium one, so test vectors can be passed.
6685
+ // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after
6686
+ // `r0 += ct0`.
6687
+ // See dilithium-py README section "Optimising decomposition and making hints".
6688
+ return res0;
6689
+ };
6690
+ // m = (q-1)/(2γ2): 44 for ML-DSA-44, 16 for 65/87. Hoisted out of UseHint, which runs
6691
+ // per coefficient during verification.
6692
+ const HINT_M = Math.floor((Q - 1) / (2 * GAMMA2));
6693
+ const UseHint = (h, r) => {
6694
+ // Returns the high bits of r adjusted according to hint h
6695
+ const { r1, r0 } = decompose(r);
6696
+ // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m
6697
+ // 4: if h = 1 and r0 ≤ 0 return (r1 − 1) mod m
6698
+ if (h === 1)
6699
+ return r0 > 0 ? crystals.mod(r1 + 1, HINT_M) | 0 : crystals.mod(r1 - 1, HINT_M) | 0;
6700
+ return r1 | 0;
6701
+ };
6702
+ const Power2Round = (r) => {
6703
+ // Decomposes r into (r1, r0) such that r ≡ r1*(2**d) + r0 mod q.
6704
+ const rPlus = crystals.mod(r);
6705
+ const r0 = crystals.smod(rPlus, 2 ** D) | 0;
6706
+ return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };
6707
+ };
6708
+ const hintCoder = {
6709
+ bytesLen: OMEGA + K,
6710
+ encode: (h_) => {
6711
+ const h = h_;
6712
+ if (h === false)
6713
+ throw new Error('hint.encode: hint is false'); // should never happen
6714
+ const res = new Uint8Array(OMEGA + K);
6715
+ for (let i = 0, k = 0; i < K; i++) {
6716
+ for (let j = 0; j < N; j++)
6717
+ if (h[i][j] !== 0)
6718
+ res[k++] = j;
6719
+ res[OMEGA + i] = k;
6720
+ }
6721
+ return res;
6722
+ },
6723
+ decode: (buf) => {
6724
+ const h = [];
6725
+ let k = 0;
6726
+ for (let i = 0; i < K; i++) {
6727
+ const hi = newPoly(N);
6728
+ if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)
6729
+ return false;
6730
+ for (let j = k; j < buf[OMEGA + i]; j++) {
6731
+ if (j > k && buf[j] <= buf[j - 1])
6732
+ return false;
6733
+ hi[buf[j]] = 1;
6734
+ }
6735
+ k = buf[OMEGA + i];
6736
+ h.push(hi);
6737
+ }
6738
+ for (let j = k; j < OMEGA; j++)
6739
+ if (buf[j] !== 0)
6740
+ return false;
6741
+ return h;
6742
+ },
6743
+ };
6744
+ const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {
6745
+ if (!(-ETA <= i && i <= ETA))
6746
+ throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);
6747
+ return i;
6748
+ });
6749
+ const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i);
6750
+ const T1Coder = polyCoder(10);
6751
+ // Requires smod. Need to fix!
6752
+ const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));
6753
+ const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);
6754
+ const W1Vec = vecCoder(W1Coder, K);
6755
+ // Main structures
6756
+ const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));
6757
+ const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));
6758
+ const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);
6759
+ const CoefFromHalfByte = ETA === 2
6760
+ ? (n) => (n < 15 ? 2 - (n % 5) : false)
6761
+ : (n) => (n < 9 ? 4 - n : false);
6762
+ // Return poly in ordinary representation.
6763
+ // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply
6764
+ // `NTT.encode()` later when needed.
6765
+ function RejBoundedPoly(xof_) {
6766
+ const xof = xof_;
6767
+ // Samples an element a ∈ Rq with coeffcients in [−η, η] computed via rejection sampling from ρ.
6768
+ const r = newPoly(N);
6769
+ for (let j = 0; j < N;) {
6770
+ const b = xof();
6771
+ for (let i = 0; j < N && i < b.length; i += 1) {
6772
+ // half byte. Should be superfast with vector instructions. But very slow with js :(
6773
+ const d1 = CoefFromHalfByte(b[i] & 0x0f);
6774
+ const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);
6775
+ if (d1 !== false)
6776
+ r[j++] = d1;
6777
+ if (j < N && d2 !== false)
6778
+ r[j++] = d2;
6779
+ }
6780
+ }
6781
+ return r;
6782
+ }
6783
+ const SampleInBall = (seed) => {
6784
+ // Samples a polynomial c ∈ Rq with coeffcients from {−1, 0, 1} and Hamming weight τ
6785
+ const pre = newPoly(N);
6786
+ const s = shake256.create({}).update(seed);
6787
+ const buf = new Uint8Array(shake256.blockLen);
6788
+ s.xofInto(buf);
6789
+ // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`,
6790
+ // then rejection-samples coefficient positions from the remaining XOF stream.
6791
+ const masks = buf.slice(0, 8);
6792
+ for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {
6793
+ let b = i + 1;
6794
+ for (; b > i;) {
6795
+ b = buf[pos++];
6796
+ if (pos < shake256.blockLen)
6797
+ continue;
6798
+ s.xofInto(buf);
6799
+ pos = 0;
6800
+ }
6801
+ pre[i] = pre[b];
6802
+ pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);
6803
+ if (maskBit >= 8) {
6804
+ maskPos++;
6805
+ maskBit = 0;
6806
+ }
6807
+ }
6808
+ return pre;
6809
+ };
6810
+ const polyPowerRound = (p_) => {
6811
+ const p = p_;
6812
+ const res0 = newPoly(N);
6813
+ const res1 = newPoly(N);
6814
+ for (let i = 0; i < p.length; i++) {
6815
+ const { r0, r1 } = Power2Round(p[i]);
6816
+ res0[i] = r0;
6817
+ res1[i] = r1;
6818
+ }
6819
+ return { r0: res0, r1: res1 };
6820
+ };
6821
+ const polyUseHint = (u_, h_) => {
6822
+ const u = u_;
6823
+ const h = h_;
6824
+ // In-place on `u`: verification only needs the recovered high bits, so reuse the
6825
+ // temporary `wApprox` buffer instead of allocating another polynomial.
6826
+ for (let i = 0; i < N; i++)
6827
+ u[i] = UseHint(h[i], u[i]);
6828
+ return u;
6829
+ };
6830
+ const polyMakeHint = (a_, b_) => {
6831
+ const a = a_;
6832
+ const b = b_;
6833
+ const v = newPoly(N);
6834
+ let cnt = 0;
6835
+ for (let i = 0; i < N; i++) {
6836
+ const h = MakeHint(a[i], b[i]);
6837
+ v[i] = h;
6838
+ cnt += h;
6839
+ }
6840
+ return { v, cnt };
6841
+ };
6842
+ const signRandBytes = 32;
6843
+ const seedCoder = splitCoder('seed', 32, 64, 32);
6844
+ // API & argument positions are exactly as in FIPS204.
6845
+ const internal = Object.freeze({
6846
+ info: Object.freeze({ type: 'internal-ml-dsa' }),
6847
+ lengths: Object.freeze({
6848
+ secretKey: secretCoder.bytesLen,
6849
+ publicKey: publicCoder.bytesLen,
6850
+ seed: 32,
6851
+ signature: sigCoder.bytesLen,
6852
+ signRand: signRandBytes,
6853
+ }),
6854
+ keygen: (seed) => {
6855
+ // H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128) 2: ▷ expand seed
6856
+ const seedDst = new Uint8Array(32 + 2);
6857
+ const randSeed = seed === undefined;
6858
+ if (randSeed)
6859
+ seed = randomBytes(32);
6860
+ abytesDoc(seed, 32, 'seed');
6861
+ seedDst.set(seed);
6862
+ if (randSeed)
6863
+ cleanBytes(seed);
6864
+ seedDst[32] = K;
6865
+ seedDst[33] = L;
6866
+ const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));
6867
+ const xofPrime = XOF256(rhoPrime);
6868
+ const s1 = [];
6869
+ for (let i = 0; i < L; i++)
6870
+ s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));
6871
+ const s2 = [];
6872
+ for (let i = L; i < L + K; i++)
6873
+ s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));
6874
+ const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));
6875
+ const t0 = [];
6876
+ const t1 = [];
6877
+ const xof = XOF128(rho);
6878
+ const t = newPoly(N);
6879
+ for (let i = 0; i < K; i++) {
6880
+ // t ← NTT−1(A*NTT(s1)) + s2
6881
+ cleanBytes(t); // don't-reallocate
6882
+ for (let j = 0; j < L; j++) {
6883
+ const aij = RejNTTPoly(xof.get(j, i)); // super slow!
6884
+ polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));
6885
+ }
6886
+ crystals.NTT.decode(t);
6887
+ const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) ← Power2Round(t, d)
6888
+ t0.push(r0);
6889
+ t1.push(r1);
6890
+ }
6891
+ const publicKey = publicCoder.encode([rho, t1]); // pk ← pkEncode(ρ, t1)
6892
+ const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr ← H(BytesToBits(pk), 512)
6893
+ // sk ← skEncode(ρ, K,tr, s1, s2, t0)
6894
+ const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);
6895
+ xof.clean();
6896
+ xofPrime.clean();
6897
+ // STATS
6898
+ // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 },
6899
+ // Kyber1024: { calls: 16, xofs: 48 }
6900
+ // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 },
6901
+ // DSA87: { calls: 71, xofs: 71 }
6902
+ cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);
6903
+ return {
6904
+ publicKey: publicKey,
6905
+ secretKey: secretKey,
6906
+ };
6907
+ },
6908
+ getPublicKey: (secretKey) => {
6909
+ // (ρ, K,tr, s1, s2, t0) ← skDecode(sk)
6910
+ const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);
6911
+ const xof = XOF128(rho);
6912
+ const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));
6913
+ const t1 = [];
6914
+ const tmp = newPoly(N);
6915
+ for (let i = 0; i < K; i++) {
6916
+ tmp.fill(0);
6917
+ for (let j = 0; j < L; j++) {
6918
+ const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT
6919
+ polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j
6920
+ }
6921
+ crystals.NTT.decode(tmp); // NTT⁻¹
6922
+ polyAdd(tmp, s2[i]); // t_i = A·s1 + s2
6923
+ const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 ≈ t0
6924
+ t1.push(r1);
6925
+ }
6926
+ xof.clean();
6927
+ cleanBytes(tmp, s1Hat, _t0, s1, s2);
6928
+ return publicCoder.encode([rho, t1]);
6929
+ },
6930
+ // NOTE: random is optional.
6931
+ sign: (msg, secretKey, opts = {}) => {
6932
+ opts = validateSigOpts(opts, INTERNAL_SIG_OPT_KEYS);
6933
+ opts = validateInternalOpts(opts, INTERNAL_SIG_OPT_KEYS);
6934
+ const { extraEntropy: random, externalMu = false } = opts;
6935
+ // FIPS 204 external-mu mode expects the 64-byte message representative µ = H(tr || M).
6936
+ if (externalMu)
6937
+ abytesDoc(msg, CRH_BYTES, 'mu');
6938
+ // Prepare entropy before touching decoded secrets: randomBytes() may throw, and an RNG
6939
+ // failure must not leave expanded secret-polynomial copies behind.
6940
+ const ownRnd = random === false || random === undefined;
6941
+ const rnd = random === false
6942
+ ? new Uint8Array(32)
6943
+ : random === undefined
6944
+ ? randomBytes(signRandBytes)
6945
+ : random;
6946
+ abytesDoc(rnd, 32, 'extraEntropy');
6947
+ // This part can be pre-cached per secretKey, but there is only minor performance improvement,
6948
+ // since we re-use a lot of variables to computation.
6949
+ // (ρ, K,tr, s1, s2, t0) ← skDecode(sk)
6950
+ const decoded = (() => {
6951
+ try {
6952
+ return secretCoder.decode(secretKey);
6953
+ }
6954
+ catch (error) {
6955
+ // A malformed key must not strand entropy owned by the library.
6956
+ if (ownRnd)
6957
+ cleanBytes(rnd);
6958
+ throw error;
6959
+ }
6960
+ })();
6961
+ const [rho, _K, tr, s1, s2, t0] = decoded;
6962
+ // Cache matrix to avoid re-compute later
6963
+ const A = []; // A ← ExpandA(ρ)
6964
+ const xof = XOF128(rho);
6965
+ for (let i = 0; i < K; i++) {
6966
+ const pv = [];
6967
+ for (let j = 0; j < L; j++)
6968
+ pv.push(RejNTTPoly(xof.get(j, i)));
6969
+ A.push(pv);
6970
+ }
6971
+ xof.clean();
6972
+ for (let i = 0; i < L; i++)
6973
+ crystals.NTT.encode(s1[i]); // sˆ1 ← NTT(s1)
6974
+ for (let i = 0; i < K; i++) {
6975
+ crystals.NTT.encode(s2[i]); // sˆ2 ← NTT(s2)
6976
+ crystals.NTT.encode(t0[i]); // tˆ0 ← NTT(t0)
6977
+ }
6978
+ // This part is per msg
6979
+ const mu = externalMu
6980
+ ? msg
6981
+ : // 6: µ ← H(tr||M, 512)
6982
+ // ▷ Compute message representative µ
6983
+ shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
6984
+ const rhoprime = shake256
6985
+ .create({ dkLen: CRH_BYTES })
6986
+ .update(_K)
6987
+ .update(rnd)
6988
+ .update(mu)
6989
+ .digest(); // ρ′← H(K||rnd||µ, 512)
6990
+ // Only wipe entropy we generated; caller-provided extraEntropy stays caller-owned.
6991
+ if (ownRnd)
6992
+ cleanBytes(rnd);
6993
+ abytesDoc(rhoprime, CRH_BYTES);
6994
+ const x256 = XOF256(rhoprime, ZCoder.bytesLen);
6995
+ // Rejection sampling loop
6996
+ main_loop: for (let kappa = 0;;) {
6997
+ const y = [];
6998
+ // y ← ExpandMask(ρ , κ)
6999
+ for (let i = 0; i < L; i++, kappa++)
7000
+ y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));
7001
+ const z = y.map((i) => crystals.NTT.encode(i.slice()));
7002
+ const w = [];
7003
+ for (let i = 0; i < K; i++) {
7004
+ // w ← NTT−1(A ◦ NTT(y))
7005
+ const wi = newPoly(N);
7006
+ for (let j = 0; j < L; j++)
7007
+ polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));
7008
+ crystals.NTT.decode(wi);
7009
+ w.push(wi);
7010
+ }
7011
+ const w1 = w.map((j) => j.map(HighBits)); // w1 ← HighBits(w)
7012
+ // Commitment hash: c˜ ∈{0, 1 2λ } ← H(µ||w1Encode(w1), 2λ)
7013
+ const cTilde = shake256
7014
+ .create({ dkLen: C_TILDE_BYTES })
7015
+ .update(mu)
7016
+ .update(W1Vec.encode(w1))
7017
+ .digest();
7018
+ // Verifer’s challenge
7019
+ // c ← SampleInBall(c˜1); cˆ ← NTT(c)
7020
+ const cHat = crystals.NTT.encode(SampleInBall(cTilde));
7021
+ // ⟨⟨cs1⟩⟩ ← NTT−1(cˆ◦ sˆ1)
7022
+ const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));
7023
+ for (let i = 0; i < L; i++) {
7024
+ polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z ← y + ⟨⟨cs1⟩⟩
7025
+ if (polyChknorm(cs1[i], GAMMA1 - BETA)) {
7026
+ // Rejected. Wipe this iteration's secret-derived buffers before retrying; the
7027
+ // accepted path wipes the same set, and only the persistent key material (s1, s2,
7028
+ // t0, A, rhoprime) is kept for the next iteration and cleaned at the very end.
7029
+ cleanBytes(cTilde, cs1, cHat, w1, w, z, y);
7030
+ continue main_loop; // ||z||∞ ≥ γ1 − β
7031
+ }
7032
+ }
7033
+ // cs1 is now z (▷ Signer’s response)
7034
+ let cnt = 0;
7035
+ const h = [];
7036
+ for (let i = 0; i < K; i++) {
7037
+ const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // ⟨⟨cs2⟩⟩ ← NTT−1(cˆ◦ sˆ2)
7038
+ const r0 = polySub(w[i], cs2).map(LowBits); // r0 ← LowBits(w − ⟨⟨cs2⟩⟩)
7039
+ if (polyChknorm(r0, GAMMA2 - BETA)) {
7040
+ cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h, cs2, r0);
7041
+ continue main_loop; // ||r0||∞ ≥ γ2 − β
7042
+ }
7043
+ const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // ⟨⟨ct0⟩⟩ ← NTT−1(cˆ◦ tˆ0)
7044
+ if (polyChknorm(ct0, GAMMA2)) {
7045
+ cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h, cs2, r0, ct0);
7046
+ continue main_loop;
7047
+ }
7048
+ polyAdd(r0, ct0);
7049
+ // ▷ Signer’s hint
7050
+ const hint = polyMakeHint(r0, w1[i]); // h ← MakeHint(−⟨⟨ct0⟩⟩, w− ⟨⟨cs2⟩⟩ + ⟨⟨ct0⟩⟩)
7051
+ h.push(hint.v);
7052
+ cnt += hint.cnt;
7053
+ }
7054
+ if (cnt > OMEGA) {
7055
+ cleanBytes(cTilde, cs1, cHat, w1, w, z, y, h);
7056
+ continue; // the number of 1’s in h is greater than ω
7057
+ }
7058
+ x256.clean();
7059
+ const res = sigCoder.encode([cTilde, cs1, h]); // σ ← sigEncode(c˜, z mod±q, h)
7060
+ // rho, _K, tr is subarray of secretKey, cannot clean.
7061
+ cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);
7062
+ // `externalMu` hands ownership of `mu` to the caller,
7063
+ // so only wipe the internally derived digest form here;
7064
+ // zeroizing caller memory would break the caller's own reuse / verify path.
7065
+ if (!externalMu)
7066
+ cleanBytes(mu);
7067
+ return res;
7068
+ }
7069
+ // @ts-ignore
7070
+ throw new Error('Unreachable code path reached, report this error');
7071
+ },
7072
+ verify: (sig, msg, publicKey, opts = {}) => {
7073
+ opts = validateInternalOpts(opts, INTERNAL_VER_OPT_KEYS);
7074
+ const { externalMu = false } = opts;
7075
+ // FIPS 204 external-mu mode expects the 64-byte message representative µ = H(tr || M).
7076
+ if (externalMu)
7077
+ abytesDoc(msg, CRH_BYTES, 'mu');
7078
+ // ML-DSA.Verify(pk, M, σ): Verifes a signature σ for a message M.
7079
+ const [rho, t1] = publicCoder.decode(publicKey); // (ρ, t1) ← pkDecode(pk)
7080
+ const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr ← H(BytesToBits(pk), 512)
7081
+ if (sig.length !== sigCoder.bytesLen)
7082
+ return false; // return false instead of exception
7083
+ // (c˜, z, h) ← sigDecode(σ)
7084
+ // ▷ Signer’s commitment hash c ˜, response z and hint
7085
+ const [cTilde, z, h] = sigCoder.decode(sig);
7086
+ if (h === false)
7087
+ return false; // if h = ⊥ then return false
7088
+ for (let i = 0; i < L; i++)
7089
+ if (polyChknorm(z[i], GAMMA1 - BETA))
7090
+ return false;
7091
+ const mu = externalMu
7092
+ ? msg
7093
+ : // 7: µ ← H(tr||M, 512)
7094
+ shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
7095
+ // Compute verifer’s challenge from c˜
7096
+ const c = crystals.NTT.encode(SampleInBall(cTilde)); // c ← SampleInBall(c˜1)
7097
+ const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)
7098
+ for (let i = 0; i < L; i++)
7099
+ crystals.NTT.encode(zNtt[i]);
7100
+ const wTick1 = [];
7101
+ const xof = XOF128(rho);
7102
+ for (let i = 0; i < K; i++) {
7103
+ const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)
7104
+ const Az = newPoly(N); // // A * z
7105
+ for (let j = 0; j < L; j++) {
7106
+ const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace
7107
+ polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));
7108
+ }
7109
+ // wApprox = A*z - c*t1 * (2**d)
7110
+ const wApprox = crystals.NTT.decode(polySub(Az, ct12d));
7111
+ // Reconstruction of signer’s commitment
7112
+ wTick1.push(polyUseHint(wApprox, h[i])); // w ′ ← UseHint(h, w'approx )
7113
+ }
7114
+ xof.clean();
7115
+ // c˜′← H (µ||w1Encode(w′1), 2λ), Hash it; this should match c˜
7116
+ const c2 = shake256
7117
+ .create({ dkLen: C_TILDE_BYTES })
7118
+ .update(mu)
7119
+ .update(W1Vec.encode(wTick1))
7120
+ .digest();
7121
+ // Additional checks in FIPS-204:
7122
+ // [[ ||z||∞ < γ1 − β ]] and [[c ˜ = c˜′]] and [[number of 1’s in h is ≤ ω]]
7123
+ for (const t of h) {
7124
+ const sum = t.reduce((acc, i) => acc + i, 0);
7125
+ if (!(sum <= OMEGA))
7126
+ return false;
7127
+ }
7128
+ for (const t of z)
7129
+ if (polyChknorm(t, GAMMA1 - BETA))
7130
+ return false;
7131
+ return equalBytes(cTilde, c2);
7132
+ },
7133
+ });
7134
+ return Object.freeze({
7135
+ info: Object.freeze({ type: 'ml-dsa' }),
7136
+ internal,
7137
+ securityLevel: securityLevel,
7138
+ keygen: internal.keygen,
7139
+ lengths: internal.lengths,
7140
+ getPublicKey: internal.getPublicKey,
7141
+ sign: (msg, secretKey, opts = {}) => {
7142
+ opts = validateSigOpts(opts);
7143
+ const M = getMessage(msg, opts.context);
7144
+ // `context` is consumed by getMessage() above; forwarding it would make the internal
7145
+ // surface accept a key it never reads.
7146
+ const res = internal.sign(M, secretKey, {
7147
+ extraEntropy: opts.extraEntropy,
7148
+ externalMu: false,
7149
+ });
7150
+ cleanBytes(M);
7151
+ return res;
7152
+ },
7153
+ verify: (sig, msg, publicKey, opts = {}) => {
7154
+ opts = validateVerOpts(opts);
7155
+ abytesDoc(sig, undefined, 'signature');
7156
+ return internal.verify(sig, getMessage(msg, opts.context), publicKey, { externalMu: false });
7157
+ },
7158
+ prehash: (hash) => {
7159
+ checkHash(hash, securityLevel);
7160
+ const rawHash = hash;
7161
+ return Object.freeze({
7162
+ info: Object.freeze({ type: 'hashml-dsa' }),
7163
+ securityLevel: securityLevel,
7164
+ lengths: internal.lengths,
7165
+ keygen: internal.keygen,
7166
+ getPublicKey: internal.getPublicKey,
7167
+ sign: (msg, secretKey, opts = {}) => {
7168
+ opts = validateSigOpts(opts);
7169
+ const M = getMessagePrehash(rawHash, msg, opts.context);
7170
+ // As above: getMessagePrehash() consumes `context`, so it must not travel further.
7171
+ const res = internal.sign(M, secretKey, {
7172
+ extraEntropy: opts.extraEntropy,
7173
+ externalMu: false,
7174
+ });
7175
+ cleanBytes(M);
7176
+ return res;
7177
+ },
7178
+ verify: (sig, msg, publicKey, opts = {}) => {
7179
+ opts = validateVerOpts(opts);
7180
+ abytesDoc(sig, undefined, 'signature');
7181
+ return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey, {
7182
+ externalMu: false,
7183
+ });
7184
+ },
7185
+ });
7186
+ },
7187
+ });
7188
+ }
7189
+ /**
7190
+ * ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD.
7191
+ * @example
7192
+ * Generate deterministic ML-DSA-44 keys, sign one message, and verify the signature.
7193
+ * ```ts
7194
+ * import { sha256 } from '@noble/hashes/sha2.js';
7195
+ * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';
7196
+ * const seed = new Uint8Array(ml_dsa44.lengths.seed!);
7197
+ * const { secretKey, publicKey } = ml_dsa44.keygen(seed);
7198
+ * const msg = new TextEncoder().encode('hello noble');
7199
+ * const sig = ml_dsa44.sign(msg, secretKey);
7200
+ * const isValid = ml_dsa44.verify(sig, msg, publicKey);
7201
+ * const recovered = ml_dsa44.getPublicKey(secretKey);
7202
+ * const context = new Uint8Array([1, 2, 3]);
7203
+ * const prehash = ml_dsa44.prehash(sha256);
7204
+ * const preSig = prehash.sign(msg, secretKey, { context });
7205
+ * const preValid = prehash.verify(preSig, msg, publicKey, { context });
7206
+ * const internalSig = ml_dsa44.internal.sign(msg, secretKey);
7207
+ * ```
7208
+ */
7209
+ const ml_dsa44 = /* @__PURE__ */ (() => getDilithium({
7210
+ ...PARAMS[2],
7211
+ CRH_BYTES: 64,
7212
+ TR_BYTES: 64,
7213
+ C_TILDE_BYTES: 32,
7214
+ XOF128,
7215
+ XOF256,
7216
+ securityLevel: 128,
7217
+ }))();
7218
+
7219
+ var _MLDSAKey_key, _MLDSAPublicKey_key;
7220
+ // Octez stores the 2560-byte ML-DSA-44 secret followed by its 1312-byte public key.
7221
+ const SECRET_KEY_SIZE = 2560;
7222
+ class MLDSAKey {
7223
+ constructor(key, decrypt) {
7224
+ _MLDSAKey_key.set(this, void 0);
7225
+ const [encoded, prefix] = utils$1.b58DecodeAndCheckPrefix(key, [
7226
+ utils$1.PrefixV2.MLDSA44SecretKey,
7227
+ utils$1.PrefixV2.MLDSA44EncryptedSecretKey,
7228
+ ]);
7229
+ let data = encoded;
7230
+ if (prefix === utils$1.PrefixV2.MLDSA44EncryptedSecretKey) {
7231
+ if (!decrypt)
7232
+ throw new Error('decryption function is not provided');
7233
+ data = decrypt(data);
7234
+ }
7235
+ if (data.length !== utils$1.payloadLength[utils$1.PrefixV2.MLDSA44SecretKey]) {
7236
+ throw new core.InvalidKeyError('Invalid ML-DSA-44 secret key length');
7237
+ }
7238
+ __classPrivateFieldSet(this, _MLDSAKey_key, Uint8Array.from(data), "f");
7239
+ }
7240
+ sign(message) {
7241
+ // Octez uses pure ML-DSA with an empty context over Blake2b-256(message),
7242
+ // not HashML-DSA. InMemorySigner has already prepended any watermark.
7243
+ const rawSignature = ml_dsa44.sign(blake2b(message, { dkLen: 32 }), __classPrivateFieldGet(this, _MLDSAKey_key, "f").subarray(0, SECRET_KEY_SIZE));
7244
+ const encoded = utils$1.b58Encode(rawSignature, utils$1.PrefixV2.MLDSA44Signature);
7245
+ return { rawSignature, sig: encoded, prefixSig: encoded };
7246
+ }
7247
+ publicKey() {
7248
+ return new MLDSAPublicKey(__classPrivateFieldGet(this, _MLDSAKey_key, "f").subarray(SECRET_KEY_SIZE));
7249
+ }
7250
+ secretKey() {
7251
+ return utils$1.b58Encode(__classPrivateFieldGet(this, _MLDSAKey_key, "f"), utils$1.PrefixV2.MLDSA44SecretKey);
7252
+ }
7253
+ }
7254
+ _MLDSAKey_key = new WeakMap();
7255
+ class MLDSAPublicKey {
7256
+ constructor(src) {
7257
+ _MLDSAPublicKey_key.set(this, void 0);
7258
+ const key = typeof src === 'string' ? utils$1.b58DecodeAndCheckPrefix(src, [utils$1.PrefixV2.MLDSA44PublicKey])[0] : src;
7259
+ if (key.length !== utils$1.payloadLength[utils$1.PrefixV2.MLDSA44PublicKey]) {
7260
+ throw new utils$1.InvalidPublicKeyError('Invalid ML-DSA-44 public key length');
7261
+ }
7262
+ __classPrivateFieldSet(this, _MLDSAPublicKey_key, Uint8Array.from(key), "f");
7263
+ }
7264
+ compare(other) {
7265
+ if (!(other instanceof MLDSAPublicKey)) {
7266
+ throw new utils$1.InvalidPublicKeyError('ML-DSA-44 key expected');
7267
+ }
7268
+ return utils$1.compareArrays(__classPrivateFieldGet(this, _MLDSAPublicKey_key, "f"), __classPrivateFieldGet(other, _MLDSAPublicKey_key, "f"));
7269
+ }
7270
+ hash() {
7271
+ return utils$1.b58Encode(blake2b(__classPrivateFieldGet(this, _MLDSAPublicKey_key, "f"), { dkLen: 20 }), utils$1.PrefixV2.MLDSA44PublicKeyHash);
7272
+ }
7273
+ bytes() {
7274
+ return __classPrivateFieldGet(this, _MLDSAPublicKey_key, "f").slice();
7275
+ }
7276
+ toProtocol() {
7277
+ return utils$1.mergebuf(new Uint8Array([4]), __classPrivateFieldGet(this, _MLDSAPublicKey_key, "f"));
7278
+ }
7279
+ toString() {
7280
+ return utils$1.b58Encode(__classPrivateFieldGet(this, _MLDSAPublicKey_key, "f"), utils$1.PrefixV2.MLDSA44PublicKey);
7281
+ }
7282
+ }
7283
+ _MLDSAPublicKey_key = new WeakMap();
7284
+
7285
+ var _InMemorySigner_key;
7286
+ /**
7287
+ * A local implementation of the signer. Will represent a Tezos account and be able to produce signature in its behalf
7288
+ *
7289
+ * @remarks If running in production and dealing with tokens that have real value, it is strongly recommended to use a HSM backed signer so that private key material is not stored in memory or on disk
7290
+ * @throws InvalidMnemonicError
7291
+ */
7292
+ class InMemorySigner {
7293
+ static fromFundraiser(email, password, mnemonic) {
7294
+ if (!validateMnemonic(mnemonic, wordlist)) {
7295
+ throw new InvalidMnemonicError();
7296
+ }
7297
+ const seed = mnemonicToSeedSync(mnemonic, `${email}${password}`);
7298
+ const key = utils$1.b58Encode(seed.subarray(0, 32), utils$1.PrefixV2.Ed25519Seed);
7299
+ return new InMemorySigner(key);
7300
+ }
7301
+ static async fromSecretKey(key, passphrase) {
7302
+ return new InMemorySigner(key, passphrase);
7303
+ }
7304
+ /**
7305
+ *
7306
+ * Instantiation of an InMemorySigner instance from a mnemonic
7307
+ * @returns InMemorySigner
7308
+ * @throws InvalidMnemonicError
7309
+ */
7310
+ static fromMnemonic({ mnemonic, password = '', derivationPath = "44'/1729'/0'/0'", curve = 'ed25519', }) {
7311
+ // check if curve is defined if not default tz1
7312
+ if (!validateMnemonic(mnemonic, wordlist)) {
7313
+ // avoiding exposing mnemonic again in case of mistake making invalid
7314
+ throw new InvalidMnemonicError();
7315
+ }
7316
+ const seed = mnemonicToSeedSync(mnemonic, password);
7317
+ const sk = generateSecretKey(seed, derivationPath, curve);
7318
+ return new InMemorySigner(sk);
7319
+ }
7320
+ /**
7321
+ *
7322
+ * @param key Encoded private key
7323
+ * @param passphrase Passphrase to decrypt the private key if it is encrypted
7324
+ * @throws InvalidKeyError
7325
+ *
7326
+ */
7327
+ constructor(key, passphrase) {
7328
+ _InMemorySigner_key.set(this, void 0);
7329
+ const keyPrefixes = [
7330
+ utils$1.PrefixV2.Ed25519EncryptedSeed,
7331
+ utils$1.PrefixV2.Ed25519Seed,
7332
+ utils$1.PrefixV2.Ed25519SecretKey,
7333
+ utils$1.PrefixV2.Secp256k1EncryptedSecretKey,
7334
+ utils$1.PrefixV2.Secp256k1SecretKey,
4821
7335
  utils$1.PrefixV2.P256EncryptedSecretKey,
4822
7336
  utils$1.PrefixV2.P256SecretKey,
4823
7337
  utils$1.PrefixV2.BLS12_381EncryptedSecretKey,
4824
7338
  utils$1.PrefixV2.BLS12_381SecretKey,
7339
+ utils$1.PrefixV2.MLDSA44EncryptedSecretKey,
7340
+ utils$1.PrefixV2.MLDSA44SecretKey,
4825
7341
  ];
4826
7342
  const pre = (() => {
4827
7343
  try {
@@ -4835,7 +7351,8 @@ zoo`.split('\n'));
4835
7351
  const encrypted = pre === utils$1.PrefixV2.Ed25519EncryptedSeed ||
4836
7352
  pre === utils$1.PrefixV2.Secp256k1EncryptedSecretKey ||
4837
7353
  pre === utils$1.PrefixV2.P256EncryptedSecretKey ||
4838
- pre === utils$1.PrefixV2.BLS12_381EncryptedSecretKey;
7354
+ pre === utils$1.PrefixV2.BLS12_381EncryptedSecretKey ||
7355
+ pre === utils$1.PrefixV2.MLDSA44EncryptedSecretKey;
4839
7356
  let decrypt;
4840
7357
  if (encrypted) {
4841
7358
  if (!passphrase) {
@@ -4874,6 +7391,10 @@ zoo`.split('\n'));
4874
7391
  case utils$1.PrefixV2.BLS12_381SecretKey:
4875
7392
  __classPrivateFieldSet(this, _InMemorySigner_key, new BLSKey(key, decrypt), "f");
4876
7393
  break;
7394
+ case utils$1.PrefixV2.MLDSA44EncryptedSecretKey:
7395
+ case utils$1.PrefixV2.MLDSA44SecretKey:
7396
+ __classPrivateFieldSet(this, _InMemorySigner_key, new MLDSAKey(key, decrypt), "f");
7397
+ break;
4877
7398
  }
4878
7399
  }
4879
7400
  /**
@@ -4885,13 +7406,17 @@ zoo`.split('\n'));
4885
7406
  const msg = typeof message == 'string' ? utils$1.hex2buf(message) : message;
4886
7407
  const watermarkMsg = watermark !== undefined ? utils$1.mergebuf(watermark, msg) : msg;
4887
7408
  const { rawSignature, sig: signature, prefixSig: prefixedSignature, } = await __classPrivateFieldGet(this, _InMemorySigner_key, "f").sign(watermarkMsg);
7409
+ // Variable-length operation signatures carry the signature-prefix marker
7410
+ // and scheme tag before the complete signature payload (Octez signature_v3).
7411
+ const signatureTag = __classPrivateFieldGet(this, _InMemorySigner_key, "f") instanceof MLDSAKey ? 4 : __classPrivateFieldGet(this, _InMemorySigner_key, "f") instanceof BLSKey ? 3 : undefined;
7412
+ const signatureBytes = signatureTag === undefined
7413
+ ? rawSignature
7414
+ : utils$1.mergebuf(new Uint8Array([255, signatureTag]), rawSignature);
4888
7415
  return {
4889
7416
  bytes: utils$1.buf2hex(msg),
4890
7417
  sig: signature,
4891
7418
  prefixSig: prefixedSignature,
4892
- sbytes: utils$1.buf2hex(utils$1.mergebuf(msg,
4893
- // bls only Signature_prefix ff03 ref:https://octez.tezos.com/docs/shell/p2p_api.html#signature-prefix-tag-255 & https://octez.tezos.com/docs/shell/p2p_api.html#bls-prefix-tag-3
4894
- isPOP(__classPrivateFieldGet(this, _InMemorySigner_key, "f")) ? utils$1.mergebuf(new Uint8Array([255, 3]), rawSignature) : rawSignature)),
7419
+ sbytes: utils$1.buf2hex(utils$1.mergebuf(msg, signatureBytes)),
4895
7420
  };
4896
7421
  }
4897
7422
  async provePossession() {
@@ -4931,6 +7456,7 @@ zoo`.split('\n'));
4931
7456
  utils$1.PrefixV2.Secp256k1PublicKey,
4932
7457
  utils$1.PrefixV2.P256PublicKey,
4933
7458
  utils$1.PrefixV2.BLS12_381PublicKey,
7459
+ utils$1.PrefixV2.MLDSA44PublicKey,
4934
7460
  ]);
4935
7461
  switch (pre) {
4936
7462
  case utils$1.PrefixV2.Ed25519PublicKey:
@@ -4941,13 +7467,15 @@ zoo`.split('\n'));
4941
7467
  return new ECPublicKey(keyData, 'p256');
4942
7468
  case utils$1.PrefixV2.BLS12_381PublicKey:
4943
7469
  return new BLSPublicKey(keyData);
7470
+ case utils$1.PrefixV2.MLDSA44PublicKey:
7471
+ return new MLDSAPublicKey(keyData);
4944
7472
  }
4945
7473
  }
4946
7474
 
4947
7475
  // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT!
4948
7476
  const VERSION = {
4949
- "commitHash": "13f62cd47ea018312f100b660d0225604c757afa",
4950
- "version": "25.0.0"
7477
+ "commitHash": "a1d45363559ba27998bbc263b69c961710e4710a",
7478
+ "version": "25.1.0-beta0"
4951
7479
  };
4952
7480
 
4953
7481
  exports.ECDSA = ecdsa;