@outpost-protocol/core 0.1.1 → 0.2.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,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
+ }
package/dist/index.d.ts CHANGED
@@ -5,8 +5,12 @@ export * from "./vault.js";
5
5
  export * from "./digest.js";
6
6
  export * from "./bcur.js";
7
7
  export * from "./wire.js";
8
+ export * from "./cert0.js";
9
+ export * from "./contracts.js";
8
10
  export * from "./relayDirect.js";
9
11
  export * from "./feeBump.js";
10
12
  export * from "./wallet.js";
13
+ export * from "./walletStorage.js";
11
14
  export * from "./witnessClient.js";
15
+ export * from "./coordinators.js";
12
16
  export * from "./bleTransport.js";
package/dist/index.js CHANGED
@@ -5,8 +5,12 @@ export * from "./vault.js";
5
5
  export * from "./digest.js";
6
6
  export * from "./bcur.js";
7
7
  export * from "./wire.js";
8
+ export * from "./cert0.js";
9
+ export * from "./contracts.js";
8
10
  export * from "./relayDirect.js";
9
11
  export * from "./feeBump.js";
10
12
  export * from "./wallet.js";
13
+ export * from "./walletStorage.js";
11
14
  export * from "./witnessClient.js";
15
+ export * from "./coordinators.js";
12
16
  export * from "./bleTransport.js";
package/dist/wallet.d.ts CHANGED
@@ -56,6 +56,15 @@ export interface PocketRecord {
56
56
  readonly exitDelaySecs: bigint;
57
57
  readonly anchor: DepositAnchor;
58
58
  readonly localSeq: number;
59
+ /** Running worst-case cumulative spend (`sum(amount + maxTip)`) burned in this epoch (`0.2.0`). */
60
+ readonly estimatedSpent?: bigint;
61
+ }
62
+ export interface PocketBudget {
63
+ readonly pocketKey: string;
64
+ readonly epochTotalDeposited: bigint;
65
+ readonly estimatedSpent: bigint;
66
+ readonly remainingBudget: bigint;
67
+ readonly localSeq: number;
59
68
  }
