@ocap/mpc-hsm 1.33.6 → 1.33.8

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.
Files changed (56) hide show
  1. package/esm/bip39-english-wordlist.d.mts +11 -0
  2. package/esm/bip39-english-wordlist.mjs +31 -0
  3. package/esm/constants.d.mts +66 -2
  4. package/esm/constants.mjs +65 -1
  5. package/esm/dkg.mjs +2 -2
  6. package/esm/index.d.mts +11 -3
  7. package/esm/index.mjs +11 -3
  8. package/esm/ocap-clear-signing.d.mts +125 -0
  9. package/esm/ocap-clear-signing.mjs +1170 -0
  10. package/esm/offline-ceremony.d.mts +127 -0
  11. package/esm/offline-ceremony.mjs +481 -0
  12. package/esm/ot.d.mts +7 -1
  13. package/esm/ot.mjs +149 -16
  14. package/esm/personal-vault.d.mts +1292 -0
  15. package/esm/personal-vault.mjs +3615 -0
  16. package/esm/personal.d.mts +10 -0
  17. package/esm/personal.mjs +11 -0
  18. package/esm/presign.mjs +1 -1
  19. package/esm/rlp-eip1559.d.mts +75 -0
  20. package/esm/rlp-eip1559.mjs +293 -0
  21. package/esm/secp256k1-scalar.d.mts +1 -1
  22. package/esm/secp256k1-scalar.mjs +14 -5
  23. package/esm/steel-mnemonic.d.mts +55 -0
  24. package/esm/steel-mnemonic.mjs +247 -0
  25. package/esm/ves-backup.d.mts +296 -0
  26. package/esm/ves-backup.mjs +1025 -0
  27. package/esm/x402-agent-guard.d.mts +111 -0
  28. package/esm/x402-agent-guard.mjs +780 -0
  29. package/lib/bip39-english-wordlist.cjs +33 -0
  30. package/lib/bip39-english-wordlist.d.cts +11 -0
  31. package/lib/constants.cjs +128 -0
  32. package/lib/constants.d.cts +66 -2
  33. package/lib/dkg.cjs +2 -2
  34. package/lib/index.cjs +249 -0
  35. package/lib/index.d.cts +11 -3
  36. package/lib/ocap-clear-signing.cjs +1176 -0
  37. package/lib/ocap-clear-signing.d.cts +125 -0
  38. package/lib/offline-ceremony.cjs +487 -0
  39. package/lib/offline-ceremony.d.cts +127 -0
  40. package/lib/ot.cjs +150 -15
  41. package/lib/ot.d.cts +7 -1
  42. package/lib/personal-vault.cjs +3725 -0
  43. package/lib/personal-vault.d.cts +1292 -0
  44. package/lib/personal.cjs +338 -0
  45. package/lib/personal.d.cts +10 -0
  46. package/lib/presign.cjs +1 -1
  47. package/lib/rlp-eip1559.cjs +303 -0
  48. package/lib/rlp-eip1559.d.cts +75 -0
  49. package/lib/secp256k1-scalar.cjs +14 -5
  50. package/lib/steel-mnemonic.cjs +253 -0
  51. package/lib/steel-mnemonic.d.cts +55 -0
  52. package/lib/ves-backup.cjs +1053 -0
  53. package/lib/ves-backup.d.cts +296 -0
  54. package/lib/x402-agent-guard.cjs +788 -0
  55. package/lib/x402-agent-guard.d.cts +111 -0
  56. package/package.json +6 -1
