@serfab/cadre-core 1.22.0 → 1.24.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 (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
package/src/peer-dial.ts CHANGED
@@ -1,605 +1,698 @@
1
- /**
2
- * Dialing one peer from a list of candidate addresses, so that an address that
3
- * never answers cannot use up the time the others needed.
4
- *
5
- * libp2p's own multi-address dial (`libp2p.dial(addrs)`, `DialQueue.dialPeer`)
6
- * tries the addresses ONE AT A TIME under ONE signal. Its only per-address limit
7
- * is the connection manager's `addressDialTimeout` (libp2p 3.3+), which cadre
8
- * sizes for a cold relayed open through two admission decisions
9
- * (`optimysticDialLimits` in `link-budget.ts`: 39 s at the default declared
10
- * link). An address whose connection attempt is silently dropped — a firewall, a
11
- * subnet the dialer cannot route to, a virtual adapter's address a Windows host
12
- * reports alongside its real ones — holds that dial for that long or until the
13
- * whole signal expires, and the addresses sorted after it get what is left. It
14
- * also sorts the list itself (`defaultAddressSorter`), putting loopback addresses
15
- * last, behind exactly the LAN addresses most likely to be dropped. A phone
16
- * borrowing a node from a cadre-host whose only reachable address was the
17
- * forwarded loopback one never connected for this reason.
18
- *
19
- * So the addresses are dialed here, each as its own transport-manager dial
20
- * ({@link dialAddr}) with its own time limit ({@link PeerDialBudget.perAddressMs}),
21
- * inside a limit for the whole peer ({@link PeerDialBudget.totalMs}). One address
22
- * per call also means libp2p's sorter has nothing to reorder, so the order is
23
- * chosen here ({@link directBeforeRelayed}). The dial goes around libp2p's dial
24
- * queue because the queue joins any dial of a peer to a queued job for that peer
25
- * id, whatever address the new dial names — see {@link dialAddr}. Every address
26
- * is bound to the peer the caller expects ({@link withTrailingPeerId}) so the
27
- * handshake verifies who answered.
28
- *
29
- * Dependency-free apart from `control-stream.ts` and `link-budget.ts`, so any
30
- * module may import it without creating an import cycle. That is why the two
31
- * address helpers ({@link trailingPeerId}, {@link withTrailingPeerId}) live here
32
- * rather than in `peer-record.ts`, which pulls in the crypto plugin.
33
- */
34
-
35
- import debug from 'debug';
36
- import type { Connection, ConnectionGater, Libp2pStatus, PeerId } from '@libp2p/interface';
37
- import { peerIdFromString } from '@libp2p/peer-id';
38
- import type { Component, Multiaddr } from '@multiformats/multiaddr';
39
- import { withDeadline } from './control-stream.js';
40
- import { relayedDialBudgetMs } from './link-budget.js';
41
- import { describeThrown, toError } from './describe-thrown.js';
42
-
43
- const log = debug('sereus:cadre:peer-dial');
44
-
45
- /**
46
- * The peer id a multiaddr terminates in, or `null` when it names none.
47
- *
48
- * The LAST `/p2p/` component is the dial target: a circuit address
49
- * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
50
- * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
51
- * cannot express that distinction.
52
- */
53
- export function trailingPeerId(addr: Multiaddr): string | null {
54
- const p2p = addr.getComponents().filter((c) => c.name === 'p2p');
55
- return p2p.length > 0 ? (p2p[p2p.length - 1].value ?? null) : null;
56
- }
57
-
58
- /**
59
- * `addr` guaranteed to terminate in `/p2p/<peerId>` — the shape every dial needs,
60
- * since the upgrader verifies that id during the handshake — or `null` when it
61
- * cannot, because the address already terminates in a DIFFERENT peer id and
62
- * therefore does not reach `peerId` at all.
63
- *
64
- * Three input shapes, matching what a `CadrePeer` record can legitimately carry:
65
- *
66
- * - no `/p2p/` component (`/ip4/1.2.3.4/tcp/4001`) — the suffix is appended;
67
- * - a relay hop with the destination missing (`…/p2p/<relay>/p2p-circuit`) — the
68
- * last component is the circuit, not a peer id, so the suffix is appended and
69
- * the address becomes the full `…/p2p/<relay>/p2p-circuit/p2p/<peerId>`;
70
- * - already terminating in `/p2p/<X>` — returned untouched when `X` is `peerId`,
71
- * dropped otherwise.
72
- *
73
- * This is deliberately the same rule libp2p applies internally in
74
- * `calculateMultiaddrs` (append when the LAST component is not `p2p`) followed by
75
- * its wrong-peer-id filter, so a normalized list matches what libp2p would have
76
- * built anyway. Normalizing before a list dial is what keeps a list from mixing
77
- * suffixed and unsuffixed entries, which `getPeerAddress` rejects outright
78
- * ("Multiaddrs must all have the same peer id or have no peer id") — taking the
79
- * whole peer down with it, not just the odd address.
80
- *
81
- * Throws when `peerId` does not parse as a peer id (the encapsulation validates
82
- * it). Never use before signature verification: verification runs against the
83
- * original on-record strings.
84
- */
85
- export function withTrailingPeerId(addr: Multiaddr, peerId: string): Multiaddr | null {
86
- const components = addr.getComponents();
87
- if (components[components.length - 1]?.name !== 'p2p') {
88
- return addr.encapsulate(`/p2p/${peerId}`);
89
- }
90
- return trailingPeerId(addr) === peerId ? addr : null;
91
- }
92
-
93
- /**
94
- * Default limit on ONE address's dial attempt, in ms, at the DEFAULT declared link round trip:
95
- * `RELAYED_DIAL_ROUND_TRIPS` (5) x `DECLARED_LINK_ROUND_TRIP_MS` (3500 ms) plus
96
- * `DIAL_ADMISSION_DECISIONS` (2) x `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms) = 21 500 ms
97
- * (`relayedDialBudgetMs`). It was a fixed 8000 ms before it was derived.
98
- *
99
- * It has to cover the slowest address that should succeed, because an attempt
100
- * that needs longer fails the same way on every retry. That is a relayed dial on
101
- * a mobile link: connect to the relay (transport, encryption and multiplexer
102
- * handshakes, when no relay connection is open yet), open the circuit, then run
103
- * both handshakes again end to end through the relay. `link-budget.ts` is where that
104
- * reasoning is now a measured count instead of an estimate — five link round trips, measured at
105
- * 15 113 ms on a link whose round trip is 3 s — so the value MOVES with a host's
106
- * `NetworkConfig.linkRoundTripMs` rather than pinning the band this node can reach to whatever
107
- * number was typed here. A direct dial that works is far quicker — a phone's WebSocket dial to
108
- * a node forwarded over `adb reverse` measured 1.6 s end to end.
109
- *
110
- * Deriving it rather than leaving it fixed is deliberate: at 8000 ms fixed, the per-address
111
- * limit — not libp2p's own 10 s dial timeout — was the first thing to cut a relayed dial off,
112
- * from about 1000 ms of one-way link delay upward. Nothing said so, and a reader raising
113
- * `DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS` below would not have found it.
114
- *
115
- * NOTE: a `/p2p-circuit/webrtc` address also negotiates a WebRTC session after
116
- * the relay leg. If such dials are ever seen failing at exactly this limit, raise
117
- * the declared link round trip (or `network.controlCohort.perAddressDialTimeoutMs` on the
118
- * affected nodes) rather than the per-peer limit, which cannot help an address that is itself
119
- * cut off.
120
- *
121
- * Override per node with `network.controlCohort.perAddressDialTimeoutMs`.
122
- */
123
- export const DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS = relayedDialBudgetMs();
124
-
125
- /**
126
- * How many whole per-address dial attempts {@link DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS}
127
- * budgets for: the address that works plus the three dead ones a lent cadre-host node is
128
- * observed to report ahead of it (loopback and LAN WebSocket addresses, plus virtual adapters).
129
- */
130
- export const CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS = 4;
131
-
132
- /**
133
- * Default limit on dialing ONE peer — every candidate address together — in ms.
134
- *
135
- * Without it, an offline peer costs (address count × up to
136
- * {@link DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS}), a number that
137
- * depends on how many addresses the peer happens to report. Callers dial peers
138
- * one after another (the control-cohort reconcile pass dials each sibling in
139
- * turn), so that cost also delays every later peer. With the limit, a reconcile
140
- * pass costs at most (dialed siblings) × this.
141
- *
142
- * Sized to fit a typical list with dead addresses ahead of the one that works:
143
- * a lent cadre-host node reports two to four addresses a phone can dial
144
- * (loopback and LAN WebSocket addresses, plus any virtual adapters). So it is
145
- * {@link CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS} whole per-address budgets — three silently
146
- * dropped addresses, then the one that works, each getting the FULL per-address limit. A peer
147
- * whose working address sits behind four or more dropped ones does not fit, and fails each pass
148
- * the same way; if that shows up, the remedy is ordering (try the address that last connected
149
- * first), not a larger number here.
150
- *
151
- * Counted as whole per-address budgets rather than the flat 30_000 it was before, because the
152
- * old number left only 6 s after three dropped addresses — enough for the 1.6 s direct dial the
153
- * phone measured, but NOT for the relayed dial the per-address limit is sized to cover. A peer
154
- * whose only working address was a relayed one behind two dead ones therefore could not be
155
- * dialled at all, and the arithmetic in this comment was what said otherwise.
156
- *
157
- * Override per node with `network.controlCohort.dialTimeoutMs` — tests that
158
- * drive dead addresses on purpose set it low so a pass's duration is a chosen
159
- * number rather than a transitive libp2p default stretched by machine load.
160
- */
161
- export const DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS =
162
- CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS * DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS;
163
-
164
- /** Time limits for dialing one peer from a list of candidate addresses. */
165
- export interface PeerDialBudget {
166
- /** Limit on one address's attempt, in ms. */
167
- perAddressMs: number;
168
- /** Limit on the whole peer — every address together — in ms. */
169
- totalMs: number;
170
- }
171
-
172
- /** {@link PeerDialBudget} built from the two defaults above. */
173
- export const DEFAULT_PEER_DIAL_BUDGET: Readonly<PeerDialBudget> = {
174
- perAddressMs: DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS,
175
- totalMs: DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS,
176
- };
177
-
178
- /** What {@link dialAddr} reads of a connection the node holds, to decide whether to hand it back instead of dialing. */
179
- export interface ReusableConnection {
180
- remotePeer: { toString(): string };
181
- status?: Connection['status'];
182
- limits?: Connection['limits'];
183
- /** Whether the connection is direct rather than relayed; absent counts as direct. */
184
- direct?: boolean;
185
- }
186
-
187
- /** The slice of a libp2p node {@link dialPeerAddrs} uses. */
188
- export interface AddrDialer {
189
- /** This node's id, to recognise an address that relays through this node ({@link relaysThrough}). */
190
- readonly peerId: PeerId;
191
- /** libp2p's lifecycle state: {@link dialAddr} refuses to start an attempt once it is not `started`. */
192
- readonly status?: Libp2pStatus;
193
- /**
194
- * The connections this node holds to `peerId`. {@link dialAddr} returns an open one without relay
195
- * limits rather than opening a second — what libp2p's dial queue did (`findExistingConnection`)
196
- * and the transport manager does not. Optional so a double need not provide it, and typed by
197
- * what is read of each connection so the strand redial's node slice (bare `remotePeer`s, which
198
- * never count as open) satisfies it without a cast.
199
- */
200
- getConnections?(peerId?: PeerId): ReadonlyArray<ReusableConnection>;
201
- dial(addr: Multiaddr, options: { signal: AbortSignal }): Promise<Connection>;
202
- }
203
-
204
- /**
205
- * The libp2p internals a queue-free dial reaches — real fields on libp2p's node class, absent
206
- * from the `Libp2p` interface (the seam `relay-reservation.ts` already uses).
207
- */
208
- interface DialComponentsLike {
209
- components?: {
210
- transportManager?: { dial?: (addr: Multiaddr, options: { signal: AbortSignal }) => Promise<Connection> };
211
- connectionGater?: ConnectionGater;
212
- };
213
- }
214
-
215
- /**
216
- * libp2p's `stop` event, which ends an attempt the dial queue would otherwise have aborted at
217
- * shutdown. Structural so an {@link AddrDialer} double need not provide it.
218
- */
219
- interface StopEventsLike {
220
- addEventListener?: (type: 'stop', listener: () => void) => void;
221
- removeEventListener?: (type: 'stop', listener: () => void) => void;
222
- }
223
-
224
- /**
225
- * Dial ONE address outside libp2p's dial queue. The queue joins any new dial to a queued job
226
- * for the same peer id, whatever address the new dial names, and a joined job ends only when
227
- * every caller has aborted — so while another caller dials this peer (FRET's membership probe,
228
- * an Optimystic cluster client), a per-address attempt through the queue waits on whatever
229
- * address that job is on instead of its own. The transport manager dials exactly the address
230
- * given; the two gater hooks the queue would have consulted are run here, and the upgrader
231
- * still runs `denyOutboundConnection` and verifies the peer id the address carries during the
232
- * Noise handshake, so the address must carry the id of the peer expected to answer
233
- * ({@link withTrailingPeerId}). An open connection to that peer without relay limits is handed
234
- * back instead of dialing ({@link reusableConnection}), as the queue would have. A relayed
235
- * address still passes through the queue for its relay leg (the circuit transport dials the
236
- * relay by peer id).
237
- *
238
- * The queue would also have aborted the attempt at shutdown; here the node's `status` is
239
- * checked before dialing and its `stop` event aborts an attempt in flight. Without
240
- * `transportManager.dial` (libp2p internals moved) the attempt goes through the queue, logged.
241
- *
242
- * What else the queue did that this does not: record the outcome in the peer store
243
- * (`LAST_DIAL_SUCCESS_KEY` / `LAST_DIAL_FAILURE_KEY`, read only by libp2p's own address sorter,
244
- * which these dials do not use); apply `maxParallelDials` and `maxDialQueueLength`; and refuse
245
- * a dial of this node's own id before touching the network — the upgrader still throws
246
- * `Can not dial self` after the handshake, `dialPeerAddrs` drops addresses relaying through this
247
- * node, `applySeed` skips itself, and the reconcile pass never lists itself.
248
- */
249
- export async function dialAddr(dialer: AddrDialer, addr: Multiaddr, signal: AbortSignal, label: string): Promise<Connection> {
250
- if (dialer.status !== undefined && dialer.status !== 'started') {
251
- throw new Error(`${label}: not dialed, the node is ${dialer.status}`);
252
- }
253
- const components = (dialer as AddrDialer & DialComponentsLike).components;
254
- const manager = components?.transportManager;
255
- if (typeof manager?.dial !== 'function') {
256
- log('%s: no transportManager.dial on this node — libp2p internals moved? dialing through the queue', label);
257
- return dialer.dial(addr, { signal });
258
- }
259
- const target = boundPeer(addr, label);
260
- const open = reusableConnection(dialer, target, addr);
261
- if (open !== undefined) {
262
- log('%s: reusing the open connection to %s', label, target);
263
- return open;
264
- }
265
- const attempt = attemptSignal(dialer, signal, label);
266
- try {
267
- await assertDialAllowed(components?.connectionGater, target, addr, label);
268
- if (attempt.signal.aborted) {
269
- throw attempt.signal.reason;
270
- }
271
- // NOTE: a relayed address's relay leg still goes through the dial queue (the circuit
272
- // transport dials the relay by peer id), so another dial of the relay can join it. Fine
273
- // while a relay connection is normally already open for the reservation; revisit if a
274
- // relayed attempt is ever seen timing out while a dial of the relay by id is in flight.
275
- return await manager.dial(addr, { signal: attempt.signal });
276
- } catch (err) {
277
- // A transport reports an aborted connect as its own failure ("Could not connect to …");
278
- // why it was aborted — the deadline, or the stop — is the error worth surfacing.
279
- throw attempt.signal.aborted ? attempt.signal.reason : err;
280
- } finally {
281
- attempt.release();
282
- }
283
- }
284
-
285
- /**
286
- * The signal one attempt dials under: aborted when the caller's `signal` aborts, with its
287
- * reason, or when the node stops. Linked before anything in the attempt awaits (the gater
288
- * hooks are async), so neither event can fall between the check and the dial; a `signal`
289
- * already aborted on entry aborts it at once, since no `abort` event will come. `release`
290
- * unhooks both listeners.
291
- */
292
- function attemptSignal(dialer: AddrDialer, signal: AbortSignal, label: string): { signal: AbortSignal; release(): void } {
293
- const events = dialer as AddrDialer & StopEventsLike;
294
- const controller = new AbortController();
295
- const onAbort = (): void => controller.abort(signal.reason);
296
- const onStop = (): void => controller.abort(new Error(`${label}: the node stopped`));
297
- signal.addEventListener('abort', onAbort, { once: true });
298
- events.addEventListener?.('stop', onStop);
299
- if (signal.aborted) {
300
- onAbort();
301
- }
302
- return {
303
- signal: controller.signal,
304
- release: () => {
305
- signal.removeEventListener('abort', onAbort);
306
- events.removeEventListener?.('stop', onStop);
307
- },
308
- };
309
- }
310
-
311
- /**
312
- * The peer `addr` is bound to, or `undefined` when it names none. Throws, naming the address,
313
- * when the id it carries does not parse: the upgrader would reject the same address after
314
- * connecting, so failing before the network costs nothing and says why.
315
- */
316
- function boundPeer(addr: Multiaddr, label: string): PeerId | undefined {
317
- const id = trailingPeerId(addr);
318
- if (id === null) {
319
- return undefined;
320
- }
321
- try {
322
- return peerIdFromString(id);
323
- } catch (err) {
324
- throw new Error(`${label}: ${addr.toString()} does not end in a peer id that parses`, { cause: err });
325
- }
326
- }
327
-
328
- /**
329
- * An open connection to `target` without relay limits, when the node holds one — the rule
330
- * libp2p's dial queue applied before dialing (`findExistingConnection`): a direct connection is
331
- * preferred, and a relayed one is not reused for a direct address, so the dial can upgrade the
332
- * link. `undefined` when the node holds none, or does not expose its connections.
333
- *
334
- * Returned as the `Connection` it is on a real node. A double that reports an open connection
335
- * must supply what its caller uses of one.
336
- */
337
- function reusableConnection(dialer: AddrDialer, target: PeerId | undefined, addr: Multiaddr): Connection | undefined {
338
- if (target === undefined || dialer.getConnections === undefined) {
339
- return undefined;
340
- }
341
- const expected = target.toString();
342
- const open = dialer.getConnections(target)
343
- .filter((c) => c.status === 'open' && c.limits === undefined && c.remotePeer.toString() === expected);
344
- const existing = open.find((c) => c.direct !== false) ?? open[0];
345
- if (existing === undefined || (existing.direct === false && !isRelayed(addr))) {
346
- return undefined;
347
- }
348
- return existing as Connection;
349
- }
350
-
351
- async function assertDialAllowed(gater: ConnectionGater | undefined, target: PeerId | undefined, addr: Multiaddr, label: string): Promise<void> {
352
- if (target !== undefined && await gater?.denyDialPeer?.(target)) {
353
- throw new Error(`${label}: the connection gater denies dialing ${target.toString()}`);
354
- }
355
- if (await gater?.denyDialMultiaddr?.(addr)) {
356
- throw new Error(`${label}: the connection gater denies dialing ${addr.toString()}`);
357
- }
358
- }
359
-
360
- /**
361
- * Thrown by {@link dialPeerAddrs} when it was given addresses but every one reaches the peer by
362
- * relaying through this node, so none was dialed.
363
- *
364
- * This is where a relay lands for a peer that holds a reservation on it (a phone, or any node that
365
- * cannot listen): the address that peer publishes is `/<relay transport>/p2p/<relay>/p2p-circuit/p2p/<peer>`,
366
- * and dialing it from the relay itself fails with libp2p's `Can not dial self`. Nothing this node
367
- * does can repair it; once the peer's connection drops, only the peer can reconnect. Callers log it
368
- * as that rather than as a dial failure.
369
- */
370
- export class SelfRelayOnlyError extends Error {
371
- constructor(label: string) {
372
- super(`${label}: every candidate address relays through this node; only the peer can reconnect`);
373
- this.name = 'SelfRelayOnlyError';
374
- }
375
- }
376
-
377
- /**
378
- * No connection to the peer formed, so nothing was sent to it. `cause` is what the dial threw:
379
- * {@link dialPeerAddrs}'s error naming every address and why it failed, or a
380
- * {@link SelfRelayOnlyError}.
381
- *
382
- * Kept apart from failures after a connection formed so a caller can tell "this device could not
383
- * reach the peer" from "the peer was reached and then something else failed" without reading
384
- * libp2p's error text. `SeedBootstrapService.deliverSeed` throws it, and so `CadreNode.claimNode`.
385
- */
386
- export class PeerUnreachableError extends Error {
387
- constructor(readonly peerId: string, cause: unknown) {
388
- super(`Could not reach ${peerId}: ${describeThrown(cause)}`, { cause });
389
- this.name = 'PeerUnreachableError';
390
- }
391
- }
392
-
393
- /** One candidate's outcome, kept so the thrown error can name every attempt. */
394
- interface AddrAttemptFailure {
395
- addr: Multiaddr;
396
- error: Error;
397
- }
398
-
399
- /**
400
- * Dial `peerId` from `addrs`, one address per {@link dialAddr} call, and return the
401
- * first connection that forms. Direct addresses are tried before relayed ones
402
- * ({@link directBeforeRelayed}); otherwise the given order is kept.
403
- *
404
- * Every address is first bound to `peerId` ({@link withTrailingPeerId}), so the
405
- * handshake verifies that the peer expected is the one that answered; an address
406
- * naming another peer is dropped and logged. When that leaves nothing of a
407
- * non-empty list — every address names someone else, or `peerId` does not parse —
408
- * this throws without dialing.
409
- *
410
- * Addresses that relay through this node are dropped next ({@link relaysThrough}):
411
- * dialing one could only fail with `Can not dial self`. When that leaves nothing,
412
- * this throws {@link SelfRelayOnlyError} without dialing.
413
- *
414
- * Addresses naming a transport this node lacks are not filtered out first: the
415
- * transport manager rejects those at once (`TransportUnavailableError`), so they
416
- * cost a log line, not time.
417
- *
418
- * Otherwise throws when no address connects — see {@link tryAddrsInTurn} for the error.
419
- *
420
- * @param peerId The peer every address must reach, as every caller already holds it
421
- * (a `CadrePeer` row key, a seed peer's id, a strand member's id).
422
- * @param label Names the dial in timeout messages and logs, e.g.
423
- * `reconcileControlCohort dial of sibling <peerId>`; each attempt reads
424
- * `<label> via <addr>`.
425
- */
426
- export async function dialPeerAddrs(
427
- dialer: AddrDialer,
428
- peerId: string,
429
- addrs: readonly Multiaddr[],
430
- budget: PeerDialBudget,
431
- label: string,
432
- ): Promise<Connection> {
433
- const bound = boundTo(peerId, addrs, label);
434
- if (addrs.length > 0 && bound.length === 0) {
435
- throw new Error(`${label}: none of the ${addrs.length} candidate addresses binds to ${peerId}`);
436
- }
437
- const dialable = withoutSelfRelayed(dialer, bound, label);
438
- if (bound.length > 0 && dialable.length === 0) {
439
- throw new SelfRelayOnlyError(label);
440
- }
441
- return tryAddrsInTurn(directBeforeRelayed(dialable), budget, label, (addr, signal) => dialAddr(dialer, addr, signal, label));
442
- }
443
-
444
- /**
445
- * `addrs` each bound to `peerId` ({@link withTrailingPeerId}). An address naming another peer
446
- * is dropped, as is every address when `peerId` cannot be encapsulated (it does not parse);
447
- * each drop is logged with its reason.
448
- */
449
- function boundTo(peerId: string, addrs: readonly Multiaddr[], label: string): Multiaddr[] {
450
- const bound: Multiaddr[] = [];
451
- for (const addr of addrs) {
452
- try {
453
- const withId = withTrailingPeerId(addr, peerId);
454
- if (withId === null) {
455
- log('%s: dropping %s — it names a peer other than %s', label, addr.toString(), peerId);
456
- } else {
457
- bound.push(withId);
458
- }
459
- } catch (err) {
460
- log('%s: cannot bind %s to %s: %o', label, addr.toString(), peerId, err);
461
- }
462
- }
463
- return bound;
464
- }
465
-
466
- /**
467
- * Run `attempt` against each address in the given order until one succeeds, and
468
- * return its result.
469
- *
470
- * Each attempt is limited to `budget.perAddressMs`, or to whatever remains of
471
- * `budget.totalMs` when that is less. The attempt's signal is aborted when its
472
- * limit passes, so a dial in progress is cancelled rather than left running.
473
- * Addresses the total leaves no time for are reported as not tried.
474
- *
475
- * Throws when every address fails. With one address the error is that attempt's
476
- * own, unchanged. With several it is one error naming each address and why it
477
- * failed, in order, with the first failure as `cause` — so the report shows the
478
- * address that mattered, not only whichever happened to be tried last.
479
- *
480
- * Between attempts this waits for one macrotask (`setTimeout(0)`). A direct
481
- * address is dialed outside libp2p's dial queue ({@link dialAddr}), but a relayed
482
- * address still passes through it for the relay leg, and the queue lets a new
483
- * dial join any queued job for the same peer id WITHOUT checking whether that
484
- * job has already finished: an aborted job leaves the queue a few microtasks
485
- * after its callers are rejected, so a next attempt through the same relay made
486
- * at once would join the dying job and be rejected with `AbortError` before it
487
- * touches the network. All of the queue's cleanup runs as microtasks, so it has
488
- * finished by the time a macrotask runs. Seen against libp2p 3.1.3, and the
489
- * queue's join is unchanged in 3.3.11; `test/peer-dial.spec.ts` dials real nodes
490
- * so an upgrade that changes it shows up there.
491
- */
492
- export async function tryAddrsInTurn<T>(
493
- addrs: readonly Multiaddr[],
494
- budget: PeerDialBudget,
495
- label: string,
496
- attempt: (addr: Multiaddr, signal: AbortSignal, attemptMs: number) => Promise<T>,
497
- ): Promise<T> {
498
- const deadline = Date.now() + budget.totalMs;
499
- const failures: AddrAttemptFailure[] = [];
500
- for (const addr of addrs) {
501
- const remaining = deadline - Date.now();
502
- if (remaining <= 0) {
503
- failures.push({ addr, error: new Error(`not tried — the ${budget.totalMs}ms budget for ${label} was spent on earlier addresses`) });
504
- continue;
505
- }
506
- if (failures.length > 0) {
507
- await nextMacrotask();
508
- }
509
- const attemptMs = Math.min(budget.perAddressMs, remaining);
510
- try {
511
- return await withDeadline(attemptMs, `${label} via ${addr.toString()}`, (signal) => attempt(addr, signal, attemptMs));
512
- } catch (err) {
513
- const error = toError(err);
514
- failures.push({ addr, error });
515
- log('%s via %s failed: %o', label, addr.toString(), error);
516
- }
517
- }
518
- throw allAttemptsFailed(label, failures);
519
- }
520
-
521
- /**
522
- * `addrs` with every circuit-relay address (one containing `/p2p-circuit`) moved
523
- * after every direct one, each group keeping its given order.
524
- *
525
- * The one part of libp2p's own ordering worth keeping: a relayed connection is
526
- * slower and limited in how much data and time it may carry, so a direct
527
- * address is always worth trying first. libp2p's other rules are deliberately
528
- * dropped — it puts loopback addresses last and public ones before private ones,
529
- * which is how a forwarded loopback address ended up behind addresses that
530
- * never answer. With a per-address limit, trying a dead address first costs a
531
- * bounded amount of time, so the caller's order is the better guide.
532
- */
533
- export function directBeforeRelayed(addrs: readonly Multiaddr[]): Multiaddr[] {
534
- return [...addrs.filter((addr) => !isRelayed(addr)), ...addrs.filter(isRelayed)];
535
- }
536
-
537
- /** Whether `addr` reaches its target through a circuit relay. */
538
- function isRelayed(addr: Multiaddr): boolean {
539
- return addr.getComponents().some((c) => c.name === 'p2p-circuit');
540
- }
541
-
542
- /** `addrs` without those that relay through `dialer` itself, each dropped one logged. */
543
- function withoutSelfRelayed(dialer: AddrDialer, addrs: readonly Multiaddr[], label: string): Multiaddr[] {
544
- return addrs.filter((addr) => {
545
- if (!relaysThrough(addr, dialer.peerId)) {
546
- return true;
547
- }
548
- log('%s: skipping %s — it relays through this node', label, addr.toString());
549
- return false;
550
- });
551
- }
552
-
553
- /**
554
- * Whether `addr` reaches its target by relaying through `relay` at any hop.
555
- *
556
- * A circuit address names its relay in the `p2p` component immediately before
557
- * the `p2p-circuit` marker (`/<transport>/p2p/<relay>/p2p-circuit/p2p/<target>`),
558
- * so the components are walked rather than the text searched: the target's id
559
- * after the marker, a bare `/p2p-circuit` naming no relay, and a multi-hop chain
560
- * each read correctly that way. Same rule as db-p2p's `routesThroughRelay`, which
561
- * its package does not export.
562
- */
563
- function relaysThrough(addr: Multiaddr, relay: PeerId): boolean {
564
- const components = addr.getComponents();
565
- return components.some((component, i) => component.name === 'p2p-circuit' && namesPeer(components[i - 1], relay));
566
- }
567
-
568
- /**
569
- * Whether `component` is a `p2p` component naming `peer`. Compared as canonical
570
- * strings because a multiaddr keeps a peer id in whichever form it was written
571
- * (base58 or CIDv1). `PeerId.equals` is avoided because test doubles supply the
572
- * dialer's `peerId` with `toString` only.
573
- */
574
- function namesPeer(component: Component | undefined, peer: PeerId): boolean {
575
- if (component?.name !== 'p2p' || component.value === undefined) {
576
- return false;
577
- }
578
- const expected = peer.toString();
579
- try {
580
- return peerIdFromString(component.value).toString() === expected;
581
- } catch (err) {
582
- log('cannot read %s as a peer id; treating it as not this node: %o', component.value, err);
583
- return false;
584
- }
585
- }
586
-
587
- function allAttemptsFailed(label: string, failures: AddrAttemptFailure[]): Error {
588
- if (failures.length === 0) {
589
- return new Error(`${label}: no candidate addresses`);
590
- }
591
- if (failures.length === 1) {
592
- return failures[0].error;
593
- }
594
- const detail = failures.map((f) => `${f.addr.toString()} — ${f.error.message}`).join('; ');
595
- return new Error(`${label} failed for all ${failures.length} candidate addresses: ${detail}`, { cause: failures[0].error });
596
- }
597
-
598
- /**
599
- * Yield one macrotask: libp2p's dial queue drops an aborted job only on the next turn, so a
600
- * dialer that moves on to another address after an abort waits this long first. Shared with
601
- * the cadre invitation dialer (`cadre-invite-protocol.ts`).
602
- */
603
- export function nextMacrotask(): Promise<void> {
604
- return new Promise((resolve) => setTimeout(resolve, 0));
605
- }
1
+ /**
2
+ * Dialing one peer from a list of candidate addresses, so that an address that
3
+ * never answers cannot use up the time the others needed.
4
+ *
5
+ * libp2p's own multi-address dial (`libp2p.dial(addrs)`, `DialQueue.dialPeer`)
6
+ * tries the addresses ONE AT A TIME under ONE signal. Its only per-address limit
7
+ * is the connection manager's `addressDialTimeout` (libp2p 3.3+), which cadre
8
+ * sizes for a cold relayed open through two admission decisions
9
+ * (`optimysticDialLimits` in `link-budget.ts`: 39 s at the default declared
10
+ * link). An address whose connection attempt is silently dropped — a firewall, a
11
+ * subnet the dialer cannot route to, a virtual adapter's address a Windows host
12
+ * reports alongside its real ones — holds that dial for that long or until the
13
+ * whole signal expires, and the addresses sorted after it get what is left. It
14
+ * also sorts the list itself (`defaultAddressSorter`), putting loopback addresses
15
+ * last, behind exactly the LAN addresses most likely to be dropped. A phone
16
+ * borrowing a node from a cadre-host whose only reachable address was the
17
+ * forwarded loopback one never connected for this reason.
18
+ *
19
+ * So the addresses are dialed here, each as its own transport-manager dial
20
+ * ({@link dialAddr}) with its own time limit ({@link PeerDialBudget.perAddressMs}),
21
+ * inside a limit for the whole peer ({@link PeerDialBudget.totalMs}). One address
22
+ * per call also means libp2p's sorter has nothing to reorder, so the order is
23
+ * chosen here ({@link directBeforeRelayed}). The dial goes around libp2p's dial
24
+ * queue because the queue joins any dial of a peer to a queued job for that peer
25
+ * id, whatever address the new dial names — see {@link dialAddr}. Every address
26
+ * is bound to the peer the caller expects ({@link withTrailingPeerId}) so the
27
+ * handshake verifies who answered.
28
+ *
29
+ * Dependency-free apart from `control-stream.ts` and `link-budget.ts`, so any
30
+ * module may import it without creating an import cycle. That is why the two
31
+ * address helpers ({@link trailingPeerId}, {@link withTrailingPeerId}) live here
32
+ * rather than in `peer-record.ts`, which pulls in the crypto plugin.
33
+ */
34
+
35
+ import debug from 'debug';
36
+ import type { Connection, ConnectionGater, Libp2pStatus, PeerId } from '@libp2p/interface';
37
+ import { peerIdFromString } from '@libp2p/peer-id';
38
+ import type { Component, Multiaddr } from '@multiformats/multiaddr';
39
+ import { withDeadline } from './control-stream.js';
40
+ import { relayedDialBudgetMs } from './link-budget.js';
41
+ import { describeThrown, toError } from './describe-thrown.js';
42
+
43
+ const log = debug('sereus:cadre:peer-dial');
44
+
45
+ /**
46
+ * The peer id a multiaddr terminates in, or `null` when it names none.
47
+ *
48
+ * The LAST `/p2p/` component is the dial target: a circuit address
49
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
50
+ * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
51
+ * cannot express that distinction.
52
+ */
53
+ export function trailingPeerId(addr: Multiaddr): string | null {
54
+ const p2p = addr.getComponents().filter((c) => c.name === 'p2p');
55
+ return p2p.length > 0 ? (p2p[p2p.length - 1].value ?? null) : null;
56
+ }
57
+
58
+ /**
59
+ * `addr` guaranteed to terminate in `/p2p/<peerId>` — the shape every dial needs,
60
+ * since the upgrader verifies that id during the handshake — or `null` when it
61
+ * cannot, because the address already terminates in a DIFFERENT peer id and
62
+ * therefore does not reach `peerId` at all.
63
+ *
64
+ * Three input shapes, matching what a `CadrePeer` record can legitimately carry:
65
+ *
66
+ * - no `/p2p/` component (`/ip4/1.2.3.4/tcp/4001`) — the suffix is appended;
67
+ * - a relay hop with the destination missing (`…/p2p/<relay>/p2p-circuit`) — the
68
+ * last component is the circuit, not a peer id, so the suffix is appended and
69
+ * the address becomes the full `…/p2p/<relay>/p2p-circuit/p2p/<peerId>`;
70
+ * - already terminating in `/p2p/<X>` — returned untouched when `X` is `peerId`,
71
+ * dropped otherwise.
72
+ *
73
+ * This is deliberately the same rule libp2p applies internally in
74
+ * `calculateMultiaddrs` (append when the LAST component is not `p2p`) followed by
75
+ * its wrong-peer-id filter, so a normalized list matches what libp2p would have
76
+ * built anyway. Normalizing before a list dial is what keeps a list from mixing
77
+ * suffixed and unsuffixed entries, which `getPeerAddress` rejects outright
78
+ * ("Multiaddrs must all have the same peer id or have no peer id") — taking the
79
+ * whole peer down with it, not just the odd address.
80
+ *
81
+ * Throws when `peerId` does not parse as a peer id (the encapsulation validates
82
+ * it). Never use before signature verification: verification runs against the
83
+ * original on-record strings.
84
+ */
85
+ export function withTrailingPeerId(addr: Multiaddr, peerId: string): Multiaddr | null {
86
+ const components = addr.getComponents();
87
+ if (components[components.length - 1]?.name !== 'p2p') {
88
+ return addr.encapsulate(`/p2p/${peerId}`);
89
+ }
90
+ return trailingPeerId(addr) === peerId ? addr : null;
91
+ }
92
+
93
+ /**
94
+ * How an address reaches its peer. One classification, used by everything that has to treat
95
+ * the three differently: the dial order ({@link directBeforeRelayed}), what an open connection
96
+ * can stand in for ({@link reusableConnection}), and which addresses formation hands libp2p
97
+ * (`strand-formation-protocol.ts`).
98
+ *
99
+ * - `direct` — no relay hop. `/webrtc-direct` belongs here: it is dialed without a relay and
100
+ * needs no fallback.
101
+ * - `relayed` — a relay hop and nothing negotiated after it. The address a reservation
102
+ * publishes, and the one a dial someone is waiting on uses: it connects or fails quickly.
103
+ * - `webrtc` — a relay hop carrying WebRTC signalling, with the connection itself opening only
104
+ * if ICE (WebRTC's connectivity check) finds a path between the two networks. Sereus runs no
105
+ * TURN server, so between two networks that allow no direct path ICE never connects and the
106
+ * attempt runs to the WebRTC transport's own timeout, measured at about 23 s
107
+ * (gotchoices/sereus#61) — longer than any budget something waits on. Hence the policy in
108
+ * `docs/network/relay.md` → "Direct connections over WebRTC": a blocking dial goes relayed,
109
+ * and WebRTC is an extra tried separately.
110
+ */
111
+ export type AddrKind = 'direct' | 'relayed' | 'webrtc';
112
+
113
+ /**
114
+ * The {@link AddrKind} of `addr`: `webrtc` when a `webrtc` component follows the last relay
115
+ * hop, `relayed` when a relay hop has nothing after it, `direct` when there is no relay hop.
116
+ *
117
+ * The components are walked rather than asking `@multiformats/multiaddr-matcher`'s `Circuit` /
118
+ * `WebRTC` (what libp2p's own sorter and `isDirect` use), because those are transport-SHAPE
119
+ * matchers: they recognise a circuit only when its relay leg is a transport they know and only
120
+ * for a single hop. Measured against 3.0.2, a relay leg over `/memory` and a two-hop circuit
121
+ * each match neither `Circuit` nor `WebRTC`, which would classify a relayed address as
122
+ * `direct` and put it ahead of the addresses most likely to work. The question here is
123
+ * structural — does reaching this peer need a relay hop, and does it need ICE after that hop —
124
+ * so it is answered from the components, as {@link relaysThrough} already does.
125
+ *
126
+ * NOTE: `webrtc` is the only transport cadre negotiates after a relay hop. Another one
127
+ * (`/p2p-circuit/webtransport`, say) would come back `relayed` and could then hold a blocking
128
+ * dial; add it here if one is ever configured.
129
+ */
130
+ export function addrKind(addr: Multiaddr): AddrKind {
131
+ return addrKindOfComponents(addr.getComponents());
132
+ }
133
+
134
+ /**
135
+ * {@link addrKind} for a caller that holds the components already, so the one rule above is
136
+ * answered in one place rather than re-derived from a second `p2p-circuit` test. Taken by
137
+ * `node-claim-payload.ts`, which parses an address once and asks several questions of the same
138
+ * components, and by `peer-record.ts`, which parses a stored string to ask this one.
139
+ */
140
+ export function addrKindOfComponents(components: readonly Component[]): AddrKind {
141
+ let lastCircuit = -1;
142
+ for (let i = 0; i < components.length; i++) {
143
+ if (components[i].name === 'p2p-circuit') lastCircuit = i;
144
+ }
145
+ if (lastCircuit < 0) {
146
+ return 'direct';
147
+ }
148
+ return components.slice(lastCircuit + 1).some((c) => c.name === 'webrtc') ? 'webrtc' : 'relayed';
149
+ }
150
+
151
+ /**
152
+ * Default limit on ONE address's dial attempt, in ms, at the DEFAULT declared link round trip:
153
+ * `RELAYED_DIAL_ROUND_TRIPS` (5) x `DECLARED_LINK_ROUND_TRIP_MS` (3500 ms) plus
154
+ * `DIAL_ADMISSION_DECISIONS` (2) x `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms) = 21 500 ms
155
+ * (`relayedDialBudgetMs`). It was a fixed 8000 ms before it was derived.
156
+ *
157
+ * It has to cover the slowest address that should succeed, because an attempt
158
+ * that needs longer fails the same way on every retry. That is a relayed dial on
159
+ * a mobile link: connect to the relay (transport, encryption and multiplexer
160
+ * handshakes, when no relay connection is open yet), open the circuit, then run
161
+ * both handshakes again end to end through the relay. `link-budget.ts` is where that
162
+ * reasoning is now a measured count instead of an estimate — five link round trips, measured at
163
+ * 15 113 ms on a link whose round trip is 3 s — so the value MOVES with a host's
164
+ * `NetworkConfig.linkRoundTripMs` rather than pinning the band this node can reach to whatever
165
+ * number was typed here. A direct dial that works is far quicker — a phone's WebSocket dial to
166
+ * a node forwarded over `adb reverse` measured 1.6 s end to end.
167
+ *
168
+ * Deriving it rather than leaving it fixed is deliberate: at 8000 ms fixed, the per-address
169
+ * limit — not libp2p's own 10 s dial timeout — was the first thing to cut a relayed dial off,
170
+ * from about 1000 ms of one-way link delay upward. Nothing said so, and a reader raising
171
+ * `DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS` below would not have found it.
172
+ *
173
+ * It is NOT sized for a `/p2p-circuit/webrtc` address, which negotiates a WebRTC session after
174
+ * the relay leg and, where ICE cannot connect, answers nothing until the WebRTC transport gives
175
+ * up (about 23 s). Such an address is dialed last ({@link directBeforeRelayed}), so it is cut
176
+ * off here having cost the peer's working addresses nothing. Raising this limit to let an
177
+ * ICE-failing dial run to its own end would only make an address nothing is waiting for
178
+ * expensive.
179
+ *
180
+ * Override per node with `network.controlCohort.perAddressDialTimeoutMs`.
181
+ */
182
+ export const DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS = relayedDialBudgetMs();
183
+
184
+ /**
185
+ * How many whole per-address dial attempts {@link DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS}
186
+ * budgets for: the address that works plus the three dead ones a lent cadre-host node is
187
+ * observed to report ahead of it (loopback and LAN WebSocket addresses, plus virtual adapters).
188
+ */
189
+ export const CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS = 4;
190
+
191
+ /**
192
+ * Default limit on dialing ONE peer — every candidate address together — in ms.
193
+ *
194
+ * Without it, an offline peer costs (address count × up to
195
+ * {@link DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS}), a number that
196
+ * depends on how many addresses the peer happens to report. Callers dial peers
197
+ * one after another (the control-cohort reconcile pass dials each sibling in
198
+ * turn), so that cost also delays every later peer. With the limit, a reconcile
199
+ * pass costs at most (dialed siblings) × this.
200
+ *
201
+ * Sized to fit a typical list with dead addresses ahead of the one that works:
202
+ * a lent cadre-host node reports two to four addresses a phone can dial
203
+ * (loopback and LAN WebSocket addresses, plus any virtual adapters). So it is
204
+ * {@link CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS} whole per-address budgets — three silently
205
+ * dropped addresses, then the one that works, each getting the FULL per-address limit. A peer
206
+ * whose working address sits behind four or more dropped ones does not fit, and fails each pass
207
+ * the same way; if that shows up, the remedy is ordering (try the address that last connected
208
+ * first), not a larger number here.
209
+ *
210
+ * Counted as whole per-address budgets rather than the flat 30_000 it was before, because the
211
+ * old number left only 6 s after three dropped addresses — enough for the 1.6 s direct dial the
212
+ * phone measured, but NOT for the relayed dial the per-address limit is sized to cover. A peer
213
+ * whose only working address was a relayed one behind two dead ones therefore could not be
214
+ * dialled at all, and the arithmetic in this comment was what said otherwise.
215
+ *
216
+ * Override per node with `network.controlCohort.dialTimeoutMs` — tests that
217
+ * drive dead addresses on purpose set it low so a pass's duration is a chosen
218
+ * number rather than a transitive libp2p default stretched by machine load.
219
+ */
220
+ export const DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS =
221
+ CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS * DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS;
222
+
223
+ /** Time limits for dialing one peer from a list of candidate addresses. */
224
+ export interface PeerDialBudget {
225
+ /** Limit on one address's attempt, in ms. */
226
+ perAddressMs: number;
227
+ /** Limit on the whole peer — every address together — in ms. */
228
+ totalMs: number;
229
+ }
230
+
231
+ /** {@link PeerDialBudget} built from the two defaults above. */
232
+ export const DEFAULT_PEER_DIAL_BUDGET: Readonly<PeerDialBudget> = {
233
+ perAddressMs: DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS,
234
+ totalMs: DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS,
235
+ };
236
+
237
+ /** What {@link dialAddr} reads of a connection the node holds, to decide whether to hand it back instead of dialing. */
238
+ export interface ReusableConnection {
239
+ remotePeer: { toString(): string };
240
+ status?: Connection['status'];
241
+ limits?: Connection['limits'];
242
+ /** Whether the connection is direct rather than relayed; absent counts as direct. */
243
+ direct?: boolean;
244
+ }
245
+
246
+ /** The slice of a libp2p node {@link dialPeerAddrs} uses. */
247
+ export interface AddrDialer {
248
+ /** This node's id, to recognise an address that relays through this node ({@link relaysThrough}). */
249
+ readonly peerId: PeerId;
250
+ /** libp2p's lifecycle state: {@link dialAddr} refuses to start an attempt once it is not `started`. */
251
+ readonly status?: Libp2pStatus;
252
+ /**
253
+ * The connections this node holds to `peerId`. {@link dialAddr} returns an open one without relay
254
+ * limits rather than opening a second — what libp2p's dial queue did (`findExistingConnection`)
255
+ * and the transport manager does not. Optional so a double need not provide it, and typed by
256
+ * what is read of each connection so the strand redial's node slice (bare `remotePeer`s, which
257
+ * never count as open) satisfies it without a cast.
258
+ */
259
+ getConnections?(peerId?: PeerId): ReadonlyArray<ReusableConnection>;
260
+ dial(addr: Multiaddr, options: { signal: AbortSignal }): Promise<Connection>;
261
+ }
262
+
263
+ /**
264
+ * The libp2p internals a queue-free dial reaches — real fields on libp2p's node class, absent
265
+ * from the `Libp2p` interface (the seam `relay-reservation.ts` already uses).
266
+ */
267
+ interface DialComponentsLike {
268
+ components?: {
269
+ transportManager?: { dial?: (addr: Multiaddr, options: { signal: AbortSignal }) => Promise<Connection> };
270
+ connectionGater?: ConnectionGater;
271
+ };
272
+ }
273
+
274
+ /**
275
+ * libp2p's `stop` event, which ends an attempt the dial queue would otherwise have aborted at
276
+ * shutdown. Structural so an {@link AddrDialer} double need not provide it.
277
+ */
278
+ interface StopEventsLike {
279
+ addEventListener?: (type: 'stop', listener: () => void) => void;
280
+ removeEventListener?: (type: 'stop', listener: () => void) => void;
281
+ }
282
+
283
+ /**
284
+ * Dial ONE address outside libp2p's dial queue. The queue joins any new dial to a queued job
285
+ * for the same peer id, whatever address the new dial names, and a joined job ends only when
286
+ * every caller has aborted — so while another caller dials this peer (FRET's membership probe,
287
+ * an Optimystic cluster client), a per-address attempt through the queue waits on whatever
288
+ * address that job is on instead of its own. The transport manager dials exactly the address
289
+ * given; the two gater hooks the queue would have consulted are run here, and the upgrader
290
+ * still runs `denyOutboundConnection` and verifies the peer id the address carries during the
291
+ * Noise handshake, so the address must carry the id of the peer expected to answer
292
+ * ({@link withTrailingPeerId}). An open connection to that peer without relay limits is handed
293
+ * back instead of dialing ({@link reusableConnection}), as the queue would have. A relayed
294
+ * address still passes through the queue for its relay leg (the circuit transport dials the
295
+ * relay by peer id).
296
+ *
297
+ * The queue would also have aborted the attempt at shutdown; here the node's `status` is
298
+ * checked before dialing and its `stop` event aborts an attempt in flight. Without
299
+ * `transportManager.dial` (libp2p internals moved) the attempt goes through the queue, logged.
300
+ *
301
+ * What else the queue did that this does not: record the outcome in the peer store
302
+ * (`LAST_DIAL_SUCCESS_KEY` / `LAST_DIAL_FAILURE_KEY`, read only by libp2p's own address sorter,
303
+ * which these dials do not use); apply `maxParallelDials` and `maxDialQueueLength`; and refuse
304
+ * a dial of this node's own id before touching the network — the upgrader still throws
305
+ * `Can not dial self` after the handshake, `dialPeerAddrs` drops addresses relaying through this
306
+ * node, `applySeed` skips itself, and the reconcile pass never lists itself.
307
+ */
308
+ export async function dialAddr(dialer: AddrDialer, addr: Multiaddr, signal: AbortSignal, label: string): Promise<Connection> {
309
+ if (dialer.status !== undefined && dialer.status !== 'started') {
310
+ throw new Error(`${label}: not dialed, the node is ${dialer.status}`);
311
+ }
312
+ const components = (dialer as AddrDialer & DialComponentsLike).components;
313
+ const manager = components?.transportManager;
314
+ if (typeof manager?.dial !== 'function') {
315
+ log('%s: no transportManager.dial on this node — libp2p internals moved? dialing through the queue', label);
316
+ return dialer.dial(addr, { signal });
317
+ }
318
+ const target = boundPeer(addr, label);
319
+ const open = reusableConnection(dialer, target, addr);
320
+ if (open !== undefined) {
321
+ log('%s: reusing the open connection to %s', label, target);
322
+ return open;
323
+ }
324
+ const attempt = attemptSignal(dialer, signal, label);
325
+ try {
326
+ await assertDialAllowed(components?.connectionGater, target, addr, label);
327
+ if (attempt.signal.aborted) {
328
+ throw attempt.signal.reason;
329
+ }
330
+ // NOTE: a relayed address's relay leg still goes through the dial queue (the circuit
331
+ // transport dials the relay by peer id), so another dial of the relay can join it. Fine
332
+ // while a relay connection is normally already open for the reservation; revisit if a
333
+ // relayed attempt is ever seen timing out while a dial of the relay by id is in flight.
334
+ return await manager.dial(addr, { signal: attempt.signal });
335
+ } catch (err) {
336
+ // A transport reports an aborted connect as its own failure ("Could not connect to …");
337
+ // why it was aborted — the deadline, or the stop — is the error worth surfacing.
338
+ throw attempt.signal.aborted ? attempt.signal.reason : err;
339
+ } finally {
340
+ attempt.release();
341
+ }
342
+ }
343
+
344
+ /**
345
+ * The signal one attempt dials under: aborted when the caller's `signal` aborts, with its
346
+ * reason, or when the node stops. Linked before anything in the attempt awaits (the gater
347
+ * hooks are async), so neither event can fall between the check and the dial; a `signal`
348
+ * already aborted on entry aborts it at once, since no `abort` event will come. `release`
349
+ * unhooks both listeners.
350
+ */
351
+ function attemptSignal(dialer: AddrDialer, signal: AbortSignal, label: string): { signal: AbortSignal; release(): void } {
352
+ const events = dialer as AddrDialer & StopEventsLike;
353
+ const controller = new AbortController();
354
+ const onAbort = (): void => controller.abort(signal.reason);
355
+ const onStop = (): void => controller.abort(new Error(`${label}: the node stopped`));
356
+ signal.addEventListener('abort', onAbort, { once: true });
357
+ events.addEventListener?.('stop', onStop);
358
+ if (signal.aborted) {
359
+ onAbort();
360
+ }
361
+ return {
362
+ signal: controller.signal,
363
+ release: () => {
364
+ signal.removeEventListener('abort', onAbort);
365
+ events.removeEventListener?.('stop', onStop);
366
+ },
367
+ };
368
+ }
369
+
370
+ /**
371
+ * The peer `addr` is bound to, or `undefined` when it names none. Throws, naming the address,
372
+ * when the id it carries does not parse: the upgrader would reject the same address after
373
+ * connecting, so failing before the network costs nothing and says why.
374
+ */
375
+ function boundPeer(addr: Multiaddr, label: string): PeerId | undefined {
376
+ const id = trailingPeerId(addr);
377
+ if (id === null) {
378
+ return undefined;
379
+ }
380
+ try {
381
+ return peerIdFromString(id);
382
+ } catch (err) {
383
+ throw new Error(`${label}: ${addr.toString()} does not end in a peer id that parses`, { cause: err });
384
+ }
385
+ }
386
+
387
+ /**
388
+ * An open connection to `target` without relay limits, when the node holds one — the rule
389
+ * libp2p's dial queue applies before dialing (`findExistingConnection`, and `isDirect` in
390
+ * `libp2p/connection-manager/utils.ts`): a direct connection is preferred, and a relayed one
391
+ * is NOT handed back for an address that would not itself be relayed, so the dial can upgrade
392
+ * the link. `undefined` when the node holds none, or does not expose its connections.
393
+ *
394
+ * Only a `relayed` address ({@link AddrKind}) is served by an open relayed connection. A
395
+ * `webrtc` address is not, which is the same answer libp2p gives (its `isDirect` is
396
+ * `!Circuit.exactMatch`, and a `/p2p-circuit/webrtc` address is not an exact `Circuit` match) —
397
+ * without that, a WebRTC upgrade dial made over a live relayed connection would be handed that
398
+ * connection back and upgrade nothing. It matters only to such an upgrade dial: a blocking dial
399
+ * reaches a `webrtc` address only once every relayed one has been tried
400
+ * ({@link directBeforeRelayed}).
401
+ *
402
+ * NOTE: a WebRTC address is published beside the plain relayed address of the same relay, so a
403
+ * peer never offers one alone and a caller that wants any connection still gets the open relayed
404
+ * one for the relayed address. If a peer whose ONLY address is a WebRTC one ever appears, a dial
405
+ * of it will not reuse an open relayed connection and will pay the ICE timeout instead; hand the
406
+ * open connection back for a `webrtc` address too if that is seen.
407
+ *
408
+ * Returned as the `Connection` it is on a real node. A double that reports an open connection
409
+ * must supply what its caller uses of one.
410
+ */
411
+ function reusableConnection(dialer: AddrDialer, target: PeerId | undefined, addr: Multiaddr): Connection | undefined {
412
+ if (target === undefined || dialer.getConnections === undefined) {
413
+ return undefined;
414
+ }
415
+ const expected = target.toString();
416
+ const open = dialer.getConnections(target)
417
+ .filter((c) => c.status === 'open' && c.limits === undefined && c.remotePeer.toString() === expected);
418
+ const existing = open.find((c) => c.direct !== false) ?? open[0];
419
+ if (existing === undefined || (existing.direct === false && addrKind(addr) !== 'relayed')) {
420
+ return undefined;
421
+ }
422
+ return existing as Connection;
423
+ }
424
+
425
+ async function assertDialAllowed(gater: ConnectionGater | undefined, target: PeerId | undefined, addr: Multiaddr, label: string): Promise<void> {
426
+ if (target !== undefined && await gater?.denyDialPeer?.(target)) {
427
+ throw new Error(`${label}: the connection gater denies dialing ${target.toString()}`);
428
+ }
429
+ if (await gater?.denyDialMultiaddr?.(addr)) {
430
+ throw new Error(`${label}: the connection gater denies dialing ${addr.toString()}`);
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Thrown by {@link dialPeerAddrs} when it was given addresses but every one reaches the peer by
436
+ * relaying through this node, so none was dialed.
437
+ *
438
+ * This is where a relay lands for a peer that holds a reservation on it (a phone, or any node that
439
+ * cannot listen): the address that peer publishes is `/<relay transport>/p2p/<relay>/p2p-circuit/p2p/<peer>`,
440
+ * and dialing it from the relay itself fails with libp2p's `Can not dial self`. Nothing this node
441
+ * does can repair it; once the peer's connection drops, only the peer can reconnect. Callers log it
442
+ * as that rather than as a dial failure.
443
+ */
444
+ export class SelfRelayOnlyError extends Error {
445
+ constructor(label: string) {
446
+ super(`${label}: every candidate address relays through this node; only the peer can reconnect`);
447
+ this.name = 'SelfRelayOnlyError';
448
+ }
449
+ }
450
+
451
+ /**
452
+ * No connection to the peer formed, so nothing was sent to it. `cause` is what the dial threw:
453
+ * {@link dialPeerAddrs}'s error naming every address and why it failed, or a
454
+ * {@link SelfRelayOnlyError}.
455
+ *
456
+ * Kept apart from failures after a connection formed so a caller can tell "this device could not
457
+ * reach the peer" from "the peer was reached and then something else failed" without reading
458
+ * libp2p's error text. `SeedBootstrapService.deliverSeed` throws it, and so `CadreNode.claimNode`.
459
+ */
460
+ export class PeerUnreachableError extends Error {
461
+ constructor(readonly peerId: string, cause: unknown) {
462
+ super(`Could not reach ${peerId}: ${describeThrown(cause)}`, { cause });
463
+ this.name = 'PeerUnreachableError';
464
+ }
465
+ }
466
+
467
+ /** One candidate's outcome, kept so the thrown error can name every attempt. */
468
+ interface AddrAttemptFailure {
469
+ addr: Multiaddr;
470
+ error: Error;
471
+ }
472
+
473
+ /**
474
+ * Dial `peerId` from `addrs`, one address per {@link dialAddr} call, and return the
475
+ * first connection that forms. Direct addresses are tried first, then relayed ones, then
476
+ * WebRTC ones ({@link directBeforeRelayed}); within a group the given order is kept.
477
+ *
478
+ * Every address is first bound to `peerId` ({@link withTrailingPeerId}), so the
479
+ * handshake verifies that the peer expected is the one that answered; an address
480
+ * naming another peer is dropped and logged. When that leaves nothing of a
481
+ * non-empty list — every address names someone else, or `peerId` does not parse —
482
+ * this throws without dialing.
483
+ *
484
+ * Addresses that relay through this node are dropped next ({@link relaysThrough}):
485
+ * dialing one could only fail with `Can not dial self`. When that leaves nothing,
486
+ * this throws {@link SelfRelayOnlyError} without dialing.
487
+ *
488
+ * Addresses naming a transport this node lacks are not filtered out first: the
489
+ * transport manager rejects those at once (`TransportUnavailableError`), so they
490
+ * cost a log line, not time.
491
+ *
492
+ * Otherwise throws when no address connects — see {@link tryAddrsInTurn} for the error.
493
+ *
494
+ * @param peerId The peer every address must reach, as every caller already holds it
495
+ * (a `CadrePeer` row key, a seed peer's id, a strand member's id).
496
+ * @param label Names the dial in timeout messages and logs, e.g.
497
+ * `reconcileControlCohort dial of sibling <peerId>`; each attempt reads
498
+ * `<label> via <addr>`.
499
+ */
500
+ export async function dialPeerAddrs(
501
+ dialer: AddrDialer,
502
+ peerId: string,
503
+ addrs: readonly Multiaddr[],
504
+ budget: PeerDialBudget,
505
+ label: string,
506
+ ): Promise<Connection> {
507
+ const bound = boundTo(peerId, addrs, label);
508
+ if (addrs.length > 0 && bound.length === 0) {
509
+ throw new Error(`${label}: none of the ${addrs.length} candidate addresses binds to ${peerId}`);
510
+ }
511
+ const dialable = withoutSelfRelayed(dialer, bound, label);
512
+ if (bound.length > 0 && dialable.length === 0) {
513
+ throw new SelfRelayOnlyError(label);
514
+ }
515
+ return tryAddrsInTurn(directBeforeRelayed(dialable), budget, label, (addr, signal) => dialAddr(dialer, addr, signal, label));
516
+ }
517
+
518
+ /**
519
+ * `addrs` each bound to `peerId` ({@link withTrailingPeerId}). An address naming another peer
520
+ * is dropped, as is every address when `peerId` cannot be encapsulated (it does not parse);
521
+ * each drop is logged with its reason.
522
+ */
523
+ function boundTo(peerId: string, addrs: readonly Multiaddr[], label: string): Multiaddr[] {
524
+ const bound: Multiaddr[] = [];
525
+ for (const addr of addrs) {
526
+ try {
527
+ const withId = withTrailingPeerId(addr, peerId);
528
+ if (withId === null) {
529
+ log('%s: dropping %s — it names a peer other than %s', label, addr.toString(), peerId);
530
+ } else {
531
+ bound.push(withId);
532
+ }
533
+ } catch (err) {
534
+ log('%s: cannot bind %s to %s: %o', label, addr.toString(), peerId, err);
535
+ }
536
+ }
537
+ return bound;
538
+ }
539
+
540
+ /**
541
+ * Run `attempt` against each address in the given order until one succeeds, and
542
+ * return its result.
543
+ *
544
+ * Each attempt is limited to `budget.perAddressMs`, or to whatever remains of
545
+ * `budget.totalMs` when that is less. The attempt's signal is aborted when its
546
+ * limit passes, so a dial in progress is cancelled rather than left running.
547
+ * Addresses the total leaves no time for are reported as not tried.
548
+ *
549
+ * Throws when every address fails. With one address the error is that attempt's
550
+ * own, unchanged. With several it is one error naming each address and why it
551
+ * failed, in order, with the first failure as `cause` — so the report shows the
552
+ * address that mattered, not only whichever happened to be tried last.
553
+ *
554
+ * Between attempts this waits for one macrotask (`setTimeout(0)`). A direct
555
+ * address is dialed outside libp2p's dial queue ({@link dialAddr}), but a relayed
556
+ * address still passes through it for the relay leg, and the queue lets a new
557
+ * dial join any queued job for the same peer id WITHOUT checking whether that
558
+ * job has already finished: an aborted job leaves the queue a few microtasks
559
+ * after its callers are rejected, so a next attempt through the same relay made
560
+ * at once would join the dying job and be rejected with `AbortError` before it
561
+ * touches the network. All of the queue's cleanup runs as microtasks, so it has
562
+ * finished by the time a macrotask runs. Seen against libp2p 3.1.3, and the
563
+ * queue's join is unchanged in 3.3.11; `test/peer-dial.spec.ts` dials real nodes
564
+ * so an upgrade that changes it shows up there.
565
+ */
566
+ export async function tryAddrsInTurn<T>(
567
+ addrs: readonly Multiaddr[],
568
+ budget: PeerDialBudget,
569
+ label: string,
570
+ attempt: (addr: Multiaddr, signal: AbortSignal, attemptMs: number) => Promise<T>,
571
+ ): Promise<T> {
572
+ const deadline = Date.now() + budget.totalMs;
573
+ const failures: AddrAttemptFailure[] = [];
574
+ for (const addr of addrs) {
575
+ const remaining = deadline - Date.now();
576
+ if (remaining <= 0) {
577
+ failures.push({ addr, error: new Error(`not tried — the ${budget.totalMs}ms budget for ${label} was spent on earlier addresses`) });
578
+ continue;
579
+ }
580
+ if (failures.length > 0) {
581
+ await nextMacrotask();
582
+ }
583
+ const attemptMs = Math.min(budget.perAddressMs, remaining);
584
+ try {
585
+ return await withDeadline(attemptMs, `${label} via ${addr.toString()}`, (signal) => attempt(addr, signal, attemptMs));
586
+ } catch (err) {
587
+ const error = toError(err);
588
+ failures.push({ addr, error });
589
+ log('%s via %s failed: %o', label, addr.toString(), error);
590
+ }
591
+ }
592
+ throw allAttemptsFailed(label, failures);
593
+ }
594
+
595
+ /**
596
+ * `addrs` ordered by {@link AddrKind} — every `direct` address, then every `relayed` one,
597
+ * then every `webrtc` one — each group keeping its given order.
598
+ *
599
+ * The one part of libp2p's own ordering worth keeping: a relayed connection is
600
+ * slower and limited in how much data and time it may carry, so a direct
601
+ * address is always worth trying first. libp2p's other rules are deliberately
602
+ * dropped — it puts loopback addresses last and public ones before private ones,
603
+ * which is how a forwarded loopback address ended up behind addresses that
604
+ * never answer. With a per-address limit, trying a dead address first costs a
605
+ * bounded amount of time, so the caller's order is the better guide.
606
+ *
607
+ * A `webrtc` address goes behind every relayed one rather than being dropped, so a peer whose
608
+ * only address is a WebRTC one is still dialed; it just no longer takes the time the relayed
609
+ * address needed. Note that libp2p's own sorter would do the OPPOSITE — its
610
+ * `circuitRelayAddressesLast` only recognises an exact `Circuit` match, so a
611
+ * `/p2p-circuit/webrtc` address sorts ahead of the plain relayed one — which is why the
612
+ * ordering has to be applied here, one address per dial, and cannot be left to a list dial.
613
+ */
614
+ export function directBeforeRelayed(addrs: readonly Multiaddr[]): Multiaddr[] {
615
+ const byKind: readonly AddrKind[] = ['direct', 'relayed', 'webrtc'];
616
+ return byKind.flatMap((kind) => addrs.filter((addr) => addrKind(addr) === kind));
617
+ }
618
+
619
+ /**
620
+ * `addrs` with every `webrtc` address moved to the end, everything else keeping the order the
621
+ * caller gave. {@link directBeforeRelayed} applies both of its rules; this applies only the
622
+ * WebRTC one, for a caller whose own order of the rest must be preserved.
623
+ *
624
+ * `dialWake` (`strand-wake-protocol.ts`) is that caller: it wants the relayed address FIRST (a
625
+ * hibernating machine is usually reachable only through its relay, so its direct addresses
626
+ * blackhole), which is the order `CadreNode.resolvePeerAddrs` hands it. What it must not do is
627
+ * spend one of its two whole attempts (`WAKE_DIAL_ATTEMPTS`) on an address that answers nothing
628
+ * for about 23 s when ICE cannot connect.
629
+ */
630
+ export function webrtcLast(addrs: readonly Multiaddr[]): Multiaddr[] {
631
+ const needsIce = (addr: Multiaddr): boolean => addrKind(addr) === 'webrtc';
632
+ return [...addrs.filter((addr) => !needsIce(addr)), ...addrs.filter(needsIce)];
633
+ }
634
+
635
+ /** `addrs` without those that relay through `dialer` itself, each dropped one logged. */
636
+ function withoutSelfRelayed(dialer: AddrDialer, addrs: readonly Multiaddr[], label: string): Multiaddr[] {
637
+ return addrs.filter((addr) => {
638
+ if (!relaysThrough(addr, dialer.peerId)) {
639
+ return true;
640
+ }
641
+ log('%s: skipping %s — it relays through this node', label, addr.toString());
642
+ return false;
643
+ });
644
+ }
645
+
646
+ /**
647
+ * Whether `addr` reaches its target by relaying through `relay` at any hop.
648
+ *
649
+ * A circuit address names its relay in the `p2p` component immediately before
650
+ * the `p2p-circuit` marker (`/<transport>/p2p/<relay>/p2p-circuit/p2p/<target>`),
651
+ * so the components are walked rather than the text searched: the target's id
652
+ * after the marker, a bare `/p2p-circuit` naming no relay, and a multi-hop chain
653
+ * each read correctly that way. Same rule as db-p2p's `routesThroughRelay`, which
654
+ * its package does not export.
655
+ */
656
+ function relaysThrough(addr: Multiaddr, relay: PeerId): boolean {
657
+ const components = addr.getComponents();
658
+ return components.some((component, i) => component.name === 'p2p-circuit' && namesPeer(components[i - 1], relay));
659
+ }
660
+
661
+ /**
662
+ * Whether `component` is a `p2p` component naming `peer`. Compared as canonical
663
+ * strings because a multiaddr keeps a peer id in whichever form it was written
664
+ * (base58 or CIDv1). `PeerId.equals` is avoided because test doubles supply the
665
+ * dialer's `peerId` with `toString` only.
666
+ */
667
+ function namesPeer(component: Component | undefined, peer: PeerId): boolean {
668
+ if (component?.name !== 'p2p' || component.value === undefined) {
669
+ return false;
670
+ }
671
+ const expected = peer.toString();
672
+ try {
673
+ return peerIdFromString(component.value).toString() === expected;
674
+ } catch (err) {
675
+ log('cannot read %s as a peer id; treating it as not this node: %o', component.value, err);
676
+ return false;
677
+ }
678
+ }
679
+
680
+ function allAttemptsFailed(label: string, failures: AddrAttemptFailure[]): Error {
681
+ if (failures.length === 0) {
682
+ return new Error(`${label}: no candidate addresses`);
683
+ }
684
+ if (failures.length === 1) {
685
+ return failures[0].error;
686
+ }
687
+ const detail = failures.map((f) => `${f.addr.toString()} — ${f.error.message}`).join('; ');
688
+ return new Error(`${label} failed for all ${failures.length} candidate addresses: ${detail}`, { cause: failures[0].error });
689
+ }
690
+
691
+ /**
692
+ * Yield one macrotask: libp2p's dial queue drops an aborted job only on the next turn, so a
693
+ * dialer that moves on to another address after an abort waits this long first. Shared with
694
+ * the cadre invitation dialer (`cadre-invite-protocol.ts`).
695
+ */
696
+ export function nextMacrotask(): Promise<void> {
697
+ return new Promise((resolve) => setTimeout(resolve, 0));
698
+ }