@did-btcr2/aggregation 0.1.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.
Files changed (233) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +19 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/browser.js +24017 -0
  5. package/dist/browser.mjs +24011 -0
  6. package/dist/cjs/index.js +5690 -0
  7. package/dist/cjs/package.json +1 -0
  8. package/dist/esm/beacon-strategy.js +76 -0
  9. package/dist/esm/beacon-strategy.js.map +1 -0
  10. package/dist/esm/cohort.js +316 -0
  11. package/dist/esm/cohort.js.map +1 -0
  12. package/dist/esm/conditions.js +102 -0
  13. package/dist/esm/conditions.js.map +1 -0
  14. package/dist/esm/errors.js +22 -0
  15. package/dist/esm/errors.js.map +1 -0
  16. package/dist/esm/fallback-spend.js +132 -0
  17. package/dist/esm/fallback-spend.js.map +1 -0
  18. package/dist/esm/index.js +21 -0
  19. package/dist/esm/index.js.map +1 -0
  20. package/dist/esm/logger.js +15 -0
  21. package/dist/esm/logger.js.map +1 -0
  22. package/dist/esm/messages/base.js +36 -0
  23. package/dist/esm/messages/base.js.map +1 -0
  24. package/dist/esm/messages/bodies.js +149 -0
  25. package/dist/esm/messages/bodies.js.map +1 -0
  26. package/dist/esm/messages/constants.js +37 -0
  27. package/dist/esm/messages/constants.js.map +1 -0
  28. package/dist/esm/messages/factories.js +139 -0
  29. package/dist/esm/messages/factories.js.map +1 -0
  30. package/dist/esm/messages/guards.js +40 -0
  31. package/dist/esm/messages/guards.js.map +1 -0
  32. package/dist/esm/messages/index.js +6 -0
  33. package/dist/esm/messages/index.js.map +1 -0
  34. package/dist/esm/participant.js +588 -0
  35. package/dist/esm/participant.js.map +1 -0
  36. package/dist/esm/phases.js +45 -0
  37. package/dist/esm/phases.js.map +1 -0
  38. package/dist/esm/recovery-policy.js +156 -0
  39. package/dist/esm/recovery-policy.js.map +1 -0
  40. package/dist/esm/recovery-spend.js +106 -0
  41. package/dist/esm/recovery-spend.js.map +1 -0
  42. package/dist/esm/runner/aggregation-runner.js +75 -0
  43. package/dist/esm/runner/aggregation-runner.js.map +1 -0
  44. package/dist/esm/runner/events.js +2 -0
  45. package/dist/esm/runner/events.js.map +1 -0
  46. package/dist/esm/runner/index.js +6 -0
  47. package/dist/esm/runner/index.js.map +1 -0
  48. package/dist/esm/runner/participant-runner.js +407 -0
  49. package/dist/esm/runner/participant-runner.js.map +1 -0
  50. package/dist/esm/runner/service-runner.js +701 -0
  51. package/dist/esm/runner/service-runner.js.map +1 -0
  52. package/dist/esm/runner/typed-emitter.js +80 -0
  53. package/dist/esm/runner/typed-emitter.js.map +1 -0
  54. package/dist/esm/service.js +774 -0
  55. package/dist/esm/service.js.map +1 -0
  56. package/dist/esm/signer.js +33 -0
  57. package/dist/esm/signer.js.map +1 -0
  58. package/dist/esm/signing-session.js +195 -0
  59. package/dist/esm/signing-session.js.map +1 -0
  60. package/dist/esm/transport/didcomm.js +41 -0
  61. package/dist/esm/transport/didcomm.js.map +1 -0
  62. package/dist/esm/transport/error.js +12 -0
  63. package/dist/esm/transport/error.js.map +1 -0
  64. package/dist/esm/transport/factory.js +29 -0
  65. package/dist/esm/transport/factory.js.map +1 -0
  66. package/dist/esm/transport/http/client.js +342 -0
  67. package/dist/esm/transport/http/client.js.map +1 -0
  68. package/dist/esm/transport/http/envelope.js +126 -0
  69. package/dist/esm/transport/http/envelope.js.map +1 -0
  70. package/dist/esm/transport/http/errors.js +11 -0
  71. package/dist/esm/transport/http/errors.js.map +1 -0
  72. package/dist/esm/transport/http/inbox-buffer.js +45 -0
  73. package/dist/esm/transport/http/inbox-buffer.js.map +1 -0
  74. package/dist/esm/transport/http/index.js +12 -0
  75. package/dist/esm/transport/http/index.js.map +1 -0
  76. package/dist/esm/transport/http/nonce-cache.js +38 -0
  77. package/dist/esm/transport/http/nonce-cache.js.map +1 -0
  78. package/dist/esm/transport/http/protocol.js +28 -0
  79. package/dist/esm/transport/http/protocol.js.map +1 -0
  80. package/dist/esm/transport/http/rate-limiter.js +45 -0
  81. package/dist/esm/transport/http/rate-limiter.js.map +1 -0
  82. package/dist/esm/transport/http/request-auth.js +100 -0
  83. package/dist/esm/transport/http/request-auth.js.map +1 -0
  84. package/dist/esm/transport/http/server.js +475 -0
  85. package/dist/esm/transport/http/server.js.map +1 -0
  86. package/dist/esm/transport/http/sse-stream.js +110 -0
  87. package/dist/esm/transport/http/sse-stream.js.map +1 -0
  88. package/dist/esm/transport/http/sse-writer.js +25 -0
  89. package/dist/esm/transport/http/sse-writer.js.map +1 -0
  90. package/dist/esm/transport/in-memory.js +149 -0
  91. package/dist/esm/transport/in-memory.js.map +1 -0
  92. package/dist/esm/transport/index.js +8 -0
  93. package/dist/esm/transport/index.js.map +1 -0
  94. package/dist/esm/transport/nostr.js +491 -0
  95. package/dist/esm/transport/nostr.js.map +1 -0
  96. package/dist/esm/transport/transport.js +2 -0
  97. package/dist/esm/transport/transport.js.map +1 -0
  98. package/dist/types/beacon-strategy.d.ts +56 -0
  99. package/dist/types/beacon-strategy.d.ts.map +1 -0
  100. package/dist/types/cohort.d.ts +188 -0
  101. package/dist/types/cohort.d.ts.map +1 -0
  102. package/dist/types/conditions.d.ts +86 -0
  103. package/dist/types/conditions.d.ts.map +1 -0
  104. package/dist/types/errors.d.ts +14 -0
  105. package/dist/types/errors.d.ts.map +1 -0
  106. package/dist/types/fallback-spend.d.ts +94 -0
  107. package/dist/types/fallback-spend.d.ts.map +1 -0
  108. package/dist/types/index.d.ts +17 -0
  109. package/dist/types/index.d.ts.map +1 -0
  110. package/dist/types/logger.d.ts +22 -0
  111. package/dist/types/logger.d.ts.map +1 -0
  112. package/dist/types/messages/base.d.ts +58 -0
  113. package/dist/types/messages/base.d.ts.map +1 -0
  114. package/dist/types/messages/bodies.d.ts +177 -0
  115. package/dist/types/messages/bodies.d.ts.map +1 -0
  116. package/dist/types/messages/constants.d.ts +31 -0
  117. package/dist/types/messages/constants.d.ts.map +1 -0
  118. package/dist/types/messages/factories.d.ts +217 -0
  119. package/dist/types/messages/factories.d.ts.map +1 -0
  120. package/dist/types/messages/guards.d.ts +11 -0
  121. package/dist/types/messages/guards.d.ts.map +1 -0
  122. package/dist/types/messages/index.d.ts +6 -0
  123. package/dist/types/messages/index.d.ts.map +1 -0
  124. package/dist/types/participant.d.ts +162 -0
  125. package/dist/types/participant.d.ts.map +1 -0
  126. package/dist/types/phases.d.ts +55 -0
  127. package/dist/types/phases.d.ts.map +1 -0
  128. package/dist/types/recovery-policy.d.ts +132 -0
  129. package/dist/types/recovery-policy.d.ts.map +1 -0
  130. package/dist/types/recovery-spend.d.ts +94 -0
  131. package/dist/types/recovery-spend.d.ts.map +1 -0
  132. package/dist/types/runner/aggregation-runner.d.ts +72 -0
  133. package/dist/types/runner/aggregation-runner.d.ts.map +1 -0
  134. package/dist/types/runner/events.d.ts +147 -0
  135. package/dist/types/runner/events.d.ts.map +1 -0
  136. package/dist/types/runner/index.d.ts +6 -0
  137. package/dist/types/runner/index.d.ts.map +1 -0
  138. package/dist/types/runner/participant-runner.d.ts +122 -0
  139. package/dist/types/runner/participant-runner.d.ts.map +1 -0
  140. package/dist/types/runner/service-runner.d.ts +228 -0
  141. package/dist/types/runner/service-runner.d.ts.map +1 -0
  142. package/dist/types/runner/typed-emitter.d.ts +41 -0
  143. package/dist/types/runner/typed-emitter.d.ts.map +1 -0
  144. package/dist/types/service.d.ts +177 -0
  145. package/dist/types/service.d.ts.map +1 -0
  146. package/dist/types/signer.d.ts +50 -0
  147. package/dist/types/signer.d.ts.map +1 -0
  148. package/dist/types/signing-session.d.ts +81 -0
  149. package/dist/types/signing-session.d.ts.map +1 -0
  150. package/dist/types/transport/didcomm.d.ts +23 -0
  151. package/dist/types/transport/didcomm.d.ts.map +1 -0
  152. package/dist/types/transport/error.d.ts +8 -0
  153. package/dist/types/transport/error.d.ts.map +1 -0
  154. package/dist/types/transport/factory.d.ts +28 -0
  155. package/dist/types/transport/factory.d.ts.map +1 -0
  156. package/dist/types/transport/http/client.d.ts +56 -0
  157. package/dist/types/transport/http/client.d.ts.map +1 -0
  158. package/dist/types/transport/http/envelope.d.ts +64 -0
  159. package/dist/types/transport/http/envelope.d.ts.map +1 -0
  160. package/dist/types/transport/http/errors.d.ts +9 -0
  161. package/dist/types/transport/http/errors.d.ts.map +1 -0
  162. package/dist/types/transport/http/inbox-buffer.d.ts +32 -0
  163. package/dist/types/transport/http/inbox-buffer.d.ts.map +1 -0
  164. package/dist/types/transport/http/index.d.ts +12 -0
  165. package/dist/types/transport/http/index.d.ts.map +1 -0
  166. package/dist/types/transport/http/nonce-cache.d.ts +26 -0
  167. package/dist/types/transport/http/nonce-cache.d.ts.map +1 -0
  168. package/dist/types/transport/http/protocol.d.ts +53 -0
  169. package/dist/types/transport/http/protocol.d.ts.map +1 -0
  170. package/dist/types/transport/http/rate-limiter.d.ts +41 -0
  171. package/dist/types/transport/http/rate-limiter.d.ts.map +1 -0
  172. package/dist/types/transport/http/request-auth.d.ts +50 -0
  173. package/dist/types/transport/http/request-auth.d.ts.map +1 -0
  174. package/dist/types/transport/http/server.d.ts +118 -0
  175. package/dist/types/transport/http/server.d.ts.map +1 -0
  176. package/dist/types/transport/http/sse-stream.d.ts +34 -0
  177. package/dist/types/transport/http/sse-stream.d.ts.map +1 -0
  178. package/dist/types/transport/http/sse-writer.d.ts +12 -0
  179. package/dist/types/transport/http/sse-writer.d.ts.map +1 -0
  180. package/dist/types/transport/in-memory.d.ts +64 -0
  181. package/dist/types/transport/in-memory.d.ts.map +1 -0
  182. package/dist/types/transport/index.d.ts +8 -0
  183. package/dist/types/transport/index.d.ts.map +1 -0
  184. package/dist/types/transport/nostr.d.ts +153 -0
  185. package/dist/types/transport/nostr.d.ts.map +1 -0
  186. package/dist/types/transport/transport.d.ts +62 -0
  187. package/dist/types/transport/transport.d.ts.map +1 -0
  188. package/package.json +128 -0
  189. package/src/beacon-strategy.ts +142 -0
  190. package/src/cohort.ts +422 -0
  191. package/src/conditions.ts +172 -0
  192. package/src/errors.ts +25 -0
  193. package/src/fallback-spend.ts +223 -0
  194. package/src/index.ts +23 -0
  195. package/src/logger.ts +33 -0
  196. package/src/messages/base.ts +80 -0
  197. package/src/messages/bodies.ts +328 -0
  198. package/src/messages/constants.ts +40 -0
  199. package/src/messages/factories.ts +297 -0
  200. package/src/messages/guards.ts +61 -0
  201. package/src/messages/index.ts +5 -0
  202. package/src/participant.ts +779 -0
  203. package/src/phases.ts +91 -0
  204. package/src/recovery-policy.ts +237 -0
  205. package/src/recovery-spend.ts +192 -0
  206. package/src/runner/aggregation-runner.ts +125 -0
  207. package/src/runner/events.ts +129 -0
  208. package/src/runner/index.ts +5 -0
  209. package/src/runner/participant-runner.ts +488 -0
  210. package/src/runner/service-runner.ts +891 -0
  211. package/src/runner/typed-emitter.ts +87 -0
  212. package/src/service.ts +1000 -0
  213. package/src/signer.ts +67 -0
  214. package/src/signing-session.ts +290 -0
  215. package/src/transport/didcomm.ts +59 -0
  216. package/src/transport/error.ts +13 -0
  217. package/src/transport/factory.ts +65 -0
  218. package/src/transport/http/client.ts +409 -0
  219. package/src/transport/http/envelope.ts +204 -0
  220. package/src/transport/http/errors.ts +11 -0
  221. package/src/transport/http/inbox-buffer.ts +53 -0
  222. package/src/transport/http/index.ts +11 -0
  223. package/src/transport/http/nonce-cache.ts +43 -0
  224. package/src/transport/http/protocol.ts +57 -0
  225. package/src/transport/http/rate-limiter.ts +75 -0
  226. package/src/transport/http/request-auth.ts +164 -0
  227. package/src/transport/http/server.ts +617 -0
  228. package/src/transport/http/sse-stream.ts +121 -0
  229. package/src/transport/http/sse-writer.ts +23 -0
  230. package/src/transport/in-memory.ts +178 -0
  231. package/src/transport/index.ts +7 -0
  232. package/src/transport/nostr.ts +576 -0
  233. package/src/transport/transport.ts +79 -0
