@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,208 @@
|
|
|
1
|
+
const require_chunk = require("./chunk-DakpK96I.cjs");
|
|
2
|
+
const require_proposed_participant = require("./proposed-participant-BvHNnpcZ.cjs");
|
|
3
|
+
const require_registry_index = require("./registry/index.cjs");
|
|
4
|
+
const require_common = require("./common-CnvAUC2b.cjs");
|
|
5
|
+
const require_busy = require("./busy-B_h0bNAJ.cjs");
|
|
6
|
+
const require_registry = require("./registry-CkIbA7nt.cjs");
|
|
7
|
+
const require_receive = require("./receive-BR-knnGv.cjs");
|
|
8
|
+
const require_frost_index = require("./frost/index.cjs");
|
|
9
|
+
let _bcts_components = require("@bcts/components");
|
|
10
|
+
let _bcts_dcbor = require("@bcts/dcbor");
|
|
11
|
+
let _bcts_envelope = require("@bcts/envelope");
|
|
12
|
+
let _bcts_gstp = require("@bcts/gstp");
|
|
13
|
+
let node_fs = require("node:fs");
|
|
14
|
+
node_fs = require_chunk.__toESM(node_fs, 1);
|
|
15
|
+
let node_path = require("node:path");
|
|
16
|
+
node_path = require_chunk.__toESM(node_path, 1);
|
|
17
|
+
let _frosts_ed25519 = require("@frosts/ed25519");
|
|
18
|
+
//#region src/cmd/dkg/participant/round1.ts
|
|
19
|
+
/**
|
|
20
|
+
* Copyright © 2023-2026 Blockchain Commons, LLC
|
|
21
|
+
* Copyright © 2025-2026 Parity Technologies
|
|
22
|
+
*
|
|
23
|
+
*
|
|
24
|
+
* DKG participant round 1 command.
|
|
25
|
+
*
|
|
26
|
+
* Port of cmd/dkg/participant/round1.rs from frost-hubert-rust.
|
|
27
|
+
*
|
|
28
|
+
* @module
|
|
29
|
+
*/
|
|
30
|
+
var round1_exports = /* @__PURE__ */ require_chunk.__exportAll({ round1: () => round1 });
|
|
31
|
+
/**
|
|
32
|
+
* Resolve an invite envelope from either storage (ARID) or direct UR.
|
|
33
|
+
*
|
|
34
|
+
* Port of `resolve_invite_envelope()` from cmd/dkg/participant/round1.rs lines 256-288.
|
|
35
|
+
*/
|
|
36
|
+
async function resolveInviteEnvelope(selection, invite, timeout) {
|
|
37
|
+
if (selection !== void 0) {
|
|
38
|
+
try {
|
|
39
|
+
const arid = require_common.parseAridUr(invite);
|
|
40
|
+
const envelope = await require_busy.getWithIndicator(await require_registry.createStorageClient(selection), arid, "Invite", timeout, false);
|
|
41
|
+
if (envelope === null || envelope === void 0) throw new Error("Invite not found in Hubert storage");
|
|
42
|
+
return envelope;
|
|
43
|
+
} catch (e) {
|
|
44
|
+
if (e instanceof Error && e.message.includes("Invite not found in Hubert storage")) throw e;
|
|
45
|
+
}
|
|
46
|
+
if (timeout !== void 0) throw new Error("--timeout is only valid when retrieving invites from Hubert");
|
|
47
|
+
return require_common.parseEnvelopeUr(invite);
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
require_common.parseAridUr(invite);
|
|
51
|
+
throw new Error("Hubert storage parameters are required to retrieve invites by ARID");
|
|
52
|
+
} catch (e) {
|
|
53
|
+
if (e instanceof Error && e.message.includes("Hubert storage parameters are required")) throw e;
|
|
54
|
+
}
|
|
55
|
+
return require_common.parseEnvelopeUr(invite);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Build the response body envelope.
|
|
59
|
+
*
|
|
60
|
+
* Port of `build_response_body()` from cmd/dkg/participant/round1.rs lines 290-308.
|
|
61
|
+
*/
|
|
62
|
+
function buildResponseBody(groupId, participant, responseArid, round1Package) {
|
|
63
|
+
let envelope = _bcts_envelope.Envelope.unit().addType("dkgRound1Response").addAssertion("group", groupId).addAssertion("participant", participant).addAssertion("response_arid", responseArid);
|
|
64
|
+
if (round1Package !== void 0) {
|
|
65
|
+
const packageJson = _frosts_ed25519.serde.round1PackageToJson(round1Package);
|
|
66
|
+
const jsonStr = globalThis.JSON.stringify(packageJson);
|
|
67
|
+
const jsonBytes = new TextEncoder().encode(jsonStr);
|
|
68
|
+
const jsonWrapper = _bcts_components.JSON.fromData(jsonBytes);
|
|
69
|
+
envelope = envelope.addAssertion("round1_package", jsonWrapper);
|
|
70
|
+
}
|
|
71
|
+
return envelope;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Serialize round 1 secret package to JSON-compatible format.
|
|
75
|
+
*
|
|
76
|
+
* The @frosts/ed25519 serde module doesn't provide a serializer for SecretPackage,
|
|
77
|
+
* so we manually serialize it here.
|
|
78
|
+
*/
|
|
79
|
+
function serializeRound1SecretPackage(secret) {
|
|
80
|
+
const serializedCoefficients = secret.coefficients().map((c) => require_frost_index.bytesToHex(_frosts_ed25519.Ed25519Sha512.serializeScalar(c)));
|
|
81
|
+
const commitmentCoefficients = secret.commitment.serialize().map((c) => require_frost_index.bytesToHex(c));
|
|
82
|
+
return {
|
|
83
|
+
identifier: require_frost_index.bytesToHex(secret.identifier.serialize()),
|
|
84
|
+
coefficients: serializedCoefficients,
|
|
85
|
+
commitment: commitmentCoefficients,
|
|
86
|
+
min_signers: secret.minSigners,
|
|
87
|
+
max_signers: secret.maxSigners
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Persist round 1 state to disk.
|
|
92
|
+
*
|
|
93
|
+
* Port of `persist_round1_state()` from cmd/dkg/participant/round1.rs lines 310-337.
|
|
94
|
+
*/
|
|
95
|
+
function persistRound1State(registryPath, groupId, round1Secret, round1Package) {
|
|
96
|
+
const dir = require_common.groupStateDir(registryPath, groupId.hex());
|
|
97
|
+
node_fs.mkdirSync(dir, { recursive: true });
|
|
98
|
+
const secretPath = node_path.join(dir, "round1_secret.json");
|
|
99
|
+
const packagePath = node_path.join(dir, "round1_package.json");
|
|
100
|
+
const secretJson = serializeRound1SecretPackage(round1Secret);
|
|
101
|
+
const packageJson = _frosts_ed25519.serde.round1PackageToJson(round1Package);
|
|
102
|
+
node_fs.writeFileSync(secretPath, globalThis.JSON.stringify(secretJson, null, 2));
|
|
103
|
+
node_fs.writeFileSync(packagePath, globalThis.JSON.stringify(packageJson, null, 2));
|
|
104
|
+
return new require_registry_index.ContributionPaths({
|
|
105
|
+
round1Secret: secretPath,
|
|
106
|
+
round1Package: packagePath,
|
|
107
|
+
round2Secret: void 0,
|
|
108
|
+
keyPackage: void 0
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Execute the DKG participant round 1 command.
|
|
113
|
+
*
|
|
114
|
+
* Responds to the DKG invite with commitment packages.
|
|
115
|
+
*
|
|
116
|
+
* Port of `CommandArgs::exec()` from cmd/dkg/participant/round1.rs lines 66-254.
|
|
117
|
+
*/
|
|
118
|
+
async function round1(_client, options, cwd) {
|
|
119
|
+
if (options.storageSelection === void 0 && options.timeoutSeconds !== void 0) throw new Error("--timeout requires Hubert storage parameters");
|
|
120
|
+
if (options.storageSelection !== void 0 && options.preview === true) throw new Error("--preview cannot be used with Hubert storage options");
|
|
121
|
+
const registryPath = require_registry_index.resolveRegistryPath(options.registryPath, cwd);
|
|
122
|
+
const registry = require_registry_index.Registry.load(registryPath);
|
|
123
|
+
const owner = registry.owner();
|
|
124
|
+
if (!owner) throw new Error("Registry owner with private keys is required");
|
|
125
|
+
let expectedSender;
|
|
126
|
+
if (options.sender !== void 0) expectedSender = require_common.resolveSender(registry, options.sender);
|
|
127
|
+
const nextResponseArid = options.responseArid !== void 0 ? require_common.parseAridUr(options.responseArid) : _bcts_components.ARID.new();
|
|
128
|
+
const details = require_receive.decodeInviteDetails(await resolveInviteEnvelope(options.storageSelection, options.invite, options.timeoutSeconds), _bcts_dcbor.CborDate.now().datetime(), registry, owner.xidDocument(), expectedSender);
|
|
129
|
+
const sortedParticipants = [...details.participants].sort((a, b) => require_proposed_participant.compareXidBytes(a.xid().toData(), b.xid().toData()));
|
|
130
|
+
const ownerIndex = sortedParticipants.findIndex((doc) => doc.xid().urString() === owner.xid().urString());
|
|
131
|
+
if (ownerIndex === -1) throw new Error("Invite does not include the registry owner");
|
|
132
|
+
const identifierIndex = ownerIndex + 1;
|
|
133
|
+
if (identifierIndex > 65535) throw new Error("Too many participants for identifiers");
|
|
134
|
+
const identifier = require_frost_index.identifierFromU16(identifierIndex);
|
|
135
|
+
const total = sortedParticipants.length;
|
|
136
|
+
if (total > 65535) throw new Error("Too many participants for FROST identifiers");
|
|
137
|
+
const minSigners = details.invitation.minSigners();
|
|
138
|
+
if (minSigners > 65535) throw new Error("min_signers does not fit into identifier space");
|
|
139
|
+
const groupParticipants = require_common.buildGroupParticipants(registry, owner, sortedParticipants);
|
|
140
|
+
const coordinator = require_common.groupParticipantFromRegistry(registry, owner, details.invitation.sender());
|
|
141
|
+
const isPosting = options.storageSelection !== void 0;
|
|
142
|
+
let responseBody;
|
|
143
|
+
let contributions;
|
|
144
|
+
if (options.rejectReason === void 0 && isPosting) {
|
|
145
|
+
const [round1Secret, round1Package] = require_frost_index.dkgPart1(identifier, total, minSigners, require_frost_index.createRng());
|
|
146
|
+
contributions = persistRound1State(registryPath, details.invitation.groupId(), round1Secret, round1Package);
|
|
147
|
+
responseBody = buildResponseBody(details.invitation.groupId(), owner.xid(), nextResponseArid, round1Package);
|
|
148
|
+
const groupRecord = new require_registry_index.GroupRecord(details.invitation.charter(), details.invitation.minSigners(), coordinator, groupParticipants);
|
|
149
|
+
groupRecord.setContributions(contributions);
|
|
150
|
+
groupRecord.setListeningAtArid(nextResponseArid);
|
|
151
|
+
registry.recordGroup(details.invitation.groupId(), groupRecord);
|
|
152
|
+
registry.save(registryPath);
|
|
153
|
+
} else if (options.rejectReason === void 0) {
|
|
154
|
+
const [, round1Package] = require_frost_index.dkgPart1(identifier, total, minSigners, require_frost_index.createRng());
|
|
155
|
+
responseBody = buildResponseBody(details.invitation.groupId(), owner.xid(), nextResponseArid, round1Package);
|
|
156
|
+
} else responseBody = buildResponseBody(details.invitation.groupId(), owner.xid(), nextResponseArid, void 0);
|
|
157
|
+
const signerPrivateKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
158
|
+
if (signerPrivateKeys === void 0) throw new Error("Owner XID document has no signing keys");
|
|
159
|
+
let sealed;
|
|
160
|
+
if (options.rejectReason !== void 0) {
|
|
161
|
+
const errorBody = _bcts_envelope.Envelope.new("dkgInviteReject").addAssertion("group", details.invitation.groupId()).addAssertion("response_arid", nextResponseArid).addAssertion("reason", options.rejectReason);
|
|
162
|
+
sealed = _bcts_gstp.SealedResponse.newFailure(details.invitation.requestId(), owner.xidDocument()).withError(errorBody).withState(nextResponseArid);
|
|
163
|
+
} else sealed = _bcts_gstp.SealedResponse.newSuccess(details.invitation.requestId(), owner.xidDocument()).withResult(responseBody).withState(nextResponseArid);
|
|
164
|
+
const peerContinuation = details.invitation.peerContinuation();
|
|
165
|
+
if (peerContinuation !== void 0) sealed = sealed.withPeerContinuation(peerContinuation);
|
|
166
|
+
if (options.storageSelection !== void 0) {
|
|
167
|
+
const responseEnvelope = sealed.toEnvelope(details.invitation.validUntil(), signerPrivateKeys, details.invitation.sender());
|
|
168
|
+
const responseTarget = details.invitation.responseArid();
|
|
169
|
+
await require_busy.putWithIndicator(await require_registry.createStorageClient(options.storageSelection), responseTarget, responseEnvelope, "Round 1 Response", options.verbose ?? false);
|
|
170
|
+
if (options.verbose === true) {
|
|
171
|
+
console.log(`Sent round 1 response`);
|
|
172
|
+
console.log(`Listening at: ${nextResponseArid.urString()}`);
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
accepted: options.rejectReason === void 0,
|
|
176
|
+
listeningArid: nextResponseArid.urString()
|
|
177
|
+
};
|
|
178
|
+
} else if (options.preview === true) {
|
|
179
|
+
const envelopeUr = sealed.toEnvelope(void 0, signerPrivateKeys, void 0).urString();
|
|
180
|
+
console.log(envelopeUr);
|
|
181
|
+
return {
|
|
182
|
+
accepted: options.rejectReason === void 0,
|
|
183
|
+
envelopeUr
|
|
184
|
+
};
|
|
185
|
+
} else {
|
|
186
|
+
const envelopeUr = sealed.toEnvelope(details.invitation.validUntil(), signerPrivateKeys, details.invitation.sender()).urString();
|
|
187
|
+
console.log(envelopeUr);
|
|
188
|
+
return {
|
|
189
|
+
accepted: options.rejectReason === void 0,
|
|
190
|
+
envelopeUr
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
Object.defineProperty(exports, "round1", {
|
|
196
|
+
enumerable: true,
|
|
197
|
+
get: function() {
|
|
198
|
+
return round1;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
Object.defineProperty(exports, "round1_exports", {
|
|
202
|
+
enumerable: true,
|
|
203
|
+
get: function() {
|
|
204
|
+
return round1_exports;
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
//# sourceMappingURL=round1-CXkXoVQU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"round1-CXkXoVQU.cjs","names":["parseAridUr","getWithIndicator","createStorageClient","parseEnvelopeUr","Envelope","serde","JSONWrapper","bytesToHex","Ed25519Sha512","groupStateDir","path","ContributionPaths","resolveRegistryPath","Registry","resolveSender","ARID","decodeInviteDetails","CborDate","compareXidBytes","identifierFromU16","buildGroupParticipants","groupParticipantFromRegistry","dkgPart1","createRng","GroupRecord","SealedResponse","putWithIndicator"],"sources":["../src/cmd/dkg/participant/round1.ts"],"sourcesContent":["/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * DKG participant round 1 command.\n *\n * Port of cmd/dkg/participant/round1.rs from frost-hubert-rust.\n *\n * @module\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { ARID, JSON as JSONWrapper, type XID } from \"@bcts/components\";\nimport { compareXidBytes } from \"../../../dkg/proposed-participant.js\";\nimport { Envelope } from \"@bcts/envelope\";\nimport { SealedResponse } from \"@bcts/gstp\";\nimport type { XIDDocument } from \"@bcts/xid\";\n\nimport {\n ContributionPaths,\n GroupRecord,\n Registry,\n resolveRegistryPath,\n} from \"../../../registry/index.js\";\nimport { getWithIndicator, putWithIndicator } from \"../../busy.js\";\nimport { createStorageClient, type StorageClient, type StorageSelection } from \"../../storage.js\";\nimport { groupStateDir } from \"../../common.js\";\nimport {\n buildGroupParticipants,\n groupParticipantFromRegistry,\n parseAridUr,\n parseEnvelopeUr,\n resolveSender,\n} from \"../common.js\";\nimport {\n dkgPart1,\n identifierFromU16,\n createRng,\n bytesToHex,\n type DkgRound1Package,\n type DkgRound1SecretPackage,\n} from \"../../../frost/index.js\";\nimport { Ed25519Sha512, serde } from \"@frosts/ed25519\";\nimport { decodeInviteDetails } from \"./receive.js\";\nimport { CborDate } from \"@bcts/dcbor\";\n\n/**\n * Options for the DKG round1 command.\n */\nexport interface DkgRound1Options {\n registryPath?: string;\n timeoutSeconds?: number;\n responseArid?: string;\n preview?: boolean;\n rejectReason?: string;\n sender?: string;\n invite: string;\n storageSelection?: StorageSelection;\n verbose?: boolean;\n}\n\n/**\n * Result of the DKG round1 command.\n */\nexport interface DkgRound1Result {\n accepted: boolean;\n listeningArid?: string;\n envelopeUr?: string;\n}\n\n/**\n * Resolve an invite envelope from either storage (ARID) or direct UR.\n *\n * Port of `resolve_invite_envelope()` from cmd/dkg/participant/round1.rs lines 256-288.\n */\nasync function resolveInviteEnvelope(\n selection: StorageSelection | undefined,\n invite: string,\n timeout?: number,\n): Promise<Envelope> {\n if (selection !== undefined) {\n // Try to parse as ARID\n try {\n const arid = parseAridUr(invite);\n const client = await createStorageClient(selection);\n const envelope = await getWithIndicator(client, arid, \"Invite\", timeout, false);\n if (envelope === null || envelope === undefined) {\n throw new Error(\"Invite not found in Hubert storage\");\n }\n return envelope;\n } catch (e) {\n // Not an ARID, fall through to envelope parsing\n if (e instanceof Error && e.message.includes(\"Invite not found in Hubert storage\")) {\n throw e;\n }\n }\n\n if (timeout !== undefined) {\n throw new Error(\"--timeout is only valid when retrieving invites from Hubert\");\n }\n\n return parseEnvelopeUr(invite);\n }\n\n // No storage selection\n try {\n parseAridUr(invite);\n throw new Error(\"Hubert storage parameters are required to retrieve invites by ARID\");\n } catch (e) {\n // Not an ARID, parse as envelope\n if (e instanceof Error && e.message.includes(\"Hubert storage parameters are required\")) {\n throw e;\n }\n }\n\n return parseEnvelopeUr(invite);\n}\n\n/**\n * Build the response body envelope.\n *\n * Port of `build_response_body()` from cmd/dkg/participant/round1.rs lines 290-308.\n */\nfunction buildResponseBody(\n groupId: ARID,\n participant: XID,\n responseArid: ARID,\n round1Package: DkgRound1Package | undefined,\n): Envelope {\n let envelope = Envelope.unit()\n .addType(\"dkgRound1Response\")\n .addAssertion(\"group\", groupId)\n .addAssertion(\"participant\", participant)\n .addAssertion(\"response_arid\", responseArid);\n\n if (round1Package !== undefined) {\n // Serialize the package to JSON and wrap as CBOR JSON\n const packageJson = serde.round1PackageToJson(round1Package);\n const jsonStr = globalThis.JSON.stringify(packageJson);\n const jsonBytes = new TextEncoder().encode(jsonStr);\n const jsonWrapper = JSONWrapper.fromData(jsonBytes);\n // Pass the JSONWrapper directly - it implements CborTaggedEncodable\n envelope = envelope.addAssertion(\"round1_package\", jsonWrapper);\n }\n\n return envelope;\n}\n\n/**\n * Serialize round 1 secret package to JSON-compatible format.\n *\n * The @frosts/ed25519 serde module doesn't provide a serializer for SecretPackage,\n * so we manually serialize it here.\n */\nfunction serializeRound1SecretPackage(secret: DkgRound1SecretPackage): Record<string, unknown> {\n // Mirrors the on-disk shape produced by Rust\n // `serde_json::to_vec_pretty(&frost::keys::dkg::round1::SecretPackage)`\n // (see `frost-rust/frost-core/src/keys/dkg.rs:120-139`):\n //\n // {\n // \"identifier\": \"<lowercase hex scalar>\",\n // \"coefficients\": [\"<hex>\", \"<hex>\", ...],\n // \"commitment\": [\"<hex>\", \"<hex>\", ...],\n // \"min_signers\": <u16>,\n // \"max_signers\": <u16>\n // }\n //\n // `frost::keys::dkg::round1::SecretPackage` is `#[serde(deny_unknown_fields)]`\n // and has no `header` field (the secret package is private to the\n // participant). The earlier port emitted a top-level `header` which\n // would fail `deny_unknown_fields` validation if Rust ever loaded\n // the file.\n //\n // `Identifier`/`SerializableScalar` serialize via\n // `serdect::array::serialize_hex_lower_or_bin` → lowercase hex for\n // JSON, which `bytesToHex` produces.\n const coefficients = secret.coefficients();\n const serializedCoefficients = coefficients.map((c: unknown) =>\n bytesToHex(\n Ed25519Sha512.serializeScalar(c as Parameters<typeof Ed25519Sha512.serializeScalar>[0]),\n ),\n );\n\n const commitment = secret.commitment;\n const commitmentCoefficients = commitment.serialize().map((c: Uint8Array) => bytesToHex(c));\n\n return {\n identifier: bytesToHex(secret.identifier.serialize()),\n coefficients: serializedCoefficients,\n commitment: commitmentCoefficients,\n min_signers: secret.minSigners,\n max_signers: secret.maxSigners,\n };\n}\n\n/**\n * Persist round 1 state to disk.\n *\n * Port of `persist_round1_state()` from cmd/dkg/participant/round1.rs lines 310-337.\n */\nfunction persistRound1State(\n registryPath: string,\n groupId: ARID,\n round1Secret: DkgRound1SecretPackage,\n round1Package: DkgRound1Package,\n): ContributionPaths {\n const dir = groupStateDir(registryPath, groupId.hex());\n fs.mkdirSync(dir, { recursive: true });\n\n const secretPath = path.join(dir, \"round1_secret.json\");\n const packagePath = path.join(dir, \"round1_package.json\");\n\n // Serialize the secret package manually since serde doesn't provide it\n const secretJson = serializeRound1SecretPackage(round1Secret);\n // Serialize the public package using the standard serde function\n const packageJson = serde.round1PackageToJson(round1Package);\n\n fs.writeFileSync(secretPath, globalThis.JSON.stringify(secretJson, null, 2));\n fs.writeFileSync(packagePath, globalThis.JSON.stringify(packageJson, null, 2));\n\n return new ContributionPaths({\n round1Secret: secretPath,\n round1Package: packagePath,\n round2Secret: undefined,\n keyPackage: undefined,\n });\n}\n\n/**\n * Execute the DKG participant round 1 command.\n *\n * Responds to the DKG invite with commitment packages.\n *\n * Port of `CommandArgs::exec()` from cmd/dkg/participant/round1.rs lines 66-254.\n */\nexport async function round1(\n _client: StorageClient | undefined,\n options: DkgRound1Options,\n cwd: string,\n): Promise<DkgRound1Result> {\n // Validate options\n if (options.storageSelection === undefined && options.timeoutSeconds !== undefined) {\n throw new Error(\"--timeout requires Hubert storage parameters\");\n }\n if (options.storageSelection !== undefined && options.preview === true) {\n throw new Error(\"--preview cannot be used with Hubert storage options\");\n }\n\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 with private keys is required\");\n }\n\n // Resolve expected sender if provided. Uses the shared helper from\n // `cmd/dkg/common.ts` (mirrors Rust `resolve_sender`); the\n // duplicated inline implementation that this previously called has\n // been removed.\n let expectedSender: XIDDocument | undefined;\n if (options.sender !== undefined) {\n expectedSender = resolveSender(registry, options.sender);\n }\n\n const nextResponseArid =\n options.responseArid !== undefined ? parseAridUr(options.responseArid) : ARID.new();\n\n // Resolve the invite envelope\n const inviteEnvelope = await resolveInviteEnvelope(\n options.storageSelection,\n options.invite,\n options.timeoutSeconds,\n );\n\n // Decode the invite details\n const now = CborDate.now().datetime();\n const details = decodeInviteDetails(\n inviteEnvelope,\n now,\n registry,\n owner.xidDocument(),\n expectedSender,\n );\n\n // Sort participants by XID byte order (mirrors Rust `XID::cmp` —\n // raw 32-byte lex compare). The earlier port used\n // `xid.urString().localeCompare(...)`, which differs from byte\n // order when bytes ≥ 0x80 are present and is locale-aware,\n // producing different FROST identifier assignments and therefore\n // different secret shares than Rust.\n const sortedParticipants = [...details.participants].sort((a, b) =>\n compareXidBytes(a.xid().toData(), b.xid().toData()),\n );\n\n const ownerIndex = sortedParticipants.findIndex(\n (doc) => doc.xid().urString() === owner.xid().urString(),\n );\n if (ownerIndex === -1) {\n throw new Error(\"Invite does not include the registry owner\");\n }\n\n const identifierIndex = ownerIndex + 1; // FROST uses 1-indexed identifiers\n if (identifierIndex > 65535) {\n throw new Error(\"Too many participants for identifiers\");\n }\n const identifier = identifierFromU16(identifierIndex);\n\n const total = sortedParticipants.length;\n if (total > 65535) {\n throw new Error(\"Too many participants for FROST identifiers\");\n }\n\n const minSigners = details.invitation.minSigners();\n if (minSigners > 65535) {\n throw new Error(\"min_signers does not fit into identifier space\");\n }\n\n // Build group participants for the registry\n const groupParticipants = buildGroupParticipants(registry, owner, sortedParticipants);\n const coordinator = groupParticipantFromRegistry(registry, owner, details.invitation.sender());\n\n // Check if we're posting to storage\n const isPosting = options.storageSelection !== undefined;\n\n // Build the response body\n let responseBody: Envelope;\n let contributions: ContributionPaths | undefined;\n\n if (options.rejectReason === undefined && isPosting) {\n // Actually posting - generate and persist round1 state\n const [round1Secret, round1Package] = dkgPart1(identifier, total, minSigners, createRng());\n\n contributions = persistRound1State(\n registryPath,\n details.invitation.groupId(),\n round1Secret,\n round1Package,\n );\n\n responseBody = buildResponseBody(\n details.invitation.groupId(),\n owner.xid(),\n nextResponseArid,\n round1Package,\n );\n\n // Create and save group record\n const groupRecord = new GroupRecord(\n details.invitation.charter(),\n details.invitation.minSigners(),\n coordinator,\n groupParticipants,\n );\n groupRecord.setContributions(contributions);\n groupRecord.setListeningAtArid(nextResponseArid);\n\n registry.recordGroup(details.invitation.groupId(), groupRecord);\n registry.save(registryPath);\n } else if (options.rejectReason === undefined) {\n // Preview mode - generate dummy round1 for envelope structure only\n const [, round1Package] = dkgPart1(identifier, total, minSigners, createRng());\n\n responseBody = buildResponseBody(\n details.invitation.groupId(),\n owner.xid(),\n nextResponseArid,\n round1Package,\n );\n } else {\n // Rejecting - no round1 needed\n responseBody = buildResponseBody(\n details.invitation.groupId(),\n owner.xid(),\n nextResponseArid,\n undefined,\n );\n }\n\n // Build the sealed response\n const signerPrivateKeys = owner.xidDocument().inceptionPrivateKeys();\n if (signerPrivateKeys === undefined) {\n throw new Error(\"Owner XID document has no signing keys\");\n }\n\n let sealed: SealedResponse;\n if (options.rejectReason !== undefined) {\n // Build rejection error body\n const errorBody = Envelope.new(\"dkgInviteReject\")\n .addAssertion(\"group\", details.invitation.groupId())\n .addAssertion(\"response_arid\", nextResponseArid)\n .addAssertion(\"reason\", options.rejectReason);\n\n sealed = SealedResponse.newFailure(details.invitation.requestId(), owner.xidDocument())\n .withError(errorBody)\n .withState(nextResponseArid);\n } else {\n sealed = SealedResponse.newSuccess(details.invitation.requestId(), owner.xidDocument())\n .withResult(responseBody)\n .withState(nextResponseArid);\n }\n\n // Add peer continuation if present\n const peerContinuation = details.invitation.peerContinuation();\n if (peerContinuation !== undefined) {\n sealed = sealed.withPeerContinuation(peerContinuation);\n }\n\n // Handle output based on storage selection\n if (options.storageSelection !== undefined) {\n const responseEnvelope = sealed.toEnvelope(\n details.invitation.validUntil(),\n signerPrivateKeys,\n details.invitation.sender(),\n );\n\n const responseTarget = details.invitation.responseArid();\n const client = await createStorageClient(options.storageSelection);\n\n await putWithIndicator(\n client,\n responseTarget,\n responseEnvelope,\n \"Round 1 Response\",\n options.verbose ?? false,\n );\n\n if (options.verbose === true) {\n console.log(`Sent round 1 response`);\n console.log(`Listening at: ${nextResponseArid.urString()}`);\n }\n\n return {\n accepted: options.rejectReason === undefined,\n listeningArid: nextResponseArid.urString(),\n };\n } else if (options.preview === true) {\n // Show the GSTP response structure without encryption\n const unsealedEnvelope = sealed.toEnvelope(undefined, signerPrivateKeys, undefined);\n const envelopeUr = unsealedEnvelope.urString();\n console.log(envelopeUr);\n\n return {\n accepted: options.rejectReason === undefined,\n envelopeUr,\n };\n } else {\n // Print the sealed envelope\n const responseEnvelope = sealed.toEnvelope(\n details.invitation.validUntil(),\n signerPrivateKeys,\n details.invitation.sender(),\n );\n const envelopeUr = responseEnvelope.urString();\n console.log(envelopeUr);\n\n return {\n accepted: options.rejectReason === undefined,\n envelopeUr,\n };\n }\n}\n\n// `resolveSenderXidDocument` removed — it was an inline duplicate of\n// Rust `resolve_sender(registry, input)`. The shared helper now lives\n// in `cmd/dkg/common.ts` and is imported above.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,eAAe,sBACb,WACA,QACA,SACmB;CACnB,IAAI,cAAc,KAAA,GAAW;EAE3B,IAAI;GACF,MAAM,OAAOA,eAAAA,YAAY,MAAM;GAE/B,MAAM,WAAW,MAAMC,aAAAA,iBAAiB,MADnBC,iBAAAA,oBAAoB,SAAS,GACF,MAAM,UAAU,SAAS,KAAK;GAC9E,IAAI,aAAa,QAAQ,aAAa,KAAA,GACpC,MAAM,IAAI,MAAM,oCAAoC;GAEtD,OAAO;EACT,SAAS,GAAG;GAEV,IAAI,aAAa,SAAS,EAAE,QAAQ,SAAS,oCAAoC,GAC/E,MAAM;EAEV;EAEA,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,6DAA6D;EAG/E,OAAOC,eAAAA,gBAAgB,MAAM;CAC/B;CAGA,IAAI;EACF,eAAA,YAAY,MAAM;EAClB,MAAM,IAAI,MAAM,oEAAoE;CACtF,SAAS,GAAG;EAEV,IAAI,aAAa,SAAS,EAAE,QAAQ,SAAS,wCAAwC,GACnF,MAAM;CAEV;CAEA,OAAOA,eAAAA,gBAAgB,MAAM;AAC/B;;;;;;AAOA,SAAS,kBACP,SACA,aACA,cACA,eACU;CACV,IAAI,WAAWC,eAAAA,SAAS,KAAK,EAC1B,QAAQ,mB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EAEtB,OAAO;GACL,UAAU,QAAQ,iBAAiB,KAAA;GACnC;EACF;CACF,OAAO;EAOL,MAAM,aALmB,OAAO,WAC9B,QAAQ,WAAW,WAAW,GAC9B,mBACA,QAAQ,WAAW,OAAO,CAEM,EAAE,SAAS;EAC7C,QAAQ,IAAI,UAAU;EAEtB,OAAO;GACL,UAAU,QAAQ,iBAAiB,KAAA;GACnC;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-z9aeyW2b.mjs";
|
|
2
|
+
import { Registry, resolveRegistryPath } from "./registry/index.mjs";
|
|
3
|
+
import { c as parseAridUr, n as isVerbose } from "./common-Cf1UvJaP.mjs";
|
|
4
|
+
import { f as parallelFetch, m as parallelSend } from "./parallel-PZiwHZT8.mjs";
|
|
5
|
+
import { n as signingStateDir } from "./common-DNrD_-EI.mjs";
|
|
6
|
+
import { ARID, JSON as JSON$1, XID } from "@bcts/components";
|
|
7
|
+
import { Envelope } from "@bcts/envelope";
|
|
8
|
+
import { SealedRequest, SealedResponse } from "@bcts/gstp";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
//#region src/cmd/sign/coordinator/round1.ts
|
|
12
|
+
/**
|
|
13
|
+
* Copyright © 2023-2026 Blockchain Commons, LLC
|
|
14
|
+
* Copyright © 2025-2026 Parity Technologies
|
|
15
|
+
*
|
|
16
|
+
*
|
|
17
|
+
* Sign coordinator round 1 command.
|
|
18
|
+
*
|
|
19
|
+
* Port of cmd/sign/coordinator/round1.rs from frost-hubert-rust.
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
var round1_exports = /* @__PURE__ */ __exportAll({
|
|
24
|
+
buildShareRequestForParticipant: () => buildShareRequestForParticipant,
|
|
25
|
+
collectCommitmentsParallel: () => collectCommitmentsParallel,
|
|
26
|
+
dispatchShareRequestsParallel: () => dispatchShareRequestsParallel,
|
|
27
|
+
persistCommitments: () => persistCommitments,
|
|
28
|
+
round1: () => round1,
|
|
29
|
+
updatePendingForShare: () => updatePendingForShare,
|
|
30
|
+
validateAndExtractCommitResponse: () => validateAndExtractCommitResponse
|
|
31
|
+
});
|
|
32
|
+
/**
|
|
33
|
+
* Load the start state for a signing session.
|
|
34
|
+
*
|
|
35
|
+
* Port of `load_start_state()` from cmd/sign/coordinator/round1.rs.
|
|
36
|
+
*/
|
|
37
|
+
function loadStartState(registryPath, sessionId, groupHint) {
|
|
38
|
+
const base = path.dirname(registryPath);
|
|
39
|
+
const groupStateDir = path.join(base, "group-state");
|
|
40
|
+
const candidatePaths = [];
|
|
41
|
+
let groupDirs;
|
|
42
|
+
if (groupHint !== void 0) groupDirs = [[groupHint, path.join(groupStateDir, groupHint.hex())]];
|
|
43
|
+
else {
|
|
44
|
+
groupDirs = [];
|
|
45
|
+
if (fs.existsSync(groupStateDir)) {
|
|
46
|
+
for (const entry of fs.readdirSync(groupStateDir, { withFileTypes: true })) if (entry.isDirectory()) {
|
|
47
|
+
const dirName = entry.name;
|
|
48
|
+
if (dirName.length === 64 && /^[0-9a-fA-F]+$/.test(dirName)) {
|
|
49
|
+
const groupId = ARID.fromHex(dirName);
|
|
50
|
+
groupDirs.push([groupId, path.join(groupStateDir, dirName)]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (const [groupId, groupDir] of groupDirs) {
|
|
56
|
+
const candidate = path.join(groupDir, "signing", sessionId.hex(), "start.json");
|
|
57
|
+
if (fs.existsSync(candidate)) candidatePaths.push([groupId, candidate]);
|
|
58
|
+
}
|
|
59
|
+
if (candidatePaths.length === 0) throw new Error("No sign start state found; run `frost sign coordinator start` first");
|
|
60
|
+
if (candidatePaths.length > 1) throw new Error("Multiple signing sessions found; specify --group to disambiguate");
|
|
61
|
+
const [groupId, statePath] = candidatePaths[0];
|
|
62
|
+
const raw = JSON.parse(fs.readFileSync(statePath, "utf-8"));
|
|
63
|
+
const getStr = (key) => {
|
|
64
|
+
const value = raw[key];
|
|
65
|
+
if (typeof value !== "string") throw new Error(`Missing or invalid ${key} in start.json`);
|
|
66
|
+
return value;
|
|
67
|
+
};
|
|
68
|
+
const sessionInState = parseAridUr(getStr("session_id"));
|
|
69
|
+
const groupInState = parseAridUr(getStr("group"));
|
|
70
|
+
if (sessionInState.hex() !== sessionId.hex()) throw new Error(`start.json session ${sessionInState.urString()} does not match requested session ${sessionId.urString()}`);
|
|
71
|
+
if (groupInState.hex() !== groupId.hex()) throw new Error(`start.json group ${groupInState.urString()} does not match directory group ${groupId.urString()}`);
|
|
72
|
+
const targetUr = getStr("target");
|
|
73
|
+
const participantsVal = raw["participants"];
|
|
74
|
+
if (participantsVal === void 0 || typeof participantsVal !== "object") throw new Error("Missing participants in start.json");
|
|
75
|
+
const participants = /* @__PURE__ */ new Map();
|
|
76
|
+
for (const [xidStr, value] of Object.entries(participantsVal)) {
|
|
77
|
+
const xid = XID.fromURString(xidStr);
|
|
78
|
+
if (typeof value !== "object" || value === null) throw new Error("Participant entry is not an object in start.json");
|
|
79
|
+
const commitAridStr = value["commit_arid"];
|
|
80
|
+
const shareAridStr = value["share_arid"];
|
|
81
|
+
if (typeof commitAridStr !== "string") throw new Error("Missing commit_arid in start.json");
|
|
82
|
+
if (typeof shareAridStr !== "string") throw new Error("Missing share_arid in start.json");
|
|
83
|
+
participants.set(xid.urString(), {
|
|
84
|
+
commitArid: parseAridUr(commitAridStr),
|
|
85
|
+
shareArid: parseAridUr(shareAridStr)
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
groupId,
|
|
90
|
+
targetUr,
|
|
91
|
+
participants
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Validate and extract data from a sign commit response.
|
|
96
|
+
*
|
|
97
|
+
* Port of `validate_and_extract_sign_round1_response()` from cmd/sign/coordinator/round1.rs.
|
|
98
|
+
*/
|
|
99
|
+
function validateAndExtractCommitResponse(envelope, coordinatorKeys, expectedSender, expectedSessionId) {
|
|
100
|
+
const now = /* @__PURE__ */ new Date();
|
|
101
|
+
const sealedResponse = SealedResponse.tryFromEncryptedEnvelope(envelope, void 0, now, coordinatorKeys);
|
|
102
|
+
if (!sealedResponse.sender().xid().equals(expectedSender)) throw new Error(`Unexpected response sender: ${sealedResponse.sender().xid().urString()} (expected ${expectedSender.urString()})`);
|
|
103
|
+
if (sealedResponse.isErr()) {
|
|
104
|
+
const errorEnvelope = sealedResponse.error();
|
|
105
|
+
let reason = "unknown reason";
|
|
106
|
+
try {
|
|
107
|
+
const reasonEnv = errorEnvelope.objectForPredicate("reason");
|
|
108
|
+
if (reasonEnv !== void 0) reason = reasonEnv.extractString();
|
|
109
|
+
} catch {}
|
|
110
|
+
throw new Error(`Participant rejected signInvite: ${reason}`);
|
|
111
|
+
}
|
|
112
|
+
const result = sealedResponse.result();
|
|
113
|
+
result.checkSubjectUnit();
|
|
114
|
+
result.checkType("signRound1Response");
|
|
115
|
+
const responseSession = result.tryObjectForPredicate("session", (cbor) => ARID.fromTaggedCbor(cbor));
|
|
116
|
+
if (responseSession.hex() !== expectedSessionId.hex()) throw new Error(`Response session ${responseSession.urString()} does not match expected ${expectedSessionId.urString()}`);
|
|
117
|
+
const commitmentsJson = result.tryObjectForPredicate("commitments", (cbor) => JSON$1.fromTaggedCbor(cbor));
|
|
118
|
+
return {
|
|
119
|
+
commitments: JSON.parse(new TextDecoder().decode(commitmentsJson.toData())),
|
|
120
|
+
nextRequestArid: result.tryObjectForPredicate("response_arid", (cbor) => ARID.fromTaggedCbor(cbor))
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Collect signing commitments in parallel.
|
|
125
|
+
*
|
|
126
|
+
* Port of `collect_sign_round1_parallel()` from cmd/sign/coordinator/round1.rs.
|
|
127
|
+
*/
|
|
128
|
+
async function collectCommitmentsParallel(client, registry, startState, coordinator, sessionId, timeout) {
|
|
129
|
+
const requests = [];
|
|
130
|
+
for (const [xidStr, state] of startState.participants) {
|
|
131
|
+
const xid = XID.fromURString(xidStr);
|
|
132
|
+
const name = registry.participant(xid)?.petName() ?? xid.urString();
|
|
133
|
+
requests.push([
|
|
134
|
+
xid,
|
|
135
|
+
state.commitArid,
|
|
136
|
+
name
|
|
137
|
+
]);
|
|
138
|
+
}
|
|
139
|
+
const coordinatorKeys = coordinator.inceptionPrivateKeys();
|
|
140
|
+
if (coordinatorKeys === void 0) throw new Error("Missing coordinator private keys");
|
|
141
|
+
return parallelFetch(client, requests, (envelope, xid) => {
|
|
142
|
+
try {
|
|
143
|
+
return validateAndExtractCommitResponse(envelope, coordinatorKeys, xid, sessionId);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
return { rejected: e instanceof Error ? e.message : String(e) };
|
|
146
|
+
}
|
|
147
|
+
}, { timeoutSeconds: timeout });
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Build a sign share request for a participant.
|
|
151
|
+
*
|
|
152
|
+
* Port of `build_sign_share_request()` from cmd/sign/coordinator/round1.rs.
|
|
153
|
+
*/
|
|
154
|
+
function buildShareRequestForParticipant(sender, _groupId, sessionId, responseArid, commitments) {
|
|
155
|
+
let request = SealedRequest.new("signRound2", sessionId, sender).withParameter("session", sessionId).withParameter("response_arid", responseArid);
|
|
156
|
+
for (const [xidStr, commits] of commitments) {
|
|
157
|
+
const xid = XID.fromURString(xidStr);
|
|
158
|
+
const commitsJson = JSON$1.fromData(new TextEncoder().encode(JSON.stringify(commits)));
|
|
159
|
+
const entry = Envelope.new(xid).addAssertion("commitments", commitsJson.taggedCborData());
|
|
160
|
+
request = request.withParameter("commitment", entry);
|
|
161
|
+
}
|
|
162
|
+
return request;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Dispatch share requests to participants in parallel.
|
|
166
|
+
*
|
|
167
|
+
* Port of parallel dispatch logic from cmd/sign/coordinator/round1.rs.
|
|
168
|
+
*/
|
|
169
|
+
async function dispatchShareRequestsParallel(client, registry, owner, startState, sessionId, collection, commitments, previewShare, verbose) {
|
|
170
|
+
const signerKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
171
|
+
if (signerKeys === void 0) throw new Error("Coordinator XID document has no signing keys");
|
|
172
|
+
const validUntil = new Date(Date.now() + 3600 * 1e3);
|
|
173
|
+
const messages = [];
|
|
174
|
+
let previewPrinted = false;
|
|
175
|
+
for (const [xid, data] of collection.successes) {
|
|
176
|
+
const xidStr = xid.urString();
|
|
177
|
+
const participantState = startState.participants.get(xidStr);
|
|
178
|
+
if (participantState === void 0) throw new Error(`Participant ${xidStr} not found in start state`);
|
|
179
|
+
const participantName = registry.participant(xid)?.petName() ?? xidStr;
|
|
180
|
+
let recipientDoc;
|
|
181
|
+
if (xid.urString() === owner.xid().urString()) recipientDoc = owner.xidDocument();
|
|
182
|
+
else {
|
|
183
|
+
const record = registry.participant(xid);
|
|
184
|
+
if (record === void 0) throw new Error(`Participant ${xidStr} not found in registry`);
|
|
185
|
+
recipientDoc = record.xidDocument();
|
|
186
|
+
}
|
|
187
|
+
const request = buildShareRequestForParticipant(owner.xidDocument(), startState.groupId, sessionId, participantState.shareArid, commitments);
|
|
188
|
+
if (previewShare === true && !previewPrinted) {
|
|
189
|
+
const preview = request.toEnvelope(validUntil, signerKeys, void 0);
|
|
190
|
+
console.log(`# signRound2 preview for ${xidStr}`);
|
|
191
|
+
console.log(preview.format());
|
|
192
|
+
previewPrinted = true;
|
|
193
|
+
}
|
|
194
|
+
const sealedEnvelope = request.toEnvelopeForRecipients(validUntil, signerKeys, [recipientDoc]);
|
|
195
|
+
messages.push([
|
|
196
|
+
xid,
|
|
197
|
+
data.nextRequestArid,
|
|
198
|
+
sealedEnvelope,
|
|
199
|
+
participantName
|
|
200
|
+
]);
|
|
201
|
+
}
|
|
202
|
+
console.error();
|
|
203
|
+
return parallelSend(client, messages, verbose);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Persist collected commitments to disk.
|
|
207
|
+
*
|
|
208
|
+
* Port of commitments persistence logic from cmd/sign/coordinator/round1.rs.
|
|
209
|
+
*/
|
|
210
|
+
function persistCommitments(registryPath, groupId, sessionId, startState, commitments) {
|
|
211
|
+
const signingDir = signingStateDir(registryPath, groupId.hex(), sessionId.hex());
|
|
212
|
+
fs.mkdirSync(signingDir, { recursive: true });
|
|
213
|
+
const commitmentsPath = path.join(signingDir, "commitments.json");
|
|
214
|
+
const commitmentsJson = {};
|
|
215
|
+
for (const [xidStr, commits] of commitments) {
|
|
216
|
+
const participantState = startState.participants.get(xidStr);
|
|
217
|
+
if (participantState === void 0) throw new Error(`Participant ${xidStr} not found in start state`);
|
|
218
|
+
commitmentsJson[xidStr] = {
|
|
219
|
+
commitments: commits,
|
|
220
|
+
share_arid: participantState.shareArid.urString()
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const root = {
|
|
224
|
+
group: groupId.urString(),
|
|
225
|
+
session: sessionId.urString(),
|
|
226
|
+
target: startState.targetUr,
|
|
227
|
+
commitments: commitmentsJson
|
|
228
|
+
};
|
|
229
|
+
fs.writeFileSync(commitmentsPath, JSON.stringify(root, null, 2));
|
|
230
|
+
return commitmentsPath;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Update pending requests in the registry for share phase.
|
|
234
|
+
*
|
|
235
|
+
* Note: In the Rust implementation, the registry doesn't track pending ARIDs
|
|
236
|
+
* directly on participant records. The pending state is managed through the
|
|
237
|
+
* start.json and commitments.json files in the signing state directory.
|
|
238
|
+
*
|
|
239
|
+
* This function is provided for API compatibility but currently does nothing.
|
|
240
|
+
*/
|
|
241
|
+
function updatePendingForShare(_registry, _collection, _startState) {}
|
|
242
|
+
/**
|
|
243
|
+
* Execute the sign coordinator round 1 command.
|
|
244
|
+
*
|
|
245
|
+
* Collects signing commitments from participants.
|
|
246
|
+
*
|
|
247
|
+
* Port of `round1()` from cmd/sign/coordinator/round1.rs.
|
|
248
|
+
*/
|
|
249
|
+
async function round1(client, options, cwd) {
|
|
250
|
+
const registryPath = resolveRegistryPath(options.registryPath, cwd);
|
|
251
|
+
const registry = Registry.load(registryPath);
|
|
252
|
+
const owner = registry.owner();
|
|
253
|
+
if (owner === void 0) throw new Error("Registry owner is required");
|
|
254
|
+
const sessionId = parseAridUr(options.sessionId);
|
|
255
|
+
const startState = loadStartState(registryPath, sessionId, options.groupId !== void 0 ? parseAridUr(options.groupId) : void 0);
|
|
256
|
+
const groupId = startState.groupId;
|
|
257
|
+
const groupRecord = registry.group(groupId);
|
|
258
|
+
if (groupRecord === void 0) throw new Error("Group not found in registry");
|
|
259
|
+
if (groupRecord.coordinator().xid().urString() !== owner.xid().urString()) throw new Error(`Only the coordinator can collect signInvite responses. Coordinator: ${groupRecord.coordinator().xid().urString()}, Owner: ${owner.xid().urString()}`);
|
|
260
|
+
if (options.parallel === true) {
|
|
261
|
+
const collection = await collectCommitmentsParallel(client, registry, startState, owner.xidDocument(), sessionId, options.timeoutSeconds);
|
|
262
|
+
if (collection.rejections.length > 0) {
|
|
263
|
+
console.error();
|
|
264
|
+
console.error("Rejections:");
|
|
265
|
+
for (const [xid, reason] of collection.rejections) console.error(` ${xid.urString()}: ${reason}`);
|
|
266
|
+
}
|
|
267
|
+
if (collection.errors.length > 0) {
|
|
268
|
+
console.error();
|
|
269
|
+
console.error("Errors:");
|
|
270
|
+
for (const [xid, error] of collection.errors) console.error(` ${xid.urString()}: ${error}`);
|
|
271
|
+
}
|
|
272
|
+
if (collection.timeouts.length > 0) {
|
|
273
|
+
console.error();
|
|
274
|
+
console.error("Timeouts:");
|
|
275
|
+
for (const xid of collection.timeouts) console.error(` ${xid.urString()}`);
|
|
276
|
+
}
|
|
277
|
+
if (!collection.allSucceeded()) throw new Error(`Sign commit collection incomplete: ${collection.successes.length} succeeded, ${collection.rejections.length} rejected, ${collection.errors.length} errors, ${collection.timeouts.length} timeouts`);
|
|
278
|
+
const commitments = /* @__PURE__ */ new Map();
|
|
279
|
+
for (const [xid, data] of collection.successes) commitments.set(xid.urString(), data.commitments);
|
|
280
|
+
const commitmentsPath = persistCommitments(registryPath, groupId, sessionId, startState, commitments);
|
|
281
|
+
const failures = (await dispatchShareRequestsParallel(client, registry, owner, startState, sessionId, collection, commitments, options.previewShare, options.verbose)).filter(([_, err]) => err !== null);
|
|
282
|
+
if (failures.length > 0) {
|
|
283
|
+
for (const [xid, error] of failures) if (error !== null) console.error(`Failed to send to ${xid.urString()}: ${error.message}`);
|
|
284
|
+
throw new Error(`Failed to send signRound2 requests to ${failures.length} participants`);
|
|
285
|
+
}
|
|
286
|
+
const displayPath = path.relative(cwd, commitmentsPath) || commitmentsPath;
|
|
287
|
+
if (isVerbose() || options.verbose === true) {
|
|
288
|
+
console.error();
|
|
289
|
+
console.error(`Collected ${collection.successes.length} signInvite responses. Saved to ${displayPath}`);
|
|
290
|
+
console.error(`Dispatched ${collection.successes.length} signRound2 requests.`);
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
accepted: collection.successes.length,
|
|
294
|
+
rejected: collection.rejections.length,
|
|
295
|
+
errors: collection.errors.length,
|
|
296
|
+
timeouts: collection.timeouts.length
|
|
297
|
+
};
|
|
298
|
+
} else {
|
|
299
|
+
if (isVerbose() || options.verbose === true) console.error(`Collecting signInvite responses for session ${sessionId.urString()} from ${startState.participants.size} participants...`);
|
|
300
|
+
const commitments = /* @__PURE__ */ new Map();
|
|
301
|
+
const sendToArids = /* @__PURE__ */ new Map();
|
|
302
|
+
const errors = [];
|
|
303
|
+
const coordinatorKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
304
|
+
if (coordinatorKeys === void 0) throw new Error("Coordinator XID document has no inception private keys");
|
|
305
|
+
for (const [xidStr, participantState] of startState.participants) {
|
|
306
|
+
const xid = XID.fromURString(xidStr);
|
|
307
|
+
const participantName = registry.participant(xid)?.petName() ?? xidStr;
|
|
308
|
+
try {
|
|
309
|
+
const envelope = await client.get(participantState.commitArid, options.timeoutSeconds);
|
|
310
|
+
if (envelope === void 0) throw new Error("Response not found in Hubert storage");
|
|
311
|
+
const data = validateAndExtractCommitResponse(envelope, coordinatorKeys, xid, sessionId);
|
|
312
|
+
commitments.set(xidStr, data.commitments);
|
|
313
|
+
sendToArids.set(xidStr, data.nextRequestArid);
|
|
314
|
+
if (isVerbose() || options.verbose === true) console.error(` ✓ ${participantName}`);
|
|
315
|
+
} catch (e) {
|
|
316
|
+
errors.push([xid, e instanceof Error ? e.message : String(e)]);
|
|
317
|
+
if (isVerbose() || options.verbose === true) console.error(` ✗ ${participantName}: ${e instanceof Error ? e.message : String(e)}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (errors.length > 0) throw new Error(`Sign commit collection incomplete: ${errors.length} of ${startState.participants.size} responses failed`);
|
|
321
|
+
if (commitments.size !== startState.participants.size) {
|
|
322
|
+
const missing = [];
|
|
323
|
+
for (const xidStr of startState.participants.keys()) if (!commitments.has(xidStr)) missing.push(xidStr);
|
|
324
|
+
throw new Error(`Missing signInvite responses from: ${missing.join(", ")}`);
|
|
325
|
+
}
|
|
326
|
+
const commitmentsPath = persistCommitments(registryPath, groupId, sessionId, startState, commitments);
|
|
327
|
+
const signerKeys = owner.xidDocument().inceptionPrivateKeys();
|
|
328
|
+
if (signerKeys === void 0) throw new Error("Owner XID document has no inception private keys");
|
|
329
|
+
const validUntil = new Date(Date.now() + 3600 * 1e3);
|
|
330
|
+
if (isVerbose() || options.verbose === true) console.error(`Dispatching signRound2 requests to ${sendToArids.size} participants...`);
|
|
331
|
+
else console.error();
|
|
332
|
+
let previewPrinted = false;
|
|
333
|
+
for (const [xidStr, sendToArid] of sendToArids) {
|
|
334
|
+
const xid = XID.fromURString(xidStr);
|
|
335
|
+
const participantState = startState.participants.get(xidStr);
|
|
336
|
+
if (participantState === void 0) throw new Error(`Participant state not found for ${xidStr}`);
|
|
337
|
+
const participantName = registry.participant(xid)?.petName() ?? xidStr;
|
|
338
|
+
let recipientDoc;
|
|
339
|
+
if (xidStr === owner.xid().urString()) recipientDoc = owner.xidDocument();
|
|
340
|
+
else {
|
|
341
|
+
const record = registry.participant(xid);
|
|
342
|
+
if (record === void 0) throw new Error(`Participant ${xidStr} not found in registry`);
|
|
343
|
+
recipientDoc = record.xidDocument();
|
|
344
|
+
}
|
|
345
|
+
const request = buildShareRequestForParticipant(owner.xidDocument(), groupId, sessionId, participantState.shareArid, commitments);
|
|
346
|
+
if (options.previewShare === true && !previewPrinted) {
|
|
347
|
+
const preview = request.toEnvelope(validUntil, signerKeys, void 0);
|
|
348
|
+
console.log(`# signRound2 preview for ${xidStr}`);
|
|
349
|
+
console.log(preview.format());
|
|
350
|
+
previewPrinted = true;
|
|
351
|
+
}
|
|
352
|
+
const sealedEnvelope = request.toEnvelopeForRecipients(validUntil, signerKeys, [recipientDoc]);
|
|
353
|
+
await client.put(sendToArid, sealedEnvelope);
|
|
354
|
+
if (isVerbose() || options.verbose === true) console.error(` ✓ ${participantName}`);
|
|
355
|
+
}
|
|
356
|
+
const displayPath = path.relative(cwd, commitmentsPath) || commitmentsPath;
|
|
357
|
+
if (isVerbose() || options.verbose === true) {
|
|
358
|
+
console.error();
|
|
359
|
+
console.error(`Collected ${commitments.size} signInvite responses. Saved to ${displayPath}`);
|
|
360
|
+
console.error(`Dispatched ${commitments.size} signRound2 requests.`);
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
accepted: commitments.size,
|
|
364
|
+
rejected: 0,
|
|
365
|
+
errors: errors.length,
|
|
366
|
+
timeouts: 0
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
//#endregion
|
|
371
|
+
export { round1 as a, validateAndExtractCommitResponse as c, persistCommitments as i, collectCommitmentsParallel as n, round1_exports as o, dispatchShareRequestsParallel as r, updatePendingForShare as s, buildShareRequestForParticipant as t };
|
|
372
|
+
|
|
373
|
+
//# sourceMappingURL=round1-D8t7EzIo.mjs.map
|