@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.
- package/esm/constants.d.mts +76 -0
- package/esm/constants.mjs +78 -0
- package/esm/dkg.d.mts +279 -0
- package/esm/dkg.mjs +903 -0
- package/esm/index.d.mts +9 -0
- package/esm/index.mjs +10 -0
- package/esm/mta.d.mts +63 -0
- package/esm/mta.mjs +275 -0
- package/esm/ot.d.mts +187 -0
- package/esm/ot.mjs +593 -0
- package/esm/presign.d.mts +242 -0
- package/esm/presign.mjs +951 -0
- package/esm/secp256k1-scalar.d.mts +141 -0
- package/esm/secp256k1-scalar.mjs +465 -0
- package/esm/sign.d.mts +113 -0
- package/esm/sign.mjs +225 -0
- package/esm/tweak.d.mts +100 -0
- package/esm/tweak.mjs +168 -0
- package/lib/constants.cjs +136 -0
- package/lib/constants.d.cts +76 -0
- package/lib/dkg.cjs +910 -0
- package/lib/dkg.d.cts +279 -0
- package/lib/index.cjs +171 -0
- package/lib/index.d.cts +9 -0
- package/lib/mta.cjs +280 -0
- package/lib/mta.d.cts +63 -0
- package/lib/ot.cjs +609 -0
- package/lib/ot.d.cts +187 -0
- package/lib/presign.cjs +954 -0
- package/lib/presign.d.cts +242 -0
- package/lib/secp256k1-scalar.cjs +518 -0
- package/lib/secp256k1-scalar.d.cts +141 -0
- package/lib/sign.cjs +233 -0
- package/lib/sign.d.cts +113 -0
- package/lib/tweak.cjs +178 -0
- package/lib/tweak.d.cts +100 -0
- package/package.json +75 -4
- package/README.md +0 -3
package/lib/dkg.cjs
ADDED
|
@@ -0,0 +1,910 @@
|
|
|
1
|
+
const require_constants = require('./constants.cjs');
|
|
2
|
+
const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
|
|
3
|
+
const require_tweak = require('./tweak.cjs');
|
|
4
|
+
let node_crypto = require("node:crypto");
|
|
5
|
+
let node_fs = require("node:fs");
|
|
6
|
+
let node_path = require("node:path");
|
|
7
|
+
let _noble_curves_ed25519_js = require("@noble/curves/ed25519.js");
|
|
8
|
+
let _noble_hashes_hkdf_js = require("@noble/hashes/hkdf.js");
|
|
9
|
+
let _noble_hashes_sha2_js = require("@noble/hashes/sha2.js");
|
|
10
|
+
let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
|
|
11
|
+
|
|
12
|
+
//#region src/dkg.ts
|
|
13
|
+
const VALID_CEREMONY_ID_RE = /^[A-Za-z0-9:._-]{1,128}$/;
|
|
14
|
+
const LOWERCASE_HEX_64_RE = /^[0-9a-f]{64}$/;
|
|
15
|
+
const FORBIDDEN_PROTO_IDENTIFIERS = new Set([
|
|
16
|
+
"__proto__",
|
|
17
|
+
"constructor",
|
|
18
|
+
"prototype"
|
|
19
|
+
]);
|
|
20
|
+
const LOCK_SLEEP_ARRAY = new Int32Array(new SharedArrayBuffer(4));
|
|
21
|
+
let atomicTmpSeq = 0;
|
|
22
|
+
function assertSafeCeremonyId(ceremonyId) {
|
|
23
|
+
if (typeof ceremonyId !== "string" || !VALID_CEREMONY_ID_RE.test(ceremonyId) || FORBIDDEN_PROTO_IDENTIFIERS.has(ceremonyId)) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Invalid or unsafe ceremonyId: ${String(ceremonyId)}`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Append-only, fail-closed `DkgEchoLock` supporting in-memory and `0600` exclusive-file-locked
|
|
27
|
+
* atomic `temp+fsync+rename` persisted JSON (`dkg-echo-lock.json`, `design.md` §3.2(3)).
|
|
28
|
+
* Serializes `[ceremonyId, hDkgHex]` tuples (immune to prototype-key collisions) and exposes
|
|
29
|
+
* ZERO delete/clear methods.
|
|
30
|
+
*/
|
|
31
|
+
var AppendOnlyDkgEchoLock = class {
|
|
32
|
+
constructor(options) {
|
|
33
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
34
|
+
this.epochScopes = /* @__PURE__ */ new Map();
|
|
35
|
+
this.filePath = options?.filePath;
|
|
36
|
+
if (this.filePath && (0, node_fs.existsSync)(this.filePath)) {
|
|
37
|
+
const disk = this.loadAndValidateFromDisk(this.filePath);
|
|
38
|
+
for (const [k, v] of disk.entries) this.entries.set(k, v);
|
|
39
|
+
for (const [s, c] of disk.epochScopes) this.epochScopes.set(s, c);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
get size() {
|
|
43
|
+
return this.entries.size;
|
|
44
|
+
}
|
|
45
|
+
getLockedTranscriptHex(ceremonyId) {
|
|
46
|
+
return this.entries.get(ceremonyId);
|
|
47
|
+
}
|
|
48
|
+
loadAndValidateFromDisk(filePath) {
|
|
49
|
+
let raw;
|
|
50
|
+
try {
|
|
51
|
+
raw = (0, node_fs.readFileSync)(filePath, "utf8").trim();
|
|
52
|
+
} catch (err) {
|
|
53
|
+
throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Failed to read dkg-echo-lock file "${filePath}": ${err.message}`);
|
|
54
|
+
}
|
|
55
|
+
if (raw.length === 0) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Corrupted dkg-echo-lock file "${filePath}": empty or whitespace-only`);
|
|
56
|
+
let parsed;
|
|
57
|
+
try {
|
|
58
|
+
parsed = JSON.parse(raw);
|
|
59
|
+
} catch (err) {
|
|
60
|
+
throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Corrupted dkg-echo-lock JSON in "${filePath}": ${err.message}`);
|
|
61
|
+
}
|
|
62
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || parsed.version !== 1 || !Array.isArray(parsed.entries) || !Array.isArray(parsed.epochScopes)) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Invalid dkg-echo-lock schema or unsupported version in "${filePath}"`);
|
|
63
|
+
const v1 = parsed;
|
|
64
|
+
const diskEntries = /* @__PURE__ */ new Map();
|
|
65
|
+
for (const item of v1.entries) {
|
|
66
|
+
if (!Array.isArray(item) || item.length !== 2 || typeof item[0] !== "string" || typeof item[1] !== "string" || !LOWERCASE_HEX_64_RE.test(item[1])) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Malformed entry tuple in dkg-echo-lock "${filePath}"`);
|
|
67
|
+
if (!VALID_CEREMONY_ID_RE.test(item[0]) || FORBIDDEN_PROTO_IDENTIFIERS.has(item[0])) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Unsafe ceremonyId in dkg-echo-lock "${filePath}"`);
|
|
68
|
+
const prev = diskEntries.get(item[0]);
|
|
69
|
+
if (prev !== void 0 && prev !== item[1]) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Conflicting duplicate ceremonyId="${item[0]}" in dkg-echo-lock "${filePath}"`);
|
|
70
|
+
diskEntries.set(item[0], item[1]);
|
|
71
|
+
}
|
|
72
|
+
const diskScopes = /* @__PURE__ */ new Map();
|
|
73
|
+
for (const sc of v1.epochScopes) {
|
|
74
|
+
if (!Array.isArray(sc) || sc.length !== 2 || typeof sc[0] !== "string" || sc[0].trim().length === 0 || FORBIDDEN_PROTO_IDENTIFIERS.has(sc[0]) || typeof sc[1] !== "string") throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Malformed epochScope tuple in dkg-echo-lock "${filePath}"`);
|
|
75
|
+
if (!VALID_CEREMONY_ID_RE.test(sc[1]) || FORBIDDEN_PROTO_IDENTIFIERS.has(sc[1]) || !diskEntries.has(sc[1])) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Dangling or invalid epochScope reference "${sc[1]}" in dkg-echo-lock "${filePath}"`);
|
|
76
|
+
const prevCeremony = diskScopes.get(sc[0]);
|
|
77
|
+
if (prevCeremony !== void 0 && prevCeremony !== sc[1]) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Conflicting duplicate epochScope "${sc[0]}" in dkg-echo-lock "${filePath}"`);
|
|
78
|
+
diskScopes.set(sc[0], sc[1]);
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
entries: diskEntries,
|
|
82
|
+
epochScopes: diskScopes
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
withExclusiveFileLock(filePath, fn) {
|
|
86
|
+
const lockFilePath = `${filePath}.lock`;
|
|
87
|
+
let lockFd = null;
|
|
88
|
+
const maxAttempts = 200;
|
|
89
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) try {
|
|
90
|
+
lockFd = (0, node_fs.openSync)(lockFilePath, "wx", 384);
|
|
91
|
+
break;
|
|
92
|
+
} catch (err) {
|
|
93
|
+
if (err.code === "EEXIST" && attempt + 1 < maxAttempts) {
|
|
94
|
+
Atomics.wait(LOCK_SLEEP_ARRAY, 0, 0, 5);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Failed to acquire exclusive dkg-echo-lock "${lockFilePath}": ${err.message}`);
|
|
98
|
+
}
|
|
99
|
+
if (lockFd === null) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Timed out acquiring "${lockFilePath}"`);
|
|
100
|
+
try {
|
|
101
|
+
return fn();
|
|
102
|
+
} finally {
|
|
103
|
+
try {
|
|
104
|
+
(0, node_fs.closeSync)(lockFd);
|
|
105
|
+
} catch {}
|
|
106
|
+
try {
|
|
107
|
+
(0, node_fs.unlinkSync)(lockFilePath);
|
|
108
|
+
} catch {}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
recordAndVerify(ceremonyId, hDkg32, epochScopeKey) {
|
|
112
|
+
assertSafeCeremonyId(ceremonyId);
|
|
113
|
+
if (!(hDkg32 instanceof Uint8Array) || hDkg32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "hDkg32 must be 32 bytes");
|
|
114
|
+
if (epochScopeKey !== void 0 && (typeof epochScopeKey !== "string" || epochScopeKey.trim().length === 0 || FORBIDDEN_PROTO_IDENTIFIERS.has(epochScopeKey))) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "Invalid epochScopeKey");
|
|
115
|
+
const candidateHex = (0, _noble_hashes_utils_js.bytesToHex)(hDkg32);
|
|
116
|
+
if (!this.filePath) {
|
|
117
|
+
this.verifyAndCommitInMemory(this.entries, this.epochScopes, ceremonyId, candidateHex, epochScopeKey);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const targetPath = this.filePath;
|
|
121
|
+
this.withExclusiveFileLock(targetPath, () => {
|
|
122
|
+
const mergedEntries = /* @__PURE__ */ new Map();
|
|
123
|
+
const mergedScopes = /* @__PURE__ */ new Map();
|
|
124
|
+
if ((0, node_fs.existsSync)(targetPath)) {
|
|
125
|
+
const disk = this.loadAndValidateFromDisk(targetPath);
|
|
126
|
+
for (const [k, v] of disk.entries) mergedEntries.set(k, v);
|
|
127
|
+
for (const [s, c] of disk.epochScopes) mergedScopes.set(s, c);
|
|
128
|
+
}
|
|
129
|
+
for (const [k, v] of this.entries) {
|
|
130
|
+
const onDisk = mergedEntries.get(k);
|
|
131
|
+
if (onDisk !== void 0 && onDisk !== v) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `In-memory vs on-disk dkg-echo-lock conflict for ceremonyId="${k}"`);
|
|
132
|
+
mergedEntries.set(k, v);
|
|
133
|
+
}
|
|
134
|
+
for (const [s, c] of this.epochScopes) {
|
|
135
|
+
const onDiskScope = mergedScopes.get(s);
|
|
136
|
+
if (onDiskScope !== void 0 && onDiskScope !== c) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `In-memory vs on-disk dkg-echo-lock scope conflict for "${s}"`);
|
|
137
|
+
mergedScopes.set(s, c);
|
|
138
|
+
}
|
|
139
|
+
for (const [k, v] of mergedEntries) this.entries.set(k, v);
|
|
140
|
+
for (const [s, c] of mergedScopes) this.epochScopes.set(s, c);
|
|
141
|
+
if (epochScopeKey !== void 0) {
|
|
142
|
+
const lockedCeremonyForEpoch = mergedScopes.get(epochScopeKey);
|
|
143
|
+
if (lockedCeremonyForEpoch !== void 0 && lockedCeremonyForEpoch !== ceremonyId) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Epoch scope "${epochScopeKey}" already locked to ceremonyId="${lockedCeremonyForEpoch}"`);
|
|
144
|
+
}
|
|
145
|
+
const existing = mergedEntries.get(ceremonyId);
|
|
146
|
+
if (existing !== void 0) {
|
|
147
|
+
if (existing !== candidateHex) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Split-transcript DKG echo refused for ceremonyId="${ceremonyId}": locked=${existing}, got=${candidateHex}`);
|
|
148
|
+
if (epochScopeKey === void 0 || mergedScopes.get(epochScopeKey) === ceremonyId) return;
|
|
149
|
+
}
|
|
150
|
+
mergedEntries.set(ceremonyId, candidateHex);
|
|
151
|
+
if (epochScopeKey !== void 0) mergedScopes.set(epochScopeKey, ceremonyId);
|
|
152
|
+
this.persistAtomicFsync(mergedEntries, mergedScopes);
|
|
153
|
+
this.entries.set(ceremonyId, candidateHex);
|
|
154
|
+
if (epochScopeKey !== void 0) this.epochScopes.set(epochScopeKey, ceremonyId);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
verifyAndCommitInMemory(entriesMap, scopesMap, ceremonyId, candidateHex, epochScopeKey) {
|
|
158
|
+
if (epochScopeKey !== void 0) {
|
|
159
|
+
const lockedCeremonyForEpoch = scopesMap.get(epochScopeKey);
|
|
160
|
+
if (lockedCeremonyForEpoch !== void 0 && lockedCeremonyForEpoch !== ceremonyId) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Epoch scope "${epochScopeKey}" already locked to ceremonyId="${lockedCeremonyForEpoch}"`);
|
|
161
|
+
}
|
|
162
|
+
const existing = entriesMap.get(ceremonyId);
|
|
163
|
+
if (existing !== void 0) {
|
|
164
|
+
if (existing !== candidateHex) throw new require_constants.MpcProtocolError("DKG_ECHO_LOCK_CONFLICT", `Split-transcript DKG echo refused for ceremonyId="${ceremonyId}": locked=${existing}, got=${candidateHex}`);
|
|
165
|
+
if (epochScopeKey !== void 0) scopesMap.set(epochScopeKey, ceremonyId);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
entriesMap.set(ceremonyId, candidateHex);
|
|
169
|
+
if (epochScopeKey !== void 0) scopesMap.set(epochScopeKey, ceremonyId);
|
|
170
|
+
}
|
|
171
|
+
persistAtomicFsync(entriesMap, scopesMap) {
|
|
172
|
+
if (!this.filePath) return;
|
|
173
|
+
const payload = {
|
|
174
|
+
version: 1,
|
|
175
|
+
entries: Array.from(entriesMap.entries()),
|
|
176
|
+
epochScopes: Array.from(scopesMap.entries())
|
|
177
|
+
};
|
|
178
|
+
const serialized = `${JSON.stringify(payload, null, 2)}\n`;
|
|
179
|
+
atomicTmpSeq += 1;
|
|
180
|
+
const tmpPath = `${this.filePath}.tmp.${process.pid}.${atomicTmpSeq}`;
|
|
181
|
+
const fd = (0, node_fs.openSync)(tmpPath, "w", 384);
|
|
182
|
+
try {
|
|
183
|
+
(0, node_fs.writeSync)(fd, serialized, 0, "utf8");
|
|
184
|
+
(0, node_fs.fsyncSync)(fd);
|
|
185
|
+
} catch (err) {
|
|
186
|
+
try {
|
|
187
|
+
(0, node_fs.closeSync)(fd);
|
|
188
|
+
} catch {}
|
|
189
|
+
try {
|
|
190
|
+
(0, node_fs.unlinkSync)(tmpPath);
|
|
191
|
+
} catch {}
|
|
192
|
+
throw err;
|
|
193
|
+
}
|
|
194
|
+
(0, node_fs.closeSync)(fd);
|
|
195
|
+
(0, node_fs.renameSync)(tmpPath, this.filePath);
|
|
196
|
+
try {
|
|
197
|
+
const dirFd = (0, node_fs.openSync)((0, node_path.dirname)(this.filePath), "r");
|
|
198
|
+
try {
|
|
199
|
+
(0, node_fs.fsyncSync)(dirFd);
|
|
200
|
+
} finally {
|
|
201
|
+
(0, node_fs.closeSync)(dirFd);
|
|
202
|
+
}
|
|
203
|
+
} catch {}
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
function validateAndComputeDkgContext(config) {
|
|
207
|
+
if (config.protocolVersion !== require_constants.MPC_PROTOCOL_VERSION) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Unsupported DKG protocolVersion: ${String(config.protocolVersion)}`);
|
|
208
|
+
if (!Number.isInteger(config.t) || !Number.isInteger(config.nParties) || config.t < 2 || config.t > config.nParties || config.nParties > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Invalid online threshold (${config.t}-of-${config.nParties})`);
|
|
209
|
+
if (!Number.isInteger(config.tCold) || !Number.isInteger(config.nCold) || config.tCold < 1 || config.tCold > config.nCold || config.nCold > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Invalid cold threshold (${config.tCold}-of-${config.nCold})`);
|
|
210
|
+
if (!config.clusterId || !config.rootId || !config.ceremonyId || config.keyEpoch < 1n || !config.ocapAnchor.ocapChainId || !config.ocapAnchor.quorumRule) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "Missing required DKG / OCAP anchor strings");
|
|
211
|
+
assertSafeCeremonyId(config.ceremonyId);
|
|
212
|
+
const escapeParsed = require_tweak.parseStrictEthAddress(config.escapeColdWallet);
|
|
213
|
+
const genesisHash32 = require_secp256k1_scalar.normalizeHexBytes(config.ocapAnchor.genesisHash, 32);
|
|
214
|
+
const initialClusterHash32 = require_secp256k1_scalar.normalizeHexBytes(config.ocapAnchor.initialClusterConfigHash, 32);
|
|
215
|
+
if (config.roster.length !== config.nParties) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "Roster length must equal nParties");
|
|
216
|
+
const sortedRoster = [...config.roster].sort((a, b) => a.slot - b.slot);
|
|
217
|
+
const seenDids = /* @__PURE__ */ new Set();
|
|
218
|
+
const rosterParts = [];
|
|
219
|
+
for (let idx = 0; idx < sortedRoster.length; idx++) {
|
|
220
|
+
const entry = sortedRoster[idx];
|
|
221
|
+
if (entry.slot !== idx + 1 || !entry.nodeDid || seenDids.has(entry.nodeDid)) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Roster must have contiguous slots 1..${config.nParties} and unique nodeDids`);
|
|
222
|
+
require_secp256k1_scalar.decodePointCompressed(entry.echoVerifyPublicKeyComp33, false);
|
|
223
|
+
seenDids.add(entry.nodeDid);
|
|
224
|
+
rosterParts.push(require_secp256k1_scalar.lengthPrefixedEncode("ROSTER-ITEM", [
|
|
225
|
+
require_secp256k1_scalar.u16be(entry.slot),
|
|
226
|
+
require_secp256k1_scalar.utf8Bytes(entry.nodeDid),
|
|
227
|
+
entry.echoVerifyPublicKeyComp33
|
|
228
|
+
]));
|
|
229
|
+
}
|
|
230
|
+
if (config.guardianPublicKeysComp33.length !== config.nCold) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "guardianPublicKeysComp33 length must equal nCold");
|
|
231
|
+
const seenGuardianHex = /* @__PURE__ */ new Set();
|
|
232
|
+
for (const gpk of config.guardianPublicKeysComp33) {
|
|
233
|
+
require_secp256k1_scalar.decodePointCompressed(gpk, false);
|
|
234
|
+
const hex = (0, _noble_hashes_utils_js.bytesToHex)(gpk);
|
|
235
|
+
if (seenGuardianHex.has(hex)) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "Duplicate guardian public key");
|
|
236
|
+
seenGuardianHex.add(hex);
|
|
237
|
+
}
|
|
238
|
+
const rosterBytes = require_secp256k1_scalar.lengthPrefixedEncode("ROSTER-LIST", rosterParts);
|
|
239
|
+
const guardianKeysBytes = require_secp256k1_scalar.lengthPrefixedEncode("GUARDIAN-LIST", config.guardianPublicKeysComp33);
|
|
240
|
+
return {
|
|
241
|
+
ctxDkg32: require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_DKG_CTX_V2, require_secp256k1_scalar.u16be(config.protocolVersion), require_secp256k1_scalar.u16be(config.t), require_secp256k1_scalar.u16be(config.nParties), require_secp256k1_scalar.u16be(config.tCold), require_secp256k1_scalar.u16be(config.nCold), require_secp256k1_scalar.utf8Bytes(config.clusterId), require_secp256k1_scalar.utf8Bytes(config.rootId), require_secp256k1_scalar.u64be(config.keyEpoch), require_secp256k1_scalar.utf8Bytes(config.ceremonyId), escapeParsed.addressBytes20, require_secp256k1_scalar.utf8Bytes(config.ocapAnchor.ocapChainId), genesisHash32, require_secp256k1_scalar.u64be(config.ocapAnchor.initialValidatorEpoch), initialClusterHash32, require_secp256k1_scalar.utf8Bytes(config.ocapAnchor.quorumRule), rosterBytes, guardianKeysBytes),
|
|
242
|
+
normalizedEscapeColdWallet: escapeParsed.checksumAddress,
|
|
243
|
+
sortedRoster
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function computeDkgContextHash32(config) {
|
|
247
|
+
return validateAndComputeDkgContext(config).ctxDkg32;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Deterministic 32-byte message digest signed by subset `S` during DKG Step-4 self-testing,
|
|
251
|
+
* bound to `(DST_DKG_SELFTEST_V2, ctxDkg32, sortedSubsetBytes(S))`.
|
|
252
|
+
*/
|
|
253
|
+
function computeDkgSubsetSelfTestDigest32(ctxDkg32, subset) {
|
|
254
|
+
if (!(ctxDkg32 instanceof Uint8Array) || ctxDkg32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "ctxDkg32 must be 32 bytes");
|
|
255
|
+
return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_DKG_SELFTEST_V2, ctxDkg32, require_secp256k1_scalar.sortedSubsetBytes(require_secp256k1_scalar.normalizeSortedSubset(subset)));
|
|
256
|
+
}
|
|
257
|
+
function encodeDkgRevealBody(reveal) {
|
|
258
|
+
const pokParts = [];
|
|
259
|
+
for (const p of reveal.onlineCoeffPoks) pokParts.push(p.noncePointComp33, p.responseBytes32);
|
|
260
|
+
for (const p of reveal.coldExtraCoeffPoks) pokParts.push(p.noncePointComp33, p.responseBytes32);
|
|
261
|
+
return require_secp256k1_scalar.lengthPrefixedEncode("DKG-REVEAL-BODY-V2", [
|
|
262
|
+
require_secp256k1_scalar.u16be(reveal.dealerSlot),
|
|
263
|
+
reveal.ephemeralX25519Pub32,
|
|
264
|
+
...reveal.onlineCommitmentsComp33,
|
|
265
|
+
...reveal.coldCommitmentsComp33,
|
|
266
|
+
...pokParts,
|
|
267
|
+
reveal.coldVesPayload
|
|
268
|
+
]);
|
|
269
|
+
}
|
|
270
|
+
function computeDkgCommitmentHash(ctxDkg32, dealerSlot, comSalt32, revealBody) {
|
|
271
|
+
return (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_DKG_COM_V2, [
|
|
272
|
+
ctxDkg32,
|
|
273
|
+
require_secp256k1_scalar.u16be(dealerSlot),
|
|
274
|
+
comSalt32,
|
|
275
|
+
revealBody
|
|
276
|
+
]));
|
|
277
|
+
}
|
|
278
|
+
function sealDkgShareX25519Gcm(params) {
|
|
279
|
+
const shared = require_secp256k1_scalar.computeX25519SharedSecret(params.dealerX25519Secret32, params.recipientX25519Pub32, "DKG_SHARE_DECRYPT_FAILED", params.recipientSlot);
|
|
280
|
+
const aeadKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, shared, require_secp256k1_scalar.concatBytes(params.dealerX25519Pub32, params.recipientX25519Pub32), require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_DKG_X25519_HKDF_V2, [
|
|
281
|
+
params.ctxDkg32,
|
|
282
|
+
require_secp256k1_scalar.u16be(params.dealerSlot),
|
|
283
|
+
require_secp256k1_scalar.u16be(params.recipientSlot)
|
|
284
|
+
]), 32);
|
|
285
|
+
require_secp256k1_scalar.zeroizeBytes(shared);
|
|
286
|
+
const iv12 = params.rng(12);
|
|
287
|
+
const aad = require_secp256k1_scalar.concatBytes(require_secp256k1_scalar.utf8Bytes(require_constants.DST_DKG_SHARE_AAD_V2), params.ctxDkg32, require_secp256k1_scalar.u16be(params.dealerSlot), require_secp256k1_scalar.u16be(params.recipientSlot));
|
|
288
|
+
try {
|
|
289
|
+
const cipher = (0, node_crypto.createCipheriv)("aes-256-gcm", aeadKey32, iv12);
|
|
290
|
+
cipher.setAAD(aad);
|
|
291
|
+
const ciphertext32 = require_secp256k1_scalar.concatBytes(cipher.update(params.shareBytes32), cipher.final());
|
|
292
|
+
const authTag16 = new Uint8Array(cipher.getAuthTag());
|
|
293
|
+
return {
|
|
294
|
+
dealerSlot: params.dealerSlot,
|
|
295
|
+
recipientSlot: params.recipientSlot,
|
|
296
|
+
iv12,
|
|
297
|
+
ciphertext32,
|
|
298
|
+
authTag16
|
|
299
|
+
};
|
|
300
|
+
} finally {
|
|
301
|
+
require_secp256k1_scalar.zeroizeBytes(aeadKey32);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function openDkgShareX25519Gcm(params) {
|
|
305
|
+
const { envelope } = params;
|
|
306
|
+
if (envelope.iv12.length !== 12 || envelope.ciphertext32.length !== 32 || envelope.authTag16.length !== 16) throw new require_constants.MpcProtocolError("DKG_SHARE_DECRYPT_FAILED", `Malformed encrypted share from dealer slot ${envelope.dealerSlot}`, envelope.dealerSlot);
|
|
307
|
+
const shared = require_secp256k1_scalar.computeX25519SharedSecret(params.recipientX25519Secret32, params.dealerX25519Pub32, "DKG_SHARE_DECRYPT_FAILED", envelope.dealerSlot);
|
|
308
|
+
const aeadKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, shared, require_secp256k1_scalar.concatBytes(params.dealerX25519Pub32, params.recipientX25519Pub32), require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_DKG_X25519_HKDF_V2, [
|
|
309
|
+
params.ctxDkg32,
|
|
310
|
+
require_secp256k1_scalar.u16be(envelope.dealerSlot),
|
|
311
|
+
require_secp256k1_scalar.u16be(envelope.recipientSlot)
|
|
312
|
+
]), 32);
|
|
313
|
+
require_secp256k1_scalar.zeroizeBytes(shared);
|
|
314
|
+
const aad = require_secp256k1_scalar.concatBytes(require_secp256k1_scalar.utf8Bytes(require_constants.DST_DKG_SHARE_AAD_V2), params.ctxDkg32, require_secp256k1_scalar.u16be(envelope.dealerSlot), require_secp256k1_scalar.u16be(envelope.recipientSlot));
|
|
315
|
+
try {
|
|
316
|
+
const decipher = (0, node_crypto.createDecipheriv)("aes-256-gcm", aeadKey32, envelope.iv12);
|
|
317
|
+
decipher.setAAD(aad);
|
|
318
|
+
decipher.setAuthTag(envelope.authTag16);
|
|
319
|
+
return require_secp256k1_scalar.concatBytes(decipher.update(envelope.ciphertext32), decipher.final());
|
|
320
|
+
} catch {
|
|
321
|
+
throw new require_constants.MpcProtocolError("DKG_SHARE_DECRYPT_FAILED", `AES-256-GCM authentication failed on share from dealer slot ${envelope.dealerSlot}`, envelope.dealerSlot);
|
|
322
|
+
} finally {
|
|
323
|
+
require_secp256k1_scalar.zeroizeBytes(aeadKey32);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
var DkgParticipantSession = class {
|
|
327
|
+
constructor(params) {
|
|
328
|
+
this.phase = "INIT";
|
|
329
|
+
this.ownReveal = null;
|
|
330
|
+
this.step1CommitsBySlot = /* @__PURE__ */ new Map();
|
|
331
|
+
this.verifiedRevealsBySlot = /* @__PURE__ */ new Map();
|
|
332
|
+
this.hDkg32 = null;
|
|
333
|
+
this.accumulatedOwnShareBytes32 = new Uint8Array(32);
|
|
334
|
+
const { slot, config, echoSigningSecretBytes32, echoLock, coldBackupPlugin, rng = require_secp256k1_scalar.defaultRandomBytes } = params;
|
|
335
|
+
const mustRequireColdPlugin = Boolean(params.requireColdBackupPlugin || config.requireColdBackupPlugin);
|
|
336
|
+
const { ctxDkg32, normalizedEscapeColdWallet, sortedRoster } = validateAndComputeDkgContext(config);
|
|
337
|
+
if (slot < 1 || slot > config.nParties) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `Invalid participant slot ${slot}`);
|
|
338
|
+
if (mustRequireColdPlugin && !coldBackupPlugin) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "ColdBackupPlugin is required");
|
|
339
|
+
const echoSk = require_secp256k1_scalar.bytes32ToScalarNonZero(echoSigningSecretBytes32);
|
|
340
|
+
const expectedEchoPk = sortedRoster[slot - 1].echoVerifyPublicKeyComp33;
|
|
341
|
+
if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(echoSk)), expectedEchoPk)) throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", `echoSigningSecretBytes32 does not match roster public key for slot ${slot}`);
|
|
342
|
+
this.slot = slot;
|
|
343
|
+
this.config = config;
|
|
344
|
+
this.ctxDkg32 = ctxDkg32;
|
|
345
|
+
this.normalizedEscapeColdWallet = normalizedEscapeColdWallet;
|
|
346
|
+
this.sortedRoster = sortedRoster;
|
|
347
|
+
this.echoSigningKeyBytes32 = new Uint8Array(echoSigningSecretBytes32);
|
|
348
|
+
this.echoLock = echoLock;
|
|
349
|
+
this.coldBackupPlugin = coldBackupPlugin;
|
|
350
|
+
this.requireColdBackupPlugin = mustRequireColdPlugin;
|
|
351
|
+
this.rng = rng;
|
|
352
|
+
const a0 = require_secp256k1_scalar.sampleScalarNonZero(rng);
|
|
353
|
+
this.onlinePolyBytes32 = [require_secp256k1_scalar.scalarToBytes32(a0)];
|
|
354
|
+
for (let l = 1; l < config.t; l++) this.onlinePolyBytes32.push(require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.sampleScalarNonZero(rng)));
|
|
355
|
+
this.coldPolyBytes32 = [require_secp256k1_scalar.scalarToBytes32(a0)];
|
|
356
|
+
for (let l = 1; l < config.tCold; l++) this.coldPolyBytes32.push(require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.sampleScalarNonZero(rng)));
|
|
357
|
+
this.x25519Secret32 = rng(32);
|
|
358
|
+
this.x25519Pub32 = _noble_curves_ed25519_js.x25519.getPublicKey(this.x25519Secret32);
|
|
359
|
+
}
|
|
360
|
+
abort() {
|
|
361
|
+
this.phase = "ABORTED";
|
|
362
|
+
this.wipeDealerSecrets();
|
|
363
|
+
require_secp256k1_scalar.zeroizeBytes(this.accumulatedOwnShareBytes32, this.echoSigningKeyBytes32);
|
|
364
|
+
}
|
|
365
|
+
wipeDealerSecrets() {
|
|
366
|
+
for (const buf of this.onlinePolyBytes32) require_secp256k1_scalar.zeroizeBytes(buf);
|
|
367
|
+
for (const buf of this.coldPolyBytes32) require_secp256k1_scalar.zeroizeBytes(buf);
|
|
368
|
+
require_secp256k1_scalar.zeroizeBytes(this.x25519Secret32);
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Step 1: Computes Feldman commitments `{A_{i,l}}`, `{C_{i,l}}`, Schnorr PoK `\pi^{pok}_i`,
|
|
372
|
+
* optional `VES_i`, and broadcasts `Com_i` + `epk^{x25519}_i` authenticated under the node's
|
|
373
|
+
* roster identity key (`ARC-MPC-DKG-STEP1-AUTH-V1`).
|
|
374
|
+
*/
|
|
375
|
+
step1CreateCommitment() {
|
|
376
|
+
if (this.phase !== "INIT") {
|
|
377
|
+
this.abort();
|
|
378
|
+
throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "DKG Step 1 called out of order");
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
381
|
+
const onlineCoeffs = this.onlinePolyBytes32.map((b) => require_secp256k1_scalar.bytes32ToScalarNonZero(b));
|
|
382
|
+
const coldCoeffs = this.coldPolyBytes32.map((b) => require_secp256k1_scalar.bytes32ToScalarNonZero(b));
|
|
383
|
+
const onlinePoints = onlineCoeffs.map((c) => require_secp256k1_scalar.mulBaseG(c));
|
|
384
|
+
const coldPoints = coldCoeffs.map((c) => require_secp256k1_scalar.mulBaseG(c));
|
|
385
|
+
const onlineCommitmentsComp33 = onlinePoints.map((p) => require_secp256k1_scalar.encodePointCompressed(p));
|
|
386
|
+
const coldCommitmentsComp33 = coldPoints.map((p) => require_secp256k1_scalar.encodePointCompressed(p));
|
|
387
|
+
const basePokContext = [
|
|
388
|
+
this.ctxDkg32,
|
|
389
|
+
require_secp256k1_scalar.u16be(this.slot),
|
|
390
|
+
this.x25519Pub32,
|
|
391
|
+
...onlineCommitmentsComp33,
|
|
392
|
+
...coldCommitmentsComp33
|
|
393
|
+
];
|
|
394
|
+
const onlineCoeffPoks = onlineCoeffs.map((coeff, l) => require_secp256k1_scalar.createSchnorrPokInBase({
|
|
395
|
+
dst: require_constants.DST_DKG_POK_V2,
|
|
396
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
397
|
+
statementPoint: onlinePoints[l],
|
|
398
|
+
secretScalar: coeff,
|
|
399
|
+
contextParts: [
|
|
400
|
+
...basePokContext,
|
|
401
|
+
require_secp256k1_scalar.u8(0),
|
|
402
|
+
require_secp256k1_scalar.u16be(l)
|
|
403
|
+
],
|
|
404
|
+
rng: this.rng
|
|
405
|
+
}));
|
|
406
|
+
const coldExtraCoeffPoks = coldCoeffs.slice(1).map((coeff, idx) => require_secp256k1_scalar.createSchnorrPokInBase({
|
|
407
|
+
dst: require_constants.DST_DKG_POK_V2,
|
|
408
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
409
|
+
statementPoint: coldPoints[idx + 1],
|
|
410
|
+
secretScalar: coeff,
|
|
411
|
+
contextParts: [
|
|
412
|
+
...basePokContext,
|
|
413
|
+
require_secp256k1_scalar.u8(1),
|
|
414
|
+
require_secp256k1_scalar.u16be(idx + 1)
|
|
415
|
+
],
|
|
416
|
+
rng: this.rng
|
|
417
|
+
}));
|
|
418
|
+
let coldVesPayload = new Uint8Array(0);
|
|
419
|
+
if (this.coldBackupPlugin) {
|
|
420
|
+
const coldEvaluationsByGuardian = this.config.guardianPublicKeysComp33.map((gpk, idx) => ({
|
|
421
|
+
guardianIndex: idx + 1,
|
|
422
|
+
evaluationScalar: require_secp256k1_scalar.evaluatePolynomialModN(coldCoeffs, BigInt(idx + 1)),
|
|
423
|
+
guardianPublicKeyComp33: gpk
|
|
424
|
+
}));
|
|
425
|
+
coldVesPayload = this.coldBackupPlugin.createDealerContribution({
|
|
426
|
+
ctxDkg32: this.ctxDkg32,
|
|
427
|
+
dealerSlot: this.slot,
|
|
428
|
+
coldCommitmentsComp33,
|
|
429
|
+
guardianPublicKeysComp33: this.config.guardianPublicKeysComp33,
|
|
430
|
+
coldEvaluationsByGuardian
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
const comSalt32 = this.rng(32);
|
|
434
|
+
const reveal = {
|
|
435
|
+
dealerSlot: this.slot,
|
|
436
|
+
comSalt32,
|
|
437
|
+
ephemeralX25519Pub32: new Uint8Array(this.x25519Pub32),
|
|
438
|
+
onlineCommitmentsComp33,
|
|
439
|
+
coldCommitmentsComp33,
|
|
440
|
+
onlineCoeffPoks,
|
|
441
|
+
coldExtraCoeffPoks,
|
|
442
|
+
coldVesPayload
|
|
443
|
+
};
|
|
444
|
+
const commitment32 = computeDkgCommitmentHash(this.ctxDkg32, this.slot, comSalt32, encodeDkgRevealBody(reveal));
|
|
445
|
+
const identitySk = require_secp256k1_scalar.bytes32ToScalarNonZero(this.echoSigningKeyBytes32);
|
|
446
|
+
const step1AuthPok = require_secp256k1_scalar.createSchnorrPokInBase({
|
|
447
|
+
dst: require_constants.DST_DKG_STEP1_AUTH_V1,
|
|
448
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
449
|
+
statementPoint: require_secp256k1_scalar.decodePointCompressed(this.sortedRoster[this.slot - 1].echoVerifyPublicKeyComp33, false),
|
|
450
|
+
secretScalar: identitySk,
|
|
451
|
+
contextParts: [
|
|
452
|
+
this.ctxDkg32,
|
|
453
|
+
require_secp256k1_scalar.u32be(this.slot),
|
|
454
|
+
commitment32,
|
|
455
|
+
this.x25519Pub32
|
|
456
|
+
],
|
|
457
|
+
rng: this.rng
|
|
458
|
+
});
|
|
459
|
+
this.ownReveal = reveal;
|
|
460
|
+
this.phase = "STEP1_COMMITTED";
|
|
461
|
+
return {
|
|
462
|
+
dealerSlot: this.slot,
|
|
463
|
+
commitment32,
|
|
464
|
+
ephemeralX25519Pub32: new Uint8Array(this.x25519Pub32),
|
|
465
|
+
step1AuthPok
|
|
466
|
+
};
|
|
467
|
+
} catch (err) {
|
|
468
|
+
this.abort();
|
|
469
|
+
throw err;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Step 2: Verifies every peer's Step-1 roster authentication signature over
|
|
474
|
+
* `(ctxDkg32, u32be(j), commitment32, ephemeralX25519Pub32)` BEFORE encrypting any Shamir share,
|
|
475
|
+
* then reveals `Reveal_i` and seals `f_i(j) mod n` via `X25519 + HKDF-SHA256 + AES-256-GCM`.
|
|
476
|
+
*/
|
|
477
|
+
step2CreateRevealAndShares(allCommitments) {
|
|
478
|
+
if (this.phase !== "STEP1_COMMITTED") {
|
|
479
|
+
this.abort();
|
|
480
|
+
throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "DKG Step 2 called out of order");
|
|
481
|
+
}
|
|
482
|
+
try {
|
|
483
|
+
if (allCommitments.length !== this.config.nParties) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", `Expected ${this.config.nParties} Step-1 commitments, got ${allCommitments.length}`);
|
|
484
|
+
const map = /* @__PURE__ */ new Map();
|
|
485
|
+
for (const msg of allCommitments) {
|
|
486
|
+
if (!msg || msg.dealerSlot < 1 || msg.dealerSlot > this.config.nParties || !(msg.commitment32 instanceof Uint8Array) || msg.commitment32.length !== 32 || !(msg.ephemeralX25519Pub32 instanceof Uint8Array) || msg.ephemeralX25519Pub32.length !== 32 || !msg.step1AuthPok || map.has(msg.dealerSlot)) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", `Invalid Step-1 commitment from slot ${msg?.dealerSlot}`, msg?.dealerSlot);
|
|
487
|
+
require_secp256k1_scalar.assertValidX25519PublicKey(msg.ephemeralX25519Pub32, "DKG_COMMITMENT_MISMATCH", msg.dealerSlot);
|
|
488
|
+
if (!require_secp256k1_scalar.verifySchnorrPokInBase({
|
|
489
|
+
dst: require_constants.DST_DKG_STEP1_AUTH_V1,
|
|
490
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
491
|
+
statementPoint: require_secp256k1_scalar.decodePointCompressed(this.sortedRoster[msg.dealerSlot - 1].echoVerifyPublicKeyComp33, false),
|
|
492
|
+
proof: msg.step1AuthPok,
|
|
493
|
+
contextParts: [
|
|
494
|
+
this.ctxDkg32,
|
|
495
|
+
require_secp256k1_scalar.u32be(msg.dealerSlot),
|
|
496
|
+
msg.commitment32,
|
|
497
|
+
msg.ephemeralX25519Pub32
|
|
498
|
+
]
|
|
499
|
+
})) throw new require_constants.MpcProtocolError("DKG_POK_INVALID", `Invalid Step-1 ephemeral X25519 authentication proof from slot ${msg.dealerSlot}`, msg.dealerSlot);
|
|
500
|
+
map.set(msg.dealerSlot, msg);
|
|
501
|
+
}
|
|
502
|
+
this.step1CommitsBySlot = map;
|
|
503
|
+
const onlineCoeffs = this.onlinePolyBytes32.map((b) => require_secp256k1_scalar.bytes32ToScalarNonZero(b));
|
|
504
|
+
const encryptedShares = [];
|
|
505
|
+
for (let j = 1; j <= this.config.nParties; j++) {
|
|
506
|
+
const shareBytes32 = require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.evaluatePolynomialModN(onlineCoeffs, BigInt(j)));
|
|
507
|
+
try {
|
|
508
|
+
const recipientPub32 = map.get(j).ephemeralX25519Pub32;
|
|
509
|
+
encryptedShares.push(sealDkgShareX25519Gcm({
|
|
510
|
+
ctxDkg32: this.ctxDkg32,
|
|
511
|
+
dealerSlot: this.slot,
|
|
512
|
+
recipientSlot: j,
|
|
513
|
+
dealerX25519Secret32: this.x25519Secret32,
|
|
514
|
+
dealerX25519Pub32: this.x25519Pub32,
|
|
515
|
+
recipientX25519Pub32: recipientPub32,
|
|
516
|
+
shareBytes32,
|
|
517
|
+
rng: this.rng
|
|
518
|
+
}));
|
|
519
|
+
} finally {
|
|
520
|
+
require_secp256k1_scalar.zeroizeBytes(shareBytes32);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
for (const buf of this.onlinePolyBytes32) require_secp256k1_scalar.zeroizeBytes(buf);
|
|
524
|
+
for (const buf of this.coldPolyBytes32) require_secp256k1_scalar.zeroizeBytes(buf);
|
|
525
|
+
this.phase = "STEP2_REVEALED";
|
|
526
|
+
return {
|
|
527
|
+
reveal: this.ownReveal,
|
|
528
|
+
encryptedShares
|
|
529
|
+
};
|
|
530
|
+
} catch (err) {
|
|
531
|
+
this.abort();
|
|
532
|
+
throw err;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Step 3a: Verifies all `Com_m`, `\pi^{pok}_m`, `A_{m,0} == C_{m,0} != O`, non-zero degree
|
|
537
|
+
* commitments, `VES_m`, and Feldman share equations; appends `ceremonyId -> H_dkg` to the
|
|
538
|
+
* append-only `DkgEchoLock` **before** signing `\sigma^{echo}_j`!
|
|
539
|
+
*/
|
|
540
|
+
step3VerifyAndCreateLockedEcho(params) {
|
|
541
|
+
if (this.phase !== "STEP2_REVEALED") {
|
|
542
|
+
this.abort();
|
|
543
|
+
throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "DKG Step 3a called out of order");
|
|
544
|
+
}
|
|
545
|
+
try {
|
|
546
|
+
const { allReveals, encryptedSharesForMe } = params;
|
|
547
|
+
if (allReveals.length !== this.config.nParties || encryptedSharesForMe.length !== this.config.nParties) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", "Missing Step-2 reveals or shares");
|
|
548
|
+
const revealsBySlot = /* @__PURE__ */ new Map();
|
|
549
|
+
for (const rev of allReveals) {
|
|
550
|
+
if (rev.dealerSlot < 1 || rev.dealerSlot > this.config.nParties || revealsBySlot.has(rev.dealerSlot)) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", `Invalid dealerSlot ${rev.dealerSlot}`, rev.dealerSlot);
|
|
551
|
+
revealsBySlot.set(rev.dealerSlot, rev);
|
|
552
|
+
}
|
|
553
|
+
const sharesByDealer = /* @__PURE__ */ new Map();
|
|
554
|
+
for (const env of encryptedSharesForMe) {
|
|
555
|
+
if (env.recipientSlot !== this.slot || env.dealerSlot < 1 || env.dealerSlot > this.config.nParties || sharesByDealer.has(env.dealerSlot)) throw new require_constants.MpcProtocolError("DKG_SHARE_DECRYPT_FAILED", `Invalid encrypted share envelope from slot ${env.dealerSlot}`, env.dealerSlot);
|
|
556
|
+
sharesByDealer.set(env.dealerSlot, env);
|
|
557
|
+
}
|
|
558
|
+
let ownShareAcc = 0n;
|
|
559
|
+
const transcriptParts = [this.ctxDkg32];
|
|
560
|
+
for (let m = 1; m <= this.config.nParties; m++) {
|
|
561
|
+
const comMsg = this.step1CommitsBySlot.get(m);
|
|
562
|
+
const rev = revealsBySlot.get(m);
|
|
563
|
+
if (rev.comSalt32.length !== 32 || !require_secp256k1_scalar.constantTimeEqual(rev.ephemeralX25519Pub32, comMsg.ephemeralX25519Pub32) || rev.onlineCommitmentsComp33.length !== this.config.t || rev.coldCommitmentsComp33.length !== this.config.tCold || rev.onlineCoeffPoks.length !== this.config.t || rev.coldExtraCoeffPoks.length !== this.config.tCold - 1) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", `Malformed reveal structure from dealer slot ${m}`, m);
|
|
564
|
+
const revealBody = encodeDkgRevealBody(rev);
|
|
565
|
+
if (!require_secp256k1_scalar.constantTimeEqual(computeDkgCommitmentHash(this.ctxDkg32, m, rev.comSalt32, revealBody), comMsg.commitment32)) throw new require_constants.MpcProtocolError("DKG_COMMITMENT_MISMATCH", `Commitment hash mismatch from dealer slot ${m}`, m);
|
|
566
|
+
let onlinePoints;
|
|
567
|
+
let coldPoints;
|
|
568
|
+
try {
|
|
569
|
+
onlinePoints = rev.onlineCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
|
|
570
|
+
coldPoints = rev.coldCommitmentsComp33.map((b) => require_secp256k1_scalar.decodePointCompressed(b, false));
|
|
571
|
+
} catch {
|
|
572
|
+
throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `Invalid or zero Feldman commitment point from dealer slot ${m}`, m);
|
|
573
|
+
}
|
|
574
|
+
if (!require_secp256k1_scalar.constantTimeEqual(rev.onlineCommitmentsComp33[0], rev.coldCommitmentsComp33[0])) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `C_{${m},0} != A_{${m},0} from dealer slot ${m}`, m);
|
|
575
|
+
const basePokContext = [
|
|
576
|
+
this.ctxDkg32,
|
|
577
|
+
require_secp256k1_scalar.u16be(m),
|
|
578
|
+
rev.ephemeralX25519Pub32,
|
|
579
|
+
...rev.onlineCommitmentsComp33,
|
|
580
|
+
...rev.coldCommitmentsComp33
|
|
581
|
+
];
|
|
582
|
+
for (let l = 0; l < this.config.t; l++) if (!require_secp256k1_scalar.verifySchnorrPokInBase({
|
|
583
|
+
dst: require_constants.DST_DKG_POK_V2,
|
|
584
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
585
|
+
statementPoint: onlinePoints[l],
|
|
586
|
+
proof: rev.onlineCoeffPoks[l],
|
|
587
|
+
contextParts: [
|
|
588
|
+
...basePokContext,
|
|
589
|
+
require_secp256k1_scalar.u8(0),
|
|
590
|
+
require_secp256k1_scalar.u16be(l)
|
|
591
|
+
]
|
|
592
|
+
})) throw new require_constants.MpcProtocolError("DKG_POK_INVALID", `Invalid Schnorr PoK on A_{${m},${l}} from dealer slot ${m}`, m);
|
|
593
|
+
for (let idx = 0; idx < this.config.tCold - 1; idx++) if (!require_secp256k1_scalar.verifySchnorrPokInBase({
|
|
594
|
+
dst: require_constants.DST_DKG_POK_V2,
|
|
595
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
596
|
+
statementPoint: coldPoints[idx + 1],
|
|
597
|
+
proof: rev.coldExtraCoeffPoks[idx],
|
|
598
|
+
contextParts: [
|
|
599
|
+
...basePokContext,
|
|
600
|
+
require_secp256k1_scalar.u8(1),
|
|
601
|
+
require_secp256k1_scalar.u16be(idx + 1)
|
|
602
|
+
]
|
|
603
|
+
})) throw new require_constants.MpcProtocolError("DKG_POK_INVALID", `Invalid Schnorr PoK on C_{${m},${idx + 1}} from dealer slot ${m}`, m);
|
|
604
|
+
if (this.coldBackupPlugin) {
|
|
605
|
+
let okVes = false;
|
|
606
|
+
try {
|
|
607
|
+
okVes = this.coldBackupPlugin.verifyDealerContribution({
|
|
608
|
+
ctxDkg32: this.ctxDkg32,
|
|
609
|
+
dealerSlot: m,
|
|
610
|
+
coldCommitmentsComp33: rev.coldCommitmentsComp33,
|
|
611
|
+
guardianPublicKeysComp33: this.config.guardianPublicKeysComp33,
|
|
612
|
+
payload: rev.coldVesPayload
|
|
613
|
+
});
|
|
614
|
+
} catch (err) {
|
|
615
|
+
throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Cold VES verification threw for dealer slot ${m}: ${err.message}`, m);
|
|
616
|
+
}
|
|
617
|
+
if (!okVes) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Invalid cold VES payload from dealer slot ${m}`, m);
|
|
618
|
+
}
|
|
619
|
+
const env = sharesByDealer.get(m);
|
|
620
|
+
const decryptedBytes32 = openDkgShareX25519Gcm({
|
|
621
|
+
ctxDkg32: this.ctxDkg32,
|
|
622
|
+
recipientX25519Secret32: this.x25519Secret32,
|
|
623
|
+
dealerX25519Pub32: rev.ephemeralX25519Pub32,
|
|
624
|
+
recipientX25519Pub32: this.x25519Pub32,
|
|
625
|
+
envelope: env
|
|
626
|
+
});
|
|
627
|
+
try {
|
|
628
|
+
let shareScalar;
|
|
629
|
+
try {
|
|
630
|
+
shareScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(decryptedBytes32);
|
|
631
|
+
} catch {
|
|
632
|
+
throw new require_constants.MpcProtocolError("DKG_FELDMAN_VERIFY_FAILED", `Zero or out-of-range share from dealer slot ${m}`, m);
|
|
633
|
+
}
|
|
634
|
+
const lhs = require_secp256k1_scalar.mulBaseG(shareScalar);
|
|
635
|
+
const rhs = require_secp256k1_scalar.evaluateFeldmanCommitments(onlinePoints, this.slot);
|
|
636
|
+
if (!lhs.equals(rhs)) throw new require_constants.MpcProtocolError("DKG_FELDMAN_VERIFY_FAILED", `Feldman verification failed on share from dealer slot ${m}`, m);
|
|
637
|
+
ownShareAcc = require_secp256k1_scalar.addModN(ownShareAcc, shareScalar);
|
|
638
|
+
} finally {
|
|
639
|
+
require_secp256k1_scalar.zeroizeBytes(decryptedBytes32);
|
|
640
|
+
}
|
|
641
|
+
transcriptParts.push(comMsg.commitment32, rev.comSalt32, revealBody);
|
|
642
|
+
}
|
|
643
|
+
require_secp256k1_scalar.zeroizeBytes(this.x25519Secret32);
|
|
644
|
+
if (ownShareAcc === 0n) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", "Aggregated own Shamir share == 0");
|
|
645
|
+
this.accumulatedOwnShareBytes32.set(require_secp256k1_scalar.scalarToBytes32(ownShareAcc));
|
|
646
|
+
const hDkg32 = require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_DKG_TRANSCRIPT_V2, ...transcriptParts);
|
|
647
|
+
const epochScopeKey = `${this.config.clusterId}|${this.config.rootId}|${this.config.keyEpoch.toString()}`;
|
|
648
|
+
this.echoLock.recordAndVerify(this.config.ceremonyId, hDkg32, epochScopeKey);
|
|
649
|
+
const echoSk = require_secp256k1_scalar.bytes32ToScalarNonZero(this.echoSigningKeyBytes32);
|
|
650
|
+
const echoSignaturePok = require_secp256k1_scalar.createSchnorrPokInBase({
|
|
651
|
+
dst: require_constants.DST_DKG_ECHO_V2,
|
|
652
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
653
|
+
statementPoint: require_secp256k1_scalar.decodePointCompressed(this.sortedRoster[this.slot - 1].echoVerifyPublicKeyComp33, false),
|
|
654
|
+
secretScalar: echoSk,
|
|
655
|
+
contextParts: [
|
|
656
|
+
this.ctxDkg32,
|
|
657
|
+
require_secp256k1_scalar.u16be(this.slot),
|
|
658
|
+
hDkg32
|
|
659
|
+
],
|
|
660
|
+
rng: this.rng
|
|
661
|
+
});
|
|
662
|
+
require_secp256k1_scalar.zeroizeBytes(this.echoSigningKeyBytes32);
|
|
663
|
+
this.verifiedRevealsBySlot = revealsBySlot;
|
|
664
|
+
this.hDkg32 = hDkg32;
|
|
665
|
+
this.phase = "STEP3_ECHOED";
|
|
666
|
+
return {
|
|
667
|
+
slot: this.slot,
|
|
668
|
+
hDkg32: new Uint8Array(hDkg32),
|
|
669
|
+
echoSignaturePok
|
|
670
|
+
};
|
|
671
|
+
} catch (err) {
|
|
672
|
+
this.abort();
|
|
673
|
+
throw err;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Step 3b: Requires unanimous authenticated echoes over `H_dkg`, checks non-zero degree and
|
|
678
|
+
* non-identity invariants (`P_root != O`, `F_{t-1} != O`, `C^{cold}_{t_c-1} != O`, `X_m != O`,
|
|
679
|
+
* `Y_k != O`), validates aggregated `recoveryPackageBytes` (`<= MAX_RECOVERY_PACKAGE_BYTES`,
|
|
680
|
+
* `sha256` match, `verifyRecoveryPackage === true`) BEFORE releasing `shareCopy`, and outputs
|
|
681
|
+
* the node's key record in `INITIALIZING` state ready for Step-4 subset self-tests.
|
|
682
|
+
*/
|
|
683
|
+
step3FinalizeFromEchoes(allEchoes) {
|
|
684
|
+
if (this.phase !== "STEP3_ECHOED") {
|
|
685
|
+
this.abort();
|
|
686
|
+
throw new require_constants.MpcProtocolError("DKG_INVALID_CONFIG", "DKG Step 3b called out of order");
|
|
687
|
+
}
|
|
688
|
+
try {
|
|
689
|
+
if (allEchoes.length !== this.config.nParties) throw new require_constants.MpcProtocolError("DKG_ECHO_INVALID", "Missing unanimous DKG echoes");
|
|
690
|
+
const echoBySlot = /* @__PURE__ */ new Map();
|
|
691
|
+
for (const echo of allEchoes) {
|
|
692
|
+
if (echo.slot < 1 || echo.slot > this.config.nParties || echoBySlot.has(echo.slot)) throw new require_constants.MpcProtocolError("DKG_ECHO_INVALID", `Invalid echo slot ${echo.slot}`, echo.slot);
|
|
693
|
+
echoBySlot.set(echo.slot, echo);
|
|
694
|
+
}
|
|
695
|
+
for (let m = 1; m <= this.config.nParties; m++) {
|
|
696
|
+
const echo = echoBySlot.get(m);
|
|
697
|
+
if (!require_secp256k1_scalar.constantTimeEqual(echo.hDkg32, this.hDkg32)) throw new require_constants.MpcProtocolError("DKG_ECHO_INVALID", `Transcript hash mismatch in echo from slot ${m}`, m);
|
|
698
|
+
const rosterEntry = this.sortedRoster[m - 1];
|
|
699
|
+
if (!require_secp256k1_scalar.verifySchnorrPokInBase({
|
|
700
|
+
dst: require_constants.DST_DKG_ECHO_V2,
|
|
701
|
+
basePoint: require_secp256k1_scalar.SECP256K1_G,
|
|
702
|
+
statementPoint: require_secp256k1_scalar.decodePointCompressed(rosterEntry.echoVerifyPublicKeyComp33, false),
|
|
703
|
+
proof: echo.echoSignaturePok,
|
|
704
|
+
contextParts: [
|
|
705
|
+
this.ctxDkg32,
|
|
706
|
+
require_secp256k1_scalar.u16be(m),
|
|
707
|
+
this.hDkg32
|
|
708
|
+
]
|
|
709
|
+
})) throw new require_constants.MpcProtocolError("DKG_ECHO_INVALID", `Invalid echo signature from slot ${m}`, m);
|
|
710
|
+
}
|
|
711
|
+
const aggOnlinePoints = new Array(this.config.t).fill(require_secp256k1_scalar.SECP256K1_ZERO);
|
|
712
|
+
const aggColdPoints = new Array(this.config.tCold).fill(require_secp256k1_scalar.SECP256K1_ZERO);
|
|
713
|
+
for (let m = 1; m <= this.config.nParties; m++) {
|
|
714
|
+
const rev = this.verifiedRevealsBySlot.get(m);
|
|
715
|
+
for (let l = 0; l < this.config.t; l++) aggOnlinePoints[l] = aggOnlinePoints[l].add(require_secp256k1_scalar.decodePointCompressed(rev.onlineCommitmentsComp33[l], false));
|
|
716
|
+
for (let l = 0; l < this.config.tCold; l++) aggColdPoints[l] = aggColdPoints[l].add(require_secp256k1_scalar.decodePointCompressed(rev.coldCommitmentsComp33[l], false));
|
|
717
|
+
}
|
|
718
|
+
const pRoot = aggOnlinePoints[0];
|
|
719
|
+
const fTop = aggOnlinePoints[this.config.t - 1];
|
|
720
|
+
const cCold0 = aggColdPoints[0];
|
|
721
|
+
const cColdTop = aggColdPoints[this.config.tCold - 1];
|
|
722
|
+
if (pRoot.is0() || fTop.is0() || cColdTop.is0() || !pRoot.equals(cCold0)) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", "Degenerate aggregate polynomial commitment (P_root == O or top coefficient == O)");
|
|
723
|
+
for (let l = 0; l < this.config.t; l++) if (aggOnlinePoints[l].is0()) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `F_${l} hit point at infinity`);
|
|
724
|
+
for (let l = 0; l < this.config.tCold; l++) if (aggColdPoints[l].is0()) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `C^{cold}_${l} hit point at infinity`);
|
|
725
|
+
const onlinePublicSharesComp33BySlot = /* @__PURE__ */ new Map();
|
|
726
|
+
for (let m = 1; m <= this.config.nParties; m++) {
|
|
727
|
+
const xM = require_secp256k1_scalar.evaluateFeldmanCommitments(aggOnlinePoints, m);
|
|
728
|
+
if (xM.is0()) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `Online public share X_${m} == O`);
|
|
729
|
+
onlinePublicSharesComp33BySlot.set(m, require_secp256k1_scalar.encodePointCompressed(xM));
|
|
730
|
+
}
|
|
731
|
+
const guardianColdPublicSharesComp33 = [];
|
|
732
|
+
for (let k = 1; k <= this.config.nCold; k++) {
|
|
733
|
+
const yK = require_secp256k1_scalar.evaluateFeldmanCommitments(aggColdPoints, k);
|
|
734
|
+
if (yK.is0()) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", `Guardian cold public share Y_${k} == O`);
|
|
735
|
+
guardianColdPublicSharesComp33.push(require_secp256k1_scalar.encodePointCompressed(yK));
|
|
736
|
+
}
|
|
737
|
+
const ownXScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(this.accumulatedOwnShareBytes32);
|
|
738
|
+
const ownXPoint = require_secp256k1_scalar.decodePointCompressed(onlinePublicSharesComp33BySlot.get(this.slot), false);
|
|
739
|
+
if (!require_secp256k1_scalar.mulBaseG(ownXScalar).equals(ownXPoint)) throw new require_constants.MpcProtocolError("DKG_DEGENERATE_KEY", "Own share x_i * G != X_i");
|
|
740
|
+
const rootPublicKeyComp33 = require_secp256k1_scalar.encodePointCompressed(pRoot);
|
|
741
|
+
const onlineFeldmanCommitmentsComp33 = aggOnlinePoints.map((pt) => require_secp256k1_scalar.encodePointCompressed(pt));
|
|
742
|
+
const coldFeldmanCommitmentsComp33 = aggColdPoints.map((pt) => require_secp256k1_scalar.encodePointCompressed(pt));
|
|
743
|
+
if (this.requireColdBackupPlugin && !this.coldBackupPlugin) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "ColdBackupPlugin is required in Step 3b");
|
|
744
|
+
let recoveryPackageBytes;
|
|
745
|
+
let recoveryPackageHash32;
|
|
746
|
+
if (this.coldBackupPlugin) {
|
|
747
|
+
const dealerPayloads = Array.from({ length: this.config.nParties }, (_, idx) => ({
|
|
748
|
+
dealerSlot: idx + 1,
|
|
749
|
+
payload: this.verifiedRevealsBySlot.get(idx + 1).coldVesPayload
|
|
750
|
+
}));
|
|
751
|
+
let aggPkg;
|
|
752
|
+
try {
|
|
753
|
+
aggPkg = this.coldBackupPlugin.aggregateRecoveryPackage({
|
|
754
|
+
ctxDkg32: this.ctxDkg32,
|
|
755
|
+
hDkg32: this.hDkg32,
|
|
756
|
+
rootPublicKeyComp33,
|
|
757
|
+
aggColdCommitmentsComp33: coldFeldmanCommitmentsComp33,
|
|
758
|
+
guardianColdPublicSharesComp33,
|
|
759
|
+
guardianPublicKeysComp33: this.config.guardianPublicKeysComp33,
|
|
760
|
+
dealerPayloads
|
|
761
|
+
});
|
|
762
|
+
} catch (err) {
|
|
763
|
+
throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Cold recovery package aggregation threw: ${err.message}`);
|
|
764
|
+
}
|
|
765
|
+
if (!aggPkg || !(aggPkg.recoveryPackageBytes instanceof Uint8Array) || aggPkg.recoveryPackageBytes.length < 1 || aggPkg.recoveryPackageBytes.length > require_constants.MAX_RECOVERY_PACKAGE_BYTES) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Invalid recoveryPackageBytes size (must satisfy 1 <= len <= ${require_constants.MAX_RECOVERY_PACKAGE_BYTES})`);
|
|
766
|
+
const computedPkgSha256 = (0, _noble_hashes_sha2_js.sha256)(aggPkg.recoveryPackageBytes);
|
|
767
|
+
if (!(aggPkg.recoveryPackageHash32 instanceof Uint8Array) || aggPkg.recoveryPackageHash32.length !== 32 || !require_secp256k1_scalar.constantTimeEqual(aggPkg.recoveryPackageHash32, computedPkgSha256)) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "recoveryPackageHash32 does not equal sha256(recoveryPackageBytes)");
|
|
768
|
+
let okPkg = false;
|
|
769
|
+
try {
|
|
770
|
+
okPkg = this.coldBackupPlugin.verifyRecoveryPackage(aggPkg.recoveryPackageBytes, {
|
|
771
|
+
ctxDkg32: this.ctxDkg32,
|
|
772
|
+
rootPublicKeyComp33,
|
|
773
|
+
aggColdCommitmentsComp33: coldFeldmanCommitmentsComp33,
|
|
774
|
+
guardianPublicKeysComp33: this.config.guardianPublicKeysComp33
|
|
775
|
+
});
|
|
776
|
+
} catch (err) {
|
|
777
|
+
throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Step-3b verifyRecoveryPackage threw: ${err.message}`);
|
|
778
|
+
}
|
|
779
|
+
if (!okPkg) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "Step-3b verifyRecoveryPackage(pkg) returned false");
|
|
780
|
+
recoveryPackageBytes = new Uint8Array(aggPkg.recoveryPackageBytes);
|
|
781
|
+
recoveryPackageHash32 = new Uint8Array(aggPkg.recoveryPackageHash32);
|
|
782
|
+
}
|
|
783
|
+
const shareCopy = new Uint8Array(this.accumulatedOwnShareBytes32);
|
|
784
|
+
require_secp256k1_scalar.zeroizeBytes(this.accumulatedOwnShareBytes32);
|
|
785
|
+
this.phase = "FINALIZED";
|
|
786
|
+
return {
|
|
787
|
+
slot: this.slot,
|
|
788
|
+
rootId: this.config.rootId,
|
|
789
|
+
keyEpoch: this.config.keyEpoch,
|
|
790
|
+
t: this.config.t,
|
|
791
|
+
nParties: this.config.nParties,
|
|
792
|
+
tCold: this.config.tCold,
|
|
793
|
+
nCold: this.config.nCold,
|
|
794
|
+
lifecycleState: "INITIALIZING",
|
|
795
|
+
ctxDkg32: new Uint8Array(this.ctxDkg32),
|
|
796
|
+
hDkg32: new Uint8Array(this.hDkg32),
|
|
797
|
+
escapeColdWallet: this.normalizedEscapeColdWallet,
|
|
798
|
+
ocapAnchor: this.config.ocapAnchor,
|
|
799
|
+
rootPublicKeyComp33,
|
|
800
|
+
rootEthAddress: require_tweak.pointToEthAddress(pRoot).checksumAddress,
|
|
801
|
+
onlineFeldmanCommitmentsComp33,
|
|
802
|
+
coldFeldmanCommitmentsComp33,
|
|
803
|
+
onlinePublicSharesComp33BySlot,
|
|
804
|
+
guardianColdPublicSharesComp33,
|
|
805
|
+
recoveryPackageBytes,
|
|
806
|
+
recoveryPackageHash32,
|
|
807
|
+
secretShareBytes32: shareCopy
|
|
808
|
+
};
|
|
809
|
+
} catch (err) {
|
|
810
|
+
this.abort();
|
|
811
|
+
throw err;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
/**
|
|
816
|
+
* Strictly single-node Step-4 promotion (`design.md` §4.3):
|
|
817
|
+
* - Takes ONLY this node's own `INITIALIZING` record (`ownRecord`) — ZERO peer secret shares ever
|
|
818
|
+
* enter this function!
|
|
819
|
+
* - Validates `ownRecord` invariants (`ctxDkg32`, `rootPublicKeyComp33`, `x_slot * G == X_slot`,
|
|
820
|
+
* and fail-closed `ColdBackupPlugin` / `sha256(recoveryPackageBytes)` verification).
|
|
821
|
+
* - Verifies that `subsetSignatures` covers EVERY `C(nParties, t)` canonical subset `S` and
|
|
822
|
+
* cryptographically `ecrecover`s each signature against `ownRecord.rootPublicKeyComp33` over
|
|
823
|
+
* `computeDkgSubsetSelfTestDigest32(ownRecord.ctxDkg32, S)`.
|
|
824
|
+
* - Zeroizes `ownRecord.secretShareBytes32` before rethrowing on ANY failure!
|
|
825
|
+
*/
|
|
826
|
+
function promoteNodeRecordAfterSelfTests(params) {
|
|
827
|
+
const { ownRecord, config, subsetSignatures, coldBackupPlugin } = params;
|
|
828
|
+
try {
|
|
829
|
+
if (!ownRecord || ownRecord.lifecycleState !== "INITIALIZING") throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", "ownRecord must be in INITIALIZING lifecycleState");
|
|
830
|
+
const { ctxDkg32: expectedCtxDkg32, normalizedEscapeColdWallet } = validateAndComputeDkgContext(config);
|
|
831
|
+
if (!(ownRecord.ctxDkg32 instanceof Uint8Array) || ownRecord.ctxDkg32.length !== 32 || !require_secp256k1_scalar.constantTimeEqual(ownRecord.ctxDkg32, expectedCtxDkg32) || !(ownRecord.hDkg32 instanceof Uint8Array) || ownRecord.hDkg32.length !== 32 || ownRecord.rootId !== config.rootId || ownRecord.keyEpoch !== config.keyEpoch || ownRecord.t !== config.t || ownRecord.nParties !== config.nParties || ownRecord.tCold !== config.tCold || ownRecord.nCold !== config.nCold || ownRecord.escapeColdWallet !== normalizedEscapeColdWallet || ownRecord.slot < 1 || ownRecord.slot > config.nParties) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", "ownRecord metadata mismatch against DkgCeremonyConfig");
|
|
832
|
+
const pRoot = require_secp256k1_scalar.decodePointCompressed(ownRecord.rootPublicKeyComp33, false);
|
|
833
|
+
const expectedRootAddr = require_tweak.pointToEthAddress(pRoot).checksumAddress;
|
|
834
|
+
if (ownRecord.rootEthAddress !== expectedRootAddr) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", "ownRecord rootEthAddress mismatch against rootPublicKey");
|
|
835
|
+
const ownShareScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(ownRecord.secretShareBytes32);
|
|
836
|
+
const ownPubComp33 = ownRecord.onlinePublicSharesComp33BySlot.get(ownRecord.slot);
|
|
837
|
+
if (!ownPubComp33) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Missing public share X_${ownRecord.slot} in ownRecord`);
|
|
838
|
+
const ownPubPoint = require_secp256k1_scalar.decodePointCompressed(ownPubComp33, false);
|
|
839
|
+
if (!require_secp256k1_scalar.mulBaseG(ownShareScalar).equals(ownPubPoint)) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `ownRecord secretShare * G != X_${ownRecord.slot}`);
|
|
840
|
+
if (Boolean(params.requireColdBackupPlugin || config.requireColdBackupPlugin || coldBackupPlugin !== void 0 || ownRecord.recoveryPackageBytes !== void 0 || ownRecord.recoveryPackageHash32 !== void 0)) {
|
|
841
|
+
if (!coldBackupPlugin) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "ColdBackupPlugin is required when requireColdBackupPlugin is set or recoveryPackageBytes is present");
|
|
842
|
+
if (!(ownRecord.recoveryPackageBytes instanceof Uint8Array) || ownRecord.recoveryPackageBytes.length < 1 || ownRecord.recoveryPackageBytes.length > require_constants.MAX_RECOVERY_PACKAGE_BYTES) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Missing or out-of-bounds recoveryPackageBytes (1..${require_constants.MAX_RECOVERY_PACKAGE_BYTES})`);
|
|
843
|
+
const computedSha256 = (0, _noble_hashes_sha2_js.sha256)(ownRecord.recoveryPackageBytes);
|
|
844
|
+
if (!(ownRecord.recoveryPackageHash32 instanceof Uint8Array) || ownRecord.recoveryPackageHash32.length !== 32 || !require_secp256k1_scalar.constantTimeEqual(ownRecord.recoveryPackageHash32, computedSha256)) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "ownRecord.recoveryPackageHash32 mismatch against sha256(recoveryPackageBytes)");
|
|
845
|
+
let okPkg = false;
|
|
846
|
+
try {
|
|
847
|
+
okPkg = coldBackupPlugin.verifyRecoveryPackage(ownRecord.recoveryPackageBytes, {
|
|
848
|
+
ctxDkg32: ownRecord.ctxDkg32,
|
|
849
|
+
rootPublicKeyComp33: ownRecord.rootPublicKeyComp33,
|
|
850
|
+
aggColdCommitmentsComp33: ownRecord.coldFeldmanCommitmentsComp33,
|
|
851
|
+
guardianPublicKeysComp33: config.guardianPublicKeysComp33
|
|
852
|
+
});
|
|
853
|
+
} catch (err) {
|
|
854
|
+
throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", `Step-4 verifyRecoveryPackage threw: ${err.message}`);
|
|
855
|
+
}
|
|
856
|
+
if (!okPkg) throw new require_constants.MpcProtocolError("DKG_COLD_PLUGIN_FAILED", "Step-4 verifyRecoveryPackage(pkg) returned false");
|
|
857
|
+
}
|
|
858
|
+
const expectedSubsets = require_secp256k1_scalar.enumerateCombinations(config.nParties, config.t);
|
|
859
|
+
if (!Array.isArray(subsetSignatures) || subsetSignatures.length !== expectedSubsets.length) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Expected ${expectedSubsets.length} subset self-test signatures, got ${subsetSignatures?.length}`);
|
|
860
|
+
const expectedKeys = new Set(expectedSubsets.map((s) => s.join(",")));
|
|
861
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
862
|
+
for (const sigEntry of subsetSignatures) {
|
|
863
|
+
if (!sigEntry || sigEntry.yParity !== 0 && sigEntry.yParity !== 1) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", "Malformed subset self-test signature entry");
|
|
864
|
+
const sortedS = require_secp256k1_scalar.normalizeSortedSubset(sigEntry.subset, config.t, config.nParties);
|
|
865
|
+
const key = sortedS.join(",");
|
|
866
|
+
if (!expectedKeys.has(key) || seenKeys.has(key)) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Unexpected or duplicate self-test subset [${sortedS.join(",")}]`);
|
|
867
|
+
seenKeys.add(key);
|
|
868
|
+
let rScalar;
|
|
869
|
+
let sScalar;
|
|
870
|
+
try {
|
|
871
|
+
rScalar = require_secp256k1_scalar.bytesToBigIntBE(require_secp256k1_scalar.normalizeHexBytes(sigEntry.rHex, 32));
|
|
872
|
+
sScalar = require_secp256k1_scalar.bytesToBigIntBE(require_secp256k1_scalar.normalizeHexBytes(sigEntry.sHex, 32));
|
|
873
|
+
} catch {
|
|
874
|
+
throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Malformed (rHex, sHex) on self-test subset [${sortedS.join(",")}]`);
|
|
875
|
+
}
|
|
876
|
+
if (rScalar < 1n || rScalar >= require_constants.SECP256K1_N || sScalar < 1n || sScalar > require_constants.SECP256K1_HALF_N) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Out-of-range or high-S scalar on self-test subset [${sortedS.join(",")}]`);
|
|
877
|
+
const msgDigest32 = computeDkgSubsetSelfTestDigest32(ownRecord.ctxDkg32, sortedS);
|
|
878
|
+
let recovered;
|
|
879
|
+
try {
|
|
880
|
+
recovered = require_tweak.ecrecoverEthAddress({
|
|
881
|
+
msgDigest32,
|
|
882
|
+
r: rScalar,
|
|
883
|
+
s: sScalar,
|
|
884
|
+
yParity: sigEntry.yParity
|
|
885
|
+
});
|
|
886
|
+
} catch (err) {
|
|
887
|
+
throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `ecrecover failed on self-test subset [${sortedS.join(",")}]: ${err.message}`);
|
|
888
|
+
}
|
|
889
|
+
if (!recovered.recoveredPoint.equals(pRoot) || recovered.checksumAddress !== expectedRootAddr) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", `Step-4 self-test signature mismatch against P_root on subset [${sortedS.join(",")}]`);
|
|
890
|
+
}
|
|
891
|
+
if (seenKeys.size !== expectedKeys.size) throw new require_constants.MpcProtocolError("DKG_SELFTEST_FAILED", "Incomplete Step-4 subset self-test coverage");
|
|
892
|
+
return {
|
|
893
|
+
...ownRecord,
|
|
894
|
+
lifecycleState: "PROVISIONED_UNDRILLED",
|
|
895
|
+
secretShareBytes32: new Uint8Array(ownRecord.secretShareBytes32)
|
|
896
|
+
};
|
|
897
|
+
} catch (err) {
|
|
898
|
+
if (ownRecord?.secretShareBytes32 instanceof Uint8Array) require_secp256k1_scalar.zeroizeBytes(ownRecord.secretShareBytes32);
|
|
899
|
+
throw err;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
//#endregion
|
|
904
|
+
exports.AppendOnlyDkgEchoLock = AppendOnlyDkgEchoLock;
|
|
905
|
+
exports.DkgParticipantSession = DkgParticipantSession;
|
|
906
|
+
exports.assertSafeCeremonyId = assertSafeCeremonyId;
|
|
907
|
+
exports.computeDkgContextHash32 = computeDkgContextHash32;
|
|
908
|
+
exports.computeDkgSubsetSelfTestDigest32 = computeDkgSubsetSelfTestDigest32;
|
|
909
|
+
exports.promoteNodeRecordAfterSelfTests = promoteNodeRecordAfterSelfTests;
|
|
910
|
+
exports.validateAndComputeDkgContext = validateAndComputeDkgContext;
|