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.
@@ -5,11 +5,77 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/falcon/Falcon512Signer.ts
8
- import * as starknet6 from "starknet";
8
+ import * as starknet8 from "starknet";
9
9
 
10
- // src/falcon/s2morrow/keys.ts
11
- import { isBytes as isBytes2 } from "@noble/hashes/utils.js";
12
- import * as starknet3 from "starknet";
10
+ // src/falcon/accountType.ts
11
+ var ACCOUNT_TYPES = Object.freeze([
12
+ "s2morrow",
13
+ "oz-hint",
14
+ "oz-direct"
15
+ ]);
16
+ function parseFalconOptions(options) {
17
+ if (options === void 0) return "s2morrow";
18
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
19
+ throw new Error("Falcon512: options must be an object");
20
+ }
21
+ Object.keys(options).forEach((key) => {
22
+ if (key !== "accountType") throw new Error(`Falcon512: unknown option "${key}"`);
23
+ });
24
+ const { accountType } = options;
25
+ if (accountType === void 0) return "s2morrow";
26
+ if (!ACCOUNT_TYPES.includes(accountType)) {
27
+ throw new Error(
28
+ `Falcon512: unknown accountType "${String(accountType)}" (expected 's2morrow', 'oz-hint' or 'oz-direct')`
29
+ );
30
+ }
31
+ return accountType;
32
+ }
33
+
34
+ // src/falcon/oz/ownership.ts
35
+ import * as starknet2 from "starknet";
36
+
37
+ // src/falcon/s2morrow/constants.ts
38
+ var Q = 12289;
39
+ var QB = 12289n;
40
+ var N = 512;
41
+ var SIG_BOUND_512 = 34034726;
42
+ var PACKED_SLOTS = 29;
43
+ var VALUES_PER_HALF = 9;
44
+ var SALT_FELTS = 2;
45
+ var SIGNATURE_FELTS = 61;
46
+
47
+ // src/falcon/s2morrow/felt.ts
48
+ import * as starknet from "starknet";
49
+ function assertFelt(x, label) {
50
+ if (typeof x !== "bigint") throw new Error(`Falcon512: ${label} is not a felt252`);
51
+ starknet.CairoFelt252.assertRange(x);
52
+ }
53
+ var FELT_STRING = /^(0[xX][0-9a-fA-F]{1,64}|[0-9]{1,76})$/;
54
+ function parseFelt(value, label) {
55
+ const accepted = typeof value === "bigint" && value >= 0n || typeof value === "number" && Number.isSafeInteger(value) && value >= 0 || typeof value === "string" && FELT_STRING.test(value);
56
+ if (!accepted) throw new Error(`Falcon512: ${label} is not a felt252`);
57
+ return new starknet.CairoFelt252(value).toBigInt();
58
+ }
59
+
60
+ // src/falcon/oz/ownership.ts
61
+ function ownershipAcceptanceHash(accountAddress, currentPublicKey) {
62
+ if (!Array.isArray(currentPublicKey) || currentPublicKey.length !== PACKED_SLOTS && currentPublicKey.length !== 0) {
63
+ throw new Error("Falcon512: current public key must have 29 felts, or none");
64
+ }
65
+ const address = parseFelt(accountAddress, "account address");
66
+ const key = currentPublicKey.map((x, i) => parseFelt(x, `current public key[${i}]`));
67
+ const { computePoseidonHashOnElements } = starknet2.hash;
68
+ return computePoseidonHashOnElements([
69
+ starknet2.CairoBytes31.fromText("StarkNet Message").toBigInt(),
70
+ starknet2.CairoBytes31.fromText("accept_ownership").toBigInt(),
71
+ address,
72
+ computePoseidonHashOnElements(key)
73
+ ]);
74
+ }
75
+
76
+ // src/falcon/oz/signature.ts
77
+ import { randomBytes as cryptoRandomBytes2 } from "@noble/hashes/utils.js";
78
+ import * as starknet6 from "starknet";
13
79
 
14
80
  // src/falcon/engine/noble/falcon.ts
15
81
  import { rngAesCtrDrbg256 } from "@noble/ciphers/aes.js";