60
69
  export interface SignedOrderRecord {
61
70
  readonly pocketKey: string;
@@ -78,14 +87,20 @@ export interface WalletStorage {
78
87
  getPocket(pocketKey: string): Promise<PocketRecord | undefined>;
79
88
  savePocket(pocketKey: string, record: PocketRecord): Promise<void>;
80
89
  /**
81
- * Atomically increment `localSeq += 1` and durably persist BEFORE returning the burned `seq`.
90
+ * Atomically increment `localSeq += 1` (and optionally add `costDelta` to `estimatedSpent`)
91
+ * and durably persist BEFORE returning the burned `seq`.
82
92
  */
83
- burnNextSeq(pocketKey: string): Promise<number>;
93
+ burnNextSeq(pocketKey: string, costDelta?: bigint): Promise<number>;
84
94
  /**
85
95
  * Atomically advance `localSeq` to `newSeq` (strictly monotonic: `newSeq > current.localSeq`)
86
96
  * and durably persist before returning `newSeq`.
87
97
  */
88
98
  advanceSeq(pocketKey: string, newSeq: number): Promise<number>;
99
+ /**
100
+ * Optional monotonic update advancing `estimatedSpent = max(estimatedSpent, cumulativeSpent)`
101
+ * (e.g., after verifying a `latestCert` during `resyncFromLatestCert`).
102
+ */
103
+ syncEstimatedSpent?(pocketKey: string, cumulativeSpent: bigint): Promise<bigint>;
89
104
  /**
90
105
  * Atomically update the pocket's L1 freshness anchor (monotonic ledger & timestamp).
91
106
  */
@@ -104,7 +119,7 @@ export interface WalletStorage {
104
119
  export interface InMemoryWalletStorageOptions {
105
120
  /** Optional lifecycle hook invoked on every durable write (useful for burn-before-display tests). */
106
121
  readonly onPersist?: (event: {
107
- readonly op: "savePocket" | "burnNextSeq" | "advanceSeq" | "updateAnchor" | "saveSignedOrder";
122
+ readonly op: "savePocket" | "burnNextSeq" | "advanceSeq" | "syncEstimatedSpent" | "updateAnchor" | "saveSignedOrder";
108
123
  readonly pocketKey: string;
109
124
  readonly localSeq: number;
110
125
  }) => void;
@@ -121,8 +136,17 @@ export declare class InMemoryWalletStorage implements WalletStorage {
121
136
  constructor(options?: InMemoryWalletStorageOptions);
122
137
  getPocket(pocketKey: string): Promise<PocketRecord | undefined>;
123
138
  savePocket(pocketKey: string, record: PocketRecord): Promise<void>;
124
- burnNextSeq(pocketKey: string): Promise<number>;
139
+ burnNextSeq(pocketKey: string, costDelta?: bigint): Promise<number>;
125
140
  advanceSeq(pocketKey: string, newSeq: number): Promise<number>;
141
+ syncEstimatedSpent(pocketKey: string, cumulativeSpent: bigint): Promise<bigint>;
142
+ exportSnapshot(): {
143
+ readonly pockets: Readonly<Record<string, PocketRecord>>;
144
+ readonly signedOrders: readonly SignedOrderRecord[];
145
+ };
146
+ importSnapshot(snapshot: {
147
+ readonly pockets: Readonly<Record<string, PocketRecord>>;
148
+ readonly signedOrders: readonly SignedOrderRecord[];
149
+ }): void;
126
150
  updateAnchor(pocketKey: string, anchor: DepositAnchor): Promise<void>;
127
151
  listPocketKeys(): Promise<string[]>;
128
152
  getSignedOrder(pocketKey: string, recipientStrKey: string, orderId: bigint): Promise<SignedOrderRecord | undefined>;
@@ -163,6 +187,8 @@ export interface RegisterPocketParams {
163
187
  readonly exitDelaySecs: bigint;
164
188
  readonly anchor: DepositAnchor;
165
189
  readonly initialSeq?: number;
190
+ /** Optional starting running spent total (`0n..=epochTotalDeposited`, default `0n`). */
191
+ readonly initialEstimatedSpent?: bigint;
166
192
  }
167
193
  export interface SignVaultIntentParams {
168
194
  readonly pocketKey: string;
@@ -216,6 +242,11 @@ export interface SignVaultIntentParams {
216
242
  readonly tokenResolver?: TokenResolver;
217
243
  /** Optional hook executed right before cryptographic signing (after seq burn) for testing. */
218
244
  readonly beforeSignHook?: (burnedSeq: number) => void;
245
+ /**
246
+ * Opt-out escape hatch to bypass running `estimatedSpent + amount + maxTip <= epochTotalDeposited`
247
+ * enforcement (default `false` — running budget enforcement is ON by default).
248
+ */
249
+ readonly skipSpentBudgetCheck?: boolean;
219
250
  }
220
251
  export interface SignedVaultIntentResult {
221
252
  readonly seq: number;
@@ -259,12 +290,16 @@ export declare class OfflineWallet {
259
290
  private readonly tokenResolver;
260
291
  private readonly defaultClockCone;
261
292
  private readonly fallbackSignedOrders;
293
+ /** Bounded fallback spent tracker for legacy custom WalletStorage adapters ignoring burnNextSeq's costDelta. */
294
+ private readonly fallbackEstimatedSpent;
262
295
  /** R5-H13: Per-pocket FIFO async mutex serializing registerPocket, signVaultIntent, resyncFromLatestCert, and refreshAnchor. */
263
296
  private readonly pocketLocks;
264
297
  constructor(storage: WalletStorage, tokenResolverOrOptions?: TokenResolver | OfflineWalletOptions);
265
298
  private withPocketLock;
266
299
  private lookupSignedOrder;
267
300
  private persistSignedOrder;
301
+ private effectiveEstimatedSpent;
302
+ private setFallbackEstimatedSpent;
268
303
  /**
269
304
  * Register an onboarded `UserVault` pocket into atomic wallet storage.
270
305
  * Performs 0-RPC 108-byte `VaultFactory` vault ID derivation and validates all invariants.
@@ -274,6 +309,10 @@ export declare class OfflineWallet {
274
309
  record: PocketRecord;
275
310
  }>;
276
311
  getPocket(pocketKey: string): Promise<PocketRecord | undefined>;
312
+ /**
313
+ * Return the current running spend budget for a registered pocket.
314
+ */
315
+ getPocketBudget(pocketKey: string): Promise<PocketBudget>;
277
316
  /**
278
317
  * Cryptographically verify a `t`-of-`n` witness-signed `"SMW1_FRESH"` checkpoint and
279
318
  * monotonically advance the pocket's local L1 anchor via `storage.updateAnchor` (`M-NEW-5`).