@bcts/frost-hubert 1.0.0-alpha.23 → 1.0.0-beta.1
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/README.md +1 -1
- package/dist/bin/frost.cjs +344 -72
- package/dist/bin/frost.cjs.map +1 -1
- package/dist/bin/frost.mjs +344 -71
- package/dist/bin/frost.mjs.map +1 -1
- package/dist/busy-B_h0bNAJ.cjs +38 -0
- package/dist/busy-B_h0bNAJ.cjs.map +1 -0
- package/dist/busy-BlU8_pS2.mjs +27 -0
- package/dist/busy-BlU8_pS2.mjs.map +1 -0
- package/dist/cmd/index.cjs +27 -22
- package/dist/cmd/index.d.cts +2 -2
- package/dist/cmd/index.d.mts +2 -2
- package/dist/cmd/index.mjs +6 -3
- package/dist/cmd-CCVhHzG7.cjs +129 -0
- package/dist/cmd-CCVhHzG7.cjs.map +1 -0
- package/dist/cmd-DNsHd19v.mjs +112 -0
- package/dist/cmd-DNsHd19v.mjs.map +1 -0
- package/dist/common-7-BOgaTt.cjs +113 -0
- package/dist/common-7-BOgaTt.cjs.map +1 -0
- package/dist/common-Cf1UvJaP.mjs +282 -0
- package/dist/common-Cf1UvJaP.mjs.map +1 -0
- package/dist/common-CnvAUC2b.cjs +372 -0
- package/dist/common-CnvAUC2b.cjs.map +1 -0
- package/dist/common-DNrD_-EI.mjs +96 -0
- package/dist/common-DNrD_-EI.mjs.map +1 -0
- package/dist/dkg/index.cjs +6 -103
- package/dist/dkg/index.cjs.map +1 -1
- package/dist/dkg/index.d.cts +2 -2
- package/dist/dkg/index.d.mts +2 -2
- package/dist/dkg/index.mjs +4 -101
- package/dist/dkg/index.mjs.map +1 -1
- package/dist/finalize-BpC0rz93.mjs +389 -0
- package/dist/finalize-BpC0rz93.mjs.map +1 -0
- package/dist/finalize-Cb0obTSo.cjs +402 -0
- package/dist/finalize-Cb0obTSo.cjs.map +1 -0
- package/dist/finalize-DHEnKobp.cjs +303 -0
- package/dist/finalize-DHEnKobp.cjs.map +1 -0
- package/dist/finalize-DQ0VGUHO.cjs +265 -0
- package/dist/finalize-DQ0VGUHO.cjs.map +1 -0
- package/dist/finalize-DtRxHZ7H.mjs +290 -0
- package/dist/finalize-DtRxHZ7H.mjs.map +1 -0
- package/dist/finalize-T83Ko8nG.mjs +252 -0
- package/dist/finalize-T83Ko8nG.mjs.map +1 -0
- package/dist/frost/index.cjs +1 -1
- package/dist/frost/index.cjs.map +1 -1
- package/dist/frost/index.d.cts.map +1 -1
- package/dist/frost/index.d.mts.map +1 -1
- package/dist/frost/index.mjs +1 -1
- package/dist/frost/index.mjs.map +1 -1
- package/dist/{index-BJlwbPYu.d.cts → index-BErX9AZF.d.cts} +101 -79
- package/dist/index-BErX9AZF.d.cts.map +1 -0
- package/dist/{index-BkqLimZT.d.mts → index-BaUVw4b1.d.mts} +25 -2
- package/dist/index-BaUVw4b1.d.mts.map +1 -0
- package/dist/{index-BMbPgH0W.d.cts → index-CD50Qtgw.d.cts} +46 -2
- package/dist/index-CD50Qtgw.d.cts.map +1 -0
- package/dist/{index-DoV5HFvV.d.mts → index-CD50Qtgw.d.mts} +46 -2
- package/dist/index-CD50Qtgw.d.mts.map +1 -0
- package/dist/{index-Dzm1v4_4.d.mts → index-Drklne-Y.d.mts} +101 -79
- package/dist/index-Drklne-Y.d.mts.map +1 -0
- package/dist/{index-DmxfT59Y.d.cts → index-gkmZzEuD.d.cts} +25 -2
- package/dist/index-gkmZzEuD.d.cts.map +1 -0
- package/dist/index.cjs +30 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +8 -4
- package/dist/index.mjs.map +1 -1
- package/dist/invite-1tzg0B0P.cjs +274 -0
- package/dist/invite-1tzg0B0P.cjs.map +1 -0
- package/dist/invite-BLwtexAu.cjs +109 -0
- package/dist/invite-BLwtexAu.cjs.map +1 -0
- package/dist/invite-Be2v2SVc.mjs +96 -0
- package/dist/invite-Be2v2SVc.mjs.map +1 -0
- package/dist/invite-D8mQSnFz.mjs +219 -0
- package/dist/invite-D8mQSnFz.mjs.map +1 -0
- package/dist/parallel-PZiwHZT8.mjs +235 -0
- package/dist/parallel-PZiwHZT8.mjs.map +1 -0
- package/dist/parallel-szwYx-bi.cjs +318 -0
- package/dist/parallel-szwYx-bi.cjs.map +1 -0
- package/dist/proposed-participant-BvHNnpcZ.cjs +140 -0
- package/dist/proposed-participant-BvHNnpcZ.cjs.map +1 -0
- package/dist/proposed-participant-Detb823_.mjs +129 -0
- package/dist/proposed-participant-Detb823_.mjs.map +1 -0
- package/dist/receive-BR-knnGv.cjs +213 -0
- package/dist/receive-BR-knnGv.cjs.map +1 -0
- package/dist/receive-D_r4Mryr.cjs +190 -0
- package/dist/receive-D_r4Mryr.cjs.map +1 -0
- package/dist/receive-dkSCSGpl.mjs +188 -0
- package/dist/receive-dkSCSGpl.mjs.map +1 -0
- package/dist/receive-g8EhZF2Y.mjs +177 -0
- package/dist/receive-g8EhZF2Y.mjs.map +1 -0
- package/dist/registry/index.cjs +86 -11
- package/dist/registry/index.cjs.map +1 -1
- package/dist/registry/index.d.cts +1 -1
- package/dist/registry/index.d.mts +1 -1
- package/dist/registry/index.mjs +85 -10
- package/dist/registry/index.mjs.map +1 -1
- package/dist/{registry-loI1_Mh1.cjs → registry-CkIbA7nt.cjs} +79 -2
- package/dist/registry-CkIbA7nt.cjs.map +1 -0
- package/dist/{registry-CgrCZ4En.mjs → registry-DGjs4qDK.mjs} +74 -3
- package/dist/registry-DGjs4qDK.mjs.map +1 -0
- package/dist/round1-9FAqFvL5.cjs +465 -0
- package/dist/round1-9FAqFvL5.cjs.map +1 -0
- package/dist/round1-B8haiMM8.mjs +208 -0
- package/dist/round1-B8haiMM8.mjs.map +1 -0
- package/dist/round1-BOIE1E4O.mjs +452 -0
- package/dist/round1-BOIE1E4O.mjs.map +1 -0
- package/dist/round1-Bq0vweyQ.cjs +422 -0
- package/dist/round1-Bq0vweyQ.cjs.map +1 -0
- package/dist/round1-CXkXoVQU.cjs +208 -0
- package/dist/round1-CXkXoVQU.cjs.map +1 -0
- package/dist/round1-D8t7EzIo.mjs +373 -0
- package/dist/round1-D8t7EzIo.mjs.map +1 -0
- package/dist/round1-DriPu15x.cjs +221 -0
- package/dist/round1-DriPu15x.cjs.map +1 -0
- package/dist/round1-Y2kcVwnR.mjs +195 -0
- package/dist/round1-Y2kcVwnR.mjs.map +1 -0
- package/dist/round2-AMDYMUIg.cjs +305 -0
- package/dist/round2-AMDYMUIg.cjs.map +1 -0
- package/dist/round2-BHQKVJFo.cjs +410 -0
- package/dist/round2-BHQKVJFo.cjs.map +1 -0
- package/dist/round2-BfetYacV.mjs +450 -0
- package/dist/round2-BfetYacV.mjs.map +1 -0
- package/dist/round2-Cf5CJc_8.mjs +397 -0
- package/dist/round2-Cf5CJc_8.mjs.map +1 -0
- package/dist/round2-CvrmylN1.cjs +293 -0
- package/dist/round2-CvrmylN1.cjs.map +1 -0
- package/dist/round2-Dk_w97nl.cjs +499 -0
- package/dist/round2-Dk_w97nl.cjs.map +1 -0
- package/dist/round2-Z2JhMwxc.mjs +292 -0
- package/dist/round2-Z2JhMwxc.mjs.map +1 -0
- package/dist/round2-mF6UlkT-.mjs +280 -0
- package/dist/round2-mF6UlkT-.mjs.map +1 -0
- package/package.json +14 -14
- package/src/bin/frost.ts +849 -128
- package/src/cmd/common.ts +19 -1
- package/src/cmd/dkg/common.ts +97 -10
- package/src/cmd/dkg/coordinator/invite.ts +5 -2
- package/src/cmd/dkg/participant/finalize.ts +51 -17
- package/src/cmd/dkg/participant/round1.ts +39 -38
- package/src/cmd/dkg/participant/round2.ts +60 -26
- package/src/cmd/sign/coordinator/round2.ts +5 -1
- package/src/cmd/sign/participant/finalize.ts +6 -2
- package/src/cmd/sign/participant/receive.ts +5 -2
- package/src/dkg/group-invite.ts +12 -2
- package/src/dkg/proposed-participant.ts +32 -3
- package/src/registry/owner-record.ts +12 -0
- package/src/registry/participant-record.ts +35 -2
- package/src/registry/registry-impl.ts +74 -18
- package/dist/cmd-5yLeC_QL.mjs +0 -4708
- package/dist/cmd-5yLeC_QL.mjs.map +0 -1
- package/dist/cmd-BfZjC3Uh.cjs +0 -4847
- package/dist/cmd-BfZjC3Uh.cjs.map +0 -1
- package/dist/index-BJlwbPYu.d.cts.map +0 -1
- package/dist/index-BMbPgH0W.d.cts.map +0 -1
- package/dist/index-BkqLimZT.d.mts.map +0 -1
- package/dist/index-DmxfT59Y.d.cts.map +0 -1
- package/dist/index-DoV5HFvV.d.mts.map +0 -1
- package/dist/index-Dzm1v4_4.d.mts.map +0 -1
- package/dist/registry-CgrCZ4En.mjs.map +0 -1
- package/dist/registry-loI1_Mh1.cjs.map +0 -1
- /package/dist/{chunk-CZWwpsFl.cjs → chunk-DakpK96I.cjs} +0 -0
- /package/dist/{chunk-CjcI7cDX.mjs → chunk-z9aeyW2b.mjs} +0 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { n as __require, t as __exportAll } from "./chunk-z9aeyW2b.mjs";
|
|
2
|
+
import { Registry, resolveRegistryPath } from "./registry/index.mjs";
|
|
3
|
+
import { c as parseAridUr } from "./common-Cf1UvJaP.mjs";
|
|
4
|
+
import { n as putWithIndicator, t as getWithIndicator } from "./busy-BlU8_pS2.mjs";
|
|
5
|
+
import { createSigningPackage, deserializeKeyPackage, deserializeSigningCommitments, identifierFromU16, serializeSignatureShare, serializeSigningCommitments, signingRound2 } from "./frost/index.mjs";
|
|
6
|
+
import { n as signingStateDir } from "./common-DNrD_-EI.mjs";
|
|
7
|
+
import { ARID, JSON as JSON$1, XID } from "@bcts/components";
|
|
8
|
+
import { CborDate } from "@bcts/dcbor";
|
|
9
|
+
import { Envelope, Function } from "@bcts/envelope";
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
import { Ed25519Sha512, serde } from "@frosts/ed25519";
|
|
13
|
+
import { Nonce, SigningNonces } from "@frosts/core";
|
|
14
|
+
//#region src/cmd/sign/participant/round2.ts
|
|
15
|
+
/**
|
|
16
|
+
* Copyright © 2023-2026 Blockchain Commons, LLC
|
|
17
|
+
* Copyright © 2025-2026 Parity Technologies
|
|
18
|
+
*
|
|
19
|
+
*
|
|
20
|
+
* Sign participant round 2 command.
|
|
21
|
+
*
|
|
22
|
+
* Port of cmd/sign/participant/round2.rs from frost-hubert-rust.
|
|
23
|
+
*
|
|
24
|
+
* @module
|
|
25
|
+
*/
|
|
26
|
+
var round2_exports = /* @__PURE__ */ __exportAll({ round2: () => round2$1 });
|
|
27
|
+
/**
|
|
28
|
+
* Load receive state from sign_receive.json.
|
|
29
|
+
*
|
|
30
|
+
* Port of `load_receive_state()` from cmd/sign/participant/round2.rs.
|
|
31
|
+
*/
|
|
32
|
+
function loadReceiveState(registryPath, sessionId, groupHint) {
|
|
33
|
+
const base = path.dirname(registryPath);
|
|
34
|
+
const groupStateDir = path.join(base, "group-state");
|
|
35
|
+
let groupDirs;
|
|
36
|
+
if (groupHint) groupDirs = [[groupHint, path.join(groupStateDir, groupHint.hex())]];
|
|
37
|
+
else {
|
|
38
|
+
groupDirs = [];
|
|
39
|
+
if (fs.existsSync(groupStateDir)) {
|
|
40
|
+
for (const entry of fs.readdirSync(groupStateDir, { withFileTypes: true })) if (entry.isDirectory() && entry.name.length === 64 && /^[0-9a-f]+$/i.test(entry.name)) {
|
|
41
|
+
const groupId = ARID.fromHex(entry.name);
|
|
42
|
+
groupDirs.push([groupId, path.join(groupStateDir, entry.name)]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const candidates = [];
|
|
47
|
+
for (const [groupId, groupDir] of groupDirs) {
|
|
48
|
+
const candidate = path.join(groupDir, "signing", sessionId.hex(), "sign_receive.json");
|
|
49
|
+
if (fs.existsSync(candidate)) candidates.push([groupId, candidate]);
|
|
50
|
+
}
|
|
51
|
+
if (candidates.length === 0) throw new Error("No sign_receive.json found for this session; run `frost sign participant receive` first");
|
|
52
|
+
if (candidates.length > 1) throw new Error("Multiple groups contain this session; use --group to disambiguate");
|
|
53
|
+
const [groupId, statePath] = candidates[0];
|
|
54
|
+
const raw = JSON.parse(fs.readFileSync(statePath, "utf-8"));
|
|
55
|
+
const getStr = (key) => {
|
|
56
|
+
const value = raw[key];
|
|
57
|
+
if (typeof value !== "string") throw new Error(`Missing or invalid ${key} in sign_receive.json`);
|
|
58
|
+
return value;
|
|
59
|
+
};
|
|
60
|
+
const sessionInState = parseAridUr(getStr("session"));
|
|
61
|
+
if (sessionInState.urString() !== sessionId.urString()) throw new Error(`Session ${sessionInState.urString()} in sign_receive.json does not match requested session ${sessionId.urString()}`);
|
|
62
|
+
const groupInState = parseAridUr(getStr("group"));
|
|
63
|
+
if (groupInState.urString() !== groupId.urString()) throw new Error(`Group ${groupInState.urString()} in sign_receive.json does not match directory group ${groupId.urString()}`);
|
|
64
|
+
const participantsVal = raw["participants"];
|
|
65
|
+
if (!participantsVal || !Array.isArray(participantsVal)) throw new Error("Missing participants in sign_receive.json");
|
|
66
|
+
const participants = [];
|
|
67
|
+
for (const entry of participantsVal) {
|
|
68
|
+
if (typeof entry !== "string") throw new Error("Invalid participant entry in sign_receive.json");
|
|
69
|
+
participants.push(XID.fromURString(entry));
|
|
70
|
+
}
|
|
71
|
+
const minSigners = raw["min_signers"];
|
|
72
|
+
if (typeof minSigners !== "number") throw new Error("Missing min_signers in sign_receive.json");
|
|
73
|
+
return {
|
|
74
|
+
groupId,
|
|
75
|
+
participants,
|
|
76
|
+
minSigners,
|
|
77
|
+
targetUr: getStr("target")
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Load commit state from commit.json (includes nonces).
|
|
82
|
+
*
|
|
83
|
+
* Port of `load_commit_state()` from cmd/sign/participant/round2.rs.
|
|
84
|
+
*/
|
|
85
|
+
function loadCommitState(registryPath, groupId, sessionId) {
|
|
86
|
+
const dir = signingStateDir(registryPath, groupId.hex(), sessionId.hex());
|
|
87
|
+
const statePath = path.join(dir, "commit.json");
|
|
88
|
+
if (!fs.existsSync(statePath)) throw new Error(`Commit state not found at ${statePath}. Run \`frost sign participant commit\` first.`);
|
|
89
|
+
const raw = JSON.parse(fs.readFileSync(statePath, "utf-8"));
|
|
90
|
+
const getStr = (key) => {
|
|
91
|
+
const value = raw[key];
|
|
92
|
+
if (typeof value !== "string") throw new Error(`Missing or invalid ${key} in commit.json`);
|
|
93
|
+
return value;
|
|
94
|
+
};
|
|
95
|
+
const sessionInState = parseAridUr(getStr("session"));
|
|
96
|
+
if (sessionInState.urString() !== sessionId.urString()) throw new Error(`Session ${sessionInState.urString()} in commit.json does not match requested session ${sessionId.urString()}`);
|
|
97
|
+
const nextShareArid = parseAridUr(getStr("next_share_arid"));
|
|
98
|
+
const targetUr = getStr("target");
|
|
99
|
+
const noncesRaw = raw["signing_nonces"];
|
|
100
|
+
if (!noncesRaw) throw new Error("Missing signing_nonces in commit.json");
|
|
101
|
+
const hidingNonce = Nonce.deserialize(Ed25519Sha512, serde.hexToBytes(noncesRaw["hiding"]));
|
|
102
|
+
const bindingNonce = Nonce.deserialize(Ed25519Sha512, serde.hexToBytes(noncesRaw["binding"]));
|
|
103
|
+
const signingNonces = SigningNonces.fromNonces(Ed25519Sha512, hidingNonce, bindingNonce);
|
|
104
|
+
const commitmentsRaw = raw["signing_commitments"];
|
|
105
|
+
if (!commitmentsRaw) throw new Error("Missing signing_commitments in commit.json");
|
|
106
|
+
return {
|
|
107
|
+
nextShareArid,
|
|
108
|
+
targetUr,
|
|
109
|
+
signingNonces,
|
|
110
|
+
signingCommitments: deserializeSigningCommitments(commitmentsRaw)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Validate the incoming GSTP request.
|
|
115
|
+
*
|
|
116
|
+
* Port of request validation logic from cmd/sign/participant/round2.rs.
|
|
117
|
+
*/
|
|
118
|
+
function validateShareRequest(sealedRequest, sessionId, expectedCoordinator) {
|
|
119
|
+
const expectedFunction = Function.fromString("signRound2");
|
|
120
|
+
if (sealedRequest.function().equals(expectedFunction) !== true) throw new Error(`Unexpected request function: ${String(sealedRequest.function())}`);
|
|
121
|
+
if (sealedRequest.id().urString() !== sessionId.urString()) throw new Error(`Session ID mismatch (request ${sealedRequest.id().urString()}, expected ${sessionId.urString()})`);
|
|
122
|
+
if (sealedRequest.sender().xid().urString() !== expectedCoordinator.urString()) throw new Error(`Unexpected request sender: ${sealedRequest.sender().xid().urString()} (expected coordinator ${expectedCoordinator.urString()})`);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Extract all commitments from the signRound2 request.
|
|
126
|
+
*
|
|
127
|
+
* Port of `parse_commitments()` from cmd/sign/participant/round2.rs.
|
|
128
|
+
*/
|
|
129
|
+
function extractCommitments(sealedRequest, receiveState) {
|
|
130
|
+
const commitments = /* @__PURE__ */ new Map();
|
|
131
|
+
const commitmentObjects = sealedRequest.objectsForParameter("commitment");
|
|
132
|
+
for (const entry of commitmentObjects) {
|
|
133
|
+
const xid = XID.fromTaggedCbor(entry.subject().tryLeaf());
|
|
134
|
+
const commitmentsObjects = entry.objectsForPredicate("commitments");
|
|
135
|
+
if (commitmentsObjects.length === 0) throw new Error(`Missing commitments for participant ${xid.urString()}`);
|
|
136
|
+
const commitmentsJson = JSON$1.fromTaggedCbor(commitmentsObjects[0].subject().tryLeaf());
|
|
137
|
+
const signingCommitments = deserializeSigningCommitments(JSON.parse(commitmentsJson.asStr()));
|
|
138
|
+
const xidUr = xid.urString();
|
|
139
|
+
if (commitments.has(xidUr)) throw new Error(`Duplicate commitments for participant ${xidUr}`);
|
|
140
|
+
commitments.set(xidUr, signingCommitments);
|
|
141
|
+
}
|
|
142
|
+
if (commitments.size === 0) throw new Error("signRound2 request contains no commitments");
|
|
143
|
+
const expectedSet = new Set(receiveState.participants.map((p) => p.urString()));
|
|
144
|
+
const actualSet = new Set(commitments.keys());
|
|
145
|
+
const missing = [];
|
|
146
|
+
const extra = [];
|
|
147
|
+
for (const xid of expectedSet) if (!actualSet.has(xid)) missing.push(xid);
|
|
148
|
+
for (const xid of actualSet) if (!expectedSet.has(xid)) extra.push(xid);
|
|
149
|
+
if (missing.length > 0 || extra.length > 0) throw new Error(`signRound2 commitments do not match session participants (missing: ${missing.join(", ")}; extra: ${extra.join(", ")})`);
|
|
150
|
+
return commitments;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Build a map from XID to FROST identifier (sorted participant order).
|
|
154
|
+
*
|
|
155
|
+
* Port of `xid_identifier_map()` from cmd/sign/participant/round2.rs.
|
|
156
|
+
*/
|
|
157
|
+
function xidIdentifierMap(participants) {
|
|
158
|
+
const map = /* @__PURE__ */ new Map();
|
|
159
|
+
for (let i = 0; i < participants.length; i++) {
|
|
160
|
+
const identifier = identifierFromU16(i + 1);
|
|
161
|
+
map.set(participants[i].urString(), identifier);
|
|
162
|
+
}
|
|
163
|
+
return map;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Build signing commitments with identifiers.
|
|
167
|
+
*
|
|
168
|
+
* Port of `commitments_with_identifiers()` from cmd/sign/participant/round2.rs.
|
|
169
|
+
*/
|
|
170
|
+
function commitmentsWithIdentifiers(commitments, xidToIdentifier) {
|
|
171
|
+
const mapped = /* @__PURE__ */ new Map();
|
|
172
|
+
for (const [xidUr, commits] of commitments) {
|
|
173
|
+
const identifier = xidToIdentifier.get(xidUr);
|
|
174
|
+
if (!identifier) throw new Error(`Unknown participant ${xidUr}`);
|
|
175
|
+
mapped.set(identifier, commits);
|
|
176
|
+
}
|
|
177
|
+
return mapped;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Build the signRound2Response body envelope.
|
|
181
|
+
*
|
|
182
|
+
* Port of response body construction from cmd/sign/participant/round2.rs.
|
|
183
|
+
*/
|
|
184
|
+
function buildResponseBody(sessionId, signatureShare, finalizeArid) {
|
|
185
|
+
const shareHex = serializeSignatureShare(signatureShare);
|
|
186
|
+
const shareJson = JSON$1.fromString(JSON.stringify({ share: shareHex }));
|
|
187
|
+
return Envelope.unit().addType("signRound2Response").addAssertion("session", sessionId).addAssertion("signature_share", shareJson).addAssertion("response_arid", finalizeArid);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Persist share state to share.json.
|
|
191
|
+
*
|
|
192
|
+
* Port of `persist_share_state()` from cmd/sign/participant/round2.rs.
|
|
193
|
+
*/
|
|
194
|
+
function persistShareState(registryPath, groupId, sessionId, responseArid, finalizeArid, signatureShare, commitments) {
|
|
195
|
+
const dir = signingStateDir(registryPath, groupId.hex(), sessionId.hex());
|
|
196
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
197
|
+
const commitmentsJson = {};
|
|
198
|
+
for (const [xidUr, commits] of commitments) commitmentsJson[xidUr] = serializeSigningCommitments(commits);
|
|
199
|
+
const root = {
|
|
200
|
+
session: sessionId.urString(),
|
|
201
|
+
response_arid: responseArid.urString(),
|
|
202
|
+
finalize_arid: finalizeArid.urString(),
|
|
203
|
+
signature_share: { share: serializeSignatureShare(signatureShare) },
|
|
204
|
+
commitments: commitmentsJson
|
|
205
|
+
};
|
|
206
|
+
fs.writeFileSync(path.join(dir, "share.json"), JSON.stringify(root, null, 2));
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Execute the sign participant round 2 command.
|
|
210
|
+
*
|
|
211
|
+
* Receives round 2 request and sends signature share.
|
|
212
|
+
*
|
|
213
|
+
* Port of `CommandArgs::exec()` from cmd/sign/participant/round2.rs.
|
|
214
|
+
*/
|
|
215
|
+
async function round2$1(client, options, cwd) {
|
|
216
|
+
const registryPath = resolveRegistryPath(options.registryPath, cwd);
|
|
217
|
+
const registry = Registry.load(registryPath);
|
|
218
|
+
const owner = registry.owner();
|
|
219
|
+
if (!owner) throw new Error("Registry owner is required");
|
|
220
|
+
const ownerXidDocument = owner.xidDocument();
|
|
221
|
+
const sessionId = parseAridUr(options.sessionId);
|
|
222
|
+
const receiveState = loadReceiveState(registryPath, sessionId, options.groupId ? parseAridUr(options.groupId) : void 0);
|
|
223
|
+
const groupId = receiveState.groupId;
|
|
224
|
+
const groupRecord = registry.group(groupId);
|
|
225
|
+
if (!groupRecord) throw new Error("Group not found in registry");
|
|
226
|
+
if (groupRecord.minSigners() !== receiveState.minSigners) throw new Error(`Session min_signers ${receiveState.minSigners} does not match registry ${groupRecord.minSigners()}`);
|
|
227
|
+
const registryParticipants = new Set(groupRecord.participants().map((p) => p.xid().urString()));
|
|
228
|
+
const sessionParticipants = new Set(receiveState.participants.map((p) => p.urString()));
|
|
229
|
+
if (registryParticipants.size !== sessionParticipants.size || ![...registryParticipants].every((p) => sessionParticipants.has(p))) throw new Error("Session participants do not match registry group participants");
|
|
230
|
+
if (!sessionParticipants.has(owner.xid().urString())) throw new Error("This participant is not part of the signing session");
|
|
231
|
+
const listeningAtArid = groupRecord.listeningAtArid();
|
|
232
|
+
if (!listeningAtArid) throw new Error("No listening ARID for signRound2. Did you run `frost sign participant commit`?");
|
|
233
|
+
const commitState = loadCommitState(registryPath, groupId, sessionId);
|
|
234
|
+
if (commitState.nextShareArid.urString() !== listeningAtArid.urString()) throw new Error(`Listening ARID in registry (${listeningAtArid.urString()}) does not match persisted commit state (${commitState.nextShareArid.urString()})`);
|
|
235
|
+
if (commitState.targetUr !== receiveState.targetUr) throw new Error("Target envelope in commit state does not match persisted signInvite request");
|
|
236
|
+
const keyPackagePath = groupRecord.contributions().keyPackage;
|
|
237
|
+
if (!keyPackagePath) throw new Error("Key package path not found; did you finish DKG?");
|
|
238
|
+
const keyPackage = deserializeKeyPackage(JSON.parse(fs.readFileSync(keyPackagePath, "utf-8")).key_package);
|
|
239
|
+
const finalizeArid = ARID.new();
|
|
240
|
+
const targetDigest = Envelope.fromURString(receiveState.targetUr).subject().digest();
|
|
241
|
+
if (options.verbose === true) console.error("Fetching signRound2 request from Hubert...");
|
|
242
|
+
const requestEnvelope = await getWithIndicator(client, listeningAtArid, "signRound2 request", options.timeoutSeconds, options.verbose ?? false);
|
|
243
|
+
if (!requestEnvelope) throw new Error("signRound2 request not found in Hubert storage");
|
|
244
|
+
const signerPrivateKeys = ownerXidDocument.inceptionPrivateKeys();
|
|
245
|
+
if (!signerPrivateKeys) throw new Error("Owner XID document has no private keys");
|
|
246
|
+
const { SealedRequest: SealedRequestClass } = __require("@bcts/gstp");
|
|
247
|
+
const now = CborDate.now();
|
|
248
|
+
const sealedRequest = SealedRequestClass.tryFromEnvelope(requestEnvelope, void 0, now, signerPrivateKeys);
|
|
249
|
+
const expectedCoordinator = groupRecord.coordinator().xid();
|
|
250
|
+
validateShareRequest(sealedRequest, sessionId, expectedCoordinator);
|
|
251
|
+
const responseArid = sealedRequest.extractObjectForParameter("response_arid");
|
|
252
|
+
const commitmentsByXid = extractCommitments(sealedRequest, receiveState);
|
|
253
|
+
const myCommitments = commitmentsByXid.get(owner.xid().urString());
|
|
254
|
+
if (!myCommitments) throw new Error("signRound2 request missing commitments for this participant");
|
|
255
|
+
const myCommitmentsSerialized = serializeSigningCommitments(myCommitments);
|
|
256
|
+
const storedCommitmentsSerialized = serializeSigningCommitments(commitState.signingCommitments);
|
|
257
|
+
if (myCommitmentsSerialized.hiding !== storedCommitmentsSerialized.hiding || myCommitmentsSerialized.binding !== storedCommitmentsSerialized.binding) throw new Error("signRound2 request commitments do not match locally stored commitments");
|
|
258
|
+
const xidToIdentifier = xidIdentifierMap(receiveState.participants);
|
|
259
|
+
if (!xidToIdentifier.get(owner.xid().urString())) throw new Error("Identifier for participant not found");
|
|
260
|
+
if (keyPackage.minSigners !== receiveState.minSigners) throw new Error(`Key package min_signers ${keyPackage.minSigners} does not match session ${receiveState.minSigners}`);
|
|
261
|
+
if (commitmentsByXid.size < receiveState.minSigners) throw new Error(`signRound2 request contained ${commitmentsByXid.size} commitments but requires at least ${receiveState.minSigners} signers`);
|
|
262
|
+
const signatureShare = signingRound2(createSigningPackage(commitmentsWithIdentifiers(commitmentsByXid, xidToIdentifier), targetDigest.data()), commitState.signingNonces, keyPackage);
|
|
263
|
+
const responseBody = buildResponseBody(sessionId, signatureShare, finalizeArid);
|
|
264
|
+
const { SealedResponse: SealedResponseClass } = __require("@bcts/gstp");
|
|
265
|
+
const sealedResponse = SealedResponseClass.newSuccess(sealedRequest.id(), ownerXidDocument).withResult(responseBody);
|
|
266
|
+
if (options.preview === true) {
|
|
267
|
+
const unsealed = sealedResponse.toEnvelope(void 0, signerPrivateKeys, void 0);
|
|
268
|
+
console.log(unsealed.urString());
|
|
269
|
+
return { listeningArid: finalizeArid.urString() };
|
|
270
|
+
}
|
|
271
|
+
let coordinatorDoc;
|
|
272
|
+
if (expectedCoordinator.urString() === owner.xid().urString()) coordinatorDoc = ownerXidDocument;
|
|
273
|
+
else {
|
|
274
|
+
const coordinatorRecord = registry.participant(expectedCoordinator);
|
|
275
|
+
if (!coordinatorRecord) throw new Error(`Coordinator ${expectedCoordinator.urString()} not found in registry`);
|
|
276
|
+
coordinatorDoc = coordinatorRecord.xidDocument();
|
|
277
|
+
}
|
|
278
|
+
const expiry = CborDate.withDurationFromNow(3600);
|
|
279
|
+
await putWithIndicator(client, responseArid, sealedResponse.toEnvelope(expiry, signerPrivateKeys, coordinatorDoc), "Signature Share", options.verbose ?? false);
|
|
280
|
+
persistShareState(registryPath, groupId, sessionId, responseArid, finalizeArid, signatureShare, commitmentsByXid);
|
|
281
|
+
const groupRecordMutable = registry.group(groupId);
|
|
282
|
+
if (groupRecordMutable) {
|
|
283
|
+
groupRecordMutable.setListeningAtArid(finalizeArid);
|
|
284
|
+
registry.save(registryPath);
|
|
285
|
+
}
|
|
286
|
+
if (options.verbose === true) console.error(`Posted signature share to ${responseArid.urString()}`);
|
|
287
|
+
return { listeningArid: finalizeArid.urString() };
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
export { round2_exports as n, round2$1 as t };
|
|
291
|
+
|
|
292
|
+
//# sourceMappingURL=round2-Z2JhMwxc.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"round2-Z2JhMwxc.mjs","names":["ARIDClass","XIDClass","EnvelopeFunction","JSONComponent","round2"],"sources":["../src/cmd/sign/participant/round2.ts"],"sourcesContent":["/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Sign participant round 2 command.\n *\n * Port of cmd/sign/participant/round2.rs from frost-hubert-rust.\n *\n * @module\n */\n\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport {\n type ARID,\n type XID,\n XID as XIDClass,\n ARID as ARIDClass,\n JSON as JSONComponent,\n type Digest,\n} from \"@bcts/components\";\nimport { CborDate } from \"@bcts/dcbor\";\nimport { Envelope, Function as EnvelopeFunction } from \"@bcts/envelope\";\nimport { type XIDDocument } from \"@bcts/xid\";\n\nimport { Registry, resolveRegistryPath } from \"../../../registry/index.js\";\nimport { getWithIndicator, putWithIndicator } from \"../../busy.js\";\nimport { type StorageClient } from \"../../storage.js\";\nimport { parseAridUr } from \"../../dkg/common.js\";\nimport { signingStateDir } from \"../common.js\";\nimport {\n signingRound2,\n createSigningPackage,\n deserializeKeyPackage,\n deserializeSigningCommitments,\n serializeSignatureShare,\n serializeSigningCommitments,\n identifierFromU16,\n type SerializedKeyPackage,\n type SerializedSigningCommitments,\n type FrostIdentifier,\n type FrostKeyPackage,\n type Ed25519SigningCommitments,\n type Ed25519SignatureShare,\n} from \"../../../frost/index.js\";\n\n// Import nonces from @frosts/core\nimport { Nonce, SigningNonces } from \"@frosts/core\";\nimport { Ed25519Sha512, serde } from \"@frosts/ed25519\";\n\n/**\n * Options for the sign round2 command.\n */\nexport interface SignRound2Options {\n registryPath?: string;\n sessionId: string;\n groupId?: string;\n timeoutSeconds?: number;\n preview?: boolean;\n verbose?: boolean;\n}\n\n/**\n * Result of the sign round2 command.\n */\nexport interface SignRound2Result {\n listeningArid: string;\n}\n\n/**\n * ReceiveState loaded from sign_receive.json.\n *\n * Port of `struct ReceiveState` from cmd/sign/participant/round2.rs.\n */\ninterface ReceiveState {\n groupId: ARID;\n participants: XID[];\n minSigners: number;\n targetUr: string;\n}\n\n/**\n * CommitState loaded from commit.json.\n *\n * Port of `struct CommitState` from cmd/sign/participant/round2.rs.\n */\ninterface CommitState {\n nextShareArid: ARID;\n targetUr: string;\n signingNonces: SigningNonces<typeof Ed25519Sha512>;\n signingCommitments: Ed25519SigningCommitments;\n}\n\n/**\n * Sealed request interface for GSTP.\n */\ninterface SealedRequestInstance {\n function: () => unknown;\n id: () => ARID;\n sender: () => { xid: () => XID };\n extractObjectForParameter: <T>(name: string) => T;\n objectsForParameter: (name: string) => Envelope[];\n}\n\n/**\n * Load receive state from sign_receive.json.\n *\n * Port of `load_receive_state()` from cmd/sign/participant/round2.rs.\n */\nfunction loadReceiveState(registryPath: string, sessionId: ARID, groupHint?: ARID): ReceiveState {\n const base = path.dirname(registryPath);\n const groupStateDir = path.join(base, \"group-state\");\n\n // Find candidate paths\n let groupDirs: [ARID, string][];\n\n if (groupHint) {\n groupDirs = [[groupHint, path.join(groupStateDir, groupHint.hex())]];\n } else {\n groupDirs = [];\n if (fs.existsSync(groupStateDir)) {\n for (const entry of fs.readdirSync(groupStateDir, { withFileTypes: true })) {\n if (entry.isDirectory() && entry.name.length === 64 && /^[0-9a-f]+$/i.test(entry.name)) {\n const groupId = ARIDClass.fromHex(entry.name);\n groupDirs.push([groupId, path.join(groupStateDir, entry.name)]);\n }\n }\n }\n }\n\n const candidates: [ARID, string][] = [];\n for (const [groupId, groupDir] of groupDirs) {\n const candidate = path.join(groupDir, \"signing\", sessionId.hex(), \"sign_receive.json\");\n if (fs.existsSync(candidate)) {\n candidates.push([groupId, candidate]);\n }\n }\n\n if (candidates.length === 0) {\n throw new Error(\n \"No sign_receive.json found for this session; run `frost sign participant receive` first\",\n );\n }\n if (candidates.length > 1) {\n throw new Error(\"Multiple groups contain this session; use --group to disambiguate\");\n }\n\n const [groupId, statePath] = candidates[0];\n const raw = JSON.parse(fs.readFileSync(statePath, \"utf-8\")) as Record<string, unknown>;\n\n const getStr = (key: string): string => {\n const value = raw[key];\n if (typeof value !== \"string\") {\n throw new Error(`Missing or invalid ${key} in sign_receive.json`);\n }\n return value;\n };\n\n // Validate session matches\n const sessionInState = parseAridUr(getStr(\"session\"));\n if (sessionInState.urString() !== sessionId.urString()) {\n throw new Error(\n `Session ${sessionInState.urString()} in sign_receive.json does not match requested session ${sessionId.urString()}`,\n );\n }\n\n // Validate group matches\n const groupInState = parseAridUr(getStr(\"group\"));\n if (groupInState.urString() !== groupId.urString()) {\n throw new Error(\n `Group ${groupInState.urString()} in sign_receive.json does not match directory group ${groupId.urString()}`,\n );\n }\n\n // Parse participants\n const participantsVal = raw[\"participants\"] as string[] | undefined;\n if (!participantsVal || !Array.isArray(participantsVal)) {\n throw new Error(\"Missing participants in sign_receive.json\");\n }\n\n const participants: XID[] = [];\n for (const entry of participantsVal) {\n if (typeof entry !== \"string\") {\n throw new Error(\"Invalid participant entry in sign_receive.json\");\n }\n participants.push(XIDClass.fromURString(entry));\n }\n\n // Parse min_signers\n const minSigners = raw[\"min_signers\"];\n if (typeof minSigners !== \"number\") {\n throw new Error(\"Missing min_signers in sign_receive.json\");\n }\n\n const targetUr = getStr(\"target\");\n\n return {\n groupId,\n participants,\n minSigners,\n targetUr,\n };\n}\n\n/**\n * Load commit state from commit.json (includes nonces).\n *\n * Port of `load_commit_state()` from cmd/sign/participant/round2.rs.\n */\nfunction loadCommitState(registryPath: string, groupId: ARID, sessionId: ARID): CommitState {\n const dir = signingStateDir(registryPath, groupId.hex(), sessionId.hex());\n const statePath = path.join(dir, \"commit.json\");\n\n if (!fs.existsSync(statePath)) {\n throw new Error(\n `Commit state not found at ${statePath}. Run \\`frost sign participant commit\\` first.`,\n );\n }\n\n const raw = JSON.parse(fs.readFileSync(statePath, \"utf-8\")) as Record<string, unknown>;\n\n const getStr = (key: string): string => {\n const value = raw[key];\n if (typeof value !== \"string\") {\n throw new Error(`Missing or invalid ${key} in commit.json`);\n }\n return value;\n };\n\n // Validate session matches\n const sessionInState = parseAridUr(getStr(\"session\"));\n if (sessionInState.urString() !== sessionId.urString()) {\n throw new Error(\n `Session ${sessionInState.urString()} in commit.json does not match requested session ${sessionId.urString()}`,\n );\n }\n\n const nextShareArid = parseAridUr(getStr(\"next_share_arid\"));\n const targetUr = getStr(\"target\");\n\n // Deserialize signing nonces\n const noncesRaw = raw[\"signing_nonces\"] as Record<string, string> | undefined;\n if (!noncesRaw) {\n throw new Error(\"Missing signing_nonces in commit.json\");\n }\n\n const hidingNonce = Nonce.deserialize(Ed25519Sha512, serde.hexToBytes(noncesRaw[\"hiding\"]));\n const bindingNonce = Nonce.deserialize(Ed25519Sha512, serde.hexToBytes(noncesRaw[\"binding\"]));\n const signingNonces = SigningNonces.fromNonces(Ed25519Sha512, hidingNonce, bindingNonce);\n\n // Deserialize signing commitments\n const commitmentsRaw = raw[\"signing_commitments\"] as SerializedSigningCommitments | undefined;\n if (!commitmentsRaw) {\n throw new Error(\"Missing signing_commitments in commit.json\");\n }\n const signingCommitments = deserializeSigningCommitments(commitmentsRaw);\n\n return {\n nextShareArid,\n targetUr,\n signingNonces,\n signingCommitments,\n };\n}\n\n/**\n * Validate the incoming GSTP request.\n *\n * Port of request validation logic from cmd/sign/participant/round2.rs.\n */\nfunction validateShareRequest(\n sealedRequest: SealedRequestInstance,\n sessionId: ARID,\n expectedCoordinator: XID,\n): void {\n // Check function\n const expectedFunction = EnvelopeFunction.fromString(\"signRound2\");\n const actualFunction = sealedRequest.function();\n // @ts-expect-error - function() returns unknown, but it should have .equals()\n if (actualFunction.equals(expectedFunction) !== true) {\n throw new Error(`Unexpected request function: ${String(sealedRequest.function())}`);\n }\n\n // Check session ID\n if (sealedRequest.id().urString() !== sessionId.urString()) {\n throw new Error(\n `Session ID mismatch (request ${sealedRequest.id().urString()}, expected ${sessionId.urString()})`,\n );\n }\n\n // Check sender (coordinator)\n if (sealedRequest.sender().xid().urString() !== expectedCoordinator.urString()) {\n throw new Error(\n `Unexpected request sender: ${sealedRequest.sender().xid().urString()} (expected coordinator ${expectedCoordinator.urString()})`,\n );\n }\n}\n\n/**\n * Extract all commitments from the signRound2 request.\n *\n * Port of `parse_commitments()` from cmd/sign/participant/round2.rs.\n */\nfunction extractCommitments(\n sealedRequest: SealedRequestInstance,\n receiveState: ReceiveState,\n): Map<string, Ed25519SigningCommitments> {\n const commitments = new Map<string, Ed25519SigningCommitments>();\n\n const commitmentObjects = sealedRequest.objectsForParameter(\"commitment\");\n\n for (const entry of commitmentObjects) {\n // Extract XID subject\n const xid = XIDClass.fromTaggedCbor(entry.subject().tryLeaf());\n\n // Extract commitments from the \"commitments\" predicate\n const commitmentsObjects = entry.objectsForPredicate(\"commitments\");\n if (commitmentsObjects.length === 0) {\n throw new Error(`Missing commitments for participant ${xid.urString()}`);\n }\n\n const commitmentsJson = JSONComponent.fromTaggedCbor(commitmentsObjects[0].subject().tryLeaf());\n const serializedCommitments = JSON.parse(\n commitmentsJson.asStr(),\n ) as SerializedSigningCommitments;\n const signingCommitments = deserializeSigningCommitments(serializedCommitments);\n\n const xidUr = xid.urString();\n if (commitments.has(xidUr)) {\n throw new Error(`Duplicate commitments for participant ${xidUr}`);\n }\n commitments.set(xidUr, signingCommitments);\n }\n\n if (commitments.size === 0) {\n throw new Error(\"signRound2 request contains no commitments\");\n }\n\n // Validate expected participant set\n const expectedSet = new Set(receiveState.participants.map((p) => p.urString()));\n const actualSet = new Set(commitments.keys());\n\n const missing: string[] = [];\n const extra: string[] = [];\n\n for (const xid of expectedSet) {\n if (!actualSet.has(xid)) {\n missing.push(xid);\n }\n }\n for (const xid of actualSet) {\n if (!expectedSet.has(xid)) {\n extra.push(xid);\n }\n }\n\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `signRound2 commitments do not match session participants (missing: ${missing.join(\", \")}; extra: ${extra.join(\", \")})`,\n );\n }\n\n return commitments;\n}\n\n/**\n * Build a map from XID to FROST identifier (sorted participant order).\n *\n * Port of `xid_identifier_map()` from cmd/sign/participant/round2.rs.\n */\nfunction xidIdentifierMap(participants: XID[]): Map<string, FrostIdentifier> {\n const map = new Map<string, FrostIdentifier>();\n for (let i = 0; i < participants.length; i++) {\n const identifier = identifierFromU16(i + 1);\n map.set(participants[i].urString(), identifier);\n }\n return map;\n}\n\n/**\n * Build signing commitments with identifiers.\n *\n * Port of `commitments_with_identifiers()` from cmd/sign/participant/round2.rs.\n */\nfunction commitmentsWithIdentifiers(\n commitments: Map<string, Ed25519SigningCommitments>,\n xidToIdentifier: Map<string, FrostIdentifier>,\n): Map<FrostIdentifier, Ed25519SigningCommitments> {\n const mapped = new Map<FrostIdentifier, Ed25519SigningCommitments>();\n for (const [xidUr, commits] of commitments) {\n const identifier = xidToIdentifier.get(xidUr);\n if (!identifier) {\n throw new Error(`Unknown participant ${xidUr}`);\n }\n mapped.set(identifier, commits);\n }\n return mapped;\n}\n\n/**\n * Build the signRound2Response body envelope.\n *\n * Port of response body construction from cmd/sign/participant/round2.rs.\n */\nfunction buildResponseBody(\n sessionId: ARID,\n signatureShare: Ed25519SignatureShare,\n finalizeArid: ARID,\n): Envelope {\n const shareHex = serializeSignatureShare(signatureShare);\n const shareJson = JSONComponent.fromString(JSON.stringify({ share: shareHex }));\n\n return Envelope.unit()\n .addType(\"signRound2Response\")\n .addAssertion(\"session\", sessionId)\n .addAssertion(\"signature_share\", shareJson)\n .addAssertion(\"response_arid\", finalizeArid);\n}\n\n/**\n * Persist share state to share.json.\n *\n * Port of `persist_share_state()` from cmd/sign/participant/round2.rs.\n */\nfunction persistShareState(\n registryPath: string,\n groupId: ARID,\n sessionId: ARID,\n responseArid: ARID,\n finalizeArid: ARID,\n signatureShare: Ed25519SignatureShare,\n commitments: Map<string, Ed25519SigningCommitments>,\n): void {\n const dir = signingStateDir(registryPath, groupId.hex(), sessionId.hex());\n fs.mkdirSync(dir, { recursive: true });\n\n // Build commitments JSON object\n const commitmentsJson: Record<string, SerializedSigningCommitments> = {};\n for (const [xidUr, commits] of commitments) {\n commitmentsJson[xidUr] = serializeSigningCommitments(commits);\n }\n\n // Build root JSON object\n const root = {\n session: sessionId.urString(),\n response_arid: responseArid.urString(),\n finalize_arid: finalizeArid.urString(),\n signature_share: { share: serializeSignatureShare(signatureShare) },\n commitments: commitmentsJson,\n };\n\n fs.writeFileSync(path.join(dir, \"share.json\"), JSON.stringify(root, null, 2));\n}\n\n/**\n * Execute the sign participant round 2 command.\n *\n * Receives round 2 request and sends signature share.\n *\n * Port of `CommandArgs::exec()` from cmd/sign/participant/round2.rs.\n */\nexport async function round2(\n client: StorageClient,\n options: SignRound2Options,\n cwd: string,\n): Promise<SignRound2Result> {\n const registryPath = resolveRegistryPath(options.registryPath, cwd);\n const registry = Registry.load(registryPath);\n\n const owner = registry.owner();\n if (!owner) {\n throw new Error(\"Registry owner is required\");\n }\n const ownerXidDocument = owner.xidDocument();\n\n const sessionId = parseAridUr(options.sessionId);\n const groupHint = options.groupId ? parseAridUr(options.groupId) : undefined;\n\n // Load receive state (finds group automatically if not specified)\n const receiveState = loadReceiveState(registryPath, sessionId, groupHint);\n const groupId = receiveState.groupId;\n\n const groupRecord = registry.group(groupId);\n if (!groupRecord) {\n throw new Error(\"Group not found in registry\");\n }\n\n // Validate min_signers matches\n if (groupRecord.minSigners() !== receiveState.minSigners) {\n throw new Error(\n `Session min_signers ${receiveState.minSigners} does not match registry ${groupRecord.minSigners()}`,\n );\n }\n\n // Validate participants match\n const registryParticipants = new Set(groupRecord.participants().map((p) => p.xid().urString()));\n const sessionParticipants = new Set(receiveState.participants.map((p) => p.urString()));\n\n if (\n registryParticipants.size !== sessionParticipants.size ||\n ![...registryParticipants].every((p) => sessionParticipants.has(p))\n ) {\n throw new Error(\"Session participants do not match registry group participants\");\n }\n\n // Validate owner participates in this session\n if (!sessionParticipants.has(owner.xid().urString())) {\n throw new Error(\"This participant is not part of the signing session\");\n }\n\n // Get listening ARID from registry\n const listeningAtArid = groupRecord.listeningAtArid();\n if (!listeningAtArid) {\n throw new Error(\n \"No listening ARID for signRound2. Did you run `frost sign participant commit`?\",\n );\n }\n\n // Load commit state and validate\n const commitState = loadCommitState(registryPath, groupId, sessionId);\n\n if (commitState.nextShareArid.urString() !== listeningAtArid.urString()) {\n throw new Error(\n `Listening ARID in registry (${listeningAtArid.urString()}) does not match persisted commit state (${commitState.nextShareArid.urString()})`,\n );\n }\n\n if (commitState.targetUr !== receiveState.targetUr) {\n throw new Error(\"Target envelope in commit state does not match persisted signInvite request\");\n }\n\n // Load key package\n const keyPackagePath = groupRecord.contributions().keyPackage;\n if (!keyPackagePath) {\n throw new Error(\"Key package path not found; did you finish DKG?\");\n }\n\n interface KeyPackageFile {\n group?: string;\n key_package: SerializedKeyPackage;\n }\n\n const keyPackageFile = JSON.parse(fs.readFileSync(keyPackagePath, \"utf-8\")) as KeyPackageFile;\n const keyPackage: FrostKeyPackage = deserializeKeyPackage(keyPackageFile.key_package);\n\n // Create finalize ARID\n const finalizeArid = ARIDClass.new();\n\n // Compute target digest from persisted target envelope\n const targetEnvelope = Envelope.fromURString(receiveState.targetUr);\n const targetDigest: Digest = targetEnvelope.subject().digest();\n\n if (options.verbose === true) {\n console.error(\"Fetching signRound2 request from Hubert...\");\n }\n\n // Fetch request from storage\n const requestEnvelope = await getWithIndicator(\n client,\n listeningAtArid,\n \"signRound2 request\",\n options.timeoutSeconds,\n options.verbose ?? false,\n );\n\n if (!requestEnvelope) {\n throw new Error(\"signRound2 request not found in Hubert storage\");\n }\n\n // Parse sealed request\n const signerPrivateKeys = ownerXidDocument.inceptionPrivateKeys();\n if (!signerPrivateKeys) {\n throw new Error(\"Owner XID document has no private keys\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports, no-undef\n const { SealedRequest: SealedRequestClass } = require(\"@bcts/gstp\") as {\n SealedRequest: {\n tryFromEnvelope: (\n envelope: Envelope,\n expectedSender: XID | undefined,\n now: CborDate,\n recipientPrivateKeys: unknown,\n ) => SealedRequestInstance;\n };\n };\n\n const now = CborDate.now();\n const sealedRequest = SealedRequestClass.tryFromEnvelope(\n requestEnvelope,\n undefined,\n now,\n signerPrivateKeys,\n );\n\n // Validate request\n const expectedCoordinator = groupRecord.coordinator().xid();\n validateShareRequest(sealedRequest, sessionId, expectedCoordinator);\n\n // Extract response ARID from request\n const responseArid: ARID = sealedRequest.extractObjectForParameter(\"response_arid\");\n\n // Extract and validate commitments\n const commitmentsByXid = extractCommitments(sealedRequest, receiveState);\n\n // Verify our commitments match\n const myCommitments = commitmentsByXid.get(owner.xid().urString());\n if (!myCommitments) {\n throw new Error(\"signRound2 request missing commitments for this participant\");\n }\n\n // Compare commitments using serialized form\n const myCommitmentsSerialized = serializeSigningCommitments(myCommitments);\n const storedCommitmentsSerialized = serializeSigningCommitments(commitState.signingCommitments);\n\n if (\n myCommitmentsSerialized.hiding !== storedCommitmentsSerialized.hiding ||\n myCommitmentsSerialized.binding !== storedCommitmentsSerialized.binding\n ) {\n throw new Error(\"signRound2 request commitments do not match locally stored commitments\");\n }\n\n // Build XID to identifier map (sorted participant order)\n const xidToIdentifier = xidIdentifierMap(receiveState.participants);\n\n // Verify our identifier matches key package\n const myIdentifier = xidToIdentifier.get(owner.xid().urString());\n if (!myIdentifier) {\n throw new Error(\"Identifier for participant not found\");\n }\n\n // Verify key package min_signers matches\n if (keyPackage.minSigners !== receiveState.minSigners) {\n throw new Error(\n `Key package min_signers ${keyPackage.minSigners} does not match session ${receiveState.minSigners}`,\n );\n }\n\n // Verify enough commitments\n if (commitmentsByXid.size < receiveState.minSigners) {\n throw new Error(\n `signRound2 request contained ${commitmentsByXid.size} commitments but requires at least ${receiveState.minSigners} signers`,\n );\n }\n\n // Build signing commitments with identifiers\n const signingCommitments = commitmentsWithIdentifiers(commitmentsByXid, xidToIdentifier);\n\n // Create signing package\n const signingPackage = createSigningPackage(signingCommitments, targetDigest.data());\n\n // Generate signature share using FROST round 2\n const signatureShare = signingRound2(signingPackage, commitState.signingNonces, keyPackage);\n\n // Build response body\n const responseBody = buildResponseBody(sessionId, signatureShare, finalizeArid);\n\n // Build sealed response\n // eslint-disable-next-line @typescript-eslint/no-require-imports, no-undef\n const { SealedResponse: SealedResponseClass } = require(\"@bcts/gstp\") as {\n SealedResponse: {\n newSuccess: (\n requestId: ARID,\n sender: XIDDocument,\n ) => {\n withResult: (result: Envelope) => {\n withPeerContinuation: (continuation: unknown) => {\n toEnvelope: (\n expiry: CborDate | undefined,\n signerPrivateKeys: unknown,\n recipient: XIDDocument | undefined,\n ) => Envelope;\n };\n toEnvelope: (\n expiry: CborDate | undefined,\n signerPrivateKeys: unknown,\n recipient: XIDDocument | undefined,\n ) => Envelope;\n };\n };\n };\n };\n\n const sealedResponse = SealedResponseClass.newSuccess(\n sealedRequest.id(),\n ownerXidDocument,\n ).withResult(responseBody);\n\n // Preview mode - print unsealed response\n if (options.preview === true) {\n const unsealed = sealedResponse.toEnvelope(undefined, signerPrivateKeys, undefined);\n console.log(unsealed.urString());\n return {\n listeningArid: finalizeArid.urString(),\n };\n }\n\n // Get coordinator XID document for encryption\n let coordinatorDoc: XIDDocument;\n if (expectedCoordinator.urString() === owner.xid().urString()) {\n coordinatorDoc = ownerXidDocument;\n } else {\n const coordinatorRecord = registry.participant(expectedCoordinator);\n if (!coordinatorRecord) {\n throw new Error(`Coordinator ${expectedCoordinator.urString()} not found in registry`);\n }\n coordinatorDoc = coordinatorRecord.xidDocument();\n }\n\n // Create response envelope with expiry\n const expiry = CborDate.withDurationFromNow(60 * 60); // 1 hour\n const responseEnvelope = sealedResponse.toEnvelope(expiry, signerPrivateKeys, coordinatorDoc);\n\n // Send response\n await putWithIndicator(\n client,\n responseArid,\n responseEnvelope,\n \"Signature Share\",\n options.verbose ?? false,\n );\n\n // Persist share state\n persistShareState(\n registryPath,\n groupId,\n sessionId,\n responseArid,\n finalizeArid,\n signatureShare,\n commitmentsByXid,\n );\n\n // Update registry with finalize listening ARID\n const groupRecordMutable = registry.group(groupId);\n if (groupRecordMutable) {\n groupRecordMutable.setListeningAtArid(finalizeArid);\n registry.save(registryPath);\n }\n\n if (options.verbose === true) {\n console.error(`Posted signature share to ${responseArid.urString()}`);\n }\n\n return {\n listeningArid: finalizeArid.urString(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAS,iBAAiB,cAAsB,WAAiB,WAAgC;CAC/F,MAAM,OAAO,KAAK,QAAQ,YAAY;CACtC,MAAM,gBAAgB,KAAK,KAAK,MAAM,aAAa;CAGnD,IAAI;CAEJ,IAAI,WACF,YAAY,CAAC,CAAC,WAAW,KAAK,KAAK,eAAe,UAAU,IAAI,CAAC,CAAC,CAAC;MAC9D;EACL,YAAY,CAAC;EACb,IAAI,GAAG,WAAW,aAAa;QACxB,MAAM,SAAS,GAAG,YAAY,eAAe,EAAE,eAAe,KAAK,CAAC,GACvE,IAAI,MAAM,YAAY,KAAK,MAAM,KAAK,WAAW,MAAM,eAAe,KAAK,MAAM,IAAI,GAAG;IACtF,MAAM,UAAUA,KAAU,QAAQ,MAAM,IAAI;IAC5C,UAAU,KAAK,CAAC,SAAS,KAAK,KAAK,eAAe,MAAM,IAAI,CAAC,CAAC;GAChE;;CAGN;CAEA,MAAM,aAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,SAAS,aAAa,WAAW;EAC3C,MAAM,YAAY,KAAK,KAAK,UAAU,WAAW,UAAU,IAAI,GAAG,mBAAmB;EACrF,IAAI,GAAG,WAAW,SAAS,GACzB,WAAW,KAAK,CAAC,SAAS,SAAS,CAAC;CAExC;CAEA,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,MACR,yFACF;CAEF,IAAI,WAAW,SAAS,GACtB,MAAM,IAAI,MAAM,mEAAmE;CAGrF,MAAM,CAAC,SAAS,aAAa,WAAW;CACxC,MAAM,MAAM,KAAK,MAAM,GAAG,aAAa,WAAW,OAAO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ACf,mBACA,QAAQ,WAAW,KACrB;CAGA,kBACE,cACA,SACA,WACA,cACA,cACA,gBACA,gBACF;CAGA,MAAM,qBAAqB,SAAS,MAAM,OAAO;CACjD,IAAI,oBAAoB;EACtB,mBAAmB,mBAAmB,YAAY;EAClD,SAAS,KAAK,YAAY;CAC5B;CAEA,IAAI,QAAQ,YAAY,MACtB,QAAQ,MAAM,6BAA6B,aAAa,SAAS,GAAG;CAGtE,OAAO,EACL,eAAe,aAAa,SAAS,EACvC;AACF"}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-z9aeyW2b.mjs";
|
|
2
|
+
import { n as compareXidBytes } from "./proposed-participant-Detb823_.mjs";
|
|
3
|
+
import { Registry, resolveRegistryPath } from "./registry/index.mjs";
|
|
4
|
+
import { c as parseAridUr, n as isVerbose, t as groupStateDir } from "./common-Cf1UvJaP.mjs";
|
|
5
|
+
import { n as putWithIndicator, t as getWithIndicator } from "./busy-BlU8_pS2.mjs";
|
|
6
|
+
import { i as createStorageClient } from "./registry-DGjs4qDK.mjs";
|
|
7
|
+
import { bytesToHex, dkgPart2, hexToBytes, identifierFromU16, identifierToHex, serializeDkgRound2Package } from "./frost/index.mjs";
|
|
8
|
+
import { ARID, JSON as JSON$1, XID } from "@bcts/components";
|
|
9
|
+
import { CborDate } from "@bcts/dcbor";
|
|
10
|
+
import { Envelope, Function } from "@bcts/envelope";
|
|
11
|
+
import { SealedRequest, SealedResponse } from "@bcts/gstp";
|
|
12
|
+
import * as fs from "node:fs";
|
|
13
|
+
import * as path from "node:path";
|
|
14
|
+
import { Ed25519Sha512, serde } from "@frosts/ed25519";
|
|
15
|
+
import { CoefficientCommitment, VerifiableSecretSharingCommitment, round1 } from "@frosts/core";
|
|
16
|
+
//#region src/cmd/dkg/participant/round2.ts
|
|
17
|
+
/**
|
|
18
|
+
* Copyright © 2023-2026 Blockchain Commons, LLC
|
|
19
|
+
* Copyright © 2025-2026 Parity Technologies
|
|
20
|
+
*
|
|
21
|
+
*
|
|
22
|
+
* DKG participant round 2 command.
|
|
23
|
+
*
|
|
24
|
+
* Port of cmd/dkg/participant/round2.rs from frost-hubert-rust.
|
|
25
|
+
*
|
|
26
|
+
* @module
|
|
27
|
+
*/
|
|
28
|
+
var round2_exports = /* @__PURE__ */ __exportAll({ round2: () => round2$1 });
|
|
29
|
+
/**
|
|
30
|
+
* Load persisted round 1 state from disk.
|
|
31
|
+
*
|
|
32
|
+
* Port of round1_secret loading from cmd/dkg/participant/round2.rs lines 86-97.
|
|
33
|
+
*/
|
|
34
|
+
function loadRound1State(registryPath, groupId) {
|
|
35
|
+
const packagesDir = groupStateDir(registryPath, groupId.hex());
|
|
36
|
+
const round1SecretPath = path.join(packagesDir, "round1_secret.json");
|
|
37
|
+
if (!fs.existsSync(round1SecretPath)) throw new Error(`Round 1 secret not found at ${round1SecretPath}. Did you respond to the invite?`);
|
|
38
|
+
const secretJson = JSON.parse(fs.readFileSync(round1SecretPath, "utf-8"));
|
|
39
|
+
const coefficients = secretJson.coefficients.map((hex) => Ed25519Sha512.deserializeScalar(hexToBytes(hex)));
|
|
40
|
+
const commitment = new VerifiableSecretSharingCommitment(Ed25519Sha512, secretJson.commitment.map((hex) => CoefficientCommitment.deserialize(Ed25519Sha512, hexToBytes(hex))));
|
|
41
|
+
const idBytes = hexToBytes(secretJson.identifier);
|
|
42
|
+
let identifierU16 = 1;
|
|
43
|
+
if (idBytes.length >= 2) identifierU16 = idBytes[0] | idBytes[1] << 8;
|
|
44
|
+
if (identifierU16 === 0) identifierU16 = 1;
|
|
45
|
+
const parsedIdentifier = identifierFromU16(identifierU16);
|
|
46
|
+
const secretPackage = new round1.SecretPackage(Ed25519Sha512, parsedIdentifier, coefficients, commitment, secretJson.min_signers, secretJson.max_signers);
|
|
47
|
+
const round1PackagePath = path.join(packagesDir, "round1_package.json");
|
|
48
|
+
const packageJson = JSON.parse(fs.readFileSync(round1PackagePath, "utf-8"));
|
|
49
|
+
return {
|
|
50
|
+
secretPackage,
|
|
51
|
+
ourRound1Package: serde.round1PackageFromJson(packageJson)
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Validate the round 2 request from the coordinator.
|
|
56
|
+
*
|
|
57
|
+
* Port of request validation from cmd/dkg/participant/round2.rs lines 118-158.
|
|
58
|
+
*/
|
|
59
|
+
function validateRound2Request(sealedRequest, groupId, expectedCoordinator) {
|
|
60
|
+
if (!sealedRequest.function().equals(Function.fromString("dkgRound2"))) throw new Error(`Unexpected request function: ${sealedRequest.function().toString()}`);
|
|
61
|
+
if (sealedRequest.sender().xid().urString() !== expectedCoordinator.urString()) throw new Error(`Unexpected request sender: ${sealedRequest.sender().xid().urString()} (expected coordinator ${expectedCoordinator.urString()})`);
|
|
62
|
+
const requestGroupIdEnvelope = sealedRequest.objectForParameter("group");
|
|
63
|
+
if (requestGroupIdEnvelope === void 0) throw new Error("Request missing group parameter");
|
|
64
|
+
const requestGroupId = requestGroupIdEnvelope.extractSubject((cbor) => ARID.fromTaggedCbor(cbor));
|
|
65
|
+
if (requestGroupId.urString() !== groupId.urString()) throw new Error(`Request group ID ${requestGroupId.urString()} does not match expected ${groupId.urString()}`);
|
|
66
|
+
const responseAridEnvelope = sealedRequest.objectForParameter("responseArid");
|
|
67
|
+
if (responseAridEnvelope === void 0) throw new Error("Request missing responseArid parameter");
|
|
68
|
+
return responseAridEnvelope.extractSubject((cbor) => ARID.fromTaggedCbor(cbor));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Extract round 1 packages from the request and convert to Map<Identifier, Package>.
|
|
72
|
+
*
|
|
73
|
+
* Port of `extract_round1_packages()` from cmd/dkg/participant/round2.rs lines 291-366.
|
|
74
|
+
*/
|
|
75
|
+
function extractRound1Packages(request, groupRecord, ownerXid) {
|
|
76
|
+
const sortedXids = groupRecord.participants().map((p) => p.xid());
|
|
77
|
+
const ownerUrString = ownerXid.urString();
|
|
78
|
+
if (!sortedXids.some((xid) => xid.urString() === ownerUrString)) sortedXids.push(ownerXid);
|
|
79
|
+
sortedXids.sort((a, b) => compareXidBytes(a.toData(), b.toData()));
|
|
80
|
+
const deduped = [];
|
|
81
|
+
for (const xid of sortedXids) if (deduped.length === 0 || deduped[deduped.length - 1].urString() !== xid.urString()) deduped.push(xid);
|
|
82
|
+
const xidToIdentifier = /* @__PURE__ */ new Map();
|
|
83
|
+
for (let i = 0; i < deduped.length; i++) {
|
|
84
|
+
const identifier = identifierFromU16(i + 1);
|
|
85
|
+
xidToIdentifier.set(deduped[i].urString(), identifier);
|
|
86
|
+
}
|
|
87
|
+
const myXidStr = ownerXid.urString();
|
|
88
|
+
const packages = /* @__PURE__ */ new Map();
|
|
89
|
+
const packagesByXid = [];
|
|
90
|
+
const packageEnvelopes = request.objectsForParameter("round1Package");
|
|
91
|
+
for (const packageEnvelope of packageEnvelopes) {
|
|
92
|
+
const participantEnvelope = packageEnvelope.objectForPredicate("participant");
|
|
93
|
+
if (participantEnvelope === void 0) throw new Error("round1Package missing participant predicate");
|
|
94
|
+
const participantXid = participantEnvelope.extractSubject((cbor) => XID.fromTaggedCbor(cbor));
|
|
95
|
+
if (participantXid.urString() === myXidStr) continue;
|
|
96
|
+
const packageJson = packageEnvelope.extractSubject((cbor) => JSON$1.fromTaggedCbor(cbor));
|
|
97
|
+
const packageData = JSON.parse(new TextDecoder().decode(packageJson.toData()));
|
|
98
|
+
const pkg = serde.round1PackageFromJson(packageData);
|
|
99
|
+
const identifier = xidToIdentifier.get(participantXid.urString());
|
|
100
|
+
if (identifier === void 0) throw new Error(`Unknown participant XID in round1Package: ${participantXid.urString()}`);
|
|
101
|
+
packages.set(identifier, pkg);
|
|
102
|
+
packagesByXid.push([participantXid, pkg]);
|
|
103
|
+
}
|
|
104
|
+
const expectedPackages = xidToIdentifier.size - 1;
|
|
105
|
+
if (packages.size !== expectedPackages) throw new Error(`Expected ${expectedPackages} Round 1 packages, found ${packages.size}`);
|
|
106
|
+
return [packages, packagesByXid];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Build the response body containing Round 2 packages.
|
|
110
|
+
*
|
|
111
|
+
* Port of `build_response_body()` from cmd/dkg/participant/round2.rs lines 373-425.
|
|
112
|
+
*/
|
|
113
|
+
function buildResponseBody(groupId, participantXid, responseArid, round2Packages, groupRecord) {
|
|
114
|
+
const sortedXids = groupRecord.participants().map((p) => p.xid());
|
|
115
|
+
const participantUrString = participantXid.urString();
|
|
116
|
+
if (!sortedXids.some((xid) => xid.urString() === participantUrString)) sortedXids.push(participantXid);
|
|
117
|
+
sortedXids.sort((a, b) => compareXidBytes(a.toData(), b.toData()));
|
|
118
|
+
const deduped = [];
|
|
119
|
+
for (const xid of sortedXids) if (deduped.length === 0 || deduped[deduped.length - 1].urString() !== xid.urString()) deduped.push(xid);
|
|
120
|
+
const identifierToXid = /* @__PURE__ */ new Map();
|
|
121
|
+
for (let i = 0; i < deduped.length; i++) {
|
|
122
|
+
const identifier = identifierFromU16(i + 1);
|
|
123
|
+
identifierToXid.set(identifierToHex(identifier), deduped[i]);
|
|
124
|
+
}
|
|
125
|
+
let envelope = Envelope.unit().addType("dkgRound2Response").addAssertion("group", groupId).addAssertion("participant", participantXid).addAssertion("response_arid", responseArid);
|
|
126
|
+
for (const [identifier, pkg] of round2Packages) {
|
|
127
|
+
const idHex = identifierToHex(identifier);
|
|
128
|
+
const recipientXid = identifierToXid.get(idHex);
|
|
129
|
+
if (recipientXid === void 0) throw new Error("Unknown identifier in round2_packages");
|
|
130
|
+
const serialized = serializeDkgRound2Package(pkg);
|
|
131
|
+
const jsonStr = JSON.stringify(serialized);
|
|
132
|
+
const jsonBytes = new TextEncoder().encode(jsonStr);
|
|
133
|
+
const jsonWrapper = JSON$1.fromData(jsonBytes);
|
|
134
|
+
const packageEnvelope = Envelope.new(jsonWrapper).addAssertion("recipient", recipientXid);
|
|
135
|
+
envelope = envelope.addAssertion("round2Package", packageEnvelope);
|
|
136
|
+
}
|
|
137
|
+
return envelope;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Serialize round 2 secret package to JSON format for persistence.
|
|
141
|
+
*
|
|
142
|
+
* Mirrors the on-disk shape produced by Rust
|
|
143
|
+
* `serde_json::to_vec_pretty(&frost::keys::dkg::round2::SecretPackage)`
|
|
144
|
+
* (see `frost-rust/frost-core/src/keys/dkg.rs:269-287`):
|
|
145
|
+
*
|
|
146
|
+
* ```json
|
|
147
|
+
* {
|
|
148
|
+
* "identifier": "<lowercase hex scalar>",
|
|
149
|
+
* "commitment": ["<hex>", "<hex>", ...],
|
|
150
|
+
* "secret_share": "<hex>",
|
|
151
|
+
* "min_signers": <u16>,
|
|
152
|
+
* "max_signers": <u16>
|
|
153
|
+
* }
|
|
154
|
+
* ```
|
|
155
|
+
*
|
|
156
|
+
* `frost::keys::dkg::round2::SecretPackage` is
|
|
157
|
+
* `#[serde(deny_unknown_fields)]`. The earlier port emitted
|
|
158
|
+
* camelCase keys (`secretShare`, `minSigners`, `maxSigners`), a
|
|
159
|
+
* nested `commitment.coefficients` shape, and a numeric
|
|
160
|
+
* `identifier` — all of which Rust's standard derive would
|
|
161
|
+
* reject and which had no chance of round-tripping with Rust.
|
|
162
|
+
*
|
|
163
|
+
* `participantIndex` is unused now that the identifier comes
|
|
164
|
+
* directly from `secret.identifier.serialize()`; we keep it in the
|
|
165
|
+
* signature for source-level parity with the call sites.
|
|
166
|
+
*/
|
|
167
|
+
function serializeRound2SecretPackage(secret, _participantIndex) {
|
|
168
|
+
const commitmentCoefficients = secret.commitment.serialize().map((c) => bytesToHex(c));
|
|
169
|
+
const secretShare = bytesToHex(Ed25519Sha512.serializeScalar(secret.secretShare()));
|
|
170
|
+
return {
|
|
171
|
+
identifier: bytesToHex(secret.identifier.serialize()),
|
|
172
|
+
commitment: commitmentCoefficients,
|
|
173
|
+
secret_share: secretShare,
|
|
174
|
+
min_signers: secret.minSigners,
|
|
175
|
+
max_signers: secret.maxSigners
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Persist round 2 state to disk.
|
|
180
|
+
*
|
|
181
|
+
* Port of round 2 secret persistence from cmd/dkg/participant/round2.rs lines 229-251.
|
|
182
|
+
*/
|
|
183
|
+
function persistRound2State(registryPath, groupId, round2Secret, round1PackagesByXid, participantIndex) {
|
|
184
|
+
const packagesDir = groupStateDir(registryPath, groupId.hex());
|
|
185
|
+
fs.mkdirSync(packagesDir, { recursive: true });
|
|
186
|
+
const round2SecretPath = path.join(packagesDir, "round2_secret.json");
|
|
187
|
+
const round2SecretJson = serializeRound2SecretPackage(round2Secret, participantIndex);
|
|
188
|
+
fs.writeFileSync(round2SecretPath, JSON.stringify(round2SecretJson, null, 2));
|
|
189
|
+
const round1PackagesPath = path.join(packagesDir, "collected_round1.json");
|
|
190
|
+
const round1Json = {};
|
|
191
|
+
for (const [xid, pkg] of round1PackagesByXid) {
|
|
192
|
+
const packageJson = serde.round1PackageToJson(pkg);
|
|
193
|
+
round1Json[xid.urString()] = packageJson;
|
|
194
|
+
}
|
|
195
|
+
fs.writeFileSync(round1PackagesPath, JSON.stringify(round1Json, null, 2));
|
|
196
|
+
return round2SecretPath;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Execute the DKG participant round 2 command.
|
|
200
|
+
*
|
|
201
|
+
* Responds to the Round 2 request from the coordinator, runs FROST DKG part2
|
|
202
|
+
* to generate Round 2 packages, and posts the response back.
|
|
203
|
+
*
|
|
204
|
+
* Port of `CommandArgs::exec()` from cmd/dkg/participant/round2.rs lines 55-288.
|
|
205
|
+
*/
|
|
206
|
+
async function round2$1(_client, options, cwd) {
|
|
207
|
+
if (options.storageSelection === void 0) throw new Error("Hubert storage is required for round2");
|
|
208
|
+
const registryPath = resolveRegistryPath(options.registryPath, cwd);
|
|
209
|
+
const registry = Registry.load(registryPath);
|
|
210
|
+
const owner = registry.owner();
|
|
211
|
+
if (owner === void 0) throw new Error("Registry owner is required");
|
|
212
|
+
const groupId = parseAridUr(options.groupId);
|
|
213
|
+
const groupRecord = registry.group(groupId);
|
|
214
|
+
if (groupRecord === void 0) throw new Error("Group not found in registry");
|
|
215
|
+
const listeningAtArid = groupRecord.listeningAtArid();
|
|
216
|
+
if (listeningAtArid === void 0) throw new Error("No listening ARID for this group. Did you respond to the invite?");
|
|
217
|
+
const round1State = loadRound1State(registryPath, groupId);
|
|
218
|
+
if (isVerbose() || options.verbose === true) console.error("Fetching Round 2 request from Hubert...");
|
|
219
|
+
const client = await createStorageClient(options.storageSelection);
|
|
220
|
+
const requestEnvelope = await getWithIndicator(client, listeningAtArid, "Round 2 request", options.timeoutSeconds, options.verbose ?? false);
|
|
221
|
+
if (requestEnvelope === null || requestEnvelope === void 0) throw new Error("Round 2 request not found in Hubert storage");
|
|
222
|
+
const ownerPrivateKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
223
|
+
if (ownerPrivateKeys === void 0) throw new Error("Owner XID document has no private keys");
|
|
224
|
+
const now = CborDate.now().datetime();
|
|
225
|
+
const sealedRequest = SealedRequest.tryFromEnvelope(requestEnvelope, void 0, now, ownerPrivateKeys);
|
|
226
|
+
const responseArid = validateRound2Request(sealedRequest, groupId, groupRecord.coordinator().xid());
|
|
227
|
+
const [round1Packages, round1PackagesByXid] = extractRound1Packages(sealedRequest, groupRecord, owner.xid());
|
|
228
|
+
if (isVerbose() || options.verbose === true) console.error(`Received ${round1Packages.size} Round 1 packages. Running DKG part2...`);
|
|
229
|
+
const nextResponseArid = ARID.new();
|
|
230
|
+
const round1PackagesHex = /* @__PURE__ */ new Map();
|
|
231
|
+
for (const [id, pkg] of round1Packages) round1PackagesHex.set(identifierToHex(id), pkg);
|
|
232
|
+
const [round2Secret, round2Packages] = dkgPart2(round1State.secretPackage, round1PackagesHex);
|
|
233
|
+
if (isVerbose() || options.verbose === true) console.error(`Generated ${round2Packages.size} Round 2 packages.`);
|
|
234
|
+
const round2PackagesById = /* @__PURE__ */ new Map();
|
|
235
|
+
for (const [idHex, pkg] of round2Packages) for (const [id] of round1Packages) if (identifierToHex(id) === idHex) {
|
|
236
|
+
round2PackagesById.set(id, pkg);
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
const responseBody = buildResponseBody(groupId, owner.xid(), nextResponseArid, round2PackagesById, groupRecord);
|
|
240
|
+
const signerPrivateKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
241
|
+
if (signerPrivateKeys === void 0) throw new Error("Owner XID document has no signing keys");
|
|
242
|
+
const coordinatorXid = groupRecord.coordinator().xid();
|
|
243
|
+
const coordinatorRecord = registry.participant(coordinatorXid);
|
|
244
|
+
let coordinatorDoc;
|
|
245
|
+
if (coordinatorRecord !== void 0) coordinatorDoc = coordinatorRecord.xidDocument();
|
|
246
|
+
else if (owner.xid().urString() === coordinatorXid.urString()) coordinatorDoc = owner.xidDocument();
|
|
247
|
+
else throw new Error(`Coordinator ${coordinatorXid.urString()} not found in registry`);
|
|
248
|
+
const peerContinuation = sealedRequest.peerContinuation();
|
|
249
|
+
let sealed = SealedResponse.newSuccess(sealedRequest.id(), owner.xidDocument()).withResult(responseBody);
|
|
250
|
+
if (peerContinuation !== void 0) sealed = sealed.withPeerContinuation(peerContinuation);
|
|
251
|
+
if (options.preview === true) {
|
|
252
|
+
const envelopeUr = sealed.toEnvelope(void 0, signerPrivateKeys, void 0).urString();
|
|
253
|
+
console.log(envelopeUr);
|
|
254
|
+
return {
|
|
255
|
+
listeningArid: nextResponseArid.urString(),
|
|
256
|
+
envelopeUr
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const sortedParticipantXids = groupRecord.participants().map((p) => p.xid());
|
|
260
|
+
const ownerXid = owner.xid();
|
|
261
|
+
const ownerXidStr = ownerXid.urString();
|
|
262
|
+
if (!sortedParticipantXids.some((x) => x.urString() === ownerXidStr)) sortedParticipantXids.push(ownerXid);
|
|
263
|
+
sortedParticipantXids.sort((a, b) => compareXidBytes(a.toData(), b.toData()));
|
|
264
|
+
const round2SecretPath = persistRound2State(registryPath, groupId, round2Secret, round1PackagesByXid, sortedParticipantXids.findIndex((x) => x.urString() === ownerXidStr) + 1);
|
|
265
|
+
await putWithIndicator(client, responseArid, sealed.toEnvelope(void 0, signerPrivateKeys, coordinatorDoc), "Round 2 Response", options.verbose ?? false);
|
|
266
|
+
const updatedGroupRecord = registry.group(groupId);
|
|
267
|
+
if (updatedGroupRecord !== void 0) {
|
|
268
|
+
const contributions = updatedGroupRecord.contributions();
|
|
269
|
+
contributions.round2Secret = round2SecretPath;
|
|
270
|
+
updatedGroupRecord.setContributions(contributions);
|
|
271
|
+
updatedGroupRecord.setListeningAtArid(nextResponseArid);
|
|
272
|
+
registry.save(registryPath);
|
|
273
|
+
}
|
|
274
|
+
if (isVerbose() || options.verbose === true) console.error(`Posted Round 2 response to ${responseArid.urString()}`);
|
|
275
|
+
return { listeningArid: nextResponseArid.urString() };
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
export { round2_exports as n, round2$1 as t };
|
|
279
|
+
|
|
280
|
+
//# sourceMappingURL=round2-mF6UlkT-.mjs.map
|