@serfab/cadre-core 1.7.0 → 1.8.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 (162) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +386 -114
  3. package/dist/cadre-node.js +887 -359
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +8 -6
  45. package/dist/index.js +15 -9
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +90 -25
  48. package/dist/joined-strand-store.js +223 -55
  49. package/dist/joined-strand-store.js.map +1 -1
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/link-budget.d.ts +367 -69
  53. package/dist/link-budget.js +375 -72
  54. package/dist/link-budget.js.map +1 -1
  55. package/dist/membership-connection-gater.d.ts +30 -43
  56. package/dist/membership-connection-gater.js +31 -42
  57. package/dist/membership-connection-gater.js.map +1 -1
  58. package/dist/peer-dial.d.ts +24 -4
  59. package/dist/peer-dial.js +74 -5
  60. package/dist/peer-dial.js.map +1 -1
  61. package/dist/peer-join-backfill.d.ts +2 -1
  62. package/dist/peer-join-backfill.js +6 -5
  63. package/dist/peer-join-backfill.js.map +1 -1
  64. package/dist/push-fanout.d.ts +6 -0
  65. package/dist/push-fanout.js +6 -0
  66. package/dist/push-fanout.js.map +1 -1
  67. package/dist/relay-reservation.d.ts +3 -1
  68. package/dist/relay-reservation.js +3 -1
  69. package/dist/relay-reservation.js.map +1 -1
  70. package/dist/relay-server.d.ts +79 -0
  71. package/dist/relay-server.js +74 -0
  72. package/dist/relay-server.js.map +1 -0
  73. package/dist/seed-bootstrap.d.ts +57 -4
  74. package/dist/seed-bootstrap.js +107 -83
  75. package/dist/seed-bootstrap.js.map +1 -1
  76. package/dist/storage-scope.d.ts +33 -17
  77. package/dist/storage-scope.js +44 -23
  78. package/dist/storage-scope.js.map +1 -1
  79. package/dist/strand-addr-protocol.d.ts +58 -21
  80. package/dist/strand-addr-protocol.js +133 -85
  81. package/dist/strand-addr-protocol.js.map +1 -1
  82. package/dist/strand-database.d.ts +20 -2
  83. package/dist/strand-database.js +42 -5
  84. package/dist/strand-database.js.map +1 -1
  85. package/dist/strand-first-sync-gate.d.ts +59 -21
  86. package/dist/strand-first-sync-gate.js +58 -19
  87. package/dist/strand-first-sync-gate.js.map +1 -1
  88. package/dist/strand-formation-deadlines.d.ts +151 -0
  89. package/dist/strand-formation-deadlines.js +171 -0
  90. package/dist/strand-formation-deadlines.js.map +1 -0
  91. package/dist/strand-formation-manager.d.ts +63 -30
  92. package/dist/strand-formation-manager.js +67 -41
  93. package/dist/strand-formation-manager.js.map +1 -1
  94. package/dist/strand-formation-protocol.d.ts +45 -35
  95. package/dist/strand-formation-protocol.js +59 -122
  96. package/dist/strand-formation-protocol.js.map +1 -1
  97. package/dist/strand-instance-manager.d.ts +113 -6
  98. package/dist/strand-instance-manager.js +257 -41
  99. package/dist/strand-instance-manager.js.map +1 -1
  100. package/dist/strand-membership-writer.d.ts +6 -0
  101. package/dist/strand-membership-writer.js +11 -0
  102. package/dist/strand-membership-writer.js.map +1 -1
  103. package/dist/strand-peer-book-protocol.d.ts +13 -4
  104. package/dist/strand-peer-book-protocol.js +3 -7
  105. package/dist/strand-peer-book-protocol.js.map +1 -1
  106. package/dist/strand-peer-book.d.ts +1 -1
  107. package/dist/strand-peer-book.js +8 -1
  108. package/dist/strand-peer-book.js.map +1 -1
  109. package/dist/strand-peer-observer.js +1 -1
  110. package/dist/strand-revocation-enforcer.js +2 -1
  111. package/dist/strand-revocation-enforcer.js.map +1 -1
  112. package/dist/strand-solicitation.d.ts +36 -20
  113. package/dist/strand-solicitation.js +4 -4
  114. package/dist/strand-solicitation.js.map +1 -1
  115. package/dist/strand-wake-protocol.d.ts +80 -23
  116. package/dist/strand-wake-protocol.js +89 -64
  117. package/dist/strand-wake-protocol.js.map +1 -1
  118. package/dist/types.d.ts +128 -38
  119. package/dist/types.js +4 -3
  120. package/dist/types.js.map +1 -1
  121. package/package.json +7 -7
  122. package/src/cadre-node.ts +8367 -7776
  123. package/src/control-authorization.ts +2 -1
  124. package/src/control-cohort.ts +6 -0
  125. package/src/control-database.ts +122 -18
  126. package/src/control-formation-recorder.ts +354 -305
  127. package/src/control-read-retry.ts +14 -12
  128. package/src/control-schema.ts +67 -5
  129. package/src/control-stream.ts +25 -1
  130. package/src/control-write-retry.ts +13 -2
  131. package/src/delegate-admission.ts +23 -13
  132. package/src/diagnostics/connection-path.ts +0 -7
  133. package/src/formation-approval.ts +610 -604
  134. package/src/fs-atomic.ts +14 -4
  135. package/src/hibernation-manager.ts +638 -437
  136. package/src/index.ts +28 -10
  137. package/src/joined-strand-store.ts +247 -57
  138. package/src/key-store-file.ts +14 -5
  139. package/src/link-budget.ts +393 -74
  140. package/src/membership-connection-gater.ts +31 -45
  141. package/src/peer-dial.ts +81 -7
  142. package/src/peer-join-backfill.ts +8 -6
  143. package/src/push-fanout.ts +6 -0
  144. package/src/relay-reservation.ts +3 -1
  145. package/src/relay-server.ts +98 -0
  146. package/src/seed-bootstrap.ts +133 -91
  147. package/src/storage-scope.ts +44 -23
  148. package/src/strand-addr-protocol.ts +547 -458
  149. package/src/strand-database.ts +287 -242
  150. package/src/strand-first-sync-gate.ts +58 -19
  151. package/src/strand-formation-deadlines.ts +227 -0
  152. package/src/strand-formation-manager.ts +700 -647
  153. package/src/strand-formation-protocol.ts +103 -150
  154. package/src/strand-instance-manager.ts +287 -44
  155. package/src/strand-membership-writer.ts +12 -0
  156. package/src/strand-peer-book-protocol.ts +16 -13
  157. package/src/strand-peer-book.ts +8 -1
  158. package/src/strand-peer-observer.ts +1 -1
  159. package/src/strand-revocation-enforcer.ts +2 -1
  160. package/src/strand-solicitation.ts +519 -500
  161. package/src/strand-wake-protocol.ts +401 -355
  162. package/src/types.ts +130 -38
