@serfab/cadre-core 1.9.0 → 1.11.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 (119) hide show
  1. package/dist/cadre-node.d.ts +148 -44
  2. package/dist/cadre-node.js +363 -139
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-authorization.d.ts +2 -2
  5. package/dist/control-authorization.js +1 -0
  6. package/dist/control-authorization.js.map +1 -1
  7. package/dist/control-cohort.d.ts +1 -1
  8. package/dist/control-cohort.js +1 -1
  9. package/dist/control-database.d.ts +105 -14
  10. package/dist/control-database.js +242 -73
  11. package/dist/control-database.js.map +1 -1
  12. package/dist/control-formation-recorder.d.ts +6 -6
  13. package/dist/control-formation-recorder.js +7 -8
  14. package/dist/control-formation-recorder.js.map +1 -1
  15. package/dist/control-schema.d.ts +1 -1
  16. package/dist/control-schema.js +1066 -979
  17. package/dist/control-schema.js.map +1 -1
  18. package/dist/control-write-retry.d.ts +21 -15
  19. package/dist/control-write-retry.js +21 -15
  20. package/dist/control-write-retry.js.map +1 -1
  21. package/dist/diagnostics/connection-path.d.ts +1 -18
  22. package/dist/diagnostics/connection-path.js +1 -20
  23. package/dist/diagnostics/connection-path.js.map +1 -1
  24. package/dist/identity-key.d.ts +0 -30
  25. package/dist/identity-key.js +7 -40
  26. package/dist/identity-key.js.map +1 -1
  27. package/dist/index.d.ts +8 -5
  28. package/dist/index.js +12 -6
  29. package/dist/index.js.map +1 -1
  30. package/dist/invitation-bootstrap.d.ts +32 -0
  31. package/dist/invitation-bootstrap.js +30 -0
  32. package/dist/invitation-bootstrap.js.map +1 -0
  33. package/dist/link-budget.d.ts +204 -119
  34. package/dist/link-budget.js +208 -120
  35. package/dist/link-budget.js.map +1 -1
  36. package/dist/membership-connection-gater.d.ts +3 -3
  37. package/dist/membership-connection-gater.js +3 -3
  38. package/dist/peer-dial.d.ts +18 -14
  39. package/dist/peer-dial.js +18 -14
  40. package/dist/peer-dial.js.map +1 -1
  41. package/dist/peer-join-backfill.d.ts +3 -3
  42. package/dist/pending-join-runner.d.ts +186 -0
  43. package/dist/pending-join-runner.js +649 -0
  44. package/dist/pending-join-runner.js.map +1 -0
  45. package/dist/push-fanout.d.ts +1 -1
  46. package/dist/push-fanout.js +1 -1
  47. package/dist/relay-stun.d.ts +24 -0
  48. package/dist/relay-stun.js +51 -0
  49. package/dist/relay-stun.js.map +1 -0
  50. package/dist/seed-bootstrap.d.ts +2 -2
  51. package/dist/seed-bootstrap.js +5 -5
  52. package/dist/strand-addr-protocol.js +2 -2
  53. package/dist/strand-formation-deadlines.d.ts +5 -5
  54. package/dist/strand-formation-deadlines.js +5 -5
  55. package/dist/strand-formation-manager.d.ts +18 -4
  56. package/dist/strand-formation-manager.js +48 -33
  57. package/dist/strand-formation-manager.js.map +1 -1
  58. package/dist/strand-formation-protocol.d.ts +71 -14
  59. package/dist/strand-formation-protocol.js +222 -47
  60. package/dist/strand-formation-protocol.js.map +1 -1
  61. package/dist/strand-formation-rejection.d.ts +94 -0
  62. package/dist/strand-formation-rejection.js +77 -0
  63. package/dist/strand-formation-rejection.js.map +1 -0
  64. package/dist/strand-instance-manager.js +4 -1
  65. package/dist/strand-instance-manager.js.map +1 -1
  66. package/dist/strand-membership-writer.js +32 -32
  67. package/dist/strand-solicitation.d.ts +11 -3
  68. package/dist/strand-solicitation.js +9 -0
  69. package/dist/strand-solicitation.js.map +1 -1
  70. package/dist/types.d.ts +103 -17
  71. package/dist/types.js +5 -9
  72. package/dist/types.js.map +1 -1
  73. package/package.json +22 -22
  74. package/src/cadre-node.ts +8654 -8400
  75. package/src/control-authorization.ts +2 -1
  76. package/src/control-cohort.ts +128 -128
  77. package/src/control-database.ts +303 -82
  78. package/src/control-formation-recorder.ts +353 -354
  79. package/src/control-read-retry.ts +216 -216
  80. package/src/control-schema.ts +1078 -991
  81. package/src/control-write-retry.ts +567 -561
  82. package/src/diagnostics/connection-path.ts +1 -29
  83. package/src/formation-approval.ts +610 -610
  84. package/src/hibernation-manager.ts +638 -638
  85. package/src/identity-key.ts +7 -62
  86. package/src/index.ts +644 -627
  87. package/src/invitation-bootstrap.ts +40 -0
  88. package/src/joined-strand-store.ts +498 -498
  89. package/src/link-budget.ts +684 -583
  90. package/src/membership-connection-gater.ts +570 -570
  91. package/src/node-local-snapshot.ts +298 -298
  92. package/src/peer-dial.ts +315 -311
  93. package/src/peer-join-backfill.ts +710 -710
  94. package/src/pending-join-runner.ts +735 -0
  95. package/src/push-fanout.ts +1 -1
  96. package/src/relay-reservation.ts +1121 -1121
  97. package/src/relay-server.ts +98 -98
  98. package/src/relay-stun.ts +58 -0
  99. package/src/seed-bootstrap.ts +1448 -1448
  100. package/src/strand-addr-protocol.ts +547 -547
  101. package/src/strand-database.ts +287 -287
  102. package/src/strand-first-sync-gate.ts +391 -391
  103. package/src/strand-formation-deadlines.ts +227 -227
  104. package/src/strand-formation-manager.ts +725 -700
  105. package/src/strand-formation-protocol.ts +1036 -802
  106. package/src/strand-formation-rejection.ts +129 -0
  107. package/src/strand-fret-addrs.ts +145 -145
  108. package/src/strand-instance-manager.ts +1789 -1786
  109. package/src/strand-membership-writer.ts +1974 -1974
  110. package/src/strand-network-state-file.ts +40 -40
  111. package/src/strand-network-state.ts +243 -243
  112. package/src/strand-revocation-enforcer.ts +654 -654
  113. package/src/strand-solicitation.ts +532 -519
  114. package/src/strand-wake-protocol.ts +401 -401
  115. package/src/types.ts +2222 -2140
  116. package/dist/diagnostics/webrtc-turn-tracker.d.ts +0 -50
  117. package/dist/diagnostics/webrtc-turn-tracker.js +0 -196
  118. package/dist/diagnostics/webrtc-turn-tracker.js.map +0 -1
  119. package/src/diagnostics/webrtc-turn-tracker.ts +0 -222
@@ -1,547 +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
- * 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
- }
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`, 28.5 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 (28.5 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
+ }