@ocap/mpc-hsm 0.0.0-stage → 1.33.6

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.
@@ -0,0 +1,951 @@
1
+ import { DST_PRESIG_COM_V1, DST_PRESIG_ID_V1, DST_PRESIG_PI_LIN_K_V1, DST_PRESIG_PI_POK_Z_V1, DST_PRESIG_POK_B_V1, DST_PRESIG_POK_CK_V1, DST_PRESIG_POK_GAMMA_V1, DST_PRESIG_ZETA_V1, MAX_MPC_CLUSTER_NODES, MpcProtocolError, SECP256K1_N } from "./constants.mjs";
2
+ import { H_scalar, SECP256K1_G, SECP256K1_ZERO, addModN, assertValidX25519PublicKey, bytes32ToScalarNonZero, bytes32ToScalarStrict, bytesToHex, computeX25519SharedSecret, concatBytes, constantTimeEqual, createLinearPedersenDleqProof, createPedersenPok, createSchnorrPokInBase, decodePointCompressed, defaultRandomBytes, encodePointCompressed, invModN, lagrangeCoefficientAtZero, lengthPrefixedEncode, mulBaseG, mulModN, mulPoint, negModN, normalizeHexBytes, normalizeSortedSubset, pedersenCommit, sampleScalarNonZero, scalarToBytes32, sortedSubsetBytes, subModN, subsetsEqual, u16be, u64be, u8, utf8Bytes, verifyLinearPedersenDleqProof, verifyPedersenPok, verifySchnorrPokInBase, zeroizeBytes } from "./secp256k1-scalar.mjs";
3
+ import { otExtendReceiverStep1, otExtendReceiverStep3, otExtendSenderStep2, otExtendSenderStep4VerifyBeforePads, wipeVerifiedCotReceiverRows, wipeVerifiedCotSenderRows } from "./ot.mjs";
4
+ import { decomposeScalarWithLhlGadget, gadgetMtaReceiverVerifyAndFinish, gadgetMtaSenderCreateMessage } from "./mta.mjs";
5
+ import { x25519 } from "@noble/curves/ed25519.js";
6
+ import { sha256 } from "@noble/hashes/sha2.js";
7
+
8
+ //#region src/presign.ts
9
+ function encodeRound1RevealForCommit(reveal) {
10
+ return lengthPrefixedEncode("ARC-MPC-PRESIG-REVEAL-BODY-V1", [
11
+ u16be(reveal.slot),
12
+ reveal.gammaPointComp33,
13
+ reveal.bPointComp33,
14
+ reveal.ckPointComp33,
15
+ reveal.zetaEpk32,
16
+ reveal.pokGamma.noncePointComp33,
17
+ reveal.pokGamma.responseBytes32,
18
+ reveal.pokB.noncePointComp33,
19
+ reveal.pokB.responseBytes32,
20
+ reveal.pokCk.noncePointComp33,
21
+ reveal.pokCk.responseValueBytes32,
22
+ reveal.pokCk.responseBlindBytes32
23
+ ]);
24
+ }
25
+ function computeRound1CommitmentHash(params) {
26
+ return sha256(lengthPrefixedEncode(DST_PRESIG_COM_V1, [
27
+ utf8Bytes(params.rootId),
28
+ u64be(params.keyEpoch),
29
+ sortedSubsetBytes(params.subset),
30
+ params.hDkg32,
31
+ params.sessionNonce32,
32
+ u16be(params.slot),
33
+ params.comSalt32,
34
+ params.revealBodyBytes
35
+ ]));
36
+ }
37
+ /**
38
+ * Computes the canonical subset-bound `presigId` (`design.md` §4.5(1)):
39
+ * `SHA256("ARC-MPC-PRESIG-ID-V1" || LP(rootId) || u64be(keyEpoch) || sortedSubsetBytes(S) || H_dkg || Com^{pre}_{i_1..i_t})`.
40
+ */
41
+ function computeSubsetBoundPresigId(params) {
42
+ const sorted = normalizeSortedSubset(params.subset);
43
+ if (params.orderedCommitments32.length !== sorted.length) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", "Ordered commitment count must match subset cardinality");
44
+ return sha256(lengthPrefixedEncode(DST_PRESIG_ID_V1, [
45
+ utf8Bytes(params.rootId),
46
+ u64be(params.keyEpoch),
47
+ sortedSubsetBytes(sorted),
48
+ params.hDkg32,
49
+ ...params.orderedCommitments32
50
+ ]));
51
+ }
52
+ function deriveMtaContextAndNonce(presigId32, kind, senderSlotA, receiverSlotB) {
53
+ const kindByte = kind === "k_gamma" ? 1 : 2;
54
+ return {
55
+ ctxMta: lengthPrefixedEncode("ARC-MPC-PRESIG-MTA-CTX-V1", [
56
+ presigId32,
57
+ u8(kindByte),
58
+ u16be(senderSlotA),
59
+ u16be(receiverSlotB)
60
+ ]),
61
+ mtaNonce: concatBytes(presigId32, u8(kindByte), u16be(senderSlotA), u16be(receiverSlotB))
62
+ };
63
+ }
64
+ /**
65
+ * Stateful single-party 4-round Beaver-masked Presignature participant (`design.md` §4.5(1)).
66
+ * Enforces strict phase ordering, non-reuse of `b_i`, and immediate zeroization of all single-use
67
+ * ephemeral scalars upon completion or any abort!
68
+ */
69
+ var PresignPartySession = class {
70
+ constructor(params) {
71
+ this.phase = "INIT";
72
+ this.cShareBytes32 = new Uint8Array(32);
73
+ this.deltaShareBytes32 = new Uint8Array(32);
74
+ this.chiShareBytes32 = new Uint8Array(32);
75
+ this.ownRevealMsg = null;
76
+ this.round1CommitmentsBySlot = /* @__PURE__ */ new Map();
77
+ this.round1RevealsBySlot = /* @__PURE__ */ new Map();
78
+ this.linearizedPublicSharesBySlot = /* @__PURE__ */ new Map();
79
+ this.presigId32 = null;
80
+ this.aggGammaPoint = null;
81
+ this.rPoint = null;
82
+ this.pendingOtReceiverByPeer = /* @__PURE__ */ new Map();
83
+ this.pendingOtSenderByPeer = /* @__PURE__ */ new Map();
84
+ this.verifiedOtReceiverByPeer = /* @__PURE__ */ new Map();
85
+ this.senderMtaGammaAcc = 0n;
86
+ this.senderMtaBAcc = 0n;
87
+ const { slot, nodeSecretShareBytes32, cluster, subset, sessionNonce32, baseOtChannels, rng = defaultRandomBytes } = params;
88
+ if (sessionNonce32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "Presign sessionNonce32 must be 32 bytes");
89
+ if (cluster.hDkg32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "hDkg32 must be 32 bytes");
90
+ if (!Number.isInteger(cluster.t) || !Number.isInteger(cluster.nParties) || cluster.t < 2 || cluster.t > cluster.nParties || cluster.nParties > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Invalid cluster threshold (${cluster.t}-of-${cluster.nParties}); online MPC requires 2 <= t <= n <= ${MAX_MPC_CLUSTER_NODES}`);
91
+ const sortedSubset = normalizeSortedSubset(subset, cluster.t, cluster.nParties);
92
+ if (!sortedSubset.includes(slot)) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Party slot ${slot} not in subset`);
93
+ if (baseOtChannels.ownerSlot !== slot) throw new MpcProtocolError("INVALID_PARAMETER", "Base-OT channel ownerSlot mismatch");
94
+ this.slot = slot;
95
+ this.cluster = cluster;
96
+ this.subset = sortedSubset;
97
+ this.sessionNonce32 = new Uint8Array(sessionNonce32);
98
+ this.baseOtChannels = baseOtChannels;
99
+ this.rng = rng;
100
+ const pRoot = decodePointCompressed(cluster.rootPublicKeyComp33, false);
101
+ let sumX = SECP256K1_ZERO;
102
+ for (const j of sortedSubset) {
103
+ const xjBytes = cluster.publicSharesComp33BySlot.get(j);
104
+ if (!xjBytes) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Missing public share X_${j}`);
105
+ const xTildeJ = mulPoint(decodePointCompressed(xjBytes, false), lagrangeCoefficientAtZero(j, sortedSubset));
106
+ if (xTildeJ.is0()) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Degenerate linearized X_${j}`);
107
+ this.linearizedPublicSharesBySlot.set(j, xTildeJ);
108
+ sumX = sumX.add(xTildeJ);
109
+ }
110
+ if (!sumX.equals(pRoot)) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", "Public shares do not interpolate to P_root");
111
+ const xOwn = bytes32ToScalarNonZero(nodeSecretShareBytes32);
112
+ const xTildeOwn = mulModN(lagrangeCoefficientAtZero(slot, sortedSubset), xOwn);
113
+ const expectedXTildePoint = this.linearizedPublicSharesBySlot.get(slot);
114
+ if (!mulBaseG(xTildeOwn).equals(expectedXTildePoint)) throw new MpcProtocolError("INVALID_SCALAR", `Node secret share mismatch for slot ${slot}`);
115
+ this.xTildeBytes32 = scalarToBytes32(xTildeOwn);
116
+ this.kBytes32 = scalarToBytes32(sampleScalarNonZero(rng));
117
+ this.gammaBytes32 = scalarToBytes32(sampleScalarNonZero(rng));
118
+ this.bBytes32 = scalarToBytes32(sampleScalarNonZero(rng));
119
+ this.rhoKBytes32 = scalarToBytes32(sampleScalarNonZero(rng));
120
+ this.zetaEsk32 = rng(32);
121
+ }
122
+ get isAborted() {
123
+ return this.phase === "ABORTED";
124
+ }
125
+ abort() {
126
+ this.phase = "ABORTED";
127
+ this.wipeAllEphemeralSecrets();
128
+ }
129
+ wipeAllEphemeralSecrets() {
130
+ zeroizeBytes(this.xTildeBytes32, this.kBytes32, this.gammaBytes32, this.bBytes32, this.rhoKBytes32, this.zetaEsk32, this.cShareBytes32, this.deltaShareBytes32, this.chiShareBytes32);
131
+ for (const [, pending] of this.pendingOtReceiverByPeer) {
132
+ zeroizeBytes(pending.kGamma.allChoiceBits1024, pending.kB.allChoiceBits1024);
133
+ for (const r of pending.kGamma.tRows1024) zeroizeBytes(r);
134
+ for (const r of pending.kB.tRows1024) zeroizeBytes(r);
135
+ }
136
+ for (const [, pending] of this.pendingOtSenderByPeer) {
137
+ zeroizeBytes(pending.kGamma.xiSeed32, pending.kB.xiSeed32);
138
+ for (const q of pending.kGamma.qRows1024) zeroizeBytes(q);
139
+ for (const q of pending.kB.qRows1024) zeroizeBytes(q);
140
+ }
141
+ for (const [, verified] of this.verifiedOtReceiverByPeer) {
142
+ wipeVerifiedCotReceiverRows(verified.kGamma);
143
+ wipeVerifiedCotReceiverRows(verified.kB);
144
+ }
145
+ this.pendingOtReceiverByPeer.clear();
146
+ this.pendingOtSenderByPeer.clear();
147
+ this.verifiedOtReceiverByPeer.clear();
148
+ this.senderMtaGammaAcc = 0n;
149
+ this.senderMtaBAcc = 0n;
150
+ }
151
+ assertPhase(expected) {
152
+ if (this.phase !== expected) {
153
+ this.abort();
154
+ throw new MpcProtocolError("PRESIG_STATE_VIOLATION", `Expected presign phase ${expected}, got ${this.phase}`);
155
+ }
156
+ }
157
+ pokContextParts(targetSlot) {
158
+ return [
159
+ utf8Bytes(this.cluster.rootId),
160
+ u64be(this.cluster.keyEpoch),
161
+ sortedSubsetBytes(this.subset),
162
+ this.cluster.hDkg32,
163
+ this.sessionNonce32,
164
+ u16be(targetSlot)
165
+ ];
166
+ }
167
+ /**
168
+ * Round 1a: Generates hash commitment `Com^{pre}_i` over `(\Gamma_i, B_i, C_{k,i}, \pi_\Gamma, \pi_B, \pi_{C_k})`.
169
+ */
170
+ round1CreateCommitment() {
171
+ this.assertPhase("INIT");
172
+ try {
173
+ const kScalar = bytes32ToScalarNonZero(this.kBytes32);
174
+ const gammaScalar = bytes32ToScalarNonZero(this.gammaBytes32);
175
+ const bScalar = bytes32ToScalarNonZero(this.bBytes32);
176
+ const rhoKScalar = bytes32ToScalarNonZero(this.rhoKBytes32);
177
+ const gammaPoint = mulBaseG(gammaScalar);
178
+ const bPoint = mulBaseG(bScalar);
179
+ const ckPoint = pedersenCommit(kScalar, rhoKScalar);
180
+ if (ckPoint.is0()) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Pedersen C_{k,i} hit infinity");
181
+ const zetaEpk32 = x25519.getPublicKey(this.zetaEsk32);
182
+ const ctxParts = this.pokContextParts(this.slot);
183
+ const pokGamma = createSchnorrPokInBase({
184
+ dst: DST_PRESIG_POK_GAMMA_V1,
185
+ basePoint: SECP256K1_G,
186
+ statementPoint: gammaPoint,
187
+ secretScalar: gammaScalar,
188
+ contextParts: ctxParts,
189
+ rng: this.rng
190
+ });
191
+ const pokB = createSchnorrPokInBase({
192
+ dst: DST_PRESIG_POK_B_V1,
193
+ basePoint: SECP256K1_G,
194
+ statementPoint: bPoint,
195
+ secretScalar: bScalar,
196
+ contextParts: ctxParts,
197
+ rng: this.rng
198
+ });
199
+ const pokCk = createPedersenPok({
200
+ dst: DST_PRESIG_POK_CK_V1,
201
+ commitmentPoint: ckPoint,
202
+ valueScalar: kScalar,
203
+ blindingScalar: rhoKScalar,
204
+ contextParts: ctxParts,
205
+ rng: this.rng
206
+ });
207
+ const comSalt32 = this.rng(32);
208
+ const reveal = {
209
+ slot: this.slot,
210
+ comSalt32,
211
+ gammaPointComp33: encodePointCompressed(gammaPoint),
212
+ bPointComp33: encodePointCompressed(bPoint),
213
+ ckPointComp33: encodePointCompressed(ckPoint),
214
+ zetaEpk32,
215
+ pokGamma,
216
+ pokB,
217
+ pokCk
218
+ };
219
+ const revealBody = encodeRound1RevealForCommit(reveal);
220
+ const commitment32 = computeRound1CommitmentHash({
221
+ rootId: this.cluster.rootId,
222
+ keyEpoch: this.cluster.keyEpoch,
223
+ subset: this.subset,
224
+ hDkg32: this.cluster.hDkg32,
225
+ sessionNonce32: this.sessionNonce32,
226
+ slot: this.slot,
227
+ comSalt32,
228
+ revealBodyBytes: revealBody
229
+ });
230
+ this.ownRevealMsg = reveal;
231
+ this.phase = "R1_COMMITTED";
232
+ return {
233
+ slot: this.slot,
234
+ commitment32
235
+ };
236
+ } catch (err) {
237
+ this.abort();
238
+ throw err;
239
+ }
240
+ }
241
+ /**
242
+ * Round 1b: Locks all `t` commitments, derives subset-bound `presigId`, and reveals `Reveal^{pre}_i`.
243
+ */
244
+ round1ReceiveCommitmentsAndReveal(commitments) {
245
+ this.assertPhase("R1_COMMITTED");
246
+ try {
247
+ if (commitments.length !== this.subset.length) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", "Missing Round-1 commitments for subset");
248
+ const map = /* @__PURE__ */ new Map();
249
+ for (const msg of commitments) {
250
+ if (!this.subset.includes(msg.slot) || msg.commitment32.length !== 32 || map.has(msg.slot)) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", `Invalid Round-1 commitment from slot ${msg.slot}`, msg.slot);
251
+ map.set(msg.slot, new Uint8Array(msg.commitment32));
252
+ }
253
+ const orderedCommitments = this.subset.map((s) => map.get(s));
254
+ const presigId32 = computeSubsetBoundPresigId({
255
+ rootId: this.cluster.rootId,
256
+ keyEpoch: this.cluster.keyEpoch,
257
+ subset: this.subset,
258
+ hDkg32: this.cluster.hDkg32,
259
+ orderedCommitments32: orderedCommitments
260
+ });
261
+ this.round1CommitmentsBySlot = map;
262
+ this.presigId32 = presigId32;
263
+ this.phase = "R1_REVEALED";
264
+ return {
265
+ presigId32: new Uint8Array(presigId32),
266
+ reveal: this.ownRevealMsg
267
+ };
268
+ } catch (err) {
269
+ this.abort();
270
+ throw err;
271
+ }
272
+ }
273
+ /**
274
+ * Verifies all `t` Round-1 reveals & PoKs, attributing `culpritSlot` on any invalid commitment or PoK.
275
+ */
276
+ round1VerifyAllReveals(reveals) {
277
+ this.assertPhase("R1_REVEALED");
278
+ try {
279
+ if (!this.presigId32 || reveals.length !== this.subset.length) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", "Incomplete Round-1 reveals");
280
+ const bySlot = /* @__PURE__ */ new Map();
281
+ for (const rev of reveals) {
282
+ if (!this.subset.includes(rev.slot) || bySlot.has(rev.slot)) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", `Unexpected Round-1 reveal slot ${rev.slot}`, rev.slot);
283
+ bySlot.set(rev.slot, rev);
284
+ }
285
+ let gammaSum = SECP256K1_ZERO;
286
+ for (const j of this.subset) {
287
+ const rev = bySlot.get(j);
288
+ if (rev.comSalt32.length !== 32 || rev.zetaEpk32.length !== 32) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", `Malformed Round-1 reveal fields from slot ${j}`, j);
289
+ assertValidX25519PublicKey(rev.zetaEpk32, "PRESIG_POK_INVALID", j);
290
+ if (!constantTimeEqual(this.round1CommitmentsBySlot.get(j), computeRound1CommitmentHash({
291
+ rootId: this.cluster.rootId,
292
+ keyEpoch: this.cluster.keyEpoch,
293
+ subset: this.subset,
294
+ hDkg32: this.cluster.hDkg32,
295
+ sessionNonce32: this.sessionNonce32,
296
+ slot: j,
297
+ comSalt32: rev.comSalt32,
298
+ revealBodyBytes: encodeRound1RevealForCommit(rev)
299
+ }))) throw new MpcProtocolError("PRESIG_COMMITMENT_MISMATCH", `Round-1 commitment mismatch from slot ${j}`, j);
300
+ let gammaJ;
301
+ let bJ;
302
+ let ckJ;
303
+ try {
304
+ gammaJ = decodePointCompressed(rev.gammaPointComp33, false);
305
+ bJ = decodePointCompressed(rev.bPointComp33, false);
306
+ ckJ = decodePointCompressed(rev.ckPointComp33, false);
307
+ } catch {
308
+ throw new MpcProtocolError("PRESIG_POK_INVALID", `Invalid curve point in Round-1 reveal from slot ${j}`, j);
309
+ }
310
+ const ctxParts = this.pokContextParts(j);
311
+ if (!verifySchnorrPokInBase({
312
+ dst: DST_PRESIG_POK_GAMMA_V1,
313
+ basePoint: SECP256K1_G,
314
+ statementPoint: gammaJ,
315
+ proof: rev.pokGamma,
316
+ contextParts: ctxParts
317
+ }) || !verifySchnorrPokInBase({
318
+ dst: DST_PRESIG_POK_B_V1,
319
+ basePoint: SECP256K1_G,
320
+ statementPoint: bJ,
321
+ proof: rev.pokB,
322
+ contextParts: ctxParts
323
+ }) || !verifyPedersenPok({
324
+ dst: DST_PRESIG_POK_CK_V1,
325
+ commitmentPoint: ckJ,
326
+ proof: rev.pokCk,
327
+ contextParts: ctxParts
328
+ })) throw new MpcProtocolError("PRESIG_POK_INVALID", `Invalid Round-1 zero-knowledge proof from slot ${j}`, j);
329
+ gammaSum = gammaSum.add(gammaJ);
330
+ }
331
+ if (gammaSum.is0()) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Aggregate Gamma == O");
332
+ this.round1RevealsBySlot = bySlot;
333
+ this.aggGammaPoint = gammaSum;
334
+ this.phase = "R1_VERIFIED";
335
+ } catch (err) {
336
+ this.abort();
337
+ throw err;
338
+ }
339
+ }
340
+ /**
341
+ * Round 2 Step 1 (acting as Extended Receiver `B` for `(\gamma_i, b_i)` against each peer `j != i`):
342
+ * Encodes `\gamma_i` and `b_i` via LHL NUMS gadget (`768` bits + `256` sacrifice bits) and emits
343
+ * `OT-Ext Step 1` columns (`\tilde{x}_i` NEVER enters OT!).
344
+ */
345
+ round2CreateOtStep1Messages() {
346
+ this.assertPhase("R1_VERIFIED");
347
+ try {
348
+ const gammaScalar = bytes32ToScalarNonZero(this.gammaBytes32);
349
+ const bScalar = bytes32ToScalarNonZero(this.bBytes32);
350
+ const out = [];
351
+ for (const peerSenderA of this.subset) {
352
+ if (peerSenderA === this.slot) continue;
353
+ const baseOtSender = this.baseOtChannels.asExtendedReceiverB.get(peerSenderA);
354
+ if (!baseOtSender) throw new MpcProtocolError("INVALID_PARAMETER", `Missing BaseOtSenderState for peer ${peerSenderA}`);
355
+ const gammaChoice768 = decomposeScalarWithLhlGadget(gammaScalar, this.rng);
356
+ const bChoice768 = decomposeScalarWithLhlGadget(bScalar, this.rng);
357
+ const { ctxMta: ctxGamma, mtaNonce: nonceGamma } = deriveMtaContextAndNonce(this.presigId32, "k_gamma", peerSenderA, this.slot);
358
+ const { ctxMta: ctxB, mtaNonce: nonceB } = deriveMtaContextAndNonce(this.presigId32, "k_b", peerSenderA, this.slot);
359
+ const ot1Gamma = otExtendReceiverStep1({
360
+ baseOtSender,
361
+ ctxOtExt: ctxGamma,
362
+ mtaNonce: nonceGamma,
363
+ gadgetChoiceBits768: gammaChoice768,
364
+ rng: this.rng
365
+ });
366
+ let ot1B;
367
+ try {
368
+ ot1B = otExtendReceiverStep1({
369
+ baseOtSender,
370
+ ctxOtExt: ctxB,
371
+ mtaNonce: nonceB,
372
+ gadgetChoiceBits768: bChoice768,
373
+ rng: this.rng
374
+ });
375
+ } catch (err) {
376
+ zeroizeBytes(ot1Gamma.pendingReceiver.allChoiceBits1024);
377
+ for (const r of ot1Gamma.pendingReceiver.tRows1024) zeroizeBytes(r);
378
+ throw err;
379
+ } finally {
380
+ zeroizeBytes(gammaChoice768, bChoice768);
381
+ }
382
+ this.pendingOtReceiverByPeer.set(peerSenderA, {
383
+ kGamma: ot1Gamma.pendingReceiver,
384
+ kB: ot1B.pendingReceiver
385
+ });
386
+ out.push({
387
+ fromReceiverSlotB: this.slot,
388
+ toSenderSlotA: peerSenderA,
389
+ kGammaOt1: ot1Gamma.step1Message,
390
+ kBOt1: ot1B.step1Message
391
+ });
392
+ }
393
+ this.phase = "R2_OT1_SENT";
394
+ return out;
395
+ } catch (err) {
396
+ this.abort();
397
+ throw err;
398
+ }
399
+ }
400
+ /**
401
+ * Round 2 Step 2 (acting as Extended Sender `A` against each peer `j != i`):
402
+ * Transposes `Q` and issues coin-toss `xiSeed32` challenges BEFORE touching `k_i`.
403
+ */
404
+ round2ProcessOtStep1AndCreateStep2(incomingStep1) {
405
+ this.assertPhase("R2_OT1_SENT");
406
+ try {
407
+ const expectedPeers = this.subset.filter((s) => s !== this.slot);
408
+ if (incomingStep1.length !== expectedPeers.length) throw new MpcProtocolError("INVALID_PARAMETER", "Missing Round-2 OT Step 1 messages");
409
+ const byPeer = /* @__PURE__ */ new Map();
410
+ for (const msg of incomingStep1) {
411
+ if (msg.toSenderSlotA !== this.slot || !expectedPeers.includes(msg.fromReceiverSlotB) || byPeer.has(msg.fromReceiverSlotB)) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid OT Step 1 routing from slot ${msg.fromReceiverSlotB}`, msg.fromReceiverSlotB);
412
+ byPeer.set(msg.fromReceiverSlotB, msg);
413
+ }
414
+ const out = [];
415
+ for (const peerReceiverB of expectedPeers) {
416
+ const msg = byPeer.get(peerReceiverB);
417
+ const baseOtReceiver = this.baseOtChannels.asExtendedSenderA.get(peerReceiverB);
418
+ if (!baseOtReceiver) throw new MpcProtocolError("INVALID_PARAMETER", `Missing BaseOtReceiverState for peer ${peerReceiverB}`);
419
+ const { ctxMta: ctxGamma, mtaNonce: expectedNonceGamma } = deriveMtaContextAndNonce(this.presigId32, "k_gamma", this.slot, peerReceiverB);
420
+ const { ctxMta: ctxB, mtaNonce: expectedNonceB } = deriveMtaContextAndNonce(this.presigId32, "k_b", this.slot, peerReceiverB);
421
+ if (!constantTimeEqual(msg.kGammaOt1.mtaNonce, expectedNonceGamma) || !constantTimeEqual(msg.kBOt1.mtaNonce, expectedNonceB)) throw new MpcProtocolError("INVALID_PARAMETER", `OT Step 1 mtaNonce mismatch from peer slot ${peerReceiverB}`, peerReceiverB);
422
+ const ot2Gamma = otExtendSenderStep2({
423
+ baseOtReceiver,
424
+ ctxOtExt: ctxGamma,
425
+ step1Message: msg.kGammaOt1,
426
+ rng: this.rng
427
+ });
428
+ let ot2B;
429
+ try {
430
+ ot2B = otExtendSenderStep2({
431
+ baseOtReceiver,
432
+ ctxOtExt: ctxB,
433
+ step1Message: msg.kBOt1,
434
+ rng: this.rng
435
+ });
436
+ } catch (err) {
437
+ zeroizeBytes(ot2Gamma.pendingSender.xiSeed32);
438
+ for (const q of ot2Gamma.pendingSender.qRows1024) zeroizeBytes(q);
439
+ throw err;
440
+ }
441
+ this.pendingOtSenderByPeer.set(peerReceiverB, {
442
+ kGamma: ot2Gamma.pendingSender,
443
+ kB: ot2B.pendingSender
444
+ });
445
+ out.push({
446
+ fromSenderSlotA: this.slot,
447
+ toReceiverSlotB: peerReceiverB,
448
+ kGammaOt2: ot2Gamma.step2Message,
449
+ kBOt2: ot2B.step2Message
450
+ });
451
+ }
452
+ this.phase = "R2_OT2_SENT";
453
+ return out;
454
+ } catch (err) {
455
+ this.abort();
456
+ throw err;
457
+ }
458
+ }
459
+ /**
460
+ * Round 2 Step 3 (acting as Extended Receiver `B`):
461
+ * Emits `KOS15` correlation proofs `(x, T_chk)`.
462
+ */
463
+ round2ProcessOtStep2AndCreateStep3(incomingStep2) {
464
+ this.assertPhase("R2_OT2_SENT");
465
+ try {
466
+ const expectedPeers = this.subset.filter((s) => s !== this.slot);
467
+ if (incomingStep2.length !== expectedPeers.length) throw new MpcProtocolError("INVALID_PARAMETER", "Missing Round-2 OT Step 2 messages");
468
+ const byPeer = /* @__PURE__ */ new Map();
469
+ for (const msg of incomingStep2) {
470
+ if (msg.toReceiverSlotB !== this.slot || !expectedPeers.includes(msg.fromSenderSlotA) || byPeer.has(msg.fromSenderSlotA)) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid OT Step 2 routing from slot ${msg.fromSenderSlotA}`, msg.fromSenderSlotA);
471
+ byPeer.set(msg.fromSenderSlotA, msg);
472
+ }
473
+ const out = [];
474
+ for (const peerSenderA of expectedPeers) {
475
+ const msg = byPeer.get(peerSenderA);
476
+ const pending = this.pendingOtReceiverByPeer.get(peerSenderA);
477
+ const resGamma = otExtendReceiverStep3({
478
+ pendingReceiver: pending.kGamma,
479
+ step2Message: msg.kGammaOt2,
480
+ peerSenderSlotA: peerSenderA
481
+ });
482
+ let resB;
483
+ try {
484
+ resB = otExtendReceiverStep3({
485
+ pendingReceiver: pending.kB,
486
+ step2Message: msg.kBOt2,
487
+ peerSenderSlotA: peerSenderA
488
+ });
489
+ } catch (err) {
490
+ wipeVerifiedCotReceiverRows(resGamma.receiverRows);
491
+ throw err;
492
+ }
493
+ this.verifiedOtReceiverByPeer.set(peerSenderA, {
494
+ kGamma: resGamma.receiverRows,
495
+ kB: resB.receiverRows
496
+ });
497
+ out.push({
498
+ fromReceiverSlotB: this.slot,
499
+ toSenderSlotA: peerSenderA,
500
+ kGammaOt3: resGamma.step3Message,
501
+ kBOt3: resB.step3Message
502
+ });
503
+ }
504
+ this.pendingOtReceiverByPeer.clear();
505
+ this.phase = "R2_OT3_SENT";
506
+ return out;
507
+ } catch (err) {
508
+ this.abort();
509
+ throw err;
510
+ }
511
+ }
512
+ /**
513
+ * Round 2 Step 4a (acting as Extended Sender `A`):
514
+ * Runs `KOS15` check strictly BEFORE computing single-row dual-pad `GadgetMtA` messages
515
+ * anchored to Round-1 `C_{k,i}`.
516
+ */
517
+ round2VerifyKos15AndCreateMtaPayloads(incomingStep3) {
518
+ this.assertPhase("R2_OT3_SENT");
519
+ try {
520
+ const expectedPeers = this.subset.filter((s) => s !== this.slot);
521
+ if (incomingStep3.length !== expectedPeers.length) throw new MpcProtocolError("INVALID_PARAMETER", "Missing Round-2 OT Step 3 messages");
522
+ const byPeer = /* @__PURE__ */ new Map();
523
+ for (const msg of incomingStep3) {
524
+ if (msg.toSenderSlotA !== this.slot || !expectedPeers.includes(msg.fromReceiverSlotB) || byPeer.has(msg.fromReceiverSlotB)) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid OT Step 3 routing from slot ${msg.fromReceiverSlotB}`, msg.fromReceiverSlotB);
525
+ byPeer.set(msg.fromReceiverSlotB, msg);
526
+ }
527
+ const kScalar = bytes32ToScalarNonZero(this.kBytes32);
528
+ const rhoKScalar = bytes32ToScalarNonZero(this.rhoKBytes32);
529
+ const ownCkComp33 = this.ownRevealMsg.ckPointComp33;
530
+ let accGamma = 0n;
531
+ let accB = 0n;
532
+ const out = [];
533
+ for (const peerReceiverB of expectedPeers) {
534
+ const msg = byPeer.get(peerReceiverB);
535
+ const pending = this.pendingOtSenderByPeer.get(peerReceiverB);
536
+ const verifiedGammaRows = otExtendSenderStep4VerifyBeforePads({
537
+ pendingSender: pending.kGamma,
538
+ step3Message: msg.kGammaOt3
539
+ });
540
+ let verifiedBRows;
541
+ try {
542
+ verifiedBRows = otExtendSenderStep4VerifyBeforePads({
543
+ pendingSender: pending.kB,
544
+ step3Message: msg.kBOt3
545
+ });
546
+ } catch (err) {
547
+ wipeVerifiedCotSenderRows(verifiedGammaRows);
548
+ throw err;
549
+ }
550
+ try {
551
+ const { ctxMta: ctxGamma } = deriveMtaContextAndNonce(this.presigId32, "k_gamma", this.slot, peerReceiverB);
552
+ const { ctxMta: ctxB } = deriveMtaContextAndNonce(this.presigId32, "k_b", this.slot, peerReceiverB);
553
+ const mtaGamma = gadgetMtaSenderCreateMessage({
554
+ ctxMta: ctxGamma,
555
+ senderSlotA: this.slot,
556
+ receiverSlotB: peerReceiverB,
557
+ verifiedSenderRows: verifiedGammaRows,
558
+ alphaScalar: kScalar,
559
+ rhoAlphaScalar: rhoKScalar,
560
+ expectedRound1CommitmentCk: ownCkComp33,
561
+ rng: this.rng
562
+ });
563
+ const mtaB = gadgetMtaSenderCreateMessage({
564
+ ctxMta: ctxB,
565
+ senderSlotA: this.slot,
566
+ receiverSlotB: peerReceiverB,
567
+ verifiedSenderRows: verifiedBRows,
568
+ alphaScalar: kScalar,
569
+ rhoAlphaScalar: rhoKScalar,
570
+ expectedRound1CommitmentCk: ownCkComp33,
571
+ rng: this.rng
572
+ });
573
+ accGamma = addModN(accGamma, mtaGamma.senderShareModN);
574
+ accB = addModN(accB, mtaB.senderShareModN);
575
+ out.push({
576
+ fromSenderSlotA: this.slot,
577
+ toReceiverSlotB: peerReceiverB,
578
+ kGammaMta: mtaGamma.payload,
579
+ kBMta: mtaB.payload
580
+ });
581
+ } finally {
582
+ wipeVerifiedCotSenderRows(verifiedGammaRows);
583
+ wipeVerifiedCotSenderRows(verifiedBRows);
584
+ }
585
+ }
586
+ this.pendingOtSenderByPeer.clear();
587
+ this.senderMtaGammaAcc = accGamma;
588
+ this.senderMtaBAcc = accB;
589
+ this.phase = "R2_MTA_SENT";
590
+ return out;
591
+ } catch (err) {
592
+ this.abort();
593
+ throw err;
594
+ }
595
+ }
596
+ /**
597
+ * Round 2 Step 4b (acting as Extended Receiver `B`):
598
+ * Verifies `C_alpha === C_{k,j}`, Pedersen openings, and all 768 single-row dual-pad checks,
599
+ * then accumulates `\delta_i` and `c_i`.
600
+ */
601
+ round2VerifyMtaPayloads(incomingMta) {
602
+ this.assertPhase("R2_MTA_SENT");
603
+ try {
604
+ const expectedPeers = this.subset.filter((s) => s !== this.slot);
605
+ if (incomingMta.length !== expectedPeers.length) throw new MpcProtocolError("INVALID_PARAMETER", "Missing Round-2 GadgetMtA payloads");
606
+ const byPeer = /* @__PURE__ */ new Map();
607
+ for (const msg of incomingMta) {
608
+ if (msg.toReceiverSlotB !== this.slot || !expectedPeers.includes(msg.fromSenderSlotA) || byPeer.has(msg.fromSenderSlotA)) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid MtA routing from slot ${msg.fromSenderSlotA}`, msg.fromSenderSlotA);
609
+ byPeer.set(msg.fromSenderSlotA, msg);
610
+ }
611
+ let recvGammaAcc = 0n;
612
+ let recvBAcc = 0n;
613
+ for (const peerSenderA of expectedPeers) {
614
+ const msg = byPeer.get(peerSenderA);
615
+ const verifiedRows = this.verifiedOtReceiverByPeer.get(peerSenderA);
616
+ const peerReveal = this.round1RevealsBySlot.get(peerSenderA);
617
+ try {
618
+ const { ctxMta: ctxGamma } = deriveMtaContextAndNonce(this.presigId32, "k_gamma", peerSenderA, this.slot);
619
+ const { ctxMta: ctxB } = deriveMtaContextAndNonce(this.presigId32, "k_b", peerSenderA, this.slot);
620
+ const vGamma = gadgetMtaReceiverVerifyAndFinish({
621
+ ctxMta: ctxGamma,
622
+ senderSlotA: peerSenderA,
623
+ receiverSlotB: this.slot,
624
+ verifiedReceiverRows: verifiedRows.kGamma,
625
+ expectedRound1CommitmentCk: peerReveal.ckPointComp33,
626
+ payload: msg.kGammaMta
627
+ });
628
+ const vB = gadgetMtaReceiverVerifyAndFinish({
629
+ ctxMta: ctxB,
630
+ senderSlotA: peerSenderA,
631
+ receiverSlotB: this.slot,
632
+ verifiedReceiverRows: verifiedRows.kB,
633
+ expectedRound1CommitmentCk: peerReveal.ckPointComp33,
634
+ payload: msg.kBMta
635
+ });
636
+ recvGammaAcc = addModN(recvGammaAcc, vGamma);
637
+ recvBAcc = addModN(recvBAcc, vB);
638
+ } finally {
639
+ wipeVerifiedCotReceiverRows(verifiedRows.kGamma);
640
+ wipeVerifiedCotReceiverRows(verifiedRows.kB);
641
+ }
642
+ }
643
+ this.verifiedOtReceiverByPeer.clear();
644
+ const kOwn = bytes32ToScalarNonZero(this.kBytes32);
645
+ const gammaOwn = bytes32ToScalarNonZero(this.gammaBytes32);
646
+ const bOwn = bytes32ToScalarNonZero(this.bBytes32);
647
+ const deltaI = addModN(mulModN(kOwn, gammaOwn), addModN(this.senderMtaGammaAcc, recvGammaAcc));
648
+ const cI = addModN(mulModN(kOwn, bOwn), addModN(this.senderMtaBAcc, recvBAcc));
649
+ this.deltaShareBytes32.set(scalarToBytes32(deltaI));
650
+ this.cShareBytes32.set(scalarToBytes32(cI));
651
+ zeroizeBytes(this.gammaBytes32);
652
+ this.phase = "R2_DONE";
653
+ } catch (err) {
654
+ this.abort();
655
+ throw err;
656
+ }
657
+ }
658
+ /**
659
+ * Round 3a: Reveals `(\delta_i, e_i = \tilde{x}_i - b_i mod n)` and IMMEDIATELY zeroizes
660
+ * `b_i` and `\tilde{x}_i` so `b_i` can never be reused across any abort or retry!
661
+ */
662
+ round3CreateBroadcast() {
663
+ this.assertPhase("R2_DONE");
664
+ try {
665
+ const eOwn = subModN(bytes32ToScalarNonZero(this.xTildeBytes32), bytes32ToScalarNonZero(this.bBytes32));
666
+ zeroizeBytes(this.bBytes32, this.xTildeBytes32);
667
+ this.phase = "R3_EMITTED";
668
+ return {
669
+ slot: this.slot,
670
+ deltaShareBytes32: new Uint8Array(this.deltaShareBytes32),
671
+ eShareBytes32: scalarToBytes32(eOwn)
672
+ };
673
+ } catch (err) {
674
+ this.abort();
675
+ throw err;
676
+ }
677
+ }
678
+ /**
679
+ * Round 3b: Verifies `e_j * G == \tilde{X}_j - B_j` (attributing exact `culpritSlot = j` on
680
+ * corruption), computes `R = \delta^{-1} \Gamma` (`R != O && R_x < n`), and derives `\chi_i`
681
+ * with pairwise cancelling `\zeta_{i,j} = -\zeta_{j,i} mod n`.
682
+ */
683
+ round3VerifyAndCreateRound4Broadcast(round3Messages) {
684
+ this.assertPhase("R3_EMITTED");
685
+ try {
686
+ if (round3Messages.length !== this.subset.length) throw new MpcProtocolError("PRESIG_ROUND3_E_MISMATCH", "Missing Round-3 messages");
687
+ const bySlot = /* @__PURE__ */ new Map();
688
+ for (const msg of round3Messages) {
689
+ if (!this.subset.includes(msg.slot) || bySlot.has(msg.slot)) throw new MpcProtocolError("PRESIG_ROUND3_E_MISMATCH", `Invalid Round-3 slot ${msg.slot}`, msg.slot);
690
+ bySlot.set(msg.slot, msg);
691
+ }
692
+ let deltaSum = 0n;
693
+ let eSum = 0n;
694
+ for (const j of this.subset) {
695
+ const msg = bySlot.get(j);
696
+ let deltaJ;
697
+ let eJ;
698
+ try {
699
+ deltaJ = bytes32ToScalarStrict(msg.deltaShareBytes32);
700
+ eJ = bytes32ToScalarStrict(msg.eShareBytes32);
701
+ } catch {
702
+ throw new MpcProtocolError("PRESIG_ROUND3_E_MISMATCH", `Invalid scalar encoding in Round-3 message from slot ${j}`, j);
703
+ }
704
+ const xTildeJ = this.linearizedPublicSharesBySlot.get(j);
705
+ const bJ = decodePointCompressed(this.round1RevealsBySlot.get(j).bPointComp33, false);
706
+ const expectedEG = xTildeJ.subtract(bJ);
707
+ if (!mulBaseG(eJ).equals(expectedEG)) throw new MpcProtocolError("PRESIG_ROUND3_E_MISMATCH", `Identifiable abort: corrupted e_${j} in Round 3`, j);
708
+ deltaSum = addModN(deltaSum, deltaJ);
709
+ eSum = addModN(eSum, eJ);
710
+ }
711
+ if (deltaSum === 0n) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Aggregate delta == 0 mod n");
712
+ const rPoint = mulPoint(this.aggGammaPoint, invModN(deltaSum));
713
+ if (rPoint.is0()) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Presignature R == O");
714
+ const rAffine = rPoint.toAffine();
715
+ if (rAffine.x >= SECP256K1_N || rAffine.x % SECP256K1_N === 0n) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Presignature R_x >= n or R_x mod n == 0");
716
+ this.rPoint = rPoint;
717
+ let zetaSum = 0n;
718
+ for (const j of this.subset) {
719
+ if (j === this.slot) continue;
720
+ const peerEpk = this.round1RevealsBySlot.get(j).zetaEpk32;
721
+ const shared = computeX25519SharedSecret(this.zetaEsk32, peerEpk, "PRESIG_POK_INVALID", j);
722
+ const minSlot = Math.min(this.slot, j);
723
+ const maxSlot = Math.max(this.slot, j);
724
+ const baseZeta = H_scalar(DST_PRESIG_ZETA_V1, this.presigId32, u16be(minSlot), u16be(maxSlot), shared);
725
+ zeroizeBytes(shared);
726
+ const zetaIJ = this.slot < j ? baseZeta : negModN(baseZeta);
727
+ zetaSum = addModN(zetaSum, zetaIJ);
728
+ }
729
+ zeroizeBytes(this.zetaEsk32, this.deltaShareBytes32);
730
+ const kOwn = bytes32ToScalarNonZero(this.kBytes32);
731
+ const rhoKOwn = bytes32ToScalarNonZero(this.rhoKBytes32);
732
+ const cOwn = bytes32ToScalarStrict(this.cShareBytes32);
733
+ zeroizeBytes(this.cShareBytes32);
734
+ const chiOwn = addModN(addModN(cOwn, mulModN(kOwn, eSum)), zetaSum);
735
+ if (chiOwn === 0n) throw new MpcProtocolError("PRESIG_DEGENERATE_NONCE", "Degenerate zero chi_i share");
736
+ this.chiShareBytes32.set(scalarToBytes32(chiOwn));
737
+ const kSharePoint = mulPoint(rPoint, kOwn);
738
+ const zSharePoint = mulPoint(rPoint, chiOwn);
739
+ const piLinK = createLinearPedersenDleqProof({
740
+ dst: DST_PRESIG_PI_LIN_K_V1,
741
+ baseR: rPoint,
742
+ pointK: kSharePoint,
743
+ commitmentCk: decodePointCompressed(this.ownRevealMsg.ckPointComp33, false),
744
+ kScalar: kOwn,
745
+ rhoScalar: rhoKOwn,
746
+ contextParts: [this.presigId32, u16be(this.slot)],
747
+ rng: this.rng
748
+ });
749
+ zeroizeBytes(this.rhoKBytes32);
750
+ const piPokZ = createSchnorrPokInBase({
751
+ dst: DST_PRESIG_PI_POK_Z_V1,
752
+ basePoint: rPoint,
753
+ statementPoint: zSharePoint,
754
+ secretScalar: chiOwn,
755
+ contextParts: [this.presigId32, u16be(this.slot)],
756
+ rng: this.rng
757
+ });
758
+ this.phase = "R4_EMITTED";
759
+ return {
760
+ slot: this.slot,
761
+ kSharePointComp33: encodePointCompressed(kSharePoint),
762
+ zSharePointComp33: encodePointCompressed(zSharePoint),
763
+ piLinK,
764
+ piPokZ
765
+ };
766
+ } catch (err) {
767
+ this.abort();
768
+ throw err;
769
+ }
770
+ }
771
+ /**
772
+ * Round 4b: Verifies `\pi^{lin}_{K,j}` and `\pi^{pok}_{Z,j}` in base `R` for every `j \in S`
773
+ * (attributing exact `culpritSlot = j` on invalid proof), checks `\sum K_j == G` and
774
+ * `\sum Z_j == P_root`, and outputs the single-use `PresignatureShareRecord`.
775
+ */
776
+ round4VerifyAndFinalize(round4Messages) {
777
+ this.assertPhase("R4_EMITTED");
778
+ try {
779
+ if (round4Messages.length !== this.subset.length) throw new MpcProtocolError("PRESIG_GLOBAL_SUM_MISMATCH", "Missing Round-4 messages");
780
+ const bySlot = /* @__PURE__ */ new Map();
781
+ for (const msg of round4Messages) {
782
+ if (!this.subset.includes(msg.slot) || bySlot.has(msg.slot)) throw new MpcProtocolError("PRESIG_GLOBAL_SUM_MISMATCH", `Invalid Round-4 slot ${msg.slot}`, msg.slot);
783
+ bySlot.set(msg.slot, msg);
784
+ }
785
+ const rPoint = this.rPoint;
786
+ let sumK = SECP256K1_ZERO;
787
+ let sumZ = SECP256K1_ZERO;
788
+ const kPointsComp33BySlot = /* @__PURE__ */ new Map();
789
+ const zPointsComp33BySlot = /* @__PURE__ */ new Map();
790
+ for (const j of this.subset) {
791
+ const msg = bySlot.get(j);
792
+ let kJ;
793
+ let zJ;
794
+ try {
795
+ kJ = decodePointCompressed(msg.kSharePointComp33, false);
796
+ } catch {
797
+ throw new MpcProtocolError("PRESIG_PI_LIN_K_INVALID", `Invalid K_${j} point from slot ${j}`, j);
798
+ }
799
+ try {
800
+ zJ = decodePointCompressed(msg.zSharePointComp33, false);
801
+ } catch {
802
+ throw new MpcProtocolError("PRESIG_PI_POK_Z_INVALID", `Invalid Z_${j} point from slot ${j}`, j);
803
+ }
804
+ const ckJ = decodePointCompressed(this.round1RevealsBySlot.get(j).ckPointComp33, false);
805
+ if (!verifyLinearPedersenDleqProof({
806
+ dst: DST_PRESIG_PI_LIN_K_V1,
807
+ baseR: rPoint,
808
+ pointK: kJ,
809
+ commitmentCk: ckJ,
810
+ proof: msg.piLinK,
811
+ contextParts: [this.presigId32, u16be(j)]
812
+ })) throw new MpcProtocolError("PRESIG_PI_LIN_K_INVALID", `Identifiable abort: invalid pi^{lin}_{K,${j}} proof from slot ${j}`, j);
813
+ if (!verifySchnorrPokInBase({
814
+ dst: DST_PRESIG_PI_POK_Z_V1,
815
+ basePoint: rPoint,
816
+ statementPoint: zJ,
817
+ proof: msg.piPokZ,
818
+ contextParts: [this.presigId32, u16be(j)]
819
+ })) throw new MpcProtocolError("PRESIG_PI_POK_Z_INVALID", `Identifiable abort: invalid pi^{pok}_{Z,${j}} proof from slot ${j}`, j);
820
+ sumK = sumK.add(kJ);
821
+ sumZ = sumZ.add(zJ);
822
+ kPointsComp33BySlot.set(j, new Uint8Array(msg.kSharePointComp33));
823
+ zPointsComp33BySlot.set(j, new Uint8Array(msg.zSharePointComp33));
824
+ }
825
+ const pRoot = decodePointCompressed(this.cluster.rootPublicKeyComp33, false);
826
+ if (!sumK.equals(SECP256K1_G)) throw new MpcProtocolError("PRESIG_GLOBAL_SUM_MISMATCH", "Round-4 sum_{j in S} K_j != G");
827
+ if (!sumZ.equals(pRoot)) throw new MpcProtocolError("PRESIG_GLOBAL_SUM_MISMATCH", "Round-4 sum_{j in S} Z_j != P_root");
828
+ const kCopy = new Uint8Array(this.kBytes32);
829
+ const chiCopy = new Uint8Array(this.chiShareBytes32);
830
+ this.wipeAllEphemeralSecrets();
831
+ this.phase = "COMPLETED";
832
+ const presigIdCopy = new Uint8Array(this.presigId32);
833
+ return {
834
+ slot: this.slot,
835
+ publicVerification: {
836
+ presigId32: presigIdCopy,
837
+ presigIdHex: bytesToHex(presigIdCopy),
838
+ rootId: this.cluster.rootId,
839
+ keyEpoch: this.cluster.keyEpoch,
840
+ subset: [...this.subset],
841
+ hDkg32: new Uint8Array(this.cluster.hDkg32),
842
+ rootPublicKeyComp33: new Uint8Array(this.cluster.rootPublicKeyComp33),
843
+ rPointComp33: encodePointCompressed(rPoint),
844
+ kPointsComp33BySlot,
845
+ zPointsComp33BySlot
846
+ },
847
+ kShareBytes32: kCopy,
848
+ chiShareBytes32: chiCopy
849
+ };
850
+ } catch (err) {
851
+ this.abort();
852
+ throw err;
853
+ }
854
+ }
855
+ };
856
+ /**
857
+ * Volatile in-RAM single-use presignature pool (`design.md` §4.5(1), §7):
858
+ * - Synchronous `consume-before-use` atomic lock: under concurrent `Promise.all` contention,
859
+ * exact 1 caller acquires the `PresignatureShareRecord` and all others synchronously fail.
860
+ * - Strict `requestedSubset === presig.S` enforcement.
861
+ * - `wipeRoot(rootId)` / `wipeAll()` zeroize all RAM presignature scalars on Panic or shutdown.
862
+ */
863
+ var VolatilePresignaturePool = class {
864
+ constructor() {
865
+ this.activeByPresigIdHex = /* @__PURE__ */ new Map();
866
+ this.tombstonedPresigIdHexes = /* @__PURE__ */ new Set();
867
+ }
868
+ get size() {
869
+ return this.activeByPresigIdHex.size;
870
+ }
871
+ isTombstoned(presigId) {
872
+ const idHex = bytesToHex(normalizeHexBytes(presigId, 32));
873
+ return this.tombstonedPresigIdHexes.has(idHex);
874
+ }
875
+ store(record) {
876
+ if (!record || !record.publicVerification) throw new MpcProtocolError("INVALID_PARAMETER", "Missing presignature record");
877
+ const wipeCallerBuffers = () => {
878
+ zeroizeBytes(record.kShareBytes32, record.chiShareBytes32);
879
+ };
880
+ let canonicalIdBytes32;
881
+ try {
882
+ canonicalIdBytes32 = normalizeHexBytes(record.publicVerification.presigId32, 32);
883
+ } catch (err) {
884
+ wipeCallerBuffers();
885
+ throw err;
886
+ }
887
+ const canonicalIdHex = bytesToHex(canonicalIdBytes32);
888
+ if (record.publicVerification.presigIdHex !== canonicalIdHex) {
889
+ wipeCallerBuffers();
890
+ throw new MpcProtocolError("INVALID_PARAMETER", `Uncanonicalized presigIdHex: expected ${canonicalIdHex}, got ${String(record.publicVerification.presigIdHex)}`);
891
+ }
892
+ if (this.tombstonedPresigIdHexes.has(canonicalIdHex) || this.activeByPresigIdHex.has(canonicalIdHex)) {
893
+ if (this.activeByPresigIdHex.get(canonicalIdHex) !== record) wipeCallerBuffers();
894
+ throw new MpcProtocolError("PRESIG_ALREADY_CONSUMED", `Duplicate or tombstoned presigId ${canonicalIdHex}`);
895
+ }
896
+ try {
897
+ bytes32ToScalarNonZero(record.kShareBytes32);
898
+ bytes32ToScalarNonZero(record.chiShareBytes32);
899
+ } catch (err) {
900
+ wipeCallerBuffers();
901
+ throw err;
902
+ }
903
+ const poolOwnedRecord = {
904
+ slot: record.slot,
905
+ publicVerification: record.publicVerification,
906
+ kShareBytes32: new Uint8Array(record.kShareBytes32),
907
+ chiShareBytes32: new Uint8Array(record.chiShareBytes32)
908
+ };
909
+ wipeCallerBuffers();
910
+ this.activeByPresigIdHex.set(canonicalIdHex, poolOwnedRecord);
911
+ }
912
+ /**
913
+ * Synchronously validates `(rootId, requestedSubset)` and atomically removes + tombstones
914
+ * `presigId` in a single JS turn with zero `await` points.
915
+ */
916
+ consume(params) {
917
+ const idHex = bytesToHex(normalizeHexBytes(params.presigId, 32));
918
+ if (this.tombstonedPresigIdHexes.has(idHex)) throw new MpcProtocolError("PRESIG_ALREADY_CONSUMED", `Presignature ${idHex} has already been consumed or wiped`);
919
+ const record = this.activeByPresigIdHex.get(idHex);
920
+ if (!record) throw new MpcProtocolError("PRESIG_ALREADY_CONSUMED", `Unknown presignature ${idHex}`);
921
+ if (record.publicVerification.rootId !== params.rootId) throw new MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Presignature rootId mismatch: expected ${record.publicVerification.rootId}, got ${params.rootId}`);
922
+ if (!subsetsEqual(params.requestedSubset, record.publicVerification.subset)) throw new MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Signing request subset [${params.requestedSubset.join(",")}] != presignature subset [${record.publicVerification.subset.join(",")}]`);
923
+ if (params.preValidateRecord) params.preValidateRecord(record);
924
+ this.activeByPresigIdHex.delete(idHex);
925
+ this.tombstonedPresigIdHexes.add(idHex);
926
+ return record;
927
+ }
928
+ wipeRoot(rootId) {
929
+ let wiped = 0;
930
+ for (const [idHex, rec] of this.activeByPresigIdHex) if (rec.publicVerification.rootId === rootId) {
931
+ zeroizeBytes(rec.kShareBytes32, rec.chiShareBytes32);
932
+ this.activeByPresigIdHex.delete(idHex);
933
+ this.tombstonedPresigIdHexes.add(idHex);
934
+ wiped += 1;
935
+ }
936
+ return wiped;
937
+ }
938
+ wipeAll() {
939
+ let wiped = 0;
940
+ for (const [idHex, rec] of this.activeByPresigIdHex) {
941
+ zeroizeBytes(rec.kShareBytes32, rec.chiShareBytes32);
942
+ this.tombstonedPresigIdHexes.add(idHex);
943
+ wiped += 1;
944
+ }
945
+ this.activeByPresigIdHex.clear();
946
+ return wiped;
947
+ }
948
+ };
949
+
950
+ //#endregion
951
+ export { PresignPartySession, VolatilePresignaturePool, computeSubsetBoundPresigId };