starknet 11.7.2 → 11.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,16 +31,83 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var falcon_exports = {};
32
32
  __export(falcon_exports, {
33
33
  Falcon512Signer: () => Falcon512Signer,
34
- falcon512: () => falcon512_exports
34
+ falcon512: () => falcon512_exports,
35
+ mlkem: () => mlkem_exports
35
36
  });
36
37
  module.exports = __toCommonJS(falcon_exports);
37
38
 
38
39
  // src/falcon/Falcon512Signer.ts
39
- var starknet6 = __toESM(require("starknet"));
40
+ var starknet8 = __toESM(require("starknet"));
40
41
 
41
- // src/falcon/s2morrow/keys.ts
42
- var import_utils6 = require("@noble/hashes/utils.js");
43
- var starknet3 = __toESM(require("starknet"));
42
+ // src/falcon/accountType.ts
43
+ var ACCOUNT_TYPES = Object.freeze([
44
+ "s2morrow",
45
+ "oz-hint",
46
+ "oz-direct"
47
+ ]);
48
+ function parseFalconOptions(options) {
49
+ if (options === void 0) return "s2morrow";
50
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
51
+ throw new Error("Falcon512: options must be an object");
52
+ }
53
+ Object.keys(options).forEach((key) => {
54
+ if (key !== "accountType") throw new Error(`Falcon512: unknown option "${key}"`);
55
+ });
56
+ const { accountType } = options;
57
+ if (accountType === void 0) return "s2morrow";
58
+ if (!ACCOUNT_TYPES.includes(accountType)) {
59
+ throw new Error(
60
+ `Falcon512: unknown accountType "${String(accountType)}" (expected 's2morrow', 'oz-hint' or 'oz-direct')`
61
+ );
62
+ }
63
+ return accountType;
64
+ }
65
+
66
+ // src/falcon/oz/ownership.ts
67
+ var starknet2 = __toESM(require("starknet"));
68
+
69
+ // src/falcon/s2morrow/constants.ts
70
+ var Q = 12289;
71
+ var QB = 12289n;
72
+ var N = 512;
73
+ var SIG_BOUND_512 = 34034726;
74
+ var PACKED_SLOTS = 29;
75
+ var VALUES_PER_HALF = 9;
76
+ var SALT_FELTS = 2;
77
+ var SIGNATURE_FELTS = 61;
78
+
79
+ // src/falcon/s2morrow/felt.ts
80
+ var starknet = __toESM(require("starknet"));
81
+ function assertFelt(x, label) {
82
+ if (typeof x !== "bigint") throw new Error(`Falcon512: ${label} is not a felt252`);
83
+ starknet.CairoFelt252.assertRange(x);
84
+ }
85
+ var FELT_STRING = /^(0[xX][0-9a-fA-F]{1,64}|[0-9]{1,76})$/;
86
+ function parseFelt(value, label) {
87
+ const accepted = typeof value === "bigint" && value >= 0n || typeof value === "number" && Number.isSafeInteger(value) && value >= 0 || typeof value === "string" && FELT_STRING.test(value);
88
+ if (!accepted) throw new Error(`Falcon512: ${label} is not a felt252`);
89
+ return new starknet.CairoFelt252(value).toBigInt();
90
+ }
91
+
92
+ // src/falcon/oz/ownership.ts
93
+ function ownershipAcceptanceHash(accountAddress, currentPublicKey) {
94
+ if (!Array.isArray(currentPublicKey) || currentPublicKey.length !== PACKED_SLOTS && currentPublicKey.length !== 0) {
95
+ throw new Error("Falcon512: current public key must have 29 felts, or none");
96
+ }
97
+ const address = parseFelt(accountAddress, "account address");
98
+ const key = currentPublicKey.map((x, i) => parseFelt(x, `current public key[${i}]`));
99
+ const { computePoseidonHashOnElements } = starknet2.hash;
100
+ return computePoseidonHashOnElements([
101
+ starknet2.CairoBytes31.fromText("StarkNet Message").toBigInt(),
102
+ starknet2.CairoBytes31.fromText("accept_ownership").toBigInt(),
103
+ address,
104
+ computePoseidonHashOnElements(key)
105
+ ]);
106
+ }
107
+
108
+ // src/falcon/oz/signature.ts
109
+ var import_utils9 = require("@noble/hashes/utils.js");
110
+ var starknet6 = __toESM(require("starknet"));
44
111
 
45
112
  // src/falcon/engine/noble/falcon.ts
46
113
  var import_aes = require("@noble/ciphers/aes.js");
@@ -57,6 +124,15 @@ var import_sha3 = require("@noble/hashes/sha3.js");
57
124
 
58
125
  // src/falcon/engine/noble/utils.ts
59
126
  var import_utils = require("@noble/hashes/utils.js");
