@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,576 @@
1
+ import type { Did } from '@did-btcr2/common';
2
+ import type { SchnorrKeyPair } from '@did-btcr2/keypair';
3
+ import { CompressedSecp256k1PublicKey } from '@did-btcr2/keypair';
4
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
5
+ import type { SubCloser } from 'nostr-tools/abstract-pool';
6
+ import type { Event, EventTemplate} from 'nostr-tools';
7
+ import { finalizeEvent, nip44 } from 'nostr-tools';
8
+ import { SimplePool } from 'nostr-tools/pool';
9
+ import type { Logger } from '../logger.js';
10
+ import { CONSOLE_LOGGER } from '../logger.js';
11
+ import type { BaseMessage } from '../messages/base.js';
12
+ import { COHORT_ADVERT } from '../messages/constants.js';
13
+ import { isAggregationMessageType, isKeygenMessageType, isSignMessageType, isUpdateMessageType } from '../messages/guards.js';
14
+ import { TransportAdapterError } from './error.js';
15
+ import type { MessageHandler, Transport } from './transport.js';
16
+
17
+ /**
18
+ * Default Nostr relay URLs.
19
+ * @constant {Array<string>} DEFAULT_NOSTR_RELAYS
20
+ */
21
+ export const DEFAULT_NOSTR_RELAYS = [
22
+ 'wss://relay.damus.io',
23
+ 'wss://nos.lol',
24
+ 'wss://relay.snort.social',
25
+ 'wss://nostr-pub.wellorder.net',
26
+ ];
27
+
28
+ export interface NostrTransportConfig {
29
+ relays?: string[];
30
+ /**
31
+ * Optional logger for transport-level diagnostics (publish/subscribe events,
32
+ * relay rejections, parse failures). Defaults to {@link CONSOLE_LOGGER}.
33
+ */
34
+ logger?: Logger;
35
+ /**
36
+ * How far back (in milliseconds) to set the `since` filter on the broadcast
37
+ * (COHORT_ADVERT) subscription. Some public relays do NOT replay historical
38
+ * events to late subscribers when the filter has no `since`, so the advert
39
+ * gets lost if the subscription lands after the publish. A short lookback
40
+ * window nudges those relays into delivering recent adverts. Set to 0 to
41
+ * disable the filter entirely (unbounded history). Defaults to
42
+ * {@link DEFAULT_BROADCAST_LOOKBACK_MS} (5 minutes).
43
+ */
44
+ broadcastLookbackMs?: number;
45
+ }
46
+
47
+ /** Default `since` lookback for broadcast (COHORT_ADVERT) subscriptions: 5 minutes. */
48
+ export const DEFAULT_BROADCAST_LOOKBACK_MS = 5 * 60 * 1000;
49
+
50
+ /** Internal registration for a single actor sharing this transport. */
51
+ interface ActorEntry {
52
+ keys: SchnorrKeyPair;
53
+ handlers: Map<string, MessageHandler>;
54
+ /** Relay-pool subscriptions opened for this actor. Closed on unregisterActor(). */
55
+ subscriptions: SubCloser[];
56
+ }
57
+
58
+ /**
59
+ * Nostr Transport for did:btcr2 aggregation messages.
60
+ *
61
+ * A single NostrTransport manages one relay pool and supports multiple
62
+ * registered actors. Each actor registers its own DID and keys via
63
+ * {@link registerActor}; the transport resolves the correct identity when
64
+ * sending or receiving.
65
+ *
66
+ * Message routing:
67
+ * - Keygen messages (COHORT_ADVERT, COHORT_OPT_IN, COHORT_OPT_IN_ACCEPT, COHORT_READY) to kind 1 (plaintext)
68
+ * - Update messages (SUBMIT_UPDATE, DISTRIBUTE_AGGREGATED_DATA, VALIDATION_ACK) to kind 1059 (NIP-44 encrypted)
69
+ * - Sign messages to kind 1059 (NIP-44 encrypted)
70
+ *
71
+ * @class NostrTransport
72
+ * @implements {Transport}
73
+ */
74
+ export class NostrTransport implements Transport {
75
+ name: string = 'nostr';
76
+
77
+ pool?: SimplePool;
78
+ #relays: string[];
79
+ #actors: Map<string, ActorEntry> = new Map();
80
+ #peerRegistry: Map<string, Uint8Array> = new Map();
81
+ #started = false;
82
+ #logger: Logger;
83
+ #broadcastLookbackMs: number;
84
+
85
+ constructor(config?: NostrTransportConfig) {
86
+ this.#relays = config?.relays ?? DEFAULT_NOSTR_RELAYS;
87
+ this.#logger = config?.logger ?? CONSOLE_LOGGER;
88
+ this.#broadcastLookbackMs = config?.broadcastLookbackMs ?? DEFAULT_BROADCAST_LOOKBACK_MS;
89
+ }
90
+
91
+ /**
92
+ * Registers an actor (DID + keys) to send/receive messages with.
93
+ * Must be called before start() to ensure subscriptions are created for the actor.
94
+ * @param {string} did - The DID of the actor.
95
+ * @param {SchnorrKeyPair} keys - The Schnorr key pair for the actor.
96
+ * @throws {TransportAdapterError} If the actor is already registered or if the transport has already started.
97
+ * @example
98
+ * const transport = new NostrTransport();
99
+ * const keys = SchnorrKeyPair.generate();
100
+ * const did = DidBtcr2.create(keys.publicKey.compressed, { idType: 'KEY', network: 'mutinynet' });
101
+ * transport.registerActor(did, keys);
102
+ * transport.start();
103
+ */
104
+ registerActor(did: string, keys: SchnorrKeyPair): void {
105
+ const entry: ActorEntry = { keys, handlers: new Map(), subscriptions: [] };
106
+ this.#actors.set(did, entry);
107
+
108
+ // If already started, create a directed subscription for this actor
109
+ if(this.#started && this.pool) {
110
+ this.#subscribeDirected(did, entry);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Detach an actor: drop its handlers, close its relay subscriptions, and remove its keys + peer
116
+ * mapping. Idempotent.
117
+ * @param {string} did - The DID of the actor to unregister.
118
+ * @returns {void}
119
+ * @throws {TransportAdapterError} If the transport is not started or if the pool is unavailable.
120
+ * @example
121
+ * transport.unregisterActor(did);
122
+ */
123
+ unregisterActor(did: string): void {
124
+ const entry = this.#actors.get(did);
125
+ if(!entry) return;
126
+ for(const sub of entry.subscriptions) {
127
+ try { sub.close(); } catch(err) { this.#logger.debug(`Error closing subscription for ${did}:`, err); }
128
+ }
129
+ entry.subscriptions.length = 0;
130
+ entry.handlers.clear();
131
+ this.#actors.delete(did);
132
+ this.#peerRegistry.delete(did);
133
+ }
134
+
135
+ /**
136
+ * Remove a single (actor, messageType) handler. Idempotent.
137
+ * @param {string} actorDid - The DID of the actor.
138
+ * @param {string} messageType - The type of message to unregister the handler for.
139
+ * @returns {void}
140
+ * @example
141
+ * transport.unregisterMessageHandler(actorDid, messageType);
142
+ */
143
+ unregisterMessageHandler(actorDid: string, messageType: string): void {
144
+ const actor = this.#actors.get(actorDid);
145
+ if(!actor) return;
146
+ actor.handlers.delete(messageType);
147
+ }
148
+
149
+ /**
150
+ * Gets the public key for a registered actor by their DID.
151
+ * @param {string} did - The DID of the registered actor to get the public key for.
152
+ * @returns {Uint8Array | undefined} The compressed public key bytes for the actor's DID, or
153
+ * undefined if the DID is not registered.
154
+ */
155
+ getActorPk(did: string): Uint8Array | undefined {
156
+ return this.#actors.get(did)?.keys.publicKey.compressed;
157
+ }
158
+
159
+ /**
160
+ * Registers a peer's communication public key for encrypted messages.
161
+ * @param {string} did - The DID of the peer to register.
162
+ * @param {Uint8Array} communicationPk - The compressed secp256k1 public key bytes for the peer.
163
+ */
164
+ registerPeer(did: string, communicationPk: Uint8Array): void {
165
+ try {
166
+ new CompressedSecp256k1PublicKey(communicationPk);
167
+ } catch {
168
+ throw new TransportAdapterError(
169
+ `Invalid communication public key for peer ${did}: expected a 33-byte compressed secp256k1 key.`,
170
+ 'INVALID_PEER_KEY', { adapter: this.name, did, keyLength: communicationPk.length }
171
+ );
172
+ }
173
+ this.#peerRegistry.set(did, communicationPk);
174
+ }
175
+
176
+ /**
177
+ * Gets the registered communication public key for a peer by their DID.
178
+ * @param {string} did - The DID of the peer to get the communication public key for.
179
+ * @returns {Uint8Array | undefined} The compressed secp256k1 public key bytes for the peer, or
180
+ * undefined if the peer is not registered.
181
+ */
182
+ getPeerPk(did: string): Uint8Array | undefined {
183
+ return this.#peerRegistry.get(did);
184
+ }
185
+
186
+ /**
187
+ * Registers a message handler function for a specific actor and message type. The handler will be called
188
+ * when a message of the specified type is received for the actor's DID. The transport must have been
189
+ * started for handlers to be invoked. If the transport is already started, the handler will be registered
190
+ * immediately; otherwise, it will be registered when the transport starts and the actor's subscription is created.
191
+ * @param {string} actorDid - The DID of the actor to register the message handler for.
192
+ * @param {string} messageType - The type of message to handle.
193
+ * @param {MessageHandler} handler - The function to handle incoming messages of the specified type.
194
+ * @throws {TransportAdapterError} If the actor DID is not registered or if the handler is invalid.
195
+ */
196
+ registerMessageHandler(actorDid: string, messageType: string, handler: MessageHandler): void {
197
+ const actor = this.#actors.get(actorDid);
198
+ if(!actor) {
199
+ throw new TransportAdapterError(
200
+ `Cannot register handler: actor ${actorDid} not registered. Call registerActor() first.`,
201
+ 'UNKNOWN_ACTOR_ERROR', { adapter: this.name, did: actorDid }
202
+ );
203
+ }
204
+ actor.handlers.set(messageType, handler);
205
+ }
206
+
207
+ /**
208
+ * Starts the transport by connecting to the configured Nostr relays and setting up subscriptions
209
+ * for all registered actors. This method must be called after registering actors via registerActor()
210
+ * and before sending or receiving messages. The transport will subscribe to broadcast events (kind 1)
211
+ * for cohort adverts and directed events (kinds 1 and 1059) for each registered actor based on their
212
+ * public keys. Incoming events are processed and dispatched to the appropriate handlers based on
213
+ * message type. If the transport is already started, this method has no effect.
214
+ * @returns {NostrTransport}
215
+ */
216
+ start(): NostrTransport {
217
+ if(this.#started) return this;
218
+ this.#started = true;
219
+
220
+ this.pool = new SimplePool();
221
+
222
+ // Broadcast subscription: kind 1 COHORT_ADVERT events (all actors receive
223
+ // these). Duplicate adverts are idempotent: AggregationParticipant stores
224
+ // discovered cohorts in a Map keyed by cohortId.
225
+ //
226
+ // The `since` filter is a workaround for relays that don't backfill
227
+ // historical events to late subscribers (observed on nos.lol and
228
+ // relay.snort.social). Without it, an advert published before a
229
+ // participant's subscription lands is lost on those relays. The default
230
+ // 5-minute window is generous enough to cover network + subscription
231
+ // setup delays while still excluding ancient traffic. Set
232
+ // broadcastLookbackMs to 0 to disable.
233
+ const broadcastFilter: { kinds: number[]; '#t': string[]; since?: number } = {
234
+ kinds : [1],
235
+ '#t' : [COHORT_ADVERT],
236
+ };
237
+ if(this.#broadcastLookbackMs > 0) {
238
+ broadcastFilter.since = Math.floor((Date.now() - this.#broadcastLookbackMs) / 1000);
239
+ }
240
+ this.pool.subscribeMany(this.#relays, broadcastFilter, {
241
+ onclose : (reasons: string[]) => this.#logger.debug('Nostr broadcast subscription closed', reasons),
242
+ onevent : this.#handleBroadcastEvent.bind(this),
243
+ });
244
+
245
+ // Directed subscriptions for any actors already registered
246
+ for(const [did, entry] of this.#actors) {
247
+ this.#subscribeDirected(did, entry);
248
+ }
249
+
250
+ this.#logger.info(`NostrTransport started, listening on ${this.#relays.length} relay(s)`);
251
+ return this;
252
+ }
253
+
254
+ /**
255
+ * Sends a message by publishing a Nostr event to the configured relays. The message is serialized
256
+ * as JSON and included in the event content.
257
+ * @param {BaseMessage} message - The aggregation message to send. Must include a valid `type` property.
258
+ * @param {Did} sender - The DID of the registered actor sending the message. Must have been
259
+ * registered via registerActor().
260
+ * @param {Did} [to] - Optional recipient DID for directed messages. Required for encrypted message
261
+ * types. If provided, must have been registered via registerPeer().
262
+ * @returns {Promise<void>} Resolves when the message has been published to the relays. Note that
263
+ * publication is best-effort: the method will resolve as long as at least one relay accepts the
264
+ * event, even if others reject it.
265
+ */
266
+ async sendMessage(message: BaseMessage, sender: Did, to?: Did): Promise<void> {
267
+ const type = message.type;
268
+
269
+ if(!type) {
270
+ throw new TransportAdapterError(
271
+ 'Message type is undefined',
272
+ 'SEND_MESSAGE_ERROR', { adapter: this.name, type }
273
+ );
274
+ }
275
+
276
+ const actor = this.#actors.get(sender);
277
+ if(!actor) {
278
+ throw new TransportAdapterError(
279
+ `Unknown sender: ${sender}. Call registerActor() before sending messages.`,
280
+ 'UNKNOWN_ACTOR_ERROR', { adapter: this.name, did: sender }
281
+ );
282
+ }
283
+
284
+ const senderKeys = actor.keys;
285
+
286
+ // Sender p-tag matches the event signing key
287
+ const tags: string[][] = [
288
+ ['p', bytesToHex(senderKeys.publicKey.x)],
289
+ ['t', type],
290
+ ];
291
+
292
+ if(to) {
293
+ const recipientPkBytes = this.#peerRegistry.get(to);
294
+ if(recipientPkBytes) {
295
+ const recipientPk = new CompressedSecp256k1PublicKey(recipientPkBytes);
296
+ tags.push(['p', bytesToHex(recipientPk.x)]);
297
+ }
298
+ }
299
+
300
+ // Keygen messages: plaintext, kind 1
301
+ if(isKeygenMessageType(type)) {
302
+ const event = finalizeEvent({
303
+ kind : 1,
304
+ created_at : Math.floor(Date.now() / 1000),
305
+ tags,
306
+ content : JSON.stringify(message, NostrTransport.#jsonReplacer),
307
+ } as EventTemplate, senderKeys.secretKey.bytes);
308
+ this.#logger.debug(`Publishing kind 1 [${type}]`);
309
+ await this.#publishToRelays(event);
310
+ return;
311
+ }
312
+
313
+ // Update and sign messages: NIP-44 encrypted, kind 1059
314
+ if(isUpdateMessageType(type) || isSignMessageType(type)) {
315
+ if(!to) {
316
+ throw new TransportAdapterError(
317
+ `Encrypted messages require a recipient DID, got undefined for type: ${type}`,
318
+ 'SEND_MESSAGE_ERROR', { adapter: this.name }
319
+ );
320
+ }
321
+ const recipientPkBytes = this.#peerRegistry.get(to);
322
+ if(!recipientPkBytes) {
323
+ throw new TransportAdapterError(
324
+ `Unknown peer DID: ${to}. Register peer via registerPeer() before sending encrypted messages.`,
325
+ 'UNKNOWN_PEER_ERROR', { adapter: this.name, did: to }
326
+ );
327
+ }
328
+ const recipientPk = new CompressedSecp256k1PublicKey(recipientPkBytes);
329
+ const conversationKey = nip44.v2.utils.getConversationKey(
330
+ senderKeys.secretKey.bytes,
331
+ bytesToHex(recipientPk.x)
332
+ );
333
+ const content = nip44.v2.encrypt(JSON.stringify(message, NostrTransport.#jsonReplacer), conversationKey);
334
+
335
+ const event = finalizeEvent({
336
+ kind : 1059,
337
+ created_at : Math.floor(Date.now() / 1000),
338
+ tags,
339
+ content,
340
+ } as EventTemplate, senderKeys.secretKey.bytes);
341
+ this.#logger.debug(`Publishing kind 1059 [${type}]`);
342
+ await this.#publishToRelays(event);
343
+ return;
344
+ }
345
+
346
+ this.#logger.warn(`Unsupported message type: ${type}`);
347
+ }
348
+
349
+ /**
350
+ * Publish the message once immediately and then re-publish on an interval
351
+ * until the returned stop function is invoked.
352
+ *
353
+ * Useful for broadcast messages (COHORT_ADVERT) on relays that don't
354
+ * backfill historical events to late subscribers: republishing gives late
355
+ * joiners a window to discover the message without requiring protocol
356
+ * changes. Relay rate-limit / publish failures inside the interval are
357
+ * caught and logged rather than propagated - the caller should stop the
358
+ * repeater once the protocol condition is satisfied.
359
+ */
360
+ publishRepeating(message: BaseMessage, sender: Did, intervalMs: number, recipient?: Did): () => void {
361
+ let stopped = false;
362
+ // Fire the first publish eagerly; any error surfaces as a rejected
363
+ // promise that we swallow to avoid unhandled rejections - the caller can
364
+ // observe delivery via receive-side handlers.
365
+ void this.sendMessage(message, sender, recipient).catch((err) => {
366
+ this.#logger.debug('publishRepeating first send failed:', err);
367
+ });
368
+ const timer = setInterval(() => {
369
+ if(stopped) return;
370
+ void this.sendMessage(message, sender, recipient).catch((err) => {
371
+ this.#logger.debug('publishRepeating retry failed:', err);
372
+ });
373
+ }, intervalMs);
374
+ return () => {
375
+ if(stopped) return;
376
+ stopped = true;
377
+ clearInterval(timer);
378
+ };
379
+ }
380
+
381
+ /**
382
+ * Creates a directed subscription for the given actor, filtering for messages that match the
383
+ * actor's public key. Messages received on this subscription are dispatched to the actor's
384
+ * registered handlers based on message type.
385
+ * @param {string} did - The DID of the actor to create the subscription for.
386
+ * @param {ActorEntry} entry - The actor's registration entry containing keys and handlers.
387
+ * @returns {void}
388
+ * @throws {TransportAdapterError} If the transport is not started or if the pool is unavailable.
389
+ */
390
+ #subscribeDirected(did: string, entry: ActorEntry): void {
391
+ if(!this.pool) return;
392
+
393
+ const pkHex = bytesToHex(entry.keys.publicKey.x);
394
+
395
+ // No `since` filter: directed messages must be retrievable on reconnect /
396
+ // crash-recovery. Out-of-phase messages are silently dropped by the state
397
+ // machines (AggregationService, AggregationParticipant), so replayed stale
398
+ // messages are harmless.
399
+ const sub = this.pool.subscribeMany(this.#relays, { kinds: [1, 1059], '#p': [pkHex] }, {
400
+ onclose : (reasons: string[]) => this.#logger.debug(`Nostr directed subscription closed for ${did}`, reasons),
401
+ onevent : this.#makeActorEventHandler(did),
402
+ });
403
+ entry.subscriptions.push(sub);
404
+ }
405
+
406
+ /**
407
+ * Creates an event handler function for a specific actor that processes incoming events, decrypts
408
+ * if necessary, and dispatches messages to the actor's registered handlers based on message type.
409
+ * @param {string} actorDid - The DID of the actor to create the event handler for.
410
+ * @returns {(event: Event) => Promise<void>} An asynchronous event handler function that
411
+ * processes incoming events for the specified actor.
412
+ */
413
+ #makeActorEventHandler(actorDid: string): (event: Event) => Promise<void> {
414
+ return async (event: Event) => {
415
+ const actor = this.#actors.get(actorDid);
416
+ if(!actor) return;
417
+
418
+ // Relay self-echo: sendMessage() adds the sender's own pubkey to the
419
+ // event's `p` tags (so recipients can reply). The directed subscription
420
+ // filter `{'#p': [actor_pk]}` therefore matches every event this actor
421
+ // publishes. Skip - we don't need to process our own outgoing events,
422
+ // and attempting to NIP-44-decrypt them fails with "invalid MAC" because
423
+ // the content was encrypted for the recipient, not self.
424
+ if(event.pubkey === bytesToHex(actor.keys.publicKey.x)) return;
425
+
426
+ let message: Record<string, unknown>;
427
+
428
+ try {
429
+ if(event.kind === 1) {
430
+ message = JSON.parse(event.content, NostrTransport.#jsonReviver);
431
+ } else if(event.kind === 1059) {
432
+ const conversationKey = nip44.v2.utils.getConversationKey(
433
+ actor.keys.secretKey.bytes,
434
+ event.pubkey
435
+ );
436
+ const plaintext = nip44.v2.decrypt(event.content, conversationKey);
437
+ message = JSON.parse(plaintext, NostrTransport.#jsonReviver);
438
+ } else {
439
+ return;
440
+ }
441
+ } catch(err) {
442
+ this.#logger.debug(`Failed to parse event ${event.id} for ${actorDid}:`, err);
443
+ return;
444
+ }
445
+
446
+ this.#dispatchMessage(message, actor);
447
+ };
448
+ }
449
+
450
+ /**
451
+ * Handles incoming broadcast events (kind 1) by parsing the event content, validating it as an
452
+ * aggregation message, and dispatching it to all registered actors that have handlers for the
453
+ * message type. This is used for COHORT_ADVERT messages that need to be received by all actors
454
+ * regardless of DID.
455
+ * @param {Event} event - The Nostr event to handle, expected to be a kind 1 broadcast containing
456
+ * a COHORT_ADVERT message. The event content is parsed and dispatched to all registered actors
457
+ * that have handlers for the
458
+ * @returns
459
+ */
460
+ async #handleBroadcastEvent(event: Event): Promise<void> {
461
+ if(event.kind !== 1) return;
462
+
463
+ let message: Record<string, unknown>;
464
+ try {
465
+ message = JSON.parse(event.content, NostrTransport.#jsonReviver);
466
+ } catch(err) {
467
+ this.#logger.debug(`Failed to parse broadcast event ${event.id}:`, err);
468
+ return;
469
+ }
470
+
471
+ if(message.body && typeof message.body === 'object') {
472
+ message = { ...message, ...(message.body as Record<string, unknown>) };
473
+ }
474
+
475
+ const messageType = message.type as string;
476
+ if(!messageType || !isAggregationMessageType(messageType)) return;
477
+
478
+ // Dispatch to ALL actors that have a handler for this message type
479
+ for(const actor of this.#actors.values()) {
480
+ const handler = actor.handlers.get(messageType);
481
+ if(handler) await handler(message);
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Dispatches a parsed message to the appropriate handler of a registered actor based on message type.
487
+ * The message is expected to have already been parsed from the Nostr event content and validated as
488
+ * an aggregation message. If the message has a body, its properties are merged into the top-level
489
+ * message object for easier handler access. The message is then dispatched to the handler registered
490
+ * for its type, if one exists.
491
+ * @param {Record<string, unknown>} message - The message object parsed from a Nostr event, expected to
492
+ * @param {ActorEntry} actor - The registered actor entry containing keys and handlers to dispatch the message to.
493
+ * @returns {void}
494
+ * @throws {TransportAdapterError} If the message type is unsupported or if no handler is registered
495
+ * for the message type.
496
+ */
497
+ #dispatchMessage(message: Record<string, unknown>, actor: ActorEntry): void {
498
+ if(message.body && typeof message.body === 'object') {
499
+ message = { ...message, ...(message.body as Record<string, unknown>) };
500
+ }
501
+
502
+ const messageType = message.type as string;
503
+ if(!messageType || !isAggregationMessageType(messageType)) return;
504
+
505
+ const handler = actor.handlers.get(messageType);
506
+ if(handler) handler(message);
507
+ }
508
+
509
+ /**
510
+ * Publishes a Nostr event to the configured relays and handles the results. The method waits for all
511
+ * relay promises to settle and checks how many accepted or rejected the event. If all relays reject the event,
512
+ * an error is thrown. Otherwise, the method completes successfully even if some relays rejected the event,
513
+ * as long as at least one relay accepted it. Relay rejections are logged for debugging purposes.
514
+ * @param {Event} event - The Nostr event to publish to the configured relays. The event should already
515
+ * @returns {Promise<void>} A promise that resolves if the event was accepted by at least one relay, or rejects
516
+ * with a TransportAdapterError if all relays rejected the event.
517
+ * @throws {TransportAdapterError} If the pool is not initialized or if all relays reject the event.
518
+ */
519
+ async #publishToRelays(event: Event): Promise<void> {
520
+ const relayPromises = this.pool?.publish(this.#relays, event);
521
+ if(!relayPromises?.length) return;
522
+
523
+ const results = await Promise.allSettled(relayPromises);
524
+ const accepted = results.filter(r => r.status === 'fulfilled').length;
525
+ const rejected = results.filter(r => r.status === 'rejected');
526
+
527
+ for(const r of rejected) {
528
+ this.#logger.debug(`Relay rejected event ${event.id}: ${(r as PromiseRejectedResult).reason}`);
529
+ }
530
+
531
+ if(accepted === 0) {
532
+ throw new TransportAdapterError(
533
+ `All ${results.length} relay(s) rejected event ${event.id}`,
534
+ 'PUBLISH_ERROR', { adapter: this.name, reasons: rejected.map(r => String((r as PromiseRejectedResult).reason)) }
535
+ );
536
+ }
537
+ }
538
+
539
+ /**
540
+ * Custom JSON replacer to handle serialization of Uint8Array values as hex strings in message
541
+ * content. This allows messages containing binary data (e.g. public keys, signatures) to be correctly
542
+ * serialized to JSON for Nostr event content. The replacer checks if a value is a Uint8Array and, if so,
543
+ * converts it to a hex string wrapped in an object with a __bytes property. The corresponding reviver
544
+ * can then convert this back to a Uint8Array when parsing the message content from the event.
545
+ * @param {string} _key - The key of the property being processed.
546
+ * @param {unknown} value - The value to check if the message type is valid.
547
+ * @returns {unknown} The transformed value for JSON serialization. If the value is a Uint8Array,
548
+ * it returns an object with a __bytes property containing the hex string. Otherwise, it returns
549
+ * the value unchanged.
550
+ */
551
+ static #jsonReplacer(_key: string, value: unknown): unknown {
552
+ if(value instanceof Uint8Array) {
553
+ return { __bytes: bytesToHex(value) };
554
+ }
555
+ return value;
556
+ }
557
+
558
+ /**
559
+ * Custom JSON reviver to handle deserialization of hex strings back into Uint8Array values in message
560
+ * content. This complements the custom replacer used during serialization, allowing messages that contain
561
+ * binary data (e.g. public keys, signatures) to be correctly reconstructed when parsing JSON from
562
+ * Nostr event content. The reviver checks if a value is an object with a __bytes property and,
563
+ * if so, converts the hex string back into a Uint8Array. Otherwise, it returns the value unchanged.
564
+ * @param {string} _key - The key of the property being processed.
565
+ * @param {unknown} value - The value to check if it is an object containing a __bytes property for
566
+ * hex string conversion.
567
+ * @returns {unknown} The transformed value for JSON deserialization. If the value is an object
568
+ * with a __bytes property, it returns a Uint8Array. Otherwise, it returns the value unchanged.
569
+ */
570
+ static #jsonReviver(_key: string, value: unknown): unknown {
571
+ if(value && typeof value === 'object' && '__bytes' in (value as Record<string, unknown>)) {
572
+ return hexToBytes((value as { __bytes: string }).__bytes);
573
+ }
574
+ return value;
575
+ }
576
+ }
@@ -0,0 +1,79 @@
1
+ import type { SchnorrKeyPair } from '@did-btcr2/keypair';
2
+ import type { BaseMessage } from '../messages/base.js';
3
+
4
+ export type SyncMessageHandler = (msg: any) => void;
5
+ export type AsyncMessageHandler = (msg: any) => Promise<void>;
6
+ export type MessageHandler = SyncMessageHandler | AsyncMessageHandler;
7
+
8
+ export type TransportType = 'nostr' | 'didcomm' | 'http';
9
+
10
+ /**
11
+ * Multi-actor message transport.
12
+ *
13
+ * A single transport instance manages one connection (relay pool, channel, etc.)
14
+ * shared by all registered actors. Each actor registers its own DID and keys;
15
+ * the transport resolves the correct identity when sending or receiving messages.
16
+ *
17
+ * The transport is a pure passthrough: it knows nothing about the aggregation
18
+ * protocol. It only signs/encrypts outgoing messages with the sender's keys and
19
+ * dispatches incoming messages to the correct actor's registered handler.
20
+ *
21
+ * @interface Transport
22
+ */
23
+ export interface Transport {
24
+ name: string;
25
+
26
+ /** Start the underlying transport (idempotent, only starts once). */
27
+ start(): void;
28
+
29
+ /** Register an actor (service or participant) with this transport. */
30
+ registerActor(did: string, keys: SchnorrKeyPair): void;
31
+
32
+ /** Return a registered actor's compressed communication public key. */
33
+ getActorPk(did: string): Uint8Array | undefined;
34
+
35
+ /** Store a remote peer's communication public key for encrypted routing. */
36
+ registerPeer(did: string, communicationPk: Uint8Array): void;
37
+
38
+ /** Retrieve a remote peer's communication public key. */
39
+ getPeerPk(did: string): Uint8Array | undefined;
40
+
41
+ /** Register a message handler scoped to a specific actor. */
42
+ registerMessageHandler(actorDid: string, messageType: string, handler: MessageHandler): void;
43
+
44
+ /** Remove a previously-registered handler. No-op if not registered. */
45
+ unregisterMessageHandler(actorDid: string, messageType: string): void;
46
+
47
+ /**
48
+ * Detach an actor: unregister all its handlers, drop its keys, and close any
49
+ * transport-level subscriptions created for it. No-op if the actor is not
50
+ * registered.
51
+ */
52
+ unregisterActor(did: string): void;
53
+
54
+ /** Send a message. The transport looks up sender to resolve signing keys. */
55
+ sendMessage(message: BaseMessage, sender: string, recipient?: string): Promise<void>;
56
+
57
+ /**
58
+ * Publish the message once immediately and then repeat it on a fixed
59
+ * interval. Returns a stop function the caller MUST invoke when the repeat
60
+ * is no longer needed (e.g. once the protocol state that required the
61
+ * message is satisfied).
62
+ *
63
+ * Useful for broadcasts on transports that don't reliably backfill
64
+ * historical events to late subscribers (many Nostr relays): republishing
65
+ * gives late joiners a window in which to discover the message. The first
66
+ * publish is synchronous-ish (fired before the method returns).
67
+ *
68
+ * Callers specify `recipient` only for directed messages; for broadcasts
69
+ * it is omitted.
70
+ *
71
+ * @returns A stop function. Idempotent, safe to call more than once.
72
+ */
73
+ publishRepeating(
74
+ message: BaseMessage,
75
+ sender: string,
76
+ intervalMs: number,
77
+ recipient?: string,
78
+ ): () => void;
79
+ }