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