@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,491 @@
1
+ var _a;
2
+ import { CompressedSecp256k1PublicKey } from '@did-btcr2/keypair';
3
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
4
+ import { finalizeEvent, nip44 } from 'nostr-tools';
5
+ import { SimplePool } from 'nostr-tools/pool';
6
+ import { CONSOLE_LOGGER } from '../logger.js';
7
+ import { COHORT_ADVERT } from '../messages/constants.js';
8
+ import { isAggregationMessageType, isKeygenMessageType, isSignMessageType, isUpdateMessageType } from '../messages/guards.js';
9
+ import { TransportAdapterError } from './error.js';
10
+ /**
11
+ * Default Nostr relay URLs.
12
+ * @constant {Array<string>} DEFAULT_NOSTR_RELAYS
13
+ */
14
+ export const DEFAULT_NOSTR_RELAYS = [
15
+ 'wss://relay.damus.io',
16
+ 'wss://nos.lol',
17
+ 'wss://relay.snort.social',
18
+ 'wss://nostr-pub.wellorder.net',
19
+ ];
20
+ /** Default `since` lookback for broadcast (COHORT_ADVERT) subscriptions: 5 minutes. */
21
+ export const DEFAULT_BROADCAST_LOOKBACK_MS = 5 * 60 * 1000;
22
+ /**
23
+ * Nostr Transport for did:btcr2 aggregation messages.
24
+ *
25
+ * A single NostrTransport manages one relay pool and supports multiple
26
+ * registered actors. Each actor registers its own DID and keys via
27
+ * {@link registerActor}; the transport resolves the correct identity when
28
+ * sending or receiving.
29
+ *
30
+ * Message routing:
31
+ * - Keygen messages (COHORT_ADVERT, COHORT_OPT_IN, COHORT_OPT_IN_ACCEPT, COHORT_READY) to kind 1 (plaintext)
32
+ * - Update messages (SUBMIT_UPDATE, DISTRIBUTE_AGGREGATED_DATA, VALIDATION_ACK) to kind 1059 (NIP-44 encrypted)
33
+ * - Sign messages to kind 1059 (NIP-44 encrypted)
34
+ *
35
+ * @class NostrTransport
36
+ * @implements {Transport}
37
+ */
38
+ export class NostrTransport {
39
+ name = 'nostr';
40
+ pool;
41
+ #relays;
42
+ #actors = new Map();
43
+ #peerRegistry = new Map();
44
+ #started = false;
45
+ #logger;
46
+ #broadcastLookbackMs;
47
+ constructor(config) {
48
+ this.#relays = config?.relays ?? DEFAULT_NOSTR_RELAYS;
49
+ this.#logger = config?.logger ?? CONSOLE_LOGGER;
50
+ this.#broadcastLookbackMs = config?.broadcastLookbackMs ?? DEFAULT_BROADCAST_LOOKBACK_MS;
51
+ }
52
+ /**
53
+ * Registers an actor (DID + keys) to send/receive messages with.
54
+ * Must be called before start() to ensure subscriptions are created for the actor.
55
+ * @param {string} did - The DID of the actor.
56
+ * @param {SchnorrKeyPair} keys - The Schnorr key pair for the actor.
57
+ * @throws {TransportAdapterError} If the actor is already registered or if the transport has already started.
58
+ * @example
59
+ * const transport = new NostrTransport();
60
+ * const keys = SchnorrKeyPair.generate();
61
+ * const did = DidBtcr2.create(keys.publicKey.compressed, { idType: 'KEY', network: 'mutinynet' });
62
+ * transport.registerActor(did, keys);
63
+ * transport.start();
64
+ */
65
+ registerActor(did, keys) {
66
+ const entry = { keys, handlers: new Map(), subscriptions: [] };
67
+ this.#actors.set(did, entry);
68
+ // If already started, create a directed subscription for this actor
69
+ if (this.#started && this.pool) {
70
+ this.#subscribeDirected(did, entry);
71
+ }
72
+ }
73
+ /**
74
+ * Detach an actor: drop its handlers, close its relay subscriptions, and remove its keys + peer
75
+ * mapping. Idempotent.
76
+ * @param {string} did - The DID of the actor to unregister.
77
+ * @returns {void}
78
+ * @throws {TransportAdapterError} If the transport is not started or if the pool is unavailable.
79
+ * @example
80
+ * transport.unregisterActor(did);
81
+ */
82
+ unregisterActor(did) {
83
+ const entry = this.#actors.get(did);
84
+ if (!entry)
85
+ return;
86
+ for (const sub of entry.subscriptions) {
87
+ try {
88
+ sub.close();
89
+ }
90
+ catch (err) {
91
+ this.#logger.debug(`Error closing subscription for ${did}:`, err);
92
+ }
93
+ }
94
+ entry.subscriptions.length = 0;
95
+ entry.handlers.clear();
96
+ this.#actors.delete(did);
97
+ this.#peerRegistry.delete(did);
98
+ }
99
+ /**
100
+ * Remove a single (actor, messageType) handler. Idempotent.
101
+ * @param {string} actorDid - The DID of the actor.
102
+ * @param {string} messageType - The type of message to unregister the handler for.
103
+ * @returns {void}
104
+ * @example
105
+ * transport.unregisterMessageHandler(actorDid, messageType);
106
+ */
107
+ unregisterMessageHandler(actorDid, messageType) {
108
+ const actor = this.#actors.get(actorDid);
109
+ if (!actor)
110
+ return;
111
+ actor.handlers.delete(messageType);
112
+ }
113
+ /**
114
+ * Gets the public key for a registered actor by their DID.
115
+ * @param {string} did - The DID of the registered actor to get the public key for.
116
+ * @returns {Uint8Array | undefined} The compressed public key bytes for the actor's DID, or
117
+ * undefined if the DID is not registered.
118
+ */
119
+ getActorPk(did) {
120
+ return this.#actors.get(did)?.keys.publicKey.compressed;
121
+ }
122
+ /**
123
+ * Registers a peer's communication public key for encrypted messages.
124
+ * @param {string} did - The DID of the peer to register.
125
+ * @param {Uint8Array} communicationPk - The compressed secp256k1 public key bytes for the peer.
126
+ */
127
+ registerPeer(did, communicationPk) {
128
+ try {
129
+ new CompressedSecp256k1PublicKey(communicationPk);
130
+ }
131
+ catch {
132
+ throw new TransportAdapterError(`Invalid communication public key for peer ${did}: expected a 33-byte compressed secp256k1 key.`, 'INVALID_PEER_KEY', { adapter: this.name, did, keyLength: communicationPk.length });
133
+ }
134
+ this.#peerRegistry.set(did, communicationPk);
135
+ }
136
+ /**
137
+ * Gets the registered communication public key for a peer by their DID.
138
+ * @param {string} did - The DID of the peer to get the communication public key for.
139
+ * @returns {Uint8Array | undefined} The compressed secp256k1 public key bytes for the peer, or
140
+ * undefined if the peer is not registered.
141
+ */
142
+ getPeerPk(did) {
143
+ return this.#peerRegistry.get(did);
144
+ }
145
+ /**
146
+ * Registers a message handler function for a specific actor and message type. The handler will be called
147
+ * when a message of the specified type is received for the actor's DID. The transport must have been
148
+ * started for handlers to be invoked. If the transport is already started, the handler will be registered
149
+ * immediately; otherwise, it will be registered when the transport starts and the actor's subscription is created.
150
+ * @param {string} actorDid - The DID of the actor to register the message handler for.
151
+ * @param {string} messageType - The type of message to handle.
152
+ * @param {MessageHandler} handler - The function to handle incoming messages of the specified type.
153
+ * @throws {TransportAdapterError} If the actor DID is not registered or if the handler is invalid.
154
+ */
155
+ registerMessageHandler(actorDid, messageType, handler) {
156
+ const actor = this.#actors.get(actorDid);
157
+ if (!actor) {
158
+ throw new TransportAdapterError(`Cannot register handler: actor ${actorDid} not registered. Call registerActor() first.`, 'UNKNOWN_ACTOR_ERROR', { adapter: this.name, did: actorDid });
159
+ }
160
+ actor.handlers.set(messageType, handler);
161
+ }
162
+ /**
163
+ * Starts the transport by connecting to the configured Nostr relays and setting up subscriptions
164
+ * for all registered actors. This method must be called after registering actors via registerActor()
165
+ * and before sending or receiving messages. The transport will subscribe to broadcast events (kind 1)
166
+ * for cohort adverts and directed events (kinds 1 and 1059) for each registered actor based on their
167
+ * public keys. Incoming events are processed and dispatched to the appropriate handlers based on
168
+ * message type. If the transport is already started, this method has no effect.
169
+ * @returns {NostrTransport}
170
+ */
171
+ start() {
172
+ if (this.#started)
173
+ return this;
174
+ this.#started = true;
175
+ this.pool = new SimplePool();
176
+ // Broadcast subscription: kind 1 COHORT_ADVERT events (all actors receive
177
+ // these). Duplicate adverts are idempotent: AggregationParticipant stores
178
+ // discovered cohorts in a Map keyed by cohortId.
179
+ //
180
+ // The `since` filter is a workaround for relays that don't backfill
181
+ // historical events to late subscribers (observed on nos.lol and
182
+ // relay.snort.social). Without it, an advert published before a
183
+ // participant's subscription lands is lost on those relays. The default
184
+ // 5-minute window is generous enough to cover network + subscription
185
+ // setup delays while still excluding ancient traffic. Set
186
+ // broadcastLookbackMs to 0 to disable.
187
+ const broadcastFilter = {
188
+ kinds: [1],
189
+ '#t': [COHORT_ADVERT],
190
+ };
191
+ if (this.#broadcastLookbackMs > 0) {
192
+ broadcastFilter.since = Math.floor((Date.now() - this.#broadcastLookbackMs) / 1000);
193
+ }
194
+ this.pool.subscribeMany(this.#relays, broadcastFilter, {
195
+ onclose: (reasons) => this.#logger.debug('Nostr broadcast subscription closed', reasons),
196
+ onevent: this.#handleBroadcastEvent.bind(this),
197
+ });
198
+ // Directed subscriptions for any actors already registered
199
+ for (const [did, entry] of this.#actors) {
200
+ this.#subscribeDirected(did, entry);
201
+ }
202
+ this.#logger.info(`NostrTransport started, listening on ${this.#relays.length} relay(s)`);
203
+ return this;
204
+ }
205
+ /**
206
+ * Sends a message by publishing a Nostr event to the configured relays. The message is serialized
207
+ * as JSON and included in the event content.
208
+ * @param {BaseMessage} message - The aggregation message to send. Must include a valid `type` property.
209
+ * @param {Did} sender - The DID of the registered actor sending the message. Must have been
210
+ * registered via registerActor().
211
+ * @param {Did} [to] - Optional recipient DID for directed messages. Required for encrypted message
212
+ * types. If provided, must have been registered via registerPeer().
213
+ * @returns {Promise<void>} Resolves when the message has been published to the relays. Note that
214
+ * publication is best-effort: the method will resolve as long as at least one relay accepts the
215
+ * event, even if others reject it.
216
+ */
217
+ async sendMessage(message, sender, to) {
218
+ const type = message.type;
219
+ if (!type) {
220
+ throw new TransportAdapterError('Message type is undefined', 'SEND_MESSAGE_ERROR', { adapter: this.name, type });
221
+ }
222
+ const actor = this.#actors.get(sender);
223
+ if (!actor) {
224
+ throw new TransportAdapterError(`Unknown sender: ${sender}. Call registerActor() before sending messages.`, 'UNKNOWN_ACTOR_ERROR', { adapter: this.name, did: sender });
225
+ }
226
+ const senderKeys = actor.keys;
227
+ // Sender p-tag matches the event signing key
228
+ const tags = [
229
+ ['p', bytesToHex(senderKeys.publicKey.x)],
230
+ ['t', type],
231
+ ];
232
+ if (to) {
233
+ const recipientPkBytes = this.#peerRegistry.get(to);
234
+ if (recipientPkBytes) {
235
+ const recipientPk = new CompressedSecp256k1PublicKey(recipientPkBytes);
236
+ tags.push(['p', bytesToHex(recipientPk.x)]);
237
+ }
238
+ }
239
+ // Keygen messages: plaintext, kind 1
240
+ if (isKeygenMessageType(type)) {
241
+ const event = finalizeEvent({
242
+ kind: 1,
243
+ created_at: Math.floor(Date.now() / 1000),
244
+ tags,
245
+ content: JSON.stringify(message, _a.#jsonReplacer),
246
+ }, senderKeys.secretKey.bytes);
247
+ this.#logger.debug(`Publishing kind 1 [${type}]`);
248
+ await this.#publishToRelays(event);
249
+ return;
250
+ }
251
+ // Update and sign messages: NIP-44 encrypted, kind 1059
252
+ if (isUpdateMessageType(type) || isSignMessageType(type)) {
253
+ if (!to) {
254
+ throw new TransportAdapterError(`Encrypted messages require a recipient DID, got undefined for type: ${type}`, 'SEND_MESSAGE_ERROR', { adapter: this.name });
255
+ }
256
+ const recipientPkBytes = this.#peerRegistry.get(to);
257
+ if (!recipientPkBytes) {
258
+ throw new TransportAdapterError(`Unknown peer DID: ${to}. Register peer via registerPeer() before sending encrypted messages.`, 'UNKNOWN_PEER_ERROR', { adapter: this.name, did: to });
259
+ }
260
+ const recipientPk = new CompressedSecp256k1PublicKey(recipientPkBytes);
261
+ const conversationKey = nip44.v2.utils.getConversationKey(senderKeys.secretKey.bytes, bytesToHex(recipientPk.x));
262
+ const content = nip44.v2.encrypt(JSON.stringify(message, _a.#jsonReplacer), conversationKey);
263
+ const event = finalizeEvent({
264
+ kind: 1059,
265
+ created_at: Math.floor(Date.now() / 1000),
266
+ tags,
267
+ content,
268
+ }, senderKeys.secretKey.bytes);
269
+ this.#logger.debug(`Publishing kind 1059 [${type}]`);
270
+ await this.#publishToRelays(event);
271
+ return;
272
+ }
273
+ this.#logger.warn(`Unsupported message type: ${type}`);
274
+ }
275
+ /**
276
+ * Publish the message once immediately and then re-publish on an interval
277
+ * until the returned stop function is invoked.
278
+ *
279
+ * Useful for broadcast messages (COHORT_ADVERT) on relays that don't
280
+ * backfill historical events to late subscribers: republishing gives late
281
+ * joiners a window to discover the message without requiring protocol
282
+ * changes. Relay rate-limit / publish failures inside the interval are
283
+ * caught and logged rather than propagated - the caller should stop the
284
+ * repeater once the protocol condition is satisfied.
285
+ */
286
+ publishRepeating(message, sender, intervalMs, recipient) {
287
+ let stopped = false;
288
+ // Fire the first publish eagerly; any error surfaces as a rejected
289
+ // promise that we swallow to avoid unhandled rejections - the caller can
290
+ // observe delivery via receive-side handlers.
291
+ void this.sendMessage(message, sender, recipient).catch((err) => {
292
+ this.#logger.debug('publishRepeating first send failed:', err);
293
+ });
294
+ const timer = setInterval(() => {
295
+ if (stopped)
296
+ return;
297
+ void this.sendMessage(message, sender, recipient).catch((err) => {
298
+ this.#logger.debug('publishRepeating retry failed:', err);
299
+ });
300
+ }, intervalMs);
301
+ return () => {
302
+ if (stopped)
303
+ return;
304
+ stopped = true;
305
+ clearInterval(timer);
306
+ };
307
+ }
308
+ /**
309
+ * Creates a directed subscription for the given actor, filtering for messages that match the
310
+ * actor's public key. Messages received on this subscription are dispatched to the actor's
311
+ * registered handlers based on message type.
312
+ * @param {string} did - The DID of the actor to create the subscription for.
313
+ * @param {ActorEntry} entry - The actor's registration entry containing keys and handlers.
314
+ * @returns {void}
315
+ * @throws {TransportAdapterError} If the transport is not started or if the pool is unavailable.
316
+ */
317
+ #subscribeDirected(did, entry) {
318
+ if (!this.pool)
319
+ return;
320
+ const pkHex = bytesToHex(entry.keys.publicKey.x);
321
+ // No `since` filter: directed messages must be retrievable on reconnect /
322
+ // crash-recovery. Out-of-phase messages are silently dropped by the state
323
+ // machines (AggregationService, AggregationParticipant), so replayed stale
324
+ // messages are harmless.
325
+ const sub = this.pool.subscribeMany(this.#relays, { kinds: [1, 1059], '#p': [pkHex] }, {
326
+ onclose: (reasons) => this.#logger.debug(`Nostr directed subscription closed for ${did}`, reasons),
327
+ onevent: this.#makeActorEventHandler(did),
328
+ });
329
+ entry.subscriptions.push(sub);
330
+ }
331
+ /**
332
+ * Creates an event handler function for a specific actor that processes incoming events, decrypts
333
+ * if necessary, and dispatches messages to the actor's registered handlers based on message type.
334
+ * @param {string} actorDid - The DID of the actor to create the event handler for.
335
+ * @returns {(event: Event) => Promise<void>} An asynchronous event handler function that
336
+ * processes incoming events for the specified actor.
337
+ */
338
+ #makeActorEventHandler(actorDid) {
339
+ return async (event) => {
340
+ const actor = this.#actors.get(actorDid);
341
+ if (!actor)
342
+ return;
343
+ // Relay self-echo: sendMessage() adds the sender's own pubkey to the
344
+ // event's `p` tags (so recipients can reply). The directed subscription
345
+ // filter `{'#p': [actor_pk]}` therefore matches every event this actor
346
+ // publishes. Skip - we don't need to process our own outgoing events,
347
+ // and attempting to NIP-44-decrypt them fails with "invalid MAC" because
348
+ // the content was encrypted for the recipient, not self.
349
+ if (event.pubkey === bytesToHex(actor.keys.publicKey.x))
350
+ return;
351
+ let message;
352
+ try {
353
+ if (event.kind === 1) {
354
+ message = JSON.parse(event.content, _a.#jsonReviver);
355
+ }
356
+ else if (event.kind === 1059) {
357
+ const conversationKey = nip44.v2.utils.getConversationKey(actor.keys.secretKey.bytes, event.pubkey);
358
+ const plaintext = nip44.v2.decrypt(event.content, conversationKey);
359
+ message = JSON.parse(plaintext, _a.#jsonReviver);
360
+ }
361
+ else {
362
+ return;
363
+ }
364
+ }
365
+ catch (err) {
366
+ this.#logger.debug(`Failed to parse event ${event.id} for ${actorDid}:`, err);
367
+ return;
368
+ }
369
+ this.#dispatchMessage(message, actor);
370
+ };
371
+ }
372
+ /**
373
+ * Handles incoming broadcast events (kind 1) by parsing the event content, validating it as an
374
+ * aggregation message, and dispatching it to all registered actors that have handlers for the
375
+ * message type. This is used for COHORT_ADVERT messages that need to be received by all actors
376
+ * regardless of DID.
377
+ * @param {Event} event - The Nostr event to handle, expected to be a kind 1 broadcast containing
378
+ * a COHORT_ADVERT message. The event content is parsed and dispatched to all registered actors
379
+ * that have handlers for the
380
+ * @returns
381
+ */
382
+ async #handleBroadcastEvent(event) {
383
+ if (event.kind !== 1)
384
+ return;
385
+ let message;
386
+ try {
387
+ message = JSON.parse(event.content, _a.#jsonReviver);
388
+ }
389
+ catch (err) {
390
+ this.#logger.debug(`Failed to parse broadcast event ${event.id}:`, err);
391
+ return;
392
+ }
393
+ if (message.body && typeof message.body === 'object') {
394
+ message = { ...message, ...message.body };
395
+ }
396
+ const messageType = message.type;
397
+ if (!messageType || !isAggregationMessageType(messageType))
398
+ return;
399
+ // Dispatch to ALL actors that have a handler for this message type
400
+ for (const actor of this.#actors.values()) {
401
+ const handler = actor.handlers.get(messageType);
402
+ if (handler)
403
+ await handler(message);
404
+ }
405
+ }
406
+ /**
407
+ * Dispatches a parsed message to the appropriate handler of a registered actor based on message type.
408
+ * The message is expected to have already been parsed from the Nostr event content and validated as
409
+ * an aggregation message. If the message has a body, its properties are merged into the top-level
410
+ * message object for easier handler access. The message is then dispatched to the handler registered
411
+ * for its type, if one exists.
412
+ * @param {Record<string, unknown>} message - The message object parsed from a Nostr event, expected to
413
+ * @param {ActorEntry} actor - The registered actor entry containing keys and handlers to dispatch the message to.
414
+ * @returns {void}
415
+ * @throws {TransportAdapterError} If the message type is unsupported or if no handler is registered
416
+ * for the message type.
417
+ */
418
+ #dispatchMessage(message, actor) {
419
+ if (message.body && typeof message.body === 'object') {
420
+ message = { ...message, ...message.body };
421
+ }
422
+ const messageType = message.type;
423
+ if (!messageType || !isAggregationMessageType(messageType))
424
+ return;
425
+ const handler = actor.handlers.get(messageType);
426
+ if (handler)
427
+ handler(message);
428
+ }
429
+ /**
430
+ * Publishes a Nostr event to the configured relays and handles the results. The method waits for all
431
+ * relay promises to settle and checks how many accepted or rejected the event. If all relays reject the event,
432
+ * an error is thrown. Otherwise, the method completes successfully even if some relays rejected the event,
433
+ * as long as at least one relay accepted it. Relay rejections are logged for debugging purposes.
434
+ * @param {Event} event - The Nostr event to publish to the configured relays. The event should already
435
+ * @returns {Promise<void>} A promise that resolves if the event was accepted by at least one relay, or rejects
436
+ * with a TransportAdapterError if all relays rejected the event.
437
+ * @throws {TransportAdapterError} If the pool is not initialized or if all relays reject the event.
438
+ */
439
+ async #publishToRelays(event) {
440
+ const relayPromises = this.pool?.publish(this.#relays, event);
441
+ if (!relayPromises?.length)
442
+ return;
443
+ const results = await Promise.allSettled(relayPromises);
444
+ const accepted = results.filter(r => r.status === 'fulfilled').length;
445
+ const rejected = results.filter(r => r.status === 'rejected');
446
+ for (const r of rejected) {
447
+ this.#logger.debug(`Relay rejected event ${event.id}: ${r.reason}`);
448
+ }
449
+ if (accepted === 0) {
450
+ throw new TransportAdapterError(`All ${results.length} relay(s) rejected event ${event.id}`, 'PUBLISH_ERROR', { adapter: this.name, reasons: rejected.map(r => String(r.reason)) });
451
+ }
452
+ }
453
+ /**
454
+ * Custom JSON replacer to handle serialization of Uint8Array values as hex strings in message
455
+ * content. This allows messages containing binary data (e.g. public keys, signatures) to be correctly
456
+ * serialized to JSON for Nostr event content. The replacer checks if a value is a Uint8Array and, if so,
457
+ * converts it to a hex string wrapped in an object with a __bytes property. The corresponding reviver
458
+ * can then convert this back to a Uint8Array when parsing the message content from the event.
459
+ * @param {string} _key - The key of the property being processed.
460
+ * @param {unknown} value - The value to check if the message type is valid.
461
+ * @returns {unknown} The transformed value for JSON serialization. If the value is a Uint8Array,
462
+ * it returns an object with a __bytes property containing the hex string. Otherwise, it returns
463
+ * the value unchanged.
464
+ */
465
+ static #jsonReplacer(_key, value) {
466
+ if (value instanceof Uint8Array) {
467
+ return { __bytes: bytesToHex(value) };
468
+ }
469
+ return value;
470
+ }
471
+ /**
472
+ * Custom JSON reviver to handle deserialization of hex strings back into Uint8Array values in message
473
+ * content. This complements the custom replacer used during serialization, allowing messages that contain
474
+ * binary data (e.g. public keys, signatures) to be correctly reconstructed when parsing JSON from
475
+ * Nostr event content. The reviver checks if a value is an object with a __bytes property and,
476
+ * if so, converts the hex string back into a Uint8Array. Otherwise, it returns the value unchanged.
477
+ * @param {string} _key - The key of the property being processed.
478
+ * @param {unknown} value - The value to check if it is an object containing a __bytes property for
479
+ * hex string conversion.
480
+ * @returns {unknown} The transformed value for JSON deserialization. If the value is an object
481
+ * with a __bytes property, it returns a Uint8Array. Otherwise, it returns the value unchanged.
482
+ */
483
+ static #jsonReviver(_key, value) {
484
+ if (value && typeof value === 'object' && '__bytes' in value) {
485
+ return hexToBytes(value.__bytes);
486
+ }
487
+ return value;
488
+ }
489
+ }
490
+ _a = NostrTransport;
491
+ //# sourceMappingURL=nostr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nostr.js","sourceRoot":"","sources":["../../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,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACxC,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,YAAY,CAAC,IAAY,EAAE,KAAc;QAC9C,IAAG,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,SAAS,IAAK,KAAiC,EAAE,CAAC;YACzF,OAAO,UAAU,CAAE,KAA6B,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/transport/transport.ts"],"names":[],"mappings":""}
@@ -0,0 +1,56 @@
1
+ import type { SignedBTCR2Update } from '@did-btcr2/cryptosuite';
2
+ import type { SerializedSMTProof } from '@did-btcr2/smt';
3
+ import type { AggregationCohort } from './cohort.js';
4
+ import type { BaseBody } from './messages/base.js';
5
+ /** Validation result returned to the participant for a distribute-data message. */
6
+ export interface BeaconValidationResult {
7
+ matches: boolean;
8
+ casAnnouncement?: Record<string, string>;
9
+ smtProof?: SerializedSMTProof;
10
+ }
11
+ /** Per-participant body attached to DISTRIBUTE_AGGREGATED_DATA by the service. */
12
+ export interface BeaconDistributePayload {
13
+ casAnnouncement?: Record<string, string>;
14
+ smtProof?: Record<string, unknown>;
15
+ }
16
+ /**
17
+ * Pluggable strategy for beacon-type-specific aggregation, distribution, and
18
+ * participant-side validation. Lets new beacon types be added without
19
+ * modifying the service or participant state machines: register a new strategy
20
+ * via {@link registerBeaconStrategy}.
21
+ */
22
+ export interface AggregateBeaconStrategy {
23
+ /** String constant used as `beaconType` on CohortConfig / BaseMessage bodies. */
24
+ readonly type: string;
25
+ /**
26
+ * Service: build the aggregated data on the cohort after all updates are
27
+ * collected. Implementation should mutate the cohort (set signalBytes,
28
+ * casAnnouncement, smtProofs, etc.).
29
+ */
30
+ buildAggregatedData(cohort: AggregationCohort): void;
31
+ /**
32
+ * Service: produce the body fields to attach to DISTRIBUTE_AGGREGATED_DATA
33
+ * for a specific participant. Called once per cohort member.
34
+ */
35
+ getDistributePayload(cohort: AggregationCohort, participantDid: string): BeaconDistributePayload;
36
+ /**
37
+ * Participant: verify the aggregated data they received reflects their own
38
+ * slot. A submitter (`included: true`) checks its update is included; a
39
+ * decliner (`included: false`, cooperative non-inclusion) checks its
40
+ * non-inclusion slot instead (absence from the CAS map, or an SMT
41
+ * non-inclusion proof). `submittedUpdate`/`expectedHash` are present only for a
42
+ * submitter. Pure function: returns matches + sidecar fields for the caller.
43
+ */
44
+ validateParticipantView(params: {
45
+ participantDid: string;
46
+ included: boolean;
47
+ submittedUpdate?: SignedBTCR2Update;
48
+ expectedHash?: string;
49
+ body: BaseBody;
50
+ }): BeaconValidationResult;
51
+ }
52
+ /** Register a custom beacon strategy. Overwrites any existing entry with the same type. */
53
+ export declare function registerBeaconStrategy(strategy: AggregateBeaconStrategy): void;
54
+ /** Look up a registered beacon strategy by type, or undefined if not registered. */
55
+ export declare function getBeaconStrategy(type: string): AggregateBeaconStrategy | undefined;
56
+ //# sourceMappingURL=beacon-strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"beacon-strategy.d.ts","sourceRoot":"","sources":["../../src/beacon-strategy.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD,mFAAmF;AACnF,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA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