@@ -0,0 +1,1053 @@
1
+ const require_constants = require('./constants.cjs');
2
+ const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
3
+ const require_tweak = require('./tweak.cjs');
4
+ const require_dkg = require('./dkg.cjs');
5
+ const require_steel_mnemonic = require('./steel-mnemonic.cjs');
6
+ let _noble_hashes_sha2_js = require("@noble/hashes/sha2.js");
7
+ let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
8
+
9
+ //#region src/ves-backup.ts
10
+ /**
11
+ * Direct Bit-ElGamal Verifiable Encrypted Secret Sharing (`design.md` §5.1):
12
+ * - Zero `PEDERSEN_H` blinding variable: every cold share bit `bit_{i,k,m,b} in {0, 1}` is encrypted
13
+ * directly under Guardian `k`'s secp256k1 public key `EK_k = sk_k * G`:
14
+ * `R_{i,k,m,b} = u * G`, `S_{i,k,m,b} = bit * G + u * EK_k`
15
+ * with a Cramer-Damgard-Schoenmakers (CDS) 1-of-2 Chaum-Pedersen DLEQ OR-proof (`e0 ^ e1 == e_128`).
16
+ * - Homomorphic 16-bit chunk derivation:
17
+ * `R^{(chunk)}_{i,k,m} = \sum_{b=0}^{15} 2^b R_{i,k,m,b}`,
18
+ * `S^{(chunk)}_{i,k,m} = \sum_{b=0}^{15} 2^b S_{i,k,m,b}`
19
+ * plus a single Chaum-Pedersen linear DLEQ proof `\pi^{lin}_{i,k}` proving `(R^{tot}_{i,k}, S^{tot}_{i,k} - G_{i,k})`
20
+ * has equal discrete log across `(G, EK_k)`, where `G_{i,k} = \sum_{l=0}^{t_c-1} k^l C_{i,l}`.
21
+ * - Unconditional BSGS (`M = 680`, `680^2 = 462,400 > 7 * 65535 = 458,745`) decoding of aggregated
22
+ * guardian chunks `[0, nParties * 65535]`, exact multi-limb integer sum reduced `mod n`, and
23
+ * verification against `Y_k` before zeroizing `sk_k`.
24
+ */
25
+ const VES_DEALER_MAGIC = require_secp256k1_scalar.utf8Bytes("ARCVESD2");
26
+ const VES_PACKAGE_MAGIC = require_secp256k1_scalar.utf8Bytes("ARCVESP2");
27
+ const VES_CHUNKS_PER_SHARE = 16;
28
+ const VES_BITS_PER_CHUNK = 16;
29
+ const VES_BITS_PER_SHARE = 256;
30
+ const VES_MAX_LIMB_VALUE = 65535;
31
+ const VES_MAX_SUMMED_LIMB = require_constants.MAX_MPC_CLUSTER_NODES * VES_MAX_LIMB_VALUE;
32
+ const VES_BIT_RECORD_BYTES = 162;
33
+ const VES_LINEAR_DLEQ_BYTES = 98;
34
+ const VES_GUARDIAN_BUNDLE_BYTES = 2 + VES_BITS_PER_SHARE * VES_BIT_RECORD_BYTES + VES_LINEAR_DLEQ_BYTES;
35
+ let cachedBsgsBabyStepTable = null;
36
+ const MAX_VERIFIED_DEALER_CACHE_SIZE = 256;
37
+ const verifiedDealerContributionDigests = /* @__PURE__ */ new Set();
38
+ function computeVerifiedDealerCacheKey(params) {
39
+ return (0, _noble_hashes_utils_js.bytesToHex)((0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode("ARC-MPC-VES-VERIFIED-DEALER-CACHE-V1", [
40
+ params.ctxDkg32,
41
+ require_secp256k1_scalar.u16be(params.dealerSlot),
42
+ require_secp256k1_scalar.u16be(params.coldCommitmentsComp33.length),
43
+ ...params.coldCommitmentsComp33,
44
+ require_secp256k1_scalar.u16be(params.guardianPublicKeysComp33.length),
45
+ ...params.guardianPublicKeysComp33,
46
+ params.payload
47
+ ])));
48
+ }
49
+ function recordVerifiedDealerCacheKey(cacheKey) {
50
+ if (verifiedDealerContributionDigests.size >= MAX_VERIFIED_DEALER_CACHE_SIZE) {
51
+ const oldest = verifiedDealerContributionDigests.values().next().value;
52
+ if (oldest !== void 0) verifiedDealerContributionDigests.delete(oldest);
53
+ }
54
+ verifiedDealerContributionDigests.add(cacheKey);
55
+ }
56
+ function getBsgsBabyStepTable() {
57
+ if (cachedBsgsBabyStepTable) return cachedBsgsBabyStepTable;
58
+ const map = /* @__PURE__ */ new Map();
59
+ map.set("00", 0);
60
+ let acc = require_secp256k1_scalar.SECP256K1_ZERO;
61
+ for (let r = 1; r < require_constants.BSGS_M; r++) {
62
+ acc = acc.add(require_secp256k1_scalar.SECP256K1_G);
63
+ map.set((0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.encodePointCompressed(acc)), r);
64
+ }
65
+ cachedBsgsBabyStepTable = {
66
+ babyMap: map,
67
+ minusMG: acc.add(require_secp256k1_scalar.SECP256K1_G).negate()
68
+ };
69
+ return cachedBsgsBabyStepTable;
70
+ }
71
+ /**
72
+ * Solves `targetPoint == v * G` for `0 <= v <= maxBound` using Baby-Step Giant-Step (`M = 680`).
73
+ */
74
+ function solveDiscreteLogBsgs(targetPoint, maxBound = VES_MAX_SUMMED_LIMB) {
75
+ if (!Number.isInteger(maxBound) || maxBound < 0 || maxBound >= require_constants.BSGS_M * require_constants.BSGS_M) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `maxBound ${maxBound} exceeds BSGS capacity ${require_constants.BSGS_M * require_constants.BSGS_M - 1}`);
76
+ const { babyMap, minusMG } = getBsgsBabyStepTable();
77
+ let gamma = targetPoint;
78
+ for (let q = 0; q < require_constants.BSGS_M; q++) {
79
+ const key = gamma.is0() ? "00" : (0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.encodePointCompressed(gamma));
80
+ const r = babyMap.get(key);
81
+ if (r !== void 0) {
82
+ const value = q * require_constants.BSGS_M + r;
83
+ if (value > maxBound) throw new require_constants.MpcProtocolError("VES_BSGS_DECODE_FAILED", `Decoded BSGS limb ${value} exceeds allowed upper bound ${maxBound}`);
84
+ return value;
85
+ }
86
+ gamma = gamma.add(minusMG);
87
+ }
88
+ throw new require_constants.MpcProtocolError("VES_BSGS_DECODE_FAILED", `BSGS failed to locate discrete log within [0, ${maxBound}]`);
89
+ }
90
+ function createBitElGamalWithCdsProof(params) {
91
+ const { ctxDkg32, dealerSlot, guardianIndex, chunkIndex, bitIndex, bitValue, ekPoint, ekComp33, rng } = params;
92
+ for (;;) {
93
+ const uScalar = require_secp256k1_scalar.sampleScalarNonZero(rng);
94
+ const rPoint = require_secp256k1_scalar.mulBaseG(uScalar);
95
+ const uEk = require_secp256k1_scalar.mulPoint(ekPoint, uScalar);
96
+ const sPoint = bitValue === 1 ? require_secp256k1_scalar.SECP256K1_G.add(uEk) : uEk;
97
+ if (rPoint.is0() || sPoint.is0()) continue;
98
+ const rComp33 = require_secp256k1_scalar.encodePointCompressed(rPoint);
99
+ const sComp33 = require_secp256k1_scalar.encodePointCompressed(sPoint);
100
+ const kReal = require_secp256k1_scalar.sampleScalarNonZero(rng);
101
+ const aReal = require_secp256k1_scalar.mulBaseG(kReal);
102
+ const bReal = require_secp256k1_scalar.mulPoint(ekPoint, kReal);
103
+ if (aReal.is0() || bReal.is0()) continue;
104
+ const eSim16 = rng(16);
105
+ if (eSim16.length !== 16) {
106
+ require_secp256k1_scalar.zeroizeBytes(eSim16);
107
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "RNG must return 16 bytes for CDS challenge share");
108
+ }
109
+ const eSimScalar = require_secp256k1_scalar.bytesToBigIntBE(eSim16);
110
+ const zSim = require_secp256k1_scalar.sampleScalarNonZero(rng);
111
+ const ySim = bitValue === 0 ? sPoint.add(require_secp256k1_scalar.SECP256K1_G.negate()) : sPoint;
112
+ const aSim = require_secp256k1_scalar.mulBaseG(zSim).add(require_secp256k1_scalar.mulPoint(rPoint, eSimScalar).negate());
113
+ const bSim = require_secp256k1_scalar.mulPoint(ekPoint, zSim).add(require_secp256k1_scalar.mulPoint(ySim, eSimScalar).negate());
114
+ if (aSim.is0() || bSim.is0()) {
115
+ require_secp256k1_scalar.zeroizeBytes(eSim16);
116
+ continue;
117
+ }
118
+ const a0Comp33 = require_secp256k1_scalar.encodePointCompressed(bitValue === 0 ? aReal : aSim);
119
+ const b0Comp33 = require_secp256k1_scalar.encodePointCompressed(bitValue === 0 ? bReal : bSim);
120
+ const a1Comp33 = require_secp256k1_scalar.encodePointCompressed(bitValue === 0 ? aSim : aReal);
121
+ const b1Comp33 = require_secp256k1_scalar.encodePointCompressed(bitValue === 0 ? bSim : bReal);
122
+ const eFull32 = require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_VES_BIT_OR_V1, ctxDkg32, require_secp256k1_scalar.u16be(dealerSlot), require_secp256k1_scalar.u16be(guardianIndex), require_secp256k1_scalar.u8(chunkIndex), require_secp256k1_scalar.u8(bitIndex), ekComp33, rComp33, sComp33, a0Comp33, b0Comp33, a1Comp33, b1Comp33);
123
+ const eReal16 = new Uint8Array(16);
124
+ for (let j = 0; j < 16; j++) eReal16[j] = eFull32[j] ^ eSim16[j];
125
+ const zReal = require_secp256k1_scalar.addModN(kReal, require_secp256k1_scalar.mulModN(require_secp256k1_scalar.bytesToBigIntBE(eReal16), uScalar));
126
+ const e0Bytes16 = bitValue === 0 ? eReal16 : eSim16;
127
+ const e1Bytes16 = bitValue === 0 ? eSim16 : eReal16;
128
+ const z0Bytes32 = require_secp256k1_scalar.scalarToBytes32(bitValue === 0 ? zReal : zSim);
129
+ const z1Bytes32 = require_secp256k1_scalar.scalarToBytes32(bitValue === 0 ? zSim : zReal);
130
+ const encodedRecord162 = new Uint8Array(VES_BIT_RECORD_BYTES);
131
+ encodedRecord162.set(rComp33, 0);
132
+ encodedRecord162.set(sComp33, 33);
133
+ encodedRecord162.set(e0Bytes16, 66);
134
+ encodedRecord162.set(e1Bytes16, 82);
135
+ encodedRecord162.set(z0Bytes32, 98);
136
+ encodedRecord162.set(z1Bytes32, 130);
137
+ return {
138
+ uScalar,
139
+ rPoint,
140
+ sPoint,
141
+ encodedRecord162
142
+ };
143
+ }
144
+ }
145
+ function verifyAndDecodeBitRecord(params) {
146
+ const { ctxDkg32, dealerSlot, guardianIndex, chunkIndex, bitIndex, ekPoint, ekComp33, record162, verifyProof } = params;
147
+ const rComp33 = record162.subarray(0, 33);
148
+ const sComp33 = record162.subarray(33, 66);
149
+ const rPoint = require_secp256k1_scalar.decodePointCompressed(rComp33, false);
150
+ const sPoint = require_secp256k1_scalar.decodePointCompressed(sComp33, false);
151
+ if (!verifyProof) return {
152
+ rPoint,
153
+ sPoint
154
+ };
155
+ const e0Bytes16 = record162.subarray(66, 82);
156
+ const e1Bytes16 = record162.subarray(82, 98);
157
+ const z0 = require_secp256k1_scalar.bytes32ToScalarStrict(record162.subarray(98, 130));
158
+ const z1 = require_secp256k1_scalar.bytes32ToScalarStrict(record162.subarray(130, 162));
159
+ const e0Scalar = require_secp256k1_scalar.bytesToBigIntBE(e0Bytes16);
160
+ const e1Scalar = require_secp256k1_scalar.bytesToBigIntBE(e1Bytes16);
161
+ const a0 = require_secp256k1_scalar.SECP256K1_G.multiplyUnsafe(z0).subtract(rPoint.multiplyUnsafe(e0Scalar));
162
+ const b0 = ekPoint.multiplyUnsafe(z0).subtract(sPoint.multiplyUnsafe(e0Scalar));
163
+ if (a0.is0() || b0.is0()) throw new require_constants.MpcProtocolError("VES_BIT_PROOF_INVALID", "Degenerate branch-0 point in CDS bit OR-proof", dealerSlot);
164
+ const sMinusG = sPoint.subtract(require_secp256k1_scalar.SECP256K1_G);
165
+ const a1 = require_secp256k1_scalar.SECP256K1_G.multiplyUnsafe(z1).subtract(rPoint.multiplyUnsafe(e1Scalar));
166
+ const b1 = ekPoint.multiplyUnsafe(z1).subtract(sMinusG.multiplyUnsafe(e1Scalar));
167
+ if (a1.is0() || b1.is0()) throw new require_constants.MpcProtocolError("VES_BIT_PROOF_INVALID", "Degenerate branch-1 point in CDS bit OR-proof", dealerSlot);
168
+ const eExpected32 = require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_VES_BIT_OR_V1, ctxDkg32, require_secp256k1_scalar.u16be(dealerSlot), require_secp256k1_scalar.u16be(guardianIndex), require_secp256k1_scalar.u8(chunkIndex), require_secp256k1_scalar.u8(bitIndex), ekComp33, rComp33, sComp33, a0.toBytes(true), b0.toBytes(true), a1.toBytes(true), b1.toBytes(true));
169
+ const xor16 = new Uint8Array(16);
170
+ for (let j = 0; j < 16; j++) xor16[j] = e0Bytes16[j] ^ e1Bytes16[j];
171
+ if (!require_secp256k1_scalar.constantTimeEqual(xor16, eExpected32.subarray(0, 16))) throw new require_constants.MpcProtocolError("VES_BIT_PROOF_INVALID", `CDS 1-of-2 bit OR-proof failed for dealer ${dealerSlot}, guardian ${guardianIndex}, chunk ${chunkIndex}, bit ${bitIndex}`, dealerSlot);
172
+ return {
173
+ rPoint,
174
+ sPoint
175
+ };
176
+ }
177
+ function createGuardianLinearDleqProof(params) {
178
+ const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, ekPoint, ekComp33, gIkPoint, rTotPoint, dIkPoint, uTotScalar, rng } = params;
179
+ if (gIkPoint.is0() || rTotPoint.is0() || dIkPoint.is0()) throw new require_constants.MpcProtocolError("VES_LINEAR_PROOF_INVALID", "Linear DLEQ statement point cannot be O", dealerSlot);
180
+ const wNonce = require_secp256k1_scalar.sampleScalarNonZero(rng);
181
+ const a1Comp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(wNonce));
182
+ const a2Comp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulPoint(ekPoint, wNonce));
183
+ const gIkComp33 = require_secp256k1_scalar.encodePointCompressed(gIkPoint);
184
+ const rTotComp33 = require_secp256k1_scalar.encodePointCompressed(rTotPoint);
185
+ const dIkComp33 = require_secp256k1_scalar.encodePointCompressed(dIkPoint);
186
+ const zScalar = require_secp256k1_scalar.addModN(wNonce, require_secp256k1_scalar.mulModN(require_secp256k1_scalar.H_scalar(require_constants.DST_VES_CHUNK_LIN_V1, ctxDkg32, require_secp256k1_scalar.u16be(dealerSlot), require_secp256k1_scalar.u16be(guardianIndex), ...coldCommitmentsComp33, ekComp33, gIkComp33, rTotComp33, dIkComp33, a1Comp33, a2Comp33), uTotScalar));
187
+ const out = new Uint8Array(VES_LINEAR_DLEQ_BYTES);
188
+ out.set(a1Comp33, 0);
189
+ out.set(a2Comp33, 33);
190
+ out.set(require_secp256k1_scalar.scalarToBytes32(zScalar), 66);
191
+ return out;
192
+ }
193
+ function verifyGuardianLinearDleqProof(params) {
194
+ const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, ekPoint, ekComp33, gIkPoint, rTotPoint, dIkPoint, proof98 } = params;
195
+ if (gIkPoint.is0() || rTotPoint.is0() || dIkPoint.is0()) throw new require_constants.MpcProtocolError("VES_LINEAR_PROOF_INVALID", "Degenerate linear DLEQ statement point", dealerSlot);
196
+ const a1Comp33 = proof98.subarray(0, 33);
197
+ const a2Comp33 = proof98.subarray(33, 66);
198
+ const a1 = require_secp256k1_scalar.decodePointCompressed(a1Comp33, false);
199
+ const a2 = require_secp256k1_scalar.decodePointCompressed(a2Comp33, false);
200
+ const zScalar = require_secp256k1_scalar.bytes32ToScalarStrict(proof98.subarray(66, 98));
201
+ const challenge = require_secp256k1_scalar.H_scalar(require_constants.DST_VES_CHUNK_LIN_V1, ctxDkg32, require_secp256k1_scalar.u16be(dealerSlot), require_secp256k1_scalar.u16be(guardianIndex), ...coldCommitmentsComp33, ekComp33, require_secp256k1_scalar.encodePointCompressed(gIkPoint), require_secp256k1_scalar.encodePointCompressed(rTotPoint), require_secp256k1_scalar.encodePointCompressed(dIkPoint), a1Comp33, a2Comp33);
202
+ const lhs1 = require_secp256k1_scalar.mulBaseG(zScalar);
203
+ const rhs1 = a1.add(require_secp256k1_scalar.mulPoint(rTotPoint, challenge));
204
+ if (!lhs1.equals(rhs1)) throw new require_constants.MpcProtocolError("VES_LINEAR_PROOF_INVALID", `Linear DLEQ base-G check failed for dealer ${dealerSlot}, guardian ${guardianIndex}`, dealerSlot);
205
+ const lhs2 = require_secp256k1_scalar.mulPoint(ekPoint, zScalar);
206
+ const rhs2 = a2.add(require_secp256k1_scalar.mulPoint(dIkPoint, challenge));
207
+ if (!lhs2.equals(rhs2)) throw new require_constants.MpcProtocolError("VES_LINEAR_PROOF_INVALID", `Linear DLEQ base-EK check failed for dealer ${dealerSlot}, guardian ${guardianIndex}`, dealerSlot);
208
+ }
209
+ function parseDealerVesPayload(payload) {
210
+ if (!(payload instanceof Uint8Array) || payload.length < 14) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", "Dealer VES payload truncated");
211
+ if (!require_secp256k1_scalar.constantTimeEqual(payload.subarray(0, 8), VES_DEALER_MAGIC)) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", "Invalid dealer VES magic header");
212
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
213
+ const dealerSlot = view.getUint16(8, false);
214
+ const tCold = view.getUint16(10, false);
215
+ const nCold = view.getUint16(12, false);
216
+ if (dealerSlot < 1 || dealerSlot > require_constants.MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", "Out-of-bounds dealer VES header fields", dealerSlot);
217
+ const expectedLen = 14 + tCold * 33 + nCold * VES_GUARDIAN_BUNDLE_BYTES;
218
+ if (payload.length !== expectedLen) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Dealer VES payload size mismatch: expected ${expectedLen}, got ${payload.length}`, dealerSlot);
219
+ let offset = 14;
220
+ const coldCommitmentsComp33 = [];
221
+ for (let l = 0; l < tCold; l++) {
222
+ coldCommitmentsComp33.push(payload.subarray(offset, offset + 33));
223
+ offset += 33;
224
+ }
225
+ const guardianBundles = [];
226
+ for (let k = 1; k <= nCold; k++) {
227
+ const rawBundleBytes = payload.subarray(offset, offset + VES_GUARDIAN_BUNDLE_BYTES);
228
+ const bundleGuardianIdx = new DataView(rawBundleBytes.buffer, rawBundleBytes.byteOffset, rawBundleBytes.byteLength).getUint16(0, false);
229
+ if (bundleGuardianIdx !== k) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Guardian bundle index mismatch: expected ${k}, got ${bundleGuardianIdx}`, dealerSlot);
230
+ guardianBundles.push({
231
+ guardianIndex: k,
232
+ rawBundleBytes
233
+ });
234
+ offset += VES_GUARDIAN_BUNDLE_BYTES;
235
+ }
236
+ return {
237
+ dealerSlot,
238
+ tCold,
239
+ nCold,
240
+ coldCommitmentsComp33,
241
+ guardianBundles
242
+ };
243
+ }
244
+ function decodeAndOptionallyVerifyGuardianBundle(params) {
245
+ const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, coldPoints, ekPoint, ekComp33, rawBundleBytes, verifyProofs } = params;
246
+ const chunkR = new Array(VES_CHUNKS_PER_SHARE);
247
+ const chunkS = new Array(VES_CHUNKS_PER_SHARE);
248
+ let pos = 2;
249
+ for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
250
+ const rBits = new Array(VES_BITS_PER_CHUNK);
251
+ const sBits = new Array(VES_BITS_PER_CHUNK);
252
+ for (let b = 0; b < VES_BITS_PER_CHUNK; b++) {
253
+ const rec = rawBundleBytes.subarray(pos, pos + VES_BIT_RECORD_BYTES);
254
+ pos += VES_BIT_RECORD_BYTES;
255
+ const { rPoint, sPoint } = verifyAndDecodeBitRecord({
256
+ ctxDkg32,
257
+ dealerSlot,
258
+ guardianIndex,
259
+ chunkIndex: m,
260
+ bitIndex: b,
261
+ ekPoint,
262
+ ekComp33,
263
+ record162: rec,
264
+ verifyProof: verifyProofs
265
+ });
266
+ rBits[b] = rPoint;
267
+ sBits[b] = sPoint;
268
+ }
269
+ let rChunk = require_secp256k1_scalar.SECP256K1_ZERO;
270
+ let sChunk = require_secp256k1_scalar.SECP256K1_ZERO;
271
+ for (let b = VES_BITS_PER_CHUNK - 1; b >= 0; b--) {
272
+ rChunk = rChunk.double().add(rBits[b]);
273
+ sChunk = sChunk.double().add(sBits[b]);
274
+ }
275
+ chunkR[m] = rChunk;
276
+ chunkS[m] = sChunk;
277
+ }
278
+ if (verifyProofs) {
279
+ let rTot = require_secp256k1_scalar.SECP256K1_ZERO;
280
+ let sTot = require_secp256k1_scalar.SECP256K1_ZERO;
281
+ for (let m = VES_CHUNKS_PER_SHARE - 1; m >= 0; m--) {
282
+ for (let d = 0; d < 16; d++) {
283
+ rTot = rTot.double();
284
+ sTot = sTot.double();
285
+ }
286
+ rTot = rTot.add(chunkR[m]);
287
+ sTot = sTot.add(chunkS[m]);
288
+ }
289
+ const gIkPoint = require_secp256k1_scalar.evaluateFeldmanCommitments(coldPoints, guardianIndex);
290
+ const dIkPoint = sTot.add(gIkPoint.negate());
291
+ const proof98 = rawBundleBytes.subarray(pos, pos + VES_LINEAR_DLEQ_BYTES);
292
+ verifyGuardianLinearDleqProof({
293
+ ctxDkg32,
294
+ dealerSlot,
295
+ guardianIndex,
296
+ coldCommitmentsComp33,
297
+ ekPoint,
298
+ ekComp33,
299
+ gIkPoint,
300
+ rTotPoint: rTot,
301
+ dIkPoint,
302
+ proof98
303
+ });
304
+ }
305
+ return {
306
+ chunkR,
307
+ chunkS
308
+ };
309
+ }
310
+ /**
311
+ * Creates dealer `i`'s Direct Bit-ElGamal VES contribution across all `k = 1..nCold` guardians.
312
+ */
313
+ function createNodeColdVesContribution(input, options) {
314
+ const rng = options?.rng ?? require_secp256k1_scalar.defaultRandomBytes;
315
+ const { ctxDkg32, dealerSlot, coldCommitmentsComp33, guardianPublicKeysComp33, coldEvaluationsByGuardian } = input;
316
+ if (!(ctxDkg32 instanceof Uint8Array) || ctxDkg32.length !== 32) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", "ctxDkg32 must be 32 bytes");
317
+ if (!Number.isInteger(dealerSlot) || dealerSlot < 1 || dealerSlot > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid dealerSlot ${dealerSlot}`);
318
+ const tCold = coldCommitmentsComp33.length;
319
+ const nCold = guardianPublicKeysComp33.length;
320
+ if (tCold < 1 || tCold > nCold || nCold > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid cold threshold (${tCold}-of-${nCold})`);
321
+ if (coldEvaluationsByGuardian.length !== nCold) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", "coldEvaluationsByGuardian length mismatch");
322
+ const coldPoints = coldCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
323
+ const guardianBundleBuffers = [];
324
+ for (let idx = 0; idx < nCold; idx++) {
325
+ const k = idx + 1;
326
+ const evalEntry = coldEvaluationsByGuardian[idx];
327
+ if (evalEntry.guardianIndex !== k || !require_secp256k1_scalar.constantTimeEqual(evalEntry.guardianPublicKeyComp33, guardianPublicKeysComp33[idx])) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Guardian evaluation entry mismatch at index ${k}`);
328
+ const yScalar = evalEntry.evaluationScalar;
329
+ if (typeof yScalar !== "bigint" || yScalar < 1n || yScalar >= require_constants.SECP256K1_N) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid cold evaluation scalar for guardian ${k}`);
330
+ const gIkPoint = require_secp256k1_scalar.evaluateFeldmanCommitments(coldPoints, k);
331
+ if (!require_secp256k1_scalar.mulBaseG(yScalar).equals(gIkPoint)) throw new require_constants.MpcProtocolError("VES_INVALID_PAYLOAD", `Dealer ${dealerSlot} cold evaluation y_{${dealerSlot},${k}} * G != Feldman G_{${dealerSlot},${k}}`);
332
+ const ekComp33 = guardianPublicKeysComp33[idx];
333
+ const ekPoint = require_secp256k1_scalar.decodePointCompressed(ekComp33, false);
334
+ ekPoint.precompute(8);
335
+ for (;;) {
336
+ const bundle = new Uint8Array(VES_GUARDIAN_BUNDLE_BYTES);
337
+ bundle.set(require_secp256k1_scalar.u16be(k), 0);
338
+ let pos = 2;
339
+ let uTot = 0n;
340
+ const chunkR = new Array(VES_CHUNKS_PER_SHARE);
341
+ const chunkS = new Array(VES_CHUNKS_PER_SHARE);
342
+ for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
343
+ const rBits = new Array(VES_BITS_PER_CHUNK);
344
+ const sBits = new Array(VES_BITS_PER_CHUNK);
345
+ for (let b = 0; b < VES_BITS_PER_CHUNK; b++) {
346
+ const bitShift = BigInt(16 * m + b);
347
+ const bitValue = Number(yScalar >> bitShift & 1n);
348
+ const bitRes = createBitElGamalWithCdsProof({
349
+ ctxDkg32,
350
+ dealerSlot,
351
+ guardianIndex: k,
352
+ chunkIndex: m,
353
+ bitIndex: b,
354
+ bitValue,
355
+ ekPoint,
356
+ ekComp33,
357
+ rng
358
+ });
359
+ bundle.set(bitRes.encodedRecord162, pos);
360
+ pos += VES_BIT_RECORD_BYTES;
361
+ rBits[b] = bitRes.rPoint;
362
+ sBits[b] = bitRes.sPoint;
363
+ const weight = 1n << bitShift;
364
+ uTot = require_secp256k1_scalar.addModN(uTot, require_secp256k1_scalar.mulModN(bitRes.uScalar, require_secp256k1_scalar.modN(weight)));
365
+ }
366
+ let rChunk = require_secp256k1_scalar.SECP256K1_ZERO;
367
+ let sChunk = require_secp256k1_scalar.SECP256K1_ZERO;
368
+ for (let b = VES_BITS_PER_CHUNK - 1; b >= 0; b--) {
369
+ rChunk = rChunk.double().add(rBits[b]);
370
+ sChunk = sChunk.double().add(sBits[b]);
371
+ }
372
+ chunkR[m] = rChunk;
373
+ chunkS[m] = sChunk;
374
+ }
375
+ if (uTot === 0n) continue;
376
+ let rTot = require_secp256k1_scalar.SECP256K1_ZERO;
377
+ let sTot = require_secp256k1_scalar.SECP256K1_ZERO;
378
+ for (let m = VES_CHUNKS_PER_SHARE - 1; m >= 0; m--) {
379
+ for (let d = 0; d < 16; d++) {
380
+ rTot = rTot.double();
381
+ sTot = sTot.double();
382
+ }
383
+ rTot = rTot.add(chunkR[m]);
384
+ sTot = sTot.add(chunkS[m]);
385
+ }
386
+ const dIkPoint = sTot.add(gIkPoint.negate());
387
+ if (rTot.is0() || dIkPoint.is0()) continue;
388
+ const linProof98 = createGuardianLinearDleqProof({
389
+ ctxDkg32,
390
+ dealerSlot,
391
+ guardianIndex: k,
392
+ coldCommitmentsComp33,
393
+ ekPoint,
394
+ ekComp33,
395
+ gIkPoint,
396
+ rTotPoint: rTot,
397
+ dIkPoint,
398
+ uTotScalar: uTot,
399
+ rng
400
+ });
401
+ bundle.set(linProof98, pos);
402
+ guardianBundleBuffers.push(bundle);
403
+ break;
404
+ }
405
+ }
406
+ return require_secp256k1_scalar.concatBytes(VES_DEALER_MAGIC, require_secp256k1_scalar.u16be(dealerSlot), require_secp256k1_scalar.u16be(tCold), require_secp256k1_scalar.u16be(nCold), ...coldCommitmentsComp33, ...guardianBundleBuffers);
407
+ }
408
+ /**
409
+ * Verifies dealer `i`'s Direct Bit-ElGamal VES contribution (all 256 CDS bit OR-proofs + linear DLEQ
410
+ * per guardian).
411
+ */
412
+ function verifyNodeColdVesContribution(input) {
413
+ try {
414
+ const { ctxDkg32, dealerSlot, coldCommitmentsComp33, guardianPublicKeysComp33, payload } = input;
415
+ if (!(ctxDkg32 instanceof Uint8Array) || ctxDkg32.length !== 32) return false;
416
+ const parsed = parseDealerVesPayload(payload);
417
+ if (parsed.dealerSlot !== dealerSlot || parsed.tCold !== coldCommitmentsComp33.length || parsed.nCold !== guardianPublicKeysComp33.length) return false;
418
+ for (let l = 0; l < parsed.tCold; l++) if (!require_secp256k1_scalar.constantTimeEqual(parsed.coldCommitmentsComp33[l], coldCommitmentsComp33[l])) return false;
419
+ const cacheKey = computeVerifiedDealerCacheKey({
420
+ ctxDkg32,
421
+ dealerSlot,
422
+ coldCommitmentsComp33,
423
+ guardianPublicKeysComp33,
424
+ payload
425
+ });
426
+ if (verifiedDealerContributionDigests.has(cacheKey)) return true;
427
+ const coldPoints = coldCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
428
+ for (let idx = 0; idx < parsed.nCold; idx++) {
429
+ const ekComp33 = guardianPublicKeysComp33[idx];
430
+ const ekPoint = require_secp256k1_scalar.decodePointCompressed(ekComp33, false);
431
+ ekPoint.precompute(8);
432
+ decodeAndOptionallyVerifyGuardianBundle({
433
+ ctxDkg32,
434
+ dealerSlot,
435
+ guardianIndex: idx + 1,
436
+ coldCommitmentsComp33,
437
+ coldPoints,
438
+ ekPoint,
439
+ ekComp33,
440
+ rawBundleBytes: parsed.guardianBundles[idx].rawBundleBytes,
441
+ verifyProofs: true
442
+ });
443
+ }
444
+ recordVerifiedDealerCacheKey(cacheKey);
445
+ return true;
446
+ } catch {
447
+ return false;
448
+ }
449
+ }
450
+ function parseRecoveryPackageBytes(recoveryPackageBytes) {
451
+ if (!(recoveryPackageBytes instanceof Uint8Array) || recoveryPackageBytes.length < 113 || recoveryPackageBytes.length >= require_constants.MAX_RECOVERY_PACKAGE_BYTES) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Recovery package size must satisfy 113 <= bytes < ${require_constants.MAX_RECOVERY_PACKAGE_BYTES}, got ${recoveryPackageBytes?.length}`);
452
+ if (!require_secp256k1_scalar.constantTimeEqual(recoveryPackageBytes.subarray(0, 8), VES_PACKAGE_MAGIC)) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package magic header");
453
+ const view = new DataView(recoveryPackageBytes.buffer, recoveryPackageBytes.byteOffset, recoveryPackageBytes.byteLength);
454
+ const protocolVersion = view.getUint16(8, false);
455
+ const nParties = view.getUint16(10, false);
456
+ const tCold = view.getUint16(12, false);
457
+ const nCold = view.getUint16(14, false);
458
+ if (protocolVersion !== require_constants.MPC_PROTOCOL_VERSION || nParties < 1 || nParties > require_constants.MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package dimensions or protocolVersion");
459
+ const singleDealerPayloadLen = 14 + tCold * 33 + nCold * VES_GUARDIAN_BUNDLE_BYTES;
460
+ const expectedTotalLen = 80 + (1 + tCold + nCold + nCold) * 33 + nParties * (6 + singleDealerPayloadLen);
461
+ if (recoveryPackageBytes.length !== expectedTotalLen) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Recovery package byte length mismatch: expected ${expectedTotalLen}, got ${recoveryPackageBytes.length}`);
462
+ let offset = 16;
463
+ const ctxDkg32 = recoveryPackageBytes.subarray(offset, offset + 32);
464
+ offset += 32;
465
+ const hDkg32 = recoveryPackageBytes.subarray(offset, offset + 32);
466
+ offset += 32;
467
+ const rootPublicKeyComp33 = recoveryPackageBytes.subarray(offset, offset + 33);
468
+ offset += 33;
469
+ const aggColdCommitmentsComp33 = [];
470
+ for (let l = 0; l < tCold; l++) {
471
+ aggColdCommitmentsComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
472
+ offset += 33;
473
+ }
474
+ const guardianColdPublicSharesComp33 = [];
475
+ for (let k = 0; k < nCold; k++) {
476
+ guardianColdPublicSharesComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
477
+ offset += 33;
478
+ }
479
+ const guardianPublicKeysComp33 = [];
480
+ for (let k = 0; k < nCold; k++) {
481
+ guardianPublicKeysComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
482
+ offset += 33;
483
+ }
484
+ const dealerContributions = [];
485
+ for (let i = 1; i <= nParties; i++) {
486
+ const slot = view.getUint16(offset, false);
487
+ offset += 2;
488
+ const payloadLen = view.getUint32(offset, false);
489
+ offset += 4;
490
+ if (slot !== i || payloadLen !== singleDealerPayloadLen) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Unexpected dealer entry at slot ${i}`);
491
+ const payload = recoveryPackageBytes.subarray(offset, offset + payloadLen);
492
+ offset += payloadLen;
493
+ const parsed = parseDealerVesPayload(payload);
494
+ if (parsed.dealerSlot !== i || parsed.tCold !== tCold || parsed.nCold !== nCold) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Dealer ${i} header mismatch inside recovery package`);
495
+ dealerContributions.push({
496
+ dealerSlot: i,
497
+ payload,
498
+ parsed
499
+ });
500
+ }
501
+ return {
502
+ protocolVersion,
503
+ nParties,
504
+ tCold,
505
+ nCold,
506
+ ctxDkg32,
507
+ hDkg32,
508
+ rootPublicKeyComp33,
509
+ aggColdCommitmentsComp33,
510
+ guardianColdPublicSharesComp33,
511
+ guardianPublicKeysComp33,
512
+ dealerContributions
513
+ };
514
+ }
515
+ /**
516
+ * Aggregates all `nParties` verified dealer VES payloads into a canonical binary recovery package
517
+ * (`< MAX_RECOVERY_PACKAGE_BYTES = 2 MiB`) and returns `(recoveryPackageBytes, sha256(recoveryPackageBytes))`.
518
+ */
519
+ function aggregateRecoveryPackage(input) {
520
+ const { ctxDkg32, hDkg32, rootPublicKeyComp33, aggColdCommitmentsComp33, guardianColdPublicSharesComp33, guardianPublicKeysComp33, dealerPayloads } = input;
521
+ if (ctxDkg32.length !== 32 || hDkg32.length !== 32 || rootPublicKeyComp33.length !== 33) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Invalid ctxDkg32/hDkg32/rootPublicKeyComp33 byte length");
522
+ const nParties = dealerPayloads.length;
523
+ const tCold = aggColdCommitmentsComp33.length;
524
+ const nCold = guardianPublicKeysComp33.length;
525
+ if (nParties < 1 || nParties > require_constants.MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > require_constants.MAX_MPC_CLUSTER_NODES || guardianColdPublicSharesComp33.length !== nCold) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package dimensions");
526
+ const sortedDealers = [...dealerPayloads].sort((a, b) => a.dealerSlot - b.dealerSlot);
527
+ const dealerRecords = [];
528
+ for (let idx = 0; idx < nParties; idx++) {
529
+ const entry = sortedDealers[idx];
530
+ if (entry.dealerSlot !== idx + 1) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Missing dealer slot ${idx + 1} in dealerPayloads`);
531
+ dealerRecords.push(require_secp256k1_scalar.u16be(entry.dealerSlot), require_secp256k1_scalar.u32be(entry.payload.length), entry.payload);
532
+ }
533
+ const recoveryPackageBytes = require_secp256k1_scalar.concatBytes(VES_PACKAGE_MAGIC, require_secp256k1_scalar.u16be(require_constants.MPC_PROTOCOL_VERSION), require_secp256k1_scalar.u16be(nParties), require_secp256k1_scalar.u16be(tCold), require_secp256k1_scalar.u16be(nCold), ctxDkg32, hDkg32, rootPublicKeyComp33, ...aggColdCommitmentsComp33, ...guardianColdPublicSharesComp33, ...guardianPublicKeysComp33, ...dealerRecords);
534
+ if (recoveryPackageBytes.length >= require_constants.MAX_RECOVERY_PACKAGE_BYTES) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Serialized recovery package (${recoveryPackageBytes.length}B) exceeds < ${require_constants.MAX_RECOVERY_PACKAGE_BYTES}B bound`);
535
+ return {
536
+ recoveryPackageBytes,
537
+ recoveryPackageHash32: (0, _noble_hashes_sha2_js.sha256)(recoveryPackageBytes)
538
+ };
539
+ }
540
+ /**
541
+ * Self-contained verification of a serialized Direct Bit-ElGamal recovery package:
542
+ * - Enforces `< MAX_RECOVERY_PACKAGE_BYTES` (`< 2 MiB`) and canonical byte layout.
543
+ * - Verifies `C^{cold}_0 == P_root`, distinct valid `EK_k`, and `Y_k == \sum_l k^l C^{cold}_l`.
544
+ * - Verifies EVERY dealer's 256-bit CDS OR-proofs + linear DLEQ `\pi^{lin}_{i,k}` and confirms
545
+ * `\sum_{i=1}^{nParties} C_{i,l} == C^{cold}_l` across all `l = 0..tCold-1`.
546
+ */
547
+ function verifyRecoveryPackage(recoveryPackageBytes, expected) {
548
+ try {
549
+ const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
550
+ if (expected) {
551
+ if (!require_secp256k1_scalar.constantTimeEqual(pkg.ctxDkg32, expected.ctxDkg32) || !require_secp256k1_scalar.constantTimeEqual(pkg.rootPublicKeyComp33, expected.rootPublicKeyComp33) || pkg.aggColdCommitmentsComp33.length !== expected.aggColdCommitmentsComp33.length || pkg.guardianPublicKeysComp33.length !== expected.guardianPublicKeysComp33.length) return false;
552
+ for (let l = 0; l < pkg.tCold; l++) if (!require_secp256k1_scalar.constantTimeEqual(pkg.aggColdCommitmentsComp33[l], expected.aggColdCommitmentsComp33[l])) return false;
553
+ for (let k = 0; k < pkg.nCold; k++) if (!require_secp256k1_scalar.constantTimeEqual(pkg.guardianPublicKeysComp33[k], expected.guardianPublicKeysComp33[k])) return false;
554
+ }
555
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(pkg.rootPublicKeyComp33, false);
556
+ const aggColdPoints = pkg.aggColdCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
557
+ if (!pRoot.equals(aggColdPoints[0])) return false;
558
+ const guardianEkPoints = [];
559
+ const seenEkHex = /* @__PURE__ */ new Set();
560
+ for (let k = 0; k < pkg.nCold; k++) {
561
+ const ekComp = pkg.guardianPublicKeysComp33[k];
562
+ const ekHex = (0, _noble_hashes_utils_js.bytesToHex)(ekComp);
563
+ if (seenEkHex.has(ekHex)) return false;
564
+ seenEkHex.add(ekHex);
565
+ const ekPt = require_secp256k1_scalar.decodePointCompressed(ekComp, false);
566
+ ekPt.precompute(8);
567
+ guardianEkPoints.push(ekPt);
568
+ const expectedYk = require_secp256k1_scalar.evaluateFeldmanCommitments(aggColdPoints, k + 1);
569
+ const pkgYk = require_secp256k1_scalar.decodePointCompressed(pkg.guardianColdPublicSharesComp33[k], false);
570
+ if (expectedYk.is0() || !expectedYk.equals(pkgYk)) return false;
571
+ }
572
+ const summedColdCommitments = new Array(pkg.tCold).fill(require_secp256k1_scalar.SECP256K1_ZERO);
573
+ for (const dealer of pkg.dealerContributions) {
574
+ const dealerColdPoints = dealer.parsed.coldCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
575
+ for (let l = 0; l < pkg.tCold; l++) summedColdCommitments[l] = summedColdCommitments[l].add(dealerColdPoints[l]);
576
+ const cacheKey = computeVerifiedDealerCacheKey({
577
+ ctxDkg32: pkg.ctxDkg32,
578
+ dealerSlot: dealer.dealerSlot,
579
+ coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
580
+ guardianPublicKeysComp33: pkg.guardianPublicKeysComp33,
581
+ payload: dealer.payload
582
+ });
583
+ if (verifiedDealerContributionDigests.has(cacheKey)) continue;
584
+ for (let idx = 0; idx < pkg.nCold; idx++) decodeAndOptionallyVerifyGuardianBundle({
585
+ ctxDkg32: pkg.ctxDkg32,
586
+ dealerSlot: dealer.dealerSlot,
587
+ guardianIndex: idx + 1,
588
+ coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
589
+ coldPoints: dealerColdPoints,
590
+ ekPoint: guardianEkPoints[idx],
591
+ ekComp33: pkg.guardianPublicKeysComp33[idx],
592
+ rawBundleBytes: dealer.parsed.guardianBundles[idx].rawBundleBytes,
593
+ verifyProofs: true
594
+ });
595
+ recordVerifiedDealerCacheKey(cacheKey);
596
+ }
597
+ for (let l = 0; l < pkg.tCold; l++) if (!summedColdCommitments[l].equals(aggColdPoints[l])) return false;
598
+ return true;
599
+ } catch {
600
+ return false;
601
+ }
602
+ }
603
+ var DirectBitElGamalVesPlugin = class {
604
+ constructor(options) {
605
+ this.rng = options?.rng ?? require_secp256k1_scalar.defaultRandomBytes;
606
+ }
607
+ createDealerContribution(input) {
608
+ return createNodeColdVesContribution(input, { rng: this.rng });
609
+ }
610
+ verifyDealerContribution(input) {
611
+ return verifyNodeColdVesContribution(input);
612
+ }
613
+ aggregateRecoveryPackage(input) {
614
+ return aggregateRecoveryPackage(input);
615
+ }
616
+ verifyRecoveryPackage(recoveryPackageBytes, expected) {
617
+ return verifyRecoveryPackage(recoveryPackageBytes, expected);
618
+ }
619
+ };
620
+ /**
621
+ * Verifies the recovery package (unless `skipPackageProofVerification` is never set — always verified!),
622
+ * aggregates `(R^{agg}_{k,m}, S^{agg}_{k,m})` across all `nParties` dealers, solves each of the 16
623
+ * summed limbs in `[0, nParties * 65535]` via `BSGS_M = 680`, reduces `\sum_{m=0}^{15} Y_{k,m} 2^{16m} mod n`,
624
+ * asserts `g(k) * G == Y_k`, and wipes `guardianSecretKeyBytes32` in `finally` (`wipeSecretKeyInput` default `true`).
625
+ */
626
+ function decryptGuardianColdShareBsgs(params) {
627
+ const { recoveryPackageBytes, guardianIndex, guardianSecretKeyBytes32, expectedManifest, wipeSecretKeyInput = true } = params;
628
+ let skScalar = 0n;
629
+ let shareScalar = 0n;
630
+ try {
631
+ if (!verifyRecoveryPackage(recoveryPackageBytes, expectedManifest)) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Recovery package failed cryptographic verification");
632
+ const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
633
+ if (!Number.isInteger(guardianIndex) || guardianIndex < 1 || guardianIndex > pkg.nCold) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `guardianIndex ${guardianIndex} out of 1..${pkg.nCold}`);
634
+ skScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(guardianSecretKeyBytes32);
635
+ const derivedEkComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(skScalar));
636
+ const expectedEkComp33 = pkg.guardianPublicKeysComp33[guardianIndex - 1];
637
+ if (!require_secp256k1_scalar.constantTimeEqual(derivedEkComp33, expectedEkComp33)) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", `Guardian secret key does not match guardianPublicKeysComp33[${guardianIndex - 1}]`);
638
+ const ekPoint = require_secp256k1_scalar.decodePointCompressed(expectedEkComp33, false);
639
+ const aggR = new Array(VES_CHUNKS_PER_SHARE).fill(require_secp256k1_scalar.SECP256K1_ZERO);
640
+ const aggS = new Array(VES_CHUNKS_PER_SHARE).fill(require_secp256k1_scalar.SECP256K1_ZERO);
641
+ for (const dealer of pkg.dealerContributions) {
642
+ const dealerColdPoints = dealer.parsed.coldCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
643
+ const { chunkR, chunkS } = decodeAndOptionallyVerifyGuardianBundle({
644
+ ctxDkg32: pkg.ctxDkg32,
645
+ dealerSlot: dealer.dealerSlot,
646
+ guardianIndex,
647
+ coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
648
+ coldPoints: dealerColdPoints,
649
+ ekPoint,
650
+ ekComp33: expectedEkComp33,
651
+ rawBundleBytes: dealer.parsed.guardianBundles[guardianIndex - 1].rawBundleBytes,
652
+ verifyProofs: false
653
+ });
654
+ for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
655
+ aggR[m] = aggR[m].add(chunkR[m]);
656
+ aggS[m] = aggS[m].add(chunkS[m]);
657
+ }
658
+ }
659
+ const maxAllowedLimb = pkg.nParties * VES_MAX_LIMB_VALUE;
660
+ const decodedLimbs16 = new Array(VES_CHUNKS_PER_SHARE);
661
+ let exactIntegerSum = 0n;
662
+ for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
663
+ const limbVal = solveDiscreteLogBsgs(aggS[m].add(require_secp256k1_scalar.mulPoint(aggR[m], skScalar).negate()), maxAllowedLimb);
664
+ decodedLimbs16[m] = limbVal;
665
+ exactIntegerSum += BigInt(limbVal) << BigInt(16 * m);
666
+ }
667
+ shareScalar = require_secp256k1_scalar.modN(exactIntegerSum);
668
+ if (shareScalar === 0n) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", "Decrypted guardian cold share reduced to zero");
669
+ const expectedYkComp33 = pkg.guardianColdPublicSharesComp33[guardianIndex - 1];
670
+ const expectedYk = require_secp256k1_scalar.decodePointCompressed(expectedYkComp33, false);
671
+ if (!require_secp256k1_scalar.mulBaseG(shareScalar).equals(expectedYk)) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", `Decrypted guardian cold share g(${guardianIndex}) * G != Y_${guardianIndex}`);
672
+ return {
673
+ guardianIndex,
674
+ coldShareBytes32: require_secp256k1_scalar.scalarToBytes32(shareScalar),
675
+ coldPublicShareComp33: new Uint8Array(expectedYkComp33),
676
+ decodedLimbs16
677
+ };
678
+ } finally {
679
+ skScalar = 0n;
680
+ shareScalar = 0n;
681
+ if (wipeSecretKeyInput) require_secp256k1_scalar.zeroizeBytes(guardianSecretKeyBytes32);
682
+ }
683
+ }
684
+ /**
685
+ * Exports a deterministic, human-verifiable `PrintableManifestCard` pinning `ctxDkg`, `hDkg`,
686
+ * `rootPublicKey`, `escapeColdWallet`, `C^{cold}_{0..t_c-1}`, `Y_{1..n_c}`, `EK_{1..n_c}`, and
687
+ * `sha256(recoveryPackageBytes)` for air-gapped custodian and disaster-recovery verification.
688
+ */
689
+ function exportPrintableManifestCard(params) {
690
+ const { clusterId, rootId, keyEpoch, t, nParties, tCold, nCold, ctxDkg32, hDkg32, rootPublicKeyComp33, escapeColdWallet, coldFeldmanCommitmentsComp33, guardianColdPublicSharesComp33, guardianPublicKeysComp33, recoveryPackageHash32 } = params;
691
+ if (typeof clusterId !== "string" || clusterId.trim().length === 0 || typeof rootId !== "string" || rootId.trim().length === 0 || typeof keyEpoch !== "bigint" || keyEpoch < 1n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Invalid clusterId, rootId, or keyEpoch for manifest card");
692
+ if (!Number.isInteger(t) || !Number.isInteger(nParties) || t < 2 || t > nParties || nParties > require_constants.MAX_MPC_CLUSTER_NODES || !Number.isInteger(tCold) || !Number.isInteger(nCold) || tCold < 1 || tCold > nCold || nCold > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Invalid online or cold threshold dimensions for manifest card");
693
+ if (ctxDkg32.length !== 32 || hDkg32.length !== 32 || recoveryPackageHash32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Manifest hashes must be 32 bytes");
694
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false);
695
+ const rootEthAddress = require_tweak.pointToEthAddress(pRoot).checksumAddress;
696
+ const normalizedEscape = require_tweak.parseStrictEthAddress(escapeColdWallet).checksumAddress;
697
+ if (coldFeldmanCommitmentsComp33.length !== tCold || guardianColdPublicSharesComp33.length !== nCold || guardianPublicKeysComp33.length !== nCold) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Cold commitment/guardian vector length mismatch");
698
+ const coldPoints = coldFeldmanCommitmentsComp33.map((c) => require_secp256k1_scalar.decodePointCompressed(c, false));
699
+ if (!coldPoints[0].equals(pRoot)) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Manifest C^{cold}_0 must equal rootPublicKey");
700
+ const seenEk = /* @__PURE__ */ new Set();
701
+ for (let k = 1; k <= nCold; k++) {
702
+ const ekHexKey = (0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.decodePointCompressed(guardianPublicKeysComp33[k - 1], false).toBytes(true));
703
+ if (seenEk.has(ekHexKey)) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Duplicate guardian public key in manifest card");
704
+ seenEk.add(ekHexKey);
705
+ const expectedYk = require_secp256k1_scalar.evaluateFeldmanCommitments(coldPoints, k);
706
+ const givenYk = require_secp256k1_scalar.decodePointCompressed(guardianColdPublicSharesComp33[k - 1], false);
707
+ if (expectedYk.is0() || !expectedYk.equals(givenYk)) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Manifest Y_${k} does not match Feldman evaluation`);
708
+ }
709
+ const ctxDkgHex = `0x${(0, _noble_hashes_utils_js.bytesToHex)(ctxDkg32)}`;
710
+ const hDkgHex = `0x${(0, _noble_hashes_utils_js.bytesToHex)(hDkg32)}`;
711
+ const rootPublicKeyHex = `0x${(0, _noble_hashes_utils_js.bytesToHex)(rootPublicKeyComp33)}`;
712
+ const recoveryPackageSha256Hex = `0x${(0, _noble_hashes_utils_js.bytesToHex)(recoveryPackageHash32)}`;
713
+ const coldFeldmanCommitmentsHex = coldFeldmanCommitmentsComp33.map((c) => `0x${(0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.decodePointCompressed(c, false).toBytes(true))}`);
714
+ const guardianColdPublicSharesHex = guardianColdPublicSharesComp33.map((y) => `0x${(0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.decodePointCompressed(y, false).toBytes(true))}`);
715
+ const guardianPublicKeysHex = guardianPublicKeysComp33.map((ek) => `0x${(0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.decodePointCompressed(ek, false).toBytes(true))}`);
716
+ const guardianLines = guardianColdPublicSharesHex.map((yHex, idx) => ` [${idx + 1}] ${require_steel_mnemonic.guardianIndexToPlateLabel(idx + 1)}: EK=${guardianPublicKeysHex[idx]} | Y_${idx + 1}=${yHex}`);
717
+ const printableText = [
718
+ "=== ARC LOGICAL-HSM COLD RECOVERY MANIFEST CARD (V2) ===",
719
+ `Cluster / Root : ${clusterId} / ${rootId} (epoch ${keyEpoch.toString()})`,
720
+ `Quorums : Online ${t}-of-${nParties} | Cold Steel ${tCold}-of-${nCold} (24w BIP-39, ZERO passphrase)`,
721
+ `Root EOA : ${rootEthAddress} (${rootPublicKeyHex})`,
722
+ `Escape Wallet : ${normalizedEscape} [IMMUTABLE DESTINATION LOCK]`,
723
+ `ctx_dkg : ${ctxDkgHex}`,
724
+ `H_dkg : ${hDkgHex}`,
725
+ `VES Pkg SHA256 : ${recoveryPackageSha256Hex}`,
726
+ "Custodian Plates:",
727
+ ...guardianLines,
728
+ "========================================================"
729
+ ].join("\n");
730
+ return {
731
+ version: 2,
732
+ clusterId,
733
+ rootId,
734
+ keyEpoch: keyEpoch.toString(),
735
+ t,
736
+ nParties,
737
+ tCold,
738
+ nCold,
739
+ ctxDkgHex,
740
+ hDkgHex,
741
+ rootPublicKeyHex,
742
+ rootEthAddress,
743
+ escapeColdWallet: normalizedEscape,
744
+ coldFeldmanCommitmentsHex,
745
+ guardianColdPublicSharesHex,
746
+ guardianPublicKeysHex,
747
+ recoveryPackageSha256Hex,
748
+ printableText
749
+ };
750
+ }
751
+ /**
752
+ * Validates full internal & human-readable (`printableText`) self-consistency of a `PrintableManifestCard`:
753
+ * - Enforces version, integer bounds, EIP-55 `escapeColdWallet` & `rootEthAddress`, `C^{cold}_0 == P_root`,
754
+ * distinct `EK_k`, and `Y_k == \sum_l k^l C^{cold}_l`.
755
+ * - Recomputes canonical `printableText` via `exportPrintableManifestCard` and rejects any split-view
756
+ * mismatch between JSON fields (such as `escapeColdWallet`) and `printableText`.
757
+ */
758
+ function validatePrintableManifestCard(manifest) {
759
+ if (!manifest || manifest.version !== 2 || typeof manifest.keyEpoch !== "string" || !/^[1-9]\d*$/.test(manifest.keyEpoch) || !Array.isArray(manifest.coldFeldmanCommitmentsHex) || !Array.isArray(manifest.guardianColdPublicSharesHex) || !Array.isArray(manifest.guardianPublicKeysHex) || typeof manifest.printableText !== "string") throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Malformed PrintableManifestCard structure");
760
+ let canonical;
761
+ try {
762
+ canonical = exportPrintableManifestCard({
763
+ clusterId: manifest.clusterId,
764
+ rootId: manifest.rootId,
765
+ keyEpoch: BigInt(manifest.keyEpoch),
766
+ t: manifest.t,
767
+ nParties: manifest.nParties,
768
+ tCold: manifest.tCold,
769
+ nCold: manifest.nCold,
770
+ ctxDkg32: require_secp256k1_scalar.normalizeHexBytes(manifest.ctxDkgHex, 32),
771
+ hDkg32: require_secp256k1_scalar.normalizeHexBytes(manifest.hDkgHex, 32),
772
+ rootPublicKeyComp33: require_secp256k1_scalar.normalizeHexBytes(manifest.rootPublicKeyHex, 33),
773
+ escapeColdWallet: manifest.escapeColdWallet,
774
+ coldFeldmanCommitmentsComp33: manifest.coldFeldmanCommitmentsHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33)),
775
+ guardianColdPublicSharesComp33: manifest.guardianColdPublicSharesHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33)),
776
+ guardianPublicKeysComp33: manifest.guardianPublicKeysHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33)),
777
+ recoveryPackageHash32: require_secp256k1_scalar.normalizeHexBytes(manifest.recoveryPackageSha256Hex, 32)
778
+ });
779
+ } catch (err) {
780
+ throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", `Invalid PrintableManifestCard: ${err.message}`);
781
+ }
782
+ if (manifest.rootEthAddress !== canonical.rootEthAddress || manifest.escapeColdWallet !== canonical.escapeColdWallet || manifest.ctxDkgHex.toLowerCase() !== canonical.ctxDkgHex.toLowerCase() || manifest.hDkgHex.toLowerCase() !== canonical.hDkgHex.toLowerCase() || manifest.rootPublicKeyHex.toLowerCase() !== canonical.rootPublicKeyHex.toLowerCase() || manifest.recoveryPackageSha256Hex.toLowerCase() !== canonical.recoveryPackageSha256Hex.toLowerCase() || manifest.printableText !== canonical.printableText) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "PrintableManifestCard failed canonical or printableText consistency check (possible escapeColdWallet spoofing)");
783
+ }
784
+ function verifyManifestAgainstDkgConfig(manifest, config) {
785
+ try {
786
+ validatePrintableManifestCard(manifest);
787
+ const { ctxDkg32, normalizedEscapeColdWallet } = require_dkg.validateAndComputeDkgContext(config);
788
+ if (manifest.clusterId !== config.clusterId || manifest.rootId !== config.rootId || BigInt(manifest.keyEpoch) !== config.keyEpoch || manifest.t !== config.t || manifest.nParties !== config.nParties || manifest.tCold !== config.tCold || manifest.nCold !== config.nCold || manifest.escapeColdWallet !== normalizedEscapeColdWallet || !require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(manifest.ctxDkgHex, 32), ctxDkg32)) return false;
789
+ for (let k = 0; k < config.nCold; k++) if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(manifest.guardianPublicKeysHex[k], 33), config.guardianPublicKeysComp33[k])) return false;
790
+ return true;
791
+ } catch {
792
+ return false;
793
+ }
794
+ }
795
+ function verifyManifestAgainstRecoveryPackage(manifest, recoveryPackageBytes) {
796
+ try {
797
+ validatePrintableManifestCard(manifest);
798
+ const expectedPkgHash32 = require_secp256k1_scalar.normalizeHexBytes(manifest.recoveryPackageSha256Hex, 32);
799
+ if (!require_secp256k1_scalar.constantTimeEqual((0, _noble_hashes_sha2_js.sha256)(recoveryPackageBytes), expectedPkgHash32)) return false;
800
+ const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
801
+ if (pkg.nParties !== manifest.nParties || pkg.tCold !== manifest.tCold || pkg.nCold !== manifest.nCold || !require_secp256k1_scalar.constantTimeEqual(pkg.ctxDkg32, require_secp256k1_scalar.normalizeHexBytes(manifest.ctxDkgHex, 32)) || !require_secp256k1_scalar.constantTimeEqual(pkg.hDkg32, require_secp256k1_scalar.normalizeHexBytes(manifest.hDkgHex, 32))) return false;
802
+ for (let k = 0; k < pkg.nCold; k++) if (!require_secp256k1_scalar.constantTimeEqual(pkg.guardianColdPublicSharesComp33[k], require_secp256k1_scalar.normalizeHexBytes(manifest.guardianColdPublicSharesHex[k], 33))) return false;
803
+ return verifyRecoveryPackage(recoveryPackageBytes, {
804
+ ctxDkg32: require_secp256k1_scalar.normalizeHexBytes(manifest.ctxDkgHex, 32),
805
+ rootPublicKeyComp33: require_secp256k1_scalar.normalizeHexBytes(manifest.rootPublicKeyHex, 33),
806
+ aggColdCommitmentsComp33: manifest.coldFeldmanCommitmentsHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33)),
807
+ guardianPublicKeysComp33: manifest.guardianPublicKeysHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33))
808
+ });
809
+ } catch {
810
+ return false;
811
+ }
812
+ }
813
+ function computeCanaryChallengeDigest32(bundle) {
814
+ if (!bundle || bundle.version !== 2 || typeof bundle.rootId !== "string" || bundle.rootId.trim().length === 0 || typeof bundle.challengeId !== "string" || bundle.challengeId.trim().length === 0 || typeof bundle.keyEpoch !== "string" || !/^[1-9]\d*$/.test(bundle.keyEpoch)) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "Malformed CanaryChallengeBundle");
815
+ const keyEpochBig = BigInt(bundle.keyEpoch);
816
+ if (!Number.isSafeInteger(bundle.issuedAtSec) || bundle.issuedAtSec < 0 || !Number.isSafeInteger(bundle.expiresAtSec) || bundle.expiresAtSec <= bundle.issuedAtSec || bundle.expiresAtSec - bundle.issuedAtSec > 900) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "CanaryChallengeBundle TTL must satisfy 0 < ttl <= 900s");
817
+ const ctxDkg32 = require_secp256k1_scalar.normalizeHexBytes(bundle.ctxDkgHex, 32);
818
+ const hDkg32 = require_secp256k1_scalar.normalizeHexBytes(bundle.hDkgHex, 32);
819
+ const nonce32 = require_secp256k1_scalar.normalizeHexBytes(bundle.challengeNonceHex, 32);
820
+ if (!Number.isInteger(bundle.nCold) || bundle.nCold < 1 || bundle.nCold > require_constants.MAX_MPC_CLUSTER_NODES || !Array.isArray(bundle.guardianColdPublicSharesHex) || bundle.guardianColdPublicSharesHex.length !== bundle.nCold) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "Invalid guardianColdPublicSharesHex in CanaryChallengeBundle");
821
+ const yParts = bundle.guardianColdPublicSharesHex.map((h) => require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(h, 33), false).toBytes(true));
822
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_CANARY_CHALLENGE_V1, require_secp256k1_scalar.utf8Bytes(bundle.rootId), require_secp256k1_scalar.u64be(keyEpochBig), ctxDkg32, hDkg32, require_secp256k1_scalar.utf8Bytes(bundle.challengeId), nonce32, require_secp256k1_scalar.u64be(BigInt(bundle.issuedAtSec)), require_secp256k1_scalar.u64be(BigInt(bundle.expiresAtSec)), require_secp256k1_scalar.u16be(bundle.nCold), ...yParts);
823
+ }
824
+ function assertChallengeBundleMatchesManifest(challengeBundle, manifestCard) {
825
+ validatePrintableManifestCard(manifestCard);
826
+ if (manifestCard.rootId !== challengeBundle.rootId || manifestCard.keyEpoch !== challengeBundle.keyEpoch || manifestCard.nCold !== challengeBundle.nCold || !Array.isArray(challengeBundle.guardianColdPublicSharesHex) || challengeBundle.guardianColdPublicSharesHex.length !== manifestCard.nCold || !require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(manifestCard.ctxDkgHex, 32), require_secp256k1_scalar.normalizeHexBytes(challengeBundle.ctxDkgHex, 32)) || !require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(manifestCard.hDkgHex, 32), require_secp256k1_scalar.normalizeHexBytes(challengeBundle.hDkgHex, 32))) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "CanaryChallengeBundle metadata mismatch against pinned PrintableManifestCard");
827
+ for (let k = 0; k < manifestCard.nCold; k++) if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(manifestCard.guardianColdPublicSharesHex[k], 33), require_secp256k1_scalar.normalizeHexBytes(challengeBundle.guardianColdPublicSharesHex[k], 33))) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", `CanaryChallengeBundle Y_${k + 1} mismatch against pinned PrintableManifestCard`);
828
+ }
829
+ function signCanaryChallengeApproval(params) {
830
+ const digest32 = computeCanaryChallengeDigest32(params.bundle);
831
+ const sk = require_secp256k1_scalar.bytes32ToScalarNonZero(params.rosterSigningSecretBytes32);
832
+ const pok = require_secp256k1_scalar.createSchnorrPokInBase({
833
+ dst: require_constants.DST_CANARY_CHALLENGE_V1,
834
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
835
+ statementPoint: require_secp256k1_scalar.mulBaseG(sk),
836
+ secretScalar: sk,
837
+ contextParts: [require_secp256k1_scalar.u16be(params.slot), digest32],
838
+ rng: params.rng
839
+ });
840
+ return {
841
+ slot: params.slot,
842
+ noncePointHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pok.noncePointComp33)}`,
843
+ responseHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pok.responseBytes32)}`
844
+ };
845
+ }
846
+ function verifyCanaryChallengeBundle(bundle, options) {
847
+ try {
848
+ const digest32 = computeCanaryChallengeDigest32(bundle);
849
+ if (options?.trustedNowSec !== void 0) {
850
+ if (!Number.isSafeInteger(options.trustedNowSec) || options.trustedNowSec < bundle.issuedAtSec || options.trustedNowSec >= bundle.expiresAtSec) return false;
851
+ }
852
+ const hasRosterMap = options?.rosterVerifyKeysComp33BySlot !== void 0;
853
+ const hasQuorumT = options?.requiredQuorumT !== void 0;
854
+ if (hasRosterMap !== hasQuorumT) return false;
855
+ if (hasRosterMap && hasQuorumT) {
856
+ const requiredT = options.requiredQuorumT;
857
+ const rosterMap = options.rosterVerifyKeysComp33BySlot;
858
+ if (!Number.isInteger(requiredT) || requiredT < 1 || requiredT > require_constants.MAX_MPC_CLUSTER_NODES || rosterMap.size === 0) return false;
859
+ const approvals = bundle.peerApprovals ?? [];
860
+ if (!Array.isArray(approvals) || approvals.length < requiredT) return false;
861
+ const seenSlots = /* @__PURE__ */ new Set();
862
+ for (const app of approvals) {
863
+ if (!app || !Number.isInteger(app.slot) || app.slot < 1 || seenSlots.has(app.slot)) return false;
864
+ const pkComp33 = rosterMap.get(app.slot);
865
+ if (!pkComp33) return false;
866
+ if (!require_secp256k1_scalar.verifySchnorrPokInBase({
867
+ dst: require_constants.DST_CANARY_CHALLENGE_V1,
868
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
869
+ statementPoint: require_secp256k1_scalar.decodePointCompressed(pkComp33, false),
870
+ proof: {
871
+ noncePointComp33: require_secp256k1_scalar.normalizeHexBytes(app.noncePointHex, 33),
872
+ responseBytes32: require_secp256k1_scalar.normalizeHexBytes(app.responseHex, 32)
873
+ },
874
+ contextParts: [require_secp256k1_scalar.u16be(app.slot), digest32]
875
+ })) return false;
876
+ seenSlots.add(app.slot);
877
+ }
878
+ }
879
+ return true;
880
+ } catch {
881
+ return false;
882
+ }
883
+ }
884
+ /**
885
+ * Generates Custodian `k`'s Schnorr PoK `\pi^{cold}_k` over `(ctxDkg32, u16be(guardianIndex), challengeNonce32)`
886
+ * under cold share `g(k)` (`Y_k = g(k) * G`), proving physical steel-plate possession in zero knowledge
887
+ * WITHOUT revealing `g(k)` or reconstructing `x_root`.
888
+ *
889
+ * Strictly verifies `g(k) * G == Y_k` BEFORE generating the proof whenever `expectedColdPublicShare` is supplied.
890
+ */
891
+ function createColdShardSchnorrPok(params) {
892
+ const { ctxDkg, guardianIndex, challengeNonce, coldShareBytes32, expectedColdPublicShare, rng, wipeColdShareInput = false } = params;
893
+ let gScalar = 0n;
894
+ try {
895
+ if (!Number.isInteger(guardianIndex) || guardianIndex < 1 || guardianIndex > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Invalid guardianIndex: ${guardianIndex}`);
896
+ const ctxDkg32 = require_secp256k1_scalar.normalizeHexBytes(ctxDkg, 32);
897
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(challengeNonce, 32);
898
+ gScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(coldShareBytes32);
899
+ const ykPoint = require_secp256k1_scalar.mulBaseG(gScalar);
900
+ if (expectedColdPublicShare !== void 0) {
901
+ const expectedYkPt = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(expectedColdPublicShare, 33), false);
902
+ if (!ykPoint.equals(expectedYkPt)) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", `Cold share scalar * G does not match expected Y_${guardianIndex}`);
903
+ }
904
+ const pok = require_secp256k1_scalar.createSchnorrPokInBase({
905
+ dst: require_constants.DST_CANARY_SHARD_POK_V1,
906
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
907
+ statementPoint: ykPoint,
908
+ secretScalar: gScalar,
909
+ contextParts: [
910
+ ctxDkg32,
911
+ require_secp256k1_scalar.u16be(guardianIndex),
912
+ challengeNonce32
913
+ ],
914
+ rng
915
+ });
916
+ return {
917
+ guardianIndex,
918
+ coldPublicShareHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.encodePointCompressed(ykPoint))}`,
919
+ noncePointHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pok.noncePointComp33)}`,
920
+ responseHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pok.responseBytes32)}`
921
+ };
922
+ } finally {
923
+ gScalar = 0n;
924
+ if (wipeColdShareInput) require_secp256k1_scalar.zeroizeBytes(coldShareBytes32);
925
+ }
926
+ }
927
+ function verifyColdShardSchnorrPok(params) {
928
+ try {
929
+ const { ctxDkg, challengeNonce, expectedColdPublicShare, shardProof } = params;
930
+ if (!shardProof || !Number.isInteger(shardProof.guardianIndex) || shardProof.guardianIndex < 1) return false;
931
+ const ctxDkg32 = require_secp256k1_scalar.normalizeHexBytes(ctxDkg, 32);
932
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(challengeNonce, 32);
933
+ const expectedYkComp33 = require_secp256k1_scalar.normalizeHexBytes(expectedColdPublicShare, 33);
934
+ if (!require_secp256k1_scalar.constantTimeEqual(expectedYkComp33, require_secp256k1_scalar.normalizeHexBytes(shardProof.coldPublicShareHex, 33))) return false;
935
+ return require_secp256k1_scalar.verifySchnorrPokInBase({
936
+ dst: require_constants.DST_CANARY_SHARD_POK_V1,
937
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
938
+ statementPoint: require_secp256k1_scalar.decodePointCompressed(expectedYkComp33, false),
939
+ proof: {
940
+ noncePointComp33: require_secp256k1_scalar.normalizeHexBytes(shardProof.noncePointHex, 33),
941
+ responseBytes32: require_secp256k1_scalar.normalizeHexBytes(shardProof.responseHex, 32)
942
+ },
943
+ contextParts: [
944
+ ctxDkg32,
945
+ require_secp256k1_scalar.u16be(shardProof.guardianIndex),
946
+ challengeNonce32
947
+ ]
948
+ });
949
+ } catch {
950
+ return false;
951
+ }
952
+ }
953
+ function assembleCanaryActivationCert(params) {
954
+ const { clusterChallengeBundle, shardProofs, manifestCard } = params;
955
+ if (manifestCard) assertChallengeBundleMatchesManifest(clusterChallengeBundle, manifestCard);
956
+ const cert = {
957
+ version: 2,
958
+ clusterChallengeBundle,
959
+ shardProofs: [...shardProofs].sort((a, b) => a.guardianIndex - b.guardianIndex)
960
+ };
961
+ if (!verifyCanaryActivationCert(cert, {
962
+ ctxDkg: manifestCard ? manifestCard.ctxDkgHex : clusterChallengeBundle.ctxDkgHex,
963
+ hDkg: manifestCard ? manifestCard.hDkgHex : clusterChallengeBundle.hDkgHex,
964
+ rootId: manifestCard ? manifestCard.rootId : clusterChallengeBundle.rootId,
965
+ keyEpoch: BigInt(manifestCard ? manifestCard.keyEpoch : clusterChallengeBundle.keyEpoch),
966
+ nCold: manifestCard ? manifestCard.nCold : clusterChallengeBundle.nCold,
967
+ guardianColdPublicSharesComp33: manifestCard ? manifestCard.guardianColdPublicSharesHex : clusterChallengeBundle.guardianColdPublicSharesHex,
968
+ ...manifestCard ? { coldFeldmanCommitmentsComp33: manifestCard.coldFeldmanCommitmentsHex } : {}
969
+ })) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "Assembled CanaryActivationCert failed cryptographic verification");
970
+ return cert;
971
+ }
972
+ /**
973
+ * Verifies a self-verifying `CanaryActivationCert` (`design.md` §5.2):
974
+ * - Validates `clusterChallengeBundle` metadata, TTL (`<= 900s`), optional `trustedNowSec`, and
975
+ * optional `>= t` HSM roster approvals.
976
+ * - Requires ALL `nCold` (`3/3` default) distinct guardian Schnorr PoKs `\pi^{cold}_{1..nCold}`
977
+ * verified against `guardianColdPublicSharesComp33` (`Y_{1..nCold}`) and optional `coldFeldmanCommitmentsComp33`.
978
+ */
979
+ function verifyCanaryActivationCert(cert, expected) {
980
+ try {
981
+ if (!cert || cert.version !== 2 || !cert.clusterChallengeBundle || !Array.isArray(cert.shardProofs)) return false;
982
+ const { clusterChallengeBundle: bundle, shardProofs } = cert;
983
+ if (!verifyCanaryChallengeBundle(bundle, {
984
+ rosterVerifyKeysComp33BySlot: expected.rosterVerifyKeysComp33BySlot,
985
+ requiredQuorumT: expected.requiredQuorumT,
986
+ trustedNowSec: expected.trustedNowSec
987
+ })) return false;
988
+ const expectedCtx32 = require_secp256k1_scalar.normalizeHexBytes(expected.ctxDkg, 32);
989
+ if (!require_secp256k1_scalar.constantTimeEqual(expectedCtx32, require_secp256k1_scalar.normalizeHexBytes(bundle.ctxDkgHex, 32))) return false;
990
+ if (expected.hDkg !== void 0) {
991
+ if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(expected.hDkg, 32), require_secp256k1_scalar.normalizeHexBytes(bundle.hDkgHex, 32))) return false;
992
+ }
993
+ if (expected.rootId !== void 0 && bundle.rootId !== expected.rootId) return false;
994
+ if (expected.keyEpoch !== void 0 && BigInt(bundle.keyEpoch) !== expected.keyEpoch) return false;
995
+ const nCold = expected.nCold;
996
+ if (!Number.isInteger(nCold) || nCold < 1 || nCold > require_constants.MAX_MPC_CLUSTER_NODES || bundle.nCold !== nCold || expected.guardianColdPublicSharesComp33.length !== nCold || bundle.guardianColdPublicSharesHex.length !== nCold || shardProofs.length !== nCold) return false;
997
+ const coldPoints = expected.coldFeldmanCommitmentsComp33?.map((c) => require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(c, 33), false));
998
+ for (let k = 1; k <= nCold; k++) {
999
+ const expectedYk33 = require_secp256k1_scalar.normalizeHexBytes(expected.guardianColdPublicSharesComp33[k - 1], 33);
1000
+ if (!require_secp256k1_scalar.constantTimeEqual(expectedYk33, require_secp256k1_scalar.normalizeHexBytes(bundle.guardianColdPublicSharesHex[k - 1], 33))) return false;
1001
+ if (coldPoints) {
1002
+ const evalYk = require_secp256k1_scalar.evaluateFeldmanCommitments(coldPoints, k);
1003
+ if (evalYk.is0() || !evalYk.equals(require_secp256k1_scalar.decodePointCompressed(expectedYk33, false))) return false;
1004
+ }
1005
+ }
1006
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(bundle.challengeNonceHex, 32);
1007
+ const seenGuardians = /* @__PURE__ */ new Set();
1008
+ for (const sp of shardProofs) {
1009
+ const k = sp.guardianIndex;
1010
+ if (!Number.isInteger(k) || k < 1 || k > nCold || seenGuardians.has(k)) return false;
1011
+ seenGuardians.add(k);
1012
+ if (!verifyColdShardSchnorrPok({
1013
+ ctxDkg: expectedCtx32,
1014
+ challengeNonce: challengeNonce32,
1015
+ expectedColdPublicShare: require_secp256k1_scalar.normalizeHexBytes(expected.guardianColdPublicSharesComp33[k - 1], 33),
1016
+ shardProof: sp
1017
+ })) return false;
1018
+ }
1019
+ return seenGuardians.size === nCold;
1020
+ } catch {
1021
+ return false;
1022
+ }
1023
+ }
1024
+
1025
+ //#endregion
1026
+ exports.DirectBitElGamalVesPlugin = DirectBitElGamalVesPlugin;
1027
+ exports.VES_BITS_PER_CHUNK = VES_BITS_PER_CHUNK;
1028
+ exports.VES_BITS_PER_SHARE = VES_BITS_PER_SHARE;
1029
+ exports.VES_BIT_RECORD_BYTES = VES_BIT_RECORD_BYTES;
1030
+ exports.VES_CHUNKS_PER_SHARE = VES_CHUNKS_PER_SHARE;
1031
+ exports.VES_GUARDIAN_BUNDLE_BYTES = VES_GUARDIAN_BUNDLE_BYTES;
1032
+ exports.VES_LINEAR_DLEQ_BYTES = VES_LINEAR_DLEQ_BYTES;
1033
+ exports.VES_MAX_LIMB_VALUE = VES_MAX_LIMB_VALUE;
1034
+ exports.VES_MAX_SUMMED_LIMB = VES_MAX_SUMMED_LIMB;
1035
+ exports.aggregateRecoveryPackage = aggregateRecoveryPackage;
1036
+ exports.assembleCanaryActivationCert = assembleCanaryActivationCert;
1037
+ exports.assertChallengeBundleMatchesManifest = assertChallengeBundleMatchesManifest;
1038
+ exports.computeCanaryChallengeDigest32 = computeCanaryChallengeDigest32;
1039
+ exports.createColdShardSchnorrPok = createColdShardSchnorrPok;
1040
+ exports.createNodeColdVesContribution = createNodeColdVesContribution;
1041
+ exports.decryptGuardianColdShareBsgs = decryptGuardianColdShareBsgs;
1042
+ exports.exportPrintableManifestCard = exportPrintableManifestCard;
1043
+ exports.parseRecoveryPackageBytes = parseRecoveryPackageBytes;
1044
+ exports.signCanaryChallengeApproval = signCanaryChallengeApproval;
1045
+ exports.solveDiscreteLogBsgs = solveDiscreteLogBsgs;
1046
+ exports.validatePrintableManifestCard = validatePrintableManifestCard;
1047
+ exports.verifyCanaryActivationCert = verifyCanaryActivationCert;
1048
+ exports.verifyCanaryChallengeBundle = verifyCanaryChallengeBundle;
1049
+ exports.verifyColdShardSchnorrPok = verifyColdShardSchnorrPok;
1050
+ exports.verifyManifestAgainstDkgConfig = verifyManifestAgainstDkgConfig;
1051
+ exports.verifyManifestAgainstRecoveryPackage = verifyManifestAgainstRecoveryPackage;
1052
+ exports.verifyNodeColdVesContribution = verifyNodeColdVesContribution;
1053
+ exports.verifyRecoveryPackage = verifyRecoveryPackage;