@@ -0,0 +1,701 @@
1
+ var _a;
2
+ import { AggregationServiceError } from '../errors.js';
3
+ import { COHORT_OPT_IN, FALLBACK_SIGNATURE, NONCE_CONTRIBUTION, SIGNATURE_AUTHORIZATION, SUBMIT_NONINCLUDED, SUBMIT_UPDATE, VALIDATION_ACK, } from '../messages/constants.js';
4
+ import { ServiceCohortPhase } from '../phases.js';
5
+ import { AggregationService } from '../service.js';
6
+ import { StaticFeeEstimator } from '@did-btcr2/bitcoin';
7
+ import { TypedEventEmitter } from './typed-emitter.js';
8
+ /** Default fee estimator the runner uses when a caller supplies none: a static 5 sat/vB rate. */
9
+ const DEFAULT_FEE_ESTIMATOR = new StaticFeeEstimator(5);
10
+ /** Default cadence for re-publishing COHORT_ADVERT until keygen completes: 60 seconds. */
11
+ export const DEFAULT_ADVERT_REPEAT_INTERVAL_MS = 60_000;
12
+ /**
13
+ * High-level facade for running an Aggregation Service over a Transport.
14
+ *
15
+ * Wires the {@link AggregationService} state machine to a {@link Transport},
16
+ * encapsulating message handler registration, outgoing message dispatch,
17
+ * and decision callback orchestration.
18
+ *
19
+ * A single runner is a long-lived multiplexer: it advertises and drives many
20
+ * cohorts concurrently over one transport. Each advertised cohort owns an
21
+ * independent completion promise and fails in isolation - a stalled or failed
22
+ * cohort never settles its siblings (see ADR 040). Use
23
+ * {@link AggregationServiceRunner.advertiseCohort} for the multi-cohort path;
24
+ * {@link AggregationServiceRunner.run} is a thin single-cohort convenience over
25
+ * it.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const transport = new NostrTransport({ relays: [RELAY] });
30
+ * transport.registerActor(serviceDid, serviceKeys);
31
+ *
32
+ * const runner = new AggregationServiceRunner({
33
+ * transport,
34
+ * did: serviceDid,
35
+ * keys: serviceKeys,
36
+ * onProvideTxData: async ({ beaconAddress, signalBytes, feeEstimator }) => {
37
+ * // Forward feeEstimator so a dynamic rate injected at the runner is honored.
38
+ * return await buildBeaconTransaction(beaconAddress, signalBytes, bitcoin, feeEstimator);
39
+ * },
40
+ * });
41
+ *
42
+ * runner.on('keygen-complete', ({ cohortId, beaconAddress }) => console.log(beaconAddress));
43
+ * runner.on('signing-complete', ({ cohortId, signature }) => console.log('done', cohortId));
44
+ *
45
+ * // Multi-cohort: advertise several cohorts; each completion resolves independently.
46
+ * const a = runner.advertiseCohort({ minParticipants: 2, network: 'mutinynet', beaconType: 'CASBeacon' });
47
+ * const b = runner.advertiseCohort({ minParticipants: 3, network: 'mutinynet', beaconType: 'SMTBeacon' });
48
+ * const [ra, rb] = await Promise.all([a.completion, b.completion]);
49
+ *
50
+ * // Single-cohort convenience (requires `config` in the options):
51
+ * // const result = await runner.run();
52
+ * ```
53
+ *
54
+ * For full manual control, drop down to the underlying state machine via
55
+ * `runner.session`. The state machine has no transport coupling and exposes
56
+ * every protocol decision as an explicit method.
57
+ *
58
+ * @class AggregationServiceRunner
59
+ */
60
+ export class AggregationServiceRunner extends TypedEventEmitter {
61
+ /** Direct access to the underlying state machine for advanced use. */
62
+ session;
63
+ #transport;
64
+ #did;
65
+ #defaultConfig;
66
+ #onOptInReceived;
67
+ #onReadyToFinalize;
68
+ #onProvideTxData;
69
+ #feeEstimator;
70
+ #cohortTtlMs;
71
+ #phaseTimeoutMs;
72
+ #advertRepeatIntervalMs;
73
+ #autoFallbackOnStall;
74
+ /** Phases during which a stall can be salvaged by the k-of-n fallback (ADR 042). */
75
+ static #SIGNING_PHASES = [
76
+ ServiceCohortPhase.SigningStarted,
77
+ ServiceCohortPhase.NoncesCollected,
78
+ ServiceCohortPhase.AwaitingPartialSigs,
79
+ ];
80
+ /** Per-cohort run state, keyed by cohortId. */
81
+ #contexts = new Map();
82
+ #handlersRegistered = false;
83
+ #stopped = false;
84
+ constructor(options) {
85
+ super();
86
+ this.#transport = options.transport;
87
+ this.#did = options.did;
88
+ this.#defaultConfig = options.config;
89
+ this.#onOptInReceived = options.onOptInReceived ?? (async () => ({ accepted: true }));
90
+ this.#onReadyToFinalize = options.onReadyToFinalize ?? (async ({ acceptedCount, minRequired }) => ({
91
+ finalize: acceptedCount >= minRequired,
92
+ }));
93
+ this.#onProvideTxData = options.onProvideTxData;
94
+ this.#feeEstimator = options.feeEstimator ?? DEFAULT_FEE_ESTIMATOR;
95
+ this.#cohortTtlMs = options.cohortTtlMs;
96
+ this.#phaseTimeoutMs = options.phaseTimeoutMs;
97
+ this.#advertRepeatIntervalMs = options.advertRepeatIntervalMs ?? DEFAULT_ADVERT_REPEAT_INTERVAL_MS;
98
+ this.#autoFallbackOnStall = options.autoFallbackOnStall ?? false;
99
+ this.session = new AggregationService({
100
+ // The coordinator never signs, so the state machine receives only the
101
+ // public half of the operator's keypair (see ADR 038). The full keypair
102
+ // remains the operator's transport/communication identity.
103
+ did: options.did,
104
+ publicKey: options.keys.publicKey,
105
+ maxUpdateSizeBytes: options.maxUpdateSizeBytes,
106
+ });
107
+ }
108
+ /** Resolve the {@link RunContext} an inbound message belongs to, by cohortId. */
109
+ #contextFor(msg) {
110
+ const cohortId = msg.body?.cohortId;
111
+ if (!cohortId)
112
+ return undefined;
113
+ return this.#contexts.get(cohortId);
114
+ }
115
+ /**
116
+ * Drain any silent rejections the state machine recorded for a cohort during
117
+ * the most recent receive() and surface them as `message-rejected` events.
118
+ */
119
+ #drainRejections(ctx) {
120
+ for (const r of this.session.drainRejections(ctx.cohortId)) {
121
+ this.emit('message-rejected', { cohortId: ctx.cohortId, ...r });
122
+ }
123
+ }
124
+ /**
125
+ * Advertise a new cohort and begin driving it to completion. Callable many
126
+ * times on one runner; each cohort runs concurrently and independently.
127
+ *
128
+ * @param config Per-cohort conditions + network (see {@link CohortConfig}).
129
+ * @returns The new cohort's id and a `completion` promise that resolves with
130
+ * that cohort's {@link AggregationResult} (or rejects if it fails/stalls).
131
+ * @throws If the runner has been stopped, or the config is invalid
132
+ * (fail-fast via `createCohort`).
133
+ */
134
+ advertiseCohort(config) {
135
+ if (this.#stopped) {
136
+ throw new AggregationServiceError('Cannot advertise on a stopped runner.', 'RUNNER_STOPPED', {});
137
+ }
138
+ this.#registerHandlers();
139
+ // createCohort validates the conditions and throws on a bad config before
140
+ // any context exists - fail-fast, nothing to clean up.
141
+ const cohortId = this.session.createCohort(config);
142
+ let resolve;
143
+ let reject;
144
+ const completion = new Promise((res, rej) => { resolve = res; reject = rej; });
145
+ const ctx = {
146
+ cohortId,
147
+ config,
148
+ resolve,
149
+ reject,
150
+ completion,
151
+ finalizing: false,
152
+ settled: false,
153
+ };
154
+ this.#contexts.set(cohortId, ctx);
155
+ try {
156
+ this.#startTimers(ctx);
157
+ // Emit cohort-advertised BEFORE the send so the event fires before any downstream cascade.
158
+ const advertMsgs = this.session.advertise(cohortId);
159
+ this.#onPhaseMaybeChanged(ctx);
160
+ this.emit('cohort-advertised', { cohortId });
161
+ // Publish the advert. If advertRepeatIntervalMs > 0 we republish on that
162
+ // cadence until this cohort's keygen-complete / fail / stop - works around
163
+ // relays that don't backfill historical events to late subscribers.
164
+ // Otherwise fall back to a single send.
165
+ if (this.#advertRepeatIntervalMs > 0) {
166
+ this.#startAdvertRepeat(ctx, advertMsgs);
167
+ }
168
+ else {
169
+ this.#sendAll(advertMsgs).catch(err => this.#failCohort(ctx, err));
170
+ }
171
+ }
172
+ catch (err) {
173
+ this.#failCohort(ctx, err);
174
+ }
175
+ return { cohortId, completion };
176
+ }
177
+ /**
178
+ * Run a single cohort to completion using the `config` supplied in the
179
+ * runner options. Thin convenience over {@link advertiseCohort} for the
180
+ * single-cohort case (and the path {@link AggregationRunner.solo} rides).
181
+ *
182
+ * @returns {Promise<AggregationResult>} The final result with signature and signed tx.
183
+ */
184
+ run() {
185
+ if (!this.#defaultConfig) {
186
+ return Promise.reject(new AggregationServiceError('run() requires `config` in the runner options; use advertiseCohort(config) to drive cohorts explicitly.', 'MISSING_COHORT_CONFIG', {}));
187
+ }
188
+ try {
189
+ return this.advertiseCohort(this.#defaultConfig).completion;
190
+ }
191
+ catch (err) {
192
+ return Promise.reject(err);
193
+ }
194
+ }
195
+ /**
196
+ * Wait for every currently-outstanding cohort to settle and return the
197
+ * successful results. Dynamic drain: cohorts advertised while this is pending
198
+ * are included, and it resolves only once no cohorts remain. Failed cohorts
199
+ * are surfaced via `error` / `cohort-failed` events and their rejected
200
+ * `completion` promises; they are omitted from the returned array (this
201
+ * method does not throw). Bound long-running cohorts with `cohortTtlMs` /
202
+ * `phaseTimeoutMs` or this may never resolve.
203
+ *
204
+ * @returns {Promise<AggregationResult[]>} Results of the cohorts that completed.
205
+ */
206
+ async runAll() {
207
+ const collected = new Map();
208
+ // Capture every completion, including a cohort that is advertised and
209
+ // finishes entirely within one drain round (so it never appears in a
210
+ // snapshot below).
211
+ const onComplete = (result) => { collected.set(result.cohortId, result); };
212
+ this.on('signing-complete', onComplete);
213
+ try {
214
+ // Block until the live set empties; re-snapshot each round to pick up
215
+ // cohorts advertised mid-drain.
216
+ while (this.#contexts.size > 0) {
217
+ await Promise.allSettled([...this.#contexts.values()].map(c => c.completion));
218
+ }
219
+ }
220
+ finally {
221
+ this.off('signing-complete', onComplete);
222
+ }
223
+ return [...collected.values()];
224
+ }
225
+ /**
226
+ * Begin publishing a cohort's advert immediately and on a repeating interval
227
+ * until the cohort's advert loop is stopped. Each advert is broadcast (no
228
+ * recipient) via the transport's `publishRepeating` primitive.
229
+ */
230
+ #startAdvertRepeat(ctx, advertMsgs) {
231
+ // COHORT_ADVERT is always a single broadcast message in the current
232
+ // protocol, but iterate for generality.
233
+ const stops = [];
234
+ for (const msg of advertMsgs) {
235
+ stops.push(this.#transport.publishRepeating(msg, this.#did, this.#advertRepeatIntervalMs));
236
+ }
237
+ ctx.stopAdvertRepeat = () => {
238
+ for (const stop of stops) {
239
+ try {
240
+ stop();
241
+ }
242
+ catch { /* ignore */ }
243
+ }
244
+ };
245
+ }
246
+ /** Stop a cohort's advert republish loop. Idempotent. */
247
+ #stopAdvertRepeating(ctx) {
248
+ if (!ctx.stopAdvertRepeat)
249
+ return;
250
+ const stop = ctx.stopAdvertRepeat;
251
+ ctx.stopAdvertRepeat = undefined;
252
+ stop();
253
+ }
254
+ /** Schedule a cohort's TTL + phase timeout when it is advertised. */
255
+ #startTimers(ctx) {
256
+ if (this.#cohortTtlMs !== undefined) {
257
+ ctx.cohortTtlTimer = setTimeout(() => {
258
+ const reason = `Cohort ${ctx.cohortId} exceeded TTL of ${this.#cohortTtlMs}ms`;
259
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
260
+ this.#failCohort(ctx, new Error(reason));
261
+ }, this.#cohortTtlMs);
262
+ }
263
+ this.#resetPhaseTimer(ctx);
264
+ }
265
+ /** Reset a cohort's per-phase stall timer. Called when a phase transition is observed. */
266
+ #resetPhaseTimer(ctx) {
267
+ if (ctx.phaseTimer)
268
+ clearTimeout(ctx.phaseTimer);
269
+ ctx.phaseTimer = undefined;
270
+ if (this.#phaseTimeoutMs === undefined)
271
+ return;
272
+ ctx.phaseTimer = setTimeout(() => {
273
+ // A stall during the optimistic signing round can be salvaged by the k-of-n
274
+ // fallback rather than failing the whole cohort (graceful liveness, ADR
275
+ // 042) - but only if enabled and not already committed to a path.
276
+ const phase = this.session.getCohortPhase(ctx.cohortId);
277
+ const inSigning = phase !== undefined && _a.#SIGNING_PHASES.includes(phase);
278
+ if (this.#autoFallbackOnStall && inSigning && !ctx.committedPath && !ctx.settled) {
279
+ this.triggerFallback(ctx.cohortId).catch(err => this.#failCohort(ctx, err));
280
+ return;
281
+ }
282
+ const reason = `Cohort ${ctx.cohortId} stalled in phase ${ctx.lastObservedPhase ?? '?'} for ${this.#phaseTimeoutMs}ms`;
283
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
284
+ this.#failCohort(ctx, new Error(reason));
285
+ }, this.#phaseTimeoutMs);
286
+ }
287
+ /**
288
+ * Abandon the optimistic n-of-n key path for a cohort and collect k-of-n
289
+ * fallback (script-path) signatures instead (ADR 042). Idempotent and safe
290
+ * against the optimistic completion: it commits the cohort to the fallback
291
+ * path synchronously (the `committedPath` latch) before sending anything, so a
292
+ * late optimistic signature can no longer complete-and-broadcast a competing
293
+ * spend of the same UTXO. No-op if the cohort is unknown, already settled, or
294
+ * already committed to a path.
295
+ *
296
+ * Wired automatically to the phase-stall timer when `autoFallbackOnStall` is
297
+ * set; otherwise call it from an operator decision (a UI "fall back now"
298
+ * action). Throws only if the underlying state machine rejects the transition
299
+ * (e.g. signing has not started).
300
+ */
301
+ async triggerFallback(cohortId) {
302
+ const ctx = this.#contexts.get(cohortId);
303
+ if (!ctx || ctx.settled || ctx.committedPath)
304
+ return;
305
+ // startFallbackSigning is synchronous and throws if the cohort is not in a
306
+ // signing phase (e.g. a premature operator call). Run it FIRST so a rejected
307
+ // transition cannot poison the latch: only after it commits the state machine
308
+ // to the fallback do we set committedPath. This still happens synchronously
309
+ // before any await, so a concurrent optimistic completion observes the latch
310
+ // and stands down - but a bad-phase call leaves the optimistic path intact.
311
+ const messages = this.session.startFallbackSigning(cohortId);
312
+ ctx.committedPath = 'fallback';
313
+ this.#stopAdvertRepeating(ctx);
314
+ this.#onPhaseMaybeChanged(ctx);
315
+ const sessionId = this.session.getSigningSessionId(cohortId) ?? '';
316
+ this.emit('fallback-started', { cohortId, sessionId });
317
+ await this.#sendAll(messages);
318
+ }
319
+ /** Detect a phase change for a cohort since the last observation and reset its phase timer. */
320
+ #onPhaseMaybeChanged(ctx) {
321
+ const phase = this.session.getCohortPhase(ctx.cohortId);
322
+ if (phase !== ctx.lastObservedPhase) {
323
+ ctx.lastObservedPhase = phase;
324
+ this.#resetPhaseTimer(ctx);
325
+ }
326
+ }
327
+ /** Clear a cohort's timers. Called on completion, stop, and failure. */
328
+ #clearTimers(ctx) {
329
+ if (ctx.cohortTtlTimer)
330
+ clearTimeout(ctx.cohortTtlTimer);
331
+ if (ctx.phaseTimer)
332
+ clearTimeout(ctx.phaseTimer);
333
+ ctx.cohortTtlTimer = undefined;
334
+ ctx.phaseTimer = undefined;
335
+ }
336
+ /**
337
+ * Reclaim one cohort's runner-layer bookkeeping: stop its advert loop, clear
338
+ * its timers, and drop its {@link RunContext}. Does NOT touch sibling cohorts
339
+ * and does NOT detach the shared transport handlers. Leaves the cohort in the
340
+ * state machine; whether that cohort's `session` state is also removed is the
341
+ * caller's choice (see {@link #completeCohort} vs {@link #failCohort}).
342
+ */
343
+ #disposeCohort(ctx) {
344
+ this.#stopAdvertRepeating(ctx);
345
+ this.#clearTimers(ctx);
346
+ this.#contexts.delete(ctx.cohortId);
347
+ }
348
+ /**
349
+ * Settle one cohort successfully. Reclaims the runner context but leaves the
350
+ * completed cohort in `session` so callers can read its beaconAddress / cohort
351
+ * via `session.getCohort(result.cohortId)`; reclaim it with
352
+ * `session.removeCohort(cohortId)` when done. Idempotent via `ctx.settled`.
353
+ */
354
+ #completeCohort(ctx, result) {
355
+ if (ctx.settled)
356
+ return;
357
+ ctx.settled = true;
358
+ this.#disposeCohort(ctx);
359
+ this.emit('signing-complete', result);
360
+ ctx.resolve(result);
361
+ }
362
+ /**
363
+ * Fail one cohort. Reclaims its runner context, drops its now-dead state from
364
+ * the state machine, and rejects only its completion; siblings keep running
365
+ * and the shared transport handlers stay registered. Idempotent via
366
+ * `ctx.settled`.
367
+ */
368
+ #failCohort(ctx, err) {
369
+ if (ctx.settled)
370
+ return;
371
+ ctx.settled = true;
372
+ this.#disposeCohort(ctx);
373
+ this.session.removeCohort(ctx.cohortId);
374
+ this.emit('error', err);
375
+ ctx.reject(err);
376
+ }
377
+ /**
378
+ * Stop a single cohort early without affecting the rest of the runner. Drops
379
+ * the cohort's state machine state; its `completion` promise rejects with a
380
+ * stopped error.
381
+ */
382
+ stopCohort(cohortId) {
383
+ const ctx = this.#contexts.get(cohortId);
384
+ if (!ctx || ctx.settled)
385
+ return;
386
+ ctx.settled = true;
387
+ this.#disposeCohort(ctx);
388
+ this.session.removeCohort(cohortId);
389
+ ctx.reject(new AggregationServiceError(`Cohort ${cohortId} stopped.`, 'COHORT_STOPPED', { cohortId }));
390
+ }
391
+ /**
392
+ * Stop the whole runner. Fails every outstanding cohort, then detaches the
393
+ * shared transport handlers so a restart or a new runner doesn't inherit
394
+ * stale dispatch. Safe to call repeatedly.
395
+ */
396
+ stop() {
397
+ this.#stopped = true;
398
+ for (const ctx of [...this.#contexts.values()]) {
399
+ if (ctx.settled)
400
+ continue;
401
+ ctx.settled = true;
402
+ this.#disposeCohort(ctx);
403
+ this.session.removeCohort(ctx.cohortId);
404
+ ctx.reject(new AggregationServiceError('Service runner stopped.', 'RUNNER_STOPPED', { cohortId: ctx.cohortId }));
405
+ }
406
+ this.#contexts.clear();
407
+ this.#unregisterHandlers();
408
+ }
409
+ /** Message types this runner listens for on the transport. */
410
+ static #HANDLED_MESSAGE_TYPES = [
411
+ COHORT_OPT_IN,
412
+ SUBMIT_UPDATE,
413
+ SUBMIT_NONINCLUDED,
414
+ VALIDATION_ACK,
415
+ NONCE_CONTRIBUTION,
416
+ SIGNATURE_AUTHORIZATION,
417
+ FALLBACK_SIGNATURE,
418
+ ];
419
+ /**
420
+ * Internal: handler registration with the transport. Idempotent. Handlers
421
+ * are DID-scoped and cohort-agnostic - one registration serves every cohort
422
+ * this runner drives; demux to the right {@link RunContext} happens in each
423
+ * handler via the inbound message's cohortId.
424
+ */
425
+ #registerHandlers() {
426
+ if (this.#handlersRegistered)
427
+ return;
428
+ this.#handlersRegistered = true;
429
+ this.#transport.registerMessageHandler(this.#did, COHORT_OPT_IN, this.#handleOptIn.bind(this));
430
+ this.#transport.registerMessageHandler(this.#did, SUBMIT_UPDATE, this.#handleSubmitUpdate.bind(this));
431
+ // A non-inclusion (decline) is an update-phase response handled identically:
432
+ // session.receive() routes by type, and the response gate + distribute
433
+ // trigger are shared with SUBMIT_UPDATE.
434
+ this.#transport.registerMessageHandler(this.#did, SUBMIT_NONINCLUDED, this.#handleSubmitUpdate.bind(this));
435
+ this.#transport.registerMessageHandler(this.#did, VALIDATION_ACK, this.#handleValidationAck.bind(this));
436
+ this.#transport.registerMessageHandler(this.#did, NONCE_CONTRIBUTION, this.#handleNonceContribution.bind(this));
437
+ this.#transport.registerMessageHandler(this.#did, SIGNATURE_AUTHORIZATION, this.#handleSignatureAuthorization.bind(this));
438
+ this.#transport.registerMessageHandler(this.#did, FALLBACK_SIGNATURE, this.#handleFallbackSignature.bind(this));
439
+ }
440
+ /** Internal: detach from the transport. Safe to call repeatedly. */
441
+ #unregisterHandlers() {
442
+ if (!this.#handlersRegistered)
443
+ return;
444
+ this.#handlersRegistered = false;
445
+ for (const type of _a.#HANDLED_MESSAGE_TYPES) {
446
+ this.#transport.unregisterMessageHandler(this.#did, type);
447
+ }
448
+ }
449
+ /**
450
+ * Internal: message handlers for each protocol step. Each handler:
451
+ * 1) resolves the cohort the message belongs to (by cohortId); ignores it if unknown
452
+ * 2) feeds the message into the state machine via session.receive()
453
+ * 3) emits a high-level event (carrying cohortId) for external observers
454
+ * 4) checks if the new state triggers any automatic next steps, and if so:
455
+ * a) calls the appropriate decision callback(s)
456
+ * b) sends any resulting messages from the state machine
457
+ * Errors fail only the owning cohort. A stopped runner ignores messages.
458
+ * @param {BaseMessage} msg - The incoming message to handle.
459
+ * @returns {Promise<void>} Resolves when handling is complete.
460
+ */
461
+ async #handleOptIn(msg) {
462
+ if (this.#stopped)
463
+ return;
464
+ const ctx = this.#contextFor(msg);
465
+ if (!ctx)
466
+ return;
467
+ try {
468
+ this.session.receive(msg);
469
+ this.#drainRejections(ctx);
470
+ this.#onPhaseMaybeChanged(ctx);
471
+ const optIn = this.session.pendingOptIns(ctx.cohortId).get(msg.from);
472
+ if (!optIn)
473
+ return;
474
+ // PendingOptIn already carries cohortId, so this event is cohort-identified.
475
+ this.emit('opt-in-received', optIn);
476
+ // Register peer key for encrypted messaging
477
+ if (optIn.communicationPk) {
478
+ this.#transport.registerPeer(msg.from, optIn.communicationPk);
479
+ }
480
+ const decision = await this.#onOptInReceived(optIn);
481
+ if (!decision.accepted)
482
+ return;
483
+ // Don't accept past the advertised maxParticipants: acceptParticipant
484
+ // would throw COHORT_FULL and fail the cohort. Silently ignore the surplus
485
+ // opt-in (the cohort is full).
486
+ const maxParticipants = ctx.config.maxParticipants;
487
+ const cohortNow = this.session.getCohort(ctx.cohortId);
488
+ if (maxParticipants !== undefined && cohortNow && cohortNow.participants.length >= maxParticipants) {
489
+ return;
490
+ }
491
+ await this.#sendAll(this.session.acceptParticipant(ctx.cohortId, msg.from));
492
+ this.emit('participant-accepted', { cohortId: ctx.cohortId, participantDid: msg.from });
493
+ // Check if it's time to finalize. The per-cohort `finalizing` flag is set
494
+ // synchronously before the first await so concurrent opt-in handlers for
495
+ // the same cohort observe it and skip - otherwise two handlers could both
496
+ // pass the minParticipants check and both call finalizeKeygen, the second
497
+ // of which would throw (phase mismatch).
498
+ const cohort = this.session.getCohort(ctx.cohortId);
499
+ if (cohort.participants.length >= ctx.config.minParticipants && !ctx.finalizing) {
500
+ ctx.finalizing = true;
501
+ const finalizeDecision = await this.#onReadyToFinalize({
502
+ acceptedCount: cohort.participants.length,
503
+ minRequired: ctx.config.minParticipants,
504
+ });
505
+ if (!finalizeDecision.finalize) {
506
+ // Operator declined - reset the flag so a later opt-in can retry.
507
+ ctx.finalizing = false;
508
+ return;
509
+ }
510
+ // finalizeKeygen() computes the beacon address synchronously
511
+ // emit BEFORE awaiting sendAll. Otherwise the downstream cascade
512
+ // (which can run all the way to signing-complete) would resolve the
513
+ // cohort's completion promise before this event fires.
514
+ const readyMsgs = this.session.finalizeKeygen(ctx.cohortId);
515
+ // Keygen done - stop re-advertising the cohort. New participants
516
+ // arriving after this point would be rejected anyway.
517
+ this.#stopAdvertRepeating(ctx);
518
+ this.emit('keygen-complete', {
519
+ cohortId: ctx.cohortId,
520
+ beaconAddress: cohort.beaconAddress,
521
+ });
522
+ await this.#sendAll(readyMsgs);
523
+ }
524
+ }
525
+ catch (err) {
526
+ this.#failCohort(ctx, err);
527
+ }
528
+ }
529
+ /**
530
+ * Handler for receiving participant updates. When all updates are received, automatically builds
531
+ * and distributes the data for validation.
532
+ * @param {BaseMessage} msg - The incoming message to handle.
533
+ * @returns {Promise<void>} Resolves when handling is complete.
534
+ */
535
+ async #handleSubmitUpdate(msg) {
536
+ if (this.#stopped)
537
+ return;
538
+ const ctx = this.#contextFor(msg);
539
+ if (!ctx)
540
+ return;
541
+ try {
542
+ this.session.receive(msg);
543
+ this.#drainRejections(ctx);
544
+ this.#onPhaseMaybeChanged(ctx);
545
+ this.emit('update-received', { cohortId: ctx.cohortId, participantDid: msg.from });
546
+ // When all updates collected, build and distribute
547
+ if (this.session.getCohortPhase(ctx.cohortId) === ServiceCohortPhase.UpdatesCollected) {
548
+ const distributeMsgs = this.session.buildAndDistribute(ctx.cohortId);
549
+ this.emit('data-distributed', { cohortId: ctx.cohortId });
550
+ await this.#sendAll(distributeMsgs);
551
+ }
552
+ }
553
+ catch (err) {
554
+ this.#failCohort(ctx, err);
555
+ }
556
+ }
557
+ /**
558
+ * Handler for receiving validation acknowledgments. When all validations are received,
559
+ * automatically requests tx data and starts signing.
560
+ * @param {BaseMessage} msg - The incoming message to handle.
561
+ * @returns {Promise<void>} Resolves when handling is complete.
562
+ */
563
+ async #handleValidationAck(msg) {
564
+ if (this.#stopped)
565
+ return;
566
+ const ctx = this.#contextFor(msg);
567
+ if (!ctx)
568
+ return;
569
+ try {
570
+ this.session.receive(msg);
571
+ this.#drainRejections(ctx);
572
+ this.#onPhaseMaybeChanged(ctx);
573
+ const approved = !!msg.body?.approved;
574
+ this.emit('validation-received', { cohortId: ctx.cohortId, participantDid: msg.from, approved });
575
+ const phase = this.session.getCohortPhase(ctx.cohortId);
576
+ // A participant rejection flips the cohort to Failed. Emit a structured
577
+ // event so the runner/caller sees the failure instead of the cohort
578
+ // silently stalling.
579
+ if (phase === ServiceCohortPhase.Failed) {
580
+ const reason = `Validation rejected by participant ${msg.from}`;
581
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
582
+ this.#failCohort(ctx, new Error(reason));
583
+ return;
584
+ }
585
+ // When all validations received, request tx data and start signing
586
+ if (phase === ServiceCohortPhase.Validated) {
587
+ const cohort = this.session.getCohort(ctx.cohortId);
588
+ const txData = await this.#onProvideTxData({
589
+ cohortId: ctx.cohortId,
590
+ beaconAddress: cohort.beaconAddress,
591
+ signalBytes: cohort.signalBytes,
592
+ feeEstimator: this.#feeEstimator,
593
+ });
594
+ const authMsgs = this.session.startSigning(ctx.cohortId, txData);
595
+ const sessionId = this.session.getSigningSessionId(ctx.cohortId) ?? '';
596
+ this.emit('signing-started', { cohortId: ctx.cohortId, sessionId });
597
+ await this.#sendAll(authMsgs);
598
+ }
599
+ }
600
+ catch (err) {
601
+ this.#failCohort(ctx, err);
602
+ }
603
+ }
604
+ /**
605
+ * Handler for receiving nonce contributions. When all nonces are received, sends the aggregated
606
+ * nonce back to the cohort.
607
+ * @param {BaseMessage} msg - The incoming message to handle.
608
+ * @returns {Promise<void>} Resolves when handling is complete.
609
+ */
610
+ async #handleNonceContribution(msg) {
611
+ if (this.#stopped)
612
+ return;
613
+ const ctx = this.#contextFor(msg);
614
+ if (!ctx)
615
+ return;
616
+ try {
617
+ this.session.receive(msg);
618
+ this.#drainRejections(ctx);
619
+ this.#onPhaseMaybeChanged(ctx);
620
+ this.emit('nonce-received', { cohortId: ctx.cohortId, participantDid: msg.from });
621
+ // When all nonces collected, send aggregated nonce
622
+ if (this.session.getCohortPhase(ctx.cohortId) === ServiceCohortPhase.NoncesCollected) {
623
+ await this.#sendAll(this.session.sendAggregatedNonce(ctx.cohortId));
624
+ }
625
+ }
626
+ catch (err) {
627
+ this.#failCohort(ctx, err);
628
+ }
629
+ }
630
+ /**
631
+ * Handler for receiving signature authorizations. When all partial signatures are received, the
632
+ * session automatically completes; the final result is emitted and the cohort's completion
633
+ * promise resolves.
634
+ * @param {BaseMessage} msg - The incoming message to handle.
635
+ * @returns {Promise<void>} Resolves when handling is complete.
636
+ */
637
+ async #handleSignatureAuthorization(msg) {
638
+ if (this.#stopped)
639
+ return;
640
+ const ctx = this.#contextFor(msg);
641
+ if (!ctx)
642
+ return;
643
+ try {
644
+ this.session.receive(msg);
645
+ this.#drainRejections(ctx);
646
+ this.#onPhaseMaybeChanged(ctx);
647
+ // If the cohort already committed to the fallback path, ignore a late
648
+ // optimistic completion: only one path may finalize the single beacon UTXO.
649
+ if (ctx.committedPath === 'fallback')
650
+ return;
651
+ // The state machine auto-completes when all partial sigs received.
652
+ const result = this.session.getResult(ctx.cohortId);
653
+ if (result) {
654
+ ctx.committedPath = 'optimistic';
655
+ this.#completeCohort(ctx, result);
656
+ }
657
+ }
658
+ catch (err) {
659
+ this.#failCohort(ctx, err);
660
+ }
661
+ }
662
+ /**
663
+ * Handler for receiving fallback (k-of-n script-path) signatures. The state
664
+ * machine assembles and finalizes the fallback spend once k valid signatures
665
+ * are in; the result is then emitted and the cohort's completion resolves. The
666
+ * cohort is already committed to the fallback path (via {@link triggerFallback}).
667
+ * @param {BaseMessage} msg - The incoming FALLBACK_SIGNATURE message.
668
+ * @returns {Promise<void>} Resolves when handling is complete.
669
+ */
670
+ async #handleFallbackSignature(msg) {
671
+ if (this.#stopped)
672
+ return;
673
+ const ctx = this.#contextFor(msg);
674
+ if (!ctx)
675
+ return;
676
+ try {
677
+ this.session.receive(msg);
678
+ this.#drainRejections(ctx);
679
+ this.#onPhaseMaybeChanged(ctx);
680
+ const result = this.session.getResult(ctx.cohortId);
681
+ if (result) {
682
+ this.#completeCohort(ctx, result);
683
+ }
684
+ }
685
+ catch (err) {
686
+ this.#failCohort(ctx, err);
687
+ }
688
+ }
689
+ /**
690
+ * Internal: helper to send all messages sequentially. Catches and propagates errors.
691
+ * @param {BaseMessage[]} msgs - The messages to send.
692
+ * @returns {Promise<void>} Resolves when all messages have been sent.
693
+ */
694
+ async #sendAll(msgs) {
695
+ for (const m of msgs) {
696
+ await this.#transport.sendMessage(m, this.#did, m.to);
697
+ }
698
+ }
699
+ }
700
+ _a = AggregationServiceRunner;
701
+ //# sourceMappingURL=service-runner.js.map