@outpost-protocol/core 0.1.1 → 0.3.0

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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Multi-Witness Certificate Assembly Coordinators for Outpost v1.2 Wallets:
3
+ * - `coordinateInitGenesis`: collects `>= t` verified `"SMW1_GENESIS"` signatures, assembles
4
+ * canonical `cert_0` (`EpochGenesisCert`), and optionally propagates quorum `cert_0` to all witnesses.
5
+ * - `coordinateRefreshFreshness`: collects `>= t` verified `"SMW1_FRESH"` signatures, assembles
6
+ * a quorum `StoredFreshCertDto`, and optionally propagates it to all witnesses.
7
+ * - `coordinateCloseCooperative`: signs/forwards owner or device `"SMW1_CLOSE"` auth, collects
8
+ * `>= t` verified witness close signatures sorted by `witness_index` for `buildClosePocketCooperativeOp`.
9
+ *
10
+ * Every witness response is cryptographically verified against the caller's pinned `witnesses`
11
+ * set and locally recomputed canonical digest before acceptance (`AGENTS.md` §1.1 & §1.6).
12
+ */
13
+ import type { EpochGenesisCert, IndexedWitnessSignature } from "./wire.js";
14
+ import { WitnessClient, type StoredFreshCertDto, type WitnessClientOptions } from "./witnessClient.js";
15
+ import { TokenResolver, type NetworkHint, type WireAddress, type WireToken } from "./xdr.js";
16
+ export type WitnessClientInput = WitnessClient | string;
17
+ export interface WitnessCallFailure {
18
+ readonly endpoint: string;
19
+ readonly reason: string;
20
+ }
21
+ export interface CoordinateInitGenesisParams {
22
+ /** Witness stations (`WitnessClient` instances or base URLs like `"https://witness.outpost.cash/w1"`). */
23
+ readonly witnessClients: readonly WitnessClientInput[];
24
+ readonly witnessClientOptions?: WitnessClientOptions;
25
+ readonly networkHint: NetworkHint;
26
+ readonly networkPassphrase?: string;
27
+ readonly factoryVer: number;
28
+ readonly owner: WireAddress | string;
29
+ readonly vaultId: string | WireAddress | Uint8Array;
30
+ readonly pocketId: number;
31
+ readonly epoch: number;
32
+ readonly token: WireToken;
33
+ readonly tokenResolver?: TokenResolver;
34
+ readonly devicePubkey: Uint8Array | string;
35
+ /** Strictly ascending unique 32B witness Ed25519 pubkeys (`sortWitnesses()`). */
36
+ readonly witnesses: readonly (Uint8Array | string)[];
37
+ readonly witnessThreshold: number;
38
+ readonly epochTotalDeposited: bigint;
39
+ readonly exitDelaySecs: bigint | number;
40
+ /** Monotonic L1 ledger sequence (e.g. deposit confirmation ledger or current latest ledger). */
41
+ readonly targetLedgerSeq: number;
42
+ /** Monotonic L1 ledger close timestamp in unix seconds. */
43
+ readonly targetTs: bigint | number;
44
+ /**
45
+ * When `true` (default), performs a second best-effort pass pushing the assembled quorum `cert_0`
46
+ * and `genesis_sigs` back to all witnesses so every station caches full quorum `cert_0`.
47
+ */
48
+ readonly propagateCert0?: boolean;
49
+ }
50
+ export interface CoordinateInitGenesisResult {
51
+ readonly cert0: EpochGenesisCert;
52
+ readonly cert0Bytes: Uint8Array;
53
+ readonly cert0Hex: string;
54
+ readonly genesisDigest: Uint8Array;
55
+ readonly syncedLedgerSeq: number;
56
+ readonly syncedAtTs: bigint;
57
+ readonly verifiedWitnessIndices: number[];
58
+ readonly propagatedCount: number;
59
+ readonly failures: readonly WitnessCallFailure[];
60
+ }
61
+ /**
62
+ * Coordinate `POST /init-genesis` across a pocket's witnesses, cryptographically verifying each
63
+ * `"SMW1_GENESIS"` signature against the locally computed digest and pinned `witnesses` set,
64
+ * assembling canonical `cert_0`, and optionally propagating quorum `cert_0` back to all witnesses.
65
+ */
66
+ export declare function coordinateInitGenesis(params: CoordinateInitGenesisParams): Promise<CoordinateInitGenesisResult>;
67
+ export interface CoordinateRefreshFreshnessParams {
68
+ readonly witnessClients: readonly WitnessClientInput[];
69
+ readonly witnessClientOptions?: WitnessClientOptions;
70
+ readonly networkHint: NetworkHint;
71
+ readonly networkPassphrase?: string;
72
+ readonly vaultId: string | WireAddress | Uint8Array;
73
+ readonly pocketId: number;
74
+ readonly epoch: number;
75
+ readonly witnesses: readonly (Uint8Array | string)[];
76
+ readonly witnessThreshold: number;
77
+ readonly targetLedgerSeq: number;
78
+ readonly targetTs: bigint | number;
79
+ /** When `true` (default), pushes the assembled quorum `fresh_cert` back to all witnesses. */
80
+ readonly propagateFreshCert?: boolean;
81
+ }
82
+ export interface CoordinateRefreshFreshnessResult {
83
+ readonly freshCert: StoredFreshCertDto;
84
+ readonly freshDigest: Uint8Array;
85
+ readonly syncedLedgerSeq: number;
86
+ readonly syncedAtTs: bigint;
87
+ readonly verifiedWitnessIndices: number[];
88
+ readonly propagatedCount: number;
89
+ readonly failures: readonly WitnessCallFailure[];
90
+ }
91
+ /**
92
+ * Coordinate `POST /refresh-freshness` across a pocket's witnesses, cryptographically verifying
93
+ * each `"SMW1_FRESH"` signature, assembling a quorum `StoredFreshCertDto` (directly passable to
94
+ * `OfflineWallet.refreshAnchor`), and optionally propagating it back to all witnesses.
95
+ */
96
+ export declare function coordinateRefreshFreshness(params: CoordinateRefreshFreshnessParams): Promise<CoordinateRefreshFreshnessResult>;
97
+ export interface CoordinateCloseCooperativeParams {
98
+ readonly witnessClients: readonly WitnessClientInput[];
99
+ readonly witnessClientOptions?: WitnessClientOptions;
100
+ readonly networkHint: NetworkHint;
101
+ readonly networkPassphrase?: string;
102
+ readonly vaultId: string | WireAddress | Uint8Array;
103
+ readonly pocketId: number;
104
+ readonly epoch: number;
105
+ readonly witnesses: readonly (Uint8Array | string)[];
106
+ readonly witnessThreshold: number;
107
+ /** Optional `G...` or `C...` owner StrKey forwarded to witnesses. */
108
+ readonly owner?: WireAddress | string;
109
+ /** Classic `G...` owner 32-byte Ed25519 secret key (automatically signs `"SMW1_CLOSE"`). */
110
+ readonly ownerSecretKey?: Uint8Array;
111
+ /** Pre-computed 64-byte Ed25519 signature by classic `G...` owner over `"SMW1_CLOSE"`. */
112
+ readonly ownerSig?: Uint8Array | string;
113
+ /** Smart-account `C...` pocket device 32-byte Ed25519 secret key (automatically signs `"SMW1_CLOSE"`). */
114
+ readonly deviceSecretKey?: Uint8Array;
115
+ /** Pre-computed 64-byte Ed25519 signature by pocket device key over `"SMW1_CLOSE"`. */
116
+ readonly deviceSig?: Uint8Array | string;
117
+ /** Optional `SMESHC1...` latest certificate to sync lagging witnesses before closing. */
118
+ readonly latestCert?: string;
119
+ }
120
+ export interface CoordinateCloseCooperativeResult {
121
+ readonly closeDigest: Uint8Array;
122
+ /** Strictly ascending unique witness signatures ready for `buildClosePocketCooperativeOp`. */
123
+ readonly witnessSigs: readonly IndexedWitnessSignature[];
124
+ readonly verifiedWitnessIndices: number[];
125
+ readonly failures: readonly WitnessCallFailure[];
126
+ }
127
+ /**
128
+ * Coordinate `POST /close-cooperative` across a pocket's witnesses, verifying each `"SMW1_CLOSE"`
129
+ * witness signature and returning sorted `witnessSigs` ready for `buildClosePocketCooperativeOp`.
130
+ */
131
+ export declare function coordinateCloseCooperative(params: CoordinateCloseCooperativeParams): Promise<CoordinateCloseCooperativeResult>;
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Multi-Witness Certificate Assembly Coordinators for Outpost v1.2 Wallets:
3
+ * - `coordinateInitGenesis`: collects `>= t` verified `"SMW1_GENESIS"` signatures, assembles
4
+ * canonical `cert_0` (`EpochGenesisCert`), and optionally propagates quorum `cert_0` to all witnesses.
5
+ * - `coordinateRefreshFreshness`: collects `>= t` verified `"SMW1_FRESH"` signatures, assembles
6
+ * a quorum `StoredFreshCertDto`, and optionally propagates it to all witnesses.
7
+ * - `coordinateCloseCooperative`: signs/forwards owner or device `"SMW1_CLOSE"` auth, collects
8
+ * `>= t` verified witness close signatures sorted by `witness_index` for `buildClosePocketCooperativeOp`.
9
+ *
10
+ * Every witness response is cryptographically verified against the caller's pinned `witnesses`
11
+ * set and locally recomputed canonical digest before acceptance (`AGENTS.md` §1.1 & §1.6).
12
+ */
13
+ import { encodeCert0Bytes, encodeCert0Hex } from "./cert0.js";
14
+ import { assertBigInt, assertBytesLength, assertSortedUniqueWitnesses, assertU16, assertU32, computeCloseDigest, computeFreshDigest, computeGenesisDigest, MAX_U64, signEd25519, verifyEd25519, } from "./digest.js";
15
+ import { MAX_EXIT_DELAY_SECS, MIN_EXIT_DELAY_SECS } from "./wallet.js";
16
+ import { bytesToHex, createWitnessClient, hexToBytes, } from "./witnessClient.js";
17
+ import { assertNetworkHint, assertNotMuxedStrKey, assertValidWireAddress, bytesEqual, defaultTokenResolver, networkIdFromPassphrase, networkPassphraseForHint, normalizeContractHash, strKeyToWireAddress, wireAddressToStrKey, } from "./xdr.js";
18
+ import * as StellarSdk from "@stellar/stellar-sdk";
19
+ function resolveWitnessClients(inputs, options) {
20
+ if (inputs.length === 0) {
21
+ throw new Error("witnessClients must contain at least 1 witness endpoint");
22
+ }
23
+ return inputs.map((item) => typeof item === "string" ? createWitnessClient(item, options) : item);
24
+ }
25
+ function normalizeWitnessPubkeys(raw) {
26
+ const out = raw.map((w, i) => {
27
+ const b = typeof w === "string" ? hexToBytes(w) : new Uint8Array(w);
28
+ assertBytesLength(b, 32, `witnesses[${i}]`);
29
+ return b;
30
+ });
31
+ assertSortedUniqueWitnesses(out);
32
+ return out;
33
+ }
34
+ function assertValidThreshold(threshold, n) {
35
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > n || threshold * 2 <= n) {
36
+ throw new Error(`witnessThreshold (${threshold}) must satisfy 0 < t <= n and 2t > n (n=${n})`);
37
+ }
38
+ }
39
+ function normalizeU64Ts(ts, label) {
40
+ if (typeof ts === "bigint") {
41
+ if (ts <= 0n || ts > MAX_U64) {
42
+ throw new RangeError(`${label} must be in 1..=u64::MAX, got ${ts}`);
43
+ }
44
+ return ts;
45
+ }
46
+ if (!Number.isSafeInteger(ts) || ts <= 0) {
47
+ throw new RangeError(`${label} must be a positive safe integer, got ${ts}`);
48
+ }
49
+ return BigInt(ts);
50
+ }
51
+ function normalizeFixedBytes(val, expectedLen, label) {
52
+ const b = typeof val === "string" ? hexToBytes(val) : new Uint8Array(val);
53
+ assertBytesLength(b, expectedLen, label);
54
+ return b;
55
+ }
56
+ function formatError(err) {
57
+ return err instanceof Error ? err.message : String(err);
58
+ }
59
+ /**
60
+ * Coordinate `POST /init-genesis` across a pocket's witnesses, cryptographically verifying each
61
+ * `"SMW1_GENESIS"` signature against the locally computed digest and pinned `witnesses` set,
62
+ * assembling canonical `cert_0`, and optionally propagating quorum `cert_0` back to all witnesses.
63
+ */
64
+ export async function coordinateInitGenesis(params) {
65
+ assertNetworkHint(params.networkHint);
66
+ if (!Number.isInteger(params.factoryVer) || params.factoryVer < 1 || params.factoryVer > 15) {
67
+ throw new Error(`factoryVer must be in 1..=15, got ${params.factoryVer}`);
68
+ }
69
+ assertU16(params.pocketId, "pocketId");
70
+ assertU32(params.epoch, "epoch");
71
+ if (params.epoch === 0)
72
+ throw new Error("epoch must be >= 1");
73
+ assertU32(params.targetLedgerSeq, "targetLedgerSeq");
74
+ if (params.targetLedgerSeq === 0)
75
+ throw new Error("targetLedgerSeq must be >= 1");
76
+ const targetTs = normalizeU64Ts(params.targetTs, "targetTs");
77
+ assertBigInt(params.epochTotalDeposited, "epochTotalDeposited");
78
+ if (params.epochTotalDeposited <= 0n || params.epochTotalDeposited > MAX_U64) {
79
+ throw new Error(`epochTotalDeposited out of u64 (>0) range: ${params.epochTotalDeposited}`);
80
+ }
81
+ const exitDelaySecs = normalizeU64Ts(params.exitDelaySecs, "exitDelaySecs");
82
+ if (exitDelaySecs < MIN_EXIT_DELAY_SECS || exitDelaySecs > MAX_EXIT_DELAY_SECS) {
83
+ throw new Error(`exitDelaySecs (${exitDelaySecs}) must be within [${MIN_EXIT_DELAY_SECS}, ${MAX_EXIT_DELAY_SECS}]`);
84
+ }
85
+ const ownerWire = typeof params.owner === "string" ? strKeyToWireAddress(params.owner) : params.owner;
86
+ assertValidWireAddress(ownerWire);
87
+ const vaultRaw = normalizeContractHash(params.vaultId);
88
+ const vaultStrKey = StellarSdk.StrKey.encodeContract(vaultRaw);
89
+ const devicePubkey = normalizeFixedBytes(params.devicePubkey, 32, "devicePubkey");
90
+ const witnesses = normalizeWitnessPubkeys(params.witnesses);
91
+ assertValidThreshold(params.witnessThreshold, witnesses.length);
92
+ const clients = resolveWitnessClients(params.witnessClients, params.witnessClientOptions);
93
+ const resolver = params.tokenResolver ?? defaultTokenResolver;
94
+ const resolvedToken = resolver.resolve(params.token, params.networkHint);
95
+ const passphrase = params.networkPassphrase ?? networkPassphraseForHint(params.networkHint);
96
+ const networkId = networkIdFromPassphrase(passphrase);
97
+ const expectedDigest = computeGenesisDigest({
98
+ networkId,
99
+ factoryVer: params.factoryVer,
100
+ owner: ownerWire,
101
+ vaultId: vaultRaw,
102
+ pocketId: params.pocketId,
103
+ epoch: params.epoch,
104
+ token: resolvedToken.contractId,
105
+ devicePubkey,
106
+ epochTotalDeposited: params.epochTotalDeposited,
107
+ exitDelaySecs,
108
+ syncedAtTs: targetTs,
109
+ syncedLedgerSeq: params.targetLedgerSeq,
110
+ witnessThreshold: params.witnessThreshold,
111
+ witnesses,
112
+ });
113
+ const round1 = await Promise.allSettled(clients.map((client) => client.initGenesis({
114
+ vault_id: vaultStrKey,
115
+ pocket_id: params.pocketId,
116
+ epoch: params.epoch,
117
+ target_ledger_seq: params.targetLedgerSeq,
118
+ target_ts: targetTs,
119
+ })));
120
+ const verifiedByIdx = new Map();
121
+ const failures = [];
122
+ for (let i = 0; i < round1.length; i++) {
123
+ const outcome = round1[i];
124
+ const endpoint = clients[i].baseUrl;
125
+ if (outcome.status === "rejected") {
126
+ failures.push({ endpoint, reason: formatError(outcome.reason) });
127
+ continue;
128
+ }
129
+ const resp = outcome.value;
130
+ try {
131
+ if (!Number.isInteger(resp.witness_index) ||
132
+ resp.witness_index < 0 ||
133
+ resp.witness_index >= witnesses.length) {
134
+ throw new Error(`witness_index ${resp.witness_index} out of bounds`);
135
+ }
136
+ if (resp.synced_ledger_seq !== params.targetLedgerSeq) {
137
+ throw new Error(`synced_ledger_seq mismatch: expected ${params.targetLedgerSeq}, got ${resp.synced_ledger_seq}`);
138
+ }
139
+ if (!/^\d+$/.test(resp.synced_at_ts) || BigInt(resp.synced_at_ts) !== targetTs) {
140
+ throw new Error(`synced_at_ts mismatch: expected ${targetTs}, got "${resp.synced_at_ts}"`);
141
+ }
142
+ const returnedPk = normalizeFixedBytes(resp.witness_pubkey, 32, "witness_pubkey");
143
+ const expectedPk = witnesses[resp.witness_index];
144
+ if (!bytesEqual(returnedPk, expectedPk)) {
145
+ throw new Error(`witness_pubkey mismatch for index ${resp.witness_index}: returned ${bytesToHex(returnedPk)}`);
146
+ }
147
+ const returnedDigest = normalizeFixedBytes(resp.genesis_digest, 32, "genesis_digest");
148
+ if (!bytesEqual(returnedDigest, expectedDigest)) {
149
+ throw new Error("genesis_digest does not match canonical SMW1_GENESIS digest");
150
+ }
151
+ const sigBytes = normalizeFixedBytes(resp.signature, 64, "signature");
152
+ if (!verifyEd25519(sigBytes, expectedDigest, expectedPk)) {
153
+ throw new Error(`Ed25519 signature verification failed for witness ${resp.witness_index}`);
154
+ }
155
+ if (!verifiedByIdx.has(resp.witness_index)) {
156
+ verifiedByIdx.set(resp.witness_index, sigBytes);
157
+ }
158
+ }
159
+ catch (err) {
160
+ failures.push({ endpoint, reason: formatError(err) });
161
+ }
162
+ }
163
+ const sortedIndices = Array.from(verifiedByIdx.keys()).sort((a, b) => a - b);
164
+ if (sortedIndices.length < params.witnessThreshold) {
165
+ const details = failures.map((f) => `${f.endpoint}: ${f.reason}`).join("; ");
166
+ throw new Error(`init-genesis quorum not reached: verified ${sortedIndices.length}/${params.witnessThreshold} witnesses` +
167
+ (details ? ` (${details})` : ""));
168
+ }
169
+ const genesisSigs = sortedIndices.map((index) => ({
170
+ index,
171
+ signature: verifiedByIdx.get(index),
172
+ }));
173
+ const cert0 = {
174
+ token: params.token.kind === "custom"
175
+ ? { kind: "custom", contractId: new Uint8Array(params.token.contractId) }
176
+ : params.token,
177
+ devicePubkey,
178
+ epochTotalDeposited: params.epochTotalDeposited,
179
+ exitDelaySecs,
180
+ syncedAtTs: targetTs,
181
+ syncedLedgerSeq: params.targetLedgerSeq,
182
+ witnessThreshold: params.witnessThreshold,
183
+ witnesses,
184
+ genesisSigs,
185
+ };
186
+ const cert0Bytes = encodeCert0Bytes(cert0);
187
+ const cert0Hex = encodeCert0Hex(cert0);
188
+ let propagatedCount = 0;
189
+ if (params.propagateCert0 !== false) {
190
+ const genesisSigsDto = genesisSigs.map((s) => ({
191
+ witness_index: s.index,
192
+ signature: bytesToHex(s.signature),
193
+ }));
194
+ const round2 = await Promise.allSettled(clients.map((client) => client.initGenesis({
195
+ vault_id: vaultStrKey,
196
+ pocket_id: params.pocketId,
197
+ epoch: params.epoch,
198
+ target_ledger_seq: params.targetLedgerSeq,
199
+ target_ts: targetTs,
200
+ cert_0: cert0Hex,
201
+ genesis_sigs: genesisSigsDto,
202
+ })));
203
+ for (const r of round2) {
204
+ if (r.status === "fulfilled") {
205
+ propagatedCount++;
206
+ }
207
+ }
208
+ }
209
+ return {
210
+ cert0,
211
+ cert0Bytes,
212
+ cert0Hex,
213
+ genesisDigest: expectedDigest,
214
+ syncedLedgerSeq: params.targetLedgerSeq,
215
+ syncedAtTs: targetTs,
216
+ verifiedWitnessIndices: sortedIndices,
217
+ propagatedCount,
218
+ failures,
219
+ };
220
+ }
221
+ /**
222
+ * Coordinate `POST /refresh-freshness` across a pocket's witnesses, cryptographically verifying
223
+ * each `"SMW1_FRESH"` signature, assembling a quorum `StoredFreshCertDto` (directly passable to
224
+ * `OfflineWallet.refreshAnchor`), and optionally propagating it back to all witnesses.
225
+ */
226
+ export async function coordinateRefreshFreshness(params) {
227
+ assertNetworkHint(params.networkHint);
228
+ assertU16(params.pocketId, "pocketId");
229
+ assertU32(params.epoch, "epoch");
230
+ if (params.epoch === 0)
231
+ throw new Error("epoch must be >= 1");
232
+ assertU32(params.targetLedgerSeq, "targetLedgerSeq");
233
+ if (params.targetLedgerSeq === 0)
234
+ throw new Error("targetLedgerSeq must be >= 1");
235
+ const targetTs = normalizeU64Ts(params.targetTs, "targetTs");
236
+ const vaultRaw = normalizeContractHash(params.vaultId);
237
+ const vaultStrKey = StellarSdk.StrKey.encodeContract(vaultRaw);
238
+ const witnesses = normalizeWitnessPubkeys(params.witnesses);
239
+ assertValidThreshold(params.witnessThreshold, witnesses.length);
240
+ const clients = resolveWitnessClients(params.witnessClients, params.witnessClientOptions);
241
+ const passphrase = params.networkPassphrase ?? networkPassphraseForHint(params.networkHint);
242
+ const networkId = networkIdFromPassphrase(passphrase);
243
+ const expectedDigest = computeFreshDigest({
244
+ networkId,
245
+ vaultId: vaultRaw,
246
+ pocketId: params.pocketId,
247
+ epoch: params.epoch,
248
+ syncedAtTs: targetTs,
249
+ syncedLedgerSeq: params.targetLedgerSeq,
250
+ });
251
+ const round1 = await Promise.allSettled(clients.map((client) => client.refreshFreshness({
252
+ vault_id: vaultStrKey,
253
+ pocket_id: params.pocketId,
254
+ epoch: params.epoch,
255
+ target_ledger_seq: params.targetLedgerSeq,
256
+ target_ts: targetTs,
257
+ })));
258
+ const verifiedByIdx = new Map();
259
+ const failures = [];
260
+ for (let i = 0; i < round1.length; i++) {
261
+ const outcome = round1[i];
262
+ const endpoint = clients[i].baseUrl;
263
+ if (outcome.status === "rejected") {
264
+ failures.push({ endpoint, reason: formatError(outcome.reason) });
265
+ continue;
266
+ }
267
+ const resp = outcome.value;
268
+ try {
269
+ if (!Number.isInteger(resp.witness_index) ||
270
+ resp.witness_index < 0 ||
271
+ resp.witness_index >= witnesses.length) {
272
+ throw new Error(`witness_index ${resp.witness_index} out of bounds`);
273
+ }
274
+ if (resp.synced_ledger_seq !== params.targetLedgerSeq) {
275
+ throw new Error(`synced_ledger_seq mismatch: expected ${params.targetLedgerSeq}, got ${resp.synced_ledger_seq}`);
276
+ }
277
+ if (!/^\d+$/.test(resp.synced_at_ts) || BigInt(resp.synced_at_ts) !== targetTs) {
278
+ throw new Error(`synced_at_ts mismatch: expected ${targetTs}, got "${resp.synced_at_ts}"`);
279
+ }
280
+ const returnedPk = normalizeFixedBytes(resp.witness_pubkey, 32, "witness_pubkey");
281
+ const expectedPk = witnesses[resp.witness_index];
282
+ if (!bytesEqual(returnedPk, expectedPk)) {
283
+ throw new Error(`witness_pubkey mismatch for index ${resp.witness_index}: returned ${bytesToHex(returnedPk)}`);
284
+ }
285
+ const returnedDigest = normalizeFixedBytes(resp.fresh_digest, 32, "fresh_digest");
286
+ if (!bytesEqual(returnedDigest, expectedDigest)) {
287
+ throw new Error("fresh_digest does not match canonical SMW1_FRESH digest");
288
+ }
289
+ const sigBytes = normalizeFixedBytes(resp.signature, 64, "signature");
290
+ if (!verifyEd25519(sigBytes, expectedDigest, expectedPk)) {
291
+ throw new Error(`Ed25519 signature verification failed for witness ${resp.witness_index}`);
292
+ }
293
+ if (!verifiedByIdx.has(resp.witness_index)) {
294
+ verifiedByIdx.set(resp.witness_index, sigBytes);
295
+ }
296
+ }
297
+ catch (err) {
298
+ failures.push({ endpoint, reason: formatError(err) });
299
+ }
300
+ }
301
+ const sortedIndices = Array.from(verifiedByIdx.keys()).sort((a, b) => a - b);
302
+ if (sortedIndices.length < params.witnessThreshold) {
303
+ const details = failures.map((f) => `${f.endpoint}: ${f.reason}`).join("; ");
304
+ throw new Error(`refresh-freshness quorum not reached: verified ${sortedIndices.length}/${params.witnessThreshold} witnesses` +
305
+ (details ? ` (${details})` : ""));
306
+ }
307
+ const freshCert = {
308
+ synced_at_ts: targetTs.toString(10),
309
+ synced_ledger_seq: params.targetLedgerSeq,
310
+ fresh_digest: bytesToHex(expectedDigest),
311
+ sigs: sortedIndices.map((index) => ({
312
+ witness_index: index,
313
+ signature: bytesToHex(verifiedByIdx.get(index)),
314
+ })),
315
+ };
316
+ let propagatedCount = 0;
317
+ if (params.propagateFreshCert !== false) {
318
+ const round2 = await Promise.allSettled(clients.map((client) => client.refreshFreshness({
319
+ vault_id: vaultStrKey,
320
+ pocket_id: params.pocketId,
321
+ epoch: params.epoch,
322
+ target_ledger_seq: params.targetLedgerSeq,
323
+ target_ts: targetTs,
324
+ fresh_cert: freshCert,
325
+ })));
326
+ for (const r of round2) {
327
+ if (r.status === "fulfilled") {
328
+ propagatedCount++;
329
+ }
330
+ }
331
+ }
332
+ return {
333
+ freshCert,
334
+ freshDigest: expectedDigest,
335
+ syncedLedgerSeq: params.targetLedgerSeq,
336
+ syncedAtTs: targetTs,
337
+ verifiedWitnessIndices: sortedIndices,
338
+ propagatedCount,
339
+ failures,
340
+ };
341
+ }
342
+ /**
343
+ * Coordinate `POST /close-cooperative` across a pocket's witnesses, verifying each `"SMW1_CLOSE"`
344
+ * witness signature and returning sorted `witnessSigs` ready for `buildClosePocketCooperativeOp`.
345
+ */
346
+ export async function coordinateCloseCooperative(params) {
347
+ assertNetworkHint(params.networkHint);
348
+ assertU16(params.pocketId, "pocketId");
349
+ assertU32(params.epoch, "epoch");
350
+ if (params.epoch === 0)
351
+ throw new Error("epoch must be >= 1");
352
+ const vaultRaw = normalizeContractHash(params.vaultId);
353
+ const vaultStrKey = StellarSdk.StrKey.encodeContract(vaultRaw);
354
+ const witnesses = normalizeWitnessPubkeys(params.witnesses);
355
+ assertValidThreshold(params.witnessThreshold, witnesses.length);
356
+ const clients = resolveWitnessClients(params.witnessClients, params.witnessClientOptions);
357
+ let ownerStrKey;
358
+ if (params.owner !== undefined) {
359
+ if (typeof params.owner === "string") {
360
+ assertNotMuxedStrKey(params.owner);
361
+ ownerStrKey = wireAddressToStrKey(strKeyToWireAddress(params.owner));
362
+ }
363
+ else {
364
+ assertValidWireAddress(params.owner);
365
+ ownerStrKey = wireAddressToStrKey(params.owner);
366
+ }
367
+ }
368
+ const passphrase = params.networkPassphrase ?? networkPassphraseForHint(params.networkHint);
369
+ const networkId = networkIdFromPassphrase(passphrase);
370
+ const closeDigest = computeCloseDigest({
371
+ networkId,
372
+ vaultId: vaultRaw,
373
+ pocketId: params.pocketId,
374
+ epoch: params.epoch,
375
+ });
376
+ let ownerSigHex;
377
+ if (params.ownerSig !== undefined) {
378
+ ownerSigHex = bytesToHex(normalizeFixedBytes(params.ownerSig, 64, "ownerSig"));
379
+ }
380
+ else if (params.ownerSecretKey !== undefined) {
381
+ assertBytesLength(params.ownerSecretKey, 32, "ownerSecretKey");
382
+ ownerSigHex = bytesToHex(signEd25519(closeDigest, params.ownerSecretKey));
383
+ }
384
+ let deviceSigHex;
385
+ if (params.deviceSig !== undefined) {
386
+ deviceSigHex = bytesToHex(normalizeFixedBytes(params.deviceSig, 64, "deviceSig"));
387
+ }
388
+ else if (params.deviceSecretKey !== undefined) {
389
+ assertBytesLength(params.deviceSecretKey, 32, "deviceSecretKey");
390
+ deviceSigHex = bytesToHex(signEd25519(closeDigest, params.deviceSecretKey));
391
+ }
392
+ if (ownerSigHex === undefined && deviceSigHex === undefined) {
393
+ throw new Error("coordinateCloseCooperative requires ownerSecretKey/ownerSig (G... owner) or deviceSecretKey/deviceSig (C... owner)");
394
+ }
395
+ const outcomes = await Promise.allSettled(clients.map((client) => client.closeCooperative({
396
+ vault_id: vaultStrKey,
397
+ pocket_id: params.pocketId,
398
+ epoch: params.epoch,
399
+ ...(ownerStrKey !== undefined ? { owner: ownerStrKey } : {}),
400
+ ...(ownerSigHex !== undefined ? { owner_sig: ownerSigHex } : {}),
401
+ ...(deviceSigHex !== undefined ? { device_sig: deviceSigHex } : {}),
402
+ ...(params.latestCert !== undefined ? { latest_cert: params.latestCert } : {}),
403
+ })));
404
+ const verifiedByIdx = new Map();
405
+ const failures = [];
406
+ for (let i = 0; i < outcomes.length; i++) {
407
+ const outcome = outcomes[i];
408
+ const endpoint = clients[i].baseUrl;
409
+ if (outcome.status === "rejected") {
410
+ failures.push({ endpoint, reason: formatError(outcome.reason) });
411
+ continue;
412
+ }
413
+ const resp = outcome.value;
414
+ try {
415
+ if (!Number.isInteger(resp.witness_index) ||
416
+ resp.witness_index < 0 ||
417
+ resp.witness_index >= witnesses.length) {
418
+ throw new Error(`witness_index ${resp.witness_index} out of bounds`);
419
+ }
420
+ const returnedPk = normalizeFixedBytes(resp.witness_pubkey, 32, "witness_pubkey");
421
+ const expectedPk = witnesses[resp.witness_index];
422
+ if (!bytesEqual(returnedPk, expectedPk)) {
423
+ throw new Error(`witness_pubkey mismatch for index ${resp.witness_index}: returned ${bytesToHex(returnedPk)}`);
424
+ }
425
+ const returnedDigest = normalizeFixedBytes(resp.close_digest, 32, "close_digest");
426
+ if (!bytesEqual(returnedDigest, closeDigest)) {
427
+ throw new Error("close_digest does not match canonical SMW1_CLOSE digest");
428
+ }
429
+ const sigBytes = normalizeFixedBytes(resp.signature, 64, "signature");
430
+ if (!verifyEd25519(sigBytes, closeDigest, expectedPk)) {
431
+ throw new Error(`Ed25519 signature verification failed for witness ${resp.witness_index}`);
432
+ }
433
+ if (!verifiedByIdx.has(resp.witness_index)) {
434
+ verifiedByIdx.set(resp.witness_index, sigBytes);
435
+ }
436
+ }
437
+ catch (err) {
438
+ failures.push({ endpoint, reason: formatError(err) });
439
+ }
440
+ }
441
+ const sortedIndices = Array.from(verifiedByIdx.keys()).sort((a, b) => a - b);
442
+ if (sortedIndices.length < params.witnessThreshold) {
443
+ const details = failures.map((f) => `${f.endpoint}: ${f.reason}`).join("; ");
444
+ throw new Error(`close-cooperative quorum not reached: verified ${sortedIndices.length}/${params.witnessThreshold} witnesses` +
445
+ (details ? ` (${details})` : ""));
446
+ }
447
+ const witnessSigs = sortedIndices.map((index) => ({
448
+ index,
449
+ signature: verifiedByIdx.get(index),
450
+ }));
451
+ return {
452
+ closeDigest,
453
+ witnessSigs,
454
+ verifiedWitnessIndices: sortedIndices,
455
+ failures,
456
+ };
457
+ }