127
+ var abytesDoc = import_utils.abytes;
128
+ var randomBytes = import_utils.randomBytes;
129
+ function aarray(item, title, inner = () => {
130
+ }) {
131
+ if (!Array.isArray(item))
132
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
133
+ for (let i = 0; i < item.length; i++) inner(item[i], `${title}[${i}]`);
134
+ return item;
135
+ }
60
136
  function aobject(value, title = "object") {
61
137
  if (value === null || typeof value !== "object" || Array.isArray(value))
62
138
  throw new TypeError(
@@ -64,6 +140,14 @@ function aobject(value, title = "object") {
64
140
  );
65
141
  return value;
66
142
  }
143
+ function equalBytes(a, b) {
144
+ a = (0, import_utils.abytes)(a);
145
+ b = (0, import_utils.abytes)(b);
146
+ if (a.length !== b.length) return false;
147
+ let diff = 0;
148
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
149
+ return diff === 0;
150
+ }
67
151
  function copyBytes(bytes) {
68
152
  return new Uint8Array((0, import_utils.abytes)(bytes));
69
153
  }
@@ -86,10 +170,10 @@ function byteSwap64(arr) {
86
170
  return arr;
87
171
  }
88
172
  var baswap64If = import_utils.isLE ? (arr) => arr : byteSwap64;
89
- function validateOpts(opts) {
90
- if ((0, import_utils.isBytes)(opts)) throw new TypeError('"opts" expected object, got Uint8Array');
91
- aobject(opts, "opts");
92
- const proto = Object.getPrototypeOf(opts);
173
+ function validateOpts(opts2) {
174
+ if ((0, import_utils.isBytes)(opts2)) throw new TypeError('"opts" expected object, got Uint8Array');
175
+ aobject(opts2, "opts");
176
+ const proto = Object.getPrototypeOf(opts2);
93
177
  if (proto !== null && proto !== Object.prototype)
94
178
  throw new TypeError('"opts" expected a plain object');
95
179
  }
@@ -100,9 +184,9 @@ var SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([
100
184
  "context",
101
185
  "extraEntropy"
102
186
  ]);
103
- function checkOptKeys(opts, allowed) {
104
- validateOpts(opts);
105
- const normalized = Object.assign(/* @__PURE__ */ Object.create(null), opts);
187
+ function checkOptKeys(opts2, allowed) {
188
+ validateOpts(opts2);
189
+ const normalized = Object.assign(/* @__PURE__ */ Object.create(null), opts2);
106
190
  for (const [k, v] of Object.entries(normalized)) {
107
191
  if (v === void 0) continue;
108
192
  if (!allowed.includes(k))
@@ -112,13 +196,13 @@ function checkOptKeys(opts, allowed) {
112
196
  }
113
197
  return Object.freeze(normalized);
114
198
  }
115
- function validateVerOpts(opts, allowed = VER_OPT_KEYS) {
116
- const normalized = checkOptKeys(opts, allowed);
199
+ function validateVerOpts(opts2, allowed = VER_OPT_KEYS) {
200
+ const normalized = checkOptKeys(opts2, allowed);
117
201
  if (normalized.context !== void 0) (0, import_utils.abytes)(normalized.context, void 0, "opts.context");
118
202
  return normalized;
119
203
  }
120
- function validateSigOpts(opts, allowed = SIG_OPT_KEYS) {
121
- const normalized = checkOptKeys(opts, allowed);
204
+ function validateSigOpts(opts2, allowed = SIG_OPT_KEYS) {
205
+ const normalized = checkOptKeys(opts2, allowed);
122
206
  if (normalized.context !== void 0) (0, import_utils.abytes)(normalized.context, void 0, "opts.context");
123
207
  if (normalized.extraEntropy !== false && normalized.extraEntropy !== void 0)
124
208
  (0, import_utils.abytes)(normalized.extraEntropy, void 0, "opts.extraEntropy");
@@ -155,6 +239,33 @@ function splitCoder(label, ...lengths) {
155
239
  }
156
240
  };
157
241
  }
242
+ function vecCoder(c, vecLen) {
243
+ const coder = c;
244
+ const bytesLen = vecLen * coder.bytesLen;
245
+ return {
246
+ bytesLen,
247
+ encode: (u) => {
248
+ const uArr = aarray(u, "u");
249
+ if (uArr.length !== vecLen)
250
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
251
+ const res = new Uint8Array(bytesLen);
252
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
253
+ const b = coder.encode(uArr[i]);
254
+ res.set(b, pos);
255
+ b.fill(0);
256
+ pos += b.length;
257
+ }
258
+ return res;
259
+ },
260
+ decode: (a) => {
261
+ (0, import_utils.abytes)(a, bytesLen);
262
+ const r = [];
263
+ for (let i = 0; i < a.length; i += coder.bytesLen)
264
+ r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
265
+ return r;
266
+ }
267
+ };
268
+ }
158
269
  function cleanBytes(...list) {
159
270
  for (const t of list) {
160
271
  if (Array.isArray(t)) for (const b of t) b.fill(0);
@@ -168,21 +279,21 @@ function getMask(bits) {
168
279
  }
169
280
 
170
281
  // src/falcon/engine/noble/_crystals.ts
171
- var genCrystals = (opts) => {
172
- const { newPoly, N: N2, Q: Q3, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;
173
- const mod = (a, modulo = Q3) => {
282
+ var genCrystals = (opts2) => {
283
+ const { newPoly, N: N3, Q: Q4, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts2;
284
+ const mod = (a, modulo = Q4) => {
174
285
  const result = a % modulo | 0;
175
286
  return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
176
287
  };
177
- const smod = (a, modulo = Q3) => {
288
+ const smod = (a, modulo = Q4) => {
178
289
  const r = mod(a, modulo) | 0;
179
290
  return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
180
291
  };
181
292
  function getZettas() {
182
- const out = newPoly(N2);
183
- for (let i = 0; i < N2; i++) {
293
+ const out = newPoly(N3);
294
+ for (let i = 0; i < N3; i++) {
184
295
  const b = (0, import_fft.reverseBits)(i, brvBits);
185
- const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q3);
296
+ const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q4);
186
297
  out[i] = Number(p) | 0;
187
298
  }
188
299
  return out;
@@ -194,11 +305,11 @@ var genCrystals = (opts) => {
194
305
  const field = isKyber ? {
195
306
  add: (a, b) => {
196
307
  const r = a + b | 0;
197
- return r >= Q3 ? r - Q3 | 0 : r;
308
+ return r >= Q4 ? r - Q4 | 0 : r;
198
309
  },
199
310
  sub: (a, b) => {
200
311
  const r = a - b | 0;
201
- return r < 0 ? r + Q3 | 0 : r;
312
+ return r < 0 ? r + Q4 | 0 : r;
202
313
  },
203
314
  mul: (a, b) => mod((a | 0) * (b | 0)) | 0,
204
315
  inv
@@ -209,7 +320,7 @@ var genCrystals = (opts) => {
209
320
  inv
210
321
  };
211
322
  const nttOpts = {
212
- N: N2,
323
+ N: N3,
213
324
  roots: nttZetas,
214
325
  invertButterflies: true,
215
326
  skipStages: isKyber ? 1 : 0,
@@ -223,18 +334,18 @@ var genCrystals = (opts) => {
223
334
  },
224
335
  decode: (r) => {
225
336
  dit(r);
226
- for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);
337
+ for (let i = 0; i < r.length; i++) r[i] = mod(F2 * r[i]);
227
338
  return r;
228
339
  }
229
340
  };
230
341
  const bitsCoder = (d, c) => {
231
- for (let i = 0, bufLen = 0; i < N2; i++) {
342
+ for (let i = 0, bufLen = 0; i < N3; i++) {
232
343
  bufLen += d;
233
344
  if (bufLen > 32) getMask(bufLen);
234
345
  bufLen %= 8;
235
346
  }
236
347
  const mask = getMask(d);
237
- const bytesLen = d * (N2 / 8);
348
+ const bytesLen = d * (N3 / 8);
238
349
  return {
239
350
  bytesLen,
240
351
  encode: (poly_) => {
@@ -248,7 +359,7 @@ var genCrystals = (opts) => {
248
359
  return r;
249
360
  },
250
361
  decode: (bytes) => {
251
- const r = newPoly(N2);
362
+ const r = newPoly(N3);
252
363
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
253
364
  buf |= bytes[i] << bufLen;
254
365
  bufLen += 8;
@@ -269,15 +380,44 @@ var genCrystals = (opts) => {
269
380
  bitsCoder
270
381
  };
271
382
  };
383
+ var createXofShake = (shake) => (seed, blockLen) => {
384
+ if (!blockLen) blockLen = shake.blockLen;
385
+ const _seed = new Uint8Array(seed.length + 2);
386
+ _seed.set(seed);
387
+ const seedLen = seed.length;
388
+ const buf = new Uint8Array(blockLen);
389
+ let h = shake.create({});
390
+ let calls = 0;
391
+ let xofs = 0;
392
+ return {
393
+ stats: () => ({ calls, xofs }),
394
+ get: (x, y) => {
395
+ _seed[seedLen + 0] = x;
396
+ _seed[seedLen + 1] = y;
397
+ h.destroy();
398
+ h = shake.create({}).update(_seed);
399
+ calls++;
400
+ return () => {
401
+ xofs++;
402
+ return h.xofInto(buf);
403
+ };
404
+ },
405
+ clean: () => {
406
+ h.destroy();
407
+ cleanBytes(buf, _seed);
408
+ }
409
+ };
410
+ };
411
+ var XOF128 = /* @__PURE__ */ createXofShake(import_sha3.shake128);
272
412
 
273
413
  // src/falcon/engine/noble/falcon.ts
274
- var bitsCoderMSB = (newPoly, N2, d, c) => {
414
+ var bitsCoderMSB = (newPoly, N3, d, c) => {
275
415
  const mask = getMask(d);
276
- const bytesLen = d * (N2 / 8);
416
+ const bytesLen = d * (N3 / 8);
277
417
  return {
278
418
  bytesLen,
279
419
  encode: (poly) => {
280
- if (poly.length !== N2) throw new Error(`wrong length: expected ${N2}, got ${poly.length}`);
420
+ if (poly.length !== N3) throw new Error(`wrong length: expected ${N3}, got ${poly.length}`);
281
421
  const r = new Uint8Array(bytesLen);
282
422
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
283
423
  buf = buf << d | c.encode(poly[i]) & mask;
@@ -287,7 +427,7 @@ var bitsCoderMSB = (newPoly, N2, d, c) => {
287
427
  return r;
288
428
  },
289
429
  decode: (bytes) => {
290
- const r = newPoly(N2);
430
+ const r = newPoly(N3);
291
431
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
292
432
  buf = buf << 8 | bytes[i];
293
433
  bufLen += 8;
@@ -397,43 +537,43 @@ var cleanCPoly = (...list) => {
397
537
  }
398
538
  };
399
539
  function getComplex(field) {
400
- const F = field;
540
+ const F2 = field;
401
541
  return {
402
542
  lift: (x) => {
403
543
  if (x.re !== void 0 && x.im !== void 0) return x;
404
- return { re: x, im: F.ZERO };
544
+ return { re: x, im: F2.ZERO };
405
545
  },
406
546
  add: (a, b) => ({
407
- re: F.add(a.re, b.re),
408
- im: F.add(a.im, b.im)
547
+ re: F2.add(a.re, b.re),
548
+ im: F2.add(a.im, b.im)
409
549
  }),
410
550
  sub: (a, b) => ({
411
- re: F.sub(a.re, b.re),
412
- im: F.sub(a.im, b.im)
551
+ re: F2.sub(a.re, b.re),
552
+ im: F2.sub(a.im, b.im)
413
553
  }),
414
554
  mul: (a, b) => ({
415
- re: F.sub(F.mul(a.re, b.re), F.mul(a.im, b.im)),
416
- im: F.add(F.mul(a.re, b.im), F.mul(a.im, b.re))
555
+ re: F2.sub(F2.mul(a.re, b.re), F2.mul(a.im, b.im)),
556
+ im: F2.add(F2.mul(a.re, b.im), F2.mul(a.im, b.re))
417
557
  }),
418
558
  div: (a, b) => {
419
- const denom = F.add(F.mul(b.re, b.re), F.mul(b.im, b.im));
559
+ const denom = F2.add(F2.mul(b.re, b.re), F2.mul(b.im, b.im));
420
560
  return {
421
- re: F.div(F.add(F.mul(a.re, b.re), F.mul(a.im, b.im)), denom),
422
- im: F.div(F.sub(F.mul(a.im, b.re), F.mul(a.re, b.im)), denom)
561
+ re: F2.div(F2.add(F2.mul(a.re, b.re), F2.mul(a.im, b.im)), denom),
562
+ im: F2.div(F2.sub(F2.mul(a.im, b.re), F2.mul(a.re, b.im)), denom)
423
563
  };
424
564
  },
425
- neg: (a) => ({ re: F.neg(a.re), im: F.neg(a.im) }),
426
- conj: (a) => ({ re: a.re, im: F.neg(a.im) }),
565
+ neg: (a) => ({ re: F2.neg(a.re), im: F2.neg(a.im) }),
566
+ conj: (a) => ({ re: a.re, im: F2.neg(a.im) }),
427
567
  scale: (a, x) => ({
428
- re: F.mul(a.re, x),
429
- im: F.mul(a.im, x)
568
+ re: F2.mul(a.re, x),
569
+ im: F2.mul(a.im, x)
430
570
  }),
431
571
  // a.re * a.re + a.im * a.im + b.re * b.re + b.im * b.im;
432
- magSqSum: (a, b) => F.add(
433
- F.add(F.add(F.mul(a.re, a.re), F.mul(a.im, a.im)), F.mul(b.re, b.re)),
434
- F.mul(b.im, b.im)
572
+ magSqSum: (a, b) => F2.add(
573
+ F2.add(F2.add(F2.mul(a.re, a.re), F2.mul(a.im, a.im)), F2.mul(b.re, b.re)),
574
+ F2.mul(b.im, b.im)
435
575
  ),
436
- eql: (a, b) => F.eql(a.re, b.re) && F.eql(a.im, b.im),
576
+ eql: (a, b) => F2.eql(a.re, b.re) && F2.eql(a.im, b.im),
437
577
  clone: (a) => ({ re: a.re, im: a.im }),
438
578
  inv: () => {
439
579
  throw new Error("not implemented");
@@ -442,8 +582,8 @@ function getComplex(field) {
442
582
  }
443
583
  var ComplexArr = {
444
584
  decode(lst) {
445
- const N2 = lst.length;
446
- const hn = N2 >> 1;
585
+ const N3 = lst.length;
586
+ const hn = N3 >> 1;
447
587
  const len = lst.length;
448
588
  if (len === 0) return [];
449
589
  if (len % 2 !== 0)
@@ -505,9 +645,9 @@ var Float = /* @__PURE__ */ Object.freeze({
505
645
  var f64b = (n) => Float.decode((0, import_utils3.numberToHexUnpadded)(n));
506
646
  var EMPTY_CHACHA20_BLOCK = /* @__PURE__ */ new Uint8Array(64);
507
647
  var NONCELEN = 40;
508
- var Q = 12289;
509
- var Qhalf = Q >> 1;
510
- var QBig = BigInt(Q);
648
+ var Q2 = 12289;
649
+ var Qhalf = Q2 >> 1;
650
+ var QBig = BigInt(Q2);
511
651
  var _0n = /* @__PURE__ */ BigInt(0);
512
652
  var _1n = /* @__PURE__ */ BigInt(1);
513
653
  var _10n = /* @__PURE__ */ BigInt(10);
@@ -520,7 +660,7 @@ var MASK_32n = /* @__PURE__ */ BigInt("0xffffffff");
520
660
  var MASK_63n = /* @__PURE__ */ BigInt("0x7fffffffffffffff");
521
661
  var R2 = 10952;
522
662
  var Q0I = 12287;
523
- var F_INV_Q = 1 / Q;
663
+ var F_INV_Q = 1 / Q2;
524
664
  var F_MINUS_INV_Q = -F_INV_Q;
525
665
  var MAX_BL_SMALL = [1, 1, 2, 2, 4, 7, 14, 27, 53, 106, 209];
526
666
  var MAX_BL_LARGE = [2, 2, 5, 7, 12, 21, 40, 78, 157, 308];
@@ -681,9 +821,9 @@ var COMPLEX_ROOTS = /* @__PURE__ */ (() => {
681
821
  var intField = {
682
822
  mul(x, y) {
683
823
  let z = Math.imul(x, y);
684
- let w = Math.imul(Q, Math.imul(z, Q0I) & 65535);
685
- z = (z + w >>> 16) - Q;
686
- z += Q & z >> 31;
824
+ let w = Math.imul(Q2, Math.imul(z, Q0I) & 65535);
825
+ z = (z + w >>> 16) - Q2;
826
+ z += Q2 & z >> 31;
687
827
  return z >>> 0;
688
828
  },
689
829
  inv(y) {
@@ -714,11 +854,11 @@ var intField = {
714
854
  function getIntPoly(logn) {
715
855
  const n = 1 << logn;
716
856
  const newPoly = (n2) => new Uint16Array(n2);
717
- const F = Number((0, import_modular.invert)(BigInt(n), QBig));
857
+ const F2 = Number((0, import_modular.invert)(BigInt(n), QBig));
718
858
  const { mod, smod, NTT } = genCrystals({
719
859
  N: n,
720
- Q,
721
- F,
860
+ Q: Q2,
861
+ F: F2,
722
862
  ROOT_OF_UNITY: 7,
723
863
  newPoly,
724
864
  isKyber: false,
@@ -868,9 +1008,9 @@ function ApproxExp(x, ccs) {
868
1008
  for (let i = ev.length - 2; i >= 0; i--) z = z * y + ev[i];
869
1009
  return ccs * (1 + z * y);
870
1010
  }
871
- function genFalcon(opts) {
872
- const { N: N2 } = opts;
873
- const logn = Math.log2(N2);
1011
+ function genFalcon(opts2) {
1012
+ const { N: N3 } = opts2;
1013
+ const logn = Math.log2(N3);
874
1014
  const id = (n) => n;
875
1015
  const { newPoly, intPoly, signedCoder } = getIntPoly(logn);
876
1016
  const floatPoly = getFloatPoly(logn);
@@ -957,7 +1097,7 @@ function genFalcon(opts) {
957
1097
  }
958
1098
  return a;
959
1099
  }
960
- reduce(logn2, f, g, F, G, logn_top) {
1100
+ reduce(logn2, f, g, F2, G, logn_top) {
961
1101
  const n = 1 << logn2;
962
1102
  const depth = logn_top - logn2;
963
1103
  const floatPoly2 = getFloatPoly(logn2);
@@ -984,7 +1124,7 @@ function genFalcon(opts) {
984
1124
  while (true) {
985
1125
  let scaleFG = _31n * (FGlen - _10n);
986
1126
  for (let i = 0; i < n; i++) {
987
- Fx[i] = Number(F[i] >> scaleFG);
1127
+ Fx[i] = Number(F2[i] >> scaleFG);
988
1128
  Gx[i] = Number(G[i] >> scaleFG);
989
1129
  }
990
1130
  const rt2 = floatPoly2.mul(floatPoly2.FFT(floatPoly2.to(Gx)), rt4);
@@ -999,7 +1139,7 @@ function genFalcon(opts) {
999
1139
  if (val <= -BOUND || val >= BOUND) return false;
1000
1140
  k[i] = BigInt(Math.round(val));
1001
1141
  }
1002
- F = this.subMul(logn2, F, f, k, scaleK);
1142
+ F2 = this.subMul(logn2, F2, f, k, scaleK);
1003
1143
  G = this.subMul(logn2, G, g, k, scaleK);
1004
1144
  const maxfgNew = scaleK + BigInt(Math.round(fgMaxBits)) + _10n;
1005
1145
  if (maxfgNew < maxFGBits) maxFGBits = maxfgNew;
@@ -1011,7 +1151,7 @@ function genFalcon(opts) {
1011
1151
  return true;
1012
1152
  }
1013
1153
  // This is recursive thing that goes from logn to 0
1014
- solveBranch(logn2, f, g, F, G, logn_top) {
1154
+ solveBranch(logn2, f, g, F2, G, logn_top) {
1015
1155
  if (logn2 === 0) {
1016
1156
  const xf = f[0];
1017
1157
  const xg = g[0];
@@ -1019,7 +1159,7 @@ function genFalcon(opts) {
1019
1159
  try {
1020
1160
  const u1 = (0, import_modular.invert)(xf, xg);
1021
1161
  const v1 = (_1n - u1 * xf) / xg;
1022
- F[0] = -v1 * QBig;
1162
+ F2[0] = -v1 * QBig;
1023
1163
  G[0] = u1 * QBig;
1024
1164
  return true;
1025
1165
  } catch (e) {
@@ -1035,9 +1175,9 @@ function genFalcon(opts) {
1035
1175
  const Fp = new Array(hn);
1036
1176
  const Gp = new Array(hn);
1037
1177
  if (!this.solveBranch(logn2 - 1, fp, gp, Fp, Gp, logn_top)) return false;
1038
- F = this.mulConjD(logn2, F, g, Fp);
1178
+ F2 = this.mulConjD(logn2, F2, g, Fp);
1039
1179
  G = this.mulConjD(logn2, G, f, Gp);
1040
- return this.reduce(logn2, f, g, F, G, logn_top);
1180
+ return this.reduce(logn2, f, g, F2, G, logn_top);
1041
1181
  }
1042
1182
  solve(f, g) {
1043
1183
  const n = 1 << logn;
@@ -1046,16 +1186,16 @@ function genFalcon(opts) {
1046
1186
  const bF = new Array(n);
1047
1187
  const bG = new Array(n);
1048
1188
  if (!this.solveBranch(logn, bf, bg, bF, bG)) return false;
1049
- const F = new Int8Array(n);
1189
+ const F2 = new Int8Array(n);
1050
1190
  const G = new Int8Array(n);
1051
1191
  for (let i = 0; i < n; i++) {
1052
1192
  const x = bF[i];
1053
1193
  const y = bG[i];
1054
1194
  if (x < -127 || x > 127 || y < -127 || y > 127) return false;
1055
- F[i] = Number(x);
1195
+ F2[i] = Number(x);
1056
1196
  G[i] = Number(y);
1057
1197
  }
1058
- return [F, G];
1198
+ return [F2, G];
1059
1199
  }
1060
1200
  generate() {
1061
1201
  let max = 1e6;
@@ -1064,8 +1204,8 @@ function genFalcon(opts) {
1064
1204
  if (curr++ === max) throw new Error("can't generate key");
1065
1205
  const f = this.polyGauss();
1066
1206
  const g = this.polyGauss();
1067
- let lim = 1 << opts.fgBits - 1;
1068
- for (let u = 0; u < N2; u++) {
1207
+ let lim = 1 << opts2.fgBits - 1;
1208
+ for (let u = 0; u < N3; u++) {
1069
1209
  if (f[u] >= lim || f[u] <= -lim || g[u] >= lim || g[u] <= -lim) {
1070
1210
  lim = -1;
1071
1211
  break;
@@ -1079,8 +1219,8 @@ function genFalcon(opts) {
1079
1219
  let rt1 = floatPoly.FFT(floatPoly.convSmall(f));
1080
1220
  let rt2 = floatPoly.FFT(floatPoly.convSmall(g));
1081
1221
  const rt3 = floatPoly.invNorm(rt1, rt2);
1082
- rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q), rt3));
1083
- rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q), rt3));
1222
+ rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q2), rt3));
1223
+ rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q2), rt3));
1084
1224
  let bnorm = 0;
1085
1225
  for (let u = 0; u < rt1.length; u++) {
1086
1226
  bnorm += rt1[u].re * rt1[u].re;
@@ -1104,7 +1244,7 @@ function genFalcon(opts) {
1104
1244
  }
1105
1245
  }
1106
1246
  const modqCoder = () => {
1107
- const coder = bitsCoderMSB(newPoly, N2, 14, {
1247
+ const coder = bitsCoderMSB(newPoly, N3, 14, {
1108
1248
  encode: id,
1109
1249
  decode: id
1110
1250
  });
@@ -1130,7 +1270,7 @@ function genFalcon(opts) {
1130
1270
  };
1131
1271
  const trimI8Coder = (bits) => {
1132
1272
  const shift = 32 - bits;
1133
- const coder = bitsCoderMSB((len) => new Int8Array(len), N2, bits, {
1273
+ const coder = bitsCoderMSB((len) => new Int8Array(len), N3, bits, {
1134
1274
  encode: (v) => v & (1 << bits) - 1,
1135
1275
  decode: (w) => (w & getMask(bits)) << shift >> shift
1136
1276
  });
@@ -1152,25 +1292,25 @@ function genFalcon(opts) {
1152
1292
  }
1153
1293
  };
1154
1294
  };
1155
- const fgCoder = trimI8Coder(opts.fgBits);
1156
- const FGCoder = trimI8Coder(opts.FGBits);
1295
+ const fgCoder = trimI8Coder(opts2.fgBits);
1296
+ const FGCoder = trimI8Coder(opts2.FGBits);
1157
1297
  const secretKeyCoder = headerCoder(
1158
1298
  80 + logn,
1159
1299
  splitCoder("falcon.secretKey", fgCoder, fgCoder, FGCoder)
1160
1300
  );
1161
1301
  const publicKeyCoder = headerCoder(0 + logn, modqCoder());
1162
1302
  const decodePaddedSig = (s2) => {
1163
- const normalized = compCoder(N2).encode(compCoder(N2).decode(s2));
1303
+ const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
1164
1304
  for (let i = normalized.length; i < s2.length; i++)
1165
1305
  if (s2[i] !== 0) throw new Error("non-zero padding");
1166
1306
  return normalized;
1167
1307
  };
1168
1308
  const decodeUnpaddedSig = (s2) => {
1169
- const normalized = compCoder(N2).encode(compCoder(N2).decode(s2));
1309
+ const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
1170
1310
  if (normalized.length !== s2.length) throw new Error("wrong signature length");
1171
1311
  return s2;
1172
1312
  };
1173
- const decodeSig = opts.padded ? decodePaddedSig : decodeUnpaddedSig;
1313
+ const decodeSig = opts2.padded ? decodePaddedSig : decodeUnpaddedSig;
1174
1314
  const SignatureCoderBasic = (logn2) => {
1175
1315
  const TYPE_BYTE = 32 + logn2;
1176
1316
  return {
@@ -1207,7 +1347,7 @@ function genFalcon(opts) {
1207
1347
  };
1208
1348
  };
1209
1349
  const SignatureCoderPadded = (logn2) => {
1210
- const sigLen = opts.paddedLen;
1350
+ const sigLen = opts2.paddedLen;
1211
1351
  return {
1212
1352
  encode({ msg, nonce, s2 }) {
1213
1353
  return headerCoder(
@@ -1228,19 +1368,19 @@ function genFalcon(opts) {
1228
1368
  };
1229
1369
  };
1230
1370
  const SignatureCoderDetached = (logn2) => {
1231
- const paddedSigLen = opts.sigLen - 1 - NONCELEN;
1232
- const getSigLen = (s2) => opts.padded ? paddedSigLen : s2.length;
1371
+ const paddedSigLen = opts2.sigLen - 1 - NONCELEN;
1372
+ const getSigLen = (s2) => opts2.padded ? paddedSigLen : s2.length;
1233
1373
  return {
1234
1374
  encode({ nonce, s2 }) {
1235
1375
  return headerCoder(
1236
1376
  48 + logn2,
1237
1377
  splitCoder("falcon.detachedSignature", NONCELEN, getSigLen(s2))
1238
- ).encode([nonce, opts.padded ? pad(paddedSigLen).encode(s2) : s2]);
1378
+ ).encode([nonce, opts2.padded ? pad(paddedSigLen).encode(s2) : s2]);
1239
1379
  },
1240
1380
  decode(data) {
1241
- if (!opts.padded && data.length > 1 + NONCELEN + opts.maxS2Len)
1381
+ if (!opts2.padded && data.length > 1 + NONCELEN + opts2.maxS2Len)
1242
1382
  throw new Error("detached signature too long");
1243
- const payloadLen = opts.padded ? paddedSigLen : data.length - NONCELEN - 1;
1383
+ const payloadLen = opts2.padded ? paddedSigLen : data.length - NONCELEN - 1;
1244
1384
  const [nonce, raw] = headerCoder(
1245
1385
  48 + logn2,
1246
1386
  splitCoder("falcon.detachedSignature", NONCELEN, payloadLen)
@@ -1250,10 +1390,10 @@ function genFalcon(opts) {
1250
1390
  }
1251
1391
  };
1252
1392
  };
1253
- const SignatureCoder = (opts.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn);
1393
+ const SignatureCoder = (opts2.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn);
1254
1394
  const invertF = (f) => {
1255
1395
  const tt = intPoly.ntt(signedCoder.decode(f));
1256
- for (let u = 0; u < N2; u++)
1396
+ for (let u = 0; u < N3; u++)
1257
1397
  if (tt[u] === 0) throw new Error("invalid secretKey: non-invertible f");
1258
1398
  return tt;
1259
1399
  };
@@ -1264,15 +1404,15 @@ function genFalcon(opts) {
1264
1404
  cleanBytes(tt);
1265
1405
  return res2;
1266
1406
  }
1267
- function completePrivate(f, g, F) {
1407
+ function completePrivate(f, g, F2) {
1268
1408
  let t1 = intPoly.toMontgomery(intPoly.ntt(signedCoder.decode(g)));
1269
- const t2 = intPoly.ntt(signedCoder.decode(F));
1409
+ const t2 = intPoly.ntt(signedCoder.decode(F2));
1270
1410
  const tt = invertF(f);
1271
1411
  t1 = intPoly.div(intPoly.mul(t1, t2), tt);
1272
- const G = new Int8Array(N2);
1273
- for (let u = 0; u < N2; u++) {
1412
+ const G = new Int8Array(N3);
1413
+ for (let u = 0; u < N3; u++) {
1274
1414
  let w = t1[u];
1275
- w -= Q & ~-(w - Qhalf >>> 31);
1415
+ w -= Q2 & ~-(w - Qhalf >>> 31);
1276
1416
  const gi = w | 0;
1277
1417
  if (gi < -127 || gi > 127) {
1278
1418
  cleanBytes(t1, t2, tt, G);
@@ -1285,12 +1425,12 @@ function genFalcon(opts) {
1285
1425
  }
1286
1426
  function HashToPoint(nonce, msg) {
1287
1427
  const h = import_sha32.shake256.create().update(nonce).update(msg);
1288
- const c = new Uint16Array(N2);
1289
- const kQ = 5 * Q;
1290
- for (let i = 0; i < N2; ) {
1428
+ const c = new Uint16Array(N3);
1429
+ const kQ = 5 * Q2;
1430
+ for (let i = 0; i < N3; ) {
1291
1431
  const tmp = h.xof(2);
1292
1432
  let w = tmp[0] << 8 | tmp[1];
1293
- if (w < kQ) c[i++] = w % Q;
1433
+ if (w < kQ) c[i++] = w % Q2;
1294
1434
  }
1295
1435
  return c;
1296
1436
  }
@@ -1542,15 +1682,15 @@ function genFalcon(opts) {
1542
1682
  const seed = rnd(48);
1543
1683
  (0, import_utils4.abytes)(seed, 48, "seed");
1544
1684
  try {
1545
- const [f, g, F] = secretKeyCoder.decode(sk);
1685
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1546
1686
  try {
1547
- const G = completePrivate(f, g, F);
1687
+ const G = completePrivate(f, g, F2);
1548
1688
  const b00 = floatPoly.FFT(floatPoly.convSmall(g));
1549
1689
  const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
1550
1690
  const b10 = floatPoly.FFT(floatPoly.convSmall(G));
1551
- const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F)));
1691
+ const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
1552
1692
  const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
1553
- const s2 = new Int16Array(N2);
1693
+ const s2 = new Int16Array(N3);
1554
1694
  try {
1555
1695
  while (true) {
1556
1696
  const { t0, t1 } = sampler.sample(hm);
@@ -1558,7 +1698,7 @@ function genFalcon(opts) {
1558
1698
  const t3 = floatPoly.mul(t0, b01);
1559
1699
  const t4 = floatPoly.iFFT(t2);
1560
1700
  const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
1561
- const hn = N2 >> 1;
1701
+ const hn = N3 >> 1;
1562
1702
  let sqn = 0;
1563
1703
  for (let i = 0; i < hn; i++) {
1564
1704
  sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
@@ -1572,7 +1712,7 @@ function genFalcon(opts) {
1572
1712
  }
1573
1713
  cleanCPoly(t0, t1, t2, t3, t4, t5);
1574
1714
  if (!(sqn <= L2BOUND[logn])) continue;
1575
- const s2comp = compCoder(N2).encode(s2);
1715
+ const s2comp = compCoder(N3).encode(s2);
1576
1716
  if (s2comp.length > maxLen) {
1577
1717
  cleanBytes(s2comp);
1578
1718
  continue;
@@ -1586,14 +1726,14 @@ function genFalcon(opts) {
1586
1726
  cleanBytes(G);
1587
1727
  }
1588
1728
  } finally {
1589
- cleanBytes(f, g, F);
1729
+ cleanBytes(f, g, F2);
1590
1730
  }
1591
1731
  } finally {
1592
1732
  cleanBytes(seed);
1593
1733
  }
1594
1734
  };
1595
1735
  const verifyRaw = (pk, s2comp, nonce, msg) => {
1596
- const s2 = compCoder(N2).decode(s2comp);
1736
+ const s2 = compCoder(N3).decode(s2comp);
1597
1737
  const c0 = HashToPoint(nonce, msg);
1598
1738
  const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
1599
1739
  const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
@@ -1607,54 +1747,54 @@ function genFalcon(opts) {
1607
1747
  secretKey: secretKeyCoder.bytesLen
1608
1748
  });
1609
1749
  const FALCON_SIG_OPT_KEYS = [...SIG_OPT_KEYS, "random"];
1610
- const getRnd = (opts2 = {}) => {
1611
- opts2 = validateSigOpts(opts2, FALCON_SIG_OPT_KEYS);
1612
- if (opts2.context !== void 0) throw new Error("context is not supported");
1613
- if (opts2.random !== void 0 && typeof opts2.random !== "function")
1614
- throw new TypeError('"opts.random" expected function, got type=' + typeof opts2.random);
1615
- if (opts2.random !== void 0) return opts2.random;
1616
- if (opts2.extraEntropy === void 0) return import_utils4.randomBytes;
1617
- const seed = opts2.extraEntropy === false ? new Uint8Array(48) : opts2.extraEntropy;
1750
+ const getRnd = (opts3 = {}) => {
1751
+ opts3 = validateSigOpts(opts3, FALCON_SIG_OPT_KEYS);
1752
+ if (opts3.context !== void 0) throw new Error("context is not supported");
1753
+ if (opts3.random !== void 0 && typeof opts3.random !== "function")
1754
+ throw new TypeError('"opts.random" expected function, got type=' + typeof opts3.random);
1755
+ if (opts3.random !== void 0) return opts3.random;
1756
+ if (opts3.extraEntropy === void 0) return import_utils4.randomBytes;
1757
+ const seed = opts3.extraEntropy === false ? new Uint8Array(48) : opts3.extraEntropy;
1618
1758
  (0, import_utils4.abytes)(seed, 48, "opts.extraEntropy");
1619
1759
  const drbg = (0, import_aes.rngAesCtrDrbg256)(seed);
1620
1760
  return (len = 0) => drbg.randomBytes(len);
1621
1761
  };
1622
- const checkVerOpts = (opts2 = {}) => {
1623
- const normalized = validateVerOpts(opts2);
1762
+ const checkVerOpts = (opts3 = {}) => {
1763
+ const normalized = validateVerOpts(opts3);
1624
1764
  if (normalized.context !== void 0) throw new Error("context is not supported");
1625
1765
  };
1626
1766
  const tests = Object.freeze({
1627
1767
  publicKeyCoder: Object.freeze(publicKeyCoder),
1628
1768
  privateKeyCoder: Object.freeze(secretKeyCoder),
1629
- maxS2Len: opts.maxS2Len
1769
+ maxS2Len: opts2.maxS2Len
1630
1770
  });
1631
1771
  const attachedLengths = Object.freeze({ ...keyLengths, signRand: 48 });
1632
- const lengths = opts.padded ? Object.freeze({ ...attachedLengths, signature: opts.sigLen }) : attachedLengths;
1772
+ const lengths = opts2.padded ? Object.freeze({ ...attachedLengths, signature: opts2.sigLen }) : attachedLengths;
1633
1773
  const keygen = (seed) => {
1634
1774
  const randSeed = seed === void 0;
1635
1775
  if (randSeed) seed = (0, import_utils4.randomBytes)(48);
1636
1776
  (0, import_utils4.abytes)(seed, 48, "seed");
1637
- const [f, g, F, _G, pub] = new NTRU(logn, seed).generate();
1638
- const sk = secretKeyCoder.encode([f, g, F]);
1777
+ const [f, g, F2, _G, pub] = new NTRU(logn, seed).generate();
1778
+ const sk = secretKeyCoder.encode([f, g, F2]);
1639
1779
  const pk = publicKeyCoder.encode(pub);
1640
1780
  if (randSeed) cleanBytes(seed);
1641
- cleanBytes(f, g, F, _G);
1781
+ cleanBytes(f, g, F2, _G);
1642
1782
  return { publicKey: pk, secretKey: sk };
1643
1783
  };
1644
1784
  const getPublicKey2 = (sk) => {
1645
1785
  (0, import_utils4.abytes)(sk, secretKeyCoder.bytesLen, "secretKey");
1646
- const [f, g, F] = secretKeyCoder.decode(sk);
1786
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1647
1787
  try {
1648
1788
  const h = computePublic(f, g);
1649
- cleanBytes(f, g, F);
1789
+ cleanBytes(f, g, F2);
1650
1790
  return publicKeyCoder.encode(h);
1651
1791
  } catch (e) {
1652
- cleanBytes(f, g, F);
1792
+ cleanBytes(f, g, F2);
1653
1793
  throw e;
1654
1794
  }
1655
1795
  };
1656
1796
  const sign = (msg, sk, sigOpts = {}) => {
1657
- const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts));
1797
+ const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
1658
1798
  return SignatureCoderDetached(logn).encode({ nonce, s2 });
1659
1799
  };
1660
1800
  const verify2 = (sig, msg, pk, verOpts = {}) => {
@@ -1675,7 +1815,7 @@ function genFalcon(opts) {
1675
1815
  keygen,
1676
1816
  getPublicKey: getPublicKey2,
1677
1817
  seal(msg, sk, sigOpts = {}) {
1678
- const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts));
1818
+ const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
1679
1819
  return SignatureCoder.encode({ msg, nonce, s2 });
1680
1820
  },
1681
1821
  open(sig, pk, verOpts = {}) {
@@ -1701,10 +1841,10 @@ function genFalcon(opts) {
1701
1841
  });
1702
1842
  const INTERNAL_MAX_ITERATIONS = 1e3;
1703
1843
  const checkHashPoint = (hashPoint) => {
1704
- if (!(hashPoint instanceof Uint16Array) || hashPoint.length !== N2)
1705
- throw new Error(`hashPoint: expected Uint16Array(${N2})`);
1706
- for (let i = 0; i < N2; i++)
1707
- if (hashPoint[i] >= Q) throw new Error("hashPoint: coefficient out of range");
1844
+ if (!(hashPoint instanceof Uint16Array) || hashPoint.length !== N3)
1845
+ throw new Error(`hashPoint: expected Uint16Array(${N3})`);
1846
+ for (let i = 0; i < N3; i++)
1847
+ if (hashPoint[i] >= Q2) throw new Error("hashPoint: coefficient out of range");
1708
1848
  };
1709
1849
  const internal = Object.freeze({
1710
1850
  sign(hashPoint, sk, internalOpts = {}) {
@@ -1716,15 +1856,15 @@ function genFalcon(opts) {
1716
1856
  const seed = rnd(48);
1717
1857
  (0, import_utils4.abytes)(seed, 48, "seed");
1718
1858
  try {
1719
- const [f, g, F] = secretKeyCoder.decode(sk);
1859
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1720
1860
  try {
1721
- const G = completePrivate(f, g, F);
1861
+ const G = completePrivate(f, g, F2);
1722
1862
  const b00 = floatPoly.FFT(floatPoly.convSmall(g));
1723
1863
  const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
1724
1864
  const b10 = floatPoly.FFT(floatPoly.convSmall(G));
1725
- const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F)));
1865
+ const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
1726
1866
  const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
1727
- const s2 = new Int16Array(N2);
1867
+ const s2 = new Int16Array(N3);
1728
1868
  try {
1729
1869
  for (let iteration = 0; iteration < maxIterations; iteration++) {
1730
1870
  const { t0, t1 } = sampler.sample(hm);
@@ -1732,7 +1872,7 @@ function genFalcon(opts) {
1732
1872
  const t3 = floatPoly.mul(t0, b01);
1733
1873
  const t4 = floatPoly.iFFT(t2);
1734
1874
  const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
1735
- const hn = N2 >> 1;
1875
+ const hn = N3 >> 1;
1736
1876
  let sqn = 0;
1737
1877
  for (let i = 0; i < hn; i++) {
1738
1878
  sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
@@ -1755,7 +1895,7 @@ function genFalcon(opts) {
1755
1895
  cleanBytes(G);
1756
1896
  }
1757
1897
  } finally {
1758
- cleanBytes(f, g, F);
1898
+ cleanBytes(f, g, F2);
1759
1899
  }
1760
1900
  } finally {
1761
1901
  cleanBytes(seed);
@@ -1763,8 +1903,8 @@ function genFalcon(opts) {
1763
1903
  },
1764
1904
  verify(s2, hashPoint, pk) {
1765
1905
  checkHashPoint(hashPoint);
1766
- if (!(s2 instanceof Int16Array) || s2.length !== N2)
1767
- throw new Error(`s2: expected Int16Array(${N2})`);
1906
+ if (!(s2 instanceof Int16Array) || s2.length !== N3)
1907
+ throw new Error(`s2: expected Int16Array(${N3})`);
1768
1908
  (0, import_utils4.abytes)(pk, publicKeyCoder.bytesLen, "publicKey");
1769
1909
  const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
1770
1910
  const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
@@ -1798,6 +1938,380 @@ var falcon512opts = {
1798
1938
  };
1799
1939
  var falcon512 = /* @__PURE__ */ (() => genFalcon({ ...falcon512opts, maxS2Len: 711 }))();
1800
1940
 
1941
+ // src/falcon/engine/noble/ml-kem.ts
1942
+ var import_sha33 = require("@noble/hashes/sha3.js");
1943
+ var import_utils6 = require("@noble/hashes/utils.js");
1944
+ var N2 = 256;
1945
+ var Q3 = 3329;
1946
+ var F = 3303;
1947
+ var ROOT_OF_UNITY = 17;
1948
+ var crystals = /* @__PURE__ */ genCrystals({
1949
+ N: N2,
1950
+ Q: Q3,
1951
+ F,
1952
+ ROOT_OF_UNITY,
1953
+ newPoly: (n) => new Uint16Array(n),
1954
+ brvBits: 7,
1955
+ isKyber: true
1956
+ });
1957
+ var PARAMS = /* @__PURE__ */ (() => Object.freeze({
1958
+ 512: Object.freeze({ N: N2, Q: Q3, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
1959
+ 768: Object.freeze({ N: N2, Q: Q3, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
1960
+ 1024: Object.freeze({ N: N2, Q: Q3, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
1961
+ }))();
1962
+ var compress = (d) => {
1963
+ if (d >= 12) return { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i };
1964
+ const a = 2 ** (d - 1);
1965
+ return {
1966
+ // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
1967
+ encode: (i) => ((i << d) + Q3 / 2) / Q3,
1968
+ // const decompress = (i: number) => round((Q / 2 ** d) * i);
1969
+ decode: (i) => i * Q3 + a >>> d
1970
+ };
1971
+ };
1972
+ var byteCoder = (d) => crystals.bitsCoder(
1973
+ d,
1974
+ d === 12 ? { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i } : { encode: (i) => i, decode: (i) => i }
1975
+ );
1976
+ var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d));
1977
+ function polyAdd(a_, b_) {
1978
+ const a = a_;
1979
+ const b = b_;
1980
+ for (let i = 0; i < N2; i++) {
1981
+ const r = a[i] + b[i];
1982
+ a[i] = r >= Q3 ? r - Q3 : r;
1983
+ }
1984
+ }
1985
+ function polySub(a_, b_) {
1986
+ const a = a_;
1987
+ const b = b_;
1988
+ for (let i = 0; i < N2; i++) {
1989
+ const r = a[i] - b[i];
1990
+ a[i] = r < 0 ? r + Q3 : r;
1991
+ }
1992
+ }
1993
+ function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
1994
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
1995
+ const c1 = crystals.mod(a0 * b1 + a1 * b0);
1996
+ return { c0, c1 };
1997
+ }
1998
+ function MultiplyNTTs(f_, g_) {
1999
+ const f = f_;
2000
+ const g = g_;
2001
+ for (let i = 0; i < N2 / 2; i++) {
2002
+ let z = crystals.nttZetas[64 + (i >> 1)];
2003
+ if (i & 1) z = -z;
2004
+ const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
2005
+ f[2 * i + 0] = c0;
2006
+ f[2 * i + 1] = c1;
2007
+ }
2008
+ return f;
2009
+ }
2010
+ function SampleNTT(xof_) {
2011
+ const xof = xof_;
2012
+ const r = new Uint16Array(N2);
2013
+ for (let j = 0; j < N2; ) {
2014
+ const b = xof();
2015
+ if (b.length % 3) throw new Error("SampleNTT: unaligned block");
2016
+ for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) {
2017
+ const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
2018
+ const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
2019
+ if (d1 < Q3) r[j++] = d1;
2020
+ if (j < N2 && d2 < Q3) r[j++] = d2;
2021
+ }
2022
+ }
2023
+ return r;
2024
+ }
2025
+ var sampleCBDBytes = (buf, eta) => {
2026
+ const r = new Uint16Array(N2);
2027
+ const b32 = (0, import_utils6.u32)(buf);
2028
+ (0, import_utils6.swap32IfBE)(b32);
2029
+ let len = 0;
2030
+ for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
2031
+ let b = b32[i];
2032
+ for (let j = 0; j < 32; j++) {
2033
+ bb += b & 1;
2034
+ b >>= 1;
2035
+ len += 1;
2036
+ if (len === eta) {
2037
+ t0 = bb;
2038
+ bb = 0;
2039
+ } else if (len === 2 * eta) {
2040
+ r[p++] = crystals.mod(t0 - bb);
2041
+ bb = 0;
2042
+ len = 0;
2043
+ }
2044
+ }
2045
+ }
2046
+ (0, import_utils6.swap32IfBE)(b32);
2047
+ if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);
2048
+ return r;
2049
+ };
2050
+ function sampleCBD(PRF_, seed, nonce, eta) {
2051
+ const PRF = PRF_;
2052
+ return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
2053
+ }
2054
+ var genKPKE = (opts_) => {
2055
+ const opts2 = opts_;
2056
+ const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
2057
+ const poly1 = polyCoder(1);
2058
+ const polyV = polyCoder(dv);
2059
+ const polyU = polyCoder(du);
2060
+ const publicCoder = splitCoder("publicKey", vecCoder(polyCoder(12), K), 32);
2061
+ const secretCoder = vecCoder(polyCoder(12), K);
2062
+ const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2063
+ const seedCoder = splitCoder("seed", 32, 32);
2064
+ const encryptCore = (tHat, getA, msg, seed) => {
2065
+ const rHat = [];
2066
+ for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2067
+ const tmp2 = new Uint16Array(N2);
2068
+ const u = [];
2069
+ for (let i = 0; i < K; i++) {
2070
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2071
+ const tmp = new Uint16Array(N2);
2072
+ for (let j = 0; j < K; j++) {
2073
+ const aij = getA(i, j);
2074
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2075
+ }
2076
+ polyAdd(e1, crystals.NTT.decode(tmp));
2077
+ u.push(e1);
2078
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2079
+ cleanBytes(tmp);
2080
+ }
2081
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2082
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2083
+ const v = poly1.decode(msg);
2084
+ polyAdd(v, e2);
2085
+ cleanBytes(tHat, rHat, tmp2, e2);
2086
+ return cipherCoder.encode([u, v]);
2087
+ };
2088
+ return {
2089
+ secretCoder,
2090
+ lengths: {
2091
+ secretKey: secretCoder.bytesLen,
2092
+ publicKey: publicCoder.bytesLen,
2093
+ cipherText: cipherCoder.bytesLen
2094
+ },
2095
+ keygen: (seed) => {
2096
+ abytesDoc(seed, 32, "seed");
2097
+ const seedDst = new Uint8Array(33);
2098
+ seedDst.set(seed);
2099
+ seedDst[32] = K;
2100
+ const seedHash = HASH512(seedDst);
2101
+ const [rho, sigma] = seedCoder.decode(seedHash);
2102
+ const sHat = [];
2103
+ const tHat = [];
2104
+ for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
2105
+ const x = XOF(rho);
2106
+ for (let i = 0; i < K; i++) {
2107
+ const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
2108
+ for (let j = 0; j < K; j++) {
2109
+ const aji = SampleNTT(x.get(j, i));
2110
+ polyAdd(e, MultiplyNTTs(aji, sHat[j]));
2111
+ }
2112
+ tHat.push(e);
2113
+ }
2114
+ x.clean();
2115
+ const res = {
2116
+ publicKey: publicCoder.encode([tHat, rho]),
2117
+ secretKey: secretCoder.encode(sHat)
2118
+ };
2119
+ cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
2120
+ return res;
2121
+ },
2122
+ encrypt: (publicKey, msg, seed) => {
2123
+ const [tHat, rho] = publicCoder.decode(publicKey);
2124
+ const x = XOF(rho);
2125
+ const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
2126
+ x.clean();
2127
+ return res;
2128
+ },
2129
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
2130
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
2131
+ // call because encryptCore mutates its inputs in place.
2132
+ prepare: (publicKey) => {
2133
+ const [tHat, rho] = publicCoder.decode(publicKey);
2134
+ const x = XOF(rho);
2135
+ const A = [];
2136
+ for (let i = 0; i < K; i++)
2137
+ for (let j = 0; j < K; j++) A.push(SampleNTT(x.get(i, j)));
2138
+ x.clean();
2139
+ return {
2140
+ encrypt: (msg, seed) => encryptCore(
2141
+ tHat.map((p) => p.slice()),
2142
+ (i, j) => A[i * K + j].slice(),
2143
+ msg,
2144
+ seed
2145
+ ),
2146
+ clean: () => cleanBytes(tHat, A)
2147
+ };
2148
+ },
2149
+ decrypt: (cipherText, privateKey) => {
2150
+ const [u, v] = cipherCoder.decode(cipherText);
2151
+ const sk = secretCoder.decode(privateKey);
2152
+ const tmp = new Uint16Array(N2);
2153
+ for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2154
+ polySub(v, crystals.NTT.decode(tmp));
2155
+ const res = poly1.encode(v);
2156
+ cleanBytes(tmp, sk, u, v);
2157
+ return res;
2158
+ }
2159
+ };
2160
+ };
2161
+ function createKyber(opts2) {
2162
+ const rawOpts = opts2;
2163
+ const KPKE = genKPKE(rawOpts);
2164
+ const { HASH256, HASH512, KDF } = rawOpts;
2165
+ const { secretCoder: KPKESecretCoder, lengths } = KPKE;
2166
+ const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2167
+ const msgLen = 32;
2168
+ const seedLen = 64;
2169
+ const validateModulus = (publicKey, fn) => {
2170
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
2171
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));
2172
+ const ok = equalBytes(ek, eke);
2173
+ cleanBytes(ek);
2174
+ if (!ok) throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
2175
+ };
2176
+ const kemLengths = Object.freeze({
2177
+ ...lengths,
2178
+ seed: 64,
2179
+ msg: msgLen,
2180
+ msgRand: msgLen,
2181
+ secretKey: secretCoder.bytesLen
2182
+ });
2183
+ return Object.freeze({
2184
+ info: Object.freeze({ type: "ml-kem" }),
2185
+ lengths: kemLengths,
2186
+ keygen: (seed) => {
2187
+ const ownSeed = seed === void 0;
2188
+ const s = ownSeed ? randomBytes(seedLen) : seed;
2189
+ let sk;
2190
+ let publicKeyHash;
2191
+ try {
2192
+ abytesDoc(s, seedLen, "seed");
2193
+ const keys = KPKE.keygen(s.subarray(0, 32));
2194
+ const publicKey = keys.publicKey;
2195
+ sk = keys.secretKey;
2196
+ publicKeyHash = HASH256(publicKey);
2197
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
2198
+ return {
2199
+ publicKey,
2200
+ secretKey
2201
+ };
2202
+ } finally {
2203
+ if (sk !== void 0) cleanBytes(sk);
2204
+ if (publicKeyHash !== void 0) cleanBytes(publicKeyHash);
2205
+ if (ownSeed) cleanBytes(s);
2206
+ }
2207
+ },
2208
+ getPublicKey: (secretKey) => {
2209
+ const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2210
+ return Uint8Array.from(publicKey);
2211
+ },
2212
+ encapsulate: (publicKey, msg) => {
2213
+ const ownMsg = msg === void 0;
2214
+ const m = ownMsg ? randomBytes(msgLen) : msg;
2215
+ let kr;
2216
+ try {
2217
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2218
+ abytesDoc(m, msgLen, "message");
2219
+ validateModulus(publicKey, "encapsulate");
2220
+ kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
2221
+ const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
2222
+ return {
2223
+ cipherText,
2224
+ sharedSecret: kr.subarray(0, 32)
2225
+ };
2226
+ } finally {
2227
+ if (kr !== void 0) cleanBytes(kr.subarray(32));
2228
+ if (ownMsg) cleanBytes(m);
2229
+ }
2230
+ },
2231
+ decapsulate: (cipherText, secretKey) => {
2232
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2233
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2234
+ const k768 = secretCoder.bytesLen - 96;
2235
+ const start = k768 + 32;
2236
+ const test = HASH256(secretKey.subarray(k768 / 2, start));
2237
+ if (!equalBytes(test, secretKey.subarray(start, start + 32)))
2238
+ throw new Error("invalid secretKey: hash check failed");
2239
+ const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2240
+ const msg = KPKE.decrypt(cipherText, sk);
2241
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2242
+ const Khat = kr.subarray(0, 32);
2243
+ const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2244
+ const isValid = equalBytes(cipherText, cipherText2);
2245
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2246
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2247
+ return isValid ? Khat : Kbar;
2248
+ },
2249
+ /**
2250
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
2251
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
2252
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
2253
+ */
2254
+ prepare: (publicKey) => {
2255
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2256
+ validateModulus(publicKey, "prepare");
2257
+ const ek = copyBytes(publicKey);
2258
+ const publicKeyHash = HASH256(ek);
2259
+ const cached = KPKE.prepare(ek);
2260
+ return Object.freeze({
2261
+ publicKey: ek,
2262
+ encapsulate: (msg) => {
2263
+ const ownMsg = msg === void 0;
2264
+ const m = ownMsg ? randomBytes(msgLen) : msg;
2265
+ let kr;
2266
+ try {
2267
+ abytesDoc(m, msgLen, "message");
2268
+ kr = HASH512.create().update(m).update(publicKeyHash).digest();
2269
+ const cipherText = cached.encrypt(m, kr.subarray(32, 64));
2270
+ return {
2271
+ cipherText,
2272
+ sharedSecret: kr.subarray(0, 32)
2273
+ };
2274
+ } finally {
2275
+ if (kr !== void 0) cleanBytes(kr.subarray(32));
2276
+ if (ownMsg) cleanBytes(m);
2277
+ }
2278
+ },
2279
+ decapsulate: (cipherText, secretKey) => {
2280
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2281
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2282
+ const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
2283
+ if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
2284
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
2285
+ const msg = KPKE.decrypt(cipherText, sk);
2286
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2287
+ const Khat = kr.subarray(0, 32);
2288
+ const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
2289
+ const isValid = equalBytes(cipherText, cipherText2);
2290
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2291
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2292
+ return isValid ? Khat : Kbar;
2293
+ },
2294
+ clean: cached.clean
2295
+ });
2296
+ }
2297
+ });
2298
+ }
2299
+ function shakePRF(dkLen, key, nonce) {
2300
+ return import_sha33.shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
2301
+ }
2302
+ var opts = /* @__PURE__ */ (() => ({
2303
+ HASH256: import_sha33.sha3_256,
2304
+ HASH512: import_sha33.sha3_512,
2305
+ KDF: import_sha33.shake256,
2306
+ XOF: XOF128,
2307
+ PRF: shakePRF
2308
+ }))();
2309
+ var mk = (params) => createKyber({
2310
+ ...opts,
2311
+ ...params
2312
+ });
2313
+ var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
2314
+
1801
2315
  // src/falcon/engine/engine.ts
1802
2316
  var nobleEngine = Object.freeze({
1803
2317
  keygen: (seed) => falcon512.keygen(seed),
@@ -1806,16 +2320,6 @@ var nobleEngine = Object.freeze({
1806
2320
  verifyHashPoint: (s2, hashPoint, publicKey) => falcon512.internal.verify(s2, hashPoint, publicKey)
1807
2321
  });
1808
2322
 
1809
- // src/falcon/s2morrow/constants.ts
1810
- var Q2 = 12289;
1811
- var QB = 12289n;
1812
- var N = 512;
1813
- var SIG_BOUND_512 = 34034726;
1814
- var PACKED_SLOTS = 29;
1815
- var VALUES_PER_HALF = 9;
1816
- var SALT_FELTS = 2;
1817
- var SIGNATURE_FELTS = 61;
1818
-
1819
2323
  // src/falcon/s2morrow/nttRoots.ts
1820
2324
  var NTT_ROOTS_ALL = Object.freeze([
1821
2325
  1479,
@@ -2845,20 +3349,20 @@ var NTT_ROOTS_ALL = Object.freeze([
2845
3349
  // src/falcon/s2morrow/ntt.ts
2846
3350
  var I2 = 6145;
2847
3351
  var SQR1 = 1479;
2848
- var modQ = (a) => (a % Q2 + Q2) % Q2;
3352
+ var modQ = (a) => (a % Q + Q) % Q;
2849
3353
  function powMod(base, exponent) {
2850
3354
  let result = 1;
2851
3355
  let b = modQ(base);
2852
3356
  for (let e = exponent; e > 0; e >>= 1) {
2853
- if (e & 1) result = result * b % Q2;
2854
- b = b * b % Q2;
3357
+ if (e & 1) result = result * b % Q;
3358
+ b = b * b % Q;
2855
3359
  }
2856
3360
  return result;
2857
3361
  }
2858
3362
  function invMod(x) {
2859
3363
  const r = modQ(x);
2860
3364
  if (r === 0) throw new Error("Falcon512: 0 has no inverse mod q");
2861
- return powMod(r, Q2 - 2);
3365
+ return powMod(r, Q - 2);
2862
3366
  }
2863
3367
  var nttRoots = (n) => NTT_ROOTS_ALL.slice(n - 2, 2 * n - 2);
2864
3368
  function checkSize(n) {
@@ -2869,7 +3373,7 @@ function checkSize(n) {
2869
3373
  function nttRec(f) {
2870
3374
  const n = f.length;
2871
3375
  if (n === 2) {
2872
- const t = SQR1 * f[1] % Q2;
3376
+ const t = SQR1 * f[1] % Q;
2873
3377
  return [modQ(f[0] + t), modQ(f[0] - t)];
2874
3378
  }
2875
3379
  const half = n / 2;
@@ -2884,7 +3388,7 @@ function nttRec(f) {
2884
3388
  const w = nttRoots(n);
2885
3389
  const out = new Array(n);
2886
3390
  for (let i = 0; i < half; i++) {
2887
- const wb = w[2 * i] * b[i] % Q2;
3391
+ const wb = w[2 * i] * b[i] % Q;
2888
3392
  out[2 * i] = modQ(a[i] + wb);
2889
3393
  out[2 * i + 1] = modQ(a[i] - wb);
2890
3394
  }
@@ -2895,7 +3399,7 @@ function inttRec(fNtt) {
2895
3399
  if (n === 2) {
2896
3400
  const s = modQ(fNtt[0] + fNtt[1]);
2897
3401
  const d = modQ(fNtt[0] - fNtt[1]);
2898
- return [I2 * s % Q2, I2 * invMod(SQR1) % Q2 * d % Q2];
3402
+ return [I2 * s % Q, I2 * invMod(SQR1) % Q * d % Q];
2899
3403
  }
2900
3404
  const half = n / 2;
2901
3405
  const w = nttRoots(n);
@@ -2904,8 +3408,8 @@ function inttRec(fNtt) {
2904
3408
  for (let i = 0; i < half; i++) {
2905
3409
  const s = modQ(fNtt[2 * i] + fNtt[2 * i + 1]);
2906
3410
  const d = modQ(fNtt[2 * i] - fNtt[2 * i + 1]);
2907
- f0[i] = I2 * s % Q2;
2908
- f1[i] = I2 * d % Q2 * invMod(w[2 * i]) % Q2;
3411
+ f0[i] = I2 * s % Q;
3412
+ f1[i] = I2 * d % Q * invMod(w[2 * i]) % Q;
2909
3413
  }
2910
3414
  const a = inttRec(f0);
2911
3415
  const b = inttRec(f1);
@@ -2928,14 +3432,14 @@ function mulZq(a, b) {
2928
3432
  if (a.length !== b.length) throw new Error("Falcon512: polynomial sizes differ");
2929
3433
  const an = ntt(a);
2930
3434
  const bn = ntt(b);
2931
- return intt(an.map((v, i) => v * bn[i] % Q2));
3435
+ return intt(an.map((v, i) => v * bn[i] % Q));
2932
3436
  }
2933
3437
  function divZq(a, b) {
2934
3438
  if (a.length !== b.length) throw new Error("Falcon512: polynomial sizes differ");
2935
3439
  const an = ntt(a);
2936
3440
  const bn = ntt(b);
2937
3441
  if (bn.some((v) => v === 0)) throw new Error("Falcon512: polynomial is not invertible mod q");
2938
- return intt(an.map((v, i) => v * invMod(bn[i]) % Q2));
3442
+ return intt(an.map((v, i) => v * invMod(bn[i]) % Q));
2939
3443
  }
2940
3444
  function mulNegacyclicInt(a, b) {
2941
3445
  const n = a.length;
@@ -2955,22 +3459,7 @@ function mulNegacyclicInt(a, b) {
2955
3459
  }
2956
3460
 
2957
3461
  // src/falcon/s2morrow/packing.ts
2958
- var starknet2 = __toESM(require("starknet"));
2959
-
2960
- // src/falcon/s2morrow/felt.ts
2961
- var starknet = __toESM(require("starknet"));
2962
- function assertFelt(x, label) {
2963
- if (typeof x !== "bigint") throw new Error(`Falcon512: ${label} is not a felt252`);
2964
- starknet.CairoFelt252.assertRange(x);
2965
- }
2966
- var FELT_STRING = /^(0[xX][0-9a-fA-F]{1,64}|[0-9]{1,76})$/;
2967
- function parseFelt(value, label) {
2968
- const accepted = typeof value === "bigint" && value >= 0n || typeof value === "number" && Number.isSafeInteger(value) && value >= 0 || typeof value === "string" && FELT_STRING.test(value);
2969
- if (!accepted) throw new Error(`Falcon512: ${label} is not a felt252`);
2970
- return new starknet.CairoFelt252(value).toBigInt();
2971
- }
2972
-
2973
- // src/falcon/s2morrow/packing.ts
3462
+ var starknet3 = __toESM(require("starknet"));
2974
3463
  var horner = (values, start, end) => {
2975
3464
  let acc = 0n;
2976
3465
  for (let i = end - 1; i >= start; i--) acc = acc * QB + BigInt(values[i]);
@@ -2980,7 +3469,7 @@ function packPoly(poly) {
2980
3469
  if (poly.length !== N) throw new Error(`Falcon512: polynomial must have ${N} coefficients`);
2981
3470
  for (let i = 0; i < N; i++) {
2982
3471
  const v = poly[i];
2983
- if (!Number.isInteger(v) || v < 0 || v >= Q2) {
3472
+ if (!Number.isInteger(v) || v < 0 || v >= Q) {
2984
3473
  throw new Error("Falcon512: polynomial coefficient out of range");
2985
3474
  }
2986
3475
  }
@@ -3000,7 +3489,7 @@ function unpackPoly(felts) {
3000
3489
  let idx = 0;
3001
3490
  for (const felt of felts) {
3002
3491
  assertFelt(felt, "packed polynomial slot");
3003
- for (const half of [felt & starknet2.UINT_128_MAX, felt >> 128n]) {
3492
+ for (const half of [felt & starknet3.UINT_128_MAX, felt >> 128n]) {
3004
3493
  const count = Math.min(VALUES_PER_HALF, N - idx);
3005
3494
  if (half >= QB ** BigInt(count)) {
3006
3495
  throw new Error("Falcon512: non-canonical packed polynomial");
@@ -3015,7 +3504,227 @@ function unpackPoly(felts) {
3015
3504
  return out;
3016
3505
  }
3017
3506
 
3507
+ // src/falcon/s2morrow/signature.ts
3508
+ var import_utils8 = require("@noble/hashes/utils.js");
3509
+ var starknet5 = __toESM(require("starknet"));
3510
+
3511
+ // src/falcon/s2morrow/hashToPoint.ts
3512
+ var import_starknet = require("@scure/starknet");
3513
+ var starknet4 = __toESM(require("starknet"));
3514
+ function hashToPoint(message, salt) {
3515
+ message.forEach((m) => assertFelt(m, "message element"));
3516
+ salt.forEach((s) => assertFelt(s, "salt element"));
3517
+ const out = new Uint16Array(N);
3518
+ let idx = 0;
3519
+ const extract6 = (value) => {
3520
+ let v = value;
3521
+ for (let i = 0; i < 6 && idx < N; i++) {
3522
+ out[idx++] = Number(v % QB);
3523
+ v /= QB;
3524
+ }
3525
+ };
3526
+ const extract12 = (felt) => {
3527
+ extract6(felt & starknet4.UINT_128_MAX);
3528
+ extract6(felt >> 128n);
3529
+ };
3530
+ let state = [(0, import_starknet.poseidonHashMany)([...message, ...salt]), 0n, 0n];
3531
+ for (let round = 0; round < 21; round++) {
3532
+ state = (0, import_starknet.poseidonSmall)(state);
3533
+ extract12(state[0]);
3534
+ extract12(state[1]);
3535
+ }
3536
+ state = (0, import_starknet.poseidonSmall)(state);
3537
+ extract12(state[0]);
3538
+ return out;
3539
+ }
3540
+
3541
+ // src/falcon/s2morrow/signature.ts
3542
+ var defaultDeps = { engine: nobleEngine, randomBytes: import_utils8.randomBytes };
3543
+ function computeMulHint(s1, pkNtt) {
3544
+ const s1Ntt = ntt(s1);
3545
+ return intt(s1Ntt.map((v, i) => v * pkNtt[i] % Q));
3546
+ }
3547
+ var centeredSquare = (x) => {
3548
+ const c = x <= (Q - 1) / 2 ? x : Q - x;
3549
+ return c * c;
3550
+ };
3551
+ function checkSignatureEquation(hashPoint, s1, mulHint, pkNtt) {
3552
+ if (hashPoint.length !== N || s1.length !== N || mulHint.length !== N || pkNtt.length !== N) {
3553
+ return false;
3554
+ }
3555
+ const s1Ntt = ntt(s1);
3556
+ const hintNtt = ntt(mulHint);
3557
+ for (let i = 0; i < N; i += 1) {
3558
+ if (s1Ntt[i] * pkNtt[i] % Q !== hintNtt[i]) return false;
3559
+ }
3560
+ let norm = 0;
3561
+ for (let i = 0; i < N; i += 1) {
3562
+ norm += centeredSquare(modQ(hashPoint[i] - mulHint[i])) + centeredSquare(s1[i]);
3563
+ }
3564
+ return norm <= SIG_BOUND_512;
3565
+ }
3566
+ function formatSignature(sig) {
3567
+ const felts = [
3568
+ ...packPoly(sig.s1),
3569
+ BigInt(sig.salt.length),
3570
+ ...sig.salt,
3571
+ ...packPoly(sig.mulHint)
3572
+ ];
3573
+ return felts.map((x) => starknet5.num.toHex(x));
3574
+ }
3575
+ function parseSignature(signature) {
3576
+ if (!Array.isArray(signature) || signature.length !== SIGNATURE_FELTS) {
3577
+ throw new Error(`Falcon512: signature must have ${SIGNATURE_FELTS} felts`);
3578
+ }
3579
+ const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3580
+ if (felts[PACKED_SLOTS] !== BigInt(SALT_FELTS)) {
3581
+ throw new Error("Falcon512: unexpected salt length");
3582
+ }
3583
+ const saltStart = PACKED_SLOTS + 1;
3584
+ return {
3585
+ s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3586
+ salt: felts.slice(saltStart, saltStart + SALT_FELTS),
3587
+ mulHint: unpackPoly(felts.slice(saltStart + SALT_FELTS))
3588
+ };
3589
+ }
3590
+ var randomSaltFelt = (randomBytes4) => BigInt(`0x${starknet5.encode.buf2hex(randomBytes4(31))}`);
3591
+ function signHash(msgHash, secretKey, pkNtt, deps = defaultDeps) {
3592
+ assertFelt(msgHash, "message hash");
3593
+ const salt = [randomSaltFelt(deps.randomBytes), randomSaltFelt(deps.randomBytes)];
3594
+ const hashPoint = hashToPoint([msgHash], salt);
3595
+ const s2 = deps.engine.signHashPoint(hashPoint, secretKey);
3596
+ const s1 = Uint16Array.from(s2, modQ);
3597
+ const mulHint = Uint16Array.from(computeMulHint(s1, pkNtt));
3598
+ const signature = formatSignature({ s1, salt, mulHint });
3599
+ const decoded = parseSignature(signature);
3600
+ if (!checkSignatureEquation(hashPoint, decoded.s1, decoded.mulHint, pkNtt)) {
3601
+ throw new Error("Falcon512: self-verification failed, signature discarded");
3602
+ }
3603
+ return signature;
3604
+ }
3605
+ function verifyHash(msgHash, signature, pkNtt) {
3606
+ let decoded;
3607
+ try {
3608
+ assertFelt(msgHash, "message hash");
3609
+ decoded = parseSignature(signature);
3610
+ } catch {
3611
+ return false;
3612
+ }
3613
+ return checkSignatureEquation(
3614
+ hashToPoint([msgHash], decoded.salt),
3615
+ decoded.s1,
3616
+ decoded.mulHint,
3617
+ pkNtt
3618
+ );
3619
+ }
3620
+
3621
+ // src/falcon/oz/hashToPoint.ts
3622
+ var import_sha34 = require("@noble/hashes/sha3.js");
3623
+ var SALT_BYTES = 20;
3624
+ var SALT_LIMIT = 1n << BigInt(8 * SALT_BYTES);
3625
+ var KQ = 5 * Q;
3626
+ var writeLittleEndian = (x, out, offset, length) => {
3627
+ let v = x;
3628
+ for (let i = 0; i < length; i += 1) {
3629
+ out[offset + i] = Number(v & 0xffn);
3630
+ v >>= 8n;
3631
+ }
3632
+ };
3633
+ function saltFeltsToBytes(saltA, saltB) {
3634
+ [saltA, saltB].forEach((salt) => {
3635
+ if (typeof salt !== "bigint" || salt < 0n || salt >= SALT_LIMIT) {
3636
+ throw new Error("Falcon512: salt felt must be non-negative and below 2^160");
3637
+ }
3638
+ });
3639
+ const out = new Uint8Array(2 * SALT_BYTES);
3640
+ writeLittleEndian(saltA, out, 0, SALT_BYTES);
3641
+ writeLittleEndian(saltB, out, SALT_BYTES, SALT_BYTES);
3642
+ return out;
3643
+ }
3644
+ function hashToPointShake(msgHash, saltA, saltB) {
3645
+ assertFelt(msgHash, "message hash");
3646
+ const message = new Uint8Array(32);
3647
+ writeLittleEndian(msgHash, message, 0, 32);
3648
+ const xof = import_sha34.shake256.create().update(saltFeltsToBytes(saltA, saltB)).update(message);
3649
+ const out = new Uint16Array(N);
3650
+ for (let i = 0; i < N; ) {
3651
+ const [high, low] = xof.xof(2);
3652
+ const word = high << 8 | low;
3653
+ if (word < KQ) {
3654
+ out[i] = word % Q;
3655
+ i += 1;
3656
+ }
3657
+ }
3658
+ return out;
3659
+ }
3660
+
3661
+ // src/falcon/oz/signature.ts
3662
+ var OZ_SIGNATURE_FELTS = Object.freeze({
3663
+ hint: 2 * PACKED_SLOTS + 2,
3664
+ direct: PACKED_SLOTS + 2
3665
+ });
3666
+ var defaultDeps2 = { engine: nobleEngine, randomBytes: import_utils9.randomBytes };
3667
+ var readLittleEndian = (bytes) => bytes.reduceRight((acc, byte) => acc * 256n + BigInt(byte), 0n);
3668
+ function formatOzSignature(sig, variant) {
3669
+ const felts = [...packPoly(sig.s1), sig.saltA, sig.saltB];
3670
+ if (variant === "hint") {
3671
+ if (!sig.mulHint) throw new Error("Falcon512: the hint layout needs the hint polynomial");
3672
+ felts.push(...packPoly(sig.mulHint));
3673
+ }
3674
+ return felts.map((x) => starknet6.num.toHex(x));
3675
+ }
3676
+ function parseOzSignature(signature, variant) {
3677
+ const length = OZ_SIGNATURE_FELTS[variant];
3678
+ if (!Array.isArray(signature) || signature.length !== length) {
3679
+ throw new Error(`Falcon512: signature must have ${length} felts`);
3680
+ }
3681
+ const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3682
+ const saltA = felts[PACKED_SLOTS];
3683
+ const saltB = felts[PACKED_SLOTS + 1];
3684
+ saltFeltsToBytes(saltA, saltB);
3685
+ return {
3686
+ s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3687
+ saltA,
3688
+ saltB,
3689
+ mulHint: variant === "hint" ? unpackPoly(felts.slice(PACKED_SLOTS + 2)) : void 0
3690
+ };
3691
+ }
3692
+ function signHashOz(msgHash, secretKey, pkNtt, variant, deps = defaultDeps2) {
3693
+ assertFelt(msgHash, "message hash");
3694
+ const salt = deps.randomBytes(2 * SALT_BYTES);
3695
+ const saltA = readLittleEndian(salt.subarray(0, SALT_BYTES));
3696
+ const saltB = readLittleEndian(salt.subarray(SALT_BYTES));
3697
+ const hashPoint = hashToPointShake(msgHash, saltA, saltB);
3698
+ const s1 = Uint16Array.from(deps.engine.signHashPoint(hashPoint, secretKey), modQ);
3699
+ const mulHint = variant === "hint" ? Uint16Array.from(computeMulHint(s1, pkNtt)) : void 0;
3700
+ const signature = formatOzSignature({ s1, saltA, saltB, mulHint }, variant);
3701
+ const decoded = parseOzSignature(signature, variant);
3702
+ const decodedHint = decoded.mulHint ?? computeMulHint(decoded.s1, pkNtt);
3703
+ if (!checkSignatureEquation(hashPoint, decoded.s1, decodedHint, pkNtt)) {
3704
+ throw new Error("Falcon512: self-verification failed, signature discarded");
3705
+ }
3706
+ return signature;
3707
+ }
3708
+ function verifyHashOz(msgHash, signature, pkNtt, variant) {
3709
+ let decoded;
3710
+ try {
3711
+ assertFelt(msgHash, "message hash");
3712
+ decoded = parseOzSignature(signature, variant);
3713
+ } catch {
3714
+ return false;
3715
+ }
3716
+ const mulHint = decoded.mulHint ?? computeMulHint(decoded.s1, pkNtt);
3717
+ return checkSignatureEquation(
3718
+ hashToPointShake(msgHash, decoded.saltA, decoded.saltB),
3719
+ decoded.s1,
3720
+ mulHint,
3721
+ pkNtt
3722
+ );
3723
+ }
3724
+
3018
3725
  // src/falcon/s2morrow/keys.ts
3726
+ var import_utils10 = require("@noble/hashes/utils.js");
3727
+ var starknet7 = __toESM(require("starknet"));
3019
3728
  var SECRET_KEY_LENGTH = 1281;
3020
3729
  var PUBLIC_KEY_LENGTH = 897;
3021
3730
  var SEED_LENGTH = 48;
@@ -3029,7 +3738,7 @@ var FG_MAX = 31;
3029
3738
  var CAPITAL_FG_MAX = 127;
3030
3739
  var FG_BYTES = N * FG_BITS / 8;
3031
3740
  function toBytes(input, expectedLength, label) {
3032
- if ((0, import_utils6.isBytes)(input)) {
3741
+ if ((0, import_utils10.isBytes)(input)) {
3033
3742
  if (input.length !== expectedLength) {
3034
3743
  throw new Error(`Falcon512: ${label} must be ${expectedLength} bytes, got ${input.length}`);
3035
3744
  }
@@ -3038,7 +3747,7 @@ function toBytes(input, expectedLength, label) {
3038
3747
  if (typeof input !== "string") {
3039
3748
  throw new Error(`Falcon512: ${label} must be a Uint8Array or a hex string`);
3040
3749
  }
3041
- const hex = starknet3.encode.removeHexPrefix(input);
3750
+ const hex = starknet7.encode.removeHexPrefix(input);
3042
3751
  if (!/^[0-9a-fA-F]*$/.test(hex)) {
3043
3752
  throw new Error(`Falcon512: ${label} is not a valid hex string`);
3044
3753
  }
@@ -3047,12 +3756,12 @@ function toBytes(input, expectedLength, label) {
3047
3756
  `Falcon512: ${label} must have ${2 * expectedLength} hex digits, got ${hex.length}`
3048
3757
  );
3049
3758
  }
3050
- return starknet3.num.hexToBytes(starknet3.encode.addHexPrefix(hex));
3759
+ return starknet7.num.hexToBytes(starknet7.encode.addHexPrefix(hex));
3051
3760
  }
3052
3761
  var wipe = (...arrays) => {
3053
3762
  arrays.forEach((a) => a.fill(0));
3054
3763
  };
3055
- var center = (x) => x > Q2 >> 1 ? x - Q2 : x;
3764
+ var center = (x) => x > Q >> 1 ? x - Q : x;
3056
3765
  var toSigned = (raw, bits) => raw << 32 - bits >> 32 - bits;
3057
3766
  function encodeBitsMSB(values, bits) {
3058
3767
  const out = new Uint8Array(values.length * bits / 8);
@@ -3118,7 +3827,7 @@ function decode14LSB(bytes) {
3118
3827
  const v = acc & 16383;
3119
3828
  acc >>>= 14;
3120
3829
  accBits -= 14;
3121
- if (v >= Q2) {
3830
+ if (v >= Q) {
3122
3831
  throw new Error("Falcon512: invalid falcon-rs secret key (coefficient out of range)");
3123
3832
  }
3124
3833
  out.push(v);
@@ -3136,8 +3845,8 @@ function checkRange(poly, max, label) {
3136
3845
  }
3137
3846
  }
3138
3847
  }
3139
- function completeG(f, g, F) {
3140
- const gF = mulZq(g, F);
3848
+ function completeG(f, g, F2) {
3849
+ const gF = mulZq(g, F2);
3141
3850
  let quotient = [];
3142
3851
  let G = [];
3143
3852
  try {
@@ -3149,12 +3858,12 @@ function completeG(f, g, F) {
3149
3858
  wipe(gF, quotient, G);
3150
3859
  }
3151
3860
  }
3152
- function checkNtruEquation({ f, g, F, G }) {
3861
+ function checkNtruEquation({ f, g, F: F2, G }) {
3153
3862
  const fG = mulNegacyclicInt(f, G);
3154
- const gF = mulNegacyclicInt(g, F);
3863
+ const gF = mulNegacyclicInt(g, F2);
3155
3864
  try {
3156
3865
  for (let i = 0; i < N; i++) {
3157
- if (fG[i] - gF[i] !== (i === 0 ? Q2 : 0)) {
3866
+ if (fG[i] - gF[i] !== (i === 0 ? Q : 0)) {
3158
3867
  throw new Error("Falcon512: invalid secret key (NTRU equation not satisfied)");
3159
3868
  }
3160
3869
  }
@@ -3186,11 +3895,11 @@ function decodeSecretKey(secretKey) {
3186
3895
  parts.push(f);
3187
3896
  const g = decodeSigned(bytes.subarray(1 + FG_BYTES, 1 + 2 * FG_BYTES), FG_BITS, "g");
3188
3897
  parts.push(g);
3189
- const F = decodeSigned(bytes.subarray(1 + 2 * FG_BYTES), CAPITAL_FG_BITS, "F");
3190
- parts.push(F);
3191
- const G = completeG(f, g, F);
3898
+ const F2 = decodeSigned(bytes.subarray(1 + 2 * FG_BYTES), CAPITAL_FG_BITS, "F");
3899
+ parts.push(F2);
3900
+ const G = completeG(f, g, F2);
3192
3901
  parts.push(G);
3193
- const polys = { f, g, F, G };
3902
+ const polys = { f, g, F: F2, G };
3194
3903
  checkNtruEquation(polys);
3195
3904
  return polys;
3196
3905
  } catch (error) {
@@ -3200,13 +3909,13 @@ function decodeSecretKey(secretKey) {
3200
3909
  wipe(bytes);
3201
3910
  }
3202
3911
  }
3203
- function encodeSecretKey({ f, g, F }) {
3912
+ function encodeSecretKey({ f, g, F: F2 }) {
3204
3913
  checkRange(f, FG_MAX, "f");
3205
3914
  checkRange(g, FG_MAX, "g");
3206
- checkRange(F, CAPITAL_FG_MAX, "F");
3915
+ checkRange(F2, CAPITAL_FG_MAX, "F");
3207
3916
  const fBits = Array.from(f, (v) => v & 63);
3208
3917
  const gBits = Array.from(g, (v) => v & 63);
3209
- const capitalFBits = Array.from(F, (v) => v & 255);
3918
+ const capitalFBits = Array.from(F2, (v) => v & 255);
3210
3919
  const encoded = [
3211
3920
  encodeBitsMSB(fBits, FG_BITS),
3212
3921
  encodeBitsMSB(gBits, FG_BITS),
@@ -3227,7 +3936,7 @@ function decodePublicKey(publicKey) {
3227
3936
  const bytes = toBytes(publicKey, PUBLIC_KEY_LENGTH, "public key");
3228
3937
  if (bytes[0] !== PUBLIC_KEY_HEADER) throw new Error("Falcon512: invalid public key header");
3229
3938
  const h = decodeBitsMSB(bytes.subarray(1), N, 14);
3230
- if (h.some((v) => v >= Q2)) {
3939
+ if (h.some((v) => v >= Q)) {
3231
3940
  throw new Error("Falcon512: invalid public key (coefficient out of range)");
3232
3941
  }
3233
3942
  return Uint16Array.from(h);
@@ -3237,7 +3946,7 @@ function encodePublicKey(h) {
3237
3946
  throw new Error(`Falcon512: public key polynomial must have ${N} coefficients`);
3238
3947
  }
3239
3948
  for (let i = 0; i < N; i++) {
3240
- if (!Number.isInteger(h[i]) || h[i] < 0 || h[i] >= Q2) {
3949
+ if (!Number.isInteger(h[i]) || h[i] < 0 || h[i] >= Q) {
3241
3950
  throw new Error("Falcon512: invalid public key (coefficient out of range)");
3242
3951
  }
3243
3952
  }
@@ -3247,7 +3956,7 @@ function encodePublicKey(h) {
3247
3956
  return out;
3248
3957
  }
3249
3958
  function generateKeyPair(seed) {
3250
- if (seed !== void 0 && (!(0, import_utils6.isBytes)(seed) || seed.length !== SEED_LENGTH)) {
3959
+ if (seed !== void 0 && (!(0, import_utils10.isBytes)(seed) || seed.length !== SEED_LENGTH)) {
3251
3960
  throw new Error(`Falcon512: seed must be a Uint8Array of ${SEED_LENGTH} bytes`);
3252
3961
  }
3253
3962
  return nobleEngine.keygen(seed);
@@ -3264,14 +3973,14 @@ function publicKeyToNtt(publicKey) {
3264
3973
  return Uint16Array.from(ntt(decodePublicKey(publicKey)));
3265
3974
  }
3266
3975
  function getPackedPublicKey(publicKey) {
3267
- return packPoly(publicKeyToNtt(publicKey)).map((x) => starknet3.num.toHex(x));
3976
+ return packPoly(publicKeyToNtt(publicKey)).map((x) => starknet7.num.toHex(x));
3268
3977
  }
3269
3978
  function importFalconRsSecretKey(secretKey) {
3270
3979
  const bytes = toBytes(secretKey, FALCON_RS_SECRET_KEY_LENGTH, "falcon-rs secret key");
3271
3980
  const parts = [];
3272
3981
  try {
3273
3982
  const names = ["f", "g", "F", "G"];
3274
- const [f, g, F, G] = names.map((name, k) => {
3983
+ const [f, g, F2, G] = names.map((name, k) => {
3275
3984
  const chunk = bytes.subarray(k * FALCON_RS_POLY_LENGTH, (k + 1) * FALCON_RS_POLY_LENGTH);
3276
3985
  const decoded = decode14LSB(chunk);
3277
3986
  parts.push(decoded);
@@ -3282,13 +3991,13 @@ function importFalconRsSecretKey(secretKey) {
3282
3991
  parts.push(p);
3283
3992
  return p;
3284
3993
  });
3285
- const recomputed = completeG(f, g, F);
3994
+ const recomputed = completeG(f, g, F2);
3286
3995
  parts.push(recomputed);
3287
3996
  if (recomputed.some((v, i) => v !== G[i])) {
3288
3997
  throw new Error("Falcon512: invalid falcon-rs secret key (G does not match f, g, F)");
3289
3998
  }
3290
- checkNtruEquation({ f, g, F, G });
3291
- return encodeSecretKey({ f, g, F });
3999
+ checkNtruEquation({ f, g, F: F2, G });
4000
+ return encodeSecretKey({ f, g, F: F2 });
3292
4001
  } finally {
3293
4002
  wipe(bytes, ...parts);
3294
4003
  }
@@ -3310,144 +4019,35 @@ function exportFalconRsSecretKey(secretKey) {
3310
4019
  }
3311
4020
  }
3312
4021
 
3313
- // src/falcon/s2morrow/signature.ts
3314
- var import_utils7 = require("@noble/hashes/utils.js");
3315
- var starknet5 = __toESM(require("starknet"));
3316
-
3317
- // src/falcon/s2morrow/hashToPoint.ts
3318
- var import_starknet = require("@scure/starknet");
3319
- var starknet4 = __toESM(require("starknet"));
3320
- function hashToPoint(message, salt) {
3321
- message.forEach((m) => assertFelt(m, "message element"));
3322
- salt.forEach((s) => assertFelt(s, "salt element"));
3323
- const out = new Uint16Array(N);
3324
- let idx = 0;
3325
- const extract6 = (value) => {
3326
- let v = value;
3327
- for (let i = 0; i < 6 && idx < N; i++) {
3328
- out[idx++] = Number(v % QB);
3329
- v /= QB;
3330
- }
3331
- };
3332
- const extract12 = (felt) => {
3333
- extract6(felt & starknet4.UINT_128_MAX);
3334
- extract6(felt >> 128n);
3335
- };
3336
- let state = [(0, import_starknet.poseidonHashMany)([...message, ...salt]), 0n, 0n];
3337
- for (let round = 0; round < 21; round++) {
3338
- state = (0, import_starknet.poseidonSmall)(state);
3339
- extract12(state[0]);
3340
- extract12(state[1]);
3341
- }
3342
- state = (0, import_starknet.poseidonSmall)(state);
3343
- extract12(state[0]);
3344
- return out;
3345
- }
3346
-
3347
- // src/falcon/s2morrow/signature.ts
3348
- var defaultDeps = { engine: nobleEngine, randomBytes: import_utils7.randomBytes };
3349
- function computeMulHint(s1, pkNtt) {
3350
- const s1Ntt = ntt(s1);
3351
- return intt(s1Ntt.map((v, i) => v * pkNtt[i] % Q2));
3352
- }
3353
- var centeredSquare = (x) => {
3354
- const c = x <= (Q2 - 1) / 2 ? x : Q2 - x;
3355
- return c * c;
3356
- };
3357
- function checkSignatureEquation(hashPoint, s1, mulHint, pkNtt) {
3358
- if (hashPoint.length !== N || s1.length !== N || mulHint.length !== N || pkNtt.length !== N) {
3359
- return false;
3360
- }
3361
- const s1Ntt = ntt(s1);
3362
- const hintNtt = ntt(mulHint);
3363
- for (let i = 0; i < N; i += 1) {
3364
- if (s1Ntt[i] * pkNtt[i] % Q2 !== hintNtt[i]) return false;
3365
- }
3366
- let norm = 0;
3367
- for (let i = 0; i < N; i += 1) {
3368
- norm += centeredSquare(modQ(hashPoint[i] - mulHint[i])) + centeredSquare(s1[i]);
3369
- }
3370
- return norm <= SIG_BOUND_512;
3371
- }
3372
- function formatSignature(sig) {
3373
- const felts = [
3374
- ...packPoly(sig.s1),
3375
- BigInt(sig.salt.length),
3376
- ...sig.salt,
3377
- ...packPoly(sig.mulHint)
3378
- ];
3379
- return felts.map((x) => starknet5.num.toHex(x));
3380
- }
3381
- function parseSignature(signature) {
3382
- if (!Array.isArray(signature) || signature.length !== SIGNATURE_FELTS) {
3383
- throw new Error(`Falcon512: signature must have ${SIGNATURE_FELTS} felts`);
3384
- }
3385
- const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3386
- if (felts[PACKED_SLOTS] !== BigInt(SALT_FELTS)) {
3387
- throw new Error("Falcon512: unexpected salt length");
3388
- }
3389
- const saltStart = PACKED_SLOTS + 1;
3390
- return {
3391
- s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3392
- salt: felts.slice(saltStart, saltStart + SALT_FELTS),
3393
- mulHint: unpackPoly(felts.slice(saltStart + SALT_FELTS))
3394
- };
3395
- }
3396
- var randomSaltFelt = (randomBytes2) => BigInt(`0x${starknet5.encode.buf2hex(randomBytes2(31))}`);
3397
- function signHash(msgHash, secretKey, pkNtt, deps = defaultDeps) {
3398
- assertFelt(msgHash, "message hash");
3399
- const salt = [randomSaltFelt(deps.randomBytes), randomSaltFelt(deps.randomBytes)];
3400
- const hashPoint = hashToPoint([msgHash], salt);
3401
- const s2 = deps.engine.signHashPoint(hashPoint, secretKey);
3402
- const s1 = Uint16Array.from(s2, modQ);
3403
- const mulHint = Uint16Array.from(computeMulHint(s1, pkNtt));
3404
- const signature = formatSignature({ s1, salt, mulHint });
3405
- const decoded = parseSignature(signature);
3406
- if (!checkSignatureEquation(hashPoint, decoded.s1, decoded.mulHint, pkNtt)) {
3407
- throw new Error("Falcon512: self-verification failed, signature discarded");
3408
- }
3409
- return signature;
3410
- }
3411
- function verifyHash(msgHash, signature, pkNtt) {
3412
- let decoded;
3413
- try {
3414
- assertFelt(msgHash, "message hash");
3415
- decoded = parseSignature(signature);
3416
- } catch {
3417
- return false;
3418
- }
3419
- return checkSignatureEquation(
3420
- hashToPoint([msgHash], decoded.salt),
3421
- decoded.s1,
3422
- decoded.mulHint,
3423
- pkNtt
3424
- );
3425
- }
3426
-
3427
4022
  // src/falcon/Falcon512Signer.ts
3428
4023
  function assertV3(details) {
3429
- if (!starknet6.isV3Tx(details)) throw new Error("Falcon512: only V3 transactions are supported");
4024
+ if (!starknet8.isV3Tx(details)) throw new Error("Falcon512: only V3 transactions are supported");
3430
4025
  }
3431
4026
  var Falcon512Signer = class _Falcon512Signer {
3432
4027
  #secretKey;
3433
4028
  #publicKey;
3434
4029
  #pkNtt;
3435
4030
  #packedPublicKey;
4031
+ #accountType;
3436
4032
  /**
3437
4033
  * Builds a signer from a NIST Falcon-512 secret key. The key is fully checked, then copied: the
3438
4034
  * signer keeps its own copy, in a private field.
3439
4035
  * @param {Uint8Array | string} secretKey NIST Falcon-512 secret key (1281 bytes), Uint8Array or
3440
4036
  * hex string. Prefer a Uint8Array: a string cannot be wiped from memory.
3441
- * @throws {Error} when the secret key is invalid
4037
+ * @param {Falcon512Options} [options] `accountType`: the type of the account that checks the
4038
+ * signatures, `'s2morrow'` (default), `'oz-hint'` or `'oz-direct'`
4039
+ * @throws {Error} when the secret key or an option is invalid
3442
4040
  * @example
3443
4041
  * ```typescript
3444
4042
  * const { secretKey } = falcon512.generateKeyPair();
3445
- * const mySigner = new Falcon512Signer(secretKey);
4043
+ * const mySigner = new Falcon512Signer(secretKey); // for an S2morrow account
4044
+ * const myOzSigner = new Falcon512Signer(secretKey, { accountType: 'oz-hint' });
3446
4045
  * new Falcon512Signer(new Uint8Array(1281));
3447
4046
  * // throws Error("Falcon512: invalid secret key header")
3448
4047
  * ```
3449
4048
  */
3450
- constructor(secretKey) {
4049
+ constructor(secretKey, options) {
4050
+ const accountType = parseFalconOptions(options);
3451
4051
  const bytes = toBytes(secretKey, SECRET_KEY_LENGTH, "secret key");
3452
4052
  let publicKey;
3453
4053
  try {
@@ -3456,6 +4056,7 @@ var Falcon512Signer = class _Falcon512Signer {
3456
4056
  bytes.fill(0);
3457
4057
  throw error;
3458
4058
  }
4059
+ this.#accountType = accountType;
3459
4060
  this.#publicKey = publicKey;
3460
4061
  this.#secretKey = bytes;
3461
4062
  this.#pkNtt = publicKeyToNtt(this.#publicKey);
@@ -3467,10 +4068,12 @@ var Falcon512Signer = class _Falcon512Signer {
3467
4068
  * Warning: falcon-rs derives the seed of its sampler from the public salt of each signature, so
3468
4069
  * the signatures it produced may leak information about the secret key. Use this for continuity
3469
4070
  * only; for real funds, generate a new key with `falcon512.generateKeyPair`. The S2morrow account
3470
- * cannot change its key: a new key means a new account.
4071
+ * cannot change its key: a new key means a new account. An OpenZeppelin account can change its
4072
+ * key (see `signOwnershipAcceptance`).
3471
4073
  * @param {Uint8Array | string} secretKey the falcon-rs secret key (3584 bytes), or its hex string
4074
+ * @param {Falcon512Options} [options] `accountType`, as for the constructor
3472
4075
  * @returns {Falcon512Signer} a signer that holds the same key, in the NIST format
3473
- * @throws {Error} when the falcon-rs secret key is invalid
4076
+ * @throws {Error} when the falcon-rs secret key or an option is invalid
3474
4077
  * @example
3475
4078
  * ```typescript
3476
4079
  * const mySigner = Falcon512Signer.fromFalconRs(falconRsSecretKey); // 3584 bytes, from falcon-rs
@@ -3478,10 +4081,10 @@ var Falcon512Signer = class _Falcon512Signer {
3478
4081
  * // result = ['0xb2cf4f8b3c6f60cc662f438970ad34017e260c52d7911297a42811ce3cea2b', …] (29 felts)
3479
4082
  * ```
3480
4083
  */
3481
- static fromFalconRs(secretKey) {
4084
+ static fromFalconRs(secretKey, options) {
3482
4085
  const nist = importFalconRsSecretKey(secretKey);
3483
4086
  try {
3484
- return new _Falcon512Signer(nist);
4087
+ return new _Falcon512Signer(nist, options);
3485
4088
  } finally {
3486
4089
  nist.fill(0);
3487
4090
  }
@@ -3498,10 +4101,12 @@ var Falcon512Signer = class _Falcon512Signer {
3498
4101
  * ```
3499
4102
  */
3500
4103
  async getPubKey() {
3501
- return starknet6.encode.addHexPrefix(starknet6.encode.buf2hex(this.#publicKey));
4104
+ return starknet8.encode.addHexPrefix(starknet8.encode.buf2hex(this.#publicKey));
3502
4105
  }
3503
4106
  /**
3504
- * The 29 felts of the account constructor argument `pk_packed`.
4107
+ * The 29 felts of the public key, in the form the accounts store it: the constructor argument
4108
+ * `pk_packed` of S2morrow, or the `public_key` array of an OpenZeppelin account (whose
4109
+ * constructor calldata is `29`, then these 29 felts). The same for the three account types.
3505
4110
  * @returns {string[]} the 29 felts, as hex strings (a new array at each call)
3506
4111
  * @example
3507
4112
  * ```typescript
@@ -3518,21 +4123,23 @@ var Falcon512Signer = class _Falcon512Signer {
3518
4123
  * Signs a SNIP-12 message (TypedData) for off-chain use.
3519
4124
  * @param {TypedData} typedData the message to sign
3520
4125
  * @param {string} accountAddress address of the account that signs the message
3521
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4126
+ * @returns {Promise<Signature>} the signature, as hex strings: 61 felts (S2morrow), 60
4127
+ * (OpenZeppelin, hint) or 31 (OpenZeppelin, direct)
3522
4128
  * @example
3523
4129
  * ```typescript
3524
4130
  * const result = await mySigner.signMessage(myTypedData, accountAddress);
3525
- * // result = ['0x…', …] (61 felts, random salt); result[29] = '0x2' (salt length)
4131
+ * // result = ['0x…', …] (S2morrow: 61 felts, random salt); result[29] = '0x2' (salt length)
3526
4132
  * ```
3527
4133
  */
3528
4134
  async signMessage(typedData3, accountAddress) {
3529
- return this.signRaw(starknet6.typedData.getMessageHash(typedData3, accountAddress));
4135
+ return this.signRaw(starknet8.typedData.getMessageHash(typedData3, accountAddress));
3530
4136
  }
3531
4137
  /**
3532
4138
  * Signs an INVOKE transaction (V3 only).
3533
4139
  * @param {Call[]} transactions the calls of the transaction
3534
4140
  * @param {InvocationsSignerDetails} details the details needed to hash the transaction
3535
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4141
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4142
+ * the account type
3536
4143
  * @throws {Error} when the transaction is not V3
3537
4144
  * @example
3538
4145
  * ```typescript
@@ -3561,29 +4168,30 @@ var Falcon512Signer = class _Falcon512Signer {
3561
4168
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3562
4169
  * };
3563
4170
  * const result = await mySigner.signTransaction(calls, details);
3564
- * // result = ['0x…', …] (61 felts)
4171
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3565
4172
  * ```
3566
4173
  */
3567
4174
  async signTransaction(transactions, details) {
3568
4175
  assertV3(details);
3569
- const compiledCalldata = starknet6.transaction.getExecuteCalldata(
4176
+ const compiledCalldata = starknet8.transaction.getExecuteCalldata(
3570
4177
  transactions,
3571
4178
  details.cairoVersion
3572
4179
  );
3573
- const msgHash = starknet6.hash.calculateInvokeTransactionHash({
4180
+ const msgHash = starknet8.hash.calculateInvokeTransactionHash({
3574
4181
  ...details,
3575
4182
  senderAddress: details.walletAddress,
3576
4183
  compiledCalldata,
3577
4184
  version: details.version,
3578
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3579
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4185
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4186
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3580
4187
  });
3581
4188
  return this.signRaw(msgHash);
3582
4189
  }
3583
4190
  /**
3584
4191
  * Signs the DEPLOY_ACCOUNT transaction of a Falcon-512 account (V3 only).
3585
4192
  * @param {DeployAccountSignerDetails} details the details needed to hash the transaction
3586
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4193
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4194
+ * the account type
3587
4195
  * @throws {Error} when the transaction is not V3
3588
4196
  * @example
3589
4197
  * ```typescript
@@ -3610,26 +4218,27 @@ var Falcon512Signer = class _Falcon512Signer {
3610
4218
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3611
4219
  * };
3612
4220
  * const result = await mySigner.signDeployAccountTransaction(details);
3613
- * // result = ['0x…', …] (61 felts)
4221
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3614
4222
  * ```
3615
4223
  */
3616
4224
  async signDeployAccountTransaction(details) {
3617
4225
  assertV3(details);
3618
- const compiledConstructorCalldata = starknet6.CallData.compile(details.constructorCalldata);
3619
- const msgHash = starknet6.hash.calculateDeployAccountTransactionHash({
4226
+ const compiledConstructorCalldata = starknet8.CallData.compile(details.constructorCalldata);
4227
+ const msgHash = starknet8.hash.calculateDeployAccountTransactionHash({
3620
4228
  ...details,
3621
4229
  salt: details.addressSalt,
3622
4230
  compiledConstructorCalldata,
3623
4231
  version: details.version,
3624
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3625
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4232
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4233
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3626
4234
  });
3627
4235
  return this.signRaw(msgHash);
3628
4236
  }
3629
4237
  /**
3630
4238
  * Signs a DECLARE transaction (V3 only).
3631
4239
  * @param {DeclareSignerDetails} details the details needed to hash the transaction
3632
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4240
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4241
+ * the account type
3633
4242
  * @throws {Error} when the transaction is not V3
3634
4243
  * @example
3635
4244
  * ```typescript
@@ -3652,24 +4261,75 @@ var Falcon512Signer = class _Falcon512Signer {
3652
4261
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3653
4262
  * };
3654
4263
  * const result = await mySigner.signDeclareTransaction(details);
3655
- * // result = ['0x…', …] (61 felts)
4264
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3656
4265
  * ```
3657
4266
  */
3658
4267
  async signDeclareTransaction(details) {
3659
4268
  assertV3(details);
3660
- const msgHash = starknet6.hash.calculateDeclareTransactionHash({
4269
+ const msgHash = starknet8.hash.calculateDeclareTransactionHash({
3661
4270
  ...details,
3662
4271
  version: details.version,
3663
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3664
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4272
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4273
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3665
4274
  });
3666
4275
  return this.signRaw(msgHash);
3667
4276
  }
3668
4277
  /**
3669
- * Signs a hash: the last step of all the methods above. It stays protected, so that no public
3670
- * method signs an arbitrary hash. A subclass can override it, as for every starknet.js signer.
4278
+ * Signs the acceptance of a key change of an OpenZeppelin Falcon-512 account.
4279
+ *
4280
+ * The account changes its key when it calls its own `set_public_key(new_public_key, signature)`:
4281
+ * the current key signs that transaction, as any other, and the new key must sign an acceptance.
4282
+ * Call this method on the signer of the new key, with the key that the account holds now. The
4283
+ * signed hash is Poseidon('StarkNet Message', 'accept_ownership', account address,
4284
+ * Poseidon(current key)). It holds no chain id, nonce or expiry: an acceptance is not single-use,
4285
+ * and the current key must still sign each key change.
4286
+ * @param {BigNumberish} accountAddress the address of the account
4287
+ * @param {BigNumberish[]} currentPublicKey the 29 felts of the key that the account holds now
4288
+ * (`getPackedPublicKey()` of its current signer, or its `get_public_key`)
4289
+ * @returns {Promise<string[]>} the acceptance, as hex strings, in the layout of this signer: 60
4290
+ * felts (`'oz-hint'`) or 31 (`'oz-direct'`)
4291
+ * @throws {Error} for an S2morrow signer (that account cannot change its key), or when the
4292
+ * current key has neither 29 felts nor none, or a value is not a felt252. Also when a subclass
4293
+ * makes `signRaw` return something else than an array of felts
4294
+ * @example
4295
+ * ```typescript
4296
+ * const newSigner = new Falcon512Signer(newSecretKey, { accountType: 'oz-hint' });
4297
+ * const acceptance = await newSigner.signOwnershipAcceptance(
4298
+ * falconAccount.address,
4299
+ * currentSigner.getPackedPublicKey()
4300
+ * );
4301
+ * const { transaction_hash } = await falconAccount.execute(
4302
+ * {
4303
+ * contractAddress: falconAccount.address,
4304
+ * entrypoint: 'set_public_key',
4305
+ * calldata: CallData.compile({
4306
+ * new_public_key: newSigner.getPackedPublicKey(),
4307
+ * signature: acceptance,
4308
+ * }),
4309
+ * },
4310
+ * { skipValidate: false }
4311
+ * );
4312
+ * await myProvider.waitForTransaction(transaction_hash);
4313
+ * // From now on, the account checks the signatures of newSigner.
4314
+ * ```
4315
+ */
4316
+ async signOwnershipAcceptance(accountAddress, currentPublicKey) {
4317
+ if (this.#accountType === "s2morrow") {
4318
+ throw new Error("Falcon512: an S2morrow account cannot change its key");
4319
+ }
4320
+ const signature = await this.signRaw(ownershipAcceptanceHash(accountAddress, currentPublicKey));
4321
+ if (!Array.isArray(signature)) {
4322
+ throw new Error("Falcon512: signRaw must return an array of felts");
4323
+ }
4324
+ return signature;
4325
+ }
4326
+ /**
4327
+ * Signs a hash: the last step of all the methods above, in the layout of the account type. It
4328
+ * stays protected, so that no public method signs an arbitrary hash. A subclass can override it,
4329
+ * as for every starknet.js signer.
3671
4330
  * @param {string} msgHash the hash to sign, a felt252
3672
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4331
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4332
+ * the account type
3673
4333
  * @example
3674
4334
  * ```typescript
3675
4335
  * class LoggedFalconSigner extends Falcon512Signer {
@@ -3683,7 +4343,15 @@ var Falcon512Signer = class _Falcon512Signer {
3683
4343
  * ```
3684
4344
  */
3685
4345
  async signRaw(msgHash) {
3686
- return signHash(starknet6.num.toBigInt(msgHash), this.#secretKey, this.#pkNtt);
4346
+ const value = starknet8.num.toBigInt(msgHash);
4347
+ switch (this.#accountType) {
4348
+ case "oz-hint":
4349
+ return signHashOz(value, this.#secretKey, this.#pkNtt, "hint");
4350
+ case "oz-direct":
4351
+ return signHashOz(value, this.#secretKey, this.#pkNtt, "direct");
4352
+ default:
4353
+ return signHash(value, this.#secretKey, this.#pkNtt);
4354
+ }
3687
4355
  }
3688
4356
  };
3689
4357
 
@@ -3700,7 +4368,7 @@ __export(falcon512_exports, {
3700
4368
  });
3701
4369
 
3702
4370
  // src/falcon/verify.ts
3703
- var starknet7 = __toESM(require("starknet"));
4371
+ var starknet9 = __toESM(require("starknet"));
3704
4372
  function toMessageHash(value) {
3705
4373
  try {
3706
4374
  return parseFelt(value, "message hash");
@@ -3708,29 +4376,280 @@ function toMessageHash(value) {
3708
4376
  return void 0;
3709
4377
  }
3710
4378
  }
3711
- function verify(signature, msgHash, fullPublicKey) {
3712
- const pkNtt = publicKeyToNtt(fullPublicKey);
4379
+ function toPkNtt(fullPublicKey) {
4380
+ if (Array.isArray(fullPublicKey)) {
4381
+ if (fullPublicKey.length !== PACKED_SLOTS) {
4382
+ throw new Error(`Falcon512: packed public key must have ${PACKED_SLOTS} felts`);
4383
+ }
4384
+ return unpackPoly(fullPublicKey.map((x, i) => parseFelt(x, `public key[${i}]`)));
4385
+ }
4386
+ return publicKeyToNtt(fullPublicKey);
4387
+ }
4388
+ function verify(signature, msgHash, fullPublicKey, options) {
4389
+ const accountType = parseFalconOptions(options);
4390
+ const pkNtt = toPkNtt(fullPublicKey);
3713
4391
  const h = toMessageHash(msgHash);
3714
4392
  if (h === void 0 || !Array.isArray(signature)) return false;
3715
- return verifyHash(h, signature, pkNtt);
4393
+ switch (accountType) {
4394
+ case "oz-hint":
4395
+ return verifyHashOz(h, signature, pkNtt, "hint");
4396
+ case "oz-direct":
4397
+ return verifyHashOz(h, signature, pkNtt, "direct");
4398
+ default:
4399
+ return verifyHash(h, signature, pkNtt);
4400
+ }
3716
4401
  }
3717
- function verifyMessage(message, signature, fullPublicKey, accountAddress) {
4402
+ function verifyMessage(message, signature, fullPublicKey, accountAddressOrOptions, options) {
3718
4403
  if (typeof message === "object" && message !== null) {
3719
- if (accountAddress === void 0) {
4404
+ if (accountAddressOrOptions === void 0) {
3720
4405
  throw new Error("Falcon512: accountAddress is required to verify a TypedData message");
3721
4406
  }
4407
+ const accountAddress = accountAddressOrOptions;
3722
4408
  return verify(
3723
4409
  signature,
3724
- starknet7.typedData.getMessageHash(message, accountAddress),
3725
- fullPublicKey
4410
+ starknet9.typedData.getMessageHash(message, accountAddress),
4411
+ fullPublicKey,
4412
+ options
4413
+ );
4414
+ }
4415
+ const hashOptions = typeof accountAddressOrOptions === "object" && accountAddressOrOptions !== null && !Array.isArray(accountAddressOrOptions) ? accountAddressOrOptions : void 0;
4416
+ return verify(signature, message, fullPublicKey, hashOptions);
4417
+ }
4418
+
4419
+ // src/falcon/mlkem/index.ts
4420
+ var mlkem_exports = {};
4421
+ __export(mlkem_exports, {
4422
+ createKey: () => createKey,
4423
+ decapsulate: () => decapsulate,
4424
+ encapsulate: () => encapsulate
4425
+ });
4426
+
4427
+ // src/falcon/mlkem/exchange.ts
4428
+ var import_hkdf = require("@noble/hashes/hkdf.js");
4429
+ var import_sha2 = require("@noble/hashes/sha2.js");
4430
+ var import_utils12 = require("@noble/hashes/utils.js");
4431
+ var starknet13 = __toESM(require("starknet"));
4432
+
4433
+ // src/falcon/mlkem/messages.ts
4434
+ var starknet10 = __toESM(require("starknet"));
4435
+ var DOMAIN_NAME = "ML-KEM key exchange";
4436
+ var DOMAIN_VERSION = "1";
4437
+ var ALGORITHM = "ML-KEM-768";
4438
+ function messageDomain(chainId) {
4439
+ return {
4440
+ type: [
4441
+ { name: "name", type: "shortstring" },
4442
+ { name: "version", type: "shortstring" },
4443
+ { name: "chainId", type: "shortstring" },
4444
+ { name: "revision", type: "shortstring" }
4445
+ ],
4446
+ domain: {
4447
+ name: DOMAIN_NAME,
4448
+ version: DOMAIN_VERSION,
4449
+ chainId,
4450
+ revision: starknet10.TypedDataRevision.ACTIVE
4451
+ }
4452
+ };
4453
+ }
4454
+ function publicKeyMessage(chainId, keyHash, validUntil) {
4455
+ const { type, domain } = messageDomain(chainId);
4456
+ return {
4457
+ types: {
4458
+ StarknetDomain: type,
4459
+ MlKemPublicKey: [
4460
+ { name: "Algorithm", type: "shortstring" },
4461
+ { name: "Key hash", type: "felt" },
4462
+ { name: "Valid until", type: "timestamp" }
4463
+ ]
4464
+ },
4465
+ primaryType: "MlKemPublicKey",
4466
+ domain,
4467
+ message: { Algorithm: ALGORITHM, "Key hash": keyHash, "Valid until": validUntil }
4468
+ };
4469
+ }
4470
+ function capsuleMessage(chainId, keyOwnerAddress, keyHash, capsuleHash, timestamp) {
4471
+ const { type, domain } = messageDomain(chainId);
4472
+ return {
4473
+ types: {
4474
+ StarknetDomain: type,
4475
+ MlKemCapsule: [
4476
+ { name: "Key owner", type: "ContractAddress" },
4477
+ { name: "Key hash", type: "felt" },
4478
+ { name: "Capsule hash", type: "felt" },
4479
+ { name: "Timestamp", type: "timestamp" }
4480
+ ]
4481
+ },
4482
+ primaryType: "MlKemCapsule",
4483
+ domain,
4484
+ message: {
4485
+ "Key owner": starknet10.num.toHex(keyOwnerAddress),
4486
+ "Key hash": keyHash,
4487
+ "Capsule hash": capsuleHash,
4488
+ Timestamp: timestamp
4489
+ }
4490
+ };
4491
+ }
4492
+
4493
+ // src/falcon/mlkem/signatures.ts
4494
+ var starknet11 = __toESM(require("starknet"));
4495
+ async function checkSignature(provider, typedData3, signature, accountAddress) {
4496
+ const address = starknet11.num.toHex(parseFelt(accountAddress, "ML-KEM account address"));
4497
+ let answer;
4498
+ try {
4499
+ answer = await provider.callContract({
4500
+ contractAddress: address,
4501
+ entrypoint: "get_public_key"
4502
+ });
4503
+ } catch (error) {
4504
+ throw new Error(
4505
+ `ML-KEM: cannot read the public key of the account ${address}. The account must be deployed, and must be a Falcon-512 account of OpenZeppelin.`,
4506
+ { cause: error }
4507
+ );
4508
+ }
4509
+ if (answer.length !== PACKED_SLOTS + 1 || BigInt(answer[0]) !== BigInt(PACKED_SLOTS)) {
4510
+ throw new Error(`ML-KEM: the account ${address} is not a Falcon-512 account of OpenZeppelin.`);
4511
+ }
4512
+ const length = Array.isArray(signature) ? signature.length : 0;
4513
+ let accountType;
4514
+ if (length === 60) {
4515
+ accountType = "oz-hint";
4516
+ } else if (length === 31) {
4517
+ accountType = "oz-direct";
4518
+ } else {
4519
+ throw new Error(
4520
+ `ML-KEM: the signature of the account ${address} is not a Falcon-512 signature.`
4521
+ );
4522
+ }
4523
+ if (!verifyMessage(typedData3, signature, answer.slice(1), address, { accountType })) {
4524
+ throw new Error(`ML-KEM: the signature of the account ${address} is not valid.`);
4525
+ }
4526
+ }
4527
+
4528
+ // src/falcon/mlkem/utils/bytes.ts
4529
+ var import_utils11 = require("@noble/hashes/utils.js");
4530
+ var starknet12 = __toESM(require("starknet"));
4531
+ function checkBytes(value, size, name) {
4532
+ if (!(0, import_utils11.isBytes)(value) || value.length !== size) {
4533
+ throw new Error(`ML-KEM: the ${name} must be a Uint8Array of ${size} bytes.`);
4534
+ }
4535
+ return value;
4536
+ }
4537
+ function hashBytes(bytes) {
4538
+ const groupSize = starknet12.constants.TEXT_TO_FELT_MAX_LEN;
4539
+ const felts = [];
4540
+ for (let start = 0; start < bytes.length; start += groupSize) {
4541
+ const group = bytes.subarray(start, start + groupSize);
4542
+ felts.push(starknet12.encode.addHexPrefix(starknet12.encode.buf2hex(group)));
4543
+ }
4544
+ return starknet12.hash.computePoseidonHashOnElements(felts);
4545
+ }
4546
+
4547
+ // src/falcon/mlkem/utils/time.ts
4548
+ var MAX_TIME = 4294967295;
4549
+ function nowInSeconds() {
4550
+ return Math.floor(Date.now() / 1e3);
4551
+ }
4552
+ function checkTime(value, name) {
4553
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > MAX_TIME) {
4554
+ throw new Error(
4555
+ `ML-KEM: ${name} must be a time in seconds, from 0 to ${MAX_TIME}. Note: Date.now() gives milliseconds, so divide it by 1000.`
3726
4556
  );
3727
4557
  }
3728
- return verify(signature, message, fullPublicKey);
4558
+ return value;
4559
+ }
4560
+
4561
+ // src/falcon/mlkem/exchange.ts
4562
+ var PUBLIC_KEY_SIZE = 1184;
4563
+ var CAPSULE_SIZE = 1088;
4564
+ var SEED_SIZE = 64;
4565
+ var SHARED_SECRET_SIZE = 32;
4566
+ function finalSecret(mlKemSecret, context) {
4567
+ const contextHash = starknet13.hash.computePoseidonHashOnElements([
4568
+ starknet13.CairoBytes31.fromText(DOMAIN_NAME).toBigInt(),
4569
+ starknet13.CairoBytes31.fromText(DOMAIN_VERSION).toBigInt(),
4570
+ context.chainId,
4571
+ context.keyOwnerAddress,
4572
+ context.senderAddress,
4573
+ context.keyHash,
4574
+ context.capsuleHash
4575
+ ]);
4576
+ const info = starknet13.num.hexToBytes(starknet13.num.toHex64(contextHash));
4577
+ return (0, import_hkdf.hkdf)(import_sha2.sha256, mlKemSecret, void 0, info, SHARED_SECRET_SIZE);
4578
+ }
4579
+ function createKey(chainId, validUntil) {
4580
+ if (typeof chainId !== "string" || chainId === "") {
4581
+ throw new Error("ML-KEM: chainId must be the chain id, as provider.getChainId() returns it.");
4582
+ }
4583
+ checkTime(validUntil, "validUntil");
4584
+ if (validUntil <= nowInSeconds()) throw new Error("ML-KEM: validUntil must be in the future.");
4585
+ const seed = (0, import_utils12.randomBytes)(SEED_SIZE);
4586
+ const { publicKey, secretKey } = ml_kem768.keygen(seed);
4587
+ secretKey.fill(0);
4588
+ const typedData3 = publicKeyMessage(chainId, hashBytes(publicKey), validUntil);
4589
+ return { seed, publicKey, typedData: typedData3 };
4590
+ }
4591
+ async function encapsulate(provider, signedKey, senderAddress) {
4592
+ checkBytes(signedKey.publicKey, PUBLIC_KEY_SIZE, "public key");
4593
+ checkTime(signedKey.validUntil, "validUntil");
4594
+ const aliceAddress = parseFelt(signedKey.keyOwnerAddress, "ML-KEM key owner address");
4595
+ const bobAddress = parseFelt(senderAddress, "ML-KEM sender address");
4596
+ if (signedKey.validUntil <= nowInSeconds()) {
4597
+ const owner = starknet13.num.toHex(aliceAddress);
4598
+ throw new Error(`ML-KEM: the key of the account ${owner} has expired.`);
4599
+ }
4600
+ const chainId = await provider.getChainId();
4601
+ const keyHash = hashBytes(signedKey.publicKey);
4602
+ const keyMessage = publicKeyMessage(chainId, keyHash, signedKey.validUntil);
4603
+ await checkSignature(provider, keyMessage, signedKey.signature, aliceAddress);
4604
+ const { cipherText: capsule, sharedSecret: mlKemSecret } = ml_kem768.encapsulate(
4605
+ signedKey.publicKey
4606
+ );
4607
+ const capsuleHash = hashBytes(capsule);
4608
+ const timestamp = nowInSeconds();
4609
+ const sharedSecret = finalSecret(mlKemSecret, {
4610
+ chainId,
4611
+ keyOwnerAddress: aliceAddress,
4612
+ senderAddress: bobAddress,
4613
+ keyHash,
4614
+ capsuleHash
4615
+ });
4616
+ mlKemSecret.fill(0);
4617
+ const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
4618
+ return { sharedSecret, capsule, timestamp, typedData: typedData3 };
4619
+ }
4620
+ async function decapsulate(provider, signedCapsule, keyOwnerAddress, seed) {
4621
+ checkBytes(signedCapsule.capsule, CAPSULE_SIZE, "capsule");
4622
+ checkTime(signedCapsule.timestamp, "timestamp");
4623
+ checkBytes(seed, SEED_SIZE, "seed");
4624
+ const aliceAddress = parseFelt(keyOwnerAddress, "ML-KEM key owner address");
4625
+ const bobAddress = parseFelt(signedCapsule.senderAddress, "ML-KEM sender address");
4626
+ const { publicKey, secretKey } = ml_kem768.keygen(seed);
4627
+ try {
4628
+ const chainId = await provider.getChainId();
4629
+ const keyHash = hashBytes(publicKey);
4630
+ const capsuleHash = hashBytes(signedCapsule.capsule);
4631
+ const { timestamp } = signedCapsule;
4632
+ const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
4633
+ await checkSignature(provider, typedData3, signedCapsule.signature, bobAddress);
4634
+ const mlKemSecret = ml_kem768.decapsulate(signedCapsule.capsule, secretKey);
4635
+ const sharedSecret = finalSecret(mlKemSecret, {
4636
+ chainId,
4637
+ keyOwnerAddress: aliceAddress,
4638
+ senderAddress: bobAddress,
4639
+ keyHash,
4640
+ capsuleHash
4641
+ });
4642
+ mlKemSecret.fill(0);
4643
+ return sharedSecret;
4644
+ } finally {
4645
+ secretKey.fill(0);
4646
+ }
3729
4647
  }
3730
4648
  // Annotate the CommonJS export names for ESM import in node:
3731
4649
  0 && (module.exports = {
3732
4650
  Falcon512Signer,
3733
- falcon512
4651
+ falcon512,
4652
+ mlkem
3734
4653
  });
3735
4654
  /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
3736
4655
  //# sourceMappingURL=index.js.map