@serfab/cadre-core 0.13.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +20 -6
  2. package/dist/bootstrap-peer-store-file.js +2 -2
  3. package/dist/bootstrap-peer-store.d.ts +32 -12
  4. package/dist/bootstrap-peer-store.js +41 -15
  5. package/dist/bootstrap-peer-store.js.map +1 -1
  6. package/dist/cadre-node.d.ts +558 -80
  7. package/dist/cadre-node.js +1060 -170
  8. package/dist/cadre-node.js.map +1 -1
  9. package/dist/control-authorization.d.ts +2 -2
  10. package/dist/control-authorization.js +1 -0
  11. package/dist/control-authorization.js.map +1 -1
  12. package/dist/control-cohort.d.ts +13 -26
  13. package/dist/control-cohort.js +0 -26
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +299 -44
  16. package/dist/control-database.js +469 -69
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-read-retry.d.ts +40 -11
  19. package/dist/control-read-retry.js +48 -15
  20. package/dist/control-read-retry.js.map +1 -1
  21. package/dist/control-retry.d.ts +58 -3
  22. package/dist/control-retry.js +58 -3
  23. package/dist/control-retry.js.map +1 -1
  24. package/dist/control-schema.d.ts +1 -1
  25. package/dist/control-schema.js +103 -19
  26. package/dist/control-schema.js.map +1 -1
  27. package/dist/control-write-retry.d.ts +80 -11
  28. package/dist/control-write-retry.js +176 -29
  29. package/dist/control-write-retry.js.map +1 -1
  30. package/dist/enrolled-machine-store.js +2 -2
  31. package/dist/index.d.ts +14 -7
  32. package/dist/index.js +33 -6
  33. package/dist/index.js.map +1 -1
  34. package/dist/node-local-snapshot.d.ts +15 -7
  35. package/dist/node-local-snapshot.js +23 -8
  36. package/dist/node-local-snapshot.js.map +1 -1
  37. package/dist/peer-dial.d.ts +143 -0
  38. package/dist/peer-dial.js +176 -0
  39. package/dist/peer-dial.js.map +1 -0
  40. package/dist/relay-addrs.d.ts +90 -52
  41. package/dist/relay-addrs.js +91 -59
  42. package/dist/relay-addrs.js.map +1 -1
  43. package/dist/relay-reservation.d.ts +71 -3
  44. package/dist/relay-reservation.js +116 -8
  45. package/dist/relay-reservation.js.map +1 -1
  46. package/dist/seed-bootstrap.d.ts +30 -1
  47. package/dist/seed-bootstrap.js +62 -17
  48. package/dist/seed-bootstrap.js.map +1 -1
  49. package/dist/storage-scope.d.ts +62 -0
  50. package/dist/storage-scope.js +75 -0
  51. package/dist/storage-scope.js.map +1 -0
  52. package/dist/strand-database.d.ts +34 -16
  53. package/dist/strand-database.js +38 -24
  54. package/dist/strand-database.js.map +1 -1
  55. package/dist/strand-first-sync-gate.d.ts +152 -0
  56. package/dist/strand-first-sync-gate.js +208 -0
  57. package/dist/strand-first-sync-gate.js.map +1 -0
  58. package/dist/strand-formation-manager.d.ts +87 -5
  59. package/dist/strand-formation-manager.js +109 -5
  60. package/dist/strand-formation-manager.js.map +1 -1
  61. package/dist/strand-formation-protocol.d.ts +21 -1
  62. package/dist/strand-formation-protocol.js +30 -0
  63. package/dist/strand-formation-protocol.js.map +1 -1
  64. package/dist/strand-instance-manager.d.ts +243 -6
  65. package/dist/strand-instance-manager.js +470 -37
  66. package/dist/strand-instance-manager.js.map +1 -1
  67. package/dist/strand-member-key.d.ts +20 -12
  68. package/dist/strand-member-key.js +20 -12
  69. package/dist/strand-member-key.js.map +1 -1
  70. package/dist/strand-member-registry.js +3 -0
  71. package/dist/strand-member-registry.js.map +1 -1
  72. package/dist/strand-membership-reconciler.d.ts +361 -0
  73. package/dist/strand-membership-reconciler.js +548 -0
  74. package/dist/strand-membership-reconciler.js.map +1 -0
  75. package/dist/strand-membership-writer.d.ts +131 -11
  76. package/dist/strand-membership-writer.js +396 -134
  77. package/dist/strand-membership-writer.js.map +1 -1
  78. package/dist/strand-network-config.d.ts +46 -14
  79. package/dist/strand-network-config.js +79 -23
  80. package/dist/strand-network-config.js.map +1 -1
  81. package/dist/strand-solicitation.d.ts +10 -1
  82. package/dist/strand-solicitation.js +5 -0
  83. package/dist/strand-solicitation.js.map +1 -1
  84. package/dist/strand-wake-protocol.d.ts +11 -7
  85. package/dist/strand-wake-protocol.js +20 -52
  86. package/dist/strand-wake-protocol.js.map +1 -1
  87. package/dist/strand-watcher.js +6 -0
  88. package/dist/strand-watcher.js.map +1 -1
  89. package/dist/timed-step.d.ts +12 -0
  90. package/dist/timed-step.js +28 -0
  91. package/dist/timed-step.js.map +1 -0
  92. package/dist/timeout-scheduler.d.ts +19 -0
  93. package/dist/timeout-scheduler.js +22 -0
  94. package/dist/timeout-scheduler.js.map +1 -0
  95. package/dist/types.d.ts +262 -30
  96. package/dist/types.js.map +1 -1
  97. package/package.json +8 -8
  98. package/src/bootstrap-peer-store-file.ts +2 -2
  99. package/src/bootstrap-peer-store.ts +69 -27
  100. package/src/cadre-node.ts +7301 -6353
  101. package/src/control-authorization.ts +2 -1
  102. package/src/control-cohort.ts +122 -130
  103. package/src/control-database.ts +537 -69
  104. package/src/control-read-retry.ts +202 -167
  105. package/src/control-retry.ts +297 -190
  106. package/src/control-schema.ts +103 -19
  107. package/src/control-write-retry.ts +533 -383
  108. package/src/enrolled-machine-store.ts +2 -2
  109. package/src/index.ts +83 -6
  110. package/src/node-local-snapshot.ts +25 -8
  111. package/src/peer-dial.ts +215 -0
  112. package/src/relay-addrs.ts +458 -436
  113. package/src/relay-reservation.ts +951 -828
  114. package/src/seed-bootstrap.ts +76 -18
  115. package/src/storage-scope.ts +78 -0
  116. package/src/strand-database.ts +50 -27
  117. package/src/strand-first-sync-gate.ts +258 -0
  118. package/src/strand-formation-manager.ts +140 -5
  119. package/src/strand-formation-protocol.ts +43 -1
  120. package/src/strand-instance-manager.ts +577 -37
  121. package/src/strand-member-key.ts +20 -12
  122. package/src/strand-member-registry.ts +3 -0
  123. package/src/strand-membership-reconciler.ts +680 -0
  124. package/src/strand-membership-writer.ts +527 -189
  125. package/src/strand-network-config.ts +102 -24
  126. package/src/strand-solicitation.ts +16 -1
  127. package/src/strand-wake-protocol.ts +21 -66
  128. package/src/strand-watcher.ts +6 -0
  129. package/src/timed-step.ts +28 -0
  130. package/src/timeout-scheduler.ts +28 -0
  131. package/src/types.ts +1789 -1554