@@ -1,458 +1,547 @@
1
- /**
2
- * Control-network strand-address RPC.
3
- *
4
- * A strand runs as its own libp2p node (`strand-<id>`, random port), separate
5
- * from the control node (`control-<partyId>`), with its own transport peerId
6
- * derived from the cadre identity key (`strand-transport-key.ts`). To seed a
7
- * strand's mesh, a node needs a sibling's **strand-network** address — but
8
- * `CadrePeer.Multiaddr` only stores the **control** node's addresses, and a
9
- * control address now names a different peer entirely, not merely a different
10
- * port. This protocol resolves the strand address on demand: a node asks its
11
- * connected co-cadre siblings "what are your live strand-`X` multiaddrs?" and
12
- * uses the union of their answers as the seed.
13
- *
14
- * Modeled directly on `strand-wake-protocol.ts`: a dedicated libp2p protocol id,
15
- * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
16
- * `node.dialProtocol` for the client, and the shared `ControlStream` primitives
17
- * from `control-stream.ts`. The exchange is a single request → single response on
18
- * one stream, so each side reads to EOF (under a read timeout) and decodes one
19
- * frame via the shared {@link decodeLengthPrefixedFrame} guard.
20
- *
21
- * **Authorization (v1):** like wake, the receiver defers entirely to the injected
22
- * `isMember` predicate and requires no further signature; a peer it rejects gets
23
- * an empty address list. `CadreNode` injects its AUTHORIZED-membership predicate
24
- * (`isAuthorizedMember`: voucher on the requester's `CadrePeer` row verified
25
- * against the node-local trusted-owner anchor), so an outsider that published its
26
- * own rows into the replicated control DB cannot harvest live strand addresses.
27
- * Cross-party strand bootstrap is a different mechanism (strand formation /
28
- * `MemberPeer`) and is out of scope here.
29
- */
30
-
31
- import debug from 'debug';
32
- import type { Libp2p, Connection, PeerId } from '@libp2p/interface';
33
- import type { Multiaddr } from '@multiformats/multiaddr';
34
- import { peerIdFromString } from '@libp2p/peer-id';
35
- import type { StrandAddrRequest, StrandAddrResponse } from './types.js';
36
- import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
37
- import { orderSignalingFirst } from './peer-record.js';
38
- import { type ControlStream, writeFrame, withDeadline, exchangeFrame, readStreamToEnd } from './control-stream.js';
39
-
40
- const log = debug('sereus:cadre:strand-addr');
41
-
42
- /** Protocol id for the control-network strand-address RPC (parallel to `/sereus/strand-wake/1.0.0`). */
43
- export const STRAND_ADDR_PROTOCOL = '/sereus/strand-addr/1.0.0';
44
-
45
- /**
46
- * Maximum strand-addr frame size. Responses are tiny (a strand id + a few
47
- * multiaddrs), so this is a defensive cap — far below the 1MB seed ceiling —
48
- * that bounds the bytes a peer can make the receiver buffer per stream.
49
- */
50
- const MAX_ADDR_SIZE = 64 * 1024;
51
-
52
- /** Default time to wait for the response before abandoning a strand-addr dial (ms). */
53
- const DEFAULT_ADDR_TIMEOUT_MS = 10_000;
54
-
55
- /** Default time the receiver waits for an inbound request frame before aborting (ms). */
56
- const DEFAULT_ADDR_READ_TIMEOUT_MS = 10_000;
57
-
58
- /** Default cap on concurrent inbound strand-addr streams a single peer can pin open. */
59
- const DEFAULT_MAX_CONCURRENT_ADDRS = 100;
60
-
61
- /**
62
- * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
63
- * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
64
- * awaited forever) and capped at {@link MAX_ADDR_SIZE}, reusing the shared
65
- * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
66
- */
67
- async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
68
- const data = await readStreamToEnd(stream, { maxBytes: MAX_ADDR_SIZE, timeoutMs, label: 'Strand-addr' });
69
- const body = decodeLengthPrefixedFrame(data, MAX_ADDR_SIZE);
70
- return JSON.parse(new TextDecoder().decode(body)) as T;
71
- }
72
-
73
- /** Empty response used on every reject/error path (cap, malformed frame, non-member). */
74
- function emptyResponse(strandId: string): StrandAddrResponse {
75
- return { strandId, multiaddrs: [] };
76
- }
77
-
78
- /**
79
- * Dependencies the {@link StrandAddrService} receiver needs from its host
80
- * (`CadreNode`), injected so the service is testable without a full node.
81
- */
82
- export interface StrandAddrServiceOptions {
83
- /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
84
- isMember(remotePeerId: string): Promise<boolean>;
85
- /**
86
- * The local strand instance's dialable strand-network multiaddrs, ordered
87
- * signaling-first. Returns `[]` when the strand is not running / has no live
88
- * node (hibernating, quiescing, or never participated). Kept injectable so the
89
- * decision logic is unit-testable without a full node.
90
- */
91
- getStrandMultiaddrs(strandId: string): string[];
92
- /**
93
- * Called when a member's request carries a `delegatePeerId` — the derived
94
- * transport peerId its strand-`strandId` node runs as. Invoked only AFTER the
95
- * `isMember` gate passed, with a validated (parseable, non-self) peerId.
96
- * `CadreNode` injects its delegate-admission grant recorder so this node's
97
- * connection gate — and thus its circuit-relay server, when it runs one —
98
- * admits that peerId (see `delegate-admission.ts`). Optional: absent, an
99
- * announce is ignored and the address lookup proceeds unchanged.
100
- */
101
- onDelegateAnnounce?(announcerPeerId: string, strandId: string, delegatePeerId: string): void;
102
- /**
103
- * Time to wait for the inbound request frame before aborting the read (ms).
104
- * Defaults to {@link DEFAULT_ADDR_READ_TIMEOUT_MS}. Bounds a buggy/compromised
105
- * own-cadre node that opens a stream and never half-closes its write end.
106
- */
107
- readTimeoutMs?: number;
108
- /**
109
- * Cap on concurrent inbound strand-addr streams (defaults to
110
- * {@link DEFAULT_MAX_CONCURRENT_ADDRS}). Over the cap, an empty response is
111
- * returned without looking up any strand address.
112
- */
113
- maxConcurrent?: number;
114
- }
115
-
116
- /**
117
- * Receiver side of the strand-address RPC. Registers a `STRAND_ADDR_PROTOCOL`
118
- * handler on the control node and, for each inbound {@link StrandAddrRequest},
119
- * gates on cadre membership, then replies with the local strand instance's live
120
- * multiaddrs (or an empty list when not a member / not running).
121
- */
122
- export class StrandAddrService {
123
- private readonly options: StrandAddrServiceOptions;
124
- private readonly readTimeoutMs: number;
125
- private readonly maxConcurrent: number;
126
- private node: Libp2p | null = null;
127
- /** In-flight inbound strand-addr streams, used to enforce {@link maxConcurrent}. */
128
- private activeStreams = 0;
129
-
130
- constructor(options: StrandAddrServiceOptions) {
131
- this.options = options;
132
- this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_ADDR_READ_TIMEOUT_MS;
133
- this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_ADDRS;
134
- }
135
-
136
- /** Number of in-flight inbound strand-addr streams. */
137
- get activeCount(): number {
138
- return this.activeStreams;
139
- }
140
-
141
- /** Register the strand-addr protocol handler on the control node. */
142
- initialize(node: Libp2p): void {
143
- this.node = node;
144
- // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
145
- // sibling is reached over a circuit-relay connection, which libp2p marks
146
- // "limited" (the relay caps its data/duration). Without this the receiver
147
- // would refuse the inbound stream on exactly the connection the protocol is
148
- // designed to use (same reasoning as wake; see the relay note on
149
- // `collectStrandAddrs`).
150
- void node.handle(STRAND_ADDR_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
151
- const remotePeerId = (rawConnection as Connection).remotePeer.toString();
152
- await this.handleStream(rawStream as ControlStream, remotePeerId);
153
- }, { runOnLimitedConnection: true });
154
- log('StrandAddrService registered handler: %s', STRAND_ADDR_PROTOCOL);
155
- }
156
-
157
- /** Unregister the handler and release the node reference. */
158
- async shutdown(): Promise<void> {
159
- if (this.node) {
160
- await this.node.unhandle(STRAND_ADDR_PROTOCOL);
161
- this.node = null;
162
- log('StrandAddrService shutdown');
163
- }
164
- }
165
-
166
- /**
167
- * Read the inbound request, decide the response, and write it back.
168
- *
169
- * Three hardening layers, all reported as an empty {@link StrandAddrResponse}
170
- * rather than a dropped/hung stream: a concurrency cap (over
171
- * {@link maxConcurrent}, reply without looking up any address), a read timeout
172
- * (a peer that never half-closes is aborted inside {@link readFrame}/
173
- * `readStreamToEnd`), and the existing malformed/oversized-frame guard.
174
- */
175
- private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
176
- log('Incoming strand-addr request from: %s', remotePeerId);
177
-
178
- if (this.activeStreams >= this.maxConcurrent) {
179
- log('Rejecting strand-addr from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
180
- // The request frame is unread here, so the strand id is unknown — reply
181
- // with an empty list under an empty strand id; the client treats any empty
182
- // response as "no addrs" and skips this sibling.
183
- try {
184
- writeFrame(stream, emptyResponse(''));
185
- } catch {
186
- // Ignore send errors on the reject path.
187
- }
188
- try {
189
- await stream.close();
190
- } catch {
191
- // Ignore close errors.
192
- }
193
- return;
194
- }
195
-
196
- this.activeStreams++;
197
- try {
198
- const request = await readFrame<StrandAddrRequest>(stream, this.readTimeoutMs);
199
- const response = await this.processAddrRequest(request, remotePeerId);
200
- writeFrame(stream, response);
201
- } catch (err) {
202
- log('Error handling strand-addr request from %s: %o', remotePeerId, err);
203
- // Malformed/oversized/timed-out request: strand id is unknown, so reply
204
- // with an empty list under an empty strand id rather than hanging.
205
- try {
206
- writeFrame(stream, emptyResponse(''));
207
- } catch {
208
- // Ignore send errors on the error path.
209
- }
210
- } finally {
211
- this.activeStreams--;
212
- try {
213
- await stream.close();
214
- } catch {
215
- // Ignore close errors.
216
- }
217
- }
218
- }
219
-
220
- /**
221
- * Decide the response for a decoded request. Exposed (not private) so the
222
- * decision matrix can be unit-tested directly (mirrors wake's
223
- * `processWakeRequest`).
224
- *
225
- * - Non-member sender → empty `multiaddrs` (refused), no delegate grant.
226
- * - Member request carrying a `delegatePeerId` → recorded via
227
- * {@link StrandAddrServiceOptions.onDelegateAnnounce} before the lookup.
228
- * - Strand not running locally → empty `multiaddrs` (`getStrandMultiaddrs` → `[]`).
229
- * - Member + running strand → the strand's live, signaling-first multiaddrs.
230
- */
231
- async processAddrRequest(request: StrandAddrRequest, remotePeerId: string): Promise<StrandAddrResponse> {
232
- // Control-network membership is the v1 authorization: only this party's
233
- // cadre peers may ask us for a strand address (or announce a delegate).
234
- if (!(await this.options.isMember(remotePeerId))) {
235
- log('Refusing strand-addr from non-member %s', remotePeerId);
236
- return emptyResponse(request.strandId);
237
- }
238
-
239
- this.recordDelegateAnnounce(request, remotePeerId);
240
-
241
- const multiaddrs = this.options.getStrandMultiaddrs(request.strandId);
242
- log('Strand-addr for %s → %d addr(s)', request.strandId, multiaddrs.length);
243
- return { strandId: request.strandId, multiaddrs };
244
- }
245
-
246
- /**
247
- * Validate and forward a member's delegate announcement. A malformed field
248
- * (unparsable peerId) and a self-announcement (`delegatePeerId` equal to the
249
- * announcer's own peerId — a member is admitted directly, never by grant)
250
- * are logged and dropped; the address lookup proceeds either way.
251
- */
252
- private recordDelegateAnnounce(request: StrandAddrRequest, remotePeerId: string): void {
253
- const { strandId, delegatePeerId } = request;
254
- if (delegatePeerId === undefined || !this.options.onDelegateAnnounce) {
255
- return;
256
- }
257
- if (delegatePeerId === remotePeerId) {
258
- log('Ignoring self-announcement from %s (strand %s)', remotePeerId, strandId);
259
- return;
260
- }
261
- try {
262
- peerIdFromString(delegatePeerId);
263
- } catch (err) {
264
- log('Ignoring malformed delegatePeerId %o from %s: %o', delegatePeerId, remotePeerId, err);
265
- return;
266
- }
267
- this.options.onDelegateAnnounce(remotePeerId, strandId, delegatePeerId);
268
- }
269
- }
270
-
271
- /** A sibling to ask for its strand address. */
272
- export interface StrandAddrPeer {
273
- /** The sibling's control-network peer id (also its strand-node peer id). */
274
- peerId: string;
275
- /**
276
- * Pre-resolved control-network multiaddrs, used as a fallback when no control
277
- * connection is already open. Dialing by {@link peerId} is preferred (it
278
- * reuses an existing connection); these are tried only if that fails.
279
- */
280
- addrs?: Multiaddr[];
281
- }
282
-
283
- /** Options for {@link collectStrandAddrs}. */
284
- export interface CollectStrandAddrsOptions {
285
- /** Per-dial timeout in ms (default {@link DEFAULT_ADDR_TIMEOUT_MS}). */
286
- timeoutMs?: number;
287
- /** Override the protocol id (defaults to {@link STRAND_ADDR_PROTOCOL}). */
288
- protocolId?: string;
289
- /**
290
- * The derived transport peerId the caller's own strand-`strandId` node runs
291
- * (or is about to run) as. Set on every request this collection sends, so
292
- * each receiver records a delegate admission grant for it — see
293
- * {@link StrandAddrRequest.delegatePeerId}. Omit for a pure address lookup.
294
- */
295
- delegatePeerId?: string;
296
- }
297
-
298
- /**
299
- * Client side: ask each candidate sibling for its live strand-`strandId`
300
- * multiaddrs and return the **deduplicated union** of every answer, ordered
301
- * signaling-first.
302
- *
303
- * Best-effort per peer: a failed/timed-out/empty sibling is logged and skipped,
304
- * never fatal — an empty union (no sibling online or running the strand) returns
305
- * `[]`, which the caller treats as an acceptable seed that self-heals on the next
306
- * resume/reconcile pass. The local node (`node.peerId`) is excluded so we never
307
- * RPC ourselves or seed with our own strand address.
308
- *
309
- * Dials run concurrently but the union preserves candidate order, so the result
310
- * is deterministic regardless of which sibling answers first.
311
- */
312
- export async function collectStrandAddrs(
313
- node: Libp2p,
314
- peers: StrandAddrPeer[],
315
- strandId: string,
316
- options: CollectStrandAddrsOptions = {}
317
- ): Promise<string[]> {
318
- const selfId = node.peerId.toString();
319
- const request: StrandAddrRequest = options.delegatePeerId !== undefined
320
- ? { strandId, delegatePeerId: options.delegatePeerId }
321
- : { strandId };
322
- const candidates = peers.filter(p => p.peerId !== selfId);
323
-
324
- // Concurrent dials; `dialOneSibling` swallows per-peer failure into `[]`, so
325
- // `Promise.all` never rejects and the result array stays in candidate order.
326
- const perPeer = await Promise.all(
327
- candidates.map(peer => dialOneSibling(node, peer, request, options))
328
- );
329
-
330
- // Deduplicated union in candidate order, then signaling-first for a usable
331
- // dial sequence (relay/`p2p-circuit` ahead of direct addrs).
332
- const seen = new Set<string>();
333
- const union: string[] = [];
334
- for (const addrs of perPeer) {
335
- for (const addr of addrs) {
336
- if (!seen.has(addr)) {
337
- seen.add(addr);
338
- union.push(addr);
339
- }
340
- }
341
- }
342
- return orderSignalingFirst(union);
343
- }
344
-
345
- /**
346
- * Ask one sibling for its strand address, returning its multiaddrs or `[]` on any
347
- * failure. Tries each dial target in order (peerId first to reuse an open control
348
- * connection, then explicit addrs) until one answers; a total failure is logged
349
- * and folded to `[]` so a single dead sibling never aborts the collection.
350
- *
351
- * A total failure logs ONE line naming every target and its cause. `[]` alone
352
- * cannot tell the caller "this sibling was unreachable" apart from "this sibling
353
- * answered and has no strand address" — and per-target lines scattered through a
354
- * concurrent fan-out do not reassemble into that answer either. The return
355
- * contract is unchanged: best-effort `[]`, never a throw.
356
- *
357
- * NOTE: cost is (targets × `timeoutMs`) with no whole-sibling budget, the same
358
- * shape `dialWake` bounds with `DEFAULT_WAKE_DIAL_BUDGET_MS`. Fine today —
359
- * `dialTargets` yields the peerId plus whatever `resolvePeerAddrs` returned,
360
- * which for a cadre device is one or two addresses. If a sibling's record ever
361
- * carries a long address list, give this the same whole-sibling budget.
362
- */
363
- async function dialOneSibling(
364
- node: Libp2p,
365
- peer: StrandAddrPeer,
366
- request: StrandAddrRequest,
367
- options: CollectStrandAddrsOptions
368
- ): Promise<string[]> {
369
- const protocolId = options.protocolId ?? STRAND_ADDR_PROTOCOL;
370
- const timeoutMs = options.timeoutMs ?? DEFAULT_ADDR_TIMEOUT_MS;
371
- const targets = dialTargets(peer);
372
-
373
- if (targets.length === 0) {
374
- log('No dial target for sibling %s', peer.peerId);
375
- return [];
376
- }
377
-
378
- const failures: string[] = [];
379
- for (const target of targets) {
380
- try {
381
- // One deadline per attempt: its signal aborts the in-flight dialProtocol and
382
- // resets the live stream, so neither the connect nor the response-read leaks.
383
- const response = await withDeadline(
384
- timeoutMs,
385
- `Strand-addr dial ${peer.peerId}`,
386
- (signal) => sendStrandAddr(node, target, protocolId, request, timeoutMs, signal),
387
- );
388
- return response.multiaddrs;
389
- } catch (err) {
390
- const error = err instanceof Error ? err : new Error(String(err));
391
- failures.push(`${describeTarget(target)} — ${error.message}`);
392
- log('Strand-addr dial to %s via %s failed: %o', peer.peerId, describeTarget(target), err);
393
- }
394
- }
395
- log('Strand-addr dial to %s failed on all %d target(s), contributing no addrs: %s',
396
- peer.peerId, failures.length, failures.join('; '));
397
- return [];
398
- }
399
-
400
- /**
401
- * Dial targets for a sibling, peerId first. Dialing by peerId lets libp2p reuse
402
- * an already-open control connection (the common case — the wiring ticket passes
403
- * connected siblings); the explicit control addrs are a fallback for when no
404
- * connection is open. An unparsable peerId is skipped (rely on addrs).
405
- */
406
- function dialTargets(peer: StrandAddrPeer): Array<PeerId | Multiaddr> {
407
- const targets: Array<PeerId | Multiaddr> = [];
408
- try {
409
- targets.push(peerIdFromString(peer.peerId));
410
- } catch (err) {
411
- log('Unparsable peer id %s, falling back to addrs: %o', peer.peerId, err);
412
- }
413
- if (peer.addrs) {
414
- targets.push(...peer.addrs);
415
- }
416
- return targets;
417
- }
418
-
419
- /** Short label for a dial target (peerId or multiaddr) for logging. */
420
- function describeTarget(target: PeerId | Multiaddr): string {
421
- return target.toString();
422
- }
423
-
424
- /**
425
- * Open one stream to a target, send the request, half-close, and read the
426
- * response.
427
- *
428
- * `signal` is the per-attempt deadline from {@link dialOneSibling}: it goes to
429
- * `dialProtocol` so a timeout during connect aborts the dial, and into
430
- * {@link exchangeFrame} so a timeout after the stream is open resets it —
431
- * releasing the otherwise unbounded response-read.
432
- */
433
- async function sendStrandAddr(
434
- node: Libp2p,
435
- target: PeerId | Multiaddr,
436
- protocolId: string,
437
- request: StrandAddrRequest,
438
- timeoutMs: number,
439
- signal: AbortSignal,
440
- ): Promise<StrandAddrResponse> {
441
- // `runOnLimitedConnection: true`: the sibling may be reachable only over a
442
- // circuit-relay connection (the signaling-first addr), which libp2p marks
443
- // "limited". The exchange is a single tiny request→response well within the
444
- // relay's data/duration cap, so opening it on the limited connection is safe
445
- // and is the whole point of dialing over the relay.
446
- const rawStream = await node.dialProtocol(target, protocolId, { runOnLimitedConnection: true, signal });
447
-
448
- const response = await exchangeFrame(
449
- rawStream as unknown as ControlStream,
450
- signal,
451
- request,
452
- (stream) => readFrame<StrandAddrResponse>(stream, timeoutMs),
453
- 'Strand-addr dial aborted by timeout',
454
- );
455
-
456
- log('Strand-addr response: %d addr(s) for %s', response.multiaddrs.length, response.strandId);
457
- return response;
458
- }
1
+ /**
2
+ * Control-network strand-address RPC.
3
+ *
4
+ * A strand runs as its own libp2p node (`strand-<id>`, random port), separate
5
+ * from the control node (`control-<partyId>`), with its own transport peerId
6
+ * derived from the cadre identity key (`strand-transport-key.ts`). To seed a
7
+ * strand's mesh, a node needs a sibling's **strand-network** address — but
8
+ * `CadrePeer.Multiaddr` only stores the **control** node's addresses, and a
9
+ * control address now names a different peer entirely, not merely a different
10
+ * port. This protocol resolves the strand address on demand: a node asks its
11
+ * connected co-cadre siblings "what are your live strand-`X` multiaddrs?" and
12
+ * uses the union of their answers as the seed.
13
+ *
14
+ * Modeled directly on `strand-wake-protocol.ts`: a dedicated libp2p protocol id,
15
+ * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
16
+ * `node.dialProtocol` for the client, and the shared `ControlStream` primitives
17
+ * from `control-stream.ts`. The exchange is a single request → single response on
18
+ * one stream, so each side reads to EOF (under a read timeout) and decodes one
19
+ * frame via the shared {@link decodeLengthPrefixedFrame} guard.
20
+ *
21
+ * **Authorization (v1):** like wake, the receiver defers entirely to the injected
22
+ * `isMember` predicate and requires no further signature; a peer it rejects gets
23
+ * a `refused` reply with no addresses. `CadreNode` injects its AUTHORIZED-membership predicate
24
+ * (`isAuthorizedMember`: voucher on the requester's `CadrePeer` row verified
25
+ * against the node-local trusted-owner anchor), so an outsider that published its
26
+ * own rows into the replicated control DB cannot harvest live strand addresses.
27
+ * Cross-party strand bootstrap is a different mechanism (strand formation /
28
+ * `MemberPeer`) and is out of scope here.
29
+ */
30
+
31
+ import debug from 'debug';
32
+ import type { Libp2p, Connection, PeerId } from '@libp2p/interface';
33
+ import type { Multiaddr } from '@multiformats/multiaddr';
34
+ import { peerIdFromString } from '@libp2p/peer-id';
35
+ import type { StrandAddrRequest, StrandAddrResponse, StrandAddrStatus } from './types.js';
36
+ import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
37
+ import { orderSignalingFirst } from './peer-record.js';
38
+ import { type ControlStream, withDeadline, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
39
+ import { relayedRequestBudgetMs } from './link-budget.js';
40
+
41
+ const log = debug('sereus:cadre:strand-addr');
42
+
43
+ /** Protocol id for the control-network strand-address RPC (parallel to `/sereus/strand-wake/1.0.0`). */
44
+ export const STRAND_ADDR_PROTOCOL = '/sereus/strand-addr/1.0.0';
45
+
46
+ /**
47
+ * Maximum strand-addr frame size. Responses are tiny (a strand id + a few
48
+ * multiaddrs), so this is a defensive cap — far below the 1MB seed ceiling —
49
+ * that bounds the bytes a peer can make the receiver buffer per stream.
50
+ */
51
+ const MAX_ADDR_SIZE = 64 * 1024;
52
+
53
+ /** Default time the receiver waits for an inbound request frame before aborting (ms). */
54
+ // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one small request frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
55
+ const DEFAULT_ADDR_READ_TIMEOUT_MS = 10_000;
56
+
57
+ /** Default cap on concurrent inbound strand-addr streams a single peer can pin open. */
58
+ const DEFAULT_MAX_CONCURRENT_ADDRS = 100;
59
+
60
+ /**
61
+ * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
62
+ * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
63
+ * awaited forever) and capped at {@link MAX_ADDR_SIZE}, reusing the shared
64
+ * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
65
+ */
66
+ async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
67
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_ADDR_SIZE, timeoutMs, label: 'Strand-addr' });
68
+ const body = decodeLengthPrefixedFrame(data, MAX_ADDR_SIZE);
69
+ return JSON.parse(new TextDecoder().decode(body)) as T;
70
+ }
71
+
72
+ /** An address-free reply, for every path but a member's lookup: cap, unreadable request, lookup failure, non-member. */
73
+ function addrlessResponse(status: StrandAddrStatus, strandId: string): StrandAddrResponse {
74
+ return { status, strandId, multiaddrs: [] };
75
+ }
76
+
77
+ /**
78
+ * Dependencies the {@link StrandAddrService} receiver needs from its host
79
+ * (`CadreNode`), injected so the service is testable without a full node.
80
+ */
81
+ export interface StrandAddrServiceOptions {
82
+ /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
83
+ isMember(remotePeerId: string): Promise<boolean>;
84
+ /**
85
+ * The local strand instance's dialable strand-network multiaddrs, ordered
86
+ * signaling-first. Returns `[]` when the strand is not running / has no live
87
+ * node (hibernating, quiescing, or never participated). Kept injectable so the
88
+ * decision logic is unit-testable without a full node.
89
+ */
90
+ getStrandMultiaddrs(strandId: string): string[];
91
+ /**
92
+ * Called when a member's request carries a `delegatePeerId` — the derived
93
+ * transport peerId its strand-`strandId` node runs as. Invoked only AFTER the
94
+ * `isMember` gate passed, with a validated (parseable, non-self) peerId.
95
+ * `CadreNode` injects its delegate-admission grant recorder so this node's
96
+ * connection gate — and thus its circuit-relay server, when it runs one —
97
+ * admits that peerId (see `delegate-admission.ts`). Optional: absent, an
98
+ * announce is ignored and the address lookup proceeds unchanged.
99
+ */
100
+ onDelegateAnnounce?(announcerPeerId: string, strandId: string, delegatePeerId: string): void;
101
+ /**
102
+ * Time to wait for the inbound request frame before aborting the read (ms).
103
+ * Defaults to {@link DEFAULT_ADDR_READ_TIMEOUT_MS}. Bounds a buggy/compromised
104
+ * own-cadre node that opens a stream and never half-closes its write end.
105
+ */
106
+ readTimeoutMs?: number;
107
+ /**
108
+ * Cap on concurrent inbound strand-addr streams (defaults to
109
+ * {@link DEFAULT_MAX_CONCURRENT_ADDRS}). Over the cap, an `unavailable` reply is
110
+ * returned without looking up any strand address.
111
+ */
112
+ maxConcurrent?: number;
113
+ }
114
+
115
+ /**
116
+ * Receiver side of the strand-address RPC. Registers a `STRAND_ADDR_PROTOCOL`
117
+ * handler on the control node and, for each inbound {@link StrandAddrRequest},
118
+ * gates on cadre membership, then replies with the local strand instance's live
119
+ * multiaddrs — `ok` with an empty list when the strand is not running, `refused`
120
+ * for a non-member, `unavailable` when it could not answer at all.
121
+ */
122
+ export class StrandAddrService {
123
+ private readonly options: StrandAddrServiceOptions;
124
+ private readonly readTimeoutMs: number;
125
+ private readonly maxConcurrent: number;
126
+ private node: Libp2p | null = null;
127
+ /** In-flight inbound strand-addr streams, used to enforce {@link maxConcurrent}. */
128
+ private activeStreams = 0;
129
+
130
+ constructor(options: StrandAddrServiceOptions) {
131
+ this.options = options;
132
+ this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_ADDR_READ_TIMEOUT_MS;
133
+ this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_ADDRS;
134
+ }
135
+
136
+ /** Number of in-flight inbound strand-addr streams. */
137
+ get activeCount(): number {
138
+ return this.activeStreams;
139
+ }
140
+
141
+ /**
142
+ * Register the strand-addr protocol handler on the control node. Rejects when
143
+ * libp2p refuses the registration (a duplicate handler, a peer-store write
144
+ * failure); the node reference is kept only once the handler is in place.
145
+ */
146
+ async initialize(node: Libp2p): Promise<void> {
147
+ // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
148
+ // sibling is reached over a circuit-relay connection, which libp2p marks
149
+ // "limited" (the relay caps its data/duration). Without this the receiver
150
+ // would refuse the inbound stream on exactly the connection the protocol is
151
+ // designed to use (same reasoning as wake; see the relay note on
152
+ // `collectStrandAddrs`).
153
+ await node.handle(STRAND_ADDR_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
154
+ const remotePeerId = (rawConnection as Connection).remotePeer.toString();
155
+ await this.handleStream(rawStream as ControlStream, remotePeerId);
156
+ }, { runOnLimitedConnection: true });
157
+ this.node = node;
158
+ log('StrandAddrService registered handler: %s', STRAND_ADDR_PROTOCOL);
159
+ }
160
+
161
+ /** Unregister the handler and release the node reference. */
162
+ async shutdown(): Promise<void> {
163
+ if (this.node) {
164
+ await this.node.unhandle(STRAND_ADDR_PROTOCOL);
165
+ this.node = null;
166
+ log('StrandAddrService shutdown');
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Read the inbound request, decide the response, and write it back.
172
+ *
173
+ * Three hardening layers, all reported as an `unavailable`
174
+ * {@link StrandAddrResponse} rather than a dropped/hung stream: a concurrency cap
175
+ * (over {@link maxConcurrent}, reply without looking up any address), a read
176
+ * timeout (a peer that never half-closes is aborted inside {@link readFrame}/
177
+ * `readStreamToEnd`), and the existing malformed/oversized-frame guard. A
178
+ * lookup that throws — the membership read failing, say — is `unavailable` too,
179
+ * never a `refused` or an empty `ok` the asker would wait ten minutes on.
180
+ */
181
+ private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
182
+ log('Incoming strand-addr request from: %s', remotePeerId);
183
+
184
+ if (this.activeStreams >= this.maxConcurrent) {
185
+ log('Rejecting strand-addr from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
186
+ // The request frame is unread here, so the strand id is unknown — reply
187
+ // under an empty strand id; the asker retries an `unavailable` sibling soon.
188
+ await replyAndClose(stream, addrlessResponse('unavailable', ''), 'Strand-addr');
189
+ return;
190
+ }
191
+
192
+ this.activeStreams++;
193
+ try {
194
+ await replyAndClose(stream, await this.answerStream(stream, remotePeerId), 'Strand-addr');
195
+ } finally {
196
+ this.activeStreams--;
197
+ }
198
+ }
199
+
200
+ /** Read and decide one inbound request; any failure becomes an `unavailable` response. */
201
+ private async answerStream(stream: ControlStream, remotePeerId: string): Promise<StrandAddrResponse> {
202
+ try {
203
+ const request = await readFrame<StrandAddrRequest>(stream, this.readTimeoutMs);
204
+ return await this.processAddrRequest(request, remotePeerId);
205
+ } catch (err) {
206
+ log('Error handling strand-addr request from %s: %o', remotePeerId, err);
207
+ // Malformed/oversized/timed-out request, or a lookup that threw: reply
208
+ // under an empty strand id rather than hanging.
209
+ return addrlessResponse('unavailable', '');
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Decide the response for a decoded request. Exposed (not private) so the
215
+ * decision matrix can be unit-tested directly (mirrors wake's
216
+ * `processWakeRequest`).
217
+ *
218
+ * - Non-member sender → `refused`, no delegate grant.
219
+ * - Member request carrying a `delegatePeerId` → recorded via
220
+ * {@link StrandAddrServiceOptions.onDelegateAnnounce} before the lookup.
221
+ * - Strand not running locally → `ok` with empty `multiaddrs` (`getStrandMultiaddrs` → `[]`).
222
+ * - Member + running strand → `ok` with the strand's live, signaling-first multiaddrs.
223
+ *
224
+ * A throwing `isMember` propagates; {@link handleStream} answers it `unavailable`.
225
+ */
226
+ async processAddrRequest(request: StrandAddrRequest, remotePeerId: string): Promise<StrandAddrResponse> {
227
+ // Control-network membership is the v1 authorization: only this party's
228
+ // cadre peers may ask us for a strand address (or announce a delegate).
229
+ if (!(await this.options.isMember(remotePeerId))) {
230
+ log('Refusing strand-addr from non-member %s', remotePeerId);
231
+ return addrlessResponse('refused', request.strandId);
232
+ }
233
+
234
+ this.recordDelegateAnnounce(request, remotePeerId);
235
+
236
+ const multiaddrs = this.options.getStrandMultiaddrs(request.strandId);
237
+ log('Strand-addr for %s → %d addr(s)', request.strandId, multiaddrs.length);
238
+ return { status: 'ok', strandId: request.strandId, multiaddrs };
239
+ }
240
+
241
+ /**
242
+ * Validate and forward a member's delegate announcement. A malformed field
243
+ * (unparsable peerId) and a self-announcement (`delegatePeerId` equal to the
244
+ * announcer's own peerId — a member is admitted directly, never by grant)
245
+ * are logged and dropped; the address lookup proceeds either way.
246
+ */
247
+ private recordDelegateAnnounce(request: StrandAddrRequest, remotePeerId: string): void {
248
+ const { strandId, delegatePeerId } = request;
249
+ if (delegatePeerId === undefined || !this.options.onDelegateAnnounce) {
250
+ return;
251
+ }
252
+ if (delegatePeerId === remotePeerId) {
253
+ log('Ignoring self-announcement from %s (strand %s)', remotePeerId, strandId);
254
+ return;
255
+ }
256
+ try {
257
+ peerIdFromString(delegatePeerId);
258
+ } catch (err) {
259
+ log('Ignoring malformed delegatePeerId %o from %s: %o', delegatePeerId, remotePeerId, err);
260
+ return;
261
+ }
262
+ this.options.onDelegateAnnounce(remotePeerId, strandId, delegatePeerId);
263
+ }
264
+ }
265
+
266
+ /** A sibling to ask for its strand address. */
267
+ export interface StrandAddrPeer {
268
+ /** The sibling's control-network peer id (also its strand-node peer id). */
269
+ peerId: string;
270
+ /**
271
+ * Pre-resolved control-network multiaddrs, used as a fallback when no control
272
+ * connection is already open. Dialing by {@link peerId} is preferred (it
273
+ * reuses an existing connection); these are tried only if that fails.
274
+ */
275
+ addrs?: Multiaddr[];
276
+ }
277
+
278
+ /** Options for {@link collectStrandAddrs}. */
279
+ export interface CollectStrandAddrsOptions {
280
+ /**
281
+ * The asker's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which the
282
+ * per-dial timeout is derived when {@link timeoutMs} is not given. Unset means the declared
283
+ * default.
284
+ */
285
+ linkRoundTripMs?: number;
286
+ /** Per-dial timeout in ms (default: {@link attemptTimeoutMs}). */
287
+ timeoutMs?: number;
288
+ /** Override the protocol id (defaults to {@link STRAND_ADDR_PROTOCOL}). */
289
+ protocolId?: string;
290
+ /**
291
+ * The derived transport peerId the caller's own strand-`strandId` node runs
292
+ * (or is about to run) as. Set on every request this collection sends, so
293
+ * each receiver records a delegate admission grant for it — see
294
+ * {@link StrandAddrRequest.delegatePeerId}. Omit for a pure address lookup.
295
+ */
296
+ delegatePeerId?: string;
297
+ }
298
+
299
+ /**
300
+ * What asking one sibling produced, as {@link collectStrandAddrs} reports it.
301
+ *
302
+ * - `answered` — status `ok` with at least one address.
303
+ * - `empty` — status `ok` with no address: the sibling does not run the strand
304
+ * right now, a normal steady state.
305
+ * - `unavailable` — the sibling replied that it could not answer.
306
+ * - `refused` — the sibling does not (yet) count the asker as an authorized member.
307
+ * - `unreachable` — no reply at all: every dial target failed or timed out, or
308
+ * the reply was malformed.
309
+ */
310
+ export type StrandAddrOutcome = 'answered' | 'empty' | 'unavailable' | 'refused' | 'unreachable';
311
+
312
+ /** Result of {@link collectStrandAddrs}. */
313
+ export interface StrandAddrCollection {
314
+ /** Deduplicated union of every answer, signaling-first. */
315
+ addrs: string[];
316
+ /** One entry per candidate (self excluded), keyed by the sibling's control peerId. */
317
+ outcomes: Map<string, StrandAddrOutcome>;
318
+ }
319
+
320
+ /** One sibling's share of a {@link StrandAddrCollection}. */
321
+ interface SiblingAnswer {
322
+ outcome: StrandAddrOutcome;
323
+ multiaddrs: string[];
324
+ }
325
+
326
+ /**
327
+ * Client side: ask each candidate sibling for its live strand-`strandId`
328
+ * multiaddrs and return the **deduplicated union** of every answer, ordered
329
+ * signaling-first, alongside each sibling's {@link StrandAddrOutcome}.
330
+ *
331
+ * Best-effort per peer: a failed/timed-out/empty sibling contributes no address
332
+ * and never fails the collection — an empty union (no sibling online or running
333
+ * the strand) is an acceptable seed that self-heals on the next resume/reconcile
334
+ * pass. `outcomes` is what lets a caller retry the siblings that could not answer
335
+ * sooner than the ones that answered with nothing. The local node (`node.peerId`)
336
+ * is excluded so we never RPC ourselves or seed with our own strand address.
337
+ *
338
+ * Dials run concurrently but the union preserves candidate order, so the result
339
+ * is deterministic regardless of which sibling answers first.
340
+ */
341
+ export async function collectStrandAddrs(
342
+ node: Libp2p,
343
+ peers: StrandAddrPeer[],
344
+ strandId: string,
345
+ options: CollectStrandAddrsOptions = {}
346
+ ): Promise<StrandAddrCollection> {
347
+ const selfId = node.peerId.toString();
348
+ const request: StrandAddrRequest = options.delegatePeerId !== undefined
349
+ ? { strandId, delegatePeerId: options.delegatePeerId }
350
+ : { strandId };
351
+ const candidates = peers.filter(p => p.peerId !== selfId);
352
+
353
+ // Concurrent dials; `dialOneSibling` folds per-peer failure into an outcome, so
354
+ // `Promise.all` never rejects and the result array stays in candidate order.
355
+ const answers = await Promise.all(
356
+ candidates.map(async (peer) => ({ peerId: peer.peerId, ...await dialOneSibling(node, peer, request, options) }))
357
+ );
358
+
359
+ const outcomes = new Map<string, StrandAddrOutcome>();
360
+ // Deduplicated union in candidate order, then signaling-first for a usable
361
+ // dial sequence (relay/`p2p-circuit` ahead of direct addrs).
362
+ const seen = new Set<string>();
363
+ const union: string[] = [];
364
+ for (const { peerId, outcome, multiaddrs } of answers) {
365
+ outcomes.set(peerId, outcome);
366
+ for (const addr of multiaddrs) {
367
+ if (!seen.has(addr)) {
368
+ seen.add(addr);
369
+ union.push(addr);
370
+ }
371
+ }
372
+ }
373
+ return { addrs: orderSignalingFirst(union), outcomes };
374
+ }
375
+
376
+ /**
377
+ * Ask one sibling for its strand address. Tries each dial target in order (peerId
378
+ * first to reuse an open control connection, then explicit addrs) until one
379
+ * produces a well-formed reply, and reports that reply's outcome; a total failure
380
+ * is `unreachable`, so a single dead sibling never aborts the collection. Never
381
+ * throws.
382
+ *
383
+ * A reply of any status ends the loop: every target reaches the same responder,
384
+ * so asking it again by another address would get the same answer.
385
+ *
386
+ * A total failure logs ONE line naming every target and its cause, because
387
+ * per-target lines scattered through a concurrent fan-out do not reassemble into
388
+ * "this sibling was unreachable".
389
+ *
390
+ * NOTE: cost is (targets × `timeoutMs`, 23 s each at the default declared link) with
391
+ * no whole-sibling budget, the same shape `dialWake` bounds with
392
+ * `DEFAULT_WAKE_DIAL_BUDGET_MS`. Siblings are asked concurrently, so a collection costs
393
+ * its slowest sibling, not the sum. Fine today — `dialTargets` yields the peerId plus
394
+ * whatever `resolvePeerAddrs` returned, which for a cadre device is one or two
395
+ * addresses. If a sibling's record ever carries a long address list, give this the same
396
+ * whole-sibling budget.
397
+ */
398
+ async function dialOneSibling(
399
+ node: Libp2p,
400
+ peer: StrandAddrPeer,
401
+ request: StrandAddrRequest,
402
+ options: CollectStrandAddrsOptions
403
+ ): Promise<SiblingAnswer> {
404
+ const protocolId = options.protocolId ?? STRAND_ADDR_PROTOCOL;
405
+ const timeoutMs = attemptTimeoutMs(options);
406
+ const targets = dialTargets(peer);
407
+
408
+ if (targets.length === 0) {
409
+ log('No dial target for sibling %s', peer.peerId);
410
+ return { outcome: 'unreachable', multiaddrs: [] };
411
+ }
412
+
413
+ const failures: string[] = [];
414
+ for (const target of targets) {
415
+ try {
416
+ // One deadline per attempt: its signal aborts the in-flight dialProtocol and
417
+ // resets the live stream, so neither the connect nor the response-read leaks.
418
+ const response = await withDeadline(
419
+ timeoutMs,
420
+ `Strand-addr dial ${peer.peerId}`,
421
+ (signal) => sendStrandAddr(node, target, protocolId, request, timeoutMs, signal),
422
+ );
423
+ return siblingAnswer(response);
424
+ } catch (err) {
425
+ const error = err instanceof Error ? err : new Error(String(err));
426
+ failures.push(`${describeTarget(target)} — ${error.message}`);
427
+ log('Strand-addr dial to %s via %s failed: %o', peer.peerId, describeTarget(target), err);
428
+ }
429
+ }
430
+ log('Strand-addr dial to %s failed on all %d target(s), contributing no addrs: %s',
431
+ peer.peerId, failures.length, failures.join('; '));
432
+ return { outcome: 'unreachable', multiaddrs: [] };
433
+ }
434
+
435
+ /**
436
+ * Deadline for ONE attempt to ask a sibling — dial, request, response — unless the caller set
437
+ * its own: `relayedRequestBudgetMs` at the declared link (23 s at the default).
438
+ *
439
+ * An attempt is either a dial by peer id, which normally reuses an open control connection
440
+ * (`CIRCUIT_REQUEST_ROUND_TRIPS`, 2), or the fallback to the sibling's control addresses, a
441
+ * fresh and possibly relayed dial. One deadline covers both, so it is sized for the fallback.
442
+ *
443
+ * NOTE: the receiver's membership check (two live control reads) runs inside this deadline and
444
+ * is not counted. In steady state those reads touch only held blocks and do not consult the
445
+ * cohort. If a wake or address request is seen timing out while the receiver's membership read
446
+ * is consulting, count one membership decision in this deadline or answer the check from the
447
+ * materialized authorized-peer snapshot. See docs/cadre-consistency.md → "Deadlines Over
448
+ * Optimystic's Reads and Commits".
449
+ */
450
+ function attemptTimeoutMs(options: CollectStrandAddrsOptions): number {
451
+ return options.timeoutMs ?? relayedRequestBudgetMs(options.linkRoundTripMs);
452
+ }
453
+
454
+ /** Map a validated reply to its outcome; only an `ok` reply contributes addresses. */
455
+ function siblingAnswer(response: StrandAddrResponse): SiblingAnswer {
456
+ if (response.status !== 'ok') {
457
+ return { outcome: response.status, multiaddrs: [] };
458
+ }
459
+ return {
460
+ outcome: response.multiaddrs.length > 0 ? 'answered' : 'empty',
461
+ multiaddrs: response.multiaddrs
462
+ };
463
+ }
464
+
465
+ /**
466
+ * Dial targets for a sibling, peerId first. Dialing by peerId lets libp2p reuse
467
+ * an already-open control connection (the common case — the wiring ticket passes
468
+ * connected siblings); the explicit control addrs are a fallback for when no
469
+ * connection is open. An unparsable peerId is skipped (rely on addrs).
470
+ */
471
+ function dialTargets(peer: StrandAddrPeer): Array<PeerId | Multiaddr> {
472
+ const targets: Array<PeerId | Multiaddr> = [];
473
+ try {
474
+ targets.push(peerIdFromString(peer.peerId));
475
+ } catch (err) {
476
+ log('Unparsable peer id %s, falling back to addrs: %o', peer.peerId, err);
477
+ }
478
+ if (peer.addrs) {
479
+ targets.push(...peer.addrs);
480
+ }
481
+ return targets;
482
+ }
483
+
484
+ /** Short label for a dial target (peerId or multiaddr) for logging. */
485
+ function describeTarget(target: PeerId | Multiaddr): string {
486
+ return target.toString();
487
+ }
488
+
489
+ /**
490
+ * Open one stream to a target, send the request, half-close, and read the
491
+ * response.
492
+ *
493
+ * `signal` is the per-attempt deadline from {@link dialOneSibling}: it goes to
494
+ * `dialProtocol` so a timeout during connect aborts the dial, and into
495
+ * {@link exchangeFrame} so a timeout after the stream is open resets it —
496
+ * releasing the otherwise unbounded response-read.
497
+ */
498
+ async function sendStrandAddr(
499
+ node: Libp2p,
500
+ target: PeerId | Multiaddr,
501
+ protocolId: string,
502
+ request: StrandAddrRequest,
503
+ timeoutMs: number,
504
+ signal: AbortSignal,
505
+ ): Promise<StrandAddrResponse> {
506
+ // `runOnLimitedConnection: true`: the sibling may be reachable only over a
507
+ // circuit-relay connection (the signaling-first addr), which libp2p marks
508
+ // "limited". The exchange is a single tiny request→response well within the
509
+ // relay's data/duration cap, so opening it on the limited connection is safe
510
+ // and is the whole point of dialing over the relay.
511
+ const rawStream = await node.dialProtocol(target, protocolId, { runOnLimitedConnection: true, signal });
512
+
513
+ const response = await exchangeFrame(
514
+ rawStream as unknown as ControlStream,
515
+ signal,
516
+ request,
517
+ (stream) => readFrame<unknown>(stream, timeoutMs),
518
+ 'Strand-addr dial aborted by timeout',
519
+ );
520
+ if (!isStrandAddrResponse(response)) {
521
+ throw new Error('Malformed strand-addr response');
522
+ }
523
+
524
+ log('Strand-addr response: %s, %d addr(s) for %s', response.status, response.multiaddrs.length, response.strandId);
525
+ return response;
526
+ }
527
+
528
+ const STRAND_ADDR_STATUSES: ReadonlySet<string> = new Set<StrandAddrStatus>(['ok', 'unavailable', 'refused']);
529
+
530
+ /**
531
+ * Shape check on a decoded reply: the responder is another machine, so a reply
532
+ * missing its status (an older responder, or a buggy one) or carrying anything but
533
+ * strings in `multiaddrs` is a failed exchange, not an answer.
534
+ *
535
+ * Deliberately not `sanitizeStrandAddrs` (strand-formation-protocol.ts): that drops
536
+ * bad entries and caps the list at 16, which suits a cross-party formation result
537
+ * but would silently truncate a sibling's full address list here.
538
+ */
539
+ function isStrandAddrResponse(value: unknown): value is StrandAddrResponse {
540
+ if (typeof value !== 'object' || value === null) {
541
+ return false;
542
+ }
543
+ const { status, strandId, multiaddrs } = value as Record<string, unknown>;
544
+ return typeof status === 'string' && STRAND_ADDR_STATUSES.has(status)
545
+ && typeof strandId === 'string'
546
+ && Array.isArray(multiaddrs) && multiaddrs.every((addr) => typeof addr === 'string');
547
+ }