@@ -23,7 +89,7 @@ import {
23
89
  bytesToHex as bytesToHex2,
24
90
  createView,
25
91
  hexToBytes,
26
- randomBytes,
92
+ randomBytes as randomBytes2,
27
93
  swap32IfBE,
28
94
  u32,
29
95
  u8
@@ -45,6 +111,15 @@ import {
45
111
  isLE,
46
112
  randomBytes as randb
47
113
  } from "@noble/hashes/utils.js";
114
+ var abytesDoc = abytes;
115
+ var randomBytes = randb;
116
+ function aarray(item, title, inner = () => {
117
+ }) {
118
+ if (!Array.isArray(item))
119
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
120
+ for (let i = 0; i < item.length; i++) inner(item[i], `${title}[${i}]`);
121
+ return item;
122
+ }
48
123
  function aobject(value, title = "object") {
49
124
  if (value === null || typeof value !== "object" || Array.isArray(value))
50
125
  throw new TypeError(
@@ -52,6 +127,14 @@ function aobject(value, title = "object") {
52
127
  );
53
128
  return value;
54
129
  }
130
+ function equalBytes(a, b) {
131
+ a = abytes(a);
132
+ b = abytes(b);
133
+ if (a.length !== b.length) return false;
134
+ let diff = 0;
135
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
136
+ return diff === 0;
137
+ }
55
138
  function copyBytes(bytes) {
56
139
  return new Uint8Array(abytes(bytes));
57
140
  }
@@ -74,10 +157,10 @@ function byteSwap64(arr) {
74
157
  return arr;
75
158
  }
76
159
  var baswap64If = isLE ? (arr) => arr : byteSwap64;
77
- function validateOpts(opts) {
78
- if (isBytes(opts)) throw new TypeError('"opts" expected object, got Uint8Array');
79
- aobject(opts, "opts");
80
- const proto = Object.getPrototypeOf(opts);
160
+ function validateOpts(opts2) {
161
+ if (isBytes(opts2)) throw new TypeError('"opts" expected object, got Uint8Array');
162
+ aobject(opts2, "opts");
163
+ const proto = Object.getPrototypeOf(opts2);
81
164
  if (proto !== null && proto !== Object.prototype)
82
165
  throw new TypeError('"opts" expected a plain object');
83
166
  }
@@ -88,9 +171,9 @@ var SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([
88
171
  "context",
89
172
  "extraEntropy"
90
173
  ]);
91
- function checkOptKeys(opts, allowed) {
92
- validateOpts(opts);
93
- const normalized = Object.assign(/* @__PURE__ */ Object.create(null), opts);
174
+ function checkOptKeys(opts2, allowed) {
175
+ validateOpts(opts2);
176
+ const normalized = Object.assign(/* @__PURE__ */ Object.create(null), opts2);
94
177
  for (const [k, v] of Object.entries(normalized)) {
95
178
  if (v === void 0) continue;
96
179
  if (!allowed.includes(k))
@@ -100,13 +183,13 @@ function checkOptKeys(opts, allowed) {
100
183
  }
101
184
  return Object.freeze(normalized);
102
185
  }
103
- function validateVerOpts(opts, allowed = VER_OPT_KEYS) {
104
- const normalized = checkOptKeys(opts, allowed);
186
+ function validateVerOpts(opts2, allowed = VER_OPT_KEYS) {
187
+ const normalized = checkOptKeys(opts2, allowed);
105
188
  if (normalized.context !== void 0) abytes(normalized.context, void 0, "opts.context");
106
189
  return normalized;
107
190
  }
108
- function validateSigOpts(opts, allowed = SIG_OPT_KEYS) {
109
- const normalized = checkOptKeys(opts, allowed);
191
+ function validateSigOpts(opts2, allowed = SIG_OPT_KEYS) {
192
+ const normalized = checkOptKeys(opts2, allowed);
110
193
  if (normalized.context !== void 0) abytes(normalized.context, void 0, "opts.context");
111
194
  if (normalized.extraEntropy !== false && normalized.extraEntropy !== void 0)
112
195
  abytes(normalized.extraEntropy, void 0, "opts.extraEntropy");
@@ -143,6 +226,33 @@ function splitCoder(label, ...lengths) {
143
226
  }
144
227
  };
145
228
  }
229
+ function vecCoder(c, vecLen) {
230
+ const coder = c;
231
+ const bytesLen = vecLen * coder.bytesLen;
232
+ return {
233
+ bytesLen,
234
+ encode: (u) => {
235
+ const uArr = aarray(u, "u");
236
+ if (uArr.length !== vecLen)
237
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
238
+ const res = new Uint8Array(bytesLen);
239
+ for (let i = 0, pos = 0; i < uArr.length; i++) {
240
+ const b = coder.encode(uArr[i]);
241
+ res.set(b, pos);
242
+ b.fill(0);
243
+ pos += b.length;
244
+ }
245
+ return res;
246
+ },
247
+ decode: (a) => {
248
+ abytes_(a, bytesLen);
249
+ const r = [];
250
+ for (let i = 0; i < a.length; i += coder.bytesLen)
251
+ r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
252
+ return r;
253
+ }
254
+ };
255
+ }
146
256
  function cleanBytes(...list) {
147
257
  for (const t of list) {
148
258
  if (Array.isArray(t)) for (const b of t) b.fill(0);
@@ -156,21 +266,21 @@ function getMask(bits) {
156
266
  }
157
267
 
158
268
  // src/falcon/engine/noble/_crystals.ts
159
- var genCrystals = (opts) => {
160
- const { newPoly, N: N2, Q: Q3, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;
161
- const mod = (a, modulo = Q3) => {
269
+ var genCrystals = (opts2) => {
270
+ const { newPoly, N: N3, Q: Q4, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts2;
271
+ const mod = (a, modulo = Q4) => {
162
272
  const result = a % modulo | 0;
163
273
  return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
164
274
  };
165
- const smod = (a, modulo = Q3) => {
275
+ const smod = (a, modulo = Q4) => {
166
276
  const r = mod(a, modulo) | 0;
167
277
  return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
168
278
  };
169
279
  function getZettas() {
170
- const out = newPoly(N2);
171
- for (let i = 0; i < N2; i++) {
280
+ const out = newPoly(N3);
281
+ for (let i = 0; i < N3; i++) {
172
282
  const b = reverseBits(i, brvBits);
173
- const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q3);
283
+ const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q4);
174
284
  out[i] = Number(p) | 0;
175
285
  }
176
286
  return out;
@@ -182,11 +292,11 @@ var genCrystals = (opts) => {
182
292
  const field = isKyber ? {
183
293
  add: (a, b) => {
184
294
  const r = a + b | 0;
185
- return r >= Q3 ? r - Q3 | 0 : r;
295
+ return r >= Q4 ? r - Q4 | 0 : r;
186
296
  },
187
297
  sub: (a, b) => {
188
298
  const r = a - b | 0;
189
- return r < 0 ? r + Q3 | 0 : r;
299
+ return r < 0 ? r + Q4 | 0 : r;
190
300
  },
191
301
  mul: (a, b) => mod((a | 0) * (b | 0)) | 0,
192
302
  inv
@@ -197,7 +307,7 @@ var genCrystals = (opts) => {
197
307
  inv
198
308
  };
199
309
  const nttOpts = {
200
- N: N2,
310
+ N: N3,
201
311
  roots: nttZetas,
202
312
  invertButterflies: true,
203
313
  skipStages: isKyber ? 1 : 0,
@@ -211,18 +321,18 @@ var genCrystals = (opts) => {
211
321
  },
212
322
  decode: (r) => {
213
323
  dit(r);
214
- for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);
324
+ for (let i = 0; i < r.length; i++) r[i] = mod(F2 * r[i]);
215
325
  return r;
216
326
  }
217
327
  };
218
328
  const bitsCoder = (d, c) => {
219
- for (let i = 0, bufLen = 0; i < N2; i++) {
329
+ for (let i = 0, bufLen = 0; i < N3; i++) {
220
330
  bufLen += d;
221
331
  if (bufLen > 32) getMask(bufLen);
222
332
  bufLen %= 8;
223
333
  }
224
334
  const mask = getMask(d);
225
- const bytesLen = d * (N2 / 8);
335
+ const bytesLen = d * (N3 / 8);
226
336
  return {
227
337
  bytesLen,
228
338
  encode: (poly_) => {
@@ -236,7 +346,7 @@ var genCrystals = (opts) => {
236
346
  return r;
237
347
  },
238
348
  decode: (bytes) => {
239
- const r = newPoly(N2);
349
+ const r = newPoly(N3);
240
350
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
241
351
  buf |= bytes[i] << bufLen;
242
352
  bufLen += 8;
@@ -257,15 +367,44 @@ var genCrystals = (opts) => {
257
367
  bitsCoder
258
368
  };
259
369
  };
370
+ var createXofShake = (shake) => (seed, blockLen) => {
371
+ if (!blockLen) blockLen = shake.blockLen;
372
+ const _seed = new Uint8Array(seed.length + 2);
373
+ _seed.set(seed);
374
+ const seedLen = seed.length;
375
+ const buf = new Uint8Array(blockLen);
376
+ let h = shake.create({});
377
+ let calls = 0;
378
+ let xofs = 0;
379
+ return {
380
+ stats: () => ({ calls, xofs }),
381
+ get: (x, y) => {
382
+ _seed[seedLen + 0] = x;
383
+ _seed[seedLen + 1] = y;
384
+ h.destroy();
385
+ h = shake.create({}).update(_seed);
386
+ calls++;
387
+ return () => {
388
+ xofs++;
389
+ return h.xofInto(buf);
390
+ };
391
+ },
392
+ clean: () => {
393
+ h.destroy();
394
+ cleanBytes(buf, _seed);
395
+ }
396
+ };
397
+ };
398
+ var XOF128 = /* @__PURE__ */ createXofShake(shake128);
260
399
 
261
400
  // src/falcon/engine/noble/falcon.ts
262
- var bitsCoderMSB = (newPoly, N2, d, c) => {
401
+ var bitsCoderMSB = (newPoly, N3, d, c) => {
263
402
  const mask = getMask(d);
264
- const bytesLen = d * (N2 / 8);
403
+ const bytesLen = d * (N3 / 8);
265
404
  return {
266
405
  bytesLen,
267
406
  encode: (poly) => {
268
- if (poly.length !== N2) throw new Error(`wrong length: expected ${N2}, got ${poly.length}`);
407
+ if (poly.length !== N3) throw new Error(`wrong length: expected ${N3}, got ${poly.length}`);
269
408
  const r = new Uint8Array(bytesLen);
270
409
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
271
410
  buf = buf << d | c.encode(poly[i]) & mask;
@@ -275,7 +414,7 @@ var bitsCoderMSB = (newPoly, N2, d, c) => {
275
414
  return r;
276
415
  },
277
416
  decode: (bytes) => {
278
- const r = newPoly(N2);
417
+ const r = newPoly(N3);
279
418
  for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
280
419
  buf = buf << 8 | bytes[i];
281
420
  bufLen += 8;
@@ -385,43 +524,43 @@ var cleanCPoly = (...list) => {
385
524
  }
386
525
  };
387
526
  function getComplex(field) {
388
- const F = field;
527
+ const F2 = field;
389
528
  return {
390
529
  lift: (x) => {
391
530
  if (x.re !== void 0 && x.im !== void 0) return x;
392
- return { re: x, im: F.ZERO };
531
+ return { re: x, im: F2.ZERO };
393
532
  },
394
533
  add: (a, b) => ({
395
- re: F.add(a.re, b.re),
396
- im: F.add(a.im, b.im)
534
+ re: F2.add(a.re, b.re),
535
+ im: F2.add(a.im, b.im)
397
536
  }),
398
537
  sub: (a, b) => ({
399
- re: F.sub(a.re, b.re),
400
- im: F.sub(a.im, b.im)
538
+ re: F2.sub(a.re, b.re),
539
+ im: F2.sub(a.im, b.im)
401
540
  }),
402
541
  mul: (a, b) => ({
403
- re: F.sub(F.mul(a.re, b.re), F.mul(a.im, b.im)),
404
- im: F.add(F.mul(a.re, b.im), F.mul(a.im, b.re))
542
+ re: F2.sub(F2.mul(a.re, b.re), F2.mul(a.im, b.im)),
543
+ im: F2.add(F2.mul(a.re, b.im), F2.mul(a.im, b.re))
405
544
  }),
406
545
  div: (a, b) => {
407
- const denom = F.add(F.mul(b.re, b.re), F.mul(b.im, b.im));
546
+ const denom = F2.add(F2.mul(b.re, b.re), F2.mul(b.im, b.im));
408
547
  return {
409
- re: F.div(F.add(F.mul(a.re, b.re), F.mul(a.im, b.im)), denom),
410
- im: F.div(F.sub(F.mul(a.im, b.re), F.mul(a.re, b.im)), denom)
548
+ re: F2.div(F2.add(F2.mul(a.re, b.re), F2.mul(a.im, b.im)), denom),
549
+ im: F2.div(F2.sub(F2.mul(a.im, b.re), F2.mul(a.re, b.im)), denom)
411
550
  };
412
551
  },
413
- neg: (a) => ({ re: F.neg(a.re), im: F.neg(a.im) }),
414
- conj: (a) => ({ re: a.re, im: F.neg(a.im) }),
552
+ neg: (a) => ({ re: F2.neg(a.re), im: F2.neg(a.im) }),
553
+ conj: (a) => ({ re: a.re, im: F2.neg(a.im) }),
415
554
  scale: (a, x) => ({
416
- re: F.mul(a.re, x),
417
- im: F.mul(a.im, x)
555
+ re: F2.mul(a.re, x),
556
+ im: F2.mul(a.im, x)
418
557
  }),
419
558
  // a.re * a.re + a.im * a.im + b.re * b.re + b.im * b.im;
420
- magSqSum: (a, b) => F.add(
421
- F.add(F.add(F.mul(a.re, a.re), F.mul(a.im, a.im)), F.mul(b.re, b.re)),
422
- F.mul(b.im, b.im)
559
+ magSqSum: (a, b) => F2.add(
560
+ F2.add(F2.add(F2.mul(a.re, a.re), F2.mul(a.im, a.im)), F2.mul(b.re, b.re)),
561
+ F2.mul(b.im, b.im)
423
562
  ),
424
- eql: (a, b) => F.eql(a.re, b.re) && F.eql(a.im, b.im),
563
+ eql: (a, b) => F2.eql(a.re, b.re) && F2.eql(a.im, b.im),
425
564
  clone: (a) => ({ re: a.re, im: a.im }),
426
565
  inv: () => {
427
566
  throw new Error("not implemented");
@@ -430,8 +569,8 @@ function getComplex(field) {
430
569
  }
431
570
  var ComplexArr = {
432
571
  decode(lst) {
433
- const N2 = lst.length;
434
- const hn = N2 >> 1;
572
+ const N3 = lst.length;
573
+ const hn = N3 >> 1;
435
574
  const len = lst.length;
436
575
  if (len === 0) return [];
437
576
  if (len % 2 !== 0)
@@ -493,9 +632,9 @@ var Float = /* @__PURE__ */ Object.freeze({
493
632
  var f64b = (n) => Float.decode(numberToHexUnpadded(n));
494
633
  var EMPTY_CHACHA20_BLOCK = /* @__PURE__ */ new Uint8Array(64);
495
634
  var NONCELEN = 40;
496
- var Q = 12289;
497
- var Qhalf = Q >> 1;
498
- var QBig = BigInt(Q);
635
+ var Q2 = 12289;
636
+ var Qhalf = Q2 >> 1;
637
+ var QBig = BigInt(Q2);
499
638
  var _0n = /* @__PURE__ */ BigInt(0);
500
639
  var _1n = /* @__PURE__ */ BigInt(1);
501
640
  var _10n = /* @__PURE__ */ BigInt(10);
@@ -508,7 +647,7 @@ var MASK_32n = /* @__PURE__ */ BigInt("0xffffffff");
508
647
  var MASK_63n = /* @__PURE__ */ BigInt("0x7fffffffffffffff");
509
648
  var R2 = 10952;
510
649
  var Q0I = 12287;
511
- var F_INV_Q = 1 / Q;
650
+ var F_INV_Q = 1 / Q2;
512
651
  var F_MINUS_INV_Q = -F_INV_Q;
513
652
  var MAX_BL_SMALL = [1, 1, 2, 2, 4, 7, 14, 27, 53, 106, 209];
514
653
  var MAX_BL_LARGE = [2, 2, 5, 7, 12, 21, 40, 78, 157, 308];
@@ -669,9 +808,9 @@ var COMPLEX_ROOTS = /* @__PURE__ */ (() => {
669
808
  var intField = {
670
809
  mul(x, y) {
671
810
  let z = Math.imul(x, y);
672
- let w = Math.imul(Q, Math.imul(z, Q0I) & 65535);
673
- z = (z + w >>> 16) - Q;
674
- z += Q & z >> 31;
811
+ let w = Math.imul(Q2, Math.imul(z, Q0I) & 65535);
812
+ z = (z + w >>> 16) - Q2;
813
+ z += Q2 & z >> 31;
675
814
  return z >>> 0;
676
815
  },
677
816
  inv(y) {
@@ -702,11 +841,11 @@ var intField = {
702
841
  function getIntPoly(logn) {
703
842
  const n = 1 << logn;
704
843
  const newPoly = (n2) => new Uint16Array(n2);
705
- const F = Number(invert(BigInt(n), QBig));
844
+ const F2 = Number(invert(BigInt(n), QBig));
706
845
  const { mod, smod, NTT } = genCrystals({
707
846
  N: n,
708
- Q,
709
- F,
847
+ Q: Q2,
848
+ F: F2,
710
849
  ROOT_OF_UNITY: 7,
711
850
  newPoly,
712
851
  isKyber: false,
@@ -856,9 +995,9 @@ function ApproxExp(x, ccs) {
856
995
  for (let i = ev.length - 2; i >= 0; i--) z = z * y + ev[i];
857
996
  return ccs * (1 + z * y);
858
997
  }
859
- function genFalcon(opts) {
860
- const { N: N2 } = opts;
861
- const logn = Math.log2(N2);
998
+ function genFalcon(opts2) {
999
+ const { N: N3 } = opts2;
1000
+ const logn = Math.log2(N3);
862
1001
  const id = (n) => n;
863
1002
  const { newPoly, intPoly, signedCoder } = getIntPoly(logn);
864
1003
  const floatPoly = getFloatPoly(logn);
@@ -945,7 +1084,7 @@ function genFalcon(opts) {
945
1084
  }
946
1085
  return a;
947
1086
  }
948
- reduce(logn2, f, g, F, G, logn_top) {
1087
+ reduce(logn2, f, g, F2, G, logn_top) {
949
1088
  const n = 1 << logn2;
950
1089
  const depth = logn_top - logn2;
951
1090
  const floatPoly2 = getFloatPoly(logn2);
@@ -972,7 +1111,7 @@ function genFalcon(opts) {
972
1111
  while (true) {
973
1112
  let scaleFG = _31n * (FGlen - _10n);
974
1113
  for (let i = 0; i < n; i++) {
975
- Fx[i] = Number(F[i] >> scaleFG);
1114
+ Fx[i] = Number(F2[i] >> scaleFG);
976
1115
  Gx[i] = Number(G[i] >> scaleFG);
977
1116
  }
978
1117
  const rt2 = floatPoly2.mul(floatPoly2.FFT(floatPoly2.to(Gx)), rt4);
@@ -987,7 +1126,7 @@ function genFalcon(opts) {
987
1126
  if (val <= -BOUND || val >= BOUND) return false;
988
1127
  k[i] = BigInt(Math.round(val));
989
1128
  }
990
- F = this.subMul(logn2, F, f, k, scaleK);
1129
+ F2 = this.subMul(logn2, F2, f, k, scaleK);
991
1130
  G = this.subMul(logn2, G, g, k, scaleK);
992
1131
  const maxfgNew = scaleK + BigInt(Math.round(fgMaxBits)) + _10n;
993
1132
  if (maxfgNew < maxFGBits) maxFGBits = maxfgNew;
@@ -999,7 +1138,7 @@ function genFalcon(opts) {
999
1138
  return true;
1000
1139
  }
1001
1140
  // This is recursive thing that goes from logn to 0
1002
- solveBranch(logn2, f, g, F, G, logn_top) {
1141
+ solveBranch(logn2, f, g, F2, G, logn_top) {
1003
1142
  if (logn2 === 0) {
1004
1143
  const xf = f[0];
1005
1144
  const xg = g[0];
@@ -1007,7 +1146,7 @@ function genFalcon(opts) {
1007
1146
  try {
1008
1147
  const u1 = invert(xf, xg);
1009
1148
  const v1 = (_1n - u1 * xf) / xg;
1010
- F[0] = -v1 * QBig;
1149
+ F2[0] = -v1 * QBig;
1011
1150
  G[0] = u1 * QBig;
1012
1151
  return true;
1013
1152
  } catch (e) {
@@ -1023,9 +1162,9 @@ function genFalcon(opts) {
1023
1162
  const Fp = new Array(hn);
1024
1163
  const Gp = new Array(hn);
1025
1164
  if (!this.solveBranch(logn2 - 1, fp, gp, Fp, Gp, logn_top)) return false;
1026
- F = this.mulConjD(logn2, F, g, Fp);
1165
+ F2 = this.mulConjD(logn2, F2, g, Fp);
1027
1166
  G = this.mulConjD(logn2, G, f, Gp);
1028
- return this.reduce(logn2, f, g, F, G, logn_top);
1167
+ return this.reduce(logn2, f, g, F2, G, logn_top);
1029
1168
  }
1030
1169
  solve(f, g) {
1031
1170
  const n = 1 << logn;
@@ -1034,16 +1173,16 @@ function genFalcon(opts) {
1034
1173
  const bF = new Array(n);
1035
1174
  const bG = new Array(n);
1036
1175
  if (!this.solveBranch(logn, bf, bg, bF, bG)) return false;
1037
- const F = new Int8Array(n);
1176
+ const F2 = new Int8Array(n);
1038
1177
  const G = new Int8Array(n);
1039
1178
  for (let i = 0; i < n; i++) {
1040
1179
  const x = bF[i];
1041
1180
  const y = bG[i];
1042
1181
  if (x < -127 || x > 127 || y < -127 || y > 127) return false;
1043
- F[i] = Number(x);
1182
+ F2[i] = Number(x);
1044
1183
  G[i] = Number(y);
1045
1184
  }
1046
- return [F, G];
1185
+ return [F2, G];
1047
1186
  }
1048
1187
  generate() {
1049
1188
  let max = 1e6;
@@ -1052,8 +1191,8 @@ function genFalcon(opts) {
1052
1191
  if (curr++ === max) throw new Error("can't generate key");
1053
1192
  const f = this.polyGauss();
1054
1193
  const g = this.polyGauss();
1055
- let lim = 1 << opts.fgBits - 1;
1056
- for (let u = 0; u < N2; u++) {
1194
+ let lim = 1 << opts2.fgBits - 1;
1195
+ for (let u = 0; u < N3; u++) {
1057
1196
  if (f[u] >= lim || f[u] <= -lim || g[u] >= lim || g[u] <= -lim) {
1058
1197
  lim = -1;
1059
1198
  break;
@@ -1067,8 +1206,8 @@ function genFalcon(opts) {
1067
1206
  let rt1 = floatPoly.FFT(floatPoly.convSmall(f));
1068
1207
  let rt2 = floatPoly.FFT(floatPoly.convSmall(g));
1069
1208
  const rt3 = floatPoly.invNorm(rt1, rt2);
1070
- rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q), rt3));
1071
- rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q), rt3));
1209
+ rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q2), rt3));
1210
+ rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q2), rt3));
1072
1211
  let bnorm = 0;
1073
1212
  for (let u = 0; u < rt1.length; u++) {
1074
1213
  bnorm += rt1[u].re * rt1[u].re;
@@ -1092,7 +1231,7 @@ function genFalcon(opts) {
1092
1231
  }
1093
1232
  }
1094
1233
  const modqCoder = () => {
1095
- const coder = bitsCoderMSB(newPoly, N2, 14, {
1234
+ const coder = bitsCoderMSB(newPoly, N3, 14, {
1096
1235
  encode: id,
1097
1236
  decode: id
1098
1237
  });
@@ -1118,7 +1257,7 @@ function genFalcon(opts) {
1118
1257
  };
1119
1258
  const trimI8Coder = (bits) => {
1120
1259
  const shift = 32 - bits;
1121
- const coder = bitsCoderMSB((len) => new Int8Array(len), N2, bits, {
1260
+ const coder = bitsCoderMSB((len) => new Int8Array(len), N3, bits, {
1122
1261
  encode: (v) => v & (1 << bits) - 1,
1123
1262
  decode: (w) => (w & getMask(bits)) << shift >> shift
1124
1263
  });
@@ -1140,25 +1279,25 @@ function genFalcon(opts) {
1140
1279
  }
1141
1280
  };
1142
1281
  };
1143
- const fgCoder = trimI8Coder(opts.fgBits);
1144
- const FGCoder = trimI8Coder(opts.FGBits);
1282
+ const fgCoder = trimI8Coder(opts2.fgBits);
1283
+ const FGCoder = trimI8Coder(opts2.FGBits);
1145
1284
  const secretKeyCoder = headerCoder(
1146
1285
  80 + logn,
1147
1286
  splitCoder("falcon.secretKey", fgCoder, fgCoder, FGCoder)
1148
1287
  );
1149
1288
  const publicKeyCoder = headerCoder(0 + logn, modqCoder());
1150
1289
  const decodePaddedSig = (s2) => {
1151
- const normalized = compCoder(N2).encode(compCoder(N2).decode(s2));
1290
+ const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
1152
1291
  for (let i = normalized.length; i < s2.length; i++)
1153
1292
  if (s2[i] !== 0) throw new Error("non-zero padding");
1154
1293
  return normalized;
1155
1294
  };
1156
1295
  const decodeUnpaddedSig = (s2) => {
1157
- const normalized = compCoder(N2).encode(compCoder(N2).decode(s2));
1296
+ const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
1158
1297
  if (normalized.length !== s2.length) throw new Error("wrong signature length");
1159
1298
  return s2;
1160
1299
  };
1161
- const decodeSig = opts.padded ? decodePaddedSig : decodeUnpaddedSig;
1300
+ const decodeSig = opts2.padded ? decodePaddedSig : decodeUnpaddedSig;
1162
1301
  const SignatureCoderBasic = (logn2) => {
1163
1302
  const TYPE_BYTE = 32 + logn2;
1164
1303
  return {
@@ -1195,7 +1334,7 @@ function genFalcon(opts) {
1195
1334
  };
1196
1335
  };
1197
1336
  const SignatureCoderPadded = (logn2) => {
1198
- const sigLen = opts.paddedLen;
1337
+ const sigLen = opts2.paddedLen;
1199
1338
  return {
1200
1339
  encode({ msg, nonce, s2 }) {
1201
1340
  return headerCoder(
@@ -1216,19 +1355,19 @@ function genFalcon(opts) {
1216
1355
  };
1217
1356
  };
1218
1357
  const SignatureCoderDetached = (logn2) => {
1219
- const paddedSigLen = opts.sigLen - 1 - NONCELEN;
1220
- const getSigLen = (s2) => opts.padded ? paddedSigLen : s2.length;
1358
+ const paddedSigLen = opts2.sigLen - 1 - NONCELEN;
1359
+ const getSigLen = (s2) => opts2.padded ? paddedSigLen : s2.length;
1221
1360
  return {
1222
1361
  encode({ nonce, s2 }) {
1223
1362
  return headerCoder(
1224
1363
  48 + logn2,
1225
1364
  splitCoder("falcon.detachedSignature", NONCELEN, getSigLen(s2))
1226
- ).encode([nonce, opts.padded ? pad(paddedSigLen).encode(s2) : s2]);
1365
+ ).encode([nonce, opts2.padded ? pad(paddedSigLen).encode(s2) : s2]);
1227
1366
  },
1228
1367
  decode(data) {
1229
- if (!opts.padded && data.length > 1 + NONCELEN + opts.maxS2Len)
1368
+ if (!opts2.padded && data.length > 1 + NONCELEN + opts2.maxS2Len)
1230
1369
  throw new Error("detached signature too long");
1231
- const payloadLen = opts.padded ? paddedSigLen : data.length - NONCELEN - 1;
1370
+ const payloadLen = opts2.padded ? paddedSigLen : data.length - NONCELEN - 1;
1232
1371
  const [nonce, raw] = headerCoder(
1233
1372
  48 + logn2,
1234
1373
  splitCoder("falcon.detachedSignature", NONCELEN, payloadLen)
@@ -1238,10 +1377,10 @@ function genFalcon(opts) {
1238
1377
  }
1239
1378
  };
1240
1379
  };
1241
- const SignatureCoder = (opts.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn);
1380
+ const SignatureCoder = (opts2.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn);
1242
1381
  const invertF = (f) => {
1243
1382
  const tt = intPoly.ntt(signedCoder.decode(f));
1244
- for (let u = 0; u < N2; u++)
1383
+ for (let u = 0; u < N3; u++)
1245
1384
  if (tt[u] === 0) throw new Error("invalid secretKey: non-invertible f");
1246
1385
  return tt;
1247
1386
  };
@@ -1252,15 +1391,15 @@ function genFalcon(opts) {
1252
1391
  cleanBytes(tt);
1253
1392
  return res2;
1254
1393
  }
1255
- function completePrivate(f, g, F) {
1394
+ function completePrivate(f, g, F2) {
1256
1395
  let t1 = intPoly.toMontgomery(intPoly.ntt(signedCoder.decode(g)));
1257
- const t2 = intPoly.ntt(signedCoder.decode(F));
1396
+ const t2 = intPoly.ntt(signedCoder.decode(F2));
1258
1397
  const tt = invertF(f);
1259
1398
  t1 = intPoly.div(intPoly.mul(t1, t2), tt);
1260
- const G = new Int8Array(N2);
1261
- for (let u = 0; u < N2; u++) {
1399
+ const G = new Int8Array(N3);
1400
+ for (let u = 0; u < N3; u++) {
1262
1401
  let w = t1[u];
1263
- w -= Q & ~-(w - Qhalf >>> 31);
1402
+ w -= Q2 & ~-(w - Qhalf >>> 31);
1264
1403
  const gi = w | 0;
1265
1404
  if (gi < -127 || gi > 127) {
1266
1405
  cleanBytes(t1, t2, tt, G);
@@ -1273,12 +1412,12 @@ function genFalcon(opts) {
1273
1412
  }
1274
1413
  function HashToPoint(nonce, msg) {
1275
1414
  const h = shake2562.create().update(nonce).update(msg);
1276
- const c = new Uint16Array(N2);
1277
- const kQ = 5 * Q;
1278
- for (let i = 0; i < N2; ) {
1415
+ const c = new Uint16Array(N3);
1416
+ const kQ = 5 * Q2;
1417
+ for (let i = 0; i < N3; ) {
1279
1418
  const tmp = h.xof(2);
1280
1419
  let w = tmp[0] << 8 | tmp[1];
1281
- if (w < kQ) c[i++] = w % Q;
1420
+ if (w < kQ) c[i++] = w % Q2;
1282
1421
  }
1283
1422
  return c;
1284
1423
  }
@@ -1521,7 +1660,7 @@ function genFalcon(opts) {
1521
1660
  return this.ffsampRec(this.logn, t0f, t1f, this.g00, this.g01, this.g11);
1522
1661
  }
1523
1662
  }
1524
- const signRaw = (sk, msg, maxLen, rnd = randomBytes) => {
1663
+ const signRaw = (sk, msg, maxLen, rnd = randomBytes2) => {
1525
1664
  abytes2(msg, void 0, "msg");
1526
1665
  abytes2(sk, secretKeyCoder.bytesLen, "secretKey");
1527
1666
  const nonce = rnd(40);
@@ -1530,15 +1669,15 @@ function genFalcon(opts) {
1530
1669
  const seed = rnd(48);
1531
1670
  abytes2(seed, 48, "seed");
1532
1671
  try {
1533
- const [f, g, F] = secretKeyCoder.decode(sk);
1672
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1534
1673
  try {
1535
- const G = completePrivate(f, g, F);
1674
+ const G = completePrivate(f, g, F2);
1536
1675
  const b00 = floatPoly.FFT(floatPoly.convSmall(g));
1537
1676
  const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
1538
1677
  const b10 = floatPoly.FFT(floatPoly.convSmall(G));
1539
- const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F)));
1678
+ const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
1540
1679
  const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
1541
- const s2 = new Int16Array(N2);
1680
+ const s2 = new Int16Array(N3);
1542
1681
  try {
1543
1682
  while (true) {
1544
1683
  const { t0, t1 } = sampler.sample(hm);
@@ -1546,7 +1685,7 @@ function genFalcon(opts) {
1546
1685
  const t3 = floatPoly.mul(t0, b01);
1547
1686
  const t4 = floatPoly.iFFT(t2);
1548
1687
  const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
1549
- const hn = N2 >> 1;
1688
+ const hn = N3 >> 1;
1550
1689
  let sqn = 0;
1551
1690
  for (let i = 0; i < hn; i++) {
1552
1691
  sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
@@ -1560,7 +1699,7 @@ function genFalcon(opts) {
1560
1699
  }
1561
1700
  cleanCPoly(t0, t1, t2, t3, t4, t5);
1562
1701
  if (!(sqn <= L2BOUND[logn])) continue;
1563
- const s2comp = compCoder(N2).encode(s2);
1702
+ const s2comp = compCoder(N3).encode(s2);
1564
1703
  if (s2comp.length > maxLen) {
1565
1704
  cleanBytes(s2comp);
1566
1705
  continue;
@@ -1574,14 +1713,14 @@ function genFalcon(opts) {
1574
1713
  cleanBytes(G);
1575
1714
  }
1576
1715
  } finally {
1577
- cleanBytes(f, g, F);
1716
+ cleanBytes(f, g, F2);
1578
1717
  }
1579
1718
  } finally {
1580
1719
  cleanBytes(seed);
1581
1720
  }
1582
1721
  };
1583
1722
  const verifyRaw = (pk, s2comp, nonce, msg) => {
1584
- const s2 = compCoder(N2).decode(s2comp);
1723
+ const s2 = compCoder(N3).decode(s2comp);
1585
1724
  const c0 = HashToPoint(nonce, msg);
1586
1725
  const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
1587
1726
  const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
@@ -1595,54 +1734,54 @@ function genFalcon(opts) {
1595
1734
  secretKey: secretKeyCoder.bytesLen
1596
1735
  });
1597
1736
  const FALCON_SIG_OPT_KEYS = [...SIG_OPT_KEYS, "random"];
1598
- const getRnd = (opts2 = {}) => {
1599
- opts2 = validateSigOpts(opts2, FALCON_SIG_OPT_KEYS);
1600
- if (opts2.context !== void 0) throw new Error("context is not supported");
1601
- if (opts2.random !== void 0 && typeof opts2.random !== "function")
1602
- throw new TypeError('"opts.random" expected function, got type=' + typeof opts2.random);
1603
- if (opts2.random !== void 0) return opts2.random;
1604
- if (opts2.extraEntropy === void 0) return randomBytes;
1605
- const seed = opts2.extraEntropy === false ? new Uint8Array(48) : opts2.extraEntropy;
1737
+ const getRnd = (opts3 = {}) => {
1738
+ opts3 = validateSigOpts(opts3, FALCON_SIG_OPT_KEYS);
1739
+ if (opts3.context !== void 0) throw new Error("context is not supported");
1740
+ if (opts3.random !== void 0 && typeof opts3.random !== "function")
1741
+ throw new TypeError('"opts.random" expected function, got type=' + typeof opts3.random);
1742
+ if (opts3.random !== void 0) return opts3.random;
1743
+ if (opts3.extraEntropy === void 0) return randomBytes2;
1744
+ const seed = opts3.extraEntropy === false ? new Uint8Array(48) : opts3.extraEntropy;
1606
1745
  abytes2(seed, 48, "opts.extraEntropy");
1607
1746
  const drbg = rngAesCtrDrbg256(seed);
1608
1747
  return (len = 0) => drbg.randomBytes(len);
1609
1748
  };
1610
- const checkVerOpts = (opts2 = {}) => {
1611
- const normalized = validateVerOpts(opts2);
1749
+ const checkVerOpts = (opts3 = {}) => {
1750
+ const normalized = validateVerOpts(opts3);
1612
1751
  if (normalized.context !== void 0) throw new Error("context is not supported");
1613
1752
  };
1614
1753
  const tests = Object.freeze({
1615
1754
  publicKeyCoder: Object.freeze(publicKeyCoder),
1616
1755
  privateKeyCoder: Object.freeze(secretKeyCoder),
1617
- maxS2Len: opts.maxS2Len
1756
+ maxS2Len: opts2.maxS2Len
1618
1757
  });
1619
1758
  const attachedLengths = Object.freeze({ ...keyLengths, signRand: 48 });
1620
- const lengths = opts.padded ? Object.freeze({ ...attachedLengths, signature: opts.sigLen }) : attachedLengths;
1759
+ const lengths = opts2.padded ? Object.freeze({ ...attachedLengths, signature: opts2.sigLen }) : attachedLengths;
1621
1760
  const keygen = (seed) => {
1622
1761
  const randSeed = seed === void 0;
1623
- if (randSeed) seed = randomBytes(48);
1762
+ if (randSeed) seed = randomBytes2(48);
1624
1763
  abytes2(seed, 48, "seed");
1625
- const [f, g, F, _G, pub] = new NTRU(logn, seed).generate();
1626
- const sk = secretKeyCoder.encode([f, g, F]);
1764
+ const [f, g, F2, _G, pub] = new NTRU(logn, seed).generate();
1765
+ const sk = secretKeyCoder.encode([f, g, F2]);
1627
1766
  const pk = publicKeyCoder.encode(pub);
1628
1767
  if (randSeed) cleanBytes(seed);
1629
- cleanBytes(f, g, F, _G);
1768
+ cleanBytes(f, g, F2, _G);
1630
1769
  return { publicKey: pk, secretKey: sk };
1631
1770
  };
1632
1771
  const getPublicKey2 = (sk) => {
1633
1772
  abytes2(sk, secretKeyCoder.bytesLen, "secretKey");
1634
- const [f, g, F] = secretKeyCoder.decode(sk);
1773
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1635
1774
  try {
1636
1775
  const h = computePublic(f, g);
1637
- cleanBytes(f, g, F);
1776
+ cleanBytes(f, g, F2);
1638
1777
  return publicKeyCoder.encode(h);
1639
1778
  } catch (e) {
1640
- cleanBytes(f, g, F);
1779
+ cleanBytes(f, g, F2);
1641
1780
  throw e;
1642
1781
  }
1643
1782
  };
1644
1783
  const sign = (msg, sk, sigOpts = {}) => {
1645
- const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts));
1784
+ const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
1646
1785
  return SignatureCoderDetached(logn).encode({ nonce, s2 });
1647
1786
  };
1648
1787
  const verify2 = (sig, msg, pk, verOpts = {}) => {
@@ -1663,7 +1802,7 @@ function genFalcon(opts) {
1663
1802
  keygen,
1664
1803
  getPublicKey: getPublicKey2,
1665
1804
  seal(msg, sk, sigOpts = {}) {
1666
- const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts));
1805
+ const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
1667
1806
  return SignatureCoder.encode({ msg, nonce, s2 });
1668
1807
  },
1669
1808
  open(sig, pk, verOpts = {}) {
@@ -1689,30 +1828,30 @@ function genFalcon(opts) {
1689
1828
  });
1690
1829
  const INTERNAL_MAX_ITERATIONS = 1e3;
1691
1830
  const checkHashPoint = (hashPoint) => {
1692
- if (!(hashPoint instanceof Uint16Array) || hashPoint.length !== N2)
1693
- throw new Error(`hashPoint: expected Uint16Array(${N2})`);
1694
- for (let i = 0; i < N2; i++)
1695
- if (hashPoint[i] >= Q) throw new Error("hashPoint: coefficient out of range");
1831
+ if (!(hashPoint instanceof Uint16Array) || hashPoint.length !== N3)
1832
+ throw new Error(`hashPoint: expected Uint16Array(${N3})`);
1833
+ for (let i = 0; i < N3; i++)
1834
+ if (hashPoint[i] >= Q2) throw new Error("hashPoint: coefficient out of range");
1696
1835
  };
1697
1836
  const internal = Object.freeze({
1698
1837
  sign(hashPoint, sk, internalOpts = {}) {
1699
1838
  checkHashPoint(hashPoint);
1700
1839
  abytes2(sk, secretKeyCoder.bytesLen, "secretKey");
1701
- const rnd = internalOpts.random ?? randomBytes;
1840
+ const rnd = internalOpts.random ?? randomBytes2;
1702
1841
  const maxIterations = internalOpts.maxIterations ?? INTERNAL_MAX_ITERATIONS;
1703
1842
  const hm = Uint16Array.from(hashPoint);
1704
1843
  const seed = rnd(48);
1705
1844
  abytes2(seed, 48, "seed");
1706
1845
  try {
1707
- const [f, g, F] = secretKeyCoder.decode(sk);
1846
+ const [f, g, F2] = secretKeyCoder.decode(sk);
1708
1847
  try {
1709
- const G = completePrivate(f, g, F);
1848
+ const G = completePrivate(f, g, F2);
1710
1849
  const b00 = floatPoly.FFT(floatPoly.convSmall(g));
1711
1850
  const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
1712
1851
  const b10 = floatPoly.FFT(floatPoly.convSmall(G));
1713
- const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F)));
1852
+ const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
1714
1853
  const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
1715
- const s2 = new Int16Array(N2);
1854
+ const s2 = new Int16Array(N3);
1716
1855
  try {
1717
1856
  for (let iteration = 0; iteration < maxIterations; iteration++) {
1718
1857
  const { t0, t1 } = sampler.sample(hm);
@@ -1720,7 +1859,7 @@ function genFalcon(opts) {
1720
1859
  const t3 = floatPoly.mul(t0, b01);
1721
1860
  const t4 = floatPoly.iFFT(t2);
1722
1861
  const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
1723
- const hn = N2 >> 1;
1862
+ const hn = N3 >> 1;
1724
1863
  let sqn = 0;
1725
1864
  for (let i = 0; i < hn; i++) {
1726
1865
  sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
@@ -1743,7 +1882,7 @@ function genFalcon(opts) {
1743
1882
  cleanBytes(G);
1744
1883
  }
1745
1884
  } finally {
1746
- cleanBytes(f, g, F);
1885
+ cleanBytes(f, g, F2);
1747
1886
  }
1748
1887
  } finally {
1749
1888
  cleanBytes(seed);
@@ -1751,8 +1890,8 @@ function genFalcon(opts) {
1751
1890
  },
1752
1891
  verify(s2, hashPoint, pk) {
1753
1892
  checkHashPoint(hashPoint);
1754
- if (!(s2 instanceof Int16Array) || s2.length !== N2)
1755
- throw new Error(`s2: expected Int16Array(${N2})`);
1893
+ if (!(s2 instanceof Int16Array) || s2.length !== N3)
1894
+ throw new Error(`s2: expected Int16Array(${N3})`);
1756
1895
  abytes2(pk, publicKeyCoder.bytesLen, "publicKey");
1757
1896
  const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
1758
1897
  const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
@@ -1786,6 +1925,380 @@ var falcon512opts = {
1786
1925
  };
1787
1926
  var falcon512 = /* @__PURE__ */ (() => genFalcon({ ...falcon512opts, maxS2Len: 711 }))();
1788
1927
 
1928
+ // src/falcon/engine/noble/ml-kem.ts
1929
+ import { sha3_256, sha3_512, shake256 as shake2563 } from "@noble/hashes/sha3.js";
1930
+ import { swap32IfBE as swap32IfBE2, u32 as u322 } from "@noble/hashes/utils.js";
1931
+ var N2 = 256;
1932
+ var Q3 = 3329;
1933
+ var F = 3303;
1934
+ var ROOT_OF_UNITY = 17;
1935
+ var crystals = /* @__PURE__ */ genCrystals({
1936
+ N: N2,
1937
+ Q: Q3,
1938
+ F,
1939
+ ROOT_OF_UNITY,
1940
+ newPoly: (n) => new Uint16Array(n),
1941
+ brvBits: 7,
1942
+ isKyber: true
1943
+ });
1944
+ var PARAMS = /* @__PURE__ */ (() => Object.freeze({
1945
+ 512: Object.freeze({ N: N2, Q: Q3, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
1946
+ 768: Object.freeze({ N: N2, Q: Q3, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
1947
+ 1024: Object.freeze({ N: N2, Q: Q3, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
1948
+ }))();
1949
+ var compress = (d) => {
1950
+ if (d >= 12) return { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i };
1951
+ const a = 2 ** (d - 1);
1952
+ return {
1953
+ // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
1954
+ encode: (i) => ((i << d) + Q3 / 2) / Q3,
1955
+ // const decompress = (i: number) => round((Q / 2 ** d) * i);
1956
+ decode: (i) => i * Q3 + a >>> d
1957
+ };
1958
+ };
1959
+ var byteCoder = (d) => crystals.bitsCoder(
1960
+ d,
1961
+ d === 12 ? { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i } : { encode: (i) => i, decode: (i) => i }
1962
+ );
1963
+ var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d));
1964
+ function polyAdd(a_, b_) {
1965
+ const a = a_;
1966
+ const b = b_;
1967
+ for (let i = 0; i < N2; i++) {
1968
+ const r = a[i] + b[i];
1969
+ a[i] = r >= Q3 ? r - Q3 : r;
1970
+ }
1971
+ }
1972
+ function polySub(a_, b_) {
1973
+ const a = a_;
1974
+ const b = b_;
1975
+ for (let i = 0; i < N2; i++) {
1976
+ const r = a[i] - b[i];
1977
+ a[i] = r < 0 ? r + Q3 : r;
1978
+ }
1979
+ }
1980
+ function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
1981
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
1982
+ const c1 = crystals.mod(a0 * b1 + a1 * b0);
1983
+ return { c0, c1 };
1984
+ }
1985
+ function MultiplyNTTs(f_, g_) {
1986
+ const f = f_;
1987
+ const g = g_;
1988
+ for (let i = 0; i < N2 / 2; i++) {
1989
+ let z = crystals.nttZetas[64 + (i >> 1)];
1990
+ if (i & 1) z = -z;
1991
+ const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
1992
+ f[2 * i + 0] = c0;
1993
+ f[2 * i + 1] = c1;
1994
+ }
1995
+ return f;
1996
+ }
1997
+ function SampleNTT(xof_) {
1998
+ const xof = xof_;
1999
+ const r = new Uint16Array(N2);
2000
+ for (let j = 0; j < N2; ) {
2001
+ const b = xof();
2002
+ if (b.length % 3) throw new Error("SampleNTT: unaligned block");
2003
+ for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) {
2004
+ const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
2005
+ const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
2006
+ if (d1 < Q3) r[j++] = d1;
2007
+ if (j < N2 && d2 < Q3) r[j++] = d2;
2008
+ }
2009
+ }
2010
+ return r;
2011
+ }
2012
+ var sampleCBDBytes = (buf, eta) => {
2013
+ const r = new Uint16Array(N2);
2014
+ const b32 = u322(buf);
2015
+ swap32IfBE2(b32);
2016
+ let len = 0;
2017
+ for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
2018
+ let b = b32[i];
2019
+ for (let j = 0; j < 32; j++) {
2020
+ bb += b & 1;
2021
+ b >>= 1;
2022
+ len += 1;
2023
+ if (len === eta) {
2024
+ t0 = bb;
2025
+ bb = 0;
2026
+ } else if (len === 2 * eta) {
2027
+ r[p++] = crystals.mod(t0 - bb);
2028
+ bb = 0;
2029
+ len = 0;
2030
+ }
2031
+ }
2032
+ }
2033
+ swap32IfBE2(b32);
2034
+ if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);
2035
+ return r;
2036
+ };
2037
+ function sampleCBD(PRF_, seed, nonce, eta) {
2038
+ const PRF = PRF_;
2039
+ return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
2040
+ }
2041
+ var genKPKE = (opts_) => {
2042
+ const opts2 = opts_;
2043
+ const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
2044
+ const poly1 = polyCoder(1);
2045
+ const polyV = polyCoder(dv);
2046
+ const polyU = polyCoder(du);
2047
+ const publicCoder = splitCoder("publicKey", vecCoder(polyCoder(12), K), 32);
2048
+ const secretCoder = vecCoder(polyCoder(12), K);
2049
+ const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
2050
+ const seedCoder = splitCoder("seed", 32, 32);
2051
+ const encryptCore = (tHat, getA, msg, seed) => {
2052
+ const rHat = [];
2053
+ for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
2054
+ const tmp2 = new Uint16Array(N2);
2055
+ const u = [];
2056
+ for (let i = 0; i < K; i++) {
2057
+ const e1 = sampleCBD(PRF, seed, K + i, ETA2);
2058
+ const tmp = new Uint16Array(N2);
2059
+ for (let j = 0; j < K; j++) {
2060
+ const aij = getA(i, j);
2061
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
2062
+ }
2063
+ polyAdd(e1, crystals.NTT.decode(tmp));
2064
+ u.push(e1);
2065
+ polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
2066
+ cleanBytes(tmp);
2067
+ }
2068
+ const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
2069
+ polyAdd(e2, crystals.NTT.decode(tmp2));
2070
+ const v = poly1.decode(msg);
2071
+ polyAdd(v, e2);
2072
+ cleanBytes(tHat, rHat, tmp2, e2);
2073
+ return cipherCoder.encode([u, v]);
2074
+ };
2075
+ return {
2076
+ secretCoder,
2077
+ lengths: {
2078
+ secretKey: secretCoder.bytesLen,
2079
+ publicKey: publicCoder.bytesLen,
2080
+ cipherText: cipherCoder.bytesLen
2081
+ },
2082
+ keygen: (seed) => {
2083
+ abytesDoc(seed, 32, "seed");
2084
+ const seedDst = new Uint8Array(33);
2085
+ seedDst.set(seed);
2086
+ seedDst[32] = K;
2087
+ const seedHash = HASH512(seedDst);
2088
+ const [rho, sigma] = seedCoder.decode(seedHash);
2089
+ const sHat = [];
2090
+ const tHat = [];
2091
+ for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
2092
+ const x = XOF(rho);
2093
+ for (let i = 0; i < K; i++) {
2094
+ const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
2095
+ for (let j = 0; j < K; j++) {
2096
+ const aji = SampleNTT(x.get(j, i));
2097
+ polyAdd(e, MultiplyNTTs(aji, sHat[j]));
2098
+ }
2099
+ tHat.push(e);
2100
+ }
2101
+ x.clean();
2102
+ const res = {
2103
+ publicKey: publicCoder.encode([tHat, rho]),
2104
+ secretKey: secretCoder.encode(sHat)
2105
+ };
2106
+ cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
2107
+ return res;
2108
+ },
2109
+ encrypt: (publicKey, msg, seed) => {
2110
+ const [tHat, rho] = publicCoder.decode(publicKey);
2111
+ const x = XOF(rho);
2112
+ const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
2113
+ x.clean();
2114
+ return res;
2115
+ },
2116
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
2117
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
2118
+ // call because encryptCore mutates its inputs in place.
2119
+ prepare: (publicKey) => {
2120
+ const [tHat, rho] = publicCoder.decode(publicKey);
2121
+ const x = XOF(rho);
2122
+ const A = [];
2123
+ for (let i = 0; i < K; i++)
2124
+ for (let j = 0; j < K; j++) A.push(SampleNTT(x.get(i, j)));
2125
+ x.clean();
2126
+ return {
2127
+ encrypt: (msg, seed) => encryptCore(
2128
+ tHat.map((p) => p.slice()),
2129
+ (i, j) => A[i * K + j].slice(),
2130
+ msg,
2131
+ seed
2132
+ ),
2133
+ clean: () => cleanBytes(tHat, A)
2134
+ };
2135
+ },
2136
+ decrypt: (cipherText, privateKey) => {
2137
+ const [u, v] = cipherCoder.decode(cipherText);
2138
+ const sk = secretCoder.decode(privateKey);
2139
+ const tmp = new Uint16Array(N2);
2140
+ for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
2141
+ polySub(v, crystals.NTT.decode(tmp));
2142
+ const res = poly1.encode(v);
2143
+ cleanBytes(tmp, sk, u, v);
2144
+ return res;
2145
+ }
2146
+ };
2147
+ };
2148
+ function createKyber(opts2) {
2149
+ const rawOpts = opts2;
2150
+ const KPKE = genKPKE(rawOpts);
2151
+ const { HASH256, HASH512, KDF } = rawOpts;
2152
+ const { secretCoder: KPKESecretCoder, lengths } = KPKE;
2153
+ const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
2154
+ const msgLen = 32;
2155
+ const seedLen = 64;
2156
+ const validateModulus = (publicKey, fn) => {
2157
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
2158
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));
2159
+ const ok = equalBytes(ek, eke);
2160
+ cleanBytes(ek);
2161
+ if (!ok) throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
2162
+ };
2163
+ const kemLengths = Object.freeze({
2164
+ ...lengths,
2165
+ seed: 64,
2166
+ msg: msgLen,
2167
+ msgRand: msgLen,
2168
+ secretKey: secretCoder.bytesLen
2169
+ });
2170
+ return Object.freeze({
2171
+ info: Object.freeze({ type: "ml-kem" }),
2172
+ lengths: kemLengths,
2173
+ keygen: (seed) => {
2174
+ const ownSeed = seed === void 0;
2175
+ const s = ownSeed ? randomBytes(seedLen) : seed;
2176
+ let sk;
2177
+ let publicKeyHash;
2178
+ try {
2179
+ abytesDoc(s, seedLen, "seed");
2180
+ const keys = KPKE.keygen(s.subarray(0, 32));
2181
+ const publicKey = keys.publicKey;
2182
+ sk = keys.secretKey;
2183
+ publicKeyHash = HASH256(publicKey);
2184
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
2185
+ return {
2186
+ publicKey,
2187
+ secretKey
2188
+ };
2189
+ } finally {
2190
+ if (sk !== void 0) cleanBytes(sk);
2191
+ if (publicKeyHash !== void 0) cleanBytes(publicKeyHash);
2192
+ if (ownSeed) cleanBytes(s);
2193
+ }
2194
+ },
2195
+ getPublicKey: (secretKey) => {
2196
+ const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
2197
+ return Uint8Array.from(publicKey);
2198
+ },
2199
+ encapsulate: (publicKey, msg) => {
2200
+ const ownMsg = msg === void 0;
2201
+ const m = ownMsg ? randomBytes(msgLen) : msg;
2202
+ let kr;
2203
+ try {
2204
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2205
+ abytesDoc(m, msgLen, "message");
2206
+ validateModulus(publicKey, "encapsulate");
2207
+ kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
2208
+ const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
2209
+ return {
2210
+ cipherText,
2211
+ sharedSecret: kr.subarray(0, 32)
2212
+ };
2213
+ } finally {
2214
+ if (kr !== void 0) cleanBytes(kr.subarray(32));
2215
+ if (ownMsg) cleanBytes(m);
2216
+ }
2217
+ },
2218
+ decapsulate: (cipherText, secretKey) => {
2219
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2220
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2221
+ const k768 = secretCoder.bytesLen - 96;
2222
+ const start = k768 + 32;
2223
+ const test = HASH256(secretKey.subarray(k768 / 2, start));
2224
+ if (!equalBytes(test, secretKey.subarray(start, start + 32)))
2225
+ throw new Error("invalid secretKey: hash check failed");
2226
+ const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
2227
+ const msg = KPKE.decrypt(cipherText, sk);
2228
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2229
+ const Khat = kr.subarray(0, 32);
2230
+ const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
2231
+ const isValid = equalBytes(cipherText, cipherText2);
2232
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2233
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2234
+ return isValid ? Khat : Kbar;
2235
+ },
2236
+ /**
2237
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
2238
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
2239
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
2240
+ */
2241
+ prepare: (publicKey) => {
2242
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
2243
+ validateModulus(publicKey, "prepare");
2244
+ const ek = copyBytes(publicKey);
2245
+ const publicKeyHash = HASH256(ek);
2246
+ const cached = KPKE.prepare(ek);
2247
+ return Object.freeze({
2248
+ publicKey: ek,
2249
+ encapsulate: (msg) => {
2250
+ const ownMsg = msg === void 0;
2251
+ const m = ownMsg ? randomBytes(msgLen) : msg;
2252
+ let kr;
2253
+ try {
2254
+ abytesDoc(m, msgLen, "message");
2255
+ kr = HASH512.create().update(m).update(publicKeyHash).digest();
2256
+ const cipherText = cached.encrypt(m, kr.subarray(32, 64));
2257
+ return {
2258
+ cipherText,
2259
+ sharedSecret: kr.subarray(0, 32)
2260
+ };
2261
+ } finally {
2262
+ if (kr !== void 0) cleanBytes(kr.subarray(32));
2263
+ if (ownMsg) cleanBytes(m);
2264
+ }
2265
+ },
2266
+ decapsulate: (cipherText, secretKey) => {
2267
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
2268
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
2269
+ const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
2270
+ if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
2271
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
2272
+ const msg = KPKE.decrypt(cipherText, sk);
2273
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
2274
+ const Khat = kr.subarray(0, 32);
2275
+ const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
2276
+ const isValid = equalBytes(cipherText, cipherText2);
2277
+ const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
2278
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
2279
+ return isValid ? Khat : Kbar;
2280
+ },
2281
+ clean: cached.clean
2282
+ });
2283
+ }
2284
+ });
2285
+ }
2286
+ function shakePRF(dkLen, key, nonce) {
2287
+ return shake2563.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
2288
+ }
2289
+ var opts = /* @__PURE__ */ (() => ({
2290
+ HASH256: sha3_256,
2291
+ HASH512: sha3_512,
2292
+ KDF: shake2563,
2293
+ XOF: XOF128,
2294
+ PRF: shakePRF
2295
+ }))();
2296
+ var mk = (params) => createKyber({
2297
+ ...opts,
2298
+ ...params
2299
+ });
2300
+ var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
2301
+
1789
2302
  // src/falcon/engine/engine.ts
1790
2303
  var nobleEngine = Object.freeze({
1791
2304
  keygen: (seed) => falcon512.keygen(seed),
@@ -1794,16 +2307,6 @@ var nobleEngine = Object.freeze({
1794
2307
  verifyHashPoint: (s2, hashPoint, publicKey) => falcon512.internal.verify(s2, hashPoint, publicKey)
1795
2308
  });
1796
2309
 
1797
- // src/falcon/s2morrow/constants.ts
1798
- var Q2 = 12289;
1799
- var QB = 12289n;
1800
- var N = 512;
1801
- var SIG_BOUND_512 = 34034726;
1802
- var PACKED_SLOTS = 29;
1803
- var VALUES_PER_HALF = 9;
1804
- var SALT_FELTS = 2;
1805
- var SIGNATURE_FELTS = 61;
1806
-
1807
2310
  // src/falcon/s2morrow/nttRoots.ts
1808
2311
  var NTT_ROOTS_ALL = Object.freeze([
1809
2312
  1479,
@@ -2833,20 +3336,20 @@ var NTT_ROOTS_ALL = Object.freeze([
2833
3336
  // src/falcon/s2morrow/ntt.ts
2834
3337
  var I2 = 6145;
2835
3338
  var SQR1 = 1479;
2836
- var modQ = (a) => (a % Q2 + Q2) % Q2;
3339
+ var modQ = (a) => (a % Q + Q) % Q;
2837
3340
  function powMod(base, exponent) {
2838
3341
  let result = 1;
2839
3342
  let b = modQ(base);
2840
3343
  for (let e = exponent; e > 0; e >>= 1) {
2841
- if (e & 1) result = result * b % Q2;
2842
- b = b * b % Q2;
3344
+ if (e & 1) result = result * b % Q;
3345
+ b = b * b % Q;
2843
3346
  }
2844
3347
  return result;
2845
3348
  }
2846
3349
  function invMod(x) {
2847
3350
  const r = modQ(x);
2848
3351
  if (r === 0) throw new Error("Falcon512: 0 has no inverse mod q");
2849
- return powMod(r, Q2 - 2);
3352
+ return powMod(r, Q - 2);
2850
3353
  }
2851
3354
  var nttRoots = (n) => NTT_ROOTS_ALL.slice(n - 2, 2 * n - 2);
2852
3355
  function checkSize(n) {
@@ -2857,7 +3360,7 @@ function checkSize(n) {
2857
3360
  function nttRec(f) {
2858
3361
  const n = f.length;
2859
3362
  if (n === 2) {
2860
- const t = SQR1 * f[1] % Q2;
3363
+ const t = SQR1 * f[1] % Q;
2861
3364
  return [modQ(f[0] + t), modQ(f[0] - t)];
2862
3365
  }
2863
3366
  const half = n / 2;
@@ -2872,7 +3375,7 @@ function nttRec(f) {
2872
3375
  const w = nttRoots(n);
2873
3376
  const out = new Array(n);
2874
3377
  for (let i = 0; i < half; i++) {
2875
- const wb = w[2 * i] * b[i] % Q2;
3378
+ const wb = w[2 * i] * b[i] % Q;
2876
3379
  out[2 * i] = modQ(a[i] + wb);
2877
3380
  out[2 * i + 1] = modQ(a[i] - wb);
2878
3381
  }
@@ -2883,7 +3386,7 @@ function inttRec(fNtt) {
2883
3386
  if (n === 2) {
2884
3387
  const s = modQ(fNtt[0] + fNtt[1]);
2885
3388
  const d = modQ(fNtt[0] - fNtt[1]);
2886
- return [I2 * s % Q2, I2 * invMod(SQR1) % Q2 * d % Q2];
3389
+ return [I2 * s % Q, I2 * invMod(SQR1) % Q * d % Q];
2887
3390
  }
2888
3391
  const half = n / 2;
2889
3392
  const w = nttRoots(n);
@@ -2892,8 +3395,8 @@ function inttRec(fNtt) {
2892
3395
  for (let i = 0; i < half; i++) {
2893
3396
  const s = modQ(fNtt[2 * i] + fNtt[2 * i + 1]);
2894
3397
  const d = modQ(fNtt[2 * i] - fNtt[2 * i + 1]);
2895
- f0[i] = I2 * s % Q2;
2896
- f1[i] = I2 * d % Q2 * invMod(w[2 * i]) % Q2;
3398
+ f0[i] = I2 * s % Q;
3399
+ f1[i] = I2 * d % Q * invMod(w[2 * i]) % Q;
2897
3400
  }
2898
3401
  const a = inttRec(f0);
2899
3402
  const b = inttRec(f1);
@@ -2916,14 +3419,14 @@ function mulZq(a, b) {
2916
3419
  if (a.length !== b.length) throw new Error("Falcon512: polynomial sizes differ");
2917
3420
  const an = ntt(a);
2918
3421
  const bn = ntt(b);
2919
- return intt(an.map((v, i) => v * bn[i] % Q2));
3422
+ return intt(an.map((v, i) => v * bn[i] % Q));
2920
3423
  }
2921
3424
  function divZq(a, b) {
2922
3425
  if (a.length !== b.length) throw new Error("Falcon512: polynomial sizes differ");
2923
3426
  const an = ntt(a);
2924
3427
  const bn = ntt(b);
2925
3428
  if (bn.some((v) => v === 0)) throw new Error("Falcon512: polynomial is not invertible mod q");
2926
- return intt(an.map((v, i) => v * invMod(bn[i]) % Q2));
3429
+ return intt(an.map((v, i) => v * invMod(bn[i]) % Q));
2927
3430
  }
2928
3431
  function mulNegacyclicInt(a, b) {
2929
3432
  const n = a.length;
@@ -2943,22 +3446,7 @@ function mulNegacyclicInt(a, b) {
2943
3446
  }
2944
3447
 
2945
3448
  // src/falcon/s2morrow/packing.ts
2946
- import * as starknet2 from "starknet";
2947
-
2948
- // src/falcon/s2morrow/felt.ts
2949
- import * as starknet from "starknet";
2950
- function assertFelt(x, label) {
2951
- if (typeof x !== "bigint") throw new Error(`Falcon512: ${label} is not a felt252`);
2952
- starknet.CairoFelt252.assertRange(x);
2953
- }
2954
- var FELT_STRING = /^(0[xX][0-9a-fA-F]{1,64}|[0-9]{1,76})$/;
2955
- function parseFelt(value, label) {
2956
- const accepted = typeof value === "bigint" && value >= 0n || typeof value === "number" && Number.isSafeInteger(value) && value >= 0 || typeof value === "string" && FELT_STRING.test(value);
2957
- if (!accepted) throw new Error(`Falcon512: ${label} is not a felt252`);
2958
- return new starknet.CairoFelt252(value).toBigInt();
2959
- }
2960
-
2961
- // src/falcon/s2morrow/packing.ts
3449
+ import * as starknet3 from "starknet";
2962
3450
  var horner = (values, start, end) => {
2963
3451
  let acc = 0n;
2964
3452
  for (let i = end - 1; i >= start; i--) acc = acc * QB + BigInt(values[i]);
@@ -2968,7 +3456,7 @@ function packPoly(poly) {
2968
3456
  if (poly.length !== N) throw new Error(`Falcon512: polynomial must have ${N} coefficients`);
2969
3457
  for (let i = 0; i < N; i++) {
2970
3458
  const v = poly[i];
2971
- if (!Number.isInteger(v) || v < 0 || v >= Q2) {
3459
+ if (!Number.isInteger(v) || v < 0 || v >= Q) {
2972
3460
  throw new Error("Falcon512: polynomial coefficient out of range");
2973
3461
  }
2974
3462
  }
@@ -2988,7 +3476,7 @@ function unpackPoly(felts) {
2988
3476
  let idx = 0;
2989
3477
  for (const felt of felts) {
2990
3478
  assertFelt(felt, "packed polynomial slot");
2991
- for (const half of [felt & starknet2.UINT_128_MAX, felt >> 128n]) {
3479
+ for (const half of [felt & starknet3.UINT_128_MAX, felt >> 128n]) {
2992
3480
  const count = Math.min(VALUES_PER_HALF, N - idx);
2993
3481
  if (half >= QB ** BigInt(count)) {
2994
3482
  throw new Error("Falcon512: non-canonical packed polynomial");
@@ -3003,7 +3491,227 @@ function unpackPoly(felts) {
3003
3491
  return out;
3004
3492
  }
3005
3493
 
3494
+ // src/falcon/s2morrow/signature.ts
3495
+ import { randomBytes as cryptoRandomBytes } from "@noble/hashes/utils.js";
3496
+ import * as starknet5 from "starknet";
3497
+
3498
+ // src/falcon/s2morrow/hashToPoint.ts
3499
+ import { poseidonHashMany, poseidonSmall } from "@scure/starknet";
3500
+ import * as starknet4 from "starknet";
3501
+ function hashToPoint(message, salt) {
3502
+ message.forEach((m) => assertFelt(m, "message element"));
3503
+ salt.forEach((s) => assertFelt(s, "salt element"));
3504
+ const out = new Uint16Array(N);
3505
+ let idx = 0;
3506
+ const extract6 = (value) => {
3507
+ let v = value;
3508
+ for (let i = 0; i < 6 && idx < N; i++) {
3509
+ out[idx++] = Number(v % QB);
3510
+ v /= QB;
3511
+ }
3512
+ };
3513
+ const extract12 = (felt) => {
3514
+ extract6(felt & starknet4.UINT_128_MAX);
3515
+ extract6(felt >> 128n);
3516
+ };
3517
+ let state = [poseidonHashMany([...message, ...salt]), 0n, 0n];
3518
+ for (let round = 0; round < 21; round++) {
3519
+ state = poseidonSmall(state);
3520
+ extract12(state[0]);
3521
+ extract12(state[1]);
3522
+ }
3523
+ state = poseidonSmall(state);
3524
+ extract12(state[0]);
3525
+ return out;
3526
+ }
3527
+
3528
+ // src/falcon/s2morrow/signature.ts
3529
+ var defaultDeps = { engine: nobleEngine, randomBytes: cryptoRandomBytes };
3530
+ function computeMulHint(s1, pkNtt) {
3531
+ const s1Ntt = ntt(s1);
3532
+ return intt(s1Ntt.map((v, i) => v * pkNtt[i] % Q));
3533
+ }
3534
+ var centeredSquare = (x) => {
3535
+ const c = x <= (Q - 1) / 2 ? x : Q - x;
3536
+ return c * c;
3537
+ };
3538
+ function checkSignatureEquation(hashPoint, s1, mulHint, pkNtt) {
3539
+ if (hashPoint.length !== N || s1.length !== N || mulHint.length !== N || pkNtt.length !== N) {
3540
+ return false;
3541
+ }
3542
+ const s1Ntt = ntt(s1);
3543
+ const hintNtt = ntt(mulHint);
3544
+ for (let i = 0; i < N; i += 1) {
3545
+ if (s1Ntt[i] * pkNtt[i] % Q !== hintNtt[i]) return false;
3546
+ }
3547
+ let norm = 0;
3548
+ for (let i = 0; i < N; i += 1) {
3549
+ norm += centeredSquare(modQ(hashPoint[i] - mulHint[i])) + centeredSquare(s1[i]);
3550
+ }
3551
+ return norm <= SIG_BOUND_512;
3552
+ }
3553
+ function formatSignature(sig) {
3554
+ const felts = [
3555
+ ...packPoly(sig.s1),
3556
+ BigInt(sig.salt.length),
3557
+ ...sig.salt,
3558
+ ...packPoly(sig.mulHint)
3559
+ ];
3560
+ return felts.map((x) => starknet5.num.toHex(x));
3561
+ }
3562
+ function parseSignature(signature) {
3563
+ if (!Array.isArray(signature) || signature.length !== SIGNATURE_FELTS) {
3564
+ throw new Error(`Falcon512: signature must have ${SIGNATURE_FELTS} felts`);
3565
+ }
3566
+ const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3567
+ if (felts[PACKED_SLOTS] !== BigInt(SALT_FELTS)) {
3568
+ throw new Error("Falcon512: unexpected salt length");
3569
+ }
3570
+ const saltStart = PACKED_SLOTS + 1;
3571
+ return {
3572
+ s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3573
+ salt: felts.slice(saltStart, saltStart + SALT_FELTS),
3574
+ mulHint: unpackPoly(felts.slice(saltStart + SALT_FELTS))
3575
+ };
3576
+ }
3577
+ var randomSaltFelt = (randomBytes4) => BigInt(`0x${starknet5.encode.buf2hex(randomBytes4(31))}`);
3578
+ function signHash(msgHash, secretKey, pkNtt, deps = defaultDeps) {
3579
+ assertFelt(msgHash, "message hash");
3580
+ const salt = [randomSaltFelt(deps.randomBytes), randomSaltFelt(deps.randomBytes)];
3581
+ const hashPoint = hashToPoint([msgHash], salt);
3582
+ const s2 = deps.engine.signHashPoint(hashPoint, secretKey);
3583
+ const s1 = Uint16Array.from(s2, modQ);
3584
+ const mulHint = Uint16Array.from(computeMulHint(s1, pkNtt));
3585
+ const signature = formatSignature({ s1, salt, mulHint });
3586
+ const decoded = parseSignature(signature);
3587
+ if (!checkSignatureEquation(hashPoint, decoded.s1, decoded.mulHint, pkNtt)) {
3588
+ throw new Error("Falcon512: self-verification failed, signature discarded");
3589
+ }
3590
+ return signature;
3591
+ }
3592
+ function verifyHash(msgHash, signature, pkNtt) {
3593
+ let decoded;
3594
+ try {
3595
+ assertFelt(msgHash, "message hash");
3596
+ decoded = parseSignature(signature);
3597
+ } catch {
3598
+ return false;
3599
+ }
3600
+ return checkSignatureEquation(
3601
+ hashToPoint([msgHash], decoded.salt),
3602
+ decoded.s1,
3603
+ decoded.mulHint,
3604
+ pkNtt
3605
+ );
3606
+ }
3607
+
3608
+ // src/falcon/oz/hashToPoint.ts
3609
+ import { shake256 as shake2564 } from "@noble/hashes/sha3.js";
3610
+ var SALT_BYTES = 20;
3611
+ var SALT_LIMIT = 1n << BigInt(8 * SALT_BYTES);
3612
+ var KQ = 5 * Q;
3613
+ var writeLittleEndian = (x, out, offset, length) => {
3614
+ let v = x;
3615
+ for (let i = 0; i < length; i += 1) {
3616
+ out[offset + i] = Number(v & 0xffn);
3617
+ v >>= 8n;
3618
+ }
3619
+ };
3620
+ function saltFeltsToBytes(saltA, saltB) {
3621
+ [saltA, saltB].forEach((salt) => {
3622
+ if (typeof salt !== "bigint" || salt < 0n || salt >= SALT_LIMIT) {
3623
+ throw new Error("Falcon512: salt felt must be non-negative and below 2^160");
3624
+ }
3625
+ });
3626
+ const out = new Uint8Array(2 * SALT_BYTES);
3627
+ writeLittleEndian(saltA, out, 0, SALT_BYTES);
3628
+ writeLittleEndian(saltB, out, SALT_BYTES, SALT_BYTES);
3629
+ return out;
3630
+ }
3631
+ function hashToPointShake(msgHash, saltA, saltB) {
3632
+ assertFelt(msgHash, "message hash");
3633
+ const message = new Uint8Array(32);
3634
+ writeLittleEndian(msgHash, message, 0, 32);
3635
+ const xof = shake2564.create().update(saltFeltsToBytes(saltA, saltB)).update(message);
3636
+ const out = new Uint16Array(N);
3637
+ for (let i = 0; i < N; ) {
3638
+ const [high, low] = xof.xof(2);
3639
+ const word = high << 8 | low;
3640
+ if (word < KQ) {
3641
+ out[i] = word % Q;
3642
+ i += 1;
3643
+ }
3644
+ }
3645
+ return out;
3646
+ }
3647
+
3648
+ // src/falcon/oz/signature.ts
3649
+ var OZ_SIGNATURE_FELTS = Object.freeze({
3650
+ hint: 2 * PACKED_SLOTS + 2,
3651
+ direct: PACKED_SLOTS + 2
3652
+ });
3653
+ var defaultDeps2 = { engine: nobleEngine, randomBytes: cryptoRandomBytes2 };
3654
+ var readLittleEndian = (bytes) => bytes.reduceRight((acc, byte) => acc * 256n + BigInt(byte), 0n);
3655
+ function formatOzSignature(sig, variant) {
3656
+ const felts = [...packPoly(sig.s1), sig.saltA, sig.saltB];
3657
+ if (variant === "hint") {
3658
+ if (!sig.mulHint) throw new Error("Falcon512: the hint layout needs the hint polynomial");
3659
+ felts.push(...packPoly(sig.mulHint));
3660
+ }
3661
+ return felts.map((x) => starknet6.num.toHex(x));
3662
+ }
3663
+ function parseOzSignature(signature, variant) {
3664
+ const length = OZ_SIGNATURE_FELTS[variant];
3665
+ if (!Array.isArray(signature) || signature.length !== length) {
3666
+ throw new Error(`Falcon512: signature must have ${length} felts`);
3667
+ }
3668
+ const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3669
+ const saltA = felts[PACKED_SLOTS];
3670
+ const saltB = felts[PACKED_SLOTS + 1];
3671
+ saltFeltsToBytes(saltA, saltB);
3672
+ return {
3673
+ s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3674
+ saltA,
3675
+ saltB,
3676
+ mulHint: variant === "hint" ? unpackPoly(felts.slice(PACKED_SLOTS + 2)) : void 0
3677
+ };
3678
+ }
3679
+ function signHashOz(msgHash, secretKey, pkNtt, variant, deps = defaultDeps2) {
3680
+ assertFelt(msgHash, "message hash");
3681
+ const salt = deps.randomBytes(2 * SALT_BYTES);
3682
+ const saltA = readLittleEndian(salt.subarray(0, SALT_BYTES));
3683
+ const saltB = readLittleEndian(salt.subarray(SALT_BYTES));
3684
+ const hashPoint = hashToPointShake(msgHash, saltA, saltB);
3685
+ const s1 = Uint16Array.from(deps.engine.signHashPoint(hashPoint, secretKey), modQ);
3686
+ const mulHint = variant === "hint" ? Uint16Array.from(computeMulHint(s1, pkNtt)) : void 0;
3687
+ const signature = formatOzSignature({ s1, saltA, saltB, mulHint }, variant);
3688
+ const decoded = parseOzSignature(signature, variant);
3689
+ const decodedHint = decoded.mulHint ?? computeMulHint(decoded.s1, pkNtt);
3690
+ if (!checkSignatureEquation(hashPoint, decoded.s1, decodedHint, pkNtt)) {
3691
+ throw new Error("Falcon512: self-verification failed, signature discarded");
3692
+ }
3693
+ return signature;
3694
+ }
3695
+ function verifyHashOz(msgHash, signature, pkNtt, variant) {
3696
+ let decoded;
3697
+ try {
3698
+ assertFelt(msgHash, "message hash");
3699
+ decoded = parseOzSignature(signature, variant);
3700
+ } catch {
3701
+ return false;
3702
+ }
3703
+ const mulHint = decoded.mulHint ?? computeMulHint(decoded.s1, pkNtt);
3704
+ return checkSignatureEquation(
3705
+ hashToPointShake(msgHash, decoded.saltA, decoded.saltB),
3706
+ decoded.s1,
3707
+ mulHint,
3708
+ pkNtt
3709
+ );
3710
+ }
3711
+
3006
3712
  // src/falcon/s2morrow/keys.ts
3713
+ import { isBytes as isBytes2 } from "@noble/hashes/utils.js";
3714
+ import * as starknet7 from "starknet";
3007
3715
  var SECRET_KEY_LENGTH = 1281;
3008
3716
  var PUBLIC_KEY_LENGTH = 897;
3009
3717
  var SEED_LENGTH = 48;
@@ -3026,7 +3734,7 @@ function toBytes(input, expectedLength, label) {
3026
3734
  if (typeof input !== "string") {
3027
3735
  throw new Error(`Falcon512: ${label} must be a Uint8Array or a hex string`);
3028
3736
  }
3029
- const hex = starknet3.encode.removeHexPrefix(input);
3737
+ const hex = starknet7.encode.removeHexPrefix(input);
3030
3738
  if (!/^[0-9a-fA-F]*$/.test(hex)) {
3031
3739
  throw new Error(`Falcon512: ${label} is not a valid hex string`);
3032
3740
  }
@@ -3035,12 +3743,12 @@ function toBytes(input, expectedLength, label) {
3035
3743
  `Falcon512: ${label} must have ${2 * expectedLength} hex digits, got ${hex.length}`
3036
3744
  );
3037
3745
  }
3038
- return starknet3.num.hexToBytes(starknet3.encode.addHexPrefix(hex));
3746
+ return starknet7.num.hexToBytes(starknet7.encode.addHexPrefix(hex));
3039
3747
  }
3040
3748
  var wipe = (...arrays) => {
3041
3749
  arrays.forEach((a) => a.fill(0));
3042
3750
  };
3043
- var center = (x) => x > Q2 >> 1 ? x - Q2 : x;
3751
+ var center = (x) => x > Q >> 1 ? x - Q : x;
3044
3752
  var toSigned = (raw, bits) => raw << 32 - bits >> 32 - bits;
3045
3753
  function encodeBitsMSB(values, bits) {
3046
3754
  const out = new Uint8Array(values.length * bits / 8);
@@ -3106,7 +3814,7 @@ function decode14LSB(bytes) {
3106
3814
  const v = acc & 16383;
3107
3815
  acc >>>= 14;
3108
3816
  accBits -= 14;
3109
- if (v >= Q2) {
3817
+ if (v >= Q) {
3110
3818
  throw new Error("Falcon512: invalid falcon-rs secret key (coefficient out of range)");
3111
3819
  }
3112
3820
  out.push(v);
@@ -3124,8 +3832,8 @@ function checkRange(poly, max, label) {
3124
3832
  }
3125
3833
  }
3126
3834
  }
3127
- function completeG(f, g, F) {
3128
- const gF = mulZq(g, F);
3835
+ function completeG(f, g, F2) {
3836
+ const gF = mulZq(g, F2);
3129
3837
  let quotient = [];
3130
3838
  let G = [];
3131
3839
  try {
@@ -3137,12 +3845,12 @@ function completeG(f, g, F) {
3137
3845
  wipe(gF, quotient, G);
3138
3846
  }
3139
3847
  }
3140
- function checkNtruEquation({ f, g, F, G }) {
3848
+ function checkNtruEquation({ f, g, F: F2, G }) {
3141
3849
  const fG = mulNegacyclicInt(f, G);
3142
- const gF = mulNegacyclicInt(g, F);
3850
+ const gF = mulNegacyclicInt(g, F2);
3143
3851
  try {
3144
3852
  for (let i = 0; i < N; i++) {
3145
- if (fG[i] - gF[i] !== (i === 0 ? Q2 : 0)) {
3853
+ if (fG[i] - gF[i] !== (i === 0 ? Q : 0)) {
3146
3854
  throw new Error("Falcon512: invalid secret key (NTRU equation not satisfied)");
3147
3855
  }
3148
3856
  }
@@ -3174,11 +3882,11 @@ function decodeSecretKey(secretKey) {
3174
3882
  parts.push(f);
3175
3883
  const g = decodeSigned(bytes.subarray(1 + FG_BYTES, 1 + 2 * FG_BYTES), FG_BITS, "g");
3176
3884
  parts.push(g);
3177
- const F = decodeSigned(bytes.subarray(1 + 2 * FG_BYTES), CAPITAL_FG_BITS, "F");
3178
- parts.push(F);
3179
- const G = completeG(f, g, F);
3885
+ const F2 = decodeSigned(bytes.subarray(1 + 2 * FG_BYTES), CAPITAL_FG_BITS, "F");
3886
+ parts.push(F2);
3887
+ const G = completeG(f, g, F2);
3180
3888
  parts.push(G);
3181
- const polys = { f, g, F, G };
3889
+ const polys = { f, g, F: F2, G };
3182
3890
  checkNtruEquation(polys);
3183
3891
  return polys;
3184
3892
  } catch (error) {
@@ -3188,13 +3896,13 @@ function decodeSecretKey(secretKey) {
3188
3896
  wipe(bytes);
3189
3897
  }
3190
3898
  }
3191
- function encodeSecretKey({ f, g, F }) {
3899
+ function encodeSecretKey({ f, g, F: F2 }) {
3192
3900
  checkRange(f, FG_MAX, "f");
3193
3901
  checkRange(g, FG_MAX, "g");
3194
- checkRange(F, CAPITAL_FG_MAX, "F");
3902
+ checkRange(F2, CAPITAL_FG_MAX, "F");
3195
3903
  const fBits = Array.from(f, (v) => v & 63);
3196
3904
  const gBits = Array.from(g, (v) => v & 63);
3197
- const capitalFBits = Array.from(F, (v) => v & 255);
3905
+ const capitalFBits = Array.from(F2, (v) => v & 255);
3198
3906
  const encoded = [
3199
3907
  encodeBitsMSB(fBits, FG_BITS),
3200
3908
  encodeBitsMSB(gBits, FG_BITS),
@@ -3215,7 +3923,7 @@ function decodePublicKey(publicKey) {
3215
3923
  const bytes = toBytes(publicKey, PUBLIC_KEY_LENGTH, "public key");
3216
3924
  if (bytes[0] !== PUBLIC_KEY_HEADER) throw new Error("Falcon512: invalid public key header");
3217
3925
  const h = decodeBitsMSB(bytes.subarray(1), N, 14);
3218
- if (h.some((v) => v >= Q2)) {
3926
+ if (h.some((v) => v >= Q)) {
3219
3927
  throw new Error("Falcon512: invalid public key (coefficient out of range)");
3220
3928
  }
3221
3929
  return Uint16Array.from(h);
@@ -3225,7 +3933,7 @@ function encodePublicKey(h) {
3225
3933
  throw new Error(`Falcon512: public key polynomial must have ${N} coefficients`);
3226
3934
  }
3227
3935
  for (let i = 0; i < N; i++) {
3228
- if (!Number.isInteger(h[i]) || h[i] < 0 || h[i] >= Q2) {
3936
+ if (!Number.isInteger(h[i]) || h[i] < 0 || h[i] >= Q) {
3229
3937
  throw new Error("Falcon512: invalid public key (coefficient out of range)");
3230
3938
  }
3231
3939
  }
@@ -3252,14 +3960,14 @@ function publicKeyToNtt(publicKey) {
3252
3960
  return Uint16Array.from(ntt(decodePublicKey(publicKey)));
3253
3961
  }
3254
3962
  function getPackedPublicKey(publicKey) {
3255
- return packPoly(publicKeyToNtt(publicKey)).map((x) => starknet3.num.toHex(x));
3963
+ return packPoly(publicKeyToNtt(publicKey)).map((x) => starknet7.num.toHex(x));
3256
3964
  }
3257
3965
  function importFalconRsSecretKey(secretKey) {
3258
3966
  const bytes = toBytes(secretKey, FALCON_RS_SECRET_KEY_LENGTH, "falcon-rs secret key");
3259
3967
  const parts = [];
3260
3968
  try {
3261
3969
  const names = ["f", "g", "F", "G"];
3262
- const [f, g, F, G] = names.map((name, k) => {
3970
+ const [f, g, F2, G] = names.map((name, k) => {
3263
3971
  const chunk = bytes.subarray(k * FALCON_RS_POLY_LENGTH, (k + 1) * FALCON_RS_POLY_LENGTH);
3264
3972
  const decoded = decode14LSB(chunk);
3265
3973
  parts.push(decoded);
@@ -3270,13 +3978,13 @@ function importFalconRsSecretKey(secretKey) {
3270
3978
  parts.push(p);
3271
3979
  return p;
3272
3980
  });
3273
- const recomputed = completeG(f, g, F);
3981
+ const recomputed = completeG(f, g, F2);
3274
3982
  parts.push(recomputed);
3275
3983
  if (recomputed.some((v, i) => v !== G[i])) {
3276
3984
  throw new Error("Falcon512: invalid falcon-rs secret key (G does not match f, g, F)");
3277
3985
  }
3278
- checkNtruEquation({ f, g, F, G });
3279
- return encodeSecretKey({ f, g, F });
3986
+ checkNtruEquation({ f, g, F: F2, G });
3987
+ return encodeSecretKey({ f, g, F: F2 });
3280
3988
  } finally {
3281
3989
  wipe(bytes, ...parts);
3282
3990
  }
@@ -3298,144 +4006,35 @@ function exportFalconRsSecretKey(secretKey) {
3298
4006
  }
3299
4007
  }
3300
4008
 
3301
- // src/falcon/s2morrow/signature.ts
3302
- import { randomBytes as cryptoRandomBytes } from "@noble/hashes/utils.js";
3303
- import * as starknet5 from "starknet";
3304
-
3305
- // src/falcon/s2morrow/hashToPoint.ts
3306
- import { poseidonHashMany, poseidonSmall } from "@scure/starknet";
3307
- import * as starknet4 from "starknet";
3308
- function hashToPoint(message, salt) {
3309
- message.forEach((m) => assertFelt(m, "message element"));
3310
- salt.forEach((s) => assertFelt(s, "salt element"));
3311
- const out = new Uint16Array(N);
3312
- let idx = 0;
3313
- const extract6 = (value) => {
3314
- let v = value;
3315
- for (let i = 0; i < 6 && idx < N; i++) {
3316
- out[idx++] = Number(v % QB);
3317
- v /= QB;
3318
- }
3319
- };
3320
- const extract12 = (felt) => {
3321
- extract6(felt & starknet4.UINT_128_MAX);
3322
- extract6(felt >> 128n);
3323
- };
3324
- let state = [poseidonHashMany([...message, ...salt]), 0n, 0n];
3325
- for (let round = 0; round < 21; round++) {
3326
- state = poseidonSmall(state);
3327
- extract12(state[0]);
3328
- extract12(state[1]);
3329
- }
3330
- state = poseidonSmall(state);
3331
- extract12(state[0]);
3332
- return out;
3333
- }
3334
-
3335
- // src/falcon/s2morrow/signature.ts
3336
- var defaultDeps = { engine: nobleEngine, randomBytes: cryptoRandomBytes };
3337
- function computeMulHint(s1, pkNtt) {
3338
- const s1Ntt = ntt(s1);
3339
- return intt(s1Ntt.map((v, i) => v * pkNtt[i] % Q2));
3340
- }
3341
- var centeredSquare = (x) => {
3342
- const c = x <= (Q2 - 1) / 2 ? x : Q2 - x;
3343
- return c * c;
3344
- };
3345
- function checkSignatureEquation(hashPoint, s1, mulHint, pkNtt) {
3346
- if (hashPoint.length !== N || s1.length !== N || mulHint.length !== N || pkNtt.length !== N) {
3347
- return false;
3348
- }
3349
- const s1Ntt = ntt(s1);
3350
- const hintNtt = ntt(mulHint);
3351
- for (let i = 0; i < N; i += 1) {
3352
- if (s1Ntt[i] * pkNtt[i] % Q2 !== hintNtt[i]) return false;
3353
- }
3354
- let norm = 0;
3355
- for (let i = 0; i < N; i += 1) {
3356
- norm += centeredSquare(modQ(hashPoint[i] - mulHint[i])) + centeredSquare(s1[i]);
3357
- }
3358
- return norm <= SIG_BOUND_512;
3359
- }
3360
- function formatSignature(sig) {
3361
- const felts = [
3362
- ...packPoly(sig.s1),
3363
- BigInt(sig.salt.length),
3364
- ...sig.salt,
3365
- ...packPoly(sig.mulHint)
3366
- ];
3367
- return felts.map((x) => starknet5.num.toHex(x));
3368
- }
3369
- function parseSignature(signature) {
3370
- if (!Array.isArray(signature) || signature.length !== SIGNATURE_FELTS) {
3371
- throw new Error(`Falcon512: signature must have ${SIGNATURE_FELTS} felts`);
3372
- }
3373
- const felts = signature.map((x, i) => parseFelt(x, `signature[${i}]`));
3374
- if (felts[PACKED_SLOTS] !== BigInt(SALT_FELTS)) {
3375
- throw new Error("Falcon512: unexpected salt length");
3376
- }
3377
- const saltStart = PACKED_SLOTS + 1;
3378
- return {
3379
- s1: unpackPoly(felts.slice(0, PACKED_SLOTS)),
3380
- salt: felts.slice(saltStart, saltStart + SALT_FELTS),
3381
- mulHint: unpackPoly(felts.slice(saltStart + SALT_FELTS))
3382
- };
3383
- }
3384
- var randomSaltFelt = (randomBytes2) => BigInt(`0x${starknet5.encode.buf2hex(randomBytes2(31))}`);
3385
- function signHash(msgHash, secretKey, pkNtt, deps = defaultDeps) {
3386
- assertFelt(msgHash, "message hash");
3387
- const salt = [randomSaltFelt(deps.randomBytes), randomSaltFelt(deps.randomBytes)];
3388
- const hashPoint = hashToPoint([msgHash], salt);
3389
- const s2 = deps.engine.signHashPoint(hashPoint, secretKey);
3390
- const s1 = Uint16Array.from(s2, modQ);
3391
- const mulHint = Uint16Array.from(computeMulHint(s1, pkNtt));
3392
- const signature = formatSignature({ s1, salt, mulHint });
3393
- const decoded = parseSignature(signature);
3394
- if (!checkSignatureEquation(hashPoint, decoded.s1, decoded.mulHint, pkNtt)) {
3395
- throw new Error("Falcon512: self-verification failed, signature discarded");
3396
- }
3397
- return signature;
3398
- }
3399
- function verifyHash(msgHash, signature, pkNtt) {
3400
- let decoded;
3401
- try {
3402
- assertFelt(msgHash, "message hash");
3403
- decoded = parseSignature(signature);
3404
- } catch {
3405
- return false;
3406
- }
3407
- return checkSignatureEquation(
3408
- hashToPoint([msgHash], decoded.salt),
3409
- decoded.s1,
3410
- decoded.mulHint,
3411
- pkNtt
3412
- );
3413
- }
3414
-
3415
4009
  // src/falcon/Falcon512Signer.ts
3416
4010
  function assertV3(details) {
3417
- if (!starknet6.isV3Tx(details)) throw new Error("Falcon512: only V3 transactions are supported");
4011
+ if (!starknet8.isV3Tx(details)) throw new Error("Falcon512: only V3 transactions are supported");
3418
4012
  }
3419
4013
  var Falcon512Signer = class _Falcon512Signer {
3420
4014
  #secretKey;
3421
4015
  #publicKey;
3422
4016
  #pkNtt;
3423
4017
  #packedPublicKey;
4018
+ #accountType;
3424
4019
  /**
3425
4020
  * Builds a signer from a NIST Falcon-512 secret key. The key is fully checked, then copied: the
3426
4021
  * signer keeps its own copy, in a private field.
3427
4022
  * @param {Uint8Array | string} secretKey NIST Falcon-512 secret key (1281 bytes), Uint8Array or
3428
4023
  * hex string. Prefer a Uint8Array: a string cannot be wiped from memory.
3429
- * @throws {Error} when the secret key is invalid
4024
+ * @param {Falcon512Options} [options] `accountType`: the type of the account that checks the
4025
+ * signatures, `'s2morrow'` (default), `'oz-hint'` or `'oz-direct'`
4026
+ * @throws {Error} when the secret key or an option is invalid
3430
4027
  * @example
3431
4028
  * ```typescript
3432
4029
  * const { secretKey } = falcon512.generateKeyPair();
3433
- * const mySigner = new Falcon512Signer(secretKey);
4030
+ * const mySigner = new Falcon512Signer(secretKey); // for an S2morrow account
4031
+ * const myOzSigner = new Falcon512Signer(secretKey, { accountType: 'oz-hint' });
3434
4032
  * new Falcon512Signer(new Uint8Array(1281));
3435
4033
  * // throws Error("Falcon512: invalid secret key header")
3436
4034
  * ```
3437
4035
  */
3438
- constructor(secretKey) {
4036
+ constructor(secretKey, options) {
4037
+ const accountType = parseFalconOptions(options);
3439
4038
  const bytes = toBytes(secretKey, SECRET_KEY_LENGTH, "secret key");
3440
4039
  let publicKey;
3441
4040
  try {
@@ -3444,6 +4043,7 @@ var Falcon512Signer = class _Falcon512Signer {
3444
4043
  bytes.fill(0);
3445
4044
  throw error;
3446
4045
  }
4046
+ this.#accountType = accountType;
3447
4047
  this.#publicKey = publicKey;
3448
4048
  this.#secretKey = bytes;
3449
4049
  this.#pkNtt = publicKeyToNtt(this.#publicKey);
@@ -3455,10 +4055,12 @@ var Falcon512Signer = class _Falcon512Signer {
3455
4055
  * Warning: falcon-rs derives the seed of its sampler from the public salt of each signature, so
3456
4056
  * the signatures it produced may leak information about the secret key. Use this for continuity
3457
4057
  * only; for real funds, generate a new key with `falcon512.generateKeyPair`. The S2morrow account
3458
- * cannot change its key: a new key means a new account.
4058
+ * cannot change its key: a new key means a new account. An OpenZeppelin account can change its
4059
+ * key (see `signOwnershipAcceptance`).
3459
4060
  * @param {Uint8Array | string} secretKey the falcon-rs secret key (3584 bytes), or its hex string
4061
+ * @param {Falcon512Options} [options] `accountType`, as for the constructor
3460
4062
  * @returns {Falcon512Signer} a signer that holds the same key, in the NIST format
3461
- * @throws {Error} when the falcon-rs secret key is invalid
4063
+ * @throws {Error} when the falcon-rs secret key or an option is invalid
3462
4064
  * @example
3463
4065
  * ```typescript
3464
4066
  * const mySigner = Falcon512Signer.fromFalconRs(falconRsSecretKey); // 3584 bytes, from falcon-rs
@@ -3466,10 +4068,10 @@ var Falcon512Signer = class _Falcon512Signer {
3466
4068
  * // result = ['0xb2cf4f8b3c6f60cc662f438970ad34017e260c52d7911297a42811ce3cea2b', …] (29 felts)
3467
4069
  * ```
3468
4070
  */
3469
- static fromFalconRs(secretKey) {
4071
+ static fromFalconRs(secretKey, options) {
3470
4072
  const nist = importFalconRsSecretKey(secretKey);
3471
4073
  try {
3472
- return new _Falcon512Signer(nist);
4074
+ return new _Falcon512Signer(nist, options);
3473
4075
  } finally {
3474
4076
  nist.fill(0);
3475
4077
  }
@@ -3486,10 +4088,12 @@ var Falcon512Signer = class _Falcon512Signer {
3486
4088
  * ```
3487
4089
  */
3488
4090
  async getPubKey() {
3489
- return starknet6.encode.addHexPrefix(starknet6.encode.buf2hex(this.#publicKey));
4091
+ return starknet8.encode.addHexPrefix(starknet8.encode.buf2hex(this.#publicKey));
3490
4092
  }
3491
4093
  /**
3492
- * The 29 felts of the account constructor argument `pk_packed`.
4094
+ * The 29 felts of the public key, in the form the accounts store it: the constructor argument
4095
+ * `pk_packed` of S2morrow, or the `public_key` array of an OpenZeppelin account (whose
4096
+ * constructor calldata is `29`, then these 29 felts). The same for the three account types.
3493
4097
  * @returns {string[]} the 29 felts, as hex strings (a new array at each call)
3494
4098
  * @example
3495
4099
  * ```typescript
@@ -3506,21 +4110,23 @@ var Falcon512Signer = class _Falcon512Signer {
3506
4110
  * Signs a SNIP-12 message (TypedData) for off-chain use.
3507
4111
  * @param {TypedData} typedData the message to sign
3508
4112
  * @param {string} accountAddress address of the account that signs the message
3509
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4113
+ * @returns {Promise<Signature>} the signature, as hex strings: 61 felts (S2morrow), 60
4114
+ * (OpenZeppelin, hint) or 31 (OpenZeppelin, direct)
3510
4115
  * @example
3511
4116
  * ```typescript
3512
4117
  * const result = await mySigner.signMessage(myTypedData, accountAddress);
3513
- * // result = ['0x…', …] (61 felts, random salt); result[29] = '0x2' (salt length)
4118
+ * // result = ['0x…', …] (S2morrow: 61 felts, random salt); result[29] = '0x2' (salt length)
3514
4119
  * ```
3515
4120
  */
3516
4121
  async signMessage(typedData3, accountAddress) {
3517
- return this.signRaw(starknet6.typedData.getMessageHash(typedData3, accountAddress));
4122
+ return this.signRaw(starknet8.typedData.getMessageHash(typedData3, accountAddress));
3518
4123
  }
3519
4124
  /**
3520
4125
  * Signs an INVOKE transaction (V3 only).
3521
4126
  * @param {Call[]} transactions the calls of the transaction
3522
4127
  * @param {InvocationsSignerDetails} details the details needed to hash the transaction
3523
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4128
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4129
+ * the account type
3524
4130
  * @throws {Error} when the transaction is not V3
3525
4131
  * @example
3526
4132
  * ```typescript
@@ -3549,29 +4155,30 @@ var Falcon512Signer = class _Falcon512Signer {
3549
4155
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3550
4156
  * };
3551
4157
  * const result = await mySigner.signTransaction(calls, details);
3552
- * // result = ['0x…', …] (61 felts)
4158
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3553
4159
  * ```
3554
4160
  */
3555
4161
  async signTransaction(transactions, details) {
3556
4162
  assertV3(details);
3557
- const compiledCalldata = starknet6.transaction.getExecuteCalldata(
4163
+ const compiledCalldata = starknet8.transaction.getExecuteCalldata(
3558
4164
  transactions,
3559
4165
  details.cairoVersion
3560
4166
  );
3561
- const msgHash = starknet6.hash.calculateInvokeTransactionHash({
4167
+ const msgHash = starknet8.hash.calculateInvokeTransactionHash({
3562
4168
  ...details,
3563
4169
  senderAddress: details.walletAddress,
3564
4170
  compiledCalldata,
3565
4171
  version: details.version,
3566
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3567
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4172
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4173
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3568
4174
  });
3569
4175
  return this.signRaw(msgHash);
3570
4176
  }
3571
4177
  /**
3572
4178
  * Signs the DEPLOY_ACCOUNT transaction of a Falcon-512 account (V3 only).
3573
4179
  * @param {DeployAccountSignerDetails} details the details needed to hash the transaction
3574
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4180
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4181
+ * the account type
3575
4182
  * @throws {Error} when the transaction is not V3
3576
4183
  * @example
3577
4184
  * ```typescript
@@ -3598,26 +4205,27 @@ var Falcon512Signer = class _Falcon512Signer {
3598
4205
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3599
4206
  * };
3600
4207
  * const result = await mySigner.signDeployAccountTransaction(details);
3601
- * // result = ['0x…', …] (61 felts)
4208
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3602
4209
  * ```
3603
4210
  */
3604
4211
  async signDeployAccountTransaction(details) {
3605
4212
  assertV3(details);
3606
- const compiledConstructorCalldata = starknet6.CallData.compile(details.constructorCalldata);
3607
- const msgHash = starknet6.hash.calculateDeployAccountTransactionHash({
4213
+ const compiledConstructorCalldata = starknet8.CallData.compile(details.constructorCalldata);
4214
+ const msgHash = starknet8.hash.calculateDeployAccountTransactionHash({
3608
4215
  ...details,
3609
4216
  salt: details.addressSalt,
3610
4217
  compiledConstructorCalldata,
3611
4218
  version: details.version,
3612
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3613
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4219
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4220
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3614
4221
  });
3615
4222
  return this.signRaw(msgHash);
3616
4223
  }
3617
4224
  /**
3618
4225
  * Signs a DECLARE transaction (V3 only).
3619
4226
  * @param {DeclareSignerDetails} details the details needed to hash the transaction
3620
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4227
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4228
+ * the account type
3621
4229
  * @throws {Error} when the transaction is not V3
3622
4230
  * @example
3623
4231
  * ```typescript
@@ -3640,24 +4248,75 @@ var Falcon512Signer = class _Falcon512Signer {
3640
4248
  * feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
3641
4249
  * };
3642
4250
  * const result = await mySigner.signDeclareTransaction(details);
3643
- * // result = ['0x…', …] (61 felts)
4251
+ * // result = ['0x…', …] (S2morrow: 61 felts)
3644
4252
  * ```
3645
4253
  */
3646
4254
  async signDeclareTransaction(details) {
3647
4255
  assertV3(details);
3648
- const msgHash = starknet6.hash.calculateDeclareTransactionHash({
4256
+ const msgHash = starknet8.hash.calculateDeclareTransactionHash({
3649
4257
  ...details,
3650
4258
  version: details.version,
3651
- nonceDataAvailabilityMode: starknet6.stark.intDAM(details.nonceDataAvailabilityMode),
3652
- feeDataAvailabilityMode: starknet6.stark.intDAM(details.feeDataAvailabilityMode)
4259
+ nonceDataAvailabilityMode: starknet8.stark.intDAM(details.nonceDataAvailabilityMode),
4260
+ feeDataAvailabilityMode: starknet8.stark.intDAM(details.feeDataAvailabilityMode)
3653
4261
  });
3654
4262
  return this.signRaw(msgHash);
3655
4263
  }
3656
4264
  /**
3657
- * Signs a hash: the last step of all the methods above. It stays protected, so that no public
3658
- * method signs an arbitrary hash. A subclass can override it, as for every starknet.js signer.
4265
+ * Signs the acceptance of a key change of an OpenZeppelin Falcon-512 account.
4266
+ *
4267
+ * The account changes its key when it calls its own `set_public_key(new_public_key, signature)`:
4268
+ * the current key signs that transaction, as any other, and the new key must sign an acceptance.
4269
+ * Call this method on the signer of the new key, with the key that the account holds now. The
4270
+ * signed hash is Poseidon('StarkNet Message', 'accept_ownership', account address,
4271
+ * Poseidon(current key)). It holds no chain id, nonce or expiry: an acceptance is not single-use,
4272
+ * and the current key must still sign each key change.
4273
+ * @param {BigNumberish} accountAddress the address of the account
4274
+ * @param {BigNumberish[]} currentPublicKey the 29 felts of the key that the account holds now
4275
+ * (`getPackedPublicKey()` of its current signer, or its `get_public_key`)
4276
+ * @returns {Promise<string[]>} the acceptance, as hex strings, in the layout of this signer: 60
4277
+ * felts (`'oz-hint'`) or 31 (`'oz-direct'`)
4278
+ * @throws {Error} for an S2morrow signer (that account cannot change its key), or when the
4279
+ * current key has neither 29 felts nor none, or a value is not a felt252. Also when a subclass
4280
+ * makes `signRaw` return something else than an array of felts
4281
+ * @example
4282
+ * ```typescript
4283
+ * const newSigner = new Falcon512Signer(newSecretKey, { accountType: 'oz-hint' });
4284
+ * const acceptance = await newSigner.signOwnershipAcceptance(
4285
+ * falconAccount.address,
4286
+ * currentSigner.getPackedPublicKey()
4287
+ * );
4288
+ * const { transaction_hash } = await falconAccount.execute(
4289
+ * {
4290
+ * contractAddress: falconAccount.address,
4291
+ * entrypoint: 'set_public_key',
4292
+ * calldata: CallData.compile({
4293
+ * new_public_key: newSigner.getPackedPublicKey(),
4294
+ * signature: acceptance,
4295
+ * }),
4296
+ * },
4297
+ * { skipValidate: false }
4298
+ * );
4299
+ * await myProvider.waitForTransaction(transaction_hash);
4300
+ * // From now on, the account checks the signatures of newSigner.
4301
+ * ```
4302
+ */
4303
+ async signOwnershipAcceptance(accountAddress, currentPublicKey) {
4304
+ if (this.#accountType === "s2morrow") {
4305
+ throw new Error("Falcon512: an S2morrow account cannot change its key");
4306
+ }
4307
+ const signature = await this.signRaw(ownershipAcceptanceHash(accountAddress, currentPublicKey));
4308
+ if (!Array.isArray(signature)) {
4309
+ throw new Error("Falcon512: signRaw must return an array of felts");
4310
+ }
4311
+ return signature;
4312
+ }
4313
+ /**
4314
+ * Signs a hash: the last step of all the methods above, in the layout of the account type. It
4315
+ * stays protected, so that no public method signs an arbitrary hash. A subclass can override it,
4316
+ * as for every starknet.js signer.
3659
4317
  * @param {string} msgHash the hash to sign, a felt252
3660
- * @returns {Promise<Signature>} the 61 felts of the signature, as hex strings
4318
+ * @returns {Promise<Signature>} the signature, as hex strings: 61, 60 or 31 felts, according to
4319
+ * the account type
3661
4320
  * @example
3662
4321
  * ```typescript
3663
4322
  * class LoggedFalconSigner extends Falcon512Signer {
@@ -3671,7 +4330,15 @@ var Falcon512Signer = class _Falcon512Signer {
3671
4330
  * ```
3672
4331
  */
3673
4332
  async signRaw(msgHash) {
3674
- return signHash(starknet6.num.toBigInt(msgHash), this.#secretKey, this.#pkNtt);
4333
+ const value = starknet8.num.toBigInt(msgHash);
4334
+ switch (this.#accountType) {
4335
+ case "oz-hint":
4336
+ return signHashOz(value, this.#secretKey, this.#pkNtt, "hint");
4337
+ case "oz-direct":
4338
+ return signHashOz(value, this.#secretKey, this.#pkNtt, "direct");
4339
+ default:
4340
+ return signHash(value, this.#secretKey, this.#pkNtt);
4341
+ }
3675
4342
  }
3676
4343
  };
3677
4344
 
@@ -3688,7 +4355,7 @@ __export(falcon512_exports, {
3688
4355
  });
3689
4356
 
3690
4357
  // src/falcon/verify.ts
3691
- import * as starknet7 from "starknet";
4358
+ import * as starknet9 from "starknet";
3692
4359
  function toMessageHash(value) {
3693
4360
  try {
3694
4361
  return parseFelt(value, "message hash");
@@ -3696,28 +4363,279 @@ function toMessageHash(value) {
3696
4363
  return void 0;
3697
4364
  }
3698
4365
  }
3699
- function verify(signature, msgHash, fullPublicKey) {
3700
- const pkNtt = publicKeyToNtt(fullPublicKey);
4366
+ function toPkNtt(fullPublicKey) {
4367
+ if (Array.isArray(fullPublicKey)) {
4368
+ if (fullPublicKey.length !== PACKED_SLOTS) {
4369
+ throw new Error(`Falcon512: packed public key must have ${PACKED_SLOTS} felts`);
4370
+ }
4371
+ return unpackPoly(fullPublicKey.map((x, i) => parseFelt(x, `public key[${i}]`)));
4372
+ }
4373
+ return publicKeyToNtt(fullPublicKey);
4374
+ }
4375
+ function verify(signature, msgHash, fullPublicKey, options) {
4376
+ const accountType = parseFalconOptions(options);
4377
+ const pkNtt = toPkNtt(fullPublicKey);
3701
4378
  const h = toMessageHash(msgHash);
3702
4379
  if (h === void 0 || !Array.isArray(signature)) return false;
3703
- return verifyHash(h, signature, pkNtt);
4380
+ switch (accountType) {
4381
+ case "oz-hint":
4382
+ return verifyHashOz(h, signature, pkNtt, "hint");
4383
+ case "oz-direct":
4384
+ return verifyHashOz(h, signature, pkNtt, "direct");
4385
+ default:
4386
+ return verifyHash(h, signature, pkNtt);
4387
+ }
3704
4388
  }
3705
- function verifyMessage(message, signature, fullPublicKey, accountAddress) {
4389
+ function verifyMessage(message, signature, fullPublicKey, accountAddressOrOptions, options) {
3706
4390
  if (typeof message === "object" && message !== null) {
3707
- if (accountAddress === void 0) {
4391
+ if (accountAddressOrOptions === void 0) {
3708
4392
  throw new Error("Falcon512: accountAddress is required to verify a TypedData message");
3709
4393
  }
4394
+ const accountAddress = accountAddressOrOptions;
3710
4395
  return verify(
3711
4396
  signature,
3712
- starknet7.typedData.getMessageHash(message, accountAddress),
3713
- fullPublicKey
4397
+ starknet9.typedData.getMessageHash(message, accountAddress),
4398
+ fullPublicKey,
4399
+ options
4400
+ );
4401
+ }
4402
+ const hashOptions = typeof accountAddressOrOptions === "object" && accountAddressOrOptions !== null && !Array.isArray(accountAddressOrOptions) ? accountAddressOrOptions : void 0;
4403
+ return verify(signature, message, fullPublicKey, hashOptions);
4404
+ }
4405
+
4406
+ // src/falcon/mlkem/index.ts
4407
+ var mlkem_exports = {};
4408
+ __export(mlkem_exports, {
4409
+ createKey: () => createKey,
4410
+ decapsulate: () => decapsulate,
4411
+ encapsulate: () => encapsulate
4412
+ });
4413
+
4414
+ // src/falcon/mlkem/exchange.ts
4415
+ import { hkdf } from "@noble/hashes/hkdf.js";
4416
+ import { sha256 } from "@noble/hashes/sha2.js";
4417
+ import { randomBytes as randomBytes3 } from "@noble/hashes/utils.js";
4418
+ import * as starknet13 from "starknet";
4419
+
4420
+ // src/falcon/mlkem/messages.ts
4421
+ import * as starknet10 from "starknet";
4422
+ var DOMAIN_NAME = "ML-KEM key exchange";
4423
+ var DOMAIN_VERSION = "1";
4424
+ var ALGORITHM = "ML-KEM-768";
4425
+ function messageDomain(chainId) {
4426
+ return {
4427
+ type: [
4428
+ { name: "name", type: "shortstring" },
4429
+ { name: "version", type: "shortstring" },
4430
+ { name: "chainId", type: "shortstring" },
4431
+ { name: "revision", type: "shortstring" }
4432
+ ],
4433
+ domain: {
4434
+ name: DOMAIN_NAME,
4435
+ version: DOMAIN_VERSION,
4436
+ chainId,
4437
+ revision: starknet10.TypedDataRevision.ACTIVE
4438
+ }
4439
+ };
4440
+ }
4441
+ function publicKeyMessage(chainId, keyHash, validUntil) {
4442
+ const { type, domain } = messageDomain(chainId);
4443
+ return {
4444
+ types: {
4445
+ StarknetDomain: type,
4446
+ MlKemPublicKey: [
4447
+ { name: "Algorithm", type: "shortstring" },
4448
+ { name: "Key hash", type: "felt" },
4449
+ { name: "Valid until", type: "timestamp" }
4450
+ ]
4451
+ },
4452
+ primaryType: "MlKemPublicKey",
4453
+ domain,
4454
+ message: { Algorithm: ALGORITHM, "Key hash": keyHash, "Valid until": validUntil }
4455
+ };
4456
+ }
4457
+ function capsuleMessage(chainId, keyOwnerAddress, keyHash, capsuleHash, timestamp) {
4458
+ const { type, domain } = messageDomain(chainId);
4459
+ return {
4460
+ types: {
4461
+ StarknetDomain: type,
4462
+ MlKemCapsule: [
4463
+ { name: "Key owner", type: "ContractAddress" },
4464
+ { name: "Key hash", type: "felt" },
4465
+ { name: "Capsule hash", type: "felt" },
4466
+ { name: "Timestamp", type: "timestamp" }
4467
+ ]
4468
+ },
4469
+ primaryType: "MlKemCapsule",
4470
+ domain,
4471
+ message: {
4472
+ "Key owner": starknet10.num.toHex(keyOwnerAddress),
4473
+ "Key hash": keyHash,
4474
+ "Capsule hash": capsuleHash,
4475
+ Timestamp: timestamp
4476
+ }
4477
+ };
4478
+ }
4479
+
4480
+ // src/falcon/mlkem/signatures.ts
4481
+ import * as starknet11 from "starknet";
4482
+ async function checkSignature(provider, typedData3, signature, accountAddress) {
4483
+ const address = starknet11.num.toHex(parseFelt(accountAddress, "ML-KEM account address"));
4484
+ let answer;
4485
+ try {
4486
+ answer = await provider.callContract({
4487
+ contractAddress: address,
4488
+ entrypoint: "get_public_key"
4489
+ });
4490
+ } catch (error) {
4491
+ throw new Error(
4492
+ `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.`,
4493
+ { cause: error }
4494
+ );
4495
+ }
4496
+ if (answer.length !== PACKED_SLOTS + 1 || BigInt(answer[0]) !== BigInt(PACKED_SLOTS)) {
4497
+ throw new Error(`ML-KEM: the account ${address} is not a Falcon-512 account of OpenZeppelin.`);
4498
+ }
4499
+ const length = Array.isArray(signature) ? signature.length : 0;
4500
+ let accountType;
4501
+ if (length === 60) {
4502
+ accountType = "oz-hint";
4503
+ } else if (length === 31) {
4504
+ accountType = "oz-direct";
4505
+ } else {
4506
+ throw new Error(
4507
+ `ML-KEM: the signature of the account ${address} is not a Falcon-512 signature.`
4508
+ );
4509
+ }
4510
+ if (!verifyMessage(typedData3, signature, answer.slice(1), address, { accountType })) {
4511
+ throw new Error(`ML-KEM: the signature of the account ${address} is not valid.`);
4512
+ }
4513
+ }
4514
+
4515
+ // src/falcon/mlkem/utils/bytes.ts
4516
+ import { isBytes as isBytes3 } from "@noble/hashes/utils.js";
4517
+ import * as starknet12 from "starknet";
4518
+ function checkBytes(value, size, name) {
4519
+ if (!isBytes3(value) || value.length !== size) {
4520
+ throw new Error(`ML-KEM: the ${name} must be a Uint8Array of ${size} bytes.`);
4521
+ }
4522
+ return value;
4523
+ }
4524
+ function hashBytes(bytes) {
4525
+ const groupSize = starknet12.constants.TEXT_TO_FELT_MAX_LEN;
4526
+ const felts = [];
4527
+ for (let start = 0; start < bytes.length; start += groupSize) {
4528
+ const group = bytes.subarray(start, start + groupSize);
4529
+ felts.push(starknet12.encode.addHexPrefix(starknet12.encode.buf2hex(group)));
4530
+ }
4531
+ return starknet12.hash.computePoseidonHashOnElements(felts);
4532
+ }
4533
+
4534
+ // src/falcon/mlkem/utils/time.ts
4535
+ var MAX_TIME = 4294967295;
4536
+ function nowInSeconds() {
4537
+ return Math.floor(Date.now() / 1e3);
4538
+ }
4539
+ function checkTime(value, name) {
4540
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > MAX_TIME) {
4541
+ throw new Error(
4542
+ `ML-KEM: ${name} must be a time in seconds, from 0 to ${MAX_TIME}. Note: Date.now() gives milliseconds, so divide it by 1000.`
3714
4543
  );
3715
4544
  }
3716
- return verify(signature, message, fullPublicKey);
4545
+ return value;
4546
+ }
4547
+
4548
+ // src/falcon/mlkem/exchange.ts
4549
+ var PUBLIC_KEY_SIZE = 1184;
4550
+ var CAPSULE_SIZE = 1088;
4551
+ var SEED_SIZE = 64;
4552
+ var SHARED_SECRET_SIZE = 32;
4553
+ function finalSecret(mlKemSecret, context) {
4554
+ const contextHash = starknet13.hash.computePoseidonHashOnElements([
4555
+ starknet13.CairoBytes31.fromText(DOMAIN_NAME).toBigInt(),
4556
+ starknet13.CairoBytes31.fromText(DOMAIN_VERSION).toBigInt(),
4557
+ context.chainId,
4558
+ context.keyOwnerAddress,
4559
+ context.senderAddress,
4560
+ context.keyHash,
4561
+ context.capsuleHash
4562
+ ]);
4563
+ const info = starknet13.num.hexToBytes(starknet13.num.toHex64(contextHash));
4564
+ return hkdf(sha256, mlKemSecret, void 0, info, SHARED_SECRET_SIZE);
4565
+ }
4566
+ function createKey(chainId, validUntil) {
4567
+ if (typeof chainId !== "string" || chainId === "") {
4568
+ throw new Error("ML-KEM: chainId must be the chain id, as provider.getChainId() returns it.");
4569
+ }
4570
+ checkTime(validUntil, "validUntil");
4571
+ if (validUntil <= nowInSeconds()) throw new Error("ML-KEM: validUntil must be in the future.");
4572
+ const seed = randomBytes3(SEED_SIZE);
4573
+ const { publicKey, secretKey } = ml_kem768.keygen(seed);
4574
+ secretKey.fill(0);
4575
+ const typedData3 = publicKeyMessage(chainId, hashBytes(publicKey), validUntil);
4576
+ return { seed, publicKey, typedData: typedData3 };
4577
+ }
4578
+ async function encapsulate(provider, signedKey, senderAddress) {
4579
+ checkBytes(signedKey.publicKey, PUBLIC_KEY_SIZE, "public key");
4580
+ checkTime(signedKey.validUntil, "validUntil");
4581
+ const aliceAddress = parseFelt(signedKey.keyOwnerAddress, "ML-KEM key owner address");
4582
+ const bobAddress = parseFelt(senderAddress, "ML-KEM sender address");
4583
+ if (signedKey.validUntil <= nowInSeconds()) {
4584
+ const owner = starknet13.num.toHex(aliceAddress);
4585
+ throw new Error(`ML-KEM: the key of the account ${owner} has expired.`);
4586
+ }
4587
+ const chainId = await provider.getChainId();
4588
+ const keyHash = hashBytes(signedKey.publicKey);
4589
+ const keyMessage = publicKeyMessage(chainId, keyHash, signedKey.validUntil);
4590
+ await checkSignature(provider, keyMessage, signedKey.signature, aliceAddress);
4591
+ const { cipherText: capsule, sharedSecret: mlKemSecret } = ml_kem768.encapsulate(
4592
+ signedKey.publicKey
4593
+ );
4594
+ const capsuleHash = hashBytes(capsule);
4595
+ const timestamp = nowInSeconds();
4596
+ const sharedSecret = finalSecret(mlKemSecret, {
4597
+ chainId,
4598
+ keyOwnerAddress: aliceAddress,
4599
+ senderAddress: bobAddress,
4600
+ keyHash,
4601
+ capsuleHash
4602
+ });
4603
+ mlKemSecret.fill(0);
4604
+ const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
4605
+ return { sharedSecret, capsule, timestamp, typedData: typedData3 };
4606
+ }
4607
+ async function decapsulate(provider, signedCapsule, keyOwnerAddress, seed) {
4608
+ checkBytes(signedCapsule.capsule, CAPSULE_SIZE, "capsule");
4609
+ checkTime(signedCapsule.timestamp, "timestamp");
4610
+ checkBytes(seed, SEED_SIZE, "seed");
4611
+ const aliceAddress = parseFelt(keyOwnerAddress, "ML-KEM key owner address");
4612
+ const bobAddress = parseFelt(signedCapsule.senderAddress, "ML-KEM sender address");
4613
+ const { publicKey, secretKey } = ml_kem768.keygen(seed);
4614
+ try {
4615
+ const chainId = await provider.getChainId();
4616
+ const keyHash = hashBytes(publicKey);
4617
+ const capsuleHash = hashBytes(signedCapsule.capsule);
4618
+ const { timestamp } = signedCapsule;
4619
+ const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
4620
+ await checkSignature(provider, typedData3, signedCapsule.signature, bobAddress);
4621
+ const mlKemSecret = ml_kem768.decapsulate(signedCapsule.capsule, secretKey);
4622
+ const sharedSecret = finalSecret(mlKemSecret, {
4623
+ chainId,
4624
+ keyOwnerAddress: aliceAddress,
4625
+ senderAddress: bobAddress,
4626
+ keyHash,
4627
+ capsuleHash
4628
+ });
4629
+ mlKemSecret.fill(0);
4630
+ return sharedSecret;
4631
+ } finally {
4632
+ secretKey.fill(0);
4633
+ }
3717
4634
  }
3718
4635
  export {
3719
4636
  Falcon512Signer,
3720
- falcon512_exports as falcon512
4637
+ falcon512_exports as falcon512,
4638
+ mlkem_exports as mlkem
3721
4639
  };
3722
4640
  /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
3723
4641
  //# sourceMappingURL=index.mjs.map