@@ -1,436 +1,458 @@
1
- /**
2
- * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
- * setting — into the listen entry a node needs before it can hold a circuit-relay
4
- * slot, and validate the operator's entries while doing it.
5
- *
6
- * `@libp2p/circuit-relay-v2`'s listener branches on the SHAPE of the listen addr,
7
- * and the same `relayAddrs` list resolves to either shape depending on WHO is
8
- * listening ({@link RelayListenRoute}):
9
- *
10
- * | route | listen entry | libp2p behaviour |
11
- * | -------------- | ------------------------------------------- | --------------------------------------------------------- |
12
- * | `'configured'` | `<relayAddr>/p2p-circuit`, one per relay | dial that relay from inside `listen()` and reserve, or throw |
13
- * | `'search'` | a single bare `/p2p-circuit` | register a pending reservation; open no connection |
14
- *
15
- * The CONTROL node takes the `'search'` route, and `CadreNode.start()` drives the
16
- * reservation explicitly (`relay-reservation.ts`) once the control database is up.
17
- * That ordering is the point: a configured circuit listener dials the relay from
18
- * inside `libp2p.start()`, so the control database was being built while a sibling
19
- * relay was already in this node's cohort — and a sibling that has not yet
20
- * replicated this node's `CadrePeer` row correctly refuses its control-DB streams,
21
- * which killed `start()` outright. See `cadre-node.ts` → `start()`.
22
- *
23
- * STRAND nodes keep the `'configured'` route (`strand-instance-manager.ts`): they
24
- * inherit the control node's `NetworkConfig`, nothing drives an explicit
25
- * reservation for them, and their relay connection cannot disturb a control-DB
26
- * bring-up (a strand node's protocol ids are namespaced `/optimystic/strand-<id>/…`,
27
- * so the relay is never in its cohort).
28
- *
29
- * `network.relayAddrs` is FAIL-FAST for the operator on both routes, just from
30
- * different places: a malformed entry throws here at config resolution, and on the
31
- * control node a first reservation attempt that does not land throws out of
32
- * `start()` (`RelayReservationFailedError`). Naming a relay that is down still
33
- * means the node does not come up.
34
- *
35
- * The bare `/p2p-circuit` search listener cannot open a connection on its own:
36
- * libp2p fills a pending reservation from `RelayDiscovery`, which nominates a peer
37
- * only once the relay-hop protocol id is in that peer's peer-store protocol list,
38
- * and that list is written exclusively by IDENTIFY — which `@optimystic/db-p2p`
39
- * namespaces per network, so a cadre node and a stock relay never identify each
40
- * other. See `relay-reservation.ts`'s module doc and `docs/architecture.md`.
41
- */
42
-
43
- import { multiaddr, type Component } from '@multiformats/multiaddr';
44
- import { circuitRelayTargetOrThrow } from './delegate-admission.js';
45
- import type { NetworkConfig } from './types.js';
46
- import type { RelayReservationState } from './relay-reservation.js';
47
-
48
- /**
49
- * The direct listener a node keeps when it configures `relayAddrs` but no
50
- * `listenAddrs`. Without this, naming a relay would silently REPLACE the node's
51
- * direct TCP listener with a circuit-only one.
52
- *
53
- * NOTE: mirrors `createLibp2pNode`'s own default listen addr in
54
- * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (`/ip4/0.0.0.0/tcp/<port>`,
55
- * and `CadreNode` passes `port: 0`) — that file is the source of truth. If it
56
- * ever changes its default, this constant has to follow.
57
- */
58
- const DEFAULT_DIRECT_LISTEN_ADDR = '/ip4/0.0.0.0/tcp/0';
59
-
60
- /**
61
- * libp2p's relay SEARCH listener: registers one pending reservation and dials
62
- * nothing. One entry covers every configured relay — the pending reservation is
63
- * per-listener, not per-relay, and `relay-reservation.ts` fills it with whichever
64
- * relay answers first.
65
- */
66
- export const RELAY_SEARCH_LISTEN_ADDR = '/p2p-circuit';
67
-
68
- /**
69
- * Which listener shape `network.relayAddrs` resolves to for this caller — see the
70
- * table in the module doc. Defaults to `'configured'` everywhere except the
71
- * control node's own libp2p options.
72
- */
73
- export type RelayListenRoute = 'configured' | 'search';
74
-
75
- /**
76
- * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
77
- * An entry that already carries `/p2p-circuit` is passed through unchanged.
78
- * Throws on an entry that is unparsable or names no relay peerId — this is
79
- * operator configuration, so a typo must fail loudly at start rather than
80
- * silently costing the node its reachability.
81
- *
82
- * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
83
- * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
84
- * one bad entry must not be fatal.
85
- */
86
- export function relayCircuitAddrs(relayAddrs: readonly string[]): string[] {
87
- return dedupe(relayAddrs.map(circuitListenAddr));
88
- }
89
-
90
- /**
91
- * The listen multiaddrs a node actually binds: configured `listenAddrs` plus the
92
- * relay listen entry `route` calls for, deduplicated, order-stable (configured
93
- * entries first). Returns `undefined` when neither field is set, so callers keep
94
- * omitting `listenAddrs` and inherit db-p2p's default.
95
- *
96
- * Every `relayAddrs` entry is validated on BOTH routes — the `'search'` route
97
- * discards the resolved circuit addrs, but an operator typo must fail at config
98
- * resolution either way.
99
- */
100
- export function resolveListenAddrs(
101
- network: NetworkConfig | undefined,
102
- route: RelayListenRoute = 'configured'
103
- ): string[] | undefined {
104
- const configured = relayCircuitAddrs(network?.relayAddrs ?? []);
105
- const relayEntries = route === 'search'
106
- ? (configured.length > 0 ? [RELAY_SEARCH_LISTEN_ADDR] : [])
107
- : configured;
108
- const listenAddrs = network?.listenAddrs;
109
- if (route === 'search') {
110
- rejectConfiguredCircuitListenAddrs(listenAddrs ?? []);
111
- }
112
- if (!listenAddrs && relayEntries.length === 0) {
113
- return undefined;
114
- }
115
- // An explicitly empty `listenAddrs` (the React Native "cannot listen" case) stays
116
- // empty — but a relay named alongside it still gets its listen entry, since
117
- // acquiring a slot is the whole point of configuring a relay.
118
- return dedupe([...(listenAddrs ?? [DEFAULT_DIRECT_LISTEN_ADDR]), ...relayEntries]);
119
- }
120
-
121
- /**
122
- * The transport-derived `createLibp2pNode` options a resolved listen set implies —
123
- * see {@link resolveTransportOptions}.
124
- */
125
- export interface ListenTransportOptions {
126
- /**
127
- * Present when some listen entry names WebSocket. Its VALUE is never bound; it is
128
- * the switch that makes `@optimystic/db-p2p` add `webSockets()` — see
129
- * {@link WS_TRANSPORT_SWITCH_PORT}.
130
- */
131
- wsPort?: number;
132
- }
133
-
134
- /**
135
- * The `wsPort` value passed purely to turn `@optimystic/db-p2p`'s WebSocket transport
136
- * ON. It is never bound, so it is deliberately `0` rather than a port scraped from a
137
- * listen entry.
138
- *
139
- * WHY it is a switch and not a port: `createLibp2pNode`
140
- * (`../optimystic/packages/db-p2p/src/libp2p-node.ts`) feeds `wsPort` into BOTH its
141
- * default transports and its default listen addrs, and `createLibp2pNodeBase`
142
- * (`libp2p-node-base.ts:490-491`) falls back to those two defaults INDEPENDENTLY:
143
- *
144
- * ```ts
145
- * const listenAddrs = options.listenAddrs ?? defaults.listenAddrs;
146
- * const transports = options.transports ?? defaults.transports;
147
- * ```
148
- *
149
- * `cadre-core` always supplies explicit `listenAddrs` alongside it, so the synthesized
150
- * `/ip4/<wsHost>/tcp/<wsPort>/ws` default ADDRESS is discarded while the `webSockets()`
151
- * transport it added survives. A scraped port would also be a lie whenever a config
152
- * names several WebSocket addresses on different ports, and the strand path rewrites
153
- * fixed ports to `0` regardless (`strand-network-config.ts`).
154
- *
155
- * NOTE: db-p2p's own doc comment on `wsPort` (`libp2p-node-base.ts:170-172`) says it is
156
- * "Ignored when `transports`/`listenAddrs` are explicitly provided" — true of the
157
- * address half, NOT of the transport half, which is the half this depends on. Re-verify
158
- * empirically rather than trusting that comment: `test/listen-transport-options.spec.ts`
159
- * boots a real node and asserts a `/ws` multiaddr appears. If db-p2p ever makes the
160
- * comment true of both halves, it needs an explicit `enableWebSockets` switch and this
161
- * constant becomes unusable.
162
- */
163
- const WS_TRANSPORT_SWITCH_PORT = 0;
164
-
165
- /**
166
- * The transport-derived libp2p options `listenAddrs` implies, and the gate that stops a
167
- * listen address the node has no transport for from being SILENTLY dropped.
168
- *
169
- * libp2p's transport manager sorts configured listen addresses by which transport claims
170
- * them, discards the unclaimed ones, and raises `UnsupportedListenAddressesError` only
171
- * when EVERY address was discarded. Pair a TCP address with a WebSocket one — which is
172
- * exactly what the shipped configs do — and the TCP address carries the start while the
173
- * missing WebSocket listener is never reported. Two halves of `NetworkConfig` that have
174
- * to agree (`listenAddrs`, and the transports the node will actually have) were never
175
- * checked against each other; this is that check, and it covers both node kinds because
176
- * both resolve their listen set through {@link resolveListenAddrs}.
177
- *
178
- * The two transport classes are handled differently, on purpose:
179
- *
180
- * - **WebSocket is DERIVED.** It is the one non-TCP transport the shipped configs need
181
- * (the React Native reference app's companion drone; `cadre start --ws-port`), and
182
- * `@optimystic/db-p2p` already knows how to add it. `cadre-core` grows no dependency
183
- * and decides no transport policy — it flips db-p2p's own switch
184
- * ({@link WS_TRANSPORT_SWITCH_PORT}).
185
- * - **Everything else is REFUSED.** Deriving `/quic-v1`, `/webrtc` or `/webtransport`
186
- * would mean importing transport packages into every `cadre-core` consumer including
187
- * the React Native and browser bundles (against the cross-platform rule in
188
- * `AGENTS.md`) and duplicating policy `libp2p-node.ts` owns. So name the address, name
189
- * the transport it needs, and refuse to start — matching how `network.relayAddrs` and
190
- * `network.announceAddrs` already treat an operator typo.
191
- *
192
- * Returns `{}` unconditionally when `network.transports` is set: a programmatic embedder
193
- * supplying transport factories owns the policy, and the factories are opaque — nothing
194
- * can be inferred from them. That is what keeps the RN phone, the web app, and the
195
- * integration-test harness unaffected.
196
- *
197
- * NOTE: pairing this with {@link resolveListenAddrs} is a CONVENTION, not a structure —
198
- * a third libp2p-node build site could resolve listen addrs and forget to call this,
199
- * putting the original bug back on that path. Both existing sites are covered
200
- * (`cadre-node.ts` → `buildControlNodeOptions`, `strand-network-config.ts` →
201
- * `strandNodeAddrs`), and they are the only two `createLibp2pNode` callers in this repo
202
- * that derive their listen set from a `NetworkConfig` — the other callers
203
- * (`integration-tests/src/harness/test-party.ts`, `quereus-plugin-sereus`'s `connect.ts`
204
- * and `connect-browser.ts`) pass no `listenAddrs` at all, or pass their own transports
205
- * with it. If a third CONFIG-derived site appears, fold the two functions into one that
206
- * returns listen addrs and transport options together, so forgetting becomes impossible
207
- * rather than merely unlikely.
208
- *
209
- * @param listenAddrs the ALREADY-resolved listen set — the output of
210
- * {@link resolveListenAddrs} after any per-node rewriting — so the check reads what
211
- * this node will actually bind.
212
- * @throws {UnbindableListenAddressError} when a listen entry names a transport outside
213
- * {tcp, ws/wss, p2p-circuit}.
214
- */
215
- export function resolveTransportOptions(
216
- network: NetworkConfig | undefined,
217
- listenAddrs: readonly string[] | undefined
218
- ): ListenTransportOptions {
219
- if (network?.transports) {
220
- return {};
221
- }
222
- const kinds = (listenAddrs ?? []).map((addr) => [addr, listenTransportKind(addr)] as const);
223
- const unsupported = kinds.filter(([, kind]) => kind === 'unsupported').map(([addr]) => addr);
224
- if (unsupported.length > 0) {
225
- throw new UnbindableListenAddressError(unsupported);
226
- }
227
- return kinds.some(([, kind]) => kind === 'websockets') ? { wsPort: WS_TRANSPORT_SWITCH_PORT } : {};
228
- }
229
-
230
- /**
231
- * Thrown at config resolution when `network.listenAddrs` names an address none of the
232
- * default transports can bind. Names each offending address alongside the libp2p
233
- * transport package it would need — what the operator has without this is a node that
234
- * starts and silently never listens there.
235
- */
236
- export class UnbindableListenAddressError extends Error {
237
- constructor(readonly listenAddrs: readonly string[]) {
238
- super(
239
- 'network.listenAddrs names an address this node has no transport for: ' +
240
- `${listenAddrs.map((a) => `${a} — ${unbindableReason(a)}`).join('; ')}. ` +
241
- 'Default transports bind TCP (including /unix/<path>), WebSocket (/ws, /wss) and circuit-relay addresses only. ' +
242
- 'Either drop the address, or supply the transport programmatically via network.transports.'
243
- );
244
- this.name = 'UnbindableListenAddressError';
245
- }
246
- }
247
-
248
- /**
249
- * Which default transport claims `listenAddr`, or `'unsupported'` when none does.
250
- *
251
- * Classification is a multiaddr COMPONENT question, not a string question, so this
252
- * parses and reads the transport stack — the component names left once the addressing
253
- * and security layers are dropped. That stack is outermost-LAST
254
- * (`/ip4/…/tcp/443/tls/ws` → `['tcp', 'ws']`), which is why its terminal entry decides.
255
- *
256
- * An unparsable entry is `'ignored'` and passes through untouched, following
257
- * `isConfiguredCircuitListenAddr` below and `ephemeralPortListenAddr`
258
- * (`strand-network-config.ts`): libp2p reports a bad listen addr itself, and this check
259
- * must only ever ADD a denial.
260
- */
261
- function listenTransportKind(listenAddr: string): 'tcp' | 'websockets' | 'circuit' | 'ignored' | 'unsupported' {
262
- let stack: readonly string[];
263
- try {
264
- stack = transportStack(listenAddr);
265
- } catch {
266
- return 'ignored';
267
- }
268
- const outermost = stack.at(-1);
269
- if (outermost === undefined) {
270
- // Nothing but addressing components — a bare `/ip4/1.2.3.4`. No transport claims
271
- // it, so it is dropped by exactly the same silent path this check exists to close.
272
- return 'unsupported';
273
- }
274
- if (outermost === 'p2p-circuit') {
275
- return 'circuit';
276
- }
277
- if (outermost === 'ws' || outermost === 'wss') {
278
- return 'websockets';
279
- }
280
- // Only a BARE tcp or unix stack is TCP. `@libp2p/tcp` binds both — its `listenFilter`
281
- // accepts an exact TCP match OR a `/unix/<path>` address (a named pipe on Windows) —
282
- // and nothing layered on top of either, which is why `/tcp/<port>/<anything else>` is
283
- // NOT waved through merely because a `tcp` component happens to appear.
284
- return stack.length === 1 && (outermost === 'tcp' || outermost === 'unix') ? 'tcp' : 'unsupported';
285
- }
286
-
287
- /**
288
- * Component names of `listenAddr` with the addressing and security layers removed, so
289
- * what remains names transports. Host components (`ip4`, `dns4`, …) and the layers that
290
- * ride inside a transport without being one (`tls`, `sni`, `certhash`, `p2p`) say
291
- * nothing about which transport has to be configured.
292
- */
293
- function transportStack(listenAddr: string): string[] {
294
- return multiaddr(listenAddr).getComponents()
295
- .map((component) => component.name)
296
- .filter((name) => !NON_TRANSPORT_COMPONENTS.has(name));
297
- }
298
-
299
- /** Components that address or secure a connection rather than name its transport. */
300
- const NON_TRANSPORT_COMPONENTS = new Set([
301
- 'ip4', 'ip6', 'ip6zone', 'dns', 'dns4', 'dns6', 'dnsaddr',
302
- 'tls', 'sni', 'certhash', 'p2p', 'noise'
303
- ]);
304
-
305
- /**
306
- * Why `listenAddr` cannot be bound, phrased for the operator: the libp2p package that
307
- * would make it bindable where one is known, and otherwise what is wrong with it.
308
- *
309
- * Read OUTERMOST-first (`/udp/…/quic-v1/webtransport` needs `@libp2p/webtransport`,
310
- * not the `@libp2p/quic` it rides on), matching how `listenTransportKind` decides.
311
- */
312
- function unbindableReason(listenAddr: string): string {
313
- let stack: readonly string[];
314
- try {
315
- stack = transportStack(listenAddr);
316
- } catch {
317
- return 'not a parsable multiaddr';
318
- }
319
- if (stack.length === 0) {
320
- return 'it names no transport component';
321
- }
322
- const pkg = [...stack].reverse().map((name) => TRANSPORT_PACKAGES[name]).find((p) => p !== undefined);
323
- return pkg === undefined ? 'needs an unrecognized transport' : `needs ${pkg}`;
324
- }
325
-
326
- /**
327
- * The libp2p package each unbindable transport component comes from. Naming the package
328
- * is the actionable half of the refusal — the operator either drops the address or wires
329
- * that package in through `network.transports`.
330
- */
331
- const TRANSPORT_PACKAGES: Record<string, string> = {
332
- 'quic': '@libp2p/quic',
333
- 'quic-v1': '@libp2p/quic',
334
- 'webtransport': '@libp2p/webtransport',
335
- 'webrtc': '@libp2p/webrtc',
336
- 'webrtc-direct': '@libp2p/webrtc'
337
- };
338
-
339
- /**
340
- * Thrown out of `CadreNode.start()` when the boot-path reservation drive for
341
- * `network.relayAddrs` produces no `/p2p-circuit` address on its FIRST attempt.
342
- *
343
- * This is what keeps `network.relayAddrs` fail-fast now that the control node
344
- * takes the `'search'` route: libp2p's own `UnsupportedListenAddressesError` used
345
- * to abort start from inside `listen()`, and an operator who names a relay is
346
- * telling the node it has no other reachability — coming up undialable is worse
347
- * than not coming up. Names the relays and the reservation's own reason, both of
348
- * which the libp2p error omitted.
349
- */
350
- export class RelayReservationFailedError extends Error {
351
- constructor(
352
- readonly relayAddrs: readonly string[],
353
- readonly state: RelayReservationState
354
- ) {
355
- super(
356
- `network.relayAddrs reservation failed (status: ${state.status}): ` +
357
- `${state.error ?? 'no /p2p-circuit address appeared'} — relays: ${relayAddrs.join(', ')}`
358
- );
359
- this.name = 'RelayReservationFailedError';
360
- }
361
- }
362
-
363
- /**
364
- * A hand-written `<relay>/p2p-circuit` entry in `network.listenAddrs` is the
365
- * CONFIGURED listener shape, and it is unusable on the `'search'` route: libp2p
366
- * dials that relay from inside `listen()`, the bring-up quiet period
367
- * (`membership-connection-gater.ts`) denies exactly that dial, `listen()` fails, and
368
- * the transport manager's default `FATAL_ALL` aborts `libp2p.start()`. The operator
369
- * would see `UnsupportedListenAddressesError` from deep inside bring-up with nothing
370
- * naming the cause, so name it here instead.
371
- *
372
- * `network.relayAddrs` is the exact replacement — same relay, and the reservation is
373
- * driven after bring-up, which is the whole point of the route.
374
- */
375
- function rejectConfiguredCircuitListenAddrs(listenAddrs: readonly string[]): void {
376
- const configured = listenAddrs.filter(isConfiguredCircuitListenAddr);
377
- if (configured.length > 0) {
378
- throw new Error(
379
- 'network.listenAddrs names a relay directly ' +
380
- `(${configured.join(', ')}), which a control node cannot listen on: libp2p would ` +
381
- 'dial that relay during control-database bring-up, when the node accepts no ' +
382
- 'connections. Move the relay to network.relayAddrs, which reserves after bring-up.'
383
- );
384
- }
385
- }
386
-
387
- /** `<something>/p2p-circuit` — the configured shape, as opposed to the bare search addr. */
388
- function isConfiguredCircuitListenAddr(listenAddr: string): boolean {
389
- if (listenAddr === RELAY_SEARCH_LISTEN_ADDR) {
390
- return false;
391
- }
392
- try {
393
- return multiaddr(listenAddr).getComponents().some((c) => c.name === 'p2p-circuit');
394
- } catch {
395
- // Not our error to raise: libp2p reports an unparsable listen addr itself, and
396
- // this helper only ever ADDS a denial.
397
- return false;
398
- }
399
- }
400
-
401
- /**
402
- * One entry of {@link relayCircuitAddrs}: the addr the node listens on for this relay.
403
- *
404
- * NOTE: an entry carrying components AFTER `/p2p-circuit` — a full relayed DIAL addr,
405
- * `…/p2p/<relay>/p2p-circuit/p2p/<someone else>` — is passed through as written and
406
- * would be listened on verbatim. It validates (the relay it names is real), so only an
407
- * operator who pastes a peer's relayed address into `relayAddrs` hits it; if that turns
408
- * out to be a common paste, truncate at the `/p2p-circuit` component here.
409
- */
410
- function circuitListenAddr(relayAddr: string): string {
411
- const alreadyCircuit = parseComponents(relayAddr).some((c) => c.name === 'p2p-circuit');
412
- const listenAddr = alreadyCircuit ? relayAddr : `${relayAddr}/p2p-circuit`;
413
- try {
414
- circuitRelayTargetOrThrow(listenAddr); // validates the relay peerId
415
- } catch (err) {
416
- throw new Error(
417
- `network.relayAddrs entry names no relay peerId (expected <dial addr>/p2p/<relayPeerId>): ${relayAddr}`,
418
- { cause: err }
419
- );
420
- }
421
- return listenAddr;
422
- }
423
-
424
- /** Multiaddr components of `relayAddr`, with the config field named on a parse failure. */
425
- function parseComponents(relayAddr: string): Component[] {
426
- try {
427
- return multiaddr(relayAddr).getComponents();
428
- } catch (err) {
429
- throw new Error(`network.relayAddrs entry is not a valid multiaddr: ${relayAddr}`, { cause: err });
430
- }
431
- }
432
-
433
- /** Exact-string dedupe, first occurrence wins, so the list is stable across restarts. */
434
- function dedupe(addrs: readonly string[]): string[] {
435
- return [...new Set(addrs)];
436
- }
1
+ /**
2
+ * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
+ * setting — into the listen entry a node needs before it can hold a circuit-relay
4
+ * slot, and validate the operator's entries while doing it.
5
+ *
6
+ * `@libp2p/circuit-relay-v2`'s listener branches on the SHAPE of the listen addr:
7
+ *
8
+ * | listen entry | libp2p behaviour |
9
+ * | ----------------------------------- | --------------------------------------------------------------- |
10
+ * | `<relayAddr>/p2p-circuit` | CONFIGURED: dial that relay from inside `listen()` and reserve, or throw |
11
+ * | bare `/p2p-circuit` | SEARCH: register a pending reservation; open no connection |
12
+ *
13
+ * Every cadre-built node takes the SEARCH shape, and something explicit drives the
14
+ * reservation afterwards (`relay-reservation.ts`):
15
+ *
16
+ * - The CONTROL node resolves `relayAddrs` here to ONE bare entry (whichever relay
17
+ * answers first fills it) and `CadreNode.start()` drives the reservation once the
18
+ * control database is up. That ordering is the point: a configured circuit
19
+ * listener dials the relay from inside `libp2p.start()`, so the control database
20
+ * was being built while a sibling relay was already in this node's cohort — and a
21
+ * sibling that has not yet replicated this node's `CadrePeer` row correctly refuses
22
+ * its control-DB streams, which killed `start()` outright. See `cadre-node.ts` →
23
+ * `start()`.
24
+ * - Each STRAND node resolves the same `relayAddrs` to one bare entry PER relay and
25
+ * runs one reservation supervisor per relay (`strand-network-config.ts`,
26
+ * `strand-instance-manager.ts`).
27
+ *
28
+ * The CONFIGURED shape is deliberately not producible from a `NetworkConfig` any
29
+ * more: it loses its address and never recovers when the relay restarts, when either
30
+ * side hangs up, and — with no network event at all — on libp2p's own reservation
31
+ * refresh, which removes the reservation before re-creating it while a configured
32
+ * listener republishes only from inside its own `listen()`. A hand-written
33
+ * `<relay>/p2p-circuit` entry in `network.listenAddrs` is rejected on the control
34
+ * node ({@link resolveListenAddrs}) and folded into the supervised relay set on a
35
+ * strand node.
36
+ *
37
+ * `network.relayAddrs` is FAIL-FAST for the operator by default: a malformed entry
38
+ * throws here at config resolution regardless of posture, and on the control node a
39
+ * first reservation attempt that does not land throws out of `start()`
40
+ * (`RelayReservationFailedError`). Naming a relay that is down still means the control
41
+ * node does not come up. `network.requireRelay: false` softens the second half only —
42
+ * for a node that must still boot with no network (a phone, a browser tab) — logging
43
+ * the failed attempt instead of throwing and leaving the retry supervisor running in
44
+ * the background; the malformed-entry check is unaffected. A strand node is
45
+ * fail-SOFT regardless of `requireRelay` (its supervisor keeps trying while the
46
+ * strand serves).
47
+ *
48
+ * The bare `/p2p-circuit` search listener cannot open a connection on its own:
49
+ * libp2p fills a pending reservation from `RelayDiscovery`, which nominates a peer
50
+ * only once the relay-hop protocol id is in that peer's peer-store protocol list,
51
+ * and that list is written exclusively by IDENTIFY — which `@optimystic/db-p2p`
52
+ * namespaces per network, so a cadre node and a stock relay never identify each
53
+ * other. See `relay-reservation.ts`'s module doc and `docs/architecture.md`.
54
+ */
55
+
56
+ import { multiaddr, type Component } from '@multiformats/multiaddr';
57
+ import { circuitRelayTargetOrThrow } from './delegate-admission.js';
58
+ import type { NetworkConfig } from './types.js';
59
+ import type { RelayReservationState } from './relay-reservation.js';
60
+
61
+ /**
62
+ * The direct listener a node keeps when it configures `relayAddrs` but no
63
+ * `listenAddrs`. Without this, naming a relay would silently REPLACE the node's
64
+ * direct TCP listener with a circuit-only one. Shared with the strand-node
65
+ * derivation (`strand-network-config.ts`), which applies the same rule.
66
+ *
67
+ * NOTE: mirrors `createLibp2pNode`'s own default listen addr in
68
+ * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (`/ip4/0.0.0.0/tcp/<port>`,
69
+ * and `CadreNode` passes `port: 0`) — that file is the source of truth. If it
70
+ * ever changes its default, this constant has to follow.
71
+ */
72
+ export const DEFAULT_DIRECT_LISTEN_ADDR = '/ip4/0.0.0.0/tcp/0';
73
+
74
+ /**
75
+ * libp2p's relay SEARCH listener: registers one pending reservation and dials
76
+ * nothing. The pending reservation is per-LISTENER, not per-relay: the control
77
+ * node binds one entry for its whole relay list (`relay-reservation.ts` fills it
78
+ * with whichever relay answers first), a strand node binds one entry per relay so
79
+ * each relay's supervisor has a slot of its own to fill.
80
+ */
81
+ export const RELAY_SEARCH_LISTEN_ADDR = '/p2p-circuit';
82
+
83
+ /**
84
+ * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
85
+ * An entry that already carries `/p2p-circuit` is passed through unchanged.
86
+ * Throws on an entry that is unparsable or names no relay peerId — this is
87
+ * operator configuration, so a typo must fail loudly at start rather than
88
+ * silently costing the node its reachability.
89
+ *
90
+ * No node LISTENS on these any more (see the module doc); they are the validated
91
+ * form of `relayAddrs`, read by `CadreNode.circuitRelayTargets` for the delegate
92
+ * announce and by `strand-network-config.ts` for the per-relay supervisor list.
93
+ *
94
+ * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
95
+ * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
96
+ * one bad entry must not be fatal.
97
+ */
98
+ export function relayCircuitAddrs(relayAddrs: readonly string[]): string[] {
99
+ return dedupe(relayAddrs.map(circuitListenAddr));
100
+ }
101
+
102
+ /**
103
+ * The listen multiaddrs the CONTROL node binds: configured `listenAddrs` plus ONE
104
+ * bare `/p2p-circuit` search entry when `relayAddrs` names any relay, deduplicated,
105
+ * order-stable (configured entries first). Returns `undefined` when neither field
106
+ * is set, so callers keep omitting `listenAddrs` and inherit db-p2p's default.
107
+ *
108
+ * Every `relayAddrs` entry is validated even though the search entry discards the
109
+ * resolved circuit addrs — an operator typo must fail at config resolution. A
110
+ * hand-written `<relay>/p2p-circuit` entry in `listenAddrs` is rejected outright
111
+ * (see {@link rejectConfiguredCircuitListenAddrs}).
112
+ *
113
+ * Strand nodes derive their own listen set from the same config in
114
+ * `strand-network-config.ts` (`strandNodeAddrs`) — one search entry per relay,
115
+ * fixed direct ports made ephemeral.
116
+ */
117
+ export function resolveListenAddrs(network: NetworkConfig | undefined): string[] | undefined {
118
+ const relayEntries = relayCircuitAddrs(network?.relayAddrs ?? []).length > 0
119
+ ? [RELAY_SEARCH_LISTEN_ADDR]
120
+ : [];
121
+ const listenAddrs = network?.listenAddrs;
122
+ rejectConfiguredCircuitListenAddrs(listenAddrs ?? []);
123
+ if (!listenAddrs && relayEntries.length === 0) {
124
+ return undefined;
125
+ }
126
+ // An explicitly empty `listenAddrs` (the React Native "cannot listen" case) stays
127
+ // empty — but a relay named alongside it still gets its listen entry, since
128
+ // acquiring a slot is the whole point of configuring a relay.
129
+ return dedupe([...(listenAddrs ?? [DEFAULT_DIRECT_LISTEN_ADDR]), ...relayEntries]);
130
+ }
131
+
132
+ /**
133
+ * The transport-derived `createLibp2pNode` options a resolved listen set implies —
134
+ * see {@link resolveTransportOptions}.
135
+ */
136
+ export interface ListenTransportOptions {
137
+ /**
138
+ * Present when some listen entry names WebSocket. Its VALUE is never bound; it is
139
+ * the switch that makes `@optimystic/db-p2p` add `webSockets()` — see
140
+ * {@link WS_TRANSPORT_SWITCH_PORT}.
141
+ */
142
+ wsPort?: number;
143
+ }
144
+
145
+ /**
146
+ * The `wsPort` value passed purely to turn `@optimystic/db-p2p`'s WebSocket transport
147
+ * ON. It is never bound, so it is deliberately `0` rather than a port scraped from a
148
+ * listen entry.
149
+ *
150
+ * WHY it is a switch and not a port: `createLibp2pNode`
151
+ * (`../optimystic/packages/db-p2p/src/libp2p-node.ts`) feeds `wsPort` into BOTH its
152
+ * default transports and its default listen addrs, and `createLibp2pNodeBase`
153
+ * (`libp2p-node-base.ts:490-491`) falls back to those two defaults INDEPENDENTLY:
154
+ *
155
+ * ```ts
156
+ * const listenAddrs = options.listenAddrs ?? defaults.listenAddrs;
157
+ * const transports = options.transports ?? defaults.transports;
158
+ * ```
159
+ *
160
+ * `cadre-core` always supplies explicit `listenAddrs` alongside it, so the synthesized
161
+ * `/ip4/<wsHost>/tcp/<wsPort>/ws` default ADDRESS is discarded while the `webSockets()`
162
+ * transport it added survives. A scraped port would also be a lie whenever a config
163
+ * names several WebSocket addresses on different ports, and the strand path rewrites
164
+ * fixed ports to `0` regardless (`strand-network-config.ts`).
165
+ *
166
+ * NOTE: db-p2p's own doc comment on `wsPort` (`libp2p-node-base.ts:170-172`) says it is
167
+ * "Ignored when `transports`/`listenAddrs` are explicitly provided" — true of the
168
+ * address half, NOT of the transport half, which is the half this depends on. Re-verify
169
+ * empirically rather than trusting that comment: `test/listen-transport-options.spec.ts`
170
+ * boots a real node and asserts a `/ws` multiaddr appears. If db-p2p ever makes the
171
+ * comment true of both halves, it needs an explicit `enableWebSockets` switch and this
172
+ * constant becomes unusable.
173
+ */
174
+ const WS_TRANSPORT_SWITCH_PORT = 0;
175
+
176
+ /**
177
+ * The transport-derived libp2p options `listenAddrs` implies, and the gate that stops a
178
+ * listen address the node has no transport for from being SILENTLY dropped.
179
+ *
180
+ * libp2p's transport manager sorts configured listen addresses by which transport claims
181
+ * them, discards the unclaimed ones, and raises `UnsupportedListenAddressesError` only
182
+ * when EVERY address was discarded. Pair a TCP address with a WebSocket one — which is
183
+ * exactly what the shipped configs do — and the TCP address carries the start while the
184
+ * missing WebSocket listener is never reported. Two halves of `NetworkConfig` that have
185
+ * to agree (`listenAddrs`, and the transports the node will actually have) were never
186
+ * checked against each other; this is that check, and it covers both node kinds because
187
+ * both derive their listen set from the same config here ({@link resolveListenAddrs}) or
188
+ * in `strand-network-config.ts`, and both call this on the result.
189
+ *
190
+ * The two transport classes are handled differently, on purpose:
191
+ *
192
+ * - **WebSocket is DERIVED.** It is the one non-TCP transport the shipped configs need
193
+ * (the React Native reference app's companion drone; `cadre start --ws-port`), and
194
+ * `@optimystic/db-p2p` already knows how to add it. `cadre-core` grows no dependency
195
+ * and decides no transport policy — it flips db-p2p's own switch
196
+ * ({@link WS_TRANSPORT_SWITCH_PORT}).
197
+ * - **Everything else is REFUSED.** Deriving `/quic-v1`, `/webrtc` or `/webtransport`
198
+ * would mean importing transport packages into every `cadre-core` consumer including
199
+ * the React Native and browser bundles (against the cross-platform rule in
200
+ * `AGENTS.md`) and duplicating policy `libp2p-node.ts` owns. So name the address, name
201
+ * the transport it needs, and refuse to start — matching how `network.relayAddrs` and
202
+ * `network.announceAddrs` already treat an operator typo.
203
+ *
204
+ * Returns `{}` unconditionally when `network.transports` is set: a programmatic embedder
205
+ * supplying transport factories owns the policy, and the factories are opaque — nothing
206
+ * can be inferred from them. That is what keeps the RN phone, the web app, and the
207
+ * integration-test harness unaffected.
208
+ *
209
+ * NOTE: pairing this with {@link resolveListenAddrs} is a CONVENTION, not a structure —
210
+ * a third libp2p-node build site could resolve listen addrs and forget to call this,
211
+ * putting the original bug back on that path. Both existing sites are covered
212
+ * (`cadre-node.ts` → `buildControlNodeOptions`, `strand-network-config.ts` →
213
+ * `strandNodeAddrs`), and they are the only two `createLibp2pNode` callers in this repo
214
+ * that derive their listen set from a `NetworkConfig` — the other callers
215
+ * (`integration-tests/src/harness/test-party.ts`, `quereus-plugin-sereus`'s `connect.ts`
216
+ * and `connect-browser.ts`) pass no `listenAddrs` at all, or pass their own transports
217
+ * with it. If a third CONFIG-derived site appears, fold the two functions into one that
218
+ * returns listen addrs and transport options together, so forgetting becomes impossible
219
+ * rather than merely unlikely.
220
+ *
221
+ * @param listenAddrs the ALREADY-resolved listen set — the output of
222
+ * {@link resolveListenAddrs}, or the strand derivation, after any per-node rewriting —
223
+ * so the check reads what this node will actually bind.
224
+ * @throws {UnbindableListenAddressError} when a listen entry names a transport outside
225
+ * {tcp, ws/wss, p2p-circuit}.
226
+ */
227
+ export function resolveTransportOptions(
228
+ network: NetworkConfig | undefined,
229
+ listenAddrs: readonly string[] | undefined
230
+ ): ListenTransportOptions {
231
+ if (network?.transports) {
232
+ return {};
233
+ }
234
+ const kinds = (listenAddrs ?? []).map((addr) => [addr, listenTransportKind(addr)] as const);
235
+ const unsupported = kinds.filter(([, kind]) => kind === 'unsupported').map(([addr]) => addr);
236
+ if (unsupported.length > 0) {
237
+ throw new UnbindableListenAddressError(unsupported);
238
+ }
239
+ return kinds.some(([, kind]) => kind === 'websockets') ? { wsPort: WS_TRANSPORT_SWITCH_PORT } : {};
240
+ }
241
+
242
+ /**
243
+ * Thrown at config resolution when `network.listenAddrs` names an address none of the
244
+ * default transports can bind. Names each offending address alongside the libp2p
245
+ * transport package it would need — what the operator has without this is a node that
246
+ * starts and silently never listens there.
247
+ */
248
+ export class UnbindableListenAddressError extends Error {
249
+ constructor(readonly listenAddrs: readonly string[]) {
250
+ super(
251
+ 'network.listenAddrs names an address this node has no transport for: ' +
252
+ `${listenAddrs.map((a) => `${a} — ${unbindableReason(a)}`).join('; ')}. ` +
253
+ 'Default transports bind TCP (including /unix/<path>), WebSocket (/ws, /wss) and circuit-relay addresses only. ' +
254
+ 'Either drop the address, or supply the transport programmatically via network.transports.'
255
+ );
256
+ this.name = 'UnbindableListenAddressError';
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Which default transport claims `listenAddr`, or `'unsupported'` when none does.
262
+ *
263
+ * Classification is a multiaddr COMPONENT question, not a string question, so this
264
+ * parses and reads the transport stack — the component names left once the addressing
265
+ * and security layers are dropped. That stack is outermost-LAST
266
+ * (`/ip4/…/tcp/443/tls/ws` → `['tcp', 'ws']`), which is why its terminal entry decides.
267
+ *
268
+ * An unparsable entry is `'ignored'` and passes through untouched, following
269
+ * `isConfiguredCircuitListenAddr` below and `ephemeralPortListenAddr`
270
+ * (`strand-network-config.ts`): libp2p reports a bad listen addr itself, and this check
271
+ * must only ever ADD a denial.
272
+ */
273
+ function listenTransportKind(listenAddr: string): 'tcp' | 'websockets' | 'circuit' | 'ignored' | 'unsupported' {
274
+ let stack: readonly string[];
275
+ try {
276
+ stack = transportStack(listenAddr);
277
+ } catch {
278
+ return 'ignored';
279
+ }
280
+ const outermost = stack.at(-1);
281
+ if (outermost === undefined) {
282
+ // Nothing but addressing components — a bare `/ip4/1.2.3.4`. No transport claims
283
+ // it, so it is dropped by exactly the same silent path this check exists to close.
284
+ return 'unsupported';
285
+ }
286
+ if (outermost === 'p2p-circuit') {
287
+ return 'circuit';
288
+ }
289
+ if (outermost === 'ws' || outermost === 'wss') {
290
+ return 'websockets';
291
+ }
292
+ // Only a BARE tcp or unix stack is TCP. `@libp2p/tcp` binds both — its `listenFilter`
293
+ // accepts an exact TCP match OR a `/unix/<path>` address (a named pipe on Windows) —
294
+ // and nothing layered on top of either, which is why `/tcp/<port>/<anything else>` is
295
+ // NOT waved through merely because a `tcp` component happens to appear.
296
+ return stack.length === 1 && (outermost === 'tcp' || outermost === 'unix') ? 'tcp' : 'unsupported';
297
+ }
298
+
299
+ /**
300
+ * Component names of `listenAddr` with the addressing and security layers removed, so
301
+ * what remains names transports. Host components (`ip4`, `dns4`, …) and the layers that
302
+ * ride inside a transport without being one (`tls`, `sni`, `certhash`, `p2p`) say
303
+ * nothing about which transport has to be configured.
304
+ */
305
+ function transportStack(listenAddr: string): string[] {
306
+ return multiaddr(listenAddr).getComponents()
307
+ .map((component) => component.name)
308
+ .filter((name) => !NON_TRANSPORT_COMPONENTS.has(name));
309
+ }
310
+
311
+ /** Components that address or secure a connection rather than name its transport. */
312
+ const NON_TRANSPORT_COMPONENTS = new Set([
313
+ 'ip4', 'ip6', 'ip6zone', 'dns', 'dns4', 'dns6', 'dnsaddr',
314
+ 'tls', 'sni', 'certhash', 'p2p', 'noise'
315
+ ]);
316
+
317
+ /**
318
+ * Why `listenAddr` cannot be bound, phrased for the operator: the libp2p package that
319
+ * would make it bindable where one is known, and otherwise what is wrong with it.
320
+ *
321
+ * Read OUTERMOST-first (`/udp/…/quic-v1/webtransport` needs `@libp2p/webtransport`,
322
+ * not the `@libp2p/quic` it rides on), matching how `listenTransportKind` decides.
323
+ */
324
+ function unbindableReason(listenAddr: string): string {
325
+ let stack: readonly string[];
326
+ try {
327
+ stack = transportStack(listenAddr);
328
+ } catch {
329
+ return 'not a parsable multiaddr';
330
+ }
331
+ if (stack.length === 0) {
332
+ return 'it names no transport component';
333
+ }
334
+ const pkg = [...stack].reverse().map((name) => TRANSPORT_PACKAGES[name]).find((p) => p !== undefined);
335
+ return pkg === undefined ? 'needs an unrecognized transport' : `needs ${pkg}`;
336
+ }
337
+
338
+ /**
339
+ * The libp2p package each unbindable transport component comes from. Naming the package
340
+ * is the actionable half of the refusal — the operator either drops the address or wires
341
+ * that package in through `network.transports`.
342
+ */
343
+ const TRANSPORT_PACKAGES: Record<string, string> = {
344
+ 'quic': '@libp2p/quic',
345
+ 'quic-v1': '@libp2p/quic',
346
+ 'webtransport': '@libp2p/webtransport',
347
+ 'webrtc': '@libp2p/webrtc',
348
+ 'webrtc-direct': '@libp2p/webrtc'
349
+ };
350
+
351
+ /**
352
+ * Thrown out of `CadreNode.start()` when the boot-path reservation drive for
353
+ * `network.relayAddrs` produces no `/p2p-circuit` address on its FIRST attempt,
354
+ * UNLESS `network.requireRelay` is explicitly `false` (see `driveControlRelayReservation`,
355
+ * which logs and returns instead on that posture).
356
+ *
357
+ * This is what keeps `network.relayAddrs` fail-fast by default now that the control node
358
+ * listens on the bare search entry: libp2p's own `UnsupportedListenAddressesError` used
359
+ * to abort start from inside `listen()`, and an operator who names a relay is
360
+ * telling the node it has no other reachability — coming up undialable is worse
361
+ * than not coming up. Names the relays and the reservation's own reason, both of
362
+ * which the libp2p error omitted.
363
+ */
364
+ export class RelayReservationFailedError extends Error {
365
+ constructor(
366
+ readonly relayAddrs: readonly string[],
367
+ readonly state: RelayReservationState
368
+ ) {
369
+ super(
370
+ `network.relayAddrs reservation failed (status: ${state.status}): ` +
371
+ `${state.error ?? 'no /p2p-circuit address appeared'} — relays: ${relayAddrs.join(', ')}`
372
+ );
373
+ this.name = 'RelayReservationFailedError';
374
+ }
375
+ }
376
+
377
+ /**
378
+ * A hand-written `<relay>/p2p-circuit` entry in `network.listenAddrs` is the
379
+ * CONFIGURED listener shape, and it is unusable on the control node: libp2p
380
+ * dials that relay from inside `listen()`, the bring-up quiet period
381
+ * (`membership-connection-gater.ts`) denies exactly that dial, `listen()` fails, and
382
+ * the transport manager's default `FATAL_ALL` aborts `libp2p.start()`. The operator
383
+ * would see `UnsupportedListenAddressesError` from deep inside bring-up with nothing
384
+ * naming the cause, so name it here instead.
385
+ *
386
+ * `network.relayAddrs` is the exact replacement — same relay, and the reservation is
387
+ * driven after bring-up, which is the whole point of the search shape. (A strand node
388
+ * built directly from such a config folds the entry into its supervised relay set
389
+ * instead — `strand-network-config.ts` — but the control node's resolution runs first
390
+ * on every machine, so in production the entry never reaches a strand node.)
391
+ */
392
+ function rejectConfiguredCircuitListenAddrs(listenAddrs: readonly string[]): void {
393
+ const configured = listenAddrs.filter(isConfiguredCircuitListenAddr);
394
+ if (configured.length > 0) {
395
+ throw new Error(
396
+ 'network.listenAddrs names a relay directly ' +
397
+ `(${configured.join(', ')}), which a control node cannot listen on: libp2p would ` +
398
+ 'dial that relay during control-database bring-up, when the node accepts no ' +
399
+ 'connections. Move the relay to network.relayAddrs, which reserves after bring-up.'
400
+ );
401
+ }
402
+ }
403
+
404
+ /**
405
+ * `<something>/p2p-circuit` — the configured shape, as opposed to the bare search
406
+ * addr. An unparsable entry is `false`: libp2p reports a bad listen addr itself,
407
+ * and this helper only ever ADDS a denial (or, on the strand path, a supervisor).
408
+ */
409
+ export function isConfiguredCircuitListenAddr(listenAddr: string): boolean {
410
+ if (listenAddr === RELAY_SEARCH_LISTEN_ADDR) {
411
+ return false;
412
+ }
413
+ try {
414
+ return multiaddr(listenAddr).getComponents().some((c) => c.name === 'p2p-circuit');
415
+ } catch {
416
+ // Not our error to raise: libp2p reports an unparsable listen addr itself, and
417
+ // this helper only ever ADDS a denial.
418
+ return false;
419
+ }
420
+ }
421
+
422
+ /**
423
+ * One entry of {@link relayCircuitAddrs}: this relay's addr in the configured shape.
424
+ *
425
+ * NOTE: an entry carrying components AFTER `/p2p-circuit` — a full relayed DIAL addr,
426
+ * `…/p2p/<relay>/p2p-circuit/p2p/<someone else>` — is passed through as written. It
427
+ * validates (the relay it names is real), and every consumer reads only the relay
428
+ * peer id and the dial prefix before `/p2p-circuit`, so the tail is ignored rather
429
+ * than harmful; if that paste turns out to be common, truncate at the `/p2p-circuit`
430
+ * component here so the resolved list is canonical.
431
+ */
432
+ function circuitListenAddr(relayAddr: string): string {
433
+ const alreadyCircuit = parseComponents(relayAddr).some((c) => c.name === 'p2p-circuit');
434
+ const listenAddr = alreadyCircuit ? relayAddr : `${relayAddr}/p2p-circuit`;
435
+ try {
436
+ circuitRelayTargetOrThrow(listenAddr); // validates the relay peerId
437
+ } catch (err) {
438
+ throw new Error(
439
+ `network.relayAddrs entry names no relay peerId (expected <dial addr>/p2p/<relayPeerId>): ${relayAddr}`,
440
+ { cause: err }
441
+ );
442
+ }
443
+ return listenAddr;
444
+ }
445
+
446
+ /** Multiaddr components of `relayAddr`, with the config field named on a parse failure. */
447
+ function parseComponents(relayAddr: string): Component[] {
448
+ try {
449
+ return multiaddr(relayAddr).getComponents();
450
+ } catch (err) {
451
+ throw new Error(`network.relayAddrs entry is not a valid multiaddr: ${relayAddr}`, { cause: err });
452
+ }
453
+ }
454
+
455
+ /** Exact-string dedupe, first occurrence wins, so the list is stable across restarts. */
456
+ function dedupe(addrs: readonly string[]): string[] {
457
+ return [...new Set(addrs)];
458
+ }