@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,891 @@
1
+ import type { SchnorrKeyPair } from '@did-btcr2/keypair';
2
+ import { AggregationServiceError } from '../errors.js';
3
+ import type { BaseMessage } from '../messages/base.js';
4
+ import {
5
+ COHORT_OPT_IN,
6
+ FALLBACK_SIGNATURE,
7
+ NONCE_CONTRIBUTION,
8
+ SIGNATURE_AUTHORIZATION,
9
+ SUBMIT_NONINCLUDED,
10
+ SUBMIT_UPDATE,
11
+ VALIDATION_ACK,
12
+ } from '../messages/constants.js';
13
+ import { ServiceCohortPhase } from '../phases.js';
14
+ import type { ServiceCohortPhaseType } from '../phases.js';
15
+ import type {
16
+ AggregationResult,
17
+ CohortConfig,
18
+ PendingOptIn,
19
+ SigningTxData} from '../service.js';
20
+ import {
21
+ AggregationService
22
+ } from '../service.js';
23
+ import type { Transport } from '../transport/transport.js';
24
+ import { StaticFeeEstimator } from '@did-btcr2/bitcoin';
25
+ import type { FeeEstimator } from '@did-btcr2/bitcoin';
26
+ import type { AggregationServiceEvents } from './events.js';
27
+ import { TypedEventEmitter } from './typed-emitter.js';
28
+
29
+ /** Default fee estimator the runner uses when a caller supplies none: a static 5 sat/vB rate. */
30
+ const DEFAULT_FEE_ESTIMATOR: FeeEstimator = new StaticFeeEstimator(5);
31
+
32
+ /** Decision callback: accept or reject a participant's opt-in. */
33
+ export type OnOptInReceived = (optIn: PendingOptIn) => Promise<{ accepted: boolean }>;
34
+
35
+ /** Decision callback: finalize keygen now, or wait for more participants. */
36
+ export type OnReadyToFinalize = (info: {
37
+ acceptedCount: number;
38
+ minRequired: number;
39
+ }) => Promise<{ finalize: boolean }>;
40
+
41
+ /** Data callback: provide the Bitcoin transaction data to sign. */
42
+ export type OnProvideTxData = (info: {
43
+ cohortId: string;
44
+ beaconAddress: string;
45
+ signalBytes: Uint8Array;
46
+ /**
47
+ * Fee estimator the runner is configured with (the runner's `feeEstimator`
48
+ * option, or a static 5 sat/vB default). Forward it to the beacon transaction
49
+ * builder so a dynamic rate injected at the runner is honored, rather than
50
+ * hard-coding a rate inside this callback (ADR 045).
51
+ */
52
+ feeEstimator: FeeEstimator;
53
+ }) => Promise<SigningTxData>;
54
+
55
+ export interface AggregationServiceRunnerOptions {
56
+ /** Underlying transport (NostrTransport, MockTransport, etc.). */
57
+ transport: Transport;
58
+
59
+ /** This service's identity. */
60
+ did: string;
61
+ keys: SchnorrKeyPair;
62
+
63
+ /**
64
+ * Default cohort configuration for the {@link AggregationServiceRunner.run}
65
+ * convenience path. Optional: omit it when driving the runner with
66
+ * {@link AggregationServiceRunner.advertiseCohort}, which takes a per-cohort
67
+ * config and can be called many times on one runner.
68
+ */
69
+ config?: CohortConfig;
70
+
71
+ /**
72
+ * Decide whether to accept a participant's opt-in.
73
+ * Default: auto-accept all opt-ins.
74
+ */
75
+ onOptInReceived?: OnOptInReceived;
76
+
77
+ /**
78
+ * Decide whether to finalize keygen now or wait for more participants.
79
+ * Called after each accepted opt-in once minParticipants is reached.
80
+ * Default: finalize as soon as minParticipants is reached.
81
+ */
82
+ onReadyToFinalize?: OnReadyToFinalize;
83
+
84
+ /**
85
+ * Provide the Bitcoin transaction data to sign.
86
+ * REQUIRED - no sensible default.
87
+ */
88
+ onProvideTxData: OnProvideTxData;
89
+
90
+ /**
91
+ * Fee estimator passed to {@link OnProvideTxData} so the beacon transaction the
92
+ * callback builds is sized at a chosen rate. Inject a dynamic estimator (a mempool
93
+ * API or Bitcoin Core `estimatesmartfee`) here as the single standard point for
94
+ * fee-rate selection, instead of hard-coding a rate inside the callback (ADR 045).
95
+ * Defaults to a static 5 sat/vB estimator.
96
+ */
97
+ feeEstimator?: FeeEstimator;
98
+
99
+ /**
100
+ * Maximum canonicalized byte-length of a signed update body. Submissions
101
+ * above this cap are rejected and surfaced via the `message-rejected` event.
102
+ * Defaults to {@link DEFAULT_MAX_UPDATE_SIZE_BYTES} (256 KiB).
103
+ */
104
+ maxUpdateSizeBytes?: number;
105
+
106
+ /**
107
+ * Overall wall-clock budget for each cohort, from advertise to
108
+ * signing-complete. On expiry the cohort is dropped, `cohort-failed` is
109
+ * emitted, and that cohort's completion rejects with a timeout error. Other
110
+ * cohorts on the same runner are unaffected. Leave undefined to disable.
111
+ */
112
+ cohortTtlMs?: number;
113
+
114
+ /**
115
+ * Maximum time allowed between phase transitions for a cohort. Protects
116
+ * against stalled cohorts (e.g. a participant vanishing mid-protocol). Reset
117
+ * automatically on every observed phase change. Applied per cohort. Leave
118
+ * undefined to disable.
119
+ */
120
+ phaseTimeoutMs?: number;
121
+
122
+ /**
123
+ * Re-publish COHORT_ADVERT on this interval until a cohort's keygen is
124
+ * finalized. Works around relays that don't backfill historical events to
125
+ * late subscribers - a republish gives late joiners a window to discover the
126
+ * advert without protocol changes. The first publish is immediate;
127
+ * subsequent publishes fire every `advertRepeatIntervalMs` until that
128
+ * cohort's keygen completes, fails, or is stopped. Defaults to
129
+ * {@link DEFAULT_ADVERT_REPEAT_INTERVAL_MS} (60 s). Set to 0 to publish
130
+ * once and never retry.
131
+ */
132
+ advertRepeatIntervalMs?: number;
133
+
134
+ /**
135
+ * When a cohort stalls (phase timeout) while the optimistic n-of-n signing
136
+ * round is in flight, fall back to the k-of-n script path instead of failing
137
+ * the cohort (graceful liveness, ADR 042). Off by default: enabling it trades a
138
+ * cheaper/private key-path spend for a larger script-path spend whenever the
139
+ * optimistic round does not complete in time. A stall outside the signing
140
+ * phases still fails the cohort. Operators can also drive the fallback
141
+ * explicitly via {@link AggregationServiceRunner.triggerFallback}.
142
+ */
143
+ autoFallbackOnStall?: boolean;
144
+ }
145
+
146
+ /** Default cadence for re-publishing COHORT_ADVERT until keygen completes: 60 seconds. */
147
+ export const DEFAULT_ADVERT_REPEAT_INTERVAL_MS = 60_000;
148
+
149
+ /**
150
+ * Per-cohort runtime bookkeeping the runner keeps for each advertised cohort.
151
+ * One {@link RunContext} per cohortId lives in the runner's `#contexts` map so
152
+ * many cohorts run concurrently on a single runner, each with its own
153
+ * completion promise, finalize guard, timers, and advert-republish loop. The
154
+ * underlying {@link AggregationService} state machine is already keyed by
155
+ * cohortId; this struct is the runner-layer counterpart (see ADR 040).
156
+ */
157
+ interface RunContext {
158
+ /** The cohort this context drives. */
159
+ cohortId: string;
160
+ /** The conditions this cohort was advertised with. */
161
+ config: CohortConfig;
162
+ /** Resolve this cohort's completion with its aggregation result. */
163
+ resolve: (result: AggregationResult) => void;
164
+ /** Reject this cohort's completion. */
165
+ reject: (err: Error) => void;
166
+ /** The promise handed back from {@link AggregationServiceRunner.advertiseCohort}. */
167
+ completion: Promise<AggregationResult>;
168
+ /**
169
+ * Guard against the async race where two concurrent #handleOptIn invocations
170
+ * for THIS cohort both pass the `participants.length >= minParticipants`
171
+ * check before either mutates the cohort phase. Set synchronously before any
172
+ * `await` so subsequent handlers observe it on their next resumption.
173
+ */
174
+ finalizing: boolean;
175
+ /** Once settled (resolved or rejected), late timers/messages must not re-settle. */
176
+ settled: boolean;
177
+ /**
178
+ * The spend path this cohort is committed to once signing reaches a decision:
179
+ * `optimistic` (n-of-n key path) or `fallback` (k-of-n script path). A cohort
180
+ * spends its single beacon UTXO exactly once, so this latch (set synchronously
181
+ * before any await) ensures the optimistic completion and the fallback never
182
+ * both finalize and broadcast the same UTXO (the ADR-042 double-spend hazard).
183
+ */
184
+ committedPath?: 'optimistic' | 'fallback';
185
+ cohortTtlTimer?: ReturnType<typeof setTimeout>;
186
+ phaseTimer?: ReturnType<typeof setTimeout>;
187
+ lastObservedPhase?: string;
188
+ /** Stop handle for THIS cohort's repeating COHORT_ADVERT publish loop. */
189
+ stopAdvertRepeat?: () => void;
190
+ }
191
+
192
+ /**
193
+ * High-level facade for running an Aggregation Service over a Transport.
194
+ *
195
+ * Wires the {@link AggregationService} state machine to a {@link Transport},
196
+ * encapsulating message handler registration, outgoing message dispatch,
197
+ * and decision callback orchestration.
198
+ *
199
+ * A single runner is a long-lived multiplexer: it advertises and drives many
200
+ * cohorts concurrently over one transport. Each advertised cohort owns an
201
+ * independent completion promise and fails in isolation - a stalled or failed
202
+ * cohort never settles its siblings (see ADR 040). Use
203
+ * {@link AggregationServiceRunner.advertiseCohort} for the multi-cohort path;
204
+ * {@link AggregationServiceRunner.run} is a thin single-cohort convenience over
205
+ * it.
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * const transport = new NostrTransport({ relays: [RELAY] });
210
+ * transport.registerActor(serviceDid, serviceKeys);
211
+ *
212
+ * const runner = new AggregationServiceRunner({
213
+ * transport,
214
+ * did: serviceDid,
215
+ * keys: serviceKeys,
216
+ * onProvideTxData: async ({ beaconAddress, signalBytes, feeEstimator }) => {
217
+ * // Forward feeEstimator so a dynamic rate injected at the runner is honored.
218
+ * return await buildBeaconTransaction(beaconAddress, signalBytes, bitcoin, feeEstimator);
219
+ * },
220
+ * });
221
+ *
222
+ * runner.on('keygen-complete', ({ cohortId, beaconAddress }) => console.log(beaconAddress));
223
+ * runner.on('signing-complete', ({ cohortId, signature }) => console.log('done', cohortId));
224
+ *
225
+ * // Multi-cohort: advertise several cohorts; each completion resolves independently.
226
+ * const a = runner.advertiseCohort({ minParticipants: 2, network: 'mutinynet', beaconType: 'CASBeacon' });
227
+ * const b = runner.advertiseCohort({ minParticipants: 3, network: 'mutinynet', beaconType: 'SMTBeacon' });
228
+ * const [ra, rb] = await Promise.all([a.completion, b.completion]);
229
+ *
230
+ * // Single-cohort convenience (requires `config` in the options):
231
+ * // const result = await runner.run();
232
+ * ```
233
+ *
234
+ * For full manual control, drop down to the underlying state machine via
235
+ * `runner.session`. The state machine has no transport coupling and exposes
236
+ * every protocol decision as an explicit method.
237
+ *
238
+ * @class AggregationServiceRunner
239
+ */
240
+ export class AggregationServiceRunner extends TypedEventEmitter<AggregationServiceEvents> {
241
+ /** Direct access to the underlying state machine for advanced use. */
242
+ readonly session: AggregationService;
243
+
244
+ readonly #transport: Transport;
245
+ readonly #did: string;
246
+ readonly #defaultConfig?: CohortConfig;
247
+ readonly #onOptInReceived: OnOptInReceived;
248
+ readonly #onReadyToFinalize: OnReadyToFinalize;
249
+ readonly #onProvideTxData: OnProvideTxData;
250
+ readonly #feeEstimator: FeeEstimator;
251
+ readonly #cohortTtlMs?: number;
252
+ readonly #phaseTimeoutMs?: number;
253
+ readonly #advertRepeatIntervalMs: number;
254
+ readonly #autoFallbackOnStall: boolean;
255
+
256
+ /** Phases during which a stall can be salvaged by the k-of-n fallback (ADR 042). */
257
+ static readonly #SIGNING_PHASES: readonly ServiceCohortPhaseType[] = [
258
+ ServiceCohortPhase.SigningStarted,
259
+ ServiceCohortPhase.NoncesCollected,
260
+ ServiceCohortPhase.AwaitingPartialSigs,
261
+ ];
262
+
263
+ /** Per-cohort run state, keyed by cohortId. */
264
+ readonly #contexts: Map<string, RunContext> = new Map();
265
+ #handlersRegistered = false;
266
+ #stopped = false;
267
+
268
+ constructor(options: AggregationServiceRunnerOptions) {
269
+ super();
270
+ this.#transport = options.transport;
271
+ this.#did = options.did;
272
+ this.#defaultConfig = options.config;
273
+ this.#onOptInReceived = options.onOptInReceived ?? (async () => ({ accepted: true }));
274
+ this.#onReadyToFinalize = options.onReadyToFinalize ?? (async ({ acceptedCount, minRequired }) => ({
275
+ finalize : acceptedCount >= minRequired,
276
+ }));
277
+ this.#onProvideTxData = options.onProvideTxData;
278
+ this.#feeEstimator = options.feeEstimator ?? DEFAULT_FEE_ESTIMATOR;
279
+ this.#cohortTtlMs = options.cohortTtlMs;
280
+ this.#phaseTimeoutMs = options.phaseTimeoutMs;
281
+ this.#advertRepeatIntervalMs = options.advertRepeatIntervalMs ?? DEFAULT_ADVERT_REPEAT_INTERVAL_MS;
282
+ this.#autoFallbackOnStall = options.autoFallbackOnStall ?? false;
283
+
284
+ this.session = new AggregationService({
285
+ // The coordinator never signs, so the state machine receives only the
286
+ // public half of the operator's keypair (see ADR 038). The full keypair
287
+ // remains the operator's transport/communication identity.
288
+ did : options.did,
289
+ publicKey : options.keys.publicKey,
290
+ maxUpdateSizeBytes : options.maxUpdateSizeBytes,
291
+ });
292
+ }
293
+
294
+ /** Resolve the {@link RunContext} an inbound message belongs to, by cohortId. */
295
+ #contextFor(msg: BaseMessage): RunContext | undefined {
296
+ const cohortId = msg.body?.cohortId;
297
+ if(!cohortId) return undefined;
298
+ return this.#contexts.get(cohortId);
299
+ }
300
+
301
+ /**
302
+ * Drain any silent rejections the state machine recorded for a cohort during
303
+ * the most recent receive() and surface them as `message-rejected` events.
304
+ */
305
+ #drainRejections(ctx: RunContext): void {
306
+ for(const r of this.session.drainRejections(ctx.cohortId)) {
307
+ this.emit('message-rejected', { cohortId: ctx.cohortId, ...r });
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Advertise a new cohort and begin driving it to completion. Callable many
313
+ * times on one runner; each cohort runs concurrently and independently.
314
+ *
315
+ * @param config Per-cohort conditions + network (see {@link CohortConfig}).
316
+ * @returns The new cohort's id and a `completion` promise that resolves with
317
+ * that cohort's {@link AggregationResult} (or rejects if it fails/stalls).
318
+ * @throws If the runner has been stopped, or the config is invalid
319
+ * (fail-fast via `createCohort`).
320
+ */
321
+ advertiseCohort(config: CohortConfig): { cohortId: string; completion: Promise<AggregationResult> } {
322
+ if(this.#stopped) {
323
+ throw new AggregationServiceError('Cannot advertise on a stopped runner.', 'RUNNER_STOPPED', {});
324
+ }
325
+ this.#registerHandlers();
326
+ // createCohort validates the conditions and throws on a bad config before
327
+ // any context exists - fail-fast, nothing to clean up.
328
+ const cohortId = this.session.createCohort(config);
329
+
330
+ let resolve!: (result: AggregationResult) => void;
331
+ let reject!: (err: Error) => void;
332
+ const completion = new Promise<AggregationResult>((res, rej) => { resolve = res; reject = rej; });
333
+ const ctx: RunContext = {
334
+ cohortId,
335
+ config,
336
+ resolve,
337
+ reject,
338
+ completion,
339
+ finalizing : false,
340
+ settled : false,
341
+ };
342
+ this.#contexts.set(cohortId, ctx);
343
+
344
+ try {
345
+ this.#startTimers(ctx);
346
+ // Emit cohort-advertised BEFORE the send so the event fires before any downstream cascade.
347
+ const advertMsgs = this.session.advertise(cohortId);
348
+ this.#onPhaseMaybeChanged(ctx);
349
+ this.emit('cohort-advertised', { cohortId });
350
+ // Publish the advert. If advertRepeatIntervalMs > 0 we republish on that
351
+ // cadence until this cohort's keygen-complete / fail / stop - works around
352
+ // relays that don't backfill historical events to late subscribers.
353
+ // Otherwise fall back to a single send.
354
+ if(this.#advertRepeatIntervalMs > 0) {
355
+ this.#startAdvertRepeat(ctx, advertMsgs);
356
+ } else {
357
+ this.#sendAll(advertMsgs).catch(err => this.#failCohort(ctx, err as Error));
358
+ }
359
+ } catch(err) {
360
+ this.#failCohort(ctx, err as Error);
361
+ }
362
+
363
+ return { cohortId, completion };
364
+ }
365
+
366
+ /**
367
+ * Run a single cohort to completion using the `config` supplied in the
368
+ * runner options. Thin convenience over {@link advertiseCohort} for the
369
+ * single-cohort case (and the path {@link AggregationRunner.solo} rides).
370
+ *
371
+ * @returns {Promise<AggregationResult>} The final result with signature and signed tx.
372
+ */
373
+ run(): Promise<AggregationResult> {
374
+ if(!this.#defaultConfig) {
375
+ return Promise.reject(new AggregationServiceError(
376
+ 'run() requires `config` in the runner options; use advertiseCohort(config) to drive cohorts explicitly.',
377
+ 'MISSING_COHORT_CONFIG', {}
378
+ ));
379
+ }
380
+ try {
381
+ return this.advertiseCohort(this.#defaultConfig).completion;
382
+ } catch(err) {
383
+ return Promise.reject(err as Error);
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Wait for every currently-outstanding cohort to settle and return the
389
+ * successful results. Dynamic drain: cohorts advertised while this is pending
390
+ * are included, and it resolves only once no cohorts remain. Failed cohorts
391
+ * are surfaced via `error` / `cohort-failed` events and their rejected
392
+ * `completion` promises; they are omitted from the returned array (this
393
+ * method does not throw). Bound long-running cohorts with `cohortTtlMs` /
394
+ * `phaseTimeoutMs` or this may never resolve.
395
+ *
396
+ * @returns {Promise<AggregationResult[]>} Results of the cohorts that completed.
397
+ */
398
+ async runAll(): Promise<AggregationResult[]> {
399
+ const collected = new Map<string, AggregationResult>();
400
+ // Capture every completion, including a cohort that is advertised and
401
+ // finishes entirely within one drain round (so it never appears in a
402
+ // snapshot below).
403
+ const onComplete = (result: AggregationResult): void => { collected.set(result.cohortId, result); };
404
+ this.on('signing-complete', onComplete);
405
+ try {
406
+ // Block until the live set empties; re-snapshot each round to pick up
407
+ // cohorts advertised mid-drain.
408
+ while(this.#contexts.size > 0) {
409
+ await Promise.allSettled([ ...this.#contexts.values() ].map(c => c.completion));
410
+ }
411
+ } finally {
412
+ this.off('signing-complete', onComplete);
413
+ }
414
+ return [ ...collected.values() ];
415
+ }
416
+
417
+ /**
418
+ * Begin publishing a cohort's advert immediately and on a repeating interval
419
+ * until the cohort's advert loop is stopped. Each advert is broadcast (no
420
+ * recipient) via the transport's `publishRepeating` primitive.
421
+ */
422
+ #startAdvertRepeat(ctx: RunContext, advertMsgs: BaseMessage[]): void {
423
+ // COHORT_ADVERT is always a single broadcast message in the current
424
+ // protocol, but iterate for generality.
425
+ const stops: Array<() => void> = [];
426
+ for(const msg of advertMsgs) {
427
+ stops.push(this.#transport.publishRepeating(msg, this.#did, this.#advertRepeatIntervalMs));
428
+ }
429
+ ctx.stopAdvertRepeat = () => {
430
+ for(const stop of stops) {
431
+ try { stop(); } catch { /* ignore */ }
432
+ }
433
+ };
434
+ }
435
+
436
+ /** Stop a cohort's advert republish loop. Idempotent. */
437
+ #stopAdvertRepeating(ctx: RunContext): void {
438
+ if(!ctx.stopAdvertRepeat) return;
439
+ const stop = ctx.stopAdvertRepeat;
440
+ ctx.stopAdvertRepeat = undefined;
441
+ stop();
442
+ }
443
+
444
+ /** Schedule a cohort's TTL + phase timeout when it is advertised. */
445
+ #startTimers(ctx: RunContext): void {
446
+ if(this.#cohortTtlMs !== undefined) {
447
+ ctx.cohortTtlTimer = setTimeout(() => {
448
+ const reason = `Cohort ${ctx.cohortId} exceeded TTL of ${this.#cohortTtlMs}ms`;
449
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
450
+ this.#failCohort(ctx, new Error(reason));
451
+ }, this.#cohortTtlMs);
452
+ }
453
+ this.#resetPhaseTimer(ctx);
454
+ }
455
+
456
+ /** Reset a cohort's per-phase stall timer. Called when a phase transition is observed. */
457
+ #resetPhaseTimer(ctx: RunContext): void {
458
+ if(ctx.phaseTimer) clearTimeout(ctx.phaseTimer);
459
+ ctx.phaseTimer = undefined;
460
+ if(this.#phaseTimeoutMs === undefined) return;
461
+ ctx.phaseTimer = setTimeout(() => {
462
+ // A stall during the optimistic signing round can be salvaged by the k-of-n
463
+ // fallback rather than failing the whole cohort (graceful liveness, ADR
464
+ // 042) - but only if enabled and not already committed to a path.
465
+ const phase = this.session.getCohortPhase(ctx.cohortId);
466
+ const inSigning = phase !== undefined && AggregationServiceRunner.#SIGNING_PHASES.includes(phase);
467
+ if(this.#autoFallbackOnStall && inSigning && !ctx.committedPath && !ctx.settled) {
468
+ this.triggerFallback(ctx.cohortId).catch(err => this.#failCohort(ctx, err as Error));
469
+ return;
470
+ }
471
+ const reason = `Cohort ${ctx.cohortId} stalled in phase ${ctx.lastObservedPhase ?? '?'} for ${this.#phaseTimeoutMs}ms`;
472
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
473
+ this.#failCohort(ctx, new Error(reason));
474
+ }, this.#phaseTimeoutMs);
475
+ }
476
+
477
+ /**
478
+ * Abandon the optimistic n-of-n key path for a cohort and collect k-of-n
479
+ * fallback (script-path) signatures instead (ADR 042). Idempotent and safe
480
+ * against the optimistic completion: it commits the cohort to the fallback
481
+ * path synchronously (the `committedPath` latch) before sending anything, so a
482
+ * late optimistic signature can no longer complete-and-broadcast a competing
483
+ * spend of the same UTXO. No-op if the cohort is unknown, already settled, or
484
+ * already committed to a path.
485
+ *
486
+ * Wired automatically to the phase-stall timer when `autoFallbackOnStall` is
487
+ * set; otherwise call it from an operator decision (a UI "fall back now"
488
+ * action). Throws only if the underlying state machine rejects the transition
489
+ * (e.g. signing has not started).
490
+ */
491
+ async triggerFallback(cohortId: string): Promise<void> {
492
+ const ctx = this.#contexts.get(cohortId);
493
+ if(!ctx || ctx.settled || ctx.committedPath) return;
494
+ // startFallbackSigning is synchronous and throws if the cohort is not in a
495
+ // signing phase (e.g. a premature operator call). Run it FIRST so a rejected
496
+ // transition cannot poison the latch: only after it commits the state machine
497
+ // to the fallback do we set committedPath. This still happens synchronously
498
+ // before any await, so a concurrent optimistic completion observes the latch
499
+ // and stands down - but a bad-phase call leaves the optimistic path intact.
500
+ const messages = this.session.startFallbackSigning(cohortId);
501
+ ctx.committedPath = 'fallback';
502
+ this.#stopAdvertRepeating(ctx);
503
+ this.#onPhaseMaybeChanged(ctx);
504
+ const sessionId = this.session.getSigningSessionId(cohortId) ?? '';
505
+ this.emit('fallback-started', { cohortId, sessionId });
506
+ await this.#sendAll(messages);
507
+ }
508
+
509
+ /** Detect a phase change for a cohort since the last observation and reset its phase timer. */
510
+ #onPhaseMaybeChanged(ctx: RunContext): void {
511
+ const phase = this.session.getCohortPhase(ctx.cohortId);
512
+ if(phase !== ctx.lastObservedPhase) {
513
+ ctx.lastObservedPhase = phase;
514
+ this.#resetPhaseTimer(ctx);
515
+ }
516
+ }
517
+
518
+ /** Clear a cohort's timers. Called on completion, stop, and failure. */
519
+ #clearTimers(ctx: RunContext): void {
520
+ if(ctx.cohortTtlTimer) clearTimeout(ctx.cohortTtlTimer);
521
+ if(ctx.phaseTimer) clearTimeout(ctx.phaseTimer);
522
+ ctx.cohortTtlTimer = undefined;
523
+ ctx.phaseTimer = undefined;
524
+ }
525
+
526
+ /**
527
+ * Reclaim one cohort's runner-layer bookkeeping: stop its advert loop, clear
528
+ * its timers, and drop its {@link RunContext}. Does NOT touch sibling cohorts
529
+ * and does NOT detach the shared transport handlers. Leaves the cohort in the
530
+ * state machine; whether that cohort's `session` state is also removed is the
531
+ * caller's choice (see {@link #completeCohort} vs {@link #failCohort}).
532
+ */
533
+ #disposeCohort(ctx: RunContext): void {
534
+ this.#stopAdvertRepeating(ctx);
535
+ this.#clearTimers(ctx);
536
+ this.#contexts.delete(ctx.cohortId);
537
+ }
538
+
539
+ /**
540
+ * Settle one cohort successfully. Reclaims the runner context but leaves the
541
+ * completed cohort in `session` so callers can read its beaconAddress / cohort
542
+ * via `session.getCohort(result.cohortId)`; reclaim it with
543
+ * `session.removeCohort(cohortId)` when done. Idempotent via `ctx.settled`.
544
+ */
545
+ #completeCohort(ctx: RunContext, result: AggregationResult): void {
546
+ if(ctx.settled) return;
547
+ ctx.settled = true;
548
+ this.#disposeCohort(ctx);
549
+ this.emit('signing-complete', result);
550
+ ctx.resolve(result);
551
+ }
552
+
553
+ /**
554
+ * Fail one cohort. Reclaims its runner context, drops its now-dead state from
555
+ * the state machine, and rejects only its completion; siblings keep running
556
+ * and the shared transport handlers stay registered. Idempotent via
557
+ * `ctx.settled`.
558
+ */
559
+ #failCohort(ctx: RunContext, err: Error): void {
560
+ if(ctx.settled) return;
561
+ ctx.settled = true;
562
+ this.#disposeCohort(ctx);
563
+ this.session.removeCohort(ctx.cohortId);
564
+ this.emit('error', err);
565
+ ctx.reject(err);
566
+ }
567
+
568
+ /**
569
+ * Stop a single cohort early without affecting the rest of the runner. Drops
570
+ * the cohort's state machine state; its `completion` promise rejects with a
571
+ * stopped error.
572
+ */
573
+ stopCohort(cohortId: string): void {
574
+ const ctx = this.#contexts.get(cohortId);
575
+ if(!ctx || ctx.settled) return;
576
+ ctx.settled = true;
577
+ this.#disposeCohort(ctx);
578
+ this.session.removeCohort(cohortId);
579
+ ctx.reject(new AggregationServiceError(`Cohort ${cohortId} stopped.`, 'COHORT_STOPPED', { cohortId }));
580
+ }
581
+
582
+ /**
583
+ * Stop the whole runner. Fails every outstanding cohort, then detaches the
584
+ * shared transport handlers so a restart or a new runner doesn't inherit
585
+ * stale dispatch. Safe to call repeatedly.
586
+ */
587
+ stop(): void {
588
+ this.#stopped = true;
589
+ for(const ctx of [ ...this.#contexts.values() ]) {
590
+ if(ctx.settled) continue;
591
+ ctx.settled = true;
592
+ this.#disposeCohort(ctx);
593
+ this.session.removeCohort(ctx.cohortId);
594
+ ctx.reject(new AggregationServiceError('Service runner stopped.', 'RUNNER_STOPPED', { cohortId: ctx.cohortId }));
595
+ }
596
+ this.#contexts.clear();
597
+ this.#unregisterHandlers();
598
+ }
599
+
600
+ /** Message types this runner listens for on the transport. */
601
+ static readonly #HANDLED_MESSAGE_TYPES: readonly string[] = [
602
+ COHORT_OPT_IN,
603
+ SUBMIT_UPDATE,
604
+ SUBMIT_NONINCLUDED,
605
+ VALIDATION_ACK,
606
+ NONCE_CONTRIBUTION,
607
+ SIGNATURE_AUTHORIZATION,
608
+ FALLBACK_SIGNATURE,
609
+ ];
610
+
611
+ /**
612
+ * Internal: handler registration with the transport. Idempotent. Handlers
613
+ * are DID-scoped and cohort-agnostic - one registration serves every cohort
614
+ * this runner drives; demux to the right {@link RunContext} happens in each
615
+ * handler via the inbound message's cohortId.
616
+ */
617
+ #registerHandlers(): void {
618
+ if(this.#handlersRegistered) return;
619
+ this.#handlersRegistered = true;
620
+
621
+ this.#transport.registerMessageHandler(this.#did, COHORT_OPT_IN, this.#handleOptIn.bind(this));
622
+ this.#transport.registerMessageHandler(this.#did, SUBMIT_UPDATE, this.#handleSubmitUpdate.bind(this));
623
+ // A non-inclusion (decline) is an update-phase response handled identically:
624
+ // session.receive() routes by type, and the response gate + distribute
625
+ // trigger are shared with SUBMIT_UPDATE.
626
+ this.#transport.registerMessageHandler(this.#did, SUBMIT_NONINCLUDED, this.#handleSubmitUpdate.bind(this));
627
+ this.#transport.registerMessageHandler(this.#did, VALIDATION_ACK, this.#handleValidationAck.bind(this));
628
+ this.#transport.registerMessageHandler(this.#did, NONCE_CONTRIBUTION, this.#handleNonceContribution.bind(this));
629
+ this.#transport.registerMessageHandler(this.#did, SIGNATURE_AUTHORIZATION, this.#handleSignatureAuthorization.bind(this));
630
+ this.#transport.registerMessageHandler(this.#did, FALLBACK_SIGNATURE, this.#handleFallbackSignature.bind(this));
631
+ }
632
+
633
+ /** Internal: detach from the transport. Safe to call repeatedly. */
634
+ #unregisterHandlers(): void {
635
+ if(!this.#handlersRegistered) return;
636
+ this.#handlersRegistered = false;
637
+ for(const type of AggregationServiceRunner.#HANDLED_MESSAGE_TYPES) {
638
+ this.#transport.unregisterMessageHandler(this.#did, type);
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Internal: message handlers for each protocol step. Each handler:
644
+ * 1) resolves the cohort the message belongs to (by cohortId); ignores it if unknown
645
+ * 2) feeds the message into the state machine via session.receive()
646
+ * 3) emits a high-level event (carrying cohortId) for external observers
647
+ * 4) checks if the new state triggers any automatic next steps, and if so:
648
+ * a) calls the appropriate decision callback(s)
649
+ * b) sends any resulting messages from the state machine
650
+ * Errors fail only the owning cohort. A stopped runner ignores messages.
651
+ * @param {BaseMessage} msg - The incoming message to handle.
652
+ * @returns {Promise<void>} Resolves when handling is complete.
653
+ */
654
+ async #handleOptIn(msg: BaseMessage): Promise<void> {
655
+ if(this.#stopped) return;
656
+ const ctx = this.#contextFor(msg);
657
+ if(!ctx) return;
658
+ try {
659
+ this.session.receive(msg);
660
+ this.#drainRejections(ctx);
661
+ this.#onPhaseMaybeChanged(ctx);
662
+
663
+ const optIn = this.session.pendingOptIns(ctx.cohortId).get(msg.from);
664
+ if(!optIn) return;
665
+ // PendingOptIn already carries cohortId, so this event is cohort-identified.
666
+ this.emit('opt-in-received', optIn);
667
+
668
+ // Register peer key for encrypted messaging
669
+ if(optIn.communicationPk) {
670
+ this.#transport.registerPeer(msg.from, optIn.communicationPk);
671
+ }
672
+
673
+ const decision = await this.#onOptInReceived(optIn);
674
+ if(!decision.accepted) return;
675
+
676
+ // Don't accept past the advertised maxParticipants: acceptParticipant
677
+ // would throw COHORT_FULL and fail the cohort. Silently ignore the surplus
678
+ // opt-in (the cohort is full).
679
+ const maxParticipants = ctx.config.maxParticipants;
680
+ const cohortNow = this.session.getCohort(ctx.cohortId);
681
+ if(maxParticipants !== undefined && cohortNow && cohortNow.participants.length >= maxParticipants) {
682
+ return;
683
+ }
684
+
685
+ await this.#sendAll(this.session.acceptParticipant(ctx.cohortId, msg.from));
686
+ this.emit('participant-accepted', { cohortId: ctx.cohortId, participantDid: msg.from });
687
+
688
+ // Check if it's time to finalize. The per-cohort `finalizing` flag is set
689
+ // synchronously before the first await so concurrent opt-in handlers for
690
+ // the same cohort observe it and skip - otherwise two handlers could both
691
+ // pass the minParticipants check and both call finalizeKeygen, the second
692
+ // of which would throw (phase mismatch).
693
+ const cohort = this.session.getCohort(ctx.cohortId)!;
694
+ if(cohort.participants.length >= ctx.config.minParticipants && !ctx.finalizing) {
695
+ ctx.finalizing = true;
696
+ const finalizeDecision = await this.#onReadyToFinalize({
697
+ acceptedCount : cohort.participants.length,
698
+ minRequired : ctx.config.minParticipants,
699
+ });
700
+ if(!finalizeDecision.finalize) {
701
+ // Operator declined - reset the flag so a later opt-in can retry.
702
+ ctx.finalizing = false;
703
+ return;
704
+ }
705
+ // finalizeKeygen() computes the beacon address synchronously
706
+ // emit BEFORE awaiting sendAll. Otherwise the downstream cascade
707
+ // (which can run all the way to signing-complete) would resolve the
708
+ // cohort's completion promise before this event fires.
709
+ const readyMsgs = this.session.finalizeKeygen(ctx.cohortId);
710
+ // Keygen done - stop re-advertising the cohort. New participants
711
+ // arriving after this point would be rejected anyway.
712
+ this.#stopAdvertRepeating(ctx);
713
+ this.emit('keygen-complete', {
714
+ cohortId : ctx.cohortId,
715
+ beaconAddress : cohort.beaconAddress,
716
+ });
717
+ await this.#sendAll(readyMsgs);
718
+ }
719
+ } catch(err) {
720
+ this.#failCohort(ctx, err as Error);
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Handler for receiving participant updates. When all updates are received, automatically builds
726
+ * and distributes the data for validation.
727
+ * @param {BaseMessage} msg - The incoming message to handle.
728
+ * @returns {Promise<void>} Resolves when handling is complete.
729
+ */
730
+ async #handleSubmitUpdate(msg: BaseMessage): Promise<void> {
731
+ if(this.#stopped) return;
732
+ const ctx = this.#contextFor(msg);
733
+ if(!ctx) return;
734
+ try {
735
+ this.session.receive(msg);
736
+ this.#drainRejections(ctx);
737
+ this.#onPhaseMaybeChanged(ctx);
738
+ this.emit('update-received', { cohortId: ctx.cohortId, participantDid: msg.from });
739
+
740
+ // When all updates collected, build and distribute
741
+ if(this.session.getCohortPhase(ctx.cohortId) === ServiceCohortPhase.UpdatesCollected) {
742
+ const distributeMsgs = this.session.buildAndDistribute(ctx.cohortId);
743
+ this.emit('data-distributed', { cohortId: ctx.cohortId });
744
+ await this.#sendAll(distributeMsgs);
745
+ }
746
+ } catch(err) {
747
+ this.#failCohort(ctx, err as Error);
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Handler for receiving validation acknowledgments. When all validations are received,
753
+ * automatically requests tx data and starts signing.
754
+ * @param {BaseMessage} msg - The incoming message to handle.
755
+ * @returns {Promise<void>} Resolves when handling is complete.
756
+ */
757
+ async #handleValidationAck(msg: BaseMessage): Promise<void> {
758
+ if(this.#stopped) return;
759
+ const ctx = this.#contextFor(msg);
760
+ if(!ctx) return;
761
+ try {
762
+ this.session.receive(msg);
763
+ this.#drainRejections(ctx);
764
+ this.#onPhaseMaybeChanged(ctx);
765
+ const approved = !!msg.body?.approved;
766
+ this.emit('validation-received', { cohortId: ctx.cohortId, participantDid: msg.from, approved });
767
+
768
+ const phase = this.session.getCohortPhase(ctx.cohortId);
769
+
770
+ // A participant rejection flips the cohort to Failed. Emit a structured
771
+ // event so the runner/caller sees the failure instead of the cohort
772
+ // silently stalling.
773
+ if(phase === ServiceCohortPhase.Failed) {
774
+ const reason = `Validation rejected by participant ${msg.from}`;
775
+ this.emit('cohort-failed', { cohortId: ctx.cohortId, reason });
776
+ this.#failCohort(ctx, new Error(reason));
777
+ return;
778
+ }
779
+
780
+ // When all validations received, request tx data and start signing
781
+ if(phase === ServiceCohortPhase.Validated) {
782
+ const cohort = this.session.getCohort(ctx.cohortId)!;
783
+ const txData = await this.#onProvideTxData({
784
+ cohortId : ctx.cohortId,
785
+ beaconAddress : cohort.beaconAddress,
786
+ signalBytes : cohort.signalBytes!,
787
+ feeEstimator : this.#feeEstimator,
788
+ });
789
+ const authMsgs = this.session.startSigning(ctx.cohortId, txData);
790
+ const sessionId = this.session.getSigningSessionId(ctx.cohortId) ?? '';
791
+ this.emit('signing-started', { cohortId: ctx.cohortId, sessionId });
792
+ await this.#sendAll(authMsgs);
793
+ }
794
+ } catch(err) {
795
+ this.#failCohort(ctx, err as Error);
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Handler for receiving nonce contributions. When all nonces are received, sends the aggregated
801
+ * nonce back to the cohort.
802
+ * @param {BaseMessage} msg - The incoming message to handle.
803
+ * @returns {Promise<void>} Resolves when handling is complete.
804
+ */
805
+ async #handleNonceContribution(msg: BaseMessage): Promise<void> {
806
+ if(this.#stopped) return;
807
+ const ctx = this.#contextFor(msg);
808
+ if(!ctx) return;
809
+ try {
810
+ this.session.receive(msg);
811
+ this.#drainRejections(ctx);
812
+ this.#onPhaseMaybeChanged(ctx);
813
+ this.emit('nonce-received', { cohortId: ctx.cohortId, participantDid: msg.from });
814
+
815
+ // When all nonces collected, send aggregated nonce
816
+ if(this.session.getCohortPhase(ctx.cohortId) === ServiceCohortPhase.NoncesCollected) {
817
+ await this.#sendAll(this.session.sendAggregatedNonce(ctx.cohortId));
818
+ }
819
+ } catch(err) {
820
+ this.#failCohort(ctx, err as Error);
821
+ }
822
+ }
823
+
824
+ /**
825
+ * Handler for receiving signature authorizations. When all partial signatures are received, the
826
+ * session automatically completes; the final result is emitted and the cohort's completion
827
+ * promise resolves.
828
+ * @param {BaseMessage} msg - The incoming message to handle.
829
+ * @returns {Promise<void>} Resolves when handling is complete.
830
+ */
831
+ async #handleSignatureAuthorization(msg: BaseMessage): Promise<void> {
832
+ if(this.#stopped) return;
833
+ const ctx = this.#contextFor(msg);
834
+ if(!ctx) return;
835
+ try {
836
+ this.session.receive(msg);
837
+ this.#drainRejections(ctx);
838
+ this.#onPhaseMaybeChanged(ctx);
839
+
840
+ // If the cohort already committed to the fallback path, ignore a late
841
+ // optimistic completion: only one path may finalize the single beacon UTXO.
842
+ if(ctx.committedPath === 'fallback') return;
843
+
844
+ // The state machine auto-completes when all partial sigs received.
845
+ const result = this.session.getResult(ctx.cohortId);
846
+ if(result) {
847
+ ctx.committedPath = 'optimistic';
848
+ this.#completeCohort(ctx, result);
849
+ }
850
+ } catch(err) {
851
+ this.#failCohort(ctx, err as Error);
852
+ }
853
+ }
854
+
855
+ /**
856
+ * Handler for receiving fallback (k-of-n script-path) signatures. The state
857
+ * machine assembles and finalizes the fallback spend once k valid signatures
858
+ * are in; the result is then emitted and the cohort's completion resolves. The
859
+ * cohort is already committed to the fallback path (via {@link triggerFallback}).
860
+ * @param {BaseMessage} msg - The incoming FALLBACK_SIGNATURE message.
861
+ * @returns {Promise<void>} Resolves when handling is complete.
862
+ */
863
+ async #handleFallbackSignature(msg: BaseMessage): Promise<void> {
864
+ if(this.#stopped) return;
865
+ const ctx = this.#contextFor(msg);
866
+ if(!ctx) return;
867
+ try {
868
+ this.session.receive(msg);
869
+ this.#drainRejections(ctx);
870
+ this.#onPhaseMaybeChanged(ctx);
871
+
872
+ const result = this.session.getResult(ctx.cohortId);
873
+ if(result) {
874
+ this.#completeCohort(ctx, result);
875
+ }
876
+ } catch(err) {
877
+ this.#failCohort(ctx, err as Error);
878
+ }
879
+ }
880
+
881
+ /**
882
+ * Internal: helper to send all messages sequentially. Catches and propagates errors.
883
+ * @param {BaseMessage[]} msgs - The messages to send.
884
+ * @returns {Promise<void>} Resolves when all messages have been sent.
885
+ */
886
+ async #sendAll(msgs: BaseMessage[]): Promise<void> {
887
+ for(const m of msgs) {
888
+ await this.#transport.sendMessage(m, this.#did, m.to);
889
+ }
890
+ }
